@flowgram.ai/variable-core 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2072 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __decorateClass = (decorators, target, key, kind) => {
20
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
21
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
22
+ if (decorator = decorators[i])
23
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
24
+ if (kind && result) __defProp(target, key, result);
25
+ return result;
26
+ };
27
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
28
+
29
+ // src/index.ts
30
+ var src_exports = {};
31
+ __export(src_exports, {
32
+ ASTFactory: () => ASTFactory,
33
+ ASTKind: () => ASTKind,
34
+ ASTNode: () => ASTNode,
35
+ ASTNodeFlags: () => ASTNodeFlags,
36
+ ASTRegisters: () => ASTRegisters,
37
+ ArrayType: () => ArrayType,
38
+ BaseExpression: () => BaseExpression,
39
+ BaseType: () => BaseType,
40
+ BaseVariableField: () => BaseVariableField,
41
+ BooleanType: () => BooleanType,
42
+ DataNode: () => DataNode,
43
+ EnumerateExpression: () => EnumerateExpression,
44
+ ExpressionList: () => ExpressionList,
45
+ IntegerType: () => IntegerType,
46
+ KeyPathExpression: () => KeyPathExpression,
47
+ KeyPathExpressionV2: () => KeyPathExpressionV2,
48
+ ListNode: () => ListNode,
49
+ MapNode: () => MapNode,
50
+ MapType: () => MapType,
51
+ NumberType: () => NumberType,
52
+ ObjectType: () => ObjectType,
53
+ Property: () => Property,
54
+ Scope: () => Scope,
55
+ ScopeChain: () => ScopeChain,
56
+ ScopeOutputData: () => ScopeOutputData,
57
+ ScopeProvider: () => ScopeProvider,
58
+ StringType: () => StringType,
59
+ VariableContainerModule: () => VariableContainerModule,
60
+ VariableDeclaration: () => VariableDeclaration,
61
+ VariableDeclarationList: () => VariableDeclarationList,
62
+ VariableEngine: () => VariableEngine,
63
+ VariableEngineProvider: () => VariableEngineProvider,
64
+ VariableFieldKeyRenameService: () => VariableFieldKeyRenameService,
65
+ VariableTable: () => VariableTable,
66
+ injectToAST: () => injectToAST,
67
+ isMatchAST: () => isMatchAST,
68
+ postConstructAST: () => postConstructAST,
69
+ useAvailableVariables: () => useAvailableVariables,
70
+ useCurrentScope: () => useCurrentScope,
71
+ useScopeAvailable: () => useScopeAvailable,
72
+ useScopeContext: () => useScopeContext
73
+ });
74
+ module.exports = __toCommonJS(src_exports);
75
+
76
+ // src/variable-container-module.ts
77
+ var import_inversify7 = require("inversify");
78
+
79
+ // src/variable-engine.ts
80
+ var import_rxjs6 = require("rxjs");
81
+ var import_inversify5 = require("inversify");
82
+ var import_utils10 = require("@flowgram.ai/utils");
83
+ var import_utils11 = require("@flowgram.ai/utils");
84
+
85
+ // src/utils/toDisposable.tsx
86
+ var import_utils = require("@flowgram.ai/utils");
87
+ function subsToDisposable(subscription) {
88
+ return import_utils.Disposable.create(() => subscription.unsubscribe());
89
+ }
90
+
91
+ // src/utils/memo.ts
92
+ var createMemo = () => {
93
+ const _memoCache = /* @__PURE__ */ new Map();
94
+ const memo = (key, fn) => {
95
+ if (_memoCache.has(key)) {
96
+ return _memoCache.get(key);
97
+ }
98
+ const data = fn();
99
+ _memoCache.set(key, data);
100
+ return data;
101
+ };
102
+ const clear = (key) => {
103
+ if (key) {
104
+ _memoCache.delete(key);
105
+ } else {
106
+ _memoCache.clear();
107
+ }
108
+ };
109
+ memo.clear = clear;
110
+ return memo;
111
+ };
112
+
113
+ // src/scope/scope-chain.ts
114
+ var import_inversify = require("inversify");
115
+ var import_utils2 = require("@flowgram.ai/utils");
116
+
117
+ // src/providers.ts
118
+ var VariableEngineProvider = Symbol("DynamicVariableEngine");
119
+ var ContainerProvider = Symbol("ContainerProvider");
120
+
121
+ // src/scope/scope-chain.ts
122
+ var ScopeChain = class {
123
+ constructor() {
124
+ this.toDispose = new import_utils2.DisposableCollection();
125
+ }
126
+ get variableEngine() {
127
+ return this.variableEngineProvider();
128
+ }
129
+ /**
130
+ * 所有作用域依赖关系刷新
131
+ */
132
+ refreshAllChange() {
133
+ this.variableEngine.getAllScopes().forEach((_scope) => {
134
+ _scope.refreshCovers();
135
+ _scope.refreshDeps();
136
+ });
137
+ }
138
+ dispose() {
139
+ this.toDispose.dispose();
140
+ }
141
+ get disposed() {
142
+ return this.toDispose.disposed;
143
+ }
144
+ get onDispose() {
145
+ return this.toDispose.onDispose;
146
+ }
147
+ };
148
+ __decorateClass([
149
+ (0, import_inversify.inject)(VariableEngineProvider)
150
+ ], ScopeChain.prototype, "variableEngineProvider", 2);
151
+ ScopeChain = __decorateClass([
152
+ (0, import_inversify.injectable)()
153
+ ], ScopeChain);
154
+
155
+ // src/scope/scope.ts
156
+ var import_utils9 = require("@flowgram.ai/utils");
157
+
158
+ // src/ast/types.ts
159
+ var ASTKind = /* @__PURE__ */ ((ASTKind2) => {
160
+ ASTKind2["String"] = "String";
161
+ ASTKind2["Number"] = "Number";
162
+ ASTKind2["Integer"] = "Integer";
163
+ ASTKind2["Boolean"] = "Boolean";
164
+ ASTKind2["Object"] = "Object";
165
+ ASTKind2["Array"] = "Array";
166
+ ASTKind2["Map"] = "Map";
167
+ ASTKind2["Union"] = "Union";
168
+ ASTKind2["Any"] = "Any";
169
+ ASTKind2["Property"] = "Property";
170
+ ASTKind2["VariableDeclaration"] = "VariableDeclaration";
171
+ ASTKind2["VariableDeclarationList"] = "VariableDeclarationList";
172
+ ASTKind2["KeyPathExpression"] = "KeyPathExpression";
173
+ ASTKind2["EnumerateExpression"] = "EnumerateExpression";
174
+ ASTKind2["ExpressionList"] = "ExpressionList";
175
+ ASTKind2["ListNode"] = "ListNode";
176
+ ASTKind2["DataNode"] = "DataNode";
177
+ ASTKind2["MapNode"] = "MapNode";
178
+ return ASTKind2;
179
+ })(ASTKind || {});
180
+
181
+ // src/ast/ast-registers.ts
182
+ var import_lodash3 = require("lodash");
183
+ var import_inversify2 = require("inversify");
184
+
185
+ // src/ast/utils/inversify.ts
186
+ var injectToAST = (serviceIdentifier) => function(target, propertyKey) {
187
+ if (!serviceIdentifier) {
188
+ throw new Error(
189
+ `ServiceIdentifier ${serviceIdentifier} in @lazyInject is Empty, it might be caused by file circular dependency, please check it.`
190
+ );
191
+ }
192
+ const descriptor = {
193
+ get() {
194
+ const container = this.scope.variableEngine.container;
195
+ return container.get(serviceIdentifier);
196
+ },
197
+ set() {
198
+ },
199
+ configurable: true,
200
+ enumerable: true
201
+ };
202
+ return descriptor;
203
+ };
204
+ var POST_CONSTRUCT_AST_SYMBOL = Symbol("post_construct_ast");
205
+ var postConstructAST = () => (target, propertyKey) => {
206
+ if (!Reflect.hasMetadata(POST_CONSTRUCT_AST_SYMBOL, target)) {
207
+ Reflect.defineMetadata(POST_CONSTRUCT_AST_SYMBOL, propertyKey, target);
208
+ } else {
209
+ throw Error("Duplication Post Construct AST");
210
+ }
211
+ };
212
+
213
+ // src/ast/utils/helpers.ts
214
+ function updateChildNodeHelper({
215
+ getChildNode,
216
+ updateChildNode,
217
+ removeChildNode,
218
+ nextJSON
219
+ }) {
220
+ const currNode = getChildNode();
221
+ const isNewKind = currNode?.kind !== nextJSON?.kind;
222
+ const isNewKey = nextJSON?.key && nextJSON?.key !== currNode?.key;
223
+ if (isNewKind || isNewKey) {
224
+ if (currNode) {
225
+ currNode.dispose();
226
+ removeChildNode();
227
+ }
228
+ if (nextJSON) {
229
+ const newNode = this.createChildNode(nextJSON);
230
+ updateChildNode(newNode);
231
+ this.fireChange();
232
+ return newNode;
233
+ } else {
234
+ this.fireChange();
235
+ }
236
+ } else if (nextJSON) {
237
+ currNode?.fromJSON(nextJSON);
238
+ }
239
+ return currNode;
240
+ }
241
+ function parseTypeJsonOrKind(typeJSONOrKind) {
242
+ return typeof typeJSONOrKind === "string" ? { kind: typeJSONOrKind } : typeJSONOrKind;
243
+ }
244
+ function getAllChildren(ast) {
245
+ return [...ast.children, ...ast.children.map((_child) => getAllChildren(_child)).flat()];
246
+ }
247
+ function isMatchAST(node, targetType) {
248
+ return node?.kind === targetType?.kind;
249
+ }
250
+
251
+ // src/ast/flags.ts
252
+ var ASTNodeFlags = /* @__PURE__ */ ((ASTNodeFlags2) => {
253
+ ASTNodeFlags2[ASTNodeFlags2["None"] = 0] = "None";
254
+ ASTNodeFlags2[ASTNodeFlags2["VariableField"] = 1] = "VariableField";
255
+ ASTNodeFlags2[ASTNodeFlags2["Expression"] = 4] = "Expression";
256
+ ASTNodeFlags2[ASTNodeFlags2["BasicType"] = 8] = "BasicType";
257
+ ASTNodeFlags2[ASTNodeFlags2["DrilldownType"] = 16] = "DrilldownType";
258
+ ASTNodeFlags2[ASTNodeFlags2["EnumerateType"] = 32] = "EnumerateType";
259
+ ASTNodeFlags2[ASTNodeFlags2["UnionType"] = 64] = "UnionType";
260
+ ASTNodeFlags2[ASTNodeFlags2["VariableType"] = 120] = "VariableType";
261
+ return ASTNodeFlags2;
262
+ })(ASTNodeFlags || {});
263
+
264
+ // src/ast/ast-node.ts
265
+ var import_rxjs = require("rxjs");
266
+ var import_nanoid = require("nanoid");
267
+ var import_fast_equals = require("fast-equals");
268
+ var import_utils3 = require("@flowgram.ai/utils");
269
+ var ASTNode = class _ASTNode {
270
+ /**
271
+ * 构造函数
272
+ * @param createParams 创建 ASTNode 的必要参数
273
+ * @param injectOptions 依赖注入各种模块
274
+ */
275
+ constructor({ key, parent, scope }, opts) {
276
+ /**
277
+ * 节点 Flags,记录一些 Flag 信息
278
+ */
279
+ this.flags = 0 /* None */;
280
+ /**
281
+ * 节点的版本号,每 fireChange 一次 version + 1
282
+ */
283
+ this._version = 0;
284
+ /**
285
+ * 更新锁
286
+ */
287
+ this.changeLocked = false;
288
+ /**
289
+ * Batch Update 相关参数
290
+ */
291
+ this._batch = {
292
+ batching: false,
293
+ hasChangesInBatch: false
294
+ };
295
+ /**
296
+ * AST 节点变化事件,基于 Rxjs 实现
297
+ * - 使用了 BehaviorSubject, 在订阅时会自动触发一次事件,事件为当前值
298
+ */
299
+ this.value$ = new import_rxjs.BehaviorSubject(this);
300
+ /**
301
+ * 子节点
302
+ */
303
+ this._children = /* @__PURE__ */ new Set();
304
+ /**
305
+ * 删除节点处理事件列表
306
+ */
307
+ this.toDispose = new import_utils3.DisposableCollection(
308
+ import_utils3.Disposable.create(() => {
309
+ this.parent?.fireChange();
310
+ this.children.forEach((child) => child.dispose());
311
+ })
312
+ );
313
+ /**
314
+ * 销毁时触发的回调
315
+ */
316
+ this.onDispose = this.toDispose.onDispose;
317
+ this.scope = scope;
318
+ this.parent = parent;
319
+ this.opts = opts;
320
+ this.key = key || (0, import_nanoid.nanoid)();
321
+ this.fromJSON = this.withBatchUpdate(this.fromJSON.bind(this));
322
+ this.dispatchGlobalEvent({ type: "NewAST" });
323
+ }
324
+ /**
325
+ * AST 节点的类型
326
+ */
327
+ get kind() {
328
+ if (!this.constructor.kind) {
329
+ throw new Error(`ASTNode Registry need a kind: ${this.constructor.name}`);
330
+ }
331
+ return this.constructor.kind;
332
+ }
333
+ /**
334
+ * 获取当前节点所有子节点
335
+ */
336
+ get children() {
337
+ return Array.from(this._children);
338
+ }
339
+ /**
340
+ * 转化为 ASTNodeJSON
341
+ * @returns
342
+ */
343
+ toJSON() {
344
+ console.warn("[VariableEngine] Please Implement toJSON method for " + this.kind);
345
+ return {
346
+ kind: this.kind
347
+ };
348
+ }
349
+ /**
350
+ * 创建子节点
351
+ * @param json 子节点的 AST JSON
352
+ * @returns
353
+ */
354
+ createChildNode(json) {
355
+ const astRegisters = this.scope.variableEngine.astRegisters;
356
+ const child = astRegisters.createAST(json, {
357
+ parent: this,
358
+ scope: this.scope
359
+ });
360
+ this._children.add(child);
361
+ child.toDispose.push(
362
+ import_utils3.Disposable.create(() => {
363
+ this._children.delete(child);
364
+ })
365
+ );
366
+ return child;
367
+ }
368
+ /**
369
+ * 更新子节点,快速实现子节点更新消费逻辑
370
+ * @param keyInThis 当前对象上的指定 key
371
+ */
372
+ updateChildNodeByKey(keyInThis, nextJSON) {
373
+ this.withBatchUpdate(updateChildNodeHelper).call(this, {
374
+ getChildNode: () => this[keyInThis],
375
+ updateChildNode: (_node) => this[keyInThis] = _node,
376
+ removeChildNode: () => this[keyInThis] = void 0,
377
+ nextJSON
378
+ });
379
+ }
380
+ /**
381
+ * 批处理更新,批处理函数内所有的 fireChange 都合并成一个
382
+ * @param updater 批处理函数
383
+ * @returns
384
+ */
385
+ withBatchUpdate(updater) {
386
+ return (...args) => {
387
+ if (this._batch.batching) {
388
+ return updater.call(this, ...args);
389
+ }
390
+ this._batch.hasChangesInBatch = false;
391
+ this._batch.batching = true;
392
+ const res = updater.call(this, ...args);
393
+ this._batch.batching = false;
394
+ if (this._batch.hasChangesInBatch) {
395
+ this.fireChange();
396
+ }
397
+ this._batch.hasChangesInBatch = false;
398
+ return res;
399
+ };
400
+ }
401
+ /**
402
+ * 触发当前节点更新
403
+ */
404
+ fireChange() {
405
+ if (this.changeLocked || this.disposed) {
406
+ return;
407
+ }
408
+ if (this._batch.batching) {
409
+ this._batch.hasChangesInBatch = true;
410
+ return;
411
+ }
412
+ this._version++;
413
+ this.value$.next(this);
414
+ this.dispatchGlobalEvent({ type: "UpdateAST" });
415
+ this.parent?.fireChange();
416
+ }
417
+ /**
418
+ * 节点的版本值
419
+ * - 通过 NodeA === NodeB && versionA === versionB 可以比较两者是否相等
420
+ */
421
+ get version() {
422
+ return this._version;
423
+ }
424
+ /**
425
+ * 节点唯一 hash 值
426
+ */
427
+ get hash() {
428
+ return `${this._version}${this.kind}${this.key}`;
429
+ }
430
+ /**
431
+ * 监听 AST 节点的变化
432
+ * @param observer 监听回调
433
+ * @param selector 监听指定数据
434
+ * @returns
435
+ */
436
+ subscribe(observer, { selector, debounceAnimation, triggerOnInit } = {}) {
437
+ return subsToDisposable(
438
+ this.value$.pipe(
439
+ (0, import_rxjs.map)(() => selector ? selector(this) : this),
440
+ (0, import_rxjs.distinctUntilChanged)(
441
+ (a, b) => (0, import_fast_equals.shallowEqual)(a, b),
442
+ (value) => {
443
+ if (value instanceof _ASTNode) {
444
+ return value.hash;
445
+ }
446
+ return value;
447
+ }
448
+ ),
449
+ // 默认跳过 BehaviorSubject 第一次触发
450
+ triggerOnInit ? (0, import_rxjs.tap)(() => null) : (0, import_rxjs.skip)(1),
451
+ // 每个 animationFrame 内所有更新合并成一个
452
+ debounceAnimation ? (0, import_rxjs.debounceTime)(0, import_rxjs.animationFrameScheduler) : (0, import_rxjs.tap)(() => null)
453
+ ).subscribe(observer)
454
+ );
455
+ }
456
+ dispatchGlobalEvent(event) {
457
+ this.scope.event.dispatch({
458
+ ...event,
459
+ ast: this
460
+ });
461
+ }
462
+ /**
463
+ * 销毁
464
+ */
465
+ dispose() {
466
+ if (this.toDispose.disposed) {
467
+ return;
468
+ }
469
+ this.toDispose.dispose();
470
+ this.dispatchGlobalEvent({ type: "DisposeAST" });
471
+ this.value$.complete();
472
+ this.value$.unsubscribe();
473
+ }
474
+ get disposed() {
475
+ return this.toDispose.disposed;
476
+ }
477
+ };
478
+
479
+ // src/ast/type/base-type.ts
480
+ var BaseType = class extends ASTNode {
481
+ constructor() {
482
+ super(...arguments);
483
+ this.flags = 8 /* BasicType */;
484
+ }
485
+ /**
486
+ * 类型是否一致,节点有额外信息判断,请参考 extraTypeInfoEqual
487
+ * @param targetTypeJSON
488
+ */
489
+ isTypeEqual(targetTypeJSONOrKind) {
490
+ const targetTypeJSON = parseTypeJsonOrKind(targetTypeJSONOrKind);
491
+ if (targetTypeJSON?.kind === "Union" /* Union */) {
492
+ return (targetTypeJSON?.types || [])?.some(
493
+ (_subType) => this.isTypeEqual(_subType)
494
+ );
495
+ }
496
+ return this.kind === targetTypeJSON?.kind;
497
+ }
498
+ /**
499
+ * 可下钻类型需实现
500
+ * @param keyPath
501
+ */
502
+ getByKeyPath(keyPath = []) {
503
+ throw new Error(`Get By Key Path is not implemented for Type: ${this.kind}`);
504
+ }
505
+ toJSON() {
506
+ return {
507
+ kind: this.kind
508
+ };
509
+ }
510
+ };
511
+
512
+ // src/ast/type/array.ts
513
+ var ArrayType = class extends BaseType {
514
+ constructor() {
515
+ super(...arguments);
516
+ this.flags = 16 /* DrilldownType */ | 32 /* EnumerateType */;
517
+ }
518
+ fromJSON({ items }) {
519
+ this.updateChildNodeByKey("items", parseTypeJsonOrKind(items));
520
+ }
521
+ // items 类型是否可下钻
522
+ get canDrilldownItems() {
523
+ return !!(this.items?.flags & 16 /* DrilldownType */);
524
+ }
525
+ getByKeyPath(keyPath) {
526
+ const [curr, ...rest] = keyPath || [];
527
+ if (curr === "0" && this.canDrilldownItems) {
528
+ return this.items.getByKeyPath(rest);
529
+ }
530
+ return void 0;
531
+ }
532
+ isTypeEqual(targetTypeJSONOrKind) {
533
+ const targetTypeJSON = parseTypeJsonOrKind(targetTypeJSONOrKind);
534
+ const isSuperEqual = super.isTypeEqual(targetTypeJSONOrKind);
535
+ if (targetTypeJSON?.weak || targetTypeJSON?.kind === "Union" /* Union */) {
536
+ return isSuperEqual;
537
+ }
538
+ return targetTypeJSON && isSuperEqual && // 弱比较,只需要比较 Kind 即可
539
+ (targetTypeJSON?.weak || this.customStrongEqual(targetTypeJSON));
540
+ }
541
+ /**
542
+ * Array 强比较
543
+ * @param targetTypeJSON
544
+ * @returns
545
+ */
546
+ customStrongEqual(targetTypeJSON) {
547
+ if (!this.items) {
548
+ return !targetTypeJSON?.items;
549
+ }
550
+ return this.items?.isTypeEqual(targetTypeJSON.items);
551
+ }
552
+ toJSON() {
553
+ return {
554
+ kind: "Array" /* Array */,
555
+ items: this.items?.toJSON()
556
+ };
557
+ }
558
+ };
559
+ ArrayType.kind = "Array" /* Array */;
560
+
561
+ // src/ast/type/string.ts
562
+ var StringType = class extends BaseType {
563
+ constructor() {
564
+ super(...arguments);
565
+ this.flags = 8 /* BasicType */;
566
+ }
567
+ fromJSON() {
568
+ }
569
+ };
570
+ StringType.kind = "String" /* String */;
571
+
572
+ // src/ast/type/integer.ts
573
+ var IntegerType = class extends BaseType {
574
+ constructor() {
575
+ super(...arguments);
576
+ this.flags = 8 /* BasicType */;
577
+ }
578
+ fromJSON() {
579
+ }
580
+ };
581
+ IntegerType.kind = "Integer" /* Integer */;
582
+
583
+ // src/ast/type/boolean.ts
584
+ var BooleanType = class extends BaseType {
585
+ fromJSON() {
586
+ }
587
+ };
588
+ BooleanType.kind = "Boolean" /* Boolean */;
589
+
590
+ // src/ast/type/number.ts
591
+ var NumberType = class extends BaseType {
592
+ fromJSON() {
593
+ }
594
+ };
595
+ NumberType.kind = "Number" /* Number */;
596
+
597
+ // src/ast/type/map.ts
598
+ var MapType = class extends BaseType {
599
+ fromJSON({ keyType = "String" /* String */, valueType }) {
600
+ this.updateChildNodeByKey("keyType", parseTypeJsonOrKind(keyType));
601
+ this.updateChildNodeByKey("valueType", parseTypeJsonOrKind(valueType));
602
+ }
603
+ // Value 类型是否可下钻,后续实现
604
+ // get canDrilldownValue(): boolean {
605
+ // return !!(this.valueType.flags & ASTNodeFlags.DrilldownType);
606
+ // }
607
+ // getByKeyPath(keyPath: string[]): BaseVariableField | undefined {
608
+ // const [curr, ...rest] = keyPath || [];
609
+ // if (curr === '*' && this.canDrilldownValue) {
610
+ // return this.valueType.getByKeyPath(rest);
611
+ // }
612
+ // return undefined;
613
+ // }
614
+ isTypeEqual(targetTypeJSONOrKind) {
615
+ const targetTypeJSON = parseTypeJsonOrKind(targetTypeJSONOrKind);
616
+ const isSuperEqual = super.isTypeEqual(targetTypeJSONOrKind);
617
+ if (targetTypeJSON?.weak || targetTypeJSON?.kind === "Union" /* Union */) {
618
+ return isSuperEqual;
619
+ }
620
+ return targetTypeJSON && isSuperEqual && // 弱比较,只需要比较 Kind 即可
621
+ (targetTypeJSON?.weak || this.customStrongEqual(targetTypeJSON));
622
+ }
623
+ /**
624
+ * Map 强比较
625
+ * @param targetTypeJSON
626
+ * @returns
627
+ */
628
+ customStrongEqual(targetTypeJSON) {
629
+ const { keyType = "String" /* String */, valueType } = targetTypeJSON;
630
+ const isValueTypeEqual = !valueType && !this.valueType || this.valueType?.isTypeEqual(valueType);
631
+ return isValueTypeEqual && this.keyType?.isTypeEqual(keyType);
632
+ }
633
+ toJSON() {
634
+ return {
635
+ kind: "Map" /* Map */,
636
+ keyType: this.keyType?.toJSON(),
637
+ valueType: this.valueType?.toJSON()
638
+ };
639
+ }
640
+ };
641
+ // public flags: ASTNodeFlags = ASTNodeFlags.DrilldownType | ASTNodeFlags.EnumerateType;
642
+ MapType.kind = "Map" /* Map */;
643
+
644
+ // src/ast/type/object.ts
645
+ var import_lodash = require("lodash");
646
+ var ObjectType = class extends BaseType {
647
+ constructor() {
648
+ super(...arguments);
649
+ this.flags = 16 /* DrilldownType */;
650
+ this.propertyTable = /* @__PURE__ */ new Map();
651
+ }
652
+ fromJSON({ properties }) {
653
+ const removedKeys = new Set(this.propertyTable.keys());
654
+ const prev = [...this.properties || []];
655
+ this.properties = (properties || []).map((property) => {
656
+ const existProperty = this.propertyTable.get(property.key);
657
+ removedKeys.delete(property.key);
658
+ if (existProperty) {
659
+ existProperty.fromJSON(property);
660
+ return existProperty;
661
+ } else {
662
+ const newProperty = this.createChildNode({
663
+ ...property,
664
+ kind: "Property" /* Property */
665
+ });
666
+ this.fireChange();
667
+ this.propertyTable.set(property.key, newProperty);
668
+ return newProperty;
669
+ }
670
+ });
671
+ removedKeys.forEach((key) => {
672
+ const property = this.propertyTable.get(key);
673
+ property?.dispose();
674
+ this.propertyTable.delete(key);
675
+ this.fireChange();
676
+ });
677
+ this.dispatchGlobalEvent({
678
+ type: "ObjectPropertiesChange",
679
+ payload: {
680
+ prev,
681
+ next: [...this.properties]
682
+ }
683
+ });
684
+ }
685
+ toJSON() {
686
+ return {
687
+ kind: "Object" /* Object */,
688
+ properties: this.properties.map((_property) => _property.toJSON())
689
+ };
690
+ }
691
+ /**
692
+ * 根据 KeyPath 找到对应的变量
693
+ * @param keyPath 变量路径
694
+ * @returns
695
+ */
696
+ getByKeyPath(keyPath) {
697
+ const [curr, ...restKeyPath] = keyPath;
698
+ const property = this.propertyTable.get(curr);
699
+ if (!restKeyPath.length) {
700
+ return property;
701
+ }
702
+ if (property?.type && property?.type?.flags & 16 /* DrilldownType */) {
703
+ return property.type.getByKeyPath(restKeyPath);
704
+ }
705
+ return void 0;
706
+ }
707
+ isTypeEqual(targetTypeJSONOrKind) {
708
+ const targetTypeJSON = parseTypeJsonOrKind(targetTypeJSONOrKind);
709
+ const isSuperEqual = super.isTypeEqual(targetTypeJSONOrKind);
710
+ if (targetTypeJSON?.weak || targetTypeJSON?.kind === "Union" /* Union */) {
711
+ return isSuperEqual;
712
+ }
713
+ return targetTypeJSON && isSuperEqual && // 弱比较,只需要比较 Kind 即可
714
+ (targetTypeJSON?.weak || this.customStrongEqual(targetTypeJSON));
715
+ }
716
+ /**
717
+ * Object 类型强比较
718
+ * @param targetTypeJSON
719
+ * @returns
720
+ */
721
+ customStrongEqual(targetTypeJSON) {
722
+ const targetProperties = targetTypeJSON.properties || [];
723
+ const sourcePropertyKeys = Array.from(this.propertyTable.keys());
724
+ const targetPropertyKeys = targetProperties.map((_target) => _target.key);
725
+ const isKeyStrongEqual = !(0, import_lodash.xor)(sourcePropertyKeys, targetPropertyKeys).length;
726
+ return isKeyStrongEqual && targetProperties.every((targetProperty) => {
727
+ const sourceProperty = this.propertyTable.get(targetProperty.key);
728
+ return sourceProperty && sourceProperty.key === targetProperty.key && sourceProperty.type?.isTypeEqual(targetProperty?.type);
729
+ });
730
+ }
731
+ };
732
+ ObjectType.kind = "Object" /* Object */;
733
+
734
+ // src/ast/expression/base-expression.ts
735
+ var import_rxjs2 = require("rxjs");
736
+ var import_fast_equals2 = require("fast-equals");
737
+
738
+ // src/ast/utils/variable-field.ts
739
+ function getParentFields(ast) {
740
+ let curr = ast.parent;
741
+ const res = [];
742
+ while (curr) {
743
+ if (curr.flags & 1 /* VariableField */) {
744
+ res.push(curr);
745
+ }
746
+ curr = curr.parent;
747
+ }
748
+ return res;
749
+ }
750
+
751
+ // src/ast/expression/base-expression.ts
752
+ var BaseExpression = class extends ASTNode {
753
+ constructor(params, opts) {
754
+ super(params, opts);
755
+ this.flags = 4 /* Expression */;
756
+ /**
757
+ * 引用变量
758
+ */
759
+ this._refs = [];
760
+ this.refreshRefs$ = new import_rxjs2.Subject();
761
+ /**
762
+ * 监听引用变量变化
763
+ * 监听 [a.b.c] -> [a.b]
764
+ */
765
+ this.refs$ = this.refreshRefs$.pipe(
766
+ (0, import_rxjs2.map)(() => this.getRefFields()),
767
+ (0, import_rxjs2.distinctUntilChanged)(import_fast_equals2.shallowEqual),
768
+ (0, import_rxjs2.switchMap)(
769
+ (refs) => !refs?.length ? (0, import_rxjs2.of)([]) : (0, import_rxjs2.combineLatest)(
770
+ refs.map(
771
+ (ref) => ref ? ref.value$ : (0, import_rxjs2.of)(void 0)
772
+ )
773
+ )
774
+ ),
775
+ (0, import_rxjs2.share)()
776
+ );
777
+ this.toDispose.push(
778
+ subsToDisposable(
779
+ this.refs$.subscribe((_refs) => {
780
+ this._refs = _refs;
781
+ this.fireChange();
782
+ })
783
+ )
784
+ );
785
+ }
786
+ /**
787
+ * 获取全局变量表,方便表达式获取引用变量
788
+ */
789
+ get globalVariableTable() {
790
+ return this.scope.variableEngine.globalVariableTable;
791
+ }
792
+ /**
793
+ * 父变量字段,通过由近而远的方式进行排序
794
+ */
795
+ get parentFields() {
796
+ return getParentFields(this);
797
+ }
798
+ get refs() {
799
+ return this._refs;
800
+ }
801
+ /**
802
+ * 刷新变量引用
803
+ */
804
+ refreshRefs() {
805
+ this.refreshRefs$.next();
806
+ }
807
+ };
808
+
809
+ // src/ast/expression/expression-list.ts
810
+ var ExpressionList = class extends ASTNode {
811
+ fromJSON({ expressions }) {
812
+ this.expressions = expressions.map((_expression, idx) => {
813
+ const prevExpression = this.expressions[idx];
814
+ if (prevExpression.kind !== _expression.kind) {
815
+ prevExpression.dispose();
816
+ this.fireChange();
817
+ return this.createChildNode(_expression);
818
+ }
819
+ prevExpression.fromJSON(_expression);
820
+ return prevExpression;
821
+ });
822
+ }
823
+ toJSON() {
824
+ return {
825
+ kind: "ExpressionList" /* ExpressionList */,
826
+ properties: this.expressions.map((_expression) => _expression.toJSON())
827
+ };
828
+ }
829
+ };
830
+ ExpressionList.kind = "ExpressionList" /* ExpressionList */;
831
+
832
+ // src/ast/expression/keypath-expression.ts
833
+ var import_fast_equals3 = require("fast-equals");
834
+ var KeyPathExpression = class extends BaseExpression {
835
+ constructor(params, opts) {
836
+ super(params, opts);
837
+ this._keyPath = [];
838
+ this.toDispose.pushAll([
839
+ // 可以用变量列表变化时候 (有新增或者删除时)
840
+ this.scope.available.onVariableListChange(() => {
841
+ this.refreshRefs();
842
+ }),
843
+ // this._keyPath 指向的可引用变量发生变化时,刷新引用数据
844
+ this.scope.available.onAnyVariableChange((_v) => {
845
+ if (_v.key === this._keyPath[0]) {
846
+ this.refreshRefs();
847
+ }
848
+ })
849
+ ]);
850
+ }
851
+ get keyPath() {
852
+ return this._keyPath;
853
+ }
854
+ getRefFields() {
855
+ const ref = this.scope.available.getByKeyPath(this._keyPath);
856
+ return ref ? [ref] : [];
857
+ }
858
+ get returnType() {
859
+ const [refNode] = this._refs || [];
860
+ if (refNode && refNode.flags & 1 /* VariableField */) {
861
+ return refNode.type;
862
+ }
863
+ return;
864
+ }
865
+ /**
866
+ * 业务重改该方法可快速定制自己的 Path 表达式
867
+ * - 只需要将业务的 Path 解析为变量系统的 KeyPath 即可
868
+ * @param json 业务定义的 Path 表达式
869
+ * @returns
870
+ */
871
+ parseToKeyPath(json) {
872
+ return json.keyPath;
873
+ }
874
+ fromJSON(json) {
875
+ const keyPath = this.parseToKeyPath(json);
876
+ if (!(0, import_fast_equals3.shallowEqual)(keyPath, this._keyPath)) {
877
+ this._keyPath = keyPath;
878
+ this.refreshRefs();
879
+ }
880
+ }
881
+ toJSON() {
882
+ return {
883
+ kind: "KeyPathExpression" /* KeyPathExpression */,
884
+ keyPath: this._keyPath
885
+ };
886
+ }
887
+ };
888
+ KeyPathExpression.kind = "KeyPathExpression" /* KeyPathExpression */;
889
+
890
+ // src/ast/expression/enumerate-expression.ts
891
+ var EnumerateExpression = class extends BaseExpression {
892
+ get enumerateFor() {
893
+ return this._enumerateFor;
894
+ }
895
+ get returnType() {
896
+ const childReturnType = this.enumerateFor?.returnType;
897
+ if (childReturnType?.kind === "Array" /* Array */) {
898
+ return childReturnType.items;
899
+ }
900
+ return void 0;
901
+ }
902
+ getRefFields() {
903
+ return [];
904
+ }
905
+ fromJSON({ enumerateFor: expression }) {
906
+ this.updateChildNodeByKey("_enumerateFor", expression);
907
+ }
908
+ toJSON() {
909
+ return {
910
+ kind: "EnumerateExpression" /* EnumerateExpression */,
911
+ enumerateFor: this.enumerateFor?.toJSON()
912
+ };
913
+ }
914
+ };
915
+ EnumerateExpression.kind = "EnumerateExpression" /* EnumerateExpression */;
916
+
917
+ // src/ast/expression/keypath-expression-v2.ts
918
+ var import_fast_equals4 = require("fast-equals");
919
+
920
+ // src/ast/utils/expression.ts
921
+ var import_lodash2 = require("lodash");
922
+ function getAllRefs(ast) {
923
+ return getAllChildren(ast).filter((_child) => _child.flags & 4 /* Expression */).map((_child) => _child.refs).flat().filter(Boolean);
924
+ }
925
+ function checkRefCycle(curr, refNodes) {
926
+ if ((0, import_lodash2.intersection)(curr.scope.coverScopes, refNodes.map((_ref) => _ref?.scope).filter(Boolean)).length === 0) {
927
+ return false;
928
+ }
929
+ const visited = /* @__PURE__ */ new Set();
930
+ const queue = [...refNodes];
931
+ while (queue.length) {
932
+ const currNode = queue.shift();
933
+ visited.add(currNode);
934
+ for (const ref of getAllRefs(currNode).filter((_ref) => !visited.has(_ref))) {
935
+ queue.push(ref);
936
+ }
937
+ }
938
+ return (0, import_lodash2.intersection)(Array.from(visited), getParentFields(curr)).length > 0;
939
+ }
940
+
941
+ // src/ast/expression/keypath-expression-v2.ts
942
+ var KeyPathExpressionV2 = class extends BaseExpression {
943
+ constructor(params, opts) {
944
+ super(params, opts);
945
+ this._keyPath = [];
946
+ this.toDispose.pushAll([
947
+ // 可以用变量列表变化时候 (有新增或者删除时)
948
+ this.scope.available.onVariableListChange(() => {
949
+ this.refreshRefs();
950
+ }),
951
+ // this._keyPath 指向的可引用变量发生变化时,刷新引用数据
952
+ this.scope.available.onAnyVariableChange((_v) => {
953
+ if (_v.key === this._keyPath[0]) {
954
+ this.refreshRefs();
955
+ }
956
+ }),
957
+ subsToDisposable(
958
+ this.refs$.subscribe((_type) => {
959
+ const [ref] = this._refs;
960
+ if (this.prevRefTypeHash !== ref?.type?.hash) {
961
+ this.prevRefTypeHash = ref?.type?.hash;
962
+ this.updateChildNodeByKey("_returnType", this.getReturnTypeJSONByRef(ref));
963
+ }
964
+ })
965
+ )
966
+ ]);
967
+ }
968
+ get keyPath() {
969
+ return this._keyPath;
970
+ }
971
+ getRefFields() {
972
+ const ref = this.scope.available.getByKeyPath(this._keyPath);
973
+ if (checkRefCycle(this, [ref])) {
974
+ console.warn(
975
+ "[CustomKeyPathExpression] checkRefCycle: Reference Cycle Existed",
976
+ this.parentFields.map((_field) => _field.key).reverse()
977
+ );
978
+ return [];
979
+ }
980
+ return ref ? [ref] : [];
981
+ }
982
+ get returnType() {
983
+ return this._returnType;
984
+ }
985
+ /**
986
+ * 业务重改该方法可快速定制自己的 Path 表达式
987
+ * - 只需要将业务的 Path 解析为变量系统的 KeyPath 即可
988
+ * @param json 业务定义的 Path 表达式
989
+ * @returns
990
+ */
991
+ parseToKeyPath(json) {
992
+ return json.keyPath;
993
+ }
994
+ fromJSON(json) {
995
+ const keyPath = this.parseToKeyPath(json);
996
+ if (!(0, import_fast_equals4.shallowEqual)(keyPath, this._keyPath)) {
997
+ this._keyPath = keyPath;
998
+ this.refreshRefs();
999
+ }
1000
+ }
1001
+ getReturnTypeJSONByRef(_ref) {
1002
+ return _ref?.type?.toJSON();
1003
+ }
1004
+ toJSON() {
1005
+ return {
1006
+ kind: "KeyPathExpression" /* KeyPathExpression */,
1007
+ keyPath: this._keyPath
1008
+ };
1009
+ }
1010
+ };
1011
+ KeyPathExpressionV2.kind = "KeyPathExpression" /* KeyPathExpression */;
1012
+
1013
+ // src/ast/declaration/variable-declaration.ts
1014
+ var import_utils4 = require("@flowgram.ai/utils");
1015
+
1016
+ // src/ast/declaration/base-variable-field.ts
1017
+ var import_fast_equals5 = require("fast-equals");
1018
+ var BaseVariableField = class extends ASTNode {
1019
+ constructor() {
1020
+ super(...arguments);
1021
+ this.flags = 1 /* VariableField */;
1022
+ this._meta = {};
1023
+ }
1024
+ /**
1025
+ * 父变量字段,通过由近而远的方式进行排序
1026
+ */
1027
+ get parentFields() {
1028
+ return getParentFields(this);
1029
+ }
1030
+ get meta() {
1031
+ return this._meta;
1032
+ }
1033
+ get type() {
1034
+ return this._initializer?.returnType || this._type;
1035
+ }
1036
+ get initializer() {
1037
+ return this._initializer;
1038
+ }
1039
+ /**
1040
+ * 解析 VariableDeclarationJSON 从而生成变量声明节点
1041
+ */
1042
+ fromJSON({ type, initializer, meta }) {
1043
+ this.updateType(type);
1044
+ this.updateInitializer(initializer);
1045
+ this.updateMeta(meta);
1046
+ }
1047
+ updateType(type) {
1048
+ const nextTypeJson = typeof type === "string" ? { kind: type } : type;
1049
+ this.updateChildNodeByKey("_type", nextTypeJson);
1050
+ }
1051
+ updateInitializer(nextInitializer) {
1052
+ this.updateChildNodeByKey("_initializer", nextInitializer);
1053
+ }
1054
+ updateMeta(nextMeta) {
1055
+ if (!(0, import_fast_equals5.shallowEqual)(nextMeta, this._meta)) {
1056
+ this._meta = nextMeta;
1057
+ this.fireChange();
1058
+ }
1059
+ }
1060
+ /**
1061
+ * 根据 keyPath 去找下钻的变量字段
1062
+ * @param keyPath
1063
+ * @returns
1064
+ */
1065
+ getByKeyPath(keyPath) {
1066
+ if (this.type?.flags & 16 /* DrilldownType */) {
1067
+ return this.type.getByKeyPath(keyPath);
1068
+ }
1069
+ return void 0;
1070
+ }
1071
+ /**
1072
+ * 监听类型变化
1073
+ * @param observer
1074
+ * @returns
1075
+ */
1076
+ onTypeChange(observer) {
1077
+ return this.subscribe(observer, { selector: (curr) => curr.type });
1078
+ }
1079
+ /**
1080
+ * 转换为 JSON
1081
+ * @returns
1082
+ */
1083
+ toJSON() {
1084
+ return {
1085
+ kind: this.kind,
1086
+ key: this.key,
1087
+ type: this.type?.toJSON(),
1088
+ initializer: this.initializer?.toJSON(),
1089
+ meta: this._meta
1090
+ };
1091
+ }
1092
+ };
1093
+
1094
+ // src/ast/declaration/variable-declaration.ts
1095
+ var VariableDeclaration = class extends BaseVariableField {
1096
+ constructor(params) {
1097
+ super(params);
1098
+ this._order = 0;
1099
+ this.scope.output.addVariableToTable(this);
1100
+ this.toDispose.push(
1101
+ import_utils4.Disposable.create(() => {
1102
+ this.scope.output.setHasChanges();
1103
+ this.scope.output.removeVariableFromTable(this.key);
1104
+ })
1105
+ );
1106
+ }
1107
+ get order() {
1108
+ return this._order;
1109
+ }
1110
+ /**
1111
+ * 解析 VariableDeclarationJSON 从而生成变量声明节点
1112
+ */
1113
+ fromJSON({ order, ...rest }) {
1114
+ this.updateOrder(order);
1115
+ super.fromJSON(rest);
1116
+ }
1117
+ updateOrder(order = 0) {
1118
+ if (order !== this._order) {
1119
+ this._order = order;
1120
+ this.scope.output.setHasChanges();
1121
+ this.fireChange();
1122
+ }
1123
+ }
1124
+ // 监听类型变化
1125
+ onTypeChange(observer) {
1126
+ return this.subscribe(observer, { selector: (curr) => curr.type });
1127
+ }
1128
+ };
1129
+ VariableDeclaration.kind = "VariableDeclaration" /* VariableDeclaration */;
1130
+
1131
+ // src/ast/declaration/variable-declaration-list.ts
1132
+ var VariableDeclarationList = class extends ASTNode {
1133
+ constructor() {
1134
+ super(...arguments);
1135
+ this.declarationTable = /* @__PURE__ */ new Map();
1136
+ }
1137
+ fromJSON({ declarations, startOrder }) {
1138
+ const removedKeys = new Set(this.declarationTable.keys());
1139
+ const prev = [...this.declarations || []];
1140
+ this.declarations = (declarations || []).map(
1141
+ (declaration, idx) => {
1142
+ const order = (startOrder || 0) + idx;
1143
+ const declarationKey = declaration.key || this.declarations?.[idx]?.key;
1144
+ const existDeclaration = this.declarationTable.get(declarationKey);
1145
+ if (declarationKey) {
1146
+ removedKeys.delete(declarationKey);
1147
+ }
1148
+ if (existDeclaration) {
1149
+ existDeclaration.fromJSON({ order, ...declaration });
1150
+ return existDeclaration;
1151
+ } else {
1152
+ const newDeclaration = this.createChildNode({
1153
+ order,
1154
+ ...declaration,
1155
+ kind: "VariableDeclaration" /* VariableDeclaration */
1156
+ });
1157
+ this.fireChange();
1158
+ this.declarationTable.set(newDeclaration.key, newDeclaration);
1159
+ return newDeclaration;
1160
+ }
1161
+ }
1162
+ );
1163
+ removedKeys.forEach((key) => {
1164
+ const declaration = this.declarationTable.get(key);
1165
+ declaration?.dispose();
1166
+ this.declarationTable.delete(key);
1167
+ });
1168
+ this.dispatchGlobalEvent({
1169
+ type: "VariableListChange",
1170
+ payload: {
1171
+ prev,
1172
+ next: [...this.declarations]
1173
+ }
1174
+ });
1175
+ }
1176
+ toJSON() {
1177
+ return {
1178
+ kind: "VariableDeclarationList" /* VariableDeclarationList */,
1179
+ properties: this.declarations.map((_declaration) => _declaration.toJSON())
1180
+ };
1181
+ }
1182
+ };
1183
+ VariableDeclarationList.kind = "VariableDeclarationList" /* VariableDeclarationList */;
1184
+
1185
+ // src/ast/declaration/property.ts
1186
+ var Property = class extends BaseVariableField {
1187
+ };
1188
+ Property.kind = "Property" /* Property */;
1189
+
1190
+ // src/ast/common/data-node.ts
1191
+ var import_fast_equals6 = require("fast-equals");
1192
+ var DataNode = class extends ASTNode {
1193
+ get data() {
1194
+ return this._data;
1195
+ }
1196
+ fromJSON(json) {
1197
+ const { kind, ...restData } = json;
1198
+ if (!(0, import_fast_equals6.shallowEqual)(restData, this._data)) {
1199
+ this._data = restData;
1200
+ this.fireChange();
1201
+ }
1202
+ }
1203
+ toJSON() {
1204
+ return {
1205
+ kind: "DataNode" /* DataNode */,
1206
+ ...this._data
1207
+ };
1208
+ }
1209
+ partialUpdate(nextData) {
1210
+ if (!(0, import_fast_equals6.shallowEqual)(nextData, this._data)) {
1211
+ this._data = {
1212
+ ...this._data,
1213
+ ...nextData
1214
+ };
1215
+ this.fireChange();
1216
+ }
1217
+ }
1218
+ };
1219
+ DataNode.kind = "DataNode" /* DataNode */;
1220
+
1221
+ // src/ast/common/list-node.ts
1222
+ var ListNode = class extends ASTNode {
1223
+ get list() {
1224
+ return this._list;
1225
+ }
1226
+ fromJSON({ list }) {
1227
+ this._list.slice(list.length).forEach((_item) => {
1228
+ _item.dispose();
1229
+ this.fireChange();
1230
+ });
1231
+ this._list = list.map((_item, idx) => {
1232
+ const prevItem = this._list[idx];
1233
+ if (prevItem.kind !== _item.kind) {
1234
+ prevItem.dispose();
1235
+ this.fireChange();
1236
+ return this.createChildNode(_item);
1237
+ }
1238
+ prevItem.fromJSON(_item);
1239
+ return prevItem;
1240
+ });
1241
+ }
1242
+ toJSON() {
1243
+ return {
1244
+ kind: "ListNode" /* ListNode */,
1245
+ list: this._list.map((item) => item.toJSON())
1246
+ };
1247
+ }
1248
+ };
1249
+ ListNode.kind = "ListNode" /* ListNode */;
1250
+
1251
+ // src/ast/common/map-node.ts
1252
+ var MapNode = class extends ASTNode {
1253
+ constructor() {
1254
+ super(...arguments);
1255
+ this.map = /* @__PURE__ */ new Map();
1256
+ }
1257
+ fromJSON({ map: map4 }) {
1258
+ const removedKeys = new Set(this.map.keys());
1259
+ for (const [key, item] of map4 || []) {
1260
+ removedKeys.delete(key);
1261
+ this.set(key, item);
1262
+ }
1263
+ for (const removeKey of Array.from(removedKeys)) {
1264
+ this.remove(removeKey);
1265
+ }
1266
+ }
1267
+ toJSON() {
1268
+ return {
1269
+ kind: "MapNode" /* MapNode */,
1270
+ map: Array.from(this.map.entries())
1271
+ };
1272
+ }
1273
+ /**
1274
+ * 往 Map 中设置 ASTNode
1275
+ * @param key ASTNode 的索引,
1276
+ * @param json
1277
+ */
1278
+ set(key, nextJSON) {
1279
+ return this.withBatchUpdate(updateChildNodeHelper).call(this, {
1280
+ getChildNode: () => this.get(key),
1281
+ removeChildNode: () => this.map.delete(key),
1282
+ updateChildNode: (nextNode) => this.map.set(key, nextNode),
1283
+ nextJSON
1284
+ });
1285
+ }
1286
+ /**
1287
+ * 移除指定 ASTNode
1288
+ * @param key
1289
+ */
1290
+ remove(key) {
1291
+ this.get(key)?.dispose();
1292
+ this.map.delete(key);
1293
+ this.fireChange();
1294
+ }
1295
+ /**
1296
+ * 获取 ASTNode
1297
+ * @param key
1298
+ * @returns
1299
+ */
1300
+ get(key) {
1301
+ return this.map.get(key);
1302
+ }
1303
+ };
1304
+ MapNode.kind = "MapNode" /* MapNode */;
1305
+
1306
+ // src/ast/ast-registers.ts
1307
+ var ASTRegisters = class {
1308
+ /**
1309
+ * 核心 AST 节点注册
1310
+ */
1311
+ constructor() {
1312
+ this.injectors = /* @__PURE__ */ new Map();
1313
+ this.astMap = /* @__PURE__ */ new Map();
1314
+ this.registerAST(StringType);
1315
+ this.registerAST(NumberType);
1316
+ this.registerAST(BooleanType);
1317
+ this.registerAST(IntegerType);
1318
+ this.registerAST(ObjectType);
1319
+ this.registerAST(ArrayType);
1320
+ this.registerAST(MapType);
1321
+ this.registerAST(Property);
1322
+ this.registerAST(VariableDeclaration);
1323
+ this.registerAST(VariableDeclarationList);
1324
+ this.registerAST(KeyPathExpression);
1325
+ this.registerAST(EnumerateExpression);
1326
+ this.registerAST(ExpressionList);
1327
+ this.registerAST(MapNode);
1328
+ this.registerAST(DataNode);
1329
+ }
1330
+ /**
1331
+ * 创建 AST 节点
1332
+ * @param param 创建参数
1333
+ * @returns
1334
+ */
1335
+ createAST(json, { parent, scope }) {
1336
+ const Registry = this.astMap.get(json.kind);
1337
+ if (!Registry) {
1338
+ throw Error(`ASTKind: ${String(json.kind)} can not find its ASTNode Registry`);
1339
+ }
1340
+ const injector = this.injectors.get(json.kind);
1341
+ const node = new Registry(
1342
+ {
1343
+ key: json.key,
1344
+ scope,
1345
+ parent
1346
+ },
1347
+ injector?.() || {}
1348
+ );
1349
+ node.changeLocked = true;
1350
+ node.fromJSON((0, import_lodash3.omit)(json, ["key", "kind"]));
1351
+ node.changeLocked = false;
1352
+ if (Reflect.hasMetadata(POST_CONSTRUCT_AST_SYMBOL, node)) {
1353
+ const postConstructKey = Reflect.getMetadata(POST_CONSTRUCT_AST_SYMBOL, node);
1354
+ node[postConstructKey]?.();
1355
+ }
1356
+ return node;
1357
+ }
1358
+ /**
1359
+ * 根据 AST 节点类型获取节点 Registry
1360
+ * @param kind
1361
+ * @returns
1362
+ */
1363
+ getASTRegistryByKind(kind) {
1364
+ return this.astMap.get(kind);
1365
+ }
1366
+ /**
1367
+ * 注册 AST 节点
1368
+ * @param ASTNode
1369
+ * @param injector
1370
+ */
1371
+ registerAST(ASTNode2, injector) {
1372
+ this.astMap.set(ASTNode2.kind, ASTNode2);
1373
+ if (injector) {
1374
+ this.injectors.set(ASTNode2.kind, injector);
1375
+ }
1376
+ }
1377
+ };
1378
+ ASTRegisters = __decorateClass([
1379
+ (0, import_inversify2.injectable)()
1380
+ ], ASTRegisters);
1381
+
1382
+ // src/ast/factory.ts
1383
+ var ASTFactory;
1384
+ ((ASTFactory2) => {
1385
+ ASTFactory2.createString = () => ({ kind: "String" /* String */ });
1386
+ ASTFactory2.createNumber = () => ({ kind: "Number" /* Number */ });
1387
+ ASTFactory2.createBoolean = () => ({ kind: "Boolean" /* Boolean */ });
1388
+ ASTFactory2.createInteger = () => ({ kind: "Integer" /* Integer */ });
1389
+ ASTFactory2.createObject = (json) => ({
1390
+ kind: "Object" /* Object */,
1391
+ ...json
1392
+ });
1393
+ ASTFactory2.createArray = (json) => ({
1394
+ kind: "Array" /* Array */,
1395
+ ...json
1396
+ });
1397
+ ASTFactory2.createMap = (json) => ({
1398
+ kind: "Map" /* Map */,
1399
+ ...json
1400
+ });
1401
+ ASTFactory2.createUnion = (json) => ({
1402
+ kind: "Union" /* Union */,
1403
+ ...json
1404
+ });
1405
+ ASTFactory2.createVariableDeclaration = (json) => ({
1406
+ kind: "VariableDeclaration" /* VariableDeclaration */,
1407
+ ...json
1408
+ });
1409
+ ASTFactory2.createProperty = (json) => ({
1410
+ kind: "Property" /* Property */,
1411
+ ...json
1412
+ });
1413
+ ASTFactory2.createVariableDeclarationList = (json) => ({
1414
+ kind: "VariableDeclarationList" /* VariableDeclarationList */,
1415
+ ...json
1416
+ });
1417
+ ASTFactory2.createEnumerateExpression = (json) => ({
1418
+ kind: "EnumerateExpression" /* EnumerateExpression */,
1419
+ ...json
1420
+ });
1421
+ ASTFactory2.createKeyPathExpression = (json) => ({
1422
+ kind: "KeyPathExpression" /* KeyPathExpression */,
1423
+ ...json
1424
+ });
1425
+ })(ASTFactory || (ASTFactory = {}));
1426
+
1427
+ // src/scope/variable-table.ts
1428
+ var import_rxjs3 = require("rxjs");
1429
+ var import_utils5 = require("@flowgram.ai/utils");
1430
+ var import_utils6 = require("@flowgram.ai/utils");
1431
+ var VariableTable = class {
1432
+ constructor(parentTable) {
1433
+ this.parentTable = parentTable;
1434
+ this.table = /* @__PURE__ */ new Map();
1435
+ this.onDataChangeEmitter = new import_utils5.Emitter();
1436
+ this.variables$ = new import_rxjs3.Subject();
1437
+ // 监听变量列表中的单个变量变化
1438
+ this.anyVariableChange$ = this.variables$.pipe(
1439
+ (0, import_rxjs3.switchMap)(
1440
+ (_variables) => (0, import_rxjs3.merge)(
1441
+ ..._variables.map(
1442
+ (_v) => _v.value$.pipe(
1443
+ // 跳过 BehaviorSubject 第一个
1444
+ (0, import_rxjs3.skip)(1)
1445
+ )
1446
+ )
1447
+ )
1448
+ ),
1449
+ (0, import_rxjs3.share)()
1450
+ );
1451
+ this.onDataChange = this.onDataChangeEmitter.event;
1452
+ this._version = 0;
1453
+ }
1454
+ /**
1455
+ * 监听任意变量变化
1456
+ * @param observer 监听器,变量变化时会吐出值
1457
+ * @returns
1458
+ */
1459
+ onAnyVariableChange(observer) {
1460
+ return subsToDisposable(this.anyVariableChange$.subscribe(observer));
1461
+ }
1462
+ /**
1463
+ * 列表或者任意变量变化
1464
+ * @param observer
1465
+ */
1466
+ onAnyChange(observer) {
1467
+ const disposables = new import_utils6.DisposableCollection();
1468
+ disposables.pushAll([this.onDataChange(observer), this.onAnyVariableChange(observer)]);
1469
+ return disposables;
1470
+ }
1471
+ fireChange() {
1472
+ this._version++;
1473
+ this.onDataChangeEmitter.fire();
1474
+ this.parentTable?.fireChange();
1475
+ }
1476
+ get version() {
1477
+ return this._version;
1478
+ }
1479
+ get variables() {
1480
+ return Array.from(this.table.values());
1481
+ }
1482
+ get variableKeys() {
1483
+ return Array.from(this.table.keys());
1484
+ }
1485
+ /**
1486
+ * 根据 keyPath 找到对应的变量,或 Property 节点
1487
+ * @param keyPath
1488
+ * @returns
1489
+ */
1490
+ getByKeyPath(keyPath) {
1491
+ const [variableKey, ...propertyKeys] = keyPath || [];
1492
+ if (!variableKey) {
1493
+ return;
1494
+ }
1495
+ const variable = this.getVariableByKey(variableKey);
1496
+ return propertyKeys.length ? variable?.getByKeyPath(propertyKeys) : variable;
1497
+ }
1498
+ /**
1499
+ * 根据 key 值找到相应的变量
1500
+ * @param key
1501
+ * @returns
1502
+ */
1503
+ getVariableByKey(key) {
1504
+ return this.table.get(key);
1505
+ }
1506
+ /**
1507
+ * 往 variableTable 添加输出变量
1508
+ * @param variable
1509
+ */
1510
+ addVariableToTable(variable) {
1511
+ this.table.set(variable.key, variable);
1512
+ if (this.parentTable) {
1513
+ this.parentTable.addVariableToTable(variable);
1514
+ }
1515
+ this.variables$.next(this.variables);
1516
+ }
1517
+ /**
1518
+ * 从 variableTable 中移除变量
1519
+ * @param key
1520
+ */
1521
+ removeVariableFromTable(key) {
1522
+ this.table.delete(key);
1523
+ if (this.parentTable) {
1524
+ this.parentTable.removeVariableFromTable(key);
1525
+ }
1526
+ this.variables$.next(this.variables);
1527
+ }
1528
+ dispose() {
1529
+ this.variableKeys.forEach((_key) => this.parentTable?.removeVariableFromTable(_key));
1530
+ this.onDataChangeEmitter.dispose();
1531
+ }
1532
+ };
1533
+
1534
+ // src/scope/datas/scope-output-data.ts
1535
+ var ScopeOutputData = class {
1536
+ constructor(scope) {
1537
+ this.scope = scope;
1538
+ this.memo = createMemo();
1539
+ this._hasChanges = false;
1540
+ this.variableTable = new VariableTable(scope.variableEngine.globalVariableTable);
1541
+ this.scope.toDispose.pushAll([
1542
+ // AST 根节点更新时,检查在这次 AST 变化期间节点是否有变化
1543
+ this.scope.ast.subscribe(() => {
1544
+ if (this._hasChanges) {
1545
+ this.memo.clear();
1546
+ this.notifyCoversChange();
1547
+ this.variableTable.fireChange();
1548
+ this._hasChanges = false;
1549
+ }
1550
+ }),
1551
+ this.variableTable
1552
+ ]);
1553
+ }
1554
+ get variableEngine() {
1555
+ return this.scope.variableEngine;
1556
+ }
1557
+ get globalVariableTable() {
1558
+ return this.scope.variableEngine.globalVariableTable;
1559
+ }
1560
+ get onDataChange() {
1561
+ return this.variableTable.onDataChange.bind(this.variableTable);
1562
+ }
1563
+ get onAnyVariableChange() {
1564
+ return this.variableTable.onAnyVariableChange.bind(this.variableTable);
1565
+ }
1566
+ /**
1567
+ * 作用域输出变量
1568
+ */
1569
+ get variables() {
1570
+ return this.memo(
1571
+ "variables",
1572
+ () => this.variableTable.variables.sort((a, b) => a.order - b.order)
1573
+ );
1574
+ }
1575
+ /**
1576
+ * 输出的变量 keys
1577
+ */
1578
+ get variableKeys() {
1579
+ return this.memo("variableKeys", () => this.variableTable.variableKeys);
1580
+ }
1581
+ addVariableToTable(variable) {
1582
+ if (variable.scope !== this.scope) {
1583
+ throw Error("VariableDeclaration must be a ast node in scope");
1584
+ }
1585
+ this.variableTable.addVariableToTable(variable);
1586
+ this._hasChanges = true;
1587
+ }
1588
+ // 标记为发生了变化,用于变量排序变化的场景
1589
+ setHasChanges() {
1590
+ this._hasChanges = true;
1591
+ }
1592
+ removeVariableFromTable(key) {
1593
+ this.variableTable.removeVariableFromTable(key);
1594
+ this._hasChanges = true;
1595
+ }
1596
+ getVariableByKey(key) {
1597
+ return this.variableTable.getVariableByKey(key);
1598
+ }
1599
+ // 通知覆盖作用域更新可用变量
1600
+ notifyCoversChange() {
1601
+ this.scope.coverScopes.forEach((scope) => scope.available.refresh());
1602
+ }
1603
+ };
1604
+
1605
+ // src/scope/datas/scope-available-data.ts
1606
+ var import_rxjs4 = require("rxjs");
1607
+ var import_lodash4 = require("lodash");
1608
+ var import_fast_equals7 = require("fast-equals");
1609
+ var import_utils7 = require("@flowgram.ai/utils");
1610
+ var import_utils8 = require("@flowgram.ai/utils");
1611
+ var ScopeAvailableData = class {
1612
+ constructor(scope) {
1613
+ this.scope = scope;
1614
+ this.memo = createMemo();
1615
+ this.refresh$ = new import_rxjs4.Subject();
1616
+ this._variables = [];
1617
+ /**
1618
+ * 监听
1619
+ */
1620
+ this.variables$ = this.refresh$.pipe(
1621
+ // 输出变量是否 version 发生变化
1622
+ (0, import_rxjs4.map)(() => (0, import_lodash4.flatten)(this.depScopes.map((scope) => scope.output.variables || []))),
1623
+ // 变量列表浅比较
1624
+ (0, import_rxjs4.distinctUntilChanged)(import_fast_equals7.shallowEqual),
1625
+ (0, import_rxjs4.share)()
1626
+ );
1627
+ // 监听变量列表中的单个变量变化
1628
+ this.anyVariableChange$ = this.variables$.pipe(
1629
+ (0, import_rxjs4.switchMap)(
1630
+ (_variables) => (0, import_rxjs4.merge)(
1631
+ ..._variables.map(
1632
+ (_v) => _v.value$.pipe(
1633
+ // 跳过 BehaviorSubject 第一个
1634
+ (0, import_rxjs4.skip)(1)
1635
+ )
1636
+ )
1637
+ )
1638
+ ),
1639
+ (0, import_rxjs4.share)()
1640
+ );
1641
+ this.onDataChangeEmitter = new import_utils8.Emitter();
1642
+ /**
1643
+ * 监听变量列表变化 + 任意子变量变化
1644
+ */
1645
+ this.onDataChange = this.onDataChangeEmitter.event;
1646
+ this.scope.toDispose.pushAll([
1647
+ this.onVariableListChange((_variables) => {
1648
+ this._variables = _variables;
1649
+ this.memo.clear();
1650
+ this.onDataChangeEmitter.fire(this._variables);
1651
+ }),
1652
+ this.onAnyVariableChange(() => {
1653
+ this.onDataChangeEmitter.fire(this._variables);
1654
+ }),
1655
+ import_utils7.Disposable.create(() => {
1656
+ this.refresh$.complete();
1657
+ this.refresh$.unsubscribe();
1658
+ })
1659
+ ]);
1660
+ }
1661
+ get globalVariableTable() {
1662
+ return this.scope.variableEngine.globalVariableTable;
1663
+ }
1664
+ // 刷新可访问变量列表
1665
+ refresh() {
1666
+ if (this.scope.disposed) {
1667
+ return;
1668
+ }
1669
+ this.refresh$.next();
1670
+ }
1671
+ /**
1672
+ * 监听任意变量变化
1673
+ * @param observer 监听器,变量变化时会吐出值
1674
+ * @returns
1675
+ */
1676
+ onAnyVariableChange(observer) {
1677
+ return subsToDisposable(this.anyVariableChange$.subscribe(observer));
1678
+ }
1679
+ /**
1680
+ * 监听变量列表变化
1681
+ * @param observer
1682
+ * @returns
1683
+ */
1684
+ onVariableListChange(observer) {
1685
+ return subsToDisposable(this.variables$.subscribe(observer));
1686
+ }
1687
+ /**
1688
+ * 获取可消费变量
1689
+ */
1690
+ get variables() {
1691
+ return this._variables;
1692
+ }
1693
+ /**
1694
+ * 获取可访问的变量 keys
1695
+ */
1696
+ get variableKeys() {
1697
+ return this.memo("availableKeys", () => this._variables.map((_v) => _v.key));
1698
+ }
1699
+ /**
1700
+ * 返回依赖的作用域
1701
+ */
1702
+ get depScopes() {
1703
+ return this.scope.depScopes;
1704
+ }
1705
+ /**
1706
+ * 通过 keyPath 找到可用变量
1707
+ * @param keyPath
1708
+ * @returns
1709
+ */
1710
+ getByKeyPath(keyPath = []) {
1711
+ if (!this.variableKeys.includes(keyPath[0])) {
1712
+ return;
1713
+ }
1714
+ return this.globalVariableTable.getByKeyPath(keyPath);
1715
+ }
1716
+ };
1717
+
1718
+ // src/scope/datas/scope-event-data.ts
1719
+ var import_rxjs5 = require("rxjs");
1720
+ var ScopeEventData = class {
1721
+ constructor(scope) {
1722
+ this.scope = scope;
1723
+ this.event$ = new import_rxjs5.Subject();
1724
+ scope.toDispose.pushAll([
1725
+ this.subscribe((_action) => {
1726
+ scope.variableEngine.fireGlobalEvent(_action);
1727
+ })
1728
+ ]);
1729
+ }
1730
+ dispatch(action) {
1731
+ if (this.scope.disposed) {
1732
+ return;
1733
+ }
1734
+ this.event$.next(action);
1735
+ }
1736
+ subscribe(observer) {
1737
+ return subsToDisposable(this.event$.subscribe(observer));
1738
+ }
1739
+ on(type, observer) {
1740
+ return subsToDisposable(
1741
+ this.event$.pipe((0, import_rxjs5.filter)((_action) => _action.type === type)).subscribe(observer)
1742
+ );
1743
+ }
1744
+ };
1745
+
1746
+ // src/scope/scope.ts
1747
+ var Scope = class {
1748
+ constructor(options) {
1749
+ /**
1750
+ * 数据缓存
1751
+ */
1752
+ this.memo = createMemo();
1753
+ this.toDispose = new import_utils9.DisposableCollection();
1754
+ this.onDispose = this.toDispose.onDispose;
1755
+ this.id = options.id;
1756
+ this.meta = options.meta || {};
1757
+ this.variableEngine = options.variableEngine;
1758
+ this.event = new ScopeEventData(this);
1759
+ this.ast = this.variableEngine.astRegisters.createAST(
1760
+ {
1761
+ kind: "MapNode" /* MapNode */,
1762
+ key: this.id
1763
+ },
1764
+ {
1765
+ scope: this
1766
+ }
1767
+ );
1768
+ this.output = new ScopeOutputData(this);
1769
+ this.available = new ScopeAvailableData(this);
1770
+ }
1771
+ refreshCovers() {
1772
+ this.memo.clear("covers");
1773
+ }
1774
+ refreshDeps() {
1775
+ this.memo.clear("deps");
1776
+ this.available.refresh();
1777
+ }
1778
+ get depScopes() {
1779
+ return this.memo(
1780
+ "deps",
1781
+ () => this.variableEngine.chain.getDeps(this).filter((_scope) => Boolean(_scope) && !_scope?.disposed)
1782
+ );
1783
+ }
1784
+ get coverScopes() {
1785
+ return this.memo(
1786
+ "covers",
1787
+ () => this.variableEngine.chain.getCovers(this).filter((_scope) => Boolean(_scope) && !_scope?.disposed)
1788
+ );
1789
+ }
1790
+ dispose() {
1791
+ this.ast.dispose();
1792
+ this.toDispose.dispose();
1793
+ this.coverScopes.forEach((_scope) => _scope.refreshDeps());
1794
+ this.depScopes.forEach((_scope) => _scope.refreshCovers());
1795
+ }
1796
+ get disposed() {
1797
+ return this.toDispose.disposed;
1798
+ }
1799
+ };
1800
+
1801
+ // src/variable-engine.ts
1802
+ var VariableEngine = class {
1803
+ constructor(chain, astRegisters) {
1804
+ this.chain = chain;
1805
+ this.astRegisters = astRegisters;
1806
+ this.toDispose = new import_utils10.DisposableCollection();
1807
+ this.memo = createMemo();
1808
+ this.scopeMap = /* @__PURE__ */ new Map();
1809
+ this.globalEvent$ = new import_rxjs6.Subject();
1810
+ this.onScopeChangeEmitter = new import_utils11.Emitter();
1811
+ this.globalVariableTable = new VariableTable();
1812
+ this.onScopeChange = this.onScopeChangeEmitter.event;
1813
+ this.toDispose.pushAll([
1814
+ chain,
1815
+ import_utils10.Disposable.create(() => {
1816
+ this.getAllScopes().forEach((scope) => scope.dispose());
1817
+ this.globalVariableTable.dispose();
1818
+ })
1819
+ ]);
1820
+ }
1821
+ get container() {
1822
+ return this.containerProvider();
1823
+ }
1824
+ dispose() {
1825
+ this.toDispose.dispose();
1826
+ }
1827
+ // 根据 scopeId 找到作用域
1828
+ getScopeById(scopeId) {
1829
+ return this.scopeMap.get(scopeId);
1830
+ }
1831
+ // 移除作用域
1832
+ removeScopeById(scopeId) {
1833
+ this.getScopeById(scopeId)?.dispose();
1834
+ }
1835
+ // 获取 Scope,如果 Scope 存在且类型相同,则会直接使用
1836
+ createScope(id, meta) {
1837
+ let scope = this.getScopeById(id);
1838
+ if (!scope) {
1839
+ scope = new Scope({ variableEngine: this, meta, id });
1840
+ this.scopeMap.set(id, scope);
1841
+ this.onScopeChangeEmitter.fire({ type: "add", scope });
1842
+ scope.toDispose.pushAll([
1843
+ scope.ast.subscribe(() => {
1844
+ this.onScopeChangeEmitter.fire({ type: "update", scope });
1845
+ }),
1846
+ // 可用变量发生变化
1847
+ scope.available.onDataChange(() => {
1848
+ this.onScopeChangeEmitter.fire({ type: "available", scope });
1849
+ })
1850
+ ]);
1851
+ scope.onDispose(() => {
1852
+ this.scopeMap.delete(id);
1853
+ this.onScopeChangeEmitter.fire({ type: "delete", scope });
1854
+ });
1855
+ }
1856
+ return scope;
1857
+ }
1858
+ // 获取系统中所有的作用域
1859
+ getAllScopes({
1860
+ sort
1861
+ } = {}) {
1862
+ const allScopes = Array.from(this.scopeMap.values());
1863
+ if (sort) {
1864
+ const sortScopes = this.chain.sortAll();
1865
+ const remainScopes = new Set(allScopes);
1866
+ sortScopes.forEach((_scope) => remainScopes.delete(_scope));
1867
+ return [...sortScopes, ...Array.from(remainScopes)];
1868
+ }
1869
+ return [...allScopes];
1870
+ }
1871
+ fireGlobalEvent(event) {
1872
+ this.globalEvent$.next(event);
1873
+ }
1874
+ onGlobalEvent(type, observer) {
1875
+ return subsToDisposable(
1876
+ this.globalEvent$.subscribe((_action) => {
1877
+ if (_action.type === type) {
1878
+ observer(_action);
1879
+ }
1880
+ })
1881
+ );
1882
+ }
1883
+ };
1884
+ __decorateClass([
1885
+ (0, import_inversify5.inject)(ContainerProvider)
1886
+ ], VariableEngine.prototype, "containerProvider", 2);
1887
+ __decorateClass([
1888
+ (0, import_inversify5.preDestroy)()
1889
+ ], VariableEngine.prototype, "dispose", 1);
1890
+ VariableEngine = __decorateClass([
1891
+ (0, import_inversify5.injectable)(),
1892
+ __decorateParam(0, (0, import_inversify5.inject)(ScopeChain)),
1893
+ __decorateParam(1, (0, import_inversify5.inject)(ASTRegisters))
1894
+ ], VariableEngine);
1895
+
1896
+ // src/services/variable-field-key-rename-service.ts
1897
+ var import_lodash5 = require("lodash");
1898
+ var import_inversify6 = require("inversify");
1899
+ var import_utils12 = require("@flowgram.ai/utils");
1900
+ var VariableFieldKeyRenameService = class {
1901
+ constructor() {
1902
+ this.toDispose = new import_utils12.DisposableCollection();
1903
+ this.renameEmitter = new import_utils12.Emitter();
1904
+ // 没有被 rename 的字段通过 disposeInList 透出,让业务区分变量是 rename 删除的,还是真正从列表中删除的
1905
+ this.disposeInListEmitter = new import_utils12.Emitter();
1906
+ this.onRename = this.renameEmitter.event;
1907
+ this.onDisposeInList = this.disposeInListEmitter.event;
1908
+ }
1909
+ handleFieldListChange(ast, prev, next) {
1910
+ if (!ast || !prev?.length || !next?.length) {
1911
+ this.notifyFieldsDispose(prev, next);
1912
+ return;
1913
+ }
1914
+ if (prev.length !== next.length) {
1915
+ this.notifyFieldsDispose(prev, next);
1916
+ return;
1917
+ }
1918
+ let renameNodeInfo = null;
1919
+ let existFieldChanged = false;
1920
+ for (const [index, prevField] of prev.entries()) {
1921
+ const nextField = next[index];
1922
+ if (prevField.key !== nextField.key) {
1923
+ if (existFieldChanged) {
1924
+ this.notifyFieldsDispose(prev, next);
1925
+ return;
1926
+ }
1927
+ existFieldChanged = true;
1928
+ if (prevField.type?.kind === nextField.type?.kind) {
1929
+ renameNodeInfo = { before: prevField, after: nextField };
1930
+ }
1931
+ }
1932
+ }
1933
+ if (!renameNodeInfo) {
1934
+ this.notifyFieldsDispose(prev, next);
1935
+ return;
1936
+ }
1937
+ this.renameEmitter.fire(renameNodeInfo);
1938
+ }
1939
+ notifyFieldsDispose(prev, next) {
1940
+ const removedFields = (0, import_lodash5.difference)(prev || [], next || []);
1941
+ removedFields.forEach((_field) => this.disposeInListEmitter.fire(_field));
1942
+ }
1943
+ init() {
1944
+ this.toDispose.pushAll([
1945
+ this.variableEngine.onGlobalEvent(
1946
+ "VariableListChange",
1947
+ (_action) => {
1948
+ this.handleFieldListChange(_action.ast, _action.payload?.prev, _action.payload?.next);
1949
+ }
1950
+ ),
1951
+ this.variableEngine.onGlobalEvent(
1952
+ "ObjectPropertiesChange",
1953
+ (_action) => {
1954
+ this.handleFieldListChange(_action.ast, _action.payload?.prev, _action.payload?.next);
1955
+ }
1956
+ )
1957
+ ]);
1958
+ }
1959
+ dispose() {
1960
+ this.toDispose.dispose();
1961
+ }
1962
+ };
1963
+ __decorateClass([
1964
+ (0, import_inversify6.inject)(VariableEngine)
1965
+ ], VariableFieldKeyRenameService.prototype, "variableEngine", 2);
1966
+ __decorateClass([
1967
+ (0, import_inversify6.postConstruct)()
1968
+ ], VariableFieldKeyRenameService.prototype, "init", 1);
1969
+ __decorateClass([
1970
+ (0, import_inversify6.preDestroy)()
1971
+ ], VariableFieldKeyRenameService.prototype, "dispose", 1);
1972
+ VariableFieldKeyRenameService = __decorateClass([
1973
+ (0, import_inversify6.injectable)()
1974
+ ], VariableFieldKeyRenameService);
1975
+
1976
+ // src/variable-container-module.ts
1977
+ var VariableContainerModule = new import_inversify7.ContainerModule((bind) => {
1978
+ bind(VariableEngine).toSelf().inSingletonScope();
1979
+ bind(ASTRegisters).toSelf().inSingletonScope();
1980
+ bind(VariableFieldKeyRenameService).toSelf().inSingletonScope();
1981
+ bind(VariableEngineProvider).toDynamicValue((ctx) => () => ctx.container.get(VariableEngine));
1982
+ bind(ContainerProvider).toDynamicValue((ctx) => () => ctx.container);
1983
+ });
1984
+
1985
+ // src/react/context.tsx
1986
+ var import_react = require("react");
1987
+ var ScopeContext = (0, import_react.createContext)(null);
1988
+ var ScopeProvider = ScopeContext.Provider;
1989
+ var useScopeContext = () => (0, import_react.useContext)(ScopeContext);
1990
+ var useCurrentScope = () => (0, import_react.useContext)(ScopeContext)?.scope;
1991
+
1992
+ // src/react/hooks/useScopeAvailable.ts
1993
+ var import_react2 = require("react");
1994
+ var import_core = require("@flowgram.ai/core");
1995
+ function useScopeAvailable() {
1996
+ const scope = useCurrentScope();
1997
+ const refresh = (0, import_core.useRefresh)();
1998
+ (0, import_react2.useEffect)(() => {
1999
+ const disposable = scope.available.onDataChange(() => {
2000
+ refresh();
2001
+ });
2002
+ return () => disposable.dispose();
2003
+ }, []);
2004
+ return scope.available;
2005
+ }
2006
+
2007
+ // src/react/hooks/useAvailableVariables.ts
2008
+ var import_react3 = require("react");
2009
+ var import_core2 = require("@flowgram.ai/core");
2010
+ function useAvailableVariables() {
2011
+ const scope = useCurrentScope();
2012
+ const variableEngine = (0, import_core2.useService)(VariableEngine);
2013
+ const refresh = (0, import_core2.useRefresh)();
2014
+ (0, import_react3.useEffect)(() => {
2015
+ if (!scope) {
2016
+ const disposable2 = variableEngine.globalVariableTable.onAnyChange(() => {
2017
+ refresh();
2018
+ });
2019
+ return () => disposable2.dispose();
2020
+ }
2021
+ const disposable = scope.available.onDataChange(() => {
2022
+ refresh();
2023
+ });
2024
+ return () => disposable.dispose();
2025
+ }, []);
2026
+ return scope ? scope.available.variables : variableEngine.globalVariableTable.variables;
2027
+ }
2028
+ // Annotate the CommonJS export names for ESM import in node:
2029
+ 0 && (module.exports = {
2030
+ ASTFactory,
2031
+ ASTKind,
2032
+ ASTNode,
2033
+ ASTNodeFlags,
2034
+ ASTRegisters,
2035
+ ArrayType,
2036
+ BaseExpression,
2037
+ BaseType,
2038
+ BaseVariableField,
2039
+ BooleanType,
2040
+ DataNode,
2041
+ EnumerateExpression,
2042
+ ExpressionList,
2043
+ IntegerType,
2044
+ KeyPathExpression,
2045
+ KeyPathExpressionV2,
2046
+ ListNode,
2047
+ MapNode,
2048
+ MapType,
2049
+ NumberType,
2050
+ ObjectType,
2051
+ Property,
2052
+ Scope,
2053
+ ScopeChain,
2054
+ ScopeOutputData,
2055
+ ScopeProvider,
2056
+ StringType,
2057
+ VariableContainerModule,
2058
+ VariableDeclaration,
2059
+ VariableDeclarationList,
2060
+ VariableEngine,
2061
+ VariableEngineProvider,
2062
+ VariableFieldKeyRenameService,
2063
+ VariableTable,
2064
+ injectToAST,
2065
+ isMatchAST,
2066
+ postConstructAST,
2067
+ useAvailableVariables,
2068
+ useCurrentScope,
2069
+ useScopeAvailable,
2070
+ useScopeContext
2071
+ });
2072
+ //# sourceMappingURL=index.js.map