@meshflow/form 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # @meshflow/form
2
+
3
+ **基于 @meshflow/core 的高性能、强类型、无头(Headless)表单逻辑驱动器。**
4
+
5
+ [![NPM Version](https://img.shields.io/npm/v/@meshflow/form.svg)](https://www.npmjs.com/package/@meshflow/form)
6
+ [![Peer Dependency](https://img.shields.io/badge/peer--deps-%40meshflow%2Fcore-%2361dafb)](https://www.npmjs.com/package/@meshflow/core)
7
+
8
+ ## 🌟 核心优势
9
+
10
+ `@meshflow/form` 是专为复杂中后台设计的表单逻辑层。它不提供任何 UI 组件,而是通过**拓扑任务编排**,赋予表单处理 500+ 节点复杂联动的能力。
11
+
12
+ - **🏗️ 真正的无头架构**:通过 `UITrigger` 与 UI 框架(Vue/React/Solid)解耦,逻辑运行在纯 JS 引擎中。
13
+ - **⚡ 极致类型推导**:基于 TypeScript 的路径感知,实现超大规模 Schema 的自动路径补全。
14
+ - **🧩 插件化扩展**:支持通过 `modules` 注入功能模块(如 Undo/Redo 历史记录)。
15
+ - **🌊 异步时序安全**:内置水位线机制,原生解决高频操作下的异步回填竞态问题。
16
+
17
+ ---
18
+
19
+ ## 🚀 快速上手
20
+
21
+ #### 安装
22
+ ```bash
23
+ npm install @meshflow/form
24
+ ```
25
+
26
+ ##### 初始化引擎
27
+ ```typescript
28
+ import { useMeshForm } from "@meshflow/form";
29
+
30
+ const schema = {
31
+ type: 'group',
32
+ name: 'billing',
33
+ label: '计费与汇总',
34
+ children: [
35
+ { type: 'number', name: 'totalPrice', label: '预估月度总价', value: 0, },
36
+ { type: 'input', name: 'priceDetail', label: '计费项说明', value: '基础配置费用'}
37
+ ]
38
+ };
39
+ const engine = useMeshForm('engine', schema, {
40
+ UITrigger: {
41
+ // Vue 响应式绑定
42
+ signalCreateor: () => ref(0),
43
+ signalTrigger(signal) {
44
+ signal.value++;
45
+ }
46
+ }
47
+ });
48
+ ```
49
+
50
+ ##### 添加联动依赖
51
+ ```typescript
52
+ engine.config.SetRule("billing.totalPrice", "billing.priceDetail", "value", {
53
+ logic: ({ slot }) => {
54
+ const [total] = slot.triggerTargets; // 从触发目标中解构出 totalPrice
55
+ return total > 2000 ? "大客户折扣" : undefined;
56
+ }
57
+ });
58
+ ```
package/index.d.mts CHANGED
@@ -1,5 +1,406 @@
1
- import * as _meshflow_core from '@meshflow/core';
2
- import { MeshPath, Engine, InferLeafPath, SchedulerType } from '@meshflow/core';
1
+ import { MeshPath as MeshPath$1 } from '@meshflow/core';
2
+
3
+ type Unwrap<T> = T extends ReadonlyArray<infer U> ? U : T;
4
+ type InferLeafPath<T, Prefix extends string = ""> = Unwrap<T> extends infer Node ? Node extends {
5
+ readonly name: infer N;
6
+ } ? N extends string ? N extends "" ? Node extends {
7
+ readonly children: infer C;
8
+ } ? InferLeafPath<C, Prefix> : never : (Node extends {
9
+ readonly children: infer C;
10
+ } ? InferLeafPath<C, Prefix extends "" ? N : `${Prefix}.${N}`> : (Prefix extends "" ? N : `${Prefix}.${N}`)) : N extends number | symbol ? Node extends {
11
+ readonly children: infer C;
12
+ } ? InferLeafPath<C, Prefix> : N : never : never : never;
13
+ type KeysOfUnion<T> = T extends any ? keyof T : never;
14
+
15
+ interface MeshErrorContext {
16
+ path: string;
17
+ error: any;
18
+ }
19
+
20
+ type ContractType = 'boolean' | 'scalar' | 'array' | 'object';
21
+ declare enum DefaultStrategy {
22
+ OR = "OR",
23
+ PRIORITY = "PRIORITY"
24
+ }
25
+ declare class SchemaBucket<P> {
26
+ private path;
27
+ private strategy;
28
+ contract: ContractType;
29
+ private rules;
30
+ private isValue;
31
+ private id;
32
+ private cache;
33
+ private pendingPromise;
34
+ private version;
35
+ private deps;
36
+ private _forceNotify;
37
+ promiseToken: any;
38
+ private effectArray;
39
+ constructor(baseValue: any, key: string | number | symbol, path: P);
40
+ forceNotify(): void;
41
+ isForceNotify(): boolean;
42
+ setStrategy(type: DefaultStrategy): void;
43
+ setDefaultRule(value: any): void;
44
+ setRules(value: any, DepsArray?: Array<[P, any]>): () => void;
45
+ updateDeps(DepsArray: Array<[P, any]>): void;
46
+ setRule(value: any, DepsArray?: Array<[P, any]>): (() => void) | undefined;
47
+ setSideEffect(data: {
48
+ fn: (args: any[]) => any;
49
+ args: any[];
50
+ }): void;
51
+ getSideEffect(): {
52
+ fn: (args: any) => any;
53
+ args: any[];
54
+ }[];
55
+ evaluate(api: any): any;
56
+ private finalizeSync;
57
+ private inferType;
58
+ }
59
+
60
+ interface MeshEvents {
61
+ 'node:start': {
62
+ path: MeshPath;
63
+ };
64
+ 'node:success': {
65
+ path: MeshPath;
66
+ };
67
+ 'node:bucket:success': {
68
+ path: MeshPath;
69
+ key: string;
70
+ value: any;
71
+ };
72
+ 'node:error': {
73
+ path: MeshPath;
74
+ error: any;
75
+ };
76
+ 'node:intercept': {
77
+ path: MeshPath;
78
+ type: number;
79
+ detail?: any;
80
+ };
81
+ 'node:release': {
82
+ path: MeshPath;
83
+ type: number;
84
+ detail?: any;
85
+ };
86
+ 'node:stagnate': {
87
+ path: MeshPath;
88
+ type: number;
89
+ };
90
+ 'node:processing': {
91
+ path: MeshPath;
92
+ };
93
+ 'flow:wait': {
94
+ type: number;
95
+ detail?: any;
96
+ };
97
+ 'flow:fire': {
98
+ path: MeshPath;
99
+ type: number;
100
+ detail?: any;
101
+ };
102
+ 'flow:start': {
103
+ path: MeshPath;
104
+ };
105
+ 'flow:success': {
106
+ duration: string;
107
+ };
108
+ 'flow:end': {
109
+ type: number;
110
+ };
111
+ 'node:pending': {
112
+ path: MeshPath;
113
+ };
114
+ }
115
+ type MeshEventName = keyof MeshEvents;
116
+ type MeshEmit = <K extends MeshEventName>(event: K, data: MeshEvents[K]) => void;
117
+ type HistoryActionItem = {
118
+ undoAction: () => void;
119
+ redoAction: () => void;
120
+ };
121
+ type MeshFlowHistory = {
122
+ Undo: () => void;
123
+ Redo: () => void;
124
+ initCanUndo: any;
125
+ initCanRedo: any;
126
+ PushIntoHistory: (action: HistoryActionItem, cleanRedo?: boolean) => void;
127
+ CreateHistoryAction: (metadata: [
128
+ {
129
+ path: string;
130
+ value: any;
131
+ },
132
+ {
133
+ path: string;
134
+ value: any;
135
+ }
136
+ ], cb: any) => {
137
+ undoAction: () => any;
138
+ redoAction: () => any;
139
+ };
140
+ };
141
+ type MeshPath = string | number | symbol;
142
+ interface MeshBucket<P> {
143
+ evaluate: (context: any) => Promise<any> | any;
144
+ [key: string]: any;
145
+ }
146
+ interface MeshFlowTaskNode<P extends MeshPath = MeshPath, V = any, S = any> {
147
+ path: P;
148
+ uid: number;
149
+ type: string;
150
+ state: V;
151
+ nodeBucket: Record<keyof S, MeshBucket<P>>;
152
+ notifyKeys: Set<keyof S>;
153
+ dirtySignal: any;
154
+ proxy: any;
155
+ meta: S;
156
+ dependOn: (cb: (val: V) => V) => void;
157
+ createView: (extraProps?: Record<string, any>) => any;
158
+ }
159
+ interface MeshFlowGroupNode<P extends MeshPath = MeshPath> {
160
+ path: P;
161
+ uid: number;
162
+ type: 'group';
163
+ children: Array<P>;
164
+ dirtySignal: any;
165
+ meta: Record<string, any>;
166
+ }
167
+ interface logicApi {
168
+ slot: {
169
+ triggerTargets: any;
170
+ affectedTatget: any;
171
+ };
172
+ }
173
+ interface SetRuleOptions<NM> {
174
+ value?: any;
175
+ priority?: number;
176
+ forceNotify?: boolean;
177
+ logic: (api: logicApi) => any;
178
+ effect?: (args: any) => any;
179
+ effectArgs?: Array<KeysOfUnion<NM>>;
180
+ }
181
+
182
+ /**
183
+ * 🌟 入口函数
184
+ * @template T - UI 信号类型 (Signal)
185
+ * @template P - 路径联合类型 ("user.name" | "user.age") 也支持number或者symbol
186
+ * @template S - 业务元数据类型 (默认使用表单的 Meta,但也允许传入 any)
187
+ */
188
+ declare function useEngineInstance<T, P extends MeshPath, S = any, NM = any>(data: S, options: {
189
+ config: {
190
+ useGreedy: boolean;
191
+ };
192
+ UITrigger: {
193
+ signalCreator: () => T;
194
+ signalTrigger: (signal: T) => void;
195
+ };
196
+ modules: {
197
+ useHistory?: () => MeshFlowHistory;
198
+ useInternalForm?: <T, P>(scheduler: any, data: any) => any;
199
+ useSchemaValidators?: <P>(Finder: (path: P) => any) => {
200
+ SetValidators: (path: P, options: {
201
+ logic: (val: any, GetByPath: any) => any;
202
+ condition: (data: any) => boolean;
203
+ }) => void;
204
+ };
205
+ };
206
+ plugins: {};
207
+ }): {
208
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
209
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
210
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStrategy) => void;
211
+ SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
212
+ cancel: () => void;
213
+ };
214
+ usePlugin: (plugin: {
215
+ apply: (api: {
216
+ on: (event: MeshEventName, cb: Function) => () => boolean;
217
+ }) => void;
218
+ }) => () => void;
219
+ SetValue: (path: P, value: any) => void;
220
+ GetValue: (path: P, key?: string) => any;
221
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
222
+ notifyAll: () => Promise<void>;
223
+ GetAllDependency: () => Map<P, Set<P>>;
224
+ GetDependencyOrder: () => P[][];
225
+ historyExports: Partial<MeshFlowHistory>;
226
+ formExports: {};
227
+ validatorExports: {
228
+ SetValidators?: (path: P, options: {
229
+ logic: (val: any, GetByPath: any) => any;
230
+ condition: (data: any) => boolean;
231
+ }) => void;
232
+ };
233
+ onError: (cb: (error: MeshErrorContext) => void) => () => void;
234
+ onSuccess: (cb: (data: unknown) => void) => () => void;
235
+ onStart: (cb: (data: {
236
+ path: P;
237
+ }) => void) => () => void;
238
+ };
239
+
240
+ declare function useScheduler<T, //ui trigger中定义的类型
241
+ P extends MeshPath, // 路径类型
242
+ S = any>(schema: S, config: {
243
+ useGreedy: boolean;
244
+ }, dependency: {
245
+ GetDependencyOrder: () => P[][];
246
+ GetAllNextDependency: (path: P) => P[];
247
+ GetNextDependency: (path: P) => P[];
248
+ GetPrevDependency: (path: P) => P[];
249
+ GetAllPrevDependency: (path: P) => P[];
250
+ GetPathToLevelMap: () => Map<P, number>;
251
+ }, history: Partial<{
252
+ pushIntoHistory: any;
253
+ createHistoryAction: any;
254
+ }>, hooks: {
255
+ callOnError: any;
256
+ callOnSuccess: any;
257
+ callOnStart: any;
258
+ emit: MeshEmit;
259
+ }, UITrigger: {
260
+ signalCreator: () => T;
261
+ signalTrigger: (signal: T) => void;
262
+ }): {
263
+ registerNode: (nodeMeta: Omit<MeshFlowTaskNode<P>, "createView" | "proxy">) => MeshFlowTaskNode<P, any, any>;
264
+ registerGroupNode: (groupMeta: Omit<MeshFlowGroupNode<P>, "createView">) => MeshFlowGroupNode<P>;
265
+ GetNodeByPath: (path: P) => MeshFlowTaskNode<P, any, S>;
266
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
267
+ notify: (path: P) => void;
268
+ notifyAll: () => Promise<void>;
269
+ UITrigger: {
270
+ signalCreator: () => T;
271
+ signalTrigger: (signal: T) => void;
272
+ };
273
+ UidToNodeMap: Map<number, MeshFlowTaskNode<P, any, S>>;
274
+ };
275
+
276
+ type SchedulerType<T, P extends MeshPath, S, NM> = ReturnType<typeof useEngineInstance<T, P, S, NM>>;
277
+ type BaseEngine<T> = {
278
+ data: {
279
+ SetValue: T extends {
280
+ SetValue: infer F;
281
+ } ? F : never;
282
+ GetValue: T extends {
283
+ GetValue: infer F;
284
+ } ? F : never;
285
+ GetGroupByPath: T extends {
286
+ GetGroupByPath: infer F;
287
+ } ? F : never;
288
+ };
289
+ config: {
290
+ SetRule: T extends {
291
+ SetRule: infer F;
292
+ } ? F : never;
293
+ SetRules: T extends {
294
+ SetRules: infer F;
295
+ } ? F : never;
296
+ SetStrategy: T extends {
297
+ SetStrategy: infer F;
298
+ } ? F : never;
299
+ notifyAll: T extends {
300
+ notifyAll: infer F;
301
+ } ? F : never;
302
+ SetTrace: T extends {
303
+ SetTrace: infer F;
304
+ } ? F : never;
305
+ usePlugin: T extends {
306
+ usePlugin: infer F;
307
+ } ? F : never;
308
+ };
309
+ dependency: {
310
+ GetAllDependency: T extends {
311
+ GetAllDependency: infer F;
312
+ } ? F : never;
313
+ GetDependencyOrder: T extends {
314
+ GetDependencyOrder: infer F;
315
+ } ? F : never;
316
+ };
317
+ hooks: {
318
+ onError: T extends {
319
+ onError: infer F;
320
+ } ? F : never;
321
+ onSuccess: T extends {
322
+ onSuccess: infer F;
323
+ } ? F : never;
324
+ onStart: T extends {
325
+ onStart: infer F;
326
+ } ? F : never;
327
+ };
328
+ };
329
+ type TransformModuleKey<T> = T extends `use${infer Rest}` ? Uncapitalize<Rest> : T;
330
+ type MapModuleToReturn<K, F, P extends MeshPath> = K extends 'useSchemaValidators' | 'schemaValidators' ? {
331
+ SetValidators: (path: P, options: {
332
+ logic: (val: any, GetByPath: (path: P) => any) => any;
333
+ condition: (data: any) => boolean;
334
+ }) => void;
335
+ } : F extends (...args: any) => infer R ? R : any;
336
+ type EngineModules<M, P extends MeshPath> = {
337
+ [K in keyof M as TransformModuleKey<string & K>]: MapModuleToReturn<K, M[K], P>;
338
+ };
339
+ type Engine<T, M, P extends MeshPath> = BaseEngine<T> & EngineModules<M, P>;
340
+
341
+ type FinalFlatten<T> = T extends infer O ? {
342
+ [K in keyof O]: O[K];
343
+ } : never;
344
+ type BaseField = {
345
+ label: string;
346
+ name: string;
347
+ placeholder?: string;
348
+ disabled: boolean;
349
+ readonly: boolean;
350
+ hidden?: boolean;
351
+ validators?: any;
352
+ theme?: string;
353
+ };
354
+ type InputField = BaseField & {
355
+ type: "input" | "number";
356
+ required: boolean;
357
+ min?: number;
358
+ maxLength: number;
359
+ value: string | number;
360
+ };
361
+ type CheckboxField = BaseField & {
362
+ type: "checkbox";
363
+ description?: string;
364
+ required: boolean;
365
+ value: boolean;
366
+ };
367
+ type SelectField = BaseField & {
368
+ type: "select";
369
+ required: boolean;
370
+ options: {
371
+ label: string;
372
+ value: any;
373
+ }[];
374
+ value: any;
375
+ };
376
+ type GroupField = Omit<BaseField, "label" | "name" | "placeholder" | "validators"> & {
377
+ type: "group";
378
+ name?: string;
379
+ children: FormFieldSchema[];
380
+ };
381
+ type FormFieldSchema = InputField | CheckboxField | SelectField | GroupField;
382
+ type RenderSchemaExtraCommonType<P = any> = {
383
+ path: P;
384
+ dirtySignal: any;
385
+ uid: number;
386
+ nodeBucket: Record<string, SchemaBucket<P>>;
387
+ dependOn: (cb: (...args: any) => void) => void;
388
+ };
389
+ type RenderSchemaFn<T> = FinalFlatten<T extends GroupField ? Omit<T, "children"> & RenderSchemaExtraCommonType & {
390
+ children: Array<RenderSchemaFn<FormFieldSchema>>;
391
+ } : T & RenderSchemaExtraCommonType>;
392
+ type RenderSchema = RenderSchemaFn<FormFieldSchema>;
393
+ declare function useInternalForm<T, P extends MeshPath>(scheduler: ReturnType<typeof useScheduler<T, P>>, rootSchema: any): {
394
+ uiSchema: RenderSchema;
395
+ GetFormData: () => any;
396
+ };
397
+
398
+ declare const useSchemaValidators: <P extends MeshPath$1>(Finder: (path: P) => any) => {
399
+ SetValidators: (path: P, options: {
400
+ logic: (val: any, GetByPath: any) => any;
401
+ condition: (data: any) => boolean;
402
+ }) => void;
403
+ };
3
404
 
4
405
  /**
5
406
  * NM: NodeMeta 的类型定义
@@ -18,46 +419,27 @@ declare function useMeshForm<const S extends Record<string, any>, NM extends Rec
18
419
  }): Engine<SchedulerType<T, P, S, NM>, M, P>;
19
420
  declare const useEngine: <M extends Record<string, any> = {}, P extends string = any, // 如果 Core 里叫 MeshPath,这里可以写成 extends MeshPath
20
421
  NM extends Record<string, any> = Record<string, any>>(id: MeshPath) => [M & {
21
- internalForm: any;
22
- schemaValidators: any;
422
+ internalForm: typeof useInternalForm;
423
+ schemaValidators: typeof useSchemaValidators;
23
424
  }] extends [never] ? Engine<{
24
- SetRule: <K extends string | number | symbol>(outDegreePath: any, inDegreePath: any, key: K, options: _meshflow_core.SetRuleOptions<any>) => void;
25
- SetRules: <K extends string | number | symbol>(outDegreePaths: any[], inDegreePath: any, key: K, options: _meshflow_core.SetRuleOptions<any>) => void;
26
- SetStrategy: (path: any, key: string | number | symbol, strategy: _meshflow_core.DefaultStrategy) => void;
425
+ SetRule: <K extends string | number | symbol>(outDegreePath: any, inDegreePath: any, key: K, options: SetRuleOptions<any>) => void;
426
+ SetRules: <K extends string | number | symbol>(outDegreePaths: any[], inDegreePath: any, key: K, options: SetRuleOptions<any>) => void;
427
+ SetStrategy: (path: any, key: string | number | symbol, strategy: DefaultStrategy) => void;
27
428
  SetTrace: (myPath: any, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
28
429
  cancel: () => void;
29
430
  };
30
431
  usePlugin: (plugin: {
31
432
  apply: (api: {
32
- on: (event: keyof _meshflow_core.MeshEvents, cb: Function) => () => boolean;
433
+ on: (event: MeshEventName, cb: Function) => () => boolean;
33
434
  }) => void;
34
435
  }) => () => void;
35
436
  SetValue: (path: any, value: any) => void;
36
437
  GetValue: (path: any, key?: string) => any;
37
- GetGroupByPath: (path: MeshPath) => _meshflow_core.MeshFlowGroupNode<MeshPath> | undefined;
438
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
38
439
  notifyAll: () => Promise<void>;
39
440
  GetAllDependency: () => Map<any, Set<any>>;
40
441
  GetDependencyOrder: () => any[][];
41
- historyExports: Partial<{
42
- Undo: () => void;
43
- Redo: () => void;
44
- initCanUndo: any;
45
- initCanRedo: any;
46
- PushIntoHistory: (action: {
47
- undoAction: () => void;
48
- redoAction: () => void;
49
- }, cleanRedo?: boolean) => void;
50
- CreateHistoryAction: (metadata: [{
51
- path: string;
52
- value: any;
53
- }, {
54
- path: string;
55
- value: any;
56
- }], cb: any) => {
57
- undoAction: () => any;
58
- redoAction: () => any;
59
- };
60
- }>;
442
+ historyExports: Partial<MeshFlowHistory>;
61
443
  formExports: {};
62
444
  validatorExports: {
63
445
  SetValidators?: ((path: any, options: {
@@ -65,49 +447,30 @@ NM extends Record<string, any> = Record<string, any>>(id: MeshPath) => [M & {
65
447
  condition: (data: any) => boolean;
66
448
  }) => void) | undefined;
67
449
  };
68
- onError: (cb: (error: _meshflow_core.MeshErrorContext) => void) => () => void;
450
+ onError: (cb: (error: MeshErrorContext) => void) => () => void;
69
451
  onSuccess: (cb: (data: unknown) => void) => () => void;
70
452
  onStart: (cb: (data: {
71
453
  path: any;
72
454
  }) => void) => () => void;
73
455
  }, {}, P> : Engine<{
74
- SetRule: <K extends NM extends any ? keyof NM : never>(outDegreePath: P, inDegreePath: P, key: K, options: _meshflow_core.SetRuleOptions<NM>) => void;
75
- SetRules: <K extends NM extends any ? keyof NM : never>(outDegreePaths: P[], inDegreePath: P, key: K, options: _meshflow_core.SetRuleOptions<NM>) => void;
76
- SetStrategy: (path: P, key: NM extends any ? keyof NM : never, strategy: _meshflow_core.DefaultStrategy) => void;
456
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
457
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
458
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStrategy) => void;
77
459
  SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
78
460
  cancel: () => void;
79
461
  };
80
462
  usePlugin: (plugin: {
81
463
  apply: (api: {
82
- on: (event: keyof _meshflow_core.MeshEvents, cb: Function) => () => boolean;
464
+ on: (event: MeshEventName, cb: Function) => () => boolean;
83
465
  }) => void;
84
466
  }) => () => void;
85
467
  SetValue: (path: P, value: any) => void;
86
468
  GetValue: (path: P, key?: string) => any;
87
- GetGroupByPath: (path: MeshPath) => _meshflow_core.MeshFlowGroupNode<MeshPath> | undefined;
469
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
88
470
  notifyAll: () => Promise<void>;
89
471
  GetAllDependency: () => Map<P, Set<P>>;
90
472
  GetDependencyOrder: () => P[][];
91
- historyExports: Partial<{
92
- Undo: () => void;
93
- Redo: () => void;
94
- initCanUndo: any;
95
- initCanRedo: any;
96
- PushIntoHistory: (action: {
97
- undoAction: () => void;
98
- redoAction: () => void;
99
- }, cleanRedo?: boolean) => void;
100
- CreateHistoryAction: (metadata: [{
101
- path: string;
102
- value: any;
103
- }, {
104
- path: string;
105
- value: any;
106
- }], cb: any) => {
107
- undoAction: () => any;
108
- redoAction: () => any;
109
- };
110
- }>;
473
+ historyExports: Partial<MeshFlowHistory>;
111
474
  formExports: {};
112
475
  validatorExports: {
113
476
  SetValidators?: ((path: P, options: {
@@ -115,14 +478,15 @@ NM extends Record<string, any> = Record<string, any>>(id: MeshPath) => [M & {
115
478
  condition: (data: any) => boolean;
116
479
  }) => void) | undefined;
117
480
  };
118
- onError: (cb: (error: _meshflow_core.MeshErrorContext) => void) => () => void;
481
+ onError: (cb: (error: MeshErrorContext) => void) => () => void;
119
482
  onSuccess: (cb: (data: unknown) => void) => () => void;
120
483
  onStart: (cb: (data: {
121
484
  path: P;
122
485
  }) => void) => () => void;
123
486
  }, M & {
124
- internalForm: any;
125
- schemaValidators: any;
487
+ internalForm: typeof useInternalForm;
488
+ schemaValidators: typeof useSchemaValidators;
126
489
  }, P>;
490
+ declare const deleteEngine: (id: MeshPath) => void;
127
491
 
128
- export { useEngine, useMeshForm };
492
+ export { deleteEngine, useEngine, useMeshForm };
package/index.d.ts CHANGED
@@ -1,5 +1,406 @@
1
- import * as _meshflow_core from '@meshflow/core';
2
- import { MeshPath, Engine, InferLeafPath, SchedulerType } from '@meshflow/core';
1
+ import { MeshPath as MeshPath$1 } from '@meshflow/core';
2
+
3
+ type Unwrap<T> = T extends ReadonlyArray<infer U> ? U : T;
4
+ type InferLeafPath<T, Prefix extends string = ""> = Unwrap<T> extends infer Node ? Node extends {
5
+ readonly name: infer N;
6
+ } ? N extends string ? N extends "" ? Node extends {
7
+ readonly children: infer C;
8
+ } ? InferLeafPath<C, Prefix> : never : (Node extends {
9
+ readonly children: infer C;
10
+ } ? InferLeafPath<C, Prefix extends "" ? N : `${Prefix}.${N}`> : (Prefix extends "" ? N : `${Prefix}.${N}`)) : N extends number | symbol ? Node extends {
11
+ readonly children: infer C;
12
+ } ? InferLeafPath<C, Prefix> : N : never : never : never;
13
+ type KeysOfUnion<T> = T extends any ? keyof T : never;
14
+
15
+ interface MeshErrorContext {
16
+ path: string;
17
+ error: any;
18
+ }
19
+
20
+ type ContractType = 'boolean' | 'scalar' | 'array' | 'object';
21
+ declare enum DefaultStrategy {
22
+ OR = "OR",
23
+ PRIORITY = "PRIORITY"
24
+ }
25
+ declare class SchemaBucket<P> {
26
+ private path;
27
+ private strategy;
28
+ contract: ContractType;
29
+ private rules;
30
+ private isValue;
31
+ private id;
32
+ private cache;
33
+ private pendingPromise;
34
+ private version;
35
+ private deps;
36
+ private _forceNotify;
37
+ promiseToken: any;
38
+ private effectArray;
39
+ constructor(baseValue: any, key: string | number | symbol, path: P);
40
+ forceNotify(): void;
41
+ isForceNotify(): boolean;
42
+ setStrategy(type: DefaultStrategy): void;
43
+ setDefaultRule(value: any): void;
44
+ setRules(value: any, DepsArray?: Array<[P, any]>): () => void;
45
+ updateDeps(DepsArray: Array<[P, any]>): void;
46
+ setRule(value: any, DepsArray?: Array<[P, any]>): (() => void) | undefined;
47
+ setSideEffect(data: {
48
+ fn: (args: any[]) => any;
49
+ args: any[];
50
+ }): void;
51
+ getSideEffect(): {
52
+ fn: (args: any) => any;
53
+ args: any[];
54
+ }[];
55
+ evaluate(api: any): any;
56
+ private finalizeSync;
57
+ private inferType;
58
+ }
59
+
60
+ interface MeshEvents {
61
+ 'node:start': {
62
+ path: MeshPath;
63
+ };
64
+ 'node:success': {
65
+ path: MeshPath;
66
+ };
67
+ 'node:bucket:success': {
68
+ path: MeshPath;
69
+ key: string;
70
+ value: any;
71
+ };
72
+ 'node:error': {
73
+ path: MeshPath;
74
+ error: any;
75
+ };
76
+ 'node:intercept': {
77
+ path: MeshPath;
78
+ type: number;
79
+ detail?: any;
80
+ };
81
+ 'node:release': {
82
+ path: MeshPath;
83
+ type: number;
84
+ detail?: any;
85
+ };
86
+ 'node:stagnate': {
87
+ path: MeshPath;
88
+ type: number;
89
+ };
90
+ 'node:processing': {
91
+ path: MeshPath;
92
+ };
93
+ 'flow:wait': {
94
+ type: number;
95
+ detail?: any;
96
+ };
97
+ 'flow:fire': {
98
+ path: MeshPath;
99
+ type: number;
100
+ detail?: any;
101
+ };
102
+ 'flow:start': {
103
+ path: MeshPath;
104
+ };
105
+ 'flow:success': {
106
+ duration: string;
107
+ };
108
+ 'flow:end': {
109
+ type: number;
110
+ };
111
+ 'node:pending': {
112
+ path: MeshPath;
113
+ };
114
+ }
115
+ type MeshEventName = keyof MeshEvents;
116
+ type MeshEmit = <K extends MeshEventName>(event: K, data: MeshEvents[K]) => void;
117
+ type HistoryActionItem = {
118
+ undoAction: () => void;
119
+ redoAction: () => void;
120
+ };
121
+ type MeshFlowHistory = {
122
+ Undo: () => void;
123
+ Redo: () => void;
124
+ initCanUndo: any;
125
+ initCanRedo: any;
126
+ PushIntoHistory: (action: HistoryActionItem, cleanRedo?: boolean) => void;
127
+ CreateHistoryAction: (metadata: [
128
+ {
129
+ path: string;
130
+ value: any;
131
+ },
132
+ {
133
+ path: string;
134
+ value: any;
135
+ }
136
+ ], cb: any) => {
137
+ undoAction: () => any;
138
+ redoAction: () => any;
139
+ };
140
+ };
141
+ type MeshPath = string | number | symbol;
142
+ interface MeshBucket<P> {
143
+ evaluate: (context: any) => Promise<any> | any;
144
+ [key: string]: any;
145
+ }
146
+ interface MeshFlowTaskNode<P extends MeshPath = MeshPath, V = any, S = any> {
147
+ path: P;
148
+ uid: number;
149
+ type: string;
150
+ state: V;
151
+ nodeBucket: Record<keyof S, MeshBucket<P>>;
152
+ notifyKeys: Set<keyof S>;
153
+ dirtySignal: any;
154
+ proxy: any;
155
+ meta: S;
156
+ dependOn: (cb: (val: V) => V) => void;
157
+ createView: (extraProps?: Record<string, any>) => any;
158
+ }
159
+ interface MeshFlowGroupNode<P extends MeshPath = MeshPath> {
160
+ path: P;
161
+ uid: number;
162
+ type: 'group';
163
+ children: Array<P>;
164
+ dirtySignal: any;
165
+ meta: Record<string, any>;
166
+ }
167
+ interface logicApi {
168
+ slot: {
169
+ triggerTargets: any;
170
+ affectedTatget: any;
171
+ };
172
+ }
173
+ interface SetRuleOptions<NM> {
174
+ value?: any;
175
+ priority?: number;
176
+ forceNotify?: boolean;
177
+ logic: (api: logicApi) => any;
178
+ effect?: (args: any) => any;
179
+ effectArgs?: Array<KeysOfUnion<NM>>;
180
+ }
181
+
182
+ /**
183
+ * 🌟 入口函数
184
+ * @template T - UI 信号类型 (Signal)
185
+ * @template P - 路径联合类型 ("user.name" | "user.age") 也支持number或者symbol
186
+ * @template S - 业务元数据类型 (默认使用表单的 Meta,但也允许传入 any)
187
+ */
188
+ declare function useEngineInstance<T, P extends MeshPath, S = any, NM = any>(data: S, options: {
189
+ config: {
190
+ useGreedy: boolean;
191
+ };
192
+ UITrigger: {
193
+ signalCreator: () => T;
194
+ signalTrigger: (signal: T) => void;
195
+ };
196
+ modules: {
197
+ useHistory?: () => MeshFlowHistory;
198
+ useInternalForm?: <T, P>(scheduler: any, data: any) => any;
199
+ useSchemaValidators?: <P>(Finder: (path: P) => any) => {
200
+ SetValidators: (path: P, options: {
201
+ logic: (val: any, GetByPath: any) => any;
202
+ condition: (data: any) => boolean;
203
+ }) => void;
204
+ };
205
+ };
206
+ plugins: {};
207
+ }): {
208
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
209
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
210
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStrategy) => void;
211
+ SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
212
+ cancel: () => void;
213
+ };
214
+ usePlugin: (plugin: {
215
+ apply: (api: {
216
+ on: (event: MeshEventName, cb: Function) => () => boolean;
217
+ }) => void;
218
+ }) => () => void;
219
+ SetValue: (path: P, value: any) => void;
220
+ GetValue: (path: P, key?: string) => any;
221
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
222
+ notifyAll: () => Promise<void>;
223
+ GetAllDependency: () => Map<P, Set<P>>;
224
+ GetDependencyOrder: () => P[][];
225
+ historyExports: Partial<MeshFlowHistory>;
226
+ formExports: {};
227
+ validatorExports: {
228
+ SetValidators?: (path: P, options: {
229
+ logic: (val: any, GetByPath: any) => any;
230
+ condition: (data: any) => boolean;
231
+ }) => void;
232
+ };
233
+ onError: (cb: (error: MeshErrorContext) => void) => () => void;
234
+ onSuccess: (cb: (data: unknown) => void) => () => void;
235
+ onStart: (cb: (data: {
236
+ path: P;
237
+ }) => void) => () => void;
238
+ };
239
+
240
+ declare function useScheduler<T, //ui trigger中定义的类型
241
+ P extends MeshPath, // 路径类型
242
+ S = any>(schema: S, config: {
243
+ useGreedy: boolean;
244
+ }, dependency: {
245
+ GetDependencyOrder: () => P[][];
246
+ GetAllNextDependency: (path: P) => P[];
247
+ GetNextDependency: (path: P) => P[];
248
+ GetPrevDependency: (path: P) => P[];
249
+ GetAllPrevDependency: (path: P) => P[];
250
+ GetPathToLevelMap: () => Map<P, number>;
251
+ }, history: Partial<{
252
+ pushIntoHistory: any;
253
+ createHistoryAction: any;
254
+ }>, hooks: {
255
+ callOnError: any;
256
+ callOnSuccess: any;
257
+ callOnStart: any;
258
+ emit: MeshEmit;
259
+ }, UITrigger: {
260
+ signalCreator: () => T;
261
+ signalTrigger: (signal: T) => void;
262
+ }): {
263
+ registerNode: (nodeMeta: Omit<MeshFlowTaskNode<P>, "createView" | "proxy">) => MeshFlowTaskNode<P, any, any>;
264
+ registerGroupNode: (groupMeta: Omit<MeshFlowGroupNode<P>, "createView">) => MeshFlowGroupNode<P>;
265
+ GetNodeByPath: (path: P) => MeshFlowTaskNode<P, any, S>;
266
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
267
+ notify: (path: P) => void;
268
+ notifyAll: () => Promise<void>;
269
+ UITrigger: {
270
+ signalCreator: () => T;
271
+ signalTrigger: (signal: T) => void;
272
+ };
273
+ UidToNodeMap: Map<number, MeshFlowTaskNode<P, any, S>>;
274
+ };
275
+
276
+ type SchedulerType<T, P extends MeshPath, S, NM> = ReturnType<typeof useEngineInstance<T, P, S, NM>>;
277
+ type BaseEngine<T> = {
278
+ data: {
279
+ SetValue: T extends {
280
+ SetValue: infer F;
281
+ } ? F : never;
282
+ GetValue: T extends {
283
+ GetValue: infer F;
284
+ } ? F : never;
285
+ GetGroupByPath: T extends {
286
+ GetGroupByPath: infer F;
287
+ } ? F : never;
288
+ };
289
+ config: {
290
+ SetRule: T extends {
291
+ SetRule: infer F;
292
+ } ? F : never;
293
+ SetRules: T extends {
294
+ SetRules: infer F;
295
+ } ? F : never;
296
+ SetStrategy: T extends {
297
+ SetStrategy: infer F;
298
+ } ? F : never;
299
+ notifyAll: T extends {
300
+ notifyAll: infer F;
301
+ } ? F : never;
302
+ SetTrace: T extends {
303
+ SetTrace: infer F;
304
+ } ? F : never;
305
+ usePlugin: T extends {
306
+ usePlugin: infer F;
307
+ } ? F : never;
308
+ };
309
+ dependency: {
310
+ GetAllDependency: T extends {
311
+ GetAllDependency: infer F;
312
+ } ? F : never;
313
+ GetDependencyOrder: T extends {
314
+ GetDependencyOrder: infer F;
315
+ } ? F : never;
316
+ };
317
+ hooks: {
318
+ onError: T extends {
319
+ onError: infer F;
320
+ } ? F : never;
321
+ onSuccess: T extends {
322
+ onSuccess: infer F;
323
+ } ? F : never;
324
+ onStart: T extends {
325
+ onStart: infer F;
326
+ } ? F : never;
327
+ };
328
+ };
329
+ type TransformModuleKey<T> = T extends `use${infer Rest}` ? Uncapitalize<Rest> : T;
330
+ type MapModuleToReturn<K, F, P extends MeshPath> = K extends 'useSchemaValidators' | 'schemaValidators' ? {
331
+ SetValidators: (path: P, options: {
332
+ logic: (val: any, GetByPath: (path: P) => any) => any;
333
+ condition: (data: any) => boolean;
334
+ }) => void;
335
+ } : F extends (...args: any) => infer R ? R : any;
336
+ type EngineModules<M, P extends MeshPath> = {
337
+ [K in keyof M as TransformModuleKey<string & K>]: MapModuleToReturn<K, M[K], P>;
338
+ };
339
+ type Engine<T, M, P extends MeshPath> = BaseEngine<T> & EngineModules<M, P>;
340
+
341
+ type FinalFlatten<T> = T extends infer O ? {
342
+ [K in keyof O]: O[K];
343
+ } : never;
344
+ type BaseField = {
345
+ label: string;
346
+ name: string;
347
+ placeholder?: string;
348
+ disabled: boolean;
349
+ readonly: boolean;
350
+ hidden?: boolean;
351
+ validators?: any;
352
+ theme?: string;
353
+ };
354
+ type InputField = BaseField & {
355
+ type: "input" | "number";
356
+ required: boolean;
357
+ min?: number;
358
+ maxLength: number;
359
+ value: string | number;
360
+ };
361
+ type CheckboxField = BaseField & {
362
+ type: "checkbox";
363
+ description?: string;
364
+ required: boolean;
365
+ value: boolean;
366
+ };
367
+ type SelectField = BaseField & {
368
+ type: "select";
369
+ required: boolean;
370
+ options: {
371
+ label: string;
372
+ value: any;
373
+ }[];
374
+ value: any;
375
+ };
376
+ type GroupField = Omit<BaseField, "label" | "name" | "placeholder" | "validators"> & {
377
+ type: "group";
378
+ name?: string;
379
+ children: FormFieldSchema[];
380
+ };
381
+ type FormFieldSchema = InputField | CheckboxField | SelectField | GroupField;
382
+ type RenderSchemaExtraCommonType<P = any> = {
383
+ path: P;
384
+ dirtySignal: any;
385
+ uid: number;
386
+ nodeBucket: Record<string, SchemaBucket<P>>;
387
+ dependOn: (cb: (...args: any) => void) => void;
388
+ };
389
+ type RenderSchemaFn<T> = FinalFlatten<T extends GroupField ? Omit<T, "children"> & RenderSchemaExtraCommonType & {
390
+ children: Array<RenderSchemaFn<FormFieldSchema>>;
391
+ } : T & RenderSchemaExtraCommonType>;
392
+ type RenderSchema = RenderSchemaFn<FormFieldSchema>;
393
+ declare function useInternalForm<T, P extends MeshPath>(scheduler: ReturnType<typeof useScheduler<T, P>>, rootSchema: any): {
394
+ uiSchema: RenderSchema;
395
+ GetFormData: () => any;
396
+ };
397
+
398
+ declare const useSchemaValidators: <P extends MeshPath$1>(Finder: (path: P) => any) => {
399
+ SetValidators: (path: P, options: {
400
+ logic: (val: any, GetByPath: any) => any;
401
+ condition: (data: any) => boolean;
402
+ }) => void;
403
+ };
3
404
 
