@variojs/core 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +31 -216
  2. package/dist/errors.js +4 -132
  3. package/dist/expression/cache.js +1 -158
  4. package/dist/expression/compiler.js +1 -141
  5. package/dist/expression/dependencies.js +1 -106
  6. package/dist/expression/evaluate.js +2 -75
  7. package/dist/expression/evaluator.js +1 -533
  8. package/dist/expression/index.js +1 -12
  9. package/dist/expression/parser.js +1 -42
  10. package/dist/expression/utils.js +1 -78
  11. package/dist/expression/whitelist.js +3 -198
  12. package/dist/index.js +1 -21
  13. package/dist/runtime/context.js +1 -7
  14. package/dist/runtime/create-context.js +1 -62
  15. package/dist/runtime/index.js +1 -10
  16. package/dist/runtime/loop-context-pool.js +1 -114
  17. package/dist/runtime/path.js +1 -302
  18. package/dist/runtime/proxy.js +1 -54
  19. package/dist/runtime/sandbox.js +1 -32
  20. package/dist/types.js +1 -20
  21. package/dist/vm/errors.js +1 -5
  22. package/dist/vm/executor.js +2 -137
  23. package/dist/vm/handlers/array/pop.js +1 -28
  24. package/dist/vm/handlers/array/push.js +1 -42
  25. package/dist/vm/handlers/array/shift.js +1 -28
  26. package/dist/vm/handlers/array/splice.js +1 -59
  27. package/dist/vm/handlers/array/unshift.js +1 -42
  28. package/dist/vm/handlers/array/utils.js +1 -33
  29. package/dist/vm/handlers/batch.js +1 -40
  30. package/dist/vm/handlers/call.js +1 -65
  31. package/dist/vm/handlers/emit.js +1 -26
  32. package/dist/vm/handlers/if.js +1 -35
  33. package/dist/vm/handlers/index.js +1 -55
  34. package/dist/vm/handlers/log.js +1 -41
  35. package/dist/vm/handlers/loop.js +1 -71
  36. package/dist/vm/handlers/navigate.js +1 -43
  37. package/dist/vm/handlers/set.js +1 -30
  38. package/dist/vm/index.js +1 -7
  39. package/package.json +2 -2
package/README.md CHANGED
@@ -1,16 +1,13 @@
1
- # @variojs/core
1
+ # @variojs/core
2
2
 
3
- Vario Core Runtime - 指令虚拟机、表达式系统、运行时上下文
3
+ Vario 核心运行时 - 指令虚拟机、表达式系统、运行时上下文
4
4
 
5
- ## 简介
5
+ ## 特点
6
6
 
7
- `@variojs/core` Vario 的核心运行时模块,提供了框架无关的基础能力:
8
-
9
- - **RuntimeContext**: 扁平化状态管理 + `$` 前缀系统 API
10
- - **Expression System**: 安全表达式解析、编译和求值
11
- - **Action VM**: 指令虚拟机,执行各种操作指令
12
- - **安全沙箱**: 多层防护机制,防止恶意代码执行
13
- - **性能优化**: 表达式缓存、对象池、路径记忆化
7
+ - 🚀 **高性能**:表达式缓存、对象池、路径记忆化
8
+ - 🔒 **安全沙箱**:多层防护,白名单机制,防止恶意代码
9
+ - 📦 **框架无关**:可在任何 JavaScript 环境中使用
10
+ - 🎯 **扁平化状态**:`$` 前缀系统 API,简洁直观
14
11
 
15
12
  ## 安装
16
13
 
@@ -20,15 +17,12 @@ npm install @variojs/core
20
17
  pnpm add @variojs/core
21
18
  ```
22
19
 
23
- ## 核心概念
24
-
25
- ### RuntimeContext 运行时上下文
26
-
27
- 运行时上下文是 Vario 的核心,提供了扁平化的状态管理和系统 API:
20
+ ## 快速开始
28
21
 
29
22
  ```typescript
