@djvlc/runtime-core 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as _djvlc_contracts_types from '@djvlc/contracts-types';
2
- import { ExpressionContext, Expression, ExpressionValidationResult, ActionRef, EventHandler, HostApi, NavigateOptions, TrackEvent, ActionResult, DialogOptions, DialogResult, ToastOptions, ClipboardApi, StorageApi, ShareOptions, ShareResult, ConfirmOptions, ActionSheetOptions, ActionSheetResult, PreviewImageOptions, ScanCodeResult, ComponentContext, ErrorCode, ManifestItem, PageManifest, CapabilityName, PageSchema, PageLifecycle } from '@djvlc/contracts-types';
2
+ import { ExpressionContext, Expression, ExpressionValidationResult, ActionRef, EventHandler, PageResolveResponse, ActionResult, HostApi, NavigateOptions, TrackEvent, DialogOptions, DialogResult, ToastOptions, ClipboardApi, StorageApi, ShareOptions, ShareResult, ConfirmOptions, ActionSheetOptions, ActionSheetResult, PreviewImageOptions, ScanCodeResult, ComponentContext, ErrorCode, ManifestItem, PageManifest, CapabilityName, PageSchema, PageLifecycle } from '@djvlc/contracts-types';
3
3
  export { ActionExecuteRequest, ActionExecuteResponse, ActionPolicy, ActionRef, ActionResult, AnyValueOrExpression, BlockedComponentInfo, BuiltinActionType, CapabilityDeclaration, CompatInfo, ComponentContext, ComponentMeta, ComponentNode, DataBinding, DataLoadStrategy, DataQueryRequest, DataQueryResponse, DialogOptions, DialogResult, ErrorCode, ErrorMessages, EventDeclaration, EventHandler, Expression, ExpressionContext, ExpressionLocal, ExpressionMeta, ExpressionType, ExpressionValidationResult, HostApi as HostAPI, HostApi, JsonValue, LayoutConfig, LayoutValues, LoopConfig, ManifestItem, NavigateOptions, NodeStyleConfig, PageConfig, PageLifecycle, PageManifest, PageMeta, PageSEO, PageSchema, PageState, PropDefinition, PropsSchema, RuntimeSpec, SchemaVersion, SemVer, StateFieldDefinition, ToastOptions, TrackEvent, UniqueId } from '@djvlc/contracts-types';
4
+ import { UserClientConfig } from '@djvlc/openapi-user-client';
4
5
 
5
6
  /**
6
7
  * 运行时初始化选项
@@ -8,8 +9,8 @@ export { ActionExecuteRequest, ActionExecuteResponse, ActionPolicy, ActionRef, A
8
9
  interface RuntimeOptions {
9
10
  /** 容器元素或选择器 */
10
11
  container: string | HTMLElement;
11
- /** 页面 UID(pageId) */
12
- pageUid: string;
12
+ /** 页面 ID(对应 contracts 中的 pageId) */
13
+ pageId: string;
13
14
  /** API 基础 URL */
14
15
  apiBaseUrl: string;
15
16
  /** CDN 基础 URL */
@@ -68,17 +69,21 @@ interface RuntimeState {
68
69
  }
69
70
  /**
70
71
  * 页面解析结果(Runtime 使用)
72
+ *
73
+ * @description
74
+ * 这是 Runtime 内部使用的类型,从 PageResolveResponse 和 PageSnapshotJson 转换而来。
75
+ * 使用 pageId 符合 contracts 定义。
71
76
  */