4
405
  /**
5
406
  * NM: NodeMeta 的类型定义
@@ -18,46 +419,27 @@ declare function useMeshForm<const S extends Record<string, any>, NM extends Rec
18
419
  }): Engine<SchedulerType<T, P, S, NM>, M, P>;
19
420
  declare const useEngine: <M extends Record<string, any> = {}, P extends string = any, // 如果 Core 里叫 MeshPath,这里可以写成 extends MeshPath
20
421
  NM extends Record<string, any> = Record<string, any>>(id: MeshPath) => [M & {
21
- internalForm: any;
22
- schemaValidators: any;
422
+ internalForm: typeof useInternalForm;
423
+ schemaValidators: typeof useSchemaValidators;
23
424
  }] extends [never] ? Engine<{
24
- SetRule: <K extends string | number | symbol>(outDegreePath: any, inDegreePath: any, key: K, options: _meshflow_core.SetRuleOptions<any>) => void;
25
- SetRules: <K extends string | number | symbol>(outDegreePaths: any[], inDegreePath: any, key: K, options: _meshflow_core.SetRuleOptions<any>) => void;
26
- SetStrategy: (path: any, key: string | number | symbol, strategy: _meshflow_core.DefaultStrategy) => void;
425
+ SetRule: <K extends string | number | symbol>(outDegreePath: any, inDegreePath: any, key: K, options: SetRuleOptions<any>) => void;
426
+ SetRules: <K extends string | number | symbol>(outDegreePaths: any[], inDegreePath: any, key: K, options: SetRuleOptions<any>) => void;
427
+ SetStrategy: (path: any, key: string | number | symbol, strategy: DefaultStrategy) => void;
27
428
  SetTrace: (myPath: any, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
28
429
  cancel: () => void;
29
430
  };
30
431
  usePlugin: (plugin: {
31
432
  apply: (api: {
32
- on: (event: keyof _meshflow_core.MeshEvents, cb: Function) => () => boolean;
433
+ on: (event: MeshEventName, cb: Function) => () => boolean;
33
434
  }) => void;
34
435
  }) => () => void;
35
436
  SetValue: (path: any, value: any) => void;
36
437
  GetValue: (path: any, key?: string) => any;
37
- GetGroupByPath: (path: MeshPath) => _meshflow_core.MeshFlowGroupNode<MeshPath> | undefined;
438
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
38
439
  notifyAll: () => Promise<void>;
39
440
  GetAllDependency: () => Map<any, Set<any>>;
40
441
  GetDependencyOrder: () => any[][];
41
- historyExports: Partial<{
42
- Undo: () => void;
43
- Redo: () => void;
44
- initCanUndo: any;
45
- initCanRedo: any;
46
- PushIntoHistory: (action: {
47
- undoAction: () => void;
48
- redoAction: () => void;
49
- }, cleanRedo?: boolean) => void;
50
- CreateHistoryAction: (metadata: [{
51
- path: string;
52
- value: any;
53
- }, {
54
- path: string;
55
- value: any;
56
- }], cb: any) => {
57
- undoAction: () => any;
58
- redoAction: () => any;
59
- };
60
- }>;
442
+ historyExports: Partial<MeshFlowHistory>;
61
443
  formExports: {};
62
444
  validatorExports: {
63
445
  SetValidators?: ((path: any, options: {
@@ -65,49 +447,30 @@ NM extends Record<string, any> = Record<string, any>>(id: MeshPath) => [M & {
65
447
  condition: (data: any) => boolean;
66
448
  }) => void) | undefined;
67
449
  };
68
- onError: (cb: (error: _meshflow_core.MeshErrorContext) => void) => () => void;
450
+ onError: (cb: (error: MeshErrorContext) => void) => () => void;
69
451
  onSuccess: (cb: (data: unknown) => void) => () => void;
70
452
  onStart: (cb: (data: {
71
453
  path: any;
72
454
  }) => void) => () => void;
73
455
  }, {}, P> : Engine<{
74
- SetRule: <K extends NM extends any ? keyof NM : never>(outDegreePath: P, inDegreePath: P, key: K, options: _meshflow_core.SetRuleOptions<NM>) => void;
75
- SetRules: <K extends NM extends any ? keyof NM : never>(outDegreePaths: P[], inDegreePath: P, key: K, options: _meshflow_core.SetRuleOptions<NM>) => void;
76
- SetStrategy: (path: P, key: NM extends any ? keyof NM : never, strategy: _meshflow_core.DefaultStrategy) => void;
456
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
457
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
458
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStrategy) => void;
77
459
  SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
78
460
  cancel: () => void;
79
461
  };
80
462
  usePlugin: (plugin: {
81
463
  apply: (api: {
82
- on: (event: keyof _meshflow_core.MeshEvents, cb: Function) => () => boolean;
464
+ on: (event: MeshEventName, cb: Function) => () => boolean;
83
465
  }) => void;
84
466
  }) => () => void;
85
467
  SetValue: (path: P, value: any) => void;
86
468
  GetValue: (path: P, key?: string) => any;
87
- GetGroupByPath: (path: MeshPath) => _meshflow_core.MeshFlowGroupNode<MeshPath> | undefined;
469
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
88
470
  notifyAll: () => Promise<void>;
89
471
  GetAllDependency: () => Map<P, Set<P>>;
90
472
  GetDependencyOrder: () => P[][];
91
- historyExports: Partial<{
92
- Undo: () => void;
93
- Redo: () => void;
94
- initCanUndo: any;
95
- initCanRedo: any;
96
- PushIntoHistory: (action: {
97
- undoAction: () => void;
98
- redoAction: () => void;
99
- }, cleanRedo?: boolean) => void;
100
- CreateHistoryAction: (metadata: [{
101
- path: string;
102
- value: any;
103
- }, {
104
- path: string;
105
- value: any;
106
- }], cb: any) => {
107
- undoAction: () => any;
108
- redoAction: () => any;
109
- };
110
- }>;
473
+ historyExports: Partial<MeshFlowHistory>;
111
474
  formExports: {};
112
475
  validatorExports: {
113
476
  SetValidators?: ((path: P, options: {
@@ -115,14 +478,15 @@ NM extends Record<string, any> = Record<string, any>>(id: MeshPath) => [M & {
115
478
  condition: (data: any) => boolean;
116
479
  }) => void) | undefined;
117
480
  };
118
- onError: (cb: (error: _meshflow_core.MeshErrorContext) => void) => () => void;
481
+ onError: (cb: (error: MeshErrorContext) => void) => () => void;
119
482
  onSuccess: (cb: (data: unknown) => void) => () => void;
120
483
  onStart: (cb: (data: {
121
484
  path: P;
122
485
  }) => void) => () => void;
123
486
  }, M & {
124
- internalForm: any;
125
- schemaValidators: any;
487
+ internalForm: typeof useInternalForm;
488
+ schemaValidators: typeof useSchemaValidators;
126
489
  }, P>;
490
+ declare const deleteEngine: (id: MeshPath) => void;
127
491
 
128
- export { useEngine, useMeshForm };
492
+ export { deleteEngine, useEngine, useMeshForm };
package/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var core=require('@meshflow/core');function T(o,l){let d=p(l),c=(e,r="")=>{let a="name"in e?e.name:void 0,t=a?r===""?a:`${r}.${a}`:r,y=o.UITrigger.signalCreator();if(e.type==="group"){let h=e,x=h.children.map(g=>c(g,t)),S={...h,type:"group",path:t,dirtySignal:y,uid:0,children:x},P=o.registerGroupNode({path:t,type:"group",uid:0,dirtySignal:y,children:x.map(g=>g.path),meta:h});return S.uid=P.uid,S}let n={},i={value:e.value},s=o.registerNode({path:t,type:e.type,uid:0,state:i,meta:e,nodeBucket:n,notifyKeys:new Set,dirtySignal:y,dependOn:null});return s.createView({path:t,type:e.type,dependOn:s.dependOn,nodeBucket:s.nodeBucket})};function p(e,r={}){let a=n=>{if(n.type=="group")return {key:n.name||"",isGroup:true,val:n.children.reduce((i,s)=>[...i,a(s)],[])};if(n.type=="input"||n.type=="number"||n.type=="select"||n.type=="checkbox")return {key:n.name,isGroup:false,val:n.value};throw Error(`undefined type:${n.type}`)},t=(n,i)=>{if(i.isGroup){let s={};i.key===""?s=n:n[i.key]=s,i.val.forEach(f=>{t(s,f);});}else n[i.key]=i.val;},y=a(e);return t(r,y),r}let u=()=>{let e=(r,a,t)=>{if(typeof r!="object"||r===null||Array.isArray(r)){if(t.length>0){let n=t[t.length-1];a[n]=o.GetNodeByPath(t.join(".")).state.value;}return}let y=Object.getOwnPropertyNames(r);for(let n of y)t.push(n),e(r[n],r,t),t.pop();};return e(d,null,[]),d},m=()=>u();return {uiSchema:c(l),GetFormData:m}}var v=o=>{let l=o;return {SetValidators:(c,p)=>{let u=l(c),m=(e,r,a)=>e(r,a),F=(e,r,a)=>e(r,a);if(!u.validators)throw Error("validator init error");u.validators.setValidators({logic:e=>m(p.logic,e,l),condition:typeof p.condition=="function"?e=>F(p.condition,e,l):()=>true});}}};function B(o,l,d){return core.useMeshFlow(o,l,{config:{useGreedy:d.config?.useGreedy??false},UITrigger:d.UITrigger,metaType:{},modules:{useInternalForm:T,useSchemaValidators:v,...d.modules}})}var I=o=>core.useEngine(o);exports.useEngine=I;exports.useMeshForm=B;
1
+ 'use strict';var Z=class{computedRules=[];store={OR:(e,n)=>{let t,c,s=this.computedRules;for(let d=0;d<s.length;d++){let l=s[d],r=l.logic(e);if(r instanceof Promise)return (async()=>{let a=await r;if(l.entityId==="__base__"?c=a:a&&(t=a),typeof t>"u")for(let i=d+1;i<s.length;i++){let y=s[i],f=y.logic(e),h=f instanceof Promise?await f:f;if(y.entityId==="__base__"){c=h;continue}if(h){t=y.value;break}}return typeof t>"u"&&(t=c),{res:t,version:n}})();let u=r;if(l.entityId==="__base__"){c=u;continue}if(u){t=l.value;break}}return typeof t>"u"&&(t=c),{res:t,version:n}},PRIORITY:(e,n)=>{let t,c=this.computedRules;for(let s=0;s<c.length;s++){let l=c[s].logic(e);if(l instanceof Promise)return (async()=>{let r=await l;if(r!==void 0)return {res:r,version:n};for(let u=s+1;u<c.length;u++){let a=c[u].logic(e),i=a instanceof Promise?await a:a;if(i!==void 0)return {res:i,version:n}}return {res:void 0,version:n}})();if(l!==void 0)return {res:l,version:n}}return {res:t,version:n}}};CurrentStrategy=()=>{};CurrentStrategyType="PRIORITY";getRules=()=>{};constructor(e){this.getRules=e,this.CurrentStrategy=this.store.PRIORITY,this.updateComputedRules();}updateComputedRules(){let e=this.getRules();this.CurrentStrategyType==="PRIORITY"?this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat().sort((n,t)=>t.priority-n.priority):this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat();}setStrategy(e){this.CurrentStrategy=this.store[e],this.updateComputedRules();}evaluate(e,n){return this.CurrentStrategy(e,n)}},X=class{path;strategy;contract;rules=new Map;isValue=false;id=0;cache=void 0;pendingPromise=null;version=0;deps=new Map;_forceNotify=false;promiseToken=null;effectArray=[];constructor(e,n,t){let c=()=>this.rules;this.strategy=new Z(c),this.path=t,this.isValue=n==="value",this.contract=this.inferType(e),this.cache=e,this.setRule({priority:0,entityId:"__base__",logic:()=>e});}forceNotify(){this._forceNotify=true;}isForceNotify(){return this._forceNotify}setStrategy(e){this.strategy.setStrategy(e);}setDefaultRule(e){let n=new Set;n.add(e),this.rules.set("defaultRules",n);}setRules(e,n){n&&this.updateDeps(n);let t=++this.id,c={...e,entityId:t};for(let s of e.triggerPaths)this.rules.has(s)||this.rules.set(s,new Set),this.rules.get(s).add(c);return this.strategy.updateComputedRules(),()=>{for(let s of e.triggerPaths){let d=this.rules.get(s);d&&(d.delete(c),d.size===0&&(this.rules.delete(s),this.deps.delete(s)));}this.strategy.updateComputedRules();}}updateDeps(e){for(let[n,t]of e)this.deps.set(n,t);}setRule(e,n){if(n&&this.updateDeps(n),typeof e.entityId=="string"){this.setDefaultRule(e);return}let t=++this.id,c={...e,entityId:t};if(e)for(let s of e.triggerPaths)this.rules.has(s)||this.rules.set(s,new Set),this.rules.get(s).add(c);return this.strategy.updateComputedRules(),()=>{for(let s of e.triggerPaths){let d=this.rules.get(s);d&&(d.delete(c),d.size===0&&(this.rules.delete(s),this.deps.delete(s)));}this.strategy.updateComputedRules();}}setSideEffect(e){this.effectArray.push(e);}getSideEffect(){return [...this.effectArray]}evaluate(e){let n=null;if(e.GetToken&&(n=e.GetToken()),this.pendingPromise&&this.promiseToken!==n&&(this.pendingPromise=null,this.promiseToken=null),this.pendingPromise)return this.pendingPromise;let t=false;if(typeof e.triggerPath=="string"){t=true;let d=this.deps.get(e.triggerPath),l=e.GetValueByPath(e.triggerPath);if(typeof d=="object"||typeof l=="object")t=false;else {let r=Array.from(this.deps.keys());for(let u of r){let a=this.deps.get(u),i=e.GetValueByPath(u);if(a!==i){t=false;break}}}}if(t)return this.cache;this.promiseToken=n;let c=++this.version,s=this.strategy.evaluate(e,c);if(!(s instanceof Promise)){let{res:d,version:l}=s;return this.finalizeSync(d,l,e,n)}return this.pendingPromise=(async()=>{try{let{res:d,version:l}=await s;return this.finalizeSync(d,l,e,n)}catch(d){throw {path:this.path,error:d}}finally{this.promiseToken===n&&(this.pendingPromise=null,this.promiseToken=null);}})(),this.pendingPromise}finalizeSync(e,n,t,c){return c!==this.promiseToken||n<this.version?this.cache:(this.cache=e,this.deps.forEach((s,d)=>{this.deps.set(d,t.GetValueByPath(d));}),e)}inferType(e){return Array.isArray(e)?"array":typeof e}};var te=(o,e,n)=>{let c=s=>{let d=n.triggerPaths.map(u=>s.GetValueByPath(u).value),l=Object.create(null);return Object.defineProperty(l,"triggerTargets",{get:()=>d||[]}),Object.defineProperty(l,"affectedTatget",{get:()=>s.GetRenderSchemaByPath(o)[e]}),n.logic({slot:l})};return {value:n.value,targetPath:o,triggerPaths:n.triggerPaths,priority:n.priority??10,logic:c}},ne=(o,e,n,t)=>{if(!o)throw Error("");let c=o,s=(r,u)=>{e.has(r)||e.set(r,new Set),e.get(r).add(u),n.has(u)||n.set(u,new Set),n.get(u).add(r);};return {SetRule:(r,u,a,i={logic:()=>{}})=>{let y=c(u),f=te(u,a,{...i,triggerPaths:[r]}),h=[r].map(p=>[p,c(p).state.value]);if(s(r,u),y.nodeBucket[a])y.nodeBucket[a].setRule(f,h),i.effect&&y.nodeBucket[a].setSideEffect({fn:i.effect,args:i.effectArgs?i.effectArgs:[a]});else {let p=y.meta[a],P=new X(p,a,u);P.setRule(f,h),i.effect&&P.setSideEffect({fn:i.effect,args:i.effectArgs?i.effectArgs:[a]}),y.nodeBucket[a]=P;}y.state[a]=y.meta[a],i.forceNotify&&y.nodeBucket[a].forceNotify();},SetRules:(r,u,a,i={logic:()=>{}})=>{let y=c(u);for(let p of r)s(p,u);let f=te(u,a,{...i,triggerPaths:r}),h=r.map(p=>[p,c(p).state.value]);if(y.nodeBucket[a])y.nodeBucket[a].setRules(f,h),i.effect&&y.nodeBucket[a].setSideEffect({fn:i.effect,args:i.effectArgs?i.effectArgs:[a]});else {let p=y.meta[a],P=new X(p,a,u);P.setRules(f,h),i.effect&&P.setSideEffect({fn:i.effect,args:i.effectArgs?i.effectArgs:[a]}),y.nodeBucket[a]=P;}y.state[a]=y.meta[a],i.forceNotify&&y.nodeBucket[a].forceNotify();}}};var re=o=>{let e=o||void 0;if(!e)throw Error("");return {SetStrategy:(t,c,s)=>{e(t).nodeBucket[c].setStrategy(s);}}};function se(){let o=new Map,e=new Map,n=new Set,t=(d,l)=>{o.set(d,l);let r=e.get(d);r&&r(l);};return {SetTrace:(d,l)=>{e.set(d,l);let r=o.get(d)||"idle";return l(r),{cancel:()=>{e.delete(d);}}},useTrace:()=>({apply:l=>{l.on("flow:start",()=>{n.forEach(r=>t(r,"idle")),n.clear(),o.clear();}),l.on("node:release",({path:r,type:u})=>{(u==1||u==2)&&(n.add(r),t(r,"pending"));}),l.on("node:pending",({path:r})=>{n.add(r),(!o.has(r)||o.get(r)==="idle")&&t(r,"pending");}),l.on("node:start",({path:r})=>{n.add(r),t(r,"calculating");}),l.on("node:success",({path:r})=>{t(r,"calculated");}),l.on("node:intercept",({path:r,type:u})=>{u==3&&t(r,"calculating"),u==6&&t(r,"idle");}),l.on("node:stagnate",({path:r})=>{t(r,"pending");}),l.on("node:error",({path:r})=>t(r,"error"));}})}}function ae(o,e,n,t){let c=a=>{let i=o(),y=e(),f=new Set;return i.get(a)?.forEach(h=>f.add(h)),f.size===0?[]:Array.from(f).filter(h=>{let p=y.get(h)||new Set;return !Array.from(p).some(v=>f.has(v))})};return {GetNextDependency:a=>{let i=t();return Array.from(i.get(a)||[])},GetPrevDependency:a=>{let i=n();return Array.from(i.get(a)||[])},GetAllPrevDependency:a=>{let i=e();return Array.from(i.get(a)||[])},GetAllNextDependency:a=>{let i=o();return Array.from(i.get(a)||[])},rebuildDirectDependencyMaps:a=>{let i=new Map,y=new Map;for(let f of a){let h=c(f);i.set(f,new Set(h));for(let p of h)y.has(p)||y.set(p,new Set),y.get(p).add(f);}return {directNextMap:i,directPrevMap:y}}}}function oe(o){let e=t=>{let c=[],s=[],d=new Map,l=t.size,r=0,u=0;for(let[a,i]of t)i===0&&s.push(a);if(s.length===0&&l>0)throw Error("Circular dependency detected");for(;s.length>0;){c.push([...s]);let a=[];for(let i of s){r++,d.set(i,u);let y=o.get(i);if(y)for(let f of y){let h=t.get(f)-1;t.set(f,h),h===0&&a.push(f);}}s=a,u++;}if(r<l)throw Error("Circular dependency detected");return {steps:c,levelMap:d}};return ()=>{let t=new Map;for(let c of o.keys()){let s=Array.from(o.get(c)||[]);t.has(c)||t.set(c,0);for(let d of s){let l=t.get(d)||0;t.set(d,++l);}}return e(t)}}var q=()=>{let o=[];return {on:e=>(o.push(e),()=>{let n=o.indexOf(e);n>-1&&o.splice(n,1);}),call:e=>o.forEach(n=>{n(e);})}};function ie(){let{on:o,call:e}=q();return {onError:o,callOnError:e}}function le(){let{on:o,call:e}=q();return {onSuccess:o,callOnSuccess:e}}var ce=()=>{let o=new Set,e=new Map,n=(s,d)=>{e.get(s)?.forEach(l=>l(d));},t=(s,d)=>(e.has(s)||e.set(s,new Set),e.get(s).add(d),()=>e.get(s).delete(d));return {usePlugin:s=>{let d=new Set,l=(r,u)=>{let a=t(r,u);return d.add(a),a};return s.apply({on:l}),o.add(s),()=>{d.forEach(r=>r()),d.clear(),o.delete(s);}},emit:n}};function ue(){let{on:o,call:e}=q();return {onStart:o,callOnStart:e}}var de=(o={frameQuota:12})=>{let e=performance.now(),n=0,t=false,c=()=>!!navigator?.scheduling?.isInputPending?.({includeContinuous:true});return {getIsFirstFrame:()=>t,reset(){e=performance.now(),n=0,t=true;},shouldYield(){let s=performance.now();return n++,!!((n>=5||t)&&(n=0,s-e>o.frameQuota||c()))},async yieldToMain(){return new Promise(s=>{Me(()=>{e=performance.now(),n=0,t&&(t=false),s();});})}}},Me=o=>{let{port1:e,port2:n}=new MessageChannel;e.onmessage=o,n.postMessage(null);};function fe(o,e,n,t,c){let s=new Map,d=o.useGreedy,l=de();return async(u,a)=>{let y=Symbol("token"),f=u||"__NOTIFY_ALL__";s.set(f,y);let h=false;l.reset();let p=new Set,P=new Set,C=new Set;a.forEach(I=>{C.add(I),e.GetAllNextDependency(I).forEach(F=>C.add(F));});let v=new Map,A=new Map,x=new Set,k=e.GetPathToLevelMap(),E=0,z=0,H=I=>{e.GetAllNextDependency(I).forEach($=>{let G=k.get($)||0;G>z&&(z=G);});};u?(E=k.get(u)??0,H(u),p.add(u)):a.forEach(I=>H(I)),a.forEach(I=>{x.add(I);});let g=performance.now();t.emit("flow:start",{path:f}),t.callOnStart({path:f});let R=false,O=30,Q=I=>{let{target:F,trigger:$}=I,G=false,B=false,V=n.GetNodeByPath(F),W=[],N=(m,T)=>{if(p.has(m)||P.has(m)||x.has(m))return;let _=0,M=k.get(m)??0;if(v.has(m))_=v.get(m)-1;else {if(M>E&&v.size>O){A.has(M)||A.set(M,new Set),A.get(M).add(m),t.emit("node:intercept",{path:m,type:7});return}let D=e.GetPrevDependency(m),S=0;for(let b of D){if(p.has(b))continue;(k.get(b)??0)>E&&S++;}_=S;}if(_<=0){let D=x.has(m),S=P.has(m);if(D||S){t.emit("node:intercept",{path:m,type:S?3:3.1});return}v.delete(m),x.add(m),t.emit("node:release",{path:m,type:T,detail:{path:F}});}else v.set(m,_);},L=(m=[])=>{if(s.get(f)!==y)return;if(m.length){let M={},D=V.proxy;for(let S of m){let b=(S.args||[]).reduce((K,Y)=>(K[Y]=D[Y],K),{});try{let K=S.fn(b);K&&typeof K=="object"&&Object.assign(M,K);}catch(K){}}for(let S in M)if(S in V.state)V.state[S]=M[S];else throw {error:`wrong effect in ${String(V.path)}`};G=true;}G&&c.flushPathSet.add(F),t.emit("node:success",{path:F}),p.add(F);let T=e.GetNextDependency(F);(G||B)&&e.GetAllNextDependency(F).forEach(D=>C.add(D));for(let M of T){if(p.has(M)){t.emit("node:intercept",{path:M,type:2});continue}if(P.has(M)||x.has(M)){t.emit("node:intercept",{path:M,type:P.has(M)?3:3.1});continue}if(G||B)N(M,1);else if(v.has(M))N(M,2);else {let S=k.get(M);A.has(S)||A.set(S,new Set);let b=A.get(S);b.has(M)||(b.add(M),t.emit("node:stagnate",{path:M,type:1}));}}P.delete(F),(async()=>{if(!h){let M=P.size,D=x.size;t.emit("flow:fire",{path:F,type:1,detail:{active:M,pending:D,blocked:v.size}}),j();}})();},U=m=>{t.emit("node:error",{path:F,error:m});let T=Symbol("abort");s.set(f,T),x.clear(),v.clear(),P.clear(),t.callOnError(m);},w=(m,T)=>{let _=false;m!==V.state[T]&&(V.state[T]=m,G=true,t.emit("node:bucket:success",{path:F,key:String(T),value:m}),V.notifyKeys.has(T)&&(_=true)),V.nodeBucket[T].isForceNotify()&&(B=true),(_||B)&&H(F);};t.emit("node:start",{path:F});try{let m=[];for(let T in V.nodeBucket){let _=V.nodeBucket[T];m.push(..._.getSideEffect());let M=_.evaluate({affectKey:T,triggerPath:$,GetRenderSchemaByPath:D=>n.GetNodeByPath(D).proxy,GetValueByPath:D=>n.GetNodeByPath(D).state,GetToken:()=>y});if(M instanceof Promise){let D=M.then(S=>{s.get(f)===y&&w(S,T);});W.push(D);}else w(M,T);}if(W.length>0)return Promise.all(W).then(()=>{L(m);}).catch(U);L(m);return}catch(m){U(m);}},j=async()=>{if(s.get(f)!==y){h=false;return}h=true;let I=l.getIsFirstFrame(),F=0,$=()=>d&&I?30:1/0,G=0,B=$();try{for(;s.get(f)===y;){let V=G>=B,W=l.shouldYield();if(V||W){if(G>0&&(F++,(I||F%2===0)&&c.requestUpdate()),await l.yieldToMain(),s.get(f)!==y)break;G=0,I=l.getIsFirstFrame();}if(x.size>0&&P.size<5){for(let N of x){if(P.size>=5||G>=B)break;let L=k.get(N)??0,U=e.GetPrevDependency(N),w=U.length>1;if((!d||w)&&L>E){x.delete(N);let T=U.filter(_=>C.has(_)&&!p.has(_)).length;v.set(N,T||0),t.emit("node:intercept",{path:N,type:T>0?4:5,detail:{targetLevel:L,currentLevel:E,pendingParentsCount:T}});continue}if(x.delete(N),P.add(N),t.emit("node:processing",{path:N}),Q({target:N,trigger:u}),G++,G>=B||l.shouldYield())break}if(x.size>0)continue}if(G<B&&d&&v.size>0&&P.size<5){let N=!1,L=0;for(let[U,w]of v)if(w<=0){let m=k.get(U)??0,T=e.GetPrevDependency(U);if(m>E&&T.length>1)continue;if(v.delete(U),x.add(U),L++,N=!0,t.emit("node:release",{path:U,type:4}),L>=B)break}if(L>0)continue;if(N){if(l.shouldYield()&&(await l.yieldToMain(),s.get(f)!==y))break;continue}}if(P.size===0&&x.size===0){let N=new Set;for(let w of A.keys())N.add(w);for(let[w]of v){let m=k.get(w)??0;m>E&&N.add(m);}let L=Array.from(N).sort((w,m)=>w-m),U=L[0];if(L.length>0&&U<=z){let w=L[0];if(w<=z){E=w;let m=A.get(w);m&&(m.forEach(T=>x.add(T)),A.delete(w));for(let[T]of v)(k.get(T)??0)===w&&(v.delete(T),x.add(T),t.emit("node:release",{path:T,type:3,detail:{level:w}}));continue}}else {A.forEach((w,m)=>{w.forEach(T=>{p.add(T),t.emit("node:intercept",{path:T,type:6});});}),A.clear();for(let[w]of v)p.add(w),t.emit("node:intercept",{path:w,type:6});v.clear();break}}x.size>0&&P.size>=5&&t.emit("flow:wait",{type:2});break}}finally{if(h=false,P.size+v.size+x.size===0){if(s.get(f)===y&&!R){R=true,t.emit("flow:end",{type:1}),c.requestUpdate();let W=performance.now();t.emit("flow:success",{duration:(W-g).toFixed(2)+"ms"}),Promise.resolve().then(()=>{t.callOnSuccess();});}}else t.emit("flow:wait",{type:1,detail:{nums:P.size}});}};j();}}function ee(o){let{path:e,uid:n,type:t,meta:c,dirtySignal:s,triggerUI:d,state:l}=o,r=null,a={path:e,uid:n,type:t,meta:c,dirtySignal:s,createView:(i={})=>{let y=new Proxy(i,{get(f,h){let p=h;return p in o.state?o.state[p]:p in o?o[p]:c&&p in c?c[p]:Reflect.get(f,h)},set(f,h,p){let P=h;return P in o.state?(o.state[P]=p,true):Reflect.set(f,h,p)},ownKeys(f){let h=new Set([...Reflect.ownKeys(f),...Object.keys(l||{}),...Object.keys(c||{})]);return Array.from(h)},getOwnPropertyDescriptor(f,h){return l&&h in l||c&&h in c?{enumerable:true,configurable:true}:Reflect.getOwnPropertyDescriptor(f,h)}});return r=y,y}};return "children"in o?{...a,children:o.children}:{...a,state:o.state,nodeBucket:o.nodeBucket,notifyKeys:o.notifyKeys,dependOn:o.dependOn,get proxy(){return r}}}function ye(o,e,n,t,c,s){let d=0,l=new Map,r=new Map,u=new Map,a=false,i=new Set,p=async()=>{let g=Array.from(i);i.clear();for(let R of g){let O=x(R);s.signalTrigger(O.dirtySignal);}},P=()=>{a||(a=true,requestAnimationFrame(()=>{try{for(;i.size>0;)p();}finally{a=false;}}));},C=fe({useGreedy:e.useGreedy},n,{GetNodeByPath:x},c,{requestUpdate:P,flushPathSet:i}),v=g=>{if(l.has(g.path))throw new Error(`[MeshFlow] Duplicate Path: ${String(g.path)}`);let R=++d,O={path:g.path,getNode:I=>x(I)},Q=I=>{let F=I({...O}),$=x(g.path);if(t.createHistoryAction&&t.pushIntoHistory){let G=t.createHistoryAction([{path:g.path,value:$.state.value},{path:g.path,value:F}],B=>{let V=x(B.path);V.state.value=B.value,E(B.path);});t.pushIntoHistory(G);}$.state.value=F,E(g.path);};g.notifyKeys.size==0&&g.notifyKeys.add("value");let j=ee({uid:R,path:g.path,state:g.state,meta:g.meta,nodeBucket:g.nodeBucket,dirtySignal:g.dirtySignal,notifyKeys:g.notifyKeys,dependOn:Q});return l.set(j.path,R),r.set(R,j),j},A=g=>{if(l.has(g.path))throw new Error(`[MeshFlow] Duplicate Path: ${String(g.path)}`);let R=++d,O=ee({uid:R,path:g.path,state:{},meta:g,nodeBucket:{},children:g.children});return l.set(O.path,R),u.set(R,O),O};function x(g){let R=l.get(g),O=r.get(R);if(!O)throw Error("wrong ID");return O}function k(g){let R=l.get(g);return u.get(R)}let E=g=>{if(!x(g))throw Error("Node undefined");i.add(g),P();let O=n.GetNextDependency(g);z(O,g);};function z(g,R){C(R,g);}return {registerNode:v,registerGroupNode:A,GetNodeByPath:x,GetGroupByPath:k,notify:E,notifyAll:async()=>{Promise.resolve().then(async()=>{let g=n.GetDependencyOrder();if(!g||g.length===0)return;let R=g[0];try{C(null,R);}catch(O){throw c.callOnError(O),O}finally{P();}});},UITrigger:s,UidToNodeMap:r}}function pe(o,e){let n=false,t=false,c=new Map,s=new Map,d=new Map,l=new Map,r=[],u=new Map,{GetNextDependency:i,GetPrevDependency:y,GetAllPrevDependency:f,GetAllNextDependency:h,rebuildDirectDependencyMaps:p}=ae(()=>c,()=>s,()=>l,()=>d),P={},C={};if(e.modules.useHistory){let{Undo:S,Redo:b,PushIntoHistory:K,CreateHistoryAction:Y,initCanUndo:Te,initCanRedo:xe}=e.modules.useHistory();P.pushIntoHistory=K,P.createHistoryAction=Y,C={Undo:S,Redo:b,initCanUndo:Te,initCanRedo:xe};}let{onError:v,callOnError:A}=ie(),{onSuccess:x,callOnSuccess:k}=le(),{onStart:E,callOnStart:z}=ue(),{emit:H,usePlugin:g}=ce(),{SetTrace:R,useTrace:O}=se(),Q=O();g(Q);let j=ye(o,{useGreedy:e.config.useGreedy},{GetDependencyOrder:()=>r,GetAllNextDependency:h,GetNextDependency:i,GetPrevDependency:y,GetAllPrevDependency:f,GetPathToLevelMap:()=>u},P,{callOnError:A,callOnSuccess:k,callOnStart:z,emit:H},e.UITrigger),{GetGroupByPath:I,GetNodeByPath:F,notifyAll:$}=j,G={};if(e.modules.useInternalForm){let{uiSchema:S,GetFormData:b}=e.modules.useInternalForm(j,o);G={uiSchema:S,GetFormData:b};}let B={};if(e.modules.useSchemaValidators){let{SetValidators:S}=e.modules.useSchemaValidators(F);B={SetValidators:S};}let{SetRule:V,SetRules:W}=ne(F,c,s),{SetStrategy:N}=re(F),L=oe(c),U=()=>{let S=L();r=S.steps,u=S.levelMap;},w=()=>{t||(t=true,Promise.resolve().then(()=>{if(U(),n){let{directNextMap:S,directPrevMap:b}=p(r.flat());d=S,l=b;}}).finally(()=>{t=false,n=false;}));};return {SetRule:(S,b,K,Y)=>{V(S,b,K,Y),n=true,w();},SetRules:(S,b,K,Y)=>{W(S,b,K,Y),n=true,w();},SetStrategy:N,SetTrace:R,usePlugin:g,SetValue:(S,b)=>{F(S).dependOn(()=>b);},GetValue:(S,b="value")=>F(S)[b],GetGroupByPath:I,notifyAll:async()=>{U(),await $();},GetAllDependency:()=>c,GetDependencyOrder:()=>r,historyExports:C,formExports:G,validatorExports:B,onError:v,onSuccess:x,onStart:E}}var J=new Map,ve=(o,e,n)=>{try{if(typeof n.UITrigger.signalCreator!="function"||typeof n.UITrigger.signalTrigger!="function")throw Error("ui trigger undefined");if(J.has(o))throw Error("engineID repeated");let t=pe(e,{config:n.config||{useGreedy:!1},UITrigger:n.UITrigger,modules:n.modules||{},plugins:{}}),{SetRule:c,SetRules:s,SetStrategy:d,SetValue:l,GetValue:r,usePlugin:u,GetGroupByPath:a,notifyAll:i,SetTrace:y,GetAllDependency:f,GetDependencyOrder:h,historyExports:p,formExports:P,validatorExports:C,onError:v,onSuccess:A,onStart:x}=t,E={...{config:{SetRule:c,SetRules:s,SetStrategy:d,notifyAll:i,SetTrace:y,usePlugin:u},data:{SetValue:l,GetValue:r,GetGroupByPath:a},dependency:{GetAllDependency:f,GetDependencyOrder:h},hooks:{onError:v,onSuccess:A,onStart:x}}},z=n.modules;return z&&Object.keys(z).forEach(H=>{let g=H;if(g.startsWith("use")){let R=g.slice(3);g=R.charAt(0).toLowerCase()+R.slice(1);}H==="useHistory"&&p?Object.keys(p).length>0&&(E[g]=p):H==="useInternalForm"?Object.keys(P).length>0&&(E[g]=P):H==="useSchemaValidators"?Object.keys(C).length>0&&(E[g]=C):E[g]=z[H](t,e);}),J.set(o,E),E}catch(t){throw Error(t)}};var he=o=>{let e=J.get(o);if(e)return e;throw Error("[MeshFlow] Engine ID not found.")},ge=o=>{J.delete(o);},me=ve;function Pe(o,e){let n=c(e),t=(r,u="")=>{let a="name"in r?r.name:void 0,i=a?u===""?a:`${u}.${a}`:u,y=o.UITrigger.signalCreator();if(r.type==="group"){let C=r,v=C.children.map(k=>t(k,i)),A={...C,type:"group",path:i,dirtySignal:y,uid:0,children:v},x=o.registerGroupNode({path:i,type:"group",uid:0,dirtySignal:y,children:v.map(k=>k.path),meta:C});return A.uid=x.uid,A}let f={},h={value:r.value},p=o.registerNode({path:i,type:r.type,uid:0,state:h,meta:r,nodeBucket:f,notifyKeys:new Set,dirtySignal:y,dependOn:null});return p.createView({path:i,type:r.type,dependOn:p.dependOn,nodeBucket:p.nodeBucket})};function c(r,u={}){let a=f=>{if(f.type=="group")return {key:f.name||"",isGroup:true,val:f.children.reduce((h,p)=>[...h,a(p)],[])};if(f.type=="input"||f.type=="number"||f.type=="select"||f.type=="checkbox")return {key:f.name,isGroup:false,val:f.value};throw Error(`undefined type:${f.type}`)},i=(f,h)=>{if(h.isGroup){let p={};h.key===""?p=f:f[h.key]=p,h.val.forEach(P=>{i(p,P);});}else f[h.key]=h.val;},y=a(r);return i(u,y),u}let s=()=>{let r=(u,a,i)=>{if(typeof u!="object"||u===null||Array.isArray(u)){if(i.length>0){let f=i[i.length-1];a[f]=o.GetNodeByPath(i.join(".")).state.value;}return}let y=Object.getOwnPropertyNames(u);for(let f of y)i.push(f),r(u[f],u,i),i.pop();};return r(n,null,[]),n},d=()=>s();return {uiSchema:t(e),GetFormData:d}}var Se=o=>{let e=o;return {SetValidators:(t,c)=>{let s=e(t),d=(r,u,a)=>r(u,a),l=(r,u,a)=>r(u,a);if(!s.validators)throw Error("validator init error");s.validators.setValidators({logic:r=>d(c.logic,r,e),condition:typeof c.condition=="function"?r=>l(c.condition,r,e):()=>true});}}};function ut(o,e,n){return me(o,e,{config:{useGreedy:n.config?.useGreedy??false},UITrigger:n.UITrigger,metaType:{},modules:{useInternalForm:Pe,useSchemaValidators:Se,...n.modules}})}var dt=o=>he(o),ft=o=>{ge(o);};exports.deleteEngine=ft;exports.useEngine=dt;exports.useMeshForm=ut;
package/index.mjs CHANGED
@@ -1 +1 @@
1
- import {useMeshFlow,useEngine}from'@meshflow/core';function T(o,l){let d=p(l),c=(e,r="")=>{let a="name"in e?e.name:void 0,t=a?r===""?a:`${r}.${a}`:r,y=o.UITrigger.signalCreator();if(e.type==="group"){let h=e,x=h.children.map(g=>c(g,t)),S={...h,type:"group",path:t,dirtySignal:y,uid:0,children:x},P=o.registerGroupNode({path:t,type:"group",uid:0,dirtySignal:y,children:x.map(g=>g.path),meta:h});return S.uid=P.uid,S}let n={},i={value:e.value},s=o.registerNode({path:t,type:e.type,uid:0,state:i,meta:e,nodeBucket:n,notifyKeys:new Set,dirtySignal:y,dependOn:null});return s.createView({path:t,type:e.type,dependOn:s.dependOn,nodeBucket:s.nodeBucket})};function p(e,r={}){let a=n=>{if(n.type=="group")return {key:n.name||"",isGroup:true,val:n.children.reduce((i,s)=>[...i,a(s)],[])};if(n.type=="input"||n.type=="number"||n.type=="select"||n.type=="checkbox")return {key:n.name,isGroup:false,val:n.value};throw Error(`undefined type:${n.type}`)},t=(n,i)=>{if(i.isGroup){let s={};i.key===""?s=n:n[i.key]=s,i.val.forEach(f=>{t(s,f);});}else n[i.key]=i.val;},y=a(e);return t(r,y),r}let u=()=>{let e=(r,a,t)=>{if(typeof r!="object"||r===null||Array.isArray(r)){if(t.length>0){let n=t[t.length-1];a[n]=o.GetNodeByPath(t.join(".")).state.value;}return}let y=Object.getOwnPropertyNames(r);for(let n of y)t.push(n),e(r[n],r,t),t.pop();};return e(d,null,[]),d},m=()=>u();return {uiSchema:c(l),GetFormData:m}}var v=o=>{let l=o;return {SetValidators:(c,p)=>{let u=l(c),m=(e,r,a)=>e(r,a),F=(e,r,a)=>e(r,a);if(!u.validators)throw Error("validator init error");u.validators.setValidators({logic:e=>m(p.logic,e,l),condition:typeof p.condition=="function"?e=>F(p.condition,e,l):()=>true});}}};function B(o,l,d){return useMeshFlow(o,l,{config:{useGreedy:d.config?.useGreedy??false},UITrigger:d.UITrigger,metaType:{},modules:{useInternalForm:T,useSchemaValidators:v,...d.modules}})}var I=o=>useEngine(o);export{I as useEngine,B as useMeshForm};
1
+ var Z=class{computedRules=[];store={OR:(e,n)=>{let t,c,s=this.computedRules;for(let d=0;d<s.length;d++){let l=s[d],r=l.logic(e);if(r instanceof Promise)return (async()=>{let a=await r;if(l.entityId==="__base__"?c=a:a&&(t=a),typeof t>"u")for(let i=d+1;i<s.length;i++){let y=s[i],f=y.logic(e),h=f instanceof Promise?await f:f;if(y.entityId==="__base__"){c=h;continue}if(h){t=y.value;break}}return typeof t>"u"&&(t=c),{res:t,version:n}})();let u=r;if(l.entityId==="__base__"){c=u;continue}if(u){t=l.value;break}}return typeof t>"u"&&(t=c),{res:t,version:n}},PRIORITY:(e,n)=>{let t,c=this.computedRules;for(let s=0;s<c.length;s++){let l=c[s].logic(e);if(l instanceof Promise)return (async()=>{let r=await l;if(r!==void 0)return {res:r,version:n};for(let u=s+1;u<c.length;u++){let a=c[u].logic(e),i=a instanceof Promise?await a:a;if(i!==void 0)return {res:i,version:n}}return {res:void 0,version:n}})();if(l!==void 0)return {res:l,version:n}}return {res:t,version:n}}};CurrentStrategy=()=>{};CurrentStrategyType="PRIORITY";getRules=()=>{};constructor(e){this.getRules=e,this.CurrentStrategy=this.store.PRIORITY,this.updateComputedRules();}updateComputedRules(){let e=this.getRules();this.CurrentStrategyType==="PRIORITY"?this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat().sort((n,t)=>t.priority-n.priority):this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat();}setStrategy(e){this.CurrentStrategy=this.store[e],this.updateComputedRules();}evaluate(e,n){return this.CurrentStrategy(e,n)}},X=class{path;strategy;contract;rules=new Map;isValue=false;id=0;cache=void 0;pendingPromise=null;version=0;deps=new Map;_forceNotify=false;promiseToken=null;effectArray=[];constructor(e,n,t){let c=()=>this.rules;this.strategy=new Z(c),this.path=t,this.isValue=n==="value",this.contract=this.inferType(e),this.cache=e,this.setRule({priority:0,entityId:"__base__",logic:()=>e});}forceNotify(){this._forceNotify=true;}isForceNotify(){return this._forceNotify}setStrategy(e){this.strategy.setStrategy(e);}setDefaultRule(e){let n=new Set;n.add(e),this.rules.set("defaultRules",n);}setRules(e,n){n&&this.updateDeps(n);let t=++this.id,c={...e,entityId:t};for(let s of e.triggerPaths)this.rules.has(s)||this.rules.set(s,new Set),this.rules.get(s).add(c);return this.strategy.updateComputedRules(),()=>{for(let s of e.triggerPaths){let d=this.rules.get(s);d&&(d.delete(c),d.size===0&&(this.rules.delete(s),this.deps.delete(s)));}this.strategy.updateComputedRules();}}updateDeps(e){for(let[n,t]of e)this.deps.set(n,t);}setRule(e,n){if(n&&this.updateDeps(n),typeof e.entityId=="string"){this.setDefaultRule(e);return}let t=++this.id,c={...e,entityId:t};if(e)for(let s of e.triggerPaths)this.rules.has(s)||this.rules.set(s,new Set),this.rules.get(s).add(c);return this.strategy.updateComputedRules(),()=>{for(let s of e.triggerPaths){let d=this.rules.get(s);d&&(d.delete(c),d.size===0&&(this.rules.delete(s),this.deps.delete(s)));}this.strategy.updateComputedRules();}}setSideEffect(e){this.effectArray.push(e);}getSideEffect(){return [...this.effectArray]}evaluate(e){let n=null;if(e.GetToken&&(n=e.GetToken()),this.pendingPromise&&this.promiseToken!==n&&(this.pendingPromise=null,this.promiseToken=null),this.pendingPromise)return this.pendingPromise;let t=false;if(typeof e.triggerPath=="string"){t=true;let d=this.deps.get(e.triggerPath),l=e.GetValueByPath(e.triggerPath);if(typeof d=="object"||typeof l=="object")t=false;else {let r=Array.from(this.deps.keys());for(let u of r){let a=this.deps.get(u),i=e.GetValueByPath(u);if(a!==i){t=false;break}}}}if(t)return this.cache;this.promiseToken=n;let c=++this.version,s=this.strategy.evaluate(e,c);if(!(s instanceof Promise)){let{res:d,version:l}=s;return this.finalizeSync(d,l,e,n)}return this.pendingPromise=(async()=>{try{let{res:d,version:l}=await s;return this.finalizeSync(d,l,e,n)}catch(d){throw {path:this.path,error:d}}finally{this.promiseToken===n&&(this.pendingPromise=null,this.promiseToken=null);}})(),this.pendingPromise}finalizeSync(e,n,t,c){return c!==this.promiseToken||n<this.version?this.cache:(this.cache=e,this.deps.forEach((s,d)=>{this.deps.set(d,t.GetValueByPath(d));}),e)}inferType(e){return Array.isArray(e)?"array":typeof e}};var te=(o,e,n)=>{let c=s=>{let d=n.triggerPaths.map(u=>s.GetValueByPath(u).value),l=Object.create(null);return Object.defineProperty(l,"triggerTargets",{get:()=>d||[]}),Object.defineProperty(l,"affectedTatget",{get:()=>s.GetRenderSchemaByPath(o)[e]}),n.logic({slot:l})};return {value:n.value,targetPath:o,triggerPaths:n.triggerPaths,priority:n.priority??10,logic:c}},ne=(o,e,n,t)=>{if(!o)throw Error("");let c=o,s=(r,u)=>{e.has(r)||e.set(r,new Set),e.get(r).add(u),n.has(u)||n.set(u,new Set),n.get(u).add(r);};return {SetRule:(r,u,a,i={logic:()=>{}})=>{let y=c(u),f=te(u,a,{...i,triggerPaths:[r]}),h=[r].map(p=>[p,c(p).state.value]);if(s(r,u),y.nodeBucket[a])y.nodeBucket[a].setRule(f,h),i.effect&&y.nodeBucket[a].setSideEffect({fn:i.effect,args:i.effectArgs?i.effectArgs:[a]});else {let p=y.meta[a],P=new X(p,a,u);P.setRule(f,h),i.effect&&P.setSideEffect({fn:i.effect,args:i.effectArgs?i.effectArgs:[a]}),y.nodeBucket[a]=P;}y.state[a]=y.meta[a],i.forceNotify&&y.nodeBucket[a].forceNotify();},SetRules:(r,u,a,i={logic:()=>{}})=>{let y=c(u);for(let p of r)s(p,u);let f=te(u,a,{...i,triggerPaths:r}),h=r.map(p=>[p,c(p).state.value]);if(y.nodeBucket[a])y.nodeBucket[a].setRules(f,h),i.effect&&y.nodeBucket[a].setSideEffect({fn:i.effect,args:i.effectArgs?i.effectArgs:[a]});else {let p=y.meta[a],P=new X(p,a,u);P.setRules(f,h),i.effect&&P.setSideEffect({fn:i.effect,args:i.effectArgs?i.effectArgs:[a]}),y.nodeBucket[a]=P;}y.state[a]=y.meta[a],i.forceNotify&&y.nodeBucket[a].forceNotify();}}};var re=o=>{let e=o||void 0;if(!e)throw Error("");return {SetStrategy:(t,c,s)=>{e(t).nodeBucket[c].setStrategy(s);}}};function se(){let o=new Map,e=new Map,n=new Set,t=(d,l)=>{o.set(d,l);let r=e.get(d);r&&r(l);};return {SetTrace:(d,l)=>{e.set(d,l);let r=o.get(d)||"idle";return l(r),{cancel:()=>{e.delete(d);}}},useTrace:()=>({apply:l=>{l.on("flow:start",()=>{n.forEach(r=>t(r,"idle")),n.clear(),o.clear();}),l.on("node:release",({path:r,type:u})=>{(u==1||u==2)&&(n.add(r),t(r,"pending"));}),l.on("node:pending",({path:r})=>{n.add(r),(!o.has(r)||o.get(r)==="idle")&&t(r,"pending");}),l.on("node:start",({path:r})=>{n.add(r),t(r,"calculating");}),l.on("node:success",({path:r})=>{t(r,"calculated");}),l.on("node:intercept",({path:r,type:u})=>{u==3&&t(r,"calculating"),u==6&&t(r,"idle");}),l.on("node:stagnate",({path:r})=>{t(r,"pending");}),l.on("node:error",({path:r})=>t(r,"error"));}})}}function ae(o,e,n,t){let c=a=>{let i=o(),y=e(),f=new Set;return i.get(a)?.forEach(h=>f.add(h)),f.size===0?[]:Array.from(f).filter(h=>{let p=y.get(h)||new Set;return !Array.from(p).some(v=>f.has(v))})};return {GetNextDependency:a=>{let i=t();return Array.from(i.get(a)||[])},GetPrevDependency:a=>{let i=n();return Array.from(i.get(a)||[])},GetAllPrevDependency:a=>{let i=e();return Array.from(i.get(a)||[])},GetAllNextDependency:a=>{let i=o();return Array.from(i.get(a)||[])},rebuildDirectDependencyMaps:a=>{let i=new Map,y=new Map;for(let f of a){let h=c(f);i.set(f,new Set(h));for(let p of h)y.has(p)||y.set(p,new Set),y.get(p).add(f);}return {directNextMap:i,directPrevMap:y}}}}function oe(o){let e=t=>{let c=[],s=[],d=new Map,l=t.size,r=0,u=0;for(let[a,i]of t)i===0&&s.push(a);if(s.length===0&&l>0)throw Error("Circular dependency detected");for(;s.length>0;){c.push([...s]);let a=[];for(let i of s){r++,d.set(i,u);let y=o.get(i);if(y)for(let f of y){let h=t.get(f)-1;t.set(f,h),h===0&&a.push(f);}}s=a,u++;}if(r<l)throw Error("Circular dependency detected");return {steps:c,levelMap:d}};return ()=>{let t=new Map;for(let c of o.keys()){let s=Array.from(o.get(c)||[]);t.has(c)||t.set(c,0);for(let d of s){let l=t.get(d)||0;t.set(d,++l);}}return e(t)}}var q=()=>{let o=[];return {on:e=>(o.push(e),()=>{let n=o.indexOf(e);n>-1&&o.splice(n,1);}),call:e=>o.forEach(n=>{n(e);})}};function ie(){let{on:o,call:e}=q();return {onError:o,callOnError:e}}function le(){let{on:o,call:e}=q();return {onSuccess:o,callOnSuccess:e}}var ce=()=>{let o=new Set,e=new Map,n=(s,d)=>{e.get(s)?.forEach(l=>l(d));},t=(s,d)=>(e.has(s)||e.set(s,new Set),e.get(s).add(d),()=>e.get(s).delete(d));return {usePlugin:s=>{let d=new Set,l=(r,u)=>{let a=t(r,u);return d.add(a),a};return s.apply({on:l}),o.add(s),()=>{d.forEach(r=>r()),d.clear(),o.delete(s);}},emit:n}};function ue(){let{on:o,call:e}=q();return {onStart:o,callOnStart:e}}var de=(o={frameQuota:12})=>{let e=performance.now(),n=0,t=false,c=()=>!!navigator?.scheduling?.isInputPending?.({includeContinuous:true});return {getIsFirstFrame:()=>t,reset(){e=performance.now(),n=0,t=true;},shouldYield(){let s=performance.now();return n++,!!((n>=5||t)&&(n=0,s-e>o.frameQuota||c()))},async yieldToMain(){return new Promise(s=>{Me(()=>{e=performance.now(),n=0,t&&(t=false),s();});})}}},Me=o=>{let{port1:e,port2:n}=new MessageChannel;e.onmessage=o,n.postMessage(null);};function fe(o,e,n,t,c){let s=new Map,d=o.useGreedy,l=de();return async(u,a)=>{let y=Symbol("token"),f=u||"__NOTIFY_ALL__";s.set(f,y);let h=false;l.reset();let p=new Set,P=new Set,C=new Set;a.forEach(I=>{C.add(I),e.GetAllNextDependency(I).forEach(F=>C.add(F));});let v=new Map,A=new Map,x=new Set,k=e.GetPathToLevelMap(),E=0,z=0,H=I=>{e.GetAllNextDependency(I).forEach($=>{let G=k.get($)||0;G>z&&(z=G);});};u?(E=k.get(u)??0,H(u),p.add(u)):a.forEach(I=>H(I)),a.forEach(I=>{x.add(I);});let g=performance.now();t.emit("flow:start",{path:f}),t.callOnStart({path:f});let R=false,O=30,Q=I=>{let{target:F,trigger:$}=I,G=false,B=false,V=n.GetNodeByPath(F),W=[],N=(m,T)=>{if(p.has(m)||P.has(m)||x.has(m))return;let _=0,M=k.get(m)??0;if(v.has(m))_=v.get(m)-1;else {if(M>E&&v.size>O){A.has(M)||A.set(M,new Set),A.get(M).add(m),t.emit("node:intercept",{path:m,type:7});return}let D=e.GetPrevDependency(m),S=0;for(let b of D){if(p.has(b))continue;(k.get(b)??0)>E&&S++;}_=S;}if(_<=0){let D=x.has(m),S=P.has(m);if(D||S){t.emit("node:intercept",{path:m,type:S?3:3.1});return}v.delete(m),x.add(m),t.emit("node:release",{path:m,type:T,detail:{path:F}});}else v.set(m,_);},L=(m=[])=>{if(s.get(f)!==y)return;if(m.length){let M={},D=V.proxy;for(let S of m){let b=(S.args||[]).reduce((K,Y)=>(K[Y]=D[Y],K),{});try{let K=S.fn(b);K&&typeof K=="object"&&Object.assign(M,K);}catch(K){}}for(let S in M)if(S in V.state)V.state[S]=M[S];else throw {error:`wrong effect in ${String(V.path)}`};G=true;}G&&c.flushPathSet.add(F),t.emit("node:success",{path:F}),p.add(F);let T=e.GetNextDependency(F);(G||B)&&e.GetAllNextDependency(F).forEach(D=>C.add(D));for(let M of T){if(p.has(M)){t.emit("node:intercept",{path:M,type:2});continue}if(P.has(M)||x.has(M)){t.emit("node:intercept",{path:M,type:P.has(M)?3:3.1});continue}if(G||B)N(M,1);else if(v.has(M))N(M,2);else {let S=k.get(M);A.has(S)||A.set(S,new Set);let b=A.get(S);b.has(M)||(b.add(M),t.emit("node:stagnate",{path:M,type:1}));}}P.delete(F),(async()=>{if(!h){let M=P.size,D=x.size;t.emit("flow:fire",{path:F,type:1,detail:{active:M,pending:D,blocked:v.size}}),j();}})();},U=m=>{t.emit("node:error",{path:F,error:m});let T=Symbol("abort");s.set(f,T),x.clear(),v.clear(),P.clear(),t.callOnError(m);},w=(m,T)=>{let _=false;m!==V.state[T]&&(V.state[T]=m,G=true,t.emit("node:bucket:success",{path:F,key:String(T),value:m}),V.notifyKeys.has(T)&&(_=true)),V.nodeBucket[T].isForceNotify()&&(B=true),(_||B)&&H(F);};t.emit("node:start",{path:F});try{let m=[];for(let T in V.nodeBucket){let _=V.nodeBucket[T];m.push(..._.getSideEffect());let M=_.evaluate({affectKey:T,triggerPath:$,GetRenderSchemaByPath:D=>n.GetNodeByPath(D).proxy,GetValueByPath:D=>n.GetNodeByPath(D).state,GetToken:()=>y});if(M instanceof Promise){let D=M.then(S=>{s.get(f)===y&&w(S,T);});W.push(D);}else w(M,T);}if(W.length>0)return Promise.all(W).then(()=>{L(m);}).catch(U);L(m);return}catch(m){U(m);}},j=async()=>{if(s.get(f)!==y){h=false;return}h=true;let I=l.getIsFirstFrame(),F=0,$=()=>d&&I?30:1/0,G=0,B=$();try{for(;s.get(f)===y;){let V=G>=B,W=l.shouldYield();if(V||W){if(G>0&&(F++,(I||F%2===0)&&c.requestUpdate()),await l.yieldToMain(),s.get(f)!==y)break;G=0,I=l.getIsFirstFrame();}if(x.size>0&&P.size<5){for(let N of x){if(P.size>=5||G>=B)break;let L=k.get(N)??0,U=e.GetPrevDependency(N),w=U.length>1;if((!d||w)&&L>E){x.delete(N);let T=U.filter(_=>C.has(_)&&!p.has(_)).length;v.set(N,T||0),t.emit("node:intercept",{path:N,type:T>0?4:5,detail:{targetLevel:L,currentLevel:E,pendingParentsCount:T}});continue}if(x.delete(N),P.add(N),t.emit("node:processing",{path:N}),Q({target:N,trigger:u}),G++,G>=B||l.shouldYield())break}if(x.size>0)continue}if(G<B&&d&&v.size>0&&P.size<5){let N=!1,L=0;for(let[U,w]of v)if(w<=0){let m=k.get(U)??0,T=e.GetPrevDependency(U);if(m>E&&T.length>1)continue;if(v.delete(U),x.add(U),L++,N=!0,t.emit("node:release",{path:U,type:4}),L>=B)break}if(L>0)continue;if(N){if(l.shouldYield()&&(await l.yieldToMain(),s.get(f)!==y))break;continue}}if(P.size===0&&x.size===0){let N=new Set;for(let w of A.keys())N.add(w);for(let[w]of v){let m=k.get(w)??0;m>E&&N.add(m);}let L=Array.from(N).sort((w,m)=>w-m),U=L[0];if(L.length>0&&U<=z){let w=L[0];if(w<=z){E=w;let m=A.get(w);m&&(m.forEach(T=>x.add(T)),A.delete(w));for(let[T]of v)(k.get(T)??0)===w&&(v.delete(T),x.add(T),t.emit("node:release",{path:T,type:3,detail:{level:w}}));continue}}else {A.forEach((w,m)=>{w.forEach(T=>{p.add(T),t.emit("node:intercept",{path:T,type:6});});}),A.clear();for(let[w]of v)p.add(w),t.emit("node:intercept",{path:w,type:6});v.clear();break}}x.size>0&&P.size>=5&&t.emit("flow:wait",{type:2});break}}finally{if(h=false,P.size+v.size+x.size===0){if(s.get(f)===y&&!R){R=true,t.emit("flow:end",{type:1}),c.requestUpdate();let W=performance.now();t.emit("flow:success",{duration:(W-g).toFixed(2)+"ms"}),Promise.resolve().then(()=>{t.callOnSuccess();});}}else t.emit("flow:wait",{type:1,detail:{nums:P.size}});}};j();}}function ee(o){let{path:e,uid:n,type:t,meta:c,dirtySignal:s,triggerUI:d,state:l}=o,r=null,a={path:e,uid:n,type:t,meta:c,dirtySignal:s,createView:(i={})=>{let y=new Proxy(i,{get(f,h){let p=h;return p in o.state?o.state[p]:p in o?o[p]:c&&p in c?c[p]:Reflect.get(f,h)},set(f,h,p){let P=h;return P in o.state?(o.state[P]=p,true):Reflect.set(f,h,p)},ownKeys(f){let h=new Set([...Reflect.ownKeys(f),...Object.keys(l||{}),...Object.keys(c||{})]);return Array.from(h)},getOwnPropertyDescriptor(f,h){return l&&h in l||c&&h in c?{enumerable:true,configurable:true}:Reflect.getOwnPropertyDescriptor(f,h)}});return r=y,y}};return "children"in o?{...a,children:o.children}:{...a,state:o.state,nodeBucket:o.nodeBucket,notifyKeys:o.notifyKeys,dependOn:o.dependOn,get proxy(){return r}}}function ye(o,e,n,t,c,s){let d=0,l=new Map,r=new Map,u=new Map,a=false,i=new Set,p=async()=>{let g=Array.from(i);i.clear();for(let R of g){let O=x(R);s.signalTrigger(O.dirtySignal);}},P=()=>{a||(a=true,requestAnimationFrame(()=>{try{for(;i.size>0;)p();}finally{a=false;}}));},C=fe({useGreedy:e.useGreedy},n,{GetNodeByPath:x},c,{requestUpdate:P,flushPathSet:i}),v=g=>{if(l.has(g.path))throw new Error(`[MeshFlow] Duplicate Path: ${String(g.path)}`);let R=++d,O={path:g.path,getNode:I=>x(I)},Q=I=>{let F=I({...O}),$=x(g.path);if(t.createHistoryAction&&t.pushIntoHistory){let G=t.createHistoryAction([{path:g.path,value:$.state.value},{path:g.path,value:F}],B=>{let V=x(B.path);V.state.value=B.value,E(B.path);});t.pushIntoHistory(G);}$.state.value=F,E(g.path);};g.notifyKeys.size==0&&g.notifyKeys.add("value");let j=ee({uid:R,path:g.path,state:g.state,meta:g.meta,nodeBucket:g.nodeBucket,dirtySignal:g.dirtySignal,notifyKeys:g.notifyKeys,dependOn:Q});return l.set(j.path,R),r.set(R,j),j},A=g=>{if(l.has(g.path))throw new Error(`[MeshFlow] Duplicate Path: ${String(g.path)}`);let R=++d,O=ee({uid:R,path:g.path,state:{},meta:g,nodeBucket:{},children:g.children});return l.set(O.path,R),u.set(R,O),O};function x(g){let R=l.get(g),O=r.get(R);if(!O)throw Error("wrong ID");return O}function k(g){let R=l.get(g);return u.get(R)}let E=g=>{if(!x(g))throw Error("Node undefined");i.add(g),P();let O=n.GetNextDependency(g);z(O,g);};function z(g,R){C(R,g);}return {registerNode:v,registerGroupNode:A,GetNodeByPath:x,GetGroupByPath:k,notify:E,notifyAll:async()=>{Promise.resolve().then(async()=>{let g=n.GetDependencyOrder();if(!g||g.length===0)return;let R=g[0];try{C(null,R);}catch(O){throw c.callOnError(O),O}finally{P();}});},UITrigger:s,UidToNodeMap:r}}function pe(o,e){let n=false,t=false,c=new Map,s=new Map,d=new Map,l=new Map,r=[],u=new Map,{GetNextDependency:i,GetPrevDependency:y,GetAllPrevDependency:f,GetAllNextDependency:h,rebuildDirectDependencyMaps:p}=ae(()=>c,()=>s,()=>l,()=>d),P={},C={};if(e.modules.useHistory){let{Undo:S,Redo:b,PushIntoHistory:K,CreateHistoryAction:Y,initCanUndo:Te,initCanRedo:xe}=e.modules.useHistory();P.pushIntoHistory=K,P.createHistoryAction=Y,C={Undo:S,Redo:b,initCanUndo:Te,initCanRedo:xe};}let{onError:v,callOnError:A}=ie(),{onSuccess:x,callOnSuccess:k}=le(),{onStart:E,callOnStart:z}=ue(),{emit:H,usePlugin:g}=ce(),{SetTrace:R,useTrace:O}=se(),Q=O();g(Q);let j=ye(o,{useGreedy:e.config.useGreedy},{GetDependencyOrder:()=>r,GetAllNextDependency:h,GetNextDependency:i,GetPrevDependency:y,GetAllPrevDependency:f,GetPathToLevelMap:()=>u},P,{callOnError:A,callOnSuccess:k,callOnStart:z,emit:H},e.UITrigger),{GetGroupByPath:I,GetNodeByPath:F,notifyAll:$}=j,G={};if(e.modules.useInternalForm){let{uiSchema:S,GetFormData:b}=e.modules.useInternalForm(j,o);G={uiSchema:S,GetFormData:b};}let B={};if(e.modules.useSchemaValidators){let{SetValidators:S}=e.modules.useSchemaValidators(F);B={SetValidators:S};}let{SetRule:V,SetRules:W}=ne(F,c,s),{SetStrategy:N}=re(F),L=oe(c),U=()=>{let S=L();r=S.steps,u=S.levelMap;},w=()=>{t||(t=true,Promise.resolve().then(()=>{if(U(),n){let{directNextMap:S,directPrevMap:b}=p(r.flat());d=S,l=b;}}).finally(()=>{t=false,n=false;}));};return {SetRule:(S,b,K,Y)=>{V(S,b,K,Y),n=true,w();},SetRules:(S,b,K,Y)=>{W(S,b,K,Y),n=true,w();},SetStrategy:N,SetTrace:R,usePlugin:g,SetValue:(S,b)=>{F(S).dependOn(()=>b);},GetValue:(S,b="value")=>F(S)[b],GetGroupByPath:I,notifyAll:async()=>{U(),await $();},GetAllDependency:()=>c,GetDependencyOrder:()=>r,historyExports:C,formExports:G,validatorExports:B,onError:v,onSuccess:x,onStart:E}}var J=new Map,ve=(o,e,n)=>{try{if(typeof n.UITrigger.signalCreator!="function"||typeof n.UITrigger.signalTrigger!="function")throw Error("ui trigger undefined");if(J.has(o))throw Error("engineID repeated");let t=pe(e,{config:n.config||{useGreedy:!1},UITrigger:n.UITrigger,modules:n.modules||{},plugins:{}}),{SetRule:c,SetRules:s,SetStrategy:d,SetValue:l,GetValue:r,usePlugin:u,GetGroupByPath:a,notifyAll:i,SetTrace:y,GetAllDependency:f,GetDependencyOrder:h,historyExports:p,formExports:P,validatorExports:C,onError:v,onSuccess:A,onStart:x}=t,E={...{config:{SetRule:c,SetRules:s,SetStrategy:d,notifyAll:i,SetTrace:y,usePlugin:u},data:{SetValue:l,GetValue:r,GetGroupByPath:a},dependency:{GetAllDependency:f,GetDependencyOrder:h},hooks:{onError:v,onSuccess:A,onStart:x}}},z=n.modules;return z&&Object.keys(z).forEach(H=>{let g=H;if(g.startsWith("use")){let R=g.slice(3);g=R.charAt(0).toLowerCase()+R.slice(1);}H==="useHistory"&&p?Object.keys(p).length>0&&(E[g]=p):H==="useInternalForm"?Object.keys(P).length>0&&(E[g]=P):H==="useSchemaValidators"?Object.keys(C).length>0&&(E[g]=C):E[g]=z[H](t,e);}),J.set(o,E),E}catch(t){throw Error(t)}};var he=o=>{let e=J.get(o);if(e)return e;throw Error("[MeshFlow] Engine ID not found.")},ge=o=>{J.delete(o);},me=ve;function Pe(o,e){let n=c(e),t=(r,u="")=>{let a="name"in r?r.name:void 0,i=a?u===""?a:`${u}.${a}`:u,y=o.UITrigger.signalCreator();if(r.type==="group"){let C=r,v=C.children.map(k=>t(k,i)),A={...C,type:"group",path:i,dirtySignal:y,uid:0,children:v},x=o.registerGroupNode({path:i,type:"group",uid:0,dirtySignal:y,children:v.map(k=>k.path),meta:C});return A.uid=x.uid,A}let f={},h={value:r.value},p=o.registerNode({path:i,type:r.type,uid:0,state:h,meta:r,nodeBucket:f,notifyKeys:new Set,dirtySignal:y,dependOn:null});return p.createView({path:i,type:r.type,dependOn:p.dependOn,nodeBucket:p.nodeBucket})};function c(r,u={}){let a=f=>{if(f.type=="group")return {key:f.name||"",isGroup:true,val:f.children.reduce((h,p)=>[...h,a(p)],[])};if(f.type=="input"||f.type=="number"||f.type=="select"||f.type=="checkbox")return {key:f.name,isGroup:false,val:f.value};throw Error(`undefined type:${f.type}`)},i=(f,h)=>{if(h.isGroup){let p={};h.key===""?p=f:f[h.key]=p,h.val.forEach(P=>{i(p,P);});}else f[h.key]=h.val;},y=a(r);return i(u,y),u}let s=()=>{let r=(u,a,i)=>{if(typeof u!="object"||u===null||Array.isArray(u)){if(i.length>0){let f=i[i.length-1];a[f]=o.GetNodeByPath(i.join(".")).state.value;}return}let y=Object.getOwnPropertyNames(u);for(let f of y)i.push(f),r(u[f],u,i),i.pop();};return r(n,null,[]),n},d=()=>s();return {uiSchema:t(e),GetFormData:d}}var Se=o=>{let e=o;return {SetValidators:(t,c)=>{let s=e(t),d=(r,u,a)=>r(u,a),l=(r,u,a)=>r(u,a);if(!s.validators)throw Error("validator init error");s.validators.setValidators({logic:r=>d(c.logic,r,e),condition:typeof c.condition=="function"?r=>l(c.condition,r,e):()=>true});}}};function ut(o,e,n){return me(o,e,{config:{useGreedy:n.config?.useGreedy??false},UITrigger:n.UITrigger,metaType:{},modules:{useInternalForm:Pe,useSchemaValidators:Se,...n.modules}})}var dt=o=>he(o),ft=o=>{ge(o);};export{ft as deleteEngine,dt as useEngine,ut as useMeshForm};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meshflow/form",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Form orchestration adapter for @meshflow/core, providing high-level form logic and schema validation.",
5
5
  "main": "./index.cjs",
6
6
  "module": "./index.js",
@@ -18,10 +18,10 @@
18
18
  "reactive-form"
19
19
  ],
20
20
  "dependencies": {
21
- "@meshflow/core": "^0.2.6"
21
+ "@meshflow/core": "^0.2.7"
22
22
  },
23
23
  "peerDependencies": {
24
- "@meshflow/core": ">=0.2.6"
24
+ "@meshflow/core": ">=0.2.7"
25
25
  },
26
26
  "devDependencies": {
27
27
  "typescript": "^5.0.0" ,