30
- import { createRuntimeContext } from '@variojs/core'
23
+ import { createRuntimeContext, createVMExecutor } from '@variojs/core'
31
24
 
25
+ // 创建运行时上下文
32
26
  const ctx = createRuntimeContext({
33
27
  state: {
34
28
  count: 0,
@@ -46,224 +40,45 @@ ctx.count // 0
46
40
  ctx.user.name // 'John'
47
41
 
48
42
  // 使用系统 API
49
- ctx._get('count') // 0
50
- ctx._set('count', 10) // 设置值
51
- ctx.$emit('countChanged', 10) // 发射事件
52
- ```
53
-
54
- ### Expression System 表达式系统
55
-
56
- 安全、强大的表达式求值引擎,支持复杂的条件判断、数据访问和计算:
57
-
58
- ```typescript
59
- import { createExpressionSandbox, compileExpression } from '@variojs/core'
60
-
61
- const sandbox = createExpressionSandbox(ctx)
62
-
63
- // 编译表达式
64
- const expr = compileExpression('count > 10 && user.age >= 18')
65
-
66
- // 求值
67
- const result = expr.evaluate(sandbox) // true/false
68
- ```
69
-
70
- **支持的语法**:
71
- - 变量访问:`count`, `user.name`
72
- - 数组访问:`items[0]`, `todos[index]`
73
- - 可选链:`user?.profile?.email`
74
- - 二元运算:`count + 1`, `price * quantity`
75
- - 比较运算:`count > 10`, `role === "admin"`
76
- - 逻辑运算:`showContent && isActive`
77
- - 三元表达式:`count > 10 ? "high" : "low"`
78
- - 函数调用(白名单):`Array.isArray(items)`, `Math.max(a, b)`
79
-
80
- ### Action VM 指令虚拟机
81
-
82
- 执行各种操作指令,如 `set`、`call`、`if`、`loop` 等:
83
-
84
- ```typescript
85
- import { createVMExecutor } from '@variojs/core'
43
+ ctx._set('count', 10)
44
+ ctx.$emit('countChanged', 10)
86
45
 
46
+ // 执行指令
87
47
  const executor = createVMExecutor(ctx)
88
-
89
- // 执行 set 指令
90
48
  await executor.execute({
91
49
  type: 'set',
92
50
  path: 'count',
93
51
  value: 10
94
52
  })
95
-
96
- // 执行 call 指令
97
- await executor.execute({
98
- type: 'call',
99
- method: 'increment'
100
- })
101
-
102
- // 执行 if 指令
103
- await executor.execute({
104
- type: 'if',
105
- cond: 'count > 10',
106
- then: {
107
- type: 'set',
108
- path: 'status',
109
- value: 'high'
110
- }
111
- })
112
53
  ```
113
54
 
114
- ## API 参考
115
-
116
- ### createRuntimeContext
117
-
118
- 创建运行时上下文。
119
-
120
- ```typescript
121
- function createRuntimeContext<TState extends Record<string, unknown>>(
122
- options: CreateContextOptions<TState>
123
- ): RuntimeContext<TState>
124
- ```
125
-
126
- **选项**:
127
-
128
- ```typescript
129
- interface CreateContextOptions<TState> {
130
- /** 初始状态 */
131
- state?: TState
132
- /** 方法注册表 */
133
- methods?: Record<string, MethodHandler>
134
- /** 表达式选项 */
135
- exprOptions?: ExpressionOptions
136
- /** 事件发射器 */
137
- onEmit?: (event: string, data?: unknown) => void
138
- /** 状态变化回调 */
139
- onStateChange?: (path: string, value: unknown) => void
140
- }
141
- ```
142
-
143
- ### Expression System
144
-
145
- ```typescript
146
- // 创建表达式沙箱
147
- function createExpressionSandbox(ctx: RuntimeContext): ExpressionSandbox
148
-
149
- // 编译表达式
150
- function compileExpression(expr: string): CompiledExpression
151
-
152
- // 解析表达式
153
- function parseExpression(expr: string): ExpressionAST
154
-
155
- // 求值表达式
156
- function evaluateExpression(expr: string, ctx: RuntimeContext): unknown
157
- ```
55
+ ## 表达式系统
158
56
 
159
- ### Action VM
57
+ 安全、强大的表达式求值引擎:
160
58
 
161
59
  ```typescript
162
- // 创建 VM 执行器
163
- function createVMExecutor(ctx: RuntimeContext): VMExecutor
60
+ import { compileExpression, createExpressionSandbox } from '@variojs/core'
164
61
 
165
- // 执行动作
166
- function executeAction(action: Action, ctx: RuntimeContext): Promise<void>
167
- ```
168
-
169
- ### Path Utilities
170
-
171
- 路径解析和操作工具:
172
-
173
- ```typescript
174
- // 解析路径
175
- function parsePath(path: string): PathSegment[]
176
-
177
- // 获取路径值
178
- function getPathValue(obj: Record<string, unknown>, path: string): unknown
179
-
180
- // 设置路径值
181
- function setPathValue(
182
- obj: Record<string, unknown>,
183
- path: string,
184
- value: unknown,
185
- options?: { createObject?: () => object, createArray?: () => unknown[] }
186
- ): void
187
-
188
- // 路径匹配
189
- function matchPath(pattern: string, path: string): boolean
190
- ```
191
-
192
- ## 安全特性
193
-
194
- ### 表达式白名单
195
-
196
- 表达式系统使用白名单机制,只允许安全的操作:
197
-
198
- - ✅ 允许:属性访问、数组访问、数学运算、比较运算
199
- - ✅ 允许:白名单函数(`Array.isArray`, `Math.max` 等)
200
- - ❌ 禁止:`eval`, `Function`, `global`, `window` 等危险操作
201
- - ❌ 禁止:直接访问 Node.js API(`require`, `process` 等)
202
-
203
- ### 沙箱机制
204
-
205
- 表达式在隔离的沙箱中执行,无法访问外部作用域:
206
-
207
- ```typescript
208
62
  const sandbox = createExpressionSandbox(ctx)
209
-
210
- // 只能访问 ctx 中定义的状态和方法
211
- // 无法访问全局变量、Node.js API 等
212
- ```
213
-
214
- ## 性能优化
215
-
216
- ### 表达式缓存
217
-
218
- 编译后的表达式会被缓存,避免重复编译:
219
-
220
- ```typescript
221
- // 第一次编译
222
- const expr1 = compileExpression('count > 10') // 编译
223
-
224
- // 第二次使用相同表达式
225
- const expr2 = compileExpression('count > 10') // 从缓存获取
226
- ```
227
-
228
- ### 路径缓存
229
-
230
- 路径解析结果会被缓存:
231
-
232
- ```typescript
233
- parsePathCached('user.profile.name') // 第一次解析
234
- parsePathCached('user.profile.name') // 从缓存获取
235
- ```
236
-
237
- ### 对象池
238
-
239
- 循环上下文使用对象池复用,减少内存分配:
240
-
241
- ```typescript
242
- import { createLoopContext, releaseLoopContext } from '@variojs/core'
243
-
244
- // 创建循环上下文(从池中获取)
245
- const loopCtx = createLoopContext(ctx, { item, index })
246
-
247
- // 使用后释放(归还到池中)
248
- releaseLoopContext(loopCtx)
63
+ const expr = compileExpression('count > 10 && user.age >= 18')
64
+ const result = expr.evaluate(sandbox) // true/false
249
65
  ```
250
66
 
251
- ## 类型支持
252
-
253
- 完整的 TypeScript 类型定义:
254
-
255
- ```typescript
256
- import type {
257
- RuntimeContext,
258
- Action,
259
- ExpressionOptions,
260
- MethodHandler
261
- } from '@variojs/core'
262
- ```
67
+ **支持的语法**:
68
+ - 变量访问:`count`, `user.name`
69
+ - 数组访问:`items[0]`
70
+ - 可选链:`user?.profile?.email`
71
+ - 运算:`count + 1`, `price * quantity`
72
+ - 逻辑:`showContent && isActive`
73
+ - 三元:`count > 10 ? "high" : "low"`
74
+ - 白名单函数:`Array.isArray`, `Math.max`
263
75
 
264
- ## 示例
76
+ ## 优势
265
77
 
266
- 查看主项目的 `play/src/examples/` 目录下的完整示例。
78
+ - **类型安全**:完整的 TypeScript 类型定义
79
+ - ✅ **性能优化**:表达式缓存、路径缓存、对象池复用
80
+ - ✅ **安全可靠**:白名单机制,沙箱隔离,防止代码注入
81
+ - ✅ **易于扩展**:支持自定义指令和方法
267
82
 
268
83
  ## 许可证
269
84
 
package/dist/errors.js CHANGED
@@ -1,132 +1,4 @@
1
- /**
2
- * Vario 错误处理体系
3
- *
4
- * 统一的错误基类和错误码系统
5
- */
6
- /**
7
- * Vario 错误基类
8
- *
9
- * 所有 Vario 相关错误都应继承此类
10
- */
11
- export class VarioError extends Error {
12
- /** 错误码 */
13
- code;
14
- /** 错误上下文 */
15
- context;
16
- constructor(message, code, context = {}) {
17
- super(message);
18
- this.name = 'VarioError';
19
- this.code = code;
20
- this.context = context;
21
- // 确保 stack 属性存在
22
- if (Error.captureStackTrace) {
23
- Error.captureStackTrace(this, VarioError);
24
- }
25
- }
26
- /**
27
- * 获取友好的错误消息
28
- */
29
- getFriendlyMessage() {
30
- const parts = [this.message];
31
- if (this.context.schemaPath) {
32
- parts.push(`\n Schema 路径: ${this.context.schemaPath}`);
33
- }
34
- if (this.context.expression) {
35
- parts.push(`\n 表达式: ${this.context.expression}`);
36
- }
37
- if (this.context.action) {
38
- parts.push(`\n 动作类型: ${this.context.action.type}`);
39
- }
40
- return parts.join('');
41
- }
42
- /**
43
- * 转换为 JSON(用于序列化)
44
- */
45
- toJSON() {
46
- return {
47
- name: this.name,
48
- message: this.message,
49
- code: this.code,
50
- context: this.context,
51
- stack: this.stack
52
- };
53
- }
54
- }
55
- /**
56
- * 动作执行错误
57
- */
58
- export class ActionError extends VarioError {
59
- constructor(action, message, code = 'ACTION_ERROR', context = {}) {
60
- super(message, code, {
61
- ...context,
62
- action
63
- });
64
- this.name = 'ActionError';
65
- }
66
- }
67
- /**
68
- * 表达式求值错误
69
- */
70
- export class ExpressionError extends VarioError {
71
- constructor(expression, message, code = 'EXPRESSION_ERROR', context = {}) {
72
- super(message, code, {
73
- ...context,
74
- expression
75
- });
76
- this.name = 'ExpressionError';
77
- }
78
- }
79
- /**
80
- * 服务调用错误
81
- */
82
- export class ServiceError extends VarioError {
83
- service;
84
- originalError;
85
- constructor(service, message, originalError, context = {}) {
86
- super(message, 'SERVICE_ERROR', context);
87
- this.name = 'ServiceError';
88
- this.service = service;
89
- this.originalError = originalError;
90
- }
91
- }
92
- /**
93
- * 批量执行错误
94
- */
95
- export class BatchError extends VarioError {
96
- failedActions;
97
- constructor(failedActions, message, context = {}) {
98
- super(message, 'BATCH_ERROR', context);
99
- this.name = 'BatchError';
100
- this.failedActions = failedActions;
101
- }
102
- }
103
- /**
104
- * 错误码定义
105
- */
106
- export const ErrorCodes = {
107
- // 动作相关错误
108
- ACTION_UNKNOWN_TYPE: 'ACTION_UNKNOWN_TYPE',
109
- ACTION_EXECUTION_ERROR: 'ACTION_EXECUTION_ERROR',
110
- ACTION_ABORTED: 'ACTION_ABORTED',
111
- ACTION_TIMEOUT: 'ACTION_TIMEOUT',
112
- ACTION_MAX_STEPS_EXCEEDED: 'ACTION_MAX_STEPS_EXCEEDED',
113
- ACTION_MISSING_PARAM: 'ACTION_MISSING_PARAM',
114
- ACTION_INVALID_PARAM: 'ACTION_INVALID_PARAM',
115
- // 表达式相关错误
116
- EXPRESSION_PARSE_ERROR: 'EXPRESSION_PARSE_ERROR',
117
- EXPRESSION_VALIDATION_ERROR: 'EXPRESSION_VALIDATION_ERROR',
118
- EXPRESSION_EVALUATION_ERROR: 'EXPRESSION_EVALUATION_ERROR',
119
- EXPRESSION_TIMEOUT: 'EXPRESSION_TIMEOUT',
120
- EXPRESSION_MAX_STEPS_EXCEEDED: 'EXPRESSION_MAX_STEPS_EXCEEDED',
121
- EXPRESSION_UNSAFE_ACCESS: 'EXPRESSION_UNSAFE_ACCESS',
122
- EXPRESSION_FUNCTION_NOT_WHITELISTED: 'EXPRESSION_FUNCTION_NOT_WHITELISTED',
123
- // 服务相关错误
124
- SERVICE_NOT_FOUND: 'SERVICE_NOT_FOUND',
125
- SERVICE_CALL_ERROR: 'SERVICE_CALL_ERROR',
126
- // 批量执行错误
127
- BATCH_ERROR: 'BATCH_ERROR',
128
- // Schema 相关错误
129
- SCHEMA_VALIDATION_ERROR: 'SCHEMA_VALIDATION_ERROR',
130
- SCHEMA_INVALID_ACTION: 'SCHEMA_INVALID_ACTION',
131
- };
132
- //# sourceMappingURL=errors.js.map
1
+ class R extends Error{code;context;constructor(E,t,r={}){super(E),this.name="VarioError",this.code=t,this.context=r,Error.captureStackTrace&&Error.captureStackTrace(this,R)}getFriendlyMessage(){const E=[this.message];return this.context.schemaPath&&E.push(`
2
+ Schema \u8DEF\u5F84: ${this.context.schemaPath}`),this.context.expression&&E.push(`
3
+ \u8868\u8FBE\u5F0F: ${this.context.expression}`),this.context.action&&E.push(`
4
+ \u52A8\u4F5C\u7C7B\u578B: ${this.context.action.type}`),E.join("")}toJSON(){return{name:this.name,message:this.message,code:this.code,context:this.context,stack:this.stack}}}class _ extends R{constructor(E,t,r="ACTION_ERROR",e={}){super(t,r,{...e,action:E}),this.name="ActionError"}}class O extends R{constructor(E,t,r="EXPRESSION_ERROR",e={}){super(t,r,{...e,expression:E}),this.name="ExpressionError"}}class I extends R{service;originalError;constructor(E,t,r,e={}){super(t,"SERVICE_ERROR",e),this.name="ServiceError",this.service=E,this.originalError=r}}class S extends R{failedActions;constructor(E,t,r={}){super(t,"BATCH_ERROR",r),this.name="BatchError",this.failedActions=E}}const A={ACTION_UNKNOWN_TYPE:"ACTION_UNKNOWN_TYPE",ACTION_EXECUTION_ERROR:"ACTION_EXECUTION_ERROR",ACTION_ABORTED:"ACTION_ABORTED",ACTION_TIMEOUT:"ACTION_TIMEOUT",ACTION_MAX_STEPS_EXCEEDED:"ACTION_MAX_STEPS_EXCEEDED",ACTION_MISSING_PARAM:"ACTION_MISSING_PARAM",ACTION_INVALID_PARAM:"ACTION_INVALID_PARAM",EXPRESSION_PARSE_ERROR:"EXPRESSION_PARSE_ERROR",EXPRESSION_VALIDATION_ERROR:"EXPRESSION_VALIDATION_ERROR",EXPRESSION_EVALUATION_ERROR:"EXPRESSION_EVALUATION_ERROR",EXPRESSION_TIMEOUT:"EXPRESSION_TIMEOUT",EXPRESSION_MAX_STEPS_EXCEEDED:"EXPRESSION_MAX_STEPS_EXCEEDED",EXPRESSION_UNSAFE_ACCESS:"EXPRESSION_UNSAFE_ACCESS",EXPRESSION_FUNCTION_NOT_WHITELISTED:"EXPRESSION_FUNCTION_NOT_WHITELISTED",SERVICE_NOT_FOUND:"SERVICE_NOT_FOUND",SERVICE_CALL_ERROR:"SERVICE_CALL_ERROR",BATCH_ERROR:"BATCH_ERROR",SCHEMA_VALIDATION_ERROR:"SCHEMA_VALIDATION_ERROR",SCHEMA_INVALID_ACTION:"SCHEMA_INVALID_ACTION"};export{_ as ActionError,S as BatchError,A as ErrorCodes,O as ExpressionError,I as ServiceError,R as VarioError};
@@ -1,158 +1 @@
1
- /**
2
- * 表达式缓存系统
3
- *
4
- * 功能:
5
- * - 每个 RuntimeContext 独立缓存(WeakMap 关联)
6
- * - LRU 淘汰策略
7
- * - 通配符依赖匹配
8
- * - 缓存失效机制
9
- *
10
- * 设计原则:
11
- * - 惰性求值:只在需要时计算
12
- * - 依赖追踪:精确的缓存失效
13
- * - 内存友好:WeakMap + LRU 淘汰
14
- */
15
- import { matchPath } from '../runtime/path.js';
16
- /**
17
- * 每个上下文独立缓存
18
- * 使用 RuntimeContext 作为键(WeakMap 自动回收)
19
- */
20
- const cacheMap = new WeakMap();
21
- /**
22
- * 缓存配置
23
- */
24
- const CACHE_CONFIG = {
25
- /** 最大缓存条目数 */
26
- maxSize: 100,
27
- /** 缓存有效期(毫秒),0 表示不过期 */
28
- ttl: 0
29
- };
30
- /**
31
- * 获取上下文的缓存 Map
32
- */
33
- function getCache(ctx) {
34
- let cache = cacheMap.get(ctx);
35
- if (!cache) {
36
- cache = new Map();
37
- cacheMap.set(ctx, cache);
38
- }
39
- return cache;
40
- }
41
- /**
42
- * 检查缓存条目是否有效
43
- */
44
- function isCacheValid(entry, ctx) {
45
- // TTL 检查
46
- if (CACHE_CONFIG.ttl > 0 && Date.now() - entry.timestamp > CACHE_CONFIG.ttl) {
47
- return false;
48
- }
49
- // 依赖检查:所有依赖的值必须存在
50
- return entry.dependencies.every(dep => {
51
- if (dep.includes('*')) {
52
- // 通配符依赖:检查父路径是否存在
53
- const parentPath = dep.split('.*')[0];
54
- return ctx._get(parentPath) != null;
55
- }
56
- // 具体路径:检查值是否存在
57
- return ctx._get(dep) !== undefined;
58
- });
59
- }
60
- /**
61
- * LRU 淘汰:删除最旧的缓存条目
62
- */
63
- function evictOldest(cache) {
64
- let oldestKey = null;
65
- let oldestTime = Infinity;
66
- for (const [key, entry] of cache.entries()) {
67
- if (entry.timestamp < oldestTime) {
68
- oldestTime = entry.timestamp;
69
- oldestKey = key;
70
- }
71
- }
72
- if (oldestKey) {
73
- cache.delete(oldestKey);
74
- }
75
- }
76
- /**
77
- * 获取缓存的表达式结果
78
- *
79
- * @param expr 表达式字符串
80
- * @param ctx 运行时上下文
81
- * @returns 缓存的结果,无缓存或已失效返回 null
82
- */
83
- export function getCachedExpression(expr, ctx) {
84
- const cache = getCache(ctx);
85
- const entry = cache.get(expr);
86
- if (!entry) {
87
- return null;
88
- }
89
- if (!isCacheValid(entry, ctx)) {
90
- cache.delete(expr);
91
- return null;
92
- }
93
- // 更新时间戳(LRU)
94
- entry.timestamp = Date.now();
95
- return entry.result;
96
- }
97
- /**
98
- * 设置表达式缓存
99
- *
100
- * @param expr 表达式字符串
101
- * @param result 求值结果
102
- * @param dependencies 依赖的状态路径
103
- * @param ctx 运行时上下文
104
- */
105
- export function setCachedExpression(expr, result, dependencies, ctx) {
106
- const cache = getCache(ctx);
107
- // LRU 淘汰
108
- if (cache.size >= CACHE_CONFIG.maxSize) {
109
- evictOldest(cache);
110
- }
111
- cache.set(expr, {
112
- expr,
113
- result,
114
- dependencies,
115
- timestamp: Date.now()
116
- });
117
- }
118
- /**
119
- * 使缓存失效
120
- *
121
- * 当状态变化时调用,精确删除依赖该状态的缓存
122
- *
123
- * @param changedPath 变化的状态路径
124
- * @param ctx 运行时上下文
125
- */
126
- export function invalidateCache(changedPath, ctx) {
127
- const cache = getCache(ctx);
128
- const toDelete = [];
129
- for (const [expr, entry] of cache.entries()) {
130
- // 检查是否有依赖被影响
131
- const isAffected = entry.dependencies.some(dep => matchPath(dep, changedPath) || matchPath(changedPath, dep));
132
- if (isAffected) {
133
- toDelete.push(expr);
134
- }
135
- }
136
- // 批量删除
137
- for (const expr of toDelete) {
138
- cache.delete(expr);
139
- }
140
- }
141
- /**
142
- * 清除指定上下文的所有缓存
143
- */
144
- export function clearCache(ctx) {
145
- const cache = getCache(ctx);
146
- cache.clear();
147
- }
148
- /**
149
- * 获取缓存统计信息(调试用)
150
- */
151
- export function getCacheStats(ctx) {
152
- const cache = getCache(ctx);
153
- return {
154
- size: cache.size,
155
- expressions: Array.from(cache.keys())
156
- };
157
- }
158
- //# sourceMappingURL=cache.js.map
1
+ import{matchPath as a}from"../runtime/path.js";const f=new WeakMap,o={maxSize:100,ttl:0};function i(t){let e=f.get(t);return e||(e=new Map,f.set(t,e)),e}function u(t,e){return o.ttl>0&&Date.now()-t.timestamp>o.ttl?!1:t.dependencies.every(n=>{if(n.includes("*")){const s=n.split(".*")[0];return e._get(s)!=null}return e._get(n)!==void 0})}function p(t){let e=null,n=1/0;for(const[s,c]of t.entries())c.timestamp<n&&(n=c.timestamp,e=s);e&&t.delete(e)}function d(t,e){const n=i(e),s=n.get(t);return s?u(s,e)?(s.timestamp=Date.now(),s.result):(n.delete(t),null):null}function C(t,e,n,s){const c=i(s);c.size>=o.maxSize&&p(c),c.set(t,{expr:t,result:e,dependencies:n,timestamp:Date.now()})}function y(t,e){const n=i(e),s=[];for(const[c,l]of n.entries())l.dependencies.some(r=>a(r,t)||a(t,r))&&s.push(c);for(const c of s)n.delete(c)}function x(t){i(t).clear()}function g(t){const e=i(t);return{size:e.size,expressions:Array.from(e.keys())}}export{x as clearCache,g as getCacheStats,d as getCachedExpression,y as invalidateCache,C as setCachedExpression};