72
77
  interface PageResolveResult {
73
- /** 页面 UID */
74
- pageUid: string;
78
+ /** 页面 ID(对应 contracts 中的 pageId) */
79
+ pageId: string;
75
80
  /** 页面版本 ID */
76
81
  pageVersionId: string;
77
82
  /** 页面 JSON(PageSchema) */
78
83
  pageJson: _djvlc_contracts_types.PageSchema;
79
84
  /** 组件清单 */
80
85
  manifest: _djvlc_contracts_types.PageManifest;
81
- /** 运行时配置 */
86
+ /** 运行时配置(从 OpsConfig 转换而来) */
82
87
  runtimeConfig?: {
83
88
  /** 被阻断的组件列表 */
84
89
  blockedComponents?: Array<{
@@ -837,6 +842,139 @@ declare class ActionBridge {
837
842
  private log;
838
843
  }
839
844
 
845
+ /**
846
+ * User API 适配器接口
847
+ * 统一 Runtime 与 User API 的交互:页面解析、动作执行、数据查询、埋点
848
+ * 认证、请求头、重试等逻辑由实现类统一处理,便于测试与切换实现(如 openapi-user-client)
849
+ */
850
+
851
+ /** 页面解析入参 */
852
+ interface ResolvePageParams {
853
+ pageId: string;
854
+ uid?: string;
855
+ deviceId?: string;
856
+ env?: 'preview' | 'staging' | 'prod';
857
+ channel?: string;
858
+ previewToken?: string;
859
+ }
860
+ /** 动作执行入参 */
861
+ interface ExecuteActionParams {
862
+ actionType: string;
863
+ params: Record<string, unknown>;
864
+ context: {
865
+ pageVersionId: string;
866
+ uid?: string;
867
+ deviceId?: string;
868
+ channel?: string;
869
+ appId: string;
870
+ };
871
+ idempotencyKey: string;
872
+ }
873
+ /** 数据查询入参 */
874
+ interface ExecuteQueryParams {
875
+ queryVersionId: string;
876
+ params?: Record<string, unknown>;
877
+ context: {
878
+ pageVersionId: string;
879
+ uid?: string;
880
+ deviceId?: string;
881
+ };
882
+ }
883
+ /** 数据查询出参(与 User API /data/query 一致) */
884
+ interface ExecuteQueryResult {
885
+ success: boolean;
886
+ data?: unknown;
887
+ message?: string;
888
+ errorMessage?: string;
889
+ }
890
+ /** 埋点 payload(与 User API /track 一致) */
891
+ interface TrackPayload {
892
+ eventName: string;
893
+ params?: Record<string, unknown>;
894
+ type?: string;
895
+ timestamp?: number;
896
+ context: {
897
+ pageVersionId: string;
898
+ runtimeVersion: string;
899
+ userId?: string;
900
+ deviceId?: string;
901
+ channel?: string;
902
+ appId: string;
903
+ env: string;
904
+ };
905
+ }
906
+ /**
907
+ * User API 适配器
908
+ * 只约定入参/出参,不绑定具体 HTTP 库;由 Runtime 注入实现,单测可注入 Mock
909
+ */
910
+ interface UserApiAdapter {
911
+ /** 页面解析 GET /page/resolve */
912
+ resolvePage(params: ResolvePageParams): Promise<PageResolveResponse>;
913
+ /** 动作执行 POST /actions/execute */
914
+ executeAction<T = unknown>(params: ExecuteActionParams): Promise<ActionResult<T>>;
915
+ /** 数据查询 POST /data/query */
916
+ executeQuery(params: ExecuteQueryParams): Promise<ExecuteQueryResult>;
917
+ /** 埋点 POST /track(可异步、不阻塞) */
918
+ track(payload: TrackPayload): void;
919
+ }
920
+
921
+ /**
922
+ * 基于 @djvlc/openapi-user-client 的 User API 适配器
923
+ * 统一认证、请求头、重试等逻辑,不直接使用 fetch
924
+ */
925
+
926
+ type OpenApiUserAdapterOptions = UserClientConfig;
927
+ /**
928
+ * 基于 openapi-user-client 的 User API 适配器实现
929
+ * Runtime 与 User API 的交互仅通过此适配器
930
+ */
931
+ declare class OpenApiUserAdapter implements UserApiAdapter {
932
+ private readonly client;
933
+ constructor(options?: OpenApiUserAdapterOptions);
934
+ resolvePage(params: ResolvePageParams): Promise<PageResolveResponse>;
935
+ executeAction<T = unknown>(params: ExecuteActionParams): Promise<ActionResult<T>>;
936
+ executeQuery(params: ExecuteQueryParams): Promise<ExecuteQueryResult>;
937
+ track(payload: TrackPayload): void;
938
+ }
939
+
940
+ /**
941
+ * 测试用 User API 适配器 Mock
942
+ * 单测中注入,不再 mock global.fetch
943
+ */
944
+
945
+ interface MockUserApiAdapterOptions {
946
+ /** resolvePage 返回值(可覆盖) */
947
+ resolvePageResponse?: PageResolveResponse;
948
+ /** executeAction 返回值(可覆盖) */
949
+ executeActionResponse?: ActionResult<unknown>;
950
+ /** executeQuery 返回值(可覆盖) */
951
+ executeQueryResponse?: ExecuteQueryResult;
952
+ /** 是否在 resolve 时抛错 */
953
+ resolvePageThrow?: Error;
954
+ /** 是否在 executeAction 时抛错 */
955
+ executeActionThrow?: Error;
956
+ /** 是否在 executeQuery 时抛错 */
957
+ executeQueryThrow?: Error;
958
+ }
959
+ /**
960
+ * 测试用 Mock 实现
961
+ * 记录调用次数与参数,返回可配置的默认值或自定义值
962
+ */
963
+ declare class MockUserApiAdapter implements UserApiAdapter {
964
+ private readonly options;
965
+ readonly calls: {
966
+ resolvePage: ResolvePageParams[];
967
+ executeAction: ExecuteActionParams[];
968
+ executeQuery: ExecuteQueryParams[];
969
+ track: TrackPayload[];
970
+ };
971
+ constructor(options?: MockUserApiAdapterOptions);
972
+ resolvePage(params: ResolvePageParams): Promise<PageResolveResponse>;
973
+ executeAction<T = unknown>(params: ExecuteActionParams): Promise<ActionResult<T>>;
974
+ executeQuery(params: ExecuteQueryParams): Promise<ExecuteQueryResult>;
975
+ track(payload: TrackPayload): void;
976
+ }
977
+
840
978
  /**
841
979
  * Host API 实现
842
980
  * 提供给组件的安全 API,完全对齐 @djvlc/contracts-types 中的 HostApi 定义
@@ -852,7 +990,7 @@ declare class ActionBridge {
852
990
  * 运行时上下文
853
991
  */
854
992
  interface RuntimeContext {
855
- pageUid: string;
993
+ pageId: string;
856
994
  pageVersionId: string;
857
995
  runtimeVersion: string;
858
996
  userId?: string;
@@ -867,12 +1005,8 @@ interface RuntimeContext {
867
1005
  * Host API 配置
868
1006
  */
869
1007
  interface HostAPIOptions {
870
- /** API 基础 URL */
871
- apiBaseUrl: string;
872
- /** 认证 Token */
873
- authToken?: string;
874
- /** 请求头 */
875
- headers?: Record<string, string>;
1008
+ /** User API 适配器(必填,仅通过适配器调用 User API) */
1009
+ userApiAdapter: UserApiAdapter;
876
1010
  /** 状态管理器 */
877
1011
  stateManager: StateManager;
878
1012
  /** 事件总线 */
@@ -915,7 +1049,6 @@ declare class HostAPIImpl implements HostApi {
915
1049
  getState<T = unknown>(path: string): T | undefined;
916
1050
  setState(path: string, value: unknown): void;
917
1051
  getContext(): ComponentContext;
918
- private buildHeaders;
919
1052
  private generateIdempotencyKey;
920
1053
  private simpleHash;
921
1054
  private fallbackCopy;
@@ -961,6 +1094,8 @@ declare class DjvlcRuntime {
961
1094
  private renderer;
962
1095
  private hostApi;
963
1096
  private lifecycleManager;
1097
+ /** User API 适配器,统一认证/请求头,供 PageLoader 与 HostAPIImpl 使用 */
1098
+ private userApiAdapter;
964
1099
  private logger;
965
1100
  constructor(options: RuntimeOptions);
966
1101
  /**
@@ -1130,22 +1265,24 @@ declare class RenderError extends DjvlcRuntimeError {
1130
1265
 
1131
1266
  /**
1132
1267
  * 页面加载器
1133
- * 负责从 API 解析页面配置
1268
+ * 负责从 API 解析页面配置,严格按照 @djvlc/contracts-types 定义
1134
1269
  */
1135
1270
 
1136
1271
  /**
1137
1272
  * 页面加载器配置
1138
1273
  */
1139
1274
  interface PageLoaderOptions {
1140
- /** API 基础 URL */
1275
+ /** API 基础 URL(用于 preconnect、CDN 请求头) */
1141
1276
  apiBaseUrl: string;
1277
+ /** User API 适配器(必填,仅通过适配器调用 User API) */
1278
+ userApiAdapter: UserApiAdapter;
1279
+ /** 环境 */
1280
+ env?: 'preview' | 'staging' | 'prod';
1142
1281
  /** 渠道 */
1143
- channel?: 'preview' | 'prod' | 'gray';
1144
- /** 认证 Token */
1145
- authToken?: string;
1282
+ channel?: string;
1146
1283
  /** 预览 Token */
1147
1284
  previewToken?: string;
1148
- /** 请求头 */
1285
+ /** 请求头(CDN 请求用) */
1149
1286
  headers?: Record<string, string>;
1150
1287
  /** 缓存配置 */
1151
1288
  cache?: {
@@ -1158,6 +1295,7 @@ interface PageLoaderOptions {
1158
1295
  /**
1159
1296
  * 页面加载器
1160
1297
  * 负责调用 /page/resolve 接口获取页面数据
1298
+ * 严格按照 contracts 中的 PageResolveResponse 定义
1161
1299
  */
1162
1300
  declare class PageLoader {
1163
1301
  private options;
@@ -1165,13 +1303,39 @@ declare class PageLoader {
1165
1303
  constructor(options: PageLoaderOptions);
1166
1304
  /**
1167
1305
  * 解析页面
1168
- * @param pageUid 页面 UID
1306
+ * @param pageId 页面 ID(对应 contracts 中的 pageId)
1169
1307
  * @param params 额外参数
1170
1308
  */
1171
- resolve(pageUid: string, params?: {
1309
+ resolve(pageId: string, params?: {
1172
1310
  uid?: string;
1173
1311
  deviceId?: string;
1174
1312
  }): Promise<PageResolveResult>;
1313
+ /**
1314
+ * 通过 User API 适配器调用 resolve
1315
+ */
1316
+ private callResolveViaAdapter;
1317
+ /**
1318
+ * 从 CDN 加载 snapshot 和 manifest
1319
+ */
1320
+ private loadFromCdn;
1321
+ /**
1322
+ * 转换 PageSnapshotJson 为 PageResolveResult
1323
+ */
1324
+ private convertSnapshotToResult;
1325
+ /**
1326
+ * 转换 PageSnapshotPage 为 PageSchema
1327
+ * 严格按照 contracts 定义进行转换
1328
+ */
1329
+ private convertSnapshotPageToPageSchema;
1330
+ /**
1331
+ * 转换 PageSnapshotManifest 为 PageManifest
1332
+ * 注意:PageSnapshotManifest 是简化版本,缺少一些字段,需要从其他地方获取或使用默认值
1333
+ */
1334
+ private convertSnapshotManifestToPageManifest;
1335
+ /**
1336
+ * 验证 PageResolveResponse(严格按照 contracts 定义)
1337
+ */
1338
+ private isValidPageResolveResponse;
1175
1339
  /**
1176
1340
  * 预连接 API 服务器
1177
1341
  */
@@ -1179,40 +1343,43 @@ declare class PageLoader {
1179
1343
  /**
1180
1344
  * 清除缓存
1181
1345
  */
1182
- clearCache(pageUid?: string): void;
1183
- private buildResolveUrl;
1346
+ clearCache(pageId?: string): void;
1184
1347
  private buildHeaders;
1185
1348
  private getCacheKey;
1186
1349
  private isCacheValid;
1187
- private isValidPageResolveResult;
1188
1350
  private log;
1189
1351
  }
1190
1352
 
1191
1353
  /**
1192
1354
  * 组件加载器
1193
- * 负责从 CDN 加载组件资源
1355
+ * 负责从 CDN 动态加载 Web Components,支持 SRI 完整性校验、组件阻断、并行加载与降级处理。
1356
+ * @see SKILL: runtime-component-loading
1194
1357
  */
1195
1358
 
1196
1359
  /**
1197
1360
  * 组件加载器配置
1198
1361
  */
1199
1362
  interface ComponentLoaderOptions {
1200
- /** CDN 基础 URL */
1363
+ /** CDN 基础 URL,用于解析相对 entry 路径 */
1201
1364
  cdnBaseUrl: string;
1202
- /** 是否启用 SRI 校验 */
1365
+ /** 是否启用 SRI 完整性校验,默认 true */
1203
1366
  enableSRI?: boolean;
1204
- /** 被阻断的组件列表 */
1367
+ /** 被阻断的组件列表(如 `['comp@1.0.0']` 或仅组件名 `['comp']`),用于紧急止血 */
1205
1368
  blockedComponents?: string[];
1206
- /** 并行加载数量 */
1369
+ /** 并行加载数量,默认 4 */
1207
1370
  concurrency?: number;
1208
- /** 超时时间(毫秒) */
1371
+ /** 单次请求超时(毫秒),默认 30000 */
1209
1372
  timeout?: number;
1373
+ /** 请求 CDN 时附加的请求头(如认证等) */
1374
+ headers?: Record<string, string>;
1375
+ /** 自定义拉取脚本的实现,不传则使用全局 fetch;测试或自定义 CDN 客户端时注入 */
1376
+ fetchComponentScript?: (url: string, init?: RequestInit) => Promise<Response>;
1210
1377
  /** 日志器 */
1211
1378
  logger?: Logger;
1212
1379
  }
1213
1380
  /**
1214
1381
  * 组件加载器
1215
- * 负责加载 Web Components
1382
+ * 负责从 CDN 加载 Web Components,支持缓存、阻断、SRI 校验与并行加载。
1216
1383
  */
1217
1384
  declare class ComponentLoader {
1218
1385
  private options;
@@ -1221,37 +1388,47 @@ declare class ComponentLoader {
1221
1388
  private blockedSet;
1222
1389
  constructor(options: ComponentLoaderOptions);
1223
1390
  /**
1224
- * 加载单个组件
1391
+ * 加载单个组件(按 name@version 去重,同一组件并发请求复用同一 Promise)
1392
+ * @param item - 清单项(name、version、entry、integrity 等)
1393
+ * @returns 已加载的组件信息(含 Component 构造函数)
1394
+ * @throws ComponentBlockedError 当组件在阻断列表中
1395
+ * @throws ComponentLoadError 当拉取或执行失败
1396
+ * @throws IntegrityError 当 SRI 校验失败
1225
1397
  */
1226
1398
  load(item: ManifestItem): Promise<LoadedComponent>;
1227
1399
  /**
1228
- * 加载 Manifest 中的所有组件
1400
+ * manifest 批量加载组件,按 concurrency 分批并行;关键组件失败会抛出,非关键组件记录失败。
1401
+ * @param manifest - 页面清单(含 components 数组)
1402
+ * @returns 以 name@version 为 key 的加载结果 Map(status: loaded | failed | blocked)
1229
1403
  */
1230
1404
  loadAll(manifest: PageManifest): Promise<Map<string, ComponentLoadResult>>;
1231
1405
  /**
1232
- * 预加载组件
1406
+ * 预加载组件:向 document.head 插入 &lt;link rel="preload" as="script"&gt;,仅作提示,不阻塞 load。
1407
+ * @param items - 需要预加载的清单项
1233
1408
  */
1234
1409
  preload(items: ManifestItem[]): void;
1235
1410
  /**
1236
- * 检查组件是否已加载
1411
+ * 检查指定 name@version 的组件是否已加载并缓存
1237
1412
  */
1238
1413
  isLoaded(name: string, version: string): boolean;
1239
1414
  /**
1240
- * 获取已加载的组件
1415
+ * 获取已加载的组件信息,未加载则返回 undefined
1241
1416
  */
1242
1417
  get(name: string, version: string): LoadedComponent | undefined;
1243
1418
  /**
1244
- * 检查组件是否被阻断
1419
+ * 检查组件是否在阻断列表中(支持 `name@version` 或仅 `name`)
1245
1420
  */
1246
1421
  isBlocked(name: string, version: string): boolean;
1247
1422
  /**
1248
- * 更新阻断列表
1423
+ * 更新阻断列表(会完全替换当前列表)
1249
1424
  */
1250
1425
  updateBlockedList(blocked: string[]): void;
1251
1426
  private loadComponent;
1252
1427
  private fetchWithTimeout;
1253
1428
  private validateIntegrity;
1254
1429
  private executeScript;
1430
+ /** kebab-case -> PascalCase,用于匹配组件命名导出 */
1431
+ private kebabToPascal;
1255
1432
  private resolveUrl;
1256
1433
  private getComponentKey;
1257
1434
  private log;
@@ -2008,4 +2185,4 @@ declare class LifecycleManager {
2008
2185
  */
2009
2186
  declare const RUNTIME_VERSION = "1.0.0";
2010
2187
 
2011
- export { type ASTNode, ActionBridge, type ActionBridgeOptions, ActionError, type ActionExecutor, AssetLoader, type AssetLoaderOptions, BaseRenderer, type BaseRendererOptions, ComponentBlockedError, ComponentLoadError, type ComponentLoadResult, type ComponentLoadStatus, ComponentLoader, type ComponentLoaderOptions, DjvlcRuntime, DjvlcRuntimeError, type EvaluationResult, Evaluator, type EvaluatorOptions, EventBus, type EventBusOptions, type EventHandlerFn, ExpressionEngine, type ExpressionEngineOptions, ExpressionError, HostAPIImpl, type HostAPIOptions, IntegrityError, Lexer, type LifecycleEventType, LifecycleManager, type LifecycleManagerOptions, type LoadedComponent, type LogLevel, type Logger, type MetricType, PageLoadError, PageLoader, type PageLoaderOptions, type PageResolveResult, Parser, type PerformanceMetric, QueryError, RUNTIME_VERSION, RenderError, type Renderer, type RuntimeError, type RuntimeErrorType, type RuntimeEvent, type RuntimeEventType, type RuntimeOptions, type RuntimePhase, type RuntimeState, SUPPORTED_SCHEMA_VERSION as SCHEMA_VERSION, SUPPORTED_SCHEMA_VERSION, SecurityManager, type SecurityManagerOptions, type Span, type StateListener, StateManager, TelemetryManager, type TelemetryManagerOptions, type Token, type TokenType, type Unsubscribe, builtinFunctions, createFallbackElement, createRuntime, registerFallbackComponents };
2188
+ export { type ASTNode, ActionBridge, type ActionBridgeOptions, ActionError, type ActionExecutor, AssetLoader, type AssetLoaderOptions, BaseRenderer, type BaseRendererOptions, ComponentBlockedError, ComponentLoadError, type ComponentLoadResult, type ComponentLoadStatus, ComponentLoader, type ComponentLoaderOptions, DjvlcRuntime, DjvlcRuntimeError, type EvaluationResult, Evaluator, type EvaluatorOptions, EventBus, type EventBusOptions, type EventHandlerFn, type ExecuteActionParams, type ExecuteQueryParams, type ExecuteQueryResult, ExpressionEngine, type ExpressionEngineOptions, ExpressionError, HostAPIImpl, type HostAPIOptions, IntegrityError, Lexer, type LifecycleEventType, LifecycleManager, type LifecycleManagerOptions, type LoadedComponent, type LogLevel, type Logger, type MetricType, MockUserApiAdapter, type MockUserApiAdapterOptions, OpenApiUserAdapter, type OpenApiUserAdapterOptions, PageLoadError, PageLoader, type PageLoaderOptions, type PageResolveResult, Parser, type PerformanceMetric, QueryError, RUNTIME_VERSION, RenderError, type Renderer, type ResolvePageParams, type RuntimeContext, type RuntimeError, type RuntimeErrorType, type RuntimeEvent, type RuntimeEventType, type RuntimeOptions, type RuntimePhase, type RuntimeState, SUPPORTED_SCHEMA_VERSION as SCHEMA_VERSION, SUPPORTED_SCHEMA_VERSION, SecurityManager, type SecurityManagerOptions, type Span, type StateListener, StateManager, TelemetryManager, type TelemetryManagerOptions, type Token, type TokenType, type TrackPayload, type Unsubscribe, type UserApiAdapter, builtinFunctions, createFallbackElement, createRuntime, registerFallbackComponents };