@djvlc/runtime-web 1.0.3 → 1.0.4
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/dist/error-reporter.d.ts +76 -0
- package/dist/error-reporter.d.ts.map +1 -0
- package/dist/index.d.ts +56 -94
- package/dist/index.d.ts.map +1 -1
- package/dist/mount.d.ts +114 -0
- package/dist/mount.d.ts.map +1 -0
- package/dist/performance.d.ts +88 -0
- package/dist/performance.d.ts.map +1 -0
- package/dist/runtime.css +440 -0
- package/dist/runtime.esm.js +5312 -1125
- package/dist/runtime.iife.js +1 -1
- package/dist/storage.d.ts +33 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/tracking.d.ts +87 -0
- package/dist/tracking.d.ts.map +1 -0
- package/dist/utils.d.ts +66 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/version.d.ts +5 -0
- package/dist/version.d.ts.map +1 -0
- package/package.json +2 -3
package/dist/runtime.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var DJVRuntime=function(e){"use strict";var t=(e=>(e[e.UNKNOWN=1e3]="UNKNOWN",e[e.INVALID_REQUEST=1001]="INVALID_REQUEST",e[e.UNAUTHORIZED=1002]="UNAUTHORIZED",e[e.FORBIDDEN=1003]="FORBIDDEN",e[e.NOT_FOUND=1004]="NOT_FOUND",e[e.RATE_LIMITED=1005]="RATE_LIMITED",e[e.VALIDATION_ERROR=1006]="VALIDATION_ERROR",e[e.INTERNAL_ERROR=1007]="INTERNAL_ERROR",e[e.SERVICE_UNAVAILABLE=1008]="SERVICE_UNAVAILABLE",e[e.TIMEOUT=1009]="TIMEOUT",e[e.ACTION_NOT_FOUND=2001]="ACTION_NOT_FOUND",e[e.ACTION_INVALID_PARAMS=2002]="ACTION_INVALID_PARAMS",e[e.ACTION_EXECUTION_FAILED=2003]="ACTION_EXECUTION_FAILED",e[e.ACTION_IDEMPOTENCY_CONFLICT=2004]="ACTION_IDEMPOTENCY_CONFLICT",e[e.ACTION_BLOCKED=2005]="ACTION_BLOCKED",e[e.ACTION_RISK_REJECTED=2006]="ACTION_RISK_REJECTED",e[e.ACTION_EXPIRED=2007]="ACTION_EXPIRED",e[e.ACTION_QUOTA_EXCEEDED=2008]="ACTION_QUOTA_EXCEEDED",e[e.QUERY_NOT_FOUND=3001]="QUERY_NOT_FOUND",e[e.QUERY_INVALID_PARAMS=3002]="QUERY_INVALID_PARAMS",e[e.QUERY_EXECUTION_FAILED=3003]="QUERY_EXECUTION_FAILED",e[e.QUERY_FIELD_NOT_ALLOWED=3004]="QUERY_FIELD_NOT_ALLOWED",e[e.QUERY_TIMEOUT=3005]="QUERY_TIMEOUT",e[e.QUERY_DISABLED=3006]="QUERY_DISABLED",e[e.COMPONENT_NOT_FOUND=4001]="COMPONENT_NOT_FOUND",e[e.COMPONENT_VERSION_NOT_FOUND=4002]="COMPONENT_VERSION_NOT_FOUND",e[e.COMPONENT_BLOCKED=4003]="COMPONENT_BLOCKED",e[e.COMPONENT_INTEGRITY_MISMATCH=4004]="COMPONENT_INTEGRITY_MISMATCH",e[e.COMPONENT_INCOMPATIBLE=4005]="COMPONENT_INCOMPATIBLE",e[e.COMPONENT_LOAD_FAILED=4006]="COMPONENT_LOAD_FAILED",e[e.COMPONENT_RENDER_ERROR=4007]="COMPONENT_RENDER_ERROR",e[e.PAGE_NOT_FOUND=5001]="PAGE_NOT_FOUND",e[e.PAGE_VERSION_NOT_FOUND=5002]="PAGE_VERSION_NOT_FOUND",e[e.PAGE_SCHEMA_INVALID=5003]="PAGE_SCHEMA_INVALID",e[e.PAGE_MANIFEST_INVALID=5004]="PAGE_MANIFEST_INVALID",e[e.PAGE_PUBLISH_FAILED=5005]="PAGE_PUBLISH_FAILED",e[e.PAGE_ROLLBACK_FAILED=5006]="PAGE_ROLLBACK_FAILED",e[e.ACTIVITY_NOT_FOUND=6001]="ACTIVITY_NOT_FOUND",e[e.ACTIVITY_NOT_STARTED=6002]="ACTIVITY_NOT_STARTED",e[e.ACTIVITY_ENDED=6003]="ACTIVITY_ENDED",e[e.ACTIVITY_ALREADY_CLAIMED=6004]="ACTIVITY_ALREADY_CLAIMED",e[e.ACTIVITY_ALREADY_SIGNED=6005]="ACTIVITY_ALREADY_SIGNED",e[e.ACTIVITY_LIMIT_EXCEEDED=6006]="ACTIVITY_LIMIT_EXCEEDED",e[e.ACTIVITY_DISABLED=6007]="ACTIVITY_DISABLED",e[e.EXPRESSION_SYNTAX_ERROR=7001]="EXPRESSION_SYNTAX_ERROR",e[e.EXPRESSION_UNKNOWN_FUNCTION=7002]="EXPRESSION_UNKNOWN_FUNCTION",e[e.EXPRESSION_INVALID_ARGUMENT=7003]="EXPRESSION_INVALID_ARGUMENT",e[e.EXPRESSION_UNKNOWN_VARIABLE=7004]="EXPRESSION_UNKNOWN_VARIABLE",e[e.EXPRESSION_TYPE_MISMATCH=7005]="EXPRESSION_TYPE_MISMATCH",e[e.EXPRESSION_ACCESS_DENIED=7006]="EXPRESSION_ACCESS_DENIED",e[e.SCHEMA_VERSION_MISMATCH=8001]="SCHEMA_VERSION_MISMATCH",e[e.MIGRATION_FAILED=8002]="MIGRATION_FAILED",e[e.MIGRATION_NOT_FOUND=8003]="MIGRATION_NOT_FOUND",e[e.VERSION_INCOMPATIBLE=8004]="VERSION_INCOMPATIBLE",e))(t||{}),r={1e3:"未知错误",1001:"请求参数无效",1002:"未授权访问",1003:"禁止访问",1004:"资源不存在",1005:"请求频率超限",1006:"数据校验失败",1007:"服务内部错误",1008:"服务暂不可用",1009:"请求超时",2001:"动作不存在",2002:"动作参数无效",2003:"动作执行失败",2004:"重复请求",2005:"动作已被禁用",2006:"风控拒绝",2007:"动作已过期",2008:"配额已用尽",3001:"查询不存在",3002:"查询参数无效",3003:"查询执行失败",3004:"字段访问被拒绝",3005:"查询超时",3006:"查询已禁用",4001:"组件不存在",4002:"组件版本不存在",4003:"组件已被禁用",4004:"组件完整性校验失败",4005:"组件版本不兼容",4006:"组件加载失败",4007:"组件渲染错误",5001:"页面不存在",5002:"页面版本不存在",5003:"页面 Schema 无效",5004:"页面 Manifest 无效",5005:"页面发布失败",5006:"页面回滚失败",6001:"活动不存在",6002:"活动未开始",6003:"活动已结束",6004:"已领取过",6005:"今日已签到",6006:"超出领取限制",6007:"活动已禁用",7001:"表达式语法错误",7002:"未知函数",7003:"无效参数",7004:"未知变量",7005:"类型不匹配",7006:"访问被拒绝",8001:"Schema 版本不匹配",8002:"迁移失败",8003:"迁移脚本不存在",8004:"版本不兼容"},s=new Set([{name:"len",description:"获取字符串或数组长度",params:[{name:"value",type:"any",required:!0}],returnType:"number",examples:['len("hello")',"len([1,2,3])"]},{name:"trim",description:"去除字符串首尾空格",params:[{name:"str",type:"string",required:!0}],returnType:"string",examples:['trim(" hello ")']},{name:"upper",description:"转为大写",params:[{name:"str",type:"string",required:!0}],returnType:"string",examples:['upper("hello")']},{name:"lower",description:"转为小写",params:[{name:"str",type:"string",required:!0}],returnType:"string",examples:['lower("HELLO")']},{name:"substr",description:"截取子字符串",params:[{name:"str",type:"string",required:!0},{name:"start",type:"number",required:!0},{name:"length",type:"number",required:!1}],returnType:"string",examples:['substr("hello", 0, 2)']},{name:"concat",description:"连接字符串",params:[{name:"values",type:"any",required:!0,description:"可变参数"}],returnType:"string",examples:['concat("a", "b", "c")']},{name:"replace",description:"替换字符串",params:[{name:"str",type:"string",required:!0},{name:"search",type:"string",required:!0},{name:"replacement",type:"string",required:!0}],returnType:"string",examples:['replace("hello", "l", "x")']},{name:"split",description:"分割字符串",params:[{name:"str",type:"string",required:!0},{name:"separator",type:"string",required:!0}],returnType:"array",examples:['split("a,b,c", ",")']},{name:"join",description:"连接数组为字符串",params:[{name:"arr",type:"array",required:!0},{name:"separator",type:"string",required:!1,defaultValue:","}],returnType:"string",examples:['join(["a","b","c"], "-")']},{name:"toNumber",description:"转为数字",params:[{name:"value",type:"any",required:!0}],returnType:"number",examples:['toNumber("123")']},{name:"toString",description:"转为字符串",params:[{name:"value",type:"any",required:!0}],returnType:"string",examples:["toString(123)"]},{name:"round",description:"四舍五入",params:[{name:"value",type:"number",required:!0},{name:"decimals",type:"number",required:!1,defaultValue:0}],returnType:"number",examples:["round(3.14159, 2)"]},{name:"floor",description:"向下取整",params:[{name:"value",type:"number",required:!0}],returnType:"number",examples:["floor(3.7)"]},{name:"ceil",description:"向上取整",params:[{name:"value",type:"number",required:!0}],returnType:"number",examples:["ceil(3.2)"]},{name:"abs",description:"绝对值",params:[{name:"value",type:"number",required:!0}],returnType:"number",examples:["abs(-5)"]},{name:"min",description:"最小值",params:[{name:"values",type:"number",required:!0,description:"可变参数"}],returnType:"number",examples:["min(1, 2, 3)"]},{name:"max",description:"最大值",params:[{name:"values",type:"number",required:!0,description:"可变参数"}],returnType:"number",examples:["max(1, 2, 3)"]},{name:"now",description:"当前时间戳(毫秒)",params:[],returnType:"number",examples:["now()"]},{name:"dateFormat",description:"格式化日期",params:[{name:"timestamp",type:"number",required:!0},{name:"format",type:"string",required:!1,defaultValue:"YYYY-MM-DD"}],returnType:"string",examples:['dateFormat(now(), "YYYY-MM-DD HH:mm:ss")']},{name:"dateParse",description:"解析日期字符串",params:[{name:"dateStr",type:"string",required:!0},{name:"format",type:"string",required:!1}],returnType:"number",examples:['dateParse("2024-01-01")']},{name:"first",description:"获取数组第一个元素",params:[{name:"arr",type:"array",required:!0}],returnType:"any",examples:["first([1,2,3])"]},{name:"last",description:"获取数组最后一个元素",params:[{name:"arr",type:"array",required:!0}],returnType:"any",examples:["last([1,2,3])"]},{name:"includes",description:"检查数组是否包含元素",params:[{name:"arr",type:"array",required:!0},{name:"value",type:"any",required:!0}],returnType:"boolean",examples:["includes([1,2,3], 2)"]},{name:"slice",description:"截取数组",params:[{name:"arr",type:"array",required:!0},{name:"start",type:"number",required:!0},{name:"end",type:"number",required:!1}],returnType:"array",examples:["slice([1,2,3,4], 1, 3)"]},{name:"default",description:"提供默认值",params:[{name:"value",type:"any",required:!0},{name:"defaultValue",type:"any",required:!0}],returnType:"any",examples:['default(null, "fallback")']},{name:"ifElse",description:"条件判断",params:[{name:"condition",type:"boolean",required:!0},{name:"trueValue",type:"any",required:!0},{name:"falseValue",type:"any",required:!0}],returnType:"any",examples:['ifElse(age > 18, "成年", "未成年")']},{name:"isEmpty",description:"检查是否为空",params:[{name:"value",type:"any",required:!0}],returnType:"boolean",examples:['isEmpty("")',"isEmpty([])"]},{name:"isNull",description:"检查是否为 null 或 undefined",params:[{name:"value",type:"any",required:!0}],returnType:"boolean",examples:["isNull(null)"]},{name:"jsonParse",description:"解析 JSON 字符串",params:[{name:"str",type:"string",required:!0}],returnType:"any",examples:["jsonParse('{\"a\":1}')"]},{name:"jsonStringify",description:"序列化为 JSON",params:[{name:"value",type:"any",required:!0}],returnType:"string",examples:["jsonStringify({a:1})"]}].map(e=>e.name));function n(e){return null!==e&&"object"==typeof e&&!0===e.__isExpression&&"string"==typeof e.expression}var o=[];function a(e){if(o.some(t=>t.from===e.from&&t.to===e.to))throw new Error(`Migration from ${e.from} to ${e.to} already exists`);o.push(e)}a({from:"1.0.0",to:"1.1.0",description:"添加 Definition 版本绑定字段",migrate:e=>({...e,actionDefVersionIds:e.actionDefVersionIds||[],dataQueryVersionIds:e.dataQueryVersionIds||[]})}),a({from:"1.1.0",to:"2.0.0",description:"重构组件事件结构",breaking:!0,migrate:e=>({...e,components:e.components.map(e=>{var t;return{...e,events:null==(t=e.events)?void 0:t.map(e=>({...e,enabled:e.enabled??!0}))}})})});var i=class extends Error{constructor(e,t,s,n){super(t||r[e]||"Unknown error"),this.name="DjvlcRuntimeError",this.code=e,this.details=s,this.traceId=n,this.timestamp=Date.now()}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,traceId:this.traceId,timestamp:this.timestamp}}},c=class extends i{constructor(e,r,s){super(t.PAGE_NOT_FOUND,e,r,s),this.name="PageLoadError"}},l=class extends i{constructor(e,r,s,n=t.COMPONENT_NOT_FOUND,o){super(n,s,{...o,componentName:e,componentVersion:r}),this.name="ComponentLoadError",this.componentName=e,this.componentVersion=r}},p=class extends i{constructor(e,r,s,n){super(t.COMPONENT_INTEGRITY_MISMATCH,`Integrity check failed for ${e}@${r}`,{expectedHash:s,actualHash:n}),this.name="IntegrityError",this.componentName=e,this.componentVersion=r,this.expectedHash=s,this.actualHash=n}},d=class extends i{constructor(e,r,s){super(t.COMPONENT_BLOCKED,`Component ${e}@${r} is blocked`,{componentName:e,componentVersion:r,reason:s}),this.name="ComponentBlockedError",this.componentName=e,this.componentVersion=r,this.reason=s}},h=class extends i{constructor(e,r,s,n){super(t.UNKNOWN,r,{...n,expression:e,position:s}),this.name="ExpressionError",this.expression=e,this.position=s}},u=class{constructor(e){this.cache=new Map,this.options={channel:"prod",cache:{enabled:!0,maxAge:300},...e}}async resolve(e,t){var r,s;const n=this.getCacheKey(e,t);if(null==(r=this.options.cache)?void 0:r.enabled){const t=this.cache.get(n);if(t&&this.isCacheValid(t.timestamp))return this.log("debug",`Page ${e} loaded from cache`),t.data}const o=performance.now();try{const r=this.buildResolveUrl(e,t),a=await fetch(r,{method:"GET",headers:this.buildHeaders()});if(!a.ok)throw new c(`Failed to resolve page: ${a.status} ${a.statusText}`,{pageUid:e,status:a.status});const i=await a.json();if(!this.isValidPageResolveResult(i))throw new c("Invalid page resolve response",{pageUid:e});const l=i.data;(null==(s=this.options.cache)?void 0:s.enabled)&&this.cache.set(n,{data:l,timestamp:Date.now()});const p=performance.now()-o;return this.log("info",`Page ${e} resolved in ${p.toFixed(2)}ms`),l}catch(a){if(a instanceof c)throw a;throw new c(`Failed to resolve page: ${a instanceof Error?a.message:"Unknown error"}`,{pageUid:e})}}preconnect(){const e=document.createElement("link");e.rel="preconnect",e.href=this.options.apiBaseUrl,document.head.appendChild(e)}clearCache(e){if(e)for(const t of this.cache.keys())t.startsWith(e)&&this.cache.delete(t);else this.cache.clear()}buildResolveUrl(e,t){const r=new URL(`${this.options.apiBaseUrl}/page/resolve`);return r.searchParams.set("pageUid",e),this.options.channel&&r.searchParams.set("channel",this.options.channel),this.options.previewToken&&r.searchParams.set("previewToken",this.options.previewToken),(null==t?void 0:t.uid)&&r.searchParams.set("uid",t.uid),(null==t?void 0:t.deviceId)&&r.searchParams.set("deviceId",t.deviceId),r.toString()}buildHeaders(){const e={"Content-Type":"application/json",...this.options.headers};return this.options.authToken&&(e.Authorization=`Bearer ${this.options.authToken}`),e}getCacheKey(e,t){const r=[e,this.options.channel];return(null==t?void 0:t.uid)&&r.push(t.uid),(null==t?void 0:t.deviceId)&&r.push(t.deviceId),r.join(":")}isCacheValid(e){var t;const r=1e3*((null==(t=this.options.cache)?void 0:t.maxAge)??300);return Date.now()-e<r}isValidPageResolveResult(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.data||"object"!=typeof t.data)return!1;const r=t.data;return"string"==typeof r.pageUid&&"string"==typeof r.pageVersionId&&void 0!==r.pageJson&&void 0!==r.manifest}log(e,t){this.options.logger&&this.options.logger[e](t)}},m=class{constructor(e){this.loadedComponents=new Map,this.loadingPromises=new Map,this.options={enableSRI:!0,concurrency:4,timeout:3e4,blockedComponents:[],...e},this.blockedSet=new Set(this.options.blockedComponents)}async load(e){const t=this.getComponentKey(e.name,e.version);if(this.isBlocked(e.name,e.version))throw new d(e.name,e.version,"Component is blocked");const r=this.loadedComponents.get(t);if(r)return r;const s=this.loadingPromises.get(t);if(s)return s;const n=this.loadComponent(e);this.loadingPromises.set(t,n);try{const e=await n;return this.loadedComponents.set(t,e),e}finally{this.loadingPromises.delete(t)}}async loadAll(e){const t=new Map,{concurrency:r=4}=this.options,s=e.components;for(let n=0;n<s.length;n+=r){const e=s.slice(n,n+r).map(async e=>{const r=this.getComponentKey(e.name,e.version),s=performance.now();try{const n=await this.load(e);t.set(r,{name:e.name,version:e.version,status:"loaded",component:n.Component,loadTime:performance.now()-s})}catch(n){const o=n instanceof d?"blocked":"failed";if(t.set(r,{name:e.name,version:e.version,status:o,error:n instanceof Error?n.message:"Unknown error",loadTime:performance.now()-s}),e.critical)throw n}});await Promise.all(e)}return t}preload(e){e.forEach(e=>{const t=document.createElement("link");t.rel="preload",t.as="script",t.href=this.resolveUrl(e.entryUrl),this.options.enableSRI&&e.integrity&&(t.integrity=e.integrity,t.crossOrigin="anonymous"),document.head.appendChild(t)})}isLoaded(e,t){return this.loadedComponents.has(this.getComponentKey(e,t))}get(e,t){return this.loadedComponents.get(this.getComponentKey(e,t))}isBlocked(e,t){return this.blockedSet.has(`${e}@${t}`)||this.blockedSet.has(e)}updateBlockedList(e){this.blockedSet=new Set(e)}async loadComponent(e){const t=performance.now(),r=this.resolveUrl(e.entryUrl);this.log("debug",`Loading component ${e.name}@${e.version}`);try{const s=await this.fetchWithTimeout(r);if(!s.ok)throw new l(e.name,e.version,`Failed to fetch component: ${s.status} ${s.statusText}`);const n=await s.text();this.options.enableSRI&&e.integrity&&await this.validateIntegrity(e,n);const o=await this.executeScript(n,e),a=performance.now()-t;return this.log("info",`Component ${e.name}@${e.version} loaded in ${a.toFixed(2)}ms`),{name:e.name,version:e.version,Component:o,loadTime:a}}catch(s){if(s instanceof l||s instanceof p||s instanceof d)throw s;throw new l(e.name,e.version,`Failed to load component: ${s instanceof Error?s.message:"Unknown error"}`)}}async fetchWithTimeout(e){const t=new AbortController,r=setTimeout(()=>t.abort(),this.options.timeout);try{return await fetch(e,{signal:t.signal,credentials:"omit"})}finally{clearTimeout(r)}}async validateIntegrity(e,t){if(!e.integrity)return;const[r,s]=e.integrity.split("-");if(!r||!s)throw new p(e.name,e.version,e.integrity,"Invalid format");const n=await crypto.subtle.digest(r.toUpperCase(),(new TextEncoder).encode(t)),o=Array.from(new Uint8Array(n)),a=btoa(String.fromCharCode(...o));if(a!==s)throw new p(e.name,e.version,s,a)}async executeScript(e,t){const r=new Blob([e],{type:"application/javascript"}),s=URL.createObjectURL(r);try{const e=await import(s),r=e.default||e[t.name]||e.Component;if(!r)throw new l(t.name,t.version,"Component module does not export a valid component");return r}finally{URL.revokeObjectURL(s)}}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")?e:`${this.options.cdnBaseUrl}/${e.replace(/^\//,"")}`}getComponentKey(e,t){return`${e}@${t}`}log(e,t){this.options.logger&&this.options.logger[e](t)}},g=class{constructor(e){this.preconnectedHosts=new Set,this.preloadedAssets=new Set,this.options=e}preconnectAll(){[...this.options.cdnHosts,...this.options.apiHosts].forEach(e=>this.preconnect(e))}preconnect(e){if(this.preconnectedHosts.has(e))return;const t=document.createElement("link");t.rel="preconnect",t.href=e.startsWith("http")?e:`https://${e}`,t.crossOrigin="anonymous",document.head.appendChild(t),this.preconnectedHosts.add(e)}dnsPrefetch(e){const t=document.createElement("link");t.rel="dns-prefetch",t.href=e.startsWith("http")?e:`https://${e}`,document.head.appendChild(t)}preloadScript(e,t){if(this.preloadedAssets.has(e))return;const r=document.createElement("link");r.rel="preload",r.as="script",r.href=e,t&&(r.integrity=t,r.crossOrigin="anonymous"),document.head.appendChild(r),this.preloadedAssets.add(e)}preloadStyle(e,t){if(this.preloadedAssets.has(e))return;const r=document.createElement("link");r.rel="preload",r.as="style",r.href=e,t&&(r.integrity=t,r.crossOrigin="anonymous"),document.head.appendChild(r),this.preloadedAssets.add(e)}preloadImage(e){if(this.preloadedAssets.has(e))return;const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t),this.preloadedAssets.add(e)}prefetch(e,t){const r=document.createElement("link");r.rel="prefetch",r.href=e,t&&(r.as=t),document.head.appendChild(r)}loadStylesheet(e,t){return new Promise((r,s)=>{const n=document.createElement("link");n.rel="stylesheet",n.href=e,t&&(n.integrity=t,n.crossOrigin="anonymous"),n.onload=()=>r(),n.onerror=()=>s(new Error(`Failed to load stylesheet: ${e}`)),document.head.appendChild(n)})}loadScript(e,t){return new Promise((r,s)=>{const n=document.createElement("script");n.src=e,n.async=!0,t&&(n.integrity=t,n.crossOrigin="anonymous"),n.onload=()=>r(),n.onerror=()=>s(new Error(`Failed to load script: ${e}`)),document.body.appendChild(n)})}},y=class{constructor(){this.listeners=new Set,this.state=this.createInitialState()}getState(){return this.state}getPhase(){return this.state.phase}setPhase(e){this.setState({phase:e})}setPage(e){this.setState({page:e,variables:e.pageJson.page.variables||{}})}setError(e){this.setState({phase:"error",error:e})}getVariable(e){return this.state.variables[e]}setVariable(e,t){this.setState({variables:{...this.state.variables,[e]:t}})}setVariables(e){this.setState({variables:{...this.state.variables,...e}})}getQuery(e){return this.state.queries[e]}setQuery(e,t){this.setState({queries:{...this.state.queries,[e]:t}})}setComponentStatus(e,t){const r=new Map(this.state.components);r.set(e,t),this.setState({components:r})}setDestroyed(){this.setState({destroyed:!0})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}reset(){this.state=this.createInitialState(),this.notifyListeners()}setState(e){this.state={...this.state,...e},this.notifyListeners()}notifyListeners(){this.listeners.forEach(e=>{try{e(this.state)}catch(t){}})}createInitialState(){return{phase:"idle",page:null,variables:{},queries:{},components:new Map,error:null,destroyed:!1}}},f=class{constructor(e={}){this.handlers=new Map,this.options={debug:!1,maxListeners:100,...e}}emit(e){this.options.debug&&this.log("debug",`Event emitted: ${e.type}`,e);const t=this.handlers.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(r){this.log("error",`Error in event handler for ${e.type}:`,r)}})}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.size>=(this.options.maxListeners??100)&&this.log("warn",`Max listeners (${this.options.maxListeners}) reached for event: ${e}`),r.add(t),()=>{null==r||r.delete(t),0===(null==r?void 0:r.size)&&this.handlers.delete(e)}}off(e,t){const r=this.handlers.get(e);r&&(r.delete(t),0===r.size&&this.handlers.delete(e))}once(e,t){const r=this.on(e,e=>{r(),t(e)});return r}clear(e){e?this.handlers.delete(e):this.handlers.clear()}listenerCount(e){var t;return(null==(t=this.handlers.get(e))?void 0:t.size)??0}static createEvent(e,t,r){return{type:e,data:t,timestamp:Date.now(),traceId:r}}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},E=class{constructor(e){this.pos=0,this.tokens=[],this.input=e}tokenize(){for(this.pos=0,this.tokens=[];this.pos<this.input.length&&(this.skipWhitespace(),!(this.pos>=this.input.length));){const e=this.readToken();e&&this.tokens.push(e)}return this.tokens.push({type:"EOF",value:null,start:this.input.length,end:this.input.length}),this.tokens}readToken(){const e=this.input[this.pos],t=this.pos;if(this.isDigit(e)||"-"===e&&this.isDigit(this.peek(1)))return this.readNumber();if('"'===e||"'"===e)return this.readString(e);if(this.isIdentifierStart(e))return this.readIdentifier();const r=this.readOperator();if(r)return r;switch(e){case".":return this.pos++,{type:"DOT",value:".",start:t,end:this.pos};case"[":return this.pos++,{type:"LBRACKET",value:"[",start:t,end:this.pos};case"]":return this.pos++,{type:"RBRACKET",value:"]",start:t,end:this.pos};case"(":return this.pos++,{type:"LPAREN",value:"(",start:t,end:this.pos};case")":return this.pos++,{type:"RPAREN",value:")",start:t,end:this.pos};case",":return this.pos++,{type:"COMMA",value:",",start:t,end:this.pos};case"?":return this.pos++,{type:"QUESTION",value:"?",start:t,end:this.pos};case":":return this.pos++,{type:"COLON",value:":",start:t,end:this.pos}}throw new Error(`Unexpected character '${e}' at position ${this.pos}`)}readNumber(){const e=this.pos;let t="";for("-"===this.input[this.pos]&&(t+="-",this.pos++);this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;if("."===this.input[this.pos]&&this.isDigit(this.peek(1)))for(t+=".",this.pos++;this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return{type:"NUMBER",value:parseFloat(t),start:e,end:this.pos}}readString(e){const t=this.pos;this.pos++;let r="";for(;this.pos<this.input.length&&this.input[this.pos]!==e;){if("\\"===this.input[this.pos]){this.pos++;const e=this.input[this.pos];switch(e){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case'"':r+='"';break;case"'":r+="'";break;default:r+=e}}else r+=this.input[this.pos];this.pos++}if(this.input[this.pos]!==e)throw new Error(`Unterminated string at position ${t}`);return this.pos++,{type:"STRING",value:r,start:t,end:this.pos}}readIdentifier(){const e=this.pos;let t="";for(;this.pos<this.input.length&&this.isIdentifierChar(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return"true"===t?{type:"BOOLEAN",value:!0,start:e,end:this.pos}:"false"===t?{type:"BOOLEAN",value:!1,start:e,end:this.pos}:"null"===t?{type:"NULL",value:null,start:e,end:this.pos}:{type:"IDENTIFIER",value:t,start:e,end:this.pos}}readOperator(){const e=this.pos,t=this.input.slice(this.pos,this.pos+2),r=this.input[this.pos];if(["==","!=",">=","<=","&&","||","??"].includes(t))return this.pos+=2,{type:"OPERATOR",value:t,start:e,end:this.pos};return["+","-","*","/","%",">","<","!"].includes(r)?(this.pos++,{type:"OPERATOR",value:r,start:e,end:this.pos}):null}skipWhitespace(){for(;this.pos<this.input.length&&/\s/.test(this.input[this.pos]);)this.pos++}isDigit(e){return/[0-9]/.test(e)}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierChar(e){return/[a-zA-Z0-9_$]/.test(e)}peek(e=1){return this.input[this.pos+e]||""}},v={"||":1,"??":1,"&&":2,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},b=class{constructor(e){this.pos=0,this.tokens=e}parse(){const e=this.parseExpression();if("EOF"!==this.current().type)throw new Error(`Unexpected token '${this.current().value}' at position ${this.current().start}`);return e}parseExpression(){return this.parseTernary()}parseTernary(){const e=this.parseBinary(0);if("QUESTION"===this.current().type){this.advance();const t=this.parseExpression();this.expect("COLON");return{type:"conditional",test:e,consequent:t,alternate:this.parseExpression(),raw:void 0}}return e}parseBinary(e){let t=this.parseUnary();for(;;){const r=this.current();if("OPERATOR"!==r.type)break;const s=v[r.value];if(void 0===s||s<e)break;this.advance();const n=this.parseBinary(s+1);t={type:"binary",operator:r.value,left:t,right:n,raw:void 0}}return t}parseUnary(){const e=this.current();if("OPERATOR"===e.type&&("!"===e.value||"-"===e.value)){this.advance();const t=this.parseUnary();return{type:"unary",operator:e.value,argument:t,raw:void 0}}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;){const t=this.current();if("DOT"===t.type){this.advance();e={type:"member",object:e,property:this.expect("IDENTIFIER").value,computed:!1,raw:void 0}}else if("LBRACKET"===t.type){this.advance();const t=this.parseExpression();this.expect("RBRACKET"),e={type:"member",object:e,property:t,computed:!0,raw:void 0}}else{if("LPAREN"!==t.type||"identifier"!==e.type)break;{const r=e.name;if(!s.has(r))throw new Error(`Unknown function '${r}' at position ${t.start}`);this.advance();const n=this.parseArguments();this.expect("RPAREN"),e={type:"call",callee:r,arguments:n,raw:void 0}}}}return e}parsePrimary(){const e=this.current();if("NUMBER"===e.type||"STRING"===e.type||"BOOLEAN"===e.type||"NULL"===e.type)return this.advance(),{type:"literal",value:e.value,start:e.start,end:e.end,raw:void 0};if("IDENTIFIER"===e.type)return this.advance(),{type:"identifier",name:e.value,start:e.start,end:e.end,raw:void 0};if("LBRACKET"===e.type)return this.parseArray();if("LPAREN"===e.type){this.advance();const e=this.parseExpression();return this.expect("RPAREN"),e}throw new Error(`Unexpected token '${e.value}' at position ${e.start}`)}parseArray(){const e=this.current().start;this.advance();const t=[];for(;"RBRACKET"!==this.current().type&&(t.push(this.parseExpression()),"COMMA"===this.current().type);)this.advance();const r=this.current().end;return this.expect("RBRACKET"),{type:"array",elements:t,start:e,end:r,raw:void 0}}parseArguments(){const e=[];if("RPAREN"!==this.current().type)for(e.push(this.parseExpression());"COMMA"===this.current().type;)this.advance(),e.push(this.parseExpression());return e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(e){const t=this.current();if(t.type!==e)throw new Error(`Expected '${e}' but got '${t.type}' at position ${t.start}`);return this.advance()}},I={len:e=>"string"==typeof e||Array.isArray(e)?e.length:0,trim:e=>String(e??"").trim(),upper:e=>String(e??"").toUpperCase(),lower:e=>String(e??"").toLowerCase(),substr:(e,t,r)=>{const s=String(e??""),n=Number(t)||0,o=void 0!==r?Number(r):void 0;return s.substring(n,void 0!==o?n+o:void 0)},concat:(...e)=>e.map(e=>String(e??"")).join(""),replace:(e,t,r)=>String(e??"").split(String(t)).join(String(r)),split:(e,t)=>String(e??"").split(String(t)),join:(e,t)=>Array.isArray(e)?e.join(void 0!==t?String(t):","):"",startsWith:(e,t)=>String(e??"").startsWith(String(t)),endsWith:(e,t)=>String(e??"").endsWith(String(t)),contains:(e,t)=>String(e??"").includes(String(t)),toNumber:e=>{const t=Number(e);return isNaN(t)?0:t},toString:e=>String(e??""),toInt:e=>Math.trunc(Number(e)||0),toFloat:e=>parseFloat(String(e))||0,round:(e,t)=>{const r=Number(e)||0,s=Number(t)||0,n=Math.pow(10,s);return Math.round(r*n)/n},floor:e=>Math.floor(Number(e)||0),ceil:e=>Math.ceil(Number(e)||0),abs:e=>Math.abs(Number(e)||0),min:(...e)=>{const t=e.map(e=>Number(e)).filter(e=>!isNaN(e));return t.length>0?Math.min(...t):0},max:(...e)=>{const t=e.map(e=>Number(e)).filter(e=>!isNaN(e));return t.length>0?Math.max(...t):0},sum:e=>Array.isArray(e)?e.reduce((e,t)=>e+(Number(t)||0),0):0,avg:e=>{if(!Array.isArray(e)||0===e.length)return 0;return e.reduce((e,t)=>e+(Number(t)||0),0)/e.length},random:()=>Math.random(),randomInt:(e,t)=>{const r=Math.ceil(Number(e)||0),s=Math.floor(Number(t)||100);return Math.floor(Math.random()*(s-r+1))+r},now:()=>Date.now(),today:()=>(new Date).toISOString().split("T")[0],dateFormat:(e,t)=>{const r=new Date(Number(e)||Date.now()),s=e=>e.toString().padStart(2,"0");return String(t||"YYYY-MM-DD").replace("YYYY",r.getFullYear().toString()).replace("MM",s(r.getMonth()+1)).replace("DD",s(r.getDate())).replace("HH",s(r.getHours())).replace("mm",s(r.getMinutes())).replace("ss",s(r.getSeconds()))},dateParse:e=>new Date(String(e)).getTime(),year:e=>new Date(Number(e)||Date.now()).getFullYear(),month:e=>new Date(Number(e)||Date.now()).getMonth()+1,day:e=>new Date(Number(e)||Date.now()).getDate(),addDays:(e,t)=>{const r=new Date(Number(e)||Date.now());return r.setDate(r.getDate()+(Number(t)||0)),r.getTime()},diffDays:(e,t)=>{const r=new Date(Number(e)||Date.now()),s=new Date(Number(t)||Date.now()),n=Math.abs(s.getTime()-r.getTime());return Math.floor(n/864e5)},isNull:e=>null==e,isUndefined:e=>void 0===e,isEmpty:e=>null==e||("string"==typeof e||Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length),isArray:e=>Array.isArray(e),isObject:e=>null!==e&&"object"==typeof e&&!Array.isArray(e),isString:e=>"string"==typeof e,isNumber:e=>"number"==typeof e&&!isNaN(e),isBoolean:e=>"boolean"==typeof e,typeOf:e=>null===e?"null":Array.isArray(e)?"array":typeof e,default:(e,t)=>e??t,coalesce:(...e)=>{for(const t of e)if(null!=t)return t;return null},ifElse:(e,t,r)=>e?t:r,first:e=>{if(Array.isArray(e))return e[0]},last:e=>{if(Array.isArray(e))return e[e.length-1]},at:(e,t)=>{if(Array.isArray(e))return e[Number(t)||0]},slice:(e,t,r)=>Array.isArray(e)?e.slice(Number(t)||0,void 0!==r?Number(r):void 0):[],includes:(e,t)=>!!Array.isArray(e)&&e.includes(t),indexOf:(e,t)=>Array.isArray(e)?e.indexOf(t):-1,reverse:e=>Array.isArray(e)?[...e].reverse():[],sort:e=>Array.isArray(e)?[...e].sort():[],unique:e=>Array.isArray(e)?[...new Set(e)]:[],flatten:e=>Array.isArray(e)?e.flat():[],count:e=>Array.isArray(e)?e.length:0,get:(e,t,r)=>{if(null==e)return r;const s=String(t).split(".");let n=e;for(const o of s){if(null==n)return r;n=n[o]}return n??r},keys:e=>"object"!=typeof e||null===e?[]:Object.keys(e),values:e=>"object"!=typeof e||null===e?[]:Object.values(e),entries:e=>"object"!=typeof e||null===e?[]:Object.entries(e),has:(e,t)=>"object"==typeof e&&null!==e&&String(t)in e,merge:(...e)=>{const t={};for(const r of e)"object"==typeof r&&null!==r&&Object.assign(t,r);return t},and:(...e)=>e.every(e=>Boolean(e)),or:(...e)=>e.some(e=>Boolean(e)),not:e=>!e,eq:(e,t)=>e===t,ne:(e,t)=>e!==t,gt:(e,t)=>Number(e)>Number(t),gte:(e,t)=>Number(e)>=Number(t),lt:(e,t)=>Number(e)<Number(t),lte:(e,t)=>Number(e)<=Number(t),between:(e,t,r)=>{const s=Number(e);return s>=Number(t)&&s<=Number(r)},formatNumber:(e,t)=>{const r=Number(e)||0,s=Number(t)??0;return r.toLocaleString(void 0,{minimumFractionDigits:s,maximumFractionDigits:s})},formatCurrency:(e,t)=>{const r=Number(e)||0,s=String(t||"CNY");return r.toLocaleString("zh-CN",{style:"currency",currency:s})},formatPercent:(e,t)=>{const r=Number(e)||0,s=Number(t)??0;return(100*r).toFixed(s)+"%"},jsonParse:e=>{try{return JSON.parse(String(e))}catch{return null}},jsonStringify:e=>JSON.stringify(e)},N=class{constructor(e={}){this.depth=0,this.startTime=0,this.options={maxDepth:100,timeout:1e3,debug:!1,...e}}evaluate(e,t){this.depth=0,this.startTime=Date.now();try{return{value:this.evaluateNode(e,t)}}catch(r){return{value:void 0,error:r instanceof Error?r:new Error(String(r))}}}evaluateNode(e,t){switch(this.checkLimits(),e.type){case"literal":return this.evaluateLiteral(e);case"identifier":return this.evaluateIdentifier(e,t);case"member":return this.evaluateMember(e,t);case"call":return this.evaluateCall(e,t);case"binary":return this.evaluateBinary(e,t);case"unary":return this.evaluateUnary(e,t);case"conditional":return this.evaluateConditional(e,t);case"array":return this.evaluateArray(e,t);default:throw new h("",`Unknown node type: ${e.type}`)}}evaluateLiteral(e){return e.value}evaluateIdentifier(e,t){const r=e.name;switch(r){case"state":return t.state;case"query":return t.query;case"context":return t.context;case"event":return t.event;case"item":return t.item;case"index":return t.index;default:throw new h("",`Unknown variable '${r}'`,void 0!==e.start&&void 0!==e.end?{start:e.start,end:e.end}:void 0)}}evaluateMember(e,t){const r=this.evaluateNode(e.object,t);if(null==r)return;let s;if(e.computed){s=this.evaluateNode(e.property,t)}else s=e.property;return"object"==typeof r&&null!==r?r[s]:void 0}evaluateCall(e,t){const r=I[e.callee];if(!r)throw new h("",`Unknown function '${e.callee}'`);return r(...e.arguments.map(e=>this.evaluateNode(e,t)))}evaluateBinary(e,t){const r=e.operator;if("&&"===r){const r=this.evaluateNode(e.left,t);return r?this.evaluateNode(e.right,t):r}if("||"===r){const r=this.evaluateNode(e.left,t);return r||this.evaluateNode(e.right,t)}if("??"===r){const r=this.evaluateNode(e.left,t);return null!=r?r:this.evaluateNode(e.right,t)}const s=this.evaluateNode(e.left,t),n=this.evaluateNode(e.right,t);switch(r){case"+":return"string"==typeof s||"string"==typeof n?String(s)+String(n):s+n;case"-":return s-n;case"*":return s*n;case"/":return s/n;case"%":return s%n;case"==":return s===n;case"!=":return s!==n;case"<":return s<n;case">":return s>n;case"<=":return s<=n;case">=":return s>=n;default:throw new h("",`Unknown operator '${r}'`)}}evaluateUnary(e,t){const r=this.evaluateNode(e.argument,t);switch(e.operator){case"!":return!r;case"-":return-r;default:throw new h("",`Unknown unary operator '${e.operator}'`)}}evaluateConditional(e,t){return this.evaluateNode(e.test,t)?this.evaluateNode(e.consequent,t):this.evaluateNode(e.alternate,t)}evaluateArray(e,t){return e.elements.map(e=>this.evaluateNode(e,t))}checkLimits(){if(this.depth++,this.depth>(this.options.maxDepth??100))throw new h("","Maximum recursion depth exceeded");if(Date.now()-this.startTime>(this.options.timeout??1e3))throw new h("","Expression evaluation timeout")}},T=class{constructor(e={}){this.astCache=new Map,this.options={cacheAST:!0,maxCacheSize:1e3,...e},this.evaluator=new N(e)}evaluate(e,t){try{const r=this.parse(e);return this.evaluator.evaluate(r,t)}catch(r){return{value:void 0,error:r instanceof Error?r:new Error(String(r))}}}evaluateWithFallback(e,t,r){const s=this.evaluate(e,t);return s.error?(this.log("warn",`Expression evaluation failed: ${s.error.message}`,e),r):s.value}evaluateTemplate(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{const s=this.evaluate(r.trim(),t);return s.error?(this.log("warn",`Template expression failed: ${s.error.message}`,r),""):String(s.value??"")})}parse(e){if(this.options.cacheAST){const t=this.astCache.get(e);if(t)return t}try{const t=new E(e).tokenize(),r=new b(t).parse();if(this.options.cacheAST){if(this.astCache.size>=(this.options.maxCacheSize??1e3)){Array.from(this.astCache.keys()).slice(0,Math.floor(this.astCache.size/2)).forEach(e=>this.astCache.delete(e))}this.astCache.set(e,r)}return r}catch(t){throw new h(e,t instanceof Error?t.message:"Parse error")}}validate(e){const t=[],r=[],s=[],n=[];try{const t=this.parse(e);return this.collectReferences(t,s,n),{valid:!0,errors:[],warnings:r,referencedPaths:s,calledFunctions:n}}catch(o){return t.push({type:"SYNTAX_ERROR",message:o instanceof Error?o.message:"Parse error"}),{valid:!1,errors:t,warnings:r,referencedPaths:s,calledFunctions:n}}}clearCache(){this.astCache.clear()}collectReferences(e,t,r){switch(e.type){case"identifier":t.push(e.name);break;case"member":{const r=this.buildMemberPath(e);r&&t.push(r);break}case"call":r.push(e.callee),e.arguments.forEach(e=>this.collectReferences(e,t,r));break;case"binary":this.collectReferences(e.left,t,r),this.collectReferences(e.right,t,r);break;case"unary":this.collectReferences(e.argument,t,r);break;case"conditional":this.collectReferences(e.test,t,r),this.collectReferences(e.consequent,t,r),this.collectReferences(e.alternate,t,r);break;case"array":e.elements.forEach(e=>this.collectReferences(e,t,r))}}buildMemberPath(e){if("identifier"===e.type)return e.name;if("member"===e.type&&!e.computed){const t=this.buildMemberPath(e.object);if(t)return`${t}.${e.property}`}return null}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},w=class{constructor(e){this.storage={get:(e,t)=>{const r=this.getStorageKey(e,null==t?void 0:t.namespace),s=localStorage.getItem(r);if(s)try{const e=JSON.parse(s);return e.expires&&Date.now()>e.expires?void localStorage.removeItem(r):e.value}catch{return}},set:(e,t,r)=>{const s=this.getStorageKey(e,null==r?void 0:r.namespace),n={value:t,expires:(null==r?void 0:r.ttl)?Date.now()+1e3*r.ttl:void 0};localStorage.setItem(s,JSON.stringify(n))},remove:(e,t)=>{const r=this.getStorageKey(e,null==t?void 0:t.namespace);localStorage.removeItem(r)}},this.options=e,this.storageNamespace=`djvlc:${e.context.pageUid}`}async requestData(e,t){this.log("debug",`Requesting data: ${e}`,t);const r=performance.now(),s=this.options.context;try{const n=await fetch(`${this.options.apiBaseUrl}/data/query`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({queryVersionId:e,params:t||{},context:{pageVersionId:s.pageVersionId,uid:s.userId}})}),o=await n.json(),a=performance.now()-r;return this.log("debug",`Data query completed in ${a.toFixed(2)}ms`),o.success&&o.data&&this.options.stateManager.setQuery(e,o.data),o}catch(n){return this.log("error",`Data query failed: ${e}`,n),{success:!1,message:n instanceof Error?n.message:"Query failed"}}}async executeAction(e,t){this.log("debug",`Executing action: ${e}`,t);const r=performance.now(),s=this.options.context;try{const n=await fetch(`${this.options.apiBaseUrl}/actions/execute`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({actionType:e,params:t||{},context:{pageVersionId:s.pageVersionId,uid:s.userId,deviceId:s.deviceId,channel:s.channel},idempotencyKey:this.generateIdempotencyKey(e,t)})}),o=await n.json(),a=performance.now()-r;return this.log("debug",`Action completed in ${a.toFixed(2)}ms`),o}catch(n){return this.log("error",`Action failed: ${e}`,n),{success:!1,message:n instanceof Error?n.message:"Action failed"}}}navigate(e){this.log("debug","Navigate:",e),this.track({eventName:"navigate",params:{url:e.url,newTab:e.newTab}});let t=e.url;if(e.params){const r=new URLSearchParams(e.params);t+=(t.includes("?")?"&":"?")+r.toString()}e.newTab?window.open(t,"_blank"):e.replace?window.location.replace(t):window.location.href=t}goBack(){this.log("debug","Navigate back"),window.history.back()}refresh(){this.log("debug","Refresh page"),window.location.reload()}async openDialog(e){switch(this.log("debug","Open dialog:",e),e.type){case"alert":return window.alert(e.content||e.title),!0;case"confirm":return window.confirm(e.content||e.title);case"prompt":return window.prompt(e.content||e.title)||"";case"custom":return this.log("warn","Custom dialog not implemented"),!1;default:return!1}}closeDialog(){this.log("debug","Close dialog")}showToast(e){this.log("debug","Show toast:",e);const t=document.createElement("div");t.className=`djvlc-toast djvlc-toast-${e.type||"info"} djvlc-toast-${e.position||"top"}`,t.textContent=e.message,Object.assign(t.style,{position:"fixed",left:"50%",transform:"translateX(-50%)",padding:"12px 24px",borderRadius:"8px",color:"#fff",fontSize:"14px",zIndex:"10000",animation:"djvlc-toast-fade-in 0.3s ease"});t.style.backgroundColor={success:"#52c41a",error:"#ff4d4f",warning:"#faad14",info:"#1890ff"}[e.type||"info"];Object.assign(t.style,{top:{top:"20px"},center:{top:"50%",transform:"translate(-50%, -50%)"},bottom:{bottom:"20px"}}[e.position||"top"]),document.body.appendChild(t),setTimeout(()=>{t.style.animation="djvlc-toast-fade-out 0.3s ease",setTimeout(()=>t.remove(),300)},e.duration||3e3)}track(e){this.log("debug","Track event:",e);const t=this.options.context;fetch(`${this.options.apiBaseUrl}/track`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({eventName:e.eventName,params:e.params,timestamp:e.timestamp||Date.now(),context:{pageVersionId:t.pageVersionId,runtimeVersion:t.runtimeVersion,userId:t.userId,deviceId:t.deviceId,channel:t.channel}}),keepalive:!0}).catch(e=>{this.log("warn","Track failed:",e)})}async copyToClipboard(e){try{return await navigator.clipboard.writeText(e),{success:!0,content:e}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Copy failed"}}}async readFromClipboard(){try{return{success:!0,content:await navigator.clipboard.readText()}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Read failed"}}}getState(e){return this.options.stateManager.getVariable(e)}setState(e,t){this.options.stateManager.setVariable(e,t)}getVariable(e){return this.options.stateManager.getVariable(e)}postMessage(e,t){this.log("debug",`Post message to ${e}:`,t);const r=new CustomEvent(`djvlc:message:${e}`,{detail:{message:t,from:this.options.context.pageUid}});document.dispatchEvent(r)}broadcast(e,t){this.log("debug",`Broadcast to ${e}:`,t);const r=new CustomEvent(`djvlc:broadcast:${e}`,{detail:{message:t,from:this.options.context.pageUid}});document.dispatchEvent(r)}getContext(){return{...this.options.context}}buildHeaders(){const e={"Content-Type":"application/json",...this.options.headers};return this.options.authToken&&(e.Authorization=`Bearer ${this.options.authToken}`),e}getStorageKey(e,t){return`${t||this.storageNamespace}:${e}`}generateIdempotencyKey(e,t){const r=Date.now(),s=JSON.stringify(t||{});return`${e}:${r}:${this.simpleHash(s)}`}simpleHash(e){let t=0;for(let r=0;r<e.length;r++){t=(t<<5)-t+e.charCodeAt(r),t&=t}return Math.abs(t).toString(36)}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},A=class{constructor(e={}){this.blockedComponentsMap=new Map,this.blockedActionsSet=new Set,this.options={enableSRI:!0,cdnDomains:[],apiDomains:[],blockedComponents:[],blockedActions:[],...e},this.updateBlockedList(e.blockedComponents||[],e.blockedActions||[])}updateBlockedList(e,t){this.blockedComponentsMap.clear(),e.forEach(e=>{this.blockedComponentsMap.set(`${e.name}@${e.version}`,e)}),this.blockedActionsSet=new Set(t)}isComponentBlocked(e,t){return this.blockedComponentsMap.has(`${e}@${t}`)}getBlockedInfo(e,t){return this.blockedComponentsMap.get(`${e}@${t}`)}isActionBlocked(e){return this.blockedActionsSet.has(e)}async validateComponent(e,t,r,s){if(!this.options.enableSRI)return;const[n,o]=s.split("-");if(!n||!o)throw new p(e,t,s,"Invalid format");const a=await this.computeHash(r,n);if(a!==o)throw new p(e,t,o,a)}isAllowedUrl(e,t){const r="cdn"===t?this.options.cdnDomains:this.options.apiDomains;if(!r||0===r.length)return!0;try{const t=new URL(e);return r.some(e=>{if(e.startsWith("*.")){const r=e.slice(2);return t.hostname.endsWith(r)}return t.hostname===e})}catch{return!1}}generateCSPPolicy(){const e=this.options.cdnDomains||[],t=this.options.apiDomains||[],r=["'self'",...e].join(" "),s=["'self'",...t].join(" ");return["default-src 'self'",`script-src ${r}`,`style-src ${["'self'","'unsafe-inline'",...e].join(" ")}`,`img-src ${["'self'","data:","blob:",...e].join(" ")}`,`connect-src ${s}`,`font-src 'self' data: ${e.join(" ")}`,"frame-ancestors 'self'","base-uri 'self'","form-action 'self'"].join("; ")}applyCSP(){const e=document.createElement("meta");e.httpEquiv="Content-Security-Policy",e.content=this.generateCSPPolicy(),document.head.appendChild(e)}assertNotBlocked(e,t){const r=this.getBlockedInfo(e,t);if(r)throw new d(e,t,r.reason)}async computeHash(e,t){const r=(new TextEncoder).encode(e),s=await crypto.subtle.digest(t.toUpperCase(),r),n=Array.from(new Uint8Array(s));return btoa(String.fromCharCode(...n))}_log(e,t){this.options.logger&&this.options.logger[e](t)}get log(){return this._log.bind(this)}},S=class{constructor(e){this.spans=new Map,this.metrics=[],this.errors=[],this.options={enabled:!0,sampleRate:1,...e},this.traceId=this.generateId(),this.shouldSample=Math.random()<(this.options.sampleRate??1)}getTraceId(){return this.traceId}getTraceparent(){return`00-${this.traceId}-${this.generateId().slice(0,16)}-01`}startSpan(e,t,r){const s={spanId:this.generateId().slice(0,16),traceId:this.traceId,parentSpanId:t,name:e,startTime:performance.now(),attributes:r};return this.spans.set(s.spanId,s),this.log("debug",`Span started: ${e} (${s.spanId})`),s}endSpan(e,t="ok"){const r=this.spans.get(e);r&&(r.endTime=performance.now(),r.status=t,this.log("debug",`Span ended: ${r.name} (${e}) - ${r.endTime-r.startTime}ms`))}recordMetric(e,t,r,s){const n={type:e,name:t,duration:r,startTime:performance.now()-r,extra:s};this.metrics.push(n),this.log("debug",`Metric: ${e} - ${t} - ${r}ms`),this.options.onMetric&&this.options.onMetric(n)}recordError(e,t){const r={type:"LOAD_ERROR",message:e.message,stack:e instanceof Error?e.stack:void 0,timestamp:Date.now(),traceId:this.traceId,...t};this.errors.push(r),this.log("error",`Error recorded: ${e.message}`),this.shouldSample&&this.options.enabled&&this.reportError(r)}recordPageLoad(e,t){this.recordMetric("page_resolve","page_load",e,{pageVersionId:this.options.pageVersionId,...t})}recordComponentLoad(e,t,r,s){this.recordMetric("component_load",`${e}@${t}`,r,{success:s})}recordFirstRender(e){this.recordMetric("first_render","first_render",e,{pageVersionId:this.options.pageVersionId})}recordActionExecute(e,t,r){this.recordMetric("action_execute",e,t,{success:r})}recordQueryExecute(e,t,r,s){this.recordMetric("query_execute",e,t,{success:r,fromCache:s})}getMetrics(){return[...this.metrics]}getSpans(){return Array.from(this.spans.values())}clear(){this.spans.clear(),this.metrics=[],this.errors=[]}async flush(){if(!this.shouldSample||!this.options.enabled||!this.options.endpoint)return;const e={traceId:this.traceId,pageVersionId:this.options.pageVersionId,appId:this.options.appId,spans:this.getSpans(),metrics:this.metrics,errors:this.errors,timestamp:Date.now()};try{await fetch(this.options.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})}catch(t){this.log("warn","Failed to flush telemetry:",t)}}reportError(e){this.options.endpoint&&fetch(`${this.options.endpoint}/errors`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}).catch(()=>{})}generateId(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},O=class{constructor(e){this.container=null,this.renderedElements=new Map,this.expressionContext={state:{},query:{},context:{}},this.options=e}init(){this.log("debug","Renderer initialized")}render(e,t){this.container=t,this.log("debug","Rendering page",e.page.id),t.innerHTML="",this.applyPageStyles(e.page.canvas);const r=document.createDocumentFragment();for(const s of e.components){const e=this.renderComponent(s);e&&r.appendChild(e)}t.appendChild(r),this.log("info",`Rendered ${e.components.length} components`)}updateComponent(e,t){const r=this.renderedElements.get(e);r?this.applyProps(r,t):this.log("warn",`Component not found: ${e}`)}updateContext(e){this.expressionContext={...this.expressionContext,...e}}destroy(){this.renderedElements.forEach(e=>{e.remove()}),this.renderedElements.clear(),this.container&&(this.container.innerHTML=""),this.log("debug","Renderer destroyed")}renderComponent(e){const{id:t,type:r,props:s,style:n,children:o,visible:a}=e;if(!1===a)return null;try{const e=this.options.components.get(r);let a;e&&customElements.get(r)?a=document.createElement(r):(a=document.createElement("div"),a.className=`djvlc-component djvlc-${r}`,e||(this.log("warn",`Component not loaded: ${r}`),a.textContent=`[Component: ${r}]`)),a.setAttribute("data-component-id",t),a.setAttribute("data-component-type",r);const i=this.resolveProps(s);if(this.applyProps(a,i),n&&this.applyStyles(a,n),this.options.injectHostApi(a,t),o&&o.length>0)for(const t of o){const e=this.renderComponent(t);e&&a.appendChild(e)}return this.renderedElements.set(t,a),a}catch(i){if(this.log("error",`Failed to render component: ${t}`,i),this.options.onRenderError)return this.options.onRenderError(t,i);const e=document.createElement("div");return e.className="djvlc-error-boundary",e.textContent=`Error rendering component: ${r}`,e}}resolveProps(e){const t={};for(const[r,s]of Object.entries(e))if(n(s)){const e=this.options.expressionEngine.evaluateWithFallback(s.expression,this.expressionContext,s.fallback);t[r]=e}else"object"!=typeof s||null===s||Array.isArray(s)?t[r]=s:t[r]=this.resolveProps(s);return t}applyProps(e,t){for(const[r,s]of Object.entries(t))null!=s&&(e.tagName.includes("-")?e[r]=s:"boolean"==typeof s?s?e.setAttribute(r,""):e.removeAttribute(r):"object"==typeof s?e.setAttribute(r,JSON.stringify(s)):e.setAttribute(r,String(s)))}applyStyles(e,t){for(const[r,s]of Object.entries(t)){if(null==s)continue;let t;if("number"==typeof s){t=["zIndex","opacity","flex","fontWeight"].includes(r)?String(s):`${s}px`}else t=String(s);const n=r.replace(/([A-Z])/g,"-$1").toLowerCase();e.style.setProperty(n,t)}}applyPageStyles(e){this.container&&(this.container.style.width=`${e.width}px`,e.height&&(this.container.style.minHeight=`${e.height}px`),e.background&&(this.container.style.background=e.background),this.container.classList.add("djvlc-page",`djvlc-canvas-${e.type}`))}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}};function C(e){return new R(e)}var R=class{constructor(e){this.container=null,this.options={channel:"prod",debug:!1,enableSRI:!0,...e},this.logger=this.createLogger(),this.stateManager=new y,this.eventBus=new f({debug:e.debug,logger:this.logger}),this.expressionEngine=new T({debug:e.debug,logger:this.logger}),this.pageLoader=new u({apiBaseUrl:e.apiBaseUrl,channel:e.channel,authToken:e.authToken,previewToken:e.previewToken,headers:e.headers,logger:this.logger}),this.componentLoader=new m({cdnBaseUrl:e.cdnBaseUrl,enableSRI:e.enableSRI,logger:this.logger}),this.assetLoader=new g({cdnHosts:[new URL(e.cdnBaseUrl).host],apiHosts:[new URL(e.apiBaseUrl).host]}),this.securityManager=new A({enableSRI:e.enableSRI,cdnDomains:[new URL(e.cdnBaseUrl).host],apiDomains:[new URL(e.apiBaseUrl).host],logger:this.logger}),this.log("info","Runtime created")}async init(){this.log("info","Initializing runtime");const e=performance.now();try{this.container=this.resolveContainer(),this.assetLoader.preconnectAll(),this.pageLoader.preconnect(),customElements.get("djvlc-fallback")||customElements.define("djvlc-fallback",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML='\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #fff2f0;\n border: 1px solid #ffccc7;\n border-radius: 4px;\n color: #ff4d4f;\n font-size: 14px;\n }\n .title {\n font-weight: 600;\n margin-bottom: 8px;\n }\n .message {\n color: #666;\n }\n </style>\n <div class="title">组件加载失败</div>\n <div class="message"><slot>请刷新页面重试</slot></div>\n '}static get observedAttributes(){return["message","component-name"]}attributeChangedCallback(e,t,r){if("message"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".message");e&&(e.textContent=r)}if("component-name"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".title");e&&(e.textContent=`组件 ${r} 加载失败`)}}}),customElements.get("djvlc-blocked")||customElements.define("djvlc-blocked",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML='\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #fffbe6;\n border: 1px solid #ffe58f;\n border-radius: 4px;\n color: #faad14;\n font-size: 14px;\n }\n .icon {\n margin-right: 8px;\n }\n </style>\n <span class="icon">⚠️</span>\n <span>此组件已被暂停使用</span>\n '}}),customElements.get("djvlc-error-boundary")||customElements.define("djvlc-error-boundary",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML="\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #f5f5f5;\n border: 1px dashed #d9d9d9;\n border-radius: 4px;\n color: #999;\n font-size: 14px;\n text-align: center;\n }\n </style>\n <slot>渲染出错</slot>\n "}}),this.stateManager.setPhase("resolving");const t=performance.now()-e;this.log("info",`Runtime initialized in ${t.toFixed(2)}ms`)}catch(t){throw this.handleError(t),t}}async load(){var e;this.log("info","Loading page:",this.options.pageUid);const t=performance.now();try{this.stateManager.setPhase("resolving");const r=await this.pageLoader.resolve(this.options.pageUid,{uid:this.options.userId,deviceId:this.options.deviceId});this.stateManager.setPage(r),this.telemetryManager=new S({pageVersionId:r.pageVersionId,debug:this.options.debug,logger:this.logger,onMetric:this.options.onMetric}),r.runtimeConfig&&(this.securityManager.updateBlockedList(r.runtimeConfig.blockedComponents||[],r.runtimeConfig.killSwitches||[]),this.componentLoader.updateBlockedList((null==(e=r.runtimeConfig.blockedComponents)?void 0:e.map(e=>`${e.name}@${e.version}`))||[])),this.stateManager.setPhase("loading"),this.componentLoader.preload(r.manifest.components);(await this.componentLoader.loadAll(r.manifest)).forEach((e,t)=>{this.stateManager.setComponentStatus(t,e),this.telemetryManager.recordComponentLoad(e.name,e.version,e.loadTime||0,"loaded"===e.status)}),this.initHostApi(r),this.initRenderer();const s=performance.now()-t;return this.telemetryManager.recordPageLoad(s),this.log("info",`Page loaded in ${s.toFixed(2)}ms`),this.emitEvent("page:loaded",{page:r,loadTime:s}),r}catch(r){throw this.stateManager.setPhase("error"),this.handleError(r),r}}async render(){const e=this.stateManager.getState();if(!e.page||!this.container)throw new c("Page not loaded");this.log("info","Rendering page");const t=performance.now();try{this.stateManager.setPhase("rendering"),this.renderer.updateContext({state:e.variables,query:e.queries,context:{userId:this.options.userId,deviceId:this.options.deviceId,channel:this.options.channel,pageVersionId:e.page.pageVersionId}}),this.renderer.render(e.page.pageJson,this.container),this.stateManager.setPhase("ready");const r=performance.now()-t;this.telemetryManager.recordFirstRender(r),this.log("info",`Page rendered in ${r.toFixed(2)}ms`)}catch(r){throw this.stateManager.setPhase("error"),this.handleError(r),r}}getHostApi(){return this.hostApi}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.subscribe(e)}on(e,t){return this.eventBus.on(e,t)}updateComponent(e,t){this.renderer.updateComponent(e,t)}setVariable(e,t){this.stateManager.setVariable(e,t);const r=this.stateManager.getState();r.page&&this.container&&this.renderer.updateContext({state:r.variables})}async refreshData(e){const t=await this.hostApi.requestData(e);if(t.success){this.stateManager.setQuery(e,t.data);const r=this.stateManager.getState();this.renderer.updateContext({query:r.queries})}}destroy(){var e,t;this.log("info","Destroying runtime"),null==(e=this.telemetryManager)||e.flush(),null==(t=this.renderer)||t.destroy(),this.eventBus.clear(),this.stateManager.setDestroyed(),this.container&&(this.container.innerHTML=""),this.log("info","Runtime destroyed")}resolveContainer(){const{container:e}=this.options;if("string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`Container not found: ${e}`);return t}return e}initHostApi(e){const t={pageUid:e.pageUid,pageVersionId:e.pageVersionId,runtimeVersion:"0.1.0",userId:this.options.userId,deviceId:this.options.deviceId,channel:this.options.channel,isEditMode:!1,isPreviewMode:e.isPreview||!1};this.hostApi=new w({apiBaseUrl:this.options.apiBaseUrl,authToken:this.options.authToken,headers:this.options.headers,stateManager:this.stateManager,eventBus:this.eventBus,expressionEngine:this.expressionEngine,context:t,debug:this.options.debug,logger:this.logger})}initRenderer(){const e=new Map;this.stateManager.getState().components.forEach((t,r)=>{if("loaded"===t.status&&t.component){const[s,n]=r.split("@");e.set(s,{name:s,version:n,Component:t.component,loadTime:t.loadTime||0})}}),this.renderer=new O({expressionEngine:this.expressionEngine,components:e,injectHostApi:(e,t)=>{e.hostApi=this.hostApi,e.componentId=t},debug:this.options.debug,logger:this.logger,onRenderError:(e,t)=>(this.log("error",`Render error in ${e}:`,t),this.emitEvent("component:error",{componentId:e,error:t.message}),function(e,t){const r=document.createElement("djvlc-error-boundary");return t&&r.setAttribute("message",t),r}(0,t.message))}),this.renderer.init()}handleError(e){var t;const r=e instanceof i?e:{type:"LOAD_ERROR",message:e.message,timestamp:Date.now()};this.stateManager.setError(r),null==(t=this.telemetryManager)||t.recordError(e),this.emitEvent("page:error",{error:e.message}),this.options.onError&&this.options.onError(r)}emitEvent(e,t){var r;const s=f.createEvent(e,t,null==(r=this.telemetryManager)?void 0:r.getTraceId());this.eventBus.emit(s),this.options.onEvent&&this.options.onEvent(s)}createLogger(){return{debug:(...e)=>{this.options.debug},info:(...e)=>{},warn:(...e)=>{},error:(...e)=>{}}}log(e,t,...r){this.logger[e](t,...r)}};const _="1.0.2";async function M(e,t){var r,s;const n=C({container:e,pageUid:t.pageUid,apiBaseUrl:t.apiBaseUrl,cdnBaseUrl:t.cdnBaseUrl,channel:t.channel,userId:t.userId,deviceId:t.deviceId,authToken:t.authToken,previewToken:t.previewToken,debug:t.debug,enableSRI:t.enableSRI,headers:t.headers,onError:t.onError?e=>{var r;return null==(r=t.onError)?void 0:r.call(t,new Error(e.message))}:void 0,onMetric:t.onMetric});try{await n.init(),await n.load(),await n.render(),null==(r=t.onLoad)||r.call(t,n.getState())}catch(o){const e=o instanceof Error?o:new Error(String(o));throw null==(s=t.onError)||s.call(t,e),e}return{runtime:n,destroy:()=>n.destroy()}}function D(e){e.forEach(e=>{const t=document.createElement("link");t.rel="preconnect",t.href=e.startsWith("http")?e:`https://${e}`,t.crossOrigin="anonymous",document.head.appendChild(t)})}function x(e,t=_){[`${e}/runtime/${t}/runtime.esm.js`,`${e}/runtime/${t}/runtime.css`].forEach(e=>{const t=document.createElement("link");t.rel="preload",t.href=e,t.as=e.endsWith(".js")?"script":"style",e.endsWith(".js")&&(t.crossOrigin="anonymous"),document.head.appendChild(t)})}function k(){const e="djv_device_id";let t=localStorage.getItem(e);if(!t){t=`${Date.now()}-${Math.random().toString(36).substring(2,11)}`;try{localStorage.setItem(e,t)}catch{}}return t}function L(){return e=32,Array.from({length:e},()=>Math.floor(16*Math.random()).toString(16)).join("");var e}function U(){return e=16,Array.from({length:e},()=>Math.floor(16*Math.random()).toString(16)).join("");var e}function P(){return`00-${L()}-${U()}-01`}const $={mount:M,preconnect:D,preloadAssets:x,getDeviceId:k,generateTraceId:L,generateSpanId:U,generateTraceparent:P,createRuntime:C,RUNTIME_VERSION:_};return e.RUNTIME_VERSION=_,e.createRuntime=C,e.default=$,e.generateSpanId=U,e.generateTraceId=L,e.generateTraceparent=P,e.getDeviceId=k,e.mount=M,e.preconnect=D,e.preloadAssets=x,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});
|
|
1
|
+
var DJVRuntime=function(e){"use strict";const t="1.0.3";var n,r,s=Object.create,i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,c=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,d=(e,t,n)=>(n=null!=e?s(c(e)):{},((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of a(t))l.call(e,s)||s===n||i(e,s,{get:()=>t[s],enumerable:!(r=o(t,s))||r.enumerable});return e})(i(n,"default",{value:e,enumerable:!0}),e)),p=(n={"../../node_modules/.pnpm/@djvlc+contracts-types@1.8.3/node_modules/@djvlc/contracts-types/dist/index.js"(e){var t=(e=>(e.SYSTEM="SYSTEM",e.AUTH="AUTH",e.PERMISSION="PERMISSION",e.RESOURCE="RESOURCE",e.VALIDATION="VALIDATION",e.BUSINESS="BUSINESS",e.RISK="RISK",e))(t||{}),n=(e=>(e.SYSTEM_INTERNAL_ERROR="SYSTEM_INTERNAL_ERROR",e.SYSTEM_SERVICE_UNAVAILABLE="SYSTEM_SERVICE_UNAVAILABLE",e.SYSTEM_TIMEOUT="SYSTEM_TIMEOUT",e.SYSTEM_DATABASE_ERROR="SYSTEM_DATABASE_ERROR",e.SYSTEM_REDIS_ERROR="SYSTEM_REDIS_ERROR",e.AUTH_TOKEN_MISSING="AUTH_TOKEN_MISSING",e.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",e.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",e.AUTH_SIGNATURE_INVALID="AUTH_SIGNATURE_INVALID",e.AUTH_SESSION_EXPIRED="AUTH_SESSION_EXPIRED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.PERMISSION_RESOURCE_FORBIDDEN="PERMISSION_RESOURCE_FORBIDDEN",e.PERMISSION_ACTION_FORBIDDEN="PERMISSION_ACTION_FORBIDDEN",e.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",e.RESOURCE_PAGE_NOT_FOUND="RESOURCE_PAGE_NOT_FOUND",e.RESOURCE_COMPONENT_NOT_FOUND="RESOURCE_COMPONENT_NOT_FOUND",e.RESOURCE_ACTION_NOT_FOUND="RESOURCE_ACTION_NOT_FOUND",e.RESOURCE_VERSION_NOT_FOUND="RESOURCE_VERSION_NOT_FOUND",e.VALIDATION_INVALID_PARAMS="VALIDATION_INVALID_PARAMS",e.VALIDATION_SCHEMA_MISMATCH="VALIDATION_SCHEMA_MISMATCH",e.VALIDATION_EXPRESSION_ERROR="VALIDATION_EXPRESSION_ERROR",e.VALIDATION_FIELD_REQUIRED="VALIDATION_FIELD_REQUIRED",e.VALIDATION_FIELD_TYPE_ERROR="VALIDATION_FIELD_TYPE_ERROR",e.BUSINESS_ACTIVITY_NOT_STARTED="BUSINESS_ACTIVITY_NOT_STARTED",e.BUSINESS_ACTIVITY_ENDED="BUSINESS_ACTIVITY_ENDED",e.BUSINESS_ALREADY_CLAIMED="BUSINESS_ALREADY_CLAIMED",e.BUSINESS_ALREADY_SIGNED="BUSINESS_ALREADY_SIGNED",e.BUSINESS_STOCK_EXHAUSTED="BUSINESS_STOCK_EXHAUSTED",e.BUSINESS_QUOTA_EXCEEDED="BUSINESS_QUOTA_EXCEEDED",e.BUSINESS_PREREQUISITE_NOT_MET="BUSINESS_PREREQUISITE_NOT_MET",e.RISK_RATE_LIMITED="RISK_RATE_LIMITED",e.RISK_BLOCKED="RISK_BLOCKED",e.RISK_CAPTCHA_REQUIRED="RISK_CAPTCHA_REQUIRED",e.RISK_DEVICE_ABNORMAL="RISK_DEVICE_ABNORMAL",e.RISK_IDEMPOTENCY_CONFLICT="RISK_IDEMPOTENCY_CONFLICT",e.COMPONENT_LOAD_FAILED="COMPONENT_LOAD_FAILED",e.COMPONENT_INTEGRITY_MISMATCH="COMPONENT_INTEGRITY_MISMATCH",e.COMPONENT_BLOCKED="COMPONENT_BLOCKED",e.COMPONENT_DEPRECATED="COMPONENT_DEPRECATED",e.COMPONENT_INCOMPATIBLE="COMPONENT_INCOMPATIBLE",e.PUBLISH_VERSION_CONFLICT="PUBLISH_VERSION_CONFLICT",e.PUBLISH_VALIDATION_FAILED="PUBLISH_VALIDATION_FAILED",e.PUBLISH_ROLLBACK_FAILED="PUBLISH_ROLLBACK_FAILED",e))(n||{}),r={SYSTEM_INTERNAL_ERROR:500,SYSTEM_SERVICE_UNAVAILABLE:503,SYSTEM_TIMEOUT:504,SYSTEM_DATABASE_ERROR:500,SYSTEM_REDIS_ERROR:500,AUTH_TOKEN_MISSING:401,AUTH_TOKEN_INVALID:401,AUTH_TOKEN_EXPIRED:401,AUTH_SIGNATURE_INVALID:401,AUTH_SESSION_EXPIRED:401,PERMISSION_DENIED:403,PERMISSION_RESOURCE_FORBIDDEN:403,PERMISSION_ACTION_FORBIDDEN:403,RESOURCE_NOT_FOUND:404,RESOURCE_PAGE_NOT_FOUND:404,RESOURCE_COMPONENT_NOT_FOUND:404,RESOURCE_ACTION_NOT_FOUND:404,RESOURCE_VERSION_NOT_FOUND:404,VALIDATION_INVALID_PARAMS:400,VALIDATION_SCHEMA_MISMATCH:400,VALIDATION_EXPRESSION_ERROR:400,VALIDATION_FIELD_REQUIRED:400,VALIDATION_FIELD_TYPE_ERROR:400,BUSINESS_ACTIVITY_NOT_STARTED:422,BUSINESS_ACTIVITY_ENDED:422,BUSINESS_ALREADY_CLAIMED:422,BUSINESS_ALREADY_SIGNED:422,BUSINESS_STOCK_EXHAUSTED:422,BUSINESS_QUOTA_EXCEEDED:422,BUSINESS_PREREQUISITE_NOT_MET:422,RISK_RATE_LIMITED:429,RISK_BLOCKED:403,RISK_CAPTCHA_REQUIRED:428,RISK_DEVICE_ABNORMAL:403,RISK_IDEMPOTENCY_CONFLICT:409,COMPONENT_LOAD_FAILED:500,COMPONENT_INTEGRITY_MISMATCH:500,COMPONENT_BLOCKED:503,COMPONENT_DEPRECATED:410,COMPONENT_INCOMPATIBLE:500,PUBLISH_VERSION_CONFLICT:409,PUBLISH_VALIDATION_FAILED:400,PUBLISH_ROLLBACK_FAILED:500},s={SYSTEM_INTERNAL_ERROR:"系统内部错误",SYSTEM_SERVICE_UNAVAILABLE:"服务暂时不可用",SYSTEM_TIMEOUT:"请求超时",SYSTEM_DATABASE_ERROR:"数据库错误",SYSTEM_REDIS_ERROR:"缓存服务错误",AUTH_TOKEN_MISSING:"缺少认证令牌",AUTH_TOKEN_INVALID:"认证令牌无效",AUTH_TOKEN_EXPIRED:"认证令牌已过期",AUTH_SIGNATURE_INVALID:"签名无效",AUTH_SESSION_EXPIRED:"会话已过期",PERMISSION_DENIED:"权限不足",PERMISSION_RESOURCE_FORBIDDEN:"无权访问该资源",PERMISSION_ACTION_FORBIDDEN:"无权执行该操作",RESOURCE_NOT_FOUND:"资源不存在",RESOURCE_PAGE_NOT_FOUND:"页面不存在",RESOURCE_COMPONENT_NOT_FOUND:"组件不存在",RESOURCE_ACTION_NOT_FOUND:"动作不存在",RESOURCE_VERSION_NOT_FOUND:"版本不存在",VALIDATION_INVALID_PARAMS:"参数无效",VALIDATION_SCHEMA_MISMATCH:"Schema 不匹配",VALIDATION_EXPRESSION_ERROR:"表达式错误",VALIDATION_FIELD_REQUIRED:"必填字段缺失",VALIDATION_FIELD_TYPE_ERROR:"字段类型错误",BUSINESS_ACTIVITY_NOT_STARTED:"活动未开始",BUSINESS_ACTIVITY_ENDED:"活动已结束",BUSINESS_ALREADY_CLAIMED:"已经领取过",BUSINESS_ALREADY_SIGNED:"今日已签到",BUSINESS_STOCK_EXHAUSTED:"库存不足",BUSINESS_QUOTA_EXCEEDED:"超出配额限制",BUSINESS_PREREQUISITE_NOT_MET:"前置条件未满足",RISK_RATE_LIMITED:"请求过于频繁",RISK_BLOCKED:"请求被阻断",RISK_CAPTCHA_REQUIRED:"需要验证码验证",RISK_DEVICE_ABNORMAL:"设备异常",RISK_IDEMPOTENCY_CONFLICT:"重复请求",COMPONENT_LOAD_FAILED:"组件加载失败",COMPONENT_INTEGRITY_MISMATCH:"组件完整性校验失败",COMPONENT_BLOCKED:"组件已被阻断",COMPONENT_DEPRECATED:"组件已废弃",COMPONENT_INCOMPATIBLE:"组件版本不兼容",PUBLISH_VERSION_CONFLICT:"版本冲突",PUBLISH_VALIDATION_FAILED:"发布校验失败",PUBLISH_ROLLBACK_FAILED:"回滚失败"},i=(e=>(e.DRAFT="draft",e.STABLE="stable",e.DEPRECATED="deprecated",e.BLOCKED="blocked",e))(i||{}),o=(e=>(e.DRAFT="draft",e.PUBLISHED="published",e.ARCHIVED="archived",e))(o||{}),a=(e=>(e.PREVIEW="preview",e.GRAY="gray",e.PROD="prod",e))(a||{}),c=(e=>(e.PENDING="pending",e.PROCESSING="processing",e.SUCCESS="success",e.FAILED="failed",e.ROLLBACK="rollback",e))(c||{}),l=(e=>(e.PAGE_CREATE="page.create",e.PAGE_UPDATE="page.update",e.PAGE_DELETE="page.delete",e.PAGE_PUBLISH="page.publish",e.PAGE_ROLLBACK="page.rollback",e.COMPONENT_PUBLISH="component.publish",e.COMPONENT_BLOCK="component.block",e.COMPONENT_UNBLOCK="component.unblock",e.ACTION_EXECUTE="action.execute",e.DEFINITION_CREATE="definition.create",e.DEFINITION_UPDATE="definition.update",e.DEFINITION_PUBLISH="definition.publish",e.SYSTEM_KILL_SWITCH="system.kill_switch",e))(l||{}),d=[{name:"len",category:"string",description:"获取字符串长度",params:[{name:"str",type:"string",required:!0,description:"输入字符串"}],returnType:"number",pure:!0,examples:['len("hello") // 5',"len(state.name) // 动态获取"]},{name:"trim",category:"string",description:"去除首尾空白",params:[{name:"str",type:"string",required:!0,description:"输入字符串"}],returnType:"string",pure:!0,examples:['trim(" hello ") // "hello"']},{name:"upper",category:"string",description:"转换为大写",params:[{name:"str",type:"string",required:!0,description:"输入字符串"}],returnType:"string",pure:!0,examples:['upper("hello") // "HELLO"']},{name:"lower",category:"string",description:"转换为小写",params:[{name:"str",type:"string",required:!0,description:"输入字符串"}],returnType:"string",pure:!0,examples:['lower("HELLO") // "hello"']},{name:"substring",category:"string",description:"截取子字符串",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"start",type:"number",required:!0,description:"起始位置"},{name:"end",type:"number",required:!1,description:"结束位置"}],returnType:"string",pure:!0,examples:['substring("hello", 0, 2) // "he"']},{name:"replace",category:"string",description:"替换字符串",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"search",type:"string",required:!0,description:"搜索内容"},{name:"replacement",type:"string",required:!0,description:"替换内容"}],returnType:"string",pure:!0,examples:['replace("hello", "l", "x") // "hexxo"']},{name:"split",category:"string",description:"分割字符串为数组",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"separator",type:"string",required:!0,description:"分隔符"}],returnType:"array",pure:!0,examples:['split("a,b,c", ",") // ["a", "b", "c"]']},{name:"join",category:"string",description:"合并数组为字符串",params:[{name:"arr",type:"array",required:!0,description:"输入数组"},{name:"separator",type:"string",required:!1,defaultValue:",",description:"分隔符"}],returnType:"string",pure:!0,examples:['join(["a", "b", "c"], "-") // "a-b-c"']},{name:"contains",category:"string",description:"检查是否包含子字符串",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"search",type:"string",required:!0,description:"搜索内容"}],returnType:"boolean",pure:!0,examples:['contains("hello", "ell") // true']},{name:"startsWith",category:"string",description:"检查是否以指定前缀开始",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"prefix",type:"string",required:!0,description:"前缀"}],returnType:"boolean",pure:!0,examples:['startsWith("hello", "he") // true']},{name:"endsWith",category:"string",description:"检查是否以指定后缀结束",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"suffix",type:"string",required:!0,description:"后缀"}],returnType:"boolean",pure:!0,examples:['endsWith("hello", "lo") // true']}],p=[{name:"toNumber",category:"number",description:"转换为数字",params:[{name:"value",type:"any",required:!0,description:"输入值"},{name:"defaultValue",type:"number",required:!1,defaultValue:0,description:"默认值"}],returnType:"number",pure:!0,examples:['toNumber("123") // 123','toNumber("abc", 0) // 0']},{name:"round",category:"number",description:"四舍五入",params:[{name:"value",type:"number",required:!0,description:"输入数字"},{name:"decimals",type:"number",required:!1,defaultValue:0,description:"小数位数"}],returnType:"number",pure:!0,examples:["round(3.14159, 2) // 3.14"]},{name:"floor",category:"number",description:"向下取整",params:[{name:"value",type:"number",required:!0,description:"输入数字"}],returnType:"number",pure:!0,examples:["floor(3.7) // 3"]},{name:"ceil",category:"number",description:"向上取整",params:[{name:"value",type:"number",required:!0,description:"输入数字"}],returnType:"number",pure:!0,examples:["ceil(3.2) // 4"]},{name:"abs",category:"number",description:"绝对值",params:[{name:"value",type:"number",required:!0,description:"输入数字"}],returnType:"number",pure:!0,examples:["abs(-5) // 5"]},{name:"min",category:"number",description:"最小值",params:[{name:"values",type:"number",required:!0,variadic:!0,description:"数字列表"}],returnType:"number",pure:!0,examples:["min(1, 2, 3) // 1"]},{name:"max",category:"number",description:"最大值",params:[{name:"values",type:"number",required:!0,variadic:!0,description:"数字列表"}],returnType:"number",pure:!0,examples:["max(1, 2, 3) // 3"]},{name:"clamp",category:"number",description:"限制范围",params:[{name:"value",type:"number",required:!0,description:"输入数字"},{name:"min",type:"number",required:!0,description:"最小值"},{name:"max",type:"number",required:!0,description:"最大值"}],returnType:"number",pure:!0,examples:["clamp(5, 0, 3) // 3"]}],u=[{name:"length",category:"array",description:"获取数组长度",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"number",pure:!0,examples:["length([1, 2, 3]) // 3"]},{name:"first",category:"array",description:"获取第一个元素",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"any",pure:!0,examples:["first([1, 2, 3]) // 1"]},{name:"last",category:"array",description:"获取最后一个元素",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"any",pure:!0,examples:["last([1, 2, 3]) // 3"]},{name:"at",category:"array",description:"获取指定索引的元素",params:[{name:"arr",type:"array",required:!0,description:"输入数组"},{name:"index",type:"number",required:!0,description:"索引"}],returnType:"any",pure:!0,examples:["at([1, 2, 3], 1) // 2"]},{name:"includes",category:"array",description:"检查是否包含元素",params:[{name:"arr",type:"array",required:!0,description:"输入数组"},{name:"value",type:"any",required:!0,description:"搜索值"}],returnType:"boolean",pure:!0,examples:["includes([1, 2, 3], 2) // true"]},{name:"slice",category:"array",description:"截取数组",params:[{name:"arr",type:"array",required:!0,description:"输入数组"},{name:"start",type:"number",required:!0,description:"起始位置"},{name:"end",type:"number",required:!1,description:"结束位置"}],returnType:"array",pure:!0,examples:["slice([1, 2, 3, 4], 1, 3) // [2, 3]"]},{name:"concat",category:"array",description:"合并数组",params:[{name:"arrays",type:"array",required:!0,variadic:!0,description:"数组列表"}],returnType:"array",pure:!0,examples:["concat([1, 2], [3, 4]) // [1, 2, 3, 4]"]},{name:"unique",category:"array",description:"去重",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"array",pure:!0,examples:["unique([1, 2, 2, 3]) // [1, 2, 3]"]},{name:"reverse",category:"array",description:"反转数组",params:[{name:"arr",type:"array",required:!0,description:"输入数组"}],returnType:"array",pure:!0,examples:["reverse([1, 2, 3]) // [3, 2, 1]"]},{name:"sum",category:"array",description:"求和",params:[{name:"arr",type:"array",required:!0,description:"数字数组"}],returnType:"number",pure:!0,examples:["sum([1, 2, 3]) // 6"]},{name:"average",category:"array",description:"平均值",params:[{name:"arr",type:"array",required:!0,description:"数字数组"}],returnType:"number",pure:!0,examples:["average([1, 2, 3]) // 2"]}],h=[{name:"now",category:"date",description:"当前时间戳",params:[],returnType:"number",pure:!1,examples:["now() // 1704067200000"]},{name:"today",category:"date",description:"今天日期(YYYY-MM-DD)",params:[],returnType:"string",pure:!1,examples:['today() // "2024-01-01"']},{name:"dateFormat",category:"date",description:"格式化日期",params:[{name:"date",type:"any",required:!0,description:"日期(时间戳或字符串)"},{name:"format",type:"string",required:!0,description:"格式模板"}],returnType:"string",pure:!0,examples:['dateFormat(now(), "YYYY-MM-DD") // "2024-01-01"']},{name:"dateParse",category:"date",description:"解析日期字符串",params:[{name:"str",type:"string",required:!0,description:"日期字符串"},{name:"format",type:"string",required:!1,description:"格式模板"}],returnType:"number",pure:!0,examples:['dateParse("2024-01-01") // 1704067200000']},{name:"dateAdd",category:"date",description:"日期加减",params:[{name:"date",type:"any",required:!0,description:"日期"},{name:"amount",type:"number",required:!0,description:"数量"},{name:"unit",type:"string",required:!0,description:"单位(day/week/month/year)"}],returnType:"number",pure:!0,examples:['dateAdd(now(), 7, "day") // 一周后']},{name:"dateDiff",category:"date",description:"日期差",params:[{name:"date1",type:"any",required:!0,description:"日期1"},{name:"date2",type:"any",required:!0,description:"日期2"},{name:"unit",type:"string",required:!1,defaultValue:"day",description:"单位"}],returnType:"number",pure:!0,examples:['dateDiff("2024-01-10", "2024-01-01", "day") // 9']}],m=[{name:"if",category:"logic",description:"条件判断",params:[{name:"condition",type:"boolean",required:!0,description:"条件"},{name:"trueValue",type:"any",required:!0,description:"条件为真时的值"},{name:"falseValue",type:"any",required:!0,description:"条件为假时的值"}],returnType:"any",pure:!0,examples:['if(state.count > 0, "有", "无")']},{name:"and",category:"logic",description:"逻辑与",params:[{name:"values",type:"boolean",required:!0,variadic:!0,description:"布尔值列表"}],returnType:"boolean",pure:!0,examples:["and(true, true, false) // false"]},{name:"or",category:"logic",description:"逻辑或",params:[{name:"values",type:"boolean",required:!0,variadic:!0,description:"布尔值列表"}],returnType:"boolean",pure:!0,examples:["or(true, false) // true"]},{name:"not",category:"logic",description:"逻辑非",params:[{name:"value",type:"boolean",required:!0,description:"布尔值"}],returnType:"boolean",pure:!0,examples:["not(true) // false"]},{name:"eq",category:"logic",description:"相等判断",params:[{name:"a",type:"any",required:!0,description:"值1"},{name:"b",type:"any",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["eq(1, 1) // true"]},{name:"ne",category:"logic",description:"不相等判断",params:[{name:"a",type:"any",required:!0,description:"值1"},{name:"b",type:"any",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["ne(1, 2) // true"]},{name:"gt",category:"logic",description:"大于",params:[{name:"a",type:"number",required:!0,description:"值1"},{name:"b",type:"number",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["gt(2, 1) // true"]},{name:"gte",category:"logic",description:"大于等于",params:[{name:"a",type:"number",required:!0,description:"值1"},{name:"b",type:"number",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["gte(2, 2) // true"]},{name:"lt",category:"logic",description:"小于",params:[{name:"a",type:"number",required:!0,description:"值1"},{name:"b",type:"number",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["lt(1, 2) // true"]},{name:"lte",category:"logic",description:"小于等于",params:[{name:"a",type:"number",required:!0,description:"值1"},{name:"b",type:"number",required:!0,description:"值2"}],returnType:"boolean",pure:!0,examples:["lte(2, 2) // true"]}],g=[{name:"default",category:"utility",description:"默认值",params:[{name:"value",type:"any",required:!0,description:"输入值"},{name:"defaultValue",type:"any",required:!0,description:"默认值"}],returnType:"any",pure:!0,examples:['default(state.name, "未知")']},{name:"coalesce",category:"utility",description:"返回第一个非空值",params:[{name:"values",type:"any",required:!0,variadic:!0,description:"值列表"}],returnType:"any",pure:!0,examples:['coalesce(null, undefined, "value") // "value"']},{name:"isEmpty",category:"utility",description:"检查是否为空",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"boolean",pure:!0,examples:['isEmpty("") // true',"isEmpty([]) // true"]},{name:"isNull",category:"utility",description:"检查是否为 null/undefined",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"boolean",pure:!0,examples:["isNull(null) // true"]},{name:"type",category:"utility",description:"获取值类型",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"string",pure:!0,examples:['type([]) // "array"','type({}) // "object"']},{name:"toString",category:"type",description:"转换为字符串",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"string",pure:!0,examples:['toString(123) // "123"']},{name:"toBoolean",category:"type",description:"转换为布尔值",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"boolean",pure:!0,examples:['toBoolean("true") // true',"toBoolean(1) // true"]},{name:"toJSON",category:"utility",description:"转换为 JSON 字符串",params:[{name:"value",type:"any",required:!0,description:"输入值"}],returnType:"string",pure:!0,examples:['toJSON({a: 1}) // "{\\"a\\":1}"']},{name:"fromJSON",category:"utility",description:"解析 JSON 字符串",params:[{name:"str",type:"string",required:!0,description:"JSON 字符串"}],returnType:"any",pure:!0,examples:['fromJSON("{\\"a\\":1}") // {a: 1}']},{name:"get",category:"object",description:"获取嵌套属性",params:[{name:"obj",type:"object",required:!0,description:"输入对象"},{name:"path",type:"string",required:!0,description:"属性路径(点分隔)"},{name:"defaultValue",type:"any",required:!1,description:"默认值"}],returnType:"any",pure:!0,examples:['get(state, "user.name", "未知")']}],y=[{name:"currency",category:"format",description:"格式化货币",params:[{name:"value",type:"number",required:!0,description:"金额"},{name:"symbol",type:"string",required:!1,defaultValue:"¥",description:"货币符号"},{name:"decimals",type:"number",required:!1,defaultValue:2,description:"小数位数"}],returnType:"string",pure:!0,examples:['currency(1234.5) // "¥1,234.50"']},{name:"percent",category:"format",description:"格式化百分比",params:[{name:"value",type:"number",required:!0,description:"数值(0-1)"},{name:"decimals",type:"number",required:!1,defaultValue:0,description:"小数位数"}],returnType:"string",pure:!0,examples:['percent(0.1234) // "12%"']},{name:"number",category:"format",description:"格式化数字(千分位)",params:[{name:"value",type:"number",required:!0,description:"数值"},{name:"decimals",type:"number",required:!1,defaultValue:0,description:"小数位数"}],returnType:"string",pure:!0,examples:['number(1234567) // "1,234,567"']},{name:"pluralize",category:"format",description:"复数形式",params:[{name:"count",type:"number",required:!0,description:"数量"},{name:"singular",type:"string",required:!0,description:"单数形式"},{name:"plural",type:"string",required:!0,description:"复数形式"}],returnType:"string",pure:!0,examples:['pluralize(1, "item", "items") // "1 item"']},{name:"mask",category:"format",description:"掩码处理",params:[{name:"str",type:"string",required:!0,description:"输入字符串"},{name:"keepPrefix",type:"number",required:!1,defaultValue:3,description:"保留前缀"},{name:"keepSuffix",type:"number",required:!1,defaultValue:4,description:"保留后缀"},{name:"maskChar",type:"string",required:!1,defaultValue:"*",description:"掩码字符"}],returnType:"string",pure:!0,examples:['mask("13812345678", 3, 4) // "138****5678"']}],f=[...d,...p,...u,...h,...m,...g,...y],E=f.map(e=>e.name),b={allowedContextPaths:["state","binding","local","props","event"],allowedFunctions:E,maxDepth:10,maxLength:1e3,allowTemplate:!0,allowChaining:!0},v={STATE:"state",BINDING:"binding",LOCAL:"local",PROPS:"props",EVENT:"event"};function S(e,t){return`${e}.${t}`}var I=/^[A-Za-z_][A-Za-z0-9_-]*$/,T=/\b(state|binding|local|props|event)\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\.\d+|\[\d+\])*/g,w=/\b[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\.\d+|\[\d+\])*\b/g,C=new Set(["true","false","null","undefined","NaN","Infinity","typeof","instanceof","new","void","delete","Math","Date","JSON","Array","Object","String","Number","Boolean"]),A=["state","binding","local","props","event"];function N(e){const t=new Set;for(const n of e.matchAll(T))t.add(n[0]);return[...t]}function R(e){const t=new Set;for(const n of e.matchAll(w)){const e=n[0];C.has(e)||A.some(t=>e.startsWith(`${t}.`))||A.includes(e)||t.add(e)}return[...t]}var O=class extends Error{constructor(e,t,n){super(e),this.bareVariables=t,this.expression=n,this.name="TemplateParseError"}},x=(e=>(e.CLAIM="claim",e.SIGNIN="signin",e.LOTTERY="lottery",e.RESERVE="reserve",e.BIND="bind",e.TASK_COMPLETE="task_complete",e.VOTE="vote",e.SHARE="share",e.FORM_SUBMIT="form_submit",e.CUSTOM="custom",e))(x||{});e.ALLOWED_FUNCTION_NAMES=E,e.ALL_BUILTIN_FUNCTIONS=f,e.ARRAY_FUNCTIONS=u,e.ActionType=x,e.AuditAction=l,e.CURRENT_ACTION_SPEC_VERSION="1.0.0",e.CURRENT_COMPONENT_META_VERSION="1.0.0",e.CURRENT_DATA_QUERY_SPEC_VERSION="1.0.0",e.CURRENT_SCHEMA_VERSION="1.0.0",e.DATE_FUNCTIONS=h,e.DEFAULT_EXPRESSION_VALIDATION_CONFIG=b,e.DEPENDENCY_PREFIX=v,e.ErrorCategory=t,e.ErrorCode=n,e.ErrorCodeToHttpStatus=r,e.ErrorMessages=s,e.FORMAT_FUNCTIONS=y,e.LOGIC_FUNCTIONS=m,e.NUMBER_FUNCTIONS=p,e.PROTOCOL_VERSION="1.0.0",e.PageStatus=o,e.PublishChannel=a,e.PublishStatus=c,e.STRING_FUNCTIONS=d,e.TemplateParseError=O,e.UTILITY_FUNCTIONS=g,e.VERSION="1.0.0",e.VersionStatus=i,e.bindingRef=function(e,t,n){if(!I.test(e))throw new Error(`Invalid bindingId: "${e}". Must match pattern [A-Za-z_][A-Za-z0-9_-]* (no dots allowed).`);return{type:"binding",value:`${e}.${t}`,fallback:n,meta:{dependencies:[S(v.BINDING,`${e}.${t}`)]}}},e.createDjvlcError=function(e,t,n){const i=r[e]||500,o=new Error(t||s[e]||"未知错误");return o.name="DjvlcError",o.code=e,o.httpStatus=i,o.details=n,o},e.createExpressionContext=function(e){return{state:{},binding:{},local:{},...e}},e.createLoopLocal=function(e,t,n){return{...n,item:e,index:t}},e.dep=S,e.isDjvlcError=function(e){return e instanceof Error&&"code"in e&&"httpStatus"in e&&"DjvlcError"===e.name},e.localRef=function(e,t){return{type:"local",value:e,fallback:t,meta:{dependencies:[S(v.LOCAL,e)]}}},e.stateRef=function(e,t){return{type:"state",value:e,fallback:t,meta:{dependencies:[S(v.STATE,e)]}}},e.template=function(e,t){const n=function(e,t="strict"){const n=new Set,r=/\$\{([^}]+)\}/g;for(const s of e.matchAll(r)){const e=(s[1]??"").trim();if(!e)continue;const r=N(e);for(const t of r)n.add(t);if("strict"===t){const t=R(e);if(t.length>0)throw new O(`Template variable must use prefix (state./binding./local./props./event.). Found bare variables: ${t.join(", ")} in \${${e}}`,t,e)}}return[...n]}(e,"strict");return{type:"template",value:e,fallback:t,meta:{dependencies:n}}}}},function(){return r||(0,n[a(n)[0]])((r={exports:{}}).exports,r),r.exports}),u=d(p()),h=d(p()),m=class extends Error{constructor(e,t,n,r){super(t||h.ErrorMessages[e]||"Unknown error"),this.name="DjvlcRuntimeError",this.code=e,this.details=n,this.traceId=r,this.timestamp=Date.now()}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,traceId:this.traceId,timestamp:this.timestamp}}},g=class extends m{constructor(e,t,n){super(h.ErrorCode.RESOURCE_PAGE_NOT_FOUND,e,t,n),this.name="PageLoadError"}},y=class extends m{constructor(e,t,n,r=h.ErrorCode.COMPONENT_LOAD_FAILED,s){super(r,n,{...s,componentName:e,componentVersion:t}),this.name="ComponentLoadError",this.componentName=e,this.componentVersion=t}},f=class extends m{constructor(e,t,n,r){super(h.ErrorCode.COMPONENT_INTEGRITY_MISMATCH,`Integrity check failed for ${e}@${t}`,{expectedHash:n,actualHash:r}),this.name="IntegrityError",this.componentName=e,this.componentVersion=t,this.expectedHash=n,this.actualHash=r}},E=class extends m{constructor(e,t,n){super(h.ErrorCode.COMPONENT_BLOCKED,`Component ${e}@${t} is blocked`,{componentName:e,componentVersion:t,reason:n}),this.name="ComponentBlockedError",this.componentName=e,this.componentVersion=t,this.reason=n}},b=class extends m{constructor(e,t,n,r){super(h.ErrorCode.VALIDATION_EXPRESSION_ERROR,t,{...r,expression:e,position:n}),this.name="ExpressionError",this.expression=e,this.position=n}},v=class extends m{constructor(e,t,n=h.ErrorCode.SYSTEM_INTERNAL_ERROR,r,s){super(n,t,{...s,actionType:e,actionId:r}),this.name="ActionError",this.actionType=e,this.actionId=r}},S=class extends m{constructor(e,t,n=h.ErrorCode.SYSTEM_INTERNAL_ERROR,r){super(n,t,{...r,queryId:e}),this.name="QueryError",this.queryId=e}},I=class{constructor(e){this.cache=new Map,this.options={channel:"prod",cache:{enabled:!0,maxAge:300},...e}}async resolve(e,t){var n,r;const s=this.getCacheKey(e,t);if(null==(n=this.options.cache)?void 0:n.enabled){const t=this.cache.get(s);if(t&&this.isCacheValid(t.timestamp))return this.log("debug",`Page ${e} loaded from cache`),t.data}const i=performance.now();try{const n=this.buildResolveUrl(e,t),o=await fetch(n,{method:"GET",headers:this.buildHeaders()});if(!o.ok)throw new g(`Failed to resolve page: ${o.status} ${o.statusText}`,{pageUid:e,status:o.status});const a=await o.json();if(!this.isValidPageResolveResult(a))throw new g("Invalid page resolve response",{pageUid:e});const c=a.data;(null==(r=this.options.cache)?void 0:r.enabled)&&this.cache.set(s,{data:c,timestamp:Date.now()});const l=performance.now()-i;return this.log("info",`Page ${e} resolved in ${l.toFixed(2)}ms`),c}catch(o){if(o instanceof g)throw o;throw new g(`Failed to resolve page: ${o instanceof Error?o.message:"Unknown error"}`,{pageUid:e})}}preconnect(){const e=document.createElement("link");e.rel="preconnect",e.href=this.options.apiBaseUrl,document.head.appendChild(e)}clearCache(e){if(e)for(const t of this.cache.keys())t.startsWith(e)&&this.cache.delete(t);else this.cache.clear()}buildResolveUrl(e,t){const n=new URL(`${this.options.apiBaseUrl}/page/resolve`);return n.searchParams.set("pageUid",e),this.options.channel&&n.searchParams.set("channel",this.options.channel),this.options.previewToken&&n.searchParams.set("previewToken",this.options.previewToken),(null==t?void 0:t.uid)&&n.searchParams.set("uid",t.uid),(null==t?void 0:t.deviceId)&&n.searchParams.set("deviceId",t.deviceId),n.toString()}buildHeaders(){const e={"Content-Type":"application/json",...this.options.headers};return this.options.authToken&&(e.Authorization=`Bearer ${this.options.authToken}`),e}getCacheKey(e,t){const n=[e,this.options.channel];return(null==t?void 0:t.uid)&&n.push(t.uid),(null==t?void 0:t.deviceId)&&n.push(t.deviceId),n.join(":")}isCacheValid(e){var t;const n=1e3*((null==(t=this.options.cache)?void 0:t.maxAge)??300);return Date.now()-e<n}isValidPageResolveResult(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.data||"object"!=typeof t.data)return!1;const n=t.data;return"string"==typeof n.pageUid&&"string"==typeof n.pageVersionId&&void 0!==n.pageJson&&void 0!==n.manifest}log(e,t){this.options.logger&&this.options.logger[e](t)}},T=class{constructor(e){this.loadedComponents=new Map,this.loadingPromises=new Map,this.options={enableSRI:!0,concurrency:4,timeout:3e4,blockedComponents:[],...e},this.blockedSet=new Set(this.options.blockedComponents)}async load(e){const t=this.getComponentKey(e.name,e.version);if(this.isBlocked(e.name,e.version))throw new E(e.name,e.version,"Component is blocked");const n=this.loadedComponents.get(t);if(n)return n;const r=this.loadingPromises.get(t);if(r)return r;const s=this.loadComponent(e);this.loadingPromises.set(t,s);try{const e=await s;return this.loadedComponents.set(t,e),e}finally{this.loadingPromises.delete(t)}}async loadAll(e){const t=new Map,{concurrency:n=4}=this.options,r=e.components;for(let s=0;s<r.length;s+=n){const e=r.slice(s,s+n).map(async e=>{const n=this.getComponentKey(e.name,e.version),r=performance.now();try{const s=await this.load(e);t.set(n,{name:e.name,version:e.version,status:"loaded",component:s.Component,loadTime:performance.now()-r})}catch(s){const i=s instanceof E?"blocked":"failed";if(t.set(n,{name:e.name,version:e.version,status:i,error:s instanceof Error?s.message:"Unknown error",loadTime:performance.now()-r}),"critical"===e.priority)throw s}});await Promise.all(e)}return t}preload(e){e.forEach(e=>{const t=document.createElement("link");t.rel="preload",t.as="script",t.href=this.resolveUrl(e.entry),this.options.enableSRI&&e.integrity&&(t.integrity=e.integrity,t.crossOrigin="anonymous"),document.head.appendChild(t)})}isLoaded(e,t){return this.loadedComponents.has(this.getComponentKey(e,t))}get(e,t){return this.loadedComponents.get(this.getComponentKey(e,t))}isBlocked(e,t){return this.blockedSet.has(`${e}@${t}`)||this.blockedSet.has(e)}updateBlockedList(e){this.blockedSet=new Set(e)}async loadComponent(e){const t=performance.now(),n=this.resolveUrl(e.entry);this.log("debug",`Loading component ${e.name}@${e.version}`);try{const r=await this.fetchWithTimeout(n);if(!r.ok)throw new y(e.name,e.version,`Failed to fetch component: ${r.status} ${r.statusText}`);const s=await r.text();this.options.enableSRI&&e.integrity&&await this.validateIntegrity(e,s);const i=await this.executeScript(s,e),o=performance.now()-t;return this.log("info",`Component ${e.name}@${e.version} loaded in ${o.toFixed(2)}ms`),{name:e.name,version:e.version,Component:i,loadTime:o}}catch(r){if(r instanceof y||r instanceof f||r instanceof E)throw r;throw new y(e.name,e.version,`Failed to load component: ${r instanceof Error?r.message:"Unknown error"}`)}}async fetchWithTimeout(e){const t=new AbortController,n=setTimeout(()=>t.abort(),this.options.timeout);try{return await fetch(e,{signal:t.signal,credentials:"omit"})}finally{clearTimeout(n)}}async validateIntegrity(e,t){if(!e.integrity)return;const[n,r]=e.integrity.split("-");if(!n||!r)throw new f(e.name,e.version,e.integrity,"Invalid format");const s=await crypto.subtle.digest(n.toUpperCase(),(new TextEncoder).encode(t)),i=Array.from(new Uint8Array(s)),o=btoa(String.fromCharCode(...i));if(o!==r)throw new f(e.name,e.version,r,o)}async executeScript(e,t){const n=new Blob([e],{type:"application/javascript"}),r=URL.createObjectURL(n);try{const e=await import(r),n=e.default||e[t.name]||e.Component;if(!n)throw new y(t.name,t.version,"Component module does not export a valid component");return n}finally{URL.revokeObjectURL(r)}}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")?e:`${this.options.cdnBaseUrl}/${e.replace(/^\//,"")}`}getComponentKey(e,t){return`${e}@${t}`}log(e,t){this.options.logger&&this.options.logger[e](t)}},w=class{constructor(e){this.preconnectedHosts=new Set,this.preloadedAssets=new Set,this.options=e}preconnectAll(){[...this.options.cdnHosts,...this.options.apiHosts].forEach(e=>this.preconnect(e))}preconnect(e){if(this.preconnectedHosts.has(e))return;const t=document.createElement("link");t.rel="preconnect",t.href=e.startsWith("http")?e:`https://${e}`,t.crossOrigin="anonymous",document.head.appendChild(t),this.preconnectedHosts.add(e)}dnsPrefetch(e){const t=document.createElement("link");t.rel="dns-prefetch",t.href=e.startsWith("http")?e:`https://${e}`,document.head.appendChild(t)}preloadScript(e,t){if(this.preloadedAssets.has(e))return;const n=document.createElement("link");n.rel="preload",n.as="script",n.href=e,t&&(n.integrity=t,n.crossOrigin="anonymous"),document.head.appendChild(n),this.preloadedAssets.add(e)}preloadStyle(e,t){if(this.preloadedAssets.has(e))return;const n=document.createElement("link");n.rel="preload",n.as="style",n.href=e,t&&(n.integrity=t,n.crossOrigin="anonymous"),document.head.appendChild(n),this.preloadedAssets.add(e)}preloadImage(e){if(this.preloadedAssets.has(e))return;const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t),this.preloadedAssets.add(e)}prefetch(e,t){const n=document.createElement("link");n.rel="prefetch",n.href=e,t&&(n.as=t),document.head.appendChild(n)}loadStylesheet(e,t){return new Promise((n,r)=>{const s=document.createElement("link");s.rel="stylesheet",s.href=e,t&&(s.integrity=t,s.crossOrigin="anonymous"),s.onload=()=>n(),s.onerror=()=>r(new Error(`Failed to load stylesheet: ${e}`)),document.head.appendChild(s)})}loadScript(e,t){return new Promise((n,r)=>{const s=document.createElement("script");s.src=e,s.async=!0,t&&(s.integrity=t,s.crossOrigin="anonymous"),s.onload=()=>n(),s.onerror=()=>r(new Error(`Failed to load script: ${e}`)),document.body.appendChild(s)})}},C=class{constructor(){this.listeners=new Set,this.changeCallbacks=new Set,this.state=this.createInitialState()}getState(){return this.state}getPhase(){return this.state.phase}setPhase(e){this.setState({phase:e})}setPage(e){const t=e.pageJson,n=this.initializePageState(t);e.preloadedData&&Object.assign(n,e.preloadedData),this.setState({page:e,variables:n})}initializePageState(e){const t={};if(e.state&&e.state.fields)for(const[n,r]of Object.entries(e.state.fields))if(r&&"object"==typeof r){const e=r;t[n]=e.initialValue}return t}setError(e){this.setState({phase:"error",error:e})}clearError(){this.state.error&&this.setState({error:null})}getVariable(e){return e.includes(".")?this.getNestedValue(this.state.variables,e):this.state.variables[e]}setVariable(e,t){const n=this.getVariable(e);if(e.includes(".")){const n={...this.state.variables};this.setNestedValue(n,e,t),this.setState({variables:n})}else this.setState({variables:{...this.state.variables,[e]:t}});this.notifyChange({key:e,oldValue:n,newValue:t})}setVariables(e){const t=[];for(const[n,r]of Object.entries(e)){const e=this.getVariable(n);t.push({key:n,oldValue:e,newValue:r})}this.setState({variables:{...this.state.variables,...e}}),t.forEach(e=>this.notifyChange(e))}getQuery(e){return this.state.queries[e]}setQuery(e,t){this.setState({queries:{...this.state.queries,[e]:t}})}clearQuery(e){const{[e]:t,...n}=this.state.queries;this.setState({queries:n})}setComponentStatus(e,t){const n=new Map(this.state.components);n.set(e,t),this.setState({components:n})}getComponentStatus(e){return this.state.components.get(e)}setDestroyed(){this.setState({phase:"destroyed",destroyed:!0})}isDestroyed(){return this.state.destroyed}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}onStateChange(e){return this.changeCallbacks.add(e),()=>{this.changeCallbacks.delete(e)}}reset(){this.state=this.createInitialState(),this.notifyListeners()}getExpressionContext(){var e,t;return{state:this.state.variables,binding:this.state.queries,local:{},context:{pageVersionId:null==(e=this.state.page)?void 0:e.pageVersionId,pageUid:null==(t=this.state.page)?void 0:t.pageUid,phase:this.state.phase,$now:Date.now()}}}setState(e){this.state={...this.state,...e},this.notifyListeners()}notifyListeners(){this.listeners.forEach(e=>{try{e(this.state)}catch(t){}})}notifyChange(e){this.changeCallbacks.forEach(t=>{try{t(e)}catch(n){}})}getNestedValue(e,t){const n=t.split(".");let r=e;for(const s of n){if(null==r)return;r=r[s]}return r}setNestedValue(e,t,n){const r=t.split(".");let s=e;for(let i=0;i<r.length-1;i++){const e=r[i];void 0!==s[e]&&null!==s[e]||(s[e]={}),s=s[e]}s[r[r.length-1]]=n}createInitialState(){return{phase:"idle",page:null,variables:{},queries:{},components:new Map,error:null,destroyed:!1}}},A=class{constructor(e){this.bindings=new Map,this.dependencyGraph=new Map,this.bindingDependencies=new Map,this.options=e}registerBindings(e){for(const t of e)this.registerBinding(t)}registerBinding(e){if(this.bindings.set(e.id,{binding:e,loading:!1,retryCount:0}),e.dependencies)for(const t of e.dependencies)this.dependencyGraph.has(t)||this.dependencyGraph.set(t,new Set),this.dependencyGraph.get(t).add(e.id);this.updateBindingDependencies(e),this.log("debug",`Registered data binding: ${e.id}`)}updateBindingDependencies(e){var t;for(const[n,r]of this.bindings){if(n===e.id)continue;(null==(t=r.binding.dependencies)?void 0:t.includes(e.targetState))&&(this.bindingDependencies.has(e.id)||this.bindingDependencies.set(e.id,new Set),this.bindingDependencies.get(e.id).add(n))}if(e.dependencies)for(const n of e.dependencies)for(const[t,r]of this.bindings)t!==e.id&&r.binding.targetState===n&&(this.bindingDependencies.has(t)||this.bindingDependencies.set(t,new Set),this.bindingDependencies.get(t).add(e.id))}async initializeBindings(e){var t,n;const r=[];for(const o of this.bindings.values())"eager"===o.binding.loadStrategy&&r.push(o.binding);const s=this.topologicalSort(r),i=this.createLoadBatches(s);for(const o of i){const r=await Promise.allSettled(o.map(t=>this.loadBinding(t.id,e))),s=new Map;r.forEach((e,t)=>{const n=o[t].id;"fulfilled"===e.status?s.set(n,{success:!0,data:e.value}):s.set(n,{success:!1,error:e.reason})}),null==(n=(t=this.options).onBatchComplete)||n.call(t,s)}}topologicalSort(e){const t=new Map(e.map(e=>[e.id,e])),n=new Set,r=[],s=e=>{if(!n.has(e.id)){if(n.add(e.id),e.dependencies)for(const r of e.dependencies)for(const[e,i]of t)i.targetState!==r||n.has(e)||s(i);r.push(e)}};for(const i of e)s(i);return r}createLoadBatches(e){const t=[],n=new Set;for(;n.size<e.length;){const r=[];for(const t of e){if(n.has(t.id))continue;let s=!0;if(t.dependencies)for(const r of t.dependencies){for(const t of e)if(t.targetState===r&&!n.has(t.id)){s=!1;break}if(!s)break}s&&r.push(t)}if(0===r.length)for(const t of e)if(!n.has(t.id)){r.push(t),this.log("warn",`Possible circular dependency detected at binding: ${t.id}`);break}r.forEach(e=>n.add(e.id)),r.length>0&&t.push(r)}return t}async loadBinding(e,t,n=!1){var r,s,i;const o=this.bindings.get(e);if(!o)throw new S(e,`Data binding not found: ${e}`);const{binding:a}=o;if(a.condition){if(!this.evaluateCondition(a.condition,t))return void this.log("debug",`Binding ${e} skipped by condition`)}if(!n&&this.isCacheValid(o))return this.log("debug",`Binding ${e} returned from cache`),o.cachedData;if(o.loading)this.log("debug",`Binding ${e} is already loading`);else{o.loading=!0;try{const n=this.resolveParams(a.params||{},t),c=await this.executeWithRetry(a,n),l=a.transform?this.applyTransform(c,a.transform,t):c;return o.cachedData=l,o.lastLoadTime=Date.now(),(null==(r=a.cache)?void 0:r.ttl)&&(o.cacheExpireTime=Date.now()+1e3*a.cache.ttl),o.retryCount=0,this.options.stateSetter.setVariable(a.targetState,l),this.setupAutoRefresh(o,t),null==(i=(s=this.options).onDataLoaded)||i.call(s,e,l),this.log("info",`Binding ${e} loaded successfully`),l}catch(c){throw await this.handleLoadError(o,c,t),c}finally{o.loading=!1}}}async refreshBinding(e,t){await this.loadBinding(e,t,!0)}async refreshAll(e){const t=Array.from(this.bindings.keys()).map(t=>this.loadBinding(t,e,!0));await Promise.allSettled(t)}async onStateChange(e,t){const n=this.dependencyGraph.get(e);if(!n||0===n.size)return;this.log("debug",`State ${e} changed, refreshing dependent bindings`);const r=Array.from(n).map(e=>this.loadBinding(e,t,!0));await Promise.allSettled(r)}async triggerManualLoad(e,t){const n=this.bindings.get(e);if(!n)throw new S(e,`Data binding not found: ${e}`);return"manual"!==n.binding.loadStrategy&&this.log("warn",`Binding ${e} is not manual strategy`),this.loadBinding(e,t,!0)}checkVisibility(e,t,n){const r=this.bindings.get(e);r&&"lazy"===r.binding.loadStrategy&&t&&!r.lastLoadTime&&this.loadBinding(e,n).catch(t=>{this.log("error",`Lazy binding ${e} failed to load`,t)})}destroy(){for(const e of this.bindings.values())e.refreshTimer&&clearInterval(e.refreshTimer);this.bindings.clear(),this.dependencyGraph.clear(),this.log("debug","DataBindingManager destroyed")}async executeWithRetry(e,t){var n,r,s,i,o,a;const c=(null==(r=null==(n=e.onError)?void 0:n.retry)?void 0:r.maxRetries)??0,l=(null==(i=null==(s=e.onError)?void 0:s.retry)?void 0:i.backoffMs)??1e3,d=(null==(a=null==(o=e.onError)?void 0:o.retry)?void 0:a.backoff)??"fixed";let p;for(let h=0;h<=c;h++)try{const n=await this.options.requester.requestData(e.queryVersionId,t);if(!n.success)throw new S(e.queryVersionId,n.message||"Query failed",void 0,{params:t});return n.data}catch(u){if(p=u,this.log("warn",`Query attempt ${h+1}/${c+1} failed:`,u),h<c){const e="exponential"===d?l*Math.pow(2,h):l;await this.delay(e)}}throw p||new Error("Query failed after all retries")}async handleLoadError(e,t,n){var r,s;const{binding:i}=e,o=i.onError;e.retryCount++,void 0!==(null==o?void 0:o.fallbackValue)&&this.options.stateSetter.setVariable(i.targetState,o.fallbackValue),(null==o?void 0:o.showError)&&(null==(s=(r=this.options).onDataError)||s.call(r,i.id,t)),this.log("error",`Binding ${i.id} load failed:`,t)}setupAutoRefresh(e,t){e.refreshTimer&&(clearInterval(e.refreshTimer),e.refreshTimer=void 0);const n=e.binding.refreshInterval;!n||n<=0||(e.refreshTimer=setInterval(()=>{this.loadBinding(e.binding.id,t,!0).catch(t=>{this.log("error",`Auto refresh for ${e.binding.id} failed:`,t)})},1e3*n))}isCacheValid(e){return!(!e.cachedData||!e.lastLoadTime)&&!(e.cacheExpireTime&&Date.now()>e.cacheExpireTime)}resolveParams(e,t){const n={};for(const[r,s]of Object.entries(e))n[r]=this.resolveValue(s,t);return n}resolveValue(e,t){if(null==e)return e;if("object"==typeof e&&!Array.isArray(e)){const n=e;if("expression"===n.type||"binding"===n.type)return this.options.expressionEngine.evaluateWithFallback(n.expression,t,n.fallback);const r={};for(const[e,s]of Object.entries(n))r[e]=this.resolveValue(s,t);return r}return"string"==typeof e&&e.includes("${")?this.options.expressionEngine.evaluateTemplate(e,t):e}evaluateCondition(e,t){const n=void 0===e.fallback||e.fallback,r=this.options.expressionEngine.evaluateWithFallback(e.value,t,n);return Boolean(r)}applyTransform(e,t,n){const r={...n,local:{...n.local||{},$data:e,$response:e}},s=void 0!==t.fallback?t.fallback:e;return this.options.expressionEngine.evaluateWithFallback(t.value,r,s)}delay(e){return new Promise(t=>setTimeout(t,e))}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},N=class{constructor(e={}){this.handlers=new Map,this.options={debug:!1,maxListeners:100,...e}}emit(e){this.options.debug&&this.log("debug",`Event emitted: ${e.type}`,e);const t=this.handlers.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(n){this.log("error",`Error in event handler for ${e.type}:`,n)}})}on(e,t){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.size>=(this.options.maxListeners??100)&&this.log("warn",`Max listeners (${this.options.maxListeners}) reached for event: ${e}`),n.add(t),()=>{null==n||n.delete(t),0===(null==n?void 0:n.size)&&this.handlers.delete(e)}}off(e,t){const n=this.handlers.get(e);n&&(n.delete(t),0===n.size&&this.handlers.delete(e))}once(e,t){const n=this.on(e,e=>{n(),t(e)});return n}clear(e){e?this.handlers.delete(e):this.handlers.clear()}listenerCount(e){var t;return(null==(t=this.handlers.get(e))?void 0:t.size)??0}static createEvent(e,t,n){return{type:e,data:t,timestamp:Date.now(),traceId:n}}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},R=class e{constructor(e){this.debounceTimers=new Map,this.throttleTimers=new Map,this.options=e}async handleEvent(e,t,n){if(e.condition){if(!this.evaluateCondition(e.condition,n,t))return void this.log("debug",`Handler ${e.id} skipped by condition`)}if(e.throttle&&e.throttle>0&&!this.throttle(e.id,e.throttle))return void this.log("debug",`Handler ${e.id} throttled`);e.debounce&&e.debounce>0&&await this.debounce(e.id,e.debounce);const r={$event:t,$prevResult:void 0,$results:{}};await this.executeActionChain(e.actions,n,r)}async executeActionChain(e,t,n){const r=[];for(let s=0;s<e.length;s++){const i=e[s];if(i.condition){const e=this.buildActionContext(t,n);if(!this.evaluateCondition(i.condition,e,n.$event)){this.log("debug",`Action ${i.id||s} skipped by condition`);continue}}const o=this.executeSingleAction(i,t,n);i.async?r.push(o):await o}r.length>0&&await Promise.allSettled(r)}async executeSingleAction(e,t,n){var r,s,i,o,a,c;const l=e.id||e.alias||e.builtinAction||e.actionDefinitionVersionId||"unknown";e.silent||this.options.executor.showLoading();try{const a=this.buildActionContext(t,n),c=this.resolveParams(e.params||{},a);null==(s=(r=this.options).onActionStart)||s.call(r,e,c);const d=await this.executeWithRetry(e,c);n.$prevResult=d,e.id&&(n.$results[e.id]=d),null==(o=(i=this.options).onActionComplete)||o.call(i,e,{success:!0,data:d}),this.log("debug",`Action ${l} completed successfully`),e.onSuccess&&e.onSuccess.length>0&&await this.executeActionChain(e.onSuccess,t,n)}catch(d){this.log("error",`Action ${l} failed:`,d),null==(c=(a=this.options).onActionComplete)||c.call(a,e,{success:!1,error:d}),e.onError&&e.onError.length>0&&await this.executeActionChain(e.onError,t,{...n,$prevResult:{error:d.message}})}finally{e.silent||this.options.executor.hideLoading(),e.onFinally&&e.onFinally.length>0&&await this.executeActionChain(e.onFinally,t,n)}}async executeWithRetry(e,t){var n,r,s,i,o;const a=(null==(r=null==(n=e.policy)?void 0:n.retry)?void 0:r.maxAttempts)??1,c=(null==(i=null==(s=e.policy)?void 0:s.retry)?void 0:i.backoffMs)??1e3,l=null==(o=e.policy)?void 0:o.timeoutMs;let d;for(let u=1;u<=a;u++)try{let n;if(e.builtinAction)n=this.executeBuiltinAction(e.builtinAction,t);else{if(!e.actionDefinitionVersionId)throw new v("unknown","Action must specify builtinAction or actionDefinitionVersionId");n=this.executeCustomAction(e.actionDefinitionVersionId,t)}return l&&(n=this.withTimeout(n,l)),await n}catch(p){d=p,this.log("warn",`Action attempt ${u}/${a} failed:`,p),u<a&&await this.delay(c*u)}throw d||new Error("Action failed after all retries")}async executeBuiltinAction(e,t){switch(e){case"setState":return this.options.executor.setState(t.key,t.value),{success:!0};case"navigate":return this.options.executor.navigate({to:t.to??t.url,type:t.replace?"replace":t.external?"external":"push",params:t.params,query:t.query,newWindow:t.newWindow??t.newTab}),{success:!0};case"openDialog":return await this.options.executor.openDialog({type:t.type,content:t.content,title:t.title});case"closeDialog":return this.options.executor.closeDialog(t.dialogId),{success:!0};case"showToast":return this.options.executor.showToast({message:t.message,type:t.type,duration:t.duration}),{success:!0};case"showLoading":return this.options.executor.showLoading(t.message),{success:!0};case"hideLoading":return this.options.executor.hideLoading(),{success:!0};case"refreshData":return await this.options.executor.refreshData(t.queryId),{success:!0};case"track":return this.options.executor.track({eventName:t.eventName,params:t.params}),{success:!0};default:throw new v(e,`Unknown builtin action: ${e}`)}}async executeCustomAction(e,t){const n=e.split("@")[0],r=await this.options.executor.executeAction(n,{...t,actionDefinitionVersionId:e});if(!r.success)throw new v(n,r.errorMessage||"Action execution failed",void 0,e,{errorCode:r.errorCode});return r.data}resolveParams(e,t){const n={};for(const[r,s]of Object.entries(e))n[r]=this.resolveValue(s,t);return n}resolveValue(t,n){if(null==t)return t;if("string"==typeof t){if(t.startsWith("${")&&t.endsWith("}")){const e=t.slice(2,-1);return this.options.expressionEngine.evaluateWithFallback(e,n,t)}return t.includes("${")?this.options.expressionEngine.evaluateTemplate(t,n):t}if("number"==typeof t||"boolean"==typeof t)return t;if(Array.isArray(t))return t.map(e=>this.resolveValue(e,n));if("object"==typeof t){const r=t;if("string"==typeof r.type&&e.EXPRESSION_TYPES.includes(r.type)&&"string"==typeof r.value){const e=r;return this.options.expressionEngine.evaluateWithFallback(e.value,n,e.fallback)}const s={};for(const[e,t]of Object.entries(r))s[e]=this.resolveValue(t,n);return s}return t}evaluateCondition(e,t,n){const r={...t,local:{...t.local||{},$event:n}},s=void 0===e.fallback||e.fallback,i=this.options.expressionEngine.evaluateWithFallback(e.value,r,s);return Boolean(i)}buildActionContext(e,t){return{...e,local:{...e.local||{},$event:t.$event,$prevResult:t.$prevResult,$results:t.$results}}}withTimeout(e,t){return new Promise((n,r)=>{const s=setTimeout(()=>{r(new Error(`Action timed out after ${t}ms`))},t);e.then(e=>{clearTimeout(s),n(e)}).catch(e=>{clearTimeout(s),r(e)})})}debounce(e,t){return new Promise(n=>{const r=this.debounceTimers.get(e);r&&clearTimeout(r);const s=setTimeout(()=>{this.debounceTimers.delete(e),n()},t);this.debounceTimers.set(e,s)})}throttle(e,t){const n=Date.now();return!(n-(this.throttleTimers.get(e)??0)<t)&&(this.throttleTimers.set(e,n),!0)}delay(e){return new Promise(t=>setTimeout(t,e))}destroy(){this.debounceTimers.forEach(e=>clearTimeout(e)),this.debounceTimers.clear(),this.throttleTimers.clear()}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}};R.EXPRESSION_TYPES=["state","binding","local","template","computed"];var O=R,x=class{constructor(e){this.pos=0,this.tokens=[],this.input=e}tokenize(){for(this.pos=0,this.tokens=[];this.pos<this.input.length&&(this.skipWhitespace(),!(this.pos>=this.input.length));){const e=this.readToken();e&&this.tokens.push(e)}return this.tokens.push({type:"EOF",value:null,start:this.input.length,end:this.input.length}),this.tokens}readToken(){const e=this.input[this.pos],t=this.pos;if(this.isDigit(e)||"-"===e&&this.isDigit(this.peek(1)))return this.readNumber();if('"'===e||"'"===e)return this.readString(e);if(this.isIdentifierStart(e))return this.readIdentifier();const n=this.readOperator();if(n)return n;switch(e){case".":return this.pos++,{type:"DOT",value:".",start:t,end:this.pos};case"[":return this.pos++,{type:"LBRACKET",value:"[",start:t,end:this.pos};case"]":return this.pos++,{type:"RBRACKET",value:"]",start:t,end:this.pos};case"(":return this.pos++,{type:"LPAREN",value:"(",start:t,end:this.pos};case")":return this.pos++,{type:"RPAREN",value:")",start:t,end:this.pos};case",":return this.pos++,{type:"COMMA",value:",",start:t,end:this.pos};case"?":return this.pos++,{type:"QUESTION",value:"?",start:t,end:this.pos};case":":return this.pos++,{type:"COLON",value:":",start:t,end:this.pos}}throw new Error(`Unexpected character '${e}' at position ${this.pos}`)}readNumber(){const e=this.pos;let t="";for("-"===this.input[this.pos]&&(t+="-",this.pos++);this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;if("."===this.input[this.pos]&&this.isDigit(this.peek(1)))for(t+=".",this.pos++;this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return{type:"NUMBER",value:parseFloat(t),start:e,end:this.pos}}readString(e){const t=this.pos;this.pos++;let n="";for(;this.pos<this.input.length&&this.input[this.pos]!==e;){if("\\"===this.input[this.pos]){this.pos++;const e=this.input[this.pos];switch(e){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case'"':n+='"';break;case"'":n+="'";break;default:n+=e}}else n+=this.input[this.pos];this.pos++}if(this.input[this.pos]!==e)throw new Error(`Unterminated string at position ${t}`);return this.pos++,{type:"STRING",value:n,start:t,end:this.pos}}readIdentifier(){const e=this.pos;let t="";for(;this.pos<this.input.length&&this.isIdentifierChar(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return"true"===t?{type:"BOOLEAN",value:!0,start:e,end:this.pos}:"false"===t?{type:"BOOLEAN",value:!1,start:e,end:this.pos}:"null"===t?{type:"NULL",value:null,start:e,end:this.pos}:{type:"IDENTIFIER",value:t,start:e,end:this.pos}}readOperator(){const e=this.pos,t=this.input.slice(this.pos,this.pos+2),n=this.input[this.pos];if(["==","!=",">=","<=","&&","||","??"].includes(t))return this.pos+=2,{type:"OPERATOR",value:t,start:e,end:this.pos};return["+","-","*","/","%",">","<","!"].includes(n)?(this.pos++,{type:"OPERATOR",value:n,start:e,end:this.pos}):null}skipWhitespace(){for(;this.pos<this.input.length&&/\s/.test(this.input[this.pos]);)this.pos++}isDigit(e){return/[0-9]/.test(e)}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierChar(e){return/[a-zA-Z0-9_$]/.test(e)}peek(e=1){return this.input[this.pos+e]||""}},_=d(p()),D={"||":1,"??":1,"&&":2,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},L=class{constructor(e){this.pos=0,this.tokens=e}parse(){const e=this.parseExpression();if("EOF"!==this.current().type)throw new Error(`Unexpected token '${this.current().value}' at position ${this.current().start}`);return e}parseExpression(){return this.parseTernary()}parseTernary(){const e=this.parseBinary(0);if("QUESTION"===this.current().type){this.advance();const t=this.parseExpression();this.expect("COLON");return{type:"conditional",test:e,consequent:t,alternate:this.parseExpression(),raw:void 0}}return e}parseBinary(e){let t=this.parseUnary();for(;;){const n=this.current();if("OPERATOR"!==n.type)break;const r=D[n.value];if(void 0===r||r<e)break;this.advance();const s=this.parseBinary(r+1);t={type:"binary",operator:n.value,left:t,right:s,raw:void 0}}return t}parseUnary(){const e=this.current();if("OPERATOR"===e.type&&("!"===e.value||"-"===e.value)){this.advance();const t=this.parseUnary();return{type:"unary",operator:e.value,argument:t,raw:void 0}}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;){const t=this.current();if("DOT"===t.type){this.advance();e={type:"member",object:e,property:this.expect("IDENTIFIER").value,computed:!1,raw:void 0}}else if("LBRACKET"===t.type){this.advance();const t=this.parseExpression();this.expect("RBRACKET"),e={type:"member",object:e,property:t,computed:!0,raw:void 0}}else{if("LPAREN"!==t.type||"identifier"!==e.type)break;{const n=e.name;if(!_.ALLOWED_FUNCTION_NAMES.includes(n))throw new Error(`Unknown function '${n}' at position ${t.start}`);this.advance();const r=this.parseArguments();this.expect("RPAREN"),e={type:"call",callee:n,arguments:r,raw:void 0}}}}return e}parsePrimary(){const e=this.current();if("NUMBER"===e.type||"STRING"===e.type||"BOOLEAN"===e.type||"NULL"===e.type)return this.advance(),{type:"literal",value:e.value,start:e.start,end:e.end,raw:void 0};if("IDENTIFIER"===e.type)return this.advance(),{type:"identifier",name:e.value,start:e.start,end:e.end,raw:void 0};if("LBRACKET"===e.type)return this.parseArray();if("LPAREN"===e.type){this.advance();const e=this.parseExpression();return this.expect("RPAREN"),e}throw new Error(`Unexpected token '${e.value}' at position ${e.start}`)}parseArray(){const e=this.current().start;this.advance();const t=[];for(;"RBRACKET"!==this.current().type&&(t.push(this.parseExpression()),"COMMA"===this.current().type);)this.advance();const n=this.current().end;return this.expect("RBRACKET"),{type:"array",elements:t,start:e,end:n,raw:void 0}}parseArguments(){const e=[];if("RPAREN"!==this.current().type)for(e.push(this.parseExpression());"COMMA"===this.current().type;)this.advance(),e.push(this.parseExpression());return e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(e){const t=this.current();if(t.type!==e)throw new Error(`Expected '${e}' but got '${t.type}' at position ${t.start}`);return this.advance()}},M={len:e=>"string"==typeof e||Array.isArray(e)?e.length:0,trim:e=>String(e??"").trim(),upper:e=>String(e??"").toUpperCase(),lower:e=>String(e??"").toLowerCase(),substr:(e,t,n)=>{const r=String(e??""),s=Number(t)||0,i=void 0!==n?Number(n):void 0;return r.substring(s,void 0!==i?s+i:void 0)},concat:(...e)=>e.map(e=>String(e??"")).join(""),replace:(e,t,n)=>String(e??"").split(String(t)).join(String(n)),split:(e,t)=>String(e??"").split(String(t)),join:(e,t)=>Array.isArray(e)?e.join(void 0!==t?String(t):","):"",startsWith:(e,t)=>String(e??"").startsWith(String(t)),endsWith:(e,t)=>String(e??"").endsWith(String(t)),contains:(e,t)=>String(e??"").includes(String(t)),toNumber:e=>{const t=Number(e);return isNaN(t)?0:t},toString:e=>String(e??""),toInt:e=>Math.trunc(Number(e)||0),toFloat:e=>parseFloat(String(e))||0,round:(e,t)=>{const n=Number(e)||0,r=Number(t)||0,s=Math.pow(10,r);return Math.round(n*s)/s},floor:e=>Math.floor(Number(e)||0),ceil:e=>Math.ceil(Number(e)||0),abs:e=>Math.abs(Number(e)||0),min:(...e)=>{const t=e.map(e=>Number(e)).filter(e=>!isNaN(e));return t.length>0?Math.min(...t):0},max:(...e)=>{const t=e.map(e=>Number(e)).filter(e=>!isNaN(e));return t.length>0?Math.max(...t):0},sum:e=>Array.isArray(e)?e.reduce((e,t)=>e+(Number(t)||0),0):0,avg:e=>{if(!Array.isArray(e)||0===e.length)return 0;return e.reduce((e,t)=>e+(Number(t)||0),0)/e.length},random:()=>Math.random(),randomInt:(e,t)=>{const n=Math.ceil(Number(e)||0),r=Math.floor(Number(t)||100);return Math.floor(Math.random()*(r-n+1))+n},now:()=>Date.now(),today:()=>(new Date).toISOString().split("T")[0],dateFormat:(e,t)=>{const n=new Date(Number(e)||Date.now()),r=e=>e.toString().padStart(2,"0");return String(t||"YYYY-MM-DD").replace("YYYY",n.getFullYear().toString()).replace("MM",r(n.getMonth()+1)).replace("DD",r(n.getDate())).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},dateParse:e=>new Date(String(e)).getTime(),year:e=>new Date(Number(e)||Date.now()).getFullYear(),month:e=>new Date(Number(e)||Date.now()).getMonth()+1,day:e=>new Date(Number(e)||Date.now()).getDate(),addDays:(e,t)=>{const n=new Date(Number(e)||Date.now());return n.setDate(n.getDate()+(Number(t)||0)),n.getTime()},diffDays:(e,t)=>{const n=new Date(Number(e)||Date.now()),r=new Date(Number(t)||Date.now()),s=Math.abs(r.getTime()-n.getTime());return Math.floor(s/864e5)},isNull:e=>null==e,isUndefined:e=>void 0===e,isEmpty:e=>null==e||("string"==typeof e||Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length),isArray:e=>Array.isArray(e),isObject:e=>null!==e&&"object"==typeof e&&!Array.isArray(e),isString:e=>"string"==typeof e,isNumber:e=>"number"==typeof e&&!isNaN(e),isBoolean:e=>"boolean"==typeof e,typeOf:e=>null===e?"null":Array.isArray(e)?"array":typeof e,default:(e,t)=>e??t,coalesce:(...e)=>{for(const t of e)if(null!=t)return t;return null},ifElse:(e,t,n)=>e?t:n,first:e=>{if(Array.isArray(e))return e[0]},last:e=>{if(Array.isArray(e))return e[e.length-1]},at:(e,t)=>{if(Array.isArray(e))return e[Number(t)||0]},slice:(e,t,n)=>Array.isArray(e)?e.slice(Number(t)||0,void 0!==n?Number(n):void 0):[],includes:(e,t)=>!!Array.isArray(e)&&e.includes(t),indexOf:(e,t)=>Array.isArray(e)?e.indexOf(t):-1,reverse:e=>Array.isArray(e)?[...e].reverse():[],sort:e=>Array.isArray(e)?[...e].sort():[],unique:e=>Array.isArray(e)?[...new Set(e)]:[],flatten:e=>Array.isArray(e)?e.flat():[],count:e=>Array.isArray(e)?e.length:0,get:(e,t,n)=>{if(null==e)return n;const r=String(t).split(".");let s=e;for(const i of r){if(null==s)return n;s=s[i]}return s??n},keys:e=>"object"!=typeof e||null===e?[]:Object.keys(e),values:e=>"object"!=typeof e||null===e?[]:Object.values(e),entries:e=>"object"!=typeof e||null===e?[]:Object.entries(e),has:(e,t)=>"object"==typeof e&&null!==e&&String(t)in e,merge:(...e)=>{const t={};for(const n of e)"object"==typeof n&&null!==n&&Object.assign(t,n);return t},and:(...e)=>e.every(e=>Boolean(e)),or:(...e)=>e.some(e=>Boolean(e)),not:e=>!e,eq:(e,t)=>e===t,ne:(e,t)=>e!==t,gt:(e,t)=>Number(e)>Number(t),gte:(e,t)=>Number(e)>=Number(t),lt:(e,t)=>Number(e)<Number(t),lte:(e,t)=>Number(e)<=Number(t),between:(e,t,n)=>{const r=Number(e);return r>=Number(t)&&r<=Number(n)},formatNumber:(e,t)=>{const n=Number(e)||0,r=Number(t)??0;return n.toLocaleString(void 0,{minimumFractionDigits:r,maximumFractionDigits:r})},formatCurrency:(e,t)=>{const n=Number(e)||0,r=String(t||"CNY");return n.toLocaleString("zh-CN",{style:"currency",currency:r})},formatPercent:(e,t)=>{const n=Number(e)||0,r=Number(t)??0;return(100*n).toFixed(r)+"%"},currency:(e,t,n)=>{const r=Number(e)||0,s=String(t??"¥"),i=Number(n)??2;return`${s}${r.toLocaleString(void 0,{minimumFractionDigits:i,maximumFractionDigits:i})}`},percent:(e,t)=>{const n=Number(e)||0,r=Number(t)??0;return(100*n).toFixed(r)+"%"},number:(e,t)=>{const n=Number(e)||0,r=Number(t)??0;return n.toLocaleString(void 0,{minimumFractionDigits:r,maximumFractionDigits:r})},pluralize:(e,t,n)=>{const r=Number(e)||0;return`${r} ${String(1===r?t:n)}`},mask:(e,t,n,r)=>{const s=String(e??""),i=Number(t)||3,o=Number(n)||4,a=String(r??"*");if(s.length<=i+o)return s;const c=s.slice(0,i),l=s.slice(-o);return c+a.repeat(s.length-i-o)+l},jsonParse:e=>{try{return JSON.parse(String(e))}catch{return null}},jsonStringify:e=>JSON.stringify(e),toJSON:e=>JSON.stringify(e),fromJSON:e=>{try{return JSON.parse(String(e))}catch{return null}},clamp:(e,t,n)=>{const r=Number(e)||0,s=Number(t)||0,i=Number(n)||100;return Math.min(Math.max(r,s),i)},length:e=>Array.isArray(e)||"string"==typeof e?e.length:0,average:e=>{if(!Array.isArray(e)||0===e.length)return 0;return e.reduce((e,t)=>e+(Number(t)||0),0)/e.length},dateAdd:(e,t,n)=>{const r=new Date(Number(e)||Date.now()),s=Number(t)||0;switch(String(n??"day").toLowerCase()){case"year":case"years":r.setFullYear(r.getFullYear()+s);break;case"month":case"months":r.setMonth(r.getMonth()+s);break;case"week":case"weeks":r.setDate(r.getDate()+7*s);break;case"day":case"days":default:r.setDate(r.getDate()+s);break;case"hour":case"hours":r.setHours(r.getHours()+s);break;case"minute":case"minutes":r.setMinutes(r.getMinutes()+s)}return r.getTime()},dateDiff:(e,t,n)=>{const r=new Date(Number(e)||Date.now()),s=new Date(Number(t)||Date.now()).getTime()-r.getTime();switch(String(n??"day").toLowerCase()){case"year":case"years":return Math.floor(s/31536e6);case"month":case"months":return Math.floor(s/2592e6);case"week":case"weeks":return Math.floor(s/6048e5);case"day":case"days":default:return Math.floor(s/864e5);case"hour":case"hours":return Math.floor(s/36e5);case"minute":case"minutes":return Math.floor(s/6e4)}},$if:(e,t,n)=>e?t:n,toBoolean:e=>"string"==typeof e?"false"!==e.toLowerCase()&&"0"!==e&&""!==e:Boolean(e),substring:(e,t,n)=>{const r=String(e??""),s=Number(t)||0,i=void 0!==n?Number(n):void 0;return r.substring(s,i)},padStart:(e,t,n)=>{const r=String(e??""),s=Number(t)||0,i=String(n??" ");return r.padStart(s,i)},padEnd:(e,t,n)=>{const r=String(e??""),s=Number(t)||0,i=String(n??" ");return r.padEnd(s,i)},repeat:(e,t)=>{const n=String(e??""),r=Math.max(0,Math.floor(Number(t)||0));return n.repeat(r)}},k=class{constructor(e={}){this.depth=0,this.startTime=0,this.options={maxDepth:100,timeout:1e3,debug:!1,...e}}evaluate(e,t){this.depth=0,this.startTime=Date.now();try{return{value:this.evaluateNode(e,t)}}catch(n){return{value:void 0,error:n instanceof Error?n:new Error(String(n))}}}evaluateNode(e,t){switch(this.checkLimits(),e.type){case"literal":return this.evaluateLiteral(e);case"identifier":return this.evaluateIdentifier(e,t);case"member":return this.evaluateMember(e,t);case"call":return this.evaluateCall(e,t);case"binary":return this.evaluateBinary(e,t);case"unary":return this.evaluateUnary(e,t);case"conditional":return this.evaluateConditional(e,t);case"array":return this.evaluateArray(e,t);default:throw new b("",`Unknown node type: ${e.type}`)}}evaluateLiteral(e){return e.value}evaluateIdentifier(e,t){var n,r;const s=e.name;switch(s){case"state":return t.state;case"binding":case"query":return t.binding;case"local":return t.local;case"props":return t.props;case"event":return t.event;case"item":return null==(n=t.local)?void 0:n.item;case"index":return null==(r=t.local)?void 0:r.index;default:if(t.local&&s in t.local)return t.local[s];throw new b("",`Unknown variable '${s}'. Available: state, binding, local, props, event`)}}evaluateMember(e,t){const n=this.evaluateNode(e.object,t);if(null==n)return;let r;if(e.computed){r=this.evaluateNode(e.property,t)}else r=e.property;return"object"==typeof n&&null!==n?n[r]:void 0}evaluateCall(e,t){const n=M[e.callee];if(!n)throw new b("",`Unknown function '${e.callee}'`);return n(...e.arguments.map(e=>this.evaluateNode(e,t)))}evaluateBinary(e,t){const n=e.operator;if("&&"===n){const n=this.evaluateNode(e.left,t);return n?this.evaluateNode(e.right,t):n}if("||"===n){const n=this.evaluateNode(e.left,t);return n||this.evaluateNode(e.right,t)}if("??"===n){const n=this.evaluateNode(e.left,t);return null!=n?n:this.evaluateNode(e.right,t)}const r=this.evaluateNode(e.left,t),s=this.evaluateNode(e.right,t);switch(n){case"+":return"string"==typeof r||"string"==typeof s?String(r)+String(s):r+s;case"-":return r-s;case"*":return r*s;case"/":return r/s;case"%":return r%s;case"==":return r===s;case"!=":return r!==s;case"<":return r<s;case">":return r>s;case"<=":return r<=s;case">=":return r>=s;default:throw new b("",`Unknown operator '${n}'`)}}evaluateUnary(e,t){const n=this.evaluateNode(e.argument,t);switch(e.operator){case"!":return!n;case"-":return-n;default:throw new b("",`Unknown unary operator '${e.operator}'`)}}evaluateConditional(e,t){return this.evaluateNode(e.test,t)?this.evaluateNode(e.consequent,t):this.evaluateNode(e.alternate,t)}evaluateArray(e,t){return e.elements.map(e=>this.evaluateNode(e,t))}checkLimits(){if(this.depth++,this.depth>(this.options.maxDepth??100))throw new b("","Maximum recursion depth exceeded");if(Date.now()-this.startTime>(this.options.timeout??1e3))throw new b("","Expression evaluation timeout")}},P=class{constructor(e={}){this.astCache=new Map,this.options={cacheAST:!0,maxCacheSize:1e3,...e},this.evaluator=new k(e)}evaluate(e,t){try{const n=this.parse(e);return this.evaluator.evaluate(n,t)}catch(n){return{value:void 0,error:n instanceof Error?n:new Error(String(n))}}}evaluateWithFallback(e,t,n){const r="string"==typeof e?e:e.value,s="object"==typeof e&&void 0!==e.fallback?e.fallback:n,i=this.evaluate(r,t);return i.error?(this.log("warn",`Expression evaluation failed: ${i.error.message}`,r),s):i.value}evaluateTemplate(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,n)=>{const r=this.evaluate(n.trim(),t);return r.error?(this.log("warn",`Template expression failed: ${r.error.message}`,n),""):String(r.value??"")})}parse(e){if(this.options.cacheAST){const t=this.astCache.get(e);if(t)return t}try{const t=new x(e).tokenize(),n=new L(t).parse();if(this.options.cacheAST){if(this.astCache.size>=(this.options.maxCacheSize??1e3)){Array.from(this.astCache.keys()).slice(0,Math.floor(this.astCache.size/2)).forEach(e=>this.astCache.delete(e))}this.astCache.set(e,n)}return n}catch(t){throw new b(e,t instanceof Error?t.message:"Parse error")}}validate(e){const t=[],n=[],r=[],s=[];try{const t=this.parse(e);return this.collectReferences(t,r,s),{valid:!0,errors:[],warnings:n,referencedPaths:r,usedFunctions:s}}catch(i){return t.push({type:"invalid_syntax",message:i instanceof Error?i.message:"Parse error"}),{valid:!1,errors:t,warnings:n,referencedPaths:r,usedFunctions:s}}}clearCache(){this.astCache.clear()}collectReferences(e,t,n){switch(e.type){case"identifier":t.push(e.name);break;case"member":{const n=this.buildMemberPath(e);n&&t.push(n);break}case"call":n.push(e.callee),e.arguments.forEach(e=>this.collectReferences(e,t,n));break;case"binary":this.collectReferences(e.left,t,n),this.collectReferences(e.right,t,n);break;case"unary":this.collectReferences(e.argument,t,n);break;case"conditional":this.collectReferences(e.test,t,n),this.collectReferences(e.consequent,t,n),this.collectReferences(e.alternate,t,n);break;case"array":e.elements.forEach(e=>this.collectReferences(e,t,n))}}buildMemberPath(e){if("identifier"===e.type)return e.name;if("member"===e.type&&!e.computed){const t=this.buildMemberPath(e.object);if(t)return`${t}.${e.property}`}return null}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},U=class{constructor(e){this.loadingCount=0,this.loadingElement=null,this.clipboard={write:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch(t){return this.log("error","Clipboard write failed:",t),this.fallbackCopy(e)}},read:async()=>{try{return await navigator.clipboard.readText()}catch(e){return this.log("error","Clipboard read failed:",e),null}}},this.storage={get:e=>{const t=`${this.storageNamespace}:${e}`,n=localStorage.getItem(t);if(!n)return null;try{const e=JSON.parse(n);return e.expires&&Date.now()>e.expires?(localStorage.removeItem(t),null):e.value}catch{return null}},set:(e,t,n)=>{const r=`${this.storageNamespace}:${e}`,s={value:t,expires:(null==n?void 0:n.ttlSeconds)?Date.now()+1e3*n.ttlSeconds:void 0};("session"===(null==n?void 0:n.level)?sessionStorage:localStorage).setItem(r,JSON.stringify(s))},remove:e=>{const t=`${this.storageNamespace}:${e}`;localStorage.removeItem(t),sessionStorage.removeItem(t)},clear:()=>{const e=`${this.storageNamespace}:`;for(let t=localStorage.length-1;t>=0;t--){const n=localStorage.key(t);(null==n?void 0:n.startsWith(e))&&localStorage.removeItem(n)}for(let t=sessionStorage.length-1;t>=0;t--){const n=sessionStorage.key(t);(null==n?void 0:n.startsWith(e))&&sessionStorage.removeItem(n)}}},this.options=e,this.storageNamespace=`djvlc:${e.context.appId}`}async navigate(e){this.log("debug","Navigate:",e),this.track({eventName:"djvlc_navigate",params:{to:e.to,type:e.type},type:"click"});let t=e.to;if(e.query){const n=new URLSearchParams(e.query);t+=(t.includes("?")?"&":"?")+n.toString()}switch(e.type){case"external":e.newWindow?window.open(t,"_blank","noopener,noreferrer"):window.location.href=t;break;case"replace":window.location.replace(t);break;default:e.newWindow?window.open(t,"_blank"):window.location.href=t}}track(e){this.log("debug","Track event:",e);const t=this.options.context;fetch(`${this.options.apiBaseUrl}/track`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({eventName:e.eventName,params:e.params,type:e.type||"custom",timestamp:Date.now(),context:{pageVersionId:t.pageVersionId,runtimeVersion:t.runtimeVersion,userId:t.userId,deviceId:t.deviceId,channel:t.channel,appId:t.appId,env:t.env}}),keepalive:!0}).catch(e=>{this.log("warn","Track failed:",e)})}async requestData(e,t){this.log("debug",`Requesting data: ${e}`,t);const n=performance.now(),r=this.options.context;try{const s=await fetch(`${this.options.apiBaseUrl}/data/query`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({queryVersionId:e,params:t||{},context:{pageVersionId:r.pageVersionId,uid:r.userId,deviceId:r.deviceId}})});if(!s.ok){const e=await s.text();throw new Error(`HTTP ${s.status}: ${e||s.statusText}`)}const i=await s.json(),o=performance.now()-n;if(this.log("debug",`Data query completed in ${o.toFixed(2)}ms`),!i.success)throw new Error(i.message||i.errorMessage||"Query failed");return this.options.stateManager.setQuery(e,i.data),i.data}catch(s){const t=performance.now()-n;throw this.log("error",`Data query failed: ${e} (${t.toFixed(2)}ms)`,s),s}}async executeAction(e,t={}){this.log("debug",`Executing action: ${e}`,t);const n=performance.now(),r=this.options.context,s=this.generateIdempotencyKey(e,t);this.track({eventName:"djvlc_action_start",params:{actionType:e,idempotencyKey:s},type:"custom"});try{const i=await fetch(`${this.options.apiBaseUrl}/actions/execute`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({actionType:e,params:t||{},context:{pageVersionId:r.pageVersionId,uid:r.userId,deviceId:r.deviceId,channel:r.channel,appId:r.appId},idempotencyKey:s})});if(!i.ok){const t=await i.text(),r=performance.now()-n;return this.log("error",`Action HTTP error: ${e} (${r.toFixed(2)}ms)`,t),{success:!1,errorCode:`HTTP_${i.status}`,errorMessage:t||i.statusText}}const o=await i.json(),a=performance.now()-n;return this.log("debug",`Action completed in ${a.toFixed(2)}ms`,{success:o.success}),this.track({eventName:o.success?"djvlc_action_success":"djvlc_action_fail",params:{actionType:e,idempotencyKey:s,duration:Math.round(a),errorCode:o.errorCode},type:"custom"}),{success:o.success,data:o.data,errorCode:o.errorCode,errorMessage:o.errorMessage}}catch(i){const t=performance.now()-n;return this.log("error",`Action failed: ${e} (${t.toFixed(2)}ms)`,i),this.track({eventName:"djvlc_action_error",params:{actionType:e,idempotencyKey:s,duration:Math.round(t),errorMessage:i instanceof Error?i.message:"Unknown error"},type:"custom"}),{success:!1,errorCode:"NETWORK_ERROR",errorMessage:i instanceof Error?i.message:"Action failed"}}}async openDialog(e){return this.log("debug","Open dialog:",e),new Promise(t=>{const n=new CustomEvent("djvlc:openDialog",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(n),setTimeout(()=>{t({confirmed:!1})},6e4)})}closeDialog(e){this.log("debug","Close dialog:",e);const t=new CustomEvent("djvlc:closeDialog",{detail:{dialogId:e}});document.dispatchEvent(t)}showToast(e){this.log("debug","Show toast:",e);const t=document.createElement("div");t.className=`djvlc-toast djvlc-toast-${e.type||"info"} djvlc-toast-${e.position||"top"}`,t.setAttribute("role","alert"),t.textContent=e.message,Object.assign(t.style,{position:"fixed",left:"50%",transform:"translateX(-50%)",padding:"12px 24px",borderRadius:"8px",color:"#fff",fontSize:"14px",zIndex:"10000",boxShadow:"0 4px 12px rgba(0,0,0,0.15)",transition:"opacity 0.3s, transform 0.3s",opacity:"0"});switch(t.style.backgroundColor={success:"#52c41a",error:"#ff4d4f",warning:"#faad14",info:"#1890ff"}[e.type||"info"],e.position){case"center":t.style.top="50%",t.style.transform="translate(-50%, -50%)";break;case"bottom":t.style.bottom="20px";break;default:t.style.top="20px"}document.body.appendChild(t),requestAnimationFrame(()=>{t.style.opacity="1"}),setTimeout(()=>{t.style.opacity="0",setTimeout(()=>t.remove(),300)},e.duration||3e3)}showLoading(e){this.loadingCount++,1===this.loadingCount&&(this.loadingElement=document.createElement("div"),this.loadingElement.className="djvlc-loading-overlay",this.loadingElement.innerHTML=`\n <div class="djvlc-loading-content">\n <div class="djvlc-loading-spinner"></div>\n <div class="djvlc-loading-message">${e||"加载中..."}</div>\n </div>\n `,Object.assign(this.loadingElement.style,{position:"fixed",top:"0",left:"0",right:"0",bottom:"0",backgroundColor:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"10001"}),document.body.appendChild(this.loadingElement))}hideLoading(){this.loadingCount=Math.max(0,this.loadingCount-1),0===this.loadingCount&&this.loadingElement&&(this.loadingElement.remove(),this.loadingElement=null)}async share(e){if(this.log("debug","Share:",e),navigator.share)try{return await navigator.share({title:e.title,text:e.description,url:e.url}),{success:!0,channel:"native"}}catch(t){if("AbortError"===t.name)return{success:!1,cancelReason:"User cancelled"};throw t}if(e.url){if(await this.clipboard.write(e.url))return this.showToast({message:"链接已复制",type:"success"}),{success:!0,channel:"link"}}return{success:!1,cancelReason:"Share not supported"}}async confirm(e){return this.log("debug","Confirm:",e),window.confirm(e.content)}async showActionSheet(e){return this.log("debug","Show action sheet:",e),new Promise(t=>{const n=new CustomEvent("djvlc:showActionSheet",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(n),setTimeout(()=>{t({cancelled:!0})},6e4)})}previewImage(e){this.log("debug","Preview image:",e);const t=new CustomEvent("djvlc:previewImage",{detail:e});document.dispatchEvent(t)}async scanCode(){return this.log("debug","Scan code"),new Promise(e=>{const t=new CustomEvent("djvlc:scanCode",{detail:{resolve:t=>e(t)}});document.dispatchEvent(t),setTimeout(()=>{e({success:!1,cancelReason:"Timeout"})},6e4)})}getState(e){return this.options.stateManager.getVariable(e)}setState(e,t){this.options.stateManager.setVariable(e,t)}getContext(){const e=this.options.context;return{pageVersionId:e.pageVersionId,componentVersionId:"",instanceId:"",userId:e.userId,deviceId:e.deviceId,channel:e.channel,appId:e.appId,env:e.env}}buildHeaders(){const e={"Content-Type":"application/json",...this.options.headers};return this.options.authToken&&(e.Authorization=`Bearer ${this.options.authToken}`),e}generateIdempotencyKey(e,t){const n=Date.now(),r=JSON.stringify(t||{});return`${e}:${n}:${this.simpleHash(r)}`}simpleHash(e){let t=0;for(let n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t&=t}return Math.abs(t).toString(36)}fallbackCopy(e){const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{return document.execCommand("copy"),!0}catch{return!1}finally{document.body.removeChild(t)}}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},$=class{constructor(e={}){var t;this.blockedComponentsMap=new Map,this.blockedActionsSet=new Set,this.allowedCapabilitiesSet=null,this.options={enableSRI:!0,cdnDomains:[],apiDomains:[],blockedComponents:[],blockedActions:[],applyCSPOnInit:!1,...e},this.updateBlockedList((null==(t=e.blockedComponents)?void 0:t.map(e=>`${e.name}@${e.version}`))||[],e.blockedActions||[]),e.allowedCapabilities&&(this.allowedCapabilitiesSet=new Set(e.allowedCapabilities)),e.applyCSPOnInit&&this.applyCSP()}updateBlockedList(e,t){this.blockedComponentsMap.clear(),e.forEach(e=>{const[t,n]=e.split("@");t&&n&&this.blockedComponentsMap.set(e,{name:t,version:n,reason:"Blocked by registry"})}),this.blockedActionsSet=new Set(t)}addBlockedComponent(e){const t=`${e.name}@${e.version}`;this.blockedComponentsMap.set(t,e),this.log("warn",`Component blocked: ${t} - ${e.reason}`)}removeBlockedComponent(e,t){const n=`${e}@${t}`;this.blockedComponentsMap.delete(n),this.log("info",`Component unblocked: ${n}`)}isComponentBlocked(e,t){return this.blockedComponentsMap.has(`${e}@${t}`)}getBlockedInfo(e,t){return this.blockedComponentsMap.get(`${e}@${t}`)}getAllBlockedComponents(){return Array.from(this.blockedComponentsMap.values())}isActionBlocked(e){return this.blockedActionsSet.has(e)}isCapabilityAllowed(e){return!this.allowedCapabilitiesSet||this.allowedCapabilitiesSet.has(e)}validateCapabilities(e,t,n){if(!this.allowedCapabilitiesSet)return{valid:!0,disallowed:[]};const r=n.filter(e=>!this.allowedCapabilitiesSet.has(e));return r.length>0&&this.log("warn",`Component ${e}@${t} uses disallowed capabilities: ${r.join(", ")}`),{valid:0===r.length,disallowed:r}}async validateIntegrity(e,t,n,r){if(!this.options.enableSRI)return;const[s,i]=r.split("-");if(!s||!i)throw new f(e,t,r,"Invalid integrity format");const o=await this.computeHash(n,s);if(o!==i)throw this.log("error",`Integrity check failed for ${e}@${t}`),new f(e,t,i,o);this.log("debug",`Integrity check passed for ${e}@${t}`)}async generateIntegrity(e,t="sha384"){return`${t}-${await this.computeHash(e,t)}`}isAllowedUrl(e,t){const n="cdn"===t?this.options.cdnDomains:this.options.apiDomains;if(!n||0===n.length)return!0;try{const t=new URL(e);return n.some(e=>{if(e.startsWith("*.")){const n=e.slice(2);return t.hostname.endsWith(n)||t.hostname===n.slice(1)}return t.hostname===e})}catch{return!1}}validateExternalUrl(e){try{const t=new URL(e);if(!["http:","https:"].includes(t.protocol))return{safe:!1,reason:`Unsafe protocol: ${t.protocol}`};const n=t.hostname;return"localhost"===n||"127.0.0.1"===n||n.startsWith("192.168.")||n.startsWith("10.")||n.startsWith("172.16.")?{safe:!1,reason:"Internal network address not allowed"}:{safe:!0}}catch{return{safe:!1,reason:"Invalid URL format"}}}generateCSPPolicy(){const e=this.options.cdnDomains||[],t=this.options.apiDomains||[],n=["'self'",...e].join(" "),r=["'self'",...t,...e].join(" ");return["default-src 'self'",`script-src ${n}`,`style-src ${["'self'","'unsafe-inline'",...e].join(" ")}`,`img-src ${["'self'","data:","blob:",...e].join(" ")}`,`font-src ${["'self'","data:",...e].join(" ")}`,`connect-src ${r}`,"frame-ancestors 'self'","base-uri 'self'","form-action 'self'","upgrade-insecure-requests"].join("; ")}applyCSP(){if(document.querySelector('meta[http-equiv="Content-Security-Policy"]'))return void this.log("debug","CSP meta tag already exists, skipping");const e=document.createElement("meta");e.httpEquiv="Content-Security-Policy",e.content=this.generateCSPPolicy(),document.head.appendChild(e),this.log("info","CSP policy applied")}assertNotBlocked(e,t){const n=this.getBlockedInfo(e,t);if(n)throw new E(e,t,n.reason)}createSafeEvaluator(){return(e,t)=>{const n=Object.keys(t),r=Object.values(t);return new Function(...n,`"use strict"; return (${e});`)(...r)}}async computeHash(e,t){const n=(new TextEncoder).encode(e),r=await crypto.subtle.digest(t.toUpperCase(),n),s=Array.from(new Uint8Array(r));return btoa(String.fromCharCode(...s))}log(e,t,...n){this.options.logger&&this.options.logger[e](t,...n)}},B=class{constructor(e){this.spans=new Map,this.metrics=[],this.errors=[],this.options={enabled:!0,sampleRate:1,batchSize:50,flushInterval:3e4,...e},this.traceId=this.generateTraceId(),this.shouldSample=Math.random()<(this.options.sampleRate??1),this.options.enabled&&this.options.endpoint&&this.startAutoFlush(),"undefined"!=typeof window&&(window.addEventListener("beforeunload",()=>this.flush()),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.flush()}))}getTraceId(){return this.traceId}getTraceparent(e){const t=e||this.generateSpanId(),n=this.shouldSample?"01":"00";return`00-${this.traceId}-${t}-${n}`}parseTraceparent(e){const t=e.split("-");if(4!==t.length)return null;const[,n,r,s]=t;return{traceId:n,parentSpanId:r,sampled:"01"===s}}startSpan(e,t,n){const r={spanId:this.generateSpanId(),traceId:this.traceId,parentSpanId:t,name:e,startTime:performance.now(),attributes:{pageVersionId:this.options.pageVersionId,...n}};return this.spans.set(r.spanId,r),this.log("debug",`Span started: ${e} (${r.spanId})`),r}endSpan(e,t="ok",n){const r=this.spans.get(e);if(r){r.endTime=performance.now(),r.status=t,n&&(r.attributes={...r.attributes,...n});const s=r.endTime-r.startTime;this.log("debug",`Span ended: ${r.name} (${e}) - ${s.toFixed(2)}ms [${t}]`)}}recordPageLoad(e){this.recordMetricInternal({type:"pageLoadTime",value:e,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordComponentLoad(e,t,n,r){this.recordMetricInternal({type:"componentLoadTime",value:n,pageVersionId:this.options.pageVersionId,componentName:e,componentVersion:t,timestamp:Date.now()}),r||this.recordError(new Error(`Component load failed: ${e}@${t}`),{componentVersion:`${e}@${t}`})}recordFirstRender(e){this.recordMetricInternal({type:"firstRenderTime",value:e,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordActionExecute(e,t,n,r){this.recordMetricInternal({type:"actionExecuteTime",value:n,pageVersionId:this.options.pageVersionId,actionType:e,timestamp:Date.now()}),r||this.recordError(new Error(`Action failed: ${e}`),{actionId:t})}recordQueryExecute(e,t,n,r=!1){this.recordMetricInternal({type:"queryFetchTime",value:t,pageVersionId:this.options.pageVersionId,queryId:e,timestamp:Date.now()}),this.log("debug",`Query ${e}: ${t.toFixed(2)}ms, cache: ${r}, success: ${n}`)}recordExpressionEval(e,t,n){t>1&&this.recordMetricInternal({type:"expressionEvalTime",value:t,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordError(e,t){var n,r;const s={type:e.name||"Error",message:e.message,stack:e.stack,traceId:this.traceId,pageVersionId:this.options.pageVersionId,componentVersion:null==t?void 0:t.componentVersion,actionId:null==t?void 0:t.actionId,context:t,timestamp:Date.now()};this.errors.push(s),this.log("error",`Error recorded: ${e.message}`),null==(r=(n=this.options).onError)||r.call(n,s),this.errors.length>=(this.options.batchSize??50)&&this.flush()}getMetrics(){return[...this.metrics]}getSpans(){return Array.from(this.spans.values())}getErrors(){return[...this.errors]}getPerformanceSummary(){const e=this.metrics.filter(e=>"componentLoadTime"===e.type),t=this.metrics.find(e=>"pageLoadTime"===e.type),n=this.metrics.find(e=>"firstRenderTime"===e.type);return{pageLoadTime:null==t?void 0:t.value,firstRenderTime:null==n?void 0:n.value,componentCount:e.length,avgComponentLoadTime:e.length>0?e.reduce((e,t)=>e+t.value,0)/e.length:0,errorCount:this.errors.length}}clear(){this.spans.clear(),this.metrics=[],this.errors=[]}async flush(){if(!this.shouldSample||!this.options.enabled)return;if(0===this.metrics.length&&0===this.errors.length&&0===this.spans.size)return;const e={traceId:this.traceId,pageVersionId:this.options.pageVersionId,appId:this.options.appId,runtimeVersion:this.options.runtimeVersion,spans:this.getSpans(),metrics:this.metrics,errors:this.errors,timestamp:Date.now()};if(this.clear(),this.options.endpoint)try{await fetch(this.options.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}),this.log("debug","Telemetry flushed successfully")}catch(t){this.log("warn","Failed to flush telemetry:",t)}else this.log("debug","No endpoint configured, telemetry data discarded")}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush()}recordMetricInternal(e){var t,n;this.metrics.push(e),null==(n=(t=this.options).onMetric)||n.call(t,e),this.metrics.length>=(this.options.batchSize??50)&&this.flush()}startAutoFlush(){const e=this.options.flushInterval??3e4;this.flushTimer=setInterval(()=>this.flush(),e)}generateTraceId(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}generateSpanId(){const e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},V=class e{constructor(e){this.container=null,this.renderedElements=new Map,this.componentEventListeners=new Map,this.expressionContext={state:{},binding:{},local:{}},this.loopContextStack=[],this.styleElement=null,this.options=e}init(){this.log("debug","Renderer initialized")}render(e,t){this.container=t,this.log("debug","Rendering page",e.pageId),this.cleanup(),t.innerHTML="",this.applyPageConfig(e,t),this.initializePageState(e);const n=this.renderNode(e.root);n&&t.appendChild(n),this.log("info",`Page rendered with root component: ${e.root.componentType}`)}updateComponent(e,t){const n=this.renderedElements.get(e);n?this.applyProps(n,t):this.log("warn",`Component not found: ${e}`)}updateContext(e){this.expressionContext={...this.expressionContext,...e}}getContext(){return{...this.expressionContext}}destroy(){this.cleanup(),this.container&&(this.container.innerHTML=""),this.log("debug","Renderer destroyed")}cleanup(){this.componentEventListeners.forEach((e,t)=>{const n=this.renderedElements.get(t);n&&e.forEach(({event:e,handler:t})=>{n.removeEventListener(e,t)})}),this.componentEventListeners.clear(),this.renderedElements.forEach(e=>{e.remove()}),this.renderedElements.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.loopContextStack=[]}renderNode(e){const{id:t,componentType:n,componentVersion:r}=e;try{if(e.condition){if(!this.evaluateCondition(e.condition))return this.log("debug",`Component ${t} hidden by condition`),null}if(e.loop)return this.renderLoop(e);const s=this.createElement(e);if(!s)return null;s.setAttribute("data-component-id",t),s.setAttribute("data-component-type",n),r&&s.setAttribute("data-component-version",r);const i=this.resolveProps(e.props);if(this.applyProps(s,i),e.style&&this.applyStyles(s,e.style),e.layout&&this.applyLayout(s,e.layout),this.options.injectHostApi(s,t),e.eventHandlers&&e.eventHandlers.length>0&&this.bindEventHandlers(s,t,e.eventHandlers),this.renderChildren(s,e),e.ref){const t=this.expressionContext.local,n=t.$refs||{};n[e.ref]=s,this.expressionContext={...this.expressionContext,local:{...t,$refs:n}}}return this.renderedElements.set(t,s),s}catch(s){return this.log("error",`Failed to render component: ${t}`,s),this.options.onRenderError?this.options.onRenderError(t,s):this.createErrorFallback(t,n,s)}}createElement(e){var t;const{componentType:n}=e,r=this.options.components.get(n);if(r&&customElements.get(n))return document.createElement(n);const s=`${n}-${null==(t=e.componentVersion)?void 0:t.replace(/\./g,"-")}`;if(customElements.get(s))return document.createElement(s);const i=document.createElement("div");return i.className=`djvlc-component djvlc-${n}`,r||(this.log("warn",`Component not loaded: ${n}`),i.classList.add("djvlc-component-fallback")),i}renderLoop(e){const{loop:t}=e;if(!t)return null;const n=this.evaluateExpression(t.items);if(!Array.isArray(n))return this.log("warn",`Loop items is not an array for ${e.id}`),null;const r=document.createDocumentFragment();n.forEach((n,s)=>{this.loopContextStack.push({item:n,index:s,loopConfig:t});const i={...this.expressionContext},o={...this.expressionContext.local,[t.itemName]:n,item:n,index:s};t.indexName&&(o[t.indexName]=s),this.expressionContext={...this.expressionContext,local:o};const a={...e,id:`${e.id}_${s}`,loop:void 0},c=this.renderNode(a);if(c){const e=this.evaluateExpression(t.key);c.setAttribute("data-loop-key",String(e??s)),r.appendChild(c)}this.expressionContext=i,this.loopContextStack.pop()});const s=document.createElement("div");return s.className="djvlc-loop-container",s.setAttribute("data-loop-id",e.id),s.appendChild(r),s}renderChildren(e,t){if(t.slots&&Object.keys(t.slots).length>0)for(const[n,r]of Object.entries(t.slots)){const t=this.createSlotContainer(n);for(const e of r){const n=this.renderNode(e);n&&t.appendChild(n)}e.appendChild(t)}}createSlotContainer(e){const t=document.createElement("div");return t.className=`djvlc-slot djvlc-slot-${e}`,t.setAttribute("data-slot",e),t}bindEventHandlers(e,t,n){const r=[];for(const s of n){const{eventName:n,preventDefault:i,stopPropagation:o,throttle:a,debounce:c,condition:l}=s;let d=e=>{if(l){if(!this.evaluateCondition(l))return}i&&e.preventDefault(),o&&e.stopPropagation();const r=e.detail||{};this.options.onComponentEvent&&this.options.onComponentEvent(t,n,[s],r)};a&&a>0&&(d=this.createThrottledHandler(d,a)),c&&c>0&&(d=this.createDebouncedHandler(d,c)),e.addEventListener(n,d),r.push({event:n,handler:d})}this.componentEventListeners.set(t,r)}createThrottledHandler(e,t){let n=0;return r=>{const s=Date.now();s-n>=t&&(n=s,e(r))}}createDebouncedHandler(e,t){let n=null;return r=>{n&&clearTimeout(n),n=setTimeout(()=>{e(r),n=null},t)}}evaluateCondition(e){const t=this.evaluateExpression(e);return Boolean(t)}evaluateExpression(e){if(null==e)return e;if("object"==typeof e&&"type"in e&&"value"in e){const t=e,n=this.buildExpressionContext();return this.options.expressionEngine.evaluateWithFallback(t.value,n,t.fallback)}if("string"==typeof e){const t=this.buildExpressionContext();return this.options.expressionEngine.evaluateWithFallback(e,t,void 0)}return e}buildExpressionContext(){const e={};for(const t of this.loopContextStack)e[t.loopConfig.itemName]=t.item,e.item=t.item,e.index=t.index,t.loopConfig.indexName&&(e[t.loopConfig.indexName]=t.index);return{...this.expressionContext,local:{...this.expressionContext.local,...e}}}resolveProps(e){const t={};for(const[n,r]of Object.entries(e))t[n]=this.resolveValue(r);return t}resolveValue(t){if(null==t)return t;if("string"==typeof t)return t.includes("${")?this.options.expressionEngine.evaluateTemplate(t,this.buildExpressionContext()):t;if("number"==typeof t||"boolean"==typeof t)return t;if(Array.isArray(t))return t.map(e=>this.resolveValue(e));if("object"==typeof t){const n=t;if("string"==typeof n.type&&e.EXPRESSION_TYPES.includes(n.type)&&"string"==typeof n.value){const e=n;return this.options.expressionEngine.evaluateWithFallback(e.value,this.buildExpressionContext(),e.fallback)}const r={};for(const[e,t]of Object.entries(n))r[e]=this.resolveValue(t);return r}return t}applyProps(e,t){for(const[n,r]of Object.entries(t))null!=r&&(e.tagName.includes("-")?e[n]=r:"boolean"==typeof r?r?e.setAttribute(n,""):e.removeAttribute(n):"object"==typeof r?e.setAttribute(n,JSON.stringify(r)):e.setAttribute(n,String(r)))}applyStyles(e,t){if(t.inline)for(const[n,r]of Object.entries(t.inline)){if(null==r)continue;const t=this.resolveValue(r);let s;if("number"==typeof t){s=["zIndex","opacity","flex","fontWeight","lineHeight"].includes(n)?String(t):`${t}px`}else s=String(t);const i=n.replace(/([A-Z])/g,"-$1").toLowerCase();e.style.setProperty(i,s)}t.className&&e.classList.add(...String(t.className).split(" ").filter(Boolean))}applyLayout(e,t){const{x:n,y:r,width:s,height:i,rotation:o,zIndex:a,responsive:c}=t;e.style.position="absolute",void 0!==n&&(e.style.left=`${n}px`),void 0!==r&&(e.style.top=`${r}px`),void 0!==s&&(e.style.width=`${s}px`),void 0!==i&&(e.style.height=`${i}px`),void 0!==o&&(e.style.transform=`rotate(${o}deg)`),void 0!==a&&(e.style.zIndex=String(a)),c&&this.applyResponsiveLayout(e,c)}applyResponsiveLayout(e,t){const n=e.getAttribute("data-component-id");if(!n)return;let r="";if(t.mobile&&(r+=`\n @media (max-width: 767px) {\n [data-component-id="${n}"] {\n ${this.layoutToCSS(t.mobile)}\n }\n }\n `),t.tablet&&(r+=`\n @media (min-width: 768px) and (max-width: 1023px) {\n [data-component-id="${n}"] {\n ${this.layoutToCSS(t.tablet)}\n }\n }\n `),t.desktop&&(r+=`\n @media (min-width: 1440px) {\n [data-component-id="${n}"] {\n ${this.layoutToCSS(t.desktop)}\n }\n }\n `),r){const e=document.createElement("style");e.setAttribute("data-djvlc-responsive",n),e.textContent=r,document.head.appendChild(e)}}layoutToCSS(e){const t=[];return void 0!==e.x&&t.push(`left: ${e.x}px`),void 0!==e.y&&t.push(`top: ${e.y}px`),void 0!==e.width&&t.push(`width: ${e.width}px`),void 0!==e.height&&t.push(`height: ${e.height}px`),void 0!==e.rotation&&t.push(`transform: rotate(${e.rotation}deg)`),void 0!==e.zIndex&&t.push(`z-index: ${e.zIndex}`),t.join("; ")}applyPageConfig(e,t){t.classList.add("djvlc-page"),t.setAttribute("data-page-id",e.pageId),t.setAttribute("data-page-version",e.pageVersion),t.setAttribute("data-schema-version",e.schemaVersion);const n=e.config;n&&(this.applyLayoutConfig(t,n.layout),n.styles&&this.applyStylesConfig(t,n.styles),n.behavior&&this.applyBehaviorConfig(t,n.behavior))}applyBehaviorConfig(e,t){t.debug&&e.setAttribute("data-debug","true"),t.i18n&&this.applyI18nConfig(e,t.i18n)}applyI18nConfig(e,t){const n=this.detectLocale(t);e.setAttribute("lang",n),e.setAttribute("data-locale",n),e.setAttribute("data-default-locale",t.defaultLocale),e.setAttribute("data-supported-locales",t.supportedLocales.join(",")),t.translationBundleId&&e.setAttribute("data-translation-bundle",t.translationBundleId),e.style.setProperty("--djvlc-locale",n),e.style.setProperty("--djvlc-dir",this.getTextDirection(n));"rtl"===this.getTextDirection(n)?(e.setAttribute("dir","rtl"),e.classList.add("djvlc-rtl")):e.setAttribute("dir","ltr"),this.expressionContext={...this.expressionContext,local:{...this.expressionContext.local,$locale:n,$defaultLocale:t.defaultLocale,$supportedLocales:t.supportedLocales}},this.log("debug",`I18n configured: locale=${n}, default=${t.defaultLocale}`)}detectLocale(e){const{defaultLocale:t,supportedLocales:n,detection:r="browser"}=e;let s=null;switch(r){case"browser":case"header":s=this.detectBrowserLocale(n);break;case"url":s=this.detectUrlLocale(n);break;case"path":s=this.detectPathLocale(n);break;case"cookie":s=this.detectCookieLocale(n);break;case"manual":s=t;break;default:s=null}return s&&n.includes(s)?s:t}detectBrowserLocale(e){if("undefined"==typeof navigator)return null;const t=navigator.languages||[navigator.language];for(const n of t){if(e.includes(n))return n;const t=n.split("-")[0],r=e.find(e=>e===t||e.startsWith(`${t}-`));if(r)return r}return null}detectUrlLocale(e){if("undefined"==typeof window)return null;const t=new URLSearchParams(window.location.search),n=t.get("lang")||t.get("locale");return n&&e.includes(n)?n:null}detectPathLocale(e){if("undefined"==typeof window)return null;const t=window.location.pathname.split("/").filter(Boolean);if(t.length>0){const n=t[0];if(e.includes(n))return n}return null}detectCookieLocale(e){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(const n of t){const[t,r]=n.trim().split("=");if("lang"===t||"locale"===t||"language"===t){const t=decodeURIComponent(r);if(e.includes(t))return t}}return null}getTextDirection(e){const t=e.split("-")[0];return["ar","ar-SA","ar-EG","ar-AE","he","he-IL","fa","fa-IR","ur","ur-PK","yi","ps","dv"].some(n=>n===e||n===t)?"rtl":"ltr"}applyLayoutConfig(e,t){if(e.setAttribute("data-canvas-type",t.canvasType),t.canvasSize&&"responsive"!==t.canvasType&&(e.style.width=`${t.canvasSize.width}px`,e.style.minHeight=`${t.canvasSize.height}px`),t.maxWidth&&(e.style.maxWidth=`${t.maxWidth}px`,e.style.marginLeft="auto",e.style.marginRight="auto"),t.padding){const{top:n=0,right:r=0,bottom:s=0,left:i=0}=t.padding;e.style.padding=`${n}px ${r}px ${s}px ${i}px`}t.viewport&&(t.viewport.mobile&&e.style.setProperty("--djvlc-breakpoint-mobile",`${t.viewport.mobile}px`),t.viewport.tablet&&e.style.setProperty("--djvlc-breakpoint-tablet",`${t.viewport.tablet}px`),t.viewport.desktop&&e.style.setProperty("--djvlc-breakpoint-desktop",`${t.viewport.desktop}px`))}applyStylesConfig(e,t){if(t.theme&&this.applyThemeConfig(e,t.theme),t.background&&this.applyBackgroundConfig(e,t.background),t.cssVariables)for(const[n,r]of Object.entries(t.cssVariables)){const t=n.startsWith("--")?n:`--${n}`;e.style.setProperty(t,r)}t.customCSS&&this.injectCustomCSS(t.customCSS)}applyThemeConfig(e,t){if(t.preset&&(e.setAttribute("data-theme",t.preset),"system"===t.preset)){const t=window.matchMedia("(prefers-color-scheme: dark)").matches;e.setAttribute("data-theme-resolved",t?"dark":"light")}if(t.variables)for(const[n,r]of Object.entries(t.variables)){const t=n.startsWith("--")?n:`--theme-${n}`;e.style.setProperty(t,r)}t.transition&&e.style.setProperty("--djvlc-theme-transition","all 0.3s ease")}applyBackgroundConfig(e,t){switch(t.type){case"color":e.style.backgroundColor=t.value;break;case"image":e.style.backgroundImage=`url(${t.value})`,e.style.backgroundSize=t.size||"cover",e.style.backgroundPosition=t.position||"center",e.style.backgroundRepeat=t.repeat||"no-repeat";break;case"gradient":e.style.backgroundImage=t.value}}injectCustomCSS(e){e.trim()&&(this.styleElement=document.createElement("style"),this.styleElement.setAttribute("data-djvlc-custom","true"),this.styleElement.textContent=e,document.head.appendChild(this.styleElement))}initializePageState(e){if(e.state&&e.state.fields){const t={};for(const[n,r]of Object.entries(e.state.fields))r&&"object"==typeof r&&(t[n]=r.initialValue);this.expressionContext={...this.expressionContext,state:t}}}createErrorFallback(e,t,n){const r=document.createElement("div");return r.className="djvlc-error-boundary",r.setAttribute("data-component-id",e),r.setAttribute("data-error","true"),r.innerHTML=`\n <div class="djvlc-error-content">\n <span class="djvlc-error-icon">⚠️</span>\n <span class="djvlc-error-message">组件渲染失败: ${t}</span>\n ${this.options.debug?`<pre class="djvlc-error-detail">${n.message}</pre>`:""}\n </div>\n `,r}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}};V.EXPRESSION_TYPES=["state","binding","local","template","computed"];var j=V;var q=class{constructor(e){this.lifecycle=null,this.mounted=!1,this.destroyed=!1,this.cleanupFns=[],this.options=e}register(e){var t,n,r;e?(this.lifecycle=e,this.log("debug","Lifecycle hooks registered",{onMounted:(null==(t=e.onMounted)?void 0:t.length)??0,onBeforeUnmount:(null==(n=e.onBeforeUnmount)?void 0:n.length)??0,onVisibilityChange:(null==(r=e.onVisibilityChange)?void 0:r.length)??0}),e.onVisibilityChange&&e.onVisibilityChange.length>0&&this.setupVisibilityListener()):this.log("debug","No lifecycle hooks defined")}async triggerMounted(){var e,t,n;this.mounted||this.destroyed||(this.mounted=!0,this.log("debug","Triggering onMounted lifecycle"),await this.executeLifecycleActions("mounted",null==(e=this.lifecycle)?void 0:e.onMounted),null==(n=(t=this.options).onLifecycleEvent)||n.call(t,"mounted"))}async triggerBeforeUnmount(){var e,t,n;this.mounted&&!this.destroyed&&(this.log("debug","Triggering onBeforeUnmount lifecycle"),await this.executeLifecycleActions("beforeUnmount",null==(e=this.lifecycle)?void 0:e.onBeforeUnmount),null==(n=(t=this.options).onLifecycleEvent)||n.call(t,"beforeUnmount"))}async triggerVisibilityChange(e){var t,n,r;if(!this.mounted||this.destroyed)return;this.log("debug","Triggering onVisibilityChange lifecycle",{isVisible:e});const s=this.options.getContext(),i={...s,local:{...s.local,$visible:e,$hidden:!e}};await this.executeLifecycleActionsWithContext("visibilityChange",null==(t=this.lifecycle)?void 0:t.onVisibilityChange,i),null==(r=(n=this.options).onLifecycleEvent)||r.call(n,"visibilityChange",{isVisible:e})}async destroy(){this.destroyed||(await this.triggerBeforeUnmount(),this.cleanupFns.forEach(e=>e()),this.cleanupFns=[],this.destroyed=!0,this.lifecycle=null,this.log("debug","LifecycleManager destroyed"))}isMounted(){return this.mounted&&!this.destroyed}isDestroyed(){return this.destroyed}setupVisibilityListener(){const e=()=>{const e="visible"===document.visibilityState;this.triggerVisibilityChange(e).catch(e=>{this.log("error","Failed to handle visibility change",e)})};document.addEventListener("visibilitychange",e),this.cleanupFns.push(()=>{document.removeEventListener("visibilitychange",e)}),this.log("debug","Visibility listener registered")}async executeLifecycleActions(e,t){if(!t||0===t.length)return;const n=this.options.getContext();await this.executeLifecycleActionsWithContext(e,t,n)}async executeLifecycleActionsWithContext(e,t,n){if(t&&0!==t.length){this.log("debug",`Executing ${t.length} actions for ${e}`);try{const r={id:`lifecycle_${e}`,eventName:e,actions:t};await this.options.actionBridge.handleEvent(r,{lifecycle:e},n),this.log("debug",`Lifecycle ${e} actions completed`)}catch(r){this.log("error",`Failed to execute lifecycle ${e} actions`,r)}}}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},F=u.CURRENT_SCHEMA_VERSION,H="1.0.0";function K(e){return new Y(e)}var Y=class{constructor(e){this.container=null,this.options={channel:"prod",debug:!1,enableSRI:!0,env:"production",...e},this.logger=this.createLogger(),this.stateManager=new C,this.eventBus=new N({debug:e.debug,logger:this.logger}),this.expressionEngine=new P({debug:e.debug,logger:this.logger}),this.pageLoader=new I({apiBaseUrl:e.apiBaseUrl,channel:e.channel,authToken:e.authToken,previewToken:e.previewToken,headers:e.headers,logger:this.logger}),this.componentLoader=new T({cdnBaseUrl:e.cdnBaseUrl,enableSRI:e.enableSRI,logger:this.logger}),this.assetLoader=new w({cdnHosts:[new URL(e.cdnBaseUrl).host],apiHosts:[new URL(e.apiBaseUrl).host]}),this.securityManager=new $({enableSRI:e.enableSRI,cdnDomains:[new URL(e.cdnBaseUrl).host],apiDomains:[new URL(e.apiBaseUrl).host],logger:this.logger}),this.log("info","Runtime created",{version:H})}async init(){this.log("info","Initializing runtime");const e=performance.now();try{this.container=this.resolveContainer(),this.assetLoader.preconnectAll(),this.pageLoader.preconnect(),customElements.get("djvlc-fallback")||customElements.define("djvlc-fallback",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML='\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #fff2f0;\n border: 1px solid #ffccc7;\n border-radius: 4px;\n color: #ff4d4f;\n font-size: 14px;\n }\n .title {\n font-weight: 600;\n margin-bottom: 8px;\n }\n .message {\n color: #666;\n }\n </style>\n <div class="title">组件加载失败</div>\n <div class="message"><slot>请刷新页面重试</slot></div>\n '}static get observedAttributes(){return["message","component-name"]}attributeChangedCallback(e,t,n){if("message"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".message");e&&(e.textContent=n)}if("component-name"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".title");e&&(e.textContent=`组件 ${n} 加载失败`)}}}),customElements.get("djvlc-blocked")||customElements.define("djvlc-blocked",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML='\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #fffbe6;\n border: 1px solid #ffe58f;\n border-radius: 4px;\n color: #faad14;\n font-size: 14px;\n }\n .icon {\n margin-right: 8px;\n }\n </style>\n <span class="icon">⚠️</span>\n <span>此组件已被暂停使用</span>\n '}}),customElements.get("djvlc-error-boundary")||customElements.define("djvlc-error-boundary",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML="\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #f5f5f5;\n border: 1px dashed #d9d9d9;\n border-radius: 4px;\n color: #999;\n font-size: 14px;\n text-align: center;\n }\n </style>\n <slot>渲染出错</slot>\n "}}),this.stateManager.setPhase("resolving");const t=performance.now()-e;this.log("info",`Runtime initialized in ${t.toFixed(2)}ms`)}catch(t){throw this.handleError(t),t}}async load(){var e,t,n;this.log("info","Loading page:",this.options.pageUid);const r=performance.now();try{this.stateManager.setPhase("resolving");const s=await this.pageLoader.resolve(this.options.pageUid,{uid:this.options.userId,deviceId:this.options.deviceId});if(this.validateSchemaVersion(s.pageJson),this.stateManager.setPage(s),this.telemetryManager=new B({pageVersionId:s.pageVersionId,appId:this.options.appId,debug:this.options.debug,logger:this.logger,onMetric:this.options.onMetric}),s.runtimeConfig){const t=(null==(e=s.runtimeConfig.blockedComponents)?void 0:e.map(e=>`${e.name}@${e.version}`))||[];this.securityManager.updateBlockedList(t,[]),this.componentLoader.updateBlockedList(t)}this.stateManager.setPhase("loading"),this.componentLoader.preload(s.manifest.components);(await this.componentLoader.loadAll(s.manifest)).forEach((e,t)=>{this.stateManager.setComponentStatus(t,e),this.telemetryManager.recordComponentLoad(e.name,e.version,e.loadTime||0,"loaded"===e.status)}),this.initHostApi(s),this.initActionBridge(),this.initDataBindingManager(s.pageJson),this.initRenderer(),this.initLifecycleManager(s.pageJson);const i=performance.now()-r;return this.telemetryManager.recordPageLoad(i),this.log("info",`Page loaded in ${i.toFixed(2)}ms`),this.emitEvent("page:loaded",{page:s,loadTime:i}),null==(n=(t=this.options).onLoad)||n.call(t,s),s}catch(s){throw this.stateManager.setPhase("error"),this.handleError(s),s}}async render(){const e=this.stateManager.getState();if(!e.page||!this.container)throw new g("Page not loaded");this.log("info","Rendering page");const t=performance.now();try{this.stateManager.setPhase("rendering"),this.renderer.updateContext(this.stateManager.getExpressionContext()),this.renderer.render(e.page.pageJson,this.container),await this.dataBindingManager.initializeBindings(this.stateManager.getExpressionContext()),this.stateManager.setPhase("ready");const n=performance.now()-t;this.telemetryManager.recordFirstRender(n),this.log("info",`Page rendered in ${n.toFixed(2)}ms`),await this.lifecycleManager.triggerMounted(),this.emitEvent("page:rendered",{renderTime:n})}catch(n){throw this.stateManager.setPhase("error"),this.handleError(n),n}}getHostApi(){return this.hostApi}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.subscribe(e)}on(e,t){return this.eventBus.on(e,t)}updateComponent(e,t){this.renderer.updateComponent(e,t)}setVariable(e,t){this.stateManager.setVariable(e,t),this.renderer.updateContext(this.stateManager.getExpressionContext()),this.dataBindingManager.onStateChange(e,this.stateManager.getExpressionContext())}getVariable(e){return this.stateManager.getVariable(e)}async refreshData(e){await this.dataBindingManager.refreshBinding(e,this.stateManager.getExpressionContext()),this.renderer.updateContext(this.stateManager.getExpressionContext())}async executeAction(e,t){return this.hostApi.executeAction(e,t)}async destroy(){var e,t,n,r,s;this.log("info","Destroying runtime"),await(null==(e=this.lifecycleManager)?void 0:e.destroy()),null==(t=this.telemetryManager)||t.flush(),null==(n=this.dataBindingManager)||n.destroy(),null==(r=this.actionBridge)||r.destroy(),null==(s=this.renderer)||s.destroy(),this.eventBus.clear(),this.stateManager.setDestroyed(),this.container&&(this.container.innerHTML=""),this.emitEvent("page:destroyed",{}),this.log("info","Runtime destroyed")}validateSchemaVersion(e){if(e.schemaVersion!==F)throw new g(`Unsupported schema version: ${e.schemaVersion}. Only ${F} is supported.`,{schemaVersion:e.schemaVersion,supportedVersion:F})}resolveContainer(){const{container:e}=this.options;if("string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`Container not found: ${e}`);return t}return e}initHostApi(e){this.hostApi=new U({apiBaseUrl:this.options.apiBaseUrl,authToken:this.options.authToken,headers:this.options.headers,stateManager:this.stateManager,eventBus:this.eventBus,expressionEngine:this.expressionEngine,context:{pageUid:e.pageUid,pageVersionId:e.pageVersionId,runtimeVersion:H,userId:this.options.userId,deviceId:this.options.deviceId,channel:this.options.channel,appId:this.options.appId||"",env:this.options.env||"production",isEditMode:!1,isPreviewMode:e.isPreview||!1},debug:this.options.debug,logger:this.logger})}initActionBridge(){this.actionBridge=new O({executor:{executeAction:(e,t)=>this.hostApi.executeAction(e,t),requestData:(e,t)=>this.hostApi.requestData(e,t),navigate:e=>this.hostApi.navigate(e),openDialog:e=>this.hostApi.openDialog(e),closeDialog:()=>this.hostApi.closeDialog(),showToast:e=>this.hostApi.showToast(e),showLoading:e=>this.hostApi.showLoading(e),hideLoading:()=>this.hostApi.hideLoading(),track:e=>this.hostApi.track(e),setState:(e,t)=>this.stateManager.setVariable(e,t),getState:e=>this.stateManager.getVariable(e),refreshData:e=>this.refreshData(e)},expressionEngine:this.expressionEngine,debug:this.options.debug,logger:this.logger,onActionStart:(e,t)=>{this.emitEvent("action:executing",{action:e,params:t})},onActionComplete:(e,t)=>{var n;t.success?this.emitEvent("action:executed",{action:e,data:t.data}):this.emitEvent("action:error",{action:e,error:null==(n=t.error)?void 0:n.message})}})}initDataBindingManager(e){this.dataBindingManager=new A({requester:{requestData:(e,t)=>this.hostApi.requestData(e,t)},stateSetter:{setVariable:(e,t)=>this.stateManager.setVariable(e,t),getVariable:e=>this.stateManager.getVariable(e)},expressionEngine:this.expressionEngine,debug:this.options.debug,logger:this.logger,onDataLoaded:(e,t)=>{var n;this.emitEvent("query:fetched",{bindingId:e,data:t}),null==(n=this.renderer)||n.updateContext(this.stateManager.getExpressionContext())},onDataError:(e,t)=>{this.emitEvent("query:error",{bindingId:e,error:t.message})}}),e.dataBindings&&this.dataBindingManager.registerBindings(e.dataBindings),this.stateManager.onStateChange(({key:e})=>{this.dataBindingManager.onStateChange(e,this.stateManager.getExpressionContext())})}initLifecycleManager(e){this.lifecycleManager=new q({actionBridge:this.actionBridge,getContext:()=>this.stateManager.getExpressionContext(),debug:this.options.debug,logger:this.logger,onLifecycleEvent:(e,t)=>{this.emitEvent(`page:lifecycle:${e}`,t??{})}}),this.lifecycleManager.register(e.lifecycle)}initRenderer(){const e=new Map;this.stateManager.getState().components.forEach((t,n)=>{if("loaded"===t.status&&t.component){const[r,s]=n.split("@");e.set(r,{name:r,version:s,Component:t.component,loadTime:t.loadTime||0})}}),this.renderer=new j({expressionEngine:this.expressionEngine,components:e,injectHostApi:(e,t)=>{e.hostApi=this.hostApi,e.componentId=t},onComponentEvent:(e,t,n,r)=>{this.handleComponentEvent(e,t,n,r)},debug:this.options.debug,logger:this.logger,onRenderError:(e,t)=>(this.log("error",`Render error in ${e}:`,t),this.emitEvent("component:error",{componentId:e,error:t.message}),function(e,t){const n=document.createElement("djvlc-error-boundary");return t&&n.setAttribute("message",t),n}(0,t.message))}),this.renderer.init()}handleComponentEvent(e,t,n,r){this.log("debug",`Component event: ${e}.${t}`,r);for(const s of n)this.actionBridge.handleEvent(s,r,this.stateManager.getExpressionContext())}handleError(e){var t;const n=e instanceof m?{type:"LOAD_ERROR",message:e.message,code:e.code,details:e.details,traceId:e.traceId,timestamp:e.timestamp}:{type:"UNKNOWN_ERROR",message:e.message,cause:e,timestamp:Date.now()};this.stateManager.setError(n),null==(t=this.telemetryManager)||t.recordError(e),this.emitEvent("page:error",{error:e.message}),this.options.onError&&this.options.onError(n)}emitEvent(e,t){var n;const r=N.createEvent(e,t,null==(n=this.telemetryManager)?void 0:n.getTraceId());this.eventBus.emit(r),this.options.onEvent&&this.options.onEvent(r)}createLogger(){return{debug:(...e)=>{this.options.debug},info:(...e)=>{},warn:(...e)=>{},error:(...e)=>{}}}log(e,t,...n){this.logger[e](t,...n)}},W=d(p());function z(e){if("undefined"!=typeof PerformanceObserver)try{const t=performance.getEntriesByType("paint").find(e=>"first-contentful-paint"===e.name);t&&(e.fcp=t.startTime);new PerformanceObserver(t=>{const n=t.getEntries(),r=n[n.length-1];r&&(e.lcp=r.startTime)}).observe({type:"largest-contentful-paint",buffered:!0});new PerformanceObserver(t=>{const n=t.getEntries();if(n.length>0){const t=n[0];e.fid=t.processingStart-t.startTime}}).observe({type:"first-input",buffered:!0});let n=0;new PerformanceObserver(t=>{for(const r of t.getEntries()){const t=r;!t.hadRecentInput&&t.value&&(n+=t.value,e.cls=n)}}).observe({type:"layout-shift",buffered:!0})}catch{}}W.ErrorCode,W.ErrorMessages;class G{constructor(e=!0){this.marks=new Map,this.measures=new Map,this.enabled=e}mark(e){this.enabled&&(this.marks.set(e,performance.now()),"function"==typeof performance.mark&&performance.mark(`djvlc:${e}`))}measure(e,t,n){if(!this.enabled)return 0;const r=this.marks.get(t),s=n?this.marks.get(n):performance.now();if(void 0===r)return 0;const i=(s??performance.now())-r;if(this.measures.set(e,i),"function"==typeof performance.measure)try{performance.measure(`djvlc:${e}`,`djvlc:${t}`,n?`djvlc:${n}`:void 0)}catch{}return i}getMeasures(){return Object.fromEntries(this.measures)}clear(){this.marks.clear(),this.measures.clear()}}function J(e=!0){return new G(e)}function Q(){const e=performance.timing||{},t=performance.getEntriesByType("navigation")[0];return t?{dns:t.domainLookupEnd-t.domainLookupStart,tcp:t.connectEnd-t.connectStart,ssl:t.secureConnectionStart>0?t.connectEnd-t.secureConnectionStart:0,ttfb:t.responseStart-t.requestStart,download:t.responseEnd-t.responseStart,domParse:t.domInteractive-t.responseEnd,domContentLoaded:t.domContentLoadedEventEnd-t.domContentLoadedEventStart,load:t.loadEventEnd-t.loadEventStart,total:t.loadEventEnd-t.startTime}:{dns:e.domainLookupEnd-e.domainLookupStart,tcp:e.connectEnd-e.connectStart,ttfb:e.responseStart-e.requestStart,download:e.responseEnd-e.responseStart,domParse:e.domInteractive-e.responseEnd,domContentLoaded:e.domContentLoadedEventEnd-e.domContentLoadedEventStart,load:e.loadEventEnd-e.loadEventStart,total:e.loadEventEnd-e.navigationStart}}function X(e){return performance.getEntriesByType("resource").filter(e||(()=>!0)).map(e=>({name:e.name,type:e.initiatorType,duration:e.duration,size:e.transferSize||0}))}function Z(){return X(e=>e.name.includes("/components/")||e.name.includes("/runtime/"))}function ee(e){e.forEach(e=>{const t=document.createElement("link");t.rel="preconnect",t.href=e.startsWith("http")?e:`https://${e}`,t.crossOrigin="anonymous",document.head.appendChild(t)})}function te(e,n=t){[`${e}/runtime/${n}/runtime.esm.js`,`${e}/runtime/${n}/runtime.css`].forEach(e=>{const t=document.createElement("link");t.rel="preload",t.href=e,t.as=e.endsWith(".js")?"script":"style",e.endsWith(".js")&&(t.crossOrigin="anonymous"),document.head.appendChild(t)})}function ne(){const e="djv_device_id";let t=localStorage.getItem(e);if(!t){t=`${Date.now()}-${Math.random().toString(36).substring(2,11)}`;try{localStorage.setItem(e,t)}catch{}}return t}function re(){return e=32,Array.from({length:e},()=>Math.floor(16*Math.random()).toString(16)).join("");var e}function se(){return e=16,Array.from({length:e},()=>Math.floor(16*Math.random()).toString(16)).join("");var e}function ie(){return`00-${re()}-${se()}-01`}const oe={getParam:(e,t=window.location.href)=>new URL(t).searchParams.get(e),setParam(e,t){const n=new URL(window.location.href);n.searchParams.set(e,t),window.history.replaceState({},"",n.toString())},removeParam(e){const t=new URL(window.location.href);t.searchParams.delete(e),window.history.replaceState({},"",t.toString())},build(e,t){const n=new URL(e,window.location.origin);return Object.entries(t).forEach(([e,t])=>{void 0!==t&&n.searchParams.set(e,String(t))}),n.toString()}};function ae(e){const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}function ce(e){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}function le(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function de(){return/MicroMessenger/i.test(navigator.userAgent)}async function pe(){if("function"!=typeof createImageBitmap)return!1;try{const e=await(await fetch("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=")).blob();return await createImageBitmap(e),!0}catch{return!1}}async function ue(e,t){var n,r,s,i;const{retryCount:o=3,retryDelay:a=1e3,timeout:c=3e4,collectWebVitals:l=!1}=t,d={initTime:0,loadTime:0,renderTime:0,totalTime:0,componentLoadCount:0,componentLoadErrors:0,dataRequestCount:0,dataRequestErrors:0},p=performance.now();let u=0,h=0,m=0;const g=K({container:e,pageUid:t.pageUid,apiBaseUrl:t.apiBaseUrl,cdnBaseUrl:t.cdnBaseUrl,channel:t.channel,userId:t.userId,deviceId:t.deviceId,authToken:t.authToken,previewToken:t.previewToken,debug:t.debug,enableSRI:t.enableSRI,headers:t.headers,onError:t.onError?e=>{var n;return null==(n=t.onError)?void 0:n.call(t,new Error(e.message))}:void 0,onMetric:e=>{if("object"==typeof e&&null!==e){const t=e;"component_load"===t.type&&(d.componentLoadCount++,t.error&&d.componentLoadErrors++),"data_request"===t.type&&(d.dataRequestCount++,t.error&&d.dataRequestErrors++)}}}),y=async(e,t,n)=>{try{return await e()}catch(r){if(t>0)return await new Promise(e=>setTimeout(e,n)),y(e,t-1,n);throw r}};try{await y(async()=>{var e,n;await(e=(async()=>{var e,n,r,s;u=performance.now(),null==(e=t.onPhaseChange)||e.call(t,"initializing"),await g.init(),d.initTime=performance.now()-u,h=performance.now(),null==(n=t.onPhaseChange)||n.call(t,"loading"),await g.load(),d.loadTime=performance.now()-h,m=performance.now(),null==(r=t.onPhaseChange)||r.call(t,"rendering"),await g.render(),d.renderTime=performance.now()-m,null==(s=t.onPhaseChange)||s.call(t,"ready")})(),n=c,Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(new Error("加载超时")),n))]))},o,a),d.totalTime=performance.now()-p,l&&z(d),null==(n=t.onLoad)||n.call(t,g.getState()),null==(r=t.onMetric)||r.call(t,d)}catch(f){d.totalTime=performance.now()-p,null==(s=t.onMetric)||s.call(t,d);const e=f instanceof Error?f:new Error(String(f));throw null==(i=t.onError)||i.call(t,e),e}return{runtime:g,metrics:d,destroy:()=>g.destroy(),refresh:async()=>{await g.load(),await g.render()},setVariable:(e,t)=>g.setVariable(e,t),refreshData:e=>g.refreshData(e)}}function he(e,t){const n="string"==typeof e?document.querySelector(e):e;if(!n)return{cancel:()=>{},promise:Promise.reject(new Error("Container element not found"))};let r,s,i=!1,o=null;const a=new Promise((e,t)=>{r=e,s=t});if(t.placeholder){const e="string"==typeof t.placeholder?(()=>{const e=document.createElement("div");return e.innerHTML=t.placeholder,e.firstElementChild})():t.placeholder;e&&n.appendChild(e)}return o=new IntersectionObserver(async a=>{const c=a[0];if((null==c?void 0:c.isIntersecting)&&!i){null==o||o.disconnect(),o=null,n.innerHTML="";try{const n=await ue(e,t);r(n)}catch(l){s(l)}}},{rootMargin:t.rootMargin||"100px",threshold:t.threshold||0}),o.observe(n),{cancel:()=>{i=!0,null==o||o.disconnect(),s(new Error("Lazy mount cancelled"))},promise:a}}async function me(e,t){const{concurrency:n=3,continueOnError:r=!0}=t||{},s=performance.now(),i=new Map,o=new Map;for(let a=0;a<e.length;a+=n){const t=e.slice(a,a+n).map(async({id:e,container:t,options:n})=>{try{const r=await ue(t,n);i.set(e,r)}catch(s){if(o.set(e,s),!r)throw s}});await Promise.all(t)}return{results:i,errors:o,totalTime:performance.now()-s}}async function ge(e){return ee([new URL(e.apiBaseUrl).host,new URL(e.cdnBaseUrl).host]),te(e.cdnBaseUrl,t),{mount:t=>ue(t,e)}}class ye{constructor(e={}){this.events=[],this.flushTimer=null,this.config={endpoint:e.endpoint||"/api/track",batchSize:e.batchSize||10,flushInterval:e.flushInterval||5e3,enabled:!1!==e.enabled,sampleRate:e.sampleRate??1,reporter:e.reporter||this.defaultReporter.bind(this)},this.traceId=re(),this.config.enabled&&this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>this.flush(),this.config.flushInterval))}track(e,t,n){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const r={event:e,data:t,timestamp:Date.now(),traceId:this.traceId,...n};this.events.push(r),this.events.length>=this.config.batchSize&&this.flush()}trackPageView(e,t){this.track("page_view",{url:window.location.href,referrer:document.referrer,title:document.title},{pageUid:e,pageVersionId:t})}trackComponentView(e,t,n){this.track("component_view",{componentType:t},{componentId:e,pageUid:n})}trackComponentClick(e,t,n){this.track("component_click",{componentType:t},{componentId:e,pageUid:n})}trackAction(e,t,n,r){this.track("action_execute",{actionType:e,success:t,duration:n},{pageUid:r})}trackError(e,t){this.track("error",{message:e.message,stack:e.stack,...t})}async flush(){if(0===this.events.length)return;const e=[...this.events];this.events=[];try{await this.config.reporter(e)}catch(t){this.events=[...e,...this.events]}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush()}async defaultReporter(e){this.config.endpoint&&await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:e}),keepalive:!0})}}function fe(e){return new ye(e)}class Ee{constructor(e={}){this.config={endpoint:e.endpoint||"/api/errors",enabled:!1!==e.enabled,sampleRate:e.sampleRate??1,ignorePatterns:e.ignorePatterns||[],reporter:e.reporter||this.defaultReporter.bind(this),maxStackDepth:e.maxStackDepth||50},this.traceId=re(),this.boundHandlers={error:this.handleError.bind(this),unhandledrejection:this.handleUnhandledRejection.bind(this)}}start(){this.config.enabled&&(window.addEventListener("error",this.boundHandlers.error),window.addEventListener("unhandledrejection",this.boundHandlers.unhandledrejection))}stop(){window.removeEventListener("error",this.boundHandlers.error),window.removeEventListener("unhandledrejection",this.boundHandlers.unhandledrejection)}report(e,t){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;if(this.shouldIgnore(e.message))return;const n={message:e.message,stack:this.truncateStack(e.stack),type:"runtime",timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,context:t,traceId:this.traceId};this.config.reporter(n)}setTraceId(e){this.traceId=e}handleError(e){var t;if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;if(this.shouldIgnore(e.message))return;const n={message:e.message,stack:this.truncateStack(null==(t=e.error)?void 0:t.stack),type:"error",timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,context:{filename:e.filename,lineno:e.lineno,colno:e.colno},traceId:this.traceId};this.config.reporter(n)}handleUnhandledRejection(e){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const t=e.reason,n=t instanceof Error?t.message:String(t);if(this.shouldIgnore(n))return;const r={message:n,stack:t instanceof Error?this.truncateStack(t.stack):void 0,type:"unhandledrejection",timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,traceId:this.traceId};this.config.reporter(r)}shouldIgnore(e){return this.config.ignorePatterns.some(t=>t.test(e))}truncateStack(e){if(!e)return;return e.split("\n").slice(0,this.config.maxStackDepth).join("\n")}async defaultReporter(e){if(this.config.endpoint)try{await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})}catch{}}}function be(e){return new Ee(e)}class ve{constructor(e="djvlc",t=!1){this.namespace=e,this.storage=t?sessionStorage:localStorage}getKey(e){return`${this.namespace}:${e}`}get(e){try{const t=this.storage.getItem(this.getKey(e));if(!t)return null;const{value:n,expires:r}=JSON.parse(t);return r&&Date.now()>r?(this.remove(e),null):n}catch{return null}}set(e,t,n){try{const r={value:t,expires:n?Date.now()+n:void 0};this.storage.setItem(this.getKey(e),JSON.stringify(r))}catch{}}remove(e){this.storage.removeItem(this.getKey(e))}clear(){const e=[];for(let t=0;t<this.storage.length;t++){const n=this.storage.key(t);(null==n?void 0:n.startsWith(`${this.namespace}:`))&&e.push(n)}e.forEach(e=>this.storage.removeItem(e))}}function Se(e,t){return new ve(e,t)}const Ie={RUNTIME_VERSION:t,mount:ue,lazyMount:he,batchMount:me,warmup:ge,createTrackingManager:fe,createErrorReporter:be,createPerformanceMonitor:J,getPagePerformance:Q,getResourcePerformance:X,getRuntimeResourcePerformance:Z,createStorageHelper:Se,preconnect:ee,preloadAssets:te,getDeviceId:ne,generateTraceId:re,generateSpanId:se,generateTraceparent:ie,urlUtils:oe,onVisibilityChange:ae,onNetworkChange:ce,isMobile:le,isWeChat:de,supportsWebP:pe,createRuntime:K};return e.ErrorReporter=Ee,e.PerformanceMonitor=G,e.RUNTIME_VERSION=t,e.StorageHelper=ve,e.TrackingManager=ye,e.batchMount=me,e.collectWebVitalsMetrics=z,e.createErrorReporter=be,e.createPerformanceMonitor=J,e.createRuntime=K,e.createStorageHelper=Se,e.createTrackingManager=fe,e.default=Ie,e.generateSpanId=se,e.generateTraceId=re,e.generateTraceparent=ie,e.getDeviceId=ne,e.getPagePerformance=Q,e.getResourcePerformance=X,e.getRuntimeResourcePerformance=Z,e.isMobile=le,e.isWeChat=de,e.lazyMount=he,e.mount=ue,e.onNetworkChange=ce,e.onVisibilityChange=ae,e.preconnect=ee,e.preloadAssets=te,e.supportsWebP=pe,e.urlUtils=oe,e.warmup=ge,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 存储辅助工具
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* 存储辅助类(带命名空间和 TTL)
|
|
6
|
+
*/
|
|
7
|
+
export declare class StorageHelper {
|
|
8
|
+
private namespace;
|
|
9
|
+
private storage;
|
|
10
|
+
constructor(namespace?: string, useSession?: boolean);
|
|
11
|
+
private getKey;
|
|
12
|
+
/**
|
|
13
|
+
* 获取值
|
|
14
|
+
*/
|
|
15
|
+
get<T>(key: string): T | null;
|
|
16
|
+
/**
|
|
17
|
+
* 设置值
|
|
18
|
+
*/
|
|
19
|
+
set<T>(key: string, value: T, ttl?: number): void;
|
|
20
|
+
/**
|
|
21
|
+
* 删除值
|
|
22
|
+
*/
|
|
23
|
+
remove(key: string): void;
|
|
24
|
+
/**
|
|
25
|
+
* 清空命名空间下所有值
|
|
26
|
+
*/
|
|
27
|
+
clear(): void;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* 创建存储辅助类
|
|
31
|
+
*/
|
|
32
|
+
export declare function createStorageHelper(namespace?: string, useSession?: boolean): StorageHelper;
|
|
33
|
+
//# sourceMappingURL=storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;GAEG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,OAAO,CAAU;gBAEb,SAAS,SAAU,EAAE,UAAU,UAAQ;IAKnD,OAAO,CAAC,MAAM;IAId;;OAEG;IACH,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI;IAgB7B;;OAEG;IACH,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI;IAYjD;;OAEG;IACH,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIzB;;OAEG;IACH,KAAK,IAAI,IAAI;CAUd;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,aAAa,CAE3F"}
|