@xuzhiyang/syncvar 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,10 @@ WaterBear SDK 提供一套基于 WebSocket 的变量同步、锁、RPC、事件
13
13
  - 🚀 **MessagePack** - 高效二进制传输格式,减少 30-50% 数据量
14
14
  - 🛠️ **Worker 执行** - 远程代码执行能力
15
15
 
16
+ ## 在线演示
17
+
18
+ 访问 [在线演示地址](https://varserver.popx.com/waterbear/syncvar.html) 查看 SDK 实时交互效果。
19
+
16
20
  ## 安装
17
21
 
18
22
  ```bash
package/dist/syncvar.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! Waterbear v1.1.2 (2026-02-09T12:06:36.478Z)
1
+ /*! Waterbear v1.1.3 (2026-02-09T12:20:43.200Z)
2
2
  该SDK提供一套基于 WebSocket 的变量同步、锁、RPC 与事件订阅能力,帮助前端快速搭建协同编辑、状态共享与后台任务管理场景。
3
3
  主页: https://varserver.popx.com
4
4
  */
@@ -11,8 +11,8 @@
11
11
 
12
12
  // 版本信息模块
13
13
  class VersionInfo {
14
- static Version = "1.1.2"; // 由构建时注入
15
- static BuildTime = "2026-02-09T12:06:36.478Z";
14
+ static Version = "1.1.3"; // 由构建时注入
15
+ static BuildTime = "2026-02-09T12:20:43.200Z";
16
16
  static printInfo() {
17
17
  globalThis.console.group('%c📦 Waterbear Info', 'color: #35495e; font-size: 14px;');
18
18
  // 只在开发环境显示调试信息
@@ -1,5 +1,5 @@
1
- /*! Waterbear v1.1.2 (2026-02-09T12:06:36.478Z)
1
+ /*! Waterbear v1.1.3 (2026-02-09T12:20:43.200Z)
2
2
  该SDK提供一套基于 WebSocket 的变量同步、锁、RPC 与事件订阅能力,帮助前端快速搭建协同编辑、状态共享与后台任务管理场景。
3
3
  主页: https://varserver.popx.com
4
4
  */
5
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).WaterBear={})}(this,function(t){"use strict";class e{static Version="1.1.2";static BuildTime="2026-02-09T12:06:36.478Z";static printInfo(){globalThis.console.group("%c📦 Waterbear Info","color: #35495e; font-size: 14px;"),globalThis.console.log(`%cVersion: v${e.Version}`,"color: #41b883;"),globalThis.console.groupEnd()}}e.printInfo();const s=new TextEncoder;function i(t,e,i){t.length>50?function(t,e,i){s.encodeInto(t,e.subarray(i))}(t,e,i):function(t,e,s){const i=t.length;let r=s,n=0;for(;n<i;){let s=t.charCodeAt(n++);if(4294967168&s){if(4294965248&s){if(s>=55296&&s<=56319&&n<i){const e=t.charCodeAt(n);56320==(64512&e)&&(++n,s=((1023&s)<<10)+(1023&e)+65536)}4294901760&s?(e[r++]=s>>18&7|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128):(e[r++]=s>>12&15|224,e[r++]=s>>6&63|128)}else e[r++]=s>>6&31|192;e[r++]=63&s|128}else e[r++]=s}}(t,e,i)}function r(t,e,s){let i=e;const r=i+s,n=[];let h="";for(;i<r;){const e=t[i++];if(128&e)if(192==(224&e)){const s=63&t[i++];n.push((31&e)<<6|s)}else if(224==(240&e)){const s=63&t[i++],r=63&t[i++];n.push((31&e)<<12|s<<6|r)}else if(240==(248&e)){let s=(7&e)<<18|(63&t[i++])<<12|(63&t[i++])<<6|63&t[i++];s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s)}else n.push(e);else n.push(e);n.length>=4096&&(h+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(h+=String.fromCharCode(...n)),h}const n=new TextDecoder;function h(t,e,s){return s>200?function(t,e,s){const i=t.subarray(e,e+s);return n.decode(i)}(t,e,s):r(t,e,s)}class o{type;data;constructor(t,e){this.type=t,this.data=e}}class c extends Error{constructor(t){super(t);const e=Object.create(c.prototype);Object.setPrototypeOf(this,e),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:c.name})}}const a=4294967295;function f(t,e,s){const i=Math.floor(s/4294967296),r=s;t.setUint32(e,i),t.setUint32(e+4,r)}function l(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}const u={type:-1,encode:function(t){if(t instanceof Date){return function({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=17179869183){if(0===e&&t<=4294967295){const e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t),e}{const s=t/4294967296,i=4294967295&t,r=new Uint8Array(8),n=new DataView(r.buffer);return n.setUint32(0,e<<2|3&s),n.setUint32(4,i),r}}{const s=new Uint8Array(12),i=new DataView(s.buffer);return i.setUint32(0,e),f(i,4,t),s}}(function(t){const e=t.getTime(),s=Math.floor(e/1e3),i=1e6*(e-1e3*s),r=Math.floor(i/1e9);return{sec:s+r,nsec:i-1e9*r}}(t))}return null},decode:function(t){const e=function(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0);return{sec:4294967296*(3&t)+e.getUint32(4),nsec:t>>>2}}case 12:return{sec:l(e,4),nsec:e.getUint32(0)};default:throw new c(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}(t);return new Date(1e3*e.sec+e.nsec/1e6)}};class w{static defaultCodec=new w;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(u)}register({type:t,encode:e,decode:s}){if(t>=0)this.encoders[t]=e,this.decoders[t]=s;else{const i=-1-t;this.builtInEncoders[i]=e,this.builtInDecoders[i]=s}}tryToEncode(t,e){for(let s=0;s<this.builtInEncoders.length;s++){const i=this.builtInEncoders[s];if(null!=i){const r=i(t,e);if(null!=r){return new o(-1-s,r)}}}for(let s=0;s<this.encoders.length;s++){const i=this.encoders[s];if(null!=i){const r=i(t,e);if(null!=r){return new o(s,r)}}}return t instanceof o?t:null}decode(t,e,s){const i=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return i?i(t,e,s):new o(e,t)}}function d(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):function(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}(t)?new Uint8Array(t):Uint8Array.from(t)}class y{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??w.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??100,this.initialBufferSize=t?.initialBufferSize??2048,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new y({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered){return this.clone().encodeSharedRef(t)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered){return this.clone().encode(t)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,e){if(e>this.maxDepth)throw new Error(`Too deep objects in depth ${e}`);null==t?this.encodeNil():"boolean"==typeof t?this.encodeBoolean(t):"number"==typeof t?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):"string"==typeof t?this.encodeString(t):this.useBigInt64&&"bigint"==typeof t?this.encodeBigInt64(t):this.encodeObject(t,e)}ensureBufferSizeToWrite(t){const e=this.pos+t;this.view.byteLength<e&&this.resizeBuffer(2*e)}resizeBuffer(t){const e=new ArrayBuffer(t),s=new Uint8Array(e),i=new DataView(e);s.set(this.bytes),this.view=i,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(t){!1===t?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too long string: ${t} bytes in UTF-8`);this.writeU8(219),this.writeU32(t)}}encodeString(t){const e=function(t){const e=t.length;let s=0,i=0;for(;i<e;){let r=t.charCodeAt(i++);if(4294967168&r)if(4294965248&r){if(r>=55296&&r<=56319&&i<e){const e=t.charCodeAt(i);56320==(64512&e)&&(++i,r=((1023&r)<<10)+(1023&e)+65536)}s+=4294901760&r?4:3}else s+=2;else s++}return s}(t);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),i(t,this.bytes,this.pos),this.pos+=e}encodeObject(t,e){const s=this.extensionCodec.tryToEncode(t,this.context);if(null!=s)this.encodeExtension(s);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else{if("object"!=typeof t)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`);this.encodeMap(t,e)}}encodeBinary(t){const e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too large binary: ${e}`);this.writeU8(198),this.writeU32(e)}const s=d(t);this.writeU8a(s)}encodeArray(t,e){const s=t.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else{if(!(s<4294967296))throw new Error(`Too large array: ${s}`);this.writeU8(221),this.writeU32(s)}for(const s of t)this.doEncode(s,e+1)}countWithoutUndefined(t,e){let s=0;for(const i of e)void 0!==t[i]&&s++;return s}encodeMap(t,e){const s=Object.keys(t);this.sortKeys&&s.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(t,s):s.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else{if(!(i<4294967296))throw new Error(`Too large map object: ${i}`);this.writeU8(223),this.writeU32(i)}for(const i of s){const s=t[i];this.ignoreUndefined&&void 0===s||(this.encodeString(i),this.doEncode(s,e+1))}}encodeExtension(t){if("function"==typeof t.data){const e=t.data(this.pos+6),s=e.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);return this.writeU8(201),this.writeU32(s),this.writeI8(t.type),void this.writeU8a(e)}const e=t.data.length;if(1===e)this.writeU8(212);else if(2===e)this.writeU8(213);else if(4===e)this.writeU8(214);else if(8===e)this.writeU8(215);else if(16===e)this.writeU8(216);else if(e<256)this.writeU8(199),this.writeU8(e);else if(e<65536)this.writeU8(200),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too large extension object: ${e}`);this.writeU8(201),this.writeU32(e)}this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){const e=t.length;this.ensureBufferSizeToWrite(e),this.bytes.set(t,this.pos),this.pos+=e}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),function(t,e,s){const i=s/4294967296,r=s;t.setUint32(e,i),t.setUint32(e+4,r)}(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),f(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}function p(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const m="array",g="map_key",E="map_value",b=t=>{if("string"==typeof t||"number"==typeof t)return t;throw new c("The type of key must be string or number but "+typeof t)};class S{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){const e=this.getUninitializedStateFromPool();e.type=m,e.position=0,e.size=t,e.array=new Array(t)}pushMapState(t){const e=this.getUninitializedStateFromPool();e.type=g,e.readCount=0,e.size=t,e.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===m){const e=t;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(t.type===g||t.type===E){const e=t;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const v=new DataView(new ArrayBuffer(0)),$=new Uint8Array(v.buffer);try{v.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const x=new RangeError("Insufficient data"),k=new class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=16,e=16){this.maxKeyLength=t,this.maxLengthPerKey=e,this.caches=[];for(let t=0;t<this.maxKeyLength;t++)this.caches.push([])}canBeCached(t){return t>0&&t<=this.maxKeyLength}find(t,e,s){const i=this.caches[s-1];t:for(const r of i){const i=r.bytes;for(let r=0;r<s;r++)if(i[r]!==t[e+r])continue t;return r.str}return null}store(t,e){const s=this.caches[t.length-1],i={bytes:t,str:e};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=i:s.push(i)}decode(t,e,s){const i=this.find(t,e,s);if(null!=i)return this.hit++,i;this.miss++;const n=r(t,e,s),h=Uint8Array.prototype.slice.call(t,e,e+s);return this.store(h,n),n}};class T{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=v;bytes=$;headByte=-1;stack=new S;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??w.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??a,this.maxBinLength=t?.maxBinLength??a,this.maxArrayLength=t?.maxArrayLength??a,this.maxMapLength=t?.maxMapLength??a,this.maxExtLength=t?.maxExtLength??a,this.keyDecoder=void 0!==t?.keyDecoder?t.keyDecoder:k,this.mapKeyConverter=t?.mapKeyConverter??b}clone(){return new T({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(t){const e=d(t);this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.pos=0}appendBuffer(t){if(-1!==this.headByte||this.hasRemaining(1)){const e=this.bytes.subarray(this.pos),s=d(t),i=new Uint8Array(e.length+s.length);i.set(e),i.set(s,e.length),this.setBuffer(i)}else this.setBuffer(t)}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){const{view:e,pos:s}=this;return new RangeError(`Extra ${e.byteLength-s} of ${e.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered){return this.clone().decode(t)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);const e=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return e}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){const e=this.clone();return void(yield*e.decodeMulti(t))}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered){return this.clone().decodeAsync(t)}try{this.entered=!0;let e,s=!1;for await(const i of t){if(s)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(i);try{e=this.doDecodeSync(),s=!0}catch(t){if(!(t instanceof RangeError))throw t}this.totalPos+=this.pos}if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}const{headByte:i,pos:r,totalPos:n}=this;throw new RangeError(`Insufficient data in parsing ${p(i)} at ${n} (${r} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,e){if(this.entered){const s=this.clone();return void(yield*s.decodeMultiAsync(t,e))}try{this.entered=!0;let s=e,i=-1;for await(const r of t){if(e&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(r),s&&(i=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),0!==--i;);}catch(t){if(!(t instanceof RangeError))throw t}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){t:for(;;){const t=this.readHeadByte();let e;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){const s=t-128;if(0!==s){this.pushMapState(s),this.complete();continue t}e={}}else if(t<160){const s=t-144;if(0!==s){this.pushArrayState(s),this.complete();continue t}e=[]}else{const s=t-160;e=this.decodeString(s,0)}else if(192===t)e=null;else if(194===t)e=!1;else if(195===t)e=!0;else if(202===t)e=this.readF32();else if(203===t)e=this.readF64();else if(204===t)e=this.readU8();else if(205===t)e=this.readU16();else if(206===t)e=this.readU32();else if(207===t)e=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===t)e=this.readI8();else if(209===t)e=this.readI16();else if(210===t)e=this.readI32();else if(211===t)e=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===t){const t=this.lookU8();e=this.decodeString(t,1)}else if(218===t){const t=this.lookU16();e=this.decodeString(t,2)}else if(219===t){const t=this.lookU32();e=this.decodeString(t,4)}else if(220===t){const t=this.readU16();if(0!==t){this.pushArrayState(t),this.complete();continue t}e=[]}else if(221===t){const t=this.readU32();if(0!==t){this.pushArrayState(t),this.complete();continue t}e=[]}else if(222===t){const t=this.readU16();if(0!==t){this.pushMapState(t),this.complete();continue t}e={}}else if(223===t){const t=this.readU32();if(0!==t){this.pushMapState(t),this.complete();continue t}e={}}else if(196===t){const t=this.lookU8();e=this.decodeBinary(t,1)}else if(197===t){const t=this.lookU16();e=this.decodeBinary(t,2)}else if(198===t){const t=this.lookU32();e=this.decodeBinary(t,4)}else if(212===t)e=this.decodeExtension(1,0);else if(213===t)e=this.decodeExtension(2,0);else if(214===t)e=this.decodeExtension(4,0);else if(215===t)e=this.decodeExtension(8,0);else if(216===t)e=this.decodeExtension(16,0);else if(199===t){const t=this.lookU8();e=this.decodeExtension(t,1)}else if(200===t){const t=this.lookU16();e=this.decodeExtension(t,2)}else{if(201!==t)throw new c(`Unrecognized type byte: ${p(t)}`);{const t=this.lookU32();e=this.decodeExtension(t,4)}}this.complete();const s=this.stack;for(;s.length>0;){const t=s.top();if(t.type===m){if(t.array[t.position]=e,t.position++,t.position!==t.size)continue t;e=t.array,s.release(t)}else{if(t.type===g){if("__proto__"===e)throw new c("The key __proto__ is not allowed");t.key=this.mapKeyConverter(e),t.type=E;continue t}if(t.map[t.key]=e,t.readCount++,t.readCount!==t.size){t.key=null,t.type=g;continue t}e=t.map,s.release(t)}}return e}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:if(t<160)return t-144;throw new c(`Unrecognized array type byte: ${p(t)}`)}}pushMapState(t){if(t>this.maxMapLength)throw new c(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new c(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,e){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,e):this.decodeBinary(t,e)}decodeUtf8String(t,e){if(t>this.maxStrLength)throw new c(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+e+t)throw x;const s=this.pos+e;let i;return i=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(t)?this.keyDecoder.decode(this.bytes,s,t):h(this.bytes,s,t),this.pos+=e+t,i}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===g}return!1}decodeBinary(t,e){if(t>this.maxBinLength)throw new c(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+e))throw x;const s=this.pos+e,i=this.bytes.subarray(s,s+t);return this.pos+=e+t,i}decodeExtension(t,e){if(t>this.maxExtLength)throw new c(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);const s=this.view.getInt8(this.pos+e),i=this.decodeBinary(t,e+1);return this.extensionCodec.decode(i,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){const t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){const t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){const t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){const t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){const t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){const t=(e=this.view,s=this.pos,4294967296*e.getUint32(s)+e.getUint32(s+4));var e,s;return this.pos+=8,t}readI64(){const t=l(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){const t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){const t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){const t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){const t=this.view.getFloat64(this.pos);return this.pos+=8,t}}const U=Object.freeze({JsonString:0,MessagePack:1});function A(t,e,s,i){if(!t)throw new Error("obj is empty");if(!e?.length)throw new Error("path is empty");return s={s:"set",d:"del",S:"SET",D:"DEL"}[s]||s,function t(e,r){const n=r.shift();if(0===r.length){switch(s){case"set":case"SET":e[n]=i;break;case"del":delete e[n];break;case"DEL":e.splice(Number(n),1);break;default:throw new Error(`Invalid type: ${s}`)}return!0}if(!e[n]){const t="SET"===s||"DEL"===s;1===r.length&&t?e[n]=[]:e[n]={}}return t(e[n],r)}(t,e.slice())}const B=new class{constructor(){this.i=new Map,this.h=0}call(t,{timeout:e=1e4,data:s}={}){if(!t)throw new Error("未指定回调函数");return new Promise((i,r)=>{const n=++this.h,h=setTimeout(()=>{this.i.delete(n),r(new Error("Promise等待超时"))},e);this.i.set(n,{resolve:i,reject:r,timeoutId:h,data:s}),t(n)})}process(t,{result:e,error:s}){const i=this.i.get(t);if(!i)return!1;clearTimeout(i.timeoutId),this.i.delete(t);const{resolve:r,reject:n}=i;return s?n(new Error(s)):r(e),!s}getData(t){const e=this.i.get(t);return e?.data}};class M{constructor({delay:t=50}={}){this.o=new Map,this.l=new Set,this.u=t,this.m=!1,this.$=new Map,this.k=null,this.T=new Map}get ws(){return this.U}get id(){return this.U?.id}async bind(t){if(this.U===t)return this;if(!t?.bind)throw new Error("请绑定WebSocketClient创建的连接实例");if(this.U=t,t.bind(this),this.o.size){const t=Array.from(this.o.keys());await B.call(e=>{this.A({SyncVar:{$sync:{pid:e,names:t}}})},{data:{names:t}})}return this.T.size&&await B.call(t=>{const e=Array.from(this.T.keys());this.A({SyncVar:{$bind:{pid:t,names:e}}})}),this}close(){this.U=null}destroy(){if(this.m)return;this.m=!0;const t=new Error("SyncVar已销毁");this.l.forEach(({reject:e})=>e(t)),this.o.clear(),this.l.clear(),this.U=null}async waitUpdated(){if(this.m)throw new Error("SyncVar已销毁,无法执行锁定");return new Promise((t,e)=>this.l.add({resolve:t,reject:e}))}async rpcBind(t){if("function"!=typeof t)throw new Error("rpcBind 回调必须是函数");const e=t.name;if(!e)throw new Error("rpcBind 回调必须指定名称,不能使用匿名函数");if(this.T.has(e))throw new Error(`已存在同名函数: ${e}`);return this.T.set(e,t),B.call(t=>{this.A({SyncVar:{$bind:{pid:t,names:[e]}}})})}async rpcCall(t,e){if(!t)throw new Error("rpcCall 参数错误:name 不能为空");return B.call(s=>{this.A({SyncVar:{$call:{pid:s,name:t,args:e}}})})}onMessage(t){const{SyncVar:e}=t;if(e)try{const{$sync:t,$set:s,$update:i,$lock:r,$bind:n,$call:h,$callRet:o}=e;t&&this.B(t),s&&this.M(s),i&&this.j(i),r&&this._(r),n&&this.I(n),h&&this.V(h),o&&this.L(o)}catch(t){}}static O(t){if("function"==typeof globalThis.structuredClone)return globalThis.structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch(e){return t}}static R(t){return Object.keys(t).filter(e=>"function"!=typeof t[e])}static W(t,e){if(Object.is(t,e))return!0;if(!t||!e)return!1;const s=M.R(t),i=M.R(e);return s.length===i.length&&(0===s.length?t===e:s.every(s=>t[s]===e[s]))}static N(t,e){if(M.W(t,e))return!1;const s=M.R(t);for(const e of s)delete t[e];return Object.assign(t,e),!0}static P(t){let e=[],s=!1;function i(){if(0===e.length)return;const s=e;e=[],t(s)}return{push(t){e.push(t),s||(s=!0,Promise.resolve().then(()=>{s=!1,i()}))},flush:i}}async sync(t,e){if(this.m)throw new Error("SyncVar已销毁,无法执行同步");if("string"==typeof t&&(t=[t]),!t?.length)throw new Error("names不能为空");if(!this.U||this.U.readyState!==WebSocket.OPEN)throw new Error("WebSocket未连接");const s=t.filter(t=>!this.o.has(t)),{reset:i}=e||{};if(i&&t.forEach(t=>{const e=i[t];void 0!==e&&(this[t]=e)}),!s.length){const e={};return t.forEach(t=>{const s=this.o.get(t);if(!s)throw new Error("变量异常:"+t);e[t]=s.proxy}),e}return B.call(t=>{this.A({SyncVar:{$sync:{pid:t,names:s,...e}}})},{data:{names:t}})}B({datas:t,pid:e,error:s}){t?.forEach(({name:t,value:e})=>{let s=this.o.get(t);s?s.setValue(e):(s=this.C(t,e),this.o.set(t,s))});const i=B.getData(e),r={};i?.names?.forEach(t=>{const e=this.o.get(t);if(!e)throw new Error("同步变量异常:"+t);r[t]=e.proxy}),B.process(e,{result:r,error:s})}M({error:t,lockeds:e}){e?.forEach(({name:t,value:e})=>{const s=this.o.get(t);s&&s.setValue(e)}),this.l.forEach(({resolve:e,reject:s})=>{t?s("数据写入失败:"+t):e()}),this.l.clear()}_({name:t,value:e,promiseIds:s,error:i}){const r=this.o.get(t);r&&(r.setValue(e),r.setLocked());let n=!1;s?.forEach(e=>{let s;r?s=r.proxy:i=i||"找不到变量:"+t,B.process(e,{result:s,error:i})&&(n=!0)}),n||(r?.unlock(),this.A({SyncVar:{$unlock:{name:t}}}))}j({vars:t}){t?.forEach(({name:t,value:e,changes:s})=>{const i=this.o.get(t);i&&(s?i.setDiffs(s):i.setValue(e))})}I({pid:t,error:e}){B.process(t,{error:e})}async V({pid:t,name:e,args:s}){try{const i=this.T.get(e);if(!i)throw new Error(`函数不存在: ${e}`);const r=await i(s);this.A({SyncVar:{$callRet:{pid:t,name:e,result:r}}})}catch(e){this.A({SyncVar:{$callRet:{pid:t,error:e.message||e}}})}}L({pid:t,result:e,error:s}){B.process(t,{result:e,error:s})}F(t,e){this.$.has(t)||this.$.set(t,[]);const s=this.$.get(t);e.forEach(t=>{const{type:e,path:i}=t;for(let t=s.length-1;t>=0;t--){const{path:e}=s[t];i.every((t,s)=>e[s]===t)&&s.splice(t,1)}s.push(t)}),this.k||(this.k=setTimeout(()=>{if(this.k=null,!this.$.size)return;const t=[];if(this.$.forEach((e,s)=>{if(!e.length)return;const i=this.o.get(s);if(!i)return;const r={set:"s",del:"d",SET:"S",DEL:"D"},n=e.map(({type:t,path:e,val:s})=>({t:r[t],p:e,v:s})),h=JSON.stringify(n).length,o=JSON.stringify(i.value).length;if(h>=o){t.push({name:s,value:i.value})}else t.push({name:s,changes:n});i.unlock()}),!t.length)return;const e={diffs:t};this.l.size>0&&(e.receipt=!0),this.A({SyncVar:{$set:e}}),this.$.clear()},this.u))}C(t,e){const s=this,i=new WeakMap;let r,n=!1;const h=M.P(e=>{this.F(t,e)});const o=function t(e,s=[]){if("object"!=typeof e||null===e)return e;if(i.has(e))return i.get(e);const r=new Proxy(e,{get(e,i,r){const n=Reflect.get(e,i,r);return"function"==typeof n&&(t=>t instanceof Set||t instanceof Map)(e)?n.bind(e):t(n,s.concat(i))},set(t,e,i,r){const n=t[e];return!!M.W(n,i)||(h.push({type:Array.isArray(t)?"SET":"set",path:s.concat(e),val:M.O(i)}),Reflect.set(t,e,i,r))},deleteProperty:(t,e)=>(h.push({type:Array.isArray(t)?"DEL":"del",path:s.concat(e)}),Reflect.deleteProperty(t,e))});return i.set(e,r),r}(e);return Object.defineProperty(o,"lock",{value:async({timeout:e}={})=>{if(s.m)throw new Error("SyncVar已销毁,无法执行锁定");return n?o:B.call(e=>{s.A({SyncVar:{$lock:{promiseId:e,name:t}}})},{timeout:e})}}),Object.defineProperty(o,"unlock",{value:async()=>{if(s.m)throw new Error("SyncVar已销毁,无法执行锁定");if(n){n=!1;try{s.A({SyncVar:{$unlock:{name:t}}})}catch(t){}}}}),Object.defineProperty(o,"watch",{value:t=>{if("function"!=typeof t)throw new Error("watch 回调必须是函数");r=t}}),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>o,set(t){M.N(o,t)}}),{proxy:o,value:e,setLocked(){n=!0},unlock(){n=!1},setValue(s){M.N(e,s);try{r?.(e,t)}catch(t){}},setDiffs(s){s.forEach(({t:t,p:s,v:i})=>A(e,s,t,i));try{r?.(e,t)}catch(t){}}}}A(t){try{if(!this.U||this.U.readyState!==WebSocket.OPEN)throw new Error("WebSocket未连接");"function"==typeof this.U.sendMsg?this.U.sendMsg(t):"function"==typeof this.U.send&&this.U.send(JSON.stringify(t))}catch(t){}}}const j="https://varserver.popx.com";class _{constructor({host:t=j,namespace:e="",onError:s=null}={}){this.J=t,this.K=e,this.H=new Map,this.q=new Map,this.Z=s||(t=>{}),this.G=null,this.X=[],this.Y=null,this.tt=1e3,this.et=null,this.st=!1,this.it=null}static emit(t,e,{host:s=j,namespace:i=""}={}){const r=new URLSearchParams;i&&r.append("namespace",i);return async function(t,e){const s=await fetch(t,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}}),i=await s.json();if(i.err)throw new Error(i.err);return i}(`${s}/api/emit?${r.toString()}`,{event:t,data:e})}async rt(){if("undefined"!=typeof window&&"undefined"!=typeof document){if(!window.EventSource)throw new Error("EventSource is not supported in this browser");return window.EventSource}try{const t=await import("eventsource"),{EventSource:e}=t.default||t;return e}catch(t){throw new Error("Failed to import eventsource module. Make sure it is installed: npm install eventsource")}}async nt(){if(!this.Y)throw new Error("vars 和 events 不能同时为空");if(this.it)return this.it;const t=await this.rt();if(this.G&&this.G.readyState===t.OPEN)return this;const{varNames:e,eventNames:s}=this.Y,i=new URLSearchParams;this.K&&i.append("namespace",this.K),e.length&&i.append("vars",e),s.length&&i.append("events",s);const r=new t(`${this.J}/sse/syncvar?${i.toString()}`);return this.G=r,this.st=!1,this.ht(r),this.ot(r),this.it=new Promise((t,e)=>{let s=!1;r.onopen=()=>{s||(s=!0,this.tt=1e3,this.ct(),this.it=null,t(this))},r.onerror=()=>{const t=new Error("SSE 连接错误");if(this.Z(t),!s)return s=!0,this.it=null,void e(t);this.st||(this.it=null,this.ft())},r.onmessage=({data:t})=>this.Z(new Error("sseWatch 未处理消息: "+t))}),this.it}ht(t){t.addEventListener("$sync",t=>{try{const e=JSON.parse(t.data||"{}"),{name:s,value:i,changes:r}=e||{};if(!s)throw new Error("名字为空: "+t.data);let n=this.H.get(s);if(r){if(!n||"object"!=typeof n)throw new Error("数据为空或不可变更: "+t.data);r.forEach(({t:t,p:e,v:s})=>A(n,e,t,s))}else{if(void 0===i)throw new Error("值为空: "+t.data);n=i,this.H.set(s,n)}const h=this.q.get(s);if(h)try{h({name:s,value:n})}catch(t){this.Z(t)}else{const e=this.q.get("$all");if(!e)throw new Error("SSE 未处理消息: "+t.data);try{e({name:s,value:n})}catch(t){this.Z(t)}}}catch(t){this.Z(t)}})}ot(t){if(this.X.length)for(const{name:e,fn:s}of this.X)t.addEventListener(e,s)}ft(){this.st||this.et||(this.et=setTimeout(async()=>{this.et=null;try{this.G?.close(),this.G=null,await this.nt()}catch(t){this.Z(t),this.ft()}},this.tt),this.tt=Math.min(3e4,2*this.tt))}ct(){this.et&&(clearTimeout(this.et),this.et=null)}close(){this.st=!0,this.ct(),this.it=null;try{this.G?.close()}catch(t){}this.G=null}async watch({vars:t=[],events:e=[]}={}){const s=[],i=[],r=[];if(Array.isArray(t))for(const e of t)if("function"==typeof e){const t=e.name;if(!t)throw new Error("vars 回调必须是有名字的函数");s.push(t),this.q.set(t,e)}else{if("string"!=typeof e)throw new Error("vars 数组元素仅支持 string 或 function");s.push(e)}else{if("object"!=typeof t||null===t)throw new Error("vars 仅支持数组或对象");for(const[e,i]of Object.entries(t)){if("function"!=typeof i)throw new Error(`vars 对象中 "${e}" 的值必须是函数`);s.push(e),this.q.set(e,i)}}if(Array.isArray(e))for(const t of e)if("function"==typeof t){const e=t.name;if(!e)throw new Error("events 回调必须是有名字的函数");i.push(e),r.push({name:e,fn:t})}else{if("string"!=typeof t)throw new Error("events 数组元素仅支持 string 或 function");i.push(t)}else{if("object"!=typeof e||null===e)throw new Error("events 仅支持数组或对象");for(const[t,s]of Object.entries(e)){if("function"!=typeof s)throw new Error(`events 对象中 "${t}" 的值必须是函数`);i.push(t),r.push({name:t,fn:s})}}return this.X=r,this.Y={varNames:s,eventNames:i},this.st=!1,await this.nt(),this}onEvent(t,e,s){if(!this.G)throw new Error("未连接");return this.X.push({name:t,fn:e}),this.G.addEventListener(t,e,s)}offEvent(t,e,s){if(!this.G)throw new Error("未连接");return this.G.removeEventListener(t,e,s)}emit(t,e){return _.emit(t,e,{host:this.J,namespace:this.K})}getAll(){return this.H}get(t){return this.H.get(t)}}t.SSE=_,t.SyncVar=M,t.VersionInfo=e,t.WebSocketClient=async function(...t){let e,s;"string"==typeof arguments[0]?(e=arguments[0],s=arguments[1]):(s=arguments[0],s?.host&&(e=s.host)),e=e||"wss://varserver.popx.com/ws/syncvar";const{namespace:i="",guid:r,onopen:n,onclose:h,onerror:o=t=>{},packFormat:c=U.MessagePack,timeout:a=5e3,maxReconnectCount:f=100}=s||{},l=new Set;let u=0,w=!1;async function d(){return new Promise((t,s)=>{w=!1;const p=new URLSearchParams({namespace:i});let m=new WebSocket(`${e}?${p}`);m.binaryType="arraybuffer",m.lt=!1,m.ut=[],m.sendMsg=(t,{format:e=c}={})=>{var s,i;if(m.readyState===WebSocket.OPEN)try{e===U.MessagePack?m.send((s=t,new y(i).encodeSharedRef(s)),{binary:!0}):m.send(JSON.stringify(t))}catch(t){o?.(t)}else m.ut.push(t)};let g=null;g=setTimeout(()=>{if(!m.lt&&m.readyState===WebSocket.CONNECTING){m.close();const t=new Error("WebSocket connection timeout");o?.(t),s(t),w=!0}},a),m.onopen=t=>{n?.(m,t),function(){const t={namespace:i,guid:r,packFormat:c};m.send(JSON.stringify({$login:t}))}()},m.onmessage=async e=>{try{const{data:i}=e;let r;if("string"==typeof i)r=JSON.parse(i);else{let t;if(t=i instanceof Blob?await i.arrayBuffer():i,c!==U.MessagePack)throw new Error("不支持的消息格式");r=function(t,e){return new T(e).decode(t)}(t)}if(!r||"object"!=typeof r)throw new Error(`Invalid message format: ${i}`);if(r.$error)throw new Error(r.$error.err||"未描述的错误");if(r.$login)return function({id:e,error:i}){if(m.id=e,m.lt=!0,clearTimeout(g),i)return s(i),void(w=!0);u>0&&(l.forEach(t=>t.bind(m)),u=0),m.ut&&m.ut.length&&m.ut.splice(0).forEach(t=>m.sendMsg(t));t(m)}(r.$login);l.forEach(t=>t.onMessage?.(r))}catch(t){o?.(t)}},m.onerror=t=>{if(w)return;clearTimeout(g);const e=t instanceof Error?t:new Error(t?.message||"WebSocket error");o?.(e),m.lt||(s(e),w=!0)},m.onclose=t=>{clearTimeout(g),h?.(t),l.forEach(e=>e.close?.(t)),u<f?function(){const t=Math.min(1e3*2**u,3e4),e=Math.min(Math.floor(t*(.5+.5*Math.random())),3e4);u++,setTimeout(()=>{d().catch(t=>{})},e)}():(l.forEach(e=>e.destroy?.(t)),l.clear())},m.bind=t=>l.has(t)?t:(l.add(t),t.bind(m))})}return d()},t.Worker=class{constructor({onlog:t,onerror:e,onexit:s}={}){this.wt=t,this.dt=e,this.yt=s}async bind(t){if(this.U===t)return this;if(!t?.bind)throw new Error("请绑定WebSocketClient创建的连接实例");return this.U=t,t.bind(this),this}onMessage(t){const{Worker:e}=t;if(e)try{const{$run:t,$kill:s,$attach:i,$lists:r,$log:n,$error:h,$exit:o}=e;t&&this.gt(t),s&&this.gt(s),i&&this.gt(i),r&&this.gt(r),n&&this.wt?.(...n),h&&this.dt?.(h),o&&this.yt?.(o)}catch(t){}}gt({pid:t,error:e,...s}){B.process(t,{error:e,result:{...s}})}async run({code:t,name:e,workerData:s}){return B.call(i=>{this.U.sendMsg({Worker:{$run:{pid:i,code:t,name:e,workerData:s}}})})}async kill({name:t}){return B.call(e=>{this.U.sendMsg({Worker:{$kill:{pid:e,name:t}}})})}async attach({name:t}){return B.call(e=>{this.U.sendMsg({Worker:{$attach:{pid:e,name:t}}})})}async lists(){return B.call(t=>{this.U.sendMsg({Worker:{$lists:{pid:t}}})})}}});
5
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).WaterBear={})}(this,function(t){"use strict";class e{static Version="1.1.3";static BuildTime="2026-02-09T12:20:43.200Z";static printInfo(){globalThis.console.group("%c📦 Waterbear Info","color: #35495e; font-size: 14px;"),globalThis.console.log(`%cVersion: v${e.Version}`,"color: #41b883;"),globalThis.console.groupEnd()}}e.printInfo();const s=new TextEncoder;function i(t,e,i){t.length>50?function(t,e,i){s.encodeInto(t,e.subarray(i))}(t,e,i):function(t,e,s){const i=t.length;let r=s,n=0;for(;n<i;){let s=t.charCodeAt(n++);if(4294967168&s){if(4294965248&s){if(s>=55296&&s<=56319&&n<i){const e=t.charCodeAt(n);56320==(64512&e)&&(++n,s=((1023&s)<<10)+(1023&e)+65536)}4294901760&s?(e[r++]=s>>18&7|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128):(e[r++]=s>>12&15|224,e[r++]=s>>6&63|128)}else e[r++]=s>>6&31|192;e[r++]=63&s|128}else e[r++]=s}}(t,e,i)}function r(t,e,s){let i=e;const r=i+s,n=[];let h="";for(;i<r;){const e=t[i++];if(128&e)if(192==(224&e)){const s=63&t[i++];n.push((31&e)<<6|s)}else if(224==(240&e)){const s=63&t[i++],r=63&t[i++];n.push((31&e)<<12|s<<6|r)}else if(240==(248&e)){let s=(7&e)<<18|(63&t[i++])<<12|(63&t[i++])<<6|63&t[i++];s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s)}else n.push(e);else n.push(e);n.length>=4096&&(h+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(h+=String.fromCharCode(...n)),h}const n=new TextDecoder;function h(t,e,s){return s>200?function(t,e,s){const i=t.subarray(e,e+s);return n.decode(i)}(t,e,s):r(t,e,s)}class o{type;data;constructor(t,e){this.type=t,this.data=e}}class c extends Error{constructor(t){super(t);const e=Object.create(c.prototype);Object.setPrototypeOf(this,e),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:c.name})}}const a=4294967295;function f(t,e,s){const i=Math.floor(s/4294967296),r=s;t.setUint32(e,i),t.setUint32(e+4,r)}function l(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}const u={type:-1,encode:function(t){if(t instanceof Date){return function({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=17179869183){if(0===e&&t<=4294967295){const e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t),e}{const s=t/4294967296,i=4294967295&t,r=new Uint8Array(8),n=new DataView(r.buffer);return n.setUint32(0,e<<2|3&s),n.setUint32(4,i),r}}{const s=new Uint8Array(12),i=new DataView(s.buffer);return i.setUint32(0,e),f(i,4,t),s}}(function(t){const e=t.getTime(),s=Math.floor(e/1e3),i=1e6*(e-1e3*s),r=Math.floor(i/1e9);return{sec:s+r,nsec:i-1e9*r}}(t))}return null},decode:function(t){const e=function(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0);return{sec:4294967296*(3&t)+e.getUint32(4),nsec:t>>>2}}case 12:return{sec:l(e,4),nsec:e.getUint32(0)};default:throw new c(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}(t);return new Date(1e3*e.sec+e.nsec/1e6)}};class w{static defaultCodec=new w;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(u)}register({type:t,encode:e,decode:s}){if(t>=0)this.encoders[t]=e,this.decoders[t]=s;else{const i=-1-t;this.builtInEncoders[i]=e,this.builtInDecoders[i]=s}}tryToEncode(t,e){for(let s=0;s<this.builtInEncoders.length;s++){const i=this.builtInEncoders[s];if(null!=i){const r=i(t,e);if(null!=r){return new o(-1-s,r)}}}for(let s=0;s<this.encoders.length;s++){const i=this.encoders[s];if(null!=i){const r=i(t,e);if(null!=r){return new o(s,r)}}}return t instanceof o?t:null}decode(t,e,s){const i=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return i?i(t,e,s):new o(e,t)}}function d(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):function(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}(t)?new Uint8Array(t):Uint8Array.from(t)}class y{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??w.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??100,this.initialBufferSize=t?.initialBufferSize??2048,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new y({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered){return this.clone().encodeSharedRef(t)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered){return this.clone().encode(t)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,e){if(e>this.maxDepth)throw new Error(`Too deep objects in depth ${e}`);null==t?this.encodeNil():"boolean"==typeof t?this.encodeBoolean(t):"number"==typeof t?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):"string"==typeof t?this.encodeString(t):this.useBigInt64&&"bigint"==typeof t?this.encodeBigInt64(t):this.encodeObject(t,e)}ensureBufferSizeToWrite(t){const e=this.pos+t;this.view.byteLength<e&&this.resizeBuffer(2*e)}resizeBuffer(t){const e=new ArrayBuffer(t),s=new Uint8Array(e),i=new DataView(e);s.set(this.bytes),this.view=i,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(t){!1===t?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too long string: ${t} bytes in UTF-8`);this.writeU8(219),this.writeU32(t)}}encodeString(t){const e=function(t){const e=t.length;let s=0,i=0;for(;i<e;){let r=t.charCodeAt(i++);if(4294967168&r)if(4294965248&r){if(r>=55296&&r<=56319&&i<e){const e=t.charCodeAt(i);56320==(64512&e)&&(++i,r=((1023&r)<<10)+(1023&e)+65536)}s+=4294901760&r?4:3}else s+=2;else s++}return s}(t);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),i(t,this.bytes,this.pos),this.pos+=e}encodeObject(t,e){const s=this.extensionCodec.tryToEncode(t,this.context);if(null!=s)this.encodeExtension(s);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else{if("object"!=typeof t)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`);this.encodeMap(t,e)}}encodeBinary(t){const e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too large binary: ${e}`);this.writeU8(198),this.writeU32(e)}const s=d(t);this.writeU8a(s)}encodeArray(t,e){const s=t.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else{if(!(s<4294967296))throw new Error(`Too large array: ${s}`);this.writeU8(221),this.writeU32(s)}for(const s of t)this.doEncode(s,e+1)}countWithoutUndefined(t,e){let s=0;for(const i of e)void 0!==t[i]&&s++;return s}encodeMap(t,e){const s=Object.keys(t);this.sortKeys&&s.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(t,s):s.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else{if(!(i<4294967296))throw new Error(`Too large map object: ${i}`);this.writeU8(223),this.writeU32(i)}for(const i of s){const s=t[i];this.ignoreUndefined&&void 0===s||(this.encodeString(i),this.doEncode(s,e+1))}}encodeExtension(t){if("function"==typeof t.data){const e=t.data(this.pos+6),s=e.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);return this.writeU8(201),this.writeU32(s),this.writeI8(t.type),void this.writeU8a(e)}const e=t.data.length;if(1===e)this.writeU8(212);else if(2===e)this.writeU8(213);else if(4===e)this.writeU8(214);else if(8===e)this.writeU8(215);else if(16===e)this.writeU8(216);else if(e<256)this.writeU8(199),this.writeU8(e);else if(e<65536)this.writeU8(200),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too large extension object: ${e}`);this.writeU8(201),this.writeU32(e)}this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){const e=t.length;this.ensureBufferSizeToWrite(e),this.bytes.set(t,this.pos),this.pos+=e}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),function(t,e,s){const i=s/4294967296,r=s;t.setUint32(e,i),t.setUint32(e+4,r)}(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),f(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}function p(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const m="array",g="map_key",E="map_value",b=t=>{if("string"==typeof t||"number"==typeof t)return t;throw new c("The type of key must be string or number but "+typeof t)};class S{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){const e=this.getUninitializedStateFromPool();e.type=m,e.position=0,e.size=t,e.array=new Array(t)}pushMapState(t){const e=this.getUninitializedStateFromPool();e.type=g,e.readCount=0,e.size=t,e.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===m){const e=t;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(t.type===g||t.type===E){const e=t;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const v=new DataView(new ArrayBuffer(0)),$=new Uint8Array(v.buffer);try{v.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const x=new RangeError("Insufficient data"),k=new class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=16,e=16){this.maxKeyLength=t,this.maxLengthPerKey=e,this.caches=[];for(let t=0;t<this.maxKeyLength;t++)this.caches.push([])}canBeCached(t){return t>0&&t<=this.maxKeyLength}find(t,e,s){const i=this.caches[s-1];t:for(const r of i){const i=r.bytes;for(let r=0;r<s;r++)if(i[r]!==t[e+r])continue t;return r.str}return null}store(t,e){const s=this.caches[t.length-1],i={bytes:t,str:e};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=i:s.push(i)}decode(t,e,s){const i=this.find(t,e,s);if(null!=i)return this.hit++,i;this.miss++;const n=r(t,e,s),h=Uint8Array.prototype.slice.call(t,e,e+s);return this.store(h,n),n}};class T{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=v;bytes=$;headByte=-1;stack=new S;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??w.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??a,this.maxBinLength=t?.maxBinLength??a,this.maxArrayLength=t?.maxArrayLength??a,this.maxMapLength=t?.maxMapLength??a,this.maxExtLength=t?.maxExtLength??a,this.keyDecoder=void 0!==t?.keyDecoder?t.keyDecoder:k,this.mapKeyConverter=t?.mapKeyConverter??b}clone(){return new T({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(t){const e=d(t);this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.pos=0}appendBuffer(t){if(-1!==this.headByte||this.hasRemaining(1)){const e=this.bytes.subarray(this.pos),s=d(t),i=new Uint8Array(e.length+s.length);i.set(e),i.set(s,e.length),this.setBuffer(i)}else this.setBuffer(t)}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){const{view:e,pos:s}=this;return new RangeError(`Extra ${e.byteLength-s} of ${e.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered){return this.clone().decode(t)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);const e=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return e}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){const e=this.clone();return void(yield*e.decodeMulti(t))}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered){return this.clone().decodeAsync(t)}try{this.entered=!0;let e,s=!1;for await(const i of t){if(s)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(i);try{e=this.doDecodeSync(),s=!0}catch(t){if(!(t instanceof RangeError))throw t}this.totalPos+=this.pos}if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}const{headByte:i,pos:r,totalPos:n}=this;throw new RangeError(`Insufficient data in parsing ${p(i)} at ${n} (${r} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,e){if(this.entered){const s=this.clone();return void(yield*s.decodeMultiAsync(t,e))}try{this.entered=!0;let s=e,i=-1;for await(const r of t){if(e&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(r),s&&(i=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),0!==--i;);}catch(t){if(!(t instanceof RangeError))throw t}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){t:for(;;){const t=this.readHeadByte();let e;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){const s=t-128;if(0!==s){this.pushMapState(s),this.complete();continue t}e={}}else if(t<160){const s=t-144;if(0!==s){this.pushArrayState(s),this.complete();continue t}e=[]}else{const s=t-160;e=this.decodeString(s,0)}else if(192===t)e=null;else if(194===t)e=!1;else if(195===t)e=!0;else if(202===t)e=this.readF32();else if(203===t)e=this.readF64();else if(204===t)e=this.readU8();else if(205===t)e=this.readU16();else if(206===t)e=this.readU32();else if(207===t)e=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===t)e=this.readI8();else if(209===t)e=this.readI16();else if(210===t)e=this.readI32();else if(211===t)e=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===t){const t=this.lookU8();e=this.decodeString(t,1)}else if(218===t){const t=this.lookU16();e=this.decodeString(t,2)}else if(219===t){const t=this.lookU32();e=this.decodeString(t,4)}else if(220===t){const t=this.readU16();if(0!==t){this.pushArrayState(t),this.complete();continue t}e=[]}else if(221===t){const t=this.readU32();if(0!==t){this.pushArrayState(t),this.complete();continue t}e=[]}else if(222===t){const t=this.readU16();if(0!==t){this.pushMapState(t),this.complete();continue t}e={}}else if(223===t){const t=this.readU32();if(0!==t){this.pushMapState(t),this.complete();continue t}e={}}else if(196===t){const t=this.lookU8();e=this.decodeBinary(t,1)}else if(197===t){const t=this.lookU16();e=this.decodeBinary(t,2)}else if(198===t){const t=this.lookU32();e=this.decodeBinary(t,4)}else if(212===t)e=this.decodeExtension(1,0);else if(213===t)e=this.decodeExtension(2,0);else if(214===t)e=this.decodeExtension(4,0);else if(215===t)e=this.decodeExtension(8,0);else if(216===t)e=this.decodeExtension(16,0);else if(199===t){const t=this.lookU8();e=this.decodeExtension(t,1)}else if(200===t){const t=this.lookU16();e=this.decodeExtension(t,2)}else{if(201!==t)throw new c(`Unrecognized type byte: ${p(t)}`);{const t=this.lookU32();e=this.decodeExtension(t,4)}}this.complete();const s=this.stack;for(;s.length>0;){const t=s.top();if(t.type===m){if(t.array[t.position]=e,t.position++,t.position!==t.size)continue t;e=t.array,s.release(t)}else{if(t.type===g){if("__proto__"===e)throw new c("The key __proto__ is not allowed");t.key=this.mapKeyConverter(e),t.type=E;continue t}if(t.map[t.key]=e,t.readCount++,t.readCount!==t.size){t.key=null,t.type=g;continue t}e=t.map,s.release(t)}}return e}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:if(t<160)return t-144;throw new c(`Unrecognized array type byte: ${p(t)}`)}}pushMapState(t){if(t>this.maxMapLength)throw new c(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new c(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,e){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,e):this.decodeBinary(t,e)}decodeUtf8String(t,e){if(t>this.maxStrLength)throw new c(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+e+t)throw x;const s=this.pos+e;let i;return i=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(t)?this.keyDecoder.decode(this.bytes,s,t):h(this.bytes,s,t),this.pos+=e+t,i}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===g}return!1}decodeBinary(t,e){if(t>this.maxBinLength)throw new c(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+e))throw x;const s=this.pos+e,i=this.bytes.subarray(s,s+t);return this.pos+=e+t,i}decodeExtension(t,e){if(t>this.maxExtLength)throw new c(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);const s=this.view.getInt8(this.pos+e),i=this.decodeBinary(t,e+1);return this.extensionCodec.decode(i,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){const t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){const t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){const t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){const t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){const t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){const t=(e=this.view,s=this.pos,4294967296*e.getUint32(s)+e.getUint32(s+4));var e,s;return this.pos+=8,t}readI64(){const t=l(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){const t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){const t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){const t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){const t=this.view.getFloat64(this.pos);return this.pos+=8,t}}const U=Object.freeze({JsonString:0,MessagePack:1});function A(t,e,s,i){if(!t)throw new Error("obj is empty");if(!e?.length)throw new Error("path is empty");return s={s:"set",d:"del",S:"SET",D:"DEL"}[s]||s,function t(e,r){const n=r.shift();if(0===r.length){switch(s){case"set":case"SET":e[n]=i;break;case"del":delete e[n];break;case"DEL":e.splice(Number(n),1);break;default:throw new Error(`Invalid type: ${s}`)}return!0}if(!e[n]){const t="SET"===s||"DEL"===s;1===r.length&&t?e[n]=[]:e[n]={}}return t(e[n],r)}(t,e.slice())}const B=new class{constructor(){this.i=new Map,this.h=0}call(t,{timeout:e=1e4,data:s}={}){if(!t)throw new Error("未指定回调函数");return new Promise((i,r)=>{const n=++this.h,h=setTimeout(()=>{this.i.delete(n),r(new Error("Promise等待超时"))},e);this.i.set(n,{resolve:i,reject:r,timeoutId:h,data:s}),t(n)})}process(t,{result:e,error:s}){const i=this.i.get(t);if(!i)return!1;clearTimeout(i.timeoutId),this.i.delete(t);const{resolve:r,reject:n}=i;return s?n(new Error(s)):r(e),!s}getData(t){const e=this.i.get(t);return e?.data}};class M{constructor({delay:t=50}={}){this.o=new Map,this.l=new Set,this.u=t,this.m=!1,this.$=new Map,this.k=null,this.T=new Map}get ws(){return this.U}get id(){return this.U?.id}async bind(t){if(this.U===t)return this;if(!t?.bind)throw new Error("请绑定WebSocketClient创建的连接实例");if(this.U=t,t.bind(this),this.o.size){const t=Array.from(this.o.keys());await B.call(e=>{this.A({SyncVar:{$sync:{pid:e,names:t}}})},{data:{names:t}})}return this.T.size&&await B.call(t=>{const e=Array.from(this.T.keys());this.A({SyncVar:{$bind:{pid:t,names:e}}})}),this}close(){this.U=null}destroy(){if(this.m)return;this.m=!0;const t=new Error("SyncVar已销毁");this.l.forEach(({reject:e})=>e(t)),this.o.clear(),this.l.clear(),this.U=null}async waitUpdated(){if(this.m)throw new Error("SyncVar已销毁,无法执行锁定");return new Promise((t,e)=>this.l.add({resolve:t,reject:e}))}async rpcBind(t){if("function"!=typeof t)throw new Error("rpcBind 回调必须是函数");const e=t.name;if(!e)throw new Error("rpcBind 回调必须指定名称,不能使用匿名函数");if(this.T.has(e))throw new Error(`已存在同名函数: ${e}`);return this.T.set(e,t),B.call(t=>{this.A({SyncVar:{$bind:{pid:t,names:[e]}}})})}async rpcCall(t,e){if(!t)throw new Error("rpcCall 参数错误:name 不能为空");return B.call(s=>{this.A({SyncVar:{$call:{pid:s,name:t,args:e}}})})}onMessage(t){const{SyncVar:e}=t;if(e)try{const{$sync:t,$set:s,$update:i,$lock:r,$bind:n,$call:h,$callRet:o}=e;t&&this.B(t),s&&this.M(s),i&&this.j(i),r&&this._(r),n&&this.I(n),h&&this.V(h),o&&this.L(o)}catch(t){}}static O(t){if("function"==typeof globalThis.structuredClone)return globalThis.structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch(e){return t}}static R(t){return Object.keys(t).filter(e=>"function"!=typeof t[e])}static W(t,e){if(Object.is(t,e))return!0;if(!t||!e)return!1;const s=M.R(t),i=M.R(e);return s.length===i.length&&(0===s.length?t===e:s.every(s=>t[s]===e[s]))}static N(t,e){if(M.W(t,e))return!1;const s=M.R(t);for(const e of s)delete t[e];return Object.assign(t,e),!0}static P(t){let e=[],s=!1;function i(){if(0===e.length)return;const s=e;e=[],t(s)}return{push(t){e.push(t),s||(s=!0,Promise.resolve().then(()=>{s=!1,i()}))},flush:i}}async sync(t,e){if(this.m)throw new Error("SyncVar已销毁,无法执行同步");if("string"==typeof t&&(t=[t]),!t?.length)throw new Error("names不能为空");if(!this.U||this.U.readyState!==WebSocket.OPEN)throw new Error("WebSocket未连接");const s=t.filter(t=>!this.o.has(t)),{reset:i}=e||{};if(i&&t.forEach(t=>{const e=i[t];void 0!==e&&(this[t]=e)}),!s.length){const e={};return t.forEach(t=>{const s=this.o.get(t);if(!s)throw new Error("变量异常:"+t);e[t]=s.proxy}),e}return B.call(t=>{this.A({SyncVar:{$sync:{pid:t,names:s,...e}}})},{data:{names:t}})}B({datas:t,pid:e,error:s}){t?.forEach(({name:t,value:e})=>{let s=this.o.get(t);s?s.setValue(e):(s=this.C(t,e),this.o.set(t,s))});const i=B.getData(e),r={};i?.names?.forEach(t=>{const e=this.o.get(t);if(!e)throw new Error("同步变量异常:"+t);r[t]=e.proxy}),B.process(e,{result:r,error:s})}M({error:t,lockeds:e}){e?.forEach(({name:t,value:e})=>{const s=this.o.get(t);s&&s.setValue(e)}),this.l.forEach(({resolve:e,reject:s})=>{t?s("数据写入失败:"+t):e()}),this.l.clear()}_({name:t,value:e,promiseIds:s,error:i}){const r=this.o.get(t);r&&(r.setValue(e),r.setLocked());let n=!1;s?.forEach(e=>{let s;r?s=r.proxy:i=i||"找不到变量:"+t,B.process(e,{result:s,error:i})&&(n=!0)}),n||(r?.unlock(),this.A({SyncVar:{$unlock:{name:t}}}))}j({vars:t}){t?.forEach(({name:t,value:e,changes:s})=>{const i=this.o.get(t);i&&(s?i.setDiffs(s):i.setValue(e))})}I({pid:t,error:e}){B.process(t,{error:e})}async V({pid:t,name:e,args:s}){try{const i=this.T.get(e);if(!i)throw new Error(`函数不存在: ${e}`);const r=await i(s);this.A({SyncVar:{$callRet:{pid:t,name:e,result:r}}})}catch(e){this.A({SyncVar:{$callRet:{pid:t,error:e.message||e}}})}}L({pid:t,result:e,error:s}){B.process(t,{result:e,error:s})}F(t,e){this.$.has(t)||this.$.set(t,[]);const s=this.$.get(t);e.forEach(t=>{const{type:e,path:i}=t;for(let t=s.length-1;t>=0;t--){const{path:e}=s[t];i.every((t,s)=>e[s]===t)&&s.splice(t,1)}s.push(t)}),this.k||(this.k=setTimeout(()=>{if(this.k=null,!this.$.size)return;const t=[];if(this.$.forEach((e,s)=>{if(!e.length)return;const i=this.o.get(s);if(!i)return;const r={set:"s",del:"d",SET:"S",DEL:"D"},n=e.map(({type:t,path:e,val:s})=>({t:r[t],p:e,v:s})),h=JSON.stringify(n).length,o=JSON.stringify(i.value).length;if(h>=o){t.push({name:s,value:i.value})}else t.push({name:s,changes:n});i.unlock()}),!t.length)return;const e={diffs:t};this.l.size>0&&(e.receipt=!0),this.A({SyncVar:{$set:e}}),this.$.clear()},this.u))}C(t,e){const s=this,i=new WeakMap;let r,n=!1;const h=M.P(e=>{this.F(t,e)});const o=function t(e,s=[]){if("object"!=typeof e||null===e)return e;if(i.has(e))return i.get(e);const r=new Proxy(e,{get(e,i,r){const n=Reflect.get(e,i,r);return"function"==typeof n&&(t=>t instanceof Set||t instanceof Map)(e)?n.bind(e):t(n,s.concat(i))},set(t,e,i,r){const n=t[e];return!!M.W(n,i)||(h.push({type:Array.isArray(t)?"SET":"set",path:s.concat(e),val:M.O(i)}),Reflect.set(t,e,i,r))},deleteProperty:(t,e)=>(h.push({type:Array.isArray(t)?"DEL":"del",path:s.concat(e)}),Reflect.deleteProperty(t,e))});return i.set(e,r),r}(e);return Object.defineProperty(o,"lock",{value:async({timeout:e}={})=>{if(s.m)throw new Error("SyncVar已销毁,无法执行锁定");return n?o:B.call(e=>{s.A({SyncVar:{$lock:{promiseId:e,name:t}}})},{timeout:e})}}),Object.defineProperty(o,"unlock",{value:async()=>{if(s.m)throw new Error("SyncVar已销毁,无法执行锁定");if(n){n=!1;try{s.A({SyncVar:{$unlock:{name:t}}})}catch(t){}}}}),Object.defineProperty(o,"watch",{value:t=>{if("function"!=typeof t)throw new Error("watch 回调必须是函数");r=t}}),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>o,set(t){M.N(o,t)}}),{proxy:o,value:e,setLocked(){n=!0},unlock(){n=!1},setValue(s){M.N(e,s);try{r?.(e,t)}catch(t){}},setDiffs(s){s.forEach(({t:t,p:s,v:i})=>A(e,s,t,i));try{r?.(e,t)}catch(t){}}}}A(t){try{if(!this.U||this.U.readyState!==WebSocket.OPEN)throw new Error("WebSocket未连接");"function"==typeof this.U.sendMsg?this.U.sendMsg(t):"function"==typeof this.U.send&&this.U.send(JSON.stringify(t))}catch(t){}}}const j="https://varserver.popx.com";class _{constructor({host:t=j,namespace:e="",onError:s=null}={}){this.J=t,this.K=e,this.H=new Map,this.q=new Map,this.Z=s||(t=>{}),this.G=null,this.X=[],this.Y=null,this.tt=1e3,this.et=null,this.st=!1,this.it=null}static emit(t,e,{host:s=j,namespace:i=""}={}){const r=new URLSearchParams;i&&r.append("namespace",i);return async function(t,e){const s=await fetch(t,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}}),i=await s.json();if(i.err)throw new Error(i.err);return i}(`${s}/api/emit?${r.toString()}`,{event:t,data:e})}async rt(){if("undefined"!=typeof window&&"undefined"!=typeof document){if(!window.EventSource)throw new Error("EventSource is not supported in this browser");return window.EventSource}try{const t=await import("eventsource"),{EventSource:e}=t.default||t;return e}catch(t){throw new Error("Failed to import eventsource module. Make sure it is installed: npm install eventsource")}}async nt(){if(!this.Y)throw new Error("vars 和 events 不能同时为空");if(this.it)return this.it;const t=await this.rt();if(this.G&&this.G.readyState===t.OPEN)return this;const{varNames:e,eventNames:s}=this.Y,i=new URLSearchParams;this.K&&i.append("namespace",this.K),e.length&&i.append("vars",e),s.length&&i.append("events",s);const r=new t(`${this.J}/sse/syncvar?${i.toString()}`);return this.G=r,this.st=!1,this.ht(r),this.ot(r),this.it=new Promise((t,e)=>{let s=!1;r.onopen=()=>{s||(s=!0,this.tt=1e3,this.ct(),this.it=null,t(this))},r.onerror=()=>{const t=new Error("SSE 连接错误");if(this.Z(t),!s)return s=!0,this.it=null,void e(t);this.st||(this.it=null,this.ft())},r.onmessage=({data:t})=>this.Z(new Error("sseWatch 未处理消息: "+t))}),this.it}ht(t){t.addEventListener("$sync",t=>{try{const e=JSON.parse(t.data||"{}"),{name:s,value:i,changes:r}=e||{};if(!s)throw new Error("名字为空: "+t.data);let n=this.H.get(s);if(r){if(!n||"object"!=typeof n)throw new Error("数据为空或不可变更: "+t.data);r.forEach(({t:t,p:e,v:s})=>A(n,e,t,s))}else{if(void 0===i)throw new Error("值为空: "+t.data);n=i,this.H.set(s,n)}const h=this.q.get(s);if(h)try{h({name:s,value:n})}catch(t){this.Z(t)}else{const e=this.q.get("$all");if(!e)throw new Error("SSE 未处理消息: "+t.data);try{e({name:s,value:n})}catch(t){this.Z(t)}}}catch(t){this.Z(t)}})}ot(t){if(this.X.length)for(const{name:e,fn:s}of this.X)t.addEventListener(e,s)}ft(){this.st||this.et||(this.et=setTimeout(async()=>{this.et=null;try{this.G?.close(),this.G=null,await this.nt()}catch(t){this.Z(t),this.ft()}},this.tt),this.tt=Math.min(3e4,2*this.tt))}ct(){this.et&&(clearTimeout(this.et),this.et=null)}close(){this.st=!0,this.ct(),this.it=null;try{this.G?.close()}catch(t){}this.G=null}async watch({vars:t=[],events:e=[]}={}){const s=[],i=[],r=[];if(Array.isArray(t))for(const e of t)if("function"==typeof e){const t=e.name;if(!t)throw new Error("vars 回调必须是有名字的函数");s.push(t),this.q.set(t,e)}else{if("string"!=typeof e)throw new Error("vars 数组元素仅支持 string 或 function");s.push(e)}else{if("object"!=typeof t||null===t)throw new Error("vars 仅支持数组或对象");for(const[e,i]of Object.entries(t)){if("function"!=typeof i)throw new Error(`vars 对象中 "${e}" 的值必须是函数`);s.push(e),this.q.set(e,i)}}if(Array.isArray(e))for(const t of e)if("function"==typeof t){const e=t.name;if(!e)throw new Error("events 回调必须是有名字的函数");i.push(e),r.push({name:e,fn:t})}else{if("string"!=typeof t)throw new Error("events 数组元素仅支持 string 或 function");i.push(t)}else{if("object"!=typeof e||null===e)throw new Error("events 仅支持数组或对象");for(const[t,s]of Object.entries(e)){if("function"!=typeof s)throw new Error(`events 对象中 "${t}" 的值必须是函数`);i.push(t),r.push({name:t,fn:s})}}return this.X=r,this.Y={varNames:s,eventNames:i},this.st=!1,await this.nt(),this}onEvent(t,e,s){if(!this.G)throw new Error("未连接");return this.X.push({name:t,fn:e}),this.G.addEventListener(t,e,s)}offEvent(t,e,s){if(!this.G)throw new Error("未连接");return this.G.removeEventListener(t,e,s)}emit(t,e){return _.emit(t,e,{host:this.J,namespace:this.K})}getAll(){return this.H}get(t){return this.H.get(t)}}t.SSE=_,t.SyncVar=M,t.VersionInfo=e,t.WebSocketClient=async function(...t){let e,s;"string"==typeof arguments[0]?(e=arguments[0],s=arguments[1]):(s=arguments[0],s?.host&&(e=s.host)),e=e||"wss://varserver.popx.com/ws/syncvar";const{namespace:i="",guid:r,onopen:n,onclose:h,onerror:o=t=>{},packFormat:c=U.MessagePack,timeout:a=5e3,maxReconnectCount:f=100}=s||{},l=new Set;let u=0,w=!1;async function d(){return new Promise((t,s)=>{w=!1;const p=new URLSearchParams({namespace:i});let m=new WebSocket(`${e}?${p}`);m.binaryType="arraybuffer",m.lt=!1,m.ut=[],m.sendMsg=(t,{format:e=c}={})=>{var s,i;if(m.readyState===WebSocket.OPEN)try{e===U.MessagePack?m.send((s=t,new y(i).encodeSharedRef(s)),{binary:!0}):m.send(JSON.stringify(t))}catch(t){o?.(t)}else m.ut.push(t)};let g=null;g=setTimeout(()=>{if(!m.lt&&m.readyState===WebSocket.CONNECTING){m.close();const t=new Error("WebSocket connection timeout");o?.(t),s(t),w=!0}},a),m.onopen=t=>{n?.(m,t),function(){const t={namespace:i,guid:r,packFormat:c};m.send(JSON.stringify({$login:t}))}()},m.onmessage=async e=>{try{const{data:i}=e;let r;if("string"==typeof i)r=JSON.parse(i);else{let t;if(t=i instanceof Blob?await i.arrayBuffer():i,c!==U.MessagePack)throw new Error("不支持的消息格式");r=function(t,e){return new T(e).decode(t)}(t)}if(!r||"object"!=typeof r)throw new Error(`Invalid message format: ${i}`);if(r.$error)throw new Error(r.$error.err||"未描述的错误");if(r.$login)return function({id:e,error:i}){if(m.id=e,m.lt=!0,clearTimeout(g),i)return s(i),void(w=!0);u>0&&(l.forEach(t=>t.bind(m)),u=0),m.ut&&m.ut.length&&m.ut.splice(0).forEach(t=>m.sendMsg(t));t(m)}(r.$login);l.forEach(t=>t.onMessage?.(r))}catch(t){o?.(t)}},m.onerror=t=>{if(w)return;clearTimeout(g);const e=t instanceof Error?t:new Error(t?.message||"WebSocket error");o?.(e),m.lt||(s(e),w=!0)},m.onclose=t=>{clearTimeout(g),h?.(t),l.forEach(e=>e.close?.(t)),u<f?function(){const t=Math.min(1e3*2**u,3e4),e=Math.min(Math.floor(t*(.5+.5*Math.random())),3e4);u++,setTimeout(()=>{d().catch(t=>{})},e)}():(l.forEach(e=>e.destroy?.(t)),l.clear())},m.bind=t=>l.has(t)?t:(l.add(t),t.bind(m))})}return d()},t.Worker=class{constructor({onlog:t,onerror:e,onexit:s}={}){this.wt=t,this.dt=e,this.yt=s}async bind(t){if(this.U===t)return this;if(!t?.bind)throw new Error("请绑定WebSocketClient创建的连接实例");return this.U=t,t.bind(this),this}onMessage(t){const{Worker:e}=t;if(e)try{const{$run:t,$kill:s,$attach:i,$lists:r,$log:n,$error:h,$exit:o}=e;t&&this.gt(t),s&&this.gt(s),i&&this.gt(i),r&&this.gt(r),n&&this.wt?.(...n),h&&this.dt?.(h),o&&this.yt?.(o)}catch(t){}}gt({pid:t,error:e,...s}){B.process(t,{error:e,result:{...s}})}async run({code:t,name:e,workerData:s}){return B.call(i=>{this.U.sendMsg({Worker:{$run:{pid:i,code:t,name:e,workerData:s}}})})}async kill({name:t}){return B.call(e=>{this.U.sendMsg({Worker:{$kill:{pid:e,name:t}}})})}async attach({name:t}){return B.call(e=>{this.U.sendMsg({Worker:{$attach:{pid:e,name:t}}})})}async lists(){return B.call(t=>{this.U.sendMsg({Worker:{$lists:{pid:t}}})})}}});
@@ -1,5 +1,5 @@
1
- /*! Waterbear v1.1.2 (2026-02-09T12:06:36.478Z)
1
+ /*! Waterbear v1.1.3 (2026-02-09T12:20:43.200Z)
2
2
  该SDK提供一套基于 WebSocket 的变量同步、锁、RPC 与事件订阅能力,帮助前端快速搭建协同编辑、状态共享与后台任务管理场景。
3
3
  主页: https://varserver.popx.com
4
4
  */
5
- class t{static Version="1.1.2";static BuildTime="2026-02-09T12:06:36.478Z";static printInfo(){globalThis.console.group("%c📦 Waterbear Info","color: #35495e; font-size: 14px;"),globalThis.console.log(`%cVersion: v${t.Version}`,"color: #41b883;"),globalThis.console.groupEnd()}}t.printInfo();const e=new TextEncoder;function s(t,s,i){t.length>50?function(t,s,i){e.encodeInto(t,s.subarray(i))}(t,s,i):function(t,e,s){const i=t.length;let r=s,n=0;for(;n<i;){let s=t.charCodeAt(n++);if(4294967168&s){if(4294965248&s){if(s>=55296&&s<=56319&&n<i){const e=t.charCodeAt(n);56320==(64512&e)&&(++n,s=((1023&s)<<10)+(1023&e)+65536)}4294901760&s?(e[r++]=s>>18&7|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128):(e[r++]=s>>12&15|224,e[r++]=s>>6&63|128)}else e[r++]=s>>6&31|192;e[r++]=63&s|128}else e[r++]=s}}(t,s,i)}function i(t,e,s){let i=e;const r=i+s,n=[];let h="";for(;i<r;){const e=t[i++];if(128&e)if(192==(224&e)){const s=63&t[i++];n.push((31&e)<<6|s)}else if(224==(240&e)){const s=63&t[i++],r=63&t[i++];n.push((31&e)<<12|s<<6|r)}else if(240==(248&e)){let s=(7&e)<<18|(63&t[i++])<<12|(63&t[i++])<<6|63&t[i++];s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s)}else n.push(e);else n.push(e);n.length>=4096&&(h+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(h+=String.fromCharCode(...n)),h}const r=new TextDecoder;function n(t,e,s){return s>200?function(t,e,s){const i=t.subarray(e,e+s);return r.decode(i)}(t,e,s):i(t,e,s)}class h{type;data;constructor(t,e){this.type=t,this.data=e}}class o extends Error{constructor(t){super(t);const e=Object.create(o.prototype);Object.setPrototypeOf(this,e),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:o.name})}}const c=4294967295;function a(t,e,s){const i=Math.floor(s/4294967296),r=s;t.setUint32(e,i),t.setUint32(e+4,r)}function f(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}const l={type:-1,encode:function(t){if(t instanceof Date){return function({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=17179869183){if(0===e&&t<=4294967295){const e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t),e}{const s=t/4294967296,i=4294967295&t,r=new Uint8Array(8),n=new DataView(r.buffer);return n.setUint32(0,e<<2|3&s),n.setUint32(4,i),r}}{const s=new Uint8Array(12),i=new DataView(s.buffer);return i.setUint32(0,e),a(i,4,t),s}}(function(t){const e=t.getTime(),s=Math.floor(e/1e3),i=1e6*(e-1e3*s),r=Math.floor(i/1e9);return{sec:s+r,nsec:i-1e9*r}}(t))}return null},decode:function(t){const e=function(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0);return{sec:4294967296*(3&t)+e.getUint32(4),nsec:t>>>2}}case 12:return{sec:f(e,4),nsec:e.getUint32(0)};default:throw new o(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}(t);return new Date(1e3*e.sec+e.nsec/1e6)}};class u{static defaultCodec=new u;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(l)}register({type:t,encode:e,decode:s}){if(t>=0)this.encoders[t]=e,this.decoders[t]=s;else{const i=-1-t;this.builtInEncoders[i]=e,this.builtInDecoders[i]=s}}tryToEncode(t,e){for(let s=0;s<this.builtInEncoders.length;s++){const i=this.builtInEncoders[s];if(null!=i){const r=i(t,e);if(null!=r){return new h(-1-s,r)}}}for(let s=0;s<this.encoders.length;s++){const i=this.encoders[s];if(null!=i){const r=i(t,e);if(null!=r){return new h(s,r)}}}return t instanceof h?t:null}decode(t,e,s){const i=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return i?i(t,e,s):new h(e,t)}}function w(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):function(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}(t)?new Uint8Array(t):Uint8Array.from(t)}class d{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??u.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??100,this.initialBufferSize=t?.initialBufferSize??2048,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new d({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered){return this.clone().encodeSharedRef(t)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered){return this.clone().encode(t)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,e){if(e>this.maxDepth)throw new Error(`Too deep objects in depth ${e}`);null==t?this.encodeNil():"boolean"==typeof t?this.encodeBoolean(t):"number"==typeof t?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):"string"==typeof t?this.encodeString(t):this.useBigInt64&&"bigint"==typeof t?this.encodeBigInt64(t):this.encodeObject(t,e)}ensureBufferSizeToWrite(t){const e=this.pos+t;this.view.byteLength<e&&this.resizeBuffer(2*e)}resizeBuffer(t){const e=new ArrayBuffer(t),s=new Uint8Array(e),i=new DataView(e);s.set(this.bytes),this.view=i,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(t){!1===t?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too long string: ${t} bytes in UTF-8`);this.writeU8(219),this.writeU32(t)}}encodeString(t){const e=function(t){const e=t.length;let s=0,i=0;for(;i<e;){let r=t.charCodeAt(i++);if(4294967168&r)if(4294965248&r){if(r>=55296&&r<=56319&&i<e){const e=t.charCodeAt(i);56320==(64512&e)&&(++i,r=((1023&r)<<10)+(1023&e)+65536)}s+=4294901760&r?4:3}else s+=2;else s++}return s}(t);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),s(t,this.bytes,this.pos),this.pos+=e}encodeObject(t,e){const s=this.extensionCodec.tryToEncode(t,this.context);if(null!=s)this.encodeExtension(s);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else{if("object"!=typeof t)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`);this.encodeMap(t,e)}}encodeBinary(t){const e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too large binary: ${e}`);this.writeU8(198),this.writeU32(e)}const s=w(t);this.writeU8a(s)}encodeArray(t,e){const s=t.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else{if(!(s<4294967296))throw new Error(`Too large array: ${s}`);this.writeU8(221),this.writeU32(s)}for(const s of t)this.doEncode(s,e+1)}countWithoutUndefined(t,e){let s=0;for(const i of e)void 0!==t[i]&&s++;return s}encodeMap(t,e){const s=Object.keys(t);this.sortKeys&&s.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(t,s):s.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else{if(!(i<4294967296))throw new Error(`Too large map object: ${i}`);this.writeU8(223),this.writeU32(i)}for(const i of s){const s=t[i];this.ignoreUndefined&&void 0===s||(this.encodeString(i),this.doEncode(s,e+1))}}encodeExtension(t){if("function"==typeof t.data){const e=t.data(this.pos+6),s=e.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);return this.writeU8(201),this.writeU32(s),this.writeI8(t.type),void this.writeU8a(e)}const e=t.data.length;if(1===e)this.writeU8(212);else if(2===e)this.writeU8(213);else if(4===e)this.writeU8(214);else if(8===e)this.writeU8(215);else if(16===e)this.writeU8(216);else if(e<256)this.writeU8(199),this.writeU8(e);else if(e<65536)this.writeU8(200),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too large extension object: ${e}`);this.writeU8(201),this.writeU32(e)}this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){const e=t.length;this.ensureBufferSizeToWrite(e),this.bytes.set(t,this.pos),this.pos+=e}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),function(t,e,s){const i=s/4294967296,r=s;t.setUint32(e,i),t.setUint32(e+4,r)}(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),a(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}function y(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const p="array",m="map_key",g="map_value",E=t=>{if("string"==typeof t||"number"==typeof t)return t;throw new o("The type of key must be string or number but "+typeof t)};class b{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){const e=this.getUninitializedStateFromPool();e.type=p,e.position=0,e.size=t,e.array=new Array(t)}pushMapState(t){const e=this.getUninitializedStateFromPool();e.type=m,e.readCount=0,e.size=t,e.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===p){const e=t;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(t.type===m||t.type===g){const e=t;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const S=new DataView(new ArrayBuffer(0)),v=new Uint8Array(S.buffer);try{S.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const $=new RangeError("Insufficient data"),x=new class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=16,e=16){this.maxKeyLength=t,this.maxLengthPerKey=e,this.caches=[];for(let t=0;t<this.maxKeyLength;t++)this.caches.push([])}canBeCached(t){return t>0&&t<=this.maxKeyLength}find(t,e,s){const i=this.caches[s-1];t:for(const r of i){const i=r.bytes;for(let r=0;r<s;r++)if(i[r]!==t[e+r])continue t;return r.str}return null}store(t,e){const s=this.caches[t.length-1],i={bytes:t,str:e};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=i:s.push(i)}decode(t,e,s){const r=this.find(t,e,s);if(null!=r)return this.hit++,r;this.miss++;const n=i(t,e,s),h=Uint8Array.prototype.slice.call(t,e,e+s);return this.store(h,n),n}};class k{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=S;bytes=v;headByte=-1;stack=new b;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??u.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??c,this.maxBinLength=t?.maxBinLength??c,this.maxArrayLength=t?.maxArrayLength??c,this.maxMapLength=t?.maxMapLength??c,this.maxExtLength=t?.maxExtLength??c,this.keyDecoder=void 0!==t?.keyDecoder?t.keyDecoder:x,this.mapKeyConverter=t?.mapKeyConverter??E}clone(){return new k({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(t){const e=w(t);this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.pos=0}appendBuffer(t){if(-1!==this.headByte||this.hasRemaining(1)){const e=this.bytes.subarray(this.pos),s=w(t),i=new Uint8Array(e.length+s.length);i.set(e),i.set(s,e.length),this.setBuffer(i)}else this.setBuffer(t)}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){const{view:e,pos:s}=this;return new RangeError(`Extra ${e.byteLength-s} of ${e.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered){return this.clone().decode(t)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);const e=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return e}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){const e=this.clone();return void(yield*e.decodeMulti(t))}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered){return this.clone().decodeAsync(t)}try{this.entered=!0;let e,s=!1;for await(const i of t){if(s)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(i);try{e=this.doDecodeSync(),s=!0}catch(t){if(!(t instanceof RangeError))throw t}this.totalPos+=this.pos}if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}const{headByte:i,pos:r,totalPos:n}=this;throw new RangeError(`Insufficient data in parsing ${y(i)} at ${n} (${r} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,e){if(this.entered){const s=this.clone();return void(yield*s.decodeMultiAsync(t,e))}try{this.entered=!0;let s=e,i=-1;for await(const r of t){if(e&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(r),s&&(i=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),0!==--i;);}catch(t){if(!(t instanceof RangeError))throw t}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){t:for(;;){const t=this.readHeadByte();let e;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){const s=t-128;if(0!==s){this.pushMapState(s),this.complete();continue t}e={}}else if(t<160){const s=t-144;if(0!==s){this.pushArrayState(s),this.complete();continue t}e=[]}else{const s=t-160;e=this.decodeString(s,0)}else if(192===t)e=null;else if(194===t)e=!1;else if(195===t)e=!0;else if(202===t)e=this.readF32();else if(203===t)e=this.readF64();else if(204===t)e=this.readU8();else if(205===t)e=this.readU16();else if(206===t)e=this.readU32();else if(207===t)e=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===t)e=this.readI8();else if(209===t)e=this.readI16();else if(210===t)e=this.readI32();else if(211===t)e=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===t){const t=this.lookU8();e=this.decodeString(t,1)}else if(218===t){const t=this.lookU16();e=this.decodeString(t,2)}else if(219===t){const t=this.lookU32();e=this.decodeString(t,4)}else if(220===t){const t=this.readU16();if(0!==t){this.pushArrayState(t),this.complete();continue t}e=[]}else if(221===t){const t=this.readU32();if(0!==t){this.pushArrayState(t),this.complete();continue t}e=[]}else if(222===t){const t=this.readU16();if(0!==t){this.pushMapState(t),this.complete();continue t}e={}}else if(223===t){const t=this.readU32();if(0!==t){this.pushMapState(t),this.complete();continue t}e={}}else if(196===t){const t=this.lookU8();e=this.decodeBinary(t,1)}else if(197===t){const t=this.lookU16();e=this.decodeBinary(t,2)}else if(198===t){const t=this.lookU32();e=this.decodeBinary(t,4)}else if(212===t)e=this.decodeExtension(1,0);else if(213===t)e=this.decodeExtension(2,0);else if(214===t)e=this.decodeExtension(4,0);else if(215===t)e=this.decodeExtension(8,0);else if(216===t)e=this.decodeExtension(16,0);else if(199===t){const t=this.lookU8();e=this.decodeExtension(t,1)}else if(200===t){const t=this.lookU16();e=this.decodeExtension(t,2)}else{if(201!==t)throw new o(`Unrecognized type byte: ${y(t)}`);{const t=this.lookU32();e=this.decodeExtension(t,4)}}this.complete();const s=this.stack;for(;s.length>0;){const t=s.top();if(t.type===p){if(t.array[t.position]=e,t.position++,t.position!==t.size)continue t;e=t.array,s.release(t)}else{if(t.type===m){if("__proto__"===e)throw new o("The key __proto__ is not allowed");t.key=this.mapKeyConverter(e),t.type=g;continue t}if(t.map[t.key]=e,t.readCount++,t.readCount!==t.size){t.key=null,t.type=m;continue t}e=t.map,s.release(t)}}return e}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:if(t<160)return t-144;throw new o(`Unrecognized array type byte: ${y(t)}`)}}pushMapState(t){if(t>this.maxMapLength)throw new o(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new o(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,e){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,e):this.decodeBinary(t,e)}decodeUtf8String(t,e){if(t>this.maxStrLength)throw new o(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+e+t)throw $;const s=this.pos+e;let i;return i=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(t)?this.keyDecoder.decode(this.bytes,s,t):n(this.bytes,s,t),this.pos+=e+t,i}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===m}return!1}decodeBinary(t,e){if(t>this.maxBinLength)throw new o(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+e))throw $;const s=this.pos+e,i=this.bytes.subarray(s,s+t);return this.pos+=e+t,i}decodeExtension(t,e){if(t>this.maxExtLength)throw new o(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);const s=this.view.getInt8(this.pos+e),i=this.decodeBinary(t,e+1);return this.extensionCodec.decode(i,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){const t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){const t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){const t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){const t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){const t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){const t=(e=this.view,s=this.pos,4294967296*e.getUint32(s)+e.getUint32(s+4));var e,s;return this.pos+=8,t}readI64(){const t=f(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){const t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){const t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){const t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){const t=this.view.getFloat64(this.pos);return this.pos+=8,t}}const T=Object.freeze({JsonString:0,MessagePack:1});function U(t,e,s,i){if(!t)throw new Error("obj is empty");if(!e?.length)throw new Error("path is empty");return s={s:"set",d:"del",S:"SET",D:"DEL"}[s]||s,function t(e,r){const n=r.shift();if(0===r.length){switch(s){case"set":case"SET":e[n]=i;break;case"del":delete e[n];break;case"DEL":e.splice(Number(n),1);break;default:throw new Error(`Invalid type: ${s}`)}return!0}if(!e[n]){const t="SET"===s||"DEL"===s;1===r.length&&t?e[n]=[]:e[n]={}}return t(e[n],r)}(t,e.slice())}async function A(...t){let e,s;"string"==typeof arguments[0]?(e=arguments[0],s=arguments[1]):(s=arguments[0],s?.host&&(e=s.host)),e=e||"wss://varserver.popx.com/ws/syncvar";const{namespace:i="",guid:r,onopen:n,onclose:h,onerror:o=t=>{},packFormat:c=T.MessagePack,timeout:a=5e3,maxReconnectCount:f=100}=s||{},l=new Set;let u=0,w=!1;async function y(){return new Promise((t,s)=>{w=!1;const p=new URLSearchParams({namespace:i});let m=new WebSocket(`${e}?${p}`);m.binaryType="arraybuffer",m.i=!1,m.h=[],m.sendMsg=(t,{format:e=c}={})=>{var s,i;if(m.readyState===WebSocket.OPEN)try{e===T.MessagePack?m.send((s=t,new d(i).encodeSharedRef(s)),{binary:!0}):m.send(JSON.stringify(t))}catch(t){o?.(t)}else m.h.push(t)};let g=null;g=setTimeout(()=>{if(!m.i&&m.readyState===WebSocket.CONNECTING){m.close();const t=new Error("WebSocket connection timeout");o?.(t),s(t),w=!0}},a),m.onopen=t=>{n?.(m,t),function(){const t={namespace:i,guid:r,packFormat:c};m.send(JSON.stringify({$login:t}))}()},m.onmessage=async e=>{try{const{data:i}=e;let r;if("string"==typeof i)r=JSON.parse(i);else{let t;if(t=i instanceof Blob?await i.arrayBuffer():i,c!==T.MessagePack)throw new Error("不支持的消息格式");r=function(t,e){return new k(e).decode(t)}(t)}if(!r||"object"!=typeof r)throw new Error(`Invalid message format: ${i}`);if(r.$error)throw new Error(r.$error.err||"未描述的错误");if(r.$login)return function({id:e,error:i}){if(m.id=e,m.i=!0,clearTimeout(g),i)return s(i),void(w=!0);u>0&&(l.forEach(t=>t.bind(m)),u=0),m.h&&m.h.length&&m.h.splice(0).forEach(t=>m.sendMsg(t));t(m)}(r.$login);l.forEach(t=>t.onMessage?.(r))}catch(t){o?.(t)}},m.onerror=t=>{if(w)return;clearTimeout(g);const e=t instanceof Error?t:new Error(t?.message||"WebSocket error");o?.(e),m.i||(s(e),w=!0)},m.onclose=t=>{clearTimeout(g),h?.(t),l.forEach(e=>e.close?.(t)),u<f?function(){const t=Math.min(1e3*2**u,3e4),e=Math.min(Math.floor(t*(.5+.5*Math.random())),3e4);u++,setTimeout(()=>{y().catch(t=>{})},e)}():(l.forEach(e=>e.destroy?.(t)),l.clear())},m.bind=t=>l.has(t)?t:(l.add(t),t.bind(m))})}return y()}const B=new class{constructor(){this.o=new Map,this.l=0}call(t,{timeout:e=1e4,data:s}={}){if(!t)throw new Error("未指定回调函数");return new Promise((i,r)=>{const n=++this.l,h=setTimeout(()=>{this.o.delete(n),r(new Error("Promise等待超时"))},e);this.o.set(n,{resolve:i,reject:r,timeoutId:h,data:s}),t(n)})}process(t,{result:e,error:s}){const i=this.o.get(t);if(!i)return!1;clearTimeout(i.timeoutId),this.o.delete(t);const{resolve:r,reject:n}=i;return s?n(new Error(s)):r(e),!s}getData(t){const e=this.o.get(t);return e?.data}};class M{constructor({delay:t=50}={}){this.u=new Map,this.m=new Set,this.$=t,this.k=!1,this.T=new Map,this.U=null,this.A=new Map}get ws(){return this.B}get id(){return this.B?.id}async bind(t){if(this.B===t)return this;if(!t?.bind)throw new Error("请绑定WebSocketClient创建的连接实例");if(this.B=t,t.bind(this),this.u.size){const t=Array.from(this.u.keys());await B.call(e=>{this.M({SyncVar:{$sync:{pid:e,names:t}}})},{data:{names:t}})}return this.A.size&&await B.call(t=>{const e=Array.from(this.A.keys());this.M({SyncVar:{$bind:{pid:t,names:e}}})}),this}close(){this.B=null}destroy(){if(this.k)return;this.k=!0;const t=new Error("SyncVar已销毁");this.m.forEach(({reject:e})=>e(t)),this.u.clear(),this.m.clear(),this.B=null}async waitUpdated(){if(this.k)throw new Error("SyncVar已销毁,无法执行锁定");return new Promise((t,e)=>this.m.add({resolve:t,reject:e}))}async rpcBind(t){if("function"!=typeof t)throw new Error("rpcBind 回调必须是函数");const e=t.name;if(!e)throw new Error("rpcBind 回调必须指定名称,不能使用匿名函数");if(this.A.has(e))throw new Error(`已存在同名函数: ${e}`);return this.A.set(e,t),B.call(t=>{this.M({SyncVar:{$bind:{pid:t,names:[e]}}})})}async rpcCall(t,e){if(!t)throw new Error("rpcCall 参数错误:name 不能为空");return B.call(s=>{this.M({SyncVar:{$call:{pid:s,name:t,args:e}}})})}onMessage(t){const{SyncVar:e}=t;if(e)try{const{$sync:t,$set:s,$update:i,$lock:r,$bind:n,$call:h,$callRet:o}=e;t&&this.j(t),s&&this._(s),i&&this.I(i),r&&this.V(r),n&&this.L(n),h&&this.O(h),o&&this.R(o)}catch(t){}}static W(t){if("function"==typeof globalThis.structuredClone)return globalThis.structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch(e){return t}}static N(t){return Object.keys(t).filter(e=>"function"!=typeof t[e])}static P(t,e){if(Object.is(t,e))return!0;if(!t||!e)return!1;const s=M.N(t),i=M.N(e);return s.length===i.length&&(0===s.length?t===e:s.every(s=>t[s]===e[s]))}static C(t,e){if(M.P(t,e))return!1;const s=M.N(t);for(const e of s)delete t[e];return Object.assign(t,e),!0}static F(t){let e=[],s=!1;function i(){if(0===e.length)return;const s=e;e=[],t(s)}return{push(t){e.push(t),s||(s=!0,Promise.resolve().then(()=>{s=!1,i()}))},flush:i}}async sync(t,e){if(this.k)throw new Error("SyncVar已销毁,无法执行同步");if("string"==typeof t&&(t=[t]),!t?.length)throw new Error("names不能为空");if(!this.B||this.B.readyState!==WebSocket.OPEN)throw new Error("WebSocket未连接");const s=t.filter(t=>!this.u.has(t)),{reset:i}=e||{};if(i&&t.forEach(t=>{const e=i[t];void 0!==e&&(this[t]=e)}),!s.length){const e={};return t.forEach(t=>{const s=this.u.get(t);if(!s)throw new Error("变量异常:"+t);e[t]=s.proxy}),e}return B.call(t=>{this.M({SyncVar:{$sync:{pid:t,names:s,...e}}})},{data:{names:t}})}j({datas:t,pid:e,error:s}){t?.forEach(({name:t,value:e})=>{let s=this.u.get(t);s?s.setValue(e):(s=this.J(t,e),this.u.set(t,s))});const i=B.getData(e),r={};i?.names?.forEach(t=>{const e=this.u.get(t);if(!e)throw new Error("同步变量异常:"+t);r[t]=e.proxy}),B.process(e,{result:r,error:s})}_({error:t,lockeds:e}){e?.forEach(({name:t,value:e})=>{const s=this.u.get(t);s&&s.setValue(e)}),this.m.forEach(({resolve:e,reject:s})=>{t?s("数据写入失败:"+t):e()}),this.m.clear()}V({name:t,value:e,promiseIds:s,error:i}){const r=this.u.get(t);r&&(r.setValue(e),r.setLocked());let n=!1;s?.forEach(e=>{let s;r?s=r.proxy:i=i||"找不到变量:"+t,B.process(e,{result:s,error:i})&&(n=!0)}),n||(r?.unlock(),this.M({SyncVar:{$unlock:{name:t}}}))}I({vars:t}){t?.forEach(({name:t,value:e,changes:s})=>{const i=this.u.get(t);i&&(s?i.setDiffs(s):i.setValue(e))})}L({pid:t,error:e}){B.process(t,{error:e})}async O({pid:t,name:e,args:s}){try{const i=this.A.get(e);if(!i)throw new Error(`函数不存在: ${e}`);const r=await i(s);this.M({SyncVar:{$callRet:{pid:t,name:e,result:r}}})}catch(e){this.M({SyncVar:{$callRet:{pid:t,error:e.message||e}}})}}R({pid:t,result:e,error:s}){B.process(t,{result:e,error:s})}K(t,e){this.T.has(t)||this.T.set(t,[]);const s=this.T.get(t);e.forEach(t=>{const{type:e,path:i}=t;for(let t=s.length-1;t>=0;t--){const{path:e}=s[t];i.every((t,s)=>e[s]===t)&&s.splice(t,1)}s.push(t)}),this.U||(this.U=setTimeout(()=>{if(this.U=null,!this.T.size)return;const t=[];if(this.T.forEach((e,s)=>{if(!e.length)return;const i=this.u.get(s);if(!i)return;const r={set:"s",del:"d",SET:"S",DEL:"D"},n=e.map(({type:t,path:e,val:s})=>({t:r[t],p:e,v:s})),h=JSON.stringify(n).length,o=JSON.stringify(i.value).length;if(h>=o){t.push({name:s,value:i.value})}else t.push({name:s,changes:n});i.unlock()}),!t.length)return;const e={diffs:t};this.m.size>0&&(e.receipt=!0),this.M({SyncVar:{$set:e}}),this.T.clear()},this.$))}J(t,e){const s=this,i=new WeakMap;let r,n=!1;const h=M.F(e=>{this.K(t,e)});const o=function t(e,s=[]){if("object"!=typeof e||null===e)return e;if(i.has(e))return i.get(e);const r=new Proxy(e,{get(e,i,r){const n=Reflect.get(e,i,r);return"function"==typeof n&&(t=>t instanceof Set||t instanceof Map)(e)?n.bind(e):t(n,s.concat(i))},set(t,e,i,r){const n=t[e];return!!M.P(n,i)||(h.push({type:Array.isArray(t)?"SET":"set",path:s.concat(e),val:M.W(i)}),Reflect.set(t,e,i,r))},deleteProperty:(t,e)=>(h.push({type:Array.isArray(t)?"DEL":"del",path:s.concat(e)}),Reflect.deleteProperty(t,e))});return i.set(e,r),r}(e);return Object.defineProperty(o,"lock",{value:async({timeout:e}={})=>{if(s.k)throw new Error("SyncVar已销毁,无法执行锁定");return n?o:B.call(e=>{s.M({SyncVar:{$lock:{promiseId:e,name:t}}})},{timeout:e})}}),Object.defineProperty(o,"unlock",{value:async()=>{if(s.k)throw new Error("SyncVar已销毁,无法执行锁定");if(n){n=!1;try{s.M({SyncVar:{$unlock:{name:t}}})}catch(t){}}}}),Object.defineProperty(o,"watch",{value:t=>{if("function"!=typeof t)throw new Error("watch 回调必须是函数");r=t}}),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>o,set(t){M.C(o,t)}}),{proxy:o,value:e,setLocked(){n=!0},unlock(){n=!1},setValue(s){M.C(e,s);try{r?.(e,t)}catch(t){}},setDiffs(s){s.forEach(({t:t,p:s,v:i})=>U(e,s,t,i));try{r?.(e,t)}catch(t){}}}}M(t){try{if(!this.B||this.B.readyState!==WebSocket.OPEN)throw new Error("WebSocket未连接");"function"==typeof this.B.sendMsg?this.B.sendMsg(t):"function"==typeof this.B.send&&this.B.send(JSON.stringify(t))}catch(t){}}}class j{constructor({onlog:t,onerror:e,onexit:s}={}){this.H=t,this.q=e,this.Z=s}async bind(t){if(this.B===t)return this;if(!t?.bind)throw new Error("请绑定WebSocketClient创建的连接实例");return this.B=t,t.bind(this),this}onMessage(t){const{Worker:e}=t;if(e)try{const{$run:t,$kill:s,$attach:i,$lists:r,$log:n,$error:h,$exit:o}=e;t&&this.G(t),s&&this.G(s),i&&this.G(i),r&&this.G(r),n&&this.H?.(...n),h&&this.q?.(h),o&&this.Z?.(o)}catch(t){}}G({pid:t,error:e,...s}){B.process(t,{error:e,result:{...s}})}async run({code:t,name:e,workerData:s}){return B.call(i=>{this.B.sendMsg({Worker:{$run:{pid:i,code:t,name:e,workerData:s}}})})}async kill({name:t}){return B.call(e=>{this.B.sendMsg({Worker:{$kill:{pid:e,name:t}}})})}async attach({name:t}){return B.call(e=>{this.B.sendMsg({Worker:{$attach:{pid:e,name:t}}})})}async lists(){return B.call(t=>{this.B.sendMsg({Worker:{$lists:{pid:t}}})})}}const _="https://varserver.popx.com";class I{constructor({host:t=_,namespace:e="",onError:s=null}={}){this.X=t,this.Y=e,this.tt=new Map,this.et=new Map,this.st=s||(t=>{}),this.it=null,this.rt=[],this.nt=null,this.ht=1e3,this.ot=null,this.ct=!1,this.ft=null}static emit(t,e,{host:s=_,namespace:i=""}={}){const r=new URLSearchParams;i&&r.append("namespace",i);return async function(t,e){const s=await fetch(t,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}}),i=await s.json();if(i.err)throw new Error(i.err);return i}(`${s}/api/emit?${r.toString()}`,{event:t,data:e})}async lt(){if("undefined"!=typeof window&&"undefined"!=typeof document){if(!window.EventSource)throw new Error("EventSource is not supported in this browser");return window.EventSource}try{const t=await import("eventsource"),{EventSource:e}=t.default||t;return e}catch(t){throw new Error("Failed to import eventsource module. Make sure it is installed: npm install eventsource")}}async ut(){if(!this.nt)throw new Error("vars 和 events 不能同时为空");if(this.ft)return this.ft;const t=await this.lt();if(this.it&&this.it.readyState===t.OPEN)return this;const{varNames:e,eventNames:s}=this.nt,i=new URLSearchParams;this.Y&&i.append("namespace",this.Y),e.length&&i.append("vars",e),s.length&&i.append("events",s);const r=new t(`${this.X}/sse/syncvar?${i.toString()}`);return this.it=r,this.ct=!1,this.wt(r),this.dt(r),this.ft=new Promise((t,e)=>{let s=!1;r.onopen=()=>{s||(s=!0,this.ht=1e3,this.yt(),this.ft=null,t(this))},r.onerror=()=>{const t=new Error("SSE 连接错误");if(this.st(t),!s)return s=!0,this.ft=null,void e(t);this.ct||(this.ft=null,this.gt())},r.onmessage=({data:t})=>this.st(new Error("sseWatch 未处理消息: "+t))}),this.ft}wt(t){t.addEventListener("$sync",t=>{try{const e=JSON.parse(t.data||"{}"),{name:s,value:i,changes:r}=e||{};if(!s)throw new Error("名字为空: "+t.data);let n=this.tt.get(s);if(r){if(!n||"object"!=typeof n)throw new Error("数据为空或不可变更: "+t.data);r.forEach(({t:t,p:e,v:s})=>U(n,e,t,s))}else{if(void 0===i)throw new Error("值为空: "+t.data);n=i,this.tt.set(s,n)}const h=this.et.get(s);if(h)try{h({name:s,value:n})}catch(t){this.st(t)}else{const e=this.et.get("$all");if(!e)throw new Error("SSE 未处理消息: "+t.data);try{e({name:s,value:n})}catch(t){this.st(t)}}}catch(t){this.st(t)}})}dt(t){if(this.rt.length)for(const{name:e,fn:s}of this.rt)t.addEventListener(e,s)}gt(){this.ct||this.ot||(this.ot=setTimeout(async()=>{this.ot=null;try{this.it?.close(),this.it=null,await this.ut()}catch(t){this.st(t),this.gt()}},this.ht),this.ht=Math.min(3e4,2*this.ht))}yt(){this.ot&&(clearTimeout(this.ot),this.ot=null)}close(){this.ct=!0,this.yt(),this.ft=null;try{this.it?.close()}catch(t){}this.it=null}async watch({vars:t=[],events:e=[]}={}){const s=[],i=[],r=[];if(Array.isArray(t))for(const e of t)if("function"==typeof e){const t=e.name;if(!t)throw new Error("vars 回调必须是有名字的函数");s.push(t),this.et.set(t,e)}else{if("string"!=typeof e)throw new Error("vars 数组元素仅支持 string 或 function");s.push(e)}else{if("object"!=typeof t||null===t)throw new Error("vars 仅支持数组或对象");for(const[e,i]of Object.entries(t)){if("function"!=typeof i)throw new Error(`vars 对象中 "${e}" 的值必须是函数`);s.push(e),this.et.set(e,i)}}if(Array.isArray(e))for(const t of e)if("function"==typeof t){const e=t.name;if(!e)throw new Error("events 回调必须是有名字的函数");i.push(e),r.push({name:e,fn:t})}else{if("string"!=typeof t)throw new Error("events 数组元素仅支持 string 或 function");i.push(t)}else{if("object"!=typeof e||null===e)throw new Error("events 仅支持数组或对象");for(const[t,s]of Object.entries(e)){if("function"!=typeof s)throw new Error(`events 对象中 "${t}" 的值必须是函数`);i.push(t),r.push({name:t,fn:s})}}return this.rt=r,this.nt={varNames:s,eventNames:i},this.ct=!1,await this.ut(),this}onEvent(t,e,s){if(!this.it)throw new Error("未连接");return this.rt.push({name:t,fn:e}),this.it.addEventListener(t,e,s)}offEvent(t,e,s){if(!this.it)throw new Error("未连接");return this.it.removeEventListener(t,e,s)}emit(t,e){return I.emit(t,e,{host:this.X,namespace:this.Y})}getAll(){return this.tt}get(t){return this.tt.get(t)}}export{I as SSE,M as SyncVar,t as VersionInfo,A as WebSocketClient,j as Worker};
5
+ class t{static Version="1.1.3";static BuildTime="2026-02-09T12:20:43.200Z";static printInfo(){globalThis.console.group("%c📦 Waterbear Info","color: #35495e; font-size: 14px;"),globalThis.console.log(`%cVersion: v${t.Version}`,"color: #41b883;"),globalThis.console.groupEnd()}}t.printInfo();const e=new TextEncoder;function s(t,s,i){t.length>50?function(t,s,i){e.encodeInto(t,s.subarray(i))}(t,s,i):function(t,e,s){const i=t.length;let r=s,n=0;for(;n<i;){let s=t.charCodeAt(n++);if(4294967168&s){if(4294965248&s){if(s>=55296&&s<=56319&&n<i){const e=t.charCodeAt(n);56320==(64512&e)&&(++n,s=((1023&s)<<10)+(1023&e)+65536)}4294901760&s?(e[r++]=s>>18&7|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128):(e[r++]=s>>12&15|224,e[r++]=s>>6&63|128)}else e[r++]=s>>6&31|192;e[r++]=63&s|128}else e[r++]=s}}(t,s,i)}function i(t,e,s){let i=e;const r=i+s,n=[];let h="";for(;i<r;){const e=t[i++];if(128&e)if(192==(224&e)){const s=63&t[i++];n.push((31&e)<<6|s)}else if(224==(240&e)){const s=63&t[i++],r=63&t[i++];n.push((31&e)<<12|s<<6|r)}else if(240==(248&e)){let s=(7&e)<<18|(63&t[i++])<<12|(63&t[i++])<<6|63&t[i++];s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s)}else n.push(e);else n.push(e);n.length>=4096&&(h+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(h+=String.fromCharCode(...n)),h}const r=new TextDecoder;function n(t,e,s){return s>200?function(t,e,s){const i=t.subarray(e,e+s);return r.decode(i)}(t,e,s):i(t,e,s)}class h{type;data;constructor(t,e){this.type=t,this.data=e}}class o extends Error{constructor(t){super(t);const e=Object.create(o.prototype);Object.setPrototypeOf(this,e),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:o.name})}}const c=4294967295;function a(t,e,s){const i=Math.floor(s/4294967296),r=s;t.setUint32(e,i),t.setUint32(e+4,r)}function f(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}const l={type:-1,encode:function(t){if(t instanceof Date){return function({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=17179869183){if(0===e&&t<=4294967295){const e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t),e}{const s=t/4294967296,i=4294967295&t,r=new Uint8Array(8),n=new DataView(r.buffer);return n.setUint32(0,e<<2|3&s),n.setUint32(4,i),r}}{const s=new Uint8Array(12),i=new DataView(s.buffer);return i.setUint32(0,e),a(i,4,t),s}}(function(t){const e=t.getTime(),s=Math.floor(e/1e3),i=1e6*(e-1e3*s),r=Math.floor(i/1e9);return{sec:s+r,nsec:i-1e9*r}}(t))}return null},decode:function(t){const e=function(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0);return{sec:4294967296*(3&t)+e.getUint32(4),nsec:t>>>2}}case 12:return{sec:f(e,4),nsec:e.getUint32(0)};default:throw new o(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}(t);return new Date(1e3*e.sec+e.nsec/1e6)}};class u{static defaultCodec=new u;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(l)}register({type:t,encode:e,decode:s}){if(t>=0)this.encoders[t]=e,this.decoders[t]=s;else{const i=-1-t;this.builtInEncoders[i]=e,this.builtInDecoders[i]=s}}tryToEncode(t,e){for(let s=0;s<this.builtInEncoders.length;s++){const i=this.builtInEncoders[s];if(null!=i){const r=i(t,e);if(null!=r){return new h(-1-s,r)}}}for(let s=0;s<this.encoders.length;s++){const i=this.encoders[s];if(null!=i){const r=i(t,e);if(null!=r){return new h(s,r)}}}return t instanceof h?t:null}decode(t,e,s){const i=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return i?i(t,e,s):new h(e,t)}}function w(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):function(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}(t)?new Uint8Array(t):Uint8Array.from(t)}class d{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??u.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??100,this.initialBufferSize=t?.initialBufferSize??2048,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new d({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered){return this.clone().encodeSharedRef(t)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered){return this.clone().encode(t)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,e){if(e>this.maxDepth)throw new Error(`Too deep objects in depth ${e}`);null==t?this.encodeNil():"boolean"==typeof t?this.encodeBoolean(t):"number"==typeof t?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):"string"==typeof t?this.encodeString(t):this.useBigInt64&&"bigint"==typeof t?this.encodeBigInt64(t):this.encodeObject(t,e)}ensureBufferSizeToWrite(t){const e=this.pos+t;this.view.byteLength<e&&this.resizeBuffer(2*e)}resizeBuffer(t){const e=new ArrayBuffer(t),s=new Uint8Array(e),i=new DataView(e);s.set(this.bytes),this.view=i,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(t){!1===t?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too long string: ${t} bytes in UTF-8`);this.writeU8(219),this.writeU32(t)}}encodeString(t){const e=function(t){const e=t.length;let s=0,i=0;for(;i<e;){let r=t.charCodeAt(i++);if(4294967168&r)if(4294965248&r){if(r>=55296&&r<=56319&&i<e){const e=t.charCodeAt(i);56320==(64512&e)&&(++i,r=((1023&r)<<10)+(1023&e)+65536)}s+=4294901760&r?4:3}else s+=2;else s++}return s}(t);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),s(t,this.bytes,this.pos),this.pos+=e}encodeObject(t,e){const s=this.extensionCodec.tryToEncode(t,this.context);if(null!=s)this.encodeExtension(s);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else{if("object"!=typeof t)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`);this.encodeMap(t,e)}}encodeBinary(t){const e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too large binary: ${e}`);this.writeU8(198),this.writeU32(e)}const s=w(t);this.writeU8a(s)}encodeArray(t,e){const s=t.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else{if(!(s<4294967296))throw new Error(`Too large array: ${s}`);this.writeU8(221),this.writeU32(s)}for(const s of t)this.doEncode(s,e+1)}countWithoutUndefined(t,e){let s=0;for(const i of e)void 0!==t[i]&&s++;return s}encodeMap(t,e){const s=Object.keys(t);this.sortKeys&&s.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(t,s):s.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else{if(!(i<4294967296))throw new Error(`Too large map object: ${i}`);this.writeU8(223),this.writeU32(i)}for(const i of s){const s=t[i];this.ignoreUndefined&&void 0===s||(this.encodeString(i),this.doEncode(s,e+1))}}encodeExtension(t){if("function"==typeof t.data){const e=t.data(this.pos+6),s=e.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);return this.writeU8(201),this.writeU32(s),this.writeI8(t.type),void this.writeU8a(e)}const e=t.data.length;if(1===e)this.writeU8(212);else if(2===e)this.writeU8(213);else if(4===e)this.writeU8(214);else if(8===e)this.writeU8(215);else if(16===e)this.writeU8(216);else if(e<256)this.writeU8(199),this.writeU8(e);else if(e<65536)this.writeU8(200),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too large extension object: ${e}`);this.writeU8(201),this.writeU32(e)}this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){const e=t.length;this.ensureBufferSizeToWrite(e),this.bytes.set(t,this.pos),this.pos+=e}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),function(t,e,s){const i=s/4294967296,r=s;t.setUint32(e,i),t.setUint32(e+4,r)}(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),a(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}function y(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const p="array",m="map_key",g="map_value",E=t=>{if("string"==typeof t||"number"==typeof t)return t;throw new o("The type of key must be string or number but "+typeof t)};class b{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){const e=this.getUninitializedStateFromPool();e.type=p,e.position=0,e.size=t,e.array=new Array(t)}pushMapState(t){const e=this.getUninitializedStateFromPool();e.type=m,e.readCount=0,e.size=t,e.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===p){const e=t;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(t.type===m||t.type===g){const e=t;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const S=new DataView(new ArrayBuffer(0)),v=new Uint8Array(S.buffer);try{S.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const $=new RangeError("Insufficient data"),x=new class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=16,e=16){this.maxKeyLength=t,this.maxLengthPerKey=e,this.caches=[];for(let t=0;t<this.maxKeyLength;t++)this.caches.push([])}canBeCached(t){return t>0&&t<=this.maxKeyLength}find(t,e,s){const i=this.caches[s-1];t:for(const r of i){const i=r.bytes;for(let r=0;r<s;r++)if(i[r]!==t[e+r])continue t;return r.str}return null}store(t,e){const s=this.caches[t.length-1],i={bytes:t,str:e};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=i:s.push(i)}decode(t,e,s){const r=this.find(t,e,s);if(null!=r)return this.hit++,r;this.miss++;const n=i(t,e,s),h=Uint8Array.prototype.slice.call(t,e,e+s);return this.store(h,n),n}};class k{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=S;bytes=v;headByte=-1;stack=new b;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??u.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??c,this.maxBinLength=t?.maxBinLength??c,this.maxArrayLength=t?.maxArrayLength??c,this.maxMapLength=t?.maxMapLength??c,this.maxExtLength=t?.maxExtLength??c,this.keyDecoder=void 0!==t?.keyDecoder?t.keyDecoder:x,this.mapKeyConverter=t?.mapKeyConverter??E}clone(){return new k({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(t){const e=w(t);this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.pos=0}appendBuffer(t){if(-1!==this.headByte||this.hasRemaining(1)){const e=this.bytes.subarray(this.pos),s=w(t),i=new Uint8Array(e.length+s.length);i.set(e),i.set(s,e.length),this.setBuffer(i)}else this.setBuffer(t)}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){const{view:e,pos:s}=this;return new RangeError(`Extra ${e.byteLength-s} of ${e.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered){return this.clone().decode(t)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);const e=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return e}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){const e=this.clone();return void(yield*e.decodeMulti(t))}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered){return this.clone().decodeAsync(t)}try{this.entered=!0;let e,s=!1;for await(const i of t){if(s)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(i);try{e=this.doDecodeSync(),s=!0}catch(t){if(!(t instanceof RangeError))throw t}this.totalPos+=this.pos}if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}const{headByte:i,pos:r,totalPos:n}=this;throw new RangeError(`Insufficient data in parsing ${y(i)} at ${n} (${r} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,e){if(this.entered){const s=this.clone();return void(yield*s.decodeMultiAsync(t,e))}try{this.entered=!0;let s=e,i=-1;for await(const r of t){if(e&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(r),s&&(i=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),0!==--i;);}catch(t){if(!(t instanceof RangeError))throw t}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){t:for(;;){const t=this.readHeadByte();let e;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){const s=t-128;if(0!==s){this.pushMapState(s),this.complete();continue t}e={}}else if(t<160){const s=t-144;if(0!==s){this.pushArrayState(s),this.complete();continue t}e=[]}else{const s=t-160;e=this.decodeString(s,0)}else if(192===t)e=null;else if(194===t)e=!1;else if(195===t)e=!0;else if(202===t)e=this.readF32();else if(203===t)e=this.readF64();else if(204===t)e=this.readU8();else if(205===t)e=this.readU16();else if(206===t)e=this.readU32();else if(207===t)e=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===t)e=this.readI8();else if(209===t)e=this.readI16();else if(210===t)e=this.readI32();else if(211===t)e=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===t){const t=this.lookU8();e=this.decodeString(t,1)}else if(218===t){const t=this.lookU16();e=this.decodeString(t,2)}else if(219===t){const t=this.lookU32();e=this.decodeString(t,4)}else if(220===t){const t=this.readU16();if(0!==t){this.pushArrayState(t),this.complete();continue t}e=[]}else if(221===t){const t=this.readU32();if(0!==t){this.pushArrayState(t),this.complete();continue t}e=[]}else if(222===t){const t=this.readU16();if(0!==t){this.pushMapState(t),this.complete();continue t}e={}}else if(223===t){const t=this.readU32();if(0!==t){this.pushMapState(t),this.complete();continue t}e={}}else if(196===t){const t=this.lookU8();e=this.decodeBinary(t,1)}else if(197===t){const t=this.lookU16();e=this.decodeBinary(t,2)}else if(198===t){const t=this.lookU32();e=this.decodeBinary(t,4)}else if(212===t)e=this.decodeExtension(1,0);else if(213===t)e=this.decodeExtension(2,0);else if(214===t)e=this.decodeExtension(4,0);else if(215===t)e=this.decodeExtension(8,0);else if(216===t)e=this.decodeExtension(16,0);else if(199===t){const t=this.lookU8();e=this.decodeExtension(t,1)}else if(200===t){const t=this.lookU16();e=this.decodeExtension(t,2)}else{if(201!==t)throw new o(`Unrecognized type byte: ${y(t)}`);{const t=this.lookU32();e=this.decodeExtension(t,4)}}this.complete();const s=this.stack;for(;s.length>0;){const t=s.top();if(t.type===p){if(t.array[t.position]=e,t.position++,t.position!==t.size)continue t;e=t.array,s.release(t)}else{if(t.type===m){if("__proto__"===e)throw new o("The key __proto__ is not allowed");t.key=this.mapKeyConverter(e),t.type=g;continue t}if(t.map[t.key]=e,t.readCount++,t.readCount!==t.size){t.key=null,t.type=m;continue t}e=t.map,s.release(t)}}return e}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:if(t<160)return t-144;throw new o(`Unrecognized array type byte: ${y(t)}`)}}pushMapState(t){if(t>this.maxMapLength)throw new o(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new o(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,e){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,e):this.decodeBinary(t,e)}decodeUtf8String(t,e){if(t>this.maxStrLength)throw new o(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+e+t)throw $;const s=this.pos+e;let i;return i=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(t)?this.keyDecoder.decode(this.bytes,s,t):n(this.bytes,s,t),this.pos+=e+t,i}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===m}return!1}decodeBinary(t,e){if(t>this.maxBinLength)throw new o(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+e))throw $;const s=this.pos+e,i=this.bytes.subarray(s,s+t);return this.pos+=e+t,i}decodeExtension(t,e){if(t>this.maxExtLength)throw new o(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);const s=this.view.getInt8(this.pos+e),i=this.decodeBinary(t,e+1);return this.extensionCodec.decode(i,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){const t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){const t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){const t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){const t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){const t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){const t=(e=this.view,s=this.pos,4294967296*e.getUint32(s)+e.getUint32(s+4));var e,s;return this.pos+=8,t}readI64(){const t=f(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){const t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){const t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){const t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){const t=this.view.getFloat64(this.pos);return this.pos+=8,t}}const T=Object.freeze({JsonString:0,MessagePack:1});function U(t,e,s,i){if(!t)throw new Error("obj is empty");if(!e?.length)throw new Error("path is empty");return s={s:"set",d:"del",S:"SET",D:"DEL"}[s]||s,function t(e,r){const n=r.shift();if(0===r.length){switch(s){case"set":case"SET":e[n]=i;break;case"del":delete e[n];break;case"DEL":e.splice(Number(n),1);break;default:throw new Error(`Invalid type: ${s}`)}return!0}if(!e[n]){const t="SET"===s||"DEL"===s;1===r.length&&t?e[n]=[]:e[n]={}}return t(e[n],r)}(t,e.slice())}async function A(...t){let e,s;"string"==typeof arguments[0]?(e=arguments[0],s=arguments[1]):(s=arguments[0],s?.host&&(e=s.host)),e=e||"wss://varserver.popx.com/ws/syncvar";const{namespace:i="",guid:r,onopen:n,onclose:h,onerror:o=t=>{},packFormat:c=T.MessagePack,timeout:a=5e3,maxReconnectCount:f=100}=s||{},l=new Set;let u=0,w=!1;async function y(){return new Promise((t,s)=>{w=!1;const p=new URLSearchParams({namespace:i});let m=new WebSocket(`${e}?${p}`);m.binaryType="arraybuffer",m.i=!1,m.h=[],m.sendMsg=(t,{format:e=c}={})=>{var s,i;if(m.readyState===WebSocket.OPEN)try{e===T.MessagePack?m.send((s=t,new d(i).encodeSharedRef(s)),{binary:!0}):m.send(JSON.stringify(t))}catch(t){o?.(t)}else m.h.push(t)};let g=null;g=setTimeout(()=>{if(!m.i&&m.readyState===WebSocket.CONNECTING){m.close();const t=new Error("WebSocket connection timeout");o?.(t),s(t),w=!0}},a),m.onopen=t=>{n?.(m,t),function(){const t={namespace:i,guid:r,packFormat:c};m.send(JSON.stringify({$login:t}))}()},m.onmessage=async e=>{try{const{data:i}=e;let r;if("string"==typeof i)r=JSON.parse(i);else{let t;if(t=i instanceof Blob?await i.arrayBuffer():i,c!==T.MessagePack)throw new Error("不支持的消息格式");r=function(t,e){return new k(e).decode(t)}(t)}if(!r||"object"!=typeof r)throw new Error(`Invalid message format: ${i}`);if(r.$error)throw new Error(r.$error.err||"未描述的错误");if(r.$login)return function({id:e,error:i}){if(m.id=e,m.i=!0,clearTimeout(g),i)return s(i),void(w=!0);u>0&&(l.forEach(t=>t.bind(m)),u=0),m.h&&m.h.length&&m.h.splice(0).forEach(t=>m.sendMsg(t));t(m)}(r.$login);l.forEach(t=>t.onMessage?.(r))}catch(t){o?.(t)}},m.onerror=t=>{if(w)return;clearTimeout(g);const e=t instanceof Error?t:new Error(t?.message||"WebSocket error");o?.(e),m.i||(s(e),w=!0)},m.onclose=t=>{clearTimeout(g),h?.(t),l.forEach(e=>e.close?.(t)),u<f?function(){const t=Math.min(1e3*2**u,3e4),e=Math.min(Math.floor(t*(.5+.5*Math.random())),3e4);u++,setTimeout(()=>{y().catch(t=>{})},e)}():(l.forEach(e=>e.destroy?.(t)),l.clear())},m.bind=t=>l.has(t)?t:(l.add(t),t.bind(m))})}return y()}const B=new class{constructor(){this.o=new Map,this.l=0}call(t,{timeout:e=1e4,data:s}={}){if(!t)throw new Error("未指定回调函数");return new Promise((i,r)=>{const n=++this.l,h=setTimeout(()=>{this.o.delete(n),r(new Error("Promise等待超时"))},e);this.o.set(n,{resolve:i,reject:r,timeoutId:h,data:s}),t(n)})}process(t,{result:e,error:s}){const i=this.o.get(t);if(!i)return!1;clearTimeout(i.timeoutId),this.o.delete(t);const{resolve:r,reject:n}=i;return s?n(new Error(s)):r(e),!s}getData(t){const e=this.o.get(t);return e?.data}};class M{constructor({delay:t=50}={}){this.u=new Map,this.m=new Set,this.$=t,this.k=!1,this.T=new Map,this.U=null,this.A=new Map}get ws(){return this.B}get id(){return this.B?.id}async bind(t){if(this.B===t)return this;if(!t?.bind)throw new Error("请绑定WebSocketClient创建的连接实例");if(this.B=t,t.bind(this),this.u.size){const t=Array.from(this.u.keys());await B.call(e=>{this.M({SyncVar:{$sync:{pid:e,names:t}}})},{data:{names:t}})}return this.A.size&&await B.call(t=>{const e=Array.from(this.A.keys());this.M({SyncVar:{$bind:{pid:t,names:e}}})}),this}close(){this.B=null}destroy(){if(this.k)return;this.k=!0;const t=new Error("SyncVar已销毁");this.m.forEach(({reject:e})=>e(t)),this.u.clear(),this.m.clear(),this.B=null}async waitUpdated(){if(this.k)throw new Error("SyncVar已销毁,无法执行锁定");return new Promise((t,e)=>this.m.add({resolve:t,reject:e}))}async rpcBind(t){if("function"!=typeof t)throw new Error("rpcBind 回调必须是函数");const e=t.name;if(!e)throw new Error("rpcBind 回调必须指定名称,不能使用匿名函数");if(this.A.has(e))throw new Error(`已存在同名函数: ${e}`);return this.A.set(e,t),B.call(t=>{this.M({SyncVar:{$bind:{pid:t,names:[e]}}})})}async rpcCall(t,e){if(!t)throw new Error("rpcCall 参数错误:name 不能为空");return B.call(s=>{this.M({SyncVar:{$call:{pid:s,name:t,args:e}}})})}onMessage(t){const{SyncVar:e}=t;if(e)try{const{$sync:t,$set:s,$update:i,$lock:r,$bind:n,$call:h,$callRet:o}=e;t&&this.j(t),s&&this._(s),i&&this.I(i),r&&this.V(r),n&&this.L(n),h&&this.O(h),o&&this.R(o)}catch(t){}}static W(t){if("function"==typeof globalThis.structuredClone)return globalThis.structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch(e){return t}}static N(t){return Object.keys(t).filter(e=>"function"!=typeof t[e])}static P(t,e){if(Object.is(t,e))return!0;if(!t||!e)return!1;const s=M.N(t),i=M.N(e);return s.length===i.length&&(0===s.length?t===e:s.every(s=>t[s]===e[s]))}static C(t,e){if(M.P(t,e))return!1;const s=M.N(t);for(const e of s)delete t[e];return Object.assign(t,e),!0}static F(t){let e=[],s=!1;function i(){if(0===e.length)return;const s=e;e=[],t(s)}return{push(t){e.push(t),s||(s=!0,Promise.resolve().then(()=>{s=!1,i()}))},flush:i}}async sync(t,e){if(this.k)throw new Error("SyncVar已销毁,无法执行同步");if("string"==typeof t&&(t=[t]),!t?.length)throw new Error("names不能为空");if(!this.B||this.B.readyState!==WebSocket.OPEN)throw new Error("WebSocket未连接");const s=t.filter(t=>!this.u.has(t)),{reset:i}=e||{};if(i&&t.forEach(t=>{const e=i[t];void 0!==e&&(this[t]=e)}),!s.length){const e={};return t.forEach(t=>{const s=this.u.get(t);if(!s)throw new Error("变量异常:"+t);e[t]=s.proxy}),e}return B.call(t=>{this.M({SyncVar:{$sync:{pid:t,names:s,...e}}})},{data:{names:t}})}j({datas:t,pid:e,error:s}){t?.forEach(({name:t,value:e})=>{let s=this.u.get(t);s?s.setValue(e):(s=this.J(t,e),this.u.set(t,s))});const i=B.getData(e),r={};i?.names?.forEach(t=>{const e=this.u.get(t);if(!e)throw new Error("同步变量异常:"+t);r[t]=e.proxy}),B.process(e,{result:r,error:s})}_({error:t,lockeds:e}){e?.forEach(({name:t,value:e})=>{const s=this.u.get(t);s&&s.setValue(e)}),this.m.forEach(({resolve:e,reject:s})=>{t?s("数据写入失败:"+t):e()}),this.m.clear()}V({name:t,value:e,promiseIds:s,error:i}){const r=this.u.get(t);r&&(r.setValue(e),r.setLocked());let n=!1;s?.forEach(e=>{let s;r?s=r.proxy:i=i||"找不到变量:"+t,B.process(e,{result:s,error:i})&&(n=!0)}),n||(r?.unlock(),this.M({SyncVar:{$unlock:{name:t}}}))}I({vars:t}){t?.forEach(({name:t,value:e,changes:s})=>{const i=this.u.get(t);i&&(s?i.setDiffs(s):i.setValue(e))})}L({pid:t,error:e}){B.process(t,{error:e})}async O({pid:t,name:e,args:s}){try{const i=this.A.get(e);if(!i)throw new Error(`函数不存在: ${e}`);const r=await i(s);this.M({SyncVar:{$callRet:{pid:t,name:e,result:r}}})}catch(e){this.M({SyncVar:{$callRet:{pid:t,error:e.message||e}}})}}R({pid:t,result:e,error:s}){B.process(t,{result:e,error:s})}K(t,e){this.T.has(t)||this.T.set(t,[]);const s=this.T.get(t);e.forEach(t=>{const{type:e,path:i}=t;for(let t=s.length-1;t>=0;t--){const{path:e}=s[t];i.every((t,s)=>e[s]===t)&&s.splice(t,1)}s.push(t)}),this.U||(this.U=setTimeout(()=>{if(this.U=null,!this.T.size)return;const t=[];if(this.T.forEach((e,s)=>{if(!e.length)return;const i=this.u.get(s);if(!i)return;const r={set:"s",del:"d",SET:"S",DEL:"D"},n=e.map(({type:t,path:e,val:s})=>({t:r[t],p:e,v:s})),h=JSON.stringify(n).length,o=JSON.stringify(i.value).length;if(h>=o){t.push({name:s,value:i.value})}else t.push({name:s,changes:n});i.unlock()}),!t.length)return;const e={diffs:t};this.m.size>0&&(e.receipt=!0),this.M({SyncVar:{$set:e}}),this.T.clear()},this.$))}J(t,e){const s=this,i=new WeakMap;let r,n=!1;const h=M.F(e=>{this.K(t,e)});const o=function t(e,s=[]){if("object"!=typeof e||null===e)return e;if(i.has(e))return i.get(e);const r=new Proxy(e,{get(e,i,r){const n=Reflect.get(e,i,r);return"function"==typeof n&&(t=>t instanceof Set||t instanceof Map)(e)?n.bind(e):t(n,s.concat(i))},set(t,e,i,r){const n=t[e];return!!M.P(n,i)||(h.push({type:Array.isArray(t)?"SET":"set",path:s.concat(e),val:M.W(i)}),Reflect.set(t,e,i,r))},deleteProperty:(t,e)=>(h.push({type:Array.isArray(t)?"DEL":"del",path:s.concat(e)}),Reflect.deleteProperty(t,e))});return i.set(e,r),r}(e);return Object.defineProperty(o,"lock",{value:async({timeout:e}={})=>{if(s.k)throw new Error("SyncVar已销毁,无法执行锁定");return n?o:B.call(e=>{s.M({SyncVar:{$lock:{promiseId:e,name:t}}})},{timeout:e})}}),Object.defineProperty(o,"unlock",{value:async()=>{if(s.k)throw new Error("SyncVar已销毁,无法执行锁定");if(n){n=!1;try{s.M({SyncVar:{$unlock:{name:t}}})}catch(t){}}}}),Object.defineProperty(o,"watch",{value:t=>{if("function"!=typeof t)throw new Error("watch 回调必须是函数");r=t}}),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>o,set(t){M.C(o,t)}}),{proxy:o,value:e,setLocked(){n=!0},unlock(){n=!1},setValue(s){M.C(e,s);try{r?.(e,t)}catch(t){}},setDiffs(s){s.forEach(({t:t,p:s,v:i})=>U(e,s,t,i));try{r?.(e,t)}catch(t){}}}}M(t){try{if(!this.B||this.B.readyState!==WebSocket.OPEN)throw new Error("WebSocket未连接");"function"==typeof this.B.sendMsg?this.B.sendMsg(t):"function"==typeof this.B.send&&this.B.send(JSON.stringify(t))}catch(t){}}}class j{constructor({onlog:t,onerror:e,onexit:s}={}){this.H=t,this.q=e,this.Z=s}async bind(t){if(this.B===t)return this;if(!t?.bind)throw new Error("请绑定WebSocketClient创建的连接实例");return this.B=t,t.bind(this),this}onMessage(t){const{Worker:e}=t;if(e)try{const{$run:t,$kill:s,$attach:i,$lists:r,$log:n,$error:h,$exit:o}=e;t&&this.G(t),s&&this.G(s),i&&this.G(i),r&&this.G(r),n&&this.H?.(...n),h&&this.q?.(h),o&&this.Z?.(o)}catch(t){}}G({pid:t,error:e,...s}){B.process(t,{error:e,result:{...s}})}async run({code:t,name:e,workerData:s}){return B.call(i=>{this.B.sendMsg({Worker:{$run:{pid:i,code:t,name:e,workerData:s}}})})}async kill({name:t}){return B.call(e=>{this.B.sendMsg({Worker:{$kill:{pid:e,name:t}}})})}async attach({name:t}){return B.call(e=>{this.B.sendMsg({Worker:{$attach:{pid:e,name:t}}})})}async lists(){return B.call(t=>{this.B.sendMsg({Worker:{$lists:{pid:t}}})})}}const _="https://varserver.popx.com";class I{constructor({host:t=_,namespace:e="",onError:s=null}={}){this.X=t,this.Y=e,this.tt=new Map,this.et=new Map,this.st=s||(t=>{}),this.it=null,this.rt=[],this.nt=null,this.ht=1e3,this.ot=null,this.ct=!1,this.ft=null}static emit(t,e,{host:s=_,namespace:i=""}={}){const r=new URLSearchParams;i&&r.append("namespace",i);return async function(t,e){const s=await fetch(t,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}}),i=await s.json();if(i.err)throw new Error(i.err);return i}(`${s}/api/emit?${r.toString()}`,{event:t,data:e})}async lt(){if("undefined"!=typeof window&&"undefined"!=typeof document){if(!window.EventSource)throw new Error("EventSource is not supported in this browser");return window.EventSource}try{const t=await import("eventsource"),{EventSource:e}=t.default||t;return e}catch(t){throw new Error("Failed to import eventsource module. Make sure it is installed: npm install eventsource")}}async ut(){if(!this.nt)throw new Error("vars 和 events 不能同时为空");if(this.ft)return this.ft;const t=await this.lt();if(this.it&&this.it.readyState===t.OPEN)return this;const{varNames:e,eventNames:s}=this.nt,i=new URLSearchParams;this.Y&&i.append("namespace",this.Y),e.length&&i.append("vars",e),s.length&&i.append("events",s);const r=new t(`${this.X}/sse/syncvar?${i.toString()}`);return this.it=r,this.ct=!1,this.wt(r),this.dt(r),this.ft=new Promise((t,e)=>{let s=!1;r.onopen=()=>{s||(s=!0,this.ht=1e3,this.yt(),this.ft=null,t(this))},r.onerror=()=>{const t=new Error("SSE 连接错误");if(this.st(t),!s)return s=!0,this.ft=null,void e(t);this.ct||(this.ft=null,this.gt())},r.onmessage=({data:t})=>this.st(new Error("sseWatch 未处理消息: "+t))}),this.ft}wt(t){t.addEventListener("$sync",t=>{try{const e=JSON.parse(t.data||"{}"),{name:s,value:i,changes:r}=e||{};if(!s)throw new Error("名字为空: "+t.data);let n=this.tt.get(s);if(r){if(!n||"object"!=typeof n)throw new Error("数据为空或不可变更: "+t.data);r.forEach(({t:t,p:e,v:s})=>U(n,e,t,s))}else{if(void 0===i)throw new Error("值为空: "+t.data);n=i,this.tt.set(s,n)}const h=this.et.get(s);if(h)try{h({name:s,value:n})}catch(t){this.st(t)}else{const e=this.et.get("$all");if(!e)throw new Error("SSE 未处理消息: "+t.data);try{e({name:s,value:n})}catch(t){this.st(t)}}}catch(t){this.st(t)}})}dt(t){if(this.rt.length)for(const{name:e,fn:s}of this.rt)t.addEventListener(e,s)}gt(){this.ct||this.ot||(this.ot=setTimeout(async()=>{this.ot=null;try{this.it?.close(),this.it=null,await this.ut()}catch(t){this.st(t),this.gt()}},this.ht),this.ht=Math.min(3e4,2*this.ht))}yt(){this.ot&&(clearTimeout(this.ot),this.ot=null)}close(){this.ct=!0,this.yt(),this.ft=null;try{this.it?.close()}catch(t){}this.it=null}async watch({vars:t=[],events:e=[]}={}){const s=[],i=[],r=[];if(Array.isArray(t))for(const e of t)if("function"==typeof e){const t=e.name;if(!t)throw new Error("vars 回调必须是有名字的函数");s.push(t),this.et.set(t,e)}else{if("string"!=typeof e)throw new Error("vars 数组元素仅支持 string 或 function");s.push(e)}else{if("object"!=typeof t||null===t)throw new Error("vars 仅支持数组或对象");for(const[e,i]of Object.entries(t)){if("function"!=typeof i)throw new Error(`vars 对象中 "${e}" 的值必须是函数`);s.push(e),this.et.set(e,i)}}if(Array.isArray(e))for(const t of e)if("function"==typeof t){const e=t.name;if(!e)throw new Error("events 回调必须是有名字的函数");i.push(e),r.push({name:e,fn:t})}else{if("string"!=typeof t)throw new Error("events 数组元素仅支持 string 或 function");i.push(t)}else{if("object"!=typeof e||null===e)throw new Error("events 仅支持数组或对象");for(const[t,s]of Object.entries(e)){if("function"!=typeof s)throw new Error(`events 对象中 "${t}" 的值必须是函数`);i.push(t),r.push({name:t,fn:s})}}return this.rt=r,this.nt={varNames:s,eventNames:i},this.ct=!1,await this.ut(),this}onEvent(t,e,s){if(!this.it)throw new Error("未连接");return this.rt.push({name:t,fn:e}),this.it.addEventListener(t,e,s)}offEvent(t,e,s){if(!this.it)throw new Error("未连接");return this.it.removeEventListener(t,e,s)}emit(t,e){return I.emit(t,e,{host:this.X,namespace:this.Y})}getAll(){return this.tt}get(t){return this.tt.get(t)}}export{I as SSE,M as SyncVar,t as VersionInfo,A as WebSocketClient,j as Worker};
package/dist/syncvar.mjs CHANGED
@@ -1,12 +1,12 @@
1
- /*! Waterbear v1.1.2 (2026-02-09T12:06:36.478Z)
1
+ /*! Waterbear v1.1.3 (2026-02-09T12:20:43.200Z)
2
2
  该SDK提供一套基于 WebSocket 的变量同步、锁、RPC 与事件订阅能力,帮助前端快速搭建协同编辑、状态共享与后台任务管理场景。
3
3
  主页: https://varserver.popx.com
4
4
  */
5
5
 
6
6
  // 版本信息模块
7
7
  class VersionInfo {
8
- static Version = "1.1.2"; // 由构建时注入
9
- static BuildTime = "2026-02-09T12:06:36.478Z";
8
+ static Version = "1.1.3"; // 由构建时注入
9
+ static BuildTime = "2026-02-09T12:20:43.200Z";
10
10
  static printInfo() {
11
11
  globalThis.console.group('%c📦 Waterbear Info', 'color: #35495e; font-size: 14px;');
12
12
  // 只在开发环境显示调试信息
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xuzhiyang/syncvar",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "description": "WaterBear SDK - WebSocket 变量同步、锁、RPC、事件订阅和 Worker 执行能力",
5
5
  "main": "./dist/syncvar.mjs",
6
6
  "module": "./dist/syncvar.mjs",