@ably/ai-transport 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -19
- package/dist/ably-ai-transport.js +1790 -1091
- package/dist/ably-ai-transport.js.map +1 -1
- package/dist/ably-ai-transport.umd.cjs +1 -1
- package/dist/ably-ai-transport.umd.cjs.map +1 -1
- package/dist/constants.d.ts +2 -2
- package/dist/core/agent.d.ts +20 -5
- package/dist/core/channel-options.d.ts +57 -0
- package/dist/core/codec/codec-event.d.ts +9 -0
- package/dist/core/codec/decoder.d.ts +4 -1
- package/dist/core/codec/define-codec.d.ts +100 -0
- package/dist/core/codec/encoder.d.ts +2 -7
- package/dist/core/codec/field-bag.d.ts +85 -0
- package/dist/core/codec/fields.d.ts +141 -0
- package/dist/core/codec/index.d.ts +8 -1
- package/dist/core/codec/input-descriptor-decoder.d.ts +19 -0
- package/dist/core/codec/input-descriptor-encoder.d.ts +22 -0
- package/dist/core/codec/input-descriptors.d.ts +281 -0
- package/dist/core/codec/output-descriptor-decoder.d.ts +29 -0
- package/dist/core/codec/output-descriptor-encoder.d.ts +31 -0
- package/dist/core/codec/output-descriptors.d.ts +237 -0
- package/dist/core/codec/types.d.ts +95 -36
- package/dist/core/codec/well-known-inputs.d.ts +52 -0
- package/dist/core/transport/agent-view.d.ts +296 -0
- package/dist/core/transport/decode-fold.d.ts +40 -32
- package/dist/core/transport/headers.d.ts +30 -1
- package/dist/core/transport/index.d.ts +1 -1
- package/dist/core/transport/invocation.d.ts +1 -1
- package/dist/core/transport/load-history-pages.d.ts +71 -0
- package/dist/core/transport/load-history.d.ts +21 -16
- package/dist/core/transport/run-manager.d.ts +9 -11
- package/dist/core/transport/session-support.d.ts +55 -0
- package/dist/core/transport/tree.d.ts +165 -15
- package/dist/core/transport/types/agent.d.ts +120 -98
- package/dist/core/transport/types/client.d.ts +45 -12
- package/dist/core/transport/types/tree.d.ts +52 -10
- package/dist/core/transport/types/view.d.ts +55 -28
- package/dist/core/transport/view.d.ts +176 -58
- package/dist/core/transport/wire-log.d.ts +102 -0
- package/dist/errors.d.ts +10 -4
- package/dist/index.d.ts +6 -5
- package/dist/react/ably-ai-transport-react.js +784 -415
- package/dist/react/ably-ai-transport-react.js.map +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
- package/dist/react/contexts/client-session-context.d.ts +2 -1
- package/dist/react/contexts/client-session-provider.d.ts +3 -0
- package/dist/react/index.d.ts +2 -1
- package/dist/react/internal/skipped-session.d.ts +8 -0
- package/dist/react/use-view.d.ts +3 -3
- package/dist/utils.d.ts +22 -54
- package/dist/vercel/ably-ai-transport-vercel.js +2297 -2026
- package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
- package/dist/vercel/codec/decode-lifecycle.d.ts +9 -0
- package/dist/vercel/codec/events.d.ts +1 -2
- package/dist/vercel/codec/fields.d.ts +44 -0
- package/dist/vercel/codec/fold-content.d.ts +16 -0
- package/dist/vercel/codec/fold-data.d.ts +16 -0
- package/dist/vercel/codec/fold-input.d.ts +67 -0
- package/dist/vercel/codec/fold-lifecycle.d.ts +16 -0
- package/dist/vercel/codec/fold-text.d.ts +16 -0
- package/dist/vercel/codec/fold-tool-input.d.ts +17 -0
- package/dist/vercel/codec/fold-tool-output.d.ts +16 -0
- package/dist/vercel/codec/index.d.ts +5 -30
- package/dist/vercel/codec/inputs.d.ts +11 -0
- package/dist/vercel/codec/outputs.d.ts +11 -0
- package/dist/vercel/codec/reducer-state.d.ts +121 -0
- package/dist/vercel/codec/reducer.d.ts +20 -102
- package/dist/vercel/codec/tool-transitions.d.ts +0 -6
- package/dist/vercel/codec/wire-data.d.ts +34 -0
- package/dist/vercel/index.d.ts +1 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.js +2013 -9500
- package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +1 -70
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
- package/dist/vercel/react/contexts/chat-transport-context.d.ts +2 -1
- package/dist/vercel/run-end-reason.d.ts +66 -11
- package/dist/vercel/tool-part.d.ts +21 -0
- package/dist/vercel/transport/chat-transport.d.ts +0 -2
- package/dist/vercel/transport/index.d.ts +1 -1
- package/dist/vercel/transport/run-output-stream.d.ts +6 -8
- package/dist/version.d.ts +1 -1
- package/package.json +2 -2
- package/src/constants.ts +2 -2
- package/src/core/agent.ts +43 -19
- package/src/core/channel-options.ts +89 -0
- package/src/core/codec/codec-event.ts +27 -0
- package/src/core/codec/decoder.ts +145 -21
- package/src/core/codec/define-codec.ts +432 -0
- package/src/core/codec/encoder.ts +13 -54
- package/src/core/codec/field-bag.ts +142 -0
- package/src/core/codec/fields.ts +193 -0
- package/src/core/codec/index.ts +43 -0
- package/src/core/codec/input-descriptor-decoder.ts +97 -0
- package/src/core/codec/input-descriptor-encoder.ts +150 -0
- package/src/core/codec/input-descriptors.ts +373 -0
- package/src/core/codec/output-descriptor-decoder.ts +139 -0
- package/src/core/codec/output-descriptor-encoder.ts +101 -0
- package/src/core/codec/output-descriptors.ts +307 -0
- package/src/core/codec/types.ts +99 -36
- package/src/core/codec/well-known-inputs.ts +96 -0
- package/src/core/transport/agent-session.ts +330 -589
- package/src/core/transport/agent-view.ts +738 -0
- package/src/core/transport/client-session.ts +74 -69
- package/src/core/transport/decode-fold.ts +57 -47
- package/src/core/transport/headers.ts +57 -4
- package/src/core/transport/index.ts +2 -1
- package/src/core/transport/invocation.ts +1 -1
- package/src/core/transport/load-history-pages.ts +220 -0
- package/src/core/transport/load-history.ts +63 -61
- package/src/core/transport/pipe-stream.ts +10 -1
- package/src/core/transport/run-manager.ts +25 -31
- package/src/core/transport/session-support.ts +96 -0
- package/src/core/transport/tree.ts +414 -47
- package/src/core/transport/types/agent.ts +129 -102
- package/src/core/transport/types/client.ts +49 -13
- package/src/core/transport/types/tree.ts +61 -12
- package/src/core/transport/types/view.ts +57 -28
- package/src/core/transport/view.ts +520 -172
- package/src/core/transport/wire-log.ts +189 -0
- package/src/errors.ts +10 -3
- package/src/index.ts +44 -11
- package/src/react/contexts/client-session-context.ts +1 -1
- package/src/react/contexts/client-session-provider.tsx +38 -2
- package/src/react/index.ts +2 -1
- package/src/react/internal/skipped-session.ts +62 -0
- package/src/react/use-client-session.ts +7 -30
- package/src/react/use-view.ts +3 -3
- package/src/utils.ts +31 -97
- package/src/vercel/codec/decode-lifecycle.ts +70 -0
- package/src/vercel/codec/events.ts +1 -3
- package/src/vercel/codec/fields.ts +58 -0
- package/src/vercel/codec/fold-content.ts +54 -0
- package/src/vercel/codec/fold-data.ts +46 -0
- package/src/vercel/codec/fold-input.ts +255 -0
- package/src/vercel/codec/fold-lifecycle.ts +85 -0
- package/src/vercel/codec/fold-text.ts +55 -0
- package/src/vercel/codec/fold-tool-input.ts +86 -0
- package/src/vercel/codec/fold-tool-output.ts +79 -0
- package/src/vercel/codec/index.ts +23 -63
- package/src/vercel/codec/inputs.ts +116 -0
- package/src/vercel/codec/outputs.ts +207 -0
- package/src/vercel/codec/reducer-state.ts +169 -0
- package/src/vercel/codec/reducer.ts +52 -838
- package/src/vercel/codec/tool-transitions.ts +1 -12
- package/src/vercel/codec/wire-data.ts +64 -0
- package/src/vercel/index.ts +1 -0
- package/src/vercel/react/contexts/chat-transport-context.ts +1 -1
- package/src/vercel/react/use-chat-transport.ts +8 -28
- package/src/vercel/react/use-message-sync.ts +5 -10
- package/src/vercel/run-end-reason.ts +95 -16
- package/src/vercel/tool-part.ts +25 -0
- package/src/vercel/transport/chat-transport.ts +10 -22
- package/src/vercel/transport/index.ts +1 -1
- package/src/vercel/transport/run-output-stream.ts +7 -8
- package/src/version.ts +1 -1
- package/dist/core/transport/branch-chain.d.ts +0 -43
- package/dist/core/transport/load-conversation.d.ts +0 -128
- package/dist/vercel/codec/decoder.d.ts +0 -9
- package/dist/vercel/codec/encoder.d.ts +0 -11
- package/src/core/transport/branch-chain.ts +0 -58
- package/src/core/transport/load-conversation.ts +0 -355
- package/src/vercel/codec/decoder.ts +0 -696
- package/src/vercel/codec/encoder.ts +0 -548
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`ably`),require(`ably/react`),require(`react`),require(`react/jsx-runtime`)):typeof define==`function`&&define.amd?define([`exports`,`ably`,`ably/react`,`react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.AblyAiTransportReact={},e.Ably,e.AblyReact,e.React,e.ReactJsxRuntime))})(this,function(e,t,n,r,i){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var a=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,c=Object.getOwnPropertyNames,l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=c(t),a=0,l=i.length,d;a<l;a++)d=i[a],!u.call(e,d)&&d!==n&&o(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=s(t,d))||r.enumerable});return e};t=((e,t,n)=>(n=e==null?{}:a(l(e)),d(t||!e||!e.__esModule?o(n,`default`,{value:e,enumerable:!0}):n,e)))(t,1);var f=`status`,p=`run-id`,m=`invocation-id`,h=`event-id`,g=`codec-message-id`,_=`run-client-id`,v=`input-client-id`,y=`role`,b=`parent`,x=`fork-of`,S=`msg-regenerate`,C=`input-codec-message-id`,w=`error-code`,ee=`ai-cancel`,T=function(e){return e[e.BadRequest=4e4]=`BadRequest`,e[e.InvalidArgument=40003]=`InvalidArgument`,e[e.InsufficientCapability=40160]=`InsufficientCapability`,e[e.EncoderRecoveryFailed=104e3]=`EncoderRecoveryFailed`,e[e.SessionSubscriptionError=104001]=`SessionSubscriptionError`,e[e.CancelListenerError=104002]=`CancelListenerError`,e[e.RunLifecycleError=104003]=`RunLifecycleError`,e[e.SessionClosed=104004]=`SessionClosed`,e[e.SessionSendFailed=104005]=`SessionSendFailed`,e[e.ChannelContinuityLost=104006]=`ChannelContinuityLost`,e[e.ChannelNotReady=104007]=`ChannelNotReady`,e[e.StreamError=104008]=`StreamError`,e[e.InputEventNotFound=104010]=`InputEventNotFound`,e}({}),te=e=>({logAction:(t,n,r)=>{e.error(n,{detail:r})},shouldLog:()=>!0}),ne=t.Realtime.EventEmitter,E=class extends ne{constructor(e){super(te(e))}},re=function(e){return e.Trace=`trace`,e.Debug=`debug`,e.Info=`info`,e.Warn=`warn`,e.Error=`error`,e.Silent=`silent`,e}({}),ie=(e,t,n)=>{let r=n?`, context: ${JSON.stringify(n)}`:``,i=`[${new Date().toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;switch(t){case`trace`:case`debug`:console.log(i);break;case`info`:console.info(i);break;case`warn`:console.warn(i);break;case`error`:console.error(i);break;case`silent`:break}},ae=e=>new O(e.logHandler??ie,e.logLevel),D=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4],[`silent`,5]]),O=class e{constructor(e,n,r){this._handler=e,this._context=r;let i=D.get(n);if(i===void 0)throw new t.ErrorInfo(`unable to create logger; invalid log level: ${n}`,T.InvalidArgument,400);this._levelNumber=i}trace(e,t){this._write(e,`trace`,0,t)}debug(e,t){this._write(e,`debug`,1,t)}info(e,t){this._write(e,`info`,2,t)}warn(e,t){this._write(e,`warn`,3,t)}error(e,t){this._write(e,`error`,4,t)}withContext(t){let n=[...D.entries()].find(([,e])=>e===this._levelNumber)?.[0]??`error`;return new e(this._handler,n,this._mergeContext(t))}_write(e,t,n,r){n>=this._levelNumber&&this._handler(e,t,this._mergeContext(r))}_mergeContext(e){return this._context?e?{...this._context,...e}:this._context:e??void 0}},k=(e,t)=>{let n=e.extras;if(!n||typeof n!=`object`)return{};let r=n.ai;if(!r||typeof r!=`object`)return{};let i=r[t];return!i||typeof i!=`object`?{}:i},A=e=>k(e,`transport`),j=`0.2.0`,oe=`ai-transport-js`,se=(e,t)=>{let n=e;return n.options.agents={...n.options.agents,...t},{params:{agent:Object.entries(t).map(([e,t])=>`${e}/${t}`).join(` `)}}},ce=(e,t)=>{let n=t?.adapterTag,r={[oe]:j};return n&&(r[n]=j),se(e,r)},le=e=>{let t={[y]:e.role,[g]:e.codecMessageId};return e.runId!==void 0&&(t[p]=e.runId),e.runClientId!==void 0&&(t[_]=e.runClientId),e.parent&&(t[b]=e.parent),e.forkOf&&(t[x]=e.forkOf),e.regenerates&&(t[S]=e.regenerates),e.invocationId&&(t[m]=e.invocationId),e.inputClientId!==void 0&&(t[v]=e.inputClientId),e.inputCodecMessageId!==void 0&&(t[C]=e.inputCodecMessageId),e.inputEventId&&(t[h]=e.inputEventId),t},ue=e=>e===`ai-run-start`||e===`ai-run-suspend`||e===`ai-run-resume`||e===`ai-run-end`,de=(e,t,n)=>{let r=t[p];if(!r)return;let i=t[`run-client-id`]??``;if(e===`ai-run-start`){let e=t[b],a=t[x],o=t[S];return{type:`start`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``,...e!==void 0&&{parent:e},...a!==void 0&&{forkOf:a},...o!==void 0&&{regenerates:o}}}if(e===`ai-run-suspend`)return{type:`suspend`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``};if(e===`ai-run-resume`)return{type:`resume`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``};if(e===`ai-run-end`){let e=t[`run-reason`]??`complete`;return{type:`end`,runId:r,clientId:i,serial:n,invocationId:t[`invocation-id`]??``,reason:e}}},M=(e,t,n)=>{let r=A(n),i=n.serial;if(ue(n.name)){let t=de(n.name,r,i);return t&&e.applyRunLifecycle(t),t}let{inputs:a,outputs:o}=t.decode(n);(a.length>0||o.length>0||r[`run-id`])&&e.applyMessage({inputs:a,outputs:o},r,i)},fe=class e{constructor(e){this.inputEventId=e.inputEventId,this.sessionName=e.sessionName}static fromJSON(t){return new e(t)}toJSON(){return{inputEventId:this.inputEventId,sessionName:this.sessionName}}},N=e=>e.kind===`run`?e.runId:e.codecMessageId,P=e=>e.kind===`run`?e.startSerial:e.serial,F=(e,t,n)=>{let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)},I=(e,t,n)=>{let r=e.get(t);r&&(r.delete(n),r.size===0&&e.delete(t))},L=class{constructor(e,t){this._nodeIndex=new Map,this._codecMessageIdToNodeKey=new Map,this._sortedNodes=[],this._parentIndex=new Map,this._replyRunsByInput=new Map,this._seqCounter=0,this._structuralVersion=0,this._siblingCache=new Map,this._siblingCacheVersion=-1,this._codec=e,this._logger=t,this._emitter=new E(t)}_compareNodes(e,t){let n=P(e.node),r=P(t.node);return n===void 0&&r===void 0?e.insertSeq-t.insertSeq:n===void 0?1:r===void 0||n<r?-1:n>r?1:e.insertSeq-t.insertSeq}_insertSortedNode(e){if(P(e.node)===void 0){this._sortedNodes.push(e);return}let t=0,n=this._sortedNodes.length;for(;t<n;){let r=t+n>>>1,i=this._sortedNodes[r];if(!i)break;this._compareNodes(i,e)<=0?t=r+1:n=r}this._sortedNodes.splice(t,0,e)}_removeSortedNode(e){let t=this._sortedNodes.indexOf(e);t!==-1&&this._sortedNodes.splice(t,1)}_insertNode(e,t,n){this._nodeIndex.set(e,t),this._addToParentIndex(n,e),this._insertSortedNode(t),this._structuralVersion++}_promoteSerial(e){this._removeSortedNode(e),this._insertSortedNode(e),this._structuralVersion++}_foldInto(e,t,n,r){for(let i of t)try{e.node.projection=this._codec.fold(e.node.projection,i,{serial:n??``,messageId:r})}catch(t){this._logger.error(`Tree._foldInto(); fold threw`,{key:N(e.node),messageId:r,err:t})}}_addToParentIndex(e,t){F(this._parentIndex,e,t)}_removeFromParentIndex(e,t){I(this._parentIndex,e,t)}_parentKeyOf(e){let t=e.parentCodecMessageId;return t===void 0?void 0:this._codecMessageIdToNodeKey.get(t)}_inputGroupRoot(e){let t=e,n=new Set([N(t)]);for(;t.forkOf!==void 0&&!n.has(t.forkOf);){let e=this._nodeIndex.get(t.forkOf);if(e?.node.kind!==`input`||e.node.parentCodecMessageId!==t.parentCodecMessageId)break;t=e.node,n.add(N(t))}return t}_getSiblingGroup(e){this._siblingCacheVersion!==this._structuralVersion&&(this._siblingCache.clear(),this._siblingCacheVersion=this._structuralVersion);let t=this._siblingCache.get(e);if(t)return t;let n=this._nodeIndex.get(e);if(!n)return[];let r=n.node;r.kind===`input`&&(r=this._inputGroupRoot(r));let i=r.parentCodecMessageId,a=[],o=this._parentIndex.get(i);if(o)for(let e of o){let t=this._nodeIndex.get(e);t&&this._isSiblingOf(t.node,r)&&a.push(t)}a.sort((e,t)=>this._compareNodes(e,t));for(let e of a)this._siblingCache.set(N(e.node),a);return this._siblingCache.set(e,a),a}_isSiblingOf(e,t){if(e.kind!==t.kind||e.parentCodecMessageId!==t.parentCodecMessageId)return!1;if(e.kind===`run`)return!0;let n=N(t);if(N(e)===n)return!0;let r=e,i=new Set([N(r)]);for(;r.kind===`input`&&r.forkOf!==void 0;){if(r.forkOf===n)return!0;if(i.has(r.forkOf))break;let e=this._nodeIndex.get(r.forkOf);if(!e)break;r=e.node,i.add(N(r))}return!1}getGroupRoot(e){let t=this._nodeIndex.get(e);if(!t)return e;if(t.node.kind===`input`)return N(this._inputGroupRoot(t.node));let n=this._getSiblingGroup(e)[0]?.node;return n?N(n):e}visibleNodes(e=new Map){this._logger.trace(`DefaultTree.visibleNodes();`);let t=[],n=new Set,r=new Map;for(let i of this._sortedNodes){let a=i.node,o=N(a),s=this._parentKeyOf(a);if(s!==void 0&&!n.has(s))continue;let c=this._getSiblingGroup(o);if(c.length>1){let t=this.getGroupRoot(o),n=r.get(t);if(n===void 0){let i=e.get(t);if(i!==void 0&&c.some(e=>N(e.node)===i))n=i;else{let e=c.at(-1);if(!e)break;n=N(e.node)}r.set(t,n)}if(o!==n)continue}n.add(o),t.push(a)}return t}getRunNode(e){this._logger.trace(`DefaultTree.getRunNode();`,{runId:e});let t=this._nodeIndex.get(e)?.node;return t?.kind===`run`?t:void 0}getNode(e){return this._logger.trace(`DefaultTree.getNode();`,{key:e}),this._nodeIndex.get(e)?.node}getNodeByCodecMessageId(e){this._logger.trace(`DefaultTree.getNodeByCodecMessageId();`,{codecMessageId:e});let t=this._codecMessageIdToNodeKey.get(e);return t===void 0?void 0:this._nodeIndex.get(t)?.node}getReplyRuns(e){let t=this._replyRunsByInput.get(e);if(!t)return[];let n=[];for(let e of t){let t=this._nodeIndex.get(e)?.node;t?.kind===`run`&&n.push(t)}return n}getSiblingNodes(e){return this._logger.trace(`DefaultTree.getSiblingNodes();`,{key:e}),this._getSiblingGroup(e).map(e=>e.node)}applyMessage(e,t,n){let r=t[p],i=t[g],a=r===void 0&&i!==void 0&&t.role===`user`&&e.inputs.length>0?i:void 0;if(r===void 0&&a===void 0){this._logger.warn(`Tree.applyMessage(); message has no run-id and is not a user input; skipping`);return}let o=[...e.inputs,...e.outputs],s=a??r;if(o.length===0&&s!==void 0&&!this._nodeIndex.has(s))return;let c=this._structuralVersion;a===void 0?r!==void 0&&this._applyRunMessage(r,e,t,n):this._applyInputMessage(a,t,n,o),this._structuralVersion!==c&&this._emitter.emit(`update`)}_applyInputMessage(e,t,n,r){let i=this._nodeIndex.get(e);i?i.node.kind===`input`&&n&&!i.node.serial&&(this._logger.debug(`Tree.applyMessage(); promoting input serial`,{codecMessageId:e,serial:n}),i.node.serial=n,this._promoteSerial(i)):(i=this._createInputNodeFromHeaders(e,t,n),this._insertNode(e,i,i.node.parentCodecMessageId),this._codecMessageIdToNodeKey.set(e,e),this._logger.debug(`Tree.applyMessage(); created input node`,{codecMessageId:e})),this._foldInto(i,r,n,e),this._emitter.emit(`output`,{runId:void 0,inputCodecMessageId:e,codecMessageId:e,serial:n,events:[]})}_applyRunMessage(e,t,n,r){let i=n[g],a=n[C],o=[...t.inputs,...t.outputs],s=t.outputs,c=this._nodeIndex.get(e);if(!c&&i!==void 0){let e=this._codecMessageIdToNodeKey.get(i),t=e===void 0?void 0:this._nodeIndex.get(e);t?.node.kind===`run`&&t.node.startSerial===void 0&&(c=t)}c?r&&c.node.kind===`run`&&!c.node.startSerial&&(this._logger.debug(`Tree.applyMessage(); promoting startSerial`,{runId:e,serial:r}),c.node.startSerial=r,this._promoteSerial(c)):(c=this._createRunFromHeaders(e,n,r),this._insertNode(e,c,c.node.parentCodecMessageId),this._indexReplyRun(c.node,e),this._logger.debug(`Tree.applyMessage(); created new Run`,{runId:e}));let l=N(c.node);i&&this._codecMessageIdToNodeKey.set(i,l),this._foldInto(c,o,r,i),this._emitter.emit(`output`,{runId:l,inputCodecMessageId:a,codecMessageId:i,serial:r,events:s})}_indexReplyRun(e,t){e.parentCodecMessageId!==void 0&&F(this._replyRunsByInput,e.parentCodecMessageId,t)}applyRunLifecycle(e){this._logger.trace(`DefaultTree.applyRunLifecycle();`,{type:e.type,runId:e.runId});let t=this._structuralVersion;switch(e.type){case`start`:this._applyRunStart(e);break;case`suspend`:this._applyRunSuspend(e);break;case`resume`:this._applyRunResume(e);break;case`end`:this._applyRunEnd(e);break}this._emitter.emit(`run`,e),this._structuralVersion!==t&&this._emitter.emit(`update`)}_applyRunStart(e){let t=this._nodeIndex.get(e.runId);if(t?.node.kind===`run`){let n=t.node;if(n.status!==`active`&&(n.status=`active`),e.serial&&!n.startSerial&&(n.startSerial=e.serial,this._promoteSerial(t)),n.parentCodecMessageId===void 0&&e.parent!==void 0&&(n.parentCodecMessageId=e.parent,this._removeFromParentIndex(void 0,e.runId),this._addToParentIndex(n.parentCodecMessageId,e.runId),this._indexReplyRun(n,e.runId),this._structuralVersion++),n.forkOf===void 0&&e.forkOf!==void 0){let t=this._codecMessageIdToNodeKey.get(e.forkOf);t!==void 0&&t!==e.runId&&(n.forkOf=t,this._structuralVersion++)}n.regeneratesCodecMessageId===void 0&&e.regenerates!==void 0&&(n.regeneratesCodecMessageId=e.regenerates,this._structuralVersion++),n.invocationId===``&&e.invocationId!==``&&(n.invocationId=e.invocationId)}else if(!t){let t=this._createRunFromLifecycle(e);this._insertNode(e.runId,t,t.node.parentCodecMessageId),this._indexReplyRun(t.node,e.runId)}}_applyRunSuspend(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.status=`suspended`,t.node.endSerial=e.serial)}_applyRunResume(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&t.node.status===`suspended`&&(t.node.status=`active`)}_applyRunEnd(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.status=e.reason,t.node.endSerial=e.serial)}delete(e){let t=this._nodeIndex.get(e);t&&(this._logger.debug(`Tree.delete();`,{key:e}),this._removeFromParentIndex(t.node.parentCodecMessageId,e),this._removeSortedNode(t),this._nodeIndex.delete(e),t.node.kind===`run`&&t.node.parentCodecMessageId!==void 0&&I(this._replyRunsByInput,t.node.parentCodecMessageId,e),this._structuralVersion++,this._emitter.emit(`update`))}_createRunFromHeaders(e,t,n){let r=t[x];return this._buildRunNode({runId:e,parentCodecMessageId:t[b],forkOf:r?this._codecMessageIdToNodeKey.get(r):void 0,regeneratesCodecMessageId:t[S],clientId:t[`run-client-id`]??``,invocationId:t[`invocation-id`]??``,startSerial:n})}_buildRunNode(e){return{node:{kind:`run`,runId:e.runId,parentCodecMessageId:e.parentCodecMessageId,forkOf:e.forkOf,regeneratesCodecMessageId:e.regeneratesCodecMessageId,clientId:e.clientId,invocationId:e.invocationId,status:`active`,projection:this._codec.init(),startSerial:e.startSerial,endSerial:void 0},insertSeq:this._seqCounter++}}_createInputNodeFromHeaders(e,t,n){let r=t[x];return{node:{kind:`input`,codecMessageId:e,parentCodecMessageId:t[b],forkOf:r,projection:this._codec.init(),serial:n},insertSeq:this._seqCounter++}}_createRunFromLifecycle(e){let t=e.forkOf;return this._buildRunNode({runId:e.runId,parentCodecMessageId:e.parent,forkOf:t?this._codecMessageIdToNodeKey.get(t):void 0,regeneratesCodecMessageId:e.regenerates,clientId:e.clientId,invocationId:e.invocationId,startSerial:e.serial})}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}emitAblyMessage(e){this._logger.trace(`DefaultTree.emitAblyMessage();`),this._emitter.emit(`ably-message`,e)}},R=(e,t)=>new L(e,t),z=(e,t)=>{for(let n of t){let t=A(n),r=t[g];if(!r)continue;let i=n.action,a=i===`message.create`&&`discrete`in t,o=t.stream===`true`&&(i===`message.create`||i===`message.update`||i===`message.append`),s=t[f],c=s===`complete`||s===`cancelled`;(a||o)&&e.startedCodecMessageIds.add(r),(a||c)&&e.terminatedCodecMessageIds.add(r),e.startedCodecMessageIds.has(r)&&e.terminatedCodecMessageIds.has(r)&&e.completedCodecMessageIds.add(r)}},B=async(e,t,n)=>{e.rawMessages.push(...t.items),e.lastAblyPage=t,z(e,t.items);let r=e.returnedCount+n;for(;e.completedCodecMessageIds.size<r&&t.hasNext();){e.logger.debug(`loadHistory.fetchUntilLimit(); fetching next page`,{collected:e.rawMessages.length,completed:e.completedCodecMessageIds.size});let n=await t.next();if(!n)break;t=n,e.rawMessages.push(...n.items),e.lastAblyPage=n,z(e,n.items)}},V=(e,t)=>{let n=e.completedCodecMessageIds.size,r=Math.min(t,Math.max(0,n-e.returnedCount));e.returnedCount+=r;let i=n>e.returnedCount,a=e.lastAblyPage?.hasNext()??!1,o=e.rawMessages.length-e.returnedRawCount>0?e.rawMessages.slice(e.returnedRawCount).toReversed():[];return e.returnedRawCount=e.rawMessages.length,{rawMessages:o,hasNext:()=>i||a,next:async()=>{if(i)return V(e,t);if(!a||!e.lastAblyPage)return;let n=await e.lastAblyPage.next();if(n)return await B(e,n,t),V(e,t)}}},pe=async(e,t,n)=>{let r=t?.limit??100,i={rawMessages:[],returnedCount:0,returnedRawCount:0,lastAblyPage:void 0,startedCodecMessageIds:new Set,terminatedCodecMessageIds:new Set,completedCodecMessageIds:new Set,logger:n};n.trace(`loadHistory();`,{limit:r});let a=r*10;return await e.attach(),await B(i,await e.history({untilAttach:!0,limit:a}),r),V(i,r)},me=e=>Array.isArray(e)?e:[e],he=3,H=e=>({runId:e.runId,clientId:e.clientId,status:e.status,invocationId:e.invocationId}),ge=class{constructor(e){this._branchSelections=new Map,this._regenSelections=new Map,this._withheldRunIds=new Set,this._lastVisibleNodeKeys=[],this._lastVisibleProjections=[],this._lastVisibleMessagePairs=[],this._lastVisibleNodeKeySet=new Set,this._hasMoreHistory=!1,this._withheldBuffer=[],this._unsubs=[],this._cachedNodes=[],this._loadingOlder=!1,this._processingHistory=!1,this._closed=!1,this._tree=e.tree,this._channel=e.channel,this._codec=e.codec,this._sendDelegate=e.sendDelegate,this._onClose=e.onClose,this._logger=e.logger.withContext({component:`View`}),this._logger.trace(`DefaultView();`),this._emitter=new E(this._logger),this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._unsubs.push(this._tree.on(`update`,()=>{this._onTreeUpdate()}),this._tree.on(`ably-message`,e=>{this._onTreeAblyMessage(e)}),this._tree.on(`run`,e=>{this._onTreeRun(e)}),this._tree.on(`output`,e=>{this._onTreeOutput(e)}))}_onTreeOutput(e){this._processingHistory||(e.runId!==void 0&&this._lastVisibleNodeKeySet.has(e.runId)||e.inputCodecMessageId!==void 0&&this._lastVisibleNodeKeySet.has(e.inputCodecMessageId))&&(this._lastVisibleProjections=this._cachedNodes.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(this._cachedNodes),this._emitter.emit(`update`))}getMessages(){return this._lastVisibleMessagePairs}runs(){return this._cachedNodes.filter(e=>e.kind===`run`).map(e=>H(e))}_computeFlatNodes(){let e=this._treeVisibleNodes();return this._withheldRunIds.size===0?e:e.filter(e=>!this._withheldRunIds.has(N(e)))}_recomputeAndEmit(){this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._emitter.emit(`update`)}_recomputeAndEmitIfChanged(){let e=this._computeFlatNodes();this._visibleChanged(e)&&(this._cachedNodes=e,this._updateVisibleSnapshot(e),this._emitter.emit(`update`))}_runByCodecMessageId(e){let t=this._tree.getNodeByCodecMessageId(e);return t?.kind===`run`?t:void 0}_extractMessages(e){let t=[];for(let n of e)for(let e of this._codec.getMessages(n.projection))t.push(e);return t}hasOlder(){return this._withheldBuffer.length>0||this._hasMoreHistory}async loadOlder(e=100){if(!(this._closed||this._loadingOlder)){this._loadingOlder=!0,this._logger.trace(`DefaultView.loadOlder();`,{limit:e});try{if(this._withheldBuffer.length>0){let t=this._withheldBuffer.splice(-e,e);this._releaseWithheld(t);return}if(!this._hasMoreHistory&&!this._lastHistoryPage){await this._loadFirstPage(e);return}if(!this._hasMoreHistory)return;if(!this._lastHistoryPage?.hasNext()){this._hasMoreHistory=!1;return}let t=await this._lastHistoryPage.next();if(this._closed||!t){t||(this._hasMoreHistory=!1);return}await this._revealFromPage(t,e)}catch(e){throw this._logger.error(`DefaultView.loadOlder(); failed`,{error:e}),e}finally{this._loadingOlder=!1}}}runOf(e){this._logger.trace(`DefaultView.runOf();`,{codecMessageId:e});let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`run`)return H(t);let n=this._selectedReplyRun(t.codecMessageId);return n?H(n):void 0}_selectedReplyRun(e){let t=this._tree.getReplyRuns(e);if(t.length===0)return;if(t.length===1)return t[0];let n=this._tree.getGroupRoot(t[0]?.runId??``),r=this._regenSelections.get(n),i=r&&r.kind!==`pending`?r.selectedRunId:void 0;if(i!==void 0){let e=t.find(e=>e.runId===i);if(e)return e}return t.toSorted((e,t)=>(e.startSerial??``).localeCompare(t.startSerial??``)).at(-1)}run(e){this._logger.trace(`DefaultView.run();`,{runId:e});let t=this._tree.getRunNode(e);return t?H(t):void 0}branchSelection(e){let t=this._resolveMessageBranchPoint(e);if(t){let e=t.siblings.flatMap(e=>{let t=this._codec.getMessages(e.projection).at(0);return t?[t.message]:[]});if(e.length>0){let n=this._resolveSelectedIndex(t),r=Math.max(0,Math.min(n,e.length-1)),i=e[r];return{hasSiblings:e.length>1,siblings:e,index:r,selected:i}}}let n=this._tree.getNodeByCodecMessageId(e);if(n){let t=this._codec.getMessages(n.projection).find(t=>t.codecMessageId===e);if(t!==void 0)return{hasSiblings:!1,siblings:[t.message],index:0,selected:t.message}}return{hasSiblings:!1,siblings:[],index:0,selected:void 0}}selectSibling(e,t){this._logger.trace(`DefaultView.selectSibling();`,{codecMessageId:e,index:t});let n=this._resolveMessageBranchPoint(e);if(!n)return;let r=Math.max(0,Math.min(t,n.siblings.length-1)),i=n.siblings[r];i&&(n.kind===`fork-of`?(this._branchSelections.set(n.groupRoot,{kind:`user`,selectedKey:N(i)}),this._logger.debug(`DefaultView.selectSibling(); fork-of`,{codecMessageId:e,index:r,selectedKey:N(i)})):(this._regenSelections.set(n.groupRoot,{kind:`user`,selectedRunId:N(i)}),this._logger.debug(`DefaultView.selectSibling(); regenerate`,{codecMessageId:e,index:r,selectedRunId:N(i),groupRoot:n.groupRoot})),this._recomputeAndEmit())}_resolveSelectedIndex(e){if(e.kind===`fork-of`){let t=this._branchSelections.get(e.groupRoot);if(!t)return e.siblings.length-1;let n=e.siblings.findIndex(e=>N(e)===t.selectedKey);return n===-1?e.siblings.length-1:n}let t=this._regenSelections.get(e.groupRoot);if(!t||t.kind===`pending`)return e.siblings.length-1;let n=e.siblings.findIndex(e=>N(e)===t.selectedRunId);return n===-1?e.siblings.length-1:n}_resolveMessageBranchPoint(e){let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`input`){let e=this._tree.getSiblingNodes(t.codecMessageId);return e.length>1?{kind:`fork-of`,groupRoot:this._tree.getGroupRoot(t.codecMessageId),siblings:e}:void 0}let n=this._tree.getSiblingNodes(t.runId);if(n.length>1&&this._codec.getMessages(t.projection).at(0)?.codecMessageId===e)return{kind:`regen`,groupRoot:this._tree.getGroupRoot(t.runId),siblings:n}}async send(e,n){if(this._logger.trace(`DefaultView.send();`),this._closed)throw new t.ErrorInfo(`unable to send; view is closed`,T.InvalidArgument,400);let r=me(e),i=this._lastVisibleMessagePairs.at(-1)?.codecMessageId,a=await this._sendDelegate(r,n,i);return this._applyForkAutoSelect(a,n),a}_applyForkAutoSelect(e,t){if(!t?.forkOf)return;let n=e.optimisticCodecMessageIds.at(0);if(n===void 0)return;let r=this._tree.getGroupRoot(n);this._branchSelections.set(r,{kind:`auto`,selectedKey:n}),this._recomputeAndEmit()}_applyRegenerateAutoSelect(e,t){let n=this._runByCodecMessageId(t);if(!n)return;let r=this._tree.getGroupRoot(n.runId);this._regenSelections.set(r,{kind:`pending`,carrierCodecMessageId:e.inputCodecMessageId}),this._logger.debug(`DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection`,{anchorCodecMessageId:t,groupRoot:r,carrier:e.inputCodecMessageId}),this._resolvePendingRegenSelections(),this._recomputeAndEmitIfChanged()}async regenerate(e,n){if(this._logger.trace(`DefaultView.regenerate();`,{messageId:e}),this._closed)throw new t.ErrorInfo(`unable to regenerate; view is closed`,T.InvalidArgument,400);let r=this._runByCodecMessageId(e);if(!r)throw new t.ErrorInfo(`unable to regenerate; message not found in tree: ${e}`,T.InvalidArgument,400);let i=this._findParentMsgId(r,e);if(!i)throw new t.ErrorInfo(`unable to regenerate; parent user message not found for ${e}`,T.InvalidArgument,400);let a=e;r.regeneratesCodecMessageId!==void 0&&this._codec.getMessages(r.projection).at(0)?.codecMessageId===e&&(a=r.regeneratesCodecMessageId);let o={...n,parent:i},s=this._codec.createRegenerate(a,i),c=await this._sendDelegate([s],o,i);return this._applyRegenerateAutoSelect(c,a),c}async edit(e,n,r){if(this._logger.trace(`DefaultView.edit();`,{messageId:e}),this._closed)throw new t.ErrorInfo(`unable to edit; view is closed`,T.InvalidArgument,400);let i=this._tree.getNodeByCodecMessageId(e);if(!i)throw new t.ErrorInfo(`unable to edit; message not found in tree: ${e}`,T.InvalidArgument,400);let a=this._findParentMsgId(i,e);return this.send(n,{...r,forkOf:e,parent:a})}_findParentMsgId(e,t){let n=this._lastVisibleMessagePairs,r=n.findIndex(e=>e.codecMessageId===t);if(r>0)return n[r-1]?.codecMessageId;if(r===0)return;let i=this._codec.getMessages(e.projection),a=i.findIndex(e=>e.codecMessageId===t);if(a>0)return i[a-1]?.codecMessageId;if(a===0&&e.parentCodecMessageId!==void 0){let t=this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);if(t)return this._codec.getMessages(t.projection).at(-1)?.codecMessageId}}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}close(){if(!this._closed){this._logger.info(`DefaultView.close();`),this._closed=!0,this._loadingOlder=!1;for(let e of this._unsubs)e();this._unsubs.length=0,this._emitter.off(),this._branchSelections.clear(),this._regenSelections.clear(),this._withheldRunIds.clear(),this._withheldBuffer.length=0,this._onClose?.()}}async _loadFirstPage(e){let t=e*he,n=await pe(this._channel,{limit:t},this._logger);this._closed||await this._revealFromPage(n,e)}async _revealFromPage(e,t){let n=new Set(this._treeVisibleNodes().map(e=>N(e))),{newVisible:r,lastPage:i}=await this._loadUntilVisible(e,t,n);this._closed||(this._lastHistoryPage=i,this._hasMoreHistory=i.hasNext(),this._splitReveal(r,t))}_splitReveal(e,t){let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){if(e[i]?.kind===`run`){if(n===t)break;n++}r=i}let i=e.slice(r),a=e.slice(0,r);for(let e of a)this._withheldRunIds.add(N(e));this._withheldBuffer.push(...a),this._releaseWithheld(i)}_processHistoryPage(e){this._processingHistory=!0;try{let t=this._codec.createDecoder();for(let n of e.rawMessages)M(this._tree,t,n);for(let t of e.rawMessages)this._tree.emitAblyMessage(t)}finally{this._processingHistory=!1}}async _loadUntilVisible(e,t,n){this._processHistoryPage(e);let r=e,i=()=>{let e=0;for(let t of this._treeVisibleNodes())t.kind===`run`&&!n.has(N(t))&&e++;return e};for(;i()<t&&r.hasNext();){let e=await r.next();if(!e||this._closed)break;this._processHistoryPage(e),r=e}return{newVisible:this._treeVisibleNodes().filter(e=>!n.has(N(e))),lastPage:r}}_releaseWithheld(e){for(let t of e)this._withheldRunIds.delete(N(t));e.length>0&&this._recomputeAndEmit()}_updateVisibleSnapshot(e){let t=e??this._cachedNodes;this._lastVisibleNodeKeys=t.map(e=>N(e)),this._lastVisibleNodeKeySet=new Set(this._lastVisibleNodeKeys),this._lastVisibleProjections=t.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(t)}_onTreeUpdate(){this._processingHistory||(this._pinBranchSelections(),this._resolvePendingRegenSelections(),this._recomputeAndEmitIfChanged())}_resolveSelections(){let e=new Map;for(let[t,n]of this._branchSelections)e.set(t,n.selectedKey);for(let[t,n]of this._regenSelections)n.kind!==`pending`&&e.set(t,n.selectedRunId);return e}_treeVisibleNodes(){return this._tree.visibleNodes(this._resolveSelections())}_pinBranchSelections(){for(let e of this._lastVisibleNodeKeys){if(this._tree.getNode(e)?.kind!==`input`||this._tree.getSiblingNodes(e).length<=1)continue;let t=this._tree.getGroupRoot(e);this._branchSelections.get(t)||this._branchSelections.set(t,{kind:`pinned`,selectedKey:e})}}_resolvePendingRegenSelections(){for(let[e,t]of this._regenSelections){if(t.kind===`user`)continue;let n=this._tree.getSiblingNodes(e).filter(e=>e.kind===`run`);if(n.length<=1)continue;let r=n.at(-1);r&&this._regenSelections.set(e,{kind:`auto`,selectedRunId:r.runId})}}_onTreeAblyMessage(e){let t=A(e),n=t[g],r=t[p];if(!n&&!r){this._emitter.emit(`ably-message`,e);return}r&&this._lastVisibleNodeKeySet.has(r)&&this._emitter.emit(`ably-message`,e)}_onTreeRun(e){if(this._lastVisibleNodeKeySet.has(e.runId)){this._emitter.emit(`run`,e);return}e.type===`start`&&this._isRunStartVisible(e)&&(this._lastVisibleNodeKeySet.add(e.runId),this._emitter.emit(`run`,e))}_isRunStartVisible(e){let{parent:t}=e;if(t===void 0)return!0;let n=this._tree.getNodeByCodecMessageId(t);return n?this._lastVisibleNodeKeySet.has(N(n)):!0}_visibleChanged(e){if(e.length!==this._lastVisibleNodeKeys.length)return!0;for(let[t,n]of e.entries())if(N(n)!==this._lastVisibleNodeKeys[t]||n.projection!==this._lastVisibleProjections[t])return!0;return!1}},U=e=>new ge(e),_e=()=>{},ve=class{constructor(e){this._views=new Set,this._state=`ready`,this._pendingRunStarts=new Map;let t=ce(e.client,e.codec);if(this._channel=e.client.channels.get(e.channelName,t),this._codec=e.codec,this._clientId=e.clientId,this._logger=(e.logger??ae({logLevel:re.Silent})).withContext({component:`ClientSession`}),this._emitter=new E(this._logger),this._hasAttachedOnce=this._channel.state===`attached`,this._tree=R(this._codec,this._logger),this._view=U({tree:this._tree,channel:this._channel,codec:this._codec,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(this._view)}),this._decoder=this._codec.createDecoder(),this._encoder=this._codec.createEncoder(this._channel,this._clientId===void 0?void 0:{clientId:this._clientId}),this._views.add(this._view),this.tree=this._tree,this.view=this._view,e.messages){let t;for(let n of e.messages){let e=crypto.randomUUID(),r={[g]:e,[y]:`user`};t&&(r[b]=t),this._tree.applyMessage({inputs:[this._codec.createUserMessage(n)],outputs:[]},r),t=e}}this._onMessage=e=>{this._handleMessage(e)},this._onChannelStateChange=e=>{this._handleChannelStateChange(e)},this._channel.on(this._onChannelStateChange)}connect(){return this._state===`closed`?Promise.reject(new t.ErrorInfo(`unable to connect; session is closed`,T.SessionClosed,400)):this._connectPromise?this._connectPromise:(this._logger.trace(`DefaultClientSession.connect();`),this._connectPromise=this._channel.subscribe(this._onMessage).then(()=>{this._logger.debug(`DefaultClientSession.connect(); subscribed and attached`)},e=>{let n=new t.ErrorInfo(`unable to subscribe to channel; ${e instanceof Error?e.message:String(e)}`,T.SessionSubscriptionError,500,e instanceof t.ErrorInfo?e:void 0);throw this._logger.error(`DefaultClientSession.connect(); subscribe failed`),this._emitter.emit(`error`,n),n}),this._connectPromise)}async _requireConnected(e){if(!this._connectPromise)throw new t.ErrorInfo(`unable to ${e}; connect() must be called before ${e}()`,T.InvalidArgument,400);return this._connectPromise}_handleMessage(e){if(this._state!==`closed`)try{if(e.name===`ai-run-end`){let n=A(e);if((n[`run-reason`]??`complete`)===`error`){let e=n[w],r=e===void 0?NaN:Number(e),i=Number.isFinite(r)?r:T.SessionSubscriptionError,a=n[`error-message`]??`agent reported an error`,o=i>=1e4&&i<6e4?Math.floor(i/100):500,s=new t.ErrorInfo(a,i,o);this._logger.error(`ClientSession._handleMessage(); agent error received`,{runId:n[p],invocationId:n[m],code:i}),this._emitter.emit(`error`,s)}}let n=M(this._tree,this._decoder,e);if(n&&(n.type===`start`||n.type===`resume`)){let t=A(e)[C];if(t!==void 0){let e=this._pendingRunStarts.get(t);e&&(this._pendingRunStarts.delete(t),e.resolve(n.runId))}}this._tree.emitAblyMessage(e)}catch(e){let n=e instanceof t.ErrorInfo?e:void 0;this._emitter.emit(`error`,new t.ErrorInfo(`unable to process channel message; ${e instanceof Error?e.message:String(e)}`,T.SessionSubscriptionError,500,n))}}_handleChannelStateChange(e){if(this._state===`closed`)return;let{current:n,resumed:r}=e;if(n===`attached`&&!this._hasAttachedOnce){this._hasAttachedOnce=!0;return}if(!(n===`failed`||n===`suspended`||n===`detached`||n===`attached`&&!r))return;this._logger.error(`ClientSession._handleChannelStateChange(); channel continuity lost`,{current:n,resumed:r,previous:e.previous});let i=new t.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n===`attached`?`, resumed: false`:``})`,T.ChannelContinuityLost,500,e.reason);this._emitter.emit(`error`,i)}_cleanupFailedSend(e){for(let t of e){let e=this._tree.getNodeByCodecMessageId(t);e?.kind===`input`&&e.serial===void 0&&this._tree.delete(e.codecMessageId)}}createView(){if(this._state===`closed`)throw new t.ErrorInfo(`unable to create view; session is closed`,T.SessionClosed,400);this._logger.trace(`DefaultClientSession.createView();`);let e=U({tree:this._tree,channel:this._channel,codec:this._codec,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(e)});return this._views.add(e),e}async _internalSend(e,n,r){if(this._state===`closed`||(await this._requireConnected(`send`),this._state===`closed`))throw new t.ErrorInfo(`unable to send; session is closed`,T.SessionClosed,400);let i=this._channel.state;if(i!==`attached`&&i!==`attaching`)throw new t.ErrorInfo(`unable to send; channel is ${i}`,T.ChannelNotReady,400);this._logger.trace(`ClientSession._internalSend();`);let a=n?.runId!==void 0,o=n?.runId,s;n?.parent===void 0&&!n?.forkOf&&(s=r);let c=new Set,l=[];for(let t of e){let e=crypto.randomUUID(),r=t.codecMessageId??crypto.randomUUID();c.add(r);let i=t.kind!==`user-message`&&(t.kind===`regenerate`||t.codecMessageId!==void 0),a=t.parent??(n?.parent===void 0?s:n.parent),u=n?.forkOf,d=t.kind===`regenerate`?t.target:void 0,f=le({role:`user`,runId:o,codecMessageId:r,runClientId:this._clientId,...a!==void 0&&{parent:a},...u!==void 0&&{forkOf:u},...d!==void 0&&{regenerates:d},inputEventId:e});i||this._tree.applyMessage({inputs:[t],outputs:[]},f),l.push({input:t,codecMessageId:r,inputEventId:e,headers:f,isWireOnly:i}),!i&&n?.parent===void 0&&!n?.forkOf&&t.parent===void 0&&(s=r)}let u=l.at(-1);if(u===void 0)throw new t.ErrorInfo(`unable to send; inputs array is empty (include at least one input)`,T.InvalidArgument,400);let d=u.inputEventId,f=u.codecMessageId,p=new Promise((e,t)=>{this._pendingRunStarts.set(f,{resolve:e,reject:t})});return p.catch(()=>{}),await(async()=>{try{for(let e of l)await this._encoder.publishInput(e.input,{extras:{headers:e.headers},messageId:e.codecMessageId,...this._clientId!==void 0&&{clientId:this._clientId}})}catch(e){let n=e instanceof t.ErrorInfo?e:void 0,r=n?.statusCode===401||n?.statusCode===403,i=new t.ErrorInfo(r?`unable to publish events; missing publish capability on the channel`:`unable to publish events; ${e instanceof Error?e.message:String(e)}`,r?T.InsufficientCapability:T.SessionSendFailed,r?401:500,n);throw this._emitter.emit(`error`,i),this._pendingRunStarts.delete(f),a||this._cleanupFailedSend([...c]),i}})(),{inputCodecMessageId:f,runId:p,inputEventId:d,cancel:async()=>{await this._publishCancel({inputCodecMessageId:f,...o!==void 0&&{runId:o}})},optimisticCodecMessageIds:[...c],toInvocation:()=>fe.fromJSON({inputEventId:d,sessionName:this._channel.name})}}async cancel(e){return this._publishCancel({runId:e})}async _publishCancel(e){if(this._state===`closed`||(await this._requireConnected(`cancel`),this._state===`closed`))return;this._logger.debug(`ClientSession._publishCancel();`,{runId:e.runId,inputCodecMessageId:e.inputCodecMessageId});let t={[h]:crypto.randomUUID()};e.runId!==void 0&&(t[p]=e.runId),e.inputCodecMessageId!==void 0&&(t[C]=e.inputCodecMessageId),await this._channel.publish({name:ee,extras:{ai:{transport:t}}})}on(e,t){if(this._state===`closed`)return _e;let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}async close(){if(this._state!==`closed`){this._state=`closed`,this._logger.info(`ClientSession.close();`),this._connectPromise&&this._channel.unsubscribe(this._onMessage),this._channel.off(this._onChannelStateChange),this._emitter.off();for(let e of this._views)e.close();if(this._views.clear(),this._pendingRunStarts.size>0){let e=new t.ErrorInfo(`unable to await run-start; session closed`,T.SessionClosed,400);for(let t of this._pendingRunStarts.values())t.reject(e);this._pendingRunStarts.clear()}try{await this._encoder.close()}catch{}if(this._connectPromise)try{await this._channel.detach()}catch(e){this._logger.debug(`ClientSession.close(); channel detach failed`,{error:e})}}}},ye=e=>new ve(e),W=(0,r.createContext)({nearest:void 0,providers:{}}),G=({children:e,...a})=>{let o=(0,n.useAbly)(),{channelName:s}=a,c=(0,r.useRef)(void 0),l=(0,r.useRef)(s),u=(0,r.useRef)([]),d=(0,r.useRef)(!1),f=(0,r.useRef)(void 0);if(!(c.current||f.current)||l.current!==s){l.current=s,c.current&&u.current.push(c.current);try{c.current=ye({...a,client:o}),f.current=void 0}catch(e){c.current=void 0,f.current=e instanceof t.ErrorInfo?e:new t.ErrorInfo(`Unknown error while creating client session`,T.BadRequest,400)}}let p=(0,r.useContext)(W),m=c.current,h=f.current,g=(0,r.useMemo)(()=>({session:m,sessionError:h}),[m,h]),_=(0,r.useMemo)(()=>({nearest:g,providers:{...p.providers,[s]:g}}),[s,p,g]);return(0,r.useEffect)(()=>()=>{for(let e of u.current)e.close()},[s]),(0,r.useEffect)(()=>{c.current?.connect()},[s]),(0,r.useEffect)(()=>(d.current=!1,()=>{d.current=!0,Promise.resolve().then(()=>{d.current&&c.current?.close()})}),[]),(0,i.jsx)(W.Provider,{value:_,children:e})},K=({session:e,skip:t}={})=>{let{nearest:n}=(0,r.useContext)(W),i=n?.session;if(!t&&e!==null)return e??i},q=({session:e,skip:t}={})=>{let n=K({session:e,skip:t}),[i,a]=(0,r.useState)([]),o=(0,r.useRef)([]);return(0,r.useEffect)(()=>{if(o.current=[],a([]),n)return n.tree.on(`ably-message`,e=>{let t=[...o.current,e];o.current=t,a(t)})},[n]),i},J={get tree(){throw new t.ErrorInfo(`unable to access tree; hook is skipped`,T.InvalidArgument,400)},get view(){throw new t.ErrorInfo(`unable to access view; hook is skipped`,T.InvalidArgument,400)},connect:()=>{throw new t.ErrorInfo(`unable to connect; hook is skipped`,T.InvalidArgument,400)},createView:()=>{throw new t.ErrorInfo(`unable to create view; hook is skipped`,T.InvalidArgument,400)},cancel:()=>{throw new t.ErrorInfo(`unable to cancel; hook is skipped`,T.InvalidArgument,400)},on:()=>{throw new t.ErrorInfo(`unable to subscribe; hook is skipped`,T.InvalidArgument,400)},close:()=>{throw new t.ErrorInfo(`unable to close; hook is skipped`,T.InvalidArgument,400)}},Y=({channelName:e,skip:n,onError:i}={})=>{let{nearest:a,providers:o}=(0,r.useContext)(W),s=(0,r.useRef)(i);s.current=i;let c=n?void 0:e===void 0?a?.session:o[e]?.session;if((0,r.useEffect)(()=>{if(c)return c.on(`error`,e=>{s.current?.(e)})},[c]),n)return{session:J};if(e!==void 0){let n=o[e];return n?n.session?{session:n.session}:{session:J,sessionError:n.sessionError}:{session:J,sessionError:new t.ErrorInfo(`unable to use session; no ClientSessionProvider found for channelName "${e}"`,T.BadRequest,400)}}return a?a.session?{session:a.session}:{session:J,sessionError:a.sessionError}:{session:J,sessionError:new t.ErrorInfo(`unable to use session; no ClientSessionProvider found in the tree`,T.BadRequest,400)}},X={hasSiblings:!1,siblings:[],index:0,selected:void 0},Z=({session:e,view:n,limit:i,skip:a}={})=>{let o=K({session:e,skip:a}),s=a?void 0:n??o?.view,[c,l]=(0,r.useState)(()=>s?.getMessages()??[]),[u,d]=(0,r.useState)(()=>s?.hasOlder()??!1),[f,p]=(0,r.useState)(!1),[m,h]=(0,r.useState)(),g=(0,r.useRef)(!1),_=i!==void 0,v=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!s){l([]),d(!1),h(void 0);return}return v.current=!1,l(s.getMessages()),d(s.hasOlder()),h(void 0),s.on(`update`,()=>{l(s.getMessages()),d(s.hasOlder())})},[s]);let y=(0,r.useCallback)(async()=>{if(!(!s||g.current)){g.current=!0,p(!0);try{await s.loadOlder(i),h(void 0)}catch(e){e instanceof t.ErrorInfo?h(e):h(new t.ErrorInfo(`Unknown error loading older messages`,T.BadRequest,400))}finally{g.current=!1,p(!1)}}},[s,i]);return(0,r.useEffect)(()=>{!_||v.current||!s||(v.current=!0,y())},[_,s,y]),{messages:c,hasOlder:u,loading:f,loadError:m,loadOlder:y,runOf:(0,r.useCallback)(e=>s?.runOf(e),[s]),run:(0,r.useCallback)(e=>s?.run(e),[s]),runs:(0,r.useCallback)(()=>s?.runs()??[],[s]),branchSelection:(0,r.useCallback)(e=>s?.branchSelection(e)??X,[s]),selectSibling:(0,r.useCallback)((e,t)=>{s?.selectSibling(e,t)},[s]),send:(0,r.useCallback)(async(e,n)=>{if(!s)throw new t.ErrorInfo(`unable to send; view is not available`,T.InvalidArgument,400);return s.send(e,n)},[s]),regenerate:(0,r.useCallback)(async(e,n)=>{if(!s)throw new t.ErrorInfo(`unable to regenerate; view is not available`,T.InvalidArgument,400);return s.regenerate(e,n)},[s]),edit:(0,r.useCallback)(async(e,n,r)=>{if(!s)throw new t.ErrorInfo(`unable to edit; view is not available`,T.InvalidArgument,400);return s.edit(e,n,r)},[s])}},Q=({session:e,limit:t,skip:n}={})=>{let i=K({session:e,skip:n}),[a,o]=(0,r.useState)();return(0,r.useEffect)(()=>{if(!i){o(void 0);return}let e=i.createView();return o(e),()=>{e.close()}},[i]),Z({view:a,limit:t,skip:n})},$=({session:e}={})=>{let t=K({session:e});return{getRunNode:(0,r.useCallback)(e=>t?.tree.getRunNode(e),[t]),getNodeByCodecMessageId:(0,r.useCallback)(e=>t?.tree.getNodeByCodecMessageId(e),[t]),getSiblingNodes:(0,r.useCallback)(e=>t?.tree.getSiblingNodes(e)??[],[t])}};e.ClientSessionProvider=G,e.createSessionHooks=()=>({ClientSessionProvider:G,useClientSession:e=>Y(e??{}),useView:e=>Z(e??{}),useTree:e=>$(e??{}),useAblyMessages:e=>q(e??{}),useCreateView:e=>Q(e??{})}),e.useAblyMessages=q,e.useClientSession=Y,e.useCreateView=Q,e.useTree=$,e.useView=Z});
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`ably`),require(`ably/react`),require(`react`),require(`react/jsx-runtime`)):typeof define==`function`&&define.amd?define([`exports`,`ably`,`ably/react`,`react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.AblyAiTransportReact={},e.Ably,e.AblyReact,e.React,e.ReactJsxRuntime))})(this,function(e,t,n,r,i){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var a=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,c=Object.getOwnPropertyNames,l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=c(t),a=0,l=i.length,d;a<l;a++)d=i[a],!u.call(e,d)&&d!==n&&o(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=s(t,d))||r.enumerable});return e};t=((e,t,n)=>(n=e==null?{}:a(l(e)),d(t||!e||!e.__esModule?o(n,`default`,{value:e,enumerable:!0}):n,e)))(t,1);var f=[`PUBLISH`,`SUBSCRIBE`,`PRESENCE`,`PRESENCE_SUBSCRIBE`,`ANNOTATION_PUBLISH`],p=[`OBJECT_SUBSCRIBE`,`OBJECT_PUBLISH`],m=[`PUBLISH`,`SUBSCRIBE`,`PRESENCE`,`PRESENCE_SUBSCRIBE`,`OBJECT_PUBLISH`,`OBJECT_SUBSCRIBE`,`ANNOTATION_PUBLISH`,`ANNOTATION_SUBSCRIBE`],h=e=>{if(e===void 0||e.length===0)return;let t=new Set([...f,...e]),n=m.filter(e=>t.has(e)),r=[...t].filter(e=>!m.includes(e)).toSorted();return[...n,...r]},g=`0.3.0`,_=`ai-transport-js`,v=(e,t)=>{let n=e;return n.options.agents={...n.options.agents,...t},{params:{agent:b(t)}}},y=e=>{let t=e?.adapterTag,n={[_]:g};return t&&(n[t]=g),n},b=e=>Object.entries(e).map(([e,t])=>`${e}/${t}`).join(` `),ee=e=>b(y(e)),te=(e,t)=>v(e,y(t)),x=`stream`,ne=`status`,S=`run-id`,re=`invocation-id`,C=`event-id`,w=`codec-message-id`,ie=`run-client-id`,ae=`input-client-id`,T=`role`,E=`parent`,D=`fork-of`,O=`msg-regenerate`,k=`input-codec-message-id`,oe=`error-code`,se=`ai-cancel`,A=function(e){return e[e.BadRequest=4e4]=`BadRequest`,e[e.InvalidArgument=40003]=`InvalidArgument`,e[e.InsufficientCapability=40160]=`InsufficientCapability`,e[e.EncoderRecoveryFailed=104e3]=`EncoderRecoveryFailed`,e[e.SessionSubscriptionError=104001]=`SessionSubscriptionError`,e[e.CancelListenerError=104002]=`CancelListenerError`,e[e.RunLifecycleError=104003]=`RunLifecycleError`,e[e.SessionClosed=104004]=`SessionClosed`,e[e.SessionSendFailed=104005]=`SessionSendFailed`,e[e.ChannelContinuityLost=104006]=`ChannelContinuityLost`,e[e.ChannelNotReady=104007]=`ChannelNotReady`,e[e.StreamError=104008]=`StreamError`,e[e.InputEventNotFound=104010]=`InputEventNotFound`,e[e.HistoryFetchFailed=104011]=`HistoryFetchFailed`,e}({}),ce=e=>({logAction:(t,n,r)=>{e.error(n,{detail:r})},shouldLog:()=>!0}),le=t.Realtime.EventEmitter,j=class extends le{constructor(e){super(ce(e))}},ue=function(e){return e.Trace=`trace`,e.Debug=`debug`,e.Info=`info`,e.Warn=`warn`,e.Error=`error`,e.Silent=`silent`,e}({}),de=(e,t,n)=>{let r=n?`, context: ${JSON.stringify(n)}`:``,i=`[${new Date().toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;switch(t){case`trace`:case`debug`:console.log(i);break;case`info`:console.info(i);break;case`warn`:console.warn(i);break;case`error`:console.error(i);break;case`silent`:break}},fe=e=>new pe(e.logHandler??de,e.logLevel),M=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4],[`silent`,5]]),pe=class e{constructor(e,n,r){this._handler=e,this._context=r;let i=M.get(n);if(i===void 0)throw new t.ErrorInfo(`unable to create logger; invalid log level: ${n}`,A.InvalidArgument,400);this._levelNumber=i}trace(e,t){this._write(e,`trace`,0,t)}debug(e,t){this._write(e,`debug`,1,t)}info(e,t){this._write(e,`info`,2,t)}warn(e,t){this._write(e,`warn`,3,t)}error(e,t){this._write(e,`error`,4,t)}withContext(t){let n=[...M.entries()].find(([,e])=>e===this._levelNumber)?.[0]??`error`;return new e(this._handler,n,this._mergeContext(t))}_write(e,t,n,r){n>=this._levelNumber&&this._handler(e,t,this._mergeContext(r))}_mergeContext(e){return this._context?e?{...this._context,...e}:this._context:e??void 0}},N=e=>e instanceof Error?e.message:String(e),P=e=>e instanceof t.ErrorInfo?e:void 0,me=(e,t)=>{let n=e.extras;if(!n||typeof n!=`object`)return{};let r=n.ai;if(!r||typeof r!=`object`)return{};let i=r[t];return!i||typeof i!=`object`?{}:i},F=e=>me(e,`transport`),he=e=>{let t={[T]:e.role,[w]:e.codecMessageId};return e.runId!==void 0&&(t[S]=e.runId),e.runClientId!==void 0&&(t[ie]=e.runClientId),e.parent&&(t[E]=e.parent),e.forkOf&&(t[D]=e.forkOf),e.regenerates&&(t[O]=e.regenerates),e.invocationId&&(t[re]=e.invocationId),e.inputClientId!==void 0&&(t[ae]=e.inputClientId),e.inputCodecMessageId!==void 0&&(t[k]=e.inputCodecMessageId),e.inputEventId&&(t[C]=e.inputEventId),t},ge=e=>e===`ai-run-start`||e===`ai-run-suspend`||e===`ai-run-resume`||e===`ai-run-end`,I=e=>{let n=e[oe],r=n===void 0?NaN:Number(n),i=Number.isFinite(r)?r:A.SessionSubscriptionError,a=e[`error-message`]??`agent reported an error`,o=i>=1e4&&i<6e4?Math.floor(i/100):500;return new t.ErrorInfo(a,i,o)},_e=(e,t,n,r)=>{let i=t[S];if(!i)return;let a=t[`run-client-id`]??``,o=r===void 0?{}:{timestamp:r};if(e===`ai-run-start`){let e=t[E],r=t[D],s=t[O];return{type:`start`,runId:i,clientId:a,serial:n,invocationId:t[`invocation-id`]??``,...o,...e!==void 0&&{parent:e},...r!==void 0&&{forkOf:r},...s!==void 0&&{regenerates:s}}}if(e===`ai-run-suspend`)return{type:`suspend`,runId:i,clientId:a,serial:n,invocationId:t[`invocation-id`]??``,...o};if(e===`ai-run-resume`)return{type:`resume`,runId:i,clientId:a,serial:n,invocationId:t[`invocation-id`]??``,...o};if(e===`ai-run-end`){let e=t[`run-reason`]??`complete`,r=t[`invocation-id`]??``;return e===`error`?{type:`end`,runId:i,clientId:a,serial:n,invocationId:r,reason:e,...o,error:I(t)}:{type:`end`,runId:i,clientId:a,serial:n,invocationId:r,reason:e,...o}}},ve=(e,t,n)=>{let r=F(n),i=n.serial,a=n.timestamp;if(ge(n.name)){let t=_e(n.name,r,i,a);return t&&e.applyRunLifecycle(t),t}let{inputs:o,outputs:s}=t.decode(n);(o.length>0||s.length>0||r[`run-id`])&&e.applyMessage({inputs:o,outputs:s},r,i,a,n.version.serial)},ye=(e,t)=>({apply:n=>ve(e,t,n)}),be=class e{constructor(e){this.inputEventId=e.inputEventId,this.sessionName=e.sessionName}static fromJSON(t){return new e(t)}toJSON(){return{inputEventId:this.inputEventId,sessionName:this.sessionName}}},xe=async(e,n)=>{if(!e)throw new t.ErrorInfo(`unable to ${n}; connect() must be called before ${n}()`,A.InvalidArgument,400);return e},Se=async(e,t,n,r)=>{if(t!==void 0)try{await e.detach()}catch(e){n?.debug(`${r}.close(); channel detach failed`,{error:e})}},Ce=e=>{let{current:t,resumed:n}=e;return t===`failed`||t===`suspended`||t===`detached`||t===`attached`&&!n},we=(e,n)=>{let{current:r}=e;return new t.ErrorInfo(`unable to ${n}; channel continuity lost (${r}${r===`attached`?`, resumed: false`:``})`,A.ChannelContinuityLost,500,e.reason)},L=e=>[...e.inputs.map(e=>({direction:`input`,event:e})),...e.outputs.map(e=>({direction:`output`,event:e}))],Te=class{constructor(){this._entries=[],this._swept=!1}get swept(){return this._swept}record(e,t,n,r,i){let a=this._recordEntry(e,t,this._swept?[]:n,r,i);return a===void 0?`dropped`:this._swept||a===this._entries.length-1?`incremental`:`refold`}replay(e){for(let t of this._entries)for(let n of t.events)e(n,t.serial,t.messageId)}sweep(){this._swept=!0;for(let e of this._entries)e.events.length=0}_recordEntry(e,t,n,r,i){for(let a=this._entries.length-1;a>=0;a--){let o=this._entries[a];if(!o)break;if(o.serial===e)return r!==void 0&&(r<=o.decodedThrough||!i)?void 0:(o.events.push(...n),r!==void 0&&(o.decodedThrough=r),a);if(o.serial<e)return this._entries.splice(a+1,0,{serial:e,messageId:t,events:[...n],decodedThrough:r??e}),a+1}return this._entries.unshift({serial:e,messageId:t,events:[...n],decodedThrough:r??e}),0}},R=e=>e.kind===`run`?e.runId:e.codecMessageId,z=e=>e.kind===`run`?e.startSerial:e.serial,B=(e,t,n)=>{let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)},V=(e,t,n)=>{let r=e.get(t);r&&(r.delete(n),r.size===0&&e.delete(t))},Ee=class{constructor(e,t){this._nodeIndex=new Map,this._codecMessageIdToNodeKey=new Map,this._sortedNodes=[],this._parentIndex=new Map,this._replyRunsByInput=new Map,this._seqCounter=0,this._structuralVersion=0,this._siblingCache=new Map,this._siblingCacheVersion=-1,this._eventIdIndex=new Map,this._clock=0,this._sweepQueue=[],this._codec=e,this._logger=t,this._emitter=new j(t)}_compareNodes(e,t){let n=z(e.node),r=z(t.node);return n===void 0&&r===void 0?e.insertSeq-t.insertSeq:n===void 0?1:r===void 0||n<r?-1:n>r?1:e.insertSeq-t.insertSeq}_insertSortedNode(e){if(z(e.node)===void 0){this._sortedNodes.push(e);return}let t=0,n=this._sortedNodes.length;for(;t<n;){let r=t+n>>>1,i=this._sortedNodes[r];if(!i)break;this._compareNodes(i,e)<=0?t=r+1:n=r}this._sortedNodes.splice(t,0,e)}_removeSortedNode(e){let t=this._sortedNodes.indexOf(e);t!==-1&&this._sortedNodes.splice(t,1)}_insertNode(e,t,n){this._nodeIndex.set(e,t),this._addToParentIndex(n,e),this._insertSortedNode(t),this._structuralVersion++}_promoteSerial(e){this._removeSortedNode(e),this._insertSortedNode(e),this._structuralVersion++}_foldInto(e,t,n,r){for(let i of t)try{e.node.projection=this._codec.fold(e.node.projection,i,{serial:n??``,messageId:r})}catch(t){this._logger.error(`Tree._foldInto(); fold threw`,{key:R(e.node),messageId:r,err:t})}}_recordAndFold(e,t,n,r,i,a){if(n===void 0||t.length===0){n===void 0&&t.length>0&&(e.optimistic=!0),this._foldInto(e,t,n,r);return}let o=e.log.record(n,r,t,i,a);if(o===`dropped`){this._logger.debug(`Tree._recordAndFold(); version guard dropped re-delivered wire`,{key:R(e.node),serial:n,version:i,swept:e.log.swept});return}if(e.optimistic&&!e.log.swept){e.optimistic=!1,this._refold(e);return}if(o===`refold`){this._refold(e);return}e.log.swept&&this._logger.warn(`Tree._recordAndFold(); late wire after log retention window; folding in arrival order`,{key:R(e.node),serial:n}),this._foldInto(e,t,n,r)}_refold(e){let t=this._codec.init();e.log.replay((n,r,i)=>{try{t=this._codec.fold(t,n,{serial:r,messageId:i})}catch(t){this._logger.error(`Tree._refold(); fold threw`,{key:R(e.node),messageId:i,err:t})}}),e.node.projection=t}_recordActivity(e,t){t!==void 0&&(t>e.lastActivityTs&&(e.lastActivityTs=t),t>this._clock&&(this._clock=t,this._drainSweepQueue()))}_maybeQueueSweep(e){let t=e.node;t.kind===`run`&&(e.log.swept||e.sweepQueued||e.runStartSeen&&(t.state.status===`active`||t.state.status===`suspended`||(e.sweepQueued=!0,this._sweepQueue.push(t.runId))))}_drainSweepQueue(){for(;this._sweepQueue.length>0;){let e=this._sweepQueue[0],t=e===void 0?void 0:this._nodeIndex.get(e);if(!t||t.log.swept){this._sweepQueue.shift();continue}if(t.lastActivityTs+12e4>=this._clock)return;this._sweepQueue.shift(),t.sweepQueued=!1,t.log.sweep(),this._logger.debug(`Tree._drainSweepQueue(); dropped event-log payloads, kept replay keys`,{key:e,lastActivityTs:t.lastActivityTs})}}_addToParentIndex(e,t){B(this._parentIndex,e,t)}_removeFromParentIndex(e,t){V(this._parentIndex,e,t)}_parentKeyOf(e){let t=e.parentCodecMessageId;return t===void 0?void 0:this._codecMessageIdToNodeKey.get(t)}_inputGroupRoot(e){let t=e,n=new Set([R(t)]);for(;t.forkOf!==void 0&&!n.has(t.forkOf);){let e=this._nodeIndex.get(t.forkOf);if(e?.node.kind!==`input`||e.node.parentCodecMessageId!==t.parentCodecMessageId)break;t=e.node,n.add(R(t))}return t}_getSiblingGroup(e){this._siblingCacheVersion!==this._structuralVersion&&(this._siblingCache.clear(),this._siblingCacheVersion=this._structuralVersion);let t=this._siblingCache.get(e);if(t)return t;let n=this._nodeIndex.get(e);if(!n)return[];let r=n.node;r.kind===`input`&&(r=this._inputGroupRoot(r));let i=r.parentCodecMessageId,a=[],o=this._parentIndex.get(i);if(o)for(let e of o){let t=this._nodeIndex.get(e);t&&this._isSiblingOf(t.node,r)&&a.push(t)}a.sort((e,t)=>this._compareNodes(e,t));for(let e of a)this._siblingCache.set(R(e.node),a);return this._siblingCache.set(e,a),a}_isSiblingOf(e,t){if(e.kind!==t.kind||e.parentCodecMessageId!==t.parentCodecMessageId)return!1;if(e.kind===`run`)return!0;let n=R(t);if(R(e)===n)return!0;let r=e,i=new Set([R(r)]);for(;r.kind===`input`&&r.forkOf!==void 0;){if(r.forkOf===n)return!0;if(i.has(r.forkOf))break;let e=this._nodeIndex.get(r.forkOf);if(!e)break;r=e.node,i.add(R(r))}return!1}getGroupRoot(e){let t=this._nodeIndex.get(e);if(!t)return e;if(t.node.kind===`input`)return R(this._inputGroupRoot(t.node));let n=this._getSiblingGroup(e)[0]?.node;return n?R(n):e}visibleNodes(e=new Map){this._logger.trace(`DefaultTree.visibleNodes();`);let t=[],n=new Set,r=new Map;for(let i of this._sortedNodes){let a=i.node,o=R(a),s=this._parentKeyOf(a);if(s!==void 0&&!n.has(s))continue;let c=this._getSiblingGroup(o);if(c.length>1){let t=this.getGroupRoot(o),n=r.get(t);if(n===void 0){let i=e.get(t);if(i!==void 0&&c.some(e=>R(e.node)===i))n=i;else{let e=c.at(-1);if(!e)break;n=R(e.node)}r.set(t,n)}if(o!==n)continue}n.add(o),t.push(a)}return t}getRunNode(e){this._logger.trace(`DefaultTree.getRunNode();`,{runId:e});let t=this._nodeIndex.get(e)?.node;return t?.kind===`run`?t:void 0}getNode(e){return this._logger.trace(`DefaultTree.getNode();`,{key:e}),this._nodeIndex.get(e)?.node}getNodeByCodecMessageId(e){this._logger.trace(`DefaultTree.getNodeByCodecMessageId();`,{codecMessageId:e});let t=this._codecMessageIdToNodeKey.get(e);return t===void 0?void 0:this._nodeIndex.get(t)?.node}getReplyRuns(e){let t=this._replyRunsByInput.get(e);if(!t)return[];let n=[];for(let e of t){let t=this._nodeIndex.get(e)?.node;t?.kind===`run`&&n.push(t)}return n}getSiblingNodes(e){return this._logger.trace(`DefaultTree.getSiblingNodes();`,{key:e}),this._getSiblingGroup(e).map(e=>e.node)}applyMessage(e,t,n,r,i){let a=t[S],o=t[w],s=a===void 0&&o!==void 0&&t.role===`user`&&e.inputs.length>0?o:void 0;if(a===void 0&&s===void 0){this._logger.warn(`Tree.applyMessage(); message has no run-id and is not a user input; skipping`);return}let c=L(e),l=s??a;if(c.length===0&&l!==void 0&&!this._nodeIndex.has(l))return;let u=this._structuralVersion;s===void 0?a!==void 0&&this._applyRunMessage(a,e,t,n,r,i):this._applyInputMessage(s,t,n,r,i,c),this._structuralVersion!==u&&this._emitter.emit(`update`)}_applyInputMessage(e,t,n,r,i,a){let o=this._nodeIndex.get(e);o?o.node.kind===`input`&&n&&!o.node.serial&&(this._logger.debug(`Tree.applyMessage(); promoting input serial`,{codecMessageId:e,serial:n}),o.node.serial=n,this._promoteSerial(o)):(o=this._createInputNodeFromHeaders(e,t,n),this._insertNode(e,o,o.node.parentCodecMessageId),this._codecMessageIdToNodeKey.set(e,e),this._logger.debug(`Tree.applyMessage(); created input node`,{codecMessageId:e})),this._recordActivity(o,r),this._recordAndFold(o,a,n,e,i,t[x]===`true`),this._emitter.emit(`output`,{runId:void 0,inputCodecMessageId:e,codecMessageId:e,serial:n,events:[]})}_applyRunMessage(e,t,n,r,i,a){let o=n[w],s=n[k],c=L(t),l=t.outputs,u=this._nodeIndex.get(e);if(!u&&o!==void 0){let e=this._codecMessageIdToNodeKey.get(o),t=e===void 0?void 0:this._nodeIndex.get(e);t?.node.kind===`run`&&t.node.startSerial===void 0&&(u=t)}u?r&&u.node.kind===`run`&&!u.node.startSerial&&(this._logger.debug(`Tree.applyMessage(); promoting startSerial`,{runId:e,serial:r}),u.node.startSerial=r,this._promoteSerial(u)):(u=this._createRunFromHeaders(e,n,r),this._insertNode(e,u,u.node.parentCodecMessageId),this._indexReplyRun(u.node,e),this._logger.debug(`Tree.applyMessage(); created new Run`,{runId:e}));let d=R(u.node);o&&this._codecMessageIdToNodeKey.set(o,d),this._recordActivity(u,i),this._recordAndFold(u,c,r,o,a,n[x]===`true`),this._emitter.emit(`output`,{runId:d,inputCodecMessageId:s,codecMessageId:o,serial:r,events:l})}_indexReplyRun(e,t){e.parentCodecMessageId!==void 0&&B(this._replyRunsByInput,e.parentCodecMessageId,t)}applyRunLifecycle(e){this._logger.trace(`DefaultTree.applyRunLifecycle();`,{type:e.type,runId:e.runId});let t=this._structuralVersion;switch(e.type){case`start`:this._applyRunStart(e);break;case`suspend`:this._applyRunSuspend(e);break;case`resume`:this._applyRunResume(e);break;case`end`:this._applyRunEnd(e);break}this._emitter.emit(`run`,e),this._structuralVersion!==t&&this._emitter.emit(`update`)}_applyRunStart(e){let t=this._nodeIndex.get(e.runId);if(t?.node.kind===`run`){let n=t.node;if(n.state.status===`suspended`&&(n.state={status:`active`}),e.serial&&!n.startSerial&&(n.startSerial=e.serial,this._promoteSerial(t)),n.parentCodecMessageId===void 0&&e.parent!==void 0&&(n.parentCodecMessageId=e.parent,this._removeFromParentIndex(void 0,e.runId),this._addToParentIndex(n.parentCodecMessageId,e.runId),this._indexReplyRun(n,e.runId),this._structuralVersion++),n.forkOf===void 0&&e.forkOf!==void 0){let t=this._codecMessageIdToNodeKey.get(e.forkOf);t!==void 0&&t!==e.runId&&(n.forkOf=t,this._structuralVersion++)}n.regeneratesCodecMessageId===void 0&&e.regenerates!==void 0&&(n.regeneratesCodecMessageId=e.regenerates,this._structuralVersion++),n.invocationId===``&&e.invocationId!==``&&(n.invocationId=e.invocationId),t.runStartSeen=!0,this._recordActivity(t,e.timestamp),this._maybeQueueSweep(t)}else if(!t){let t=this._createRunFromLifecycle(e);this._insertNode(e.runId,t,t.node.parentCodecMessageId),this._indexReplyRun(t.node,e.runId),this._recordActivity(t,e.timestamp)}}_applyRunSuspend(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.state={status:`suspended`},t.node.endSerial=e.serial,this._recordActivity(t,e.timestamp))}_applyRunResume(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&t.node.state.status===`suspended`&&(t.node.state={status:`active`},this._recordActivity(t,e.timestamp))}_applyRunEnd(e){let t=this._nodeIndex.get(e.runId);t?.node.kind===`run`&&(t.node.state=e.reason===`error`?{status:`error`,error:e.error}:{status:e.reason},t.node.endSerial=e.serial,this._recordActivity(t,e.timestamp),this._maybeQueueSweep(t))}delete(e){let t=this._nodeIndex.get(e);t&&(this._logger.debug(`Tree.delete();`,{key:e}),this._removeFromParentIndex(t.node.parentCodecMessageId,e),this._removeSortedNode(t),this._nodeIndex.delete(e),t.node.kind===`run`&&t.node.parentCodecMessageId!==void 0&&V(this._replyRunsByInput,t.node.parentCodecMessageId,e),this._structuralVersion++,this._emitter.emit(`update`))}_createRunFromHeaders(e,t,n){let r=t[D];return this._buildRunNode({runId:e,parentCodecMessageId:t[E],forkOf:r?this._codecMessageIdToNodeKey.get(r):void 0,regeneratesCodecMessageId:t[O],clientId:t[`run-client-id`]??``,invocationId:t[`invocation-id`]??``,startSerial:n,runStartSeen:!1})}_wrapNode(e,t=!1){return{node:e,insertSeq:this._seqCounter++,log:new Te,lastActivityTs:0,runStartSeen:t,sweepQueued:!1,optimistic:!1}}_buildRunNode(e){let t={kind:`run`,runId:e.runId,parentCodecMessageId:e.parentCodecMessageId,forkOf:e.forkOf,regeneratesCodecMessageId:e.regeneratesCodecMessageId,clientId:e.clientId,invocationId:e.invocationId,state:{status:`active`},projection:this._codec.init(),startSerial:e.startSerial,endSerial:void 0};return this._wrapNode(t,e.runStartSeen)}_createInputNodeFromHeaders(e,t,n){let r=t[D],i={kind:`input`,codecMessageId:e,parentCodecMessageId:t[E],forkOf:r,projection:this._codec.init(),serial:n};return this._wrapNode(i)}_createRunFromLifecycle(e){let t=e.forkOf;return this._buildRunNode({runId:e.runId,parentCodecMessageId:e.parent,forkOf:t?this._codecMessageIdToNodeKey.get(t):void 0,regeneratesCodecMessageId:e.regenerates,clientId:e.clientId,invocationId:e.invocationId,startSerial:e.serial,runStartSeen:!0})}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}emitAblyMessage(e){this._logger.trace(`DefaultTree.emitAblyMessage();`);let t=F(e)[C];t!==void 0&&!this._eventIdIndex.has(t)&&this._eventIdIndex.set(t,e),this._emitter.emit(`ably-message`,e)}findAblyMessageByEventId(e){return this._eventIdIndex.get(e)}},De=(e,t)=>new Ee(e,t),Oe=(e,n)=>new Promise((r,i)=>{if(n?.aborted){i(new t.ErrorInfo(`unable to wait; signal aborted`,A.InvalidArgument,400));return}let a=setTimeout(()=>{n?.removeEventListener(`abort`,o),r()},e);typeof a==`object`&&a.unref();let o=()=>{clearTimeout(a),i(new t.ErrorInfo(`unable to wait; signal aborted`,A.InvalidArgument,400))};n?.addEventListener(`abort`,o,{once:!0})}),H=async(e,n,r,i,a)=>{let o;for(let s=0;s<=n;s++){if(i?.aborted)throw new t.ErrorInfo(`unable to fetch history page; signal aborted`,A.InvalidArgument,400,P(o));try{return await e()}catch(e){if(o=e,s===n)break;let t=r*2**s;a?.debug(`loadHistoryPages.fetchPageWithRetry(); page fetch failed, retrying`,{attempt:s+1,maxRetries:n,backoff:t}),await Oe(t,i)}}throw new t.ErrorInfo(`unable to fetch history page; ${N(o)}`,A.HistoryFetchFailed,500,P(o))},ke=async(e,n)=>{let{pageLimit:r,untilAttach:i=!0,signal:a,maxRetries:o=3,retryBackoffMs:s=100,logger:c}=n;if(a?.aborted)throw new t.ErrorInfo(`unable to load history; signal aborted`,A.InvalidArgument,400);await e.attach();let l={limit:r,untilAttach:i},u=await H(()=>e.history(l),o,s,a,c),d=!1;return{hasNext:()=>u===void 0||a?.aborted?!1:d?u.hasNext():!0,next:async()=>{if(u===void 0)return;if(a?.aborted)throw new t.ErrorInfo(`unable to load history; signal aborted`,A.InvalidArgument,400);if(!d)return d=!0,u.items;if(!u.hasNext()){u=void 0;return}let e=await H(async()=>await u?.next()??void 0,o,s,a,c);if(!e){u=void 0;return}return u=e,e.items}}},Ae=(e,t)=>{for(let n of t){let t=F(n),r=t[w];if(!r)continue;let i=n.action,a=i===`message.create`&&`discrete`in t,o=t.stream===`true`&&(i===`message.create`||i===`message.update`||i===`message.append`),s=t[ne],c=s===`complete`||s===`cancelled`;(a||o)&&e.startedCodecMessageIds.add(r),(a||c)&&e.terminatedCodecMessageIds.add(r),e.startedCodecMessageIds.has(r)&&e.terminatedCodecMessageIds.has(r)&&e.completedCodecMessageIds.add(r)}},U=async(e,t)=>{let n=e.returnedCount+t;for(;e.completedCodecMessageIds.size<n&&e.cursor.hasNext();){e.logger.debug(`loadHistory.fetchUntilLimit(); pulling next page`,{collected:e.rawMessages.length,completed:e.completedCodecMessageIds.size});let t=await e.cursor.next();if(!t)break;e.rawMessages.push(...t),Ae(e,t)}},W=(e,t)=>{let n=e.completedCodecMessageIds.size,r=Math.min(t,Math.max(0,n-e.returnedCount));e.returnedCount+=r;let i=n>e.returnedCount,a=e.cursor.hasNext(),o=e.rawMessages.length-e.returnedRawCount>0?e.rawMessages.slice(e.returnedRawCount).toReversed():[];return e.returnedRawCount=e.rawMessages.length,{rawMessages:o,hasNext:()=>i||a,next:async()=>{if(i)return W(e,t);if(a)return await U(e,t),W(e,t)}}},je=async(e,t,n)=>{let r=t?.limit??100;n.trace(`loadHistory();`,{limit:r});let i={cursor:await ke(e,{pageLimit:r*10,untilAttach:!0,logger:n}),rawMessages:[],returnedCount:0,returnedRawCount:0,startedCodecMessageIds:new Set,terminatedCodecMessageIds:new Set,completedCodecMessageIds:new Set,logger:n};return await U(i,r),W(i,r)},Me=e=>Array.isArray(e)?e:[e],G=e=>({runId:e.runId,clientId:e.clientId,invocationId:e.invocationId,...e.state}),Ne=class{constructor(e){this._branchSelections=new Map,this._regenSelections=new Map,this._nonHeadRegenSelections=new Map,this._withheldRunIds=new Set,this._lastVisibleNodeKeys=[],this._lastVisibleProjections=[],this._lastVisibleMessagePairs=[],this._lastVisibleNodeKeySet=new Set,this._hasMoreHistory=!1,this._withheldBuffer=[],this._hiddenMessageCount=0,this._unsubs=[],this._cachedNodes=[],this._loadingOlder=!1,this._processingHistory=!1,this._closed=!1,this._tree=e.tree,this._channel=e.channel,this._codec=e.codec,this._applier=e.applier,this._sendDelegate=e.sendDelegate,this._onClose=e.onClose,this._logger=e.logger.withContext({component:`View`}),this._logger.trace(`DefaultView();`),this._emitter=new j(this._logger),this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._unsubs.push(this._tree.on(`update`,()=>{this._onTreeUpdate()}),this._tree.on(`ably-message`,e=>{this._onTreeAblyMessage(e)}),this._tree.on(`run`,e=>{this._onTreeRun(e)}),this._tree.on(`output`,e=>{this._onTreeOutput(e)}))}_onTreeOutput(e){this._processingHistory||(e.runId!==void 0&&this._lastVisibleNodeKeySet.has(e.runId)||e.inputCodecMessageId!==void 0&&this._lastVisibleNodeKeySet.has(e.inputCodecMessageId))&&(this._lastVisibleProjections=this._cachedNodes.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(this._cachedNodes).slice(this._hiddenMessageCount),this._emitter.emit(`update`))}getMessages(){return this._lastVisibleMessagePairs}runs(){return this._cachedNodes.filter(e=>e.kind===`run`).map(e=>G(e))}_computeFlatNodes(){let e=this._treeVisibleNodes();return this._withheldRunIds.size===0?e:e.filter(e=>!this._withheldRunIds.has(R(e)))}_recomputeAndEmit(){this._cachedNodes=this._computeFlatNodes(),this._updateVisibleSnapshot(this._cachedNodes),this._emitter.emit(`update`)}_recomputeAndEmitIfChanged(){let e=this._computeFlatNodes();this._visibleChanged(e)&&(this._cachedNodes=e,this._updateVisibleSnapshot(e),this._emitter.emit(`update`))}_runByCodecMessageId(e){let t=this._tree.getNodeByCodecMessageId(e);return t?.kind===`run`?t:void 0}_nonHeadRegenerators(e,t){return this._tree.getReplyRuns(t).filter(t=>t.regeneratesCodecMessageId===e).toSorted((e,t)=>(e.startSerial??``).localeCompare(t.startSerial??``))}_selectedNonHeadMember(e,t,n){let r=this._nonHeadRegenSelections.get(e);return r&&r.kind!==`pending`&&[t,...n.map(e=>e.runId)].includes(r.selectedRunId)?r.selectedRunId:n.at(-1)?.runId??t}_extractMessages(e){let t=[],n=new Set;for(let r of e)r.kind===`run`&&n.has(r.runId)||this._emitNodeMessages(r,t,n);return t}_emitNodeMessages(e,t,n){let r=this._codec.getMessages(e.projection);if(e.kind!==`run`){t.push(...r);return}for(let i=0;i<r.length;i++){let a=r[i];if(!a)continue;let o=i>0?r[i-1]?.codecMessageId:void 0;if(o!==void 0){let r=this._nonHeadRegenerators(a.codecMessageId,o);if(r.length>0){for(let e of r)n.add(e.runId);let i=this._selectedNonHeadMember(a.codecMessageId,e.runId,r);if(i!==e.runId){let e=r.find(e=>e.runId===i);if(e){this._emitNodeMessages(e,t,n);return}}}}t.push(a)}}hasOlder(){return this._hiddenMessageCount>0||this._withheldBuffer.length>0||this._hasMoreHistory}async loadOlder(e=10){if(!(this._closed||this._loadingOlder)){this._loadingOlder=!0,this._logger.trace(`DefaultView.loadOlder();`,{limit:e});try{if(this._hiddenMessageCount>=e){this._hiddenMessageCount-=e,this._recomputeAndEmit();return}let t=e-this._hiddenMessageCount,n=this._extractMessages(this._computeFlatNodes()).length,r=()=>this._extractMessages(this._computeFlatNodes()).length-n;if(this._withheldBuffer.length>0){let e=this._messageTailSplitIndex(this._withheldBuffer,t),n=this._withheldBuffer.splice(e);this._releaseWithheld(n)}if(r()<t&&(await this._fetchOlder(t-r()),this._closed))return;let i=this._extractMessages(this._computeFlatNodes()).length;this._hiddenMessageCount=Math.max(0,this._hiddenMessageCount+(i-n)-e),this._recomputeAndEmit()}catch(e){throw this._logger.error(`DefaultView.loadOlder(); failed`,{error:e}),e}finally{this._loadingOlder=!1}}}async _fetchOlder(e){if(!this._hasMoreHistory&&!this._lastHistoryPage){await this._loadFirstPage(e);return}if(!this._hasMoreHistory)return;if(!this._lastHistoryPage?.hasNext()){this._hasMoreHistory=!1;return}let t=await this._lastHistoryPage.next();if(this._closed||!t){t||(this._hasMoreHistory=!1);return}await this._revealFromPage(t,e)}_messageTailSplitIndex(e,t){let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];if(i&&(n+=this._codec.getMessages(i.projection).length,n>=t))return r}return 0}runOf(e){this._logger.trace(`DefaultView.runOf();`,{codecMessageId:e});let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`run`)return G(t);let n=this._selectedReplyRun(t.codecMessageId);return n?G(n):void 0}_selectedReplyRun(e){let t=this._tree.getReplyRuns(e);if(t.length===0)return;if(t.length===1)return t[0];let n=this._tree.getGroupRoot(t[0]?.runId??``),r=this._regenSelections.get(n),i=r&&r.kind!==`pending`?r.selectedRunId:void 0;if(i!==void 0){let e=t.find(e=>e.runId===i);if(e)return e}return t.toSorted((e,t)=>(e.startSerial??``).localeCompare(t.startSerial??``)).at(-1)}run(e){this._logger.trace(`DefaultView.run();`,{runId:e});let t=this._tree.getRunNode(e);return t?G(t):void 0}branchSelection(e){let t=this._resolveMessageBranchPoint(e);if(t){let e=t.members.flatMap(e=>{let t=this._tree.getNodeByCodecMessageId(e.representativeCodecMessageId);if(!t)return[];let n=this._codec.getMessages(t.projection).find(t=>t.codecMessageId===e.representativeCodecMessageId);return n?[n.message]:[]});if(e.length>0){let n=this._resolveSelectedIndex(t),r=Math.max(0,Math.min(n,e.length-1)),i=e[r];return{hasSiblings:e.length>1,siblings:e,index:r,selected:i}}}let n=this._tree.getNodeByCodecMessageId(e);if(n){let t=this._codec.getMessages(n.projection).find(t=>t.codecMessageId===e);if(t!==void 0)return{hasSiblings:!1,siblings:[t.message],index:0,selected:t.message}}return{hasSiblings:!1,siblings:[],index:0,selected:void 0}}selectSibling(e,t){this._logger.trace(`DefaultView.selectSibling();`,{codecMessageId:e,index:t});let n=this._resolveMessageBranchPoint(e);if(!n)return;let r=Math.max(0,Math.min(t,n.members.length-1)),i=n.members[r];i&&(n.kind===`fork-of`?(this._branchSelections.set(n.groupRoot,{kind:`user`,selectedKey:i.memberNodeKey}),this._logger.debug(`DefaultView.selectSibling(); fork-of`,{codecMessageId:e,index:r,selectedKey:i.memberNodeKey})):n.kind===`non-head-regen`?(this._nonHeadRegenSelections.set(n.groupRoot,{kind:`user`,selectedRunId:i.memberNodeKey}),this._logger.debug(`DefaultView.selectSibling(); non-head-regen`,{codecMessageId:e,index:r,selectedRunId:i.memberNodeKey,anchor:n.groupRoot})):(this._regenSelections.set(n.groupRoot,{kind:`user`,selectedRunId:i.memberNodeKey}),this._logger.debug(`DefaultView.selectSibling(); regenerate`,{codecMessageId:e,index:r,selectedRunId:i.memberNodeKey,groupRoot:n.groupRoot})),this._recomputeAndEmit())}_resolveSelectedIndex(e){if(e.kind===`fork-of`){let t=this._branchSelections.get(e.groupRoot);if(!t)return e.members.length-1;let n=e.members.findIndex(e=>e.memberNodeKey===t.selectedKey);return n===-1?e.members.length-1:n}let t=e.kind===`non-head-regen`?this._nonHeadRegenSelections.get(e.groupRoot):this._regenSelections.get(e.groupRoot);if(!t||t.kind===`pending`)return e.members.length-1;let n=e.members.findIndex(e=>e.memberNodeKey===t.selectedRunId);return n===-1?e.members.length-1:n}_resolveMessageBranchPoint(e){let t=this._tree.getNodeByCodecMessageId(e);if(!t)return;if(t.kind===`input`){let e=this._tree.getSiblingNodes(t.codecMessageId);return e.length>1?{kind:`fork-of`,groupRoot:this._tree.getGroupRoot(t.codecMessageId),members:this._nodeHeadMembers(e)}:void 0}let n=this._codec.getMessages(t.projection),r=this._resolveNonHeadBranchPoint(t,n,e);if(r)return r;let i=this._tree.getSiblingNodes(t.runId);if(i.length>1&&n.at(0)?.codecMessageId===e)return{kind:`regen`,groupRoot:this._tree.getGroupRoot(t.runId),members:this._nodeHeadMembers(i)}}_resolveNonHeadBranchPoint(e,t,n){if(t.at(0)?.codecMessageId===n&&e.regeneratesCodecMessageId!==void 0){let t=e.regeneratesCodecMessageId,n=this._runByCodecMessageId(t);if(n){let e=this._codec.getMessages(n.projection),r=e.findIndex(e=>e.codecMessageId===t),i=r>0?e[r-1]?.codecMessageId:void 0;if(i!==void 0)return this._buildNonHeadGroup(t,n.runId,i)}return}let r=t.findIndex(e=>e.codecMessageId===n),i=r>0?t[r-1]?.codecMessageId:void 0;if(i!==void 0)return this._buildNonHeadGroup(n,e.runId,i)}_buildNonHeadGroup(e,t,n){let r=this._nonHeadRegenerators(e,n);if(r.length===0)return;let i=[{memberNodeKey:t,representativeCodecMessageId:e}];for(let e of r){let t=this._codec.getMessages(e.projection).at(0);t&&i.push({memberNodeKey:e.runId,representativeCodecMessageId:t.codecMessageId})}return{kind:`non-head-regen`,groupRoot:e,members:i}}_nodeHeadMembers(e){let t=[];for(let n of e){let e=this._codec.getMessages(n.projection).at(0);e&&t.push({memberNodeKey:R(n),representativeCodecMessageId:e.codecMessageId})}return t}async send(e,n){if(this._logger.trace(`DefaultView.send();`),this._closed)throw new t.ErrorInfo(`unable to send; view is closed`,A.InvalidArgument,400);let r=Me(e),i=this._lastVisibleMessagePairs.at(-1)?.codecMessageId,a=await this._sendDelegate(r,n,i);return this._applyForkAutoSelect(a,n),a}_applyForkAutoSelect(e,t){if(!t?.forkOf)return;let n=e.optimisticCodecMessageIds.at(0);if(n===void 0)return;let r=this._tree.getGroupRoot(n);this._branchSelections.set(r,{kind:`auto`,selectedKey:n}),this._recomputeAndEmit()}_applyRegenerateAutoSelect(e,t){let n=this._runByCodecMessageId(t);if(!n)return;if(this._codec.getMessages(n.projection).at(0)?.codecMessageId!==t){this._nonHeadRegenSelections.set(t,{kind:`pending`,carrierCodecMessageId:e.inputCodecMessageId}),this._logger.debug(`DefaultView._applyRegenerateAutoSelect(); deferring non-head regenerate selection`,{anchorCodecMessageId:t,carrier:e.inputCodecMessageId}),this._resolvePendingNonHeadRegenSelections(),this._recomputeAndEmitIfChanged();return}let r=this._tree.getGroupRoot(n.runId);this._regenSelections.set(r,{kind:`pending`,carrierCodecMessageId:e.inputCodecMessageId}),this._logger.debug(`DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection`,{anchorCodecMessageId:t,groupRoot:r,carrier:e.inputCodecMessageId}),this._resolvePendingRegenSelections(),this._recomputeAndEmitIfChanged()}async regenerate(e,n){if(this._logger.trace(`DefaultView.regenerate();`,{messageId:e}),this._closed)throw new t.ErrorInfo(`unable to regenerate; view is closed`,A.InvalidArgument,400);let r=this._runByCodecMessageId(e);if(!r)throw new t.ErrorInfo(`unable to regenerate; message not found in tree: ${e}`,A.InvalidArgument,400);let i=this._findParentMsgId(r,e);if(!i)throw new t.ErrorInfo(`unable to regenerate; parent user message not found for ${e}`,A.InvalidArgument,400);let a=e;r.regeneratesCodecMessageId!==void 0&&this._codec.getMessages(r.projection).at(0)?.codecMessageId===e&&(a=r.regeneratesCodecMessageId);let o={...n,parent:i},s=this._codec.createRegenerate(a,i),c=await this._sendDelegate([s],o,i);return this._applyRegenerateAutoSelect(c,a),c}async edit(e,n,r){if(this._logger.trace(`DefaultView.edit();`,{messageId:e}),this._closed)throw new t.ErrorInfo(`unable to edit; view is closed`,A.InvalidArgument,400);let i=this._tree.getNodeByCodecMessageId(e);if(!i)throw new t.ErrorInfo(`unable to edit; message not found in tree: ${e}`,A.InvalidArgument,400);let a=this._findParentMsgId(i,e);return this.send(n,{...r,forkOf:e,parent:a})}_findParentMsgId(e,t){let n=this._lastVisibleMessagePairs,r=n.findIndex(e=>e.codecMessageId===t);if(r>0)return n[r-1]?.codecMessageId;if(r===0)return;let i=this._codec.getMessages(e.projection),a=i.findIndex(e=>e.codecMessageId===t);if(a>0)return i[a-1]?.codecMessageId;if(a===0&&e.parentCodecMessageId!==void 0){let t=this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);if(t)return this._codec.getMessages(t.projection).at(-1)?.codecMessageId}}on(e,t){let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}close(){if(!this._closed){this._logger.info(`DefaultView.close();`),this._closed=!0,this._loadingOlder=!1;for(let e of this._unsubs)e();this._unsubs.length=0,this._emitter.off(),this._branchSelections.clear(),this._regenSelections.clear(),this._nonHeadRegenSelections.clear(),this._withheldRunIds.clear(),this._withheldBuffer.length=0,this._hiddenMessageCount=0,this._onClose?.()}}async _loadFirstPage(e){let t=await je(this._channel,{limit:e},this._logger);this._closed||await this._revealFromPage(t,e)}async _revealFromPage(e,t){let n=new Set(this._treeVisibleNodes().map(e=>R(e))),{newVisible:r,lastPage:i}=await this._loadUntilVisible(e,t,n);this._closed||(this._lastHistoryPage=i,this._hasMoreHistory=i.hasNext(),this._splitReveal(r,t))}_splitReveal(e,t){let n=this._messageTailSplitIndex(e,t),r=e.slice(n),i=e.slice(0,n);for(let e of i)this._withheldRunIds.add(R(e));this._withheldBuffer.push(...i),this._releaseWithheld(r)}_processHistoryPage(e){this._processingHistory=!0;try{for(let t of e.rawMessages)this._applier.apply(t);for(let t of e.rawMessages)this._tree.emitAblyMessage(t)}finally{this._processingHistory=!1}}async _loadUntilVisible(e,t,n){this._processHistoryPage(e);let r=e,i=()=>{let e=0;for(let t of this._treeVisibleNodes())n.has(R(t))||(e+=this._codec.getMessages(t.projection).length);return e};for(;i()<t&&r.hasNext();){let e=await r.next();if(!e||this._closed)break;this._processHistoryPage(e),r=e}return{newVisible:this._treeVisibleNodes().filter(e=>!n.has(R(e))),lastPage:r}}_releaseWithheld(e){for(let t of e)this._withheldRunIds.delete(R(t));e.length>0&&this._recomputeAndEmit()}_updateVisibleSnapshot(e){let t=e??this._cachedNodes;this._lastVisibleNodeKeys=t.map(e=>R(e)),this._lastVisibleNodeKeySet=new Set(this._lastVisibleNodeKeys),this._lastVisibleProjections=t.map(e=>e.projection),this._lastVisibleMessagePairs=this._extractMessages(t).slice(this._hiddenMessageCount)}_onTreeUpdate(){this._processingHistory||(this._pinBranchSelections(),this._resolvePendingRegenSelections(),this._resolvePendingNonHeadRegenSelections(),this._recomputeAndEmitIfChanged())}_resolveSelections(){let e=new Map;for(let[t,n]of this._branchSelections)e.set(t,n.selectedKey);for(let[t,n]of this._regenSelections)n.kind!==`pending`&&e.set(t,n.selectedRunId);return e}_treeVisibleNodes(){return this._tree.visibleNodes(this._resolveSelections())}_pinBranchSelections(){for(let e of this._lastVisibleNodeKeys){if(this._tree.getNode(e)?.kind!==`input`||this._tree.getSiblingNodes(e).length<=1)continue;let t=this._tree.getGroupRoot(e);this._branchSelections.get(t)||this._branchSelections.set(t,{kind:`pinned`,selectedKey:e})}}_resolvePendingRegenSelections(){for(let[e,t]of this._regenSelections){if(t.kind===`user`)continue;let n=this._tree.getSiblingNodes(e).filter(e=>e.kind===`run`);if(n.length<=1)continue;let r=n.at(-1);r&&this._regenSelections.set(e,{kind:`auto`,selectedRunId:r.runId})}}_resolvePendingNonHeadRegenSelections(){for(let[e,t]of this._nonHeadRegenSelections){if(t.kind===`user`)continue;let n=this._runByCodecMessageId(e);if(!n)continue;let r=this._codec.getMessages(n.projection),i=r.findIndex(t=>t.codecMessageId===e),a=i>0?r[i-1]?.codecMessageId:void 0;if(a===void 0)continue;let o=this._nonHeadRegenerators(e,a).at(-1);o&&this._nonHeadRegenSelections.set(e,{kind:`auto`,selectedRunId:o.runId})}}_onTreeAblyMessage(e){let t=F(e),n=t[w],r=t[S];if(!n&&!r){this._emitter.emit(`ably-message`,e);return}r&&this._lastVisibleNodeKeySet.has(r)&&this._emitter.emit(`ably-message`,e)}_onTreeRun(e){if(this._lastVisibleNodeKeySet.has(e.runId)){this._emitter.emit(`run`,e);return}e.type===`start`&&this._isRunStartVisible(e)&&(this._lastVisibleNodeKeySet.add(e.runId),this._emitter.emit(`run`,e))}_isRunStartVisible(e){let{parent:t}=e;if(t===void 0)return!0;let n=this._tree.getNodeByCodecMessageId(t);return n?this._lastVisibleNodeKeySet.has(R(n)):!0}_visibleChanged(e){if(e.length!==this._lastVisibleNodeKeys.length)return!0;for(let[t,n]of e.entries())if(R(n)!==this._lastVisibleNodeKeys[t]||n.projection!==this._lastVisibleProjections[t])return!0;return!1}},K=e=>new Ne(e),Pe=()=>{},Fe=class{constructor(e){this._views=new Set,this._state=`ready`,this._pendingRunStarts=new Map;let t=te(e.client,e.codec),n=h(e.channelModes);if(n&&(t.modes=n),this._channel=e.client.channels.get(e.channelName,t),this._client=e.client,this._codec=e.codec,this._logger=(e.logger??fe({logLevel:ue.Silent})).withContext({component:`ClientSession`}),this._emitter=new j(this._logger),this._hasAttachedOnce=this._channel.state===`attached`,this._tree=De(this._codec,this._logger),this._applier=ye(this._tree,this._codec.createDecoder()),this._view=K({tree:this._tree,channel:this._channel,codec:this._codec,applier:this._applier,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(this._view)}),this._encoder=this._codec.createEncoder(this._channel),this._views.add(this._view),this.tree=this._tree,this.view=this._view,e.messages){let t;for(let n of e.messages){let e=crypto.randomUUID(),r={[w]:e,[T]:`user`};t&&(r[E]=t),this._tree.applyMessage({inputs:[this._codec.createUserMessage(n)],outputs:[]},r),t=e}}this._onMessage=e=>{this._handleMessage(e)},this._onChannelStateChange=e=>{this._handleChannelStateChange(e)},this._channel.on(this._onChannelStateChange)}get presence(){return this._channel.presence}get object(){return this._channel.object}connect(){return this._state===`closed`?Promise.reject(new t.ErrorInfo(`unable to connect; session is closed`,A.SessionClosed,400)):this._connectPromise?this._connectPromise:(this._logger.trace(`DefaultClientSession.connect();`),this._connectPromise=this._channel.subscribe(this._onMessage).then(()=>{this._logger.debug(`DefaultClientSession.connect(); subscribed and attached`)},e=>{let n=new t.ErrorInfo(`unable to subscribe to channel; ${N(e)}`,A.SessionSubscriptionError,500,P(e));throw this._logger.error(`DefaultClientSession.connect(); subscribe failed`),this._emitter.emit(`error`,n),n}),this._connectPromise)}_resolveClientId(){let e=this._client.auth.clientId;return e&&e!==`*`?e:void 0}async _requireConnected(e){return xe(this._connectPromise,e)}_handleMessage(e){if(this._state!==`closed`)try{if(e.name===`ai-run-end`){let t=F(e);if((t[`run-reason`]??`complete`)===`error`){let e=I(t);this._logger.error(`ClientSession._handleMessage(); agent error received`,{runId:t[S],invocationId:t[re],code:e.code}),this._emitter.emit(`error`,e)}}let t=this._applier.apply(e);if(t&&(t.type===`start`||t.type===`resume`)){let n=F(e)[k];if(n!==void 0){let e=this._pendingRunStarts.get(n);e&&(this._pendingRunStarts.delete(n),e.resolve(t.runId))}}this._tree.emitAblyMessage(e)}catch(e){this._emitter.emit(`error`,new t.ErrorInfo(`unable to process channel message; ${N(e)}`,A.SessionSubscriptionError,500,P(e)))}}_handleChannelStateChange(e){if(this._state===`closed`)return;let{current:t,resumed:n}=e;if(t===`attached`&&!this._hasAttachedOnce){this._hasAttachedOnce=!0;return}if(!Ce(e))return;this._logger.error(`ClientSession._handleChannelStateChange(); channel continuity lost`,{current:t,resumed:n,previous:e.previous});let r=we(e,`deliver events`);this._emitter.emit(`error`,r)}_cleanupFailedSend(e){for(let t of e){let e=this._tree.getNodeByCodecMessageId(t);e?.kind===`input`&&e.serial===void 0&&this._tree.delete(e.codecMessageId)}}createView(){if(this._state===`closed`)throw new t.ErrorInfo(`unable to create view; session is closed`,A.SessionClosed,400);this._logger.trace(`DefaultClientSession.createView();`);let e=K({tree:this._tree,channel:this._channel,codec:this._codec,applier:this._applier,sendDelegate:this._internalSend.bind(this),logger:this._logger,onClose:()=>this._views.delete(e)});return this._views.add(e),e}async _internalSend(e,n,r){if(this._state===`closed`||(await this._requireConnected(`send`),this._state===`closed`))throw new t.ErrorInfo(`unable to send; session is closed`,A.SessionClosed,400);let i=this._channel.state;if(i!==`attached`&&i!==`attaching`)throw new t.ErrorInfo(`unable to send; channel is ${i}`,A.ChannelNotReady,400);this._logger.trace(`ClientSession._internalSend();`);let a=n?.runId!==void 0,o=n?.runId,s;n?.parent===void 0&&!n?.forkOf&&(s=r);let c=new Set,l=[];for(let t of e){let e=crypto.randomUUID(),r=t.codecMessageId??crypto.randomUUID();c.add(r);let i=t.kind!==`user-message`&&(t.kind===`regenerate`||t.codecMessageId!==void 0),a=t.parent??(n?.parent===void 0?s:n.parent),u=n?.forkOf,d=t.kind===`regenerate`?t.target:void 0,f=he({role:`user`,runId:o,codecMessageId:r,runClientId:this._resolveClientId(),...a!==void 0&&{parent:a},...u!==void 0&&{forkOf:u},...d!==void 0&&{regenerates:d},inputEventId:e});i||this._tree.applyMessage({inputs:[t],outputs:[]},f),l.push({input:t,codecMessageId:r,inputEventId:e,headers:f,isWireOnly:i}),!i&&n?.parent===void 0&&!n?.forkOf&&t.parent===void 0&&(s=r)}let u=l.at(-1);if(u===void 0)throw new t.ErrorInfo(`unable to send; inputs array is empty (include at least one input)`,A.InvalidArgument,400);let d=u.inputEventId,f=u.codecMessageId,p=new Promise((e,t)=>{this._pendingRunStarts.set(f,{resolve:e,reject:t})});return p.catch(()=>{}),await(async()=>{try{for(let e of l)await this._encoder.publishInput(e.input,{extras:{headers:e.headers},messageId:e.codecMessageId})}catch(e){let n=P(e),r=n?.statusCode===401||n?.statusCode===403,i=new t.ErrorInfo(r?`unable to publish events; missing publish capability on the channel`:`unable to publish events; ${N(e)}`,r?A.InsufficientCapability:A.SessionSendFailed,r?401:500,n);throw this._emitter.emit(`error`,i),this._pendingRunStarts.delete(f),a||this._cleanupFailedSend([...c]),i}})(),{inputCodecMessageId:f,runId:p,inputEventId:d,cancel:async()=>{await this._publishCancel({inputCodecMessageId:f,...o!==void 0&&{runId:o}})},optimisticCodecMessageIds:[...c],toInvocation:()=>be.fromJSON({inputEventId:d,sessionName:this._channel.name})}}async cancel(e){return this._publishCancel({runId:e})}async _publishCancel(e){if(this._state===`closed`||(await this._requireConnected(`cancel`),this._state===`closed`))return;this._logger.debug(`ClientSession._publishCancel();`,{runId:e.runId,inputCodecMessageId:e.inputCodecMessageId});let t={[C]:crypto.randomUUID()};e.runId!==void 0&&(t[S]=e.runId),e.inputCodecMessageId!==void 0&&(t[k]=e.inputCodecMessageId),await this._channel.publish({name:se,extras:{ai:{transport:t}}})}on(e,t){if(this._state===`closed`)return Pe;let n=t;return this._emitter.on(e,n),()=>{this._emitter.off(e,n)}}async close(){if(this._state!==`closed`){this._state=`closed`,this._logger.info(`ClientSession.close();`),this._connectPromise&&this._channel.unsubscribe(this._onMessage),this._channel.off(this._onChannelStateChange),this._emitter.off();for(let e of this._views)e.close();if(this._views.clear(),this._pendingRunStarts.size>0){let e=new t.ErrorInfo(`unable to await run-start; session closed`,A.SessionClosed,400);for(let t of this._pendingRunStarts.values())t.reject(e);this._pendingRunStarts.clear()}try{await this._encoder.close()}catch{}await Se(this._channel,this._connectPromise,this._logger,`ClientSession`)}}},Ie=e=>new Fe(e),q=(0,r.createContext)({nearest:void 0,providers:{}}),J=({children:e,...a})=>{let o=(0,n.useAbly)(),{channelName:s}=a,c=(0,r.useMemo)(()=>{let e={params:{agent:ee(a.codec)}},t=h(a.channelModes);return t&&(e.modes=t),e},[a.codec,a.channelModes]),l=(0,r.useRef)(void 0),u=(0,r.useRef)(s),d=(0,r.useRef)([]),f=(0,r.useRef)(!1),p=(0,r.useRef)(void 0);if(!(l.current||p.current)||u.current!==s){u.current=s,l.current&&d.current.push(l.current);try{l.current=Ie({...a,client:o}),p.current=void 0}catch(e){l.current=void 0,p.current=e instanceof t.ErrorInfo?e:new t.ErrorInfo(`Unknown error while creating client session`,A.BadRequest,400)}}let m=(0,r.useContext)(q),g=l.current,_=p.current,v=(0,r.useMemo)(()=>({session:g,sessionError:_}),[g,_]),y=(0,r.useMemo)(()=>({nearest:v,providers:{...m.providers,[s]:v}}),[s,m,v]);return(0,r.useEffect)(()=>()=>{for(let e of d.current)e.close()},[s]),(0,r.useEffect)(()=>{l.current?.connect()},[s]),(0,r.useEffect)(()=>(f.current=!1,()=>{f.current=!0,Promise.resolve().then(()=>{f.current&&l.current?.close()})}),[]),(0,i.jsx)(q.Provider,{value:y,children:(0,i.jsx)(n.ChannelProvider,{channelName:s,options:c,children:e})})},Y=({session:e,skip:t}={})=>{let{nearest:n}=(0,r.useContext)(q),i=n?.session;if(!t&&e!==null)return e??i},X=({session:e,skip:t}={})=>{let n=Y({session:e,skip:t}),[i,a]=(0,r.useState)([]),o=(0,r.useRef)([]);return(0,r.useEffect)(()=>{if(o.current=[],a([]),n)return n.tree.on(`ably-message`,e=>{let t=[...o.current,e];o.current=t,a(t)})},[n]),i},Z=e=>new t.ErrorInfo(`unable to ${e}; hook is skipped`,A.InvalidArgument,400),Q=()=>({get tree(){throw Z(`access tree`)},get view(){throw Z(`access view`)},get presence(){throw Z(`access presence`)},get object(){throw Z(`access object`)},connect:()=>{throw Z(`connect`)},createView:()=>{throw Z(`create view`)},cancel:()=>{throw Z(`cancel`)},on:()=>{throw Z(`subscribe`)},close:()=>{throw Z(`close`)}}),Le=({channelName:e,skip:n,onError:i}={})=>{let{nearest:a,providers:o}=(0,r.useContext)(q),s=(0,r.useRef)(i);s.current=i;let c=n?void 0:e===void 0?a?.session:o[e]?.session;if((0,r.useEffect)(()=>{if(c)return c.on(`error`,e=>{s.current?.(e)})},[c]),n)return{session:Q()};if(e!==void 0){let n=o[e];return n?n.session?{session:n.session}:{session:Q(),sessionError:n.sessionError}:{session:Q(),sessionError:new t.ErrorInfo(`unable to use session; no ClientSessionProvider found for channelName "${e}"`,A.BadRequest,400)}}return a?a.session?{session:a.session}:{session:Q(),sessionError:a.sessionError}:{session:Q(),sessionError:new t.ErrorInfo(`unable to use session; no ClientSessionProvider found in the tree`,A.BadRequest,400)}},Re={hasSiblings:!1,siblings:[],index:0,selected:void 0},$=({session:e,view:n,limit:i,skip:a}={})=>{let o=Y({session:e,skip:a}),s=a?void 0:n??o?.view,[c,l]=(0,r.useState)(()=>s?.getMessages()??[]),[u,d]=(0,r.useState)(()=>s?.hasOlder()??!1),[f,p]=(0,r.useState)(!1),[m,h]=(0,r.useState)(),g=(0,r.useRef)(!1),_=i!==void 0,v=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!s){l([]),d(!1),h(void 0);return}return v.current=!1,l(s.getMessages()),d(s.hasOlder()),h(void 0),s.on(`update`,()=>{l(s.getMessages()),d(s.hasOlder())})},[s]);let y=(0,r.useCallback)(async()=>{if(!(!s||g.current)){g.current=!0,p(!0);try{await s.loadOlder(i),h(void 0)}catch(e){e instanceof t.ErrorInfo?h(e):h(new t.ErrorInfo(`Unknown error loading older messages`,A.BadRequest,400))}finally{g.current=!1,p(!1)}}},[s,i]);return(0,r.useEffect)(()=>{!_||v.current||!s||(v.current=!0,y())},[_,s,y]),{messages:c,hasOlder:u,loading:f,loadError:m,loadOlder:y,runOf:(0,r.useCallback)(e=>s?.runOf(e),[s]),run:(0,r.useCallback)(e=>s?.run(e),[s]),runs:(0,r.useCallback)(()=>s?.runs()??[],[s]),branchSelection:(0,r.useCallback)(e=>s?.branchSelection(e)??Re,[s]),selectSibling:(0,r.useCallback)((e,t)=>{s?.selectSibling(e,t)},[s]),send:(0,r.useCallback)(async(e,n)=>{if(!s)throw new t.ErrorInfo(`unable to send; view is not available`,A.InvalidArgument,400);return s.send(e,n)},[s]),regenerate:(0,r.useCallback)(async(e,n)=>{if(!s)throw new t.ErrorInfo(`unable to regenerate; view is not available`,A.InvalidArgument,400);return s.regenerate(e,n)},[s]),edit:(0,r.useCallback)(async(e,n,r)=>{if(!s)throw new t.ErrorInfo(`unable to edit; view is not available`,A.InvalidArgument,400);return s.edit(e,n,r)},[s])}},ze=({session:e,limit:t,skip:n}={})=>{let i=Y({session:e,skip:n}),[a,o]=(0,r.useState)();return(0,r.useEffect)(()=>{if(!i){o(void 0);return}let e=i.createView();return o(e),()=>{e.close()}},[i]),$({view:a,limit:t,skip:n})},Be=({session:e}={})=>{let t=Y({session:e});return{getRunNode:(0,r.useCallback)(e=>t?.tree.getRunNode(e),[t]),getNodeByCodecMessageId:(0,r.useCallback)(e=>t?.tree.getNodeByCodecMessageId(e),[t]),getSiblingNodes:(0,r.useCallback)(e=>t?.tree.getSiblingNodes(e)??[],[t])}};e.ClientSessionProvider=J,e.OBJECT_MODES=p,e.createSessionHooks=()=>({ClientSessionProvider:J,useClientSession:e=>Le(e??{}),useView:e=>$(e??{}),useTree:e=>Be(e??{}),useAblyMessages:e=>X(e??{}),useCreateView:e=>ze(e??{})}),e.useAblyMessages=X,e.useClientSession=Le,e.useCreateView=ze,e.useTree=Be,e.useView=$});
|
|
2
2
|
//# sourceMappingURL=ably-ai-transport-react.umd.cjs.map
|