weifuwu 0.93.2 → 0.94.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/client/components/ActionSheet/ActionSheet.d.ts +1 -1
- package/dist/client/components/AlertGroup/AlertGroup.d.ts +1 -1
- package/dist/client/components/Anchor/Anchor.d.ts +1 -1
- package/dist/client/components/AppShell/AppShell.d.ts +20 -3
- package/dist/client/components/AuthPage/AuthPage.d.ts +1 -1
- package/dist/client/components/AutoComplete/AutoComplete.d.ts +1 -1
- package/dist/client/components/AvatarGroup/AvatarGroup.d.ts +1 -1
- package/dist/client/components/Button/Button.d.ts +8 -2
- package/dist/client/components/Chart/Chart.d.ts +1 -1
- package/dist/client/components/Chart/chart-utils.d.ts +1 -1
- package/dist/client/components/ChatInput/ChatInput.d.ts +3 -1
- package/dist/client/components/CodeBlock/CodeBlock.d.ts +1 -1
- package/dist/client/components/CodeBlock/highlight.d.ts +1 -1
- package/dist/client/components/Confirm/Confirm.d.ts +1 -1
- package/dist/client/components/CronPicker/CronPicker.d.ts +31 -0
- package/dist/client/components/DatePicker/DatePicker.d.ts +1 -1
- package/dist/client/components/DatePicker/calendar-utils.d.ts +1 -1
- package/dist/client/components/Descriptions/Descriptions.d.ts +1 -1
- package/dist/client/components/Drawer/Drawer.d.ts +4 -1
- package/dist/client/components/DropZone/DropZone.d.ts +1 -1
- package/dist/client/components/Dropdown/Dropdown.d.ts +1 -1
- package/dist/client/components/Editor/Editor.d.ts +1 -1
- package/dist/client/components/Editor/edit-events.d.ts +1 -1
- package/dist/client/components/Editor/model/apply.d.ts +1 -1
- package/dist/client/components/Editor/model/diff.d.ts +1 -1
- package/dist/client/components/Editor/model/dom.d.ts +1 -1
- package/dist/client/components/Editor/model/history.d.ts +1 -1
- package/dist/client/components/Editor/model/html.d.ts +1 -1
- package/dist/client/components/Editor/model/inverse.d.ts +1 -1
- package/dist/client/components/Editor/model/types.d.ts +1 -1
- package/dist/client/components/Editor/tools/table.d.ts +1 -1
- package/dist/client/components/Editor/tools/toolbar.d.ts +1 -1
- package/dist/client/components/Editor/tools/types.d.ts +1 -1
- package/dist/client/components/FilePreview/FilePreview.d.ts +1 -1
- package/dist/client/components/FilePreview/markdown.d.ts +1 -1
- package/dist/client/components/FileTree/FileTree.d.ts +1 -1
- package/dist/client/components/FileUpload/FileUpload.d.ts +1 -1
- package/dist/client/components/FloatButton/FloatButton.d.ts +1 -1
- package/dist/client/components/Grid/Grid.d.ts +1 -1
- package/dist/client/components/Highlight/Highlight.d.ts +1 -1
- package/dist/client/components/HoverCard/HoverCard.d.ts +1 -1
- package/dist/client/components/Icon/Icon.d.ts +1 -1
- package/dist/client/components/Img/Img.d.ts +1 -1
- package/dist/client/components/InView/InView.d.ts +1 -1
- package/dist/client/components/Input/Input.d.ts +6 -0
- package/dist/client/components/InputNumber/InputNumber.d.ts +1 -1
- package/dist/client/components/JSONViewer/JSONViewer.d.ts +1 -1
- package/dist/client/components/Layout/Layout.d.ts +1 -1
- package/dist/client/components/Link/Link.d.ts +1 -1
- package/dist/client/components/List/List.d.ts +1 -1
- package/dist/client/components/ListScaffold/ListScaffold.d.ts +40 -0
- package/dist/client/components/LogViewer/LogViewer.d.ts +1 -1
- package/dist/client/components/Markdown/Markdown.d.ts +1 -1
- package/dist/client/components/Markdown/parser.d.ts +1 -1
- package/dist/client/components/Menu/Menu.d.ts +3 -1
- package/dist/client/components/MessageBubble/MessageBubble.d.ts +1 -1
- package/dist/client/components/Modal/Modal.d.ts +5 -1
- package/dist/client/components/NavBar/NavBar.d.ts +1 -1
- package/dist/client/components/NavMenu/NavMenu.d.ts +1 -1
- package/dist/client/components/OfficeEditor/ai/ai-bridge.d.ts +1 -1
- package/dist/client/components/OfficeEditor/model/apply.d.ts +1 -1
- package/dist/client/components/OfficeEditor/model/types.d.ts +1 -1
- package/dist/client/components/PasswordInput/PasswordInput.d.ts +1 -1
- package/dist/client/components/Popconfirm/Popconfirm.d.ts +1 -1
- package/dist/client/components/Popover/Popover.d.ts +1 -1
- package/dist/client/components/PromptTemplate/PromptTemplate.d.ts +1 -1
- package/dist/client/components/RelationGraph/RelationGraph.d.ts +1 -1
- package/dist/client/components/Result/Result.d.ts +1 -1
- package/dist/client/components/Scrollbar/Scrollbar.d.ts +1 -1
- package/dist/client/components/SheetGrid/SheetGrid.d.ts +2 -2
- package/dist/client/components/Skeleton/Skeleton.d.ts +1 -1
- package/dist/client/components/SlideCanvas/SlideCanvas.d.ts +2 -2
- package/dist/client/components/Space/Space.d.ts +1 -1
- package/dist/client/components/StatusDot/StatusDot.d.ts +25 -0
- package/dist/client/components/TabBar/TabBar.d.ts +1 -1
- package/dist/client/components/TagsInput/TagsInput.d.ts +1 -1
- package/dist/client/components/Textarea/Textarea.d.ts +6 -0
- package/dist/client/components/ThemeSwitch/ThemeSwitch.d.ts +1 -1
- package/dist/client/components/Timeline/Timeline.d.ts +1 -1
- package/dist/client/components/Tooltip/Tooltip.d.ts +1 -1
- package/dist/client/components/VirtualTable/VirtualTable.d.ts +1 -1
- package/dist/client/components/WordCloud/WordCloud.d.ts +1 -1
- package/dist/client/components/index.d.ts +9 -3
- package/dist/client/components/index.js +36 -36
- package/dist/client/components/style.css +1 -1
- package/dist/client/layout/decl.d.ts +9 -0
- package/dist/client/layout/define.d.ts +41 -0
- package/dist/client/layout/index.d.ts +20 -0
- package/dist/client/layout/index.js +17 -0
- package/dist/client/layout/weifuwu-layout.css +1 -1
- package/dist/client/vdom/context/UIContext.d.ts +1 -1
- package/dist/client/vdom/core/create-component.d.ts +42 -0
- package/dist/client/vdom/core/create-item.d.ts +52 -0
- package/dist/client/vdom/core/vnode.d.ts +8 -2
- package/dist/client/vdom/hooks/env.d.ts +12 -0
- package/dist/client/vdom/hooks/field.d.ts +54 -0
- package/dist/client/vdom/hooks/overlay.d.ts +60 -0
- package/dist/client/vdom/hooks/signal.d.ts +25 -0
- package/dist/client/vdom/index.d.ts +9 -2
- package/dist/client/vdom/index.js +3 -3
- package/dist/client/vdom/jsx-runtime.d.ts +4 -4
- package/dist/client/vdom/jsx-runtime.js +1 -1
- package/dist/client/vdom/testing.js +2 -2
- package/dist/dev/index.js +7 -6
- package/dist/server/ai/index.js +7 -0
- package/dist/server/ai/types.d.ts +1 -1
- package/dist/server/email/index.js +1 -0
- package/dist/server/index.js +235 -5
- package/dist/server/messager/index.js +1 -0
- package/dist/server/postgres/index.js +56 -0
- package/dist/server/queue/index.js +1 -0
- package/dist/server/redis/index.js +3 -0
- package/dist/server/scheduler/index.js +1 -0
- package/dist/server/ui/index.d.ts +1 -1
- package/dist/server/ui/index.js +15 -0
- package/dist/server/user/index.js +1 -0
- package/dist/server/user/token.d.ts +1 -1
- package/dist/server/workflows/index.js +24 -0
- package/dist/shared/router/index.js +2 -0
- package/docs/client.md +143 -10
- package/docs/layout.md +14 -14
- package/docs/server.md +1 -1
- package/package.json +66 -12
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import Z from"node:net";var f=class extends Error{kind;code;cause;constructor(e,t,n){super(t),this.name="DbError",this.kind=e,this.code=n?.code,this.cause=n?.cause}},d=class extends f{constructor(e,t){super("protocol",t??`${e} is not supported by weifuwu/db`,{code:"UNSUPPORTED"}),this.name="ProtocolError"}},h=class extends f{attempts;constructor(e,t=1,n){super("connection",e,{cause:n}),this.name="ConnectionError",this.attempts=t}};var R=class extends f{operation;ms;constructor(e,t){super("timeout",`${e} timed out after ${t}ms`),this.name="TimeoutError",this.operation=e,this.ms=t}},E=class extends f{constructor(e){super("validation",e),this.name="ValidationError"}};var A=class extends f{constructor(e){super("protocol",e,{code:"RESP"}),this.name="RespError"}},b=class extends Error{constructor(){super("incomplete RESP message"),this.name="IncompleteError"}};function v(r,e){return r instanceof Uint8Array?e?X.decode(r):r:Array.isArray(r)?r.map(t=>v(t,e)):r}function C(r){let e=new Array(r.length),t=G(r.length);for(let o=0;o<r.length;o++){let a=r[o],c=typeof a=="string"?Buffer.byteLength(a):a instanceof Buffer?a.length:String(a).length;e[o]=c,t+=G(c)+c+2}let n=new Uint8Array(t),s=0,i=`*${r.length}\r
|
|
2
|
+
`;n.set(O.encode(i),0),s=i.length;for(let o=0;o<r.length;o++){let a=r[o],c=e[o],u=`$${c}\r
|
|
3
|
+
`;n.set(O.encode(u),s),s+=u.length,typeof a=="string"?n.set(O.encode(a),s):a instanceof Buffer?n.set(a,s):n.set(O.encode(String(a)),s),s+=c,n[s]=13,n[s+1]=10,s+=2}return n}function G(r){return r<10?4:r<100?5:r<1e3?6:r<1e4?7:8}var X=new TextDecoder,O=new TextEncoder,T=class{buf=new Uint8Array(0);off=0;push(e){this.append(e);let t=this.off;try{let n=this.parseValue();return this.compact(),{value:n,incomplete:!1}}catch(n){if(this.off=t,n instanceof b)return{value:null,incomplete:!0};throw n}}pushAll(e){this.append(e);let t=[];for(;;){let n=this.off;try{t.push(this.parseValue())}catch(s){if(this.off=n,s instanceof b)break;throw s}}return t.length>0&&this.compact(),t}append(e){if(e.length===0)return;let t=this.buf.length-this.off;if(t===0){this.buf=e,this.off=0;return}let n=new Uint8Array(t+e.length);n.set(this.buf.subarray(this.off),0),n.set(e,t),this.buf=n,this.off=0}compact(){this.off===this.buf.length?(this.buf=new Uint8Array(0),this.off=0):this.off>0&&(this.buf=this.buf.subarray(this.off),this.off=0)}parseValue(){if(this.buf.length-this.off<3)throw new b;let e=String.fromCharCode(this.buf[this.off]);switch(this.off++,e){case"+":return this.readLine();case"-":{let t=this.readLine();return new A(t)}case":":return this.readInt();case"$":{let t=this.readInt();return t===-1?null:this.readBulkBytes(t)}case"*":{let t=this.readInt();if(t===-1)return null;let n=[];for(let s=0;s<t;s++)n.push(this.parseValue());return n}default:throw new f("protocol",`unknown RESP type byte: ${e}`,{code:"RESP"})}}readInt(){let e=this.buf,t=this.off,n=!1;t<e.length&&e[t]===45&&(n=!0,t++);let s=0;for(;t<e.length&&e[t]>=48&&e[t]<=57;)s=s*10+(e[t]-48),t++;if(t+1<e.length&&e[t]===13&&e[t+1]===10)return this.off=t+2,n?-s:s;throw new b}readLine(){let e=Q(this.buf,this.off);if(e===-1)throw new b;let t=X.decode(this.buf.subarray(this.off,e));return this.off=e+2,t}readBulkBytes(e){if(this.buf.length-this.off<e+2)throw new b;let t=this.buf.subarray(this.off,this.off+e);return this.off+=e+2,t}};function Q(r,e=0){let t=r.indexOf(13,e);for(;t!==-1;){if(t+1<r.length&&r[t+1]===10)return t;t=r.indexOf(13,t+1)}return-1}var F=new Set(["message","pmessage"]),_=new Set(["BLPOP","BRPOP","BLMPOP","BRPOPLPUSH","BZPOPMIN","BZPOPMAX","WAIT","XREAD","XREADGROUP"]),w=class{ready=!1;opts;socket=null;parser=new T;pending=[];pendingHead=0;offlineQueue=[];subs=new Map;psubs=new Map;status="idle";retries=0;reconnectTimer=null;socketTimeoutTimer=null;connectPromise=null;closed=!1;connectedOnce=!1;constructor(e={}){this.opts={host:e.host??"127.0.0.1",port:e.port??6379,retryDelayMs:e.retryDelayMs??100,maxRetries:e.maxRetries??10,enableOfflineQueue:e.enableOfflineQueue??!0,maxOfflineQueue:e.maxOfflineQueue??5e3,commandTimeoutMs:e.commandTimeoutMs??0,socketTimeoutMs:e.socketTimeoutMs??0,onCommand:e.onCommand}}connect(){return this.connectPromise?this.connectPromise:(this.closed=!1,this.connectPromise=new Promise((e,t)=>{this.openSocket(),this.onceReady=()=>e(),this.onceFailed=n=>t(n)}).finally(()=>{this.connectPromise=null,this.onceReady=void 0,this.onceFailed=void 0}),this.connectPromise)}onceReady;onceFailed;openSocket(){this.status="connecting";let e=Z.connect(this.opts.port,this.opts.host);this.socket=e,e.on("connect",()=>{if(e.setNoDelay(!0),this.status="ready",this.retries=0,this.connectedOnce){for(let t of this.subs.keys())this.sendNow("SUBSCRIBE",[t]);for(let t of this.psubs.keys())this.sendNow("PSUBSCRIBE",[t])}this.connectedOnce=!0,this.flushOffline(),this.onceReady?.()}),e.on("data",t=>this.onData(new Uint8Array(t))),e.on("error",t=>{this.status==="connecting"&&this.handleDisconnect(t)}),e.on("close",()=>{this.socket=null,this.status!=="closed"&&this.status!=="idle"&&this.handleDisconnect(new h("redis: socket closed"))})}handleDisconnect(e){let t=this.pending.slice(this.pendingHead);this.pending=[],this.pendingHead=0;for(let s of t)s.reject(e);if(this.clearSocketTimeout(),this.closed||this.status==="closed")return;if(this.retries++,this.status="connecting",this.opts.maxRetries>0&&this.retries>this.opts.maxRetries){this.status="closed";let s=e instanceof h?e:new h(`redis: connect to ${this.opts.host}:${this.opts.port} failed`,this.retries,e);this.onceFailed?.(s);return}let n=Math.min(this.opts.retryDelayMs*2**(this.retries-1),5e3);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},n)}onData(e){try{let t=this.parser.pushAll(e);for(let n of t){let s=Array.isArray(n)&&n.length>0?v(n[0],!0):void 0;if(typeof s=="string"&&F.has(s)){this.dispatchSubscribe(v(n,!0));continue}let i=this.pending[this.pendingHead++];if(!i)break;i.timedOut||(n instanceof A?i.reject(n):i.resolve(v(n,!i.asBuffer)))}this.pendingHead>64&&this.pendingHead*2>this.pending.length&&(this.pending=this.pending.slice(this.pendingHead),this.pendingHead=0),this.opts.socketTimeoutMs>0&&(this.pendingHead<this.pending.length?this.armSocketTimeout():this.clearSocketTimeout())}catch(t){let n=this.pending.slice(this.pendingHead);this.pending=[],this.pendingHead=0;for(let s of n)s.reject(t);this.socket?.destroy()}}command(e,...t){let n=t[t.length-1],s=typeof n=="object"&&n!==null&&!(n instanceof Uint8Array)?t.pop():void 0;return this.status==="ready"&&this.socket&&!this.socket.destroyed?this.sendNow(e,t,s?.asBuffer):this.closed||this.status==="closed"||!this.opts.enableOfflineQueue?Promise.reject(new h("redis: not connected")):this.offlineQueue.length>=this.opts.maxOfflineQueue?Promise.reject(new h(`redis: offline queue full (${this.opts.maxOfflineQueue})`)):new Promise((i,o)=>{this.offlineQueue.push({name:e,args:t,resolve:i,reject:o,asBuffer:s?.asBuffer})})}sendNow(e,t,n){let s=performance.now();return new Promise((i,o)=>{let a={resolve:i,reject:o,asBuffer:n,blocking:_.has(e.toUpperCase())};this.armTimeout(a),this.pending.push(a),this.armSocketTimeout(),this.socket.write(C([e,...t]),c=>{if(c){let u=this.pending.indexOf(a);u>=0&&this.pending.splice(u,1),a.reject(c instanceof Error?c:new h("redis: socket write failed"))}})}).then(i=>(this.opts.onCommand&&this.opts.onCommand(e,t,performance.now()-s),i),i=>{throw this.opts.onCommand&&this.opts.onCommand(e,t,performance.now()-s),i})}armTimeout(e){let t=this.opts.commandTimeoutMs;t<=0||(e.timer=setTimeout(()=>{e.timedOut=!0,e.blocking?e.resolve(null):e.reject(new R("redis: command timeout",t))},t))}armSocketTimeout(){let e=this.opts.socketTimeoutMs;e<=0||(this.clearSocketTimeout(),this.socketTimeoutTimer=setTimeout(()=>{this.socketTimeoutTimer=null;let t=new h(`redis: socket timeout (no data in ${e}ms)`),n=this.pending.slice(this.pendingHead);this.pending=[],this.pendingHead=0;for(let s of n)s.reject(t);this.clearSocketTimeout(),this.socket?.destroy()},e))}clearSocketTimeout(){this.socketTimeoutTimer&&(clearTimeout(this.socketTimeoutTimer),this.socketTimeoutTimer=null)}flushOffline(){let e=this.offlineQueue;this.offlineQueue=[];for(let t of e)this.sendNow(t.name,t.args,t.asBuffer).then(t.resolve,t.reject)}batch(e,t){return this.status!=="ready"||!this.socket?Promise.reject(new h("redis: not connected")):new Promise((n,s)=>{let i=[],o=[],a=!1,c=()=>{a||i.length===t&&(a=!0,u&&clearTimeout(u),n(i))};for(let m=0;m<t;m++){let g={resolve:S=>{i.push(S),c()},reject:S=>{i.push(S),c()}};o.push(g),this.pending.push(g)}let u,l=this.opts.commandTimeoutMs;l>0&&(u=setTimeout(()=>{a=!0;for(let m of o)m.timedOut=!0;s(new R("redis: batch timeout",l))},l)),this.socket.write(e),this.armSocketTimeout()})}async subscribe(e,t){this.subs.set(e,t),await this.command("SUBSCRIBE",e)}async psubscribe(e,t){this.psubs.set(e,t),await this.command("PSUBSCRIBE",e)}dispatchSubscribe(e){let[t,n,s]=e;t==="message"?this.subs.get(n)?.(n,s):t==="pmessage"&&this.psubs.get(n)?.(s,e[3]??"")}async close(){this.closed=!0,this.status="closed",this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.clearSocketTimeout();let e=this.pending.slice(this.pendingHead);this.pending=[],this.pendingHead=0;for(let s of e)s.reject(new h("redis: connection closed"));let t=this.offlineQueue;this.offlineQueue=[];for(let s of t)s.reject(new h("redis: connection closed"));let n=this.socket;this.socket=null,n?.destroy()}get connected(){return this.status==="ready"}};var N=class{cmds=[];conn;constructor(e){this.conn=e}set(e,t,n){return this.cmds.push(n!==void 0?{name:"SET",args:[e,t,"EX",n]}:{name:"SET",args:[e,t]}),this}get(e){return this.cmds.push({name:"GET",args:[e]}),this}del(...e){return this.cmds.push({name:"DEL",args:e}),this}incr(e){return this.cmds.push({name:"INCR",args:[e]}),this}expire(e,t){return this.cmds.push({name:"EXPIRE",args:[e,t]}),this}ttl(e){return this.cmds.push({name:"TTL",args:[e]}),this}raw(e,...t){return this.cmds.push({name:e,args:t}),this}async exec(){let e=this.cmds;if(this.cmds=[],e.length===0)return[];let t=Buffer.concat(e.map(n=>Buffer.from(C([n.name,...n.args]))));return this.conn.batch(t,e.length)}};var x=class r{conn;constructor(e){this.conn=e}static async connect(e={}){let t=new w(e);return await t.connect(),new r(t)}command(e,...t){return this.conn.command(e,...t)}get connected(){return this.conn.connected}async get(e){let t=await this.conn.command("GET",e);return t===null?null:String(t)}async getBuffer(e){let t=await this.conn.command("GET",e,{asBuffer:!0});return t===null?null:t instanceof Uint8Array?t:new TextEncoder().encode(String(t))}async set(e,t,n){let s=n!==void 0?await this.conn.command("SET",e,t,"EX",n):await this.conn.command("SET",e,t);return String(s)}async del(...e){let t=await this.conn.command("DEL",...e);return Number(t)}async incr(e){return Number(await this.conn.command("INCR",e))}async expire(e,t){return Number(await this.conn.command("EXPIRE",e,t))}async ttl(e){return Number(await this.conn.command("TTL",e))}async mget(...e){return(await this.conn.command("MGET",...e)).map(n=>n===null?null:String(n))}async mset(...e){let t=await this.conn.command("MSET",...e);return String(t)}async exists(...e){return Number(await this.conn.command("EXISTS",...e))}async setnx(e,t){return Number(await this.conn.command("SETNX",e,t))}async incrby(e,t){return Number(await this.conn.command("INCRBY",e,t))}async hset(e,t,n){return Number(await this.conn.command("HSET",e,t,n))}async hget(e,t){let n=await this.conn.command("HGET",e,t);return n===null?null:String(n)}async hgetall(e){let n=await this.conn.command("HGETALL",e),s={};for(let i=0;i+1<n.length;i+=2)s[String(n[i])]=String(n[i+1]);return s}async hdel(e,...t){return Number(await this.conn.command("HDEL",e,...t))}async lpush(e,...t){return Number(await this.conn.command("LPUSH",e,...t))}async rpush(e,...t){return Number(await this.conn.command("RPUSH",e,...t))}async lpop(e){let t=await this.conn.command("LPOP",e);return t===null?null:String(t)}async rpop(e){let t=await this.conn.command("RPOP",e);return t===null?null:String(t)}async lrange(e,t,n){return(await this.conn.command("LRANGE",e,t,n)).map(String)}async sadd(e,...t){return Number(await this.conn.command("SADD",e,...t))}async srem(e,...t){return Number(await this.conn.command("SREM",e,...t))}async smembers(e){return(await this.conn.command("SMEMBERS",e)).map(String)}async zadd(e,t,n){return Number(await this.conn.command("ZADD",e,t,n))}async zrange(e,t,n){return(await this.conn.command("ZRANGE",e,t,n)).map(String)}pipeline(){return new N(this.conn)}async jsonGet(e){let t=await this.conn.command("GET",e);if(t===null)return null;try{return JSON.parse(String(t))}catch{throw new E(`redis: value of key '${e}' is not valid JSON`)}}async jsonSet(e,t,n){return this.set(e,JSON.stringify(t),n)}async cache(e,t,n){let s=await this.jsonGet(e);if(s!==null)return s;let i=await t();return i!==null&&await this.jsonSet(e,i,n),i}async close(){await this.conn.close()}};var k=class{conn;constructor(e={}){this.conn=new w(e)}async connect(){await this.conn.connect()}subscribe(e,t){return this.conn.subscribe(e,t)}psubscribe(e,t){return this.conn.psubscribe(e,t)}async close(){await this.conn.close()}};var D=class r{clients=[];rr=0;replenishWaiters=[];closed=!1;keyPrefix;opts;initPromise=null;constructor(e={}){this.keyPrefix=e.keyPrefix??"",this.opts=e}static async create(e={}){let t=new r(e);return await t.ensure(),t}readyPromise=null;ensure(){return this.readyPromise?this.readyPromise:(this.initPromise||(this.initPromise=this.init()),this.initPromise)}async init(){let e=this.opts.poolSize??5;this.clients=await Promise.all(Array.from({length:e},()=>x.connect(this.opts))),this.readyPromise=Promise.resolve()}k(e){return this.keyPrefix+e}async acquireHealthy(){if(this.closed)throw new h("redis: pool is closed");for(;this.clients.length>0;){let e=this.rr%this.clients.length;this.rr++;let t=this.clients[e];if(t.connected)return t;this.clients.splice(e,1),t.close().catch(()=>{}),this.replenish()}return new Promise((e,t)=>{let n=()=>{this.clients.length>0&&this.clients[0].connected?e(this.clients[0]):t(new h("redis: pool exhausted after reconnect wait"))};this.replenishWaiters.push(n),setTimeout(()=>{let s=this.replenishWaiters.indexOf(n);s>=0&&this.replenishWaiters.splice(s,1),t(new h("redis: no healthy connection available"))},1e3)})}replenish(){this.closed||x.connect(this.opts).then(e=>{if(this.closed){e.close();return}this.clients.push(e);let t=this.replenishWaiters;this.replenishWaiters=[];for(let n of t)n()}).catch(()=>{setTimeout(()=>this.replenish(),500)})}async createConnection(){await this.ensure();let e=new w(this.opts);return await e.connect(),e}async command(e,...t){return await this.ensure(),(await this.acquireHealthy()).command(e,...t)}async get(e){return await this.ensure(),(await this.acquireHealthy()).get(this.k(e))}async getBuffer(e){return await this.ensure(),(await this.acquireHealthy()).getBuffer(this.k(e))}async set(e,t,n){return await this.ensure(),(await this.acquireHealthy()).set(this.k(e),t,n)}async del(...e){return await this.ensure(),(await this.acquireHealthy()).del(...e.map(n=>this.k(n)))}async incr(e){return await this.ensure(),(await this.acquireHealthy()).incr(this.k(e))}async expire(e,t){return await this.ensure(),(await this.acquireHealthy()).expire(this.k(e),t)}async ttl(e){return await this.ensure(),(await this.acquireHealthy()).ttl(this.k(e))}async jsonGet(e){return await this.ensure(),(await this.acquireHealthy()).jsonGet(this.k(e))}async jsonSet(e,t,n){return await this.ensure(),(await this.acquireHealthy()).jsonSet(this.k(e),t,n)}async cache(e,t,n){return await this.ensure(),(await this.acquireHealthy()).cache(this.k(e),t,n)}async mget(...e){return await this.ensure(),(await this.acquireHealthy()).mget(...e.map(n=>this.k(n)))}async mset(...e){await this.ensure();let t=await this.acquireHealthy(),n=e.map((s,i)=>i%2===0?this.k(String(s)):s);return t.mset(...n)}async exists(...e){return await this.ensure(),(await this.acquireHealthy()).exists(...e.map(n=>this.k(n)))}async setnx(e,t){return await this.ensure(),(await this.acquireHealthy()).setnx(this.k(e),t)}async incrby(e,t){return await this.ensure(),(await this.acquireHealthy()).incrby(this.k(e),t)}async hset(e,t,n){return await this.ensure(),(await this.acquireHealthy()).hset(this.k(e),t,n)}async hget(e,t){return await this.ensure(),(await this.acquireHealthy()).hget(this.k(e),t)}async hgetall(e){return await this.ensure(),(await this.acquireHealthy()).hgetall(this.k(e))}async hdel(e,...t){return await this.ensure(),(await this.acquireHealthy()).hdel(this.k(e),...t)}async lpush(e,...t){return await this.ensure(),(await this.acquireHealthy()).lpush(this.k(e),...t)}async rpush(e,...t){return await this.ensure(),(await this.acquireHealthy()).rpush(this.k(e),...t)}async lpop(e){return await this.ensure(),(await this.acquireHealthy()).lpop(this.k(e))}async rpop(e){return await this.ensure(),(await this.acquireHealthy()).rpop(this.k(e))}async lrange(e,t,n){return await this.ensure(),(await this.acquireHealthy()).lrange(this.k(e),t,n)}async sadd(e,...t){return await this.ensure(),(await this.acquireHealthy()).sadd(this.k(e),...t)}async srem(e,...t){return await this.ensure(),(await this.acquireHealthy()).srem(this.k(e),...t)}async smembers(e){return await this.ensure(),(await this.acquireHealthy()).smembers(this.k(e))}async zadd(e,t,n){return await this.ensure(),(await this.acquireHealthy()).zadd(this.k(e),t,n)}async zrange(e,t,n){return await this.ensure(),(await this.acquireHealthy()).zrange(this.k(e),t,n)}async pipeline(){return await this.ensure(),(await this.acquireHealthy()).pipeline()}async publish(e,t){await this.ensure();let n=await this.acquireHealthy();return Number(await n.command("PUBLISH",e,t))}createSubscriber(){return new k({...this.opts})}async flushdb(){await this.ensure();let t=await(await this.acquireHealthy()).command("FLUSHDB");return String(t)}async close(){this.closed=!0,this.readyPromise=null,await Promise.all(this.clients.map(e=>e.close())),this.clients=[]}get size(){return this.clients.length}};var Y=[{name:"GET",minArity:1,maxArity:1},{name:"KEYS",minArity:1,maxArity:1},{name:"SET",minArity:2,maxArity:5,parse(r){let[e,t,...n]=r,s,i=!1;for(let a=0;a<n.length;a+=2){let c=String(n[a]).toUpperCase(),u=n[a+1];if(c==="EX"&&u!==void 0)s=Number(u)*1e3;else if(c==="PX"&&u!==void 0)s=Number(u);else if(c==="KEEPTTL")i=!0;else throw new d(`ERR syntax error: SET \u9009\u9879 ${c} \u4E0D\u652F\u6301`)}if(s!==void 0&&!Number.isFinite(s))throw new d("ERR value is not an integer or out of range");let o={keepTtl:i};return s!==void 0&&(o.ttl=s),{args:[String(e),String(t)],meta:o}}},{name:"EXISTS",minArity:1},{name:"DEL",minArity:1},{name:"EXPIRE",minArity:2,maxArity:3,parse(r){return{args:[String(r[0]),String(r[1])],meta:{ttlMs:Number(r[1])*1e3}}}},{name:"PEXPIRE",minArity:2,maxArity:3,parse(r){return{args:[String(r[0]),String(r[1])],meta:{ttlMs:Number(r[1])}}}},{name:"TTL",minArity:1,maxArity:1},{name:"INCR",minArity:1,maxArity:1},{name:"INCRBY",minArity:2,maxArity:2},{name:"STRLEN",minArity:1,maxArity:1},{name:"APPEND",minArity:2,maxArity:2},{name:"MGET",minArity:1},{name:"MSET",minArity:2},{name:"HSET",minArity:3},{name:"HGET",minArity:2,maxArity:2},{name:"HDEL",minArity:2},{name:"HGETALL",minArity:1,maxArity:1},{name:"HEXISTS",minArity:2,maxArity:2},{name:"HLEN",minArity:1,maxArity:1},{name:"HKEYS",minArity:1,maxArity:1},{name:"HVALS",minArity:1,maxArity:1},{name:"HINCRBY",minArity:3,maxArity:3},{name:"LPUSH",minArity:2},{name:"RPUSH",minArity:2},{name:"LPOP",minArity:1,maxArity:2},{name:"RPOP",minArity:1,maxArity:2},{name:"LLEN",minArity:1,maxArity:1},{name:"LRANGE",minArity:3,maxArity:3},{name:"LSET",minArity:3,maxArity:3},{name:"LINDEX",minArity:2,maxArity:2},{name:"BLPOP",minArity:2,parse(r){let e=Number(r[r.length-1]);if(!Number.isFinite(e))throw new d("ERR timeout is not a float");return{args:r.map(String),meta:{timeoutMs:e*1e3}}}},{name:"SADD",minArity:2},{name:"SREM",minArity:2},{name:"SMEMBERS",minArity:1,maxArity:1},{name:"SISMEMBER",minArity:2,maxArity:2},{name:"SCARD",minArity:1,maxArity:1},{name:"ZADD",minArity:3},{name:"ZREM",minArity:2},{name:"ZRANGE",minArity:3},{name:"ZRANGEBYSCORE",minArity:3},{name:"ZREMRANGEBYSCORE",minArity:3,maxArity:3},{name:"ZCARD",minArity:1,maxArity:1},{name:"ZSCORE",minArity:2,maxArity:2},{name:"XADD",minArity:4},{name:"XREADGROUP",minArity:5},{name:"XACK",minArity:3},{name:"XPENDING",minArity:2},{name:"XAUTOCLAIM",minArity:5},{name:"XGROUP",minArity:3},{name:"XLEN",minArity:1,maxArity:1},{name:"XRANGE",minArity:3},{name:"XDEL",minArity:2},{name:"SUBSCRIBE",minArity:1},{name:"UNSUBSCRIBE",minArity:0},{name:"PSUBSCRIBE",minArity:1},{name:"PUNSUBSCRIBE",minArity:0},{name:"PUBLISH",minArity:2,maxArity:2},{name:"PING",minArity:0},{name:"ECHO",minArity:1,maxArity:1},{name:"SELECT",minArity:1,maxArity:1},{name:"FLUSHALL",minArity:0},{name:"FLUSHDB",minArity:0},{name:"CLIENT",minArity:1},{name:"INFO",minArity:0},{name:"TIME",minArity:0},{name:"DBSIZE",minArity:0},{name:"AUTH",minArity:1,maxArity:2},{name:"QUIT",minArity:0}],J=new Map(Y.map(r=>[r.name,r]));function j(r){let e=r.name.toUpperCase(),t=J.get(e);if(!t)throw new d(`ERR unknown command '${e}'`);if(r.args.length<t.minArity)throw new d(`ERR wrong number of arguments for '${e}' command`);if(t.maxArity!==void 0&&r.args.length>t.maxArity)throw new d(`ERR wrong number of arguments for '${e}' command`);return{def:t,parsed:t.parse?t.parse(r.args):{args:r.args}}}var L=class{cmds=[];redis;constructor(e){this.redis=e}set(e,t,n){return this.cmds.push(n!==void 0?{name:"SET",args:[e,t,"EX",n]}:{name:"SET",args:[e,t]}),this}get(e){return this.cmds.push({name:"GET",args:[e]}),this}del(...e){return this.cmds.push({name:"DEL",args:e}),this}incr(e){return this.cmds.push({name:"INCR",args:[e]}),this}expire(e,t){return this.cmds.push({name:"EXPIRE",args:[e,t]}),this}ttl(e){return this.cmds.push({name:"TTL",args:[e]}),this}raw(e,...t){return this.cmds.push({name:e,args:t}),this}async exec(){let e=this.cmds;this.cmds=[];let t=[];for(let n of e)try{t.push(await this.redis.command(n.name,...n.args))}catch(s){t.push(s)}return t}},I=class{subs=new Map;connected=!1;redis;constructor(e){this.redis=e,e._registerSubscriber(this)}async connect(){this.connected=!0}async subscribe(e,t){this.subs.set(`s:${e}`,t)}async psubscribe(e,t){this.subs.set(`p:${e}`,t)}async close(){this.redis._unregisterSubscriber(this),this.subs.clear()}_dispatch(e,t){if(!this.connected)return!1;let n=!1;for(let[s,i]of this.subs)if(s.startsWith("s:"))s.slice(2)===e&&(i(e,t),n=!0);else{let o=s.slice(2);new RegExp("^"+o.split("*").map(c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$").test(e)&&(i(e,t),n=!0)}return n}},H=class{strings=new Map;hashes=new Map;lists=new Map;sets=new Map;zsets=new Map;streams=new Map;subscribers=new Set;seq=0;closed=!1;_registerSubscriber(e){this.subscribers.add(e)}_unregisterSubscriber(e){this.subscribers.delete(e)}expired(e){let t=this.strings.get(e);return!t||t.expiresAt===null?!1:t.expiresAt<=Date.now()?(this.strings.delete(e),!0):!1}async get(e){return this.assertOpen(),this.expired(e)?null:this.strings.get(e)?.value??null}async getBuffer(e){let t=await this.get(e);return t===null?null:new TextEncoder().encode(t)}async set(e,t,n){return this.assertOpen(),this.strings.set(e,{value:String(t),expiresAt:n?Date.now()+n*1e3:null}),"OK"}async del(...e){this.assertOpen();let t=0;for(let n of e)this.strings.delete(n)&&t++,this.hashes.delete(n)&&t++,this.lists.delete(n)&&t++,this.sets.delete(n)&&t++,this.zsets.delete(n)&&t++,this.streams.delete(n)&&t++;return t}async incr(e){this.assertOpen();let t=this.strings.get(e);t&&t.expiresAt!==null&&t.expiresAt<=Date.now()&&this.strings.delete(e);let n=Number(this.strings.get(e)?.value??"0");if(!Number.isInteger(n))throw new d("ERR value is not an integer or out of range");let s=n+1;return this.strings.set(e,{value:String(s),expiresAt:this.strings.get(e)?.expiresAt??null}),s}async incrby(e,t){this.assertOpen();let n=this.strings.get(e);n&&n.expiresAt!==null&&n.expiresAt<=Date.now()&&this.strings.delete(e);let s=Number(this.strings.get(e)?.value??"0");if(!Number.isInteger(s)||!Number.isInteger(t))throw new d("ERR value is not an integer or out of range");let i=s+t;return this.strings.set(e,{value:String(i),expiresAt:this.strings.get(e)?.expiresAt??null}),i}async expire(e,t){this.assertOpen();let n=this.strings.get(e);return n?(n.expiresAt=Date.now()+t*1e3,1):0}async ttl(e){this.assertOpen();let t=this.strings.get(e);if(!t)return-2;if(t.expiresAt===null)return-1;let n=t.expiresAt-Date.now();return Math.max(0,Math.ceil(n/1e3))}async mget(...e){return Promise.all(e.map(t=>this.get(t)))}async mset(...e){this.assertOpen();for(let t=0;t<e.length;t+=2)this.strings.set(String(e[t]),{value:String(e[t+1]),expiresAt:null});return"OK"}async exists(...e){this.assertOpen();let t=0;for(let n of e)await this.get(n)!==null&&t++;return t}async setnx(e,t){this.assertOpen();let n=this.strings.get(e);return n&&n.expiresAt!==null&&n.expiresAt<=Date.now()&&this.strings.delete(e),this.strings.has(e)?0:(this.strings.set(e,{value:String(t),expiresAt:null}),1)}async jsonGet(e){let t=await this.get(e);if(t===null)return null;try{return JSON.parse(t)}catch{return t}}async jsonSet(e,t,n){return this.set(e,JSON.stringify(t),n)}async cache(e,t,n){let s=await this.get(e);if(s!==null)try{return JSON.parse(s)}catch{return s}let i=await t();return i!==null&&await this.jsonSet(e,i,n),i}async hset(e,t,n){this.assertOpen();let s=this.hashes.get(e);s||(s=new Map,this.hashes.set(e,s));let i=!s.has(t);return s.set(t,String(n)),i?1:0}async hget(e,t){return this.assertOpen(),this.hashes.get(e)?.get(t)??null}async hgetall(e){this.assertOpen();let t=this.hashes.get(e);return t?Object.fromEntries(t):{}}async hdel(e,...t){this.assertOpen();let n=this.hashes.get(e);if(!n)return 0;let s=0;for(let i of t)n.delete(i)&&s++;return n.size===0&&this.hashes.delete(e),s}list(e){let t=this.lists.get(e);return t||(t=[],this.lists.set(e,t)),t}async lpush(e,...t){this.assertOpen();let n=this.list(e);for(let s of t)n.unshift(String(s));return n.length}async rpush(e,...t){this.assertOpen();let n=this.list(e);for(let s of t)n.push(String(s));return n.length}async lpop(e){this.assertOpen();let t=this.lists.get(e);if(!t||t.length===0)return null;let n=t.shift();return t.length===0&&this.lists.delete(e),n}async rpop(e){this.assertOpen();let t=this.lists.get(e);if(!t||t.length===0)return null;let n=t.pop();return t.length===0&&this.lists.delete(e),n}async lrange(e,t,n){this.assertOpen();let s=this.lists.get(e)??[],i=t<0?Math.max(0,s.length+t):t,o=n<0?s.length+n:Math.min(s.length-1,n);return i>o?[]:s.slice(i,o+1)}async sadd(e,...t){this.assertOpen();let n=this.sets.get(e);n||(n=new Set,this.sets.set(e,n));let s=0;for(let i of t){let o=String(i);n.has(o)||(n.add(o),s++)}return s}async srem(e,...t){this.assertOpen();let n=this.sets.get(e);if(!n)return 0;let s=0;for(let i of t)n.delete(String(i))&&s++;return n.size===0&&this.sets.delete(e),s}async smembers(e){return this.assertOpen(),[...this.sets.get(e)??[]]}async zadd(e,t,n){this.assertOpen();let s=this.zsets.get(e);s||(s=new Map,this.zsets.set(e,s));let i=String(n),o=!s.has(i);return s.set(i,t),o?1:0}async zrange(e,t,n){this.assertOpen();let s=this.zsets.get(e);if(!s)return[];let i=[...s.entries()].sort((c,u)=>c[1]-u[1]).map(([c])=>c),o=t<0?Math.max(0,i.length+t):t,a=n<0?i.length+n:Math.min(i.length-1,n);return o>a?[]:i.slice(o,a+1)}async publish(e,t){this.assertOpen();let n=String(t),s=0;for(let i of this.subscribers)i._dispatch(e,n)&&s++;return s}async pipeline(){return new L(this)}createSubscriber(){return new I(this)}async createConnection(){this.assertOpen();let e=this;return{get connected(){return!e.closed},command:(t,...n)=>e.command(t,...n),close:async()=>{}}}async flushdb(){return this.assertOpen(),this.strings.clear(),this.hashes.clear(),this.lists.clear(),this.sets.clear(),this.zsets.clear(),this.streams.clear(),"OK"}async close(){this.closed=!0;for(let e of this.subscribers)e.close().catch(()=>{});this.subscribers.clear()}assertOpen(){if(this.closed)throw new d("memory-redis: instance is closed")}async command(e,...t){this.assertOpen(),j({name:e,args:t});let[n,s,i,o,a]=t;switch(e.toUpperCase()){case"GET":return this.get(String(n));case"LPUSH":return this.lpush(String(n),...t.slice(1));case"RPUSH":return this.rpush(String(n),...t.slice(1));case"LPOP":return this.lpop(String(n));case"RPOP":return this.rpop(String(n));case"LLEN":return this.lists.get(String(n))?.length??0;case"LRANGE":return this.lrange(String(n),Number(s),Number(i));case"SET":return this.set(String(n),String(s),i!==void 0?Number(i==="EX"?o:i):void 0);case"DEL":return this.del(...t.map(String));case"INCR":return this.incr(String(n));case"EXPIRE":return this.expire(String(n),Number(s));case"PEXPIRE":{let c=this.strings.get(String(n));return c?(c.expiresAt=Date.now()+Number(s),1):0}case"TTL":return this.ttl(String(n));case"FLUSHDB":return this.flushdb();case"ZADD":return this.zadd(String(n),Number(s),String(i));case"ZRANGEBYSCORE":{let c=this.zsets.get(String(n));if(!c)return[];let u=Number(s),l=Number(i);return[...c.entries()].filter(([,m])=>m>=u&&m<=l).sort((m,g)=>m[1]-g[1]).map(([m])=>m)}case"ZREM":return this.zrem(String(n),String(s));case"ZCARD":return this.zsets.get(String(n))?.size??0;case"ZREMRANGEBYSCORE":return this.zremrangebyscore(String(n),Number(s),Number(i));case"XADD":return this.xadd(String(n),String(s),t.slice(2));case"XLEN":return this.streams.get(String(n))?.entries.length??0;case"XGROUP":return String(n).toUpperCase()==="DESTROY"?this.xgroupDestroy(String(s),String(i)):this.xgroup(String(s),String(i),String(o));case"XREADGROUP":return this.xreadgroup(String(n),String(s),String(i),t);case"XACK":return this.xack(String(n),String(s),String(i));case"XAUTOCLAIM":return this.xautoclaim(String(n),String(s),String(i),Number(o),t);case"XPENDING":return this.xpending(String(n),String(s));default:throw new d(`memory-redis: command '${e}' unsupported (\u8BDA\u5B9E\u88C1\u526A\u2014\u2014\u9700\u771F\u5E93/\u8865\u5B9E\u73B0)`)}}async zrem(e,t){let n=this.zsets.get(e);if(!n)return 0;let s=n.delete(t)?1:0;return n.size===0&&this.zsets.delete(e),s}async zremrangebyscore(e,t,n){let s=this.zsets.get(e);if(!s)return 0;let i=0;for(let[o,a]of[...s.entries()])a>=t&&a<=n&&(s.delete(o),i++);return s.size===0&&this.zsets.delete(e),i}stream(e){let t=this.streams.get(e);return t||(t={entries:[],lastDelivered:new Map},this.streams.set(e,t)),t}async xadd(e,t,n){let s=this.stream(e);t==="*"&&(t=`${Date.now()}-${this.seq++}`);let i={};for(let o=0;o<n.length;o+=2)i[String(n[o])]=String(n[o+1]);return s.entries.push({id:t,fields:i,pending:null}),t}async xgroup(e,t,n){if(this.strings.has(e)&&!this.streams.has(e))throw new Error("WRONGTYPE Operation against a key holding the wrong kind of value");let s=this.stream(e);if(s.lastDelivered.has(t))throw new Error(`BUSYGROUP Consumer Group name already exists: ${t}`);return s.lastDelivered.set(t,n==="$"?s.entries.length:0),"OK"}async xgroupDestroy(e,t){let n=this.streams.get(e);return n&&n.lastDelivered.delete(t)?1:0}async xreadgroup(e,t,n,s){let i=s.indexOf("STREAMS"),o=String(s[i+1]),a=this.stream(o),c=s.indexOf("COUNT"),u=c>=0?Number(s[c+1]):1,l=s.indexOf("BLOCK"),m=l>=0?Number(s[l+1]):0,g=String(s[i+2]),S=a.lastDelivered.get(t);if(g===">"){let P=typeof S=="number"?S:0,q=a.entries.slice(P).filter(p=>!p.pending);if(q.length===0){if(m>0){await new Promise(y=>setTimeout(y,m));let p=a.lastDelivered.get(t),V=typeof p=="number"?p:0,z=a.entries.slice(V).filter(y=>!y.pending);if(z.length===0)return null;let B=z.slice(0,u);for(let y of B)y.pending={consumer:n,idleSince:Date.now()};return a.lastDelivered.set(t,V+B.length),[[o,B.map(y=>[y.id,M(y.fields)])]]}return null}let U=q.slice(0,u);for(let p of U)p.pending={consumer:n,idleSince:Date.now()};return a.lastDelivered.set(t,P+U.length),[[o,U.map(p=>[p.id,M(p.fields)])]]}let $=a.entries.filter(P=>P.pending?.consumer===n);return[[o,$.slice(0,u).map(P=>[P.id,M(P.fields)])]]}async xack(e,t,...n){let s=this.streams.get(e);if(!s)return 0;let i=0;for(let o of n){let a=s.entries.find(c=>c.id===o);a?.pending&&(a.pending=null,i++)}return i}async xautoclaim(e,t,n,s,i){let o=this.streams.get(e);if(!o)return["0-0",[]];let a=i.indexOf("COUNT"),c=a>=0?Number(i[a+1]):1,u=Date.now(),m=o.entries.filter(g=>g.pending&&u-g.pending.idleSince>=s).slice(0,c);for(let g of m)g.pending={consumer:n,idleSince:u};return["0-0",m.map(g=>[g.id,M(g.fields)])]}async xpending(e,t){let n=this.streams.get(e);if(!n)return[0,"0-0","0-0",[]];let s=n.entries.filter(o=>o.pending);if(s.length===0)return[0,"0-0","0-0",[]];let i=new Map;for(let o of s){let a=o.pending.consumer;i.set(a,(i.get(a)??0)+1)}return[s.length,s[0].id,s[s.length-1].id,[...i.entries()].map(([o,a])=>[o,a])]}};function M(r){let e=[];for(let[t,n]of Object.entries(r))e.push(t,n);return e}import{AsyncLocalStorage as W}from"node:async_hooks";var K=new W;function ee(r){let e=typeof r=="string"?{url:r}:r??{};if(e.memory)return i();let t=e.url??process.env.REDIS_URL;if(!t)throw new Error("redis: REDIS_URL is not set. Pass a URL or set the REDIS_URL environment variable.");let n=new URL(t),s=new D({host:n.hostname,port:Number(n.port||6379),poolSize:e.poolSize,keyPrefix:e.keyPrefix,enableOfflineQueue:e.enableOfflineQueue,commandTimeoutMs:e.commandTimeoutMs,socketTimeoutMs:e.socketTimeoutMs,onCommand:e.onCommand?(a,c,u)=>{let l=K.getStore();e.onCommand?.(a,c,u,l||void 0)}:void 0});function i(){let a=new H,c=((u,l,m)=>(l.redis=a,m(u,l)));return c.__meta={injects:["redis"],depends:[]},c.redis=a,c.close=async()=>{await a.flushdb()},c}let o=(async(a,c,u)=>(c.redis=s,K.run(a.headers.get("x-trace-id")??"",()=>u(a,c))));return o.__meta={injects:["redis"],depends:[]},o.redis=s,o.close=()=>s.close(),o}export{ee as redis};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID as I}from"node:crypto";var A=[[0,59],[0,23],[1,31],[1,12],[0,6]];function F(n,s){let[e,t]=A[s],i=["minute","hour","day","month","weekday"][s];if(n==="*")return null;if(n.startsWith("*/")){let c=Number(n.slice(2));if(!Number.isInteger(c)||c<=0||c>t)throw new Error(`cron: invalid step '${n}' in ${i} field (must be 1..${t})`);let o=new Set;for(let d=e;d<=t;d+=c)o.add(d);return o}let w=new Set;for(let c of n.split(",")){if(c==="")throw new Error(`cron: empty item in '${n}' (${i})`);if(c.includes("-")){let[o,d]=c.split("/"),m=d!==void 0?Number(d):1,[h,f]=o.split("-").map(Number);if(!Number.isInteger(h)||!Number.isInteger(f)||h<e||f>t||h>f)throw new Error(`cron: invalid range '${c}' in ${i} field (${e}..${t})`);if(!Number.isInteger(m)||m<=0)throw new Error(`cron: invalid step in '${c}'`);for(let g=h;g<=f;g+=m)w.add(g)}else{let o=Number(c);if(!Number.isInteger(o)||o<e||o>t)throw new Error(`cron: value '${c}' out of range ${e}..${t} in ${i} field`);w.add(o)}}return w}function M(n){let s=n.trim().split(/\s+/);if(s.length!==5)throw new Error(`cron: expected 5 fields (min hour dom month dow), got ${s.length}: '${n}'`);let e=s.map((t,i)=>F(t,i));return{fields:e.map(t=>({values:t})),domExplicit:e[2]!==null,dowExplicit:e[4]!==null}}function E(n,s){return n===null?!0:n.has(s)}function H(n,s,e){let t=E(n.fields[2].values,s),i=E(n.fields[4].values,e);return n.domExplicit&&n.dowExplicit?t||i:n.domExplicit?t:n.dowExplicit?i:!0}function k(n,s,e,t){if(n===null)return s;for(let i=s;i<=t;i++)if(n.has(i))return i;return null}function v(n,s){let e=new Date(s.getTime());e.setSeconds(0,0),e.setMinutes(e.getMinutes()+1);let t=s.getTime()+5*366*24*3600*1e3;for(;e.getTime()<=t;){let i=e.getFullYear(),w=e.getMonth()+1,c=e.getDate(),o=e.getDay();if(!E(n.fields[3].values,w)){e.setMonth(w,1),e.setHours(0,0,0,0),e.setMonth(w);continue}if(!H(n,c,o)){e.setDate(c+1),e.setHours(0,0,0,0);continue}let d=e.getHours(),m=k(n.fields[1].values,d,0,23);if(m===null){e.setDate(c+1),e.setHours(0,0,0,0);continue}if(m!==d){e.setHours(m,0,0,0);continue}let h=e.getMinutes(),f=k(n.fields[0].values,h,0,59);if(f===null){e.setHours(d+1,0,0,0);continue}if(f!==h){e.setMinutes(f,0,0);continue}return e}throw new Error("cron: no next run within 5 years (invalid expression?)")}function q(n){let s=n.prefix??"wf:sched:",e=n.tickMs??1e3,t=`${s}delayed`,i=`${s}crons`,w=n.queue,c=null;function o(){return c||(c=n.redis.createConnection(),c.catch(()=>{c=null})),c}let d=!1,m=null;async function h(){await f();let r;try{r=await(await o()).command("ZRANGEBYSCORE",t,0,Date.now())}catch{return}for(let a of r){let l;try{l=await(await o()).command("ZREM",t,a)}catch{return}if(l===1)try{let u=JSON.parse(a);await w.queue.add(u.name,u.data)}catch(u){console.error("[scheduler] enqueue:",u instanceof Error?u.message:u),await(await o()).command("ZADD",t,Date.now(),a).catch(()=>{})}}}async function f(){let r;try{r=await(await o()).command("HGETALL",i)}catch{return}let a=Date.now(),l=r;for(let u=0;u+1<l.length;u+=2){let C=l[u],b=l[u+1],S;try{S=JSON.parse(b)}catch{continue}let O=M(S.expr),y=S.nextRunAt;for(;y<=a;){let x=y,P=JSON.stringify({id:`cron:${C}:${x}`,name:S.name,data:S.data});try{await(await o()).command("ZADD",t,"NX",x,P)}catch{break}y=v(O,new Date(x)).getTime()}y!==S.nextRunAt&&await(await o()).command("HSET",i,C,JSON.stringify({...S,nextRunAt:y}))}}let g=async(r,a,l)=>{let u=M(r),C=v(u,new Date),b=JSON.stringify({expr:r,name:a,data:l,nextRunAt:C.getTime()});await(await o()).command("HSET",i,a,b)},N=async r=>{let a=await(await o()).command("HDEL",i,r);try{let l=await(await o()).command("ZRANGE",t,0,-1);for(let u of l)try{JSON.parse(u).name===r&&await(await o()).command("ZREM",t,u)}catch{}}catch{}return a===1};async function $(){d||(d=!0,await o(),await h(),m=setInterval(()=>{h().catch(r=>console.error("[scheduler] tick:",r instanceof Error?r.message:r))},e),m.unref?.())}let D=async(r,a,l={})=>{let u=l.delayMs??0,C=l.when?l.when.getTime():Date.now()+u;if(!Number.isFinite(C))throw new Error("scheduler: invalid when/delayMs");let b=I(),S=JSON.stringify({id:b,name:r,data:a});return await(await o()).command("ZADD",t,C,S),{id:b}},R=async r=>{try{let a=await(await o()).command("ZRANGE",t,0,-1);for(let l of a)try{if(JSON.parse(l).id===r&&await(await o()).command("ZREM",t,l)===1)return!0}catch{}}catch{}return!1},p=(async(r,a,l)=>(a.schedule=D,a.cron=g,a.cancelCron=N,a.cancelSchedule=R,l(r,a)));return p.__meta={injects:["schedule","cron","cancelCron","cancelSchedule"],depends:["queue"]},p.schedule=D,p.cron=g,p.cancelCron=N,p.cancelSchedule=R,p.close=async()=>{d=!1,m&&(clearInterval(m),m=null),c&&await c.then(r=>r.close()).catch(()=>{})},$().catch(r=>console.error("[scheduler] start:",r instanceof Error?r.message:r)),p}export{q as scheduler};
|
|
@@ -34,7 +34,7 @@ declare module '../../server/types.ts' {
|
|
|
34
34
|
html: UiHtmlTag;
|
|
35
35
|
/** 编译 TSX → JS bundle Response(支持包名 weifuwu/ui-dom 或文件路径) */
|
|
36
36
|
js: (entryPath: string) => Promise<Response>;
|
|
37
|
-
/** 读取 CSS → CSS Response(支持包名 weifuwu/layout、weifuwu/components/style.css 或文件路径) */
|
|
37
|
+
/** 读取 CSS → CSS Response(支持包名 weifuwu/client/layout、weifuwu/client/components/style.css 或文件路径) */
|
|
38
38
|
css: (entryPath: string) => Promise<Response>;
|
|
39
39
|
/**
|
|
40
40
|
* SSR 渲染组件 → HTML 片段(HtmlSafe,可直接内联进 ctx.ui.html 模板)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
var Kn=Object.defineProperty;var Vt=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var zn=(n,e)=>{for(var t in e)Kn(n,t,{get:e[t],enumerable:!0})};function bt(n,e){return!n.startsWith("aria-")||typeof e!="boolean"?null:e?"true":"false"}function vt(n,e,t){if(e==="innerHTML"||e==="textContent"||e==="value"){n[e]=t;return}if(t==null){n.removeAttribute(e);return}let o=bt(e,t);if(o!==null){n.setAttribute(e,o);return}if(To.has(e)){n.setAttribute(e,t?"true":"false");return}if(t===!1){n.removeAttribute(e);return}if(e==="class"||e==="className"){n.setAttribute("class",String(t));return}if(typeof t=="boolean"){n.setAttribute(e,"");return}n.setAttribute(e,String(t))}var To,ht=Vt(()=>{"use strict";To=new Set(["draggable","contenteditable","spellcheck"])});var Vn={};zn(Vn,{VOID_ELEMENTS:()=>Nn,attrsToHtml:()=>Pn,commandToHtml:()=>Qo,escapeHtml:()=>we,htmlDocument:()=>er,kebab:()=>Mn});function we(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Mn(n){return n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function Pn(n){let e=[];for(let[t,o]of Object.entries(n)){let r=bt(t,o);if(r!==null){e.push(`${t}="${r}"`);continue}if(!(o==null||o===!1))if(t==="style"&&o&&typeof o=="object"){let i=Object.entries(o).filter(([,s])=>s!=null&&s!==!1).map(([s,a])=>`${Mn(s)}: ${a}`).join("; ");i&&e.push(`style="${we(i)}"`)}else typeof o=="boolean"?e.push(`${t}=""`):e.push(`${t}="${we(String(o))}"`)}return e.length?" "+e.join(" "):""}function Qo(){let n=[];return new TransformStream({transform(e,t){switch(e.op){case"create":n.push(e.tag),t.enqueue(`<${e.tag}${Pn(e.attrs)}>`);break;case"createText":t.enqueue(we(e.value));break;case"createAnchor":t.enqueue("<!--wf-hole-->");break;case"close":{let o=n.pop();o&&!Nn.has(o)&&t.enqueue(`</${o}>`);break}case"setText":t.enqueue(we(e.value));break;case"insert":case"remove":case"setProp":case"ref":case"unref":case"mount":case"unmount":case"move":case"done":break}}})}function er(n,e={}){let t=e.rootId??"root",o=e.data?`<script>window.__DATA__=${JSON.stringify(e.data).replace(/</g,"\\u003c")}</script>`:"";return`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${we(e.title??"")}</title></head><body><div id="${t}">${n}</div>${o}</body></html>`}var Nn,An=Vt(()=>{"use strict";ht();Nn=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"])});import{build as sr}from"esbuild";import{readFile as Dn,stat as Ot}from"node:fs/promises";import{createHash as ir}from"node:crypto";import{resolve as Ge,dirname as Fn,basename as ar}from"node:path";import{fileURLToPath as lr}from"node:url";import{readFile as Lt,readdir as Yn}from"node:fs/promises";var He=(n,e)=>e&&Object.keys(e).length?`${n} { ${Object.entries(e).map(([t,o])=>`${t}: ${o};`).join(" ")} }`:"";function At(n){let e=[];for(let t of n){let o=`.${t.class}`,r=He(o,t.base??{});r&&e.push(r);let i=He(`:where(${o})`,t.defaults??{});i&&e.push(i);for(let[s,a]of Object.entries(t.variants??{})){let l=`.${s}`,d=He(l,{...t.base??{},...a.cover??{}});d&&e.push(d);let u=He(`:where(${l})`,{...t.defaults??{},...a.defaults??{}});u&&e.push(u)}}return e.join(`
|
|
2
|
+
`)}var It=[{class:"wf-stack",base:{display:"flex","flex-direction":"column"},defaults:{gap:"var(--wf-gap, var(--wf-gap-md))","align-items":"var(--wf-align, stretch)"}},{class:"wf-row",base:{display:"flex","flex-wrap":"wrap"},defaults:{gap:"var(--wf-gap, var(--wf-gap-md))","align-items":"var(--wf-align, center)"},variants:{"wf-row-reverse":{cover:{"flex-direction":"row-reverse"}}}},{class:"wf-items-start",base:{"--wf-align":"flex-start"}},{class:"wf-items-center",base:{"--wf-align":"center"}},{class:"wf-items-end",base:{"--wf-align":"flex-end"}},{class:"wf-items-stretch",base:{"--wf-align":"stretch"}},{class:"wf-grid",base:{display:"grid","grid-template-columns":"var(--wf-cols, repeat(auto-fill, minmax(280px, 1fr)))"},defaults:{gap:"var(--wf-gap, var(--wf-gap-lg))"}},{class:"wf-center",base:{display:"flex","flex-direction":"column","align-items":"center","justify-content":"center"}},{class:"wf-justify-between",base:{display:"flex","justify-content":"space-between"},defaults:{"align-items":"var(--wf-align, center)",gap:"var(--wf-gap, var(--wf-gap-md))"}},{class:"wf-justify-end",base:{display:"flex","justify-content":"flex-end"},defaults:{"align-items":"var(--wf-align, center)",gap:"var(--wf-gap, var(--wf-gap-md))"}},{class:"wf-justify-center",base:{display:"flex","justify-content":"center"},defaults:{"align-items":"var(--wf-align, center)",gap:"var(--wf-gap, var(--wf-gap-md))"}},{class:"wf-fill",base:{flex:"1","min-width":"0","min-height":"0"}},{class:"wf-fill-hover",base:{"border-radius":"var(--wf-radius-sm)",padding:"2px 4px",margin:"-2px -4px",transition:"background 0.15s ease"}},{class:"wf-cover",base:{position:"fixed",inset:"0",display:"flex","align-items":"center","justify-content":"center","z-index":"var(--wf-z, var(--wf-cover-z))"}}];import{join as xe,resolve as Jn}from"node:path";var Gn=["tokens","base","layout","components","utilities"],Ht={_tokens:"tokens",_dark:"tokens",_presets:"tokens",_props:"tokens",_base:"base",_stack:"layout",_row:"layout",_split:"layout",_center:"layout",_justify:"layout",_fill:"layout",_grid:"layout",_cluster:"layout",_cover:"layout",_position:"layout",_sticky:"layout",_overflow:"layout","_safe-area":"layout",_layer:"layout","_align-self":"layout",_nowrap:"layout",_shrink:"layout",_container:"layout","_app-shell":"layout",_surface:"utilities",_spacing:"utilities",_border:"utilities",_text:"utilities",_hidden:"utilities",_block:"utilities",_flex:"utilities",_popup:"layout"},Xn="tokens",Zn=n=>n.replace(/@import\s+['"][^'"]+['"]\s*;?\s*\n?/g,"");async function Qn(n){let e=await Lt(xe(n,"weifuwu-layout.css"),"utf-8"),t=[];for(let o of e.split(`
|
|
3
|
+
`)){let r=o.match(/@import\s+['"]([^'"]+)['"]/);r&&t.push(r[1].replace(/^\.\//,""))}if(!t.length)throw new Error(`layout \u5165\u53E3\u65E0 @import\uFF08${n}/weifuwu-layout.css\uFF09\u2014\u2014\u88C5\u914D\u5355\u6E90\u5931\u6548`);return t}async function $t(n){try{let e=await Yn(n);return e.includes("weifuwu-layout.css")&&e.some(t=>/^_[a-z-]+\.css$/.test(t))}catch{return!1}}async function Dt(n){let e=Jn(n),t=await Qn(e),o=[xe(e,"weifuwu-layout.css")],r=[];for(let s of t){if(s==="_stack.css"){o.push(xe(e,"decl.ts"),xe(e,"define.ts")),r.push(`@layer ${Ht._stack} {
|
|
4
|
+
${At(It)}
|
|
5
|
+
}`);continue}if(s==="_row.css")continue;let a=xe(e,s);o.push(a);let l=Zn(await Lt(a,"utf-8")).trim(),d=s.replace(/\.css$/,""),u=Ht[d];if(!u)throw new Error(`layout \u6587\u4EF6\u672A\u767B\u8BB0 @layer \u6620\u5C04: ${s}\uFF08\u5728 src/client/layout/bundle.ts LAYER_OF \u4E2D\u767B\u8BB0\uFF09`);r.push(u===Xn?l:`@layer ${u} {
|
|
6
|
+
${l}
|
|
7
|
+
}`)}return{css:`/* weifuwu/client/layout \u2014 CSS \u5E03\u5C40\u539F\u8BED + \u8BBE\u8BA1 Token\uFF08\u88C5\u914D\u5355\u6E90\uFF1Asrc/client/layout/bundle.ts\uFF09 */
|
|
8
|
+
|
|
9
|
+
@layer ${Gn.join(", ")};
|
|
10
|
+
|
|
11
|
+
${r.join(`
|
|
12
|
+
|
|
13
|
+
`)}
|
|
14
|
+
`,inputs:o}}var de=class{value;constructor(e){this.value=e}toString(){return this.value}};var Le=globalThis;Le.__wfErrState||(Le.__wfErrState={errState:new Map,totalErrors:0});var{errState:Ze,totalErrorsRef:Xe}={errState:Le.__wfErrState.errState,totalErrorsRef:Le.__wfErrState},eo={get:()=>Xe.totalErrors,inc:()=>{Xe.totalErrors++},reset:()=>{Xe.totalErrors=0}};function Te(n,e){eo.inc();let t=Ze.get(n);if(t){t.count++;return}Ze.set(n,{shown:!0,count:1}),console.error(`[vdom] renderFn \u9519\u8BEF\uFF08${n}\uFF09\u2014\u2014\u7EC4\u4EF6\u7EA7 hole \u964D\u7EA7\uFF08\u4E0B\u4E00\u62CD\u91CD\u8BD5\u81EA\u6108\uFF09:`,e)}function Qe(n){Ze.delete(n)}var $e=()=>{},X=class{_subscribe;constructor(e){this._subscribe=e}subscribe(e){let t=to(e),o=!1,r=null,i={next:l=>{o||t.next(l)},error:l=>{o||(o=!0,t.error(l),r?.())},complete:()=>{o||(o=!0,t.complete(),r?.())}},s=this._subscribe(i);r=typeof s=="function"?s:s?()=>s.unsubscribe():$e,o&&r();let a=!1;return{unsubscribe(){a||(a=!0,o||(o=!0,r?.()))}}}pipe(...e){return e.reduce((t,o)=>o(t),this)}};function to(n){return{next:n?.next??$e,error:n?.error??$e,complete:n?.complete??$e}}function P(n){return new X(n)}var et=()=>{},O=class{subs=new Set;closed=!1;asObservable(){return P(e=>this.closed?(e.complete(),et):(this.subs.add(e),()=>{this.subs.delete(e)}))}subscribe(e){return this.asObservable().subscribe(e)}next(e){if(!this.closed)for(let t of this.subs)t.next(e)}error(e){if(!this.closed){this.closed=!0;for(let t of this.subs)t.error(e);this.subs.clear()}}complete(){if(!this.closed){this.closed=!0;for(let e of this.subs)e.complete();this.subs.clear()}}},ne=class extends O{value;constructor(e){super(),this.value=e}get(){return this.value}next(e){this.value=e,super.next(e)}asObservable(){return P(e=>this.closed?(e.complete(),et):(e.next(this.value),this.subs.add(e),()=>{this.subs.delete(e)}))}};function ce(n,e){return P(t=>{let o=!0,r=()=>{o&&(o=!1,t.complete())},i=e?.signal;if(i){if(i.aborted)return r(),et;i.addEventListener("abort",r,{once:!0})}return n.then(s=>{o&&(o=!1,t.next(s),t.complete())},s=>{o&&(o=!1,t.error(s))}),()=>{o=!1,i&&i.removeEventListener("abort",r)}})}function tt(n,e){return P(t=>{let o=n(r=>t.next(r));return e&&t.next(e()),()=>{typeof o=="function"&&o()}})}function nt(n){return e=>new X(t=>e.subscribe({next:o=>t.next(n(o)),error:o=>t.error(o),complete:()=>t.complete()}))}function ot(n){return e=>new X(t=>e.subscribe({next:o=>{n(o)&&t.next(o)},error:o=>t.error(o),complete:()=>t.complete()}))}function fe(n,e){let t=e;return o=>new X(r=>o.subscribe({next:i=>{t=n(t,i),r.next(t)},error:i=>r.error(i),complete:()=>r.complete()}))}function De(n){return e=>new X(t=>{let o=null,r=!1,i=e.subscribe({next:s=>{o?.unsubscribe();let a=!1,l=n(s).subscribe({next:d=>t.next(d),error:d=>t.error(d),complete:()=>{a=!0,o=null}});o=a?null:l},error:s=>t.error(s),complete:()=>{r=!0,o||t.complete()}});return()=>{i.unsubscribe(),o?.unsubscribe()}})}function rt(n,e){let t=e?.trailing??!1;return o=>new X(r=>{let i=null,s=!1,a,l=!1,d=!1,u=g=>{d||r.next(g)},c=()=>{i=null,t&&l&&(l=!1,u(a)),s=!1},f=o.subscribe({next:g=>{s?t&&(a=g,l=!0):(s=!0,u(g),i=setTimeout(c,n))},error:g=>{d=!0,i&&clearTimeout(i),r.error(g)},complete:()=>{d=!0,i&&clearTimeout(i),r.complete()}});return()=>{d=!0,i&&clearTimeout(i),f.unsubscribe()}})}function _t(n){let e=new Set,t=new O,o=n,r=()=>{for(let i of[...e])i();t.next(typeof o=="object"&&o!==null?{...o}:o)};return{get state(){return o},subscribe(i){return e.add(i),()=>{e.delete(i)}},set(i){typeof o=="object"&&o!==null&&!Array.isArray(o)&&typeof i=="object"&&i!==null?o={...o,...i}:o=i,r()},update(i){let s=i(o);s!==void 0&&(typeof o!="object"||o===null||s!==o)&&(o=s),r()},notify:r,changes$:t.asObservable()}}function st(n){let e=_t(n),t=(()=>e.state);return t.set=o=>e.set(o),t.update=o=>e.update(o),t.subscribe=o=>e.subscribe(o),t.notify=()=>e.notify(),t.store=e,t}function B(n,e){let t=globalThis.__wfSpy;t&&t.length<1e3&&t.push({at:Date.now()%1e5,kind:n,data:e===void 0?void 0:String(e).slice(0,80)})}function K(n,e,t,o){let r=n.getInstanceData(),i=r.get(e);if(!i){let s=t,a=!0,l=new O,d=e.subscribe({next:f=>{let g=f!==s;s=f,g&&!a&&l.next()},error:f=>{console.error("[vdom] useObservable:",f)}});a=!1;let c=(o?.throttleMs&&o.throttleMs>0?l.asObservable().pipe(rt(o.throttleMs,{trailing:!0})):l.asObservable()).subscribe({next:()=>{B("obs:next",String(s)+" \u2192 req:render"),n.requestRender()}});n.onUnmount(()=>{d.unsubscribe(),c.unsubscribe()}),i={get:()=>s},r.set(e,i)}return()=>i.get()}function Ut(n,e,t){if(typeof e=="function"){let r=e;return s=>{s?r(s):t?.()}}return{current:e}}function Wt(n,e,t){let o=typeof e=="object"?e:void 0,r=typeof e=="boolean"?e:!1,i=o??t,s=n.nextHookIndex(),a=n.getHookState(s)??{open:r};n.setHookState(s,a);let l=i?.open!==void 0;return{get open(){return i?.open??a.open},setOpen(d){l?(i?.onOpenChange||console.warn(`[vdom] useOpen${o?.name?`(${o.name})`:""} \u53D7\u63A7\u7F3A onOpenChange \u56DE\u8C03\u2014\u2014\u4EA4\u4E92\u9759\u9ED8\u5931\u6548`),i?.onOpenChange?.(d)):(a.open=d,n.requestRender())},toggle(){this.setOpen(!this.open)}}}function Fe(n,e,t){let o=t?e:(()=>!0),r=t??e,i=n.getBrowser()?.window;if(!i)return()=>{};let s=l=>{if(typeof o=="string"){if(l.key!==o)return}else if(!o(l))return;r(l)};i.addEventListener("keydown",s);let a=()=>i.removeEventListener("keydown",s);return n.onUnmount(a),a}function jt(n,e,t,o,r,i,s,a){let l=n.getBoundingClientRect();if(l.width===0&&l.height===0)return null;let d=e.innerWidth,u=e.innerHeight,c,f;switch(r){case"bottom":c=l.bottom+i,f=a?l.left+l.width/2-t/2:l.left;break;case"top":c=l.top-o-i,f=a?l.left+l.width/2-t/2:l.left;break;case"left":c=a?l.top+l.height/2-o/2:l.top,f=l.left-t-i;break;case"right":c=a?l.top+l.height/2-o/2:l.top,f=l.right+i;break}return f+t>d-s&&(f=d-t-s),f<s&&(f=s),c+o>u-s&&(c=u-o-s),c<s&&(c=s),{top:c,left:f}}function qt(n,e){let t=e.getComputedStyle(n).animationName;if(t&&t!=="none")return!0;for(let o of n.children){let r=e.getComputedStyle(o).animationName;if(r&&r!=="none")return!0}return!1}function Bt(n,e){let t=new O,o=K(n,io(n,e,t),{top:0,left:0});return{get top(){return o().top},get left(){return o().left},refresh:()=>{t.next()}}}function io(n,e,t){let o=n.getBrowser()?.window;return P(r=>{if(!o)return r.next({top:0,left:0}),r.complete(),()=>{};let i,s=()=>{let d=e.el();if(!d)return;let u=d.getBoundingClientRect();u.width===0&&u.height===0||(e.isOpen?.()??!0)&&r.next(e.compute(u))},a=()=>{i===void 0&&(i=o.requestAnimationFrame(()=>{i=void 0,s()}))};o.addEventListener("scroll",a,!0),o.addEventListener("resize",a),s();let l=t?.subscribe({next:()=>s()});return()=>{l?.unsubscribe(),i!==void 0&&o.cancelAnimationFrame(i),o.removeEventListener("scroll",a,!0),o.removeEventListener("resize",a)}})}function Kt(n){return n==null?null:typeof n=="string"?n:typeof n=="number"?String(n):(console.warn(`[vdom] key \u5FC5\u987B\u662F string|number\u2014\u2014\u5F53\u524D ${typeof n}\uFF08\u5FFD\u7565\u2014\u2014\u4F4D\u7F6E\u8EAB\u4EFD\uFF09`),null)}function zt(n){return Kt(n?.key)}function Yt(n){let e={...n??{}};return delete e.key,e}function it(n){if(!(n==null||n===!1)){if(typeof n=="string")return n.trim()||void 0;if(typeof n=="number")return String(n);if(Array.isArray(n)){let e=n.map(it).filter(t=>!!t);return e.length?e.join(" "):void 0}if(typeof n=="object"){let e=Object.entries(n).filter(([,t])=>!!t).map(([t])=>t);return e.length?e.join(" "):void 0}}}function ao(n){for(let e of["class","className"]){let t=n[e];t!=null&&typeof t!="string"&&(n[e]=it(t))}return n}function D(n,e,...t){let o=Yt(ao(e??{}));return t.length===1?o.children=t[0]:t.length>1&&(o.children=t),{type:n,props:o,key:zt(e)}}var Jt=Symbol("vdom-fragment");function Q(n){return n.type===Jt}function I(n){let e=n.children??(n.props.children===void 0?[]:n.props.children),t=o=>Array.isArray(o)?o.flatMap(t):[o];return Array.isArray(e)?e.flatMap(t):[e]}function A(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Q(n)?I(n).reduce((e,t)=>e+A(t),0):1}var Gt="pos:";function j(n,e){return`${n}.k${e.replace(/%/g,"%25").replace(/\./g,"%2E")}`}function V(n){return n==null||typeof n=="boolean"||typeof n=="string"||typeof n=="number"||Array.isArray(n)?null:n.key}function lo(n){return V(n)!==null}function at(n){return`${Gt}${n}`}function Xt(n){return n.startsWith(Gt)}function Ce(n,e){let t=new Set;for(let o of n){let r=V(o);if(r!==null){if(t.has(r)){console.warn(`[vdom] ${e}\uFF1A\u91CD\u590D key "${r}"\uFF08\u5217\u8868\u8EAB\u4EFD\u6620\u5C04\u6B67\u4E49\u2014\u2014\u589E\u5220/\u91CD\u6392\u884C\u4E3A\u4E0D\u786E\u5B9A\uFF09\u2014\u2014\u8BF7\u4E3A\u6BCF\u9879\u58F0\u660E\u552F\u4E00 key\uFF08\u6570\u636E id \u2192 keyBy\uFF09`);return}t.add(r)}}}function Zt(n,e){if(n.length<2)return;let t=n.some(r=>typeof r?.type=="function"),o=n.some(r=>!lo(r)&&typeof r?.type=="function");if(t&&o){let r=n.map(i=>{let s=i;if(s==null)return"null";if(typeof s=="boolean")return"bool";if(typeof s=="string"||typeof s=="number")return"text";if(Array.isArray(s))return"arr";if(typeof s.type=="function"){let a=s.type.name;return"comp"+(a?":"+a:"")}return"el"+(s.key?`.k{${String(s.key).slice(0,16)}}`:"")});console.warn(`[vdom] ${e}\uFF1A\u5217\u8868\u542B\u65E0 key \u7684\u7EC4\u4EF6\u9879\uFF08\u957F\u5EA6 ${n.length}\uFF09\u2014\u2014\u9879: [${r.join(", ")}]\u2014\u2014\u52A8\u6001\u589E\u5220/\u91CD\u6392\u65F6\u72B6\u6001\u4F1A\u6309\u4F4D\u7F6E\u7EE7\u627F\u2014\u2014\u8BF7\u4E3A\u7EC4\u4EF6\u9879\u58F0\u660E key\uFF08\u6570\u636E id \u2192 keyBy\uFF09`)}}function k(n,e){return`${n}.${e}`}function ke(n){let e={};for(let[t,o]of Object.entries(n))t==="children"||t==="key"||t==="ref"||typeof o!="function"&&o!==void 0&&(e[t]=o);return e}function Qt(n){return n==null||typeof n=="boolean"}function en(n){return!(n==null||typeof n=="boolean"||typeof n=="string"||typeof n=="number"||Array.isArray(n)||typeof n=="object"&&typeof n.type=="string"||typeof n.type=="function"||typeof n.type=="symbol")}function lt(n){return n==null?"null/undefined":typeof n=="object"?`object\uFF08type: ${typeof n.type}\uFF09`:typeof n}function uo(n,e,t,o){return[{op:"createAnchor",id:n,...o!==void 0?{detail:o}:{}},{op:"insert",id:n,parent:e,ref:t}]}function ut(n,e,t,o,r){for(let i of uo(e,t,o,r))n(i)}function z(n){return n===""?"hole":typeof n=="string"||typeof n=="number"?"text":Qt(n)?"hole":Array.isArray(n)?"array":typeof n.type=="string"?"element":Q(n)?"fragment":typeof n.type=="function"?"component":(en(n),"invalid")}function _e(n){return typeof n=="string"||typeof n=="number"?String(n):null}function F(n){return z(n)==="hole"}function oe(n){return z(n)==="text"}function ee(n){if(n==null)return"hole";let e=z(n);return e==="invalid"?"hole":e}function tn(n,e,t,o,r){let i=ke(n.props),s=ke(e.props);for(let[a,l]of Object.entries(s))a==="value"&&r?.formControl?o({op:"setProp",id:t,key:a,value:l}):i[a]!==l&&o({op:"setProp",id:t,key:a,value:l});for(let a of Object.keys(i))a in s||o({op:"setProp",id:t,key:a,value:void 0});for(let[a,l]of Object.entries(e.props))a==="children"||a==="key"||typeof l=="function"&&n.props[a]!==l&&o({op:"setProp",id:t,key:a,value:l,prev:n.props[a]});for(let a of Object.keys(n.props))a==="children"||a==="key"||typeof n.props[a]=="function"&&e.props[a]===void 0&&o({op:"setProp",id:t,key:a,value:void 0,prev:n.props[a]})}function pe(n,e,t){return typeof n?.type=="function"?k(e,0):Array.isArray(n)?e:F(n)?k(e,0):t}function Se(n,e,t){return typeof n?.type=="function"||Array.isArray(n)?e:t}function _(n,e,t,o,r){if(F(n)){o({op:"remove",id:e});return}if(oe(n)){o({op:"remove",id:e});return}if(Array.isArray(n)){let l=0;for(let d of n)_(d,k(e,l),e,o,r),l+=A(d);return}let i=n;if(Q(i)){let l=Number(e.slice(t.length+1)),d=I(i),u=l;for(let c of d)_(c,k(t,u),t,o,r),u+=A(c);return}if(typeof i.type=="function"){let l=i.key!==null?j(t,i.key):e;o({op:"unmount",compId:l});let d=r?.get(l)?.lastOutput;if(d!==void 0){let u=re(d),c=pe(u,l,e),g=u!==null&&typeof u=="object"&&!Array.isArray(u)&&Q(u)?e.slice(0,e.lastIndexOf(".")):Se(u,l,l);_(u,c,g,o,r)}}let s=I(i),a=0;s.forEach(l=>{let d=k(e,a);l!==null&&typeof l!="string"&&typeof l!="number"&&typeof l!="boolean"&&!Array.isArray(l)?_(l,d,e,o,r):o({op:"remove",id:d}),a+=A(l)}),o({op:"remove",id:e})}var me=(n,e,t)=>{t.emit({op:"remove",id:t.oldId}),t.emitNode(e,t.parent,t.index,t.ref)};var ge=(n,e,t)=>{t.emit({op:"remove",id:t.oldId}),t.emitNode(e,t.parent,t.index,t.ref)};var be=(n,e,t)=>{_(n,t.oldId,t.parent,t.emit,t.registry),t.emitNode(e,t.parent,t.index,t.ref)};var ve=(n,e,t)=>{t.oldCompId&&t.emit({op:"unmount",compId:t.oldCompId});let o=t.registry?.get(t.oldCompId??"")?.lastOutput;if(o!==void 0){let r=re(o);_(r,pe(r,t.oldCompId??"",k(t.parent,t.index)),Se(r,t.oldCompId??"",t.parent),t.emit,t.registry)}else t.emit({op:"remove",id:t.oldId});t.emitNode(e,t.parent,t.index,t.ref)};var Y=(n,e,t)=>{let o=Array.isArray(n)?n:I(n),r=t.index;for(let i of o)_(i,k(t.parent,r),t.parent,t.emit,t.registry),r+=A(i);t.emitNode(e,t.parent,t.index,t.ref)};var co={text:{text:null,hole:me,element:me,component:me,fragment:me,array:me},hole:{text:ge,hole:null,element:ge,component:ge,fragment:ge,array:ge},element:{text:be,hole:be,element:null,component:be,fragment:be,array:be},component:{text:ve,hole:ve,element:ve,component:null,fragment:ve,array:ve},fragment:{text:Y,hole:Y,element:Y,component:Y,fragment:null,array:Y},array:{text:Y,hole:Y,element:Y,component:Y,fragment:Y,array:null}};function dt(n,e){return co[n]?.[e]??null}var fo=0;function ft(n,e,t,o,r){let i=[],s=new Map,a={n:0},l=new Map,d=new O;d.subscribe({next:()=>{for(let b of[...i].reverse())try{b()}catch(m){console.error("[vdom] v2 onUnmount:",m)}}});let u=Object.create(t);u.onUnmount=b=>{i.push(b)},u.ui=mt({requestRender:()=>{B("req:render",o.slice(-18)),r?.()},onUnmount:b=>{i.push(b)},getBrowser:()=>t.browser??null,nextHookIndex:()=>a.n++,getHookState:b=>l.get(b),setHookState:(b,m)=>{l.set(b,m)},getInstanceData:()=>s,scheduleAfterRender:b=>{let m=t.afterRender;m?m(b):setTimeout(b,0)},getSharedContext:()=>t??null});let c=n(e,u),f;typeof c=="function"?f=c:f=(b=>{let m=n(b,u);return typeof m=="function"?null:m});let g=a.n;return{factory:n,renderFn:f,lastOutput:void 0,hookSeq:a,renderBase:g,instData:s,destroy$:d,disposed:!1,epoch:fo}}function pt(n,e){let t=n.renderFn.shouldRender;return t&&n.lastProps!==void 0&&n.lastOutput!==void 0&&!t(n.lastProps,e)?re(n.lastOutput):(n.lastProps=e,n.hookSeq.n=n.renderBase,n.renderFn(e))}function q(n,e){let t=e.get(n);if(!(!t||t.disposed)){t.disposed=!0;try{t.destroy$.next()}catch(o){console.error("[vdom] v2 destroy$:",o)}t.instData.clear(),e.delete(n)}}function po(n,e,t,o){let r=e.get(n),i=[];if(r){let a=r.lastOutput!==void 0?re(r.lastOutput):void 0;if(a!==void 0){let l={get:d=>{let u=e.get(d);return u?{lastOutput:u.lastOutput}:void 0}};_(a,pe(a,n,t),Se(a,n,o),d=>{i.push(d)},l)}}let s=[];for(let a of i)a.op==="unmount"&&e.has(a.compId)&&s.push(a.compId);q(n,e);for(let a of s)e.has(a)&&q(a,e);return i.unshift({op:"unmount",compId:n}),i}function sn(n,e,t,o){let r=n?.lastOutput;if(r===void 0)return[e+".0"];if(typeof r=="object"&&r!==null&&"kind"in r){let i=r;if(i.kind==="hole")return[e+".0"];if(i.kind==="array")return(i.items??[]).map((a,l)=>`${e}.${l}`);let s=i.v;return s?typeof s.type=="function"?[e+".0"]:[k(t,o)]:[e+".0"]}return[e+".0"]}function mo(n,e,t,o){if(F(n))return k(e,t);if(oe(n))return k(e,t);let r=n;if(typeof r.type!="function")return k(e,t);let i=V(r);if(i===null)return k(e,t);let s=j(e,i);return sn(o?.get(s),s,e,t)[0]}function nn(n,e,t,o,r,i,s,a){let l=[],d=[],u=0,c=null;for(let f=0;f<e.length;f++){let g=A(e[f]);l.push(n[f]===void 0?H(e[f],t,u,c,o,i,r,s):ae(n[f],e[f],t,u,c,o,r,i,s)),c=k(t,u+g-1),u+=g}for(let f=n.length-1;f>=e.length;f--)d.push(M(ie(n[f],t,go(n,f),r)));return a?U([...d.reverse(),...l]):(d.reverse(),U([...l,...d]))}function ae(n,e,t,o,r,i,s,a,l){let d=k(t,o),u=z(n),c=z(e);if(u==="text"&&c==="text")return String(n)===String(e)?M([]):M([{op:"setText",id:d,value:_e(e)}]);if(u==="hole"&&c==="hole")return M([]);if(u==="hole")return U([M([{op:"remove",id:d}]),H(e,t,o,r,i,a,s,l)]);if(c==="hole")return ct(n,e,t,o,r,i,a,u==="component"?Re(n,t,o):void 0,s,l);if((u==="fragment"||u==="array")&&(c==="fragment"||c==="array")){let m=Ee(Array.isArray(n)?n:I(n)),h=Ee(Array.isArray(e)?e:I(e));return Ue(h)||Ue(m)?rn(m,h,t,i,s,a,l):nn(m,h,t,i,s,a,l,!0)}if(u===c&&typeof n!="string"&&typeof n!="number"){let m=n,h=e;if(typeof m.type=="function"&&typeof h.type=="function"){if(m.type===h.type)return vo(m,h,t,o,r,i,s,a,l);let C=Re(m,t,o),x=po(C,s,k(t,o),t);return U([M(x),H(h,t,o,r,i,a,s,l)])}if(typeof m.type=="string"&&typeof h.type=="string"){if(m.type===h.type){let C=[];tn(m,h,d,v=>C.push(v),{formControl:m.type==="input"||m.type==="textarea"});let x=Ee(I(m)),T=Ee(I(h));if(yo(x,T,d),Ue(T)||Ue(x))return U([M(C),rn(x,T,d,i,s,a,l)]);let p=nn(x,T,d,i,s,a,l,!1);return U([M(C),p])}return U([M(ie(m,t,o,s)),H(h,t,o,r,i,a,s,l)])}}let f=ee(n),g=ee(e),b=z(n)==="component"?Re(n,t,o):void 0;return ct(n,e,t,o,r,i,a,b,s,l)}function go(n,e){let t=0;for(let o=0;o<e;o++)t+=A(n[o]);return t}function bo(n,e){let t=0;for(let o=0;o<e;o++)t+=A(n[o]);return t}function vo(n,e,t,o,r,i,s,a,l){let d=Re(e,t,o),u=s.get(d);if(!u||u.factory!==e.type)return u&&q(d,s),H(e,t,o,r,i,a,s,l);let c;try{c=pt(u,e.props)}catch(b){return Te(d,b),M([])}let f=u.lastOutput!==void 0?re(u.lastOutput):void 0;u.lastOutput=We(c);let g=gt(c,d,t,o);return f===void 0?H(c,g.parent,g.index,r,i,a,s,l):ho(f,c,g.parent,g.index,r,i,s,a,l)}function ho(n,e,t,o,r,i,s,a,l){if(n===e)return M([]);let d=Array.isArray(n),u=Array.isArray(e);if(d||u){let c=d?n:[n],f=u?e:[e],g=0,b=null,m=[];for(let h=0;h<f.length;h++){let C=A(f[h]);m.push(c[h]===void 0?H(f[h],t,g,b,i,a,s,l):ae(c[h],f[h],t,g,b,i,s,a,l)),b=k(t,g+C-1),g+=C}for(let h=f.length;h<c.length;h++)m.push(M(ie(c[h],t,bo(c,h),s)));return U(m)}return ae(n,e,t,o,r,i,s,a,l)}function Ee(n){let e=[];for(let t of n)t!==null&&typeof t=="object"&&!Array.isArray(t)&&Q(t)?e.push(...Ee(I(t))):e.push(t);return e}function yo(n,e,t){if(globalThis.__WF_NO_A_CHECK__)return;let o=c=>!F(c)&&!oe(c)&&!Array.isArray(c),r=n.filter(o),i=e.filter(o),s=c=>typeof c?.type=="function"&&V(c)===null,a=(c,f)=>f>=c.length||F(c[f]),l=c=>a(n,c)||s(n[c]),d=c=>a(e,c)||s(e[c]);(e.some((c,f)=>s(c)&&!l(f))||n.some((c,f)=>s(c)&&!d(f)))&&Zt(i,`children\uFF08${t}\u2014\u2014\u65E0 key \u7EC4\u4EF6\u5B9E\u69FD\u7FFB\u8F6C ${r.length}\u2192${i.length}\uFF09`)}function Re(n,e,t){return n.key!==null?j(e,n.key):k(e,t)}function Oe(n,e,t,o,r,i){let s=ee(n),a=ee(e);return dt(s,a)?ct(n,e,"root",0,null,t,r,s==="component"?Re(n,"root",0):void 0,o,i).pipe(on):ae(n,e,"root",0,null,t,o,r,i).pipe(on)}var on=n=>U([n,M([{op:"done"}])]);function wo(n,e,t,o,r,i,s,a,l){return n===void 0?H(e,t,o,r,i,a,s,l):ae(n,e,t,o,r,i,s,a,l)}function rn(n,e,t,o,r,i,s){let a=[],l=(p,v)=>V(p)??at(v),d=new Map;n.forEach((p,v)=>{let y=l(p,v);d.has(y)||d.set(y,v)});let u=new Set(e.map((p,v)=>l(p,v))),c=new Map;for(let p=0;p<n.length;p++){let v=n[p];if(F(v)){a.push({op:"remove",id:k(t,p)});continue}if(oe(v)){a.push({op:"remove",id:k(t,p)});continue}if(Array.isArray(v))continue;let y=V(v);if(y!==null){let S=(c.get(y)??0)+1;if(c.set(y,S),S===1)continue;a.push(...ie(v,t,p,r));continue}}for(let[p,v]of d)if(!u.has(p)&&(a.push(...ie(n[v],t,v,r)),!Xt(p))){let y=j(t,p);r.has(y)&&q(y,r)}let f=n.map(p=>V(p)).filter(p=>p!==null&&u.has(p)),g=e.map(p=>V(p)).filter(p=>p!==null&&d.has(p)),m=!e.some((p,v)=>{let y=V(p);if(y===null||typeof p.type!="function")return!1;let S=d.get(y);return S===void 0||S===v?!1:r?.get(j(t,y))===void 0});{let p=0;for(let v of g){let y=f.indexOf(v,p);if(y===-1){m=!1;break}p=y+1}}if(!m){n.forEach((y,S)=>{if(!(F(y)||oe(y))&&!Array.isArray(y)){if(V(y)!==null&&typeof y.type=="function"){a.push(...ie(y,t,S,r,{keepSegments:!0}));return}if(V(y)!==null){a.push({op:"remove",id:k(t,S)});return}a.push(...ie(y,t,S,r))}});let p=[],v=null;for(let y=0;y<e.length;y++){let S=e[y],N=V(S),J=N!==null?j(t,N):k(t,y);N!==null&&typeof S.type=="function"?p.push(H(S,t,y,v,o,i,r,s)):p.push(H(S,t,y,v,o,i,r,s)),v=k(t,y)}return U([M(a),...p])}let h=[];e.forEach((p,v)=>{let y=V(p);if(y===null)return;let S=d.get(y);S!==void 0&&S!==v&&h.push({oldIdx:S,newIdx:v})});let C=h.every(p=>p.newIdx<p.oldIdx);h.sort((p,v)=>C?p.newIdx-v.newIdx:v.newIdx-p.newIdx);for(let p of h){let v=e[p.newIdx],y=V(v);if(y!==null&&typeof v.type=="function"){let S=j(t,y),N=sn(r?.get(S),S,t,p.oldIdx);if(N.length===1&&!N[0].startsWith(S+"."))a.push({op:"move",id:N[0],parent:t,ref:null,newId:k(t,p.newIdx),noMove:!0});else{let Ie=p.newIdx>0?e[p.newIdx-1]:null,se=Ie===null?null:mo(Ie,t,p.newIdx-1,r);for(let ue of N)a.push({op:"move",id:ue,parent:t,ref:se,newId:ue,noMove:!1}),se=ue}}else a.push({op:"move",id:k(t,p.oldIdx),parent:t,ref:null,newId:k(t,p.newIdx),noMove:!0})}let x=[],T=null;for(let p=0;p<e.length;p++){let v=e[p],y=V(v),S=k(t,p);if(y!==null){let N=d.get(y);N===void 0?x.push(H(v,t,p,T,o,i,r,s)):typeof v.type=="function"?x.push(wo(n[N],v,t,p,T,o,r,i,s)):x.push(ae(n[N],v,t,p,T,o,r,i,s))}else{let N=d.get(at(p)),J=N===void 0?void 0:n[N];J!==void 0&&!F(J)&&!oe(J)&&!Array.isArray(J)?x.push(ae(J,v,t,p,T,o,r,i,s)):x.push(H(v,t,p,T,o,i,r,s))}T=S}return U([M(a),...x])}function ie(n,e,t,o,r){let i=[],s=k(e,t),a=o&&o.size>0?{get:d=>{let u=o.get(d);return u?{lastOutput:u.lastOutput}:void 0}}:void 0;if(_(n,s,e,d=>i.push(d),a),o&&!r?.keepSegments)for(let d of i)d.op==="unmount"&&o.has(d.compId)&&q(d.compId,o);else if(o&&r?.keepSegments){for(let d of i)if(d.op==="unmount"){let u=o.get(d.compId);u&&(u.lastOutput=void 0)}}return r?.keepSegments?i.filter(d=>d.op!=="unmount"):i}function Ue(n){return n.some(e=>V(e)!==null)}function ct(n,e,t,o,r,i,s,a,l,d){let u=dt(ee(n),ee(e));if(!u)throw new Error(`[vdom] v2 \u72B6\u6001\u673A\u8FDD\u4F8B\uFF1A\u672A\u5B9A\u4E49\u8F6C\u6362 ${ee(n)} \u2192 ${ee(e)}`);let c=[],f=null,g=[],b=l&&l.size>0?{get:C=>{let x=l.get(C);return x?{lastOutput:x.lastOutput}:void 0}}:s,m={emit:C=>{let x=C;x.op==="unmount"&&l?.has(x.compId)&&g.push(x.compId),c.push(x)},emitNode:(C,x,T,p)=>{f={v:C,p:x,i:T,r:p}},oldId:k(t,o),newId:k(t,o),parent:t,index:o,ref:r,oldCompId:a,registry:b};u(n,e,m);let h=f?P(C=>{let x=f;return H(x.v,x.p,x.i,x.r,i,s,l,d).subscribe({next:p=>C.next(p),error:p=>C.error(p),complete:()=>C.complete()})}):M([]);return U([P(C=>{for(let x of g)l?.has(x)&&q(x,l);return C.complete(),()=>{}}),M(c),h])}var je=class{table=new Map;rootTypes=new Set;doc;dispatchBound;container;phase="active";constructor(e,t){this.doc=e,this.container=t,this.dispatchBound=this.dispatch.bind(this)}set(e,t,o){if(this.phase==="disposed"){console.error(`[vdom] \u4E8B\u4EF6\u8868\u72B6\u6001\u673A\u8FDD\u4F8B\uFF1Adisposed \u540E set(${e}, ${t}) \u88AB\u5FFD\u7565`);return}if(typeof o!="function"){console.warn(`[vdom] \u4E8B\u4EF6 ${t} \u975E\u51FD\u6570\u503C\u88AB\u8DF3\u8FC7\uFF08node ${e}\uFF09\u2014\u2014\u671F\u671B\u51FD\u6570\uFF0C\u5B9E\u9645 ${typeof o}`);return}let r=this.table.get(e);r||(r=new Map,this.table.set(e,r)),r.set(t,o),this.ensureRoot(t)}get(e,t){return this.table.get(e)?.get(t)}removeEvent(e,t){let o=this.table.get(e);o&&(o.delete(t),o.size===0&&this.table.delete(e))}remove(e){for(let t of[...this.table.keys()])(t===e||t.startsWith(e+"."))&&this.table.delete(t)}removeOne(e){this.table.delete(e)}ensureRoot(e){this.rootTypes.has(e)||(this.doc.addEventListener(e,this.dispatchBound,{capture:!0}),this.rootTypes.add(e))}dispatch(e){if(this.container){let o=e.target;if(o&&!this.container.contains(o))return}if(e.type==="contextmenu"&&window.__dbgEvt){let o=e.target,r=[...this.table.entries()].map(([i,s])=>i+":"+[...s.keys()].join("+")).join(" | ");console.error("[dbg-evt-dispatch]","target:",o?.getAttribute("data-wf-id"),"ALL:",r.slice(0,400))}let t=e.target;for(t&&t.nodeType===3&&(t=t.parentElement);t;){if(!t.hasAttribute?.("data-wf-id")){let r=t.closest?.("[data-wf-id]");if(r&&r!==t){t=r;continue}}let o=t.getAttribute?.("data-wf-id");if(o){let r=this.table.get(o)?.get(e.type);if(r){try{Object.defineProperty(e,"currentTarget",{value:t,configurable:!0})}catch{}try{r(e)}catch(i){console.error("[vdom] \u4E8B\u4EF6 handler:",i)}if(e.cancelBubble)return}}t=t.parentElement}}clear(){this.table.clear()}dispose(){if(this.phase!=="disposed"){this.phase="disposed";for(let e of this.rootTypes)this.doc.removeEventListener(e,this.dispatchBound,{capture:!0});this.rootTypes.clear(),this.table.clear()}}},he=/^on[A-Z]/;function Ne(n){return he.test(n)?n.slice(2).toLowerCase():null}var qe=class{refs=new Map;phase="active";set(e,t,o){if(this.phase==="disposed"){console.error(`[vdom] ref \u8868\u72B6\u6001\u673A\u8FDD\u4F8B\uFF1Adisposed \u540E set(${e}) \u88AB\u5FFD\u7565`);return}if(o&&o!==t&&typeof o=="function")try{o(null)}catch(r){console.error("[vdom] ref prev:",r)}this.refs.set(e,t)}mount(e,t){let o=this.refs.get(e);if(typeof o=="function")try{o(t)}catch(r){console.error("[vdom] ref mount:",r)}}unmount(e){for(let[t,o]of[...this.refs])if(t===e||t.startsWith(e+".")){if(typeof o=="function")try{o(null)}catch(r){console.error("[vdom] ref unmount:",r)}this.refs.delete(t)}}unmountOne(e){let t=this.refs.get(e);if(typeof t=="function")try{t(null)}catch(o){console.error("[vdom] ref unmount:",o)}this.refs.delete(e)}remap(e,t){for(let[o,r]of[...this.refs])(o===e||o.startsWith(e+"."))&&(this.refs.delete(o),this.refs.set(t+o.slice(e.length),r))}clear(){this.refs.clear()}dispose(){this.phase!=="disposed"&&(this.phase="disposed",this.refs.clear())}};function xo(n,e){switch(e.kind){case"begin":return"consuming";case"next":return e.matched?"consuming":"failed";case"end":return n==="consuming"?e.remaining>0?"failed":"inactive":n;case"reset":return"inactive"}}var Be=class{queue=null;phase="inactive";events$;failed$;events=new O;constructor(){this.events$=this.events.asObservable(),this.events.asObservable().pipe(fe(xo,"inactive")).subscribe({next:e=>{this.phase=e}}),this.failed$=this.events.asObservable().pipe(ot(e=>e.kind==="next"&&!e.matched||e.kind==="end"&&e.remaining>0),nt(()=>{}))}begin(e){let t=[],o=r=>{t.push(r);for(let i of r.childNodes)o(i)};for(let r of e.childNodes)o(r);this.queue=t,this.events.next({kind:"begin"})}end(){if(this.phase!=="consuming")return;let e=this.queue?.length??0;this.queue=null,this.events.next({kind:"end",remaining:e})}reset(){this.queue=null,this.events.next({kind:"reset"})}next(e,t,o){if(this.phase!=="consuming")return console.error(`[vdom] absorb \u72B6\u6001\u673A\u8FDD\u4F8B\uFF1Anext \u5728 ${this.phase} \u9636\u6BB5\u8C03\u7528\uFF08\u5E94 consuming\uFF09`),null;let r=this.queue;if(!r)return null;for(;r.length>0;){let i=r.shift();if(e==="element"?i.nodeType===1&&i.tagName.toLowerCase()===t:e==="text"?i.nodeType===3:i.nodeType===8){if(e==="text"&&o!==void 0){let a=i,l=a.textContent??"";if(l!==o&&l.startsWith(o)){let d=a.splitText(o.length);r.unshift(d)}}return this.events.next({kind:"next",matched:!0}),i}}return this.events.next({kind:"next",matched:!1}),null}};ht();var Co=new Set(["zIndex","opacity","lineHeight","zoom","fontWeight","order","flex","flexGrow","flexShrink","flexBasis","animationIterationCount","orphans","widows","columns","columnCount","columnGap","counterIncrement","counterReset","aspectRatio","scale","rotate"]);function ko(n,e,t){if(t==null||t===!1){e.startsWith("--")&&n.style.removeProperty(e),n.style[e]="";return}if(e.startsWith("--")){n.style.setProperty(e,String(t));return}typeof t=="number"&&!Co.has(e)&&(t=`${t}px`),n.style[e]=String(t)}function yt(n,e){if(e==null||e===!1){n.style.cssText="";return}if(typeof e=="string"){n.setAttribute("style",e);return}if(e&&typeof e=="object"){n.style.cssText="";for(let[t,o]of Object.entries(e))ko(n,t,o)}}var Ke=null,an=new WeakSet;function So(n){if(Ke||(Ke=new WeakSet),!an.has(n)){an.add(n);let e=Ke;n.addEventListener("compositionstart",t=>{let o=t.target;o instanceof HTMLElement&&e.add(o)},!0),n.addEventListener("compositionend",t=>{let o=t.target;o instanceof HTMLElement&&e.delete(o)},!0)}return Ke}function ln(n,e){return So(n).has(e)}var Eo=new Set(["value","checked","selected","disabled","hidden","autofocus","defaultValue","defaultChecked","innerHTML","textContent","download","indeterminate","multiple","readOnly","required","tabIndex","spellcheck","draggable","scrollTop","scrollLeft","volume","muted","paused","playbackRate","open"]);function un(n){return Eo.has(n)}function dn(n,e,t){if(t===void 0){if(Ro.has(e)){n[e]=!1;return}return}if(e==="value"&&n.nodeType===1){let o=n;if(n.ownerDocument&&ln(n.ownerDocument,o))return;let r=o.value;if(r===t||String(r)===String(t))return}n[e]=t}var Ro=new Set(["disabled","checked","selected","multiple","readOnly","required","indeterminate","muted","paused","open","autofocus","draggable","hidden"]);function Me(n,e){for(let[t,o]of Object.entries(e))t==="style"?yt(n,o):vt(n,t,o)}function cn(n,e,t,o,r,i){if(o!=="ref")if(typeof r=="function"||r===void 0&&typeof i=="function"){if(he.test(o)){let s=Ne(o);s&&n.set(e,s,r)}return}else if(he.test(o)){let s=Ne(o);s&&n.set(e,s,r)}else o==="style"?yt(t,r):un(o)?dn(t,o,r):vt(t,o,r)}var Oo="http://www.w3.org/2000/svg",No=new Set(["svg","path","circle","line","rect","text","g","defs","marker","polyline","polygon","ellipse","use","symbol","tspan","textPath","clipPath","mask","pattern","linearGradient","radialGradient","stop"]);function fn(n,e){return No.has(e)?n.createElementNS(Oo,e):n.createElement(e)}function Mo(n,e){n.touched.add(e.id);let t=n.nodes.get(e.id);if(t&&t.nodeType===1&&t.tagName.toLowerCase()===e.tag)Me(t,e.attrs);else if(n.absorb.queue&&!t){let r=n.absorb.next("element",e.tag);if(r)Me(r,e.attrs),n.nodes.set(e.id,r);else{let i=fn(n.doc,e.tag);Me(i,e.attrs),n.nodes.set(e.id,i)}}else{let r=fn(n.doc,e.tag);Me(r,e.attrs),t&&(n.refRegistry.unmountOne(e.id),n.eventRegistry.removeOne(e.id),t.replaceWith(r)),n.nodes.set(e.id,r)}let o=n.nodes.get(e.id);o&&o.nodeType===1&&o.setAttribute("data-wf-id",e.id)}function Po(n,e){n.touched.add(e.id);let t=n.nodes.get(e.id);if(t&&t.nodeType===3)t.textContent!==e.value&&(t.textContent=e.value);else if(n.absorb.queue&&!t){let o=n.absorb.next("text",void 0,e.value);if(o)o.textContent!==e.value&&(o.textContent=e.value),n.nodes.set(e.id,o);else{let r=n.doc.createTextNode(e.value);n.nodes.set(e.id,r)}}else{let o=n.doc.createTextNode(e.value);t&&t.replaceWith(o),n.nodes.set(e.id,o)}}function Vo(n,e){n.touched.add(e.id);let t=n.nodes.get(e.id);if(t&&t.nodeType===8){let o=e.detail?`wf-hole: ${e.detail}`:"wf-hole";t.textContent!==o&&(t.textContent=o)}else if(n.absorb.queue&&!t){let o=n.absorb.next("comment");if(o)n.nodes.set(e.id,o);else{let r=n.doc.createComment(e.detail?`wf-hole: ${e.detail}`:"wf-hole");n.nodes.set(e.id,r)}}else{let o=n.doc.createComment(e.detail?`wf-hole: ${e.detail}`:"wf-hole");t&&t.replaceWith(o),n.nodes.set(e.id,o)}}function Ao(n,e){let t=n.nodes.get(e.id);if(!t||t.isConnected)return;let o=n.parentOf(e);if(o){if(o.nodeType===3){let r=o.parentElement;if(!r)return;let i=o.nextSibling&&o.nextSibling.parentNode===r?o.nextSibling:null;r.insertBefore(t,i),t.nodeType===1&&n.refRegistry.mount(e.id,t),n.registerChild(e.parent,e.id);return}if(o.nodeType===8){console.error(`[vdom] id \u7A7A\u95F4\u8FDD\u4F8B\uFF1Ainsert ${e.id} \u7684 parent \u662F\u6CE8\u91CA\u951A\uFF08${e.parent}\uFF09\u2014\u2014\u63D2\u5230\u951A\u540E`);let r=o.parentElement;r&&r.insertBefore(t,o.nextSibling),t.nodeType===1&&n.refRegistry.mount(e.id,t),n.registerChild(e.parent,e.id);return}if(e.ref){let r=n.nodes.get(e.ref)??null;if(!r){let i=n.childIds.size>0&&n.childIds.has(e.ref)?n.collectDesc(e.ref):null;if(i){let s="",a=-1;for(let l of i){let d=n.seq.get(l)??0;d>a&&(a=d,s=l)}s&&(r=n.nodes.get(s)??null)}else{let s=e.ref+".";for(let[a,l]of n.nodes)a.startsWith(s)&&(r=l)}}r&&r.parentNode===o?o.insertBefore(t,r.nextSibling):r?o.appendChild(t):o.insertBefore(t,o.firstChild)}else o.insertBefore(t,o.firstChild);t.nodeType===1&&n.refRegistry.mount(e.id,t),n.registerChild(e.parent,e.id)}}function Io(n,e){let t=n.nodes.get(e.id);if(t){if(!e.noMove){let o=n.parentOf(e);if(!o)return;let r=e.ref?n.nodes.get(e.ref)??null:null;r?o.insertBefore(t,r.nextSibling):e.first?o.insertBefore(t,o.firstChild):o.appendChild(t)}n.remapSubtree(e.id,e.newId)}}function Ho(n,e){n.refRegistry.unmountOne(e.id),n.eventRegistry.removeOne(e.id),n.nodes.get(e.id)?.remove();let t=n.childIds.size>0?n.collectDesc(e.id):null,o=t??[];if(!t){let r=e.id+".";for(let i of[...n.nodes.keys()])i.startsWith(r)&&o.push(i)}for(let r of o)n.refRegistry.unmountOne(r),n.eventRegistry.removeOne(r),n.nodes.delete(r),n.unregisterChild(r);n.nodes.delete(e.id),n.unregisterChild(e.id)}function Lo(n,e){let t=n.nodes.get(e.id);t&&t.nodeType===3&&(t.textContent=e.value)}function $o(n,e){let t=n.nodes.get(e.id);if(!t||t.nodeType!==1)return;let o=t;if(e.key==="ref"){let r=n.refRegistry.refs.get(e.id);if(e.value===void 0){n.refRegistry.set(e.id,void 0,r),n.refRegistry.refs.delete(e.id);return}n.refRegistry.set(e.id,e.value,r),o.isConnected&&n.refRegistry.mount(e.id,o);return}if(he.test(e.key)){let r=Ne(e.key);r&&(e.value===void 0?n.eventRegistry.removeEvent(e.id,r):n.eventRegistry.set(e.id,r,e.value));return}cn(n.eventRegistry,e.id,o,e.key,e.value,e.prev)}function Do(n,e){let t=n.nodes.get(e.id);t&&t.nodeType===1&&typeof e.fn=="function"&&(n.refRegistry.set(e.id,e.fn),n.refRegistry.mount(e.id,t))}function Fo(n,e){n.clearNodeRefs(e.id)}function _o(n,e){let t=n.registry?.get(e.compId);t&&(t.phase="mounted")}function Uo(n,e){n.registry&&wt(e.compId,n.registry)}function Wo(n,e){if(e.full&&n.absorb.end(),e.full&&n.touched.size>0)for(let[t,o]of[...n.nodes])n.touched.has(t)||(n.refRegistry.unmountOne(t),n.eventRegistry.removeOne(t),o.remove(),n.nodes.delete(t),n.unregisterChild(t));n.touched.clear()}function pn(n,e){switch(e.op){case"create":Mo(n,e);break;case"createText":Po(n,e);break;case"createAnchor":Vo(n,e);break;case"insert":Ao(n,e);break;case"move":Io(n,e);break;case"remove":Ho(n,e);break;case"setText":Lo(n,e);break;case"setProp":$o(n,e);break;case"ref":Do(n,e);break;case"unref":Fo(n,e);break;case"mount":_o(n,e);break;case"unmount":Uo(n,e);break;case"done":Wo(n,e);break;case"close":break}}var le=class{nodes=new Map;touched=new Set;childIds=new Map;byChild=new Map;seq=new Map;seqCounter=0;registerChild(e,t){this.byChild.set(t,e),this.seq.set(t,++this.seqCounter);let o=this.childIds.get(e);o||(o=new Set,this.childIds.set(e,o)),o.add(t)}unregisterChild(e){let t=this.byChild.get(e);if(t===void 0)return;this.byChild.delete(e),this.seq.delete(e);let o=this.childIds.get(t);o&&(o.delete(e),o.size===0&&this.childIds.delete(t))}collectDesc(e){let t=[],o=[e];for(;o.length>0;){let r=o.pop();t.push(r);let i=this.childIds.get(r);if(i)for(let s of i)o.push(s)}return t}reset(){this.nodes.clear(),this.touched.clear(),this.childIds.clear(),this.byChild.clear(),this.seq.clear(),this.seqCounter=0,this.eventRegistry.clear(),this.refRegistry.clear()}eventRegistry;refRegistry=new qe;absorb=new Be;container;doc;registry;devVerify=null;constructor(e,t,o){this.container=e,this.doc=t,this.registry=o??null,this.eventRegistry=new je(t,e)}dispose(){if(this.eventRegistry.dispose(),this.refRegistry.dispose(),this.registry)for(let e of[...this.registry.keys()].reverse()){let t=this.registry.get(e);if(t){for(let o of[...t.onUnmounts].reverse())try{o()}catch{}this.registry.delete(e)}}}clearNodeRefs(e){this.refRegistry.unmount(e)}remapSubtree(e,t){let o=(i,s)=>{let a=i.get(s);a!==void 0&&(i.delete(s),i.set(t+s.slice(e.length),a))};for(let i of[...this.nodes.keys()])if(i===e||i.startsWith(e+".")){o(this.nodes,i);let s=this.nodes.get(t+i.slice(e.length));s&&s.nodeType===1&&s.setAttribute("data-wf-id",t+i.slice(e.length))}for(let[i,s]of[...this.byChild]){let a=i===e||i.startsWith(e+"."),l=s===e||s.startsWith(e+".");if(!a&&!l)continue;let d=a?t+i.slice(e.length):i,u=l?t+s.slice(e.length):s;this.byChild.delete(i),this.byChild.set(d,u);let c=this.childIds.get(s);c&&(c.delete(i),c.size===0&&this.childIds.delete(s));let f=this.childIds.get(u);f||(f=new Set,this.childIds.set(u,f)),f.add(d)}let r=this.byChild.get(e);r!==void 0&&!this.byChild.has(t)&&(this.unregisterChild(e),this.registerChild(r,t)),this.refRegistry.remap(e,t);for(let i of[...this.eventRegistry.table.keys()])if(i===e||i.startsWith(e+".")){let s=this.eventRegistry.table.get(i);this.eventRegistry.table.delete(i),this.eventRegistry.table.set(t+i.slice(e.length),s)}if(this.registry){for(let i of[...this.registry.keys()])if(i===e||i.startsWith(e+".")){let s=this.registry.get(i);this.registry.delete(i),this.registry.set(t+i.slice(e.length),s)}}}parentOf(e){if(e.parent==="root")return this.container;let t=this.nodes.get(e.parent);if(t&&t.isConnected)return t;let o=e.parent.split(".");for(let r=o.length-1;r>0;r--){let i=o.slice(0,r).join(".");if(i==="root")return this.container;let s=this.nodes.get(i);if(s&&s.isConnected)return s}return null}apply(e){pn(this,e),this.devVerify&&this.devVerify(e,this)}};var ze="__wf_portal";function xt(n){return`${ze}-${n}`}function jo(n,e){switch(e.kind){case"open":return"open";case"exit":return n==="open"?"exit":n;case"closed":return"closed";case"disposed":return"closed"}}function qo(n){return typeof n=="function"?n():n}function mn(n){return n?typeof n=="function"?n():n:null}function Ye(n,e){let t={tree:null,applier:null,container:null,chain:Promise.resolve(),version:0,open:!1,phase:"closed",disposed:!1,panel:null,pos:{top:0,left:0},segments:new Map},o=new O,r=o.asObservable();o.asObservable().pipe(fe(jo,"closed")).subscribe({next:w=>{t.phase=w}});let i=w=>{o.next(w)},s=n.getBrowser()?.window,a=n.getBrowser()?.document,l=()=>{if(!a)return null;if(t.container)return t.container;let w=a.getElementById(ze);w||(w=a.createElement("div"),w.id=ze,a.body.appendChild(w));let E=e.key??"popup",R=a.getElementById(xt(E));return R?t.container=R:(t.container=a.createElement("div"),t.container.id=xt(E),w.appendChild(t.container)),t.container},d=0,u=!1,c=()=>{if(t.disposed||!t.open)return;if(e.position&&t.panel){let W=e.position();if(W&&typeof W.x=="number"&&typeof W.y=="number"){t.pos={top:W.y,left:W.x,width:W.width},u=!0,m();return}}let w=mn(e.anchor);if(!w||!t.panel){d++<10&&queueMicrotask(c);return}if(!s)return;let E=t.panel,R=E.offsetWidth||E.getBoundingClientRect().width,L=E.offsetHeight||E.getBoundingClientRect().height;if((R===0||L===0)&&d++<10){typeof s.requestAnimationFrame=="function"?s.requestAnimationFrame(c):queueMicrotask(c);return}let $=typeof e.placement=="function"?e.placement():e.placement??"bottom",G=jt(w,s,R,L,$,e.gap??8,e.margin??8,e.center??!0);if(!G){d++<10&&queueMicrotask(c);return}if(d=0,t.pos=G,t.applier){let W=h(t.tree);W&&C(W)}},f=w=>{if(t.panel=w,w&&t.open&&!u&&e.positioning!=="none"&&(s&&typeof s.requestAnimationFrame=="function"?s.requestAnimationFrame(c):queueMicrotask(c)),w&&e.presence){let E=R=>{t.phase==="exit"&&T()};w.addEventListener("animationend",E),n.onUnmount(()=>w.removeEventListener("animationend",E))}},g=null,b=w=>{g=w,w&&u&&m()},m=()=>{let w=e.mask?g:t.panel;w&&(w.style.top=`${t.pos.top}px`,w.style.left=`${t.pos.left}px`,t.pos.width!==void 0&&(w.style.width=`${t.pos.width}px`))},h=w=>{if(!w)return null;let E=w;e.mask&&(E=D("div",{class:"wf-popup-mask",style:{position:"fixed",inset:"0",background:"var(--wf-overlay, rgba(0,0,0,0.5))",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"var(--wf-z-modal, 1000)"},onClick:Z=>{e.maskClosable!==!1&&Z.target===Z.currentTarget&&p()}},e.maskCentered?{...E,props:{...E.props??{}}}:D("div",{class:"wf-popup-mask-inner",ref:b,style:e.position?{position:"fixed",top:`${t.pos.top}px`,left:`${t.pos.left}px`,...t.pos.width!==void 0?{width:`${t.pos.width}px`}:{}}:void 0},E)));let R=E.props??{},L=e.positioning==="none"||String(R.class??"").includes("mask")?R.class??"":["wf-popup",R.class].filter(Boolean).join(" "),$=!(e.mask&&e.position),G=e.positioning==="none"?{...R.style??{},position:"fixed"}:{...R.style??{},position:"fixed",...$?{top:`${t.pos.top}px`,left:`${t.pos.left}px`}:{},...$&&t.pos.width!==void 0?{width:`${t.pos.width}px`}:{}};return{...E,props:{...R,class:L,style:G,ref:f}}},C=w=>{let E=++t.version,R=t.tree;t.tree=w,t.chain=t.chain.then(async()=>{if(t.disposed||E!==t.version)return;let L=t.applier;if(!L)return;let $=L.registry;if(!$)return;let G=n.getSharedContext()??{},W=await new Promise((Z,qn)=>{let Mt=[],Pt=()=>n.requestRender?.();(R?Oe(R,w,G,t.segments,$,Pt):ye(w,G,$,t.segments,Pt)).subscribe({next:Bn=>Mt.push(Bn),error:qn,complete:()=>Z(Mt)})});for(let Z of W){if(t.disposed||E!==t.version)return;L.apply(Z)}for(let Z of W)Z.op==="unmount"&&q(Z.compId,t.segments)}).catch(L=>{console.error("[popup] render error:",L)})},x=()=>{t.disposed||(t.disposed=!0,t.applier&&(t.applier.dispose(),t.applier=null),t.tree=null,t.container&&(t.container.remove(),t.container=null))},T=()=>{t.disposed||(t.open=!1,i({kind:"closed"}),N(),x(),i({kind:"disposed"}),e.onClose?.())},p=()=>{!t.open||t.disposed||(e.presence?(i({kind:"exit"}),t.panel&&s&&!qt(t.panel,s)&&T(),t.panel||T()):T())},v={value:""},y={value:null},S={value:!1},N=()=>{S.value&&(a?.body&&(a.body.style.overflow=v.value),v.value="",y.value&&(y.value.focus?.(),y.value=null),S.value=!1)},J=()=>{n.scheduleAfterRender(()=>{let w=E=>{let R=t.panel;R?(R.querySelector?.("input, button, [tabindex], select, textarea")??R).focus?.():E<10&&t.open&&queueMicrotask(()=>w(E+1))};w(0)})},Ie=()=>{S.value=!0,e.lockScroll&&a?.body&&(v.value=a.body.style.overflow,a.body.style.overflow="hidden"),e.trapFocus&&s&&(y.value=s.document.activeElement,J())},se=null;e.trapFocus&&s&&(se=w=>{if(w.key!=="Tab"||!t.open||!t.panel)return;let E=Array.from(t.panel.querySelectorAll?.("input, button, [tabindex], select, textarea")??[]).filter(G=>!G.disabled&&G.offsetParent!==null);if(E.length===0)return;let R=E[0],L=E[E.length-1],$=s?.document.activeElement;w.shiftKey&&($===R||$===t.panel||!t.panel.contains($))?(w.preventDefault(),L.focus()):!w.shiftKey&&($===L||!t.panel.contains($))&&(w.preventDefault(),R.focus())},s.addEventListener("keydown",se));let ue=w=>{if(!t.open||(e.closeOnOutside??!0)===!1)return;let E=w.target,R=mn(e.anchor);E&&R?.contains(E)||E&&t.panel?.contains(E)||p()},Nt=w=>{t.open&&(e.closeOnEscape??!0)&&w.key==="Escape"&&p()};s&&(s.addEventListener("mousedown",ue),s.addEventListener("keydown",Nt)),n.onUnmount(()=>{s&&(s.removeEventListener("mousedown",ue),s.removeEventListener("keydown",Nt),se&&s.removeEventListener("keydown",se)),T()});let Wn=()=>{if(t.open||t.disposed)return;t.open=!0,i({kind:"open"});let w=l();if(!w)return;e.trapFocus||e.lockScroll?Ie():e.autoFocus&&J();let E=te();t.applier=new le(w,a,E),t.segments=new Map;let R=qo(e.content);R!=null?C(h(R)):T()},jn={close:p,update(w){if(t.disposed||!t.open)return;if(w==null){p();return}let E=!1;if(e.position){let R=e.position();R&&typeof R.x=="number"&&typeof R.y=="number"&&(t.pos={top:R.y,left:R.x,width:R.width},E=!0)}C(h(w)),E&&m()},refresh(){if(!(t.disposed||!t.open||!t.tree)&&e.position){let w=e.position();w&&typeof w.x=="number"&&typeof w.y=="number"&&(t.pos={top:w.y,left:w.x,width:w.width},m())}},get open(){return t.open},events$:r};return Wn(),jn}function gn(n,e,t){let o=n.nextHookIndex(),r=n.getHookState(o)??{value:t};n.setHookState(o,r);let i=e.value!==void 0;return{get value(){return e.value??r.value},controlled:e,setValue(s){i?(e.onChange||console.warn("[vdom] useControlled \u53D7\u63A7\u7F3A onChange \u56DE\u8C03\u2014\u2014\u4EA4\u4E92\u9759\u9ED8\u5931\u6548"),e.onChange?.(s)):(r.value=s,n.requestRender())}}}function bn(n,e){let t=new O,o=K(n,Bo(n,e,t),{y:0,x:0});return{get y(){return o().y},get x(){return o().x},refresh:()=>{t.next()}}}function Bo(n,e,t){let o=n.getBrowser()?.window,r=n.getBrowser()?.document??null;return P(i=>{if(!o)return i.next({y:0,x:0}),i.complete(),()=>{};let s,a=null,l=null,d=0,u=()=>{if(typeof e=="function")return e();if(e&&typeof e=="object"&&!("nodeType"in e)){let m=e;return typeof m.getScroller=="function"?m.getScroller()??null:m.root?typeof m.root=="string"?r?r.querySelector(m.root)??o:o:m.root:o}return o},c=m=>m?m===o?{y:o.scrollY||0,x:o.scrollX||0}:{y:m.scrollTop,x:m.scrollLeft}:{y:0,x:0},f=()=>{i.next(c(l))},g=()=>{if(a)return;if(l=u(),!l){d++<10&&n.scheduleAfterRender(g);return}let m=()=>{s===void 0&&(s=o.requestAnimationFrame(()=>{s=void 0,f()}))};l.addEventListener("scroll",m,{passive:!0}),a=m,f()};g();let b=t?.subscribe({next:()=>{g(),f()}});return()=>{b?.unsubscribe(),s!==void 0&&o.cancelAnimationFrame(s),a&&l&&l.removeEventListener("scroll",a),a=null}})}function vn(n,e){let t=n.nextHookIndex(),o=n.getHookState(t)??{isIn:!1,io:null,retries:0,ready:!1};n.setHookState(t,o);let i=n.getBrowser()?.window?.IntersectionObserver,s=e&&typeof e=="object"&&!("nodeType"in e)?e:void 0,a=s?.target??(typeof e=="function"||e&&"nodeType"in e?e:void 0),l=typeof s?.rootMargin=="function"?s.rootMargin():s?.rootMargin,d=typeof s?.threshold=="function"?s.threshold():s?.threshold,u=typeof s?.root=="function"?s.root():s?.root??null,c=f=>{if(!i||!f||o.io)return;let g=new i(b=>{let m=b[0];m&&m.isIntersecting!==o.isIn&&(o.isIn=m.isIntersecting,s?.onChange?.(m,m.isIntersecting),n.requestRender())},{root:u??void 0,rootMargin:l,threshold:d});g.observe(f),o.io=g,o.ready=!0,n.onUnmount(()=>o.io?.disconnect())};if(i&&!o.io){let f=typeof a=="function"?a():a??null;f?c(f):a!==void 0&&o.retries++<10&&n.scheduleAfterRender(()=>c(typeof a=="function"?a():a??null))}return{get isIn(){return o.isIn},get ready(){return o.ready},ref:f=>{f?c(f):o.io?.disconnect()},observe:f=>c(f),disconnect:()=>{o.io?.disconnect(),o.io=null}}}function hn(n,e,t){let o=n.nextHookIndex(),r=n.getHookState(o)??{keyword:"",selectedLabel:"",composing:!1};n.setHookState(o,r);let i=e.value!==void 0;return{controlled:e,get value(){return e.value??r.keyword},setValue(s){i?(e.onChange||console.warn(`[vdom] useControlledInput(${t?.name??""}) \u53D7\u63A7\u7F3A onChange \u56DE\u8C03\u2014\u2014\u4EA4\u4E92\u9759\u9ED8\u5931\u6548`),e.onChange?.(s)):(r.keyword=s,n.requestRender())},get keyword(){return r.keyword},setKeyword(s){r.keyword=s,r.composing||this.setValue(s)},get selectedLabel(){return r.selectedLabel},setSelectedLabel(s){r.selectedLabel=s},get isComposing(){return r.composing},onCompositionStart(){r.composing=!0},onCompositionEnd(){r.composing=!1}}}function wn(n,e){let t={draggable:!0,onDragStart:o=>{e.data!==void 0&&o.dataTransfer?.setData("text/plain",JSON.stringify(e.data)),e.onDragStart?.(o,e.data)},onDragEnd:o=>e.onDragEnd?.(o)};return{draggableProps:t,dragProps:t,dropProps:{onDragEnter:o=>e.onDragEnter?.(o),onDragOver:o=>{o.preventDefault(),e.onDragOver?.(o)},onDragLeave:o=>e.onDragLeave?.(o),onDrop:o=>{o.preventDefault();let r;try{r=o.dataTransfer?.getData("text/plain")?JSON.parse(o.dataTransfer.getData("text/plain")):void 0}catch{r=void 0}e.onDrop?.(o,r)}}}}var yn=new WeakMap,Ko=new Map;function zo(n,e){let t=n.getBrowser()?.window,o=t?yn.get(t)??yn.set(t,new Map).get(t):Ko,r=o.get(e);return r||(r=tt(i=>{let s=n.getBrowser()?.window,l=(s?.matchMedia?.bind(s)??(typeof globalThis.matchMedia=="function"?globalThis.matchMedia.bind(globalThis):void 0))?.(e);if(!l)return;let d=()=>i(l.matches);return l.addEventListener("change",d),()=>l.removeEventListener("change",d)},()=>{let i=n.getBrowser()?.window,s=i?.matchMedia?.bind(i)??(typeof globalThis.matchMedia=="function"?globalThis.matchMedia.bind(globalThis):void 0);return s?s(e).matches:!1}),o.set(e,r)),r}function Pe(n,e){return K(n,zo(n,e),!1)}function xn(n,e){let t=Object.entries(e).sort((o,r)=>o[1]-r[1]);return()=>{let o=t[0]?.[0]??"default";for(let[r,i]of t)Pe(n,`(min-width: ${i}px)`)()&&(o=r);return o}}var Yo=0,Tt=()=>`m${Date.now().toString(36)}${(Yo++).toString(36)}`;function Jo(){let n="";return(e,t)=>{let o=e.trim();if(!o)return null;if(o.startsWith("event:"))return n=o.slice(6).trim(),null;let r=t??n,i=o.startsWith("data:")?o.slice(5).trim():o;if(!i)return null;let s;try{s=JSON.parse(i)}catch{return null}if(!r)return s.toolCalls?{toolCalls:s.toolCalls}:s.text!==void 0?{content:String(s.text)}:s.content!==void 0?{content:s.content}:null;switch(r){case"wf:message_start":return null;case"wf:token":return{content:s.text!==void 0?String(s.text):s.content};case"wf:step":return{step:s};case"wf:usage":return{usage:s};case"wf:tool_call":return{toolCalls:[{id:s.id,name:s.name,args:s.args,status:"running",call:s}]};case"wf:tool_progress":return{toolProgress:s};case"wf:tool_result":return{toolResult:s};case"wf:approval_request":return{approval:s};case"wf:error":return{error:s};case"wf:done":{let a=s.usage?{usage:s.usage}:{};return{done:!0,...s.content?{content:s.content,doneContent:!0}:{},...a}}default:return null}}}function Tn(n,e){let t=n.nextHookIndex(),o=n.getHookState(t)??{messages:[],status:"idle",subs:new Set,changes:new O,controller:null,seq:0,input:"",error:null,usage:null,step:null};if(n.setHookState(t,o),o.messages.length===0){let a=[];e.system&&a.push({id:Tt(),role:"system",content:e.system}),e.initialMessages&&a.push(...e.initialMessages),o.messages=a}let r=()=>{for(let a of[...o.subs])a();o.changes.next([...o.messages])},i=e.parseChunk??Jo(),s={get state(){return o.messages},get messages(){return o.messages},changes$:o.changes.asObservable(),get status(){return o.status},get input(){return o.input??""},setInput(a){o.input=a},get streaming(){return o.status==="streaming"},get error(){return o.error??null},get usage(){return o.usage??null},get step(){return o.step??null},subscribe(a){return o.subs.add(a),()=>{o.subs.delete(a)}},set(){},update(){},notify:r,async send(a=o.input){let l=typeof e.url=="function"?e.url():e.url??"/api/chat",d={id:Tt(),role:"user",content:a};o.messages=[...o.messages,d];let u={id:Tt(),role:"assistant",content:"",status:"streaming"};o.messages=[...o.messages,u],o.status="streaming",r();let c=new AbortController;o.controller=c;try{let f=await fetch(l,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({messages:o.messages.map(h=>({role:h.role,content:h.content}))}),signal:c.signal});if(!f.ok||!f.body)throw new Error(`[vdom] chat \u8BF7\u6C42\u5931\u8D25 ${f.status}`);let g=f.body.getReader(),b=new TextDecoder,m="";for(;;){let{value:h,done:C}=await g.read();if(C)break;m+=b.decode(h,{stream:!0});let x=m.split(`
|
|
15
|
+
`);m=x.pop()??"";let T;for(let p of x){if(!p.trim())continue;if(p.trim().startsWith("event:")){T=p.trim().slice(6).trim();continue}let v=i(p,T);if(p.trim().startsWith("data:")&&(T=void 0),!!v){if(v.content&&(u.content=v.doneContent?u.content||v.content:u.content+v.content,r()),v.toolCalls?.length&&(u.toolCalls=[...u.toolCalls??[],...v.toolCalls],r()),v.toolProgress){let y=u.toolCalls?.find(S=>S.id===v.toolProgress.toolCallId);y&&(y.progress=v.toolProgress,r())}if(v.toolResult){let y=u.toolCalls?.find(S=>S.id===v.toolResult.id);y&&(y.result=v.toolResult.output,y.status=v.toolResult.ok===!1?"error":"ok",r())}if(v.approval){u.approval=v.approval;let y=u.toolCalls?.find(S=>S.id===v.approval.toolCallId);y&&(y.approval=v.approval),r()}v.usage&&(o.usage=v.usage,r()),v.step!==void 0&&(o.step=v.step,r()),v.error&&(o.error=v.error,u.status="error",r()),v.done&&(o.step=null,r())}}}u.status=void 0,o.status="idle"}catch(f){f.name!=="AbortError"?(u.status="error",o.status="error"):(u.status=void 0,o.status="idle")}finally{o.controller=null,r()}},stop(){o.controller?.abort()},retry(){let a=[...o.messages].reverse().find(l=>l.role==="user");a&&s.send(a.content)},reset(){o.messages=[],o.status="idle",r()},async approve(a,l,d){let u=!1;for(let c of o.messages){for(let f of c.toolCalls??[])if(!f.approved){f.approved=a!=="rejected",l&&(f.feedback=l),a==="modified"&&d&&(f.args=d),u=!0;break}if(u)break}r()}};return s}function Ct(n){return Pe(n,"(prefers-reduced-motion: reduce)")()}function Cn(n,e,t){let o=n.getBrowser()?.window,r=Ct(n),i=t?.duration??400;if(i<=0)return{value:e,reset:()=>{}};let s=t?.ease==="linear"?T=>T:T=>1-Math.pow(1-T,3),a=n.nextHookIndex(),l=n.getHookState(a);if(l)return l.reset(e),l;let d=r?e:0,u,c=e,f=0,g=i+200,b,m={get value(){return u!==void 0&&o&&o.performance.now()-f>g?c:d},set value(T){d=T},reset:()=>{}},h=()=>{n.requestRender()},C=T=>{if(c=T,r){m.value=T,h();return}if(T===m.value)return;if(!o){m.value=T;return}u!==void 0&&o.cancelAnimationFrame(u);let p=m.value,v=o.performance.now();f=v,x();let y=S=>{let N=Math.min(1,(S-v)/i);m.value=Math.round(p+(T-p)*s(N)),N<1?u=o.requestAnimationFrame(y):u=void 0,h()};u=o.requestAnimationFrame(y)},x=()=>{o&&(b!==void 0&&clearTimeout(b),b=setTimeout(()=>{b=void 0,u!==void 0&&(o&&o.cancelAnimationFrame(u),u=void 0,m.value=c,h())},g))};return m.reset=T=>{T===c&&u!==void 0||C(T)},n.onUnmount(()=>{u!==void 0&&o&&(o.cancelAnimationFrame(u),u=void 0)}),n.setHookState(a,m),l=m,l.reset(e),l}function kn(n,e){let t=n.getBrowser()?.window,o=0,r=0,i=!1,s=0,a=c=>{i&&e.onMove(c,{x:c.clientX-o,y:c.clientY-r})},l=c=>{i&&c.pointerId===s&&(i=!1,t&&(t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",l),t.removeEventListener("pointercancel",d)),e.onEnd?.(c))},d=c=>{!i||c.pointerId!==s||(i=!1,t&&(t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",l),t.removeEventListener("pointercancel",d)),e.onEnd?.(c))},u=c=>{i||(c.preventDefault(),i=!0,s=c.pointerId,o=c.clientX,r=c.clientY,t&&(t.addEventListener("pointermove",a),t.addEventListener("pointerup",l),t.addEventListener("pointercancel",d)),e.onStart?.(c))};return n.onUnmount(()=>{i&&t&&(t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",l),t.removeEventListener("pointercancel",d),i=!1)}),{onPointerDown:u}}function Sn(n){let e=K(n,Go(n),{height:0,offsetTop:0,keyboardOpen:!1});return{get height(){return e().height},get offsetTop(){return e().offsetTop},get keyboardOpen(){return e().keyboardOpen}}}function Go(n){let e=n.getBrowser()?.window;return P(t=>{let o=()=>{let s=e?.visualViewport,a=s?.height??e?.innerHeight??0;return{height:a,offsetTop:s?.offsetTop??0,keyboardOpen:a<(e?.innerHeight??0)*.9}};if(!e)return t.next({height:0,offsetTop:0,keyboardOpen:!1}),t.complete(),()=>{};let r=()=>t.next(o()),i=e.visualViewport;return i?.addEventListener?(i.addEventListener("resize",r),i.addEventListener("scroll",r),r(),()=>{i.removeEventListener("resize",r),i.removeEventListener("scroll",r)}):(e.addEventListener("resize",r),r(),()=>e.removeEventListener("resize",r))})}function kt(n,e){let t=n.nextHookIndex(),o=n.getHookState(t);return o===void 0&&(o={v:e},n.setHookState(t,o)),{get:()=>o.v,set:r=>{o.v=typeof r=="function"?r(o.v):r,n.requestRender()}}}function St(n,e){let t=null,o=e,r={onClick:l=>{o.maskClosable!==!1&&l.target===l.currentTarget&&s()}},i={role:e.role??"dialog","aria-modal":!0},s=()=>o.onOpenChange?.(!1),a=(l,d)=>{d&&(o=d);let u=!!o.open;u&&!t?t=Ye(n,{key:"overlay",presence:!!o.presence,trapFocus:o.trapFocus!==!1,lockScroll:o.lockScroll!==!1,positioning:"none",closeOnOutside:!1,closeOnEscape:!1,content:l,onClose:()=>{t=null}}):!u&&t?(t.update(l()),t.close(),t=null):t&&t.update(l())};return Fe(n,l=>{l.key==="Escape"&&t?.open&&o.closeOnEscape!==!1&&s()}),n.onUnmount?.(()=>{t&&t.close()}),{maskProps:r,panelProps:i,close:s,sync:a}}function Et(n,e){let t=e,o=()=>t.id??(t.name?`wf-${t.name}`:void 0),r=()=>o()??"wf-field";return{get hasWrap(){return!!(t.label||t.error||t.hint)},get stateClass(){return t.error?` ${t.wrapErrClass??"wf-field--err"}`:""},get inputId(){return o()},inputProps(){let i={},s=o();s&&(i.id=s),t.error&&(i["aria-invalid"]=!0);let a=[];return t.error&&a.push(`${r()}-err`),t.hint&&!t.error&&a.push(`${r()}-hint`),a.length&&(i["aria-describedby"]=a.join(" ")),t.required&&(i["aria-required"]=!0),i},renderLabel(){if(t.label==null&&!t.required)return null;let i=[];return t.label!=null&&i.push(t.label),t.required&&i.push(D("span",{class:t.reqClass??"wf-field-req"},t.reqChar??"*")),D("label",{class:t.labelClass,...o()?{for:o()}:{}},i)},renderError(){return t.error?D("div",{class:t.errClass,id:`${r()}-err`},t.error):null},renderHint(){return t.hint&&!t.error?D("div",{class:t.hintClass,id:`${r()}-hint`},t.hint):null}}}var En=new Map,Rn=new Set,Xo=new O;var Je=new Map;function mt(n){return{useObservable(e,t,o){return K(n,e,t,o)},useAsyncData(e,t){let o=En.get(t);o||(o={trigger:new ne(void 0),state$:new ne(Je.get(t)??null),fetcher:null,started:Je.has(t),seedHit:Je.has(t),sub:null},Je.delete(t),En.set(t,o)),o.fetcher=e;let r=()=>{if(o.sub||o.seedHit)return;o.started=!0;let a=o.trigger.asObservable().pipe(De(()=>{let l=o.fetcher;if(!l)return ce(Promise.resolve(null));let d=l();return Rn.add(d),d.finally(()=>Rn.delete(d)).catch(()=>{}),ce(d)}));o.sub=a.subscribe({next:l=>{o.state$.next(l)},error:l=>{console.error("[vdom] useAsyncData:",l),Xo.next({key:t,error:l}),o.state$.next(null)}})};return r(),[K(n,o.state$.asObservable(),null),()=>{o.seedHit&&(o.seedHit=!1),o.state$.next(null),o.sub?o.trigger.next():r()}]},useSession(e){let[t]=this.useAsyncData(async()=>{let o={},r=e?.token?.();r&&(o.Authorization=`Bearer ${r}`);let i=await fetch(e?.path??"/api/auth/me",{headers:o});if(!i.ok)throw new Error(`session \u83B7\u53D6\u5931\u8D25 HTTP ${i.status}`);return await i.json()},"wf:session");return t},useExternal(e){let t=n.getInstanceData(),o=t.get(e);if(!o){let r=e.subscribe(()=>n.requestRender());n.onUnmount(r),o={unsub:r},t.set(e,o)}return()=>e.state},signal:e=>{let t=st(e),o=t.subscribe(()=>n.requestRender());return n.onUnmount(o),t},hold:e=>n.onUnmount(e),useStableRef:(e,t)=>Ut(n,e,t),useOpen:(e,t)=>Wt(n,e,t),onUnmount:e=>n.onUnmount(e),useGlobalKey:(e,t)=>Fe(n,e,t),openPopup:e=>Ye(n,e),usePopupPosition:e=>Bt(n,e),useControlled:(e,t)=>gn(n,e,t),useScrollPosition:e=>bn(n,e),useInView:e=>vn(n,e),useControlledInput:(e,t)=>hn(n,e,t),useDragDrop:e=>wn(n,e),useMedia:e=>Pe(n,e),useBreakpoint:e=>xn(n,e),useChat:e=>Tn(n,e),useTween:(e,t)=>Cn(n,e,t),useDrag:e=>kn(n,e),useVisualViewport:()=>Sn(n),useReducedMotion:()=>Ct(n),useSignal:e=>kt(n,e),useOverlay:e=>St(n,e),useField:e=>Et(n,e)}}function We(n){return F(n)?{kind:"hole"}:Array.isArray(n)?{kind:"array",items:n}:{kind:"vnode",v:n}}function re(n){return n.kind==="hole"?null:n.kind==="array"?n.items:n.v}function te(){let n=new Map;return{get:e=>n.get(e),set:(e,t)=>{n.set(e,t)},delete:e=>{n.delete(e)},keys:()=>[...n.keys()],asyncTimeout:15e3}}function wt(n,e){let t=[...e.keys()].filter(o=>o===n||o.startsWith(n+".")).reverse();for(let o of t){let r=e.get(o);if(r){for(let i of r.onUnmounts.reverse())try{i()}catch(s){console.error("[vdom] onUnmount:",s)}e.delete(o)}}}function gt(n,e,t,o){return typeof n?.type=="function"||Array.isArray(n)||z(n)==="hole"?{parent:e,index:0}:{parent:t,index:o}}function H(n,e,t,o,r,i,s,a){let l=[];return Ve(n,e,t,o,r,i,s,a,l),M(l)}function Ve(n,e,t,o,r,i,s,a,l){let d=k(e,t);switch(z(n)){case"text":{let u=_e(n);l.push({op:"createText",id:d,value:u},{op:"insert",id:d,parent:e,ref:o});break}case"hole":{ut(u=>l.push(u),d,e,o);break}case"array":{let u=n;Ce(u,`\u6570\u7EC4\u5C55\u5F00\uFF08${e}\uFF09`);let c=t,f=o;for(let g of u){Ve(g,e,c,f,r,i,s,a,l);let b=A(g);f=k(e,c+b-1),c+=b}break}case"fragment":{let u=I(n);Ce(u,`Fragment \u5C55\u5F00\uFF08${e}\uFF09`);let c=t,f=o;for(let g of u){Ve(g,e,c,f,r,i,s,a,l);let b=A(g);f=k(e,c+b-1),c+=b}break}case"element":{let u=n;l.push({op:"create",id:d,tag:u.type,attrs:ke(u.props)});for(let[m,h]of Object.entries(u.props))m==="children"||m==="key"||m==="ref"||typeof h=="function"&&l.push({op:"setProp",id:d,key:m,value:h});l.push({op:"insert",id:d,parent:e,ref:o});let c=u.props.ref;typeof c=="function"&&l.push({op:"ref",id:d,fn:c});let f=I(u);Ce(f,`\u5143\u7D20 children\uFF08${d}\uFF09`);let g=null,b=0;for(let m of f){Ve(m,d,b,g,r,i,s,a,l);let h=A(m);g=k(d,b+h-1),b+=h}l.push({op:"close",id:d});break}case"component":{let u=n,c=u.key!==null?j(e,u.key):d,f=s??new Map,g=f.get(c);g&&g.factory!==u.type&&(q(c,f),g=void 0),g?B("seg:reuse",c):(g=ft(u.type,u.props,r,c,a),f.set(c,g),B("seg:create",c));let b;try{b=pt(g,u.props)}catch(h){Te(c,h),b=null}b!==null&&Qe(c),g.lastOutput=We(b);let m=gt(b,c,e,t);if(F(b)){let h=k(c,0);l.push({op:"createAnchor",id:h},{op:"insert",id:h,parent:e,ref:o},{op:"mount",compId:c});break}Ve(b,m.parent,m.index,o,r,i,f,a,l),l.push({op:"mount",compId:c});break}case"invalid":{console.warn(`[vdom] \u975E\u6CD5\u5B50\u8282\u70B9\u2014\u2014${lt(n)}`),ut(u=>l.push(u),d,e,o,lt(n));break}}}function ye(n,e,t,o,r){let i=e??{},s=t??te();return H(n,"root",0,null,i,s,o,r).pipe(Zo(M([{op:"done",full:!0}])))}function M(n){return P(e=>{for(let t of n)e.next(t);return e.complete(),()=>{}})}function U(n){return P(e=>{let t=0,o=null,r=!1,i=!1,s=()=>{if(!(r||i)){for(i=!0;!r;){if(t>=n.length){e.complete();break}let a=n[t++],l=!1,d=!0;if(o=a.subscribe({next:u=>e.next(u),error:u=>{r||(r=!0,e.error(u))},complete:()=>{l||r||(l=!0,!d&&s())}}),d=!1,!l)break}i=!1}};return s(),()=>{r=!0,o?.unsubscribe()}})}function Zo(n){return e=>U([e,n])}function In(n){return new Promise((e,t)=>{let o=[];n.subscribe({next:r=>o.push(r),error:t,complete:()=>e(o)})})}async function Rt(n,e,t){let o=t??te(),r=await In(ye(n,e,o)),{commandToHtml:i}=await Promise.resolve().then(()=>(An(),Vn)),a=new ReadableStream({start(d){for(let u of r)d.enqueue(u);d.close()}}).pipeThrough(i()).getReader(),l="";for(;;){let{value:d,done:u}=await a.read();if(u)break;l+=d}return l}function ur(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function _n(n){return n==null||n===!1||n===!0?"":Array.isArray(n)?n.map(_n).join(""):n instanceof de?n.value:ur(String(n))}function dr(n){return new de(n)}var cr=32;async function Ln(n){let e={};for(let t of n)try{let o=await Ot(t);e[t]={mtimeMs:o.mtimeMs,size:o.size}}catch{e[t]={mtimeMs:-1,size:-1}}return e}async function Un(n,e=new Set){if(e.has(n))return[];e.add(n);let t;try{t=await Dn(n,"utf-8")}catch{return[]}let o=Fn(n),r=[];for(let i of t.matchAll(/@import\s+['"](\.[^'"]+\.css)['"]/g)){let s=Ge(o,i[1]);r.push(s,...await Un(s,e))}return r}var Ae;async function fr(){if(Ae!==void 0)return Ae;try{await import("postcss"),await import("@tailwindcss/postcss"),Ae=!0}catch{Ae=!1}return Ae}function $n(n){if(n.startsWith(".")||n.startsWith("/"))return Ge(n);try{return lr(import.meta.resolve(n))}catch{return Ge(n)}}function kd(n={}){let e=n.cache!==!1,t=new Map,o=new Map,r={builds:0,hits:0,dedups:0};async function i(d){for(let[u,c]of Object.entries(d))try{let f=await Ot(u);if(f.mtimeMs!==c.mtimeMs||f.size!==c.size)return!1}catch{return!1}return!0}async function s(d,u,c){let f=`${d}:${u}`;if(e){let b=t.get(f);if(b&&await i(b.inputs))return r.hits++,b;let m=o.get(f);if(m)return r.dedups++,m}r.builds++;let g=(async()=>{let{code:b,inputs:m}=await c(),h=`"${ir("sha1").update(b).digest("hex").slice(0,20)}"`,C={code:b,etag:h,inputs:m};if(e){if(t.size>=cr){let x=t.keys().next().value;x!==void 0&&t.delete(x)}t.set(f,C)}return C})();return e&&(o.set(f,g),g.catch(()=>{}).finally(()=>o.delete(f))),g}function a(d,u,c,f){let g={"Content-Type":f,ETag:c,"Cache-Control":"no-cache"};return d.headers.get("if-none-match")===c?new Response(null,{status:304,headers:g}):new Response(u,{headers:g})}let l=(async(d,u,c)=>{function f(g,...b){let m="";for(let h=0;h<g.length;h++)m+=g[h],h<b.length&&(m+=_n(b[h]));return new Response(m,{headers:{"Content-Type":"text/html; charset=utf-8"}})}return u.ui={html:Object.assign(f,{unsafe:dr}),async ssr(g,b){return Rt(D(g,b??{}))},ssrData(g){let b=JSON.stringify(Object.fromEntries(g)).replace(/</g,"<");return new de(`<script>window.__DATA__=${b};</script>`)},async js(g){let b=$n(g),{code:m,etag:h}=await s("js",b,async()=>{let C=await sr({entryPoints:[b],bundle:!0,format:"esm",platform:"browser",jsx:"automatic",jsxImportSource:"weifuwu/client/vdom",write:!1,metafile:!0,logLevel:"silent"}),x={};for(let T of Object.keys(C.metafile?.inputs??{})){let p=Ge(T);try{let v=await Ot(p);x[p]={mtimeMs:v.mtimeMs,size:v.size}}catch{x[p]={mtimeMs:-1,size:-1}}}return{code:C.outputFiles[0].text,inputs:x}});return a(d,m,h,"application/javascript")},async css(g){let b=$n(g),{code:m,etag:h}=await s("css",b,async()=>{let C=Fn(b);if(ar(b)==="weifuwu-layout.css"&&await $t(C)){let p=await Dt(C);return{code:p.css,inputs:await Ln(p.inputs)}}let x=await Dn(b,"utf-8"),T=await Ln([b,...await Un(b)]);if(await fr())try{let p=await import("postcss"),v=await import("@tailwindcss/postcss"),y=v.default||v,S=typeof y=="function"?y():y;x=(await p.default([S]).process(x,{from:b})).css}catch(p){throw new Error(`PostCSS \u7F16\u8BD1\u5931\u8D25 (${b}): ${p.message}`,{cause:p})}return{code:x,inputs:T}});return a(d,m,h,"text/css; charset=utf-8")}},c(d,u)});return l.__stats=r,l}export{kd as ui};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var l=class extends Error{status;constructor(e,t){super(e),this.name="HttpError",this.status=t}};var Y=class extends Error{issues;constructor(e){super(e.map(t=>`${t.path}: ${t.message}`).join("; ")),this.name="ZodError",this.issues=e}},R=class{_meta={};get metaInfo(){return this._meta}meta(e){return this._meta={...this._meta,...e},this}parse(e){let t=this._parse(e);if(!t.ok)throw new Y([{path:t.path??"",message:t.message??"invalid"}]);return t.value}safeParse(e){let t=this._parse(e);return t.ok?{success:!0,data:t.value}:{success:!1,error:new Y([{path:t.path??"",message:t.message??"invalid"}])}}optional(){return new ye(this)}nullable(){return new _e(this)}default(e){return new ke(this,e)}refine(e,t){return new be(this,e,t)}transform(e){return new xe(this,e)}},Q=class extends R{_typeName(){return"string"}_parse(e){if(typeof e!="string")return{ok:!1,path:"",message:"expected string"};let t=e;return this._min!==void 0&&t.length<this._min?{ok:!1,path:"",message:`too small (min ${this._min})`}:this._max!==void 0&&t.length>this._max?{ok:!1,path:"",message:`too big (max ${this._max})`}:this._pattern&&!this._pattern.test(t)?{ok:!1,path:"",message:"invalid pattern"}:this._email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?{ok:!1,path:"",message:"invalid email"}:this._uuid&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)?{ok:!1,path:"",message:"invalid uuid"}:{ok:!0,value:t}}_min;_max;_pattern;_email=!1;_uuid=!1;min(e){return this._min=e,this}max(e){return this._max=e,this}regex(e,t){return this._pattern=e,this}email(){return this._email=!0,this}uuid(){return this._uuid=!0,this}},le=class extends R{_typeName(){return"number"}_parse(e){if(typeof e!="number"||Number.isNaN(e))return{ok:!1,path:"",message:"expected number"};let t=e;return this._int&&!Number.isInteger(t)?{ok:!1,path:"",message:"expected integer"}:this._min!==void 0&&t<this._min?{ok:!1,path:"",message:`too small (min ${this._min})`}:this._max!==void 0&&t>this._max?{ok:!1,path:"",message:`too big (max ${this._max})`}:{ok:!0,value:t}}_int=!1;_min;_max;int(){return this._int=!0,this}min(e){return this._min=e,this}max(e){return this._max=e,this}positive(){return this._min=0,this}},de=class extends R{_typeName(){return"boolean"}_parse(e){return typeof e!="boolean"?{ok:!1,path:"",message:"expected boolean"}:{ok:!0,value:e}}},ee=class extends R{lit;constructor(e){super(),this.lit=e}get value(){return this.lit}_typeName(){return"literal"}_parse(e){return e!==this.lit?{ok:!1,path:"",message:`expected literal ${JSON.stringify(this.lit)}`}:{ok:!0,value:e}}},te=class extends R{raw;constructor(e){super(),this.raw=e}get values(){return this.raw}_typeName(){return"enum"}_parse(e){return typeof e!="string"||!this.raw.includes(e)?{ok:!1,path:"",message:`expected one of ${this.raw.join(" | ")}`}:{ok:!0,value:e}}},pe=class extends R{_typeName(){return"datetime"}_parse(e){return typeof e!="string"||Number.isNaN(Date.parse(e))?{ok:!1,path:"",message:"expected datetime string (ISO)"}:{ok:!0,value:e}}},ce=class extends R{dims;constructor(e){super(),this.dims=e}_typeName(){return"vector"}_parse(e){return typeof e!="object"||e===null||!Array.isArray(e)||!e.every(t=>typeof t=="number")?{ok:!1,path:"",message:"expected number[] vector"}:this.dims>0&&e.length!==this.dims?{ok:!1,path:"",message:`expected vector(${this.dims})\u2014\u2014got ${e.length} dims`}:{ok:!0,value:e}}},ge=class extends R{_typeName(){return"json"}_parse(e){return{ok:!0,value:e}}},me=class n extends R{shape;constructor(e){super(),this.shape=e}_typeName(){return"object"}_parse(e){if(typeof e!="object"||e===null||Array.isArray(e))return{ok:!1,path:"",message:"expected object"};let t={},y=[];for(let[w,S]of Object.entries(this.shape)){let A=S._parse(e[w]);if(!A.ok){y.push({path:w,message:A.message??""});continue}t[w]=A.value}return y.length?{ok:!1,path:y[0].path,message:y[0].message}:{ok:!0,value:t}}pick(e){let t={};for(let y of e)t[y]=this.shape[y];return new n(t)}omit(e){let t={};for(let[y,w]of Object.entries(this.shape))e.includes(y)||(t[y]=w);return new n(t)}extend(e){return new n({...this.shape,...e})}},fe=class extends R{inner;constructor(e){super(),this.inner=e}get itemSchema(){return this.inner}_typeName(){return"array"}_parse(e){if(!Array.isArray(e))return{ok:!1,path:"",message:"expected array"};if(this._min!==void 0&&e.length<this._min)return{ok:!1,path:"",message:`too small (min ${this._min})`};if(this._max!==void 0&&e.length>this._max)return{ok:!1,path:"",message:`too big (max ${this._max})`};let t=[];for(let y=0;y<e.length;y++){let w=this.inner._parse(e[y]);if(!w.ok)return{ok:!1,path:`${y}`,message:w.message};t.push(w.value)}return{ok:!0,value:t}}_min;_max;min(e){return this._min=e,this}max(e){return this._max=e,this}},we=class extends R{options;constructor(e){super(),this.options=e}_typeName(){return"union"}_parse(e){let t=null;for(let y of this.options){let w=y._parse(e);if(w.ok)return{ok:!0,value:w.value};t||(t={path:w.path??"",message:w.message??""})}return{ok:!1,path:"",message:`expected union (${t?.message})`}}},he=class extends R{disc;options;discValueOf;constructor(e,t,y){super(),this.disc=e,this.options=t,this.discValueOf=y}_typeName(){return"disUnion"}_parse(e){if(typeof e!="object"||e===null)return{ok:!1,path:"",message:"expected object"};let t=e[this.disc];for(let y of this.options)if(this.discValueOf(y.shape)===t){let w=y._parse(e);return w.ok?{ok:!0,value:w.value}:{ok:!1,path:`(${String(t)})`,message:w.message??""}}return{ok:!1,path:this.disc,message:`invalid discriminator value ${JSON.stringify(t)}`}}};function Ke(n,e){let t=n[e];if(t instanceof ee)return t.lit;if(t instanceof te)return t.values;throw new Error(`z.discriminatedUnion: \u5224\u522B\u5B57\u6BB5\u9700\u4E3A literal/enum\u2014\u2014\u5F97\u5230 ${t?._typeName?.()}`)}var ye=class extends R{inner;constructor(e){super(),this.inner=e}_typeName(){return"optional"}_parse(e){return e===void 0?{ok:!0,value:void 0}:this.inner._parse(e)}},_e=class extends R{inner;constructor(e){super(),this.inner=e}_typeName(){return"nullable"}_parse(e){return e===null?{ok:!0,value:null}:this.inner._parse(e)}},ke=class extends R{inner;d;constructor(e,t){super(),this.inner=e,this.d=t}_typeName(){return"default"}_parse(e){if(e===void 0){let t=typeof this.d=="function"?this.d():this.d;return this.inner._parse(t)}return this.inner._parse(e)}},be=class extends R{inner;fn;msg;constructor(e,t,y){super(),this.inner=e,this.fn=t,this.msg=y}_typeName(){return"effects"}_parse(e){let t=this.inner._parse(e);return t.ok?this.fn(t.value)?{ok:!0,value:t.value}:{ok:!1,path:"",message:this.msg??"refine failed"}:{ok:!1,path:t.path??"",message:t.message??""}}},xe=class extends R{inner;fn;constructor(e,t){super(),this.inner=e,this.fn=t}_typeName(){return"transform"}_parse(e){let t=this.inner._parse(e);return t.ok?{ok:!0,value:this.fn(t.value)}:{ok:!1,path:t.path??"",message:t.message??""}}},i={string:()=>new Q,number:()=>new le,boolean:()=>new de,literal:n=>new ee(n),enum:n=>new te(n),date:()=>new pe,uuid:()=>new Q().uuid(),json:()=>new ge,vector:n=>new ce(n),object:n=>new me(n),array:n=>new fe(n),union:n=>new we(n),discriminatedUnion:(n,e)=>new he(n,e,t=>Ke(t,n))};function z(n,e){return n.meta(e)}var x={pk:n=>z(n,{pk:!0,default:"random"}),req:n=>z(n,{notNull:!0}),col:(n,e)=>z(n,{column:e}),now:n=>z(n,{default:"now"}),unique:n=>z(n,{unique:!0}),dflt:(n,e)=>z(n,{default:e})};import{randomBytes as We,scrypt as ze,timingSafeEqual as He}from"node:crypto";import{promisify as Fe}from"node:util";var Ae=Fe(ze),Ve=64,ne={N:16384,r:8,p:1};async function J(n){let e=We(16),t=await Ae(n,e,Ve,ne);return`scrypt$${ne.N}$${ne.r}$${ne.p}$${e.toString("hex")}$${t.toString("hex")}`}async function re(n,e){let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let[,y,w,S,A,j]=t,$=Buffer.from(j,"hex"),U=await Ae(n,Buffer.from(A,"hex"),$.length,{N:Number(y),r:Number(w),p:Number(S)});return U.length===$.length&&He(U,$)}import{createHash as Je,createHmac as qe,randomBytes as Ge,timingSafeEqual as Xe}from"node:crypto";var Oe=n=>Buffer.from(JSON.stringify(n)).toString("base64url");function se(n,e,t){let y=Math.floor(Date.now()/1e3),w=`${Oe({alg:"HS256",typ:"JWT"})}.${Oe({...n,iat:y,exp:y+t})}`,S=qe("sha256",e).update(w).digest("base64url");return`${w}.${S}`}function ae(n,e){let t=n.split(".");if(t.length!==3)return null;let[y,w,S]=t,A=`${y}.${w}`,j=qe("sha256",e).update(A).digest("base64url"),$=Buffer.from(S),U=Buffer.from(j);if($.length!==U.length||!Xe($,U))return null;try{let T=JSON.parse(Buffer.from(w,"base64url").toString("utf8"));return typeof T.exp=="number"&&T.exp<Date.now()/1e3?null:T}catch{return null}}function je(){return Ge(32).toString("hex")}function ie(n){return Je("sha256").update(n).digest("hex")}function Z(n,e){return Response.json(n,{status:200,...e})}function B(n,e){return Response.json(n,{status:201,...e})}function $e(n){return new Response(null,{status:204,...n})}function H(n){return Response.json({error:n??"Bad Request"},{status:400})}import{randomBytes as Pe}from"node:crypto";var oe={users:{id:x.pk(i.uuid()),email:x.req(i.string()).meta({unique:!0}),password_hash:i.string().nullable(),name:i.string().nullable(),role:i.string().nullable(),tenant:i.string().nullable(),email_verified:i.boolean().meta({notNull:!0,default:!1}),created_at:x.now(i.date())},sessions:{token_hash:x.req(i.string()),user_id:x.req(i.uuid()),app_id:i.string().nullable(),expires_at:x.req(i.date()),revoked_at:i.date().nullable(),created_at:x.now(i.date())},apps:{id:x.pk(i.uuid()),slug:x.req(i.string()).meta({unique:!0}),name:x.req(i.string()),owner_user_id:i.uuid().nullable(),open_registration:i.boolean().meta({notNull:!0,default:!1}),app_key:i.string().nullable(),created_at:x.now(i.date())},members:{app_id:x.req(i.uuid()),user_id:x.req(i.uuid()),role:i.string().meta({notNull:!0,default:"member"}),invited_by:i.uuid().nullable(),joined_at:x.now(i.date()),source:i.string().nullable(),last_login_at:i.date().nullable()}},Ye="_weifuwu_users",Qe="_weifuwu_sessions",Se="_weifuwu_apps",N="00000000-0000-4000-8000-0000000000b1",Ze="_weifuwu_app_members",Ne=8,et=1024;function Te(n){if(n.length<Ne)throw new l(`password must be at least ${Ne} characters`,400);if(n.length>et)throw new l("password is too long",400)}function D(n){return n.trim().toLowerCase()}var Ue=null;async function Me(n){Ue??=await J("dummy-timing-equalize-password"),await re(n,Ue)}function vt(n){let e=n.orm,t=e.table(Ye,oe.users),y=e.table(Qe,oe.sessions),w=e.table(Se,oe.apps),S=e.table(Ze,oe.members),A=n.secret??process.env.AUTH_SECRET;if(!A)throw new Error("userSystem: secret is required \u2014 pass options.secret or set AUTH_SECRET (at least 32 chars)");if(A.length<16)throw new Error("userSystem: secret must be at least 16 characters");let j=A,$=n.hooks,U=n.allowedRoles??["owner","admin","member","viewer"],T=n.sso??null,Re=n.inviteRoles??U;function ve(a){if(a!==void 0&&!U.includes(a))throw new l(`invalid role: ${a}\uFF08allowed: ${U.join("/")}\uFF09`,403)}let De=n.accessTtlSeconds??3600,Ce=n.refreshTtlDays??30,Ee=n.prefix??"/api/auth",G=a=>({id:String(a.id),email:a.email,name:a.name,role:a.role,tenant:a.tenant}),Be=168*3600;async function ue(a){let g=await t.select("id","email","name","role","tenant").where({id:{eq:a}}).run();return g.length?g[0]:null}async function F(a,g){(await S.select("role").where({app_id:{eq:N},user_id:{eq:a}}).run()).length||await S.insert({app_id:N,user_id:a,role:"member",invited_by:null,source:g}).onConflict().run()}async function P(a,g){let h=await S.select("role").where({app_id:{eq:a},user_id:{eq:g}}).run();return h.length?String(h[0].role):null}async function L(a){let g=await w.select("id").where({slug:{eq:a}}).run();return g.length?String(g[0].id):null}async function K(a){let g=await t.select("id","email","name","role","tenant").where({email:{eq:a}}).run();return g.length?g[0]:null}async function Ie(a){return(await e.query.from(`${Ze} m`).select("m.app_id","m.role","a.id","a.slug","a.name").join(`${Se} a`,{"a.id":{col:"m.app_id"}}).where({"m.user_id":{eq:a}}).run()).filter(h=>!String(h.slug).startsWith("_")).map(h=>({id:String(h.id),slug:String(h.slug),name:String(h.name),role:String(h.role)}))}async function C(a,g){let h=se({sub:a.id,...a.email?{email:a.email}:{},...a.name?{name:a.name}:{},...g?.appId?{appId:g.appId,role:g.role}:{},...!g?.appId&&a.tenant?{tenantId:a.tenant}:{}},j,De),d=je(),s=new Date(Date.now()+Ce*24*3600*1e3);return await y.insert({token_hash:ie(d),user_id:a.id,expires_at:s.toISOString(),...g?.appId?{app_id:g.appId}:{}}).run(),{token:h,refreshToken:d}}async function Le(a){let g=await y.update({revoked_at:new Date().toISOString()}).where({token_hash:{eq:ie(a)},revoked_at:{isNull:!0}}).returning("user_id","expires_at","app_id").run();if(!g.length)throw new l("Invalid refresh token",401);let h=g[0];if(new Date(String(h.expires_at))<new Date)throw new l("Refresh token expired",401);let d=await ue(h.user_id);if(!d)throw new l("User not found",401);return{user:d,appId:h.app_id?String(h.app_id):void 0}}let E=(async(a,g,h)=>{let d=null,s=null,p={},u,f,v,O=a.headers.get("authorization"),M=null;if(O?.startsWith("Bearer "))M=O.slice(7);else if(a.method==="GET"){let r=new URL(a.url??"","http://localhost"),o=r.searchParams.get("ticket");if(o){let m=ae(o,j);m?.type==="download"&&m?.sub&&(s=await ue(String(m.sub)),d=s,p.userId=String(m.sub),m.appId!=null&&(f=m.appId,p.appId=String(m.appId)))}else M=r.searchParams.get("token")}if(M&&!s){let r=ae(M,j);if(r?.sub){s=await ue(String(r.sub)),d=s;for(let[o,m]of Object.entries(r))o==="sub"||o==="iat"||o==="exp"||o==="type"||(p[o]=m);p.userId=String(r.sub),u=r.tenantId,f=r.appId,v=r.role}}g.user=s,f!=null&&(g.appId=String(f)),g.session=f!=null?{userId:String(s.id),appId:String(f),role:String(v??"")}:null,u!=null&&(g.tenantId=String(u));let W={...p,async register(r){if(!r.email||!r.password)throw new l("email and password are required",400);Te(r.password);let o=D(r.email),m=await J(r.password),c=await t.insert({email:o,password_hash:m,name:r.name??null,role:null,tenant:r.tenant??null}).run(),k=G(c[0]),b=await C(k);return await F(k.id,"register"),d=k,{...b,user:k}},async registerWithApp(r){let o=await this.register({email:r.email,password:r.password,name:r.name});await F(o.user.id,"register");let m=(r.appSlug??r.email.split("@")[1]??"default").trim().toLowerCase(),c=m;for(let _=1;_<=200&&await L(c);_++)c=`${m}-${_}`;let k=await this.createApp({slug:c,name:r.appName??`${r.name??"\u7528\u6237"} \u7684\u5E94\u7528`,openRegistration:!1}),b=await C(o.user,{appId:k.id,role:"owner"});return await $?.onRegisterApp?.(o.user.id,k),{...b,user:o.user,app:{...k,role:"owner"}}},async login(r,o){let c=(await t.select("id","email","password_hash","name","role","tenant").where({email:{eq:D(r)}}).run())[0];if(!c||c.password_hash==null)throw await Me(o),new l("Invalid email or password",401);if(!await re(o,String(c.password_hash)))throw new l("Invalid email or password",401);let b={id:String(c.id),email:String(c.email),name:c.name,role:c.role,tenant:c.tenant},_=await C(b),q=await Ie(b.id);return d=b,{..._,user:b,apps:q}},async logout(r){await y.update({revoked_at:new Date().toISOString()}).where({token_hash:{eq:ie(r)}}).run()},requireAuth(){if(!s)throw new l("Unauthorized",401);return s},async setPassword(r,o){Te(o);let m=await J(o);await t.update({password_hash:m}).where({id:{eq:r}}).run()},createToken(r,o,m){return se({type:r,...o},j,m.ttlSeconds)},async createApp(r){if(!d)throw new l("Unauthorized",401);if(!r.slug||!r.name)throw new l("slug and name are required",400);let o=r.slug.trim().toLowerCase();if(o.startsWith("_"))throw new l("slug \u4EE5 _ \u5F00\u5934\u4E3A\u7CFB\u7EDF\u4FDD\u7559\u540D",400);if(!await P(N,d.id))throw new l("\u4EC5\u5E94\u7528\u7BA1\u7406\u9762\uFF08_builtin\uFF09\u6210\u5458\u53EF\u521B\u5EFA\u5E94\u7528",403);let c=Pe(32).toString("hex"),b=(await w.insert({slug:o,name:r.name,owner_user_id:d.id,open_registration:r.openRegistration??!1,app_key:c}).run())[0];return await S.insert({app_id:b.id,user_id:d.id,role:"owner",invited_by:d.id}).run(),b},async registerInApp(r){if(!r.email||!r.password)throw new l("email and password are required",400);Te(r.password);let o=await w.select("id","open_registration").where({slug:{eq:r.appSlug}}).run();if(!o.length)throw new l("Application not found",404);let m=o[0],c=String(m.id),k=D(r.email),b="member";if(!m.open_registration){if(!r.inviteToken)throw new l("Registration closed for this application",403);let I=ae(r.inviteToken,j);if(!I||I.type!=="app-invite"||I.appId!==c)throw new l("Invalid invite",403);if(I.email&&String(I.email)!==k)throw new l("Invite email mismatch",403);typeof I.role=="string"&&I.role!=="owner"&&(ve(I.role),b=I.role)}let _=await K(k);if(!_){let I=await J(r.password),X=await t.insert({email:k,password_hash:I,name:r.name??null,role:null,tenant:null}).onConflict("email").run();if(_=X.length?G(X[0]):await K(k),!_)throw new l("User creation failed",500)}await F(_.id,"register"),await P(c,_.id)||await S.insert({app_id:c,user_id:_.id,role:b,invited_by:d?.id??null,source:"invite"}).onConflict().run();let V=await C(_,{appId:c,role:b});return await S.update({last_login_at:new Date().toISOString()}).where({app_id:{eq:c},user_id:{eq:_.id}}).run(),d=_,await $?.onJoinApp?.(_.id,c,b),{...V,user:_}},async loginApp(r,o,m){let c=await w.select("id").where({slug:{eq:r}}).run();if(!c.length)throw new l("Application not found",404);let k=String(c[0].id),_=(await t.select("id","email","password_hash","name","role","tenant").where({email:{eq:D(o)}}).run())[0];if(!_||_.password_hash==null)throw await Me(m),new l("Invalid email or password",401);if(!await re(m,String(_.password_hash)))throw new l("Invalid email or password",401);let V=await P(k,String(_.id));if(!V)throw new l("Not a member of this application",401);let I={id:String(_.id),email:String(_.email),name:_.name,role:_.role,tenant:_.tenant},X=await C(I,{appId:k,role:V});return await S.update({last_login_at:new Date().toISOString()}).where({app_id:{eq:k},user_id:{eq:I.id}}).run(),d=I,{...X,user:I,role:V}},async ssoLogin(r,o){let m=D(r),c=await K(m);if(!c){let _=await t.insert({email:m,password_hash:null,name:o?.name??null,role:null,tenant:null}).onConflict("email").run();if(c=_.length?G(_[0]):await K(m),!c)throw new l("User creation failed",500)}await F(c.id,"sso");let k;o?.appId&&(await P(o.appId,c.id)||await S.insert({app_id:o.appId,user_id:c.id,role:"member",invited_by:null,source:"sso"}).onConflict().run(),k=o.appId,await S.update({last_login_at:new Date().toISOString()}).where({app_id:{eq:o.appId},user_id:{eq:c.id}}).run());let b=await C(c,k?{appId:k,role:"member"}:void 0);return d=c,{...b,user:c}},async createInvite(r,o){if(r===N)throw new l("_builtin \u4E0D\u8D70\u9080\u8BF7\u6D41\uFF08\u4EFB\u547D\u5236\uFF09",403);if(o.role!==void 0&&!Re.includes(o.role))throw new l(`invite role not allowed: ${o.role}\uFF08allowed: ${Re.join("/")}\uFF09`,403);if(!d)throw new l("Unauthorized",401);if(await P(r,d.id)!=="owner")throw new l("Owner only",403);let c=o.role&&o.role!=="owner"?o.role:"member";return{inviteToken:se({type:"app-invite",appId:r,...o.email?{email:D(o.email)}:{},role:c},j,Be)}},async addMember(r,o,m){if(ve(m),r===N&&m!==void 0&&m==="viewer")throw new l("_builtin \u65E0\u53EA\u8BFB\uFF08viewer \u7981\u2014\u2014\u7BA1\u7406\u9762\u8EAB\u4EFD\uFF09",403);if(!d)throw new l("Unauthorized",401);if(await P(r,d.id)!=="owner")throw new l("Owner only",403);let k=await t.select("id").where({email:{eq:D(o)}}).run();if(!k.length)throw new l("User not found \u2014 invite them to register first",400);let b=m&&m!=="owner"?m:"member";await S.insert({app_id:r,user_id:String(k[0].id),role:b,invited_by:d.id}).run()},async setOpenRegistration(r,o){if(!d)throw new l("Unauthorized",401);if(r===N)throw new l("_builtin \u6CE8\u518C\u5F00\u5173\u6052 false",403);if(await P(r,d.id)!=="owner")throw new l("Owner only",403);await w.update({open_registration:o}).where({id:{eq:r}}).run()},async listMyApps(){if(!d)throw new l("Unauthorized",401);return Ie(d.id)},async requireApp(r){if(!d)throw new l("Unauthorized",401);let o=await P(r,d.id);if(!o)throw new l("Not a member of this application",403);return{userId:d.id,appId:r,role:o}}};return g.auth=W,h(a,g)});return E.__meta={injects:["user","auth"],depends:[]},E.seedBuiltinOwners=async a=>{let g={owner:null,admins:[]};for(let h of a){let d=D(h);if(!d)continue;let s=await K(d);if(!s){let u=await t.insert({email:d,password_hash:null,name:null,role:null,tenant:null}).onConflict("email").run();s=u.length?G(u[0]):await K(d)}if(!s)continue;let p=await S.select("role").where({app_id:{eq:N},user_id:{eq:s.id}}).run();if(p.length){String(p[0].role??"")==="owner"?g.owner=String(s.id):g.admins.push(String(s.id));continue}if(g.owner)await S.insert({app_id:N,user_id:String(s.id),role:"admin",invited_by:g.owner,source:"seed"}).run(),g.admins.push(String(s.id));else{await S.insert({app_id:N,user_id:String(s.id),role:"owner",invited_by:null,source:"seed"}).run(),g.owner=String(s.id);let u=await L("_default");u&&(await P(u,String(s.id))||await S.insert({app_id:u,user_id:String(s.id),role:"owner",invited_by:null,source:"seed"}).run())}}return g},E.migrate=async()=>{(await w.select("id").where({slug:{eq:"_builtin"}}).run()).length||await e.query.insert(Se).values({id:N,slug:"_builtin",name:"System",owner_user_id:null,open_registration:!1}).returning("id").run();let g=await w.select("id").where({app_key:{isNull:!0}}).run();for(let s of g)await w.update({app_key:Pe(32).toString("hex")}).where({id:{eq:String(s.id)}}).run();(await w.select("id").where({slug:{eq:"_default"}}).run()).length||await w.insert({slug:"_default",name:"Default",owner_user_id:null,open_registration:!1}).run();let d=await t.select("id").run();for(let s of d)await F(String(s.id),"migrate")},E.routes=(a,g)=>{let h=g?.prefix??Ee,d=new Set(g?.exclude??[]);if(d.has("register")||a.post(`${h}/register`,async(s,p)=>{let u=await s.json().catch(()=>({})),f=await p.auth.register(u);return B(f)}),d.has("register")||a.post(`${h}/register-app`,async(s,p)=>{let u=await s.json().catch(()=>({})),f=await p.auth.registerWithApp(u);return B(f)}),d.has("login")||a.post(`${h}/login`,async(s,p)=>{let u=await s.json().catch(()=>({}));if(!u.email||!u.password)return H("email and password are required");let f=await p.auth.login(u.email,u.password);return Z(f)}),d.has("logout")||a.post(`${h}/logout`,async(s,p)=>{let u=await s.json().catch(()=>({}));return u.refreshToken?(await p.auth.logout(u.refreshToken),$e()):H("refreshToken is required")}),d.has("refresh")||a.post(`${h}/refresh`,async(s,p)=>{let u=await s.json().catch(()=>({}));if(!u.refreshToken)throw new l("refreshToken is required",400);let{user:f,appId:v}=await Le(u.refreshToken),O;if(v){let W=await P(v,f.id);W&&(O={appId:v,role:W})}let M=await C(f,O);return Z({...M,user:f})}),d.has("me")||a.get(`${h}/me`,async(s,p)=>{if(!p.user)throw new l("Unauthorized",401);return Z({user:p.user,session:p.session??null})}),T){let s=`${h}/apps/_builtin/auth/sso`;a.get(`${s}/enabled`,async()=>Z({enabled:!0,appSlug:T.defaultAppSlug??null})),a.get(`${s}/login`,async p=>{let f=new URL(p.url??"","http://localhost").searchParams.get("app")??T.defaultAppSlug,v=new URLSearchParams({response_type:"code",client_id:T.clientId,redirect_uri:T.redirectBase?`${T.redirectBase.replace(/\/$/,"")}${s}/callback`:`${new URL(p.url,"http://localhost").origin}${s}/callback`,scope:T.scope??"openid email profile",state:f??"sso"});return new Response(null,{status:302,headers:{Location:`${T.issuer.replace(/\/$/,"")}/authorize?${v}`}})}),a.get(`${s}/callback`,async(p,u)=>{let f=new URL(p.url??"","http://localhost"),v=f.searchParams.get("code");if(!v)throw new l("SSO \u56DE\u8C03\u7F3A\u5C11 code",400);let O=T.redirectBase?`${T.redirectBase.replace(/\/$/,"")}${s}/callback`:`${f.origin}${s}/callback`,M=await fetch(`${T.issuer.replace(/\/$/,"")}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:v,redirect_uri:O,client_id:T.clientId,client_secret:T.clientSecret})});if(!M.ok)throw new l("SSO token \u4EA4\u6362\u5931\u8D25",401);let W=await M.json(),r=await fetch(`${T.issuer.replace(/\/$/,"")}/userinfo`,{headers:{Authorization:`Bearer ${W.access_token}`}});if(!r.ok)throw new l("SSO \u7528\u6237\u4FE1\u606F\u83B7\u53D6\u5931\u8D25",401);let o=await r.json(),m=(o.email??"").trim().toLowerCase();if(!m)throw new l("SSO \u672A\u8FD4\u56DE\u90AE\u7BB1\uFF08\u9700\u8981 email scope\uFF09",401);let c=f.searchParams.get("state"),k;if(c&&c!=="sso"){let q=await L(c);q&&(k=q)}let b=await u.auth.ssoLogin(m,{appId:k,name:o.name});await $?.onSsoLogin?.(b.user.id,k);let _={token:b.token,refreshToken:b.refreshToken,user:b.user};if(T.renderCallback){let q=T.renderCallback(_);return typeof q=="string"?new Response(q,{headers:{"Content-Type":"text/html; charset=utf-8"}}):q}return Z(_)})}d.has("apps")||(a.post(`${h}/apps`,async(s,p)=>{let u=await s.json().catch(()=>({})),f=await p.auth.createApp(u);return B({app:f})}),a.get(`${h}/apps`,async(s,p)=>{let u=await p.auth.listMyApps();return Z({apps:u})}),a.post(`${h}/apps/:appSlug/auth/members`,async(s,p)=>{let u=await s.json().catch(()=>({})),f=await L(p.params.appSlug);if(!f)throw new l("Application not found",404);return await p.auth.addMember(f,u.email??"",u.role),B({ok:!0})}),a.post(`${h}/apps/:appSlug/auth/invites`,async(s,p)=>{let u=await s.json().catch(()=>({})),f=await L(p.params.appSlug);if(!f)throw new l("Application not found",404);let v=await p.auth.createInvite(f,{email:u.email,role:u.role});return B(v)}),a.post(`${h}/apps/:appSlug/auth/login`,async(s,p)=>{let u=await s.json().catch(()=>({}));if(!u.email||!u.password)return H("email and password are required");let f=await p.auth.loginApp(p.params.appSlug,u.email,u.password);return Z(f)}),a.patch(`${h}/apps/:appSlug/auth/registration`,async(s,p)=>{let u=await s.json().catch(()=>({}));if(typeof u.open!="boolean")return H("open is required (boolean)");let f=await L(p.params.appSlug);if(!f)throw new l("Application not found",404);return await p.auth.setOpenRegistration(f,u.open),Z({open:u.open})}),a.post(`${h}/apps/:appSlug/auth/verify`,async(s,p)=>{let u=s.headers.get("x-wf-app-id"),f=s.headers.get("x-wf-app-key");if(!u||!f)return H("X-Wf-App-Id / X-Wf-App-Key required");let v=await w.select("id","slug","name").where({id:{eq:u},app_key:{eq:f}}).run();if(!v.length)throw new l("Invalid app credentials",403);let O=v[0];return Z({app:{id:String(O.id),slug:String(O.slug),name:String(O.name)}})}),a.post(`${h}/apps/:appSlug/auth/register`,async(s,p)=>{let u=await s.json().catch(()=>({})),f=await p.auth.registerInApp({appSlug:p.params.appSlug,email:u.email??"",password:u.password??"",name:u.name,inviteToken:u.inviteToken});return B(f)}))},E.asAppAuth=()=>E,E}var It={tables:[{name:"_weifuwu_users",columns:{id:x.pk(i.uuid()),email:x.req(i.string()).meta({unique:!0}),password_hash:i.string(),name:i.string(),role:i.string(),tenant:i.string(),email_verified:i.boolean().meta({default:!1}),created_at:i.date().meta({default:"now"})},dropNotNull:["password_hash"]},{name:"_weifuwu_sessions",columns:{token_hash:i.string().meta({pk:!0}),user_id:x.req(i.uuid()).meta({references:"_weifuwu_users",onDelete:"cascade"}),app_id:i.string(),expires_at:i.date().meta({notNull:!0}),revoked_at:i.date(),created_at:i.date().meta({default:"now"})}},{name:"_weifuwu_apps",columns:{id:x.pk(i.uuid()),slug:x.req(i.string()).meta({unique:!0}),name:x.req(i.string()),owner_user_id:i.uuid().meta({references:"_weifuwu_users",onDelete:"cascade"}),open_registration:i.boolean().meta({default:!1}),created_at:i.date().meta({default:"now"}),app_key:i.string()}},{name:"_weifuwu_app_members",columns:{app_id:x.req(i.uuid()).meta({references:"_weifuwu_apps",onDelete:"cascade"}),user_id:x.req(i.uuid()).meta({references:"_weifuwu_users",onDelete:"cascade"}),role:i.string().meta({default:"member"}),invited_by:i.uuid(),joined_at:i.date().meta({default:"now"}),source:i.string(),last_login_at:i.date()},uniques:[["app_id","user_id"]]}]};export{N as BUILTIN_APP_ID,oe as USER_TABLES,It as WEIFUWU_USER_SCHEMA,vt as userSystem};
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* 会话令牌(零依赖,node:crypto)
|
|
3
3
|
*
|
|
4
4
|
* access token:HMAC-SHA256 签名的 JWT 形态(base64url),
|
|
5
|
-
* 与 weifuwu/vdom 的 auth() 兼容(客户端解码 payload 检查 exp)。
|
|
5
|
+
* 与 weifuwu/client/vdom 的 auth() 兼容(客户端解码 payload 检查 exp)。
|
|
6
6
|
* refresh token:不透明随机串(256-bit),DB 只存 SHA-256 哈希(可撤销)。
|
|
7
7
|
*/
|
|
8
8
|
/** 签发 JWT access token(HS256) */
|