@djvlc/runtime-web 1.1.1 → 1.1.2
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/adapters/openapi-user-adapter.d.ts +17 -0
- package/dist/adapters/openapi-user-adapter.d.ts.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/mount.d.ts.map +1 -1
- package/dist/runtime.esm.js +4109 -4044
- package/dist/runtime.iife.js +1 -1
- package/package.json +4 -2
package/dist/runtime.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=function(e){"use strict";const t="1.1.0";var r=(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))(r||{}),n={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:"回滚失败"};[{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']},{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"]},{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"]},{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']},{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"]},{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", "未知")']},{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"']}].map(e=>e.name);var i=class extends Error{constructor(e){super(e),this.name=this.constructor.name,this.timestamp=new Date,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,type:this.type,message:this.message,retryable:this.retryable,timestamp:this.timestamp.toISOString(),stack:this.stack}}toString(){return`${this.name}: ${this.message}`}},s=class e extends i{constructor(e,t){super(e),this.type="NETWORK_ERROR",this.retryable=!0,this.cause=t}toJSON(){return{...super.toJSON(),cause:this.cause?{name:this.cause.name,message:this.cause.message}:void 0}}static is(t){return t instanceof e}static fromFetchError(t){const r=t.message.toLowerCase();return r.includes("network")||r.includes("failed to fetch")?new e("Network request failed",t):r.includes("dns")||r.includes("getaddrinfo")?new e("DNS resolution failed",t):r.includes("connection refused")||r.includes("econnrefused")?new e("Connection refused",t):r.includes("connection reset")||r.includes("econnreset")?new e("Connection reset",t):r.includes("ssl")||r.includes("certificate")?new e("SSL/TLS error",t):new e(t.message||"Unknown network error",t)}},a=class e extends i{constructor(e){super(`Request timeout after ${e}ms`),this.type="TIMEOUT_ERROR",this.retryable=!0,this.timeoutMs=e}toJSON(){return{...super.toJSON(),timeoutMs:this.timeoutMs}}static is(t){return t instanceof e}},o=class{constructor(e){this.type="bearer",this.getToken=e.getToken,this.headerName=e.headerName??"Authorization",this.prefix=e.prefix??"Bearer"}async authenticate(e){const t=await this.getToken();null!==t&&""!==t&&(e[this.headerName]=`${this.prefix} ${t}`)}},c=class{constructor(e){this.type="api-key",this.apiKey=e.apiKey,this.headerName=e.headerName??"X-API-Key"}authenticate(e){e[this.headerName]=this.apiKey}},u=class{constructor(e){this.type="basic",this.encodedCredentials=function(e){const t=(new TextEncoder).encode(e),r=Array.from(t,e=>String.fromCharCode(e)).join("");return"undefined"!=typeof btoa?btoa(r):(()=>{throw new Error("Base64 encoding is not supported in this environment")})()}(`${e.username}:${e.password}`)}authenticate(e){e.Authorization=`Basic ${this.encodedCredentials}`}},d=class{constructor(e){this.type="custom",this.authenticateFn=e.authenticate}async authenticate(e){await this.authenticateFn(e)}},l=new class{constructor(){this.type="none"}authenticate(e){}};function h(e){return new Promise(t=>setTimeout(t,e))}var p="X-Internal-Request-Key",m=new Map;function f(e){const t=e.headers;return(null==t?void 0:t[p])??""}function y(e={}){var t,r,n;const i=[];var y,v;if(i.push(function(e){const t=e.auth?function(e){switch(e.type){case"bearer":return new o({getToken:e.getToken,headerName:e.headerName,prefix:e.prefix});case"api-key":return new c({apiKey:e.apiKey,headerName:e.headerName});case"basic":return new u({username:e.username,password:e.password});case"custom":return new d({authenticate:e.authenticate});case"none":return l;default:throw new Error(`Unknown auth type: ${e.type}`)}}(e.auth):l;return{async pre(r){const n=`req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,i=`trace_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}_${Math.random().toString(36).slice(2,9)}`,s=`${Date.now()}-${Math.random().toString(36).substring(2,9)}`;m.set(s,{attempt:0,startTime:Date.now(),requestId:n,traceId:i});const a=r.init.headers??{},o={};if(a instanceof Headers)a.forEach((e,t)=>{o[t]=e});else if(Array.isArray(a))for(const[e,t]of a)o[e]=t;else Object.assign(o,a);return o[p]=s,o["X-Request-ID"]=n,o["X-Trace-ID"]=i,e.headers&&Object.assign(o,e.headers),await t.authenticate(o),{url:r.url,init:{...r.init,headers:o}}}}}(e)),e.logger&&i.push((y=e.logger,v=e.debug??!1,{async pre(e){var t;if(!v)return;const r=e.init.method??"GET",n=(null==(t=e.init.headers)?void 0:t["X-Request-ID"])??"";y.debug(`[Request] ${r} ${e.url}`,{requestId:n})},async post(e){var t;const r=f(e.init),n=m.get(r),i=n?Date.now()-n.startTime:0;if(r&&m.delete(r),!v)return;const s=e.init.method??"GET",a=(null==(t=e.init.headers)?void 0:t["X-Request-ID"])??"";y.debug(`[Response] ${s} ${e.url} - ${e.response.status} (${i}ms)`,{requestId:a,status:e.response.status,duration:i})},async onError(e){var t;const r=e.init.method??"GET",n=(null==(t=e.init.headers)?void 0:t["X-Request-ID"])??"",i=f(e.init),s=m.get(i),a=s?Date.now()-s.startTime:0,o=e.error instanceof Error?e.error.message:String(e.error);y.error(`[Error] ${r} ${e.url} - ${o} (${a}ms)`,{requestId:n,error:o,duration:a})}})),!1!==e.enableRetry&&e.retry&&i.push(function(e){const t=e.retry,r=t.maxRetries,n=e.logger,i=e.debug??!1;return{async onError(e){const o=f(e.init),c=m.get(o);if(!c)return;if(!function(e,t,r,n){return!(t>=r)&&(!(e instanceof Error&&"AbortError"===e.name)&&(e instanceof TypeError||e instanceof s?!1!==n.retryOnNetworkError:!(e instanceof a)||!1!==n.retryOnTimeout))}(e.error,c.attempt,r,t))return void m.delete(o);c.attempt++;const u=g(c.attempt,t);if(t.onRetry){const n=e.init.method??"GET";t.onRetry({attempt:c.attempt,maxRetries:r,delayMs:u,error:e.error instanceof Error?e.error:new Error(String(e.error)),url:e.url,method:n})}if(i&&n){const t=e.init.method??"GET";n.debug(`[Retry] ${t} ${e.url} - attempt ${c.attempt}/${r}, delay ${u}ms`)}await h(u);try{const s=await e.fetch(e.url,e.init);if(!s.ok&&function(e,t,r,n){if(t>=r)return!1;return(n.retryableStatusCodes??[429,500,502,503,504]).includes(e)}(s.status,c.attempt,r,t)){c.attempt++;const a=g(c.attempt,t);if(i&&n){const t=e.init.method??"GET";n.debug(`[Retry] ${t} ${e.url} - status ${s.status}, attempt ${c.attempt}/${r}, delay ${a}ms`)}return await h(a),e.fetch(e.url,e.init)}return m.delete(o),s}catch(d){if(c.attempt<r)throw d;throw m.delete(o),d}}}}(e)),null==(t=e.preMiddlewares)?void 0:t.length)for(const s of e.preMiddlewares)i.push({pre:s});if(null==(r=e.postMiddlewares)?void 0:r.length)for(const s of e.postMiddlewares)i.push({post:s});if(null==(n=e.errorMiddlewares)?void 0:n.length)for(const s of e.errorMiddlewares)i.push({onError:s});return i}function g(e,t){const{initialDelayMs:r=1e3,maxDelayMs:n=3e4,backoffStrategy:i="exponential",jitterFactor:s=.1}=t;let a;switch(i){case"fixed":a=r;break;case"linear":a=r*e;break;default:a=r*Math.pow(2,e-1)}if(a=Math.min(a,n),s>0){const e=a*s*(2*Math.random()-1);a=Math.max(0,a+e)}return Math.round(a)}var v="/api/user".replace(/\/+$/,""),w=class{constructor(e={}){this.configuration=e}set config(e){this.configuration=e}get basePath(){return null!=this.configuration.basePath?this.configuration.basePath:v}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||$}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const e=this.configuration.apiKey;if(e)return"function"==typeof e?e:()=>e}get accessToken(){const e=this.configuration.accessToken;if(e)return"function"==typeof e?e:async()=>e}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}},b=new w,I=class e{constructor(e=b){this.configuration=e,this.fetchApi=async(e,t)=>{let r,n={url:e,init:t};for(const s of this.middleware)s.pre&&(n=await s.pre({fetch:this.fetchApi,...n})||n);try{r=await(this.configuration.fetchApi||fetch)(n.url,n.init)}catch(i){for(const e of this.middleware)e.onError&&(r=await e.onError({fetch:this.fetchApi,url:n.url,init:n.init,error:i,response:r?r.clone():void 0})||r);if(void 0===r)throw i instanceof Error?new T(i,"The request failed and the interceptors did not return an alternative response"):i}for(const s of this.middleware)s.post&&(r=await s.post({fetch:this.fetchApi,url:n.url,init:n.init,response:r.clone()})||r);return r},this.middleware=e.middleware}withMiddleware(...e){const t=this.clone();return t.middleware=t.middleware.concat(...e),t}withPreMiddleware(...e){const t=e.map(e=>({pre:e}));return this.withMiddleware(...t)}withPostMiddleware(...e){const t=e.map(e=>({post:e}));return this.withMiddleware(...t)}isJsonMime(t){return!!t&&e.jsonRegex.test(t)}async request(e,t){const{url:r,init:n}=await this.createFetchParams(e,t),i=await this.fetchApi(r,n);if(i&&i.status>=200&&i.status<300)return i;throw new S(i,"Response returned an error code")}async createFetchParams(e,t){let r=this.configuration.basePath+e.path;void 0!==e.query&&0!==Object.keys(e.query).length&&(r+="?"+this.configuration.queryParamsStringify(e.query));const n=Object.assign({},this.configuration.headers,e.headers);Object.keys(n).forEach(e=>void 0===n[e]?delete n[e]:{});const i="function"==typeof t?t:async()=>t,s={method:e.method,headers:n,body:e.body,credentials:this.configuration.credentials},a={...s,...await i({init:s,context:e})};let o;var c;return c=a.body,o="undefined"!=typeof FormData&&c instanceof FormData||a.body instanceof URLSearchParams||function(e){return"undefined"!=typeof Blob&&e instanceof Blob}(a.body)?a.body:this.isJsonMime(n["Content-Type"])?JSON.stringify(a.body):a.body,{url:r,init:{...a,body:o}}}clone(){const e=new(0,this.constructor)(this.configuration);return e.middleware=this.middleware.slice(),e}};I.jsonRegex=new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$","i");var E=I,S=class extends Error{constructor(e,t){super(t),this.response=e,this.name="ResponseError"}},T=class extends Error{constructor(e,t){super(t),this.cause=e,this.name="FetchError"}},A=class extends Error{constructor(e,t){super(t),this.field=e,this.name="RequiredError"}};function R(e,t){return null!=e[t]}function $(e,t=""){return Object.keys(e).map(r=>N(r,e[r],t)).filter(e=>e.length>0).join("&")}function N(e,t,r=""){const n=r+(r.length?`[${e}]`:e);if(t instanceof Array){const e=t.map(e=>encodeURIComponent(String(e))).join(`&${encodeURIComponent(n)}=`);return`${encodeURIComponent(n)}=${e}`}return t instanceof Set?N(e,Array.from(t),r):t instanceof Date?`${encodeURIComponent(n)}=${encodeURIComponent(t.toISOString())}`:t instanceof Object?$(t,n):`${encodeURIComponent(n)}=${encodeURIComponent(String(t))}`}var D=class{constructor(e,t=e=>e){this.raw=e,this.transformer=t}async value(){return this.transformer(await this.raw.json())}};function x(e){if(void 0!==e)return null===e?null:{pageVersionId:e.pageVersionId,componentVersionId:e.componentVersionId,componentInstanceId:e.componentInstanceId,triggerEvent:e.triggerEvent,deviceId:e.deviceId,channel:e.channel,clientTimestamp:void 0===e.clientTimestamp?void 0:e.clientTimestamp.toISOString(),extra:e.extra}}function O(e){return function(e){return null==e?e:{actionDefinitionVersionId:R(e,"actionDefinitionVersionId")?e.actionDefinitionVersionId:void 0,actionType:R(e,"actionType")?e.actionType:void 0,name:R(e,"name")?e.name:void 0,paramsSchema:R(e,"paramsSchema")?e.paramsSchema:void 0,resultSchema:R(e,"resultSchema")?e.resultSchema:void 0}}(e)}function C(e){return function(e){return null==e?e:{type:e.type,payload:R(e,"payload")?e.payload:void 0}}(e)}function q(e){if(void 0!==e)return null===e?null:{queryVersionId:e.queryVersionId,params:e.params,alias:e.alias}}function k(e){if(void 0!==e)return null===e?null:{pageVersionId:e.pageVersionId,componentVersionId:e.componentVersionId}}function P(e){if(void 0!==e)return null===e?null:{queries:e.queries.map(q),context:k(e.context)}}function _(e){return function(e){return null==e?e:{code:R(e,"code")?e.code:void 0,message:R(e,"message")?e.message:void 0}}(e)}function M(e){return function(e){return null==e?e:{success:R(e,"success")?e.success:void 0,data:R(e,"data")?e.data:void 0,error:R(e,"error")?_(e.error):void 0}}(e)}function L(e){return function(e){return null==e?e:{id:e.id,activityId:R(e,"activityId")?e.activityId:void 0,rewardType:e.rewardType,rewardName:R(e,"rewardName")?e.rewardName:void 0,rewardValue:R(e,"rewardValue")?e.rewardValue:void 0,status:e.status,createdAt:new Date(e.createdAt),claimedAt:R(e,"claimedAt")?new Date(e.claimedAt):void 0,expiresAt:R(e,"expiresAt")?new Date(e.expiresAt):void 0}}(e)}function V(e){if(void 0!==e)return null===e?null:{actionType:e.actionType,actionDefinitionVersionId:e.actionDefinitionVersionId,params:e.params,context:x(e.context),idempotencyKey:e.idempotencyKey}}function U(e){return function(e){return null==e?e:{actionId:R(e,"actionId")?e.actionId:void 0,result:R(e,"result")?e.result:void 0,effects:R(e,"effects")?e.effects.map(C):void 0,errorCode:R(e,"errorCode")?e.errorCode:void 0,errorMessage:R(e,"errorMessage")?e.errorMessage:void 0,errorDetails:R(e,"errorDetails")?e.errorDetails:void 0,requestId:R(e,"requestId")?e.requestId:void 0,traceId:R(e,"traceId")?e.traceId:void 0,duration:R(e,"duration")?e.duration:void 0,retryable:R(e,"retryable")?e.retryable:void 0,retryAfter:R(e,"retryAfter")?e.retryAfter:void 0}}(e)}function B(e){return function(e){return null==e?e:{name:R(e,"name")?e.name:void 0,description:R(e,"description")?e.description:void 0,icon:R(e,"icon")?e.icon:void 0}}(e)}function j(e){return function(e){return null==e?e:{id:e.id,name:e.name,type:e.type,status:e.status,description:R(e,"description")?e.description:void 0,startTime:R(e,"startTime")?new Date(e.startTime):void 0,endTime:R(e,"endTime")?new Date(e.endTime):void 0,rules:R(e,"rules")?e.rules:void 0,rewards:R(e,"rewards")?e.rewards.map(B):void 0}}(e)}function F(e){return function(e){return null==e?e:{prizeId:R(e,"prizeId")?e.prizeId:void 0,name:R(e,"name")?e.name:void 0,stock:R(e,"stock")?e.stock:void 0}}(e)}function K(e,t){return null==e?e:{type:e.type,claimed:e.claimed,claimedAt:R(e,"claimedAt")?new Date(e.claimedAt):void 0,claimedPrizeId:R(e,"claimedPrizeId")?e.claimedPrizeId:void 0,availablePrizes:R(e,"availablePrizes")?e.availablePrizes.map(F):void 0}}function H(e){return function(e){return null==e?e:{dayKey:R(e,"dayKey")?e.dayKey:void 0,signed:R(e,"signed")?e.signed:void 0,isMakeup:R(e,"isMakeup")?e.isMakeup:void 0}}(e)}function z(e){return function(e){return null==e?e:{type:R(e,"type")?e.type:void 0,daysNeeded:R(e,"daysNeeded")?e.daysNeeded:void 0,reward:R(e,"reward")?e.reward:void 0}}(e)}function Y(e,t){return null==e?e:{type:e.type,signedToday:e.signedToday,todaySignedAt:R(e,"todaySignedAt")?new Date(e.todaySignedAt):void 0,consecutiveDays:e.consecutiveDays,totalDays:e.totalDays,cycleRecords:e.cycleRecords.map(H),makeupAvailable:e.makeupAvailable,nextReward:R(e,"nextReward")?z(e.nextReward):void 0}}function Q(e){return function(e){return null==e?e:{current:R(e,"current")?e.current:void 0,target:R(e,"target")?e.target:void 0}}(e)}function J(e){return function(e){return null==e?e:{type:R(e,"type")?e.type:void 0,amount:R(e,"amount")?e.amount:void 0}}(e)}function G(e,t){return null==e?e:{type:e.type,freeDrawsRemaining:e.freeDrawsRemaining,todayDrawCount:e.todayDrawCount,totalDrawCount:e.totalDrawCount,pityProgress:R(e,"pityProgress")?Q(e.pityProgress):void 0,resources:R(e,"resources")?e.resources.map(J):void 0}}function X(e){return function(e){return null==e?e:{...K(e),...Y(e),...G(e)}}(e)}function W(e){return function(e){return null==e?e:{activityId:e.activityId,userId:e.userId,activityType:e.activityType,canParticipate:e.canParticipate,notParticipateReason:R(e,"notParticipateReason")?e.notParticipateReason:void 0,remainingCount:R(e,"remainingCount")?e.remainingCount:void 0,typeState:X(e.typeState)}}(e)}function Z(e){return function(e){return null==e?e:{page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages}}(e)}function ee(e){return function(e){return null==e?e:{id:e.id,activityId:R(e,"activityId")?e.activityId:void 0,prizeId:e.prizeId,prizeName:R(e,"prizeName")?e.prizeName:void 0,prizeType:R(e,"prizeType")?e.prizeType:void 0,status:e.status,createdAt:new Date(e.createdAt),claimedAt:R(e,"claimedAt")?new Date(e.claimedAt):void 0}}(e)}function te(e){return function(e){return null==e?e:{name:R(e,"name")?e.name:void 0,amount:R(e,"amount")?e.amount:void 0}}(e)}function re(e){return function(e){return null==e?e:{day:R(e,"day")?e.day:void 0,signedIn:R(e,"signedIn")?e.signedIn:void 0,reward:R(e,"reward")?te(e.reward):void 0}}(e)}function ne(e){return function(e){return null==e?e:{year:e.year,month:e.month,records:e.records.map(re),consecutiveDays:R(e,"consecutiveDays")?e.consecutiveDays:void 0,totalDays:R(e,"totalDays")?e.totalDays:void 0}}(e)}function ie(e){return function(e){return null==e?e:{componentName:R(e,"componentName")?e.componentName:void 0,componentVersion:R(e,"componentVersion")?e.componentVersion:void 0,reason:R(e,"reason")?e.reason:void 0}}(e)}function se(e){return function(e){return null==e?e:{killSwitch:e.killSwitch,blockedComponents:e.blockedComponents.map(ie),flags:e.flags}}(e)}function ae(e){if(void 0!==e)return null===e?null:{noCache:e.noCache,forceRefresh:e.forceRefresh}}function oe(e){if(void 0!==e)return null===e?null:{queryVersionId:e.queryVersionId,params:e.params,cacheControl:ae(e.cacheControl),context:k(e.context)}}function ce(e){return function(e){return null==e?e:{queryVersionId:R(e,"queryVersionId")?e.queryVersionId:void 0,name:R(e,"name")?e.name:void 0,paramsSchema:R(e,"paramsSchema")?e.paramsSchema:void 0,resultSchema:R(e,"resultSchema")?e.resultSchema:void 0,cacheTtl:R(e,"cacheTtl")?e.cacheTtl:void 0}}(e)}function ue(e){return function(e){return null==e?e:{strategyId:R(e,"strategyId")?e.strategyId:void 0,strategyName:R(e,"strategyName")?e.strategyName:void 0,isDefault:R(e,"isDefault")?e.isDefault:void 0}}(e)}function de(e){return function(e){return null==e?e:{id:R(e,"id")?e.id:void 0,name:R(e,"name")?e.name:void 0,versionId:R(e,"versionId")?e.versionId:void 0,hash:R(e,"hash")?e.hash:void 0}}(e)}function le(e){return function(e){return null==e?e:{actions:R(e,"actions")?e.actions.map(de):void 0,queries:R(e,"queries")?e.queries.map(de):void 0}}(e)}function he(e){return function(e){return null==e?e:{js:R(e,"js")?e.js:void 0,css:R(e,"css")?e.css:void 0,chunks:R(e,"chunks")?e.chunks:void 0}}(e)}function pe(e){return function(e){return null==e?e:{name:R(e,"name")?e.name:void 0,version:R(e,"version")?e.version:void 0,integrity:R(e,"integrity")?e.integrity:void 0,assetsUrl:R(e,"assetsUrl")?e.assetsUrl:void 0,entrypoints:R(e,"entrypoints")?he(e.entrypoints):void 0}}(e)}function me(e){return function(e){return null==e?e:{version:R(e,"version")?e.version:void 0,minVersion:R(e,"minVersion")?e.minVersion:void 0}}(e)}function fe(e){return function(e){return null==e?e:{components:R(e,"components")?e.components.map(pe):void 0,runtime:R(e,"runtime")?me(e.runtime):void 0}}(e)}function ye(e){return function(e){return null==e?e:{componentVersions:R(e,"componentVersions")?e.componentVersions:void 0,definitionVersions:R(e,"definitionVersions")?e.definitionVersions:void 0}}(e)}function ge(e){return function(e){return null==e?e:{pageId:R(e,"pageId")?e.pageId:void 0,pageVersionId:R(e,"pageVersionId")?e.pageVersionId:void 0,publishId:R(e,"publishId")?e.publishId:void 0,schemaVersion:R(e,"schemaVersion")?e.schemaVersion:void 0,createdAt:R(e,"createdAt")?new Date(e.createdAt):void 0,createdBy:R(e,"createdBy")?e.createdBy:void 0,contentHash:R(e,"contentHash")?e.contentHash:void 0,bindings:R(e,"bindings")?ye(e.bindings):void 0,runtimeVersion:R(e,"runtimeVersion")?e.runtimeVersion:void 0,env:R(e,"env")?e.env:void 0}}(e)}function ve(e){return function(e){return null==e?e:{schemaVersion:R(e,"schemaVersion")?e.schemaVersion:void 0,pageId:R(e,"pageId")?e.pageId:void 0,pageVersion:R(e,"pageVersion")?e.pageVersion:void 0,title:R(e,"title")?e.title:void 0,initialState:R(e,"initialState")?e.initialState:void 0,bindings:R(e,"bindings")?e.bindings:void 0,root:R(e,"root")?e.root:void 0,config:R(e,"config")?e.config:void 0}}(e)}function we(e){return function(e){return null==e?e:{page:R(e,"page")?ve(e.page):void 0,manifest:R(e,"manifest")?fe(e.manifest):void 0,definitionsDigest:R(e,"definitionsDigest")?le(e.definitionsDigest):void 0,meta:R(e,"meta")?ge(e.meta):void 0}}(e)}function be(e){return function(e){return null==e?e:{pageId:e.pageId,resolvedVersionId:e.resolvedVersionId,cdnBase:e.cdnBase,snapshotUrl:e.snapshotUrl,manifestUrl:e.manifestUrl,ops:se(e.ops),etag:e.etag,cacheTtlSeconds:e.cacheTtlSeconds,rolloutMatch:R(e,"rolloutMatch")?ue(e.rolloutMatch):void 0,snapshot:R(e,"snapshot")?we(e.snapshot):void 0}}(e)}function Ie(e){return function(e){return null==e?e:{eventId:R(e,"eventId")?e.eventId:void 0}}(e)}function Ee(e){return function(e){return null==e?e:{index:R(e,"index")?e.index:void 0,reason:R(e,"reason")?e.reason:void 0}}(e)}function Se(e){return function(e){return null==e?e:{accepted:R(e,"accepted")?e.accepted:void 0,rejected:R(e,"rejected")?e.rejected:void 0,errors:R(e,"errors")?e.errors.map(Ee):void 0}}(e)}function Te(e){if(void 0!==e)return null===e?null:{pageVersionId:e.pageVersionId,componentVersionId:e.componentVersionId,sessionId:e.sessionId,deviceType:e.deviceType,traceId:e.traceId}}function Ae(e){if(void 0!==e)return null===e?null:{eventName:e.eventName,eventType:e.eventType,properties:e.properties,timestamp:void 0===e.timestamp?void 0:e.timestamp.toISOString(),context:Te(e.context)}}function Re(e){if(void 0!==e)return null===e?null:{events:e.events.map(Ae)}}function $e(e){if(void 0!==e)return null===e?null:{actionType:e.actionType,actionDefinitionVersionId:e.actionDefinitionVersionId,params:e.params}}function Ne(e){return function(e){return null==e?e:{path:R(e,"path")?e.path:void 0,message:R(e,"message")?e.message:void 0,code:R(e,"code")?e.code:void 0}}(e)}function De(e){return function(e){return null==e?e:{valid:e.valid,errors:R(e,"errors")?e.errors.map(Ne):void 0}}(e)}var xe=class extends E{async executeActionRaw(e,t){if(null===e.executeActionRequest||void 0===e.executeActionRequest)throw new A("executeActionRequest","Required parameter requestParameters.executeActionRequest was null or undefined when calling executeAction.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/actions/execute",method:"POST",headers:r,query:{},body:V(e.executeActionRequest)},t);return new D(n,e=>function(e){return null==e?e:{success:e.success,code:e.code,message:e.message,data:U(e.data),timestamp:e.timestamp,path:e.path,requestId:R(e,"requestId")?e.requestId:void 0}}(e))}async executeAction(e,t){const r=await this.executeActionRaw(e,t);return await r.value()}async getActionDefinitionRaw(e,t){if(null===e.actionDefinitionVersionId||void 0===e.actionDefinitionVersionId)throw new A("actionDefinitionVersionId","Required parameter requestParameters.actionDefinitionVersionId was null or undefined when calling getActionDefinition.");const r={};void 0!==e.actionDefinitionVersionId&&(r.actionDefinitionVersionId=e.actionDefinitionVersionId);const n={};if(this.configuration&&this.configuration.apiKey&&(n["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/actions/definitions",method:"GET",headers:n,query:r},t);return new D(i,e=>function(e){return null==e?e:{data:O(e.data)}}(e))}async getActionDefinition(e,t){const r=await this.getActionDefinitionRaw(e,t);return await r.value()}async validateActionParamsRaw(e,t){if(null===e.validateActionRequest||void 0===e.validateActionRequest)throw new A("validateActionRequest","Required parameter requestParameters.validateActionRequest was null or undefined when calling validateActionParams.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/actions/validate",method:"POST",headers:r,query:{},body:$e(e.validateActionRequest)},t);return new D(n,e=>function(e){return null==e?e:{data:De(e.data)}}(e))}async validateActionParams(e,t){const r=await this.validateActionParamsRaw(e,t);return await r.value()}},Oe=class extends E{async getActivityInfoRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new A("activityId","Required parameter requestParameters.activityId was null or undefined when calling getActivityInfo.");const r=await this.request({path:"/activities/{activityId}".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:{},query:{}},t);return new D(r,e=>function(e){return null==e?e:{success:R(e,"success")?e.success:void 0,data:R(e,"data")?j(e.data):void 0}}(e))}async getActivityInfo(e,t){const r=await this.getActivityInfoRaw(e,t);return await r.value()}async getActivityStateRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new A("activityId","Required parameter requestParameters.activityId was null or undefined when calling getActivityState.");const r={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/activities/{activityId}/state".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:r,query:{}},t);return new D(n,e=>function(e){return null==e?e:{success:R(e,"success")?e.success:void 0,data:R(e,"data")?W(e.data):void 0}}(e))}async getActivityState(e,t){const r=await this.getActivityStateRaw(e,t);return await r.value()}async getClaimRecordsRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new A("activityId","Required parameter requestParameters.activityId was null or undefined when calling getClaimRecords.");const r={};void 0!==e.pageSize&&(r.pageSize=e.pageSize),void 0!==e.pageToken&&(r.pageToken=e.pageToken);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/activities/{activityId}/claims".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:n,query:r},t);return new D(i,e=>function(e){return null==e?e:{success:R(e,"success")?e.success:void 0,data:R(e,"data")?e.data.map(L):void 0,meta:R(e,"meta")?Z(e.meta):void 0}}(e))}async getClaimRecords(e,t){const r=await this.getClaimRecordsRaw(e,t);return await r.value()}async getLotteryRecordsRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new A("activityId","Required parameter requestParameters.activityId was null or undefined when calling getLotteryRecords.");const r={};void 0!==e.pageSize&&(r.pageSize=e.pageSize),void 0!==e.pageToken&&(r.pageToken=e.pageToken);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/activities/{activityId}/lottery".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:n,query:r},t);return new D(i,e=>function(e){return null==e?e:{success:R(e,"success")?e.success:void 0,data:R(e,"data")?e.data.map(ee):void 0,meta:R(e,"meta")?Z(e.meta):void 0}}(e))}async getLotteryRecords(e,t){const r=await this.getLotteryRecordsRaw(e,t);return await r.value()}async getSigninCalendarRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new A("activityId","Required parameter requestParameters.activityId was null or undefined when calling getSigninCalendar.");const r={};void 0!==e.month&&(r.month=e.month);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/activities/{activityId}/signin/calendar".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:n,query:r},t);return new D(i,e=>function(e){return null==e?e:{success:R(e,"success")?e.success:void 0,data:R(e,"data")?ne(e.data):void 0}}(e))}async getSigninCalendar(e,t){const r=await this.getSigninCalendarRaw(e,t);return await r.value()}},Ce=class extends E{async resolvePageRaw(e,t){if(null===e.pageId||void 0===e.pageId)throw new A("pageId","Required parameter requestParameters.pageId was null or undefined when calling resolvePage.");const r={};void 0!==e.pageId&&(r.pageId=e.pageId),void 0!==e.env&&(r.env=e.env),void 0!==e.uid&&(r.uid=e.uid),void 0!==e.deviceId&&(r.deviceId=e.deviceId),void 0!==e.channel&&(r.channel=e.channel),void 0!==e.includeSnapshot&&(r.includeSnapshot=e.includeSnapshot);const n={};if(this.configuration&&this.configuration.apiKey&&(n["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/page/resolve",method:"GET",headers:n,query:r},t);return new D(i,e=>function(e){return null==e?e:{success:e.success,code:e.code,message:e.message,data:be(e.data),timestamp:e.timestamp,path:e.path,requestId:R(e,"requestId")?e.requestId:void 0}}(e))}async resolvePage(e,t){const r=await this.resolvePageRaw(e,t);return await r.value()}},qe=class extends E{async batchQueryDataRaw(e,t){if(null===e.batchQueryRequest||void 0===e.batchQueryRequest)throw new A("batchQueryRequest","Required parameter requestParameters.batchQueryRequest was null or undefined when calling batchQueryData.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/data/query/batch",method:"POST",headers:r,query:{},body:P(e.batchQueryRequest)},t);return new D(n,e=>function(e){return null==e?e:{success:e.success,data:(t=e.data,r=M,Object.keys(t).reduce((e,n)=>({...e,[n]:r(t[n])}),{}))};var t,r}(e))}async batchQueryData(e,t){const r=await this.batchQueryDataRaw(e,t);return await r.value()}async getQueryDefinitionRaw(e,t){if(null===e.queryVersionId||void 0===e.queryVersionId)throw new A("queryVersionId","Required parameter requestParameters.queryVersionId was null or undefined when calling getQueryDefinition.");const r={};void 0!==e.queryVersionId&&(r.queryVersionId=e.queryVersionId);const n={};if(this.configuration&&this.configuration.apiKey&&(n["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/data/definitions",method:"GET",headers:n,query:r},t);return new D(i,e=>function(e){return null==e?e:{data:ce(e.data)}}(e))}async getQueryDefinition(e,t){const r=await this.getQueryDefinitionRaw(e,t);return await r.value()}async queryDataRaw(e,t){if(null===e.queryDataRequest||void 0===e.queryDataRequest)throw new A("queryDataRequest","Required parameter requestParameters.queryDataRequest was null or undefined when calling queryData.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/data/query",method:"POST",headers:r,query:{},body:oe(e.queryDataRequest)},t);return new D(n,e=>function(e){return null==e?e:{success:e.success,code:e.code,message:e.message,data:e.data,timestamp:e.timestamp,path:e.path,requestId:R(e,"requestId")?e.requestId:void 0,errorCode:R(e,"errorCode")?e.errorCode:void 0,errorMessage:R(e,"errorMessage")?e.errorMessage:void 0,fromCache:R(e,"fromCache")?e.fromCache:void 0,cachedAt:R(e,"cachedAt")?new Date(e.cachedAt):void 0,age:R(e,"age")?e.age:void 0,traceId:R(e,"traceId")?e.traceId:void 0,duration:R(e,"duration")?e.duration:void 0,degraded:R(e,"degraded")?e.degraded:void 0,degradedReason:R(e,"degradedReason")?e.degradedReason:void 0}}(e))}async queryData(e,t){const r=await this.queryDataRaw(e,t);return await r.value()}},ke=class extends E{async trackRaw(e,t){if(null===e.trackRequest||void 0===e.trackRequest)throw new A("trackRequest","Required parameter requestParameters.trackRequest was null or undefined when calling track.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/track",method:"POST",headers:r,query:{},body:Ae(e.trackRequest)},t);return new D(n,e=>function(e){return null==e?e:{success:R(e,"success")?e.success:void 0,data:R(e,"data")?Ie(e.data):void 0}}(e))}async track(e,t){const r=await this.trackRaw(e,t);return await r.value()}async trackBatchRaw(e,t){if(null===e.trackBatchRequest||void 0===e.trackBatchRequest)throw new A("trackBatchRequest","Required parameter requestParameters.trackBatchRequest was null or undefined when calling trackBatch.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/track/batch",method:"POST",headers:r,query:{},body:Re(e.trackBatchRequest)},t);return new D(n,e=>function(e){return null==e?e:{success:R(e,"success")?e.success:void 0,data:R(e,"data")?Se(e.data):void 0}}(e))}async trackBatch(e,t){const r=await this.trackBatchRaw(e,t);return await r.value()}},Pe=class{constructor(e={}){const t=e.baseUrl??"/api",r=[...y({auth:e.auth,retry:e.retry,enableRetry:e.enableRetry,logger:e.logger,debug:e.debug,timeout:e.timeout,headers:e.headers,preMiddlewares:e.preMiddlewares,postMiddlewares:e.postMiddlewares,errorMiddlewares:e.errorMiddlewares}),...e.middlewares??[]];this.configuration=new w({basePath:t,middleware:r,headers:e.headers}),this.pages=new Ce(this.configuration),this.actions=new xe(this.configuration),this.activities=new Oe(this.configuration),this.queries=new qe(this.configuration),this.track=new ke(this.configuration)}},_e=class extends Error{constructor(e,t,r,i){super(t||n[e]||"Unknown error"),this.name="DjvlcRuntimeError",this.code=e,this.details=r,this.traceId=i,this.timestamp=Date.now()}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,traceId:this.traceId,timestamp:this.timestamp}}},Me=class extends _e{constructor(e,t,n){super(r.RESOURCE_PAGE_NOT_FOUND,e,t,n),this.name="PageLoadError"}},Le=class extends _e{constructor(e,t,n,i=r.COMPONENT_LOAD_FAILED,s){super(i,n,{...s,componentName:e,componentVersion:t}),this.name="ComponentLoadError",this.componentName=e,this.componentVersion=t}},Ve=class extends _e{constructor(e,t,n,i){super(r.COMPONENT_INTEGRITY_MISMATCH,`Integrity check failed for ${e}@${t}`,{expectedHash:n,actualHash:i}),this.name="IntegrityError",this.componentName=e,this.componentVersion=t,this.expectedHash=n,this.actualHash=i}},Ue=class extends _e{constructor(e,t,n){super(r.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}},Be=class extends _e{constructor(e,t,n,i){super(r.VALIDATION_EXPRESSION_ERROR,t,{...i,expression:e,position:n}),this.name="ExpressionError",this.expression=e,this.position=n}},je=class extends _e{constructor(e,t,n=r.SYSTEM_INTERNAL_ERROR,i,s){super(n,t,{...s,actionType:e,actionId:i}),this.name="ActionError",this.actionType=e,this.actionId=i}},Fe=class extends _e{constructor(e,t,n=r.SYSTEM_INTERNAL_ERROR,i){super(n,t,{...i,queryId:e}),this.name="QueryError",this.queryId=e}},Ke=class{constructor(e){this.cache=new Map,this.options={env:"prod",cache:{enabled:!0,maxAge:300},...e}}async resolve(e,t){var r,n;const i=this.getCacheKey(e,t);if(null==(r=this.options.cache)?void 0:r.enabled){const t=this.cache.get(i);if(t&&this.isCacheValid(t.timestamp))return this.log("debug",`Page ${e} loaded from cache`),t.data}const s=performance.now();try{const r=await this.callResolveViaAdapter(e,t),a=await this.loadFromCdn(r,e);(null==(n=this.options.cache)?void 0:n.enabled)&&this.cache.set(i,{data:a,timestamp:Date.now()});const o=performance.now()-s;return this.log("info",`Page ${e} resolved in ${o.toFixed(2)}ms`),a}catch(a){if(a instanceof Me)throw a;throw new Me(`Failed to resolve page: ${a instanceof Error?a.message:"Unknown error"}`,{pageId:e})}}async callResolveViaAdapter(e,t){const r=await this.options.userApiAdapter.resolvePage({pageId:e,uid:null==t?void 0:t.uid,deviceId:null==t?void 0:t.deviceId,env:this.options.env,channel:this.options.channel,previewToken:this.options.previewToken});if(!this.isValidPageResolveResponse(r))throw new Me("Invalid page resolve response",{pageId:e});return r}async loadFromCdn(e,t){try{const r=await fetch(e.snapshotUrl,{headers:this.buildHeaders()});if(!r.ok)throw new Me(`Failed to load snapshot: ${r.status}`,{pageId:t});const n=await r.json();return this.convertSnapshotToResult(n,e,t)}catch(r){if(r instanceof Me)throw r;throw new Me(`Failed to load from CDN: ${r instanceof Error?r.message:"Unknown error"}`,{pageId:t})}}convertSnapshotToResult(e,t,r){var n,i,s,a;const o=this.convertSnapshotPageToPageSchema(e.page),c=this.convertSnapshotManifestToPageManifest(e.manifest),u=(null==(i=null==(n=e.definitionsDigest)?void 0:n.actions)?void 0:i.map(e=>e.versionId))||[],d=(null==(a=null==(s=e.definitionsDigest)?void 0:s.queries)?void 0:a.map(e=>e.versionId))||[];return c.actionDefinitionVersionIds=u,c.dataQueryVersionIds=d,{pageId:t.pageId,pageVersionId:t.resolvedVersionId,pageJson:o,manifest:c,runtimeConfig:{blockedComponents:t.ops.blockedComponents.map(e=>({name:e.name,version:e.version||"",reason:e.reason})),killSwitches:t.ops.killSwitch.map(e=>({type:e.targetType,enabled:e.enabled})),features:t.ops.flags},isPreview:"preview"===this.options.env||!!this.options.previewToken}}convertSnapshotPageToPageSchema(e){const t={layout:{canvasType:e.config.canvasType,canvasSize:e.config.canvasSize},styles:e.config.background||e.config.cssVariables?{background:e.config.background,cssVariables:e.config.cssVariables}:void 0},r=Object.keys(e.initialState).length>0?{fields:Object.keys(e.initialState).reduce((t,r)=>{const n=e.initialState[r];let i="string";return"number"==typeof n?i="number":"boolean"==typeof n?i="boolean":Array.isArray(n)?i="array":null!==n&&"object"==typeof n&&(i="object"),t[r]={type:i,initialValue:n},t},{})}:void 0,n={title:e.title};return{schemaVersion:e.schemaVersion,pageId:e.pageId,pageVersion:e.pageVersion,runtime:{name:"djvlc-runtime",version:"1.0.0"},meta:n,config:t,seo:e.seo,state:r,dataBindings:e.bindings,root:e.root}}convertSnapshotManifestToPageManifest(e){return{id:"",pageVersionId:"",manifestVersion:"1.0.0",createdAt:(new Date).toISOString(),contentHash:"",components:e.components.map(e=>({componentId:"",name:e.name,version:e.version,entry:`${e.assetsUrl}/${e.entrypoints.js}`,styleEntry:e.entrypoints.css?`${e.assetsUrl}/${e.entrypoints.css}`:void 0,integrity:e.integrity,preload:e.preload,priority:e.priority})),actionDefinitionVersionIds:[],dataQueryVersionIds:[],runtimeVersion:{min:e.runtime.minVersion,recommended:e.runtime.version}}}isValidPageResolveResponse(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.pageId&&"string"==typeof t.resolvedVersionId&&"string"==typeof t.cdnBase&&"string"==typeof t.snapshotUrl&&"string"==typeof t.manifestUrl&&void 0!==t.ops&&"string"==typeof t.etag&&"number"==typeof t.cacheTtlSeconds}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()}buildHeaders(){return{"Content-Type":"application/json",...this.options.headers}}getCacheKey(e,t){const r=[e,this.options.env,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.filter(Boolean).join(":")}isCacheValid(e){var t;const r=1e3*((null==(t=this.options.cache)?void 0:t.maxAge)??300);return Date.now()-e<r}log(e,t){this.options.logger&&this.options.logger[e](t)}},He={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"},ze=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 Ue(e.name,e.version,"Component is blocked");const r=this.loadedComponents.get(t);if(r)return r;const n=this.loadingPromises.get(t);if(n)return n;const i=this.loadComponent(e);this.loadingPromises.set(t,i);try{const e=await i;return this.loadedComponents.set(t,e),e}finally{this.loadingPromises.delete(t)}}async loadAll(e){const t=new Map,{concurrency:r=4}=this.options,n=e.components;for(let i=0;i<n.length;i+=r){const e=n.slice(i,i+r).map(async e=>{const r=this.getComponentKey(e.name,e.version),n=performance.now();try{const i=await this.load(e);t.set(r,{name:e.name,version:e.version,status:"loaded",component:i.Component,loadTime:performance.now()-n})}catch(i){const s=i instanceof Ue?"blocked":"failed";if(t.set(r,{name:e.name,version:e.version,status:s,error:i instanceof Error?i.message:"Unknown error",loadTime:performance.now()-n}),"critical"===e.priority)throw i}});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(),r=this.resolveUrl(e.entry);this.log("debug",`Loading component ${e.name}@${e.version}`);try{const n=await this.fetchWithTimeout(r);if(!n.ok)throw new Le(e.name,e.version,`Failed to fetch component: ${n.status} ${n.statusText}`);const i=await n.text();this.options.enableSRI&&e.integrity&&await this.validateIntegrity(e,i);const s=await this.executeScript(i,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:s,loadTime:a}}catch(n){if(n instanceof Le||n instanceof Ve||n instanceof Ue)throw n;throw new Le(e.name,e.version,`Failed to load component: ${n instanceof Error?n.message:"Unknown error"}`)}}async fetchWithTimeout(e){const t=new AbortController,r=setTimeout(()=>t.abort(),this.options.timeout),n={signal:t.signal,credentials:"omit",headers:this.options.headers?{...this.options.headers}:void 0},i=this.options.fetchComponentScript??fetch;try{return await i(e,n)}finally{clearTimeout(r)}}async validateIntegrity(e,t){if(!e.integrity)return;const[r,n]=e.integrity.split("-");if(!r||!n)throw new Ve(e.name,e.version,e.integrity,"Invalid format");const i=He[r.toLowerCase()];if(!i)throw new Ve(e.name,e.version,e.integrity,`Unsupported SRI algorithm: ${r}, expected sha256/sha384/sha512`);const s=await crypto.subtle.digest(i,(new TextEncoder).encode(t)),a=Array.from(new Uint8Array(s)),o=btoa(String.fromCharCode(...a));if(o!==n)throw new Ve(e.name,e.version,n,o)}async executeScript(e,t){const r=new Blob([e],{type:"application/javascript"}),n=URL.createObjectURL(r);try{const e=await import(n),r=e.default??e[t.name]??e[this.kebabToPascal(t.name)]??e.Component;if(!r)throw new Le(t.name,t.version,"Component module does not export a valid component (expected default or Component)");return r}finally{URL.revokeObjectURL(n)}}kebabToPascal(e){return e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}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)}},Ye=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.setAttribute("as","script"),r.href=e,t&&(r.setAttribute("integrity",t),r.setAttribute("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.setAttribute("as","style"),r.href=e,t&&(r.setAttribute("integrity",t),r.setAttribute("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.setAttribute("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.setAttribute("as",t),document.head.appendChild(r)}loadStylesheet(e,t){return new Promise((r,n)=>{const i=document.createElement("link");i.rel="stylesheet",i.href=e,t&&(i.integrity=t,i.crossOrigin="anonymous"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load stylesheet: ${e}`)),document.head.appendChild(i)})}loadScript(e,t){return new Promise((r,n)=>{const i=document.createElement("script");i.src=e,i.async=!0,t&&(i.integrity=t,i.crossOrigin="anonymous"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.body.appendChild(i)})}},Qe=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,r=this.initializePageState(t);e.preloadedData&&Object.assign(r,e.preloadedData),this.setState({page:e,variables:r})}initializePageState(e){const t={};if(e.state&&e.state.fields)for(const[r,n]of Object.entries(e.state.fields))if(n&&"object"==typeof n){const e=n;t[r]=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 r=this.getVariable(e);if(e.includes(".")){const r={...this.state.variables};this.setNestedValue(r,e,t),this.setState({variables:r})}else this.setState({variables:{...this.state.variables,[e]:t}});this.notifyChange({key:e,oldValue:r,newValue:t})}setVariables(e){const t=[];for(const[r,n]of Object.entries(e)){const e=this.getVariable(r);t.push({key:r,oldValue:e,newValue:n})}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,...r}=this.state.queries;this.setState({queries:r})}setComponentStatus(e,t){const r=new Map(this.state.components);r.set(e,t),this.setState({components:r})}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,pageId:null==(t=this.state.page)?void 0:t.pageId,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(r){}})}getNestedValue(e,t){const r=t.split(".");let n=e;for(const i of r){if(null==n)return;n=n[i]}return n}setNestedValue(e,t,r){const n=t.split(".");let i=e;for(let s=0;s<n.length-1;s++){const e=n[s];void 0!==i[e]&&null!==i[e]||(i[e]={}),i=i[e]}i[n[n.length-1]]=r}createInitialState(){return{phase:"idle",page:null,variables:{},queries:{},components:new Map,error:null,destroyed:!1}}},Je=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[r,n]of this.bindings)r!==e.id&&(null==(t=n.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(r));if(e.dependencies)for(const r of e.dependencies)for(const[t,n]of this.bindings)t!==e.id&&n.binding.targetState===r&&(this.bindingDependencies.has(t)||this.bindingDependencies.set(t,new Set),this.bindingDependencies.get(t).add(e.id))}async initializeBindings(e){var t,r;const n=[];for(const a of this.bindings.values())"eager"===a.binding.loadStrategy&&n.push(a.binding);const i=this.topologicalSort(n),s=this.createLoadBatches(i);for(const a of s){const n=await Promise.allSettled(a.map(t=>this.loadBinding(t.id,e))),i=new Map;n.forEach((e,t)=>{const r=a[t].id;"fulfilled"===e.status?i.set(r,{success:!0,data:e.value}):i.set(r,{success:!1,error:e.reason})}),null==(r=(t=this.options).onBatchComplete)||r.call(t,i)}}topologicalSort(e){const t=new Map(e.map(e=>[e.id,e])),r=new Set,n=[],i=e=>{if(!r.has(e.id)){if(r.add(e.id),e.dependencies)for(const n of e.dependencies)for(const[e,s]of t)s.targetState!==n||r.has(e)||i(s);n.push(e)}};for(const s of e)i(s);return n}createLoadBatches(e){const t=[],r=new Set;for(;r.size<e.length;){const n=[];for(const t of e){if(r.has(t.id))continue;let i=!0;if(t.dependencies)for(const n of t.dependencies){for(const t of e)if(t.targetState===n&&!r.has(t.id)){i=!1;break}if(!i)break}i&&n.push(t)}if(0===n.length)for(const t of e)if(!r.has(t.id)){n.push(t),this.log("warn",`Possible circular dependency detected at binding: ${t.id}`);break}n.forEach(e=>r.add(e.id)),n.length>0&&t.push(n)}return t}async loadBinding(e,t,r=!1){var n,i,s;const a=this.bindings.get(e);if(!a)throw new Fe(e,`Data binding not found: ${e}`);const{binding:o}=a;if(!o.condition||this.evaluateCondition(o.condition,t)){if(!r&&this.isCacheValid(a))return this.log("debug",`Binding ${e} returned from cache`),a.cachedData;if(a.loading)this.log("debug",`Binding ${e} is already loading`);else{a.loading=!0;try{const r=this.resolveParams(o.params||{},t),c=await this.executeWithRetry(o,r),u=o.transform?this.applyTransform(c,o.transform,t):c;return a.cachedData=u,a.lastLoadTime=Date.now(),(null==(n=o.cache)?void 0:n.ttl)&&(a.cacheExpireTime=Date.now()+1e3*o.cache.ttl),a.retryCount=0,this.options.stateSetter.setVariable(o.targetState,u),this.setupAutoRefresh(a,t),null==(s=(i=this.options).onDataLoaded)||s.call(i,e,u),this.log("info",`Binding ${e} loaded successfully`),u}catch(c){throw await this.handleLoadError(a,c,t),c}finally{a.loading=!1}}}else this.log("debug",`Binding ${e} skipped by condition`)}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 r=this.dependencyGraph.get(e);if(!r||0===r.size)return;this.log("debug",`State ${e} changed, refreshing dependent bindings`);const n=Array.from(r).map(e=>this.loadBinding(e,t,!0));await Promise.allSettled(n)}async triggerManualLoad(e,t){const r=this.bindings.get(e);if(!r)throw new Fe(e,`Data binding not found: ${e}`);return"manual"!==r.binding.loadStrategy&&this.log("warn",`Binding ${e} is not manual strategy`),this.loadBinding(e,t,!0)}checkVisibility(e,t,r){const n=this.bindings.get(e);n&&"lazy"===n.binding.loadStrategy&&t&&!n.lastLoadTime&&this.loadBinding(e,r).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 r,n,i,s,a,o;const c=(null==(n=null==(r=e.onError)?void 0:r.retry)?void 0:n.maxRetries)??0,u=(null==(s=null==(i=e.onError)?void 0:i.retry)?void 0:s.backoffMs)??1e3,d=(null==(o=null==(a=e.onError)?void 0:a.retry)?void 0:o.backoff)??"fixed";let l;for(let p=0;p<=c;p++)try{const r=await this.options.requester.requestData(e.queryVersionId,t);if(!r.success)throw new Fe(e.queryVersionId,r.message||"Query failed",void 0,{params:t});return r.data}catch(h){if(l=h,this.log("warn",`Query attempt ${p+1}/${c+1} failed:`,h),p<c){const e="exponential"===d?u*Math.pow(2,p):u;await this.delay(e)}}throw l||new Error("Query failed after all retries")}async handleLoadError(e,t,r){var n,i;const{binding:s}=e,a=s.onError;e.retryCount++,void 0!==(null==a?void 0:a.fallbackValue)&&this.options.stateSetter.setVariable(s.targetState,a.fallbackValue),(null==a?void 0:a.showError)&&(null==(i=(n=this.options).onDataError)||i.call(n,s.id,t)),this.log("error",`Binding ${s.id} load failed:`,t)}setupAutoRefresh(e,t){e.refreshTimer&&(clearInterval(e.refreshTimer),e.refreshTimer=void 0);const r=e.binding.refreshInterval;!r||r<=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*r))}isCacheValid(e){return!(!e.cachedData||!e.lastLoadTime||e.cacheExpireTime&&Date.now()>e.cacheExpireTime)}resolveParams(e,t){const r={};for(const[n,i]of Object.entries(e))r[n]=this.resolveValue(i,t);return r}resolveValue(e,t){if(null==e)return e;if("object"==typeof e&&!Array.isArray(e)){const r=e;if("expression"===r.type||"binding"===r.type)return this.options.expressionEngine.evaluateWithFallback(r.expression,t,r.fallback);const n={};for(const[e,i]of Object.entries(r))n[e]=this.resolveValue(i,t);return n}return"string"==typeof e&&e.includes("${")?this.options.expressionEngine.evaluateTemplate(e,t):e}evaluateCondition(e,t){const r=void 0===e.fallback||e.fallback,n=this.options.expressionEngine.evaluateWithFallback(e.value,t,r);return Boolean(n)}applyTransform(e,t,r){const n={...r,local:{...r.local||{},$data:e,$response:e}},i=void 0!==t.fallback?t.fallback:e;return this.options.expressionEngine.evaluateWithFallback(t.value,n,i)}delay(e){return new Promise(t=>setTimeout(t,e))}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},Ge=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}},Xe=class e{constructor(e){this.debounceTimers=new Map,this.throttleTimers=new Map,this.options=e}async handleEvent(e,t,r){if(e.condition&&!this.evaluateCondition(e.condition,r,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 n={$event:t,$prevResult:void 0,$results:{}};await this.executeActionChain(e.actions,r,n)}async executeActionChain(e,t,r){const n=[];for(let i=0;i<e.length;i++){const s=e[i];if(s.condition){const e=this.buildActionContext(t,r);if(!this.evaluateCondition(s.condition,e,r.$event)){this.log("debug",`Action ${s.id||i} skipped by condition`);continue}}const a=this.executeSingleAction(s,t,r);s.async?n.push(a):await a}n.length>0&&await Promise.allSettled(n)}async executeSingleAction(e,t,r){var n,i,s,a,o,c;const u=e.id||e.alias||e.builtinAction||e.actionDefinitionVersionId||"unknown";e.silent||this.options.executor.showLoading();try{const o=this.buildActionContext(t,r),c=this.resolveParams(e.params||{},o);null==(i=(n=this.options).onActionStart)||i.call(n,e,c);const d=await this.executeWithRetry(e,c);r.$prevResult=d,e.id&&(r.$results[e.id]=d),null==(a=(s=this.options).onActionComplete)||a.call(s,e,{success:!0,data:d}),this.log("debug",`Action ${u} completed successfully`),e.onSuccess&&e.onSuccess.length>0&&await this.executeActionChain(e.onSuccess,t,r)}catch(d){this.log("error",`Action ${u} failed:`,d),null==(c=(o=this.options).onActionComplete)||c.call(o,e,{success:!1,error:d}),e.onError&&e.onError.length>0&&await this.executeActionChain(e.onError,t,{...r,$prevResult:{error:d.message}})}finally{e.silent||this.options.executor.hideLoading(),e.onFinally&&e.onFinally.length>0&&await this.executeActionChain(e.onFinally,t,r)}}async executeWithRetry(e,t){var r,n,i,s,a;const o=(null==(n=null==(r=e.policy)?void 0:r.retry)?void 0:n.maxAttempts)??1,c=(null==(s=null==(i=e.policy)?void 0:i.retry)?void 0:s.backoffMs)??1e3,u=null==(a=e.policy)?void 0:a.timeoutMs;let d;for(let h=1;h<=o;h++)try{let r;if(e.builtinAction)r=this.executeBuiltinAction(e.builtinAction,t);else{if(!e.actionDefinitionVersionId)throw new je("unknown","Action must specify builtinAction or actionDefinitionVersionId");r=this.executeCustomAction(e.actionDefinitionVersionId,t)}return u&&(r=this.withTimeout(r,u)),await r}catch(l){d=l,this.log("warn",`Action attempt ${h}/${o} failed:`,l),h<o&&await this.delay(c*h)}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 je(e,`Unknown builtin action: ${e}`)}}async executeCustomAction(e,t){const r=e.split("@")[0],n=await this.options.executor.executeAction(r,{...t,actionDefinitionVersionId:e});if(!n.success)throw new je(r,n.errorMessage||"Action execution failed",void 0,e,{errorCode:n.errorCode});return n.data}resolveParams(e,t){const r={};for(const[n,i]of Object.entries(e))r[n]=this.resolveValue(i,t);return r}resolveValue(t,r){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,r,t)}return t.includes("${")?this.options.expressionEngine.evaluateTemplate(t,r):t}if("number"==typeof t||"boolean"==typeof t)return t;if(Array.isArray(t))return t.map(e=>this.resolveValue(e,r));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,r,e.fallback)}const i={};for(const[e,t]of Object.entries(n))i[e]=this.resolveValue(t,r);return i}return t}evaluateCondition(e,t,r){const n={...t,local:{...t.local||{},$event:r}},i=void 0===e.fallback||e.fallback,s=this.options.expressionEngine.evaluateWithFallback(e.value,n,i);return Boolean(s)}buildActionContext(e,t){return{...e,local:{...e.local||{},$event:t.$event,$prevResult:t.$prevResult,$results:t.$results}}}withTimeout(e,t){return new Promise((r,n)=>{const i=setTimeout(()=>{n(new Error(`Action timed out after ${t}ms`))},t);e.then(e=>{clearTimeout(i),r(e)}).catch(e=>{clearTimeout(i),n(e)})})}debounce(e,t){return new Promise(r=>{const n=this.debounceTimers.get(e);n&&clearTimeout(n);const i=setTimeout(()=>{this.debounceTimers.delete(e),r()},t);this.debounceTimers.set(e,i)})}throttle(e,t){const r=Date.now();return!(r-(this.throttleTimers.get(e)??0)<t||(this.throttleTimers.set(e,r),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,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}};Xe.EXPRESSION_TYPES=["state","binding","local","template","computed"];var We=Xe,Ze=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];return["==","!=",">=","<=","&&","||","??"].includes(t)?(this.pos+=2,{type:"OPERATOR",value:t,start:e,end:this.pos}):["+","-","*","/","%",">","<","!"].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]||""}},et={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 n=String(e??""),i=Number(t)||0,s=void 0!==r?Number(r):void 0;return n.substring(i,void 0!==s?i+s: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,n=Number(t)||0,i=Math.pow(10,n);return Math.round(r*i)/i},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=>Array.isArray(e)&&0!==e.length?e.reduce((e,t)=>e+(Number(t)||0),0)/e.length:0,random:()=>Math.random(),randomInt:(e,t)=>{const r=Math.ceil(Number(e)||0),n=Math.floor(Number(t)||100);return Math.floor(Math.random()*(n-r+1))+r},now:()=>Date.now(),today:()=>(new Date).toISOString().split("T")[0],dateFormat:(e,t)=>{const r=new Date(Number(e)||Date.now()),n=e=>e.toString().padStart(2,"0");return String(t||"YYYY-MM-DD").replace("YYYY",r.getFullYear().toString()).replace("MM",n(r.getMonth()+1)).replace("DD",n(r.getDate())).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(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()),n=new Date(Number(t)||Date.now()),i=Math.abs(n.getTime()-r.getTime());return Math.floor(i/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 n=String(t).split(".");let i=e;for(const s of n){if(null==i)return r;i=i[s]}return i??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 n=Number(e);return n>=Number(t)&&n<=Number(r)},formatNumber:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return r.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})},formatCurrency:(e,t)=>{const r=Number(e)||0,n=String(t||"CNY");return r.toLocaleString("zh-CN",{style:"currency",currency:n})},formatPercent:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return(100*r).toFixed(n)+"%"},currency:(e,t,r)=>{const n=Number(e)||0,i=String(t??"¥"),s=Number(r)??2;return`${i}${n.toLocaleString(void 0,{minimumFractionDigits:s,maximumFractionDigits:s})}`},percent:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return(100*r).toFixed(n)+"%"},number:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return r.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})},pluralize:(e,t,r)=>{const n=Number(e)||0;return`${n} ${String(1===n?t:r)}`},mask:(e,t,r,n)=>{const i=String(e??""),s=Number(t)||3,a=Number(r)||4,o=String(n??"*");if(i.length<=s+a)return i;const c=i.slice(0,s),u=i.slice(-a);return c+o.repeat(i.length-s-a)+u},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,r)=>{const n=Number(e)||0,i=Number(t)||0,s=Number(r)||100;return Math.min(Math.max(n,i),s)},length:e=>Array.isArray(e)||"string"==typeof e?e.length:0,average:e=>Array.isArray(e)&&0!==e.length?e.reduce((e,t)=>e+(Number(t)||0),0)/e.length:0,dateAdd:(e,t,r)=>{const n=new Date(Number(e)||Date.now()),i=Number(t)||0;switch(String(r??"day").toLowerCase()){case"year":case"years":n.setFullYear(n.getFullYear()+i);break;case"month":case"months":n.setMonth(n.getMonth()+i);break;case"week":case"weeks":n.setDate(n.getDate()+7*i);break;case"day":case"days":default:n.setDate(n.getDate()+i);break;case"hour":case"hours":n.setHours(n.getHours()+i);break;case"minute":case"minutes":n.setMinutes(n.getMinutes()+i)}return n.getTime()},dateDiff:(e,t,r)=>{const n=new Date(Number(e)||Date.now()),i=new Date(Number(t)||Date.now()).getTime()-n.getTime();switch(String(r??"day").toLowerCase()){case"year":case"years":return Math.floor(i/31536e6);case"month":case"months":return Math.floor(i/2592e6);case"week":case"weeks":return Math.floor(i/6048e5);case"day":case"days":default:return Math.floor(i/864e5);case"hour":case"hours":return Math.floor(i/36e5);case"minute":case"minutes":return Math.floor(i/6e4)}},$if:(e,t,r)=>e?t:r,toBoolean:e=>"string"==typeof e?"false"!==e.toLowerCase()&&"0"!==e&&""!==e:Boolean(e),substring:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=void 0!==r?Number(r):void 0;return n.substring(i,s)},padStart:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=String(r??" ");return n.padStart(i,s)},padEnd:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=String(r??" ");return n.padEnd(i,s)},repeat:(e,t)=>{const r=String(e??""),n=Math.max(0,Math.floor(Number(t)||0));return r.repeat(n)}},tt={"||":1,"??":1,"&&":2,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},rt=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();return this.expect("COLON"),{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 n=tt[r.value];if(void 0===n||n<e)break;this.advance();const i=this.parseBinary(n+1);t={type:"binary",operator:r.value,left:t,right:i,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(!(r in et))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()}},nt=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 Be("",`Unknown node type: ${e.type}`)}}evaluateLiteral(e){return e.value}evaluateIdentifier(e,t){var r,n;const i=e.name;switch(i){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==(r=t.local)?void 0:r.item;case"index":return null==(n=t.local)?void 0:n.index;default:if(t.local&&i in t.local)return t.local[i];throw new Be("",`Unknown variable '${i}'. Available: state, binding, local, props, event`)}}evaluateMember(e,t){const r=this.evaluateNode(e.object,t);if(null==r)return;let n;return n=e.computed?this.evaluateNode(e.property,t):e.property,"object"==typeof r&&null!==r?r[n]:void 0}evaluateCall(e,t){const r=et[e.callee];if(!r)throw new Be("",`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)return this.evaluateNode(e.left,t)||this.evaluateNode(e.right,t);if("??"===r){const r=this.evaluateNode(e.left,t);return null!=r?r:this.evaluateNode(e.right,t)}const n=this.evaluateNode(e.left,t),i=this.evaluateNode(e.right,t);switch(r){case"+":return"string"==typeof n||"string"==typeof i?String(n)+String(i):n+i;case"-":return n-i;case"*":return n*i;case"/":return n/i;case"%":return n%i;case"==":return n===i;case"!=":return n!==i;case"<":return n<i;case">":return n>i;case"<=":return n<=i;case">=":return n>=i;default:throw new Be("",`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 Be("",`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 Be("","Maximum recursion depth exceeded");if(Date.now()-this.startTime>(this.options.timeout??1e3))throw new Be("","Expression evaluation timeout")}},it=class{constructor(e={}){this.astCache=new Map,this.options={cacheAST:!0,maxCacheSize:1e3,...e},this.evaluator=new nt(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 n="string"==typeof e?e:e.value,i="object"==typeof e&&void 0!==e.fallback?e.fallback:r,s=this.evaluate(n,t);return s.error?(this.log("warn",`Expression evaluation failed: ${s.error.message}`,n),i):s.value}evaluateTemplate(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{const n=this.evaluate(r.trim(),t);return n.error?(this.log("warn",`Template expression failed: ${n.error.message}`,r),""):String(n.value??"")})}parse(e){if(this.options.cacheAST){const t=this.astCache.get(e);if(t)return t}try{const t=new Ze(e).tokenize(),r=new rt(t).parse();return this.options.cacheAST&&(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)),r}catch(t){throw new Be(e,t instanceof Error?t.message:"Parse error")}}validate(e){const t=[],r=[],n=[],i=[];try{const t=this.parse(e);return this.collectReferences(t,n,i),{valid:!0,errors:[],warnings:r,referencedPaths:n,usedFunctions:i}}catch(s){return t.push({type:"invalid_syntax",message:s instanceof Error?s.message:"Parse error"}),{valid:!1,errors:t,warnings:r,referencedPaths:n,usedFunctions:i}}}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}},st=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}`,r=localStorage.getItem(t);if(!r)return null;try{const e=JSON.parse(r);return e.expires&&Date.now()>e.expires?(localStorage.removeItem(t),null):e.value}catch{return null}},set:(e,t,r)=>{const n=`${this.storageNamespace}:${e}`,i={value:t,expires:(null==r?void 0:r.ttlSeconds)?Date.now()+1e3*r.ttlSeconds:void 0};("session"===(null==r?void 0:r.level)?sessionStorage:localStorage).setItem(n,JSON.stringify(i))},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 r=localStorage.key(t);(null==r?void 0:r.startsWith(e))&&localStorage.removeItem(r)}for(let t=sessionStorage.length-1;t>=0;t--){const r=sessionStorage.key(t);(null==r?void 0:r.startsWith(e))&&sessionStorage.removeItem(r)}}},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 r=new URLSearchParams(e.query);t+=(t.includes("?")?"&":"?")+r.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;this.options.userApiAdapter.track({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}})}async requestData(e,t){this.log("debug",`Requesting data: ${e}`,t);const r=performance.now(),n=this.options.context;try{const i=await this.options.userApiAdapter.executeQuery({queryVersionId:e,params:t??{},context:{pageVersionId:n.pageVersionId,uid:n.userId,deviceId:n.deviceId}}),s=performance.now()-r;if(this.log("debug",`Data query completed in ${s.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(i){const t=performance.now()-r;throw this.log("error",`Data query failed: ${e} (${t.toFixed(2)}ms)`,i),i}}async executeAction(e,t={}){this.log("debug",`Executing action: ${e}`,t);const r=performance.now(),n=this.options.context,i=this.generateIdempotencyKey(e,t);this.track({eventName:"djvlc_action_start",params:{actionType:e,idempotencyKey:i},type:"custom"});try{const s=await this.options.userApiAdapter.executeAction({actionType:e,params:t||{},context:{pageVersionId:n.pageVersionId,uid:n.userId,deviceId:n.deviceId,channel:n.channel,appId:n.appId},idempotencyKey:i}),a=performance.now()-r;return this.log("debug",`Action completed in ${a.toFixed(2)}ms`,{success:s.success}),this.track({eventName:s.success?"djvlc_action_success":"djvlc_action_fail",params:{actionType:e,idempotencyKey:i,duration:Math.round(a),errorCode:s.errorCode},type:"custom"}),s}catch(s){const t=performance.now()-r;return this.log("error",`Action failed: ${e} (${t.toFixed(2)}ms)`,s),this.track({eventName:"djvlc_action_error",params:{actionType:e,idempotencyKey:i,duration:Math.round(t),errorMessage:s instanceof Error?s.message:"Unknown error"},type:"custom"}),{success:!1,errorCode:"NETWORK_ERROR",errorMessage:s instanceof Error?s.message:"Action failed"}}}async openDialog(e){return this.log("debug","Open dialog:",e),new Promise(t=>{const r=new CustomEvent("djvlc:openDialog",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(r),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");switch(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"}),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}return e.url&&await this.clipboard.write(e.url)?(this.showToast({message:"链接已复制",type:"success"}),{success:!0,channel:"link"}):{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 r=new CustomEvent("djvlc:showActionSheet",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(r),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}}generateIdempotencyKey(e,t){const r=Date.now(),n=JSON.stringify(t||{});return`${e}:${r}:${this.simpleHash(n)}`}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)}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,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},at=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,r]=e.split("@");t&&r&&this.blockedComponentsMap.set(e,{name:t,version:r,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 r=`${e}@${t}`;this.blockedComponentsMap.delete(r),this.log("info",`Component unblocked: ${r}`)}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,r){if(!this.allowedCapabilitiesSet)return{valid:!0,disallowed:[]};const n=r.filter(e=>!this.allowedCapabilitiesSet.has(e));return n.length>0&&this.log("warn",`Component ${e}@${t} uses disallowed capabilities: ${n.join(", ")}`),{valid:0===n.length,disallowed:n}}async validateIntegrity(e,t,r,n){if(!this.options.enableSRI)return;const[i,s]=n.split("-");if(!i||!s)throw new Ve(e,t,n,"Invalid integrity format");const a=await this.computeHash(r,i);if(a!==s)throw this.log("error",`Integrity check failed for ${e}@${t}`),new Ve(e,t,s,a);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 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)||t.hostname===r.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 r=t.hostname;return"localhost"===r||"127.0.0.1"===r||r.startsWith("192.168.")||r.startsWith("10.")||r.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||[],r=["'self'",...e].join(" "),n=["'self'",...t,...e].join(" ");return["default-src 'self'",`script-src ${r}`,`style-src ${["'self'","'unsafe-inline'",...e].join(" ")}`,`img-src ${["'self'","data:","blob:",...e].join(" ")}`,`font-src ${["'self'","data:",...e].join(" ")}`,`connect-src ${n}`,"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 r=this.getBlockedInfo(e,t);if(r)throw new Ue(e,t,r.reason)}createSafeEvaluator(){return(e,t)=>{const r=Object.keys(t),n=Object.values(t);return new Function(...r,`"use strict"; return (${e});`)(...n)}}async computeHash(e,t){const r=(new TextEncoder).encode(e),n=await crypto.subtle.digest(t.toUpperCase(),r),i=Array.from(new Uint8Array(n));return btoa(String.fromCharCode(...i))}log(e,t,...r){this.options.logger&&this.options.logger[e](t,...r)}},ot=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(),r=this.shouldSample?"01":"00";return`00-${this.traceId}-${t}-${r}`}parseTraceparent(e){const t=e.split("-");if(4!==t.length)return null;const[,r,n,i]=t;return{traceId:r,parentSpanId:n,sampled:"01"===i}}startSpan(e,t,r){const n={spanId:this.generateSpanId(),traceId:this.traceId,parentSpanId:t,name:e,startTime:performance.now(),attributes:{pageVersionId:this.options.pageVersionId,...r}};return this.spans.set(n.spanId,n),this.log("debug",`Span started: ${e} (${n.spanId})`),n}endSpan(e,t="ok",r){const n=this.spans.get(e);if(n){n.endTime=performance.now(),n.status=t,r&&(n.attributes={...n.attributes,...r});const i=n.endTime-n.startTime;this.log("debug",`Span ended: ${n.name} (${e}) - ${i.toFixed(2)}ms [${t}]`)}}recordPageLoad(e){this.recordMetricInternal({type:"pageLoadTime",value:e,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordComponentLoad(e,t,r,n){this.recordMetricInternal({type:"componentLoadTime",value:r,pageVersionId:this.options.pageVersionId,componentName:e,componentVersion:t,timestamp:Date.now()}),n||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,r,n){this.recordMetricInternal({type:"actionExecuteTime",value:r,pageVersionId:this.options.pageVersionId,actionType:e,timestamp:Date.now()}),n||this.recordError(new Error(`Action failed: ${e}`),{actionId:t})}recordQueryExecute(e,t,r,n=!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: ${n}, success: ${r}`)}recordExpressionEval(e,t,r){t>1&&this.recordMetricInternal({type:"expressionEvalTime",value:t,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordError(e,t){var r,n;const i={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(i),this.log("error",`Error recorded: ${e.message}`),null==(n=(r=this.options).onError)||n.call(r,i),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),r=this.metrics.find(e=>"firstRenderTime"===e.type);return{pageLoadTime:null==t?void 0:t.value,firstRenderTime:null==r?void 0:r.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,r;this.metrics.push(e),null==(r=(t=this.options).onMetric)||r.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,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},ct=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 r=this.renderNode(e.root);r&&t.appendChild(r),this.log("info",`Page rendered with root component: ${e.root.componentType}`)}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}}getContext(){return{...this.expressionContext}}destroy(){this.cleanup(),this.container&&(this.container.innerHTML=""),this.log("debug","Renderer destroyed")}cleanup(){this.componentEventListeners.forEach((e,t)=>{const r=this.renderedElements.get(t);r&&e.forEach(({event:e,handler:t})=>{r.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:r,componentVersion:n}=e;try{if(e.condition&&!this.evaluateCondition(e.condition))return this.log("debug",`Component ${t} hidden by condition`),null;if(e.loop)return this.renderLoop(e);const i=this.createElement(e);if(!i)return null;i.setAttribute("data-component-id",t),i.setAttribute("data-component-type",r),n&&i.setAttribute("data-component-version",n);const s=this.resolveProps(e.props);if(this.applyProps(i,s),e.style&&this.applyStyles(i,e.style),e.layout&&this.applyLayout(i,e.layout),this.options.injectHostApi(i,t),e.eventHandlers&&e.eventHandlers.length>0&&this.bindEventHandlers(i,t,e.eventHandlers),this.renderChildren(i,e),e.ref){const t=this.expressionContext.local,r=t.$refs||{};r[e.ref]=i,this.expressionContext={...this.expressionContext,local:{...t,$refs:r}}}return this.renderedElements.set(t,i),i}catch(i){return this.log("error",`Failed to render component: ${t}`,i),this.options.onRenderError?this.options.onRenderError(t,i):this.createErrorFallback(t,r,i)}}createElement(e){var t;const{componentType:r}=e,n=this.options.components.get(r);if(n&&customElements.get(r))return document.createElement(r);const i=`${r}-${null==(t=e.componentVersion)?void 0:t.replace(/\./g,"-")}`;if(customElements.get(i))return document.createElement(i);const s=document.createElement("div");return s.className=`djvlc-component djvlc-${r}`,n||(this.log("warn",`Component not loaded: ${r}`),s.classList.add("djvlc-component-fallback")),s}renderLoop(e){const{loop:t}=e;if(!t)return null;const r=this.evaluateExpression(t.items);if(!Array.isArray(r))return this.log("warn",`Loop items is not an array for ${e.id}`),null;const n=document.createDocumentFragment();r.forEach((r,i)=>{this.loopContextStack.push({item:r,index:i,loopConfig:t});const s={...this.expressionContext},a={...this.expressionContext.local,[t.itemName]:r,item:r,index:i};t.indexName&&(a[t.indexName]=i),this.expressionContext={...this.expressionContext,local:a};const o={...e,id:`${e.id}_${i}`,loop:void 0},c=this.renderNode(o);if(c){const e=this.evaluateExpression(t.key);c.setAttribute("data-loop-key",String(e??i)),n.appendChild(c)}this.expressionContext=s,this.loopContextStack.pop()});const i=document.createElement("div");return i.className="djvlc-loop-container",i.setAttribute("data-loop-id",e.id),i.appendChild(n),i}renderChildren(e,t){if(t.slots&&Object.keys(t.slots).length>0)for(const[r,n]of Object.entries(t.slots)){const t=this.createSlotContainer(r);for(const e of n){const r=this.renderNode(e);r&&t.appendChild(r)}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,r){const n=[];for(const i of r){const{eventName:r,preventDefault:s,stopPropagation:a,throttle:o,debounce:c,condition:u}=i;let d=e=>{if(u&&!this.evaluateCondition(u))return;s&&e.preventDefault(),a&&e.stopPropagation();const n=e.detail||{};this.options.onComponentEvent&&this.options.onComponentEvent(t,r,[i],n)};o&&o>0&&(d=this.createThrottledHandler(d,o)),c&&c>0&&(d=this.createDebouncedHandler(d,c)),e.addEventListener(r,d),n.push({event:r,handler:d})}this.componentEventListeners.set(t,n)}createThrottledHandler(e,t){let r=0;return n=>{const i=Date.now();i-r>=t&&(r=i,e(n))}}createDebouncedHandler(e,t){let r=null;return n=>{r&&clearTimeout(r),r=setTimeout(()=>{e(n),r=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,r=this.buildExpressionContext();return this.options.expressionEngine.evaluateWithFallback(t.value,r,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[r,n]of Object.entries(e))t[r]=this.resolveValue(n);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 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,this.buildExpressionContext(),e.fallback)}const n={};for(const[e,t]of Object.entries(r))n[e]=this.resolveValue(t);return n}return t}applyProps(e,t){for(const[r,n]of Object.entries(t))null!=n&&(e.tagName.includes("-")?e[r]=n:"boolean"==typeof n?n?e.setAttribute(r,""):e.removeAttribute(r):"object"==typeof n?e.setAttribute(r,JSON.stringify(n)):e.setAttribute(r,String(n)))}applyStyles(e,t){if(t.inline)for(const[r,n]of Object.entries(t.inline)){if(null==n)continue;const t=this.resolveValue(n);let i;i="number"==typeof t?["zIndex","opacity","flex","fontWeight","lineHeight"].includes(r)?String(t):`${t}px`:String(t);const s=r.replace(/([A-Z])/g,"-$1").toLowerCase();e.style.setProperty(s,i)}t.className&&e.classList.add(...String(t.className).split(" ").filter(Boolean))}applyLayout(e,t){const{x:r,y:n,width:i,height:s,rotation:a,zIndex:o,responsive:c}=t;e.style.position="absolute",void 0!==r&&(e.style.left=`${r}px`),void 0!==n&&(e.style.top=`${n}px`),void 0!==i&&(e.style.width=`${i}px`),void 0!==s&&(e.style.height=`${s}px`),void 0!==a&&(e.style.transform=`rotate(${a}deg)`),void 0!==o&&(e.style.zIndex=String(o)),c&&this.applyResponsiveLayout(e,c)}applyResponsiveLayout(e,t){const r=e.getAttribute("data-component-id");if(!r)return;let n="";if(t.mobile&&(n+=`\n @media (max-width: 767px) {\n [data-component-id="${r}"] {\n ${this.layoutToCSS(t.mobile)}\n }\n }\n `),t.tablet&&(n+=`\n @media (min-width: 768px) and (max-width: 1023px) {\n [data-component-id="${r}"] {\n ${this.layoutToCSS(t.tablet)}\n }\n }\n `),t.desktop&&(n+=`\n @media (min-width: 1440px) {\n [data-component-id="${r}"] {\n ${this.layoutToCSS(t.desktop)}\n }\n }\n `),n){const e=document.createElement("style");e.setAttribute("data-djvlc-responsive",r),e.textContent=n,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 r=e.config;r&&(this.applyLayoutConfig(t,r.layout),r.styles&&this.applyStylesConfig(t,r.styles),r.behavior&&this.applyBehaviorConfig(t,r.behavior))}applyBehaviorConfig(e,t){t.debug&&e.setAttribute("data-debug","true"),t.i18n&&this.applyI18nConfig(e,t.i18n)}applyI18nConfig(e,t){const r=this.detectLocale(t);e.setAttribute("lang",r),e.setAttribute("data-locale",r),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",r),e.style.setProperty("--djvlc-dir",this.getTextDirection(r)),"rtl"===this.getTextDirection(r)?(e.setAttribute("dir","rtl"),e.classList.add("djvlc-rtl")):e.setAttribute("dir","ltr"),this.expressionContext={...this.expressionContext,local:{...this.expressionContext.local,$locale:r,$defaultLocale:t.defaultLocale,$supportedLocales:t.supportedLocales}},this.log("debug",`I18n configured: locale=${r}, default=${t.defaultLocale}`)}detectLocale(e){const{defaultLocale:t,supportedLocales:r,detection:n="browser"}=e;let i=null;switch(n){case"browser":case"header":i=this.detectBrowserLocale(r);break;case"url":i=this.detectUrlLocale(r);break;case"path":i=this.detectPathLocale(r);break;case"cookie":i=this.detectCookieLocale(r);break;case"manual":i=t;break;default:i=null}return i&&r.includes(i)?i:t}detectBrowserLocale(e){if("undefined"==typeof navigator)return null;const t=navigator.languages||[navigator.language];for(const r of t){if(e.includes(r))return r;const t=r.split("-")[0],n=e.find(e=>e===t||e.startsWith(`${t}-`));if(n)return n}return null}detectUrlLocale(e){if("undefined"==typeof window)return null;const t=new URLSearchParams(window.location.search),r=t.get("lang")||t.get("locale");return r&&e.includes(r)?r:null}detectPathLocale(e){if("undefined"==typeof window)return null;const t=window.location.pathname.split("/").filter(Boolean);if(t.length>0){const r=t[0];if(e.includes(r))return r}return null}detectCookieLocale(e){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(const r of t){const[t,n]=r.trim().split("=");if("lang"===t||"locale"===t||"language"===t){const t=decodeURIComponent(n);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(r=>r===e||r===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:r=0,right:n=0,bottom:i=0,left:s=0}=t.padding;e.style.padding=`${r}px ${n}px ${i}px ${s}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[r,n]of Object.entries(t.cssVariables)){const t=r.startsWith("--")?r:`--${r}`;e.style.setProperty(t,n)}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[r,n]of Object.entries(t.variables)){const t=r.startsWith("--")?r:`--theme-${r}`;e.style.setProperty(t,n)}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[r,n]of Object.entries(e.state.fields))n&&"object"==typeof n&&(t[r]=n.initialValue);this.expressionContext={...this.expressionContext,state:t}}}createErrorFallback(e,t,r){const n=document.createElement("div");return n.className="djvlc-error-boundary",n.setAttribute("data-component-id",e),n.setAttribute("data-error","true"),n.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">${r.message}</pre>`:""}\n </div>\n `,n}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}};ct.EXPRESSION_TYPES=["state","binding","local","template","computed"];var ut=ct,dt=class{constructor(e){this.lifecycle=null,this.mounted=!1,this.destroyed=!1,this.cleanupFns=[],this.options=e}register(e){var t,r,n;e?(this.lifecycle=e,this.log("debug","Lifecycle hooks registered",{onMounted:(null==(t=e.onMounted)?void 0:t.length)??0,onBeforeUnmount:(null==(r=e.onBeforeUnmount)?void 0:r.length)??0,onVisibilityChange:(null==(n=e.onVisibilityChange)?void 0:n.length)??0}),e.onVisibilityChange&&e.onVisibilityChange.length>0&&this.setupVisibilityListener()):this.log("debug","No lifecycle hooks defined")}async triggerMounted(){var e,t,r;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==(r=(t=this.options).onLifecycleEvent)||r.call(t,"mounted"))}async triggerBeforeUnmount(){var e,t,r;this.mounted&&!this.destroyed&&(this.log("debug","Triggering onBeforeUnmount lifecycle"),await this.executeLifecycleActions("beforeUnmount",null==(e=this.lifecycle)?void 0:e.onBeforeUnmount),null==(r=(t=this.options).onLifecycleEvent)||r.call(t,"beforeUnmount"))}async triggerVisibilityChange(e){var t,r,n;if(!this.mounted||this.destroyed)return;this.log("debug","Triggering onVisibilityChange lifecycle",{isVisible:e});const i=this.options.getContext(),s={...i,local:{...i.local,$visible:e,$hidden:!e}};await this.executeLifecycleActionsWithContext("visibilityChange",null==(t=this.lifecycle)?void 0:t.onVisibilityChange,s),null==(n=(r=this.options).onLifecycleEvent)||n.call(r,"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 r=this.options.getContext();await this.executeLifecycleActionsWithContext(e,t,r)}async executeLifecycleActionsWithContext(e,t,r){if(t&&0!==t.length){this.log("debug",`Executing ${t.length} actions for ${e}`);try{const n={id:`lifecycle_${e}`,eventName:e,actions:t};await this.options.actionBridge.handleEvent(n,{lifecycle:e},r),this.log("debug",`Lifecycle ${e} actions completed`)}catch(n){this.log("error",`Failed to execute lifecycle ${e} actions`,n)}}}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},lt=class{constructor(e={}){var t;this.client=(t={baseUrl:e.baseUrl??"/api",timeout:e.timeout??3e4,auth:e.auth,headers:e.headers,retry:e.retry,enableRetry:e.enableRetry,logger:e.logger,debug:e.debug},new Pe(t))}async resolvePage(e){return(await this.client.pages.resolvePage({pageId:e.pageId,env:e.env,uid:e.uid,deviceId:e.deviceId,channel:e.channel})).data}async executeAction(e){const t=await this.client.actions.executeAction({executeActionRequest:{actionType:e.actionType,params:e.params,context:{pageVersionId:e.context.pageVersionId,deviceId:e.context.deviceId,channel:e.context.channel,extra:{uid:e.context.uid,appId:e.context.appId}},idempotencyKey:e.idempotencyKey}}),r=t.data;return{success:t.success,data:null==r?void 0:r.result,errorCode:null==r?void 0:r.errorCode,errorMessage:null==r?void 0:r.errorMessage}}async executeQuery(e){const t=await this.client.queries.queryData({queryDataRequest:{queryVersionId:e.queryVersionId,params:e.params??{},context:{pageVersionId:e.context.pageVersionId}}});return{success:t.success,data:t.data??void 0,message:t.message,errorMessage:t.errorMessage}}track(e){this.client.track.track({trackRequest:{eventName:e.eventName,eventType:e.type??"custom",properties:e.params,timestamp:null!=e.timestamp?new Date(e.timestamp):void 0,context:{pageVersionId:e.context.pageVersionId,sessionId:e.context.userId}}}).catch(()=>{})}},ht="1.0.0",pt="1.0.0";function mt(e){return new ft(e)}var ft=class{constructor(e){if(this.container=null,!e.pageId)throw new Error("pageId is required");this.options={channel:"prod",debug:!1,enableSRI:!0,env:"production",...e},this.logger=this.createLogger(),this.stateManager=new Qe,this.eventBus=new Ge({debug:e.debug,logger:this.logger}),this.expressionEngine=new it({debug:e.debug,logger:this.logger});const t=e;this.userApiAdapter=t.userApiAdapter??new lt({baseUrl:e.apiBaseUrl,headers:e.headers,...null!=e.authToken&&""!==e.authToken?{auth:{type:"bearer",getToken:()=>Promise.resolve(e.authToken)}}:{}}),this.pageLoader=new Ke({apiBaseUrl:e.apiBaseUrl,userApiAdapter:this.userApiAdapter,channel:e.channel,previewToken:e.previewToken,headers:e.headers,logger:this.logger}),this.componentLoader=new ze({cdnBaseUrl:e.cdnBaseUrl,enableSRI:e.enableSRI,headers:e.headers,logger:this.logger}),this.assetLoader=new Ye({cdnHosts:[new URL(e.cdnBaseUrl).host],apiHosts:[new URL(e.apiBaseUrl).host]}),this.securityManager=new at({enableSRI:e.enableSRI,cdnDomains:[new URL(e.cdnBaseUrl).host],apiDomains:[new URL(e.apiBaseUrl).host],logger:this.logger}),this.log("info","Runtime created",{version:pt})}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,t,r;this.log("info","Loading page:",this.options.pageId);const n=performance.now();try{this.stateManager.setPhase("resolving");const i=await this.pageLoader.resolve(this.options.pageId,{uid:this.options.userId,deviceId:this.options.deviceId});if(this.validateSchemaVersion(i.pageJson),this.stateManager.setPage(i),this.telemetryManager=new ot({pageVersionId:i.pageVersionId,appId:this.options.appId,debug:this.options.debug,logger:this.logger,onMetric:this.options.onMetric}),i.runtimeConfig){const t=(null==(e=i.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(i.manifest.components),(await this.componentLoader.loadAll(i.manifest)).forEach((e,t)=>{this.stateManager.setComponentStatus(t,e),this.telemetryManager.recordComponentLoad(e.name,e.version,e.loadTime||0,"loaded"===e.status)}),this.initHostApi(i),this.initActionBridge(),this.initDataBindingManager(i.pageJson),this.initRenderer(),this.initLifecycleManager(i.pageJson);const s=performance.now()-n;return this.telemetryManager.recordPageLoad(s),this.log("info",`Page loaded in ${s.toFixed(2)}ms`),this.emitEvent("page:loaded",{page:i,loadTime:s}),null==(r=(t=this.options).onLoad)||r.call(t,i),i}catch(i){throw this.stateManager.setPhase("error"),this.handleError(i),i}}async render(){const e=this.stateManager.getState();if(!e.page||!this.container)throw new Me("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 r=performance.now()-t;this.telemetryManager.recordFirstRender(r),this.log("info",`Page rendered in ${r.toFixed(2)}ms`),await this.lifecycleManager.triggerMounted(),this.emitEvent("page:rendered",{renderTime:r})}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),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,r,n,i;this.log("info","Destroying runtime"),await(null==(e=this.lifecycleManager)?void 0:e.destroy()),null==(t=this.telemetryManager)||t.flush(),null==(r=this.dataBindingManager)||r.destroy(),null==(n=this.actionBridge)||n.destroy(),null==(i=this.renderer)||i.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!==ht)throw new Me(`Unsupported schema version: ${e.schemaVersion}. Only ${ht} is supported.`,{schemaVersion:e.schemaVersion,supportedVersion:ht})}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 st({userApiAdapter:this.userApiAdapter,stateManager:this.stateManager,eventBus:this.eventBus,expressionEngine:this.expressionEngine,context:{pageId:e.pageId,pageVersionId:e.pageVersionId,runtimeVersion:pt,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 We({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 r;t.success?this.emitEvent("action:executed",{action:e,data:t.data}):this.emitEvent("action:error",{action:e,error:null==(r=t.error)?void 0:r.message})}})}initDataBindingManager(e){this.dataBindingManager=new Je({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 r;this.emitEvent("query:fetched",{bindingId:e,data:t}),null==(r=this.renderer)||r.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 dt({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,r)=>{if("loaded"===t.status&&t.component){const[n,i]=r.split("@");e.set(n,{name:n,version:i,Component:t.component,loadTime:t.loadTime||0})}}),this.renderer=new ut({expressionEngine:this.expressionEngine,components:e,injectHostApi:(e,t)=>{e.hostApi=this.hostApi,e.componentId=t},onComponentEvent:(e,t,r,n)=>{this.handleComponentEvent(e,t,r,n)},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()}handleComponentEvent(e,t,r,n){this.log("debug",`Component event: ${e}.${t}`,n);for(const i of r)this.actionBridge.handleEvent(i,n,this.stateManager.getExpressionContext())}handleError(e){var t;const r=e instanceof _e?{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(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 n=Ge.createEvent(e,t,null==(r=this.telemetryManager)?void 0:r.getTraceId());this.eventBus.emit(n),this.options.onEvent&&this.options.onEvent(n)}createLogger(){return{debug:(...e)=>{this.options.debug},info:(...e)=>{},warn:(...e)=>{},error:(...e)=>{}}}log(e,t,...r){this.logger[e](t,...r)}};function yt(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 r=t.getEntries(),n=r[r.length-1];n&&(e.lcp=n.startTime)}).observe({type:"largest-contentful-paint",buffered:!0}),new PerformanceObserver(t=>{const r=t.getEntries();if(r.length>0){const t=r[0];e.fid=t.processingStart-t.startTime}}).observe({type:"first-input",buffered:!0});let r=0;new PerformanceObserver(t=>{for(const n of t.getEntries()){const t=n;!t.hadRecentInput&&t.value&&(r+=t.value,e.cls=r)}}).observe({type:"layout-shift",buffered:!0})}catch{}}class gt{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,r){if(!this.enabled)return 0;const n=this.marks.get(t),i=r?this.marks.get(r):performance.now();if(void 0===n)return 0;const s=(i??performance.now())-n;if(this.measures.set(e,s),"function"==typeof performance.measure)try{performance.measure(`djvlc:${e}`,`djvlc:${t}`,r?`djvlc:${r}`:void 0)}catch{}return s}getMeasures(){return Object.fromEntries(this.measures)}clear(){this.marks.clear(),this.measures.clear()}}function vt(e=!0){return new gt(e)}function wt(){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 bt(e){return performance.getEntriesByType("resource").filter(e||(()=>!0)).map(e=>({name:e.name,type:e.initiatorType,duration:e.duration,size:e.transferSize||0}))}function It(){return bt(e=>e.name.includes("/components/")||e.name.includes("/runtime/"))}function Et(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 St(e,r=t){[`${e}/runtime/${r}/runtime.esm.js`,`${e}/runtime/${r}/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 Tt(){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 At(){return Array.from({length:32},()=>Math.floor(16*Math.random()).toString(16)).join("")}function Rt(){return Array.from({length:16},()=>Math.floor(16*Math.random()).toString(16)).join("")}function $t(){return`00-${At()}-${Rt()}-01`}const Nt={getParam:(e,t=window.location.href)=>new URL(t).searchParams.get(e),setParam(e,t){const r=new URL(window.location.href);r.searchParams.set(e,t),window.history.replaceState({},"",r.toString())},removeParam(e){const t=new URL(window.location.href);t.searchParams.delete(e),window.history.replaceState({},"",t.toString())},build(e,t){const r=new URL(e,window.location.origin);return Object.entries(t).forEach(([e,t])=>{void 0!==t&&r.searchParams.set(e,String(t))}),r.toString()}};function Dt(e){const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}function xt(e){const t=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",r),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}}function Ot(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Ct(){return/MicroMessenger/i.test(navigator.userAgent)}async function qt(){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 kt(e,t){var r,n,i,s;const{retryCount:a=3,retryDelay:o=1e3,timeout:c=3e4,collectWebVitals:u=!1}=t,d={initTime:0,loadTime:0,renderTime:0,totalTime:0,componentLoadCount:0,componentLoadErrors:0,dataRequestCount:0,dataRequestErrors:0},l=performance.now();let h=0,p=0,m=0;if(!t.pageId)throw new Error("pageId is required");const f=mt({container:e,pageId:t.pageId,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: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,r)=>{try{return await e()}catch(n){if(t>0)return await new Promise(e=>setTimeout(e,r)),y(e,t-1,r);throw n}};try{await y(async()=>{var e,r;await(e=(async()=>{var e,r,n,i;h=performance.now(),null==(e=t.onPhaseChange)||e.call(t,"initializing"),await f.init(),d.initTime=performance.now()-h,p=performance.now(),null==(r=t.onPhaseChange)||r.call(t,"loading"),await f.load(),d.loadTime=performance.now()-p,m=performance.now(),null==(n=t.onPhaseChange)||n.call(t,"rendering"),await f.render(),d.renderTime=performance.now()-m,null==(i=t.onPhaseChange)||i.call(t,"ready")})(),r=c,Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(new Error("加载超时")),r))]))},a,o),d.totalTime=performance.now()-l,u&&yt(d),null==(r=t.onLoad)||r.call(t,f.getState()),null==(n=t.onMetric)||n.call(t,d)}catch(g){d.totalTime=performance.now()-l,null==(i=t.onMetric)||i.call(t,d);const e=g instanceof Error?g:new Error(String(g));throw null==(s=t.onError)||s.call(t,e),e}return{runtime:f,metrics:d,destroy:()=>f.destroy(),refresh:async()=>{await f.load(),await f.render()},setVariable:(e,t)=>f.setVariable(e,t),refreshData:e=>f.refreshData(e)}}function Pt(e,t){const r="string"==typeof e?document.querySelector(e):e;if(!r)return{cancel:()=>{},promise:Promise.reject(new Error("Container element not found"))};let n,i,s=!1,a=null;const o=new Promise((e,t)=>{n=e,i=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&&r.appendChild(e)}return a=new IntersectionObserver(async o=>{const c=o[0];if((null==c?void 0:c.isIntersecting)&&!s){null==a||a.disconnect(),a=null,r.innerHTML="";try{const r=await kt(e,t);n(r)}catch(u){i(u)}}},{rootMargin:t.rootMargin||"100px",threshold:t.threshold||0}),a.observe(r),{cancel:()=>{s=!0,null==a||a.disconnect(),i(new Error("Lazy mount cancelled"))},promise:o}}async function _t(e,t){const{concurrency:r=3,continueOnError:n=!0}=t||{},i=performance.now(),s=new Map,a=new Map;for(let o=0;o<e.length;o+=r){const t=e.slice(o,o+r).map(async({id:e,container:t,options:r})=>{try{const n=await kt(t,r);s.set(e,n)}catch(i){if(a.set(e,i),!n)throw i}});await Promise.all(t)}return{results:s,errors:a,totalTime:performance.now()-i}}async function Mt(e){return Et([new URL(e.apiBaseUrl).host,new URL(e.cdnBaseUrl).host]),St(e.cdnBaseUrl,t),{mount:t=>kt(t,e)}}class Lt{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=At(),this.config.enabled&&this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>this.flush(),this.config.flushInterval))}track(e,t,r){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const n={event:e,data:t,timestamp:Date.now(),traceId:this.traceId,...r};this.events.push(n),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},{pageId:e,pageVersionId:t})}trackComponentView(e,t,r){this.track("component_view",{componentType:t},{componentId:e,pageId:r})}trackComponentClick(e,t,r){this.track("component_click",{componentType:t},{componentId:e,pageId:r})}trackAction(e,t,r,n){this.track("action_execute",{actionType:e,success:t,duration:r},{pageId:n})}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 Vt(e){return new Lt(e)}class Ut{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=At(),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 r={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(r)}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 r={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(r)}handleUnhandledRejection(e){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const t=e.reason,r=t instanceof Error?t.message:String(t);if(this.shouldIgnore(r))return;const n={message:r,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(n)}shouldIgnore(e){return this.config.ignorePatterns.some(t=>t.test(e))}truncateStack(e){if(e)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 Bt(e){return new Ut(e)}class jt{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:r,expires:n}=JSON.parse(t);return n&&Date.now()>n?(this.remove(e),null):r}catch{return null}}set(e,t,r){try{const n={value:t,expires:r?Date.now()+r:void 0};this.storage.setItem(this.getKey(e),JSON.stringify(n))}catch{}}remove(e){this.storage.removeItem(this.getKey(e))}clear(){const e=[];for(let t=0;t<this.storage.length;t++){const r=this.storage.key(t);(null==r?void 0:r.startsWith(`${this.namespace}:`))&&e.push(r)}e.forEach(e=>this.storage.removeItem(e))}}function Ft(e,t){return new jt(e,t)}const Kt={RUNTIME_VERSION:t,mount:kt,lazyMount:Pt,batchMount:_t,warmup:Mt,createTrackingManager:Vt,createErrorReporter:Bt,createPerformanceMonitor:vt,getPagePerformance:wt,getResourcePerformance:bt,getRuntimeResourcePerformance:It,createStorageHelper:Ft,preconnect:Et,preloadAssets:St,getDeviceId:Tt,generateTraceId:At,generateSpanId:Rt,generateTraceparent:$t,urlUtils:Nt,onVisibilityChange:Dt,onNetworkChange:xt,isMobile:Ot,isWeChat:Ct,supportsWebP:qt,createRuntime:mt};return e.ErrorReporter=Ut,e.PerformanceMonitor=gt,e.RUNTIME_VERSION=t,e.StorageHelper=jt,e.TrackingManager=Lt,e.batchMount=_t,e.collectWebVitalsMetrics=yt,e.createErrorReporter=Bt,e.createPerformanceMonitor=vt,e.createRuntime=mt,e.createStorageHelper=Ft,e.createTrackingManager=Vt,e.default=Kt,e.generateSpanId=Rt,e.generateTraceId=At,e.generateTraceparent=$t,e.getDeviceId=Tt,e.getPagePerformance=wt,e.getResourcePerformance=bt,e.getRuntimeResourcePerformance=It,e.isMobile=Ot,e.isWeChat=Ct,e.lazyMount=Pt,e.mount=kt,e.onNetworkChange=xt,e.onVisibilityChange=Dt,e.preconnect=Et,e.preloadAssets=St,e.supportsWebP=qt,e.urlUtils=Nt,e.warmup=Mt,Object.defineProperties(e,{t:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});
|
|
1
|
+
var e=function(e){"use strict";const t="1.1.1";var r=(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))(r||{}),n={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:"回滚失败"};[{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']},{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"]},{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"]},{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']},{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"]},{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", "未知")']},{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"']}].map(e=>e.name);var i=class extends Error{constructor(e,t,r,i){super(t||n[e]||"Unknown error"),this.name="DjvlcRuntimeError",this.code=e,this.details=r,this.traceId=i,this.timestamp=Date.now()}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,traceId:this.traceId,timestamp:this.timestamp}}},s=class extends i{constructor(e,t,n){super(r.RESOURCE_PAGE_NOT_FOUND,e,t,n),this.name="PageLoadError"}},a=class extends i{constructor(e,t,n,i=r.COMPONENT_LOAD_FAILED,s){super(i,n,{...s,componentName:e,componentVersion:t}),this.name="ComponentLoadError",this.componentName=e,this.componentVersion=t}},o=class extends i{constructor(e,t,n,i){super(r.COMPONENT_INTEGRITY_MISMATCH,`Integrity check failed for ${e}@${t}`,{expectedHash:n,actualHash:i}),this.name="IntegrityError",this.componentName=e,this.componentVersion=t,this.expectedHash=n,this.actualHash=i}},c=class extends i{constructor(e,t,n){super(r.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}},u=class extends i{constructor(e,t,n,i){super(r.VALIDATION_EXPRESSION_ERROR,t,{...i,expression:e,position:n}),this.name="ExpressionError",this.expression=e,this.position=n}},d=class extends i{constructor(e,t,n=r.SYSTEM_INTERNAL_ERROR,i,s){super(n,t,{...s,actionType:e,actionId:i}),this.name="ActionError",this.actionType=e,this.actionId=i}},l=class extends i{constructor(e,t,n=r.SYSTEM_INTERNAL_ERROR,i){super(n,t,{...i,queryId:e}),this.name="QueryError",this.queryId=e}},h=class{constructor(e){this.cache=new Map,this.options={env:"prod",cache:{enabled:!0,maxAge:300},...e}}async resolve(e,t){var r,n;const i=this.getCacheKey(e,t);if(null==(r=this.options.cache)?void 0:r.enabled){const t=this.cache.get(i);if(t&&this.isCacheValid(t.timestamp))return this.log("debug",`Page ${e} loaded from cache`),t.data}const a=performance.now();try{const r=await this.callResolveViaAdapter(e,t),s=await this.loadFromCdn(r,e);(null==(n=this.options.cache)?void 0:n.enabled)&&this.cache.set(i,{data:s,timestamp:Date.now()});const o=performance.now()-a;return this.log("info",`Page ${e} resolved in ${o.toFixed(2)}ms`),s}catch(o){if(o instanceof s)throw o;throw new s(`Failed to resolve page: ${o instanceof Error?o.message:"Unknown error"}`,{pageId:e})}}async callResolveViaAdapter(e,t){const r=await this.options.userApiAdapter.resolvePage({pageId:e,uid:null==t?void 0:t.uid,deviceId:null==t?void 0:t.deviceId,env:this.options.env,channel:this.options.channel,previewToken:this.options.previewToken});if(!this.isValidPageResolveResponse(r))throw new s("Invalid page resolve response",{pageId:e});return r}async loadFromCdn(e,t){try{const r=await fetch(e.snapshotUrl,{headers:this.buildHeaders()});if(!r.ok)throw new s(`Failed to load snapshot: ${r.status}`,{pageId:t});const n=await r.json();return this.convertSnapshotToResult(n,e,t)}catch(r){if(r instanceof s)throw r;throw new s(`Failed to load from CDN: ${r instanceof Error?r.message:"Unknown error"}`,{pageId:t})}}convertSnapshotToResult(e,t,r){var n,i,s,a;const o=this.convertSnapshotPageToPageSchema(e.page),c=this.convertSnapshotManifestToPageManifest(e.manifest),u=(null==(i=null==(n=e.definitionsDigest)?void 0:n.actions)?void 0:i.map(e=>e.versionId))||[],d=(null==(a=null==(s=e.definitionsDigest)?void 0:s.queries)?void 0:a.map(e=>e.versionId))||[];return c.actionDefinitionVersionIds=u,c.dataQueryVersionIds=d,{pageId:t.pageId,pageVersionId:t.resolvedVersionId,pageJson:o,manifest:c,runtimeConfig:{blockedComponents:t.ops.blockedComponents.map(e=>({name:e.name,version:e.version||"",reason:e.reason})),killSwitches:t.ops.killSwitch.map(e=>({type:e.targetType,enabled:e.enabled})),features:t.ops.flags},isPreview:"preview"===this.options.env||!!this.options.previewToken}}convertSnapshotPageToPageSchema(e){const t={layout:{canvasType:e.config.canvasType,canvasSize:e.config.canvasSize},styles:e.config.background||e.config.cssVariables?{background:e.config.background,cssVariables:e.config.cssVariables}:void 0},r=Object.keys(e.initialState).length>0?{fields:Object.keys(e.initialState).reduce((t,r)=>{const n=e.initialState[r];let i="string";return"number"==typeof n?i="number":"boolean"==typeof n?i="boolean":Array.isArray(n)?i="array":null!==n&&"object"==typeof n&&(i="object"),t[r]={type:i,initialValue:n},t},{})}:void 0,n={title:e.title};return{schemaVersion:e.schemaVersion,pageId:e.pageId,pageVersion:e.pageVersion,runtime:{name:"djvlc-runtime",version:"1.0.0"},meta:n,config:t,seo:e.seo,state:r,dataBindings:e.bindings,root:e.root}}convertSnapshotManifestToPageManifest(e){return{id:"",pageVersionId:"",manifestVersion:"1.0.0",createdAt:(new Date).toISOString(),contentHash:"",components:e.components.map(e=>({componentId:"",name:e.name,version:e.version,entry:`${e.assetsUrl}/${e.entrypoints.js}`,styleEntry:e.entrypoints.css?`${e.assetsUrl}/${e.entrypoints.css}`:void 0,integrity:e.integrity,preload:e.preload,priority:e.priority})),actionDefinitionVersionIds:[],dataQueryVersionIds:[],runtimeVersion:{min:e.runtime.minVersion,recommended:e.runtime.version}}}isValidPageResolveResponse(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.pageId&&"string"==typeof t.resolvedVersionId&&"string"==typeof t.cdnBase&&"string"==typeof t.snapshotUrl&&"string"==typeof t.manifestUrl&&void 0!==t.ops&&"string"==typeof t.etag&&"number"==typeof t.cacheTtlSeconds}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()}buildHeaders(){return{"Content-Type":"application/json",...this.options.headers}}getCacheKey(e,t){const r=[e,this.options.env,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.filter(Boolean).join(":")}isCacheValid(e){var t;const r=1e3*((null==(t=this.options.cache)?void 0:t.maxAge)??300);return Date.now()-e<r}log(e,t){this.options.logger&&this.options.logger[e](t)}},p={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"},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 c(e.name,e.version,"Component is blocked");const r=this.loadedComponents.get(t);if(r)return r;const n=this.loadingPromises.get(t);if(n)return n;const i=this.loadComponent(e);this.loadingPromises.set(t,i);try{const e=await i;return this.loadedComponents.set(t,e),e}finally{this.loadingPromises.delete(t)}}async loadAll(e){const t=new Map,{concurrency:r=4}=this.options,n=e.components;for(let i=0;i<n.length;i+=r){const e=n.slice(i,i+r).map(async e=>{const r=this.getComponentKey(e.name,e.version),n=performance.now();try{const i=await this.load(e);t.set(r,{name:e.name,version:e.version,status:"loaded",component:i.Component,loadTime:performance.now()-n})}catch(i){const s=i instanceof c?"blocked":"failed";if(t.set(r,{name:e.name,version:e.version,status:s,error:i instanceof Error?i.message:"Unknown error",loadTime:performance.now()-n}),"critical"===e.priority)throw i}});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(),r=this.resolveUrl(e.entry);this.log("debug",`Loading component ${e.name}@${e.version}`);try{const n=await this.fetchWithTimeout(r);if(!n.ok)throw new a(e.name,e.version,`Failed to fetch component: ${n.status} ${n.statusText}`);const i=await n.text();this.options.enableSRI&&e.integrity&&await this.validateIntegrity(e,i);const s=await this.executeScript(i,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:s,loadTime:o}}catch(n){if(n instanceof a||n instanceof o||n instanceof c)throw n;throw new a(e.name,e.version,`Failed to load component: ${n instanceof Error?n.message:"Unknown error"}`)}}async fetchWithTimeout(e){const t=new AbortController,r=setTimeout(()=>t.abort(),this.options.timeout),n={signal:t.signal,credentials:"omit",headers:this.options.headers?{...this.options.headers}:void 0},i=this.options.fetchComponentScript??fetch;try{return await i(e,n)}finally{clearTimeout(r)}}async validateIntegrity(e,t){if(!e.integrity)return;const[r,n]=e.integrity.split("-");if(!r||!n)throw new o(e.name,e.version,e.integrity,"Invalid format");const i=p[r.toLowerCase()];if(!i)throw new o(e.name,e.version,e.integrity,`Unsupported SRI algorithm: ${r}, expected sha256/sha384/sha512`);const s=await crypto.subtle.digest(i,(new TextEncoder).encode(t)),a=Array.from(new Uint8Array(s)),c=btoa(String.fromCharCode(...a));if(c!==n)throw new o(e.name,e.version,n,c)}async executeScript(e,t){const r=new Blob([e],{type:"application/javascript"}),n=URL.createObjectURL(r);try{const e=await import(n),r=e.default??e[t.name]??e[this.kebabToPascal(t.name)]??e.Component;if(!r)throw new a(t.name,t.version,"Component module does not export a valid component (expected default or Component)");return r}finally{URL.revokeObjectURL(n)}}kebabToPascal(e){return e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}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)}},f=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.setAttribute("as","script"),r.href=e,t&&(r.setAttribute("integrity",t),r.setAttribute("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.setAttribute("as","style"),r.href=e,t&&(r.setAttribute("integrity",t),r.setAttribute("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.setAttribute("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.setAttribute("as",t),document.head.appendChild(r)}loadStylesheet(e,t){return new Promise((r,n)=>{const i=document.createElement("link");i.rel="stylesheet",i.href=e,t&&(i.integrity=t,i.crossOrigin="anonymous"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load stylesheet: ${e}`)),document.head.appendChild(i)})}loadScript(e,t){return new Promise((r,n)=>{const i=document.createElement("script");i.src=e,i.async=!0,t&&(i.integrity=t,i.crossOrigin="anonymous"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.body.appendChild(i)})}},y=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,r=this.initializePageState(t);e.preloadedData&&Object.assign(r,e.preloadedData),this.setState({page:e,variables:r})}initializePageState(e){const t={};if(e.state&&e.state.fields)for(const[r,n]of Object.entries(e.state.fields))if(n&&"object"==typeof n){const e=n;t[r]=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 r=this.getVariable(e);if(e.includes(".")){const r={...this.state.variables};this.setNestedValue(r,e,t),this.setState({variables:r})}else this.setState({variables:{...this.state.variables,[e]:t}});this.notifyChange({key:e,oldValue:r,newValue:t})}setVariables(e){const t=[];for(const[r,n]of Object.entries(e)){const e=this.getVariable(r);t.push({key:r,oldValue:e,newValue:n})}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,...r}=this.state.queries;this.setState({queries:r})}setComponentStatus(e,t){const r=new Map(this.state.components);r.set(e,t),this.setState({components:r})}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,pageId:null==(t=this.state.page)?void 0:t.pageId,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(r){}})}getNestedValue(e,t){const r=t.split(".");let n=e;for(const i of r){if(null==n)return;n=n[i]}return n}setNestedValue(e,t,r){const n=t.split(".");let i=e;for(let s=0;s<n.length-1;s++){const e=n[s];void 0!==i[e]&&null!==i[e]||(i[e]={}),i=i[e]}i[n[n.length-1]]=r}createInitialState(){return{phase:"idle",page:null,variables:{},queries:{},components:new Map,error:null,destroyed:!1}}},g=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[r,n]of this.bindings)r!==e.id&&(null==(t=n.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(r));if(e.dependencies)for(const r of e.dependencies)for(const[t,n]of this.bindings)t!==e.id&&n.binding.targetState===r&&(this.bindingDependencies.has(t)||this.bindingDependencies.set(t,new Set),this.bindingDependencies.get(t).add(e.id))}async initializeBindings(e){var t,r;const n=[];for(const a of this.bindings.values())"eager"===a.binding.loadStrategy&&n.push(a.binding);const i=this.topologicalSort(n),s=this.createLoadBatches(i);for(const a of s){const n=await Promise.allSettled(a.map(t=>this.loadBinding(t.id,e))),i=new Map;n.forEach((e,t)=>{const r=a[t].id;"fulfilled"===e.status?i.set(r,{success:!0,data:e.value}):i.set(r,{success:!1,error:e.reason})}),null==(r=(t=this.options).onBatchComplete)||r.call(t,i)}}topologicalSort(e){const t=new Map(e.map(e=>[e.id,e])),r=new Set,n=[],i=e=>{if(!r.has(e.id)){if(r.add(e.id),e.dependencies)for(const n of e.dependencies)for(const[e,s]of t)s.targetState!==n||r.has(e)||i(s);n.push(e)}};for(const s of e)i(s);return n}createLoadBatches(e){const t=[],r=new Set;for(;r.size<e.length;){const n=[];for(const t of e){if(r.has(t.id))continue;let i=!0;if(t.dependencies)for(const n of t.dependencies){for(const t of e)if(t.targetState===n&&!r.has(t.id)){i=!1;break}if(!i)break}i&&n.push(t)}if(0===n.length)for(const t of e)if(!r.has(t.id)){n.push(t),this.log("warn",`Possible circular dependency detected at binding: ${t.id}`);break}n.forEach(e=>r.add(e.id)),n.length>0&&t.push(n)}return t}async loadBinding(e,t,r=!1){var n,i,s;const a=this.bindings.get(e);if(!a)throw new l(e,`Data binding not found: ${e}`);const{binding:o}=a;if(!o.condition||this.evaluateCondition(o.condition,t)){if(!r&&this.isCacheValid(a))return this.log("debug",`Binding ${e} returned from cache`),a.cachedData;if(a.loading)this.log("debug",`Binding ${e} is already loading`);else{a.loading=!0;try{const r=this.resolveParams(o.params||{},t),c=await this.executeWithRetry(o,r),u=o.transform?this.applyTransform(c,o.transform,t):c;return a.cachedData=u,a.lastLoadTime=Date.now(),(null==(n=o.cache)?void 0:n.ttl)&&(a.cacheExpireTime=Date.now()+1e3*o.cache.ttl),a.retryCount=0,this.options.stateSetter.setVariable(o.targetState,u),this.setupAutoRefresh(a,t),null==(s=(i=this.options).onDataLoaded)||s.call(i,e,u),this.log("info",`Binding ${e} loaded successfully`),u}catch(c){throw await this.handleLoadError(a,c,t),c}finally{a.loading=!1}}}else this.log("debug",`Binding ${e} skipped by condition`)}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 r=this.dependencyGraph.get(e);if(!r||0===r.size)return;this.log("debug",`State ${e} changed, refreshing dependent bindings`);const n=Array.from(r).map(e=>this.loadBinding(e,t,!0));await Promise.allSettled(n)}async triggerManualLoad(e,t){const r=this.bindings.get(e);if(!r)throw new l(e,`Data binding not found: ${e}`);return"manual"!==r.binding.loadStrategy&&this.log("warn",`Binding ${e} is not manual strategy`),this.loadBinding(e,t,!0)}checkVisibility(e,t,r){const n=this.bindings.get(e);n&&"lazy"===n.binding.loadStrategy&&t&&!n.lastLoadTime&&this.loadBinding(e,r).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 r,n,i,s,a,o;const c=(null==(n=null==(r=e.onError)?void 0:r.retry)?void 0:n.maxRetries)??0,u=(null==(s=null==(i=e.onError)?void 0:i.retry)?void 0:s.backoffMs)??1e3,d=(null==(o=null==(a=e.onError)?void 0:a.retry)?void 0:o.backoff)??"fixed";let h;for(let m=0;m<=c;m++)try{const r=await this.options.requester.requestData(e.queryVersionId,t);if(!r.success)throw new l(e.queryVersionId,r.message||"Query failed",void 0,{params:t});return r.data}catch(p){if(h=p,this.log("warn",`Query attempt ${m+1}/${c+1} failed:`,p),m<c){const e="exponential"===d?u*Math.pow(2,m):u;await this.delay(e)}}throw h||new Error("Query failed after all retries")}async handleLoadError(e,t,r){var n,i;const{binding:s}=e,a=s.onError;e.retryCount++,void 0!==(null==a?void 0:a.fallbackValue)&&this.options.stateSetter.setVariable(s.targetState,a.fallbackValue),(null==a?void 0:a.showError)&&(null==(i=(n=this.options).onDataError)||i.call(n,s.id,t)),this.log("error",`Binding ${s.id} load failed:`,t)}setupAutoRefresh(e,t){e.refreshTimer&&(clearInterval(e.refreshTimer),e.refreshTimer=void 0);const r=e.binding.refreshInterval;!r||r<=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*r))}isCacheValid(e){return!(!e.cachedData||!e.lastLoadTime||e.cacheExpireTime&&Date.now()>e.cacheExpireTime)}resolveParams(e,t){const r={};for(const[n,i]of Object.entries(e))r[n]=this.resolveValue(i,t);return r}resolveValue(e,t){if(null==e)return e;if("object"==typeof e&&!Array.isArray(e)){const r=e;if("expression"===r.type||"binding"===r.type)return this.options.expressionEngine.evaluateWithFallback(r.expression,t,r.fallback);const n={};for(const[e,i]of Object.entries(r))n[e]=this.resolveValue(i,t);return n}return"string"==typeof e&&e.includes("${")?this.options.expressionEngine.evaluateTemplate(e,t):e}evaluateCondition(e,t){const r=void 0===e.fallback||e.fallback,n=this.options.expressionEngine.evaluateWithFallback(e.value,t,r);return Boolean(n)}applyTransform(e,t,r){const n={...r,local:{...r.local||{},$data:e,$response:e}},i=void 0!==t.fallback?t.fallback:e;return this.options.expressionEngine.evaluateWithFallback(t.value,n,i)}delay(e){return new Promise(t=>setTimeout(t,e))}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},v=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}},w=class e{constructor(e){this.debounceTimers=new Map,this.throttleTimers=new Map,this.options=e}async handleEvent(e,t,r){if(e.condition&&!this.evaluateCondition(e.condition,r,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 n={$event:t,$prevResult:void 0,$results:{}};await this.executeActionChain(e.actions,r,n)}async executeActionChain(e,t,r){const n=[];for(let i=0;i<e.length;i++){const s=e[i];if(s.condition){const e=this.buildActionContext(t,r);if(!this.evaluateCondition(s.condition,e,r.$event)){this.log("debug",`Action ${s.id||i} skipped by condition`);continue}}const a=this.executeSingleAction(s,t,r);s.async?n.push(a):await a}n.length>0&&await Promise.allSettled(n)}async executeSingleAction(e,t,r){var n,i,s,a,o,c;const u=e.id||e.alias||e.builtinAction||e.actionDefinitionVersionId||"unknown";e.silent||this.options.executor.showLoading();try{const o=this.buildActionContext(t,r),c=this.resolveParams(e.params||{},o);null==(i=(n=this.options).onActionStart)||i.call(n,e,c);const d=await this.executeWithRetry(e,c);r.$prevResult=d,e.id&&(r.$results[e.id]=d),null==(a=(s=this.options).onActionComplete)||a.call(s,e,{success:!0,data:d}),this.log("debug",`Action ${u} completed successfully`),e.onSuccess&&e.onSuccess.length>0&&await this.executeActionChain(e.onSuccess,t,r)}catch(d){this.log("error",`Action ${u} failed:`,d),null==(c=(o=this.options).onActionComplete)||c.call(o,e,{success:!1,error:d}),e.onError&&e.onError.length>0&&await this.executeActionChain(e.onError,t,{...r,$prevResult:{error:d.message}})}finally{e.silent||this.options.executor.hideLoading(),e.onFinally&&e.onFinally.length>0&&await this.executeActionChain(e.onFinally,t,r)}}async executeWithRetry(e,t){var r,n,i,s,a;const o=(null==(n=null==(r=e.policy)?void 0:r.retry)?void 0:n.maxAttempts)??1,c=(null==(s=null==(i=e.policy)?void 0:i.retry)?void 0:s.backoffMs)??1e3,u=null==(a=e.policy)?void 0:a.timeoutMs;let l;for(let p=1;p<=o;p++)try{let r;if(e.builtinAction)r=this.executeBuiltinAction(e.builtinAction,t);else{if(!e.actionDefinitionVersionId)throw new d("unknown","Action must specify builtinAction or actionDefinitionVersionId");r=this.executeCustomAction(e.actionDefinitionVersionId,t)}return u&&(r=this.withTimeout(r,u)),await r}catch(h){l=h,this.log("warn",`Action attempt ${p}/${o} failed:`,h),p<o&&await this.delay(c*p)}throw l||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 d(e,`Unknown builtin action: ${e}`)}}async executeCustomAction(e,t){const r=e.split("@")[0],n=await this.options.executor.executeAction(r,{...t,actionDefinitionVersionId:e});if(!n.success)throw new d(r,n.errorMessage||"Action execution failed",void 0,e,{errorCode:n.errorCode});return n.data}resolveParams(e,t){const r={};for(const[n,i]of Object.entries(e))r[n]=this.resolveValue(i,t);return r}resolveValue(t,r){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,r,t)}return t.includes("${")?this.options.expressionEngine.evaluateTemplate(t,r):t}if("number"==typeof t||"boolean"==typeof t)return t;if(Array.isArray(t))return t.map(e=>this.resolveValue(e,r));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,r,e.fallback)}const i={};for(const[e,t]of Object.entries(n))i[e]=this.resolveValue(t,r);return i}return t}evaluateCondition(e,t,r){const n={...t,local:{...t.local||{},$event:r}},i=void 0===e.fallback||e.fallback,s=this.options.expressionEngine.evaluateWithFallback(e.value,n,i);return Boolean(s)}buildActionContext(e,t){return{...e,local:{...e.local||{},$event:t.$event,$prevResult:t.$prevResult,$results:t.$results}}}withTimeout(e,t){return new Promise((r,n)=>{const i=setTimeout(()=>{n(new Error(`Action timed out after ${t}ms`))},t);e.then(e=>{clearTimeout(i),r(e)}).catch(e=>{clearTimeout(i),n(e)})})}debounce(e,t){return new Promise(r=>{const n=this.debounceTimers.get(e);n&&clearTimeout(n);const i=setTimeout(()=>{this.debounceTimers.delete(e),r()},t);this.debounceTimers.set(e,i)})}throttle(e,t){const r=Date.now();return!(r-(this.throttleTimers.get(e)??0)<t||(this.throttleTimers.set(e,r),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,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}};w.EXPRESSION_TYPES=["state","binding","local","template","computed"];var b=w,I=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];return["==","!=",">=","<=","&&","||","??"].includes(t)?(this.pos+=2,{type:"OPERATOR",value:t,start:e,end:this.pos}):["+","-","*","/","%",">","<","!"].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]||""}},E={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 n=String(e??""),i=Number(t)||0,s=void 0!==r?Number(r):void 0;return n.substring(i,void 0!==s?i+s: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,n=Number(t)||0,i=Math.pow(10,n);return Math.round(r*i)/i},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=>Array.isArray(e)&&0!==e.length?e.reduce((e,t)=>e+(Number(t)||0),0)/e.length:0,random:()=>Math.random(),randomInt:(e,t)=>{const r=Math.ceil(Number(e)||0),n=Math.floor(Number(t)||100);return Math.floor(Math.random()*(n-r+1))+r},now:()=>Date.now(),today:()=>(new Date).toISOString().split("T")[0],dateFormat:(e,t)=>{const r=new Date(Number(e)||Date.now()),n=e=>e.toString().padStart(2,"0");return String(t||"YYYY-MM-DD").replace("YYYY",r.getFullYear().toString()).replace("MM",n(r.getMonth()+1)).replace("DD",n(r.getDate())).replace("HH",n(r.getHours())).replace("mm",n(r.getMinutes())).replace("ss",n(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()),n=new Date(Number(t)||Date.now()),i=Math.abs(n.getTime()-r.getTime());return Math.floor(i/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 n=String(t).split(".");let i=e;for(const s of n){if(null==i)return r;i=i[s]}return i??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 n=Number(e);return n>=Number(t)&&n<=Number(r)},formatNumber:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return r.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})},formatCurrency:(e,t)=>{const r=Number(e)||0,n=String(t||"CNY");return r.toLocaleString("zh-CN",{style:"currency",currency:n})},formatPercent:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return(100*r).toFixed(n)+"%"},currency:(e,t,r)=>{const n=Number(e)||0,i=String(t??"¥"),s=Number(r)??2;return`${i}${n.toLocaleString(void 0,{minimumFractionDigits:s,maximumFractionDigits:s})}`},percent:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return(100*r).toFixed(n)+"%"},number:(e,t)=>{const r=Number(e)||0,n=Number(t)??0;return r.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})},pluralize:(e,t,r)=>{const n=Number(e)||0;return`${n} ${String(1===n?t:r)}`},mask:(e,t,r,n)=>{const i=String(e??""),s=Number(t)||3,a=Number(r)||4,o=String(n??"*");if(i.length<=s+a)return i;const c=i.slice(0,s),u=i.slice(-a);return c+o.repeat(i.length-s-a)+u},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,r)=>{const n=Number(e)||0,i=Number(t)||0,s=Number(r)||100;return Math.min(Math.max(n,i),s)},length:e=>Array.isArray(e)||"string"==typeof e?e.length:0,average:e=>Array.isArray(e)&&0!==e.length?e.reduce((e,t)=>e+(Number(t)||0),0)/e.length:0,dateAdd:(e,t,r)=>{const n=new Date(Number(e)||Date.now()),i=Number(t)||0;switch(String(r??"day").toLowerCase()){case"year":case"years":n.setFullYear(n.getFullYear()+i);break;case"month":case"months":n.setMonth(n.getMonth()+i);break;case"week":case"weeks":n.setDate(n.getDate()+7*i);break;case"day":case"days":default:n.setDate(n.getDate()+i);break;case"hour":case"hours":n.setHours(n.getHours()+i);break;case"minute":case"minutes":n.setMinutes(n.getMinutes()+i)}return n.getTime()},dateDiff:(e,t,r)=>{const n=new Date(Number(e)||Date.now()),i=new Date(Number(t)||Date.now()).getTime()-n.getTime();switch(String(r??"day").toLowerCase()){case"year":case"years":return Math.floor(i/31536e6);case"month":case"months":return Math.floor(i/2592e6);case"week":case"weeks":return Math.floor(i/6048e5);case"day":case"days":default:return Math.floor(i/864e5);case"hour":case"hours":return Math.floor(i/36e5);case"minute":case"minutes":return Math.floor(i/6e4)}},$if:(e,t,r)=>e?t:r,toBoolean:e=>"string"==typeof e?"false"!==e.toLowerCase()&&"0"!==e&&""!==e:Boolean(e),substring:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=void 0!==r?Number(r):void 0;return n.substring(i,s)},padStart:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=String(r??" ");return n.padStart(i,s)},padEnd:(e,t,r)=>{const n=String(e??""),i=Number(t)||0,s=String(r??" ");return n.padEnd(i,s)},repeat:(e,t)=>{const r=String(e??""),n=Math.max(0,Math.floor(Number(t)||0));return r.repeat(n)}},S={"||":1,"??":1,"&&":2,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},T=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();return this.expect("COLON"),{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 n=S[r.value];if(void 0===n||n<e)break;this.advance();const i=this.parseBinary(n+1);t={type:"binary",operator:r.value,left:t,right:i,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(!(r in E))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()}},A=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 u("",`Unknown node type: ${e.type}`)}}evaluateLiteral(e){return e.value}evaluateIdentifier(e,t){var r,n;const i=e.name;switch(i){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==(r=t.local)?void 0:r.item;case"index":return null==(n=t.local)?void 0:n.index;default:if(t.local&&i in t.local)return t.local[i];throw new u("",`Unknown variable '${i}'. Available: state, binding, local, props, event`)}}evaluateMember(e,t){const r=this.evaluateNode(e.object,t);if(null==r)return;let n;return n=e.computed?this.evaluateNode(e.property,t):e.property,"object"==typeof r&&null!==r?r[n]:void 0}evaluateCall(e,t){const r=E[e.callee];if(!r)throw new u("",`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)return this.evaluateNode(e.left,t)||this.evaluateNode(e.right,t);if("??"===r){const r=this.evaluateNode(e.left,t);return null!=r?r:this.evaluateNode(e.right,t)}const n=this.evaluateNode(e.left,t),i=this.evaluateNode(e.right,t);switch(r){case"+":return"string"==typeof n||"string"==typeof i?String(n)+String(i):n+i;case"-":return n-i;case"*":return n*i;case"/":return n/i;case"%":return n%i;case"==":return n===i;case"!=":return n!==i;case"<":return n<i;case">":return n>i;case"<=":return n<=i;case">=":return n>=i;default:throw new u("",`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 u("",`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 u("","Maximum recursion depth exceeded");if(Date.now()-this.startTime>(this.options.timeout??1e3))throw new u("","Expression evaluation timeout")}},R=class{constructor(e={}){this.astCache=new Map,this.options={cacheAST:!0,maxCacheSize:1e3,...e},this.evaluator=new A(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 n="string"==typeof e?e:e.value,i="object"==typeof e&&void 0!==e.fallback?e.fallback:r,s=this.evaluate(n,t);return s.error?(this.log("warn",`Expression evaluation failed: ${s.error.message}`,n),i):s.value}evaluateTemplate(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{const n=this.evaluate(r.trim(),t);return n.error?(this.log("warn",`Template expression failed: ${n.error.message}`,r),""):String(n.value??"")})}parse(e){if(this.options.cacheAST){const t=this.astCache.get(e);if(t)return t}try{const t=new I(e).tokenize(),r=new T(t).parse();return this.options.cacheAST&&(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)),r}catch(t){throw new u(e,t instanceof Error?t.message:"Parse error")}}validate(e){const t=[],r=[],n=[],i=[];try{const t=this.parse(e);return this.collectReferences(t,n,i),{valid:!0,errors:[],warnings:r,referencedPaths:n,usedFunctions:i}}catch(s){return t.push({type:"invalid_syntax",message:s instanceof Error?s.message:"Parse error"}),{valid:!1,errors:t,warnings:r,referencedPaths:n,usedFunctions:i}}}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}},$=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}`,r=localStorage.getItem(t);if(!r)return null;try{const e=JSON.parse(r);return e.expires&&Date.now()>e.expires?(localStorage.removeItem(t),null):e.value}catch{return null}},set:(e,t,r)=>{const n=`${this.storageNamespace}:${e}`,i={value:t,expires:(null==r?void 0:r.ttlSeconds)?Date.now()+1e3*r.ttlSeconds:void 0};("session"===(null==r?void 0:r.level)?sessionStorage:localStorage).setItem(n,JSON.stringify(i))},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 r=localStorage.key(t);(null==r?void 0:r.startsWith(e))&&localStorage.removeItem(r)}for(let t=sessionStorage.length-1;t>=0;t--){const r=sessionStorage.key(t);(null==r?void 0:r.startsWith(e))&&sessionStorage.removeItem(r)}}},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 r=new URLSearchParams(e.query);t+=(t.includes("?")?"&":"?")+r.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;this.options.userApiAdapter.track({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}})}async requestData(e,t){this.log("debug",`Requesting data: ${e}`,t);const r=performance.now(),n=this.options.context;try{const i=await this.options.userApiAdapter.executeQuery({queryVersionId:e,params:t??{},context:{pageVersionId:n.pageVersionId,uid:n.userId,deviceId:n.deviceId}}),s=performance.now()-r;if(this.log("debug",`Data query completed in ${s.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(i){const t=performance.now()-r;throw this.log("error",`Data query failed: ${e} (${t.toFixed(2)}ms)`,i),i}}async executeAction(e,t={}){this.log("debug",`Executing action: ${e}`,t);const r=performance.now(),n=this.options.context,i=this.generateIdempotencyKey(e,t);this.track({eventName:"djvlc_action_start",params:{actionType:e,idempotencyKey:i},type:"custom"});try{const s=await this.options.userApiAdapter.executeAction({actionType:e,params:t||{},context:{pageVersionId:n.pageVersionId,uid:n.userId,deviceId:n.deviceId,channel:n.channel,appId:n.appId},idempotencyKey:i}),a=performance.now()-r;return this.log("debug",`Action completed in ${a.toFixed(2)}ms`,{success:s.success}),this.track({eventName:s.success?"djvlc_action_success":"djvlc_action_fail",params:{actionType:e,idempotencyKey:i,duration:Math.round(a),errorCode:s.errorCode},type:"custom"}),s}catch(s){const t=performance.now()-r;return this.log("error",`Action failed: ${e} (${t.toFixed(2)}ms)`,s),this.track({eventName:"djvlc_action_error",params:{actionType:e,idempotencyKey:i,duration:Math.round(t),errorMessage:s instanceof Error?s.message:"Unknown error"},type:"custom"}),{success:!1,errorCode:"NETWORK_ERROR",errorMessage:s instanceof Error?s.message:"Action failed"}}}async openDialog(e){return this.log("debug","Open dialog:",e),new Promise(t=>{const r=new CustomEvent("djvlc:openDialog",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(r),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");switch(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"}),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}return e.url&&await this.clipboard.write(e.url)?(this.showToast({message:"链接已复制",type:"success"}),{success:!0,channel:"link"}):{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 r=new CustomEvent("djvlc:showActionSheet",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(r),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}}generateIdempotencyKey(e,t){const r=Date.now(),n=JSON.stringify(t||{});return`${e}:${r}:${this.simpleHash(n)}`}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)}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,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},N=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,r]=e.split("@");t&&r&&this.blockedComponentsMap.set(e,{name:t,version:r,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 r=`${e}@${t}`;this.blockedComponentsMap.delete(r),this.log("info",`Component unblocked: ${r}`)}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,r){if(!this.allowedCapabilitiesSet)return{valid:!0,disallowed:[]};const n=r.filter(e=>!this.allowedCapabilitiesSet.has(e));return n.length>0&&this.log("warn",`Component ${e}@${t} uses disallowed capabilities: ${n.join(", ")}`),{valid:0===n.length,disallowed:n}}async validateIntegrity(e,t,r,n){if(!this.options.enableSRI)return;const[i,s]=n.split("-");if(!i||!s)throw new o(e,t,n,"Invalid integrity format");const a=await this.computeHash(r,i);if(a!==s)throw this.log("error",`Integrity check failed for ${e}@${t}`),new o(e,t,s,a);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 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)||t.hostname===r.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 r=t.hostname;return"localhost"===r||"127.0.0.1"===r||r.startsWith("192.168.")||r.startsWith("10.")||r.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||[],r=["'self'",...e].join(" "),n=["'self'",...t,...e].join(" ");return["default-src 'self'",`script-src ${r}`,`style-src ${["'self'","'unsafe-inline'",...e].join(" ")}`,`img-src ${["'self'","data:","blob:",...e].join(" ")}`,`font-src ${["'self'","data:",...e].join(" ")}`,`connect-src ${n}`,"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 r=this.getBlockedInfo(e,t);if(r)throw new c(e,t,r.reason)}createSafeEvaluator(){return(e,t)=>{const r=Object.keys(t),n=Object.values(t);return new Function(...r,`"use strict"; return (${e});`)(...n)}}async computeHash(e,t){const r=(new TextEncoder).encode(e),n=await crypto.subtle.digest(t.toUpperCase(),r),i=Array.from(new Uint8Array(n));return btoa(String.fromCharCode(...i))}log(e,t,...r){this.options.logger&&this.options.logger[e](t,...r)}},D=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(),r=this.shouldSample?"01":"00";return`00-${this.traceId}-${t}-${r}`}parseTraceparent(e){const t=e.split("-");if(4!==t.length)return null;const[,r,n,i]=t;return{traceId:r,parentSpanId:n,sampled:"01"===i}}startSpan(e,t,r){const n={spanId:this.generateSpanId(),traceId:this.traceId,parentSpanId:t,name:e,startTime:performance.now(),attributes:{pageVersionId:this.options.pageVersionId,...r}};return this.spans.set(n.spanId,n),this.log("debug",`Span started: ${e} (${n.spanId})`),n}endSpan(e,t="ok",r){const n=this.spans.get(e);if(n){n.endTime=performance.now(),n.status=t,r&&(n.attributes={...n.attributes,...r});const i=n.endTime-n.startTime;this.log("debug",`Span ended: ${n.name} (${e}) - ${i.toFixed(2)}ms [${t}]`)}}recordPageLoad(e){this.recordMetricInternal({type:"pageLoadTime",value:e,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordComponentLoad(e,t,r,n){this.recordMetricInternal({type:"componentLoadTime",value:r,pageVersionId:this.options.pageVersionId,componentName:e,componentVersion:t,timestamp:Date.now()}),n||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,r,n){this.recordMetricInternal({type:"actionExecuteTime",value:r,pageVersionId:this.options.pageVersionId,actionType:e,timestamp:Date.now()}),n||this.recordError(new Error(`Action failed: ${e}`),{actionId:t})}recordQueryExecute(e,t,r,n=!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: ${n}, success: ${r}`)}recordExpressionEval(e,t,r){t>1&&this.recordMetricInternal({type:"expressionEvalTime",value:t,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordError(e,t){var r,n;const i={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(i),this.log("error",`Error recorded: ${e.message}`),null==(n=(r=this.options).onError)||n.call(r,i),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),r=this.metrics.find(e=>"firstRenderTime"===e.type);return{pageLoadTime:null==t?void 0:t.value,firstRenderTime:null==r?void 0:r.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,r;this.metrics.push(e),null==(r=(t=this.options).onMetric)||r.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,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},x=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 r=this.renderNode(e.root);r&&t.appendChild(r),this.log("info",`Page rendered with root component: ${e.root.componentType}`)}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}}getContext(){return{...this.expressionContext}}destroy(){this.cleanup(),this.container&&(this.container.innerHTML=""),this.log("debug","Renderer destroyed")}cleanup(){this.componentEventListeners.forEach((e,t)=>{const r=this.renderedElements.get(t);r&&e.forEach(({event:e,handler:t})=>{r.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:r,componentVersion:n}=e;try{if(e.condition&&!this.evaluateCondition(e.condition))return this.log("debug",`Component ${t} hidden by condition`),null;if(e.loop)return this.renderLoop(e);const i=this.createElement(e);if(!i)return null;i.setAttribute("data-component-id",t),i.setAttribute("data-component-type",r),n&&i.setAttribute("data-component-version",n);const s=this.resolveProps(e.props);if(this.applyProps(i,s),e.style&&this.applyStyles(i,e.style),e.layout&&this.applyLayout(i,e.layout),this.options.injectHostApi(i,t),e.eventHandlers&&e.eventHandlers.length>0&&this.bindEventHandlers(i,t,e.eventHandlers),this.renderChildren(i,e),e.ref){const t=this.expressionContext.local,r=t.$refs||{};r[e.ref]=i,this.expressionContext={...this.expressionContext,local:{...t,$refs:r}}}return this.renderedElements.set(t,i),i}catch(i){return this.log("error",`Failed to render component: ${t}`,i),this.options.onRenderError?this.options.onRenderError(t,i):this.createErrorFallback(t,r,i)}}createElement(e){var t;const{componentType:r}=e,n=this.options.components.get(r);if(n&&customElements.get(r))return document.createElement(r);const i=`${r}-${null==(t=e.componentVersion)?void 0:t.replace(/\./g,"-")}`;if(customElements.get(i))return document.createElement(i);const s=document.createElement("div");return s.className=`djvlc-component djvlc-${r}`,n||(this.log("warn",`Component not loaded: ${r}`),s.classList.add("djvlc-component-fallback")),s}renderLoop(e){const{loop:t}=e;if(!t)return null;const r=this.evaluateExpression(t.items);if(!Array.isArray(r))return this.log("warn",`Loop items is not an array for ${e.id}`),null;const n=document.createDocumentFragment();r.forEach((r,i)=>{this.loopContextStack.push({item:r,index:i,loopConfig:t});const s={...this.expressionContext},a={...this.expressionContext.local,[t.itemName]:r,item:r,index:i};t.indexName&&(a[t.indexName]=i),this.expressionContext={...this.expressionContext,local:a};const o={...e,id:`${e.id}_${i}`,loop:void 0},c=this.renderNode(o);if(c){const e=this.evaluateExpression(t.key);c.setAttribute("data-loop-key",String(e??i)),n.appendChild(c)}this.expressionContext=s,this.loopContextStack.pop()});const i=document.createElement("div");return i.className="djvlc-loop-container",i.setAttribute("data-loop-id",e.id),i.appendChild(n),i}renderChildren(e,t){if(t.slots&&Object.keys(t.slots).length>0)for(const[r,n]of Object.entries(t.slots)){const t=this.createSlotContainer(r);for(const e of n){const r=this.renderNode(e);r&&t.appendChild(r)}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,r){const n=[];for(const i of r){const{eventName:r,preventDefault:s,stopPropagation:a,throttle:o,debounce:c,condition:u}=i;let d=e=>{if(u&&!this.evaluateCondition(u))return;s&&e.preventDefault(),a&&e.stopPropagation();const n=e.detail||{};this.options.onComponentEvent&&this.options.onComponentEvent(t,r,[i],n)};o&&o>0&&(d=this.createThrottledHandler(d,o)),c&&c>0&&(d=this.createDebouncedHandler(d,c)),e.addEventListener(r,d),n.push({event:r,handler:d})}this.componentEventListeners.set(t,n)}createThrottledHandler(e,t){let r=0;return n=>{const i=Date.now();i-r>=t&&(r=i,e(n))}}createDebouncedHandler(e,t){let r=null;return n=>{r&&clearTimeout(r),r=setTimeout(()=>{e(n),r=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,r=this.buildExpressionContext();return this.options.expressionEngine.evaluateWithFallback(t.value,r,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[r,n]of Object.entries(e))t[r]=this.resolveValue(n);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 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,this.buildExpressionContext(),e.fallback)}const n={};for(const[e,t]of Object.entries(r))n[e]=this.resolveValue(t);return n}return t}applyProps(e,t){for(const[r,n]of Object.entries(t))null!=n&&(e.tagName.includes("-")?e[r]=n:"boolean"==typeof n?n?e.setAttribute(r,""):e.removeAttribute(r):"object"==typeof n?e.setAttribute(r,JSON.stringify(n)):e.setAttribute(r,String(n)))}applyStyles(e,t){if(t.inline)for(const[r,n]of Object.entries(t.inline)){if(null==n)continue;const t=this.resolveValue(n);let i;i="number"==typeof t?["zIndex","opacity","flex","fontWeight","lineHeight"].includes(r)?String(t):`${t}px`:String(t);const s=r.replace(/([A-Z])/g,"-$1").toLowerCase();e.style.setProperty(s,i)}t.className&&e.classList.add(...String(t.className).split(" ").filter(Boolean))}applyLayout(e,t){const{x:r,y:n,width:i,height:s,rotation:a,zIndex:o,responsive:c}=t;e.style.position="absolute",void 0!==r&&(e.style.left=`${r}px`),void 0!==n&&(e.style.top=`${n}px`),void 0!==i&&(e.style.width=`${i}px`),void 0!==s&&(e.style.height=`${s}px`),void 0!==a&&(e.style.transform=`rotate(${a}deg)`),void 0!==o&&(e.style.zIndex=String(o)),c&&this.applyResponsiveLayout(e,c)}applyResponsiveLayout(e,t){const r=e.getAttribute("data-component-id");if(!r)return;let n="";if(t.mobile&&(n+=`\n @media (max-width: 767px) {\n [data-component-id="${r}"] {\n ${this.layoutToCSS(t.mobile)}\n }\n }\n `),t.tablet&&(n+=`\n @media (min-width: 768px) and (max-width: 1023px) {\n [data-component-id="${r}"] {\n ${this.layoutToCSS(t.tablet)}\n }\n }\n `),t.desktop&&(n+=`\n @media (min-width: 1440px) {\n [data-component-id="${r}"] {\n ${this.layoutToCSS(t.desktop)}\n }\n }\n `),n){const e=document.createElement("style");e.setAttribute("data-djvlc-responsive",r),e.textContent=n,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 r=e.config;r&&(this.applyLayoutConfig(t,r.layout),r.styles&&this.applyStylesConfig(t,r.styles),r.behavior&&this.applyBehaviorConfig(t,r.behavior))}applyBehaviorConfig(e,t){t.debug&&e.setAttribute("data-debug","true"),t.i18n&&this.applyI18nConfig(e,t.i18n)}applyI18nConfig(e,t){const r=this.detectLocale(t);e.setAttribute("lang",r),e.setAttribute("data-locale",r),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",r),e.style.setProperty("--djvlc-dir",this.getTextDirection(r)),"rtl"===this.getTextDirection(r)?(e.setAttribute("dir","rtl"),e.classList.add("djvlc-rtl")):e.setAttribute("dir","ltr"),this.expressionContext={...this.expressionContext,local:{...this.expressionContext.local,$locale:r,$defaultLocale:t.defaultLocale,$supportedLocales:t.supportedLocales}},this.log("debug",`I18n configured: locale=${r}, default=${t.defaultLocale}`)}detectLocale(e){const{defaultLocale:t,supportedLocales:r,detection:n="browser"}=e;let i=null;switch(n){case"browser":case"header":i=this.detectBrowserLocale(r);break;case"url":i=this.detectUrlLocale(r);break;case"path":i=this.detectPathLocale(r);break;case"cookie":i=this.detectCookieLocale(r);break;case"manual":i=t;break;default:i=null}return i&&r.includes(i)?i:t}detectBrowserLocale(e){if("undefined"==typeof navigator)return null;const t=navigator.languages||[navigator.language];for(const r of t){if(e.includes(r))return r;const t=r.split("-")[0],n=e.find(e=>e===t||e.startsWith(`${t}-`));if(n)return n}return null}detectUrlLocale(e){if("undefined"==typeof window)return null;const t=new URLSearchParams(window.location.search),r=t.get("lang")||t.get("locale");return r&&e.includes(r)?r:null}detectPathLocale(e){if("undefined"==typeof window)return null;const t=window.location.pathname.split("/").filter(Boolean);if(t.length>0){const r=t[0];if(e.includes(r))return r}return null}detectCookieLocale(e){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(const r of t){const[t,n]=r.trim().split("=");if("lang"===t||"locale"===t||"language"===t){const t=decodeURIComponent(n);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(r=>r===e||r===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:r=0,right:n=0,bottom:i=0,left:s=0}=t.padding;e.style.padding=`${r}px ${n}px ${i}px ${s}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[r,n]of Object.entries(t.cssVariables)){const t=r.startsWith("--")?r:`--${r}`;e.style.setProperty(t,n)}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[r,n]of Object.entries(t.variables)){const t=r.startsWith("--")?r:`--theme-${r}`;e.style.setProperty(t,n)}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[r,n]of Object.entries(e.state.fields))n&&"object"==typeof n&&(t[r]=n.initialValue);this.expressionContext={...this.expressionContext,state:t}}}createErrorFallback(e,t,r){const n=document.createElement("div");return n.className="djvlc-error-boundary",n.setAttribute("data-component-id",e),n.setAttribute("data-error","true"),n.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">${r.message}</pre>`:""}\n </div>\n `,n}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}};x.EXPRESSION_TYPES=["state","binding","local","template","computed"];var O=x,C=class{constructor(e){this.lifecycle=null,this.mounted=!1,this.destroyed=!1,this.cleanupFns=[],this.options=e}register(e){var t,r,n;e?(this.lifecycle=e,this.log("debug","Lifecycle hooks registered",{onMounted:(null==(t=e.onMounted)?void 0:t.length)??0,onBeforeUnmount:(null==(r=e.onBeforeUnmount)?void 0:r.length)??0,onVisibilityChange:(null==(n=e.onVisibilityChange)?void 0:n.length)??0}),e.onVisibilityChange&&e.onVisibilityChange.length>0&&this.setupVisibilityListener()):this.log("debug","No lifecycle hooks defined")}async triggerMounted(){var e,t,r;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==(r=(t=this.options).onLifecycleEvent)||r.call(t,"mounted"))}async triggerBeforeUnmount(){var e,t,r;this.mounted&&!this.destroyed&&(this.log("debug","Triggering onBeforeUnmount lifecycle"),await this.executeLifecycleActions("beforeUnmount",null==(e=this.lifecycle)?void 0:e.onBeforeUnmount),null==(r=(t=this.options).onLifecycleEvent)||r.call(t,"beforeUnmount"))}async triggerVisibilityChange(e){var t,r,n;if(!this.mounted||this.destroyed)return;this.log("debug","Triggering onVisibilityChange lifecycle",{isVisible:e});const i=this.options.getContext(),s={...i,local:{...i.local,$visible:e,$hidden:!e}};await this.executeLifecycleActionsWithContext("visibilityChange",null==(t=this.lifecycle)?void 0:t.onVisibilityChange,s),null==(n=(r=this.options).onLifecycleEvent)||n.call(r,"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 r=this.options.getContext();await this.executeLifecycleActionsWithContext(e,t,r)}async executeLifecycleActionsWithContext(e,t,r){if(t&&0!==t.length){this.log("debug",`Executing ${t.length} actions for ${e}`);try{const n={id:`lifecycle_${e}`,eventName:e,actions:t};await this.options.actionBridge.handleEvent(n,{lifecycle:e},r),this.log("debug",`Lifecycle ${e} actions completed`)}catch(n){this.log("error",`Failed to execute lifecycle ${e} actions`,n)}}}log(e,t,...r){this.options.logger?this.options.logger[e](t,...r):this.options.debug}},q="1.0.0",k="1.0.0";function P(e){return new _(e)}var _=class{constructor(e){if(this.container=null,!e.pageId)throw new Error("pageId is required");if(this.options={channel:"prod",debug:!1,enableSRI:!0,env:"production",...e},this.logger=this.createLogger(),this.stateManager=new y,this.eventBus=new v({debug:e.debug,logger:this.logger}),this.expressionEngine=new R({debug:e.debug,logger:this.logger}),!e.userApiAdapter)throw new Error("userApiAdapter is required. Inject a UserApiAdapter implementation (e.g. from @djvlc/runtime-web or your host).");this.userApiAdapter=e.userApiAdapter,this.pageLoader=new h({apiBaseUrl:e.apiBaseUrl,userApiAdapter:this.userApiAdapter,channel:e.channel,previewToken:e.previewToken,headers:e.headers,logger:this.logger}),this.componentLoader=new m({cdnBaseUrl:e.cdnBaseUrl,enableSRI:e.enableSRI,headers:e.headers,logger:this.logger}),this.assetLoader=new f({cdnHosts:[new URL(e.cdnBaseUrl).host],apiHosts:[new URL(e.apiBaseUrl).host]}),this.securityManager=new N({enableSRI:e.enableSRI,cdnDomains:[new URL(e.cdnBaseUrl).host],apiDomains:[new URL(e.apiBaseUrl).host],logger:this.logger}),this.log("info","Runtime created",{version:k})}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,t,r;this.log("info","Loading page:",this.options.pageId);const n=performance.now();try{this.stateManager.setPhase("resolving");const i=await this.pageLoader.resolve(this.options.pageId,{uid:this.options.userId,deviceId:this.options.deviceId});if(this.validateSchemaVersion(i.pageJson),this.stateManager.setPage(i),this.telemetryManager=new D({pageVersionId:i.pageVersionId,appId:this.options.appId,debug:this.options.debug,logger:this.logger,onMetric:this.options.onMetric}),i.runtimeConfig){const t=(null==(e=i.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(i.manifest.components),(await this.componentLoader.loadAll(i.manifest)).forEach((e,t)=>{this.stateManager.setComponentStatus(t,e),this.telemetryManager.recordComponentLoad(e.name,e.version,e.loadTime||0,"loaded"===e.status)}),this.initHostApi(i),this.initActionBridge(),this.initDataBindingManager(i.pageJson),this.initRenderer(),this.initLifecycleManager(i.pageJson);const s=performance.now()-n;return this.telemetryManager.recordPageLoad(s),this.log("info",`Page loaded in ${s.toFixed(2)}ms`),this.emitEvent("page:loaded",{page:i,loadTime:s}),null==(r=(t=this.options).onLoad)||r.call(t,i),i}catch(i){throw this.stateManager.setPhase("error"),this.handleError(i),i}}async render(){const e=this.stateManager.getState();if(!e.page||!this.container)throw new s("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 r=performance.now()-t;this.telemetryManager.recordFirstRender(r),this.log("info",`Page rendered in ${r.toFixed(2)}ms`),await this.lifecycleManager.triggerMounted(),this.emitEvent("page:rendered",{renderTime:r})}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),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,r,n,i;this.log("info","Destroying runtime"),await(null==(e=this.lifecycleManager)?void 0:e.destroy()),null==(t=this.telemetryManager)||t.flush(),null==(r=this.dataBindingManager)||r.destroy(),null==(n=this.actionBridge)||n.destroy(),null==(i=this.renderer)||i.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!==q)throw new s(`Unsupported schema version: ${e.schemaVersion}. Only ${q} is supported.`,{schemaVersion:e.schemaVersion,supportedVersion:q})}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 $({userApiAdapter:this.userApiAdapter,stateManager:this.stateManager,eventBus:this.eventBus,expressionEngine:this.expressionEngine,context:{pageId:e.pageId,pageVersionId:e.pageVersionId,runtimeVersion:k,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 b({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 r;t.success?this.emitEvent("action:executed",{action:e,data:t.data}):this.emitEvent("action:error",{action:e,error:null==(r=t.error)?void 0:r.message})}})}initDataBindingManager(e){this.dataBindingManager=new g({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 r;this.emitEvent("query:fetched",{bindingId:e,data:t}),null==(r=this.renderer)||r.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 C({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,r)=>{if("loaded"===t.status&&t.component){const[n,i]=r.split("@");e.set(n,{name:n,version:i,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},onComponentEvent:(e,t,r,n)=>{this.handleComponentEvent(e,t,r,n)},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()}handleComponentEvent(e,t,r,n){this.log("debug",`Component event: ${e}.${t}`,n);for(const i of r)this.actionBridge.handleEvent(i,n,this.stateManager.getExpressionContext())}handleError(e){var t;const r=e instanceof i?{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(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 n=v.createEvent(e,t,null==(r=this.telemetryManager)?void 0:r.getTraceId());this.eventBus.emit(n),this.options.onEvent&&this.options.onEvent(n)}createLogger(){return{debug:(...e)=>{this.options.debug},info:(...e)=>{},warn:(...e)=>{},error:(...e)=>{}}}log(e,t,...r){this.logger[e](t,...r)}},M=class extends Error{constructor(e){super(e),this.name=this.constructor.name,this.timestamp=new Date,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,type:this.type,message:this.message,retryable:this.retryable,timestamp:this.timestamp.toISOString(),stack:this.stack}}toString(){return`${this.name}: ${this.message}`}},L=class e extends M{constructor(e,t){super(e),this.type="NETWORK_ERROR",this.retryable=!0,this.cause=t}toJSON(){return{...super.toJSON(),cause:this.cause?{name:this.cause.name,message:this.cause.message}:void 0}}static is(t){return t instanceof e}static fromFetchError(t){const r=t.message.toLowerCase();return r.includes("network")||r.includes("failed to fetch")?new e("Network request failed",t):r.includes("dns")||r.includes("getaddrinfo")?new e("DNS resolution failed",t):r.includes("connection refused")||r.includes("econnrefused")?new e("Connection refused",t):r.includes("connection reset")||r.includes("econnreset")?new e("Connection reset",t):r.includes("ssl")||r.includes("certificate")?new e("SSL/TLS error",t):new e(t.message||"Unknown network error",t)}},V=class e extends M{constructor(e){super(`Request timeout after ${e}ms`),this.type="TIMEOUT_ERROR",this.retryable=!0,this.timeoutMs=e}toJSON(){return{...super.toJSON(),timeoutMs:this.timeoutMs}}static is(t){return t instanceof e}},U=class{constructor(e){this.type="bearer",this.getToken=e.getToken,this.headerName=e.headerName??"Authorization",this.prefix=e.prefix??"Bearer"}async authenticate(e){const t=await this.getToken();null!==t&&""!==t&&(e[this.headerName]=`${this.prefix} ${t}`)}},j=class{constructor(e){this.type="api-key",this.apiKey=e.apiKey,this.headerName=e.headerName??"X-API-Key"}authenticate(e){e[this.headerName]=this.apiKey}},B=class{constructor(e){this.type="basic",this.encodedCredentials=function(e){const t=(new TextEncoder).encode(e),r=Array.from(t,e=>String.fromCharCode(e)).join("");return"undefined"!=typeof btoa?btoa(r):(()=>{throw new Error("Base64 encoding is not supported in this environment")})()}(`${e.username}:${e.password}`)}authenticate(e){e.Authorization=`Basic ${this.encodedCredentials}`}},F=class{constructor(e){this.type="custom",this.authenticateFn=e.authenticate}async authenticate(e){await this.authenticateFn(e)}},K=new class{constructor(){this.type="none"}authenticate(e){}};function H(e){return new Promise(t=>setTimeout(t,e))}var z="X-Internal-Request-Key",Y=new Map;function Q(e){const t=e.headers;return(null==t?void 0:t[z])??""}function J(e={}){var t,r,n;const i=[];var s,a;if(i.push(function(e){const t=e.auth?function(e){switch(e.type){case"bearer":return new U({getToken:e.getToken,headerName:e.headerName,prefix:e.prefix});case"api-key":return new j({apiKey:e.apiKey,headerName:e.headerName});case"basic":return new B({username:e.username,password:e.password});case"custom":return new F({authenticate:e.authenticate});case"none":return K;default:throw new Error(`Unknown auth type: ${e.type}`)}}(e.auth):K;return{async pre(r){const n=`req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,i=`trace_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}_${Math.random().toString(36).slice(2,9)}`,s=`${Date.now()}-${Math.random().toString(36).substring(2,9)}`;Y.set(s,{attempt:0,startTime:Date.now(),requestId:n,traceId:i});const a=r.init.headers??{},o={};if(a instanceof Headers)a.forEach((e,t)=>{o[t]=e});else if(Array.isArray(a))for(const[e,t]of a)o[e]=t;else Object.assign(o,a);return o[z]=s,o["X-Request-ID"]=n,o["X-Trace-ID"]=i,e.headers&&Object.assign(o,e.headers),await t.authenticate(o),{url:r.url,init:{...r.init,headers:o}}}}}(e)),e.logger&&i.push((s=e.logger,a=e.debug??!1,{async pre(e){var t;if(!a)return;const r=e.init.method??"GET",n=(null==(t=e.init.headers)?void 0:t["X-Request-ID"])??"";s.debug(`[Request] ${r} ${e.url}`,{requestId:n})},async post(e){var t;const r=Q(e.init),n=Y.get(r),i=n?Date.now()-n.startTime:0;if(r&&Y.delete(r),!a)return;const o=e.init.method??"GET",c=(null==(t=e.init.headers)?void 0:t["X-Request-ID"])??"";s.debug(`[Response] ${o} ${e.url} - ${e.response.status} (${i}ms)`,{requestId:c,status:e.response.status,duration:i})},async onError(e){var t;const r=e.init.method??"GET",n=(null==(t=e.init.headers)?void 0:t["X-Request-ID"])??"",i=Q(e.init),a=Y.get(i),o=a?Date.now()-a.startTime:0,c=e.error instanceof Error?e.error.message:String(e.error);s.error(`[Error] ${r} ${e.url} - ${c} (${o}ms)`,{requestId:n,error:c,duration:o})}})),!1!==e.enableRetry&&e.retry&&i.push(function(e){const t=e.retry,r=t.maxRetries,n=e.logger,i=e.debug??!1;return{async onError(e){const s=Q(e.init),a=Y.get(s);if(!a)return;if(!function(e,t,r,n){return!(t>=r)&&(!(e instanceof Error&&"AbortError"===e.name)&&(e instanceof TypeError||e instanceof L?!1!==n.retryOnNetworkError:!(e instanceof V)||!1!==n.retryOnTimeout))}(e.error,a.attempt,r,t))return void Y.delete(s);a.attempt++;const o=G(a.attempt,t);if(t.onRetry){const n=e.init.method??"GET";t.onRetry({attempt:a.attempt,maxRetries:r,delayMs:o,error:e.error instanceof Error?e.error:new Error(String(e.error)),url:e.url,method:n})}if(i&&n){const t=e.init.method??"GET";n.debug(`[Retry] ${t} ${e.url} - attempt ${a.attempt}/${r}, delay ${o}ms`)}await H(o);try{const o=await e.fetch(e.url,e.init);if(!o.ok&&function(e,t,r,n){if(t>=r)return!1;return(n.retryableStatusCodes??[429,500,502,503,504]).includes(e)}(o.status,a.attempt,r,t)){a.attempt++;const s=G(a.attempt,t);if(i&&n){const t=e.init.method??"GET";n.debug(`[Retry] ${t} ${e.url} - status ${o.status}, attempt ${a.attempt}/${r}, delay ${s}ms`)}return await H(s),e.fetch(e.url,e.init)}return Y.delete(s),o}catch(c){if(a.attempt<r)throw c;throw Y.delete(s),c}}}}(e)),null==(t=e.preMiddlewares)?void 0:t.length)for(const o of e.preMiddlewares)i.push({pre:o});if(null==(r=e.postMiddlewares)?void 0:r.length)for(const o of e.postMiddlewares)i.push({post:o});if(null==(n=e.errorMiddlewares)?void 0:n.length)for(const o of e.errorMiddlewares)i.push({onError:o});return i}function G(e,t){const{initialDelayMs:r=1e3,maxDelayMs:n=3e4,backoffStrategy:i="exponential",jitterFactor:s=.1}=t;let a;switch(i){case"fixed":a=r;break;case"linear":a=r*e;break;default:a=r*Math.pow(2,e-1)}if(a=Math.min(a,n),s>0){const e=a*s*(2*Math.random()-1);a=Math.max(0,a+e)}return Math.round(a)}var X="/api/user".replace(/\/+$/,""),W=class{constructor(e={}){this.configuration=e}set config(e){this.configuration=e}get basePath(){return null!=this.configuration.basePath?this.configuration.basePath:X}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||ae}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const e=this.configuration.apiKey;if(e)return"function"==typeof e?e:()=>e}get accessToken(){const e=this.configuration.accessToken;if(e)return"function"==typeof e?e:async()=>e}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}},Z=new W,ee=class e{constructor(e=Z){this.configuration=e,this.fetchApi=async(e,t)=>{let r,n={url:e,init:t};for(const s of this.middleware)s.pre&&(n=await s.pre({fetch:this.fetchApi,...n})||n);try{r=await(this.configuration.fetchApi||fetch)(n.url,n.init)}catch(i){for(const e of this.middleware)e.onError&&(r=await e.onError({fetch:this.fetchApi,url:n.url,init:n.init,error:i,response:r?r.clone():void 0})||r);if(void 0===r)throw i instanceof Error?new ne(i,"The request failed and the interceptors did not return an alternative response"):i}for(const s of this.middleware)s.post&&(r=await s.post({fetch:this.fetchApi,url:n.url,init:n.init,response:r.clone()})||r);return r},this.middleware=e.middleware}withMiddleware(...e){const t=this.clone();return t.middleware=t.middleware.concat(...e),t}withPreMiddleware(...e){const t=e.map(e=>({pre:e}));return this.withMiddleware(...t)}withPostMiddleware(...e){const t=e.map(e=>({post:e}));return this.withMiddleware(...t)}isJsonMime(t){return!!t&&e.jsonRegex.test(t)}async request(e,t){const{url:r,init:n}=await this.createFetchParams(e,t),i=await this.fetchApi(r,n);if(i&&i.status>=200&&i.status<300)return i;throw new re(i,"Response returned an error code")}async createFetchParams(e,t){let r=this.configuration.basePath+e.path;void 0!==e.query&&0!==Object.keys(e.query).length&&(r+="?"+this.configuration.queryParamsStringify(e.query));const n=Object.assign({},this.configuration.headers,e.headers);Object.keys(n).forEach(e=>void 0===n[e]?delete n[e]:{});const i="function"==typeof t?t:async()=>t,s={method:e.method,headers:n,body:e.body,credentials:this.configuration.credentials},a={...s,...await i({init:s,context:e})};let o;var c;return c=a.body,o="undefined"!=typeof FormData&&c instanceof FormData||a.body instanceof URLSearchParams||function(e){return"undefined"!=typeof Blob&&e instanceof Blob}(a.body)?a.body:this.isJsonMime(n["Content-Type"])?JSON.stringify(a.body):a.body,{url:r,init:{...a,body:o}}}clone(){const e=new(0,this.constructor)(this.configuration);return e.middleware=this.middleware.slice(),e}};ee.jsonRegex=new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$","i");var te=ee,re=class extends Error{constructor(e,t){super(t),this.response=e,this.name="ResponseError"}},ne=class extends Error{constructor(e,t){super(t),this.cause=e,this.name="FetchError"}},ie=class extends Error{constructor(e,t){super(t),this.field=e,this.name="RequiredError"}};function se(e,t){return null!=e[t]}function ae(e,t=""){return Object.keys(e).map(r=>oe(r,e[r],t)).filter(e=>e.length>0).join("&")}function oe(e,t,r=""){const n=r+(r.length?`[${e}]`:e);if(t instanceof Array){const e=t.map(e=>encodeURIComponent(String(e))).join(`&${encodeURIComponent(n)}=`);return`${encodeURIComponent(n)}=${e}`}return t instanceof Set?oe(e,Array.from(t),r):t instanceof Date?`${encodeURIComponent(n)}=${encodeURIComponent(t.toISOString())}`:t instanceof Object?ae(t,n):`${encodeURIComponent(n)}=${encodeURIComponent(String(t))}`}var ce=class{constructor(e,t=e=>e){this.raw=e,this.transformer=t}async value(){return this.transformer(await this.raw.json())}};function ue(e){if(void 0!==e)return null===e?null:{pageVersionId:e.pageVersionId,componentVersionId:e.componentVersionId,componentInstanceId:e.componentInstanceId,triggerEvent:e.triggerEvent,deviceId:e.deviceId,channel:e.channel,clientTimestamp:void 0===e.clientTimestamp?void 0:e.clientTimestamp.toISOString(),extra:e.extra}}function de(e){return function(e){return null==e?e:{actionDefinitionVersionId:se(e,"actionDefinitionVersionId")?e.actionDefinitionVersionId:void 0,actionType:se(e,"actionType")?e.actionType:void 0,name:se(e,"name")?e.name:void 0,paramsSchema:se(e,"paramsSchema")?e.paramsSchema:void 0,resultSchema:se(e,"resultSchema")?e.resultSchema:void 0}}(e)}function le(e){return function(e){return null==e?e:{type:e.type,payload:se(e,"payload")?e.payload:void 0}}(e)}function he(e){if(void 0!==e)return null===e?null:{queryVersionId:e.queryVersionId,params:e.params,alias:e.alias}}function pe(e){if(void 0!==e)return null===e?null:{pageVersionId:e.pageVersionId,componentVersionId:e.componentVersionId}}function me(e){if(void 0!==e)return null===e?null:{queries:e.queries.map(he),context:pe(e.context)}}function fe(e){return function(e){return null==e?e:{code:se(e,"code")?e.code:void 0,message:se(e,"message")?e.message:void 0}}(e)}function ye(e){return function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?e.data:void 0,error:se(e,"error")?fe(e.error):void 0}}(e)}function ge(e){return function(e){return null==e?e:{id:e.id,activityId:se(e,"activityId")?e.activityId:void 0,rewardType:e.rewardType,rewardName:se(e,"rewardName")?e.rewardName:void 0,rewardValue:se(e,"rewardValue")?e.rewardValue:void 0,status:e.status,createdAt:new Date(e.createdAt),claimedAt:se(e,"claimedAt")?new Date(e.claimedAt):void 0,expiresAt:se(e,"expiresAt")?new Date(e.expiresAt):void 0}}(e)}function ve(e){if(void 0!==e)return null===e?null:{actionType:e.actionType,actionDefinitionVersionId:e.actionDefinitionVersionId,params:e.params,context:ue(e.context),idempotencyKey:e.idempotencyKey}}function we(e){return function(e){return null==e?e:{actionId:se(e,"actionId")?e.actionId:void 0,result:se(e,"result")?e.result:void 0,effects:se(e,"effects")?e.effects.map(le):void 0,errorCode:se(e,"errorCode")?e.errorCode:void 0,errorMessage:se(e,"errorMessage")?e.errorMessage:void 0,errorDetails:se(e,"errorDetails")?e.errorDetails:void 0,requestId:se(e,"requestId")?e.requestId:void 0,traceId:se(e,"traceId")?e.traceId:void 0,duration:se(e,"duration")?e.duration:void 0,retryable:se(e,"retryable")?e.retryable:void 0,retryAfter:se(e,"retryAfter")?e.retryAfter:void 0}}(e)}function be(e){return function(e){return null==e?e:{name:se(e,"name")?e.name:void 0,description:se(e,"description")?e.description:void 0,icon:se(e,"icon")?e.icon:void 0}}(e)}function Ie(e){return function(e){return null==e?e:{id:e.id,name:e.name,type:e.type,status:e.status,description:se(e,"description")?e.description:void 0,startTime:se(e,"startTime")?new Date(e.startTime):void 0,endTime:se(e,"endTime")?new Date(e.endTime):void 0,rules:se(e,"rules")?e.rules:void 0,rewards:se(e,"rewards")?e.rewards.map(be):void 0}}(e)}function Ee(e){return function(e){return null==e?e:{prizeId:se(e,"prizeId")?e.prizeId:void 0,name:se(e,"name")?e.name:void 0,stock:se(e,"stock")?e.stock:void 0}}(e)}function Se(e,t){return null==e?e:{type:e.type,claimed:e.claimed,claimedAt:se(e,"claimedAt")?new Date(e.claimedAt):void 0,claimedPrizeId:se(e,"claimedPrizeId")?e.claimedPrizeId:void 0,availablePrizes:se(e,"availablePrizes")?e.availablePrizes.map(Ee):void 0}}function Te(e){return function(e){return null==e?e:{dayKey:se(e,"dayKey")?e.dayKey:void 0,signed:se(e,"signed")?e.signed:void 0,isMakeup:se(e,"isMakeup")?e.isMakeup:void 0}}(e)}function Ae(e){return function(e){return null==e?e:{type:se(e,"type")?e.type:void 0,daysNeeded:se(e,"daysNeeded")?e.daysNeeded:void 0,reward:se(e,"reward")?e.reward:void 0}}(e)}function Re(e,t){return null==e?e:{type:e.type,signedToday:e.signedToday,todaySignedAt:se(e,"todaySignedAt")?new Date(e.todaySignedAt):void 0,consecutiveDays:e.consecutiveDays,totalDays:e.totalDays,cycleRecords:e.cycleRecords.map(Te),makeupAvailable:e.makeupAvailable,nextReward:se(e,"nextReward")?Ae(e.nextReward):void 0}}function $e(e){return function(e){return null==e?e:{current:se(e,"current")?e.current:void 0,target:se(e,"target")?e.target:void 0}}(e)}function Ne(e){return function(e){return null==e?e:{type:se(e,"type")?e.type:void 0,amount:se(e,"amount")?e.amount:void 0}}(e)}function De(e,t){return null==e?e:{type:e.type,freeDrawsRemaining:e.freeDrawsRemaining,todayDrawCount:e.todayDrawCount,totalDrawCount:e.totalDrawCount,pityProgress:se(e,"pityProgress")?$e(e.pityProgress):void 0,resources:se(e,"resources")?e.resources.map(Ne):void 0}}function xe(e){return function(e){return null==e?e:{...Se(e),...Re(e),...De(e)}}(e)}function Oe(e){return function(e){return null==e?e:{activityId:e.activityId,userId:e.userId,activityType:e.activityType,canParticipate:e.canParticipate,notParticipateReason:se(e,"notParticipateReason")?e.notParticipateReason:void 0,remainingCount:se(e,"remainingCount")?e.remainingCount:void 0,typeState:xe(e.typeState)}}(e)}function Ce(e){return function(e){return null==e?e:{page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages}}(e)}function qe(e){return function(e){return null==e?e:{id:e.id,activityId:se(e,"activityId")?e.activityId:void 0,prizeId:e.prizeId,prizeName:se(e,"prizeName")?e.prizeName:void 0,prizeType:se(e,"prizeType")?e.prizeType:void 0,status:e.status,createdAt:new Date(e.createdAt),claimedAt:se(e,"claimedAt")?new Date(e.claimedAt):void 0}}(e)}function ke(e){return function(e){return null==e?e:{name:se(e,"name")?e.name:void 0,amount:se(e,"amount")?e.amount:void 0}}(e)}function Pe(e){return function(e){return null==e?e:{day:se(e,"day")?e.day:void 0,signedIn:se(e,"signedIn")?e.signedIn:void 0,reward:se(e,"reward")?ke(e.reward):void 0}}(e)}function _e(e){return function(e){return null==e?e:{year:e.year,month:e.month,records:e.records.map(Pe),consecutiveDays:se(e,"consecutiveDays")?e.consecutiveDays:void 0,totalDays:se(e,"totalDays")?e.totalDays:void 0}}(e)}function Me(e){return function(e){return null==e?e:{componentName:se(e,"componentName")?e.componentName:void 0,componentVersion:se(e,"componentVersion")?e.componentVersion:void 0,reason:se(e,"reason")?e.reason:void 0}}(e)}function Le(e){return function(e){return null==e?e:{killSwitch:e.killSwitch,blockedComponents:e.blockedComponents.map(Me),flags:e.flags}}(e)}function Ve(e){if(void 0!==e)return null===e?null:{noCache:e.noCache,forceRefresh:e.forceRefresh}}function Ue(e){if(void 0!==e)return null===e?null:{queryVersionId:e.queryVersionId,params:e.params,cacheControl:Ve(e.cacheControl),context:pe(e.context)}}function je(e){return function(e){return null==e?e:{queryVersionId:se(e,"queryVersionId")?e.queryVersionId:void 0,name:se(e,"name")?e.name:void 0,paramsSchema:se(e,"paramsSchema")?e.paramsSchema:void 0,resultSchema:se(e,"resultSchema")?e.resultSchema:void 0,cacheTtl:se(e,"cacheTtl")?e.cacheTtl:void 0}}(e)}function Be(e){return function(e){return null==e?e:{strategyId:se(e,"strategyId")?e.strategyId:void 0,strategyName:se(e,"strategyName")?e.strategyName:void 0,isDefault:se(e,"isDefault")?e.isDefault:void 0}}(e)}function Fe(e){return function(e){return null==e?e:{id:se(e,"id")?e.id:void 0,name:se(e,"name")?e.name:void 0,versionId:se(e,"versionId")?e.versionId:void 0,hash:se(e,"hash")?e.hash:void 0}}(e)}function Ke(e){return function(e){return null==e?e:{actions:se(e,"actions")?e.actions.map(Fe):void 0,queries:se(e,"queries")?e.queries.map(Fe):void 0}}(e)}function He(e){return function(e){return null==e?e:{js:se(e,"js")?e.js:void 0,css:se(e,"css")?e.css:void 0,chunks:se(e,"chunks")?e.chunks:void 0}}(e)}function ze(e){return function(e){return null==e?e:{name:se(e,"name")?e.name:void 0,version:se(e,"version")?e.version:void 0,integrity:se(e,"integrity")?e.integrity:void 0,assetsUrl:se(e,"assetsUrl")?e.assetsUrl:void 0,entrypoints:se(e,"entrypoints")?He(e.entrypoints):void 0}}(e)}function Ye(e){return function(e){return null==e?e:{version:se(e,"version")?e.version:void 0,minVersion:se(e,"minVersion")?e.minVersion:void 0}}(e)}function Qe(e){return function(e){return null==e?e:{components:se(e,"components")?e.components.map(ze):void 0,runtime:se(e,"runtime")?Ye(e.runtime):void 0}}(e)}function Je(e){return function(e){return null==e?e:{componentVersions:se(e,"componentVersions")?e.componentVersions:void 0,definitionVersions:se(e,"definitionVersions")?e.definitionVersions:void 0}}(e)}function Ge(e){return function(e){return null==e?e:{pageId:se(e,"pageId")?e.pageId:void 0,pageVersionId:se(e,"pageVersionId")?e.pageVersionId:void 0,publishId:se(e,"publishId")?e.publishId:void 0,schemaVersion:se(e,"schemaVersion")?e.schemaVersion:void 0,createdAt:se(e,"createdAt")?new Date(e.createdAt):void 0,createdBy:se(e,"createdBy")?e.createdBy:void 0,contentHash:se(e,"contentHash")?e.contentHash:void 0,bindings:se(e,"bindings")?Je(e.bindings):void 0,runtimeVersion:se(e,"runtimeVersion")?e.runtimeVersion:void 0,env:se(e,"env")?e.env:void 0}}(e)}function Xe(e){return function(e){return null==e?e:{schemaVersion:se(e,"schemaVersion")?e.schemaVersion:void 0,pageId:se(e,"pageId")?e.pageId:void 0,pageVersion:se(e,"pageVersion")?e.pageVersion:void 0,title:se(e,"title")?e.title:void 0,initialState:se(e,"initialState")?e.initialState:void 0,bindings:se(e,"bindings")?e.bindings:void 0,root:se(e,"root")?e.root:void 0,config:se(e,"config")?e.config:void 0}}(e)}function We(e){return function(e){return null==e?e:{page:se(e,"page")?Xe(e.page):void 0,manifest:se(e,"manifest")?Qe(e.manifest):void 0,definitionsDigest:se(e,"definitionsDigest")?Ke(e.definitionsDigest):void 0,meta:se(e,"meta")?Ge(e.meta):void 0}}(e)}function Ze(e){return function(e){return null==e?e:{pageId:e.pageId,resolvedVersionId:e.resolvedVersionId,cdnBase:e.cdnBase,snapshotUrl:e.snapshotUrl,manifestUrl:e.manifestUrl,ops:Le(e.ops),etag:e.etag,cacheTtlSeconds:e.cacheTtlSeconds,rolloutMatch:se(e,"rolloutMatch")?Be(e.rolloutMatch):void 0,snapshot:se(e,"snapshot")?We(e.snapshot):void 0}}(e)}function et(e){return function(e){return null==e?e:{eventId:se(e,"eventId")?e.eventId:void 0}}(e)}function tt(e){return function(e){return null==e?e:{index:se(e,"index")?e.index:void 0,reason:se(e,"reason")?e.reason:void 0}}(e)}function rt(e){return function(e){return null==e?e:{accepted:se(e,"accepted")?e.accepted:void 0,rejected:se(e,"rejected")?e.rejected:void 0,errors:se(e,"errors")?e.errors.map(tt):void 0}}(e)}function nt(e){if(void 0!==e)return null===e?null:{pageVersionId:e.pageVersionId,componentVersionId:e.componentVersionId,sessionId:e.sessionId,deviceType:e.deviceType,traceId:e.traceId}}function it(e){if(void 0!==e)return null===e?null:{eventName:e.eventName,eventType:e.eventType,properties:e.properties,timestamp:void 0===e.timestamp?void 0:e.timestamp.toISOString(),context:nt(e.context)}}function st(e){if(void 0!==e)return null===e?null:{events:e.events.map(it)}}function at(e){if(void 0!==e)return null===e?null:{actionType:e.actionType,actionDefinitionVersionId:e.actionDefinitionVersionId,params:e.params}}function ot(e){return function(e){return null==e?e:{path:se(e,"path")?e.path:void 0,message:se(e,"message")?e.message:void 0,code:se(e,"code")?e.code:void 0}}(e)}function ct(e){return function(e){return null==e?e:{valid:e.valid,errors:se(e,"errors")?e.errors.map(ot):void 0}}(e)}var ut=class extends te{async executeActionRaw(e,t){if(null===e.executeActionRequest||void 0===e.executeActionRequest)throw new ie("executeActionRequest","Required parameter requestParameters.executeActionRequest was null or undefined when calling executeAction.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/actions/execute",method:"POST",headers:r,query:{},body:ve(e.executeActionRequest)},t);return new ce(n,e=>function(e){return null==e?e:{success:e.success,code:e.code,message:e.message,data:we(e.data),timestamp:e.timestamp,path:e.path,requestId:se(e,"requestId")?e.requestId:void 0}}(e))}async executeAction(e,t){const r=await this.executeActionRaw(e,t);return await r.value()}async getActionDefinitionRaw(e,t){if(null===e.actionDefinitionVersionId||void 0===e.actionDefinitionVersionId)throw new ie("actionDefinitionVersionId","Required parameter requestParameters.actionDefinitionVersionId was null or undefined when calling getActionDefinition.");const r={};void 0!==e.actionDefinitionVersionId&&(r.actionDefinitionVersionId=e.actionDefinitionVersionId);const n={};if(this.configuration&&this.configuration.apiKey&&(n["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/actions/definitions",method:"GET",headers:n,query:r},t);return new ce(i,e=>function(e){return null==e?e:{data:de(e.data)}}(e))}async getActionDefinition(e,t){const r=await this.getActionDefinitionRaw(e,t);return await r.value()}async validateActionParamsRaw(e,t){if(null===e.validateActionRequest||void 0===e.validateActionRequest)throw new ie("validateActionRequest","Required parameter requestParameters.validateActionRequest was null or undefined when calling validateActionParams.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/actions/validate",method:"POST",headers:r,query:{},body:at(e.validateActionRequest)},t);return new ce(n,e=>function(e){return null==e?e:{data:ct(e.data)}}(e))}async validateActionParams(e,t){const r=await this.validateActionParamsRaw(e,t);return await r.value()}},dt=class extends te{async getActivityInfoRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new ie("activityId","Required parameter requestParameters.activityId was null or undefined when calling getActivityInfo.");const r=await this.request({path:"/activities/{activityId}".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:{},query:{}},t);return new ce(r,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?Ie(e.data):void 0}}(e))}async getActivityInfo(e,t){const r=await this.getActivityInfoRaw(e,t);return await r.value()}async getActivityStateRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new ie("activityId","Required parameter requestParameters.activityId was null or undefined when calling getActivityState.");const r={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/activities/{activityId}/state".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:r,query:{}},t);return new ce(n,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?Oe(e.data):void 0}}(e))}async getActivityState(e,t){const r=await this.getActivityStateRaw(e,t);return await r.value()}async getClaimRecordsRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new ie("activityId","Required parameter requestParameters.activityId was null or undefined when calling getClaimRecords.");const r={};void 0!==e.pageSize&&(r.pageSize=e.pageSize),void 0!==e.pageToken&&(r.pageToken=e.pageToken);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/activities/{activityId}/claims".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:n,query:r},t);return new ce(i,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?e.data.map(ge):void 0,meta:se(e,"meta")?Ce(e.meta):void 0}}(e))}async getClaimRecords(e,t){const r=await this.getClaimRecordsRaw(e,t);return await r.value()}async getLotteryRecordsRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new ie("activityId","Required parameter requestParameters.activityId was null or undefined when calling getLotteryRecords.");const r={};void 0!==e.pageSize&&(r.pageSize=e.pageSize),void 0!==e.pageToken&&(r.pageToken=e.pageToken);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/activities/{activityId}/lottery".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:n,query:r},t);return new ce(i,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?e.data.map(qe):void 0,meta:se(e,"meta")?Ce(e.meta):void 0}}(e))}async getLotteryRecords(e,t){const r=await this.getLotteryRecordsRaw(e,t);return await r.value()}async getSigninCalendarRaw(e,t){if(null===e.activityId||void 0===e.activityId)throw new ie("activityId","Required parameter requestParameters.activityId was null or undefined when calling getSigninCalendar.");const r={};void 0!==e.month&&(r.month=e.month);const n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/activities/{activityId}/signin/calendar".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:n,query:r},t);return new ce(i,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?_e(e.data):void 0}}(e))}async getSigninCalendar(e,t){const r=await this.getSigninCalendarRaw(e,t);return await r.value()}},lt=class extends te{async resolvePageRaw(e,t){if(null===e.pageId||void 0===e.pageId)throw new ie("pageId","Required parameter requestParameters.pageId was null or undefined when calling resolvePage.");const r={};void 0!==e.pageId&&(r.pageId=e.pageId),void 0!==e.env&&(r.env=e.env),void 0!==e.uid&&(r.uid=e.uid),void 0!==e.deviceId&&(r.deviceId=e.deviceId),void 0!==e.channel&&(r.channel=e.channel),void 0!==e.includeSnapshot&&(r.includeSnapshot=e.includeSnapshot);const n={};if(this.configuration&&this.configuration.apiKey&&(n["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/page/resolve",method:"GET",headers:n,query:r},t);return new ce(i,e=>function(e){return null==e?e:{success:e.success,code:e.code,message:e.message,data:Ze(e.data),timestamp:e.timestamp,path:e.path,requestId:se(e,"requestId")?e.requestId:void 0}}(e))}async resolvePage(e,t){const r=await this.resolvePageRaw(e,t);return await r.value()}},ht=class extends te{async batchQueryDataRaw(e,t){if(null===e.batchQueryRequest||void 0===e.batchQueryRequest)throw new ie("batchQueryRequest","Required parameter requestParameters.batchQueryRequest was null or undefined when calling batchQueryData.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/data/query/batch",method:"POST",headers:r,query:{},body:me(e.batchQueryRequest)},t);return new ce(n,e=>function(e){return null==e?e:{success:e.success,data:(t=e.data,r=ye,Object.keys(t).reduce((e,n)=>({...e,[n]:r(t[n])}),{}))};var t,r}(e))}async batchQueryData(e,t){const r=await this.batchQueryDataRaw(e,t);return await r.value()}async getQueryDefinitionRaw(e,t){if(null===e.queryVersionId||void 0===e.queryVersionId)throw new ie("queryVersionId","Required parameter requestParameters.queryVersionId was null or undefined when calling getQueryDefinition.");const r={};void 0!==e.queryVersionId&&(r.queryVersionId=e.queryVersionId);const n={};if(this.configuration&&this.configuration.apiKey&&(n["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/data/definitions",method:"GET",headers:n,query:r},t);return new ce(i,e=>function(e){return null==e?e:{data:je(e.data)}}(e))}async getQueryDefinition(e,t){const r=await this.getQueryDefinitionRaw(e,t);return await r.value()}async queryDataRaw(e,t){if(null===e.queryDataRequest||void 0===e.queryDataRequest)throw new ie("queryDataRequest","Required parameter requestParameters.queryDataRequest was null or undefined when calling queryData.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/data/query",method:"POST",headers:r,query:{},body:Ue(e.queryDataRequest)},t);return new ce(n,e=>function(e){return null==e?e:{success:e.success,code:e.code,message:e.message,data:e.data,timestamp:e.timestamp,path:e.path,requestId:se(e,"requestId")?e.requestId:void 0,errorCode:se(e,"errorCode")?e.errorCode:void 0,errorMessage:se(e,"errorMessage")?e.errorMessage:void 0,fromCache:se(e,"fromCache")?e.fromCache:void 0,cachedAt:se(e,"cachedAt")?new Date(e.cachedAt):void 0,age:se(e,"age")?e.age:void 0,traceId:se(e,"traceId")?e.traceId:void 0,duration:se(e,"duration")?e.duration:void 0,degraded:se(e,"degraded")?e.degraded:void 0,degradedReason:se(e,"degradedReason")?e.degradedReason:void 0}}(e))}async queryData(e,t){const r=await this.queryDataRaw(e,t);return await r.value()}},pt=class extends te{async trackRaw(e,t){if(null===e.trackRequest||void 0===e.trackRequest)throw new ie("trackRequest","Required parameter requestParameters.trackRequest was null or undefined when calling track.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/track",method:"POST",headers:r,query:{},body:it(e.trackRequest)},t);return new ce(n,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?et(e.data):void 0}}(e))}async track(e,t){const r=await this.trackRaw(e,t);return await r.value()}async trackBatchRaw(e,t){if(null===e.trackBatchRequest||void 0===e.trackBatchRequest)throw new ie("trackBatchRequest","Required parameter requestParameters.trackBatchRequest was null or undefined when calling trackBatch.");const r={"Content-Type":"application/json"};if(this.configuration&&this.configuration.apiKey&&(r["X-API-Key"]=this.configuration.apiKey("X-API-Key")),this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const n=await this.request({path:"/track/batch",method:"POST",headers:r,query:{},body:st(e.trackBatchRequest)},t);return new ce(n,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?rt(e.data):void 0}}(e))}async trackBatch(e,t){const r=await this.trackBatchRaw(e,t);return await r.value()}},mt=class{constructor(e={}){const t=e.baseUrl??"/api",r=[...J({auth:e.auth,retry:e.retry,enableRetry:e.enableRetry,logger:e.logger,debug:e.debug,timeout:e.timeout,headers:e.headers,preMiddlewares:e.preMiddlewares,postMiddlewares:e.postMiddlewares,errorMiddlewares:e.errorMiddlewares}),...e.middlewares??[]];this.configuration=new W({basePath:t,middleware:r,headers:e.headers}),this.pages=new lt(this.configuration),this.actions=new ut(this.configuration),this.activities=new dt(this.configuration),this.queries=new ht(this.configuration),this.track=new pt(this.configuration)}};class ft{constructor(e={}){var t;this.client=(t={baseUrl:e.baseUrl??"/api",timeout:e.timeout??3e4,auth:e.auth,headers:e.headers,retry:e.retry,enableRetry:e.enableRetry,logger:e.logger,debug:e.debug},new mt(t))}async resolvePage(e){return(await this.client.pages.resolvePage({pageId:e.pageId,env:e.env,uid:e.uid,deviceId:e.deviceId,channel:e.channel})).data}async executeAction(e){const t=await this.client.actions.executeAction({executeActionRequest:{actionType:e.actionType,params:e.params,context:{pageVersionId:e.context.pageVersionId,deviceId:e.context.deviceId,channel:e.context.channel,extra:{uid:e.context.uid,appId:e.context.appId}},idempotencyKey:e.idempotencyKey}}),r=t.data;return{success:t.success,data:null==r?void 0:r.result,errorCode:null==r?void 0:r.errorCode,errorMessage:null==r?void 0:r.errorMessage}}async executeQuery(e){const t=await this.client.queries.queryData({queryDataRequest:{queryVersionId:e.queryVersionId,params:e.params??{},context:{pageVersionId:e.context.pageVersionId}}});return{success:t.success,data:t.data??void 0,message:t.message,errorMessage:t.errorMessage}}track(e){this.client.track.track({trackRequest:{eventName:e.eventName,eventType:e.type??"custom",properties:e.params,timestamp:null!=e.timestamp?new Date(e.timestamp):void 0,context:{pageVersionId:e.context.pageVersionId,sessionId:e.context.userId}}}).catch(()=>{})}}function yt(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 r=t.getEntries(),n=r[r.length-1];n&&(e.lcp=n.startTime)}).observe({type:"largest-contentful-paint",buffered:!0}),new PerformanceObserver(t=>{const r=t.getEntries();if(r.length>0){const t=r[0];e.fid=t.processingStart-t.startTime}}).observe({type:"first-input",buffered:!0});let r=0;new PerformanceObserver(t=>{for(const n of t.getEntries()){const t=n;!t.hadRecentInput&&t.value&&(r+=t.value,e.cls=r)}}).observe({type:"layout-shift",buffered:!0})}catch{}}class gt{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,r){if(!this.enabled)return 0;const n=this.marks.get(t),i=r?this.marks.get(r):performance.now();if(void 0===n)return 0;const s=(i??performance.now())-n;if(this.measures.set(e,s),"function"==typeof performance.measure)try{performance.measure(`djvlc:${e}`,`djvlc:${t}`,r?`djvlc:${r}`:void 0)}catch{}return s}getMeasures(){return Object.fromEntries(this.measures)}clear(){this.marks.clear(),this.measures.clear()}}function vt(e=!0){return new gt(e)}function wt(){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 bt(e){return performance.getEntriesByType("resource").filter(e||(()=>!0)).map(e=>({name:e.name,type:e.initiatorType,duration:e.duration,size:e.transferSize||0}))}function It(){return bt(e=>e.name.includes("/components/")||e.name.includes("/runtime/"))}function Et(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 St(e,r=t){[`${e}/runtime/${r}/runtime.esm.js`,`${e}/runtime/${r}/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 Tt(){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 At(){return Array.from({length:32},()=>Math.floor(16*Math.random()).toString(16)).join("")}function Rt(){return Array.from({length:16},()=>Math.floor(16*Math.random()).toString(16)).join("")}function $t(){return`00-${At()}-${Rt()}-01`}const Nt={getParam:(e,t=window.location.href)=>new URL(t).searchParams.get(e),setParam(e,t){const r=new URL(window.location.href);r.searchParams.set(e,t),window.history.replaceState({},"",r.toString())},removeParam(e){const t=new URL(window.location.href);t.searchParams.delete(e),window.history.replaceState({},"",t.toString())},build(e,t){const r=new URL(e,window.location.origin);return Object.entries(t).forEach(([e,t])=>{void 0!==t&&r.searchParams.set(e,String(t))}),r.toString()}};function Dt(e){const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}function xt(e){const t=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",r),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}}function Ot(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Ct(){return/MicroMessenger/i.test(navigator.userAgent)}async function qt(){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 kt(e,t){var r,n,i,s;const{retryCount:a=3,retryDelay:o=1e3,timeout:c=3e4,collectWebVitals:u=!1}=t,d={initTime:0,loadTime:0,renderTime:0,totalTime:0,componentLoadCount:0,componentLoadErrors:0,dataRequestCount:0,dataRequestErrors:0},l=performance.now();let h=0,p=0,m=0;if(!t.pageId)throw new Error("pageId is required");const f=P({container:e,pageId:t.pageId,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: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++)}},userApiAdapter:new ft({baseUrl:t.apiBaseUrl,headers:t.headers,timeout:3e4,...null!=t.authToken&&""!==t.authToken?{auth:{type:"bearer",getToken:()=>Promise.resolve(t.authToken)}}:{}})}),y=async(e,t,r)=>{try{return await e()}catch(n){if(t>0)return await new Promise(e=>setTimeout(e,r)),y(e,t-1,r);throw n}};try{await y(async()=>{var e,r;await(e=(async()=>{var e,r,n,i;h=performance.now(),null==(e=t.onPhaseChange)||e.call(t,"initializing"),await f.init(),d.initTime=performance.now()-h,p=performance.now(),null==(r=t.onPhaseChange)||r.call(t,"loading"),await f.load(),d.loadTime=performance.now()-p,m=performance.now(),null==(n=t.onPhaseChange)||n.call(t,"rendering"),await f.render(),d.renderTime=performance.now()-m,null==(i=t.onPhaseChange)||i.call(t,"ready")})(),r=c,Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(new Error("加载超时")),r))]))},a,o),d.totalTime=performance.now()-l,u&&yt(d),null==(r=t.onLoad)||r.call(t,f.getState()),null==(n=t.onMetric)||n.call(t,d)}catch(g){d.totalTime=performance.now()-l,null==(i=t.onMetric)||i.call(t,d);const e=g instanceof Error?g:new Error(String(g));throw null==(s=t.onError)||s.call(t,e),e}return{runtime:f,metrics:d,destroy:()=>f.destroy(),refresh:async()=>{await f.load(),await f.render()},setVariable:(e,t)=>f.setVariable(e,t),refreshData:e=>f.refreshData(e)}}function Pt(e,t){const r="string"==typeof e?document.querySelector(e):e;if(!r)return{cancel:()=>{},promise:Promise.reject(new Error("Container element not found"))};let n,i,s=!1,a=null;const o=new Promise((e,t)=>{n=e,i=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&&r.appendChild(e)}return a=new IntersectionObserver(async o=>{const c=o[0];if((null==c?void 0:c.isIntersecting)&&!s){null==a||a.disconnect(),a=null,r.innerHTML="";try{const r=await kt(e,t);n(r)}catch(u){i(u)}}},{rootMargin:t.rootMargin||"100px",threshold:t.threshold||0}),a.observe(r),{cancel:()=>{s=!0,null==a||a.disconnect(),i(new Error("Lazy mount cancelled"))},promise:o}}async function _t(e,t){const{concurrency:r=3,continueOnError:n=!0}=t||{},i=performance.now(),s=new Map,a=new Map;for(let o=0;o<e.length;o+=r){const t=e.slice(o,o+r).map(async({id:e,container:t,options:r})=>{try{const n=await kt(t,r);s.set(e,n)}catch(i){if(a.set(e,i),!n)throw i}});await Promise.all(t)}return{results:s,errors:a,totalTime:performance.now()-i}}async function Mt(e){return Et([new URL(e.apiBaseUrl).host,new URL(e.cdnBaseUrl).host]),St(e.cdnBaseUrl,t),{mount:t=>kt(t,e)}}class Lt{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=At(),this.config.enabled&&this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>this.flush(),this.config.flushInterval))}track(e,t,r){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const n={event:e,data:t,timestamp:Date.now(),traceId:this.traceId,...r};this.events.push(n),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},{pageId:e,pageVersionId:t})}trackComponentView(e,t,r){this.track("component_view",{componentType:t},{componentId:e,pageId:r})}trackComponentClick(e,t,r){this.track("component_click",{componentType:t},{componentId:e,pageId:r})}trackAction(e,t,r,n){this.track("action_execute",{actionType:e,success:t,duration:r},{pageId:n})}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 Vt(e){return new Lt(e)}class Ut{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=At(),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 r={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(r)}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 r={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(r)}handleUnhandledRejection(e){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const t=e.reason,r=t instanceof Error?t.message:String(t);if(this.shouldIgnore(r))return;const n={message:r,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(n)}shouldIgnore(e){return this.config.ignorePatterns.some(t=>t.test(e))}truncateStack(e){if(e)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 jt(e){return new Ut(e)}class Bt{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:r,expires:n}=JSON.parse(t);return n&&Date.now()>n?(this.remove(e),null):r}catch{return null}}set(e,t,r){try{const n={value:t,expires:r?Date.now()+r:void 0};this.storage.setItem(this.getKey(e),JSON.stringify(n))}catch{}}remove(e){this.storage.removeItem(this.getKey(e))}clear(){const e=[];for(let t=0;t<this.storage.length;t++){const r=this.storage.key(t);(null==r?void 0:r.startsWith(`${this.namespace}:`))&&e.push(r)}e.forEach(e=>this.storage.removeItem(e))}}function Ft(e,t){return new Bt(e,t)}const Kt={RUNTIME_VERSION:t,mount:kt,lazyMount:Pt,batchMount:_t,warmup:Mt,createTrackingManager:Vt,createErrorReporter:jt,createPerformanceMonitor:vt,getPagePerformance:wt,getResourcePerformance:bt,getRuntimeResourcePerformance:It,createStorageHelper:Ft,preconnect:Et,preloadAssets:St,getDeviceId:Tt,generateTraceId:At,generateSpanId:Rt,generateTraceparent:$t,urlUtils:Nt,onVisibilityChange:Dt,onNetworkChange:xt,isMobile:Ot,isWeChat:Ct,supportsWebP:qt,createRuntime:P};return e.ErrorReporter=Ut,e.OpenApiUserAdapter=ft,e.PerformanceMonitor=gt,e.RUNTIME_VERSION=t,e.StorageHelper=Bt,e.TrackingManager=Lt,e.batchMount=_t,e.collectWebVitalsMetrics=yt,e.createErrorReporter=jt,e.createPerformanceMonitor=vt,e.createRuntime=P,e.createStorageHelper=Ft,e.createTrackingManager=Vt,e.default=Kt,e.generateSpanId=Rt,e.generateTraceId=At,e.generateTraceparent=$t,e.getDeviceId=Tt,e.getPagePerformance=wt,e.getResourcePerformance=bt,e.getRuntimeResourcePerformance=It,e.isMobile=Ot,e.isWeChat=Ct,e.lazyMount=Pt,e.mount=kt,e.onNetworkChange=xt,e.onVisibilityChange=Dt,e.preconnect=Et,e.preloadAssets=St,e.supportsWebP=qt,e.urlUtils=Nt,e.warmup=Mt,Object.defineProperties(e,{t:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});
|