PageSourceSearch

https://app.zerosnag.ai/assets/powersync-BACnHPWX.js

js zerosnag.ai collected 2026-10-05 14:56:40 UTC 231,250 bytes, 106 lines download raw bytes

vendor: 7,803 bytes, lines 1-2
1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/IDBBatchAtomicVFS-DtJB2Vh-.js","assets/FacadeVFS-B_v2JP8g.js","assets/AccessHandlePoolVFS-Br29lmio.js","assets/OPFSCoopSyncVFS-umZAcyOw.js","assets/OPFSWriteAheadVFS-Dq1eU8Yt.js","assets/MemoryVFS-CDeBjiYu.js"])))=>i.map(i=>d[i]);
2import{r as e,t}from"./rolldown-runtime-hePW80VL.js";var n=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var ee=Array.isArray;function te(){}var S={H:null,A:null,T:null,S:null},ne=Object.prototype.hasOwnProperty;function re(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function ie(e,t){return re(e.type,t,e.props)}function C(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function ae(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var oe=/\/+/g;function se(e,t){return typeof e==`object`&&e&&e.key!=null?ae(``+e.key):t.toString(36)}function ce(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(te,te):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function le(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,le(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+se(e,0):a,ee(o)?(i=``,c!=null&&(i=c.replace(oe,`$&/`)+`/`),le(o,r,i,``,function(e){return e})):o!=null&&(C(o)&&(o=ie(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(oe,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(ee(e))for(var u=0;u<e.length;u++)a=e[u],s=l+se(a,u),c+=le(a,r,i,s,o);else if(u=m(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+se(a,u++),c+=le(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return le(ce(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function ue(e,t,n){if(e==null)return e;var r=[],i=0;return le(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function de(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var w=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)},T={map:ue,forEach:function(e,t,n){ue(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return ue(e,function(){t++}),t},toArray:function(e){return ue(e,function(e){return e})||[]},only:function(e){if(!C(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=T,e.Component=v,e.Fragment=r,e.Profiler=a,e.PureComponent=b,e.StrictMode=i,e.Suspense=l,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=S,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return S.H.useMemoCache(e)}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=g({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!ne.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return re(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)ne.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return re(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=C,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:de}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=function(e){var t=S.T,n={};S.T=n;try{var r=e(),i=S.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(te,w)}catch(e){w(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),S.T=t}},e.unstable_useCacheRefresh=function(){return S.H.useCacheRefresh()},e.use=function(e){return S.H.use(e)},e.useActionState=function(e,t,n){return S.H.useActionState(e,t,n)},e.useCallback=function(e,t){return S.H.useCallback(e,t)},e.useContext=function(e){return S.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return S.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return S.H.useEffect(e,t)},e.useEffectEvent=function(e){return S.H.useEffectEvent(e)},e.useId=function(){return S.H.useId()},e.useImperativeHandle=function(e,t,n){return S.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return S.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return S.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return S.H.useMemo(e,t)},e.useOptimistic=function(e,t){return S.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return S.H.useReducer(e,t,n)},e.useRef=function(e){return S.H.useRef(e)},e.useState=function(e){return S.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return S.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return S.H.useTransition()}
2,e.version=`19.2.8`})),r=t(((e,t)=>{t.exports=n()})),i=`modulepreload`,a=function(e){return`/`+e},o={},s=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),s=document.querySelector(`meta[property=csp-nonce]`),c=s?.nonce||s?.getAttribute(`nonce`);function l(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=l(t.map(t=>{if(t=a(t,n),t=u(t),t in o)return;o[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let s=document.createElement(`link`);if(s.rel=r?`stylesheet`:i,r||(s.as=`script`),s.crossOrigin=``,s.href=t,c&&s.setAttribute(`nonce`,c),document.head.appendChild(s),r)return new Promise((e,n)=>{s.addEventListener(`load`,e),s.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function s(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&s(e.reason);return e().catch(s)})},c;(function(e){e.TEXT=`TEXT`,e.INTEGER=`INTEGER`,e.REAL=`REAL`})(c||={});var l={type:c.TEXT},u={type:c.INTEGER},d={type:c.REAL},f=1999,p={text:l,integer:u,real:d},m=class{options;constructor(e){this.options=e}get name(){return this.options.name}get type(){return this.options.type}toJSON(){return{name:this.name,type:this.type}}},h={ascending:!0},g=class e{options;static createAscending(t){return new e({name:t,ascending:!0})}constructor(e){this.options={...h,...e}}get name(){return this.options.name}get ascending(){return this.options.ascending}toJSON(e){return{name:this.name,ascending:this.ascending,type:e.columns.find(e=>e.name===this.name)?.type??c.TEXT}}},_={columns:[]},v=class e{options;static createAscending(t,n){return new e({...t,columns:n.map(e=>g.createAscending(e))})}constructor(e){this.options=e,this.options={..._,...e}}get name(){return this.options.name}get columns(){return this.options.columns??[]}toJSON(e){return{name:this.name,columns:this.columns.map(t=>t.toJSON(e))}}};function y(e){let t=e.trackPrevious;return{local_only:e.localOnly,insert_only:e.insertOnly,include_old:t&&(t.columns??!0),include_old_only_when_changed:typeof t==`object`&&t.onlyWhenChanged==1,include_metadata:e.trackMetadata,ignore_empty_update:e.ignoreEmptyUpdates}}var b={indexes:[],insertOnly:!1,localOnly:!1,trackPrevious:!1,trackMetadata:!1,ignoreEmptyUpdates:!1},x=/["'%,.#\s[\]]/,ee=class e{options;_mappedColumns;static createLocalOnly(t){return new e({...t,localOnly:!0,insertOnly:!1})}static createInsertOnly(t){return new e({...t,localOnly:!1,insertOnly:!0})}static createTable(t,n){return new e({name:t,columns:n.columns,indexes:n.indexes,localOnly:n.options.localOnly,insertOnly:n.options.insertOnly,viewName:n.options.viewName})}constructor(e,t){this.isTableV1(e)?this.initTableV1(e):this.initTableV2(e,t)}copyWithName(t){return new e({...this.options,name:t})}isTableV1(e){return`columns`in e&&Array.isArray(e.columns)}initTableV1(e){this.options={...e,indexes:e.indexes||[]},this.applyDefaultOptions()}initTableV2(e,t){let n=Object.entries(e).map(([e,t])=>new m({name:e,type:t.type})),r=Object.entries(t?.indexes??{}).map(([e,t])=>new v({name:e,columns:t.map(e=>new g({name:e.replace(/^-/,``),ascending:!e.startsWith(`-`)}))}));this.options={name:``,columns:n,indexes:r,viewName:t?.viewName,insertOnly:t?.insertOnly,localOnly:t?.localOnly,trackPrevious:t?.trackPrevious,trackMetadata:t?.trackMetadata,ignoreEmptyUpdates:t?.ignoreEmptyUpdates},this.applyDefaultOptions(),this._mappedColumns=e}applyDefaultOptions(){this.options.insertOnly??=b.insertOnly,this.options.localOnly??=b.localOnly,this.options.trackPrevious??=b.trackPrevious,this.options.trackMetadata??=b.trackMetadata,this.options.ignoreEmptyUpdates??=b.ignoreEmptyUpdates}get name(){return this.options.name}get viewNameOverride(){return this.options.viewName}get viewName(){return this.viewNameOverride??this.name}get columns(){return this.options.columns}get columnMap(){return this._mappedColumns??this.columns.reduce((e,t)=>
2(e[t.name]={type:t.type??c.TEXT},e),{})}get indexes(){return this.options.indexes??[]}get localOnly(){return this.options.localOnly}get insertOnly(){return this.options.insertOnly}get trackPrevious(){return this.options.trackPrevious}get trackMetadata(){return this.options.trackMetadata}get ignoreEmptyUpdates(){return this.options.ignoreEmptyUpdates}get internalName(){return this.options.localOnly?`ps_data_local__${this.name}`:`ps_data__${this.name}`}get validName(){return!(x.test(this.name)||this.viewNameOverride!=null&&x.test(this.viewNameOverride))}validate(){if(x.test(this.name))throw Error(`Invalid characters in table name: ${this.name}`);if(this.viewNameOverride&&x.test(this.viewNameOverride))throw Error(`Invalid characters in view name: ${this.viewNameOverride}`);if(this.columns.length>1999)throw Error(`Table has too many columns. The maximum number of columns is ${f}.`);if(this.trackMetadata&&this.localOnly)throw Error(`Can't include metadata for local-only tables.`);if(this.trackPrevious!=0&&this.localOnly)throw Error(`Can't include old values for local-only tables.`);let e=new Set;e.add(`id`);for(let t of this.columns){let{name:n}=t;if(t.name===`id`)throw Error(`An id column is automatically added, custom id columns are not supported`);if(e.has(n))throw Error(`Duplicate column ${n}`);if(x.test(n))throw Error(`Invalid characters in column name: ${t.name}`);e.add(n)}let t=new Set;for(let n of this.indexes){if(t.has(n.name))throw Error(`Duplicate index ${n.name}`);if(x.test(n.name))throw Error(`Invalid characters in index name: ${n.name}`);for(let t of n.columns)if(!e.has(t.name))throw Error(`Column ${t.name} not found for index ${n.name}`);t.add(n.name)}}toJSON(){return{name:this.name,view_name:this.viewName,columns:this.columns.map(e=>e.toJSON()),indexes:this.indexes.map(e=>e.toJSON(this)),...y(this)}}},te;(function(e){e[e.QUEUED_UPLOAD=0]=`QUEUED_UPLOAD`,e[e.QUEUED_DOWNLOAD=1]=`QUEUED_DOWNLOAD`,e[e.QUEUED_DELETE=2]=`QUEUED_DELETE`,e[e.SYNCED=3]=`SYNCED`,e[e.ARCHIVED=4]=`ARCHIVED`})(te||={}),p.text,p.text,p.integer,p.integer,p.text,p.integer,p.integer,p.text;var S;(function(e){e.ON_DATA=`onData`,e.ON_ERROR=`onError`,e.ON_STATE_CHANGE=`onStateChange`,e.SETTINGS_WILL_UPDATE=`settingsWillUpdate`,e.CLOSED=`closed`})(S||={});var ne={throttleMs:30,reportFetching:!0},re=class{table;head;_length;constructor(e){this.table=[...e],this.head=0,this._length=this.table.length}get isEmpty(){return this.length==0}get length(){return this._length}removeFirst(){if(this.isEmpty)throw Error(`Queue is empty`);let e=this.table[this.head];return this._length--,this.table[this.head]=void 0,this.head=(this.head+1)%this.table.length,e}addLast(e){if(this.length==this.table.length)throw Error(`Queue is full`);this.table[(this.head+this._length)%this.table.length]=e,this._length++}},ie=class{available;size;firstWaiter;lastWaiter;constructor(e){this.available=new re(e),this.size=this.available.length}addWaiter(e,t){let n={isActive:!0,acquiredItems:[],remainingItems:e,onAcquire:t,prev:this.lastWaiter};return this.lastWaiter?(this.lastWaiter.next=n,this.lastWaiter=n):this.lastWaiter=this.firstWaiter=n,n}deactivateWaiter(e){let{prev:t,next:n}=e;e.isActive=!1,t&&(t.next=n),n&&(n.prev=t),e==this.firstWaiter&&(this.firstWaiter=n),e==this.lastWaiter&&(this.lastWaiter=t)}requestPermits(e,t){if(e<=0||e>this.size)throw Error(`Invalid amount of items requested (${e}), must be between 1 and ${this.size}`);return new Promise((n,r)=>{function i(){r(t?.reason??Error(`Semaphore acquire aborted`))}if(t?.aborted)return i();let a,o=()=>{let e=a.acquiredItems;a.acquiredItems=[];for(let t of e){let e=this.firstWaiter;e?(e.acquiredItems.push(t),e.remainingItems--,e.remainingItems==0&&e.onAcquire()):this.available.addLast(t)}},s=()=>{t?.removeEventListener(`abort`,s),a.isActive&&(this.deactivateWaiter(a),i())},c=()=>{this.deactivateWaiter(a),t?.removeEventListener(`abort`,s);let e=a.acquiredItems;n({items:e,release:o})};for(a=this.addWaiter(e,c);!this.available.isEmpty&&a.remainingItems>0;)a.acquiredItems.push(this.available.removeFirst()),a.remainingItems--;if(a.remainingItems==0)return c();t?.addEventListener(`abort`,s)})}async requestOne(e){let{items:t,release:n}=await this.requestPermits(1,e);return{release:n,item:t[0]}}requestAll(e){return this.requestPermits(this.size,e)}},C=class{inner=new ie([null]);async acquire(e){let{release:t}=await this.inner.requestOne(e);return t}async runExclusive(e,t){let n=await this.acquire(t);try{return await e()}finally{n()}}};function ae(e){if(e==null)return;if(`timeout`in AbortSignal)return AbortSignal.timeout(e);let t=new AbortController;return setTimeout(()=>t.abort(Error(`Timeout waiting for lock`)),e),t.signal}var oe;(function(e){e.UTF8=`utf8`,e.Base64=`base64`})(oe||={});
2function se(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var ce={exports:{}},le=ce.exports,ue;function de(){return ue?ce.exports:(ue=1,(function(e){(function(t){var n={};n.VERSION=`1.6.1`;var r,i={},a=function(e,t){return function(){return t.apply(e,arguments)}},o=function(){var e=arguments,t=e[0],n,r;for(r=1;r<e.length;r++)for(n in e[r])!(n in t)&&e[r].hasOwnProperty(n)&&(t[n]=e[r][n]);return t},s=function(e,t){return{value:e,name:t}};n.TRACE=s(1,`TRACE`),n.DEBUG=s(2,`DEBUG`),n.INFO=s(3,`INFO`),n.TIME=s(4,`TIME`),n.WARN=s(5,`WARN`),n.ERROR=s(8,`ERROR`),n.OFF=s(99,`OFF`);var c=function(e){this.context=e,this.setLevel(e.filterLevel),this.log=this.info};c.prototype={setLevel:function(e){e&&`value`in e&&(this.context.filterLevel=e)},getLevel:function(){return this.context.filterLevel},enabledFor:function(e){var t=this.context.filterLevel;return e.value>=t.value},trace:function(){this.invoke(n.TRACE,arguments)},debug:function(){this.invoke(n.DEBUG,arguments)},info:function(){this.invoke(n.INFO,arguments)},warn:function(){this.invoke(n.WARN,arguments)},error:function(){this.invoke(n.ERROR,arguments)},time:function(e){typeof e==`string`&&e.length>0&&this.invoke(n.TIME,[e,`start`])},timeEnd:function(e){typeof e==`string`&&e.length>0&&this.invoke(n.TIME,[e,`end`])},invoke:function(e,t){r&&this.enabledFor(e)&&r(t,o({level:e},this.context))}};var l=new c({filterLevel:n.OFF});(function(){var e=n;e.enabledFor=a(l,l.enabledFor),e.trace=a(l,l.trace),e.debug=a(l,l.debug),e.time=a(l,l.time),e.timeEnd=a(l,l.timeEnd),e.info=a(l,l.info),e.warn=a(l,l.warn),e.error=a(l,l.error),e.log=e.info})(),n.setHandler=function(e){r=e},n.setLevel=function(e){for(var t in l.setLevel(e),i)i.hasOwnProperty(t)&&i[t].setLevel(e)},n.getLevel=function(){return l.getLevel()},n.get=function(e){return i[e]||(i[e]=new c(o({name:e},l.context)))},n.createDefaultHandler=function(e){e||={},e.formatter=e.formatter||function(e,t){t.name&&e.unshift(`[`+t.name+`]`)};var t={},r=function(e,t){Function.prototype.apply.call(e,console,t)};return typeof console>`u`?function(){}:function(i,a){i=Array.prototype.slice.call(i);var o=console.log,s;a.level===n.TIME?(s=(a.name?`[`+a.name+`] `:``)+i[0],i[1]===`start`?console.time?console.time(s):t[s]=new Date().getTime():console.timeEnd?console.timeEnd(s):r(o,[s+`: `+(new Date().getTime()-t[s])+`ms`])):(a.level===n.WARN&&console.warn?o=console.warn:a.level===n.ERROR&&console.error?o=console.error:a.level===n.INFO&&console.info?o=console.info:a.level===n.DEBUG&&console.debug?o=console.debug:a.level===n.TRACE&&console.trace&&(o=console.trace),e.formatter(i,a),r(o,i))}},n.useDefaults=function(e){n.setLevel(e&&e.defaultLevel||n.DEBUG),n.setHandler(n.createDefaultHandler(e))},n.setDefaults=n.useDefaults,e.exports?e.exports=n:(n._prevLogger=t.Logger,n.noConflict=function(){return t.Logger=n._prevLogger,n},t.Logger=n)})(le)})(ce),ce.exports)}var w=se(de());function T(e){return class extends e{async getAll(e,t){return(await this.execute(e,t)).rows?._array??[]}async getOptional(e,t){return(await this.execute(e,t)).rows?.item(0)??null}async get(e,t){let n=(await this.execute(e,t)).rows?.item(0);if(!n)throw Error(`Result set is empty`);return n}async executeBatch(e,t=[]){if(super.executeBatch)return super.executeBatch(e,t);let n,r=0;for(let i of t){let t=await this.execute(e,i);n=t.insertId,r+=t.rowsAffected}return{rowsAffected:r,insertId:n}}}}var E;(function(e){e[e.SQLITE_INSERT=18]=`SQLITE_INSERT`,e[e.SQLITE_DELETE=9]=`SQLITE_DELETE`,e[e.SQLITE_UPDATE=23]=`SQLITE_UPDATE`})(E||={});function fe(e){return class extends e{readTransaction(e,t){return this.readLock(t=>me.runWith(t,e),t)}writeTransaction(e,t){return this.writeLock(t=>me.runWith(t,e),t)}getAll(e,t){return this.readLock(n=>n.getAll(e,t))}getOptional(e,t){return this.readLock(n=>n.getOptional(e,t))}get(e,t){return this.readLock(n=>n.get(e,t))}execute(e,t){return this.writeLock(n=>n.execute(e,t))}executeRaw(e,t){return this.writeLock(n=>n.executeRaw(e,t))}executeBatch(e,t){return this.writeTransaction(n=>n.executeBatch(e,t))}}}var pe=class{inner;finalized=!1;constructor(e){this.inner=e}async commit(){return this.finalized?{rowsAffected:0}:(this.finalized=!0,this.inner.execute(`COMMIT`))}async rollback(){return this.finalized?{rowsAffected:0}:(this.finalized=!0,this.inner.execute(`ROLLBACK`))}execute(e,t){return this.inner.execute(e,t)}executeRaw(e,t){return this.inner.executeRaw(e,t)}executeBatch(e,t){return this.inner.executeBatch(e,t)}},me=class e extends T(pe){static async runWith(t,n){let r=new e(t),i=t.connectionType!=`queryOnly`;try{await t.execute(i?`BEGIN IMMEDIATE`:`BEGIN`);let e=await n(r);return await r.commit(),e}catch(e){try{await r.rollback()}catch{}throw e}}};function he(e){return`tables`in e}function ge(e){return he(e)?e.tables:[e.table]}var D=2147483647,_e=class{internal;totalOperations;downloadedOperations;downloadedFraction;constructor(e){this.internal=e;let t=this.untilPriority(D);this.totalOperations=t.totalOperations,this.downloadedOperations=t.downloadedOperations,this.downloadedFraction=t.downloadedFraction}untilPriority(e){let t=0,n=0;for(let r of Object.values(this.internal))r.priority<=e&&(n+=r.since_last,t+=r.target_count-r.at_last);let r=t==0?0:n/t;return{totalOperations:t,downloadedOperations:n,downloadedFraction:r}}},O=class e{options;constructor(e){this.options=e}get clientImplementation(){return this.options.clientImplementation}get connected(){return this.options.connected??!1}get connecting(){return this.options.connecting??!1}get lastSyncedAt(){return this.options.lastSyncedAt}get hasSynced(){return this.options.hasSynced}get dataFlowStatus(){return this.options.dataFlow??{downloading:!1,uploading:!1}}
2get syncStreams(){return this.options.dataFlow?.internalStreamSubscriptions?.map(e=>new ve(this,e))}forStream(e){let t=JSON.stringify(e.parameters),n=this.options.dataFlow?.internalStreamSubscriptions?.find(n=>n.name==e.name&&t==JSON.stringify(n.parameters));return n&&new ve(this,n)}get priorityStatusEntries(){return(this.options.priorityStatusEntries??[]).slice().sort(e.comparePriorities)}get downloadProgress(){let e=this.options.dataFlow?.downloadProgress;return e==null?null:new _e(e)}statusForPriority(e){for(let t of this.priorityStatusEntries)if(t.priority>=e)return t;return{priority:e,lastSyncedAt:this.lastSyncedAt,hasSynced:this.hasSynced}}isEqual(e){let t=(e,t)=>t instanceof Error?this.serializeError(t):t;return JSON.stringify(this.options,t)==JSON.stringify(e.options,t)}getMessage(){let e=this.dataFlowStatus;return`SyncStatus<connected: ${this.connected} connecting: ${this.connecting} lastSyncedAt: ${this.lastSyncedAt} hasSynced: ${this.hasSynced}. Downloading: ${e.downloading}. Uploading: ${e.uploading}. UploadError: ${e.uploadError}, DownloadError?: ${e.downloadError}>`}toJSON(){return{connected:this.connected,connecting:this.connecting,dataFlow:{...this.dataFlowStatus,uploadError:this.serializeError(this.dataFlowStatus.uploadError),downloadError:this.serializeError(this.dataFlowStatus.downloadError)},lastSyncedAt:this.lastSyncedAt,hasSynced:this.hasSynced,priorityStatusEntries:this.priorityStatusEntries}}serializeError(e){if(e===void 0)return;let t={name:e.name,message:e.message,stack:e.stack};return e.cause!==void 0&&(t.cause=e.cause instanceof Error?this.serializeError(e.cause):e.cause),t}static comparePriorities(e,t){return t.priority-e.priority}},ve=class{status;core;subscription;constructor(e,t){this.status=e,this.core=t,this.subscription={name:t.name,parameters:t.parameters,active:t.active,isDefault:t.is_default,hasExplicitSubscription:t.has_explicit_subscription,expiresAt:t.expires_at==null?null:new Date(t.expires_at*1e3),hasSynced:t.last_synced_at!=null,lastSyncedAt:t.last_synced_at==null?null:new Date(t.last_synced_at*1e3)}}get progress(){if(this.status.dataFlowStatus.downloadProgress==null)return null;let{total:e,downloaded:t}=this.core.progress;return{totalOperations:e,downloadedOperations:t,downloadedFraction:e==0?0:t/e}}get priority(){return this.core.priority}},ye=class{count;size;constructor(e,t=null){this.count=e,this.size=t}toString(){return this.size==null?`UploadQueueStats<count:${this.count}>`:`UploadQueueStats<count: $count size: ${this.size/1024}kB>`}},k=class{listeners=new Set;constructor(){}dispose(){this.listeners.clear()}registerListener(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}iterateListeners(e){for(let t of this.listeners)e(t)}async iterateAsyncListeners(e){for(let t of Array.from(this.listeners.values()))await e(t)}},be=class{task;runningTask;pendingTaskParam;isThrottling;closed;constructor(e,t){this.task=e;let{throttleEnabled:n=!0}=t??{};this.isThrottling=n,this.closed=!1}schedule(e){if(!this.closed){if(!this.isThrottling){this.task(e);return}if(this.runningTask){this.pendingTaskParam=e;return}this.execute(e)}}dispose(){this.closed=!0,this.runningTask&&=void 0}async execute(e){this.runningTask=this.task(e);try{await this.runningTask}finally{if(this.runningTask=void 0,this.pendingTaskParam){let e=this.pendingTaskParam;this.pendingTaskParam=void 0,this.execute(e)}}}},xe=Symbol.asyncIterator??Symbol.for(`Symbol.asyncIterator`),A={done:!0,value:void 0};function j(e){return{done:!1,value:e}}function Se(e){let t=!1,n,r=null,i=!1,a=[],o=()=>{let e=n;return n=void 0,e},s=()=>{let n=e=>{i=!1;let t=o();t?e(t):r=e};i=!0,e.next().then(e=>{t=e.done==1,n(t=>t.resolve(e))},e=>{n(t=>t.reject(e))})};return{next:()=>new Promise((e,o)=>{if(t)return e(A);if(r){r({resolve:e,reject:o}),r=null;return}if(a.length)return e(j(a.shift()));n={resolve:e,reject:o},i||s()}),inject:e=>{let t=o();t==null?a.push(e):t.resolve(j(e))}}}function Ce(e,t){let n=``,r=[],i=!1;return{next:async()=>{for(;;){if(i)return A;{let e=r.shift();if(e)return{done:!1,value:e}}let{done:a,value:o}=await e.next();if(a){let e=n.trim();return e.length==0?A:(i=!0,{done:!1,value:e})}let s=t.decode(o,{stream:!0});n+=s;let c=n.split(`
3`);for(let e=0;e<c.length-1;e++){let t=c[e].trim();t.length>0&&r.push(t)}n=c[c.length-1]}}}}function we(e){let t=[],n=!1,r=new DataView(new ArrayBuffer(4)),i=null,a=4;return{async next(){for(;;){if(t.length)return j(t.shift());if(n)return A;let o=await e.next();if(o.done){if(n=!0,i||a!=4)throw Error(`illegal end of stream in BSON object`);return A}let s=o.value;for(let e=0;e<s.length;){let n=s.length-e;if(i){let r=Math.min(n,a),o=new Uint8Array(s.buffer,s.byteOffset+e,r);i.set(o,i.length-a),e+=r,a-=r,a==0&&(t.push(i),i=null,a=4)}else{let t=Math.min(n,a);for(let n=0;n<t;n++)r.setUint8(4-a+n,s[e+n]);if(e+=t,a-=t,a==0){let e=r.getInt32(0,!0);if(a=e-4,a<1)throw Error(`invalid length for bson: ${e}`);i=new Uint8Array(e),new DataView(i.buffer).setInt32(0,e,!0)}}}}}}}function Te(e,t){let n=null,r=()=>{e(),n=null};return function(){n??=setTimeout(r,t)}}function M(){let e=new N;return{notify(){e.countOutstandingEvents>0||e.notify()},waitForNotification(t){return e.waitForEvent(t)}}}var N=class e{options;waitingConsumer;outstandingEvents;constructor(e={}){this.options=e,this.outstandingEvents=[]}get countOutstandingEvents(){return this.outstandingEvents.length}notifyInner(e){let t=this.waitingConsumer;this.waitingConsumer=void 0;let n=t=>{e(t),this.options.eventDelivered?.()};t?n(t):this.outstandingEvents.push(n)}notify(e){this.notifyInner(t=>t.resolve(e))}notifyError(e){this.notifyInner(t=>t.reject(e))}waitForEvent(e){return new Promise((t,n)=>{if(this.waitingConsumer!=null)throw Error(`Illegal call to waitForEvent, already has a waiter.`);let r=()=>{e?.removeEventListener(`abort`,i)},i=()=>{r(),this.waitingConsumer=void 0,t(void 0)},a={resolve:e=>{r(),t(e)},reject:e=>{r(),n(e)}};if(e.aborted)t(void 0);else if(this.countOutstandingEvents>0){let[e]=this.outstandingEvents.splice(0,1);e(a)}else this.waitingConsumer=a,e.addEventListener(`abort`,i)})}static queueBasedAsyncIterable(t,n){return{[xe]:()=>{let r=new e,i=new AbortController;function a(){i.abort(),n?.removeEventListener(`abort`,a)}return n&&(n.aborted?i.abort():n.addEventListener(`abort`,a)),t(r,i.signal),{async next(){let e=await r.waitForEvent(i.signal);return e==null?A:j(e)},async return(){return a(),A}}}}}},Ee=class extends k{options;connectingPromise;syncStreamInitPromise;disconnectingPromise;pendingConnectionOptions;syncStreamImplementation;syncDisposer;locallyActiveSubscriptions=new Map;constructor(e){super(),this.options=e,this.connectingPromise=null,this.syncStreamInitPromise=null,this.disconnectingPromise=null,this.pendingConnectionOptions=null,this.syncStreamImplementation=null,this.syncDisposer=null}get connector(){return this.pendingConnectionOptions?.connector??null}get connectionOptions(){return this.pendingConnectionOptions?.options??null}get logger(){return this.options.logger}async close(){await this.syncStreamImplementation?.dispose(),await this.syncDisposer?.()}async connect(e,t){let n=!!this.pendingConnectionOptions;this.pendingConnectionOptions={connector:e,options:t},(!n||this.syncStreamImplementation)&&await this.disconnectInternal();let r=async()=>
3{if(this.pendingConnectionOptions)return this.connectingPromise=this.connectInternal().catch(()=>{}).finally(r),this.connectingPromise;this.connectingPromise=null};return this.connectingPromise??=this.connectInternal().catch(()=>{}).finally(r),this.connectingPromise}async connectInternal(){let e=null;await this.disconnectInternal(),this.syncStreamInitPromise=new Promise(async(t,n)=>{try{if(!this.pendingConnectionOptions){this.logger.debug(`No pending connection options found, not creating sync stream implementation`),t();return}if(this.disconnectingPromise){t();return}let{connector:n,options:r}=this.pendingConnectionOptions;e=r,this.pendingConnectionOptions=null;let{sync:i,onDispose:a}=await this.options.createSyncImplementation(n,{subscriptions:this.activeStreams,...r});this.iterateListeners(e=>e.syncStreamCreated?.(i)),this.syncStreamImplementation=i,this.syncDisposer=a,await this.syncStreamImplementation.waitForReady(),t()}catch(e){n(e)}}),await this.syncStreamInitPromise,this.syncStreamInitPromise=null,e&&(await this.disconnectingPromise,this.logger.debug(`Attempting to connect to PowerSync instance`),await this.syncStreamImplementation?.connect(e))}async disconnect(){this.pendingConnectionOptions=null,await this.disconnectInternal()}async disconnectInternal(){if(this.disconnectingPromise)return this.disconnectingPromise;this.disconnectingPromise=this.performDisconnect(),await this.disconnectingPromise,this.disconnectingPromise=null}async performDisconnect(){await this.syncStreamInitPromise;let e=this.syncStreamImplementation;this.syncStreamImplementation=null;let t=this.syncDisposer;this.syncDisposer=null,await e?.disconnect(),await e?.dispose(),await t?.()}stream(e,t,n){let r={name:t,parameters:n},i=t=>e.firstStatusMatching(e=>e.forStream(r)?.subscription.hasSynced,t);return{...r,subscribe:async r=>{await e.rustSubscriptionsCommand({subscribe:{stream:{name:t,params:n},ttl:r?.ttl,priority:r?.priority}}),this.syncStreamImplementation||await e.resolveOfflineSyncStatus();let a=`${t}|${JSON.stringify(n)}`,o=this.locallyActiveSubscriptions.get(a);return o??(o=new P(t,n,this.logger,i,()=>{this.locallyActiveSubscriptions.delete(a),this.subscriptionsMayHaveChanged()}),this.locallyActiveSubscriptions.set(a,o),this.subscriptionsMayHaveChanged()),new De(o)},unsubscribeAll:async()=>{await e.rustSubscriptionsCommand({unsubscribe:{name:t,params:n}}),this.subscriptionsMayHaveChanged()}}}get activeStreams(){return[...this.locallyActiveSubscriptions.values()].map(e=>({name:e.name,params:e.parameters}))}subscriptionsMayHaveChanged(){this.syncStreamImplementation?.updateSubscriptions(this.activeStreams)}},P=class{name;parameters;logger;waitForFirstSync;clearSubscription;refcount=0;constructor(e,t,n,r,i){this.name=e,this.parameters=t,this.logger=n,this.waitForFirstSync=r,this.clearSubscription=i}decrementRefCount(){this.refcount--,this.refcount==0&&this.clearSubscription()}},De=class{subscription;active=!0;constructor(e){this.subscription=e,e.refcount++,F?.register(this,e,this)}get name(){return this.subscription.name}get parameters(){return this.subscription.parameters}waitForFirstSync(e){return this.subscription.waitForFirstSync(e)}unsubscribe(){this.active&&(this.active=!1,F?.unregister(this),this.subscription.decrementRefCount())}},F=`FinalizationRegistry`in globalThis?new FinalizationRegistry(e=>{e.logger.warn(`A subscription to ${e.name} with params ${JSON.stringify(e.parameters)} leaked! Please ensure calling unsubscribe() when you don't need a subscription anymore. For global subscriptions, consider storing them in global fields to avoid this warning.`)}):null,I={checkEquality:()=>!1},Oe=class extends k{get listenerCounts(){let e={},t=0;for(let n of this.listeners)for(let r in n)n[r]&&(e[r]=(e[r]??0)+1,t++);return{...e,total:t}}get listenerMeta(){return{counts:this.listenerCounts,registerListener:e=>this.metaListener.registerListener(e)}}metaListener;constructor(){super(),this.metaListener=new k}registerListener(e){let t=super.registerListener(e),n=this.listenerCounts;return this.metaListener.iterateListeners(e=>{e.listenersChanged?.(n)}),()=>{t();let e=this.listenerCounts;this.metaListener.iterateListeners(t=>{t.listenersChanged?.(e)})}}},ke=class extends Oe{options;state;abortController;initialized;_closed;disposeListeners;get closed(){return this._closed}constructor(e){super(),this.options=e,this.abortController=new AbortController,this._closed=!1,this.state=this.constructInitialState(),this.disposeListeners=null,this.initialized=this.init(this.abortController.signal)}constructInitialState(){return{isLoading:!0,isFetching:this.reportFetching,error:null,lastUpdated:null,data:this.options.placeholderData}}get reportFetching(){return this.options.watchOptions.reportFetching??!0}async updateSettingsInternal(e,t){this._closed||t.aborted||(this.options.watchOptions=e,this.iterateListeners(e=>e[S.SETTINGS_WILL_UPDATE]?.()),!this.state.isFetching&&this.reportFetching&&await this.updateState({isFetching:!0}),await this.runWithReporting(()=>this.linkQuery({abortSignal:t,settings:e})))}async updateSettings(e){this.abortController.abort();let t=new AbortController;return this.abortController=t,await this.initialized,this.updateSettingsInternal(e,t.signal)}async updateState(e){this._closed||(e.error!==void 0&&(await this.iterateAsyncListenersWithError(async t=>t.onError?.(e.error)),e.isFetching=!1,e.isLoading=!1),Object.assign(this.state,{lastUpdated:new Date},e),e.data!==void 0&&await this.iterateAsyncListenersWithError(async e=>e.onData?.(this.state.data)),await this.iterateAsyncListenersWithError(async e=>e.onStateChange?.(this.state)))}async init(e){let{db:t}=this.options,n=t.registerListener({closing:async()=>{await this.close()}});await t.waitForReady();let r=t.registerListener({schemaChanged:async()=>{await this.runWithReporting(async()=>{await this.updateSettings(this.options.watchOptions)})}});this.disposeListeners=()=>{n(),r()},await this.runWithReporting(async()=>{await this.updateSettingsInternal(this.options.watchOptions,e)})}async close(){this._closed=!0,this.abortController.abort(),this.disposeListeners?.(),this.disposeListeners=null,this.iterateListeners(e=>e.closed?.()),this.listeners.clear()}async runWithReporting(e){try{await e()}catch(e){await this.updateState({error:e})}}async iterateAsyncListenersWithError(e){try{await this.iterateAsyncListeners(async t=>e(t))}catch(e){try{await this.iterateAsyncListeners(async t=>t.onError?.(e))}catch(e){this.options.db.logger.error(`Watched query error handler threw an Error`,e)}}}},Ae={keyBy:e=>
3e&&typeof e==`object`&&typeof e.id==`string`?e.id:JSON.stringify(e),compareBy:e=>JSON.stringify(e)},je=class extends ke{options;comparator;constructor(e){super(e),this.options=e,this.comparator=e.rowComparator??Ae}differentiate(e,t){let{keyBy:n,compareBy:r}=this.comparator,i=!1,a=new Map,o=new Set(t.keys()),s={all:[],added:[],removed:[],updated:[],unchanged:[]};for(let c of e){let e=n(c),l=r(c);a.set(e,{hash:l,item:c});let u=t.get(e);u?l==u.hash?(s.unchanged.push(u.item),s.all.push(u.item),a.set(e,u)):(i=!0,s.updated.push({current:c,previous:u.item}),s.all.push(c)):(i=!0,s.added.push(c),s.all.push(c)),o.delete(e)}return s.removed=Array.from(o).map(e=>t.get(e).item),i||=s.removed.length>0,{diff:s,hasChanged:i,map:a}}async linkQuery(e){let{db:t,watchOptions:n}=this.options,{abortSignal:r}=e,i=n.query.compile(),a=await t.resolveTables(i.sql,i.parameters,{tables:e.settings.triggerOnTables}),o=new Map;this.state.data.forEach(e=>{o.set(this.comparator.keyBy(e),{hash:this.comparator.compareBy(e),item:e})}),t.onChangeWithCallback({onChange:async()=>{if(!(this.closed||r.aborted))try{this.reportFetching&&!this.state.isFetching&&await this.updateState({isFetching:!0});let e={},t=await n.query.execute({sql:i.sql,parameters:[...i.parameters],db:this.options.db});if(r.aborted)return;this.reportFetching&&(e.isFetching=!1),this.state.isLoading&&(e.isLoading=!1);let{diff:a,hasChanged:s,map:c}=this.differentiate(t,o);o=c,s&&(await this.iterateAsyncListenersWithError(e=>e.onDiff?.(a)),Object.assign(e,{data:a.all})),this.state.error&&(e.error=null),Object.keys(e).length>0&&await this.updateState(e)}catch(e){await this.updateState({error:e})}},onError:async e=>{await this.updateState({error:e})}},{signal:r,tables:a,throttleMs:n.throttleMs,triggerImmediate:!0})}},Me=class extends ke{options;constructor(e){super(e),this.options=e}checkEquality(e,t){return this.options.comparator?.checkEquality?.(e,t)??!1}async linkQuery(e){let{db:t,watchOptions:n}=this.options,{abortSignal:r}=e,i=n.query.compile(),a=await t.resolveTables(i.sql,i.parameters,{tables:e.settings.triggerOnTables});t.onChangeWithCallback({onChange:async()=>{if(!(this.closed||r.aborted))try{this.reportFetching&&!this.state.isFetching&&await this.updateState({isFetching:!0});let e={},t=await n.query.execute({sql:i.sql,parameters:[...i.parameters],db:this.options.db});if(r.aborted)return;this.reportFetching&&(e.isFetching=!1),this.state.isLoading&&(e.isLoading=!1),this.checkEquality(t,this.state.data)||Object.assign(e,{data:t}),this.state.error&&(e.error=null),Object.keys(e).length>0&&await this.updateState(e)}catch(e){await this.updateState({error:e})}},onError:async e=>{await this.updateState({error:e})}},{signal:r,tables:a,throttleMs:n.throttleMs,triggerImmediate:!0})}},Ne=class{options;constructor(e){this.options=e}resolveOptions(e){return{reportFetching:e?.reportFetching??ne.reportFetching,throttleMs:e?.throttleMs??ne.throttleMs,triggerOnTables:e?.triggerOnTables}}watch(e){return new Me({db:this.options.db,comparator:e?.comparator??I,placeholderData:e?.placeholderData??[],watchOptions:{...this.resolveOptions(e),query:this.options.query}})}differentialWatch(e){return new je({db:this.options.db,rowComparator:e?.rowComparator,placeholderData:e?.placeholderData??[],watchOptions:{...this.resolveOptions(e),query:this.options.query}})}},Pe=e=>e&&typeof e==`object`&&`dbFilename`in e,Fe=e=>typeof e?.openDB==`function`,Ie=e=>typeof e?.writeTransaction==`function`,L;(function(e){e.DATA=`ps_data`,e.CRUD=`ps_crud`,e.BUCKETS=`ps_buckets`,e.OPLOG=`ps_oplog`,e.UNTYPED=`ps_untyped`})(L||={});var R;(function(e){e.PROCESS_TEXT_LINE=`line_text`,e.PROCESS_BSON_LINE=`line_binary`,e.STOP=`stop`,e.START=`start`,e.NOTIFY_TOKEN_REFRESHED=`refreshed_token`,e.NOTIFY_CRUD_UPLOAD_COMPLETED=`completed_upload`,e.UPDATE_SUBSCRIPTIONS=`update_subscriptions`,e.CONNECTION_STATE=`connection`})(R||={});var Le=class{crud;haveMore;complete;constructor(e,t,n){this.crud=e,this.haveMore=t,this.complete=n}},Re;(function(e){e.PUT=`PUT`,e.PATCH=`PATCH`,e.DELETE=`DELETE`})(Re||={});var ze=class e{clientId;id;op;opData;previousValues;table;transactionId;metadata;static fromRow(t){let n=JSON.parse(t.data);return new e(parseInt(t.id),n.op,n.type,n.id,t.tx_id,n.data,n.old,n.metadata)}constructor(e,t,n,r,i,a,o,s){this.clientId=e,this.id=r,this.op=t,this.opData=a,this.table=n,this.transactionId=i,this.previousValues=o,this.metadata=s}toJSON(){return{op_id:this.clientId,op:this.op,type:this.table,id:this.id,tx_i
3d:this.transactionId,data:this.opData,old:this.previousValues,metadata:this.metadata}}equals(e){return JSON.stringify(this.toComparisonArray())==JSON.stringify(e.toComparisonArray())}hashCode(){return JSON.stringify(this.toComparisonArray())}toComparisonArray(){return[this.transactionId,this.clientId,this.op,this.table,this.id,this.opData,this.previousValues,this.metadata]}},Be=class extends Le{crud;complete;transactionId;constructor(e,t,n){super(e,!1,t),this.crud=e,this.complete=t,this.transactionId=n}},z=class e extends Error{reason;constructor(t){super(t),this.reason=t,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}},Ve={},He={},Ue;function We(){if(Ue)return He;Ue=1,He.byteLength=s,He.toByteArray=l,He.fromByteArray=f;for(var e=[],t=[],n=typeof Uint8Array<`u`?Uint8Array:Array,r=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,i=0,a=r.length;i<a;++i)e[i]=r[i],t[r.charCodeAt(i)]=i;t[45]=62,t[95]=63;function o(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function s(e){var t=o(e),n=t[0],r=t[1];return(n+r)*3/4-r}function c(e,t,n){return(t+n)*3/4-n}function l(e){var r,i=o(e),a=i[0],s=i[1],l=new n(c(e,a,s)),u=0,d=s>0?a-4:a,f;for(f=0;f<d;f+=4)r=t[e.charCodeAt(f)]<<18|t[e.charCodeAt(f+1)]<<12|t[e.charCodeAt(f+2)]<<6|t[e.charCodeAt(f+3)],l[u++]=r>>16&255,l[u++]=r>>8&255,l[u++]=r&255;return s===2&&(r=t[e.charCodeAt(f)]<<2|t[e.charCodeAt(f+1)]>>4,l[u++]=r&255),s===1&&(r=t[e.charCodeAt(f)]<<10|t[e.charCodeAt(f+1)]<<4|t[e.charCodeAt(f+2)]>>2,l[u++]=r>>8&255,l[u++]=r&255),l}function u(t){return e[t>>18&63]+e[t>>12&63]+e[t>>6&63]+e[t&63]}function d(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(u(r));return i.join(``)}function f(t){for(var n,r=t.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(d(t,s,s+o>c?c:s+o));return i===1?(n=t[r-1],a.push(e[n>>2]+e[n<<4&63]+`==`)):i===2&&(n=(t[r-2]<<8)+t[r-1],a.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+`=`)),a.join(``)}return He}var Ge={},Ke;function qe(){return Ke?Ge:(Ke=1,Ge.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},Ge.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128},Ge)}var Je;function Ye(){return Je?Ve:(Je=1,(function(e){let t=We(),n=qe(),r=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbol.for(`nodejs.util.inspect.custom`):null;e.Buffer=s,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50;let i=2147483647;e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=a(),!s.TYPED_ARRAY_SUPPORT&&typeof console<`u`&&typeof console.error==`function`&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),e.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function o(e){if(e>i)throw RangeError(`The value "`+e+`" is invalid for option "size"`);let t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if(typeof e==`number`){if(typeof t==`string`)throw TypeError(`The "string" argument must be of type string. Received type number`);return d(e)}
vendor: 19,973 bytes, line 3
3return c(e,t,n)}s.poolSize=8192;function c(e,t,n){if(typeof e==`string`)return f(e,t);if(ArrayBuffer.isView(e))return m(e);if(e==null)throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e);if(M(e,ArrayBuffer)||e&&M(e.buffer,ArrayBuffer)||typeof SharedArrayBuffer<`u`&&(M(e,SharedArrayBuffer)||e&&M(e.buffer,SharedArrayBuffer)))return h(e,t,n);if(typeof e==`number`)throw TypeError(`The "value" argument must not be of type number. Received type number`);let r=e.valueOf&&e.valueOf();if(r!=null&&r!==e)return s.from(r,t,n);let i=g(e);if(i)return i;if(typeof Symbol<`u`&&Symbol.toPrimitive!=null&&typeof e[Symbol.toPrimitive]==`function`)return s.from(e[Symbol.toPrimitive](`string`),t,n);throw TypeError(`The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type `+typeof e)}s.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(e){if(typeof e!=`number`)throw TypeError(`"size" argument must be of type number`);if(e<0)throw RangeError(`The value "`+e+`" is invalid for option "size"`)}function u(e,t,n){return l(e),e<=0||t===void 0?o(e):typeof n==`string`?o(e).fill(t,n):o(e).fill(t)}s.alloc=function(e,t,n){return u(e,t,n)};function d(e){return l(e),o(e<0?0:_(e)|0)}s.allocUnsafe=function(e){return d(e)},s.allocUnsafeSlow=function(e){return d(e)};function f(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!s.isEncoding(t))throw TypeError(`Unknown encoding: `+t);let n=y(e,t)|0,r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function p(e){let t=e.length<0?0:_(e.length)|0,n=o(t);for(let r=0;r<t;r+=1)n[r]=e[r]&255;return n}function m(e){if(M(e,Uint8Array)){let t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return p(e)}function h(e,t,n){if(t<0||e.byteLength<t)throw RangeError(`"offset" is outside of buffer bounds`);if(e.byteLength<t+(n||0))throw RangeError(`"length" is outside of buffer bounds`);let r;return r=t===void 0&&n===void 0?new Uint8Array(e):n===void 0?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function g(e){if(s.isBuffer(e)){let t=_(e.length)|0,n=o(t);return n.length===0||e.copy(n,0,0,t),n}if(e.length!==void 0)return typeof e.length!=`number`||N(e.length)?o(0):p(e);if(e.type===`Buffer`&&Array.isArray(e.data))return p(e.data)}function _(e){if(e>=i)throw RangeError(`Attempt to allocate Buffer larger than maximum size: 0x`+i.toString(16)+` bytes`);return e|0}function v(e){return+e!=e&&(e=0),s.alloc(+e)}s.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==s.prototype},s.compare=function(e,t){if(M(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),M(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw TypeError(`The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array`);if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:+(r<n)},s.isEncoding=function(e){switch(String(e).toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`latin1`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw TypeError(`"list" argument must be an Array of Buffers`);if(e.length===0)return s.alloc(0);let n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;let r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){let t=e[n];if(M(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else if(s.isBuffer(t))t.copy(r,i);else throw TypeError(`"list" argument must be an Array of Buffers`);i+=t.length}return r};function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||M(e,ArrayBuffer))return e.byteLength;if(typeof e!=`string`)throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type `+typeof e);let n=e.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let i=!1;for(;;)switch(t){case`ascii`:case`latin1`:case`binary`:return n;case`utf8`:case`utf-8`:return j(e).length;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return n*2;case`hex`:return n>>>1;case`base64`:return we(e).length;default:if(i)return r?-1:j(e).length;t=(``+t).toLowerCase(),i=!0}}s.byteLength=y;function b(e,t,n){let r=!1;if((t===void 0||t<0)&&(t=0),t>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,t>>>=0,n<=t))return``;for(e||=`utf8`;;)switch(e){case`hex`:return de(this,t,n);case`utf8`:case`utf-8`:return oe(this,t,n);case`ascii`:return le(this,t,n);case`latin1`:case`binary`:return ue(this,t,n);case`base64`:return ae(this,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return w(this,t,n);default:if(r)throw TypeError(`Unknown encoding: `+e);e=(e+``).toLowerCase(),r=!0}}s.prototype._isBuffer=!0;function x(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}s.prototype.swap16=function(){let e=this.length;if(e%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let t=0;t<e;t+=2)x(this,t,t+1);return this},s.prototype.swap32=function(){let e=this.length;if(e%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let t=0;t<e;t+=4)x(this,t,t+3),x(this,t+1,t+2);return this},s.prototype.swap64=function(){let e=this.length;if(e%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let t=0;t<e;t+=8)x(this,t,t+7),x(this,t+1,t+6),x(this,t+2,t+5),x(this,t+3,t+4);return this},s.prototype.toString=function(){let e=this.length;return e===0?``:arguments.length===0?oe(this,0,e):b.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw TypeError(`Argument must be a Buffer`);return this===e||s.compare(this,e)===0},s.prototype.inspect=function(){let t=``,n=e.INSPECT_MAX_BYTES;return t=this.toString(`hex`,0,n).replace(/(.{2})/g,`$1 `).trim(),this.length>n&&(t+=` ... `),`<Buffer `+t+`>`},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(M(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError(`The "target" argument must be one of type Buffer or Uint8Array. Received type `+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),r===void 0&&(r=0),i===void 0&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw RangeError(`out of range index`);if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;let a=i-r,o=n-t,c=Math.min(a,o),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){a=l[e],o=u[e];break}return a<o?-1:+(o<a)};function ee(e,t,n,r,i){if(e.length===0)return-1;if(typeof n==`string`?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,N(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(i)n=0;else return-1}if(typeof t==`string`&&(t=s.from(t,r)),s.isBuffer(t))return t.length===0?-1:te(e,t,n,r,i);if(typeof t==`number`)return t&=255,typeof Uint8Array.prototype.indexOf==`function`?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):te(e,[t],n,r,i);throw TypeError(`val must be string, number or Buffer`)}function te(e,t,n,r,i){let a=1,o=e.length,s=t.length;if(r!==void 0&&(r=String(r).toLowerCase(),r===`ucs2`||r===`ucs-2`||r===`utf16le`||r===`utf-16le`)){if(e.length<2||t.length<2)return-1;a=2,o/=2,s/=2,n/=2}function c(e,t){return a===1?e[t]:e.readUInt16BE(t*a)}let l;if(i){let r=-1;for(l=n;l<o;l++)if(c(e,l)===c(t,r===-1?0:l-r)){if(r===-1&&(r=l),l-r+1===s)return r*a}else r!==-1&&(l-=l-r),r=-1}else for(n+s>o&&(n=o-s),l=n;l>=0;l--){let n=!0;for(let r=0;r<s;r++)if(c(e,l+r)!==c(t,r)){n=!1;break}if(n)return l}return-1}s.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},s.prototype.indexOf=function(e,t,n){return ee(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return ee(this,e,t,n,!1)};function S(e,t,n,r){n=Number(n)||0;let i=e.length-n;r?(r=Number(r),r>i&&(r=i)):r=i;let a=t.length;r>a/2&&(r=a/2);let o;for(o=0;o<r;++o){let r=parseInt(t.substr(o*2,2),16);if(N(r))return o;e[n+o]=r}return o}function ne(e,t,n,r){return Te(j(t,e.length-n),e,n,r)}function re(e,t,n,r){return Te(Se(t),e,n,r)}function ie(e,t,n,r){return Te(we(t),e,n,r)}function C(e,t,n,r){return Te(Ce(t,e.length-n),e,n,r)}s.prototype.write=function(e,t,n,r){if(t===void 0)r=`utf8`,n=this.length,t=0;else if(n===void 0&&typeof t==`string`)r=t,n=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(n)?(n>>>=0,r===void 0&&(r=`utf8`)):(r=n,n=void 0);else throw Error(`Buffer.write(string, encoding, offset[, length]) is no longer supported`);let i=this.length-t;if((n===void 0||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError(`Attempt to write outside buffer bounds`);r||=`utf8`;let a=!1;for(;;)switch(r){case`hex`:return S(this,e,t,n);case`utf8`:case`utf-8`:return ne(this,e,t,n);case`ascii`:case`latin1`:case`binary`:return re(this,e,t,n);case`base64`:return ie(this,e,t,n);case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return C(this,e,t,n);default:if(a)throw TypeError(`Unknown encoding: `+r);r=(``+r).toLowerCase(),a=!0}},s.prototype.toJSON=function(){return{type:`Buffer`,data:Array.prototype.slice.call(this._arr||this,0)}};function ae(e,n,r){return n===0&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function oe(e,t,n){n=Math.min(e.length,n);let r=[],i=t;for(;i<n;){let t=e[i],a=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[i+1],(n&192)==128&&(c=(t&31)<<6|n&63,c>127&&(a=c));break;case 3:n=e[i+1],r=e[i+2],(n&192)==128&&(r&192)==128&&(c=(t&15)<<12|(n&63)<<6|r&63,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[i+1],r=e[i+2],s=e[i+3],(n&192)==128&&(r&192)==128&&(s&192)==128&&(c=(t&15)<<18|(n&63)<<12|(r&63)<<6|s&63,c>65535&&c<1114112&&(a=c))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023),r.push(a),i+=o}return ce(r)}let se=4096;function ce(e){let t=e.length;if(t<=se)return String.fromCharCode.apply(String,e);let n=``,r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=se));return n}function le(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]&127);return r}function ue(e,t,n){let r=``;n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function de(e,t,n){let r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i=``;for(let r=t;r<n;++r)i+=Ee[e[r]];return i}function w(e,t,n){let r=e.slice(t,n),i=``;for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+r[e+1]*256);return i}s.prototype.slice=function(e,t){let n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);let r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r};function T(e,t,n){if(e%1!=0||e<0)throw RangeError(`offset is not uint`);if(e+t>n)throw RangeError(`Trying to access beyond buffer length`)}s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||T(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||T(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||T(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||T(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||T(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||T(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||T(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=P(function(e){e>>>=0,k(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&be(e,this.length-8);let r=t+this[++e]*256+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*256+this[++e]*2**16+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=P(function(e){e>>>=0,k(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&be(e,this.length-8);let r=t*2**24+this[++e]*2**16+this[++e]*256+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*256+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||T(e,t,this.length);let r=this[e],i=1,a=0;for(;++a<t&&(i*=256);)r+=this[e+a]*i;return i*=128,r>=i&&(r-=2**(8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||T(e,t,this.length);let r=t,i=1,a=this[e+--r];for(;r>0&&(i*=256);)a+=this[e+--r]*i;return i*=128,a>=i&&(a-=2**(8*t)),a},s.prototype.readInt8=function(e,t){return e>>>=0,t||T(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||T(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||T(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||T(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||T(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=P(function(e){e>>>=0,k(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&be(e,this.length-8);let r=this[e+4]+this[e+5]*256+this[e+6]*2**16+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+this[++e]*256+this[++e]*2**16+this[++e]*2**24)}),s.prototype.readBigInt64BE=P(function(e){e>>>=0,k(e,`offset`);let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&be(e,this.length-8);let r=(t<<24)+this[++e]*2**16+this[++e]*256+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*256+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||T(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||T(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||T(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||T(e,8,this.length),n.read(this,e,!1,52,8)};function E(e,t,n,r,i,a){if(!s.isBuffer(e))throw TypeError(`"buffer" argument must be a Buffer instance`);if(t>i||t<a)throw RangeError(`"value" argument is out of bounds`);if(n+r>e.length)throw RangeError(`Index out of range`)}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;E(this,e,t,n,r,0)}let i=1,a=0;for(this[t]=e&255;++a<n&&(i*=256);)this[t+a]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){let r=2**(8*n)-1;E(this,e,t,n,r,0)}let i=n-1,a=1;for(this[t+i]=e&255;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,1,255,0),this[t]=e&255,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function fe(e,t,n,r,i){ye(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function pe(e,t,n,r,i){ye(t,r,i,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}s.prototype.writeBigUInt64LE=P(function(e,t=0){return fe(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeBigUInt64BE=P(function(e,t=0){return pe(this,e,t,BigInt(0),BigInt(`0xffffffffffffffff`))}),s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);E(this,e,t,n,r-1,-r)}let i=0,a=1,o=0;for(this[t]=e&255;++i<n&&(a*=256);)e<0&&o===0&&this[t+i-1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){let r=2**(8*n-1);E(this,e,t,n,r-1,-r)}let i=n-1,a=1,o=0;for(this[t+i]=e&255;--i>=0&&(a*=256);)e<0&&o===0&&this[t+i+1]!==0&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||E(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},s.prototype.writeBigInt64LE=P(function(e,t=0){return fe(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))}),s.prototype.writeBigInt64BE=P(function(e,t=0){return pe(this,e,t,-BigInt(`0x8000000000000000`),BigInt(`0x7fffffffffffffff`))});function me(e,t,n,r,i,a){if(n+r>e.length||n<0)throw RangeError(`Index out of range`)}function he(e,t,r,i,a){return t=+t,r>>>=0,a||me(e,t,r,4),n.write(e,t,r,i,23,4),r+4}s.prototype.writeFloatLE=function(e,t,n){return he(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return he(this,e,t,!1,n)};function ge(e,t,r,i,a){return t=+t,r>>>=0,a||me(e,t,r,8),n.write(e,t,r,i,52,8),r+8}s.prototype.writeDoubleLE=function(e,t,n){return ge(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return ge(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.isBuffer(e))throw TypeError(`argument should be a Buffer`);if(n||=0,!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||=0,r>0&&r<n&&(r=n),r===n||e.length===0||this.length===0)return 0;if(t<0)throw RangeError(`targetStart out of bounds`);if(n<0||n>=this.length)throw RangeError(`Index out of range`);if(r<0)throw RangeError(`sourceEnd out of bounds`);r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);let i=r-n;return this===e&&typeof Uint8Array.prototype.copyWithin==`function`?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),i},s.prototype.fill=function(e,t,n,r){if(typeof e==`string`){if(typeof t==`string`?(r=t,t=0,n=this.length):typeof n==`string`&&(r=n,n=this.length),r!==void 0&&typeof r!=`string`)throw TypeError(`encoding must be a string`);if(typeof r==`string`&&!s.isEncoding(r))throw TypeError(`Unknown encoding: `+r);if(e.length===1){let t=e.charCodeAt(0);(r===`utf8`&&t<128||r===`latin1`)&&(e=t)}}else typeof e==`number`?e&=255:typeof e==`boolean`&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw RangeError(`Out of range index`);if(n<=t)return this;t>>>=0,n=n===void 0?this.length:n>>>0,e||=0;let i;if(typeof e==`number`)for(i=t;i<n;++i)this[i]=e;else{let a=s.isBuffer(e)?e:s.from(e,r),o=a.length;
3if(o===0)throw TypeError(`The value "`+e+`" is invalid for argument "value"`);for(i=0;i<n-t;++i)this[i+t]=a[i%o]}return this};let D={};function _e(e,t,n){D[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}_e(`ERR_BUFFER_OUT_OF_BOUNDS`,function(e){return e?`${e} is outside of buffer bounds`:`Attempt to access memory outside buffer bounds`},RangeError),_e(`ERR_INVALID_ARG_TYPE`,function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),_e(`ERR_OUT_OF_RANGE`,function(e,t,n){let r=`The value of "${e}" is out of range.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=O(String(n)):typeof n==`bigint`&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=O(i)),i+=`n`),r+=` It must be ${t}. Received ${i}`,r},RangeError);function O(e){let t=``,n=e.length,r=+(e[0]===`-`);for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function ve(e,t,n){k(t,`offset`),(e[t]===void 0||e[t+n]===void 0)&&be(t,e.length-(n+1))}function ye(e,t,n,r,i,a){if(e>n||e<t){let n=typeof t==`bigint`?`n`:``,r;throw r=t===0||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${(a+1)*8}${n}`:`>= -(2${n} ** ${(a+1)*8-1}${n}) and < 2 ** ${(a+1)*8-1}${n}`,new D.ERR_OUT_OF_RANGE(`value`,r,e)}ve(r,i,a)}function k(e,t){if(typeof e!=`number`)throw new D.ERR_INVALID_ARG_TYPE(t,`number`,e)}function be(e,t,n){throw Math.floor(e)===e?t<0?new D.ERR_BUFFER_OUT_OF_BOUNDS:new D.ERR_OUT_OF_RANGE(`offset`,`>= 0 and <= ${t}`,e):(k(e,n),new D.ERR_OUT_OF_RANGE(`offset`,`an integer`,e))}let xe=/[^+/0-9A-Za-z-_]/g;function A(e){if(e=e.split(`=`)[0],e=e.trim().replace(xe,``),e.length<2)return``;for(;e.length%4!=0;)e+=`=`;return e}function j(e,t){t||=1/0;let n,r=e.length,i=null,a=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if(--t<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,n&63|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw Error(`Invalid code point`)}return a}function Se(e){let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n)&255);return t}function Ce(e,t){let n,r,i,a=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,a.push(i),a.push(r);return a}function we(e){return t.toByteArray(A(e))}function Te(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function M(e,t){return e instanceof t||e!=null&&e.constructor!=null&&e.constructor.name!=null&&e.constructor.name===t.name}function N(e){return e!==e}let Ee=(function(){let e=`0123456789abcdef`,t=Array(256);for(let n=0;n<16;++n){let r=n*16;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t})();function P(e){return typeof BigInt>`u`?De:e}function De(){throw Error(`BigInt not supported`)}})(Ve),Ve)}var B=Ye(),Xe={},Ze={},Qe={},$e;function V(){return $e?Qe:($e=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Frame=e.Lengths=e.Flags=e.FrameTypes=void 0;var t;(function(e){e[e.RESERVED=0]=`RESERVED`,e[e.SETUP=1]=`SETUP`,e[e.LEASE=2]=`LEASE`,e[e.KEEPALIVE=3]=`KEEPALIVE`,e[e.REQUEST_RESPONSE=4]=`REQUEST_RESPONSE`,e[e.REQUEST_FNF=5]=`REQUEST_FNF`,e[e.REQUEST_STREAM=6]=`REQUEST_STREAM`,e[e.REQUEST_CHANNEL=7]=`REQUEST_CHANNEL`,e[e.REQUEST_N=8]=`REQUEST_N`,e[e.CANCEL=9]=`CANCEL`,e[e.PAYLOAD=10]=`PAYLOAD`,e[e.ERROR=11]=`ERROR`,e[e.METADATA_PUSH=12]=`METADATA_PUSH`,e[e.RESUME=13]=`RESUME`,e[e.RESUME_OK=14]=`RESUME_OK`,e[e.EXT=63]=`EXT`})(t=e.FrameTypes||={}),(function(e){e[e.NONE=0]=`NONE`,e[e.COMPLETE=64]=`COMPLETE`,e[e.FOLLOWS=128]=`FOLLOWS`,e[e.IGNORE=512]=`IGNORE`,e[e.LEASE=64]=`LEASE`,e[e.METADATA=256]=`METADATA`,e[e.NEXT=32]=`NEXT`,e[e.RESPOND=128]=`RESPOND`,e[e.RESUME_ENABLE=128]=`RESUME_ENABLE`})(e.Flags||={}),(function(e){function t(t){return(t&e.METADATA)===e.METADATA}e.hasMetadata=t;function n(t){return(t&e.COMPLETE)===e.COMPLETE}e.hasComplete=n;function r(t){return(t&e.NEXT)===e.NEXT}e.hasNext=r;function i(t){return(t&e.FOLLOWS)===e.FOLLOWS}e.hasFollows=i;function a(t){return(t&e.IGNORE)===e.IGNORE}e.hasIgnore=a;function o(t){return(t&e.RESPOND)===e.RESPOND}e.hasRespond=o;function s(t){return(t&e.LEASE)===e.LEASE}e.hasLease=s;function c(t){return(t&e.RESUME_ENABLE)===e.RESUME_ENABLE}e.hasResume=c})(e.Flags||={}),(function(e){e[e.FRAME=3]=`FRAME`,e[e.HEADER=6]=`HEADER`,e[e.METADATA=3]=`METADATA`,e[e.REQUEST=3]=`REQUEST`})(e.Lengths||={}),(function(e){function n(e){return e.streamId===0}e.isConnection=n;function r(e){return t.REQUEST_RESPONSE<=e.type&&e.type<=t.REQUEST_CHANNEL}e.isRequest=r})(e.Frame||={})})(Qe),Qe)}var et;function tt(){return et?Ze:(et=1,(function(e){var t=Ze&&Ze.__generator||function(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o;return o={next:s(0),throw:s(1),return:s(2)}
3,typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(o){if(r)throw TypeError(`Generator is already executing.`);for(;n;)try{if(r=1,i&&(a=o[0]&2?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[o[0]&2,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};Object.defineProperty(e,"__esModule",{value:!0}),e.Deserializer=e.sizeOfFrame=e.serializeFrame=e.deserializeFrame=e.serializeFrameWithLength=e.deserializeFrames=e.deserializeFrameWithLength=e.writeUInt64BE=e.readUInt64BE=e.writeUInt24BE=e.readUInt24BE=e.MAX_VERSION=e.MAX_TTL=e.MAX_STREAM_ID=e.MAX_RESUME_LENGTH=e.MAX_REQUEST_N=e.MAX_REQUEST_COUNT=e.MAX_MIME_LENGTH=e.MAX_METADATA_LENGTH=e.MAX_LIFETIME=e.MAX_KEEPALIVE=e.MAX_CODE=e.FRAME_TYPE_OFFFSET=e.FLAGS_MASK=void 0;var n=V();e.FLAGS_MASK=1023,e.FRAME_TYPE_OFFFSET=10,e.MAX_CODE=2147483647,e.MAX_KEEPALIVE=2147483647,e.MAX_LIFETIME=2147483647,e.MAX_METADATA_LENGTH=16777215,e.MAX_MIME_LENGTH=255,e.MAX_REQUEST_COUNT=2147483647,e.MAX_REQUEST_N=2147483647,e.MAX_RESUME_LENGTH=65535,e.MAX_STREAM_ID=2147483647,e.MAX_TTL=2147483647,e.MAX_VERSION=65535;var r=4294967296;function i(e,t){var n=e.readUInt8(t)<<16,r=e.readUInt8(t+1)<<8,i=e.readUInt8(t+2);return n|r|i}e.readUInt24BE=i;function a(e,t,n){return n=e.writeUInt8(t>>>16,n),n=e.writeUInt8(t>>>8&255,n),e.writeUInt8(t&255,n)}e.writeUInt24BE=a;function o(e,t){var n=e.readUInt32BE(t),i=e.readUInt32BE(t+4);return n*r+i}e.readUInt64BE=o;function s(e,t,n){var i=t/r|0,a=t%r;return n=e.writeUInt32BE(i,n),e.writeUInt32BE(a,n)}e.writeUInt64BE=s;var c=6,l=3;function u(e){var t=i(e,0);return p(e.slice(l,l+t))}e.deserializeFrameWithLength=u;function d(e){var n,r,a,o,s,c;return t(this,function(t){switch(t.label){case 0:n=0,t.label=1;case 1:return!(n+l<e.length)||(r=i(e,n),a=n+l,o=a+r,o>e.length)?[3,3]:(s=e.slice(a,o),c=p(s),n=o,[4,[c,n]]);case 2:return t.sent(),[3,1];case 3:return[2]}})}e.deserializeFrames=d;function f(e){var t=m(e),n=B.Buffer.allocUnsafe(t.length+l);return a(n,t.length,0),t.copy(n,l),n}e.serializeFrameWithLength=f;function p(t){var r=0,i=t.readInt32BE(r);r+=4;var a=t.readUInt16BE(r);r+=2;var o=a>>>e.FRAME_TYPE_OFFFSET,s=a&e.FLAGS_MASK;switch(o){case n.FrameTypes.SETUP:return b(t,i,s);case n.FrameTypes.PAYLOAD:return Se(t,i,s);case n.FrameTypes.ERROR:return S(t,i,s);case n.FrameTypes.KEEPALIVE:return C(t,i,s);case n.FrameTypes.REQUEST_FNF:return T(t,i,s);case n.FrameTypes.REQUEST_RESPONSE:return E(t,i,s);case n.FrameTypes.REQUEST_STREAM:return ge(t,i,s);case n.FrameTypes.REQUEST_CHANNEL:return D(t,i,s);case n.FrameTypes.METADATA_PUSH:return fe(t,i,s);case n.FrameTypes.REQUEST_N:return ye(t,i,s);case n.FrameTypes.RESUME:return M(t,i,s);case n.FrameTypes.RESUME_OK:return De(t,i,s);case n.FrameTypes.CANCEL:return xe(t,i,s);case n.FrameTypes.LEASE:return ce(t,i,s)}}e.deserializeFrame=p;function m(e){switch(e.type){case n.FrameTypes.SETUP:return v(e);case n.FrameTypes.PAYLOAD:return A(e);case n.FrameTypes.ERROR:return ee(e);case n.FrameTypes.KEEPALIVE:return re(e);case n.FrameTypes.REQUEST_FNF:case n.FrameTypes.REQUEST_RESPONSE:return le(e);case n.FrameTypes.REQUEST_STREAM:case n.FrameTypes.REQUEST_CHANNEL:return me(e);case n.FrameTypes.METADATA_PUSH:return de(e);case n.FrameTypes.REQUEST_N:return O(e);case n.FrameTypes.RESUME:return we(e);case n.FrameTypes.RESUME_OK:return Ee(e);case n.FrameTypes.CANCEL:return k(e);case n.FrameTypes.LEASE:return oe(e)}}e.serializeFrame=m;function h(e){switch(e.type){case n.FrameTypes.SETUP:return y(e);case n.FrameTypes.PAYLOAD:return j(e);case n.FrameTypes.ERROR:return te(e);case n.FrameTypes.KEEPALIVE:return ie(e);case n.FrameTypes.REQUEST_FNF:case n.FrameTypes.REQUEST_RESPONSE:return ue(e);case n.FrameTypes.REQUEST_STREAM:case n.FrameTypes.REQUEST_CHANNEL:return he(e);case n.FrameTypes.METADATA_PUSH:return w(e);case n.FrameTypes.REQUEST_N:return ve();case n.FrameTypes.RESUME:return Te(e);case n.FrameTypes.RESUME_OK:return P();case n.FrameTypes.CANCEL:return be();case n.FrameTypes.LEASE:return se(e)}}e.sizeOfFrame=h;var g=14,_=2;function v(e){var t=e.resumeToken==null?0:e.resumeToken.byteLength,r=e.metadataMimeType==null?0:B.Buffer.byteLength(e.metadataMimeType,`ascii`),i=e.dataMimeType==null?0:B.Buffer.byteLength(e.dataMimeType,`ascii`),a=I(e),o=B.Buffer.allocUnsafe(c+g+(t?_+t:0)+r+i+a),s=F(e,o);return s=o.writeUInt16BE(e.majorVersion,s),s=o.writeUInt16BE(e.minorVersion,s),s=o.writeUInt32BE(e.keepAlive,s),s=o.writeUInt32BE(e.lifetime,s),e.flags&n.Flags.RESUME_ENABLE&&(s=o.writeUInt16BE(t,s),e.resumeToken!=null&&(s+=e.resumeToken.copy(o,s))),s=o.writeUInt8(r,s),e.metadataMimeType!=null&&(s+=o.write(e.metadataMimeType,s,s+r,`ascii`)),s=o.writeUInt8(i,s),e.dataMimeType!=null&&(s+=o.write(e.dataMimeType,s,s+i,`ascii`)),Oe(e,o,s),o}function y(e){var t=e.resumeToken==null?0:e.resumeToken.byteLength,n=e.metadataMimeType==null?0:B.Buffer.byteLength(e.metadataMimeType,`ascii`),r=e.dataMimeType==null?0:B.Buffer.byteLength(e.dataMimeType,`ascii`),i=I(e);return c+g+(t?_+t:0)+n+r+i}function b(e,t,r){e.length;var i=c,a=e.readUInt16BE(i);i+=2;var o=e.readUInt16BE(i);i+=2;var s=e.readInt32BE(i);i+=4;var l=e.readInt32BE(i);i+=4;var u=null;if(r&n.Flags.RESUME_ENABLE){var d=e.readInt16BE(i);i+=2,u=e.slice(i,i+d),i+=d}var f=e.readUInt8(i);i+=1;var p=e.toString(`ascii`,i,i+f);i+=f;var m=e.readUInt8(i);i+=1;var h=e.toString(`ascii`,i,i+m);i+=m;var g={data:null,dataMimeType:h,flags:r,keepAlive:s,lifetime:l,majorVersion:a,metadata:null,metadataMimeType:p,minorVersion:o,resumeToken:u,streamId:0,type:n.FrameTypes.SETUP};return ke(e,g,i),g}var x=4;function ee(e){var t=e.message==null?0:B.Buffer.byteLength(e.message,`utf8`),n=B.Buffer.allocUnsafe(c+x+t),r=F(e,n);return r=n.writeUInt32BE(e.code,r),e.message!=null&&n.write(e.message,r,r+t,`utf8`),n}function te(e){var t=e.message==null?0:B.Buffer.byteLength(e.message,`utf8`);return c+x+t}function S(e,t,r){e.length;var i=c,a=e.readInt32BE(i);i+=4;var o=e.length-i,s=``;return o>0&&(s=e.toString(`utf8`,i,i+o),i+=o),{code:a,flags:r,message:s,streamId:t,type:n.FrameTypes.ERROR}}var ne=8;function re(e){var t=e.data==null?0:e.data.byteLength,n=B.Buffer.allocUnsafe(c+ne+t),r=F(e,n);return r=s(n,e.lastReceivedPosition,r),e.data!=null&&e.data.copy(n,r),n}function ie(e){var t=e.data==null?0:e.data.byteLength;return c+ne+t}function C(e,t,r){e.length;var i=c,a=o(e,i);i+=8;var s=null;return i<e.length&&(s=e.slice(i,e.length)),{data:s,flags:r,lastReceivedPosition:a,streamId:0,type:n.FrameTypes.KEEPALIVE}}var ae=8;function oe(e){var t=e.metadata==null?0:e.metadata.byteLength,n=B.Buffer.allocUnsafe(c+ae+t),r=F(e,n);return r=n.writeUInt32BE(e.ttl,r),r=n.writeUInt32BE(e.requestCount,r),e.metadata!=null&&e.metadata.copy(n,r),n}function se(e){var t=e.metadata==null?0:e.metadata.byteLength;return c+ae+t}function ce(e,t,r){var i=c,a=e.readUInt32BE(i);i+=4;var o=e.readUInt32BE(i);i+=4;var s=null;return i<e.length&&(s=e.slice(i,e.length)),{flags:r,metadata:s,requestCount:o,streamId:0,ttl:a,type:n.FrameTypes.LEASE}}function le(e){var t=I(e),n=B.Buffer.allocUnsafe(c+t);return Oe(e,n,F(e,n)),n}function ue(e){return c+I(e)}function de(e){var t=e.metadata;if(t!=null){var n=B.Buffer.allocUnsafe(c+t.byteLength),r=F(e,n);return t.copy(n,r),n}var n=B.Buffer.allocUnsafe(c);return F(e,n),n}function w(e){return c+(e.metadata==null?0:e.metadata.byteLength)}function T(e,t,r){e.length;var i={data:null,flags:r,metadata:null,streamId:t,type:n.FrameTypes.REQUEST_FNF};return ke(e,i,c),i}function E(e,t,r){var i={data:null,flags:r,metadata:null,streamId:t,type:n.FrameTypes.REQUEST_RESPONSE};return ke(e,i,c),i}function fe(e,t,r){return{flags:r,metadata:length===c?null:e.slice(c,length),streamId:0,type:n.FrameTypes.METADATA_PUSH}}var pe=4;function me(e){var t=I(e),n=B.Buffer.allocUnsafe(c+pe+t),r=F(e,n);return r=n.writeUInt32BE(e.requestN,r),Oe(e,n,r),n}function he(e){var t=I(e);return c+pe+t}function ge(e,t,r){e.length;var i=c,a=e.readInt32BE(i);i+=4;var o={data:null,flags:r,metadata:null,requestN:a,streamId:t,type:n.FrameTypes.REQUEST_STREAM};return ke(e,o,i),o}function D(e,t,r){e.length;var i=c,a=e.readInt32BE(i);i+=4;var o={data:null,flags:r,metadata:null,requestN:a,streamId:t,type:n.FrameTypes.REQUEST_CHANNEL};return ke(e,o,i),o}var _e=4;function O(e){var t=B.Buffer.allocUnsafe(c+_e),n=F(e,t);return t.writeUInt32BE(e.requestN,n),t}function ve(e){return c+_e}function ye(e,t,r){return e.length,{flags:r,requestN:e.readInt32BE(c),streamId:t,type:n.FrameTypes.REQUEST_N}}function k(e){var t=B.Buffer.allocUnsafe(c);return F(e,t),t}function be(e){return c}function xe(e,t,r){return e.length,{flags:r,streamId:t,type:n.FrameTypes.CANCEL}}function A(e){var t=I(e),n=B.Buffer.allocUnsafe(c+t);return Oe(e,n,F(e,n)),n}function j(e){return c+I(e)}function Se(e,t,r){e.length;var i={data:null,flags:r,metadata:null,streamId:t,type:n.FrameTypes.PAYLOAD};return ke(e,i,c),i}var Ce=22;function we(e){var t=e.resumeToken.byteLength,n=B.Buffer.allocUnsafe(c+Ce+t),r=F(e,n);return r=n.writeUInt16BE(e.majorVersion,r),r=n.writeUInt16BE(e.minorVersion,r),r=n.writeUInt16BE(t,r),r+=e.resumeToken.copy(n,r),r=s(n,e.serverPosition,r),s(n,e.clientPosition,r),n}function Te(e){var t=e.resumeToken.byteLength;return c+Ce+t}function M(e,t,r){e.length;var i=c,a=e.readUInt16BE(i);i+=2;var s=e.readUInt16BE(i);i+=2;var l=e.readInt16BE(i);i+=2;var u=e.slice(i,i+l);i+=l;var d=o(e,i);i+=8;var f=o(e,i);return i+=8,{clientPosition:f,flags:r,majorVersion:a,minorVersion:s,resumeToken:u,serverPosition:d,streamId:0,type:n.FrameTypes.RESUME}}var N=8;function Ee(e){var t=B.Buffer.allocUnsafe(c+N),n=F(e,t);return s(t,e.clientPosition,n),t}function P(e){return c+N}function De(e,t,r){return e.length,{clientPosition:o(e,c),flags:r,streamId:0,type:n.FrameTypes.RESUME_OK}}
3function F(t,n){var r=n.writeInt32BE(t.streamId,0);return n.writeUInt16BE(t.type<<e.FRAME_TYPE_OFFFSET|t.flags&e.FLAGS_MASK,r)}function I(e){var t=0;return e.data!=null&&(t+=e.data.byteLength),n.Flags.hasMetadata(e.flags)&&(t+=l,e.metadata!=null&&(t+=e.metadata.byteLength)),t}function Oe(e,t,r){if(n.Flags.hasMetadata(e.flags)){if(e.metadata!=null){var i=e.metadata.byteLength;r=a(t,i,r),r+=e.metadata.copy(t,r)}else r=a(t,0,r)}e.data!=null&&e.data.copy(t,r)}function ke(e,t,r){if(n.Flags.hasMetadata(t.flags)){var a=i(e,r);r+=l,a>0&&(t.metadata=e.slice(r,r+a),r+=a)}r<e.length&&(t.data=e.slice(r,e.length))}e.Deserializer=function(){function e(){}return e.prototype.deserializeFrame=function(e){return p(e)},e.prototype.deserializeFrameWithLength=function(e){return u(e)},e.prototype.deserializeFrames=function(e){return d(e)},e}()})(Ze),Ze)}var nt={},rt;function it(){return rt?nt:(rt=1,Object.defineProperty(nt,"__esModule",{value:!0}),nt)}var at={},ot;function st(){if(ot)return at;ot=1;var e=at&&at.__values||function(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)};
3return Object.defineProperty(at,"__esModule",{value:!0}),at.Deferred=void 0,at.Deferred=function(){function t(){this._done=!1,this.onCloseCallbacks=[]}return Object.defineProperty(t.prototype,"done",{get:function(){return this._done},enumerable:!1,configurable:!0}),t.prototype.close=function(t){var n,r,i,a;if(this.done){console.warn(`Trying to close for the second time. ${t?`Dropping error [${t}].`:``}`);return}if(this._done=!0,this._error=t,t){try{for(var o=e(this.onCloseCallbacks),s=o.next();!s.done;s=o.next()){var c=s.value;c(t)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return}try{for(var l=e(this.onCloseCallbacks),u=l.next();!u.done;u=l.next()){var c=u.value;c()}}catch(e){i={error:e}}finally{try{u&&!u.done&&(a=l.return)&&a.call(l)}finally{if(i)throw i.error}}},t.prototype.onClose=function(e){if(this._done){e(this._error);return}this.onCloseCallbacks.push(e)},t}(),at}var ct={},lt;function ut(){return lt?ct:(lt=1,(function(e){var t=ct&&ct.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if(typeof n!=`function`&&n!==null)throw TypeError(`Class extends value `+String(n)+` is not a constructor or null`);e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.ErrorCodes=e.RSocketError=void 0,e.RSocketError=function(e){t(n,e);function n(t,n){var r=e.call(this,n)||this;return r.code=t,r}return n}(Error),(function(e){e[e.RESERVED=0]=`RESERVED`,e[e.INVALID_SETUP=1]=`INVALID_SETUP`,e[e.UNSUPPORTED_SETUP=2]=`UNSUPPORTED_SETUP`,e[e.REJECTED_SETUP=3]=`REJECTED_SETUP`,e[e.REJECTED_RESUME=4]=`REJECTED_RESUME`,e[e.CONNECTION_CLOSE=258]=`CONNECTION_CLOSE`,e[e.CONNECTION_ERROR=257]=`CONNECTION_ERROR`,e[e.APPLICATION_ERROR=513]=`APPLICATION_ERROR`,e[e.REJECTED=514]=`REJECTED`,e[e.CANCELED=515]=`CANCELED`,e[e.INVALID=516]=`INVALID`,e[e.RESERVED_EXTENSION=4294967295]=`RESERVED_EXTENSION`})(e.ErrorCodes||={})})(ct),ct)}var dt={},ft;function pt(){return ft?dt:(ft=1,Object.defineProperty(dt,"__esMo
3dule",{value:!0}),dt)}var H={},U={},mt;function ht(){return mt?U:(mt=1,(function(e){var t=U&&U.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if(typeof n!=`function`&&n!==null)throw TypeError(`Class extends value `+String(n)+` is not a constructor or null`);e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),n=U&&U.__awaiter||function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},r=U&&U.__generator||function(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(o){if(r)throw TypeError(`Generator is already executing.`);for(;n;)try{if(r=1,i&&(a=o[0]&2?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[o[0]&2,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>
30&&a[a.length-1])&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};Object.defineProperty(e,"__esModule",{value:!0}),e.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=e.ResumableClientServerInputMultiplexerDemultiplexer=e.ClientServerInputMultiplexerDemultiplexer=e.StreamIdGenerator=void 0;var i=Ut(),a=st(),o=ut(),s=V();(function(e){function t(e){return new n(e)}e.create=t;var n=function(){function e(e){this.currentId=e}return e.prototype.next=function(e){var t=this.currentId+2;e(t)&&(this.currentId=t)},e}()})(e.StreamIdGenerator||={});var c=function(e){t(n,e);function n(t,n,r){var i=e.call(this)||this;return i.streamIdSupplier=t,i.outbound=n,i.closeable=r,i.registry={},r.onClose(i.close.bind(i)),i}return n.prototype.handle=function(e){if(s.Frame.isConnection(e)){if(e.type===i.FrameTypes.RESERVED)return;this.connectionFramesHandler.handle(e)}else if(s.Frame.isRequest(e)){if(this.registry[e.streamId])return;this.requestFramesHandler.handle(e,this)}else{var t=this.registry[e.streamId];if(!t)return;t.handle(e)}},n.prototype.connectionInbound=function(e){if(this.connectionFramesHandler)throw Error(`Connection frame handler has already been installed`);this.connectionFramesHandler=e},n.prototype.handleRequestStream=function(e){if(this.requestFramesHandler)throw Error(`Stream handler has already been installed`);this.requestFramesHandler=e},n.prototype.send=function(e){this.outbound.send(e)},Object.defineProperty(n.prototype,"connectionOutbound",{get:function(){return this},enumerable:!1,configurable:!0}),n.prototype.createRequestStream=function(e){var t=this;if(this.done){e.handleReject(Error(`Already closed`));return}var n=this.registry;this.streamIdSupplier.next(function(n){return e.handleReady(n,t)},Object.keys(n))},n.prototype.connect=function(e){this.registry[e.streamId]=e},n.prototype.disconnect=function(e){delete this.registry[e.streamId]},n.prototype.close=function(t){if(this.done){e.prototype.close.call(this,t);return}for(var n in this.registry)this.registry[n].close(Error(`Closed. ${t?`Original cause [${t}].`:``}`));e.prototype.close.call(this,t)},n}(a.Deferred);e.ClientServerInputMultiplexerDemultiplexer=c,e.ResumableClientServerInputMultiplexerDemultiplexer=function(e){t(c,e);function c(t,n,r,i,o,s,c){var l=e.call(this,t,n,new a.Deferred)||this;return l.frameStore=i,l.token=o,l.sessionTimeout=c,s instanceof Function?l.reconnector=s:l.sessionStore=s,r.onClose(l.handleConnectionClose.bind(l)),l}return c.prototype.send=function(t){if(s.Frame.isConnection(t)){if(t.type===i.FrameTypes.KEEPALIVE)t.lastReceivedPosition=this.frameStore.lastReceivedFramePosition;else if(t.type===i.FrameTypes.ERROR){this.outbound.send(t),this.sessionStore&&delete this.sessionStore[this.token],e.prototype.close.call(this,new o.RSocketError(t.code,t.message));return}}else this.frameStore.store(t);this.outbound.send(t)},c.prototype.handle=function(t){if(s.Frame.isConnection(t)){if(t.type===i.FrameTypes.KEEPALIVE)try{this.frameStore.dropTo(t.lastReceivedPosition)}catch(e){this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:e.code,message:e.message}),this.close(e)}else if(t.type===i.FrameTypes.ERROR){e.prototype.handle.call(this,t),this.sessionStore&&delete this.sessionStore[this.token],e.prototype.close.call(this,new o.RSocketError(t.code,t.message));return}}else this.frameStore.record(t);e.prototype.handle.call(this,t)},c.prototype.resume=function(e,t,n){switch(this.outbound=t,e.type){case i.FrameTypes.RESUME:if(clearTimeout(this.timeoutId),this.frameStore.lastReceivedFramePosition<e.clientPosition){var r=new o.RSocketError(i.ErrorCodes.REJECTED_RESUME,`Impossible to resume since first available client frame position is greater than last received server frame position`);this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:r.code,message:r.message}),this.close(r);return}try{this.frameStore.dropTo(e.serverPosition)}catch(e){this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:e.code,message:e.message}),this.close(e);return}this.outbound.send({type:i.FrameTypes.RESUME_OK,streamId:0,flags:i.Flags.NONE,clientPosition:this.frameStore.lastReceivedFramePosition});break;case i.FrameTypes.RESUME_OK:try{this.frameStore.dropTo(e.clientPosition)}catch(e){this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:e.code,message:e.message}),this.close(e)}}this.frameStore.drain(this.outbound.send.bind(this.outbound)),n.onClose(this.handleConnectionClose.bind(this)),this.connectionFramesHandler.resume()}
3,c.prototype.handleConnectionClose=function(e){return n(this,void 0,void 0,function(){var e;return r(this,function(t){switch(t.label){case 0:if(this.connectionFramesHandler.pause(),!this.reconnector)return[3,5];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.reconnector(this,this.frameStore)];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),this.close(e),[3,4];case 4:return[3,6];case 5:this.timeoutId=setTimeout(this.close.bind(this),this.sessionTimeout),t.label=6;case 6:return[2]}})})},c}(c),e.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=function(){function e(e,t,n){this.outbound=e,this.closeable=t,this.delegate=n,this.resumed=!1}return e.prototype.close=function(){this.delegate.close()},e.prototype.onClose=function(e){this.delegate.onClose(e)},Object.defineProperty(e.prototype,"connectionOutbound",{get:function(){return this.delegate.connectionOutbound},enumerable:!1,configurable:!0}),e.prototype.createRequestStream=function(e){this.delegate.createRequestStream(e)},e.prototype.connectionInbound=function(e){this.delegate.connectionInbound(e)},e.prototype.handleRequestStream=function(e){this.delegate.handleRequestStream(e)},e.prototype.handle=function(e){var t=this;if(!this.resumed){if(e.type===i.FrameTypes.RESUME_OK){this.resumed=!0,this.delegate.resume(e,this.outbound,this.closeable);return}this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,code:i.ErrorCodes.CONNECTION_ERROR,message:`Incomplete RESUME handshake. Unexpected frame ${e.type} received`,flags:i.Flags.NONE}),this.closeable.close(),this.closeable.onClose(function(){return t.delegate.close(new o.RSocketError(i.ErrorCodes.CONNECTION_ERROR,`Incomplete RESUME handshake. Unexpected frame ${e.type} received`))});return}this.delegate.handle(e)},e}()})(U),U)}var W={},G={},K={},gt;function _t(){if(gt)return K;gt=1;var e=K&&K.__generator||function(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(o){if(r)throw TypeError(`Generator is already executing.`);for(;n;)try{if(r=1,i&&(a=o[0]&2?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[o[0]&2,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>
30&&a[a.length-1])&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};Object.defineProperty(K,"__esModule",{value:!0}),K.fragmentWithRequestN=K.fragment=K.isFragmentable=void 0;var t=V();function n(e,n,r){return n!==0&&e.data.byteLength+(e.metadata?e.metadata.byteLength+t.Lengths.METADATA:0)+(r==t.FrameTypes.REQUEST_STREAM||r==t.FrameTypes.REQUEST_CHANNEL?t.Lengths.REQUEST:0)>n}K.isFragmentable=n;function r(n,r,i,a,o){var s,c,l,u,d,f,p,p,m,h,g,g;return o===void 0&&(o=!1),e(this,function(e){switch(e.label){case 0:return s=r.data?.byteLength??0,c=a!==t.FrameTypes.PAYLOAD,l=i,r.metadata?(d=r.metadata.byteLength,d===0?(l-=t.Lengths.METADATA,u=B.Buffer.allocUnsafe(0),[3,6]):[3,1]):[3,6];case 1:return f=0,!c||(l-=t.Lengths.METADATA,p=Math.min(d,f+l),u=r.metadata.slice(f,p),l-=u.byteLength,f=p,l!==0)?[3,3]:(c=!1,[4,{type:a,flags:t.Flags.FOLLOWS|t.Flags.METADATA,data:void 0,metadata:u,streamId:n}]);case 2:e.sent(),u=void 0,l=i,e.label=3;case 3:return f<d?(l-=t.Lengths.METADATA,p=Math.min(d,f+l),u=r.metadata.slice(f,p),l-=u.byteLength,f=p,l!==0&&s!==0?[3,5]:[4,{type:t.FrameTypes.PAYLOAD,flags:t.Flags.NEXT|t.Flags.METADATA|(f===d&&o&&s===0?t.Flags.COMPLETE:t.Flags.FOLLOWS),data:void 0,metadata:u,streamId:n}]):[3,6];case 4:e.sent(),u=void 0,l=i,e.label=5;case 5:return[3,3];case 6:return m=0,c?(g=Math.min(s,m+l),h=r.data.slice(m,g),l-=h.byteLength,m=g,[4,{type:a,flags:t.Flags.FOLLOWS|(u?t.Flags.METADATA:t.Flags.NONE),data:h,metadata:u,streamId:n}]):[3,8];case 7:e.sent(),u=void 0,h=void 0,l=i,e.label=8;case 8:return m<s?(g=Math.min(s,m+l),h=r.data.slice(m,g),l-=h.byteLength,m=g,[4,{type:t.FrameTypes.PAYLOAD,flags:m===s?(o?t.Flags.COMPLETE:t.Flags.NONE)|t.Flags.NEXT|(u?t.Flags.METADATA:0):t.Flags.FOLLOWS|t.Flags.NEXT|(u?t.Flags.METADATA:0),data:h,metadata:u,streamId:n}]):[3,10];case 9:return e.sent(),u=void 0,h=void 0,l=i,[3,8];case 10:return[2]}})}K.fragment=r;function i(n,r,i,a,o,s){var c,l,u,d,f,p,m,m,h,g,_,_;return s===void 0&&(s=!1),e(this,function(e){switch(e.label){case 0:return c=r.data?.byteLength??0,l=!0,u=i,r.metadata?(f=r.metadata.byteLength,f===0?(u-=t.Lengths.METADATA,d=B.Buffer.allocUnsafe(0),[3,6]):[3,1]):[3,6];case 1:return p=0,!l||(u-=t.Lengths.METADATA+t.Lengths.REQUEST,m=Math.min(f,p+u),d=r.metadata.slice(p,m),u-=d.byteLength,p=m,u!==0)?[3,3]:(l=!1,[4,{type:a,flags:t.Flags.FOLLOWS|t.Flags.METADATA,data:void 0,requestN:o,metadata:d,streamId:n}]);case 2:e.sent(),d=void 0,u=i,e.label=3;case 3:return p<f?(u-=t.Lengths.METADATA,m=Math.min(f,p+u),d=r.metadata.slice(p,m),u-=d.byteLength,p=m,u!==0&&c!==0?[3,5]:[4,{type:t.FrameTypes.PAYLOAD,flags:t.Flags.NEXT|t.Flags.METADATA|(p===f&&s&&c===0?t.Flags.COMPLETE:t.Flags.FOLLOWS),data:void 0,metadata:d,streamId:n}]):[3,6];case 4:e.sent(),d=void 0,u=i,e.label=5;case 5:return[3,3];case 6:return h=0,l?(u-=t.Lengths.REQUEST,_=Math.min(c,h+u),g=r.data.slice(h,_),u-=g.byteLength,h=_,[4,{type:a,flags:t.Flags.FOLLOWS|(d?t.Flags.METADATA:t.Flags.NONE),data:g,requestN:o,metadata:d,streamId:n}]):[3,8];case 7:e.sent(),d=void 0,g=void 0,u=i,e.label=8;case 8:return h<c?(_=Math.min(c,h+u),g=r.data.slice(h,_),u-=g.byteLength,h=_,[4,{type:t.FrameTypes.PAYLOAD,flags:h===c?(s?t.Flags.COMPLETE:t.Flags.NONE)|t.Flags.NEXT|(d?t.Flags.METADATA:0):t.Flags.FOLLOWS|t.Flags.NEXT|(d?t.Flags.METADATA:0),data:g,metadata:d,streamId:n}]):[3,10];case 9:return e.sent(),d=void 0,g=void 0,u=i,[3,8];case 10:return[2]}})}return K.fragmentWithRequestN=i,K}var vt={},yt;function bt(){if(yt)return vt;yt=1,Object.defineProperty(vt,"__esModule",{value:!0}),vt.cancel=vt.reassemble=vt.add=void 0;function e(e,t,n){return e.hasFragments?(e.data=e.data?B.Buffer.concat([e.data,t]):t,e.metadata&&n&&(e.metadata=B.Buffer.concat([e.metadata,n])),!0):(e.hasFragments=!0,e.data=t,n&&(e.metadata=n),!0)}vt.add=e;function t(e,t,n){e.hasFragments=!1;var r=e.data?B.Buffer.concat([e.data,t]):t;if(e.data=void 0,e.metadata){var i=n?B.Buffer.concat([e.metadata,n]):e.metadata;return e.metadata=void 0,{data:r,metadata:i}}return{data:r}}vt.reassemble=t;function n(e){e.hasFragments=!1,e.data=void 0,e.metadata=void 0}return vt.cancel=n,vt}var xt;function St(){if(xt)return G;xt=1;var e=G&&G.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),t=G&&G.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),n=G&&G.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(n!=null)for(var i in n)i!=="default"&&Object.prototype.hasOwnProperty.call(n,i)&&e(r,n,i);return t(r,n),r},r=G&&G.__values||function(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
3if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)};Object.defineProperty(G,"__esModule",{value:!0}),G.RequestChannelResponderStream=G.RequestChannelRequesterStream=void 0;var i=ut(),a=_t(),o=V(),s=n(bt());return G.RequestChannelRequesterStream=function(){function e(e,t,n,r,i,a){this.payload=e,this.isComplete=t,this.receiver=n,this.fragmentSize=r,this.initialRequestN=i,this.leaseManager=a,this.streamType=o.FrameTypes.REQUEST_CHANNEL}return e.prototype.handleReady=function(e,t){var n,i;if(this.outboundDone)return!1;this.streamId=e,this.stream=t,t.connect(this);var s=this.isComplete;if(s&&(this.outboundDone=s),(0,a.isFragmentable)(this.payload,this.fragmentSize,o.FrameTypes.REQUEST_CHANNEL))try{for(var c=r((0,a.fragmentWithRequestN)(e,this.payload,this.fragmentSize,o.FrameTypes.REQUEST_CHANNEL,this.initialRequestN,s)),l=c.next();!l.done;l=c.next()){var u=l.value;this.stream.send(u)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}else this.stream.send({type:o.FrameTypes.REQUEST_CHANNEL,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:(this.payload.metadata===void 0?o.Flags.NONE:o.Flags.METADATA)|(s?o.Flags.COMPLETE:o.Flags.NONE),streamId:e});return this.hasExtension&&this.stream.send({type:o.FrameTypes.EXT,streamId:e,extendedContent:this.extendedContent,extendedType:this.extendedType,flags:this.flags}),!0},e.prototype.handleReject=function(e){this.inboundDone||(this.inboundDone=!0,this.outboundDone=!0,this.receiver.onError(e))},e.prototype.handle=function(e){var t,n=e.type;switch(n){case o.FrameTypes.PAYLOAD:var r=o.Flags.hasComplete(e.flags),a=o.Flags.hasNext(e.flags);if(r||!o.Flags.hasFollows(e.flags)){if(r&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this),!a)){this.receiver.onComplete();return}var c=this.hasFragments?s.reassemble(this,e.data,e.metadata):{data:e.data,metadata:e.metadata};this.receiver.onNext(c,r);return}if(s.add(this,e.data,e.metadata))return;t=`Unexpected frame size`;break;case o.FrameTypes.CANCEL:if(this.outboundDone)return;this.outboundDone=!0,this.inboundDone&&this.stream.disconnect(this),this.receiver.cancel();return;case o.FrameTypes.REQUEST_N:if(this.outboundDone)return;if(this.hasFragments){t=`Unexpected frame type [${n}] during reassembly`;break}this.receiver.request(e.requestN);return;case o.FrameTypes.ERROR:var l=this.outboundDone;this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),s.cancel(this),l||this.receiver.cancel(),this.receiver.onError(new i.RSocketError(e.code,e.message));return;case o.FrameTypes.EXT:this.receiver.onExtension(e.extendedType,e.extendedContent,o.Flags.hasIgnore(e.flags));return;default:t=`Unexpected frame type [${n}]`}this.close(new i.RSocketError(i.ErrorCodes.CANCELED,t)),this.stream.send({type:o.FrameTypes.CANCEL,streamId:this.streamId,flags:o.Flags.NONE}),this.stream.disconnect(this)},e.prototype.request=function(e){if(!this.inboundDone){if(!this.streamId){this.initialRequestN+=e;return}this.stream.send({type:o.FrameTypes.REQUEST_N,flags:o.Flags.NONE,requestN:e,streamId:this.streamId})}},e.prototype.cancel=function(){var e,t=this.inboundDone,n=this.outboundDone;if(!(t&&n)){if(this.inboundDone=!0,this.outboundDone=!0,n||this.receiver.cancel(),!this.streamId){(e=this.leaseManager)==null||e.cancelRequest(this);return}this.stream.send({type:t?o.FrameTypes.ERROR:o.FrameTypes.CANCEL,flags:o.Flags.NONE,streamId:this.streamId,code:i.ErrorCodes.CANCELED,message:`Cancelled`}),this.stream.disconnect(this),s.cancel(this)}},e.prototype.onNext=function(e,t){var n,i;if(!this.outboundDone){if(t&&(this.outboundDone=!0,this.inboundDone&&this.stream.disconnect(this)),(0,a.isFragmentable)(e,this.fragmentSize,o.FrameTypes.PAYLOAD))try{for(var s=r((0,a.fragment)(this.streamId,e,this.fragmentSize,o.FrameTypes.PAYLOAD,t)),c=s.next();!c.done;c=s.next()){var l=c.value;this.stream.send(l)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}else this.stream.send({type:o.FrameTypes.PAYLOAD,streamId:this.streamId,flags:o.Flags.NEXT|(e.metadata?o.Flags.METADATA:o.Flags.NONE)|(t?o.Flags.COMPLETE:o.Flags.NONE),data:e.data,metadata:e.metadata})}},e.prototype.onComplete=function(){if(!this.streamId){this.isComplete=!0;return}this.outboundDone||(this.outboundDone=!0,this.stream.send({type:o.FrameTypes.PAYLOAD,streamId:this.streamId,flags:o.Flags.COMPLETE,data:null,metadata:null}),this.inboundDone&&this.stream.disconnect(this))},e.prototype.onError=function(e){if(!this.outboundDone){var t=this.inboundDone;this.outboundDone=!0,this.inboundDone=!0,this.stream.send({type:o.FrameTypes.ERROR,streamId:this.streamId,flags:o.Flags.NONE,code:e instanceof i.RSocketError?e.code:i.ErrorCodes.APPLICATION_ERROR,message:e.message}),this.stream.disconnect(this),t||this.receiver.onError(e)}},e.prototype.onExtension=function(e,t,n){if(!this.outboundDone){if(!this.streamId){this.hasExtension=!0,this.extendedType=e,this.extendedContent=t,this.flags=n?o.Flags.IGNORE:o.Flags.NONE;return}this.stream.send({streamId:this.streamId,type:o.FrameTypes.EXT,extendedType:e,extendedContent:t,flags:n?o.Flags.IGNORE:o.Flags.NONE})}},e.prototype.close=function(e){if(!(this.inboundDone&&this.outboundDone)){var t=this.inboundDone,n=this.outboundDone;this.inboundDone=!0,this.outboundDone=!0,s.cancel(this),n||this.receiver.cancel(),t||(e?this.receiver.onError(e):this.receiver.onComplete())}},e}(),G.RequestChannelResponderStream=function(){function e(e,t,n,r,i){if(this.streamId=e,this.stream=t,this.fragmentSize=n,this.handler=r,this.streamType=o.FrameTypes.REQUEST_CHANNEL,t.connect(this),o.Flags.hasFollows(i.flags)){s.add(this,i.data,i.metadata),this.initialRequestN=i.requestN,this.isComplete=o.Flags.hasComplete(i.flags);return}var a={data:i.data,metadata:i.metadata},c=o.Flags.hasComplete(i.flags);this.inboundDone=c;try{this.receiver=r(a,i.requestN,c,this),this.outboundDone&&this.defferedError&&this.receiver.onError(this.defferedError)}catch(e){this.outboundDone&&!this.inboundDone?this.cancel():this.inboundDone=!0,this.onError(e)}}return e.prototype.handle=function(e){var t,n=e.type;switch(n){case o.FrameTypes.PAYLOAD:if(o.Flags.hasFollows(e.flags)){if(s.add(this,e.data,e.metadata))return;t=`Unexpected frame size`;break}var r=this.hasFragments?s.reassemble(this,e.data,e.metadata):{data:e.data,metadata:e.metadata},a=o.Flags.hasComplete(e.flags);if(this.receiver){if(a&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this),!o.Flags.hasNext(e.flags))){this.receiver.onComplete();return}this.receiver.onNext(r,a)}else{var c=this.isComplete||a;c&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this));try{this.receiver=this.handler(r,this.initialRequestN,c,this),this.outboundDone&&this.defferedError}catch(e){this.outboundDone&&!this.inboundDone?this.cancel():this.inboundDone=!0,this.onError(e)}}return;case o.FrameTypes.REQUEST_N:if(!this.receiver||this.hasFragments){t=`Unexpected frame type [${n}] during reassembly`;break}this.receiver.request(e.requestN);return;case o.FrameTypes.ERROR:case o.FrameTypes.CANCEL:var c=this.inboundDone,l=this.outboundDone;if(this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),s.cancel(this),!this.receiver)return;if(l||this.receiver.cancel(),!c){var u=n===o.FrameTypes.CANCEL?new i.RSocketError(i.ErrorCodes.CANCELED,`Cancelled`):new i.RSocketError(e.code,e.message);this.receiver.onError(u)}return;case o.FrameTypes.EXT:if(!this.receiver||this.hasFragments){t=`Unexpected frame type [${n}] during reassembly`;break}this.receiver.onExtension(e.extendedType,e.extendedContent,o.Flags.hasIgnore(e.flags));return;default:t=`Unexpected frame type [${n}]`}this.stream.send({type:o.FrameTypes.ERROR,flags:o.Flags.NONE,code:i.ErrorCodes.CANCELED,message:t,streamId:this.streamId}),this.stream.disconnect(this),this.close(new i.RSocketError(i.ErrorCodes.CANCELED,t))},e.prototype.onError=function(e){if(this.outboundDone){console.warn(`Trying to error for the second time. ${e?`Dropping error [${e}].`:``}`);return}var t=this.inboundDone;this.outboundDone=!0,this.inboundDone=!0,this.stream.send({type:o.FrameTypes.ERROR,flags:o.Flags.NONE,code:e instanceof i.RSocketError?e.code:i.ErrorCodes.APPLICATION_ERROR,message:e.message,streamId:this.streamId}),this.stream.disconnect(this),t||(this.receiver?this.receiver.onError(e):this.defferedError=e)},e.prototype.onNext=function(e,t){var n,i;if(!this.outboundDone){if(t&&(this.outboundDone=!0),(0,a.isFragmentable)(e,this.fragmentSize,o.FrameTypes.PAYLOAD))try{for(var s=r((0,a.fragment)(this.streamId,e,this.fragmentSize,o.FrameTypes.PAYLOAD,t)),c=s.next();!c.done;c=s.next()){var l=c.value;this.stream.send(l)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}else this.stream.send({type:o.FrameTypes.PAYLOAD,flags:o.Flags.NEXT|(t?o.Flags.COMPLETE:o.Flags.NONE)|(e.metadata?o.Flags.METADATA:o.Flags.NONE),data:e.data,metadata:e.metadata,streamId:this.streamId});t&&this.inboundDone&&this.stream.disconnect(this)}},e.prototype.onComplete=function(){this.outboundDone||(this.outboundDone=!0,this.stream.send({type:o.FrameTypes.PAYLOAD,flags:o.Flags.COMPLETE,streamId:this.streamId,data:null,metadata:null}),this.inboundDone&&this.stream.disconnect(this))},e.prototype.onExtension=function(e,t,n){this.outboundDone&&this.inboundDone||this.stream.send({type:o.FrameTypes.EXT,streamId:this.streamId,flags:n?o.Flags.IGNORE:o.Flags.NONE,extendedType:e,extendedContent:t})},e.prototype.request=function(e){this.inboundDone||this.stream.send({type:o.FrameTypes.REQUEST_N,flags:o.Flags.NONE,streamId:this.streamId,requestN:e})},e.prototype.cancel=function(){this.inboundDone||(this.inboundDone=!0,this.stream.send({type:o.FrameTypes.CANCEL,flags:o.Flags.NONE,streamId:this.streamId}),this.outboundDone&&this.stream.disconnect(this))},e.prototype.close=function(e){if(this.inboundDone&&this.outboundDone){console.warn(`Trying to close for the second time. ${e?`Dropping error [${e}].`:``}`);return}var t=this.inboundDone,n=this.outboundDone;this.inboundDone=!0,this.outboundDone=!0,s.cancel(this);var r=this.receiver;r&&(n||r.cancel(),t||(e?r.onError(e):r.onComplete()))},e}(),G}var q={},Ct;function wt(){if(Ct)return q;Ct=1;var e=q&&q.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),t=q&&q.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),n=q&&q.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(n!=null)for(var i in n)i!=="default"&&Object.prototype.hasOwnProperty.call(n,i)&&e(r,n,i);return t(r,n),r},r=q&&q.__values||function(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
3if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)};Object.defineProperty(q,"__esModule",{value:!0}),q.RequestFnfResponderStream=q.RequestFnFRequesterStream=void 0;var i=ut(),a=_t(),o=V(),s=n(bt());return q.RequestFnFRequesterStream=function(){function e(e,t,n,r){this.payload=e,this.receiver=t,this.fragmentSize=n,this.leaseManager=r,this.streamType=o.FrameTypes.REQUEST_FNF}return e.prototype.handleReady=function(e,t){var n,i;if(this.done)return!1;if(this.streamId=e,(0,a.isFragmentable)(this.payload,this.fragmentSize,o.FrameTypes.REQUEST_FNF))try{for(var s=r((0,a.fragment)(e,this.payload,this.fragmentSize,o.FrameTypes.REQUEST_FNF)),c=s.next();!c.done;c=s.next()){var l=c.value;t.send(l)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}else t.send({type:o.FrameTypes.REQUEST_FNF,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?o.Flags.METADATA:0,streamId:e});return this.done=!0,this.receiver.onComplete(),!0},e.prototype.handleReject=function(e){this.done||(this.done=!0,this.receiver.onError(e))},e.prototype.cancel=function(){var e;this.done||(this.done=!0,(e=this.leaseManager)==null||e.cancelRequest(this))},e.prototype.handle=function(e){if(e.type==o.FrameTypes.ERROR){this.close(new i.RSocketError(e.code,e.message));return}this.close(new i.RSocketError(i.ErrorCodes.CANCELED,`Received invalid frame`))},e.prototype.close=function(e){if(this.done){console.warn(`Trying to close for the second time. ${e?`Dropping error [${e}].`:``}`);return}e?this.receiver.onError(e):this.receiver.onComplete()},e}(),q.RequestFnfResponderStream=function(){function e(e,t,n,r){if(this.streamId=e,this.stream=t,this.handler=n,this.streamType=o.FrameTypes.REQUEST_FNF,o.Flags.hasFollows(r.flags)){s.add(this,r.data,r.metadata),t.connect(this);return}var i={data:r.data,metadata:r.metadata};try{this.cancellable=n(i,this)}catch{}}return e.prototype.handle=function(e){var t;if(e.type==o.FrameTypes.PAYLOAD){if(o.Flags.hasFollows(e.flags)){if(s.add(this,e.data,e.metadata))return;t=`Unexpected fragment size`}else{this.stream.disconnect(this);var n=s.reassemble(this,e.data,e.metadata);try{this.cancellable=this.handler(n,this)}catch{}return}}else t=`Unexpected frame type [${e.type}]`;this.done=!0,e.type!=o.FrameTypes.CANCEL&&e.type!=o.FrameTypes.ERROR&&this.stream.send({type:o.FrameTypes.ERROR,streamId:this.streamId,flags:o.Flags.NONE,code:i.ErrorCodes.CANCELED,message:t}),this.stream.disconnect(this),s.cancel(this)},e.prototype.close=function(e){var t;if(this.done){console.warn(`Trying to close for the second time. ${e?`Dropping error [${e}].`:``}`);return}this.done=!0,s.cancel(this),(t=this.cancellable)==null||t.cancel()},e.prototype.onError=function(e){},e.prototype.onComplete=function(){},e}(),q}var J={},Tt;function Et(){if(Tt)return J;Tt=1;var e=J&&J.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),t=J&&J.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),n=J&&J.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(n!=null)for(var i in n)i!=="default"&&Object.prototype.hasOwnProperty.call(n,i)&&e(r,n,i);return t(r,n),r},r=J&&J.__values||function(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)};Object.defineProperty(J,"__esModule",{value:!0}),J.RequestResponseResponderStream=J.RequestResponseRequesterStream=void 0;var i=ut(),a=_t(),o=V(),s=n(bt());return J.RequestResponseRequesterStream=function(){function e(e,t,n,r){this.payload=e,this.receiver=t,this.fragmentSize=n,this.leaseManager=r,this.streamType=o.FrameTypes.REQUEST_RESPONSE}return e.prototype.handleReady=function(e,t){var n,i;if(this.done)return!1;if(this.streamId=e,this.stream=t,t.connect(this),(0,a.isFragmentable)(this.payload,this.fragmentSize,o.FrameTypes.REQUEST_RESPONSE))try{for(var s=r((0,a.fragment)(e,this.payload,this.fragmentSize,o.FrameTypes.REQUEST_RESPONSE)),c=s.next();!c.done;c=s.next()){var l=c.value;this.stream.send(l)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}else this.stream.send({type:o.FrameTypes.REQUEST_RESPONSE,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?o.Flags.METADATA:0,streamId:e});return this.hasExtension&&this.stream.send({type:o.FrameTypes.EXT,streamId:e,extendedContent:this.extendedContent,extendedType:this.extendedType,flags:this.flags}),!0},e.prototype.handleReject=function(e){this.done||(this.done=!0,this.receiver.onError(e))},e.prototype.handle=function(e){var t,n=e.type;switch(n){case o.FrameTypes.PAYLOAD:var r=o.Flags.hasComplete(e.flags),a=o.Flags.hasNext(e.flags);if(r||!o.Flags.hasFollows(e.flags)){if(this.done=!0,this.stream.disconnect(this),!a){this.receiver.onComplete();return}var c=this.hasFragments?s.reassemble(this,e.data,e.metadata):{data:e.data,metadata:e.metadata};this.receiver.onNext(c,!0);return}if(!s.add(this,e.data,e.metadata)){t=`Unexpected fragment size`;break}return;case o.FrameTypes.ERROR:this.done=!0,this.stream.disconnect(this),s.cancel(this),this.receiver.onError(new i.RSocketError(e.code,e.message));return;case o.FrameTypes.EXT:if(this.hasFragments){t=`Unexpected frame type [${n}] during reassembly`;break}this.receiver.onExtension(e.extendedType,e.extendedContent,o.Flags.hasIgnore(e.flags));return;default:t=`Unexpected frame type [${n}]`}this.close(new i.RSocketError(i.ErrorCodes.CANCELED,t)),this.stream.send({type:o.FrameTypes.CANCEL,streamId:this.streamId,flags:o.Flags.NONE}),this.stream.disconnect(this)},e.prototype.cancel=function(){var e;if(!this.done){if(this.done=!0,!this.streamId){(e=this.leaseManager)==null||e.cancelRequest(this);return}this.stream.send({type:o.FrameTypes.CANCEL,flags:o.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),s.cancel(this)}},e.prototype.onExtension=function(e,t,n){if(!this.done){if(!this.streamId){this.hasExtension=!0,this.extendedType=e,this.extendedContent=t,this.flags=n?o.Flags.IGNORE:o.Flags.NONE;return}this.stream.send({streamId:this.streamId,type:o.FrameTypes.EXT,extendedType:e,extendedContent:t,flags:n?o.Flags.IGNORE:o.Flags.NONE})}},e.prototype.close=function(e){this.done||(this.done=!0,s.cancel(this),e?this.receiver.onError(e):this.receiver.onComplete())},e}(),J.RequestResponseResponderStream=function(){function e(e,t,n,r,i){if(this.streamId=e,this.stream=t,this.fragmentSize=n,this.handler=r,this.streamType=o.FrameTypes.REQUEST_RESPONSE,t.connect(this),o.Flags.hasFollows(i.flags)){s.add(this,i.data,i.metadata);return}var a={data:i.data,metadata:i.metadata};try{this.receiver=r(a,this)}catch(e){this.onError(e)}}return e.prototype.handle=function(e){var t,n;if(!this.receiver||this.hasFragments){if(e.type===o.FrameTypes.PAYLOAD){if(o.Flags.hasFollows(e.flags)){if(s.add(this,e.data,e.metadata))return;n=`Unexpected fragment size`}else{var r=s.reassemble(this,e.data,e.metadata);try{this.receiver=this.handler(r,this)}catch(e){this.onError(e)}return}}else n=`Unexpected frame type [${e.type}] during reassembly`}else if(e.type===o.FrameTypes.EXT){this.receiver.onExtension(e.extendedType,e.extendedContent,o.Flags.hasIgnore(e.flags));return}else n=`Unexpected frame type [${e.type}]`;this.done=!0,(t=this.receiver)==null||t.cancel(),e.type!==o.FrameTypes.CANCEL&&e.type!==o.FrameTypes.ERROR&&this.stream.send({type:o.FrameTypes.ERROR,flags:o.Flags.NONE,code:i.ErrorCodes.CANCELED,message:n,streamId:this.streamId}),this.stream.disconnect(this),s.cancel(this)},e.prototype.onError=function(e){if(this.done){console.warn(`Trying to error for the second time. ${e?`Dropping error [${e}].`:``}`);return}this.done=!0,this.stream.send({type:o.FrameTypes.ERROR,flags:o.Flags.NONE,code:e instanceof i.RSocketError?e.code:i.ErrorCodes.APPLICATION_ERROR,message:e.message,streamId:this.streamId}),this.stream.disconnect(this)},e.prototype.onNext=function(e,t){var n,i;if(!this.done){if(this.done=!0,(0,a.isFragmentable)(e,this.fragmentSize,o.FrameTypes.PAYLOAD))try{for(var s=r((0,a.fragment)(this.streamId,e,this.fragmentSize,o.FrameTypes.PAYLOAD,!0)),c=s.next();!c.done;c=s.next()){var l=c.value;this.stream.send(l)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}else this.stream.send({type:o.FrameTypes.PAYLOAD,flags:o.Flags.NEXT|o.Flags.COMPLETE|(e.metadata?o.Flags.METADATA:0),data:e.data,metadata:e.metadata,streamId:this.streamId});this.stream.disconnect(this)}},e.prototype.onComplete=function(){this.done||(this.done=!0,this.stream.send({type:o.FrameTypes.PAYLOAD,flags:o.Flags.COMPLETE,streamId:this.streamId,data:null,metadata:null}),this.stream.disconnect(this))},e.prototype.onExtension=function(e,t,n){this.done||this.stream.send({type:o.FrameTypes.EXT,streamId:this.streamId,flags:n?o.Flags.IGNORE:o.Flags.NONE,extendedType:e,extendedContent:t})},e.prototype.close=function(e){var t;if(this.done){console.warn(`Trying to close for the second time. ${e?`Dropping error [${e}].`:``}`);return}s.cancel(this),(t=this.receiver)==null||t.cancel()},e}(),J}var Y={},Dt;function Ot(){if(Dt)return Y;Dt=1;var e=Y&&Y.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),t=Y&&Y.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),n=Y&&Y.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(n!=null)for(var i in n)i!=="default"&&Object.prototype.hasOwnProperty.call(n,i)&&e(r,n,i);return t(r,n),r},r=Y&&Y.__values||function(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
3if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)};Object.defineProperty(Y,"__esModule",{value:!0}),Y.RequestStreamResponderStream=Y.RequestStreamRequesterStream=void 0;var i=ut(),a=_t(),o=V(),s=n(bt());return Y.RequestStreamRequesterStream=function(){function e(e,t,n,r,i){this.payload=e,this.receiver=t,this.fragmentSize=n,this.initialRequestN=r,this.leaseManager=i,this.streamType=o.FrameTypes.REQUEST_STREAM}return e.prototype.handleReady=function(e,t){var n,i;if(this.done)return!1;if(this.streamId=e,this.stream=t,t.connect(this),(0,a.isFragmentable)(this.payload,this.fragmentSize,o.FrameTypes.REQUEST_STREAM))try{for(var s=r((0,a.fragmentWithRequestN)(e,this.payload,this.fragmentSize,o.FrameTypes.REQUEST_STREAM,this.initialRequestN)),c=s.next();!c.done;c=s.next()){var l=c.value;this.stream.send(l)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}else this.stream.send({type:o.FrameTypes.REQUEST_STREAM,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:this.payload.metadata===void 0?0:o.Flags.METADATA,streamId:e});return this.hasExtension&&this.stream.send({type:o.FrameTypes.EXT,streamId:e,extendedContent:this.extendedContent,extendedType:this.extendedType,flags:this.flags}),!0},e.prototype.handleReject=function(e){this.done||(this.done=!0,this.receiver.onError(e))},e.prototype.handle=function(e){var t,n=e.type;switch(n){case o.FrameTypes.PAYLOAD:var r=o.Flags.hasComplete(e.flags),a=o.Flags.hasNext(e.flags);if(r||!o.Flags.hasFollows(e.flags)){if(r&&(this.done=!0,this.stream.disconnect(this),!a)){this.receiver.onComplete();return}var c=this.hasFragments?s.reassemble(this,e.data,e.metadata):{data:e.data,metadata:e.metadata};this.receiver.onNext(c,r);return}if(!s.add(this,e.data,e.metadata)){t=`Unexpected fragment size`;break}return;case o.FrameTypes.ERROR:this.done=!0,this.stream.disconnect(this),s.cancel(this),this.receiver.onError(new i.RSocketError(e.code,e.message));return;case o.FrameTypes.EXT:if(this.hasFragments){t=`Unexpected frame type [${n}] during reassembly`;break}this.receiver.onExtension(e.extendedType,e.extendedContent,o.Flags.hasIgnore(e.flags));return;default:t=`Unexpected frame type [${n}]`}this.close(new i.RSocketError(i.ErrorCodes.CANCELED,t)),this.stream.send({type:o.FrameTypes.CANCEL,streamId:this.streamId,flags:o.Flags.NONE}),this.stream.disconnect(this)},e.prototype.request=function(e){if(!this.done){if(!this.streamId){this.initialRequestN+=e;return}this.stream.send({type:o.FrameTypes.REQUEST_N,flags:o.Flags.NONE,requestN:e,streamId:this.streamId})}},e.prototype.cancel=function(){var e;if(!this.done){if(this.done=!0,!this.streamId){(e=this.leaseManager)==null||e.cancelRequest(this);return}this.stream.send({type:o.FrameTypes.CANCEL,flags:o.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),s.cancel(this)}},e.prototype.onExtension=function(e,t,n){if(!this.done){if(!this.streamId){this.hasExtension=!0,this.extendedType=e,this.extendedContent=t,this.flags=n?o.Flags.IGNORE:o.Flags.NONE;return}this.stream.send({streamId:this.streamId,type:o.FrameTypes.EXT,extendedType:e,extendedContent:t,flags:n?o.Flags.IGNORE:o.Flags.NONE})}},e.prototype.close=function(e){this.done||(this.done=!0,s.cancel(this),e?this.receiver.onError(e):this.receiver.onComplete())},e}(),Y.RequestStreamResponderStream=function(){function e(e,t,n,r,i){if(this.streamId=e,this.stream=t,this.fragmentSize=n,this.handler=r,this.streamType=o.FrameTypes.REQUEST_STREAM,t.connect(this),o.Flags.hasFollows(i.flags)){this.initialRequestN=i.requestN,s.add(this,i.data,i.metadata);return}var a={data:i.data,metadata:i.metadata};try{this.receiver=r(a,i.requestN,this)}catch(e){this.onError(e)}}return e.prototype.handle=function(e){var t,n;if(!this.receiver||this.hasFragments){if(e.type===o.FrameTypes.PAYLOAD){if(o.Flags.hasFollows(e.flags)){if(s.add(this,e.data,e.metadata))return;n=`Unexpected frame size`}else{var r=s.reassemble(this,e.data,e.metadata);try{this.receiver=this.handler(r,this.initialRequestN,this)}catch(e){this.onError(e)}return}}else n=`Unexpected frame type [${e.type}] during reassembly`}else if(e.type===o.FrameTypes.REQUEST_N){this.receiver.request(e.requestN);return}else if(e.type===o.FrameTypes.EXT){this.receiver.onExtension(e.extendedType,e.extendedContent,o.Flags.hasIgnore(e.flags));return}else n=`Unexpected frame type [${e.type}]`;this.done=!0,s.cancel(this),(t=this.receiver)==null||t.cancel(),e.type!==o.FrameTypes.CANCEL&&e.type!==o.FrameTypes.ERROR&&this.stream.send({type:o.FrameTypes.ERROR,flags:o.Flags.NONE,code:i.ErrorCodes.CANCELED,message:n,streamId:this.streamId}),this.stream.disconnect(this)},e.prototype.onError=function(e){if(this.done){console.warn(`Trying to error for the second time. ${e?`Dropping error [${e}].`:``}`);return}this.done=!0,this.stream.send({type:o.FrameTypes.ERROR,flags:o.Flags.NONE,code:e instanceof i.RSocketError?e.code:i.ErrorCodes.APPLICATION_ERROR,message:e.message,streamId:this.streamId}),this.stream.disconnect(this)},e.prototype.onNext=function(e,t){var n,i;if(!this.done){if(t&&(this.done=!0),(0,a.isFragmentable)(e,this.fragmentSize,o.FrameTypes.PAYLOAD))try{for(var s=r((0,a.fragment)(this.streamId,e,this.fragmentSize,o.FrameTypes.PAYLOAD,t)),c=s.next();!c.done;c=s.next()){var l=c.value;this.stream.send(l)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}else this.stream.send({type:o.FrameTypes.PAYLOAD,flags:o.Flags.NEXT|(t?o.Flags.COMPLETE:o.Flags.NONE)|(e.metadata?o.Flags.METADATA:o.Flags.NONE),data:e.data,metadata:e.metadata,streamId:this.streamId});t&&this.stream.disconnect(this)}},e.prototype.onComplete=function(){this.done||(this.done=!0,this.stream.send({type:o.FrameTypes.PAYLOAD,flags:o.Flags.COMPLETE,streamId:this.streamId,data:null,metadata:null}),this.stream.disconnect(this))},e.prototype.onExtension=function(e,t,n){this.done||this.stream.send({type:o.FrameTypes.EXT,streamId:this.streamId,flags:n?o.Flags.IGNORE:o.Flags.NONE,extendedType:e,extendedContent:t})},e.prototype.close=function(e){var t;if(this.done){console.warn(`Trying to close for the second time. ${e?`Dropping error [${e}].`:``}`);return}s.cancel(this),(t=this.receiver)==null||t.cancel()},e}(),Y}var kt;
3function At(){if(kt)return W;kt=1,Object.defineProperty(W,"__esModule",{value:!0}),W.KeepAliveSender=W.KeepAliveHandler=W.DefaultConnectionFrameHandler=W.DefaultStreamRequestHandler=W.LeaseHandler=W.RSocketRequester=void 0;var e=ut(),t=V(),n=St(),r=wt(),i=Et(),a=Ot();W.RSocketRequester=function(){function e(e,t,n){this.connection=e,this.fragmentSize=t,this.leaseManager=n}return e.prototype.fireAndForget=function(e,t){var n=new r.RequestFnFRequesterStream(e,t,this.fragmentSize,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(n):this.connection.multiplexerDemultiplexer.createRequestStream(n),n},e.prototype.requestResponse=function(e,t){var n=new i.RequestResponseRequesterStream(e,t,this.fragmentSize,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(n):this.connection.multiplexerDemultiplexer.createRequestStream(n),n},e.prototype.requestStream=function(e,t,n){var r=new a.RequestStreamRequesterStream(e,n,this.fragmentSize,t,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(r):this.connection.multiplexerDemultiplexer.createRequestStream(r),r},e.prototype.requestChannel=function(e,t,r,i){var a=new n.RequestChannelRequesterStream(e,r,i,this.fragmentSize,t,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(a):this.connection.multiplexerDemultiplexer.createRequestStream(a),a},e.prototype.metadataPush=function(e,t){throw Error(`Method not implemented.`)},e.prototype.close=function(e){this.connection.close(e)},e.prototype.onClose=function(e){this.connection.onClose(e)},e}(),W.LeaseHandler=function(){function t(e,t){this.maxPendingRequests=e,this.multiplexer=t,this.pendingRequests=[],this.expirationTime=0,this.availableLease=0}return t.prototype.handle=function(e){for(this.expirationTime=e.ttl+Date.now(),this.availableLease=e.requestCount;this.availableLease>0&&this.pendingRequests.length>0;){var t=this.pendingRequests.shift();this.availableLease--,this.multiplexer.createRequestStream(t)}},t.prototype.requestLease=function(t){var n=this.availableLease;if(n>0&&Date.now()<this.expirationTime){this.availableLease=n-1,this.multiplexer.createRequestStream(t);return}if(this.pendingRequests.length>=this.maxPendingRequests){t.handleReject(new e.RSocketError(e.ErrorCodes.REJECTED,`No available lease given`));return}this.pendingRequests.push(t)},t.prototype.cancelRequest=function(e){var t=this.pendingRequests.indexOf(e);t>-1&&this.pendingRequests.splice(t,1)},t}(),W.DefaultStreamRequestHandler=function(){function o(e,t){this.rsocket=e,this.fragmentSize=t}return o.prototype.handle=function(e,o){switch(e.type){case t.FrameTypes.REQUEST_FNF:this.rsocket.fireAndForget&&new r.RequestFnfResponderStream(e.streamId,o,this.rsocket.fireAndForget.bind(this.rsocket),e);return;case t.FrameTypes.REQUEST_RESPONSE:if(this.rsocket.requestResponse){new i.RequestResponseResponderStream(e.streamId,o,this.fragmentSize,this.rsocket.requestResponse.bind(this.rsocket),e);return}this.rejectRequest(e.streamId,o);return;case t.FrameTypes.REQUEST_STREAM:if(this.rsocket.requestStream){new a.RequestStreamResponderStream(e.streamId,o,this.fragmentSize,this.rsocket.requestStream.bind(this.rsocket),e);return}this.rejectRequest(e.streamId,o);return;case t.FrameTypes.REQUEST_CHANNEL:if(this.rsocket.requestChannel){new n.RequestChannelResponderStream(e.streamId,o,this.fragmentSize,this.rsocket.requestChannel.bind(this.rsocket),e);return}this.rejectRequest(e.streamId,o);return}},o.prototype.rejectRequest=function(n,r){r.send({type:t.FrameTypes.ERROR,streamId:n,flags:t.Flags.NONE,code:e.ErrorCodes.REJECTED,message:`No available handler found`})},o.prototype.close=function(){},o}(),W.DefaultConnectionFrameHandler=function(){function n(e,t,n,r,i){this.connection=e,this.keepAliveHandler=t,this.keepAliveSender=n,this.leaseHandler=r,this.rsocket=i}return n.prototype.handle=function(n){switch(n.type){case t.FrameTypes.KEEPALIVE:this.keepAliveHandler.handle(n);return;case t.FrameTypes.LEASE:if(this.leaseHandler){this.leaseHandler.handle(n);return}return;case t.FrameTypes.ERROR:this.connection.close(new e.RSocketError(n.code,n.message));return;case t.FrameTypes.METADATA_PUSH:this.rsocket.metadataPush;return;default:this.connection.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,message:`Received unknown frame type`,code:e.ErrorCodes.CONNECTION_ERROR})}},n.prototype.pause=function(){var e;this.keepAliveHandler.pause(),(e=this.keepAliveSender)==null||e.pause()},n.prototype.resume=function(){var e;this.keepAliveHandler.start(),(e=this.keepAliveSender)==null||e.start()},n.prototype.close=function(e){var t;this.keepAliveHandler.close(),(t=this.rsocket.close)==null||t.call(this.rsocket,e)},n}();var o;(function(e){e[e.Paused=0]=`Paused`,e[e.Running=1]=`Running`,e[e.Closed=2]=`Closed`})(o||={}),W.KeepAliveHandler=function(){function e(e,t){this.connection=e,this.keepAliveTimeoutDuration=t,this.state=o.Paused,this.outbound=e.multiplexerDemultiplexer.connectionOutbound}return e.prototype.handle=function(e){this.keepAliveLastReceivedMillis=Date.now(),t.Flags.hasRespond(e.flags)&&this.outbound.send({type:t.FrameTypes.KEEPALIVE,streamId:0,data:e.data,flags:e.flags^t.Flags.RESPOND,lastReceivedPosition:0})},e.prototype.start=function(){this.state===o.Paused&&(this.keepAliveLastReceivedMillis=Date.now(),this.state=o.Running,this.activeTimeout=setTimeout(this.timeoutCheck.bind(this),this.keepAliveTimeoutDuration))},e.prototype.pause=function(){this.state===o.Running&&(this.state=o.Paused,clearTimeout(this.activeTimeout))},e.prototype.close=function(){this.state=o.Closed,clearTimeout(this.activeTimeout)},e.prototype.timeoutCheck=function(){var e=Date.now()-this.keepAliveLastReceivedMillis;e>=this.keepAliveTimeoutDuration?this.connection.close(Error(`No keep-alive acks for ${this.keepAliveTimeoutDuration} millis`)):this.activeTimeout=setTimeout(this.timeoutCheck.bind(this),Math.max(100,this.keepAliveTimeoutDuration-e))},e}();var s;return(function(e){e[e.Paused=0]=`Paused`,e[e.Running=1]=`Running`,e[e.Closed=2]=`Closed`})(s||={}),W.KeepAliveSender=function(){function e(e,t){this.outbound=e,this.keepAlivePeriodDuration=t,this.state=s.Paused}return e.prototype.sendKeepAlive=function(){this.outbound.send({type:t.FrameTypes.KEEPALIVE,streamId:0,data:void 0,flags:t.Flags.RESPOND,lastReceivedPosition:0})},e.prototype.start=function(){this.state===s.Paused&&(this.state=s.Running,this.activeInterval=setInterval(this.sendKeepAlive.bind(this),this.keepAlivePeriodDuration))},e.prototype.pause=function(){this.state===s.Running&&(this.state=s.Paused,clearInterval(this.activeInterval))},e.prototype.close=function(){this.state=s.Closed,clearInterval(this.activeInterval)},e}(),W}var jt={},Mt;function Nt(){if(Mt)return jt;Mt=1;var e=jt&&jt.__values||function(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
3if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)};Object.defineProperty(jt,"__esModule",{value:!0}),jt.FrameStore=void 0;var t=Ut(),n=tt();return jt.FrameStore=function(){function r(){this.storedFrames=[],this._lastReceivedFramePosition=0,this._firstAvailableFramePosition=0,this._lastSentFramePosition=0}return Object.defineProperty(r.prototype,"lastReceivedFramePosition",{get:function(){return this._lastReceivedFramePosition},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"firstAvailableFramePosition",{get:function(){return this._firstAvailableFramePosition},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"lastSentFramePosition",{get:function(){return this._lastSentFramePosition},enumerable:!1,configurable:!0}),r.prototype.store=function(e){this._lastSentFramePosition+=(0,n.sizeOfFrame)(e),this.storedFrames.push(e)},r.prototype.record=function(e){this._lastReceivedFramePosition+=(0,n.sizeOfFrame)(e)},r.prototype.dropTo=function(e){for(var r=e-this._firstAvailableFramePosition;r>0&&this.storedFrames.length>0;){var i=this.storedFrames.shift();r-=(0,n.sizeOfFrame)(i)}if(r!==0)throw new t.RSocketError(t.ErrorCodes.CONNECTION_ERROR,`State inconsistency. Expected bytes to drop ${e-this._firstAvailableFramePosition} but actual ${r}`);this._firstAvailableFramePosition=e},r.prototype.drain=function(t){var n,r;try{for(var i=e(this.storedFrames),a=i.next();!a.done;a=i.next()){var o=a.value;t(o)}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}},r}(),jt}var Pt;function Ft(){if(Pt)return H;Pt=1;var e=H&&H.__awaiter||function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},t=H&&H.__generator||function(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(o){if(r)throw TypeError(`Generator is already executing.`);for(;n;)try{if(r=1,i&&(a=o[0]&2?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[o[0]&2,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>
30&&a[a.length-1])&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};Object.defineProperty(H,"__esModule",{value:!0}),H.RSocketConnector=void 0;var n=ht(),r=V(),i=At(),a=Nt();return H.RSocketConnector=function(){function o(e){this.config=e}return o.prototype.connect=function(){return e(this,void 0,void 0,function(){var o,s,c,l,u,d,f,p,m,h=this;return t(this,function(g){switch(g.label){case 0:return o=this.config,s={type:r.FrameTypes.SETUP,dataMimeType:o.setup?.dataMimeType??`application/octet-stream`,metadataMimeType:o.setup?.metadataMimeType??`application/octet-stream`,keepAlive:o.setup?.keepAlive??6e4,lifetime:o.setup?.lifetime??3e5,metadata:o.setup?.payload?.metadata,data:o.setup?.payload?.data,resumeToken:o.resume?.tokenGenerator()??null,streamId:0,majorVersion:1,minorVersion:0,flags:(o.setup?.payload?.metadata?r.Flags.METADATA:r.Flags.NONE)|(o.lease?r.Flags.LEASE:r.Flags.NONE)|(o.resume?r.Flags.RESUME_ENABLE:r.Flags.NONE)},[4,o.transport.connect(function(i){return o.resume?new n.ResumableClientServerInputMultiplexerDemultiplexer(n.StreamIdGenerator.create(-1),i,i,new a.FrameStore,s.resumeToken.toString(),function(i,a){return e(h,void 0,void 0,function(){var e,c,l;return t(this,function(t){switch(t.label){case 0:return e=function(e){return e.send({type:r.FrameTypes.RESUME,streamId:0,flags:r.Flags.NONE,clientPosition:a.firstAvailableFramePosition,serverPosition:a.lastReceivedFramePosition,majorVersion:s.minorVersion,minorVersion:s.majorVersion,resumeToken:s.resumeToken}),new n.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(e,e,i)},c=-1,l=function(){return c++,o.resume.reconnectFunction(c).then(function(){return o.transport.connect(e).catch(l)})},[4,l()];case 1:return t.sent(),[2]}})})}):new n.ClientServerInputMultiplexerDemultiplexer(n.StreamIdGenerator.create(-1),i,i)})];case 1:return c=g.sent(),l=new i.KeepAliveSender(c.multiplexerDemultiplexer.connectionOutbound,s.keepAlive),u=new i.KeepAliveHandler(c,s.lifetime),d=o.lease?new i.LeaseHandler(o.lease.maxPendingRequests??256,c.multiplexerDemultiplexer):void 0,f=o.responder??{},p=new i.DefaultConnectionFrameHandler(c,u,l,d,f),m=new i.DefaultStreamRequestHandler(f,0),c.onClose(function(e){l.close(),u.close(),p.close(e)}),c.multiplexerDemultiplexer.connectionInbound(p),c.multiplexerDemultiplexer.handleRequestStream(m),c.multiplexerDemultiplexer.connectionOutbound.send(s),u.start(),l.start(),[2,new i.RSocketRequester(c,o.fragmentation?.maxOutboundFragmentSize??0,d)]}})})},o}(),H}var It={},Lt;function Rt(){if(Lt)return It;Lt=1;var e=It&&It.__awaiter||function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},t=It&&It.__generator||function(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(o){if(r)throw TypeError(`Generator is already executing.`);for(;n;)try{if(r=1,i&&(a=o[0]&2?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[o[0]&2,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>
30&&a[a.length-1])&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};Object.defineProperty(It,"__esModule",{value:!0}),It.RSocketServer=void 0;var n=ht(),r=ut(),i=V(),a=At(),o=Nt();return It.RSocketServer=function(){function s(e){this.acceptor=e.acceptor,this.transport=e.transport,this.lease=e.lease,this.serverSideKeepAlive=e.serverSideKeepAlive,this.sessionStore=e.resume?{}:void 0,this.sessionTimeout=e.resume?.sessionTimeout??void 0}return s.prototype.bind=function(){return e(this,void 0,void 0,function(){var s=this;return t(this,function(c){switch(c.label){case 0:return[4,this.transport.bind(function(n,o){return e(s,void 0,void 0,function(){var e,s,s,c,l,u,d,f,p,m,h;return t(this,function(t){switch(t.label){case 0:switch(e=n.type,e){case i.FrameTypes.SETUP:return[3,1];case i.FrameTypes.RESUME:return[3,5]}return[3,6];case 1:return t.trys.push([1,3,,4]),this.lease&&!i.Flags.hasLease(n.flags)?(s=new r.RSocketError(r.ErrorCodes.REJECTED_SETUP,`Lease has to be enabled`),o.multiplexerDemultiplexer.connectionOutbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:s.code,message:s.message}),o.close(s),[2]):i.Flags.hasLease(n.flags)&&!this.lease?(s=new r.RSocketError(r.ErrorCodes.REJECTED_SETUP,`Lease has to be disabled`),o.multiplexerDemultiplexer.connectionOutbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:s.code,message:s.message}),o.close(s),[2]):(c=i.Flags.hasLease(n.flags)?new a.LeaseHandler(this.lease.maxPendingRequests??256,o.multiplexerDemultiplexer):void 0,l=new a.RSocketRequester(o,this.fragmentation?.maxOutboundFragmentSize??0,c),[4,this.acceptor.accept({data:n.data,dataMimeType:n.dataMimeType,metadata:n.metadata,metadataMimeType:n.metadataMimeType,flags:n.flags,keepAliveMaxLifetime:n.lifetime,keepAliveInterval:n.keepAlive,resumeToken:n.resumeToken},l)]);case 2:return u=t.sent(),d=new a.KeepAliveHandler(o,n.lifetime),f=this.serverSideKeepAlive?new a.KeepAliveSender(o.multiplexerDemultiplexer.connectionOutbound,n.keepAlive):void 0,p=new a.DefaultConnectionFrameHandler(o,d,f,c,u),m=new a.DefaultStreamRequestHandler(u,0),o.onClose(function(e){f?.close(),d.close(),p.close(e)}),o.multiplexerDemultiplexer.connectionInbound(p),o.multiplexerDemultiplexer.handleRequestStream(m),d.start(),f?.start(),[3,4];case 3:return h=t.sent(),o.multiplexerDemultiplexer.connectionOutbound.send({type:i.FrameTypes.ERROR,streamId:0,code:r.ErrorCodes.REJECTED_SETUP,message:h.message??``,flags:i.Flags.NONE}),o.close(h instanceof r.RSocketError?h:new r.RSocketError(r.ErrorCodes.REJECTED_SETUP,h.message)),[3,4];case 4:return[2];case 5:return[2];case 6:o.multiplexerDemultiplexer.connectionOutbound.send({type:i.FrameTypes.ERROR,streamId:0,code:r.ErrorCodes.UNSUPPORTED_SETUP,message:`Unsupported setup`,flags:i.Flags.NONE}),o.close(new r.RSocketError(r.ErrorCodes.UNSUPPORTED_SETUP)),t.label=7;case 7:return[2]}})})},function(e,t){if(e.type===i.FrameTypes.RESUME){if(s.sessionStore){var a=s.sessionStore[e.resumeToken.toString()];if(!a){t.send({type:i.FrameTypes.ERROR,streamId:0,code:r.ErrorCodes.REJECTED_RESUME,message:`No session found for the given resume token`,flags:i.Flags.NONE}),t.close();return}return a.resume(e,t,t),a}t.send({type:i.FrameTypes.ERROR,streamId:0,code:r.ErrorCodes.REJECTED_RESUME,message:`Resume is not enabled`,flags:i.Flags.NONE}),t.close();return}if(e.type===i.FrameTypes.SETUP&&i.Flags.hasResume(e.flags)){if(!s.sessionStore){var c=new r.RSocketError(r.ErrorCodes.REJECTED_SETUP,`No resume support`);t.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:c.code,message:c.message}),t.close(c);return}var l=new n.ResumableClientServerInputMultiplexerDemultiplexer(n.StreamIdGenerator.create(0),t,t,new o.FrameStore,e.resumeToken.toString(),s.sessionStore,s.sessionTimeout);return s.sessionStore[e.resumeToken.toString()]=l,l}return new n.ClientServerInputMultiplexerDemultiplexer(n.StreamIdGenerator.create(0),t,t)})];case 1:return[2,c.sent()]}})})},s}(),It}var zt={},Bt;function Vt(){return Bt?zt:(Bt=1,Object.defineProperty(zt,"__esMo
3dule",{value:!0}),zt)}var Ht;function Ut(){return Ht?Xe:(Ht=1,(function(e){var t=Xe&&Xe.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=Xe&&Xe.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),n(tt(),e),n(it(),e),n(st(),e),n(ut(),e),n(V(),e),n(pt(),e),n(Ft(),e),n(Rt(),e),n(Vt(),e)})(Xe),Xe)}var Wt=Ut(),Gt={version:`1.57.3`},Kt={},qt;function Jt(){if(qt)return Kt;qt=1;var e=Kt&&Kt.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if(typeof n!=`function`&&n!==null)throw TypeError(`Class extends value `+String(n)+` is not a constructor or null`);e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(Kt,"__esModule",{value:!0}),Kt.WebsocketDuplexConnection=void 0;var t=Ut();return Kt.WebsocketDuplexConnection=function(n){e(r,n);function r(e,t,r){var i=n.call(this)||this;return i.websocket=e,i.deserializer=t,i.handleClosed=function(e){i.close(Error(e.reason||`WebsocketDuplexConnection: Socket closed unexpectedly.`))},i.handleError=function(e){i.close(e.error)},i.handleMessage=function(e){try{var t=B.Buffer.from(e.data),n=i.deserializer.deserializeFrame(t);i.multiplexerDemultiplexer.handle(n)}catch(e){i.close(e)}},e.addEventListener(`close`,i.handleClosed),e.addEventListener(`error`,i.handleError),e.addEventListener(`message`,i.handleMessage),i.multiplexerDemultiplexer=r(i),i}return Object.defineProperty(r.prototype,"availability",{get:function(){return+!this.done},enumerable:!1,configurable:!0}),r.prototype.close=function(e){if(this.done){n.prototype.close.call(this,e);return}this.websocket.removeEventListener(`close`,this.handleClosed),this.websocket.removeEventListener(`error`,this.handleError),this.websocket.removeEventListener(`message`,this.handleMessage),this.websocket.close(),delete this.websocket,n.prototype.close.call(this,e)},r.prototype.send=function(e){if(!this.done){var n=(0,t.serializeFrame)(e);this.websocket.send(n)}},r}(t.Deferred),Kt}var Yt=Jt(),Xt=class{url;factory;constructor(e){this.url=e.url,this.factory=e.wsCreator??(e=>new WebSocket(e))}connect(e){return new Promise((t,n)=>{let r=this.factory(this.url);r.binaryType=`arraybuffer`;let i,a=()=>{i(),t(new Yt.WebsocketDuplexConnection(r,new Wt.Deserializer,e))},o=e=>{let t=e;i(),t.error==null?t.message==null?n(Error(`Failed to create websocket connection to ${this.url}`)):n(Error(`Failed to create websocket connection: ${t.message}`)):n(t.error)},s=()=>{i(),n(Error(`WebSocket connection closed while opening`))};i=()=>{r.removeEventListener(`open`,a),r.removeEventListener(`error`,o),r.removeEventListener(`close`,s)},r.addEventListener(`open`,a),r.addEventListener(`error`,o),r.addEventListener(`close`,s)})}},Zt=/\/+$/,Qt=Gt.version,$t=10,en=5,tn=2e4,nn=3e4,rn=9e4,an=w.get(`PowerSyncRemote`),on;(function(e){e.Buffered=`buffered`,e.Sequential=`sequential`})(on||={});var sn=class{getFetch(){throw Error(`Unspecified fetch implementation`)}},cn={socketUrlTransformer:e=>e.replace(/^https?:\/\//,function(e){return e===`https://`?`wss://`:`ws://`}),fetchImplementation:new sn,fetchOptions:{}},ln=class{connector;logger;credentials=null;options;constructor(e,t=an,n){this.connector=e,this.logger=t,this.options={...cn,...n??{}}}get fetch(){let{fetchImplementation:e}=this.options;return e instanceof sn?e.getFetch():e}async getCredentials(){return this.credentials?this.credentials:this.prefetchCredentials()}async prefetchCredentials(){return this.credentials=await this.fetchCredentials(),this.credentials}async fetchCredentials(){let e=await this.connector.fetchCredentials();if(e?.endpoint.match(Zt))throw Error(`A trailing forward slash "/" was found in the fetchCredentials endpoint: "${e.endpoint}". Remove the trailing forward slash "/" to fix this error.`);return e}invalidateCredentials(){this.credentials=null,this.connector.invali
3dateCredentials?.()}getUserAgent(){return`powersync-js/${Qt}`}async buildRequest(e){let t=await this.getCredentials();if(t!=null&&(t.endpoint==null||t.endpoint==``))throw Error(`PowerSync endpoint not configured`);if(t?.token==null||t?.token==``){let e=Error(`Not signed in`);throw e.status=401,e}let n=this.getUserAgent();return{url:t.endpoint+e,headers:{"content-type":`application/json`,Authorization:`Token ${t.token}`,"x-user-agent":n}}}async post(e,t,n={}){let r=await this.buildRequest(e),i=await this.fetch(r.url,{method:`POST`,headers:{...n,...r.headers},body:JSON.stringify(t)});if(i.status===401&&this.invalidateCredentials(),!i.ok)throw Error(`Received ${i.status} - ${i.statusText} when posting to ${e}: ${await i.text()}}`);return i.json()}async get(e,t){let n=await this.buildRequest(e),r=await this.fetch(n.url,{method:`GET`,headers:{...t,...n.headers}});if(r.status===401&&this.invalidateCredentials(),!r.ok)throw Error(`Received ${r.status} - ${r.statusText} when getting from ${e}: ${await r.text()}}`);return r.json()}createTextDecoder(){return new TextDecoder}createSocket(e){return new WebSocket(e)}async socketStreamRaw(e){let{path:t,fetchStrategy:n=on.Buffered}=e,r=`application/json`;function i(e){return B.Buffer.from(JSON.stringify(e))}let a=n==on.Buffered?10:1,o=await this.buildRequest(t),s=this.options.socketUrlTransformer(o.url),c=this.getUserAgent(),l=null,u,d=null,f=!1,p=new N({eventDelivered:()=>{p.countOutstandingEvents<=en&&(f=!1,b())}}),m=!1,h=!1,g=a,_=null,v=()=>{m||(m=!0,clearTimeout(u),l&&l.close(),d&&d.close(),p.notify(null))};function y(e){p.notify(e),p.countOutstandingEvents>=$t&&(f=!0)}function b(){let e=a-g;!f&&e>0&&(_?.request(e),g=a)}if(e.abortSignal.aborted)throw new z(`Connection request aborted`);e.abortSignal.addEventListener(`abort`,v);let x=()=>{clearTimeout(u),u=setTimeout(()=>{this.logger.error(`No data received on WebSocket in ${nn}ms, closing connection.`),v()},nn)};x();let ee=new Wt.RSocketConnector({transport:new Xt({url:s,wsCreator:e=>{let t=l=this.createSocket(e);return t.addEventListener(`message`,()=>{x()}),t}}),setup:{keepAlive:tn,lifetime:rn,dataMimeType:r,metadataMimeType:r,payload:{data:null,metadata:i({token:o.headers.Authorization,user_agent:c})}}});try{d=await ee.connect(),l=null}catch(e){throw this.logger.error(`Failed to connect WebSocket`,e),v(),e}return x(),d.onClose(()=>d=null),await new Promise((n,r)=>{let o={next:async()=>{if(m)return A;let t=await p.waitForEvent(e.abortSignal);return m?A:j(t)}};_=d.requestStream({data:i(e.data),metadata:i({path:t})},a,{onError:e=>{e.message.includes(`PSYNC_`)?e.message.includes(`PSYNC_S21`)&&this.invalidateCredentials():e.message!==`Closed. `&&this.invalidateCredentials(),e.message!==`Closed. `&&this.logger.error(e),v(),h||r(e)},onNext:e=>{h||(h=!0,n(o));let{data:t}=e;t&&y(t),g--,b()},onComplete:()=>{v()},onExtension:()=>{}})})}get supportsStreamingBinaryResponses(){return!0}async fetchStreamRaw(e){let{data:t,path:n,headers:r,abortSignal:i}=e,a=await this.buildRequest(n);if(i.aborted)throw new z(`Abort request received before making fetchStreamRaw request`);let o=new AbortController,s=null;i.addEventListener(`abort`,()=>{let e=i.reason??new z(`Cancelling network request before it resolves. Abort signal has been received.`);s==null?o.abort(e):s.cancel(e).catch(()=>{})});let c,l=!1;try{let i=`application/x-ndjson`,s=`application/vnd.powersync.bson-stream`;if(c=await this.fetch(a.url,{method:`POST`,headers:{...r,...a.headers,accept:this.supportsStreamingBinaryResponses?`${s};q=0.9,${i};q=0.8`:i},body:JSON.stringify(t),signal:o.signal,cache:`no-store`,...this.options.fetchOptions??{},...e.fetchOptions}),!c.ok||!c.body){let e=await c.text();this.logger.error(`Could not POST streaming to ${n} - ${c.status} - ${c.statusText}: ${e}`),c.status===401&&this.invalidateCredentials();let t=Error(`HTTP ${c.statusText}: ${e}`);throw t.status=c.status,t}l=c.headers.get(`content-type`)==s}catch(e){throw e.name==`AbortError`?new z(`Pending fetch request to ${a.url} has been aborted.`):e}return s=c.body.getReader(),{isBson:l,stream:{next:async()=>{if(o.signal.aborted)return A;try{return await s.read()}catch(e){if(o.signal.aborted)return A;throw e}}}}}
3async fetchStream(e){let{isBson:t,stream:n}=await this.fetchStreamRaw(e);return t?we(n):Ce(n,this.createTextDecoder())}};function un(e){return{priority:e.priority,hasSynced:e.has_synced??void 0,lastSyncedAt:e.last_synced_at==null?void 0:new Date(e.last_synced_at*1e3)}}function dn(e){let t=e.priority_status.find(e=>e.priority==D),n=t==null?null:un(t);return{connected:e.connected,connecting:e.connecting,dataFlow:{downloading:e.downloading!=null,downloadProgress:e.downloading?.buckets,internalStreamSubscriptions:e.streams},lastSyncedAt:n?.lastSyncedAt,hasSynced:n?.hasSynced,priorityStatusEntries:e.priority_status.map(un)}}function fn(e){return`EstablishSyncStream`in e||`CloseSyncStream`in e}var pn;(function(e){e.CRUD=`crud`,e.SYNC=`sync`})(pn||={});var mn;(function(e){e.HTTP=`http`,e.WEB_SOCKET=`web-socket`})(mn||={});var hn;(function(e){e.RUST=`rust`})(hn||={});var gn=hn.RUST,_n=1e3,vn={appMetadata:{},connectionMethod:mn.WEB_SOCKET,clientImplementation:gn,fetchStrategy:on.Buffered,params:{},serializedSchema:void 0,includeDefaultStreams:!0},yn=class extends k{options;abortController;crudUpdateListener;streamingSyncPromise;logger;activeStreams;connectionMayHaveChanged=!1;crudUploadNotifier=M();notifyCompletedUploads;handleActiveStreamsChange;syncStatus;constructor(e){super(),this.options=e,this.activeStreams=e.subscriptions,this.logger=e.logger??w.get(`PowerSyncStream`),this.syncStatus=new O({connected:!1,connecting:!1,lastSyncedAt:void 0,dataFlow:{uploading:!1,downloading:!1}}),this.abortController=null}triggerCrudUpload(){this.crudUploadNotifier.notify()}async waitForReady(){}waitForStatus(e){return this.waitUntilStatusMatches(t=>{let n=(e,t)=>Object.entries(e).every(([e,r])=>{let i=t[e];return typeof r==`object`&&typeof i==`object`?n(r,i):r==i});return n(e,t)})}waitUntilStatusMatches(e){return new Promise(t=>{if(e(this.syncStatus)){t();return}let n=this.registerListener({statusChanged:r=>{e(r)&&(t(),n?.())}})})}get lastSyncedAt(){let e=this.syncStatus.lastSyncedAt;return e&&new Date(e)}get isConnected(){return this.syncStatus.connected}async dispose(){super.dispose(),this.crudUpdateListener?.(),this.crudUpdateListener=void 0}async getWriteCheckpoint(){let e=`/write-checkpoint2.json?client_id=${await this.options.adapter.getClientId()}`,t=(await this.options.remote.get(e)).data.write_checkpoint;return this.logger.debug(`Created write checkpoint: ${t}`),t}async crudUploadLoop(e){for(;!e.aborted;)await Promise.all([this._uploadAllCrud(e),this.delayRetry(e,this.options.crudUploadThrottleMs)]),await this.crudUploadNotifier.waitForNotification(e)}async _uploadAllCrud(e){return this.obtainLock({type:pn.CRUD,signal:e,callback:async()=>{let t;for(;!e.aborted;)try{let e=await this.options.adapter.nextCrudItem();if(e){if(this.updateSyncStatus({dataFlow:{uploading:!0}}),e.clientId==t?.clientId)throw this.logger.warn(`Potentially previously uploaded CRUD entries are still present in the upload queue.
4Make sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.
5The next upload iteration will be delayed.`),Error(`Delaying due to previously encountered CRUD item.`);t=e,await this.options.uploadCrud(),this.updateSyncStatus({dataFlow:{uploadError:void 0}})}else{await this.options.adapter.updateLocalTarget(()=>this.getWriteCheckpoint())?this.notifyCompletedUploads?.():t!=null&&this.logger.debug(`Upload complete, no write checkpoint needed.`);break}}catch(n){if(t=void 0,this.updateSyncStatus({dataFlow:{uploading:!1,uploadError:n}}),await this.delayRetry(e),!this.isConnected)break;this.logger.debug(`Caught exception when uploading. Upload will retry after a delay. Exception: ${n.message}`)}finally{this.updateSyncStatus({dataFlow:{uploading:!1}})}}})}async connect(e){this.abortController&&await this.disconnect();let t=new AbortController;return this.abortController=t,this.streamingSyncPromise=Promise.all([this.crudUploadLoop(t.signal).catch(e=>this.logger.error(`Error in crud upload loop`,e)),this.streamingSync(t.signal,e)]),new Promise(e=>{let t=this.registerListener({statusChanged:n=>{if(n.dataFlowStatus.downloadError!=null)this.logger.warn(`Initial connect attempt did n
5ot successfully connect to server`);else if(n.connecting)return;t(),e()}})})}async disconnect(){if(this.abortController){this.abortController.signal.aborted||this.abortController.abort(new z(`Disconnect has been requested`));try{await this.streamingSyncPromise}catch(e){this.logger.warn(e)}this.streamingSyncPromise=void 0,this.abortController=null,this.updateSyncStatus({connected:!1,connecting:!1})}}async streamingSync(e,t){this.crudUpdateListener=this.options.adapter.registerListener({crudUpdate:()=>this.triggerCrudUpload()});let n=new AbortController;for(e.addEventListener(`abort`,()=>{n.abort(e?.reason??new z(`Received command to disconnect from upstream`)),this.crudUpdateListener?.(),this.crudUpdateListener=void 0,this.updateSyncStatus({connected:!1,connecting:!1,dataFlow:{downloading:!1,downloadProgress:null}})});;){this.updateSyncStatus({connecting:!0});let r=!0,i=null;try{if(e?.aborted)break;i=await this.streamingSyncIteration(n.signal,t)}catch(e){e instanceof z?(this.logger.warn(e),r=!1):this.connectionMayHaveChanged&&e.message?.indexOf(`No iteration is active`)>=0?(this.connectionMayHaveChanged=!1,this.logger.info(`Sync error after changed connection, retrying immediately`),r=!1):this.logger.error(e),this.updateSyncStatus({dataFlow:{downloadError:e}})}finally{this.notifyCompletedUploads=void 0,e.aborted||(n.abort(new z(`Closing sync stream network requests before retry.`)),n=new AbortController),i?.immediateRestart!=1&&(this.updateSyncStatus({connected:!1,connecting:!0}),r&&await this.delayRetry(n.signal))}}this.updateSyncStatus({connected:!1,connecting:!1})}markConnectionMayHaveChanged(){this.connectionMayHaveChanged=!0,this.handleActiveStreamsChange?.()}async requireKeyFormat(e){let t=await this.options.adapter.hasMigratedSubkeys();return e&&!t?(await this.options.adapter.migrateToFixedSubkeys(),!0):t}streamingSyncIteration(e,t){return this.obtainLock({type:pn.SYNC,signal:e,callback:async()=>{let n={...vn,...t??{}},r=Object.entries(n.appMetadata).filter(([e,t])=>typeof t!=`string`);if(r.length>0)throw Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${r.map(([e,t])=>`${e}: ${t}`).join(`, `)}`);return await this.requireKeyFormat(!0),await this.rustSyncIteration(e,n)}})}receiveSyncLines(e){let{options:t,connection:n}=e,r=this.options.remote,i=async()=>n.connectionMethod==mn.HTTP?await r.fetchStream(t):await this.options.remote.socketStreamRaw({...t,fetchStrategy:n.fetchStrategy}),a,o=!1;return{async next(){if(o)return A;if(a==null)return a=await i(),j({command:R.CONNECTION_STATE,payload:`established`});{let e=await a.next();return e.done?(o=!0,j({command:R.CONNECTION_STATE,payload:`end`})):j({command:typeof e.value==`string`?R.PROCESS_TEXT_LINE:R.PROCESS_BSON_LINE,payload:e.value})}}}}async rustSyncIteration(e,t){let n=this,r=this.options.adapter,i=this.options.remote,a=!1,o;if(e.aborted)throw new z(`Connection request has been aborted`);function s(){let e={parameters:t.params,app_metadata:t.appMetadata,active_streams:n.activeStreams,include_defaults:t.includeDefaultStreams};return t.serializedSchema&&(e.schema=t.serializedSchema),l(R.START,JSON.stringify(e))}async function c(){let e=await l(R.STOP);for(let t of e)fn(t)||await u(t)}async function l(e,t){let i=await r.control(e,t??null);return n.logger.trace(`powersync_control`,e,t==null||typeof t==`string`?t:`<bytes>`,i),e!=R.STOP&&(n.connectionMayHaveChanged=!1),JSON.parse(i)}async function u(e){if(`LogLine`in e)switch(e.LogLine.severity){case`DEBUG`:n.logger.debug(e.LogLine.line);break;case`INFO`:n.logger.info(e.LogLine.line);break;case`WARNING`:n.logger.warn(e.LogLine.line)}else`UpdateSyncStatus`in e?n.updateSyncStatus(dn(e.UpdateSyncStatus.status)):`FetchCredentials`in e?e.FetchCredentials.did_expire?i.invalidateCredentials():(i.invalidateCredentials(),i.fetchCredentials().then(e=>{o?.()},e=>{n.logger.warn(`Could not prefetch credentials`,e)})):`FlushFileSystem`in e||`DidCompleteSync`in e&&n.updateSyncStatus({dataFlow:{downloadError:void 0}})}try{let r={immediateRestart:!1},i=null;for(let a of await s())if(`EstablishSyncStream`in a){let r={path:`/sync/stream`,abortSignal:e,data:a.EstablishSyncStream.request};i=Se(n.receiveSyncLines({options:r,connection:t}))}else if(`CloseSyncStream`in a)return r;else await u(a);if(i==null)return r;this.notifyCompletedUploads=()=>{i.inject({command:R.NOTIFY_CRUD_UPLOAD_COMPLETED})},this.handleActiveStreamsChange=()=>{i.inject({command:R.UPDATE_SUBSCRIPTIONS,payload:JSON.stringify(this.activeStreams)})},o=()=>{i.inject({command:R.NOTIFY_TOKEN_REFRESHED})};let c=!1;loop:for(;;){let{done:e,value:t}=await i.next();if(e)break;c||(t.command==R.PROCESS_TEXT_LINE||t.command==R.PROCESS_BSON_LINE)&&(c=!0,this.triggerCrudUpload?.());let n=await l(t.command,t.payload);for(let e of n)if(`EstablishSyncStream`in e)throw Error(`Received EstablishSyncStream while already connected.`);else if(`CloseSyncStream`in e){a=e.CloseSyncStream.hide_disconnect;break loop}else await u(e)}}finally{this.notifyCompletedUploads=this.handleActiveStreamsChange=void 0,o=void 0,await c()}return{immediateRestart:a}}updateSyncStatus(e){let t=new O({connected:e.connected??this.syncStatus.connected,connecting:!e.connected&&(e.connecting??this.syncStatus.connecting),lastSyncedAt:e.lastSyncedAt??this.syncStatus.lastSyncedAt,dataFlow:{...this.syncStatus.dataFlowStatus,...e.dataFlow},priorityStatusEntries:e.priorityStatusEntries??this.syncStatus.priorityStatusEntries,clientImplementation:e.clientImplementation??this.syncStatus.clientImplementation});this.syncStatus.isEqual(t)||(this.syncStatus=t,this.iterateListeners(e=>e.statusChanged?.(t))),this.iterateListeners(t=>t.statusUpdated?.(e))}async delayRetry(e,t=this.options.retryDelayMs){return new Promise(n=>{if(e?.aborted){n();return}let r,i=()=>{n(),r&&=(clearTimeout(r),void 0),e?.removeEventListener(`abort`,i)};e?.addEventListener(`abort`,i,{once:!0}),r=setTimeout(i,t)})}updateSubscriptions(e){this.activeStreams=e,this.handleActiveStreamsChange?.()}},bn=new Map,xn={async obtainClaim(e){if(bn.has(e))throw Error(`A claim is already present for ${e}`);let t=async()=>{bn.delete(e)};return bn.set(e,t),t},async checkClaim(e){return bn.has(e)}},X;(function(e){e.INSERT=`INSERT`,e.UPDATE=`UPDATE`,e.DELETE=`DELETE`})(X||={});var Sn={useStorageByDefault:!1},Cn=12e4,wn=class{options;schema;defaultConfig;cleanupTimeout;isDisposed;constructor(e){this.options=e,this.schema=e.schema,e.db.registerListener({schemaChanged:e=>{this.schema=e}}),this.isDisposed=!1,this.defaultConfig=Sn;let t=async()=>
5{if(this.cleanupTimeout=null,!this.isDisposed)try{await this.cleanupResources()}catch(e){this.db.logger.error(`Caught error while attempting to cleanup triggers`,e)}finally{if(this.isDisposed)return;this.cleanupTimeout=setTimeout(t,Cn)}};this.cleanupTimeout=setTimeout(t,Cn)}get db(){return this.options.db}async getUUID(e){let{id:t}=await(e??this.db).get(`
6      SELECT
7        uuid () as id
8    `);return t.replace(/-/g,`_`)}async removeTriggers(e,t){for(let n of t)await e.execute(`DROP TRIGGER IF EXISTS ${n}; `)}dispose(){this.isDisposed=!0,this.cleanupTimeout&&clearTimeout(this.cleanupTimeout)}updateDefaults(e){this.defaultConfig={...this.defaultConfig,...e}}generateTriggerName(e,t,n){return`__ps_temp_trigger_${e.toLowerCase()}__${t}__${n}`}async cleanupResources(){await this.db.database.writeLock(async e=>{let t=await e.getAll(`
9        SELECT
10          name
11        FROM
12          sqlite_master
13        WHERE
14          type = 'trigger'
15          AND name LIKE '__ps_temp_trigger_%'
16      `),n=/^__ps_temp_trigger_(?:insert|update|delete)__(.+)__([a-f0-9_]{36})$/i,r=new Map;for(let e of t){let t=e.name.match(n);if(t){let[,n,i]=t,a=r.get(i);a?a.triggerNames.push(e.name):r.set(i,{table:n,id:i,triggerNames:[e.name]})}}for(let t of r.values())if(!await this.options.claimManager.checkClaim(t.id)){this.db.logger.debug(`Clearing resources for trigger ${t.id} with table ${t.table}`);for(let n of t.triggerNames)await e.execute(`DROP TRIGGER IF EXISTS ${n}`);await e.execute(`DROP TABLE IF EXISTS ${t.table}`)}})}async createDiffTrigger(e){await this.db.waitForReady();let{source:t,destination:n,columns:r,when:i,hooks:a,setupContext:o,useStorage:s=this.defaultConfig.useStorageByDefault}=e,c=Object.keys(i);if(c.length==0)throw Error(`At least one WHEN operation must be specified for the trigger.`);let l=s?``:`TEMP`,u=Object.fromEntries(Object.entries(i).map(([e,t])=>[e,`WHEN ${t}`])),d=this.schema.tables.find(e=>e.viewName==t);if(!d)throw Error(`Source table or view "${t}" not found in the schema.`);let f=r??d.columns.map(e=>e.name),p=d.internalName,m=[],h=await this.getUUID(o),g=s?await this.options.claimManager.obtainClaim(h):null,_=(e=`NEW`)=>r==null?`${e}.data`:r.length==0?`'{}'`:`json_object(${f.map(t=>`'${t}', json_extract(${e}.data, '$.${t}')`).join(`, `)})`,v=this.db.registerListener({schemaChanged:()=>{this.db.logger.warn(`The PowerSync schema has changed while previously configured triggers are still operational. This might cause unexpected results.`)}}),y=async e=>{let{context:t}=e??{};v();let r=async e=>{await this.removeTriggers(e,m),await e.execute(`DROP TABLE IF EXISTS ${n};`),await g?.()};t?await r(t):await this.db.writeLock(r)},b=async e=>{if(await a?.beforeCreate?.(e),await e.execute(`
17        CREATE ${l} TABLE ${n} (
18          operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
19          id TEXT,
20          operation TEXT,
21          timestamp TEXT,
22          value TEXT,
23          previous_value TEXT
24        )
25      `),c.includes(X.INSERT)){let t=this.generateTriggerName(X.INSERT,n,h);m.push(t),await e.execute(`
26          CREATE ${l} TRIGGER ${t} AFTER INSERT ON ${p} ${u[X.INSERT]} BEGIN
27          INSERT INTO
28            ${n} (id, operation, timestamp, value)
29          VALUES
30            (
31              NEW.id,
32              'INSERT',
33              strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),
34              ${_(`NEW`)}
35            );
36
37          END
38        `)}if(c.includes(X.UPDATE)){let t=this.generateTriggerName(X.UPDATE,n,h);m.push(t),await e.execute(`
39          CREATE ${l} TRIGGER ${t} AFTER
40          UPDATE ON ${p} ${u[X.UPDATE]} BEGIN
41          INSERT INTO
42            ${n} (id, operation, timestamp, value, previous_value)
43          VALUES
44            (
45              NEW.id,
46              'UPDATE',
47              strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),
48              ${_(`NEW`)},
49              ${_(`OLD`)}
50            );
51
52          END;
53        `)}if(c.includes(X.DELETE)){let t=this.generateTriggerName(X.DELETE,n,h);m.push(t),await e.execute(`
54          CREATE ${l} TRIGGER ${t} AFTER DELETE ON ${p} ${u[X.DELETE]} BEGIN
55          INSERT INTO
56            ${n} (id, operation, timestamp, value)
57          VALUES
58            (
59              OLD.id,
60              'DELETE',
61              strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),
62              ${_(`OLD`)}
63            );
64
65          END;
66        `)}};try{return o?await b(o):await this.db.writeLock(b),y}catch(e){try{await y(o?{context:o}:void 0)}catch(t){throw AggregateError([e,t],`Error during operation and cleanup`)}throw e}}async trackTableDiff(e){let{source:t,when:n,columns:r,hooks:i,throttleMs:a=30}=e;await this.db.waitForReady();let o=this.schema.tables.find(e=>e.viewName==t);if(!o)throw Error(`Source table or view "${t}" not found in the schema.`);let s=r??o.columns.map(e=>e.name),c=`__ps_temp_track_${t}_${await this.getUUID()}`,l=new AbortController,u=()=>l.abort();this.db.onChange({onChange:async()=>{l.signal.aborted||await this.db.writeTransaction(async t=>{let n=await e.onChange({execute:(e,n)=>t.execute(e,n),executeBatch:(e,n)=>t.executeBatch(e,n),executeRaw:(e,n)=>t.executeRaw(e,n),get:(e,n)=>t.get(e,n),getAll:(e,n)=>t.getAll(e,n),getOptional:(e,n)=>t.getOptional(e,n),destinationTable:c,withDiff:async(e,n,r)=>{let i=`
67                  WITH
68                    DIFF AS (
69                      SELECT
70                        ${r?.castOperationIdAsText?`id, operation, CAST(operation_id AS TEXT) as operation_id, timestamp, value, previous_value`:`*`}
71                      FROM
72                        ${c}
73                      ORDER BY
74                        operation_id ASC
75                    ) ${e}
76                `;return t.getAll(i,n)},withExtractedDiff:async(e,n)=>{let r=`
77                  WITH
78                    DIFF AS (
79                      SELECT
80                        id,
81                        ${s.length>0?`${s.map(e=>`json_extract(value, '$.${e}') as ${e}`).join(`, `)},`:``} operation_id as __operation_id,
82                        operation as __operation,
83                        timestamp as __timestamp,
84                        previous_value as __previous_value
85                      FROM
86                        ${c}
87                      ORDER BY
88                        __operation_id ASC
89                    ) ${e}
90                `;return t.getAll(r,n)}});return await t.execute(`DELETE FROM ${c};`),n})}},{tables:[c],signal:l.signal,throttleMs:a});try{let e=await this.createDiffTrigger({source:t,destination:c,columns:s,when:n,hooks:i});return async()=>{u(),await e()}}catch(e){try{u()}catch(t){throw AggregateError([e,t],`Error during operation and cleanup`)}throw e}}},Tn=/(^ps_data__|^ps_data_local__)/,En={clearLocal:!0},Dn={disconnect:!0},On={retryDelayMs:5e3,crudUploadThrottleMs:_n},kn=12e4,An=e=>typeof e==`object`&&Pe(e.database),jn=class extends k{options;closed;ready;currentStatus;sdkVersion;bucketStorageAdapter;_isReadyPromise;connectionManager;subscriptions;get syncStreamImplementation(){return this.connectionManager.syncStreamImplementation}get connector(){return this.connectionManager.connector}get connectionOptions(){return this.connectionManager.connectionOptions}_schema;_database;runExclusiveMutex;triggers;triggersImpl;logger;constructor(e){super(),this.options=e;let{database:t,schema:n}=e;if(typeof n?.toJSON!=`function`)throw Error("The `schema` option should be provided and should be an instance of `Schema`.");if(Ie(t))this._database=t;else if(Fe(t))this._database=t.openDB();else if(An(e))this._database=this.openDBAdapter(e);else throw Error("The provided `database` option is invalid.");this.logger=e.logger??w.get(`PowerSyncDatabase[${this._database.name}]`),this.bucketStorageAdapter=this.generateBucketStorageAdapter(),this.closed=!1,this.currentStatus=new O({}),this.options={...On,...e},this._schema=n,this.ready=!1,this.sdkVersion=``,this.runExclusiveMutex=new C,this.subscriptions={firstStatusMatching:(e,t)=>this.waitForStatus(e,t),resolveOfflineSyncStatus:()=>this.resolveOfflineSyncStatus(),rustSubscriptionsCommand:async e=>{await this.writeTransaction(t=>t.execute(`select powersync_control(?,?)`,[`subscriptions`,JSON.stringify(e)]))}},this.connectionManager=new Ee({createSyncImplementation:async(e,t)=>(await this.waitForReady(),this.runExclusive(async()=>{let n=this.generateSyncStreamImplementation(e,this.resolvedConnectionOptions(t)),r=n.registerListener({statusChanged:e=>{this.currentStatus=new O({...e.toJSON(),hasSynced:this.currentStatus?.hasSynced||!!e.lastSyncedAt}),this.iterateListeners(e=>e.statusChanged?.(this.currentStatus))}});return await n.waitForReady(),{sync:n,onDispose:r}})),logger:this.logger}),this._isReadyPromise=this.initialize(),this.triggers=this.triggersImpl=new wn({db:this,schema:this.schema,...this.generateTriggerManagerConfig()})}get schema(){return this._schema}get database(){return this._database}get connected(){return this.currentStatus?.connected||!1}get connecting(){return this.currentStatus?.connecting||!1}generateTriggerManagerConfig(){return{claimManager:xn}}async waitForReady(){this.ready||await this._isReadyPromise}async waitForFirstSync(e){let t=e instanceof AbortSignal?e:e?.signal,n=e&&`priority`in e?e.priority:void 0,r=n===void 0?e=>e.hasSynced:e=>e.statusForPriority(n).hasSynced;return this.waitForStatus(r,t)}async waitForStatus(e,t){if(!e(this.currentStatus))return new Promise(n=>{let r=this.registerListener({statusChanged:t=>{e(t)&&i()}});function i(){r(),n()}t?.aborted?i():t?.addEventListener(`abort`,i)})}async initialize(){await this._initialize(),await this.bucketStorageAdapter.init(),await this.loadVersion(),await this.updateSchema(this.options.schema),await this.resolveOfflineSyncStatus(),await this.database.execute(`PRAGMA RECURSIVE_TRIGGERS=TRUE`),await this.triggersImpl.cleanupResources(),this.ready=!0,this.iterateListeners(e=>e.initialized?.())}async loadVersion(){try{let{version:e}=await this.database.get(`SELECT powersync_rs_version() as version`);this.sdkVersion=e}catch(e){throw Error(`The powersync extension is not loaded correctly. Details: ${e.message}`)}let e;try{e=this.sdkVersion.split(/[.\/]/).slice(0,3).map(e=>parseInt(e))}
90catch(e){throw Error(`Unsupported powersync extension version. Need >=0.4.10 <1.0.0, got: ${this.sdkVersion}. Details: ${e.message}`)}if(e[0]!=0||e[1]<4||e[1]==4&&e[2]<10)throw Error(`Unsupported powersync extension version. Need >=0.4.10 <1.0.0, got: ${this.sdkVersion}`)}async resolveOfflineSyncStatus(){let e=await this.database.get(`SELECT powersync_offline_sync_status() as r`),t=JSON.parse(e.r),n=new O({...this.currentStatus.toJSON(),...dn(t)});n.isEqual(this.currentStatus)||(this.currentStatus=n,this.iterateListeners(e=>e.statusChanged?.(this.currentStatus)))}async updateSchema(e){if(this.syncStreamImplementation)throw Error(`Cannot update schema while connected`);try{e.validate()}catch(e){this.logger.warn(`Schema validation failed. Unexpected behaviour could occur`,e)}this._schema=e,await this.database.writeTransaction(e=>e.execute(`SELECT powersync_replace_schema(?)`,[JSON.stringify(this.schema.toJSON())])),await this.database.refreshSchema(),this.iterateListeners(async t=>t.schemaChanged?.(e))}async init(){return this.waitForReady()}resolvedConnectionOptions(e){return{...e,retryDelayMs:e?.retryDelayMs??this.options.retryDelayMs??this.options.retryDelay??5e3,crudUploadThrottleMs:e?.crudUploadThrottleMs??this.options.crudUploadThrottleMs??1e3}}dispose(){return super.dispose()}runExclusive(e){return this.runExclusiveMutex.runExclusive(e)}async connect(e,t){let n=t??{};return n.serializedSchema=this.schema.toJSON(),this.connectionManager.connect(e,n)}async disconnect(){return this.connectionManager.disconnect()}async disconnectAndClear(e=En){await this.disconnect(),await this.waitForReady();let{clearLocal:t}=e;await this.database.writeTransaction(async e=>{await e.execute(`SELECT powersync_clear(?)`,[+!!t])}),this.currentStatus=new O({}),this.iterateListeners(e=>e.statusChanged?.(this.currentStatus))}syncStream(e,t){return this.connectionManager.stream(this.subscriptions,e,t??null)}async close(e=Dn){if(await this.waitForReady(),this.closed)return;this.triggersImpl.dispose(),await this.iterateAsyncListeners(async e=>e.closing?.());let{disconnect:t}=e;t&&await this.disconnect(),await this.connectionManager.close(),await this.database.close(),this.closed=!0,await this.iterateAsyncListeners(async e=>e.closed?.())}async getUploadQueueStats(e){return this.readTransaction(async t=>{if(e){let e=(await t.execute(`SELECT SUM(cast(data as blob) + 20) as size, count(*) as count FROM ${L.CRUD}`)).rows.item(0);return new ye(e?.count??0,e?.size??0)}return new ye((await t.execute(`SELECT count(*) as count FROM ${L.CRUD}`)).rows.item(0)?.count??0)})}async getCrudBatch(e=100){let t=(await this.getAll(`SELECT id, tx_id, data FROM ${L.CRUD} ORDER BY id ASC LIMIT ?`,[e+1])).map(e=>ze.fromRow(e))??[],n=!1;if(t.length>e&&(t.pop(),n=!0),t.length==0)return null;let r=t[t.length-1];return new Le(t,n,async e=>this.handleCrudCheckpoint(r.clientId,e))}async getNextCrudTransaction(){return(await this.getCrudTransactions()[xe]().next()).value}getCrudTransactions(){return{[xe]:()=>{let e=-1;return{next:async()=>{let t=await this.database.getAll(`
91WITH RECURSIVE crud_entries AS (
92  SELECT id, tx_id, data FROM ps_crud WHERE id = (SELECT min(id) FROM ps_crud WHERE id > ?)
93  UNION ALL
94  SELECT ps_crud.id, ps_crud.tx_id, ps_crud.data FROM ps_crud
95    INNER JOIN crud_entries ON crud_entries.id + 1 = rowid
96  WHERE crud_entries.tx_id = ps_crud.tx_id
97)
98SELECT * FROM crud_entries;
99    `,[e]);if(t.length==0)return{done:!0,value:null};let n=t.map(e=>ze.fromRow(e)),r=n[n.length-1],i=r.transactionId;return e=r.clientId,{done:!1,value:new Be(n,async e=>this.handleCrudCheckpoint(r.clientId,e),i)}}}}}}async getClientId(){return this.bucketStorageAdapter.getClientId()}async handleCrudCheckpoint(e,t){return this.writeTransaction(async n=>{await n.execute(`DELETE FROM ${L.CRUD} WHERE id <= ?`,[e]),t?(await n.execute(`SELECT 1 FROM ${L.CRUD} LIMIT 1`)).rows?.length||await n.execute(`UPDATE ${L.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`,[t]):await n.execute(`UPDATE ${L.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`,[this.bucketStorageAdapter.getMaxOpId()])})}async execute(e,t){return this.writeLock(n=>n.execute(e,t))}async executeRaw(e,t){return await this.waitForReady(),this.database.executeRaw(e,t)}async executeBatch(e,t){return await this.waitForReady(),this.database.executeBatch(e,t)}async getAll(e,t){return await this.waitForReady(),this.database.getAll(e,t)}async getOptional(e,t){return await this.waitForReady(),this.database.getOptional(e,t)}async get(e,t){return await this.waitForReady(),this.database.get(e,t)}async readLock(e){return await this.waitForReady(),this.database.readLock(e)}async writeLock(e){return await this.waitForReady(),this.database.writeLock(e)}async readTransaction(e,t=kn){return await this.waitForReady(),this.database.readTransaction(async t=>{let n=await e(t);return await t.rollback(),n},{timeoutMs:t})}async writeTransaction(e,t=kn){return await this.waitForReady(),this.database.writeTransaction(async t=>{let n=await e(t);return await t.commit(),n},{timeoutMs:t})}watch(e,t,n,r){if(n&&typeof n==`object`&&`onResult`in n){let i=n,a=r;return this.watchWithCallback(e,t,i,a)}let i=n;return this.watchWithAsyncGenerator(e,t,i)}query(e){let{sql:t,parameters:n=[],mapper:r}=e;return this.customQuery({compile:()=>({sql:t,parameters:n}),execute:async({sql:e,parameters:t})=>{let n=await this.getAll(e,t);return r?n.map(r):n}})}customQuery(e){return new Ne({db:this,query:e})}watchWithCallback(e,t,n,r){let{onResult:i,onError:a=e=>this.logger.error(e)}=n??{};if(!i)throw Error(`onResult is required`);let{comparator:o}=r??{}
99,s=new Me({db:this,comparator:o,placeholderData:null,watchOptions:{query:{compile:()=>({sql:e,parameters:t??[]}),execute:()=>this.executeReadOnly(e,t)},reportFetching:!1,throttleMs:r?.throttleMs??30,triggerOnTables:r?.tables}}),c=s.registerListener({onData:e=>{e&&i(e)},onError:e=>{a(e)}});r?.signal?.addEventListener(`abort`,()=>{c(),s.close()})}watchWithAsyncGenerator(e,t,n){return N.queueBasedAsyncIterable((r,i)=>{this.watchWithCallback(e,t,{onResult:e=>{r.notify(e)},onError:e=>{r.notifyError(e)}},{...n,signal:i})},n?.signal)}async resolveTables(e,t,n){let r=n?.tables?[...n.tables]:[];if(!n?.tables){let n=(await this.getAll(`EXPLAIN ${e}`,t)).filter(e=>e.opcode==`OpenRead`&&e.p3==0&&typeof e.p2==`number`).map(e=>e.p2),i=await this.getAll(`SELECT DISTINCT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?))`,[JSON.stringify(n)]);for(let e of i)r.push(e.tbl_name.replace(Tn,``))}return r}onChange(e,t){if(e&&typeof e==`object`&&`onChange`in e){let n=e,r=t;return this.onChangeWithCallback(n,r)}let n=e;return this.onChangeWithAsyncGenerator(n)}onChangeWithCallback(e,t){let{onChange:n,onError:r=e=>this.logger.error(e)}=e??{};if(!n)throw Error(`onChange is required`);let i=t??{},a=new Set((i?.tables??[]).flatMap(e=>[e,`ps_data__${e}`,`ps_data_local__${e}`])),o=new Set,s=i.throttleMs??30,c=new be(async e=>{await n(e)}),l=Te(()=>this.handleTableChanges(o,a,e=>{i?.signal?.aborted||c.schedule({changedTables:e})}),s);t?.triggerImmediate&&c.schedule({changedTables:[]});let u=this.database.registerListener({tablesUpdated:async e=>{try{this.processTableUpdates(e,o),l()}catch(e){r?.(e)}}});return i.signal?.addEventListener(`abort`,()=>{c.dispose(),u()}),()=>u()}onChangeWithAsyncGenerator(e){return N.queueBasedAsyncIterable((t,n)=>{this.onChangeWithCallback({onChange:e=>{t.notify(e)},onError:e=>{t.notifyError(e)}},{...e,signal:n})},e?.signal)}handleTableChanges(e,t,n){if(e.size>0){let r=Array.from(e.values()).filter(e=>t.has(e));r.length&&n(r)}e.clear()}processTableUpdates(e,t){let n=he(e)?e.tables:[e.table];for(let e of n)t.add(e)}async executeReadOnly(e,t){return await this.waitForReady(),this.database.readLock(n=>n.execute(e,t))}},Mn=`9223372036854775807`,Nn=class e extends k{db;logger;tableNames;updateListener;_clientId;constructor(e,t=w.get(`SqliteBucketStorage`)){super(),this.db=e,this.logger=t,this.tableNames=new Set,this.updateListener=e.registerListener({tablesUpdated:e=>{ge(e).includes(L.CRUD)&&this.iterateListeners(e=>e.crudUpdate?.())}})}
99async init(){let e=await this.db.getAll(`SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'`);for(let t of e??[])this.tableNames.add(t.name)}async dispose(){this.updateListener?.()}async _getClientId(){return(await this.db.get(`SELECT powersync_client_id() as client_id`)).client_id}getClientId(){return this._clientId??=this._getClientId(),this._clientId}getMaxOpId(){return Mn}async updateLocalTarget(e){if(!(await this.db.getAll(`SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)`,[`9223372036854775807`])).length)return!1;let t=await this.db.getAll(`SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'`);if(!t.length)return!1;let n=t[0].seq,r=await e();return this.writeTransaction(async e=>{if((await e.execute(`SELECT 1 FROM ps_crud LIMIT 1`)).rows?.length)return this.logger.debug(`New data uploaded since write checkpoint ${r} - need new write checkpoint`),!1;let t=await e.execute(`SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'`);if(!t.rows?.length)throw Error(`SQLite Sequence should not be empty`);return t.rows?.item(0).seq==n?(this.logger.debug(`Updating target write checkpoint to ${r}`),await e.execute(`UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'`,[r]),!0):(this.logger.debug(`New data uploaded since write checpoint ${r} - need new write checkpoint (sequence updated)`),!1)})}async nextCrudItem(){let e=await this.db.getOptional(`SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1`);if(e)return ze.fromRow(e)}async hasCrud(){return!!await this.db.getOptional(`SELECT 1 FROM ps_crud LIMIT 1`)}async getCrudBatch(e=100){if(!await this.hasCrud())return null;let t=await this.db.getAll(`SELECT * FROM ps_crud ORDER BY id ASC LIMIT ?`,[e]),n=[];for(let e of t)n.push(ze.fromRow(e));if(n.length===0)return null;let r=n[n.length-1];return{crud:n,haveMore:!0,complete:async e=>this.writeTransaction(async t=>{await t.execute(`DELETE FROM ps_crud WHERE id <= ?`,[r.clientId]),e?(await t.execute(`SELECT 1 FROM ps_crud LIMIT 1`)).rows?.length&&await t.execute(`UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'`,[e]):await t.execute(`UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'`,[this.getMaxOpId()])})}}async writeTransaction(e,t){return this.db.writeTransaction(e,t)}async control(e,t){return await this.writeTransaction(async n=>{let[[r]]=await n.executeRaw(`SELECT powersync_control(?, ?)`,[e,t]);return r})}async hasMigratedSubkeys(){let{r:t}=await this.db.get(`SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r`,[e._subkeyMigrationKey]);return t!=0}async migrateToFixedSubkeys(){await this.writeTransaction(async t=>{await t.execute(`UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);`),await t.execute(`INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);`,[e._subkeyMigrationKey,`1`])})}static _subkeyMigrationKey=`powersync_js_migrated_subkeys`},Pn=class e extends Error{static NAME=`ConnectionClosedError`;static MATCHES(t){return t instanceof e||t instanceof Error&&t.name==e.NAME}constructor(t){super(t),this.name=e.NAME}},Fn=class e{types;props;tables;rawTables;constructor(e){if(Array.isArray(e)){for(let t of e)if(t.name===``)throw Error(`It appears you are trying to create a new Schema with an array instead of an object. Passing in an object instead of an array into 'new Schema()' may resolve your issue.`);this.tables=e}else this.props=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.copyWithName(e)])),this.tables=Object.values(this.props);this.rawTables=[]}withRawTables(e){for(let[t,n]of Object.entries(e))this.rawTables.push({name:t,...n})}validate(){for(let e of this.tables)e.validate()}toJSON(){return{tables:this.tables.map(e=>e.toJSON()),raw_tables:this.rawTables.map(e.rawTableToJson)}}static rawTableToJson(e){let t={name:e.name,put:e.put,delete:e.delete,clear:e.clear};if(`schema`in e){let n=e.schema;t.table_name=n.tableName??e.name,t.synced_columns=n.syncedColumns,Object.assign(t,y(e.schema))}return t}},In=w;In.TRACE,In.DEBUG,In.INFO,In.TIME,In.WARN,In.ERROR,In.OFF;function Ln(e,t={}){let n=w.get(e);return t.logLevel&&n.setLevel(t.logLevel),n}var Rn=()=>
99{if(`locks`in navigator&&navigator.locks)return navigator.locks;throw Error(`Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.`)},zn={async obtainClaim(e){return new Promise(t=>{Rn().request(e,async()=>{await new Promise(e=>{t(async()=>e())})})})},async checkClaim(e){return(await Rn().query()).held?.find(t=>t.name==e)!=null}},Bn=Symbol(`Comlink.proxy`),Vn=Symbol(`Comlink.endpoint`),Hn=Symbol(`Comlink.releaseProxy`),Un=Symbol(`Comlink.finalizer`),Wn=Symbol(`Comlink.thrown`),Gn=e=>typeof e==`object`&&!!e||typeof e==`function`,Kn=new Map([[`proxy`,{canHandle:e=>Gn(e)&&e[Bn],serialize(e){let{port1:t,port2:n}=new MessageChannel;return Jn(e,t),[n,[n]]},deserialize(e){return e.start(),Zn(e)}}],[`throw`,{canHandle:e=>Gn(e)&&Wn in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(Error(e.value.message),e.value):e.value}}]]);function qn(e,t){for(let n of e)if(t===n||n===`*`||n instanceof RegExp&&n.test(t))return!0;return!1}function Jn(e,t=globalThis,n=[`*`]){t.addEventListener(`message`,function r(i){if(!i||!i.data)return;if(!qn(n,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}let{id:a,type:o,path:s}=Object.assign({path:[]},i.data),c=(i.data.argumentList||[]).map(dr),l;try{let t=s.slice(0,-1).reduce((e,t)=>e[t],e),n=s.reduce((e,t)=>e[t],e);switch(o){case`GET`:l=n;break;case`SET`:t[s.slice(-1)[0]]=dr(i.data.value),l=!0;break;case`APPLY`:l=n.apply(t,c);break;case`CONSTRUCT`:l=lr(new n(...c));break;case`ENDPOINT`:{let{port1:t,port2:n}=new MessageChannel;Jn(e,n),l=cr(t,[t])}break;case`RELEASE`:l=void 0;break;default:return}}catch(e){l={value:e,[Wn]:0}}Promise.resolve(l).catch(e=>({value:e,[Wn]:0})).then(n=>{let[i,s]=ur(n);t.postMessage(Object.assign(Object.assign({},i),{id:a}),s),o===`RELEASE`&&(t.removeEventListener(`message`,r),Xn(t),Un in e&&typeof e[Un]==`function`&&e[Un]())}).catch(e=>{let[n,r]=ur({value:TypeError(`Unserializable return value`),[Wn]:0});t.postMessage(Object.assign(Object.assign({},n),{id:a}),r)})}),t.start&&t.start()}function Yn(e){return e.constructor.name===`MessagePort`}function Xn(e){Yn(e)&&e.close()}function Zn(e,t){let n=new Map;return e.addEventListener(`message`,function(e){let{data:t}=e;if(!t||!t.id)return;let r=n.get(t.id);if(r)try{r(t)}finally{n.delete(t.id)}}),ir(e,n,[],t)}function Qn(e){if(e)throw Error(`Proxy has been released and is not useable`)}function $n(e){return fr(e,new Map,{type:`RELEASE`}).then(()=>{Xn(e)})}var er=new WeakMap,tr=`FinalizationRegistry`in globalThis&&new FinalizationRegistry(e=>{let t=(er.get(e)||0)-1;er.set(e,t),t===0&&$n(e)});function nr(e,t){let n=(er.get(t)||0)+1;er.set(t,n),tr&&tr.register(e,t,e)}function rr(e){tr&&tr.unregister(e)}function ir(e,t,n=[],r=function(){}){let i=!1,a=new Proxy(r,{get(r,o){if(Qn(i),o===Hn)return()=>{rr(a),$n(e),t.clear(),i=!0};if(o===`then`){if(n.length===0)return{then:()=>a};let r=fr(e,t,{type:`GET`,path:n.map(e=>e.toString())}).then(dr);return r.then.bind(r)}return ir(e,t,[...n,o])},set(r,a,o){Qn(i);let[s,c]=ur(o);return fr(e,t,{type:`SET`,path:[...n,a].map(e=>e.toString()),value:s},c).then(dr)},apply(r,a,o){Qn(i);let s=n[n.length-1];if(s===Vn)return fr(e,t,{type:`ENDPOINT`}).then(dr);if(s===`bind`)return ir(e,t,n.slice(0,-1));let[c,l]=or(o);return fr(e,t,{type:`APPLY`,path:n.map(e=>e.toString()),argumentList:c},l).then(dr)},construct(r,a){Qn(i);let[o,s]=or(a);return fr(e,t,{type:`CONSTRUCT`,path:n.map(e=>e.toString()),argumentList:o},s).then(dr)}});return nr(a,e),a}function ar(e){return Array.prototype.concat.apply([],e)}function or(e){let t=e.map(ur);return[t.map(e=>e[0]),ar(t.map(e=>e[1]))]}var sr=new WeakMap;function cr(e,t){return sr.set(e,t),e}function lr(e){return Object.assign(e,{[Bn]:!0})}function ur(e){for(let[t,n]of Kn)if(n.canHandle(e)){let[r,i]=n.serialize(e);return[{type:`HANDLER`,name:t,value:r},i]}return[{type:`RAW`,value:e},sr.get(e)||[]]}function dr(e){switch(e.type){case`HANDLER`:return Kn.get(e.name).deserialize(e.value);case`RAW`:return e.value}}function fr(e,t,n,r){return new Promise(i=>{let a=pr();t.set(a,i),e.start&&e.start(),e.postMessage(Object.assign({id:a},n),r)})}function pr(){return[,,,,].fill(0).map(()=>Math.floor(Math.random()*(2**53-1)).toString(16)).join(`-`)}var Z;(function(e){e.IDBBatchAtomicVFS=`IDBBatchAtomicVFS`,e.OPFSCoopSyncVFS=`OPFSCoopSyncVFS`,e.AccessHandlePoolVFS=`AccessHandlePoolVFS`,e.OPFSWriteAheadVFS=`OPFSWriteAheadVFS`,e.InMemoryVfs=`InMemoryVFS`})(Z||={});function mr(e){return e!=Z.IDBBatchAtomicVFS&&e!=Z.InMemoryVfs}async function hr(e){if(e){let{default:e}=await s(async()=>{let{default:e}=await import(`./mc-wa-sqlite-async-XseLU7Qv.js`);return{default:e}},[]);return e()}{let{default:e}=await s(async()=>{let{default:e}=await import(`./wa-sqlite-async-BHaDNK9W.js`);return{default:e}},[]);return e()}}async function gr(e){if(e){let{default:e}=await s(async()=>{let{default:e}=await import(`./mc-wa-sqlite-7IuXVR-7.js`);return{default:e}},[]);return e()}{let{default:e}=await s(async()=>{let{default:e}=await import(`./wa-sqlite-DgGBqHVK.js`);return{default:e}},[]);return e()}}async function _r({vfs:e,dbFilename:t,encryptionKey:n}){let r=gr,i;switch(e){case Z.IDBBatchAtomicVFS:{r=hr;let{IDBBatchAtomicVFS:e}=await s(async()=>{let{IDBBatchAtomicVFS:e}=await import(`./IDBBatchAtomicVFS-DtJB2Vh-.js`);return{IDBBatchAtomicVFS:e}},__vite__mapDeps([0,1]));i=n=>e.create(t,n,{lockPolicy:`exclusive`});break}
99case Z.AccessHandlePoolVFS:{let{AccessHandlePoolVFS:e}=await s(async()=>{let{AccessHandlePoolVFS:e}=await import(`./AccessHandlePoolVFS-Br29lmio.js`);return{AccessHandlePoolVFS:e}},__vite__mapDeps([2,1]));i=n=>e.create(t,n);break}case Z.OPFSCoopSyncVFS:{let{OPFSCoopSyncVFS:e}=await s(async()=>{let{OPFSCoopSyncVFS:e}=await import(`./OPFSCoopSyncVFS-umZAcyOw.js`);return{OPFSCoopSyncVFS:e}},__vite__mapDeps([3,1]));i=n=>e.create(t,n);break}case Z.OPFSWriteAheadVFS:{let{OPFSWriteAheadVFS:e}=await s(async()=>{let{OPFSWriteAheadVFS:e}=await import(`./OPFSWriteAheadVFS-Dq1eU8Yt.js`);return{OPFSWriteAheadVFS:e}},__vite__mapDeps([4,1]));i=n=>e.create(t,n,{});break}case Z.InMemoryVfs:{let{MemoryVFS:e}=await s(async()=>{let{MemoryVFS:e}=await import(`./MemoryVFS-CDeBjiYu.js`);return{MemoryVFS:e}},__vite__mapDeps([5,1]));i=n=>e.create(t,n);break}}let a=await r(n);return{module:a,vfs:await i(a)}}function vr(e,t){function n(e){t.error(`Error in database or sync worker, this likely disrupts PowerSync.`,e.error)}e.addEventListener(`error`,n)}function yr(e,t=!0,n=``,r,i){let a=r&&mr(r),o;return o=n?!a&&t?new SharedWorker(`${n}`,{name:`shared-DB-worker-${e}`}):new Worker(`${n}`,{name:`DB-worker-${e}`}):!a&&t?new SharedWorker(new URL(`/assets/WASQLiteDB.worker-KdscRAkn.js`,``+import.meta.url),{name:`shared-DB-worker-${e}`,type:`module`}):new Worker(new URL(`/assets/WASQLiteDB.worker-KdscRAkn.js`,``+import.meta.url),{name:`DB-worker-${e}`,type:`module`}),br(()=>o,i)}function br(e,t){let n=e();return t&&vr(n,t),xr(n)?n.port:n}function xr(e){return`port`in e}var Sr;(function(e){e.MEMORY=`memory`,e.FILESYSTEM=`file`})(Sr||={});var Cr=51200;function wr(){return typeof window>`u`}var Tr={broadcastLogs:!0,disableSSRWarning:!1,ssrMode:wr(),enableMultiTabs:globalThis.navigator!==void 0&&typeof SharedWorker<`u`&&!navigator.userAgent.match(/(Android|iPhone|iPod|iPad)/i)&&!window.safari,useWebWorker:!0};function Er(e){let t={...Tr,...e??{}};return e?.enableMultiTabs!==void 0&&(t.enableMultiTabs=e.enableMultiTabs),e?.useWebWorker===!1&&(t.enableMultiTabs=!1),t}var Dr={rowsAffected:0},Or=class extends k{name;readMutex;writeMutex;constructor(){super(),this.name=`SSR DB`,this.readMutex=new C,this.writeMutex=new C}close(){}async readLock(e,t){return this.readMutex.runExclusive(()=>e(this),ae(t?.timeoutMs))}async readTransaction(e,t){return this.readLock(()=>e(this.generateMockTransactionContext()),t)}async writeLock(e,t){return this.writeMutex.runExclusive(()=>e(this),ae(t?.timeoutMs))}async writeTransaction(e,t){return this.writeLock(()=>e(this.generateMockTransactionContext()),t)}async execute(e,t){return this.writeMutex.runExclusive(async()=>Dr)}async executeRaw(e,t){return this.writeMutex.runExclusive(async()=>[])}async executeBatch(e,t){return this.writeMutex.runExclusive(async()=>Dr)}async getAll(e,t){return[]}async getOptional(e,t){return null}async get(e,t){throw Error(`No values are returned in SSR mode`)}generateMockTransactionContext(){return{...this,commit:async()=>Dr,rollback:async()=>Dr}}async refreshSchema(){}},kr=class{#e;#t=0;#n=new Set;#r;#i=new Set;constructor(e){this.#e=e;let t=e.inner;this.#r=new BroadcastChannel(`${t.options.dbFilename}-table-updates`),this.#r.onmessage=({data:e})=>{this.#a(e)}}#a(e){for(let t of this.#i)t.postMessage(e)}get#o(){return this.#e.inner}get#s(){return this.#e.logger}async connect(e){let t=!0,n=this.#t++;this.#n.add(n);let r=new Map,i;function a(){if(!t)throw Error(`Client has already been closed`)}function o(e){a();let t=r.get(e);if(!t)throw Error(`Attempted to use a connection lease that has already been returned.`);return t}let s=async()=>{if(t){t=!1,i&&this.#i.delete(i);for(let{lease:e}of r.values())this.#s.debug(`Closing connection lease that hasn't been returned.`),await e.returnLease();this.#n.delete(n),this.#n.size==0?await this.forceClose():this.#s.debug(`Keeping underlying connection active since its used by other clients.`)}};return e&&navigator.locks.request(e,{},()=>{s()}),{close:s,debugIsAutoCommit:async()=>this.#o.unsafeUseInner().isAutoCommit(),requestAccess:async(e,n)=>{a();let i=await this.#o.acquireConnection(n==null?void 0:AbortSignal.timeout(n));if(!t)return await i.returnLease(),a();let o=crypto.randomUUID();return r.set(o,{lease:i,write:e}),o},completeAccess:async e=>
99{let t=o(e);r.delete(e);try{if(t.write){let{resultSet:e}=await t.lease.use(e=>e.execute(`SELECT powersync_update_hooks('get')`));if(e){let t=JSON.parse(e.rows[0][0]);t.length&&(this.#r.postMessage(t),this.#a(t))}}}finally{await t.lease.returnLease()}},execute:async(e,t,n)=>{let{lease:r}=o(e);return await r.use(e=>e.execute(t,n))},executeBatch:async(e,t,n)=>{let{lease:r}=o(e);return await r.use(e=>e.executeBatch(t,n))},setUpdateListener:async e=>{a(),i&&this.#i.delete(i),i=e,e&&this.#i.add(e)}}}async forceClose(){this.#s.debug(`Closing connection to ${this.#o.options}.`);let e=this.#o;this.#e.onClose(),this.#r.close(),await e.close()}},Ar=3338,jr=3594,Mr=4106,Nr=2570,Pr=1802,Fr=1034,Ir=3850,Lr=1546,Rr=2058,zr=1024,Br=2048,Vr=4096,Hr=8192,Ur=16384,Wr=524288,Gr=2048,Kr=16384;BigInt.prototype.toJSON===void 0&&(BigInt.prototype.toJSON=function(){return this.toString()});var qr=9223372036854775807n,Jr=-9223372036854775808n,Yr=Object.getPrototypeOf(async function(){}).constructor,Xr=class extends Error{constructor(e,t){super(e),this.code=t}},Zr=!0;function Qr(e){let t={};e.retryOps=[],e.pendingOps=[];let n=e._getSqliteFree(),r=e._malloc(8),i=[r,r+4],a=new TextEncoder;function o(t){if(typeof t!=`string`)return 0;let n=a.encode(t),r=e._sqlite3_malloc(n.byteLength+1);return e.HEAPU8.set(n,r),e.HEAPU8[r+n.byteLength]=0,r}function s(e,t){return BigInt(t)<<32n|BigInt(e)&4294967295n}let c=(function(){let e=BigInt(2**53-1)>>32n,t=BigInt(-(2**53-1))>>32n;return function(n,r){return r>e||r<t?s(n,r):r*4294967296+(n&2147483647)-(n&2147483648)}})(),l=new Set;function u(e){if(!l.has(e))throw new Xr(`not a database`,21)}let d=new Map;function f(e){if(!d.has(e))throw new Xr(`not a statement`,21)}t.bind_collection=function(e,n){f(e);let r=Array.isArray(n),i=t.bind_parameter_count(e);for(let a=1;a<=i;++a){let i=n[r?a-1:t.bind_parameter_name(e,a)];i!==void 0&&t.bind(e,a,i)}return 0},t.bind=function(e,n,r){switch(f(e),typeof r){case`number`:return r===(r|0)?t.bind_int(e,n,r):t.bind_double(e,n,r);case`string`:return t.bind_text(e,n,r);case`boolean`:return t.bind_int(e,n,+!!r);default:return r instanceof Uint8Array||Array.isArray(r)?t.bind_blob(e,n,r):r===null?t.bind_null(e,n):typeof r==`bigint`?t.bind_int64(e,n,r):r===void 0?27:(console.warn(`unknown binding converted to null`,r),t.bind_null(e,n))}},t.bind_blob=(function(){let t=`sqlite3_bind_blob`,r=e.cwrap(t,...Q(`nnnnn:n`));return function(i,a,o){f(i);let s=o.byteLength??o.length,c=e._sqlite3_malloc(s);e.HEAPU8.subarray(c).set(o);let l=r(i,a,c,s,n);return p(t,l,d.get(i))}})(),t.bind_parameter_count=(function(){let t=e.cwrap(`sqlite3_bind_parameter_count`,...Q(`n:n`));return function(e){return f(e),t(e)}})(),t.bind_double=(function(){let t=`sqlite3_bind_double`,n=e.cwrap(t,...Q(`nnn:n`));return function(e,r,i){f(e);let a=n(e,r,i);return p(t,a,d.get(e))}})(),t.bind_int=(function(){let t=`sqlite3_bind_int`,n=e.cwrap(t,...Q(`nnn:n`));return function(e,r,i){if(f(e),i>2147483647||i<-2147483648)return 25;let a=n(e,r,i);return p(t,a,d.get(e))}})(),t.bind_int64=(function(){let t=`sqlite3_bind_int64`,n=e.cwrap(t,...Q(`nnnn:n`));return function(e,r,i){if(f(e),i>qr||i<Jr)return 25;let a=i&4294967295n,o=i>>32n,s=n(e,r,Number(a),Number(o));return p(t,s,d.get(e))}})(),t.bind_null=(function(){let t=`sqlite3_bind_null`,n=e.cwrap(t,...Q(`nn:n`));return function(e,r){f(e);let i=n(e,r);return p(t,i,d.get(e))}})(),t.bind_parameter_name=(function(){let t=e.cwrap(`sqlite3_bind_parameter_name`,...Q(`n:s`));return function(e,n){return f(e),t(e,n)}})(),t.bind_text=(function(){let t=`sqlite3_bind_text`,r=e.cwrap(t,...Q(`nnnnn:n`));return function(e,i,a){f(e);let s=o(a),c=r(e,i,s,-1,n);return p(t,c,d.get(e))}})(),t.changes=(function(){let t=e.cwrap(`sqlite3_changes`,...Q(`n:n`));return function(e){return u(e),t(e)}})(),t.clear_bindings=(function(){let t=`sqlite3_clear_bindings`,n=e.cwrap(t,...Q(`n:n`));return function(e){f(e);let r=n(e);return p(t,r,d.get(e))}})(),t.last_insert_id=(function(){let t=e.cwrap(`sqlite3_last_insert_rowid`,...Q(`n:n`));return function(e){return u(e),t(e)}})(),t.close=(function(){let t=`sqlite3_close`,n=e.cwrap(t,...Q(`n:n`),{async:Zr});return async function(e){u(e);let r=await n(e);return l.delete(e),p(t,r,e)}
99})(),t.column=function(n,r){f(n);let i=t.column_type(n,r);switch(i){case 4:return t.column_blob(n,r);case 2:return t.column_double(n,r);case 1:let a=t.column_int(n,r),o=e.getTempRet0();return c(a,o);case 5:return null;case 3:return t.column_text(n,r);default:throw new Xr(`unknown type`,i)}},t.column_blob=(function(){let n=e.cwrap(`sqlite3_column_blob`,...Q(`nn:n`));return function(r,i){f(r);let a=t.column_bytes(r,i),o=n(r,i);return e.HEAPU8.subarray(o,o+a)}})(),t.column_bytes=(function(){let t=e.cwrap(`sqlite3_column_bytes`,...Q(`nn:n`));return function(e,n){return f(e),t(e,n)}})(),t.column_count=(function(){let t=e.cwrap(`sqlite3_column_count`,...Q(`n:n`));return function(e){return f(e),t(e)}})(),t.column_double=(function(){let t=e.cwrap(`sqlite3_column_double`,...Q(`nn:n`));return function(e,n){return f(e),t(e,n)}})(),t.column_int=(function(){let t=e.cwrap(`sqlite3_column_int64`,...Q(`nn:n`));return function(e,n){return f(e),t(e,n)}})(),t.column_int64=(function(){let t=e.cwrap(`sqlite3_column_int64`,...Q(`nn:n`));return function(n,r){return f(n),s(t(n,r),e.getTempRet0())}})(),t.column_name=(function(){let t=e.cwrap(`sqlite3_column_name`,...Q(`nn:s`));return function(e,n){return f(e),t(e,n)}})(),t.column_names=function(e){let n=[],r=t.column_count(e);for(let i=0;i<r;++i)n.push(t.column_name(e,i));return n},t.column_text=(function(){let t=e.cwrap(`sqlite3_column_text`,...Q(`nn:s`));return function(e,n){return f(e),t(e,n)}})(),t.column_type=(function(){let t=e.cwrap(`sqlite3_column_type`,...Q(`nn:n`));return function(e,n){return f(e),t(e,n)}})(),t.create_function=function(t,n,r,i,a,o,s,c){u(t);function l(t){return t instanceof Yr?(async(n,r,i)=>t(n,e.HEAP32.subarray(i/4,i/4+r))):((n,r,i)=>t(n,e.HEAP32.subarray(i/4,i/4+r)))}return p(`sqlite3_create_function`,e.create_function(t,n,r,i,a,o&&l(o),s&&l(s),c),t)},t.data_count=(function(){let t=e.cwrap(`sqlite3_data_count`,...Q(`n:n`));return function(e){return f(e),t(e)}})(),t.exec=async function(e,n,r){for await(let i of t.statements(e,n)){let e;for(;await t.step(i)===100;)r&&(e??=t.column_names(i),await r(t.row(i),e))}return 0},t.finalize=(function(){let t=e.cwrap(`sqlite3_finalize`,...Q(`n:n`),{async:Zr});return async function(e){let n=await t(e);return d.delete(e),n}})(),t.get_autocommit=(function(){let t=e.cwrap(`sqlite3_get_autocommit`,...Q(`n:n`));return function(e){return t(e)}})(),t.libversion=(function(){let t=e.cwrap(`sqlite3_libversion`,...Q(`:s`));return function(){return t()}})(),t.libversion_number=(function(){let t=e.cwrap(`sqlite3_libversion_number`,...Q(`:n`));return function(){return t()}})(),t.limit=(function(){let t=e.cwrap(`sqlite3_limit`,...Q(`nnn:n`));return function(e,n,r){return t(e,n,r)}})(),t.open_v2=(function(){let t=`sqlite3_open_v2`,n=e.cwrap(t,...Q(`snnn:n`),{async:Zr});return async function(r,a,s){a||=6,s=o(s);try{let o=await m(()=>n(r,i[0],a,s)),c=e.getValue(i[0],`*`);return l.add(c),e.ccall(`RegisterExtensionFunctions`,`number`,[`number`],[c]),p(t,o),c}finally{e._sqlite3_free(s)}}})(),t.progress_handler=function(t,n,r,i){u(t),e.progress_handler(t,n,r,i)},t.reset=(function(){let t=`sqlite3_reset`,n=e.cwrap(t,...Q(`n:n`),{async:Zr});return async function(e){f(e);let r=await n(e);return p(t,r,d.get(e))}})(),t.result=function(e,n){switch(typeof n){case`number`:n===(n|0)?t.result_int(e,n):t.result_double(e,n);break;case`string`:t.result_text(e,n);break;default:if(n instanceof Uint8Array||Array.isArray(n))t.result_blob(e,n);else if(n===null)t.result_null(e);else if(typeof n==`bigint`)return t.result_int64(e,n);else console.warn(`unknown result converted to null`,n),t.result_null(e)}},t.result_blob=(function(){let t=e.cwrap(`sqlite3_result_blob`,...Q(`nnnn:n`));return function(r,i){let a=i.byteLength??i.length,o=e._sqlite3_malloc(a);e.HEAPU8.subarray(o).set(i),t(r,o,a,n)}})(),t.result_double=(function(){let t=e.cwrap(`sqlite3_result_double`,...Q(`nn:n`));return function(e,n){t(e,n)}})(),t.result_int=(function(){let t=e.cwrap(`sqlite3_result_int`,...Q(`nn:n`));return function(e,n){t(e,n)}})(),t.result_int64=(function(){let t=e.cwrap(`sqlite3_result_int64`,...Q(`nnn:n`));return function(e,n){if(n>qr||n<Jr)return 25;let r=n&4294967295n,i=n>>32n;t(e,Number(r),Number(i))}})(),t.result_null=(function(){let t=e.cwrap(`sqlite3_result_null`,...Q(`n:n`));return function(e){t(e)}})(),t.result_text=(function(){let t=e.cwrap(`sqlite3_result_text`,...Q(`nnnn:n`));return function(e,r){let i=o(r);t(e,i,-1,n)}})(),t.row=function(n){let r=[],i=t.data_count(n);for(let a=0;a<i;++a){let i=t.column(n,a);
99r.push(i?.buffer===e.HEAPU8.buffer?i.slice():i)}return r},t.set_authorizer=function(t,n,r){u(t);function i(t,n,r,i,a,o){return[t,n,e.UTF8ToString(r),e.UTF8ToString(i),e.UTF8ToString(a),e.UTF8ToString(o)]}function a(e){return e instanceof Yr?(async(t,n,r,a,o,s)=>e(...i(t,n,r,a,o,s))):((t,n,r,a,o,s)=>e(...i(t,n,r,a,o,s)))}return p(`sqlite3_set_authorizer`,e.set_authorizer(t,a(n),r),t)},t.sql=(function(){let t=e.cwrap(`sqlite3_sql`,...Q(`n:s`));return function(e){return f(e),t(e)}})(),t.statements=function(n,r,i={}){let o=e.cwrap(`sqlite3_prepare_v3`,`number`,[`number`,`number`,`number`,`number`,`number`,`number`],{async:!0});return(async function*(){let s=[];try{let c=a.encode(r),l=c.byteLength-c.byteLength%4+12,u=e._sqlite3_malloc(l),f=u+c.byteLength+1;s.push(()=>e._sqlite3_free(u)),e.HEAPU8.set(c,u),e.HEAPU8[f-1]=0;let h=u+l-8,g=u+l-4,_;function v(){_&&!i.unscoped&&t.finalize(_),_=0}s.push(v),e.setValue(g,u,`*`);do{v();let t=e.getValue(g,`*`),r=await m(()=>o(n,t,f-g,i.flags||0,h,g));r!==0&&p(`sqlite3_prepare_v3`,r,n),_=e.getValue(h,`*`),_&&(d.set(_,n),yield _)}while(_)}finally{for(;s.length;)s.pop()()}})()},t.step=(function(){let t=`sqlite3_step`,n=e.cwrap(t,...Q(`n:n`),{async:Zr});return async function(e){f(e);let r=await m(()=>n(e));return p(t,r,d.get(e),[100,101])}})(),t.commit_hook=function(t,n){u(t),e.commit_hook(t,n)},t.update_hook=function(t,n){u(t);function r(t,n,r,i,a){return[t,e.UTF8ToString(n),e.UTF8ToString(r),s(i,a)]}function i(e){return e instanceof Yr?(async(t,n,i,a,o)=>e(...r(t,n,i,a,o))):((t,n,i,a,o)=>e(...r(t,n,i,a,o)))}e.update_hook(t,i(n))},t.value=function(n){let r=t.value_type(n);switch(r){case 4:return t.value_blob(n);case 2:return t.value_double(n);case 1:let i=t.value_int(n),a=e.getTempRet0();return c(i,a);case 5:return null;case 3:return t.value_text(n);default:throw new Xr(`unknown type`,r)}},t.value_blob=(function(){let n=e.cwrap(`sqlite3_value_blob`,...Q(`n:n`));return function(r){let i=t.value_bytes(r),a=n(r);return e.HEAPU8.subarray(a,a+i)}})(),t.value_bytes=(function(){let t=e.cwrap(`sqlite3_value_bytes`,...Q(`n:n`));return function(e){return t(e)}})(),t.value_double=(function(){let t=e.cwrap(`sqlite3_value_double`,...Q(`n:n`));return function(e){return t(e)}})(),t.value_int=(function(){let t=e.cwrap(`sqlite3_value_int64`,...Q(`n:n`));return function(e){return t(e)}})(),t.value_int64=(function(){let t=e.cwrap(`sqlite3_value_int64`,...Q(`n:n`));return function(n){return s(t(n),e.getTempRet0())}})(),t.value_text=(function(){let t=e.cwrap(`sqlite3_value_text`,...Q(`n:s`));return function(e){return t(e)}})(),t.value_type=(function(){let t=e.cwrap(`sqlite3_value_type`,...Q(`n:n`));return function(e){return t(e)}})(),t.vfs_register=function(t,n){return p(`sqlite3_vfs_register`,e.vfs_register(t,n))};function p(t,n,r=null,i=[0]){if(i.includes(n))return n;throw new Xr(r?e.ccall(`sqlite3_errmsg`,`string`,[`number`],[r]):t,n)}async function m(t){let n;for(let r=0;r<2;++r){if(e.retryOps.length)try{await Promise.all(e.retryOps)}finally{e.retryOps=[]}if(n=await t(),n===0||e.retryOps.length===0){if(e.pendingOps.length)try{await Promise.all(e.pendingOps)}catch(e){return console.error(`Error in pendingOps:`,e),e.code||1}finally{e.pendingOps=[]}return n}}return n}return t}function Q(e){let t=[],n=e.match(/([ns@]*):([nsv@])/);switch(n[2]){case`n`:t.push(`number`);break;case`s`:t.push(`string`);break;case`v`:t.push(null)}let r=[];for(let e of n[1])switch(e){case`n`:r.push(`number`);break;case`s`:r.push(`string`)}return t.push(r),t}var $r=class{options;_sqliteAPI=null;db=0;constructor(e){this.options=e}get isOpen(){return this.db!=0}
99async init(){let e=this._sqliteAPI=await this.openSQLiteAPI();if(this.db=await e.open_v2(this.options.dbFilename,this.options.isReadOnly?1:6),await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`),this.options.encryptionKey){let e=this.options.encryptionKey.replaceAll(`'`,`''`);await this.executeRaw(`PRAGMA key = '${e}';`)}await this.executeRaw(`PRAGMA cache_size = -${this.options.cacheSizeKb};`),await this.executeRaw(`SELECT powersync_update_hooks('install');`)}async openSQLiteAPI(){let{module:e,vfs:t}=await _r(this.options);t.mxPathname=128;let n=Qr(e);if(n.vfs_register(t,!0),e.ccall(`powersync_init_static`,`int`,[]),this.options.encryptionKey&&e.ccall(`sqlite3mc_vfs_create`,`int`,[`string`,`int`],[this.options.dbFilename,1])!==0)throw Error(`Failed to create multiple cipher vfs, Database encryption will not work`);return n}requireSqlite(){if(!this._sqliteAPI)throw Error(`Initialization has not completed`);return this._sqliteAPI}isAutoCommit(){return this.requireSqlite().get_autocommit(this.db)!=0}async execute(e,t){let n=await this.executeSingleStatementRaw(e,t);return this.wrapQueryResults(this.requireSqlite(),n)}async executeBatch(e,t){let n=[],r=this.requireSqlite();for await(let i of r.statements(this.db,e)){let e;for(let a of t){let t=await this.stepThroughStatement(r,i,a,e,!1);n.push(this.wrapQueryResults(r,t))}break}return n}wrapQueryResults(e,t){return{changes:e.changes(this.db),lastInsertRowId:e.last_insert_id(this.db),autocommit:e.get_autocommit(this.db)!=0,resultSet:t}}async executeSingleStatementRaw(e,t){let n=await this.executeRaw(e,t);return n.length?n[0]:void 0}async executeRaw(e,t){let n=[],r=this.requireSqlite();for await(let i of r.statements(this.db,e)){let e,a=await this.stepThroughStatement(r,i,t??[],e);if(e=a.columns,e.length&&n.push(a),t)break}return n}async stepThroughStatement(e,t,n,r,i=!0){n.forEach((e,t,n)=>{typeof e==`boolean`&&(n[t]=+!!e)}),e.reset(t),n&&e.bind_collection(t,n);let a=[];for(;await e.step(t)===100;)if(i){let n=e.row(t);a.push(n)}return r??=e.column_names(t),{columns:r,rows:a}}async close(){this.isOpen&&(await this.requireSqlite().close(this.db),this.db=0)}},ei=class{inner;leaseMutex;constructor(e,t){this.inner=e,this.leaseMutex=t?null:new C}get options(){return this.inner.options}acquireMutex(e){return this.leaseMutex?this.leaseMutex.acquire(e):new Promise((t,n)=>{let r={signal:e};navigator.locks.request(`db-lock-${this.options.dbFilename}`,r,e=>new Promise(e=>t(()=>{e()}))).catch(n)})}unsafeUseInner(){return this.inner}async acquireConnection(e){let t=await this.acquireMutex(e),n=new ti(t,this.inner);try{this.inner.requireSqlite(),this.inner.isAutoCommit()||await this.inner.executeRaw(`ROLLBACK`)}catch(e){throw t(),e}return n}async close(){let e=await this.acquireMutex();try{await this.inner.close()}finally{e()}}},ti=class{returnMutex;connection;useMutex=new C;closed=!1;constructor(e,t){this.returnMutex=e,this.connection=t}async returnLease(){await this.useMutex.runExclusive(async()=>{this.closed||(this.closed=!0,this.returnMutex())})}async use(e){return await this.useMutex.runExclusive(async()=>{if(this.closed)throw Error(`lease token has already been closed`);return await e(this.connection)})}},ni=`open-wasqlite-db`,ri=class{logger;activeDatabases=new Map;constructor(e){this.logger=e}async handleConnection(e){return this.logger.setLevel(e.logLevel),lr(await this.openConnectionLocally(e,e.lockName))}async connectToExisting(e,t){return Rn().request(ni,async()=>{let n=this.activeDatabases.get(e);if(n==null)throw Error(`connectToExisting(${e}) failed because the worker doesn't own a database with that name.`);return lr(await n.connect(t))})}async openConnectionLocally(e,t){let n;for(let t=0;t<2;t++)try{n=await this.databaseOpenAttempt(e)}catch(e){this.logger.warn(`Attempt ${t+1} of 3 to open database failed, retrying in 1 second...`,e),await new Promise(e=>setTimeout(e,1e3))}return n??=await this.databaseOpenAttempt(e),n.connect(t)}async databaseOpenAttempt(e){return Rn().request(ni,async()=>{let{dbFilename:t,isReadOnly:n,vfs:r}=e,i=this.activeDatabases.get(t);if(i==null){let a=!(ii||n||r==Z.InMemoryVfs),o=new $r(e),s=new ei(o,a),c=await s.acquireMutex();try{await o.init()}catch(e){throw c(),await o.close(),e}c(),i=new kr({inner:s,logger:this.logger,onClose:()=>this.activeDatabases.delete(t)}),this.activeDatabases.set(t,i)}return i})}closeAll(){let e=[...this.activeDatabases.values()];return Promise.all(e.map(e=>{e.forceClose()}))}},ii=`SharedWorkerGlobalScope`in globalThis,ai=class extends k{options;config;#e;#t=new AbortController;#n;constructor(e,t){super(),this.options=e,this.config=t,this.#e={connection:e.connection,notifyRemoteClosed:e.remoteCanCloseUnexpectedly?new AbortController:void 0,traceQuer
99ies:t.debugMode===!0};let{port1:n,port2:r}=new MessageChannel;e.connection.setUpdateListener(cr(n,[n])),this.#n=r,r.onmessage=e=>{let t={tables:e.data,groupedUpdates:{},rawUpdates:[]};this.iterateListeners(e=>{e.tablesUpdated&&e.tablesUpdated(t)})}}get name(){return this.config.dbFilename}markRemoteClosed(){this.#e.notifyRemoteClosed.abort()}async close(){this.#t.abort(),this.#n.close(),await ci(this.#e,e=>e.close(),!0),this.options.onClose?.(),this.options.source?.[Hn]()}readLock(e,t){return this.#r(!1,e,t)}writeLock(e,t){return this.#r(!0,e,t)}async#r(e,t,n){let r=await ci(this.#e,t=>t.requestAccess(e,n?.timeoutMs));try{return await t(new si(this.#e,r))}finally{await ci(this.#e,e=>e.completeAccess(r))}}async refreshSchema(){}async shareConnection(){let e=this.#t,t=this.options.source;if(t==null)throw Error(`shareConnection() is only available for connections based by workers.`);return await new Promise((t,n)=>navigator.locks.request(`shared-connection-${this.name}-${Date.now()}-${Math.round(Math.random()*1e4)}`,{signal:e.signal},async()=>{t(),!e.signal.aborted&&await new Promise(t=>{e.signal.addEventListener(`abort`,()=>{t()})})}).catch(e=>{e.name==`AbortError`?t():n(e)})),{port:await t[Vn](),identifier:this.name}}getConfiguration(){return this.config}},oi=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async maybeTrace(e,t){if(this.#e.traceQueries){let n=performance.now(),r=t();try{let t=await ci(this.#e,e);return performance.measure(`[SQL] ${r}`,{start:n}),t}catch(e){throw performance.measure(`[SQL] [ERROR: ${e.message}] ${r}`,{start:n}),e}}return ci(this.#e,e)}async execute(e,t){let n=await this.#n(e,t),r;if(n.resultSet){let e=n.resultSet;function t(t){let n={};return e.columns.forEach((e,r)=>n[e]=t[r]),n}let i=e.rows.map(t);r={_array:i,length:i.length,item:e=>i[e]}}return{rowsAffected:n.changes,insertId:n.lastInsertRowId,rows:r}}async executeRaw(e,t){return(await this.#n(e,t)).resultSet?.rows??[]}async#n(e,t){return this.maybeTrace(n=>n.execute(this.#t,e,t),()=>e)}async executeBatch(e,t=[]){let n=await this.maybeTrace(n=>n.executeBatch(this.#t,e,t),()=>`${e} (batch of ${t.length})`),r={insertId:void 0,rowsAffected:0};for(let e of n)r.insertId=e.lastInsertRowId,r.rowsAffected+=e.changes;return r}},si=class extends T(oi){};async function ci(e,t,n=!1){let r=e.notifyRemoteClosed;return r?new Promise((i,a)=>{if(r.signal.aborted&&(a(new Pn(`Called operation on closed remote`)),!n))return;function o(){a(new Pn(`Remote peer closed with request in flight`))}function s(e){r.signal.removeEventListener(`abort`,o),e()}r.signal.addEventListener(`abort`,o),t(e.connection).then(e=>s(()=>i(e))).catch(e=>s(()=>a(e)))}):t(e.connection)}function li(e){return new Promise((t,n)=>{let r={signal:e};Rn().request(`tab-close-signal-${crypto.randomUUID()}`,r,n=>(t(n.name),new Promise(t=>{e&&e.addEventListener(`abort`,()=>t())}))).catch(n)})}var ui=class{name;state;resolvedWriter;pendingListeners=new Set;constructor(e,t){this.name=t,this.state=e.then(e=>{for(let t of this.pendingListeners)t.closeAfterRegisteredOnResolvedPool=e.writer.registerListener(t.listener);return this.pendingListeners.clear(),this.resolvedWriter=e.writer,e.additionalReaders.length?fi(e.writer,e.additionalReaders):di(e.writer)})}
99async init(){await this.state}async close(){await(await this.state).close()}async readLock(e,t){return(await this.state).withConnection(!0,e,t)}async writeLock(e,t){return(await this.state).withConnection(!1,e,t)}async refreshSchema(){await(await this.state).refreshSchema()}registerListener(e){if(this.resolvedWriter)return this.resolvedWriter.registerListener(e);{let t={listener:e};return this.pendingListeners.add(t),()=>{if(t.closeAfterRegisteredOnResolvedPool)return t.closeAfterRegisteredOnResolvedPool();this.pendingListeners.delete(t)}}}};function di(e){return{writer:e,withConnection:(t,n,r)=>t?e.readLock(n,r):e.writeLock(n,r),close:()=>e.close(),refreshSchema:()=>e.refreshSchema()}}function fi(e,t){let n=new C,r=new ie(t);return{writer:e,async withConnection(t,i,a){let o=new AbortController,s=o.signal,c=null,l;a?.timeoutMs&&(c=setTimeout(()=>o.abort(`requesting database timed out`),a.timeoutMs));try{if(t){let t;return[t,l]=await new Promise((t,i)=>{let a=!1;function c(){a=!0,o.abort()}function l(e,n){a?n():(c(),t([e,n]))}function u(e){a||(c(),i(e))}n.acquire(s).then(t=>l(e,t),u),r.requestOne(s).then(({item:e,release:t})=>l(e,t),u)}),await t.readLock(i)}return await n.runExclusive(()=>e.writeLock(i),s)}finally{c!=null&&clearTimeout(c),l?.()}},async close(){await e.close(),await Promise.all(t.map(e=>e.close()))},async refreshSchema(){await e.refreshSchema(),await Promise.all(t.map(e=>e.refreshSchema()))}}}var pi=class extends fe(ui){async shareConnection(){return(await this.state).writer.shareConnection()}getConfiguration(){if(this.resolvedWriter)return this.resolvedWriter.getConfiguration();throw Error(`AsyncDbAdapter.getConfiguration() can only be called after initializing it.`)}},mi=class{options;resolvedFlags;logger;constructor(e){this.options=e,hi(e),this.resolvedFlags=Er(e.flags),this.logger=e.logger??Ln(`WASQLiteOpenFactory - ${this.options.dbFilename}`)}get waOptions(){return this.options}openAdapter(){return new pi(this.openConnection(),this.options.dbFilename)}openDB(){let{resolvedFlags:{disableSSRWarning:e,enableMultiTabs:t,ssrMode:n=wr()}}=this;return n?(e||this.logger.warn(`
100      Running PowerSync in SSR mode.
101      Only empty query results will be returned.
102      Disable this warning by setting 'disableSSRWarning: true' in options.`),new Or):(t||this.logger.warn(`Multiple tab support is not enabled. Using this site across multiple tabs may not function correctly.`),this.openAdapter())}async openConnection(){let{enableMultiTabs:e,useWebWorker:t}=this.resolvedFlags,{vfs:n=Z.IDBBatchAtomicVFS,temporaryStorage:r=Sr.MEMORY,cacheSizeKb:i=Cr,encryptionKey:a}=this.waOptions;e||this.logger.warn(`Multiple tabs are not enabled in this browser`);let o=e=>({dbFilename:this.options.dbFilename,dbLocation:this.options.dbLocation,debugMode:this.options.debugMode,vfs:n,temporaryStorage:r,cacheSizeKb:i,flags:this.resolvedFlags,encryptionKey:a,isReadOnly:e}),s,c=[],l=mr(n);if(t){let t=this.options.worker,u=async n=>{let o=typeof t==`function`?br(()=>t({...this.options,temporaryStorage:r,cacheSizeKb:i,flags:this.resolvedFlags,encryptionKey:a}),this.logger):yr(this.options.dbFilename,e,t,this.waOptions.vfs,this.logger),s=Zn(o),c=new AbortController;return new ai({connection:await s.connect({...n,logLevel:this.logger.getLevel(),lockName:await li(c.signal)}),source:s,remoteCanCloseUnexpectedly:!1,onClose:()=>{c.abort(),o instanceof Worker?o.terminate():o.close()}},{...n,requiresPersistentTriggers:l})};if(s=await u(o(!1)),n==Z.OPFSWriteAheadVFS){let e=this.options.additionalReaders??1;for(let t=0;t<e;t++){let e=await u(o(!0));c.push(e)}}}else{let e=new ri(this.logger);l=!0;let t=o(!1);s=new ai({connection:await e.openConnectionLocally(t),source:null,remoteCanCloseUnexpectedly:!1},{...t,requiresPersistentTriggers:l})}return{writer:s,additionalReaders:c}}};function hi(e){if(`vfs`in e&&`flags`in e){let{vfs:t,flags:n={}}=e;if(t&&mr(t)&&`useWebWorker`in n&&!n.useWebWorker)throw Error(`Invalid configuration: The 'useWebWorker' flag must be true when using an OPFS-based VFS (${t}).`)}if(e.dbFilename.length>112)throw Error(`dbFilename too long (max length is 112)`)}var gi=class extends k{syncMutex;crudMutex;isConnected;lastSyncedAt;syncStatus;constructor(e){super(),this.syncMutex=new C,this.crudMutex=new C,this.syncStatus=new O({}),this.isConnected=!1}obtainLock(e){return(e.type==pn.CRUD?this.crudMutex:this.syncMutex).runExclusive(e.callback,e.signal)}async connect(e){}async dispose(){}async disconnect(){}async waitForReady(){}async waitForStatus(e){return this.waitUntilStatusMatches(()=>!1)}waitUntilStatusMatches(e){return new Promise(()=>{})}async getWriteCheckpoint(){return`1`}async hasCompletedSync(){return!1}triggerCrudUpload(){}updateSubscriptions(){}markConnectionMayHaveChanged(){}},_i=class{};function vi(e){return e??=navigator,[yi(e),bi(e)].filter(e=>e!=null)}function yi(e){let t=e.userAgentData?.brands;if(t!=null)for(let{name:e,value:n}of[{name:`Google Chrome`,value:`Chrome`},{name:`Opera`,value:`Opera`},{name:`Edge`,value:`Edge`},{name:`Chromium`,value:`Chromium`}]){let r=t.find(t=>t.brand==e);if(r!=null)return`${n}/${r.version}`}let n=e.userAgent;for(let{re:e,value:t}of[{re:/(?:firefox|fxios)\/(\d+)/i,value:`Firefox`},{re:/(?:edg|edge|edga|edgios)\/(\d+)/i,value:`Edge`},{re:/opr\/(\d+)/i,value:`Opera`},{re:/(?:chrome|chromium|crios)\/(\d+)/i,value:`Chrome`},{re:/version\/(\d+).*safari/i,value:`Safari`}]){let r=e.exec(n);if(r!=null)return`${t}/${r[1]}`}return null}function bi(e){if(e.userAgentData?.platform!=null)return e.userAgentData.platform.toLowerCase();let t=e.userAgent;for(let{re:e,value:n}of[{re:/windows/i,value:`windows`},{re:/android/i,value:`android`},{re:/linux/i,value:`linux`},{re:/iphone|ipad|ipod/i,value:`ios`},{re:/macintosh|mac os x/i,value:`macos`}])if(e.test(t))return n;return null}var xi=class extends sn{getFetch(){return fetch.bind(globalThis)}},Si=class extends ln{connector;logger;constructor(e,t=an,n){super(e,t,{...n??{},fetchImplementation:n?.fetchImplementation??new xi}),this.connector=e,this.logger=t}getUserAgent(){let e=[super.getUserAgent(),`powersync-web`];try{e.push(...vi())}catch(e){this.logger.warn(`Failed to get user agent info`,e)}return e.join(` `)}},Ci=class extends yn{constructor(e){super(e)}get webOptions(){return this.options}async obtainLock(e){let t=`streaming-sync-${e.type}-${this.webOptions.identifier}`;return e.type==pn.SYNC&&this.logger.debug(`requesting lock for `,t),Rn().request(t,{signal:e.signal},e.callback)}},wi;(function(e){e.CLOSE_CLIENT=`close-client`,e.CLOSE_ACK=`close-ack`})(wi||={});var Ti=class extends _i{options;statusChanged;webDB;constructor(e,t,n){super(),this.options=e,this.statusChanged=t,this.webDB=n}async getDBWorkerPort(){let{port:e}=await this.webDB.shareConnection();return cr(e,[e])}
102invalidateCredentials(){this.options.remote.invalidateCredentials()}async fetchCredentials(){let e=await this.options.remote.getCredentials();return e==null?null:{endpoint:e.endpoint,token:e.token}}async uploadCrud(){await this.options.uploadCrud()}get logger(){return this.options.logger}trace(...e){this.logger?.trace(...e)}debug(...e){this.logger?.debug(...e)}info(...e){this.logger?.info(...e)}log(...e){this.logger?.log(...e)}warn(...e){this.logger?.warn(...e)}error(...e){this.logger?.error(...e)}time(e){this.logger?.time(e)}timeEnd(e){this.logger?.timeEnd(e)}},Ei=class extends Ci{syncManager;clientProvider;messagePort;isInitialized;dbAdapter;abortOnClose=new AbortController;constructor(e){super(e),this.dbAdapter=e.db;let t={dbFilename:this.options.identifier,temporaryStorage:Sr.MEMORY,cacheSizeKb:Cr,...e,flags:Er(e.flags)},n=e.sync?.worker;this.messagePort=n?typeof n==`function`?this.workerPort(n(t)):this.workerPort(new SharedWorker(`${n}`,{name:`shared-sync-${this.webOptions.identifier}`})):this.workerPort(new SharedWorker(new URL(`/assets/SharedSyncImplementation.worker-DX4A4_p6.js`,``+import.meta.url),{name:`shared-sync-${this.webOptions.identifier}`,type:`module`})),this.clientProvider=new Ti(this.webOptions,e=>{this.updateSyncStatus(e)},e.db),this.syncManager=Zn(this.messagePort),Jn(this.clientProvider,this.messagePort),this.syncManager.setLogLevel(this.logger.getLevel()),this.triggerCrudUpload=this.syncManager.triggerCrudUpload,this.isInitialized=this._init()}workerPort(e){return vr(e,this.logger),e.port}async _init(){let e=await li(this.abortOnClose.signal);await this.syncManager.addLockBasedCloseSignal(e);let{crudUploadThrottleMs:t,identifier:n,retryDelayMs:r}=this.options,i={...this.webOptions.flags,workers:void 0};await this.syncManager.setParams({dbParams:this.dbAdapter.getConfiguration(),streamOptions:{crudUploadThrottleMs:t,identifier:n,retryDelayMs:r,flags:i}},this.options.subscriptions)}async connect(e){return await this.waitForReady(),this.syncManager.connect(e)}async disconnect(){return await this.waitForReady(),this.syncManager.disconnect()}async getWriteCheckpoint(){return await this.waitForReady(),this.syncManager.getWriteCheckpoint()}async dispose(){await this.waitForReady(),await new Promise(e=>{this.messagePort.addEventListener(`message`,t=>{t.data?.event===wi.CLOSE_ACK&&e()});let t={event:wi.CLOSE_CLIENT,data:{}};this.messagePort.postMessage(t)}),await super.dispose(),this.abortOnClose.abort(),this.syncManager[Hn](),this.messagePort.close()}async waitForReady(){return this.isInitialized}updateSubscriptions(e){this.syncManager.updateSubscriptions(e)}},Di={...Tr,externallyUnload:!1},Oi=e=>({...Di,...e,...Er(e)});function ki(e){if(`database`in e&&`encryptionKey`in e){let{database:t}=e;if(Fe(t)||Ie(t))throw Error(`Invalid configuration: 'encryptionKey' should only be included inside the database object when using a custom ${Fe(t)?`WASQLiteOpenFactory`:`WASQLiteDBAdapter`} constructor.`)}}var Ai=class e extends jn{options;static SHARED_MUTEX=new C;resolvedFlags;constructor(e){super(e),this.options=e,ki(e),this.resolvedFlags=Oi(e.flags)}async _initialize(){this.database instanceof pi&&await this.database.init(),typeof this.database.getConfiguration==`function`&&this.database.getConfiguration().requiresPersistentTriggers&&this.triggersImpl.updateDefaults({useStorageByDefault:!0})}generateTriggerManagerConfig(){return{claimManager:zn}}openDBAdapter(e){return new mi({...e.database,flags:Oi(e.flags),encryptionKey:e.encryptionKey}).openDB()}close(e){return super.close({disconnect:e?.disconnect??!this.resolvedFlags.enableMultiTabs})}async loadVersion(){if(!wr())return super.loadVersion()}async resolveOfflineSyncStatus(){if(!wr())return super.resolveOfflineSyncStatus()}generateBucketStorageAdapter(){return new Nn(this.database)}async runExclusive(t){return this.resolvedFlags.ssrMode?e.SHARED_MUTEX.runExclusive(t):Rn().request(`lock-${this.database.name}`,t)}generateSyncStreamImplementation(e,t){let n=new Si(e,this.logger),r={...this.options,...t,flags:this.resolvedFlags,adapter:this.bucketStorageAdapter,remote:n,uploadCrud:async()=>{await this.waitForReady(),await e.uploadData(this)},identifier:this.database.name,logger:this.logger};switch(!0){case this.resolvedFlags.ssrMode:return new gi(r);case this.resolvedFlags.enableMultiTabs:if(!this.resolvedFlags.broadcastLogs){let e=`
103            Multiple tabs are enabled, but broadcasting of logs is disabled.
104            Logs for shared sync worker will only be available in the shared worker context
105          `,t=this.options.logger;t?t.warn(e):console.warn(e)}return new Ei({...r,db:this.database});default:return new Ci(r)}}},$=e(r(),1),ji=$.createContext(null),Mi=()=>$.useContext(ji),Ni=()=>{let e=(0,$.useContext)(ji),[t,n]=(0,$.useState)(e.currentStatus);return(0,$.useEffect)(()=>{let t=e.registerListener({statusChanged:e=>{n(e)}});return()=>t?.()},[e]),t},Pi=(e,t)=>{let n;try{n=e.compile()}catch{return!1}let r=n,i=e.stringifiedParameters??JSON.stringify(r.parameters),a=JSON.stringify(t),o=$.useRef({sqlStatement:r.sql,stringifiedParams:i,stringifiedOptions:a});return o.current.sqlStatement!==r.sql||o.current.stringifiedParams!=i||o.current.stringifiedOptions!=a?(o.current.sqlStatement=r.sql,o.current.stringifiedParams=i,o.current.stringifiedOptions=a,!0):!1},Fi=(e,t=[],n)=>{let r=Mi(),i=$.useMemo(()=>JSON.stringify(t),[t]),a=$.useMemo(()=>typeof e==`string`?{compile:()=>({sql:e,parameters:t}),execute:()=>r.getAll(e,t),stringifiedParameters:i}:{compile:()=>{let t=e.compile();return{sql:t.sql,parameters:[...t.parameters]}},execute:()=>e.execute()},[e,r,i]);return{parsedQuery:a,queryChanged:Pi(a,n)}},Ii=()=>Ni();function Li(e){let t=Mi(),n=Ii(),r=(0,$.useMemo)(()=>JSON.stringify(e),[e]),i=(0,$.useMemo)(()=>e.map(e=>({stream:t.syncStream(e.name,e.parameters??void 0),options:e})),[r]);return(0,$.useEffect)(()=>{let e=!0,t=[];for(let n of i)n.stream.subscribe(n.options).then(n=>{e?t.push(n):n.unsubscribe()});return()=>{e=!1;for(let e of t)e.unsubscribe()}},[r]),(0,$.useMemo)(()=>i.map(e=>n.forStream(e.stream)??null),[n,r])}function Ri(e,t){let n=Li(t??[]);return!t||t.every((e,t)=>!e.waitForStream||n[t]?.subscription?.hasSynced===!0)}var zi=e=>{let{query:t,powerSync:n,queryChanged:r,active:i}=e,[a,o]=$.useState({isLoading:!0,isFetching:!0,data:[],error:void 0}),s=$.useCallback(async e=>{o(e=>({...e,isLoading:!0,isFetching:!0,error:void 0}));try{let r=t.compile(),i=await t.execute({sql:r.sql,parameters:[...r.parameters],db:n});if(e.aborted)return;o(e=>({...e,isLoading:!1,isFetching:!1,data:i,error:void 0}))}catch(e){o(t=>({...t,isLoading:!1,isFetching:!1,data:[],error:e}))}},[r,t]);return $.useEffect(()=>{if(i){let e=new AbortController;return s(e.signal),()=>{e.abort()}}},[n,i,r]),{...a,refresh:s}},Bi=e=>{let[t,n]=$.useState(e?.state);return $.useEffect(()=>{if(e)return n(e.state),e.registerListener({onStateChange:e=>{n({...e})}})},[e]),t},Vi=e=>{let{query:t,powerSync:n,queryChanged:r,options:i,active:a}=e;function o(){return a?i.rowComparator?n.customQuery(t).differentialWatch({rowComparator:i.rowComparator,reportFetching:i.reportFetching,throttleMs:i.throttleMs}):n.customQuery(t).watch({reportFetching:i.reportFetching,throttleMs:i.throttleMs}):null}let[s,c]=$.useState(o),l=$.useRef(null);$.useEffect(()=>{s?.close();let e=o();return c(e),()=>{l.current?.(),e?.close()}},[n,a]),r&&(s?.updateSettings({query:t,throttleMs:i.throttleMs,reportFetching:i.reportFetching}),l.current?.(),l.current=s?.registerListener({settingsWillUpdate:()=>{l.current?.(),l.current=null}}));let u=(i.reportFetching??!0)&&!!l.current,d=Bi(s);return{data:d?.data??[],isLoading:d?.isLoading??!0,error:d?.error,isFetching:d?.isFetching||u}};function Hi(e,t=[],n={}){let r=Mi();if(!r)return{...Ui,isLoading:!1,error:Error(`PowerSync not configured.`)};let{parsedQuery:i,queryChanged:a}=Fi(e,t,n),o=Ri(r,n?.streams),s=n?.runQueryOnce==1,c=zi({query:i,powerSync:r,queryChanged:a,active:s&&o}),l=Vi({query:i,powerSync:r,queryChanged:a,options:{reportFetching:n.reportFetching,rowComparator:n.rowComparator},active:!s&&o});return o?(s?c:l)??Ui:{...Ui}}var Ui={isLoading:!0,isFetching:!1,data:[],error:void 0};export{C as A,Wr as C,vn as D,fe as E,ae as F,s as I,r as L,mn as M,ee as N,pn as O,p as P,zr as S,k as T,Rr as _,Ai as a,Ur as b,Gr as c,Mr as d,Nr as f,Lr as g,Ir as h,Mi as i,Fn as j,xn as k,Ar as l,Fr as m,Ii as n,Si as o,Pr as p,ji as r,Kr as s,Hi as t,jr as u,Br as v,yn as w,Vr as x,Hr as y};
106//# sourceMappingURL=powersync-BACnHPWX.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.