@djvlc/runtime-web 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const RUNTIME_VERSION = "1.1.1";
1
+ const RUNTIME_VERSION = "1.1.2";
2
2
  var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
3
3
  ErrorCode2["SYSTEM_INTERNAL_ERROR"] = "SYSTEM_INTERNAL_ERROR";
4
4
  ErrorCode2["SYSTEM_SERVICE_UNAVAILABLE"] = "SYSTEM_SERVICE_UNAVAILABLE";
@@ -4536,6 +4536,99 @@ function GetSigninCalendar200ResponseFromJSONTyped(json, ignoreDiscriminator) {
4536
4536
  "data": !exists(json, "data") ? void 0 : SigninCalendarFromJSON(json["data"])
4537
4537
  };
4538
4538
  }
4539
+ function TenantConfigBlockedComponentsInnerFromJSON(json) {
4540
+ return TenantConfigBlockedComponentsInnerFromJSONTyped(json);
4541
+ }
4542
+ function TenantConfigBlockedComponentsInnerFromJSONTyped(json, ignoreDiscriminator) {
4543
+ if (json === void 0 || json === null) {
4544
+ return json;
4545
+ }
4546
+ return {
4547
+ "componentType": !exists(json, "componentType") ? void 0 : json["componentType"],
4548
+ "version": !exists(json, "version") ? void 0 : json["version"],
4549
+ "reason": !exists(json, "reason") ? void 0 : json["reason"]
4550
+ };
4551
+ }
4552
+ function TenantConfigKillSwitchFromJSON(json) {
4553
+ return TenantConfigKillSwitchFromJSONTyped(json);
4554
+ }
4555
+ function TenantConfigKillSwitchFromJSONTyped(json, ignoreDiscriminator) {
4556
+ if (json === void 0 || json === null) {
4557
+ return json;
4558
+ }
4559
+ return {
4560
+ "enabled": !exists(json, "enabled") ? void 0 : json["enabled"],
4561
+ "pageIds": !exists(json, "pageIds") ? void 0 : json["pageIds"],
4562
+ "fallbackUrl": !exists(json, "fallbackUrl") ? void 0 : json["fallbackUrl"]
4563
+ };
4564
+ }
4565
+ function TenantConfigFromJSON(json) {
4566
+ return TenantConfigFromJSONTyped(json);
4567
+ }
4568
+ function TenantConfigFromJSONTyped(json, ignoreDiscriminator) {
4569
+ if (json === void 0 || json === null) {
4570
+ return json;
4571
+ }
4572
+ return {
4573
+ "features": !exists(json, "features") ? void 0 : json["features"],
4574
+ "theme": !exists(json, "theme") ? void 0 : json["theme"],
4575
+ "cdnDomain": !exists(json, "cdnDomain") ? void 0 : json["cdnDomain"],
4576
+ "runtimeVersion": !exists(json, "runtimeVersion") ? void 0 : json["runtimeVersion"],
4577
+ "blockedComponents": !exists(json, "blockedComponents") ? void 0 : json["blockedComponents"].map(TenantConfigBlockedComponentsInnerFromJSON),
4578
+ "killSwitch": !exists(json, "killSwitch") ? void 0 : TenantConfigKillSwitchFromJSON(json["killSwitch"])
4579
+ };
4580
+ }
4581
+ function GetTenantConfig200ResponseFromJSON(json) {
4582
+ return GetTenantConfig200ResponseFromJSONTyped(json);
4583
+ }
4584
+ function GetTenantConfig200ResponseFromJSONTyped(json, ignoreDiscriminator) {
4585
+ if (json === void 0 || json === null) {
4586
+ return json;
4587
+ }
4588
+ return {
4589
+ "success": !exists(json, "success") ? void 0 : json["success"],
4590
+ "data": !exists(json, "data") ? void 0 : TenantConfigFromJSON(json["data"])
4591
+ };
4592
+ }
4593
+ function HealthResponseDependenciesValueFromJSON(json) {
4594
+ return HealthResponseDependenciesValueFromJSONTyped(json);
4595
+ }
4596
+ function HealthResponseDependenciesValueFromJSONTyped(json, ignoreDiscriminator) {
4597
+ if (json === void 0 || json === null) {
4598
+ return json;
4599
+ }
4600
+ return {
4601
+ "status": !exists(json, "status") ? void 0 : json["status"],
4602
+ "latency": !exists(json, "latency") ? void 0 : json["latency"],
4603
+ "message": !exists(json, "message") ? void 0 : json["message"]
4604
+ };
4605
+ }
4606
+ function HealthResponseFromJSON(json) {
4607
+ return HealthResponseFromJSONTyped(json);
4608
+ }
4609
+ function HealthResponseFromJSONTyped(json, ignoreDiscriminator) {
4610
+ if (json === void 0 || json === null) {
4611
+ return json;
4612
+ }
4613
+ return {
4614
+ "status": json["status"],
4615
+ "version": json["version"],
4616
+ "uptime": !exists(json, "uptime") ? void 0 : json["uptime"],
4617
+ "timestamp": !exists(json, "timestamp") ? void 0 : new Date(json["timestamp"]),
4618
+ "dependencies": !exists(json, "dependencies") ? void 0 : mapValues(json["dependencies"], HealthResponseDependenciesValueFromJSON)
4619
+ };
4620
+ }
4621
+ function LivenessCheck200ResponseFromJSON(json) {
4622
+ return LivenessCheck200ResponseFromJSONTyped(json);
4623
+ }
4624
+ function LivenessCheck200ResponseFromJSONTyped(json, ignoreDiscriminator) {
4625
+ if (json === void 0 || json === null) {
4626
+ return json;
4627
+ }
4628
+ return {
4629
+ "alive": !exists(json, "alive") ? void 0 : json["alive"]
4630
+ };
4631
+ }
4539
4632
  function OpsConfigBlockedComponentsInnerFromJSON(json) {
4540
4633
  return OpsConfigBlockedComponentsInnerFromJSONTyped(json);
4541
4634
  }
@@ -4640,6 +4733,17 @@ function QueryDefinitionResponseFromJSONTyped(json, ignoreDiscriminator) {
4640
4733
  "data": QueryDefinitionResponseDataFromJSON(json["data"])
4641
4734
  };
4642
4735
  }
4736
+ function ReadinessCheck200ResponseFromJSON(json) {
4737
+ return ReadinessCheck200ResponseFromJSONTyped(json);
4738
+ }
4739
+ function ReadinessCheck200ResponseFromJSONTyped(json, ignoreDiscriminator) {
4740
+ if (json === void 0 || json === null) {
4741
+ return json;
4742
+ }
4743
+ return {
4744
+ "ready": !exists(json, "ready") ? void 0 : json["ready"]
4745
+ };
4746
+ }
4643
4747
  function ResolvePageResponseAllOfDataRolloutMatchFromJSON(json) {
4644
4748
  return ResolvePageResponseAllOfDataRolloutMatchFromJSONTyped(json);
4645
4749
  }
@@ -4832,6 +4936,47 @@ function ResolvePageResponseFromJSONTyped(json, ignoreDiscriminator) {
4832
4936
  "requestId": !exists(json, "requestId") ? void 0 : json["requestId"]
4833
4937
  };
4834
4938
  }
4939
+ function TenantInfoFromJSON(json) {
4940
+ return TenantInfoFromJSONTyped(json);
4941
+ }
4942
+ function TenantInfoFromJSONTyped(json, ignoreDiscriminator) {
4943
+ if (json === void 0 || json === null) {
4944
+ return json;
4945
+ }
4946
+ return {
4947
+ "appId": json["appId"],
4948
+ "appName": json["appName"],
4949
+ "status": json["status"],
4950
+ "workspaceId": !exists(json, "workspaceId") ? void 0 : json["workspaceId"],
4951
+ "cdnDomain": !exists(json, "cdnDomain") ? void 0 : json["cdnDomain"],
4952
+ "apiDomain": !exists(json, "apiDomain") ? void 0 : json["apiDomain"]
4953
+ };
4954
+ }
4955
+ function ResolveTenant200ResponseFromJSON(json) {
4956
+ return ResolveTenant200ResponseFromJSONTyped(json);
4957
+ }
4958
+ function ResolveTenant200ResponseFromJSONTyped(json, ignoreDiscriminator) {
4959
+ if (json === void 0 || json === null) {
4960
+ return json;
4961
+ }
4962
+ return {
4963
+ "success": !exists(json, "success") ? void 0 : json["success"],
4964
+ "data": !exists(json, "data") ? void 0 : TenantInfoFromJSON(json["data"])
4965
+ };
4966
+ }
4967
+ function ResolveTenantRequestToJSON(value) {
4968
+ if (value === void 0) {
4969
+ return void 0;
4970
+ }
4971
+ if (value === null) {
4972
+ return null;
4973
+ }
4974
+ return {
4975
+ "appKey": value.appKey,
4976
+ "host": value.host,
4977
+ "channel": value.channel
4978
+ };
4979
+ }
4835
4980
  function Track202ResponseDataFromJSON(json) {
4836
4981
  return Track202ResponseDataFromJSONTyped(json);
4837
4982
  }
@@ -5274,6 +5419,77 @@ var ActivitiesApi = class extends BaseAPI {
5274
5419
  return await response.value();
5275
5420
  }
5276
5421
  };
5422
+ var HealthApi = class extends BaseAPI {
5423
+ /**
5424
+ * 综合健康检查,包含所有依赖服务状态。 返回: - 服务状态(healthy/degraded/unhealthy) - 版本信息 - 运行时间 - 依赖服务状态
5425
+ * 健康检查
5426
+ */
5427
+ async healthCheckRaw(initOverrides) {
5428
+ const queryParameters = {};
5429
+ const headerParameters = {};
5430
+ const response = await this.request({
5431
+ path: `/health`,
5432
+ method: "GET",
5433
+ headers: headerParameters,
5434
+ query: queryParameters
5435
+ }, initOverrides);
5436
+ return new JSONApiResponse(response, (jsonValue) => HealthResponseFromJSON(jsonValue));
5437
+ }
5438
+ /**
5439
+ * 综合健康检查,包含所有依赖服务状态。 返回: - 服务状态(healthy/degraded/unhealthy) - 版本信息 - 运行时间 - 依赖服务状态
5440
+ * 健康检查
5441
+ */
5442
+ async healthCheck(initOverrides) {
5443
+ const response = await this.healthCheckRaw(initOverrides);
5444
+ return await response.value();
5445
+ }
5446
+ /**
5447
+ * Kubernetes liveness probe。 检查服务是否存活。
5448
+ * 存活检查
5449
+ */
5450
+ async livenessCheckRaw(initOverrides) {
5451
+ const queryParameters = {};
5452
+ const headerParameters = {};
5453
+ const response = await this.request({
5454
+ path: `/health/live`,
5455
+ method: "GET",
5456
+ headers: headerParameters,
5457
+ query: queryParameters
5458
+ }, initOverrides);
5459
+ return new JSONApiResponse(response, (jsonValue) => LivenessCheck200ResponseFromJSON(jsonValue));
5460
+ }
5461
+ /**
5462
+ * Kubernetes liveness probe。 检查服务是否存活。
5463
+ * 存活检查
5464
+ */
5465
+ async livenessCheck(initOverrides) {
5466
+ const response = await this.livenessCheckRaw(initOverrides);
5467
+ return await response.value();
5468
+ }
5469
+ /**
5470
+ * Kubernetes readiness probe。 检查服务是否准备好接收流量。
5471
+ * 就绪检查
5472
+ */
5473
+ async readinessCheckRaw(initOverrides) {
5474
+ const queryParameters = {};
5475
+ const headerParameters = {};
5476
+ const response = await this.request({
5477
+ path: `/health/ready`,
5478
+ method: "GET",
5479
+ headers: headerParameters,
5480
+ query: queryParameters
5481
+ }, initOverrides);
5482
+ return new JSONApiResponse(response, (jsonValue) => ReadinessCheck200ResponseFromJSON(jsonValue));
5483
+ }
5484
+ /**
5485
+ * Kubernetes readiness probe。 检查服务是否准备好接收流量。
5486
+ * 就绪检查
5487
+ */
5488
+ async readinessCheck(initOverrides) {
5489
+ const response = await this.readinessCheckRaw(initOverrides);
5490
+ return await response.value();
5491
+ }
5492
+ };
5277
5493
  var PagesApi = class extends BaseAPI {
5278
5494
  /**
5279
5495
  * Runtime 的核心接口,返回渲染所需的完整数据。 支持两种模式: 1. 稳定入口(推荐):支持灰度/回滚/ops,返回 resolvedVersionId 和 CDN 地址 2. 保底模式:当 includeSnapshot=1 时,返回完整 snapshot(CDN 失败时使用) 响应包含: - resolvedVersionId: 解析后的页面版本 ID(考虑灰度/回滚) - cdnBase: CDN 基础地址 - snapshotUrl: snapshot.json 的完整 URL - manifestUrl: manifest.json 的完整 URL - ops: 运维配置(killSwitch、blockedComponents、flags) - etag: 内容哈希(用于缓存) - cacheTtlSeconds: 缓存 TTL(建议 10~30 秒) - snapshot: 完整快照(仅当 includeSnapshot=1 时返回)
@@ -5447,6 +5663,75 @@ var QueriesApi = class extends BaseAPI {
5447
5663
  return await response.value();
5448
5664
  }
5449
5665
  };
5666
+ var TenantApi = class extends BaseAPI {
5667
+ /**
5668
+ * 获取当前租户的运行时配置。 包括: - 功能开关 - 主题配置 - CDN 域名 - 阻断组件列表 - Kill Switch 状态
5669
+ * 获取租户配置
5670
+ */
5671
+ async getTenantConfigRaw(requestParameters, initOverrides) {
5672
+ if (requestParameters.xAppId === null || requestParameters.xAppId === void 0) {
5673
+ throw new RequiredError("xAppId", "Required parameter requestParameters.xAppId was null or undefined when calling getTenantConfig.");
5674
+ }
5675
+ const queryParameters = {};
5676
+ const headerParameters = {};
5677
+ if (requestParameters.xAppId !== void 0 && requestParameters.xAppId !== null) {
5678
+ headerParameters["X-App-Id"] = String(requestParameters.xAppId);
5679
+ }
5680
+ if (this.configuration && this.configuration.apiKey) {
5681
+ headerParameters["X-API-Key"] = this.configuration.apiKey("X-API-Key");
5682
+ }
5683
+ if (this.configuration && this.configuration.accessToken) {
5684
+ const token = this.configuration.accessToken;
5685
+ const tokenString = await token("BearerAuth", []);
5686
+ if (tokenString) {
5687
+ headerParameters["Authorization"] = `Bearer ${tokenString}`;
5688
+ }
5689
+ }
5690
+ const response = await this.request({
5691
+ path: `/tenant/config`,
5692
+ method: "GET",
5693
+ headers: headerParameters,
5694
+ query: queryParameters
5695
+ }, initOverrides);
5696
+ return new JSONApiResponse(response, (jsonValue) => GetTenantConfig200ResponseFromJSON(jsonValue));
5697
+ }
5698
+ /**
5699
+ * 获取当前租户的运行时配置。 包括: - 功能开关 - 主题配置 - CDN 域名 - 阻断组件列表 - Kill Switch 状态
5700
+ * 获取租户配置
5701
+ */
5702
+ async getTenantConfig(requestParameters, initOverrides) {
5703
+ const response = await this.getTenantConfigRaw(requestParameters, initOverrides);
5704
+ return await response.value();
5705
+ }
5706
+ /**
5707
+ * 根据 appKey 或 host 解析租户/应用信息。 用于: - Runtime 初始化时获取应用配置 - 多租户场景下的应用隔离
5708
+ * 解析租户信息
5709
+ */
5710
+ async resolveTenantRaw(requestParameters, initOverrides) {
5711
+ if (requestParameters.resolveTenantRequest === null || requestParameters.resolveTenantRequest === void 0) {
5712
+ throw new RequiredError("resolveTenantRequest", "Required parameter requestParameters.resolveTenantRequest was null or undefined when calling resolveTenant.");
5713
+ }
5714
+ const queryParameters = {};
5715
+ const headerParameters = {};
5716
+ headerParameters["Content-Type"] = "application/json";
5717
+ const response = await this.request({
5718
+ path: `/tenant/resolve`,
5719
+ method: "POST",
5720
+ headers: headerParameters,
5721
+ query: queryParameters,
5722
+ body: ResolveTenantRequestToJSON(requestParameters.resolveTenantRequest)
5723
+ }, initOverrides);
5724
+ return new JSONApiResponse(response, (jsonValue) => ResolveTenant200ResponseFromJSON(jsonValue));
5725
+ }
5726
+ /**
5727
+ * 根据 appKey 或 host 解析租户/应用信息。 用于: - Runtime 初始化时获取应用配置 - 多租户场景下的应用隔离
5728
+ * 解析租户信息
5729
+ */
5730
+ async resolveTenant(requestParameters, initOverrides) {
5731
+ const response = await this.resolveTenantRaw(requestParameters, initOverrides);
5732
+ return await response.value();
5733
+ }
5734
+ };
5450
5735
  var TrackApi = class extends BaseAPI {
5451
5736
  /**
5452
5737
  * 接收客户端埋点数据,异步写入 Outbox。 特点: - 高性能:不阻塞主链路 - 可靠:通过 Outbox 异步持久化 - 可追溯:自动关联 pageVersionId/componentVersionId/traceId
@@ -5552,6 +5837,8 @@ var UserClient = class {
5552
5837
  this.activities = new ActivitiesApi(this.configuration);
5553
5838
  this.queries = new QueriesApi(this.configuration);
5554
5839
  this.track = new TrackApi(this.configuration);
5840
+ this.tenant = new TenantApi(this.configuration);
5841
+ this.health = new HealthApi(this.configuration);
5555
5842
  }
5556
5843
  };
5557
5844
  function createUserClient(config) {
@@ -1 +1 @@
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}({});
1
+ var e=function(e){"use strict";const t="1.1.2";var n=(e=>(e.SYSTEM_INTERNAL_ERROR="SYSTEM_INTERNAL_ERROR",e.SYSTEM_SERVICE_UNAVAILABLE="SYSTEM_SERVICE_UNAVAILABLE",e.SYSTEM_TIMEOUT="SYSTEM_TIMEOUT",e.SYSTEM_DATABASE_ERROR="SYSTEM_DATABASE_ERROR",e.SYSTEM_REDIS_ERROR="SYSTEM_REDIS_ERROR",e.AUTH_TOKEN_MISSING="AUTH_TOKEN_MISSING",e.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",e.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",e.AUTH_SIGNATURE_INVALID="AUTH_SIGNATURE_INVALID",e.AUTH_SESSION_EXPIRED="AUTH_SESSION_EXPIRED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.PERMISSION_RESOURCE_FORBIDDEN="PERMISSION_RESOURCE_FORBIDDEN",e.PERMISSION_ACTION_FORBIDDEN="PERMISSION_ACTION_FORBIDDEN",e.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",e.RESOURCE_PAGE_NOT_FOUND="RESOURCE_PAGE_NOT_FOUND",e.RESOURCE_COMPONENT_NOT_FOUND="RESOURCE_COMPONENT_NOT_FOUND",e.RESOURCE_ACTION_NOT_FOUND="RESOURCE_ACTION_NOT_FOUND",e.RESOURCE_VERSION_NOT_FOUND="RESOURCE_VERSION_NOT_FOUND",e.VALIDATION_INVALID_PARAMS="VALIDATION_INVALID_PARAMS",e.VALIDATION_SCHEMA_MISMATCH="VALIDATION_SCHEMA_MISMATCH",e.VALIDATION_EXPRESSION_ERROR="VALIDATION_EXPRESSION_ERROR",e.VALIDATION_FIELD_REQUIRED="VALIDATION_FIELD_REQUIRED",e.VALIDATION_FIELD_TYPE_ERROR="VALIDATION_FIELD_TYPE_ERROR",e.BUSINESS_ACTIVITY_NOT_STARTED="BUSINESS_ACTIVITY_NOT_STARTED",e.BUSINESS_ACTIVITY_ENDED="BUSINESS_ACTIVITY_ENDED",e.BUSINESS_ALREADY_CLAIMED="BUSINESS_ALREADY_CLAIMED",e.BUSINESS_ALREADY_SIGNED="BUSINESS_ALREADY_SIGNED",e.BUSINESS_STOCK_EXHAUSTED="BUSINESS_STOCK_EXHAUSTED",e.BUSINESS_QUOTA_EXCEEDED="BUSINESS_QUOTA_EXCEEDED",e.BUSINESS_PREREQUISITE_NOT_MET="BUSINESS_PREREQUISITE_NOT_MET",e.RISK_RATE_LIMITED="RISK_RATE_LIMITED",e.RISK_BLOCKED="RISK_BLOCKED",e.RISK_CAPTCHA_REQUIRED="RISK_CAPTCHA_REQUIRED",e.RISK_DEVICE_ABNORMAL="RISK_DEVICE_ABNORMAL",e.RISK_IDEMPOTENCY_CONFLICT="RISK_IDEMPOTENCY_CONFLICT",e.COMPONENT_LOAD_FAILED="COMPONENT_LOAD_FAILED",e.COMPONENT_INTEGRITY_MISMATCH="COMPONENT_INTEGRITY_MISMATCH",e.COMPONENT_BLOCKED="COMPONENT_BLOCKED",e.COMPONENT_DEPRECATED="COMPONENT_DEPRECATED",e.COMPONENT_INCOMPATIBLE="COMPONENT_INCOMPATIBLE",e.PUBLISH_VERSION_CONFLICT="PUBLISH_VERSION_CONFLICT",e.PUBLISH_VALIDATION_FAILED="PUBLISH_VALIDATION_FAILED",e.PUBLISH_ROLLBACK_FAILED="PUBLISH_ROLLBACK_FAILED",e))(n||{}),r={SYSTEM_INTERNAL_ERROR:"系统内部错误",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,n,i){super(t||r[e]||"Unknown error"),this.name="DjvlcRuntimeError",this.code=e,this.details=n,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,r){super(n.RESOURCE_PAGE_NOT_FOUND,e,t,r),this.name="PageLoadError"}},a=class extends i{constructor(e,t,r,i=n.COMPONENT_LOAD_FAILED,s){super(i,r,{...s,componentName:e,componentVersion:t}),this.name="ComponentLoadError",this.componentName=e,this.componentVersion=t}},o=class extends i{constructor(e,t,r,i){super(n.COMPONENT_INTEGRITY_MISMATCH,`Integrity check failed for ${e}@${t}`,{expectedHash:r,actualHash:i}),this.name="IntegrityError",this.componentName=e,this.componentVersion=t,this.expectedHash=r,this.actualHash=i}},c=class extends i{constructor(e,t,r){super(n.COMPONENT_BLOCKED,`Component ${e}@${t} is blocked`,{componentName:e,componentVersion:t,reason:r}),this.name="ComponentBlockedError",this.componentName=e,this.componentVersion=t,this.reason=r}},u=class extends i{constructor(e,t,r,i){super(n.VALIDATION_EXPRESSION_ERROR,t,{...i,expression:e,position:r}),this.name="ExpressionError",this.expression=e,this.position=r}},d=class extends i{constructor(e,t,r=n.SYSTEM_INTERNAL_ERROR,i,s){super(r,t,{...s,actionType:e,actionId:i}),this.name="ActionError",this.actionType=e,this.actionId=i}},l=class extends i{constructor(e,t,r=n.SYSTEM_INTERNAL_ERROR,i){super(r,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 n,r;const i=this.getCacheKey(e,t);if(null==(n=this.options.cache)?void 0:n.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 n=await this.callResolveViaAdapter(e,t),s=await this.loadFromCdn(n,e);(null==(r=this.options.cache)?void 0:r.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 n=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(n))throw new s("Invalid page resolve response",{pageId:e});return n}async loadFromCdn(e,t){try{const n=await fetch(e.snapshotUrl,{headers:this.buildHeaders()});if(!n.ok)throw new s(`Failed to load snapshot: ${n.status}`,{pageId:t});const r=await n.json();return this.convertSnapshotToResult(r,e,t)}catch(n){if(n instanceof s)throw n;throw new s(`Failed to load from CDN: ${n instanceof Error?n.message:"Unknown error"}`,{pageId:t})}}convertSnapshotToResult(e,t,n){var r,i,s,a;const o=this.convertSnapshotPageToPageSchema(e.page),c=this.convertSnapshotManifestToPageManifest(e.manifest),u=(null==(i=null==(r=e.definitionsDigest)?void 0:r.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},n=Object.keys(e.initialState).length>0?{fields:Object.keys(e.initialState).reduce((t,n)=>{const r=e.initialState[n];let i="string";return"number"==typeof r?i="number":"boolean"==typeof r?i="boolean":Array.isArray(r)?i="array":null!==r&&"object"==typeof r&&(i="object"),t[n]={type:i,initialValue:r},t},{})}:void 0,r={title:e.title};return{schemaVersion:e.schemaVersion,pageId:e.pageId,pageVersion:e.pageVersion,runtime:{name:"djvlc-runtime",version:"1.0.0"},meta:r,config:t,seo:e.seo,state:n,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 n=[e,this.options.env,this.options.channel];return(null==t?void 0:t.uid)&&n.push(t.uid),(null==t?void 0:t.deviceId)&&n.push(t.deviceId),n.filter(Boolean).join(":")}isCacheValid(e){var t;const n=1e3*((null==(t=this.options.cache)?void 0:t.maxAge)??300);return Date.now()-e<n}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 n=this.loadedComponents.get(t);if(n)return n;const r=this.loadingPromises.get(t);if(r)return r;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:n=4}=this.options,r=e.components;for(let i=0;i<r.length;i+=n){const e=r.slice(i,i+n).map(async e=>{const n=this.getComponentKey(e.name,e.version),r=performance.now();try{const i=await this.load(e);t.set(n,{name:e.name,version:e.version,status:"loaded",component:i.Component,loadTime:performance.now()-r})}catch(i){const s=i instanceof c?"blocked":"failed";if(t.set(n,{name:e.name,version:e.version,status:s,error:i instanceof Error?i.message:"Unknown error",loadTime:performance.now()-r}),"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(),n=this.resolveUrl(e.entry);this.log("debug",`Loading component ${e.name}@${e.version}`);try{const r=await this.fetchWithTimeout(n);if(!r.ok)throw new a(e.name,e.version,`Failed to fetch component: ${r.status} ${r.statusText}`);const i=await r.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(r){if(r instanceof a||r instanceof o||r instanceof c)throw r;throw new a(e.name,e.version,`Failed to load component: ${r instanceof Error?r.message:"Unknown error"}`)}}async fetchWithTimeout(e){const t=new AbortController,n=setTimeout(()=>t.abort(),this.options.timeout),r={signal:t.signal,credentials:"omit",headers:this.options.headers?{...this.options.headers}:void 0},i=this.options.fetchComponentScript??fetch;try{return await i(e,r)}finally{clearTimeout(n)}}async validateIntegrity(e,t){if(!e.integrity)return;const[n,r]=e.integrity.split("-");if(!n||!r)throw new o(e.name,e.version,e.integrity,"Invalid format");const i=p[n.toLowerCase()];if(!i)throw new o(e.name,e.version,e.integrity,`Unsupported SRI algorithm: ${n}, 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!==r)throw new o(e.name,e.version,r,c)}async executeScript(e,t){const n=new Blob([e],{type:"application/javascript"}),r=URL.createObjectURL(n);try{const e=await import(r),n=e.default??e[t.name]??e[this.kebabToPascal(t.name)]??e.Component;if(!n)throw new a(t.name,t.version,"Component module does not export a valid component (expected default or Component)");return n}finally{URL.revokeObjectURL(r)}}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 n=document.createElement("link");n.rel="preload",n.setAttribute("as","script"),n.href=e,t&&(n.setAttribute("integrity",t),n.setAttribute("crossorigin","anonymous")),document.head.appendChild(n),this.preloadedAssets.add(e)}preloadStyle(e,t){if(this.preloadedAssets.has(e))return;const n=document.createElement("link");n.rel="preload",n.setAttribute("as","style"),n.href=e,t&&(n.setAttribute("integrity",t),n.setAttribute("crossorigin","anonymous")),document.head.appendChild(n),this.preloadedAssets.add(e)}preloadImage(e){if(this.preloadedAssets.has(e))return;const t=document.createElement("link");t.rel="preload",t.setAttribute("as","image"),t.href=e,document.head.appendChild(t),this.preloadedAssets.add(e)}prefetch(e,t){const n=document.createElement("link");n.rel="prefetch",n.href=e,t&&n.setAttribute("as",t),document.head.appendChild(n)}loadStylesheet(e,t){return new Promise((n,r)=>{const i=document.createElement("link");i.rel="stylesheet",i.href=e,t&&(i.integrity=t,i.crossOrigin="anonymous"),i.onload=()=>n(),i.onerror=()=>r(new Error(`Failed to load stylesheet: ${e}`)),document.head.appendChild(i)})}loadScript(e,t){return new Promise((n,r)=>{const i=document.createElement("script");i.src=e,i.async=!0,t&&(i.integrity=t,i.crossOrigin="anonymous"),i.onload=()=>n(),i.onerror=()=>r(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,n=this.initializePageState(t);e.preloadedData&&Object.assign(n,e.preloadedData),this.setState({page:e,variables:n})}initializePageState(e){const t={};if(e.state&&e.state.fields)for(const[n,r]of Object.entries(e.state.fields))if(r&&"object"==typeof r){const e=r;t[n]=e.initialValue}return t}setError(e){this.setState({phase:"error",error:e})}clearError(){this.state.error&&this.setState({error:null})}getVariable(e){return e.includes(".")?this.getNestedValue(this.state.variables,e):this.state.variables[e]}setVariable(e,t){const n=this.getVariable(e);if(e.includes(".")){const n={...this.state.variables};this.setNestedValue(n,e,t),this.setState({variables:n})}else this.setState({variables:{...this.state.variables,[e]:t}});this.notifyChange({key:e,oldValue:n,newValue:t})}setVariables(e){const t=[];for(const[n,r]of Object.entries(e)){const e=this.getVariable(n);t.push({key:n,oldValue:e,newValue:r})}this.setState({variables:{...this.state.variables,...e}}),t.forEach(e=>this.notifyChange(e))}getQuery(e){return this.state.queries[e]}setQuery(e,t){this.setState({queries:{...this.state.queries,[e]:t}})}clearQuery(e){const{[e]:t,...n}=this.state.queries;this.setState({queries:n})}setComponentStatus(e,t){const n=new Map(this.state.components);n.set(e,t),this.setState({components:n})}getComponentStatus(e){return this.state.components.get(e)}setDestroyed(){this.setState({phase:"destroyed",destroyed:!0})}isDestroyed(){return this.state.destroyed}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}onStateChange(e){return this.changeCallbacks.add(e),()=>{this.changeCallbacks.delete(e)}}reset(){this.state=this.createInitialState(),this.notifyListeners()}getExpressionContext(){var e,t;return{state:this.state.variables,binding:this.state.queries,local:{},context:{pageVersionId:null==(e=this.state.page)?void 0:e.pageVersionId,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(n){}})}getNestedValue(e,t){const n=t.split(".");let r=e;for(const i of n){if(null==r)return;r=r[i]}return r}setNestedValue(e,t,n){const r=t.split(".");let i=e;for(let s=0;s<r.length-1;s++){const e=r[s];void 0!==i[e]&&null!==i[e]||(i[e]={}),i=i[e]}i[r[r.length-1]]=n}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[n,r]of this.bindings)n!==e.id&&(null==(t=r.binding.dependencies)?void 0:t.includes(e.targetState))&&(this.bindingDependencies.has(e.id)||this.bindingDependencies.set(e.id,new Set),this.bindingDependencies.get(e.id).add(n));if(e.dependencies)for(const n of e.dependencies)for(const[t,r]of this.bindings)t!==e.id&&r.binding.targetState===n&&(this.bindingDependencies.has(t)||this.bindingDependencies.set(t,new Set),this.bindingDependencies.get(t).add(e.id))}async initializeBindings(e){var t,n;const r=[];for(const a of this.bindings.values())"eager"===a.binding.loadStrategy&&r.push(a.binding);const i=this.topologicalSort(r),s=this.createLoadBatches(i);for(const a of s){const r=await Promise.allSettled(a.map(t=>this.loadBinding(t.id,e))),i=new Map;r.forEach((e,t)=>{const n=a[t].id;"fulfilled"===e.status?i.set(n,{success:!0,data:e.value}):i.set(n,{success:!1,error:e.reason})}),null==(n=(t=this.options).onBatchComplete)||n.call(t,i)}}topologicalSort(e){const t=new Map(e.map(e=>[e.id,e])),n=new Set,r=[],i=e=>{if(!n.has(e.id)){if(n.add(e.id),e.dependencies)for(const r of e.dependencies)for(const[e,s]of t)s.targetState!==r||n.has(e)||i(s);r.push(e)}};for(const s of e)i(s);return r}createLoadBatches(e){const t=[],n=new Set;for(;n.size<e.length;){const r=[];for(const t of e){if(n.has(t.id))continue;let i=!0;if(t.dependencies)for(const r of t.dependencies){for(const t of e)if(t.targetState===r&&!n.has(t.id)){i=!1;break}if(!i)break}i&&r.push(t)}if(0===r.length)for(const t of e)if(!n.has(t.id)){r.push(t),this.log("warn",`Possible circular dependency detected at binding: ${t.id}`);break}r.forEach(e=>n.add(e.id)),r.length>0&&t.push(r)}return t}async loadBinding(e,t,n=!1){var r,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(!n&&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 n=this.resolveParams(o.params||{},t),c=await this.executeWithRetry(o,n),u=o.transform?this.applyTransform(c,o.transform,t):c;return a.cachedData=u,a.lastLoadTime=Date.now(),(null==(r=o.cache)?void 0:r.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 n=this.dependencyGraph.get(e);if(!n||0===n.size)return;this.log("debug",`State ${e} changed, refreshing dependent bindings`);const r=Array.from(n).map(e=>this.loadBinding(e,t,!0));await Promise.allSettled(r)}async triggerManualLoad(e,t){const n=this.bindings.get(e);if(!n)throw new l(e,`Data binding not found: ${e}`);return"manual"!==n.binding.loadStrategy&&this.log("warn",`Binding ${e} is not manual strategy`),this.loadBinding(e,t,!0)}checkVisibility(e,t,n){const r=this.bindings.get(e);r&&"lazy"===r.binding.loadStrategy&&t&&!r.lastLoadTime&&this.loadBinding(e,n).catch(t=>{this.log("error",`Lazy binding ${e} failed to load`,t)})}destroy(){for(const e of this.bindings.values())e.refreshTimer&&clearInterval(e.refreshTimer);this.bindings.clear(),this.dependencyGraph.clear(),this.log("debug","DataBindingManager destroyed")}async executeWithRetry(e,t){var n,r,i,s,a,o;const c=(null==(r=null==(n=e.onError)?void 0:n.retry)?void 0:r.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 n=await this.options.requester.requestData(e.queryVersionId,t);if(!n.success)throw new l(e.queryVersionId,n.message||"Query failed",void 0,{params:t});return n.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,n){var r,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=(r=this.options).onDataError)||i.call(r,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 n=e.binding.refreshInterval;!n||n<=0||(e.refreshTimer=setInterval(()=>{this.loadBinding(e.binding.id,t,!0).catch(t=>{this.log("error",`Auto refresh for ${e.binding.id} failed:`,t)})},1e3*n))}isCacheValid(e){return!(!e.cachedData||!e.lastLoadTime||e.cacheExpireTime&&Date.now()>e.cacheExpireTime)}resolveParams(e,t){const n={};for(const[r,i]of Object.entries(e))n[r]=this.resolveValue(i,t);return n}resolveValue(e,t){if(null==e)return e;if("object"==typeof e&&!Array.isArray(e)){const n=e;if("expression"===n.type||"binding"===n.type)return this.options.expressionEngine.evaluateWithFallback(n.expression,t,n.fallback);const r={};for(const[e,i]of Object.entries(n))r[e]=this.resolveValue(i,t);return r}return"string"==typeof e&&e.includes("${")?this.options.expressionEngine.evaluateTemplate(e,t):e}evaluateCondition(e,t){const n=void 0===e.fallback||e.fallback,r=this.options.expressionEngine.evaluateWithFallback(e.value,t,n);return Boolean(r)}applyTransform(e,t,n){const r={...n,local:{...n.local||{},$data:e,$response:e}},i=void 0!==t.fallback?t.fallback:e;return this.options.expressionEngine.evaluateWithFallback(t.value,r,i)}delay(e){return new Promise(t=>setTimeout(t,e))}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},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(n){this.log("error",`Error in event handler for ${e.type}:`,n)}})}on(e,t){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.size>=(this.options.maxListeners??100)&&this.log("warn",`Max listeners (${this.options.maxListeners}) reached for event: ${e}`),n.add(t),()=>{null==n||n.delete(t),0===(null==n?void 0:n.size)&&this.handlers.delete(e)}}off(e,t){const n=this.handlers.get(e);n&&(n.delete(t),0===n.size&&this.handlers.delete(e))}once(e,t){const n=this.on(e,e=>{n(),t(e)});return n}clear(e){e?this.handlers.delete(e):this.handlers.clear()}listenerCount(e){var t;return(null==(t=this.handlers.get(e))?void 0:t.size)??0}static createEvent(e,t,n){return{type:e,data:t,timestamp:Date.now(),traceId:n}}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},w=class e{constructor(e){this.debounceTimers=new Map,this.throttleTimers=new Map,this.options=e}async handleEvent(e,t,n){if(e.condition&&!this.evaluateCondition(e.condition,n,t))return void this.log("debug",`Handler ${e.id} skipped by condition`);if(e.throttle&&e.throttle>0&&!this.throttle(e.id,e.throttle))return void this.log("debug",`Handler ${e.id} throttled`);e.debounce&&e.debounce>0&&await this.debounce(e.id,e.debounce);const r={$event:t,$prevResult:void 0,$results:{}};await this.executeActionChain(e.actions,n,r)}async executeActionChain(e,t,n){const r=[];for(let i=0;i<e.length;i++){const s=e[i];if(s.condition){const e=this.buildActionContext(t,n);if(!this.evaluateCondition(s.condition,e,n.$event)){this.log("debug",`Action ${s.id||i} skipped by condition`);continue}}const a=this.executeSingleAction(s,t,n);s.async?r.push(a):await a}r.length>0&&await Promise.allSettled(r)}async executeSingleAction(e,t,n){var r,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,n),c=this.resolveParams(e.params||{},o);null==(i=(r=this.options).onActionStart)||i.call(r,e,c);const d=await this.executeWithRetry(e,c);n.$prevResult=d,e.id&&(n.$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,n)}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,{...n,$prevResult:{error:d.message}})}finally{e.silent||this.options.executor.hideLoading(),e.onFinally&&e.onFinally.length>0&&await this.executeActionChain(e.onFinally,t,n)}}async executeWithRetry(e,t){var n,r,i,s,a;const o=(null==(r=null==(n=e.policy)?void 0:n.retry)?void 0:r.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 n;if(e.builtinAction)n=this.executeBuiltinAction(e.builtinAction,t);else{if(!e.actionDefinitionVersionId)throw new d("unknown","Action must specify builtinAction or actionDefinitionVersionId");n=this.executeCustomAction(e.actionDefinitionVersionId,t)}return u&&(n=this.withTimeout(n,u)),await n}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 n=e.split("@")[0],r=await this.options.executor.executeAction(n,{...t,actionDefinitionVersionId:e});if(!r.success)throw new d(n,r.errorMessage||"Action execution failed",void 0,e,{errorCode:r.errorCode});return r.data}resolveParams(e,t){const n={};for(const[r,i]of Object.entries(e))n[r]=this.resolveValue(i,t);return n}resolveValue(t,n){if(null==t)return t;if("string"==typeof t){if(t.startsWith("${")&&t.endsWith("}")){const e=t.slice(2,-1);return this.options.expressionEngine.evaluateWithFallback(e,n,t)}return t.includes("${")?this.options.expressionEngine.evaluateTemplate(t,n):t}if("number"==typeof t||"boolean"==typeof t)return t;if(Array.isArray(t))return t.map(e=>this.resolveValue(e,n));if("object"==typeof t){const r=t;if("string"==typeof r.type&&e.EXPRESSION_TYPES.includes(r.type)&&"string"==typeof r.value){const e=r;return this.options.expressionEngine.evaluateWithFallback(e.value,n,e.fallback)}const i={};for(const[e,t]of Object.entries(r))i[e]=this.resolveValue(t,n);return i}return t}evaluateCondition(e,t,n){const r={...t,local:{...t.local||{},$event:n}},i=void 0===e.fallback||e.fallback,s=this.options.expressionEngine.evaluateWithFallback(e.value,r,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((n,r)=>{const i=setTimeout(()=>{r(new Error(`Action timed out after ${t}ms`))},t);e.then(e=>{clearTimeout(i),n(e)}).catch(e=>{clearTimeout(i),r(e)})})}debounce(e,t){return new Promise(n=>{const r=this.debounceTimers.get(e);r&&clearTimeout(r);const i=setTimeout(()=>{this.debounceTimers.delete(e),n()},t);this.debounceTimers.set(e,i)})}throttle(e,t){const n=Date.now();return!(n-(this.throttleTimers.get(e)??0)<t||(this.throttleTimers.set(e,n),0))}delay(e){return new Promise(t=>setTimeout(t,e))}destroy(){this.debounceTimers.forEach(e=>clearTimeout(e)),this.debounceTimers.clear(),this.throttleTimers.clear()}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}};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 n=this.readOperator();if(n)return n;switch(e){case".":return this.pos++,{type:"DOT",value:".",start:t,end:this.pos};case"[":return this.pos++,{type:"LBRACKET",value:"[",start:t,end:this.pos};case"]":return this.pos++,{type:"RBRACKET",value:"]",start:t,end:this.pos};case"(":return this.pos++,{type:"LPAREN",value:"(",start:t,end:this.pos};case")":return this.pos++,{type:"RPAREN",value:")",start:t,end:this.pos};case",":return this.pos++,{type:"COMMA",value:",",start:t,end:this.pos};case"?":return this.pos++,{type:"QUESTION",value:"?",start:t,end:this.pos};case":":return this.pos++,{type:"COLON",value:":",start:t,end:this.pos}}throw new Error(`Unexpected character '${e}' at position ${this.pos}`)}readNumber(){const e=this.pos;let t="";for("-"===this.input[this.pos]&&(t+="-",this.pos++);this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;if("."===this.input[this.pos]&&this.isDigit(this.peek(1)))for(t+=".",this.pos++;this.isDigit(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return{type:"NUMBER",value:parseFloat(t),start:e,end:this.pos}}readString(e){const t=this.pos;this.pos++;let n="";for(;this.pos<this.input.length&&this.input[this.pos]!==e;){if("\\"===this.input[this.pos]){this.pos++;const e=this.input[this.pos];switch(e){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case'"':n+='"';break;case"'":n+="'";break;default:n+=e}}else n+=this.input[this.pos];this.pos++}if(this.input[this.pos]!==e)throw new Error(`Unterminated string at position ${t}`);return this.pos++,{type:"STRING",value:n,start:t,end:this.pos}}readIdentifier(){const e=this.pos;let t="";for(;this.pos<this.input.length&&this.isIdentifierChar(this.input[this.pos]);)t+=this.input[this.pos],this.pos++;return"true"===t?{type:"BOOLEAN",value:!0,start:e,end:this.pos}:"false"===t?{type:"BOOLEAN",value:!1,start:e,end:this.pos}:"null"===t?{type:"NULL",value:null,start:e,end:this.pos}:{type:"IDENTIFIER",value:t,start:e,end:this.pos}}readOperator(){const e=this.pos,t=this.input.slice(this.pos,this.pos+2),n=this.input[this.pos];return["==","!=",">=","<=","&&","||","??"].includes(t)?(this.pos+=2,{type:"OPERATOR",value:t,start:e,end:this.pos}):["+","-","*","/","%",">","<","!"].includes(n)?(this.pos++,{type:"OPERATOR",value:n,start:e,end:this.pos}):null}skipWhitespace(){for(;this.pos<this.input.length&&/\s/.test(this.input[this.pos]);)this.pos++}isDigit(e){return/[0-9]/.test(e)}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierChar(e){return/[a-zA-Z0-9_$]/.test(e)}peek(e=1){return this.input[this.pos+e]||""}},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,n)=>{const r=String(e??""),i=Number(t)||0,s=void 0!==n?Number(n):void 0;return r.substring(i,void 0!==s?i+s:void 0)},concat:(...e)=>e.map(e=>String(e??"")).join(""),replace:(e,t,n)=>String(e??"").split(String(t)).join(String(n)),split:(e,t)=>String(e??"").split(String(t)),join:(e,t)=>Array.isArray(e)?e.join(void 0!==t?String(t):","):"",startsWith:(e,t)=>String(e??"").startsWith(String(t)),endsWith:(e,t)=>String(e??"").endsWith(String(t)),contains:(e,t)=>String(e??"").includes(String(t)),toNumber:e=>{const t=Number(e);return isNaN(t)?0:t},toString:e=>String(e??""),toInt:e=>Math.trunc(Number(e)||0),toFloat:e=>parseFloat(String(e))||0,round:(e,t)=>{const n=Number(e)||0,r=Number(t)||0,i=Math.pow(10,r);return Math.round(n*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 n=Math.ceil(Number(e)||0),r=Math.floor(Number(t)||100);return Math.floor(Math.random()*(r-n+1))+n},now:()=>Date.now(),today:()=>(new Date).toISOString().split("T")[0],dateFormat:(e,t)=>{const n=new Date(Number(e)||Date.now()),r=e=>e.toString().padStart(2,"0");return String(t||"YYYY-MM-DD").replace("YYYY",n.getFullYear().toString()).replace("MM",r(n.getMonth()+1)).replace("DD",r(n.getDate())).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},dateParse:e=>new Date(String(e)).getTime(),year:e=>new Date(Number(e)||Date.now()).getFullYear(),month:e=>new Date(Number(e)||Date.now()).getMonth()+1,day:e=>new Date(Number(e)||Date.now()).getDate(),addDays:(e,t)=>{const n=new Date(Number(e)||Date.now());return n.setDate(n.getDate()+(Number(t)||0)),n.getTime()},diffDays:(e,t)=>{const n=new Date(Number(e)||Date.now()),r=new Date(Number(t)||Date.now()),i=Math.abs(r.getTime()-n.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,n)=>e?t:n,first:e=>{if(Array.isArray(e))return e[0]},last:e=>{if(Array.isArray(e))return e[e.length-1]},at:(e,t)=>{if(Array.isArray(e))return e[Number(t)||0]},slice:(e,t,n)=>Array.isArray(e)?e.slice(Number(t)||0,void 0!==n?Number(n):void 0):[],includes:(e,t)=>!!Array.isArray(e)&&e.includes(t),indexOf:(e,t)=>Array.isArray(e)?e.indexOf(t):-1,reverse:e=>Array.isArray(e)?[...e].reverse():[],sort:e=>Array.isArray(e)?[...e].sort():[],unique:e=>Array.isArray(e)?[...new Set(e)]:[],flatten:e=>Array.isArray(e)?e.flat():[],count:e=>Array.isArray(e)?e.length:0,get:(e,t,n)=>{if(null==e)return n;const r=String(t).split(".");let i=e;for(const s of r){if(null==i)return n;i=i[s]}return i??n},keys:e=>"object"!=typeof e||null===e?[]:Object.keys(e),values:e=>"object"!=typeof e||null===e?[]:Object.values(e),entries:e=>"object"!=typeof e||null===e?[]:Object.entries(e),has:(e,t)=>"object"==typeof e&&null!==e&&String(t)in e,merge:(...e)=>{const t={};for(const n of e)"object"==typeof n&&null!==n&&Object.assign(t,n);return t},and:(...e)=>e.every(e=>Boolean(e)),or:(...e)=>e.some(e=>Boolean(e)),not:e=>!e,eq:(e,t)=>e===t,ne:(e,t)=>e!==t,gt:(e,t)=>Number(e)>Number(t),gte:(e,t)=>Number(e)>=Number(t),lt:(e,t)=>Number(e)<Number(t),lte:(e,t)=>Number(e)<=Number(t),between:(e,t,n)=>{const r=Number(e);return r>=Number(t)&&r<=Number(n)},formatNumber:(e,t)=>{const n=Number(e)||0,r=Number(t)??0;return n.toLocaleString(void 0,{minimumFractionDigits:r,maximumFractionDigits:r})},formatCurrency:(e,t)=>{const n=Number(e)||0,r=String(t||"CNY");return n.toLocaleString("zh-CN",{style:"currency",currency:r})},formatPercent:(e,t)=>{const n=Number(e)||0,r=Number(t)??0;return(100*n).toFixed(r)+"%"},currency:(e,t,n)=>{const r=Number(e)||0,i=String(t??"¥"),s=Number(n)??2;return`${i}${r.toLocaleString(void 0,{minimumFractionDigits:s,maximumFractionDigits:s})}`},percent:(e,t)=>{const n=Number(e)||0,r=Number(t)??0;return(100*n).toFixed(r)+"%"},number:(e,t)=>{const n=Number(e)||0,r=Number(t)??0;return n.toLocaleString(void 0,{minimumFractionDigits:r,maximumFractionDigits:r})},pluralize:(e,t,n)=>{const r=Number(e)||0;return`${r} ${String(1===r?t:n)}`},mask:(e,t,n,r)=>{const i=String(e??""),s=Number(t)||3,a=Number(n)||4,o=String(r??"*");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,n)=>{const r=Number(e)||0,i=Number(t)||0,s=Number(n)||100;return Math.min(Math.max(r,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,n)=>{const r=new Date(Number(e)||Date.now()),i=Number(t)||0;switch(String(n??"day").toLowerCase()){case"year":case"years":r.setFullYear(r.getFullYear()+i);break;case"month":case"months":r.setMonth(r.getMonth()+i);break;case"week":case"weeks":r.setDate(r.getDate()+7*i);break;case"day":case"days":default:r.setDate(r.getDate()+i);break;case"hour":case"hours":r.setHours(r.getHours()+i);break;case"minute":case"minutes":r.setMinutes(r.getMinutes()+i)}return r.getTime()},dateDiff:(e,t,n)=>{const r=new Date(Number(e)||Date.now()),i=new Date(Number(t)||Date.now()).getTime()-r.getTime();switch(String(n??"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,n)=>e?t:n,toBoolean:e=>"string"==typeof e?"false"!==e.toLowerCase()&&"0"!==e&&""!==e:Boolean(e),substring:(e,t,n)=>{const r=String(e??""),i=Number(t)||0,s=void 0!==n?Number(n):void 0;return r.substring(i,s)},padStart:(e,t,n)=>{const r=String(e??""),i=Number(t)||0,s=String(n??" ");return r.padStart(i,s)},padEnd:(e,t,n)=>{const r=String(e??""),i=Number(t)||0,s=String(n??" ");return r.padEnd(i,s)},repeat:(e,t)=>{const n=String(e??""),r=Math.max(0,Math.floor(Number(t)||0));return n.repeat(r)}},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 n=this.current();if("OPERATOR"!==n.type)break;const r=S[n.value];if(void 0===r||r<e)break;this.advance();const i=this.parseBinary(r+1);t={type:"binary",operator:n.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 n=e.name;if(!(n in E))throw new Error(`Unknown function '${n}' at position ${t.start}`);this.advance();const r=this.parseArguments();this.expect("RPAREN"),e={type:"call",callee:n,arguments:r,raw:void 0}}}}return e}parsePrimary(){const e=this.current();if("NUMBER"===e.type||"STRING"===e.type||"BOOLEAN"===e.type||"NULL"===e.type)return this.advance(),{type:"literal",value:e.value,start:e.start,end:e.end,raw:void 0};if("IDENTIFIER"===e.type)return this.advance(),{type:"identifier",name:e.value,start:e.start,end:e.end,raw:void 0};if("LBRACKET"===e.type)return this.parseArray();if("LPAREN"===e.type){this.advance();const e=this.parseExpression();return this.expect("RPAREN"),e}throw new Error(`Unexpected token '${e.value}' at position ${e.start}`)}parseArray(){const e=this.current().start;this.advance();const t=[];for(;"RBRACKET"!==this.current().type&&(t.push(this.parseExpression()),"COMMA"===this.current().type);)this.advance();const n=this.current().end;return this.expect("RBRACKET"),{type:"array",elements:t,start:e,end:n,raw:void 0}}parseArguments(){const e=[];if("RPAREN"!==this.current().type)for(e.push(this.parseExpression());"COMMA"===this.current().type;)this.advance(),e.push(this.parseExpression());return e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(e){const t=this.current();if(t.type!==e)throw new Error(`Expected '${e}' but got '${t.type}' at position ${t.start}`);return this.advance()}},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(n){return{value:void 0,error:n instanceof Error?n:new Error(String(n))}}}evaluateNode(e,t){switch(this.checkLimits(),e.type){case"literal":return this.evaluateLiteral(e);case"identifier":return this.evaluateIdentifier(e,t);case"member":return this.evaluateMember(e,t);case"call":return this.evaluateCall(e,t);case"binary":return this.evaluateBinary(e,t);case"unary":return this.evaluateUnary(e,t);case"conditional":return this.evaluateConditional(e,t);case"array":return this.evaluateArray(e,t);default:throw new u("",`Unknown node type: ${e.type}`)}}evaluateLiteral(e){return e.value}evaluateIdentifier(e,t){var n,r;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==(n=t.local)?void 0:n.item;case"index":return null==(r=t.local)?void 0:r.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 n=this.evaluateNode(e.object,t);if(null==n)return;let r;return r=e.computed?this.evaluateNode(e.property,t):e.property,"object"==typeof n&&null!==n?n[r]:void 0}evaluateCall(e,t){const n=E[e.callee];if(!n)throw new u("",`Unknown function '${e.callee}'`);return n(...e.arguments.map(e=>this.evaluateNode(e,t)))}evaluateBinary(e,t){const n=e.operator;if("&&"===n){const n=this.evaluateNode(e.left,t);return n?this.evaluateNode(e.right,t):n}if("||"===n)return this.evaluateNode(e.left,t)||this.evaluateNode(e.right,t);if("??"===n){const n=this.evaluateNode(e.left,t);return null!=n?n:this.evaluateNode(e.right,t)}const r=this.evaluateNode(e.left,t),i=this.evaluateNode(e.right,t);switch(n){case"+":return"string"==typeof r||"string"==typeof i?String(r)+String(i):r+i;case"-":return r-i;case"*":return r*i;case"/":return r/i;case"%":return r%i;case"==":return r===i;case"!=":return r!==i;case"<":return r<i;case">":return r>i;case"<=":return r<=i;case">=":return r>=i;default:throw new u("",`Unknown operator '${n}'`)}}evaluateUnary(e,t){const n=this.evaluateNode(e.argument,t);switch(e.operator){case"!":return!n;case"-":return-n;default:throw new 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 n=this.parse(e);return this.evaluator.evaluate(n,t)}catch(n){return{value:void 0,error:n instanceof Error?n:new Error(String(n))}}}evaluateWithFallback(e,t,n){const r="string"==typeof e?e:e.value,i="object"==typeof e&&void 0!==e.fallback?e.fallback:n,s=this.evaluate(r,t);return s.error?(this.log("warn",`Expression evaluation failed: ${s.error.message}`,r),i):s.value}evaluateTemplate(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,n)=>{const r=this.evaluate(n.trim(),t);return r.error?(this.log("warn",`Template expression failed: ${r.error.message}`,n),""):String(r.value??"")})}parse(e){if(this.options.cacheAST){const t=this.astCache.get(e);if(t)return t}try{const t=new I(e).tokenize(),n=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,n)),n}catch(t){throw new u(e,t instanceof Error?t.message:"Parse error")}}validate(e){const t=[],n=[],r=[],i=[];try{const t=this.parse(e);return this.collectReferences(t,r,i),{valid:!0,errors:[],warnings:n,referencedPaths:r,usedFunctions:i}}catch(s){return t.push({type:"invalid_syntax",message:s instanceof Error?s.message:"Parse error"}),{valid:!1,errors:t,warnings:n,referencedPaths:r,usedFunctions:i}}}clearCache(){this.astCache.clear()}collectReferences(e,t,n){switch(e.type){case"identifier":t.push(e.name);break;case"member":{const n=this.buildMemberPath(e);n&&t.push(n);break}case"call":n.push(e.callee),e.arguments.forEach(e=>this.collectReferences(e,t,n));break;case"binary":this.collectReferences(e.left,t,n),this.collectReferences(e.right,t,n);break;case"unary":this.collectReferences(e.argument,t,n);break;case"conditional":this.collectReferences(e.test,t,n),this.collectReferences(e.consequent,t,n),this.collectReferences(e.alternate,t,n);break;case"array":e.elements.forEach(e=>this.collectReferences(e,t,n))}}buildMemberPath(e){if("identifier"===e.type)return e.name;if("member"===e.type&&!e.computed){const t=this.buildMemberPath(e.object);if(t)return`${t}.${e.property}`}return null}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},$=class{constructor(e){this.loadingCount=0,this.loadingElement=null,this.clipboard={write:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch(t){return this.log("error","Clipboard write failed:",t),this.fallbackCopy(e)}},read:async()=>{try{return await navigator.clipboard.readText()}catch(e){return this.log("error","Clipboard read failed:",e),null}}},this.storage={get:e=>{const t=`${this.storageNamespace}:${e}`,n=localStorage.getItem(t);if(!n)return null;try{const e=JSON.parse(n);return e.expires&&Date.now()>e.expires?(localStorage.removeItem(t),null):e.value}catch{return null}},set:(e,t,n)=>{const r=`${this.storageNamespace}:${e}`,i={value:t,expires:(null==n?void 0:n.ttlSeconds)?Date.now()+1e3*n.ttlSeconds:void 0};("session"===(null==n?void 0:n.level)?sessionStorage:localStorage).setItem(r,JSON.stringify(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 n=localStorage.key(t);(null==n?void 0:n.startsWith(e))&&localStorage.removeItem(n)}for(let t=sessionStorage.length-1;t>=0;t--){const n=sessionStorage.key(t);(null==n?void 0:n.startsWith(e))&&sessionStorage.removeItem(n)}}},this.options=e,this.storageNamespace=`djvlc:${e.context.appId}`}async navigate(e){this.log("debug","Navigate:",e),this.track({eventName:"djvlc_navigate",params:{to:e.to,type:e.type},type:"click"});let t=e.to;if(e.query){const n=new URLSearchParams(e.query);t+=(t.includes("?")?"&":"?")+n.toString()}switch(e.type){case"external":e.newWindow?window.open(t,"_blank","noopener,noreferrer"):window.location.href=t;break;case"replace":window.location.replace(t);break;default:e.newWindow?window.open(t,"_blank"):window.location.href=t}}track(e){this.log("debug","Track event:",e);const t=this.options.context;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 n=performance.now(),r=this.options.context;try{const i=await this.options.userApiAdapter.executeQuery({queryVersionId:e,params:t??{},context:{pageVersionId:r.pageVersionId,uid:r.userId,deviceId:r.deviceId}}),s=performance.now()-n;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()-n;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 n=performance.now(),r=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:r.pageVersionId,uid:r.userId,deviceId:r.deviceId,channel:r.channel,appId:r.appId},idempotencyKey:i}),a=performance.now()-n;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()-n;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 n=new CustomEvent("djvlc:openDialog",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(n),setTimeout(()=>{t({confirmed:!1})},6e4)})}closeDialog(e){this.log("debug","Close dialog:",e);const t=new CustomEvent("djvlc:closeDialog",{detail:{dialogId:e}});document.dispatchEvent(t)}showToast(e){this.log("debug","Show toast:",e);const t=document.createElement("div");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 n=new CustomEvent("djvlc:showActionSheet",{detail:{options:e,resolve:e=>t(e)}});document.dispatchEvent(n),setTimeout(()=>{t({cancelled:!0})},6e4)})}previewImage(e){this.log("debug","Preview image:",e);const t=new CustomEvent("djvlc:previewImage",{detail:e});document.dispatchEvent(t)}async scanCode(){return this.log("debug","Scan code"),new Promise(e=>{const t=new CustomEvent("djvlc:scanCode",{detail:{resolve:t=>e(t)}});document.dispatchEvent(t),setTimeout(()=>{e({success:!1,cancelReason:"Timeout"})},6e4)})}getState(e){return this.options.stateManager.getVariable(e)}setState(e,t){this.options.stateManager.setVariable(e,t)}getContext(){const e=this.options.context;return{pageVersionId:e.pageVersionId,componentVersionId:"",instanceId:"",userId:e.userId,deviceId:e.deviceId,channel:e.channel,appId:e.appId,env:e.env}}generateIdempotencyKey(e,t){const n=Date.now(),r=JSON.stringify(t||{});return`${e}:${n}:${this.simpleHash(r)}`}simpleHash(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t&=t;return Math.abs(t).toString(36)}fallbackCopy(e){const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{return document.execCommand("copy"),!0}catch{return!1}finally{document.body.removeChild(t)}}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},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,n]=e.split("@");t&&n&&this.blockedComponentsMap.set(e,{name:t,version:n,reason:"Blocked by registry"})}),this.blockedActionsSet=new Set(t)}addBlockedComponent(e){const t=`${e.name}@${e.version}`;this.blockedComponentsMap.set(t,e),this.log("warn",`Component blocked: ${t} - ${e.reason}`)}removeBlockedComponent(e,t){const n=`${e}@${t}`;this.blockedComponentsMap.delete(n),this.log("info",`Component unblocked: ${n}`)}isComponentBlocked(e,t){return this.blockedComponentsMap.has(`${e}@${t}`)}getBlockedInfo(e,t){return this.blockedComponentsMap.get(`${e}@${t}`)}getAllBlockedComponents(){return Array.from(this.blockedComponentsMap.values())}isActionBlocked(e){return this.blockedActionsSet.has(e)}isCapabilityAllowed(e){return!this.allowedCapabilitiesSet||this.allowedCapabilitiesSet.has(e)}validateCapabilities(e,t,n){if(!this.allowedCapabilitiesSet)return{valid:!0,disallowed:[]};const r=n.filter(e=>!this.allowedCapabilitiesSet.has(e));return r.length>0&&this.log("warn",`Component ${e}@${t} uses disallowed capabilities: ${r.join(", ")}`),{valid:0===r.length,disallowed:r}}async validateIntegrity(e,t,n,r){if(!this.options.enableSRI)return;const[i,s]=r.split("-");if(!i||!s)throw new o(e,t,r,"Invalid integrity format");const a=await this.computeHash(n,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 n="cdn"===t?this.options.cdnDomains:this.options.apiDomains;if(!n||0===n.length)return!0;try{const t=new URL(e);return n.some(e=>{if(e.startsWith("*.")){const n=e.slice(2);return t.hostname.endsWith(n)||t.hostname===n.slice(1)}return t.hostname===e})}catch{return!1}}validateExternalUrl(e){try{const t=new URL(e);if(!["http:","https:"].includes(t.protocol))return{safe:!1,reason:`Unsafe protocol: ${t.protocol}`};const n=t.hostname;return"localhost"===n||"127.0.0.1"===n||n.startsWith("192.168.")||n.startsWith("10.")||n.startsWith("172.16.")?{safe:!1,reason:"Internal network address not allowed"}:{safe:!0}}catch{return{safe:!1,reason:"Invalid URL format"}}}generateCSPPolicy(){const e=this.options.cdnDomains||[],t=this.options.apiDomains||[],n=["'self'",...e].join(" "),r=["'self'",...t,...e].join(" ");return["default-src 'self'",`script-src ${n}`,`style-src ${["'self'","'unsafe-inline'",...e].join(" ")}`,`img-src ${["'self'","data:","blob:",...e].join(" ")}`,`font-src ${["'self'","data:",...e].join(" ")}`,`connect-src ${r}`,"frame-ancestors 'self'","base-uri 'self'","form-action 'self'","upgrade-insecure-requests"].join("; ")}applyCSP(){if(document.querySelector('meta[http-equiv="Content-Security-Policy"]'))return void this.log("debug","CSP meta tag already exists, skipping");const e=document.createElement("meta");e.httpEquiv="Content-Security-Policy",e.content=this.generateCSPPolicy(),document.head.appendChild(e),this.log("info","CSP policy applied")}assertNotBlocked(e,t){const n=this.getBlockedInfo(e,t);if(n)throw new c(e,t,n.reason)}createSafeEvaluator(){return(e,t)=>{const n=Object.keys(t),r=Object.values(t);return new Function(...n,`"use strict"; return (${e});`)(...r)}}async computeHash(e,t){const n=(new TextEncoder).encode(e),r=await crypto.subtle.digest(t.toUpperCase(),n),i=Array.from(new Uint8Array(r));return btoa(String.fromCharCode(...i))}log(e,t,...n){this.options.logger&&this.options.logger[e](t,...n)}},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(),n=this.shouldSample?"01":"00";return`00-${this.traceId}-${t}-${n}`}parseTraceparent(e){const t=e.split("-");if(4!==t.length)return null;const[,n,r,i]=t;return{traceId:n,parentSpanId:r,sampled:"01"===i}}startSpan(e,t,n){const r={spanId:this.generateSpanId(),traceId:this.traceId,parentSpanId:t,name:e,startTime:performance.now(),attributes:{pageVersionId:this.options.pageVersionId,...n}};return this.spans.set(r.spanId,r),this.log("debug",`Span started: ${e} (${r.spanId})`),r}endSpan(e,t="ok",n){const r=this.spans.get(e);if(r){r.endTime=performance.now(),r.status=t,n&&(r.attributes={...r.attributes,...n});const i=r.endTime-r.startTime;this.log("debug",`Span ended: ${r.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,n,r){this.recordMetricInternal({type:"componentLoadTime",value:n,pageVersionId:this.options.pageVersionId,componentName:e,componentVersion:t,timestamp:Date.now()}),r||this.recordError(new Error(`Component load failed: ${e}@${t}`),{componentVersion:`${e}@${t}`})}recordFirstRender(e){this.recordMetricInternal({type:"firstRenderTime",value:e,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordActionExecute(e,t,n,r){this.recordMetricInternal({type:"actionExecuteTime",value:n,pageVersionId:this.options.pageVersionId,actionType:e,timestamp:Date.now()}),r||this.recordError(new Error(`Action failed: ${e}`),{actionId:t})}recordQueryExecute(e,t,n,r=!1){this.recordMetricInternal({type:"queryFetchTime",value:t,pageVersionId:this.options.pageVersionId,queryId:e,timestamp:Date.now()}),this.log("debug",`Query ${e}: ${t.toFixed(2)}ms, cache: ${r}, success: ${n}`)}recordExpressionEval(e,t,n){t>1&&this.recordMetricInternal({type:"expressionEvalTime",value:t,pageVersionId:this.options.pageVersionId,timestamp:Date.now()})}recordError(e,t){var n,r;const 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==(r=(n=this.options).onError)||r.call(n,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),n=this.metrics.find(e=>"firstRenderTime"===e.type);return{pageLoadTime:null==t?void 0:t.value,firstRenderTime:null==n?void 0:n.value,componentCount:e.length,avgComponentLoadTime:e.length>0?e.reduce((e,t)=>e+t.value,0)/e.length:0,errorCount:this.errors.length}}clear(){this.spans.clear(),this.metrics=[],this.errors=[]}async flush(){if(!this.shouldSample||!this.options.enabled)return;if(0===this.metrics.length&&0===this.errors.length&&0===this.spans.size)return;const e={traceId:this.traceId,pageVersionId:this.options.pageVersionId,appId:this.options.appId,runtimeVersion:this.options.runtimeVersion,spans:this.getSpans(),metrics:this.metrics,errors:this.errors,timestamp:Date.now()};if(this.clear(),this.options.endpoint)try{await fetch(this.options.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}),this.log("debug","Telemetry flushed successfully")}catch(t){this.log("warn","Failed to flush telemetry:",t)}else this.log("debug","No endpoint configured, telemetry data discarded")}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush()}recordMetricInternal(e){var t,n;this.metrics.push(e),null==(n=(t=this.options).onMetric)||n.call(t,e),this.metrics.length>=(this.options.batchSize??50)&&this.flush()}startAutoFlush(){const e=this.options.flushInterval??3e4;this.flushTimer=setInterval(()=>this.flush(),e)}generateTraceId(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}generateSpanId(){const e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},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 n=this.renderNode(e.root);n&&t.appendChild(n),this.log("info",`Page rendered with root component: ${e.root.componentType}`)}updateComponent(e,t){const n=this.renderedElements.get(e);n?this.applyProps(n,t):this.log("warn",`Component not found: ${e}`)}updateContext(e){this.expressionContext={...this.expressionContext,...e}}getContext(){return{...this.expressionContext}}destroy(){this.cleanup(),this.container&&(this.container.innerHTML=""),this.log("debug","Renderer destroyed")}cleanup(){this.componentEventListeners.forEach((e,t)=>{const n=this.renderedElements.get(t);n&&e.forEach(({event:e,handler:t})=>{n.removeEventListener(e,t)})}),this.componentEventListeners.clear(),this.renderedElements.forEach(e=>{e.remove()}),this.renderedElements.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.loopContextStack=[]}renderNode(e){const{id:t,componentType:n,componentVersion:r}=e;try{if(e.condition&&!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",n),r&&i.setAttribute("data-component-version",r);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,n=t.$refs||{};n[e.ref]=i,this.expressionContext={...this.expressionContext,local:{...t,$refs:n}}}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,n,i)}}createElement(e){var t;const{componentType:n}=e,r=this.options.components.get(n);if(r&&customElements.get(n))return document.createElement(n);const i=`${n}-${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-${n}`,r||(this.log("warn",`Component not loaded: ${n}`),s.classList.add("djvlc-component-fallback")),s}renderLoop(e){const{loop:t}=e;if(!t)return null;const n=this.evaluateExpression(t.items);if(!Array.isArray(n))return this.log("warn",`Loop items is not an array for ${e.id}`),null;const r=document.createDocumentFragment();n.forEach((n,i)=>{this.loopContextStack.push({item:n,index:i,loopConfig:t});const s={...this.expressionContext},a={...this.expressionContext.local,[t.itemName]:n,item:n,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)),r.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(r),i}renderChildren(e,t){if(t.slots&&Object.keys(t.slots).length>0)for(const[n,r]of Object.entries(t.slots)){const t=this.createSlotContainer(n);for(const e of r){const n=this.renderNode(e);n&&t.appendChild(n)}e.appendChild(t)}}createSlotContainer(e){const t=document.createElement("div");return t.className=`djvlc-slot djvlc-slot-${e}`,t.setAttribute("data-slot",e),t}bindEventHandlers(e,t,n){const r=[];for(const i of n){const{eventName:n,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 r=e.detail||{};this.options.onComponentEvent&&this.options.onComponentEvent(t,n,[i],r)};o&&o>0&&(d=this.createThrottledHandler(d,o)),c&&c>0&&(d=this.createDebouncedHandler(d,c)),e.addEventListener(n,d),r.push({event:n,handler:d})}this.componentEventListeners.set(t,r)}createThrottledHandler(e,t){let n=0;return r=>{const i=Date.now();i-n>=t&&(n=i,e(r))}}createDebouncedHandler(e,t){let n=null;return r=>{n&&clearTimeout(n),n=setTimeout(()=>{e(r),n=null},t)}}evaluateCondition(e){const t=this.evaluateExpression(e);return Boolean(t)}evaluateExpression(e){if(null==e)return e;if("object"==typeof e&&"type"in e&&"value"in e){const t=e,n=this.buildExpressionContext();return this.options.expressionEngine.evaluateWithFallback(t.value,n,t.fallback)}if("string"==typeof e){const t=this.buildExpressionContext();return this.options.expressionEngine.evaluateWithFallback(e,t,void 0)}return e}buildExpressionContext(){const e={};for(const t of this.loopContextStack)e[t.loopConfig.itemName]=t.item,e.item=t.item,e.index=t.index,t.loopConfig.indexName&&(e[t.loopConfig.indexName]=t.index);return{...this.expressionContext,local:{...this.expressionContext.local,...e}}}resolveProps(e){const t={};for(const[n,r]of Object.entries(e))t[n]=this.resolveValue(r);return t}resolveValue(t){if(null==t)return t;if("string"==typeof t)return t.includes("${")?this.options.expressionEngine.evaluateTemplate(t,this.buildExpressionContext()):t;if("number"==typeof t||"boolean"==typeof t)return t;if(Array.isArray(t))return t.map(e=>this.resolveValue(e));if("object"==typeof t){const n=t;if("string"==typeof n.type&&e.EXPRESSION_TYPES.includes(n.type)&&"string"==typeof n.value){const e=n;return this.options.expressionEngine.evaluateWithFallback(e.value,this.buildExpressionContext(),e.fallback)}const r={};for(const[e,t]of Object.entries(n))r[e]=this.resolveValue(t);return r}return t}applyProps(e,t){for(const[n,r]of Object.entries(t))null!=r&&(e.tagName.includes("-")?e[n]=r:"boolean"==typeof r?r?e.setAttribute(n,""):e.removeAttribute(n):"object"==typeof r?e.setAttribute(n,JSON.stringify(r)):e.setAttribute(n,String(r)))}applyStyles(e,t){if(t.inline)for(const[n,r]of Object.entries(t.inline)){if(null==r)continue;const t=this.resolveValue(r);let i;i="number"==typeof t?["zIndex","opacity","flex","fontWeight","lineHeight"].includes(n)?String(t):`${t}px`:String(t);const s=n.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:n,y:r,width:i,height:s,rotation:a,zIndex:o,responsive:c}=t;e.style.position="absolute",void 0!==n&&(e.style.left=`${n}px`),void 0!==r&&(e.style.top=`${r}px`),void 0!==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 n=e.getAttribute("data-component-id");if(!n)return;let r="";if(t.mobile&&(r+=`\n @media (max-width: 767px) {\n [data-component-id="${n}"] {\n ${this.layoutToCSS(t.mobile)}\n }\n }\n `),t.tablet&&(r+=`\n @media (min-width: 768px) and (max-width: 1023px) {\n [data-component-id="${n}"] {\n ${this.layoutToCSS(t.tablet)}\n }\n }\n `),t.desktop&&(r+=`\n @media (min-width: 1440px) {\n [data-component-id="${n}"] {\n ${this.layoutToCSS(t.desktop)}\n }\n }\n `),r){const e=document.createElement("style");e.setAttribute("data-djvlc-responsive",n),e.textContent=r,document.head.appendChild(e)}}layoutToCSS(e){const t=[];return void 0!==e.x&&t.push(`left: ${e.x}px`),void 0!==e.y&&t.push(`top: ${e.y}px`),void 0!==e.width&&t.push(`width: ${e.width}px`),void 0!==e.height&&t.push(`height: ${e.height}px`),void 0!==e.rotation&&t.push(`transform: rotate(${e.rotation}deg)`),void 0!==e.zIndex&&t.push(`z-index: ${e.zIndex}`),t.join("; ")}applyPageConfig(e,t){t.classList.add("djvlc-page"),t.setAttribute("data-page-id",e.pageId),t.setAttribute("data-page-version",e.pageVersion),t.setAttribute("data-schema-version",e.schemaVersion);const n=e.config;n&&(this.applyLayoutConfig(t,n.layout),n.styles&&this.applyStylesConfig(t,n.styles),n.behavior&&this.applyBehaviorConfig(t,n.behavior))}applyBehaviorConfig(e,t){t.debug&&e.setAttribute("data-debug","true"),t.i18n&&this.applyI18nConfig(e,t.i18n)}applyI18nConfig(e,t){const n=this.detectLocale(t);e.setAttribute("lang",n),e.setAttribute("data-locale",n),e.setAttribute("data-default-locale",t.defaultLocale),e.setAttribute("data-supported-locales",t.supportedLocales.join(",")),t.translationBundleId&&e.setAttribute("data-translation-bundle",t.translationBundleId),e.style.setProperty("--djvlc-locale",n),e.style.setProperty("--djvlc-dir",this.getTextDirection(n)),"rtl"===this.getTextDirection(n)?(e.setAttribute("dir","rtl"),e.classList.add("djvlc-rtl")):e.setAttribute("dir","ltr"),this.expressionContext={...this.expressionContext,local:{...this.expressionContext.local,$locale:n,$defaultLocale:t.defaultLocale,$supportedLocales:t.supportedLocales}},this.log("debug",`I18n configured: locale=${n}, default=${t.defaultLocale}`)}detectLocale(e){const{defaultLocale:t,supportedLocales:n,detection:r="browser"}=e;let i=null;switch(r){case"browser":case"header":i=this.detectBrowserLocale(n);break;case"url":i=this.detectUrlLocale(n);break;case"path":i=this.detectPathLocale(n);break;case"cookie":i=this.detectCookieLocale(n);break;case"manual":i=t;break;default:i=null}return i&&n.includes(i)?i:t}detectBrowserLocale(e){if("undefined"==typeof navigator)return null;const t=navigator.languages||[navigator.language];for(const n of t){if(e.includes(n))return n;const t=n.split("-")[0],r=e.find(e=>e===t||e.startsWith(`${t}-`));if(r)return r}return null}detectUrlLocale(e){if("undefined"==typeof window)return null;const t=new URLSearchParams(window.location.search),n=t.get("lang")||t.get("locale");return n&&e.includes(n)?n:null}detectPathLocale(e){if("undefined"==typeof window)return null;const t=window.location.pathname.split("/").filter(Boolean);if(t.length>0){const n=t[0];if(e.includes(n))return n}return null}detectCookieLocale(e){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(const n of t){const[t,r]=n.trim().split("=");if("lang"===t||"locale"===t||"language"===t){const t=decodeURIComponent(r);if(e.includes(t))return t}}return null}getTextDirection(e){const t=e.split("-")[0];return["ar","ar-SA","ar-EG","ar-AE","he","he-IL","fa","fa-IR","ur","ur-PK","yi","ps","dv"].some(n=>n===e||n===t)?"rtl":"ltr"}applyLayoutConfig(e,t){if(e.setAttribute("data-canvas-type",t.canvasType),t.canvasSize&&"responsive"!==t.canvasType&&(e.style.width=`${t.canvasSize.width}px`,e.style.minHeight=`${t.canvasSize.height}px`),t.maxWidth&&(e.style.maxWidth=`${t.maxWidth}px`,e.style.marginLeft="auto",e.style.marginRight="auto"),t.padding){const{top:n=0,right:r=0,bottom:i=0,left:s=0}=t.padding;e.style.padding=`${n}px ${r}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[n,r]of Object.entries(t.cssVariables)){const t=n.startsWith("--")?n:`--${n}`;e.style.setProperty(t,r)}t.customCSS&&this.injectCustomCSS(t.customCSS)}applyThemeConfig(e,t){if(t.preset&&(e.setAttribute("data-theme",t.preset),"system"===t.preset)){const t=window.matchMedia("(prefers-color-scheme: dark)").matches;e.setAttribute("data-theme-resolved",t?"dark":"light")}if(t.variables)for(const[n,r]of Object.entries(t.variables)){const t=n.startsWith("--")?n:`--theme-${n}`;e.style.setProperty(t,r)}t.transition&&e.style.setProperty("--djvlc-theme-transition","all 0.3s ease")}applyBackgroundConfig(e,t){switch(t.type){case"color":e.style.backgroundColor=t.value;break;case"image":e.style.backgroundImage=`url(${t.value})`,e.style.backgroundSize=t.size||"cover",e.style.backgroundPosition=t.position||"center",e.style.backgroundRepeat=t.repeat||"no-repeat";break;case"gradient":e.style.backgroundImage=t.value}}injectCustomCSS(e){e.trim()&&(this.styleElement=document.createElement("style"),this.styleElement.setAttribute("data-djvlc-custom","true"),this.styleElement.textContent=e,document.head.appendChild(this.styleElement))}initializePageState(e){if(e.state&&e.state.fields){const t={};for(const[n,r]of Object.entries(e.state.fields))r&&"object"==typeof r&&(t[n]=r.initialValue);this.expressionContext={...this.expressionContext,state:t}}}createErrorFallback(e,t,n){const r=document.createElement("div");return r.className="djvlc-error-boundary",r.setAttribute("data-component-id",e),r.setAttribute("data-error","true"),r.innerHTML=`\n <div class="djvlc-error-content">\n <span class="djvlc-error-icon">⚠️</span>\n <span class="djvlc-error-message">组件渲染失败: ${t}</span>\n ${this.options.debug?`<pre class="djvlc-error-detail">${n.message}</pre>`:""}\n </div>\n `,r}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}};x.EXPRESSION_TYPES=["state","binding","local","template","computed"];var C=x,O=class{constructor(e){this.lifecycle=null,this.mounted=!1,this.destroyed=!1,this.cleanupFns=[],this.options=e}register(e){var t,n,r;e?(this.lifecycle=e,this.log("debug","Lifecycle hooks registered",{onMounted:(null==(t=e.onMounted)?void 0:t.length)??0,onBeforeUnmount:(null==(n=e.onBeforeUnmount)?void 0:n.length)??0,onVisibilityChange:(null==(r=e.onVisibilityChange)?void 0:r.length)??0}),e.onVisibilityChange&&e.onVisibilityChange.length>0&&this.setupVisibilityListener()):this.log("debug","No lifecycle hooks defined")}async triggerMounted(){var e,t,n;this.mounted||this.destroyed||(this.mounted=!0,this.log("debug","Triggering onMounted lifecycle"),await this.executeLifecycleActions("mounted",null==(e=this.lifecycle)?void 0:e.onMounted),null==(n=(t=this.options).onLifecycleEvent)||n.call(t,"mounted"))}async triggerBeforeUnmount(){var e,t,n;this.mounted&&!this.destroyed&&(this.log("debug","Triggering onBeforeUnmount lifecycle"),await this.executeLifecycleActions("beforeUnmount",null==(e=this.lifecycle)?void 0:e.onBeforeUnmount),null==(n=(t=this.options).onLifecycleEvent)||n.call(t,"beforeUnmount"))}async triggerVisibilityChange(e){var t,n,r;if(!this.mounted||this.destroyed)return;this.log("debug","Triggering onVisibilityChange lifecycle",{isVisible:e});const 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==(r=(n=this.options).onLifecycleEvent)||r.call(n,"visibilityChange",{isVisible:e})}async destroy(){this.destroyed||(await this.triggerBeforeUnmount(),this.cleanupFns.forEach(e=>e()),this.cleanupFns=[],this.destroyed=!0,this.lifecycle=null,this.log("debug","LifecycleManager destroyed"))}isMounted(){return this.mounted&&!this.destroyed}isDestroyed(){return this.destroyed}setupVisibilityListener(){const e=()=>{const e="visible"===document.visibilityState;this.triggerVisibilityChange(e).catch(e=>{this.log("error","Failed to handle visibility change",e)})};document.addEventListener("visibilitychange",e),this.cleanupFns.push(()=>{document.removeEventListener("visibilitychange",e)}),this.log("debug","Visibility listener registered")}async executeLifecycleActions(e,t){if(!t||0===t.length)return;const n=this.options.getContext();await this.executeLifecycleActionsWithContext(e,t,n)}async executeLifecycleActionsWithContext(e,t,n){if(t&&0!==t.length){this.log("debug",`Executing ${t.length} actions for ${e}`);try{const r={id:`lifecycle_${e}`,eventName:e,actions:t};await this.options.actionBridge.handleEvent(r,{lifecycle:e},n),this.log("debug",`Lifecycle ${e} actions completed`)}catch(r){this.log("error",`Failed to execute lifecycle ${e} actions`,r)}}}log(e,t,...n){this.options.logger?this.options.logger[e](t,...n):this.options.debug}},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,n){if("message"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".message");e&&(e.textContent=n)}if("component-name"===e&&this.shadowRoot){const e=this.shadowRoot.querySelector(".title");e&&(e.textContent=`组件 ${n} 加载失败`)}}}),customElements.get("djvlc-blocked")||customElements.define("djvlc-blocked",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML='\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #fffbe6;\n border: 1px solid #ffe58f;\n border-radius: 4px;\n color: #faad14;\n font-size: 14px;\n }\n .icon {\n margin-right: 8px;\n }\n </style>\n <span class="icon">⚠️</span>\n <span>此组件已被暂停使用</span>\n '}}),customElements.get("djvlc-error-boundary")||customElements.define("djvlc-error-boundary",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).innerHTML="\n <style>\n :host {\n display: block;\n padding: 16px;\n background: #f5f5f5;\n border: 1px dashed #d9d9d9;\n border-radius: 4px;\n color: #999;\n font-size: 14px;\n text-align: center;\n }\n </style>\n <slot>渲染出错</slot>\n "}}),this.stateManager.setPhase("resolving");const t=performance.now()-e;this.log("info",`Runtime initialized in ${t.toFixed(2)}ms`)}catch(t){throw this.handleError(t),t}}async load(){var e,t,n;this.log("info","Loading page:",this.options.pageId);const r=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()-r;return this.telemetryManager.recordPageLoad(s),this.log("info",`Page loaded in ${s.toFixed(2)}ms`),this.emitEvent("page:loaded",{page:i,loadTime:s}),null==(n=(t=this.options).onLoad)||n.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 n=performance.now()-t;this.telemetryManager.recordFirstRender(n),this.log("info",`Page rendered in ${n.toFixed(2)}ms`),await this.lifecycleManager.triggerMounted(),this.emitEvent("page:rendered",{renderTime:n})}catch(n){throw this.stateManager.setPhase("error"),this.handleError(n),n}}getHostApi(){return this.hostApi}getState(){return this.stateManager.getState()}onStateChange(e){return this.stateManager.subscribe(e)}on(e,t){return this.eventBus.on(e,t)}updateComponent(e,t){this.renderer.updateComponent(e,t)}setVariable(e,t){this.stateManager.setVariable(e,t),this.renderer.updateContext(this.stateManager.getExpressionContext()),this.dataBindingManager.onStateChange(e,this.stateManager.getExpressionContext())}getVariable(e){return this.stateManager.getVariable(e)}async refreshData(e){await this.dataBindingManager.refreshBinding(e,this.stateManager.getExpressionContext()),this.renderer.updateContext(this.stateManager.getExpressionContext())}async executeAction(e,t){return this.hostApi.executeAction(e,t)}async destroy(){var e,t,n,r,i;this.log("info","Destroying runtime"),await(null==(e=this.lifecycleManager)?void 0:e.destroy()),null==(t=this.telemetryManager)||t.flush(),null==(n=this.dataBindingManager)||n.destroy(),null==(r=this.actionBridge)||r.destroy(),null==(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 n;t.success?this.emitEvent("action:executed",{action:e,data:t.data}):this.emitEvent("action:error",{action:e,error:null==(n=t.error)?void 0:n.message})}})}initDataBindingManager(e){this.dataBindingManager=new 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 n;this.emitEvent("query:fetched",{bindingId:e,data:t}),null==(n=this.renderer)||n.updateContext(this.stateManager.getExpressionContext())},onDataError:(e,t)=>{this.emitEvent("query:error",{bindingId:e,error:t.message})}}),e.dataBindings&&this.dataBindingManager.registerBindings(e.dataBindings),this.stateManager.onStateChange(({key:e})=>{this.dataBindingManager.onStateChange(e,this.stateManager.getExpressionContext())})}initLifecycleManager(e){this.lifecycleManager=new O({actionBridge:this.actionBridge,getContext:()=>this.stateManager.getExpressionContext(),debug:this.options.debug,logger:this.logger,onLifecycleEvent:(e,t)=>{this.emitEvent(`page:lifecycle:${e}`,t??{})}}),this.lifecycleManager.register(e.lifecycle)}initRenderer(){const e=new Map;this.stateManager.getState().components.forEach((t,n)=>{if("loaded"===t.status&&t.component){const[r,i]=n.split("@");e.set(r,{name:r,version:i,Component:t.component,loadTime:t.loadTime||0})}}),this.renderer=new C({expressionEngine:this.expressionEngine,components:e,injectHostApi:(e,t)=>{e.hostApi=this.hostApi,e.componentId=t},onComponentEvent:(e,t,n,r)=>{this.handleComponentEvent(e,t,n,r)},debug:this.options.debug,logger:this.logger,onRenderError:(e,t)=>(this.log("error",`Render error in ${e}:`,t),this.emitEvent("component:error",{componentId:e,error:t.message}),function(e,t){const n=document.createElement("djvlc-error-boundary");return t&&n.setAttribute("message",t),n}(0,t.message))}),this.renderer.init()}handleComponentEvent(e,t,n,r){this.log("debug",`Component event: ${e}.${t}`,r);for(const i of n)this.actionBridge.handleEvent(i,r,this.stateManager.getExpressionContext())}handleError(e){var t;const n=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(n),null==(t=this.telemetryManager)||t.recordError(e),this.emitEvent("page:error",{error:e.message}),this.options.onError&&this.options.onError(n)}emitEvent(e,t){var n;const r=v.createEvent(e,t,null==(n=this.telemetryManager)?void 0:n.getTraceId());this.eventBus.emit(r),this.options.onEvent&&this.options.onEvent(r)}createLogger(){return{debug:(...e)=>{this.options.debug},info:(...e)=>{},warn:(...e)=>{},error:(...e)=>{}}}log(e,t,...n){this.logger[e](t,...n)}},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 n=t.message.toLowerCase();return n.includes("network")||n.includes("failed to fetch")?new e("Network request failed",t):n.includes("dns")||n.includes("getaddrinfo")?new e("DNS resolution failed",t):n.includes("connection refused")||n.includes("econnrefused")?new e("Connection refused",t):n.includes("connection reset")||n.includes("econnreset")?new e("Connection reset",t):n.includes("ssl")||n.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),n=Array.from(t,e=>String.fromCharCode(e)).join("");return"undefined"!=typeof btoa?btoa(n):(()=>{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 G(e){const t=e.headers;return(null==t?void 0:t[z])??""}function Q(e={}){var t,n,r;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(n){const r=`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:r,traceId:i});const a=n.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"]=r,o["X-Trace-ID"]=i,e.headers&&Object.assign(o,e.headers),await t.authenticate(o),{url:n.url,init:{...n.init,headers:o}}}}}(e)),e.logger&&i.push((s=e.logger,a=e.debug??!1,{async pre(e){var t;if(!a)return;const n=e.init.method??"GET",r=(null==(t=e.init.headers)?void 0:t["X-Request-ID"])??"";s.debug(`[Request] ${n} ${e.url}`,{requestId:r})},async post(e){var t;const n=G(e.init),r=Y.get(n),i=r?Date.now()-r.startTime:0;if(n&&Y.delete(n),!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 n=e.init.method??"GET",r=(null==(t=e.init.headers)?void 0:t["X-Request-ID"])??"",i=G(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] ${n} ${e.url} - ${c} (${o}ms)`,{requestId:r,error:c,duration:o})}})),!1!==e.enableRetry&&e.retry&&i.push(function(e){const t=e.retry,n=t.maxRetries,r=e.logger,i=e.debug??!1;return{async onError(e){const s=G(e.init),a=Y.get(s);if(!a)return;if(!function(e,t,n,r){return!(t>=n)&&(!(e instanceof Error&&"AbortError"===e.name)&&(e instanceof TypeError||e instanceof L?!1!==r.retryOnNetworkError:!(e instanceof V)||!1!==r.retryOnTimeout))}(e.error,a.attempt,n,t))return void Y.delete(s);a.attempt++;const o=J(a.attempt,t);if(t.onRetry){const r=e.init.method??"GET";t.onRetry({attempt:a.attempt,maxRetries:n,delayMs:o,error:e.error instanceof Error?e.error:new Error(String(e.error)),url:e.url,method:r})}if(i&&r){const t=e.init.method??"GET";r.debug(`[Retry] ${t} ${e.url} - attempt ${a.attempt}/${n}, delay ${o}ms`)}await H(o);try{const o=await e.fetch(e.url,e.init);if(!o.ok&&function(e,t,n,r){if(t>=n)return!1;return(r.retryableStatusCodes??[429,500,502,503,504]).includes(e)}(o.status,a.attempt,n,t)){a.attempt++;const s=J(a.attempt,t);if(i&&r){const t=e.init.method??"GET";r.debug(`[Retry] ${t} ${e.url} - status ${o.status}, attempt ${a.attempt}/${n}, delay ${s}ms`)}return await H(s),e.fetch(e.url,e.init)}return Y.delete(s),o}catch(c){if(a.attempt<n)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==(n=e.postMiddlewares)?void 0:n.length)for(const o of e.postMiddlewares)i.push({post:o});if(null==(r=e.errorMiddlewares)?void 0:r.length)for(const o of e.errorMiddlewares)i.push({onError:o});return i}function J(e,t){const{initialDelayMs:n=1e3,maxDelayMs:r=3e4,backoffStrategy:i="exponential",jitterFactor:s=.1}=t;let a;switch(i){case"fixed":a=n;break;case"linear":a=n*e;break;default:a=n*Math.pow(2,e-1)}if(a=Math.min(a,r),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 n,r={url:e,init:t};for(const s of this.middleware)s.pre&&(r=await s.pre({fetch:this.fetchApi,...r})||r);try{n=await(this.configuration.fetchApi||fetch)(r.url,r.init)}catch(i){for(const e of this.middleware)e.onError&&(n=await e.onError({fetch:this.fetchApi,url:r.url,init:r.init,error:i,response:n?n.clone():void 0})||n);if(void 0===n)throw i instanceof Error?new re(i,"The request failed and the interceptors did not return an alternative response"):i}for(const s of this.middleware)s.post&&(n=await s.post({fetch:this.fetchApi,url:r.url,init:r.init,response:n.clone()})||n);return n},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:n,init:r}=await this.createFetchParams(e,t),i=await this.fetchApi(n,r);if(i&&i.status>=200&&i.status<300)return i;throw new ne(i,"Response returned an error code")}async createFetchParams(e,t){let n=this.configuration.basePath+e.path;void 0!==e.query&&0!==Object.keys(e.query).length&&(n+="?"+this.configuration.queryParamsStringify(e.query));const r=Object.assign({},this.configuration.headers,e.headers);Object.keys(r).forEach(e=>void 0===r[e]?delete r[e]:{});const i="function"==typeof t?t:async()=>t,s={method:e.method,headers:r,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(r["Content-Type"])?JSON.stringify(a.body):a.body,{url:n,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,ne=class extends Error{constructor(e,t){super(t),this.response=e,this.name="ResponseError"}},re=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(n=>oe(n,e[n],t)).filter(e=>e.length>0).join("&")}function oe(e,t,n=""){const r=n+(n.length?`[${e}]`:e);if(t instanceof Array){const e=t.map(e=>encodeURIComponent(String(e))).join(`&${encodeURIComponent(r)}=`);return`${encodeURIComponent(r)}=${e}`}return t instanceof Set?oe(e,Array.from(t),n):t instanceof Date?`${encodeURIComponent(r)}=${encodeURIComponent(t.toISOString())}`:t instanceof Object?ae(t,r):`${encodeURIComponent(r)}=${encodeURIComponent(String(t))}`}function ce(e,t){return Object.keys(e).reduce((n,r)=>({...n,[r]:t(e[r])}),{})}var ue=class{constructor(e,t=e=>e){this.raw=e,this.transformer=t}async value(){return this.transformer(await this.raw.json())}};function de(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 le(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 he(e){return function(e){return null==e?e:{type:e.type,payload:se(e,"payload")?e.payload:void 0}}(e)}function pe(e){if(void 0!==e)return null===e?null:{queryVersionId:e.queryVersionId,params:e.params,alias:e.alias}}function me(e){if(void 0!==e)return null===e?null:{pageVersionId:e.pageVersionId,componentVersionId:e.componentVersionId}}function fe(e){if(void 0!==e)return null===e?null:{queries:e.queries.map(pe),context:me(e.context)}}function ye(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 ge(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")?ye(e.error):void 0}}(e)}function ve(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 we(e){if(void 0!==e)return null===e?null:{actionType:e.actionType,actionDefinitionVersionId:e.actionDefinitionVersionId,params:e.params,context:de(e.context),idempotencyKey:e.idempotencyKey}}function be(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(he):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 Ie(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 Ee(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(Ie):void 0}}(e)}function Se(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 Te(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(Se):void 0}}function Ae(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 Re(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 $e(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(Ae),makeupAvailable:e.makeupAvailable,nextReward:se(e,"nextReward")?Re(e.nextReward):void 0}}function Ne(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 De(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 xe(e,t){return null==e?e:{type:e.type,freeDrawsRemaining:e.freeDrawsRemaining,todayDrawCount:e.todayDrawCount,totalDrawCount:e.totalDrawCount,pityProgress:se(e,"pityProgress")?Ne(e.pityProgress):void 0,resources:se(e,"resources")?e.resources.map(De):void 0}}function Ce(e){return function(e){return null==e?e:{...Te(e),...$e(e),...xe(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:Ce(e.typeState)}}(e)}function qe(e){return function(e){return null==e?e:{page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages}}(e)}function ke(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 Pe(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 _e(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")?Pe(e.reward):void 0}}(e)}function Me(e){return function(e){return null==e?e:{year:e.year,month:e.month,records:e.records.map(_e),consecutiveDays:se(e,"consecutiveDays")?e.consecutiveDays:void 0,totalDays:se(e,"totalDays")?e.totalDays:void 0}}(e)}function Le(e){return function(e){return null==e?e:{componentType:se(e,"componentType")?e.componentType:void 0,version:se(e,"version")?e.version:void 0,reason:se(e,"reason")?e.reason:void 0}}(e)}function Ve(e){return function(e){return null==e?e:{enabled:se(e,"enabled")?e.enabled:void 0,pageIds:se(e,"pageIds")?e.pageIds:void 0,fallbackUrl:se(e,"fallbackUrl")?e.fallbackUrl:void 0}}(e)}function Ue(e){return function(e){return null==e?e:{features:se(e,"features")?e.features:void 0,theme:se(e,"theme")?e.theme:void 0,cdnDomain:se(e,"cdnDomain")?e.cdnDomain:void 0,runtimeVersion:se(e,"runtimeVersion")?e.runtimeVersion:void 0,blockedComponents:se(e,"blockedComponents")?e.blockedComponents.map(Le):void 0,killSwitch:se(e,"killSwitch")?Ve(e.killSwitch):void 0}}(e)}function je(e){return function(e){return null==e?e:{status:se(e,"status")?e.status:void 0,latency:se(e,"latency")?e.latency:void 0,message:se(e,"message")?e.message:void 0}}(e)}function Be(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 Fe(e){return function(e){return null==e?e:{killSwitch:e.killSwitch,blockedComponents:e.blockedComponents.map(Be),flags:e.flags}}(e)}function Ke(e){if(void 0!==e)return null===e?null:{noCache:e.noCache,forceRefresh:e.forceRefresh}}function He(e){if(void 0!==e)return null===e?null:{queryVersionId:e.queryVersionId,params:e.params,cacheControl:Ke(e.cacheControl),context:me(e.context)}}function ze(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 Ye(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 Ge(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 Qe(e){return function(e){return null==e?e:{actions:se(e,"actions")?e.actions.map(Ge):void 0,queries:se(e,"queries")?e.queries.map(Ge):void 0}}(e)}function Je(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 Xe(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")?Je(e.entrypoints):void 0}}(e)}function We(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 Ze(e){return function(e){return null==e?e:{components:se(e,"components")?e.components.map(Xe):void 0,runtime:se(e,"runtime")?We(e.runtime):void 0}}(e)}function et(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 tt(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")?et(e.bindings):void 0,runtimeVersion:se(e,"runtimeVersion")?e.runtimeVersion:void 0,env:se(e,"env")?e.env:void 0}}(e)}function nt(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 rt(e){return function(e){return null==e?e:{page:se(e,"page")?nt(e.page):void 0,manifest:se(e,"manifest")?Ze(e.manifest):void 0,definitionsDigest:se(e,"definitionsDigest")?Qe(e.definitionsDigest):void 0,meta:se(e,"meta")?tt(e.meta):void 0}}(e)}function it(e){return function(e){return null==e?e:{pageId:e.pageId,resolvedVersionId:e.resolvedVersionId,cdnBase:e.cdnBase,snapshotUrl:e.snapshotUrl,manifestUrl:e.manifestUrl,ops:Fe(e.ops),etag:e.etag,cacheTtlSeconds:e.cacheTtlSeconds,rolloutMatch:se(e,"rolloutMatch")?Ye(e.rolloutMatch):void 0,snapshot:se(e,"snapshot")?rt(e.snapshot):void 0}}(e)}function st(e){return function(e){return null==e?e:{appId:e.appId,appName:e.appName,status:e.status,workspaceId:se(e,"workspaceId")?e.workspaceId:void 0,cdnDomain:se(e,"cdnDomain")?e.cdnDomain:void 0,apiDomain:se(e,"apiDomain")?e.apiDomain:void 0}}(e)}function at(e){if(void 0!==e)return null===e?null:{appKey:e.appKey,host:e.host,channel:e.channel}}function ot(e){return function(e){return null==e?e:{eventId:se(e,"eventId")?e.eventId:void 0}}(e)}function ct(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 ut(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(ct):void 0}}(e)}function dt(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 lt(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:dt(e.context)}}function ht(e){if(void 0!==e)return null===e?null:{events:e.events.map(lt)}}function pt(e){if(void 0!==e)return null===e?null:{actionType:e.actionType,actionDefinitionVersionId:e.actionDefinitionVersionId,params:e.params}}function mt(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 ft(e){return function(e){return null==e?e:{valid:e.valid,errors:se(e,"errors")?e.errors.map(mt):void 0}}(e)}var yt=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 n={"Content-Type":"application/json"};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 r=await this.request({path:"/actions/execute",method:"POST",headers:n,query:{},body:we(e.executeActionRequest)},t);return new ue(r,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:se(e,"requestId")?e.requestId:void 0}}(e))}async executeAction(e,t){const n=await this.executeActionRaw(e,t);return await n.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 n={};void 0!==e.actionDefinitionVersionId&&(n.actionDefinitionVersionId=e.actionDefinitionVersionId);const r={};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 i=await this.request({path:"/actions/definitions",method:"GET",headers:r,query:n},t);return new ue(i,e=>function(e){return null==e?e:{data:le(e.data)}}(e))}async getActionDefinition(e,t){const n=await this.getActionDefinitionRaw(e,t);return await n.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 n={"Content-Type":"application/json"};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 r=await this.request({path:"/actions/validate",method:"POST",headers:n,query:{},body:pt(e.validateActionRequest)},t);return new ue(r,e=>function(e){return null==e?e:{data:ft(e.data)}}(e))}async validateActionParams(e,t){const n=await this.validateActionParamsRaw(e,t);return await n.value()}},gt=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 n=await this.request({path:"/activities/{activityId}".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:{},query:{}},t);return new ue(n,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?Ee(e.data):void 0}}(e))}async getActivityInfo(e,t){const n=await this.getActivityInfoRaw(e,t);return await n.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 n={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(n.Authorization=`Bearer ${t}`)}const r=await this.request({path:"/activities/{activityId}/state".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:n,query:{}},t);return new ue(r,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 n=await this.getActivityStateRaw(e,t);return await n.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 n={};void 0!==e.pageSize&&(n.pageSize=e.pageSize),void 0!==e.pageToken&&(n.pageToken=e.pageToken);const r={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/activities/{activityId}/claims".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:r,query:n},t);return new ue(i,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?e.data.map(ve):void 0,meta:se(e,"meta")?qe(e.meta):void 0}}(e))}async getClaimRecords(e,t){const n=await this.getClaimRecordsRaw(e,t);return await n.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 n={};void 0!==e.pageSize&&(n.pageSize=e.pageSize),void 0!==e.pageToken&&(n.pageToken=e.pageToken);const r={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/activities/{activityId}/lottery".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:r,query:n},t);return new ue(i,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?e.data.map(ke):void 0,meta:se(e,"meta")?qe(e.meta):void 0}}(e))}async getLotteryRecords(e,t){const n=await this.getLotteryRecordsRaw(e,t);return await n.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 n={};void 0!==e.month&&(n.month=e.month);const r={};if(this.configuration&&this.configuration.accessToken){const e=this.configuration.accessToken,t=await e("BearerAuth",[]);t&&(r.Authorization=`Bearer ${t}`)}const i=await this.request({path:"/activities/{activityId}/signin/calendar".replace("{activityId}",encodeURIComponent(String(e.activityId))),method:"GET",headers:r,query:n},t);return new ue(i,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?Me(e.data):void 0}}(e))}async getSigninCalendar(e,t){const n=await this.getSigninCalendarRaw(e,t);return await n.value()}},vt=class extends te{async healthCheckRaw(e){const t=await this.request({path:"/health",method:"GET",headers:{},query:{}},e);return new ue(t,e=>function(e){return null==e?e:{status:e.status,version:e.version,uptime:se(e,"uptime")?e.uptime:void 0,timestamp:se(e,"timestamp")?new Date(e.timestamp):void 0,dependencies:se(e,"dependencies")?ce(e.dependencies,je):void 0}}(e))}async healthCheck(e){const t=await this.healthCheckRaw(e);return await t.value()}async livenessCheckRaw(e){const t=await this.request({path:"/health/live",method:"GET",headers:{},query:{}},e);return new ue(t,e=>function(e){return null==e?e:{alive:se(e,"alive")?e.alive:void 0}}(e))}async livenessCheck(e){const t=await this.livenessCheckRaw(e);return await t.value()}async readinessCheckRaw(e){const t=await this.request({path:"/health/ready",method:"GET",headers:{},query:{}},e);return new ue(t,e=>function(e){return null==e?e:{ready:se(e,"ready")?e.ready:void 0}}(e))}async readinessCheck(e){const t=await this.readinessCheckRaw(e);return await t.value()}},wt=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 n={};void 0!==e.pageId&&(n.pageId=e.pageId),void 0!==e.env&&(n.env=e.env),void 0!==e.uid&&(n.uid=e.uid),void 0!==e.deviceId&&(n.deviceId=e.deviceId),void 0!==e.channel&&(n.channel=e.channel),void 0!==e.includeSnapshot&&(n.includeSnapshot=e.includeSnapshot);const r={};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 i=await this.request({path:"/page/resolve",method:"GET",headers:r,query:n},t);return new ue(i,e=>function(e){return null==e?e:{success:e.success,code:e.code,message:e.message,data:it(e.data),timestamp:e.timestamp,path:e.path,requestId:se(e,"requestId")?e.requestId:void 0}}(e))}async resolvePage(e,t){const n=await this.resolvePageRaw(e,t);return await n.value()}},bt=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 n={"Content-Type":"application/json"};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 r=await this.request({path:"/data/query/batch",method:"POST",headers:n,query:{},body:fe(e.batchQueryRequest)},t);return new ue(r,e=>function(e){return null==e?e:{success:e.success,data:ce(e.data,ge)}}(e))}async batchQueryData(e,t){const n=await this.batchQueryDataRaw(e,t);return await n.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 n={};void 0!==e.queryVersionId&&(n.queryVersionId=e.queryVersionId);const r={};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 i=await this.request({path:"/data/definitions",method:"GET",headers:r,query:n},t);return new ue(i,e=>function(e){return null==e?e:{data:ze(e.data)}}(e))}async getQueryDefinition(e,t){const n=await this.getQueryDefinitionRaw(e,t);return await n.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 n={"Content-Type":"application/json"};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 r=await this.request({path:"/data/query",method:"POST",headers:n,query:{},body:He(e.queryDataRequest)},t);return new ue(r,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 n=await this.queryDataRaw(e,t);return await n.value()}},It=class extends te{async getTenantConfigRaw(e,t){if(null===e.xAppId||void 0===e.xAppId)throw new ie("xAppId","Required parameter requestParameters.xAppId was null or undefined when calling getTenantConfig.");const n={};if(void 0!==e.xAppId&&null!==e.xAppId&&(n["X-App-Id"]=String(e.xAppId)),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 r=await this.request({path:"/tenant/config",method:"GET",headers:n,query:{}},t);return new ue(r,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?Ue(e.data):void 0}}(e))}async getTenantConfig(e,t){const n=await this.getTenantConfigRaw(e,t);return await n.value()}async resolveTenantRaw(e,t){if(null===e.resolveTenantRequest||void 0===e.resolveTenantRequest)throw new ie("resolveTenantRequest","Required parameter requestParameters.resolveTenantRequest was null or undefined when calling resolveTenant.");const n=await this.request({path:"/tenant/resolve",method:"POST",headers:{"Content-Type":"application/json"},query:{},body:at(e.resolveTenantRequest)},t);return new ue(n,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?st(e.data):void 0}}(e))}async resolveTenant(e,t){const n=await this.resolveTenantRaw(e,t);return await n.value()}},Et=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 n={"Content-Type":"application/json"};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 r=await this.request({path:"/track",method:"POST",headers:n,query:{},body:lt(e.trackRequest)},t);return new ue(r,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?ot(e.data):void 0}}(e))}async track(e,t){const n=await this.trackRaw(e,t);return await n.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 n={"Content-Type":"application/json"};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 r=await this.request({path:"/track/batch",method:"POST",headers:n,query:{},body:ht(e.trackBatchRequest)},t);return new ue(r,e=>function(e){return null==e?e:{success:se(e,"success")?e.success:void 0,data:se(e,"data")?ut(e.data):void 0}}(e))}async trackBatch(e,t){const n=await this.trackBatchRaw(e,t);return await n.value()}},St=class{constructor(e={}){const t=e.baseUrl??"/api",n=[...Q({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:n,headers:e.headers}),this.pages=new wt(this.configuration),this.actions=new yt(this.configuration),this.activities=new gt(this.configuration),this.queries=new bt(this.configuration),this.track=new Et(this.configuration),this.tenant=new It(this.configuration),this.health=new vt(this.configuration)}};class Tt{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 St(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}}),n=t.data;return{success:t.success,data:null==n?void 0:n.result,errorCode:null==n?void 0:n.errorCode,errorMessage:null==n?void 0:n.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 At(e){if("undefined"!=typeof PerformanceObserver)try{const t=performance.getEntriesByType("paint").find(e=>"first-contentful-paint"===e.name);t&&(e.fcp=t.startTime),new PerformanceObserver(t=>{const n=t.getEntries(),r=n[n.length-1];r&&(e.lcp=r.startTime)}).observe({type:"largest-contentful-paint",buffered:!0}),new PerformanceObserver(t=>{const n=t.getEntries();if(n.length>0){const t=n[0];e.fid=t.processingStart-t.startTime}}).observe({type:"first-input",buffered:!0});let n=0;new PerformanceObserver(t=>{for(const r of t.getEntries()){const t=r;!t.hadRecentInput&&t.value&&(n+=t.value,e.cls=n)}}).observe({type:"layout-shift",buffered:!0})}catch{}}class Rt{constructor(e=!0){this.marks=new Map,this.measures=new Map,this.enabled=e}mark(e){this.enabled&&(this.marks.set(e,performance.now()),"function"==typeof performance.mark&&performance.mark(`djvlc:${e}`))}measure(e,t,n){if(!this.enabled)return 0;const r=this.marks.get(t),i=n?this.marks.get(n):performance.now();if(void 0===r)return 0;const s=(i??performance.now())-r;if(this.measures.set(e,s),"function"==typeof performance.measure)try{performance.measure(`djvlc:${e}`,`djvlc:${t}`,n?`djvlc:${n}`:void 0)}catch{}return s}getMeasures(){return Object.fromEntries(this.measures)}clear(){this.marks.clear(),this.measures.clear()}}function $t(e=!0){return new Rt(e)}function Nt(){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 Dt(e){return performance.getEntriesByType("resource").filter(e||(()=>!0)).map(e=>({name:e.name,type:e.initiatorType,duration:e.duration,size:e.transferSize||0}))}function xt(){return Dt(e=>e.name.includes("/components/")||e.name.includes("/runtime/"))}function Ct(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 Ot(e,n=t){[`${e}/runtime/${n}/runtime.esm.js`,`${e}/runtime/${n}/runtime.css`].forEach(e=>{const t=document.createElement("link");t.rel="preload",t.href=e,t.as=e.endsWith(".js")?"script":"style",e.endsWith(".js")&&(t.crossOrigin="anonymous"),document.head.appendChild(t)})}function qt(){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 kt(){return Array.from({length:32},()=>Math.floor(16*Math.random()).toString(16)).join("")}function Pt(){return Array.from({length:16},()=>Math.floor(16*Math.random()).toString(16)).join("")}function _t(){return`00-${kt()}-${Pt()}-01`}const Mt={getParam:(e,t=window.location.href)=>new URL(t).searchParams.get(e),setParam(e,t){const n=new URL(window.location.href);n.searchParams.set(e,t),window.history.replaceState({},"",n.toString())},removeParam(e){const t=new URL(window.location.href);t.searchParams.delete(e),window.history.replaceState({},"",t.toString())},build(e,t){const n=new URL(e,window.location.origin);return Object.entries(t).forEach(([e,t])=>{void 0!==t&&n.searchParams.set(e,String(t))}),n.toString()}};function Lt(e){const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}function Vt(e){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}function Ut(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function jt(){return/MicroMessenger/i.test(navigator.userAgent)}async function Bt(){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 Ft(e,t){var n,r,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 n;return null==(n=t.onError)?void 0:n.call(t,new Error(e.message))}:void 0,onMetric:e=>{if("object"==typeof e&&null!==e){const t=e;"component_load"===t.type&&(d.componentLoadCount++,t.error&&d.componentLoadErrors++),"data_request"===t.type&&(d.dataRequestCount++,t.error&&d.dataRequestErrors++)}},userApiAdapter:new Tt({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,n)=>{try{return await e()}catch(r){if(t>0)return await new Promise(e=>setTimeout(e,n)),y(e,t-1,n);throw r}};try{await y(async()=>{var e,n;await(e=(async()=>{var e,n,r,i;h=performance.now(),null==(e=t.onPhaseChange)||e.call(t,"initializing"),await f.init(),d.initTime=performance.now()-h,p=performance.now(),null==(n=t.onPhaseChange)||n.call(t,"loading"),await f.load(),d.loadTime=performance.now()-p,m=performance.now(),null==(r=t.onPhaseChange)||r.call(t,"rendering"),await f.render(),d.renderTime=performance.now()-m,null==(i=t.onPhaseChange)||i.call(t,"ready")})(),n=c,Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(new Error("加载超时")),n))]))},a,o),d.totalTime=performance.now()-l,u&&At(d),null==(n=t.onLoad)||n.call(t,f.getState()),null==(r=t.onMetric)||r.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 Kt(e,t){const n="string"==typeof e?document.querySelector(e):e;if(!n)return{cancel:()=>{},promise:Promise.reject(new Error("Container element not found"))};let r,i,s=!1,a=null;const o=new Promise((e,t)=>{r=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&&n.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,n.innerHTML="";try{const n=await Ft(e,t);r(n)}catch(u){i(u)}}},{rootMargin:t.rootMargin||"100px",threshold:t.threshold||0}),a.observe(n),{cancel:()=>{s=!0,null==a||a.disconnect(),i(new Error("Lazy mount cancelled"))},promise:o}}async function Ht(e,t){const{concurrency:n=3,continueOnError:r=!0}=t||{},i=performance.now(),s=new Map,a=new Map;for(let o=0;o<e.length;o+=n){const t=e.slice(o,o+n).map(async({id:e,container:t,options:n})=>{try{const r=await Ft(t,n);s.set(e,r)}catch(i){if(a.set(e,i),!r)throw i}});await Promise.all(t)}return{results:s,errors:a,totalTime:performance.now()-i}}async function zt(e){return Ct([new URL(e.apiBaseUrl).host,new URL(e.cdnBaseUrl).host]),Ot(e.cdnBaseUrl,t),{mount:t=>Ft(t,e)}}class Yt{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=kt(),this.config.enabled&&this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>this.flush(),this.config.flushInterval))}track(e,t,n){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const r={event:e,data:t,timestamp:Date.now(),traceId:this.traceId,...n};this.events.push(r),this.events.length>=this.config.batchSize&&this.flush()}trackPageView(e,t){this.track("page_view",{url:window.location.href,referrer:document.referrer,title:document.title},{pageId:e,pageVersionId:t})}trackComponentView(e,t,n){this.track("component_view",{componentType:t},{componentId:e,pageId:n})}trackComponentClick(e,t,n){this.track("component_click",{componentType:t},{componentId:e,pageId:n})}trackAction(e,t,n,r){this.track("action_execute",{actionType:e,success:t,duration:n},{pageId:r})}trackError(e,t){this.track("error",{message:e.message,stack:e.stack,...t})}async flush(){if(0===this.events.length)return;const e=[...this.events];this.events=[];try{await this.config.reporter(e)}catch(t){this.events=[...e,...this.events]}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush()}async defaultReporter(e){this.config.endpoint&&await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:e}),keepalive:!0})}}function Gt(e){return new Yt(e)}class Qt{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=kt(),this.boundHandlers={error:this.handleError.bind(this),unhandledrejection:this.handleUnhandledRejection.bind(this)}}start(){this.config.enabled&&(window.addEventListener("error",this.boundHandlers.error),window.addEventListener("unhandledrejection",this.boundHandlers.unhandledrejection))}stop(){window.removeEventListener("error",this.boundHandlers.error),window.removeEventListener("unhandledrejection",this.boundHandlers.unhandledrejection)}report(e,t){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;if(this.shouldIgnore(e.message))return;const n={message:e.message,stack:this.truncateStack(e.stack),type:"runtime",timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,context:t,traceId:this.traceId};this.config.reporter(n)}setTraceId(e){this.traceId=e}handleError(e){var t;if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;if(this.shouldIgnore(e.message))return;const n={message:e.message,stack:this.truncateStack(null==(t=e.error)?void 0:t.stack),type:"error",timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,context:{filename:e.filename,lineno:e.lineno,colno:e.colno},traceId:this.traceId};this.config.reporter(n)}handleUnhandledRejection(e){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return;const t=e.reason,n=t instanceof Error?t.message:String(t);if(this.shouldIgnore(n))return;const r={message:n,stack:t instanceof Error?this.truncateStack(t.stack):void 0,type:"unhandledrejection",timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,traceId:this.traceId};this.config.reporter(r)}shouldIgnore(e){return this.config.ignorePatterns.some(t=>t.test(e))}truncateStack(e){if(e)return 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 Qt(e)}class Xt{constructor(e="djvlc",t=!1){this.namespace=e,this.storage=t?sessionStorage:localStorage}getKey(e){return`${this.namespace}:${e}`}get(e){try{const t=this.storage.getItem(this.getKey(e));if(!t)return null;const{value:n,expires:r}=JSON.parse(t);return r&&Date.now()>r?(this.remove(e),null):n}catch{return null}}set(e,t,n){try{const r={value:t,expires:n?Date.now()+n:void 0};this.storage.setItem(this.getKey(e),JSON.stringify(r))}catch{}}remove(e){this.storage.removeItem(this.getKey(e))}clear(){const e=[];for(let t=0;t<this.storage.length;t++){const n=this.storage.key(t);(null==n?void 0:n.startsWith(`${this.namespace}:`))&&e.push(n)}e.forEach(e=>this.storage.removeItem(e))}}function Wt(e,t){return new Xt(e,t)}const Zt={RUNTIME_VERSION:t,mount:Ft,lazyMount:Kt,batchMount:Ht,warmup:zt,createTrackingManager:Gt,createErrorReporter:Jt,createPerformanceMonitor:$t,getPagePerformance:Nt,getResourcePerformance:Dt,getRuntimeResourcePerformance:xt,createStorageHelper:Wt,preconnect:Ct,preloadAssets:Ot,getDeviceId:qt,generateTraceId:kt,generateSpanId:Pt,generateTraceparent:_t,urlUtils:Mt,onVisibilityChange:Lt,onNetworkChange:Vt,isMobile:Ut,isWeChat:jt,supportsWebP:Bt,createRuntime:P};return e.ErrorReporter=Qt,e.OpenApiUserAdapter=Tt,e.PerformanceMonitor=Rt,e.RUNTIME_VERSION=t,e.StorageHelper=Xt,e.TrackingManager=Yt,e.batchMount=Ht,e.collectWebVitalsMetrics=At,e.createErrorReporter=Jt,e.createPerformanceMonitor=$t,e.createRuntime=P,e.createStorageHelper=Wt,e.createTrackingManager=Gt,e.default=Zt,e.generateSpanId=Pt,e.generateTraceId=kt,e.generateTraceparent=_t,e.getDeviceId=qt,e.getPagePerformance=Nt,e.getResourcePerformance=Dt,e.getRuntimeResourcePerformance=xt,e.isMobile=Ut,e.isWeChat=jt,e.lazyMount=Kt,e.mount=Ft,e.onNetworkChange=Vt,e.onVisibilityChange=Lt,e.preconnect=Ct,e.preloadAssets=Ot,e.supportsWebP=Bt,e.urlUtils=Mt,e.warmup=zt,Object.defineProperties(e,{t:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djvlc/runtime-web",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "description": "DJV 低代码平台浏览器版运行时(CDN 发布用)",
5
5
  "type": "module",
6
6
  "main": "./dist/runtime.iife.js",
@@ -33,9 +33,7 @@
33
33
  "clean": "rimraf dist"
34
34
  },
35
35
  "dependencies": {
36
- "@djvlc/contracts-types": "^1.8.0",
37
- "@djvlc/openapi-user-client": "^1.7.0",
38
- "@djvlc/runtime-core": "1.1.1"
36
+ "@djvlc/runtime-core": "1.1.2"
39
37
  },
40
38
  "devDependencies": {
41
39
  "@types/node": "^20.10.0",