@formvk/schema 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1034 @@
1
+ import { FormPath, each, isArr, isFn, isPlainObj, isStr, lazyMerge, map, reduce, toArr } from "@formvk/shared";
2
+ import { autorun, isObservable, observable, untracked } from "@formvk/reactive";
3
+ import { onFieldInit, onFieldInitialValueChange, onFieldInputValueChange, onFieldMount, onFieldUnmount, onFieldValidateEnd, onFieldValidateFailed, onFieldValidateStart, onFieldValidateSuccess, onFieldValueChange } from "@formvk/core";
4
+ // src/shared.ts
5
+ var REVA_ACTIONS_KEY = Symbol.for("__REVA_ACTIONS");
6
+ /** 自定义扩展 key:xKey 形式(x + 大驼峰) */
7
+ function isExtensionKey(key) {
8
+ return /^x[A-Z]/.test(key);
9
+ }
10
+ /**
11
+ * 值本身可以是函数的 schema key。
12
+ * 这些 key 在编译/序列化/遍历时不能被当作 Schema 内部方法丢弃。
13
+ */
14
+ var SchemaFunctionKeys = {
15
+ component: true,
16
+ decorator: true,
17
+ componentProps: true,
18
+ decoratorProps: true,
19
+ validator: true,
20
+ reactions: true
21
+ };
22
+ function isFunctionKey(key) {
23
+ return isExtensionKey(key) || !!SchemaFunctionKeys[key];
24
+ }
25
+ var SchemaNestedMap = {
26
+ parent: true,
27
+ root: true,
28
+ properties: true,
29
+ patternProperties: true,
30
+ additionalProperties: true,
31
+ items: true,
32
+ additionalItems: true,
33
+ reactions: true
34
+ };
35
+ /** schema key -> 字段状态 key */
36
+ var SchemaStateMap = {
37
+ title: "title",
38
+ description: "description",
39
+ default: "initialValue",
40
+ enum: "dataSource",
41
+ readOnly: "readOnly",
42
+ writeOnly: "editable",
43
+ content: "content",
44
+ data: "data",
45
+ value: "value",
46
+ editable: "editable",
47
+ disabled: "disabled",
48
+ readPretty: "readPretty",
49
+ visible: "visible",
50
+ hidden: "hidden",
51
+ display: "display",
52
+ pattern: "pattern",
53
+ validator: "validator",
54
+ decorator: "decoratorType",
55
+ component: "componentType",
56
+ decoratorProps: "decoratorProps",
57
+ componentProps: "componentProps"
58
+ };
59
+ /** schema key -> 校验规则 key */
60
+ var SchemaValidatorMap = {
61
+ required: true,
62
+ format: true,
63
+ maxItems: true,
64
+ minItems: true,
65
+ maxLength: true,
66
+ minLength: true,
67
+ maximum: true,
68
+ minimum: true,
69
+ exclusiveMaximum: true,
70
+ exclusiveMinimum: true,
71
+ const: true,
72
+ multipleOf: true,
73
+ maxProperties: true,
74
+ minProperties: true,
75
+ uniqueItems: true
76
+ };
77
+ Object.keys(SchemaStateMap);
78
+ Object.keys(SchemaValidatorMap);
79
+ function traverse(target, visitor) {
80
+ const seenObjects = [];
81
+ const root = target;
82
+ function traverse(target, path = []) {
83
+ if (isPlainObj(target)) {
84
+ if (seenObjects.indexOf(target) > -1) return;
85
+ const addIndex = seenObjects.length;
86
+ seenObjects.push(target);
87
+ if (isNoNeedCompileObject(target) && root !== target) {
88
+ visitor(target, path);
89
+ return;
90
+ }
91
+ each(target, (value, key) => {
92
+ traverse(value, path.concat(key));
93
+ });
94
+ seenObjects.splice(addIndex, 1);
95
+ } else visitor(target, path);
96
+ }
97
+ traverse(target);
98
+ }
99
+ function traverseSchema(schema, visitor) {
100
+ if (schema["validator"] !== void 0) visitor(schema["validator"], ["validator"], schema["compileOmitted"]?.includes("validator"));
101
+ const seenObjects = [];
102
+ const root = schema;
103
+ function traverse(target, path = []) {
104
+ if (path[0] === "compileOmitted" || path[0] === "validator" || path[0] === "version" || path[0] === "_isJSONSchemaObject") return;
105
+ if (isFn(target) && !isFunctionKey(String(path[0]))) return;
106
+ if (SchemaNestedMap[path[0]]) return;
107
+ if ((schema["compileOmitted"]?.indexOf(path[0]) ?? -1) > -1) {
108
+ visitor(target, path, true);
109
+ return;
110
+ }
111
+ if (isPlainObj(target)) {
112
+ if (path[0] === "default" || path[0] === "value") {
113
+ visitor(target, path);
114
+ return;
115
+ }
116
+ if (seenObjects.indexOf(target) > -1) return;
117
+ const addIndex = seenObjects.length;
118
+ seenObjects.push(target);
119
+ if (isNoNeedCompileObject(target) && root !== target) {
120
+ visitor(target, path);
121
+ return;
122
+ }
123
+ each(target, (value, key) => {
124
+ traverse(value, path.concat(key));
125
+ });
126
+ seenObjects.splice(addIndex, 1);
127
+ } else visitor(target, path);
128
+ }
129
+ traverse(schema);
130
+ }
131
+ function isNoNeedCompileObject(source) {
132
+ if ("$$typeof" in source && "_owner" in source) return true;
133
+ if (source["__v_isVNode"] || source["__v_skip"]) return true;
134
+ if (source["_isAMomentObject"]) return true;
135
+ if (source["_isJSONSchemaObject"]) return true;
136
+ if (source[REVA_ACTIONS_KEY]) return true;
137
+ if (isFn(source["toJS"])) return true;
138
+ if (isFn(source["toJSON"])) return true;
139
+ if (isObservable(source)) return true;
140
+ return false;
141
+ }
142
+ function createDataSource(source) {
143
+ return toArr(source).map((item) => {
144
+ if (typeof item === "object") return item;
145
+ else return {
146
+ label: item,
147
+ value: item
148
+ };
149
+ });
150
+ }
151
+ function patchStateFormSchema(targetState, pattern, compiled) {
152
+ untracked(() => {
153
+ const segments = FormPath.parse(pattern).segments;
154
+ const key = segments[0];
155
+ const isEnum = key === "enum" && isArr(compiled);
156
+ const schemaMapKey = SchemaStateMap[key];
157
+ if (schemaMapKey) FormPath.setIn(targetState, [schemaMapKey].concat(segments.slice(1)), isEnum ? createDataSource(compiled) : compiled);
158
+ else if (SchemaValidatorMap[key]) targetState["setValidatorRule"]?.(key, compiled);
159
+ });
160
+ }
161
+ // src/compiler.ts
162
+ var ExpRE = /^\s*\{\{([\s\S]*)\}\}\s*$/;
163
+ var Registry = {
164
+ silent: false,
165
+ compile(expression, scope = {}) {
166
+ if (Registry.silent) try {
167
+ return new Function("$root", `with($root) { return (${expression}); }`)(scope);
168
+ } catch {
169
+ return;
170
+ }
171
+ else return new Function("$root", `with($root) { return (${expression}); }`)(scope);
172
+ }
173
+ };
174
+ function silent(value = true) {
175
+ Registry.silent = !!value;
176
+ }
177
+ function registerCompiler(compiler) {
178
+ if (isFn(compiler)) Registry.compile = compiler;
179
+ }
180
+ function shallowCompile(source, scope) {
181
+ if (isStr(source)) {
182
+ const matched = source.match(ExpRE);
183
+ if (!matched) return source;
184
+ return Registry.compile(matched[1], scope);
185
+ }
186
+ return source;
187
+ }
188
+ /**
189
+ * 静态判断值中是否包含 `{{expression}}` 表达式。
190
+ * 用于 demand 模式下判断 schema 补丁是否存在动态依赖,
191
+ * 等价于 formily 的 `hasCollected`,但不需要额外的响应式收集标记。
192
+ */
193
+ function hasExpression(source) {
194
+ if (isStr(source)) return ExpRE.test(source);
195
+ if (isArr(source)) return source.some(hasExpression);
196
+ if (isPlainObj(source)) {
197
+ if (isNoNeedCompileObject(source)) return false;
198
+ return Object.keys(source).some((key) => hasExpression(source[key]));
199
+ }
200
+ return false;
201
+ }
202
+ function compile(source, scope) {
203
+ const seenObjects = [];
204
+ function compile(source) {
205
+ if (isStr(source)) return shallowCompile(source, scope);
206
+ else if (isArr(source)) return source.map((value) => compile(value));
207
+ else if (isPlainObj(source)) {
208
+ if (isNoNeedCompileObject(source)) return source;
209
+ if (seenObjects.indexOf(source) > -1) return source;
210
+ const addIndex = seenObjects.length;
211
+ seenObjects.push(source);
212
+ const results = reduce(source, (buf, value, key) => {
213
+ buf[key] = compile(value);
214
+ return buf;
215
+ }, {});
216
+ seenObjects.splice(addIndex, 1);
217
+ return results;
218
+ }
219
+ return source;
220
+ }
221
+ return compile(source);
222
+ }
223
+ function patchCompile(targetState, sourceState, scope) {
224
+ traverse(sourceState, (value, pattern) => {
225
+ const compiled = compile(value, scope);
226
+ if (compiled === void 0) return;
227
+ const path = FormPath.parse(pattern);
228
+ if (path.segments[0] in targetState) untracked(() => FormPath.setIn(targetState, path, compiled));
229
+ });
230
+ }
231
+ function patchSchemaCompile(targetState, sourceSchema, scope, demand = false) {
232
+ traverseSchema(sourceSchema, (value, path, omitCompile) => {
233
+ const dynamic = hasExpression(value);
234
+ let compiled = value;
235
+ if (!omitCompile) compiled = compile(value, scope);
236
+ if (compiled === void 0) return;
237
+ if (demand) {
238
+ if (dynamic || !targetState.initialized) patchStateFormSchema(targetState, path, compiled);
239
+ } else patchStateFormSchema(targetState, path, compiled);
240
+ });
241
+ }
242
+ // src/patches.ts
243
+ var patches = [];
244
+ function reducePatches(schema) {
245
+ return patches.reduce((buf, patch) => {
246
+ return patch(buf);
247
+ }, { ...schema });
248
+ }
249
+ function registerPatches(...args) {
250
+ args.forEach((patch) => {
251
+ if (isFn(patch)) patches.push(patch);
252
+ });
253
+ }
254
+ // src/transformer.ts
255
+ var FieldEffects = {
256
+ onFieldInit,
257
+ onFieldMount,
258
+ onFieldUnmount,
259
+ onFieldValueChange,
260
+ onFieldInputValueChange,
261
+ onFieldInitialValueChange,
262
+ onFieldValidateStart,
263
+ onFieldValidateEnd,
264
+ onFieldValidateFailed,
265
+ onFieldValidateSuccess
266
+ };
267
+ var DefaultFieldEffects = ["onFieldInit", "onFieldValueChange"];
268
+ function getDependencyValue(field, pattern, property) {
269
+ const [target, path] = String(pattern).split(/\s*#\s*/);
270
+ return field.query(target).getIn(path || property || "value");
271
+ }
272
+ function getDependencies(field, dependencies) {
273
+ if (isArr(dependencies)) {
274
+ const results = [];
275
+ dependencies.forEach((pattern) => {
276
+ if (isStr(pattern)) results.push(getDependencyValue(field, pattern));
277
+ else if (isPlainObj(pattern)) {
278
+ const item = pattern;
279
+ if (item.name && item.source) results[item.name] = getDependencyValue(field, item.source, item.property);
280
+ }
281
+ });
282
+ return results;
283
+ } else if (isPlainObj(dependencies)) return reduce(dependencies, (buf, pattern, key) => {
284
+ buf[key] = getDependencyValue(field, pattern);
285
+ return buf;
286
+ }, {});
287
+ return [];
288
+ }
289
+ function setSchemaFieldState(options, demand = false) {
290
+ const { request, target, runner, field, scope } = options || {};
291
+ if (!request) return;
292
+ if (target) {
293
+ if (request.state) field.form.setFieldState(target, (state) => patchCompile(state, request.state, lazyMerge(scope, { $target: state })));
294
+ if (request.schema) field.form.setFieldState(target, (state) => patchSchemaCompile(state, request.schema, lazyMerge(scope, { $target: state }), demand));
295
+ if (isStr(runner) && runner) field.form.setFieldState(target, (state) => {
296
+ shallowCompile(`{{function(){${runner}}}}`, lazyMerge(scope, { $target: state }))();
297
+ });
298
+ } else {
299
+ if (request.state) field.setState((state) => patchCompile(state, request.state, scope));
300
+ if (request.schema) field.setState((state) => patchSchemaCompile(state, request.schema, scope, demand));
301
+ if (isStr(runner) && runner) shallowCompile(`{{function(){${runner}}}}`, scope)();
302
+ }
303
+ }
304
+ function getBaseScope(field, options = {}) {
305
+ function $observable(target) {
306
+ return observable(target);
307
+ }
308
+ function $props(props) {
309
+ return field.setComponentProps(props);
310
+ }
311
+ function $effect(tracker) {
312
+ return autorun(tracker);
313
+ }
314
+ function $memo(callback) {
315
+ return callback();
316
+ }
317
+ const $self = field;
318
+ const $form = field.form;
319
+ const $values = field.form.values;
320
+ return lazyMerge({
321
+ get $lookup() {
322
+ return options?.scope?.$record ?? $values;
323
+ },
324
+ get $records() {
325
+ return field.records;
326
+ },
327
+ get $record() {
328
+ const record = field.record;
329
+ if (typeof record === "object") return lazyMerge(record, {
330
+ get $lookup() {
331
+ return options?.scope?.$record ?? $values;
332
+ },
333
+ get $index() {
334
+ return field.index;
335
+ }
336
+ });
337
+ return record;
338
+ },
339
+ get $index() {
340
+ return field.index;
341
+ }
342
+ }, options.scope, {
343
+ $form,
344
+ $self,
345
+ $observable,
346
+ $effect,
347
+ $memo,
348
+ $props,
349
+ $values
350
+ });
351
+ }
352
+ function getBaseReactions(schema, options) {
353
+ return (field) => {
354
+ setSchemaFieldState({
355
+ field,
356
+ request: { schema },
357
+ scope: getBaseScope(field, options)
358
+ }, true);
359
+ };
360
+ }
361
+ function getUserReactions(schema, options) {
362
+ return toArr(schema["reactions"]).map((unCompiled) => {
363
+ return (field) => {
364
+ const baseScope = getBaseScope(field, options);
365
+ const reaction = shallowCompile(unCompiled, baseScope);
366
+ if (!reaction) return;
367
+ if (isFn(reaction)) return reaction(field, baseScope);
368
+ const { when, fulfill, otherwise, target, effects } = reaction;
369
+ function run() {
370
+ const $deps = getDependencies(field, reaction.dependencies);
371
+ const scope = lazyMerge(baseScope, {
372
+ $target: null,
373
+ $deps,
374
+ $dependencies: $deps
375
+ });
376
+ const compiledWhen = shallowCompile(when, scope);
377
+ const request = (when ? compiledWhen : true) ? fulfill : otherwise;
378
+ const runner = request?.run;
379
+ setSchemaFieldState({
380
+ field,
381
+ target,
382
+ request,
383
+ runner,
384
+ scope
385
+ });
386
+ }
387
+ if (target) reaction.effects = effects?.length ? effects : DefaultFieldEffects;
388
+ if (reaction.effects) {
389
+ if (!reaction.__effectRegistered) {
390
+ reaction.__effectRegistered = true;
391
+ untracked(() => {
392
+ each(reaction.effects, (type) => {
393
+ if (FieldEffects[type]) FieldEffects[type](field.address, run);
394
+ });
395
+ });
396
+ }
397
+ } else run();
398
+ };
399
+ });
400
+ }
401
+ function transformFieldProps(schema, options = {}) {
402
+ return {
403
+ name: schema.name,
404
+ reactions: [getBaseReactions(schema, options)].concat(getUserReactions(schema, options))
405
+ };
406
+ }
407
+ // src/schema.ts
408
+ var Schema = class Schema {
409
+ parent;
410
+ root;
411
+ name;
412
+ title;
413
+ description;
414
+ default;
415
+ readOnly;
416
+ writeOnly;
417
+ type;
418
+ enum;
419
+ const;
420
+ multipleOf;
421
+ exclusiveMaximum;
422
+ maximum;
423
+ exclusiveMinimum;
424
+ minimum;
425
+ maxLength;
426
+ minLength;
427
+ pattern;
428
+ maxItems;
429
+ minItems;
430
+ uniqueItems;
431
+ maxProperties;
432
+ minProperties;
433
+ required;
434
+ format;
435
+ $ref;
436
+ $namespace;
437
+ /** 嵌套 JSON Schema 描述 */
438
+ definitions;
439
+ properties;
440
+ items;
441
+ additionalItems;
442
+ patternProperties;
443
+ additionalProperties;
444
+ /** 字段值 */
445
+ value;
446
+ /** 顺序描述 */
447
+ index;
448
+ /** 展示状态 */
449
+ display;
450
+ /** 校验器 */
451
+ validator;
452
+ /** 装饰器 */
453
+ decorator;
454
+ /** 装饰器属性 */
455
+ decoratorProps;
456
+ /** 组件 */
457
+ component;
458
+ /** 组件属性 */
459
+ componentProps;
460
+ /** 组件响应器 */
461
+ reactions;
462
+ /** 内容 */
463
+ content;
464
+ data;
465
+ visible;
466
+ hidden;
467
+ disabled;
468
+ editable;
469
+ readPretty;
470
+ compileOmitted;
471
+ slotNode;
472
+ /** 渲染到父组件的具名插槽 */
473
+ slot;
474
+ _isJSONSchemaObject = true;
475
+ version = "2.0";
476
+ constructor(json, parent) {
477
+ if (parent) {
478
+ this.parent = parent;
479
+ this.root = parent.root;
480
+ } else this.root = this;
481
+ return this.fromJSON(json);
482
+ }
483
+ addProperty = (key, schema) => {
484
+ this.properties = this.properties || {};
485
+ this.properties[key] = new Schema(schema, this);
486
+ this.properties[key].name = key;
487
+ return this.properties[key];
488
+ };
489
+ removeProperty = (key) => {
490
+ const schema = this.properties?.[key];
491
+ delete this.properties?.[key];
492
+ return schema;
493
+ };
494
+ setProperties = (properties) => {
495
+ for (const key in properties) this.addProperty(key, properties[key]);
496
+ return this;
497
+ };
498
+ addPatternProperty = (key, schema) => {
499
+ if (!schema) return;
500
+ this.patternProperties = this.patternProperties || {};
501
+ this.patternProperties[key] = new Schema(schema, this);
502
+ this.patternProperties[key].name = key;
503
+ return this.patternProperties[key];
504
+ };
505
+ removePatternProperty = (key) => {
506
+ const schema = this.patternProperties?.[key];
507
+ delete this.patternProperties?.[key];
508
+ return schema;
509
+ };
510
+ setPatternProperties = (properties) => {
511
+ if (!properties) return this;
512
+ for (const key in properties) this.addPatternProperty(key, properties[key]);
513
+ return this;
514
+ };
515
+ setAdditionalProperties = (properties) => {
516
+ if (!properties) return;
517
+ this.additionalProperties = new Schema(properties);
518
+ return this.additionalProperties;
519
+ };
520
+ setItems = (schema) => {
521
+ if (!schema) return;
522
+ if (Array.isArray(schema)) this.items = schema.map((item) => new Schema(item, this));
523
+ else this.items = new Schema(schema, this);
524
+ return this.items;
525
+ };
526
+ setAdditionalItems = (items) => {
527
+ if (!items) return;
528
+ this.additionalItems = new Schema(items, this);
529
+ return this.additionalItems;
530
+ };
531
+ findDefinitions = (ref) => {
532
+ if (!ref || !this.root || !isStr(ref)) return;
533
+ if (ref.indexOf("#/") !== 0) return;
534
+ return FormPath.getIn(this.root, ref.substring(2).split("/"));
535
+ };
536
+ mapProperties = (callback) => {
537
+ return Schema.getOrderProperties(this).map(({ schema, key }, index) => {
538
+ return callback?.(schema, key, index);
539
+ });
540
+ };
541
+ mapPatternProperties = (callback) => {
542
+ return Schema.getOrderProperties(this, "patternProperties").map(({ schema, key }, index) => {
543
+ return callback?.(schema, key, index);
544
+ });
545
+ };
546
+ reduceProperties = (callback, predicate) => {
547
+ let results = predicate;
548
+ Schema.getOrderProperties(this, "properties").forEach(({ schema, key }, index) => {
549
+ results = callback?.(results, schema, key, index);
550
+ });
551
+ return results;
552
+ };
553
+ reducePatternProperties = (callback, predicate) => {
554
+ let results = predicate;
555
+ Schema.getOrderProperties(this, "patternProperties").forEach(({ schema, key }, index) => {
556
+ results = callback?.(results, schema, key, index);
557
+ });
558
+ return results;
559
+ };
560
+ compile = (scope) => {
561
+ const schema = new Schema({}, this.parent);
562
+ each(this, (value, key) => {
563
+ if (isFn(value) && !isFunctionKey(key)) return;
564
+ if (key === "parent" || key === "root") return;
565
+ if (!SchemaNestedMap[key]) schema[key] = value ? compile(value, scope) : value;
566
+ else schema[key] = value ? shallowCompile(value, scope) : value;
567
+ });
568
+ return schema;
569
+ };
570
+ fromJSON = (json) => {
571
+ if (!json) return this;
572
+ if (Schema.isSchemaInstance(json)) return json;
573
+ each(reducePatches(json), (value, key) => {
574
+ if (isFn(value) && !isFunctionKey(key)) return;
575
+ if (key === "properties") this.setProperties(value);
576
+ else if (key === "patternProperties") this.setPatternProperties(value);
577
+ else if (key === "additionalProperties") this.setAdditionalProperties(value);
578
+ else if (key === "items") this.setItems(value);
579
+ else if (key === "additionalItems") this.setAdditionalItems(value);
580
+ else if (key === "$ref") this.fromJSON(this.findDefinitions(value));
581
+ else this[key] = value;
582
+ });
583
+ return this;
584
+ };
585
+ toJSON = (recursion = true) => {
586
+ const results = {};
587
+ each(this, (value, key) => {
588
+ if (isFn(value) && !isFunctionKey(key) || key === "parent" || key === "root") return;
589
+ if (key === "properties" || key === "patternProperties") {
590
+ if (!recursion) return;
591
+ results[key] = map(value, (item) => item?.toJSON?.());
592
+ } else if (key === "additionalProperties" || key === "additionalItems") {
593
+ if (!recursion) return;
594
+ results[key] = value?.toJSON?.();
595
+ } else if (key === "items") {
596
+ if (!recursion) return;
597
+ if (Array.isArray(value)) results[key] = value.map((item) => item?.toJSON?.());
598
+ else results[key] = value?.toJSON?.();
599
+ } else results[key] = value;
600
+ });
601
+ return results;
602
+ };
603
+ toFieldProps = (options) => {
604
+ return transformFieldProps(this, options);
605
+ };
606
+ static getOrderProperties = (schema = {}, propertiesName = "properties") => {
607
+ const orderProperties = [];
608
+ const unorderProperties = [];
609
+ for (const key in schema[propertiesName]) {
610
+ const item = schema[propertiesName][key];
611
+ const index = item?.["index"];
612
+ if (!isNaN(index)) orderProperties[index] = {
613
+ schema: item,
614
+ key
615
+ };
616
+ else unorderProperties.push({
617
+ schema: item,
618
+ key
619
+ });
620
+ }
621
+ return orderProperties.concat(unorderProperties).filter((item) => !!item);
622
+ };
623
+ static compile = (expression, scope) => {
624
+ return compile(expression, scope);
625
+ };
626
+ static shallowCompile = (expression, scope) => {
627
+ return shallowCompile(expression, scope);
628
+ };
629
+ static isSchemaInstance = (value) => {
630
+ return value instanceof Schema;
631
+ };
632
+ static registerCompiler = registerCompiler;
633
+ static registerPatches = registerPatches;
634
+ static silent = silent;
635
+ };
636
+ // src/fragment.ts
637
+ function isFn$1(value) {
638
+ return typeof value === "function";
639
+ }
640
+ function isObj(value) {
641
+ return value !== null && typeof value === "object";
642
+ }
643
+ function toArr$1(value) {
644
+ if (value === void 0) return [];
645
+ return Array.isArray(value) ? value : [value];
646
+ }
647
+ function sortPatches(patches) {
648
+ const prePatches = patches.reduce((pre, patch) => {
649
+ if (!patch || typeof patch !== "object") return pre;
650
+ if (patch.pre) pre.push(patch.patch);
651
+ return pre;
652
+ }, []);
653
+ return patches.reduce((result, patch) => {
654
+ if (!patch) return result;
655
+ if (typeof patch !== "object") result.push(patch);
656
+ else if (!patch.pre) result.push(patch.patch);
657
+ return result;
658
+ }, prePatches);
659
+ }
660
+ function itemsPatch(schema, patches) {
661
+ if (schema.type === "array") {
662
+ const { items } = schema;
663
+ return {
664
+ ...schema,
665
+ items: isFn$1(items) ? items(patches) : items
666
+ };
667
+ }
668
+ return schema;
669
+ }
670
+ function propertiesPatch(schema, patches) {
671
+ if (!("properties" in schema)) return schema;
672
+ const { properties } = schema;
673
+ if (!properties || !isObj(properties)) return {
674
+ ...schema,
675
+ properties: void 0
676
+ };
677
+ return {
678
+ ...schema,
679
+ properties: Object.entries(properties).reduce((acc, [key, generator]) => {
680
+ if (isFn$1(generator)) {
681
+ acc[key] = generator(patches);
682
+ return acc;
683
+ } else if (generator && isObj(generator)) {
684
+ acc[key] = generator;
685
+ return acc;
686
+ }
687
+ return acc;
688
+ }, {})
689
+ };
690
+ }
691
+ /**
692
+ * 默认装饰器补丁,语义对齐 formily-pro 的 defaultDecoratorPatch:
693
+ * 仅处理 string 字段,且要求存在 title、未显式声明 decorator。
694
+ */
695
+ function createDefaultDecoratorPatch(decorator) {
696
+ return (schema) => {
697
+ if (schema.type !== "string" || schema.decorator !== void 0 || schema.title === void 0) return schema;
698
+ return {
699
+ ...schema,
700
+ decorator
701
+ };
702
+ };
703
+ }
704
+ /**
705
+ * 底层 schema 构造器。
706
+ * 默认不内置任何 patch,组件 props 类型由 F / V / A 三个独立 map 注入。
707
+ */
708
+ function createFragment(options = {}) {
709
+ const defaultDecoratorPatch = options.defaultDecorator ? createDefaultDecoratorPatch(options.defaultDecorator) : void 0;
710
+ function creator(_schema = {}) {
711
+ return ((patches) => {
712
+ return sortPatches([
713
+ ...toArr$1(defaultDecoratorPatch),
714
+ ...toArr$1(options.patches),
715
+ ...toArr$1(patches)
716
+ ]).concat([(schema) => itemsPatch(schema, patches), (schema) => propertiesPatch(schema, patches)]).reduce((acc, patch) => patch(acc), _schema);
717
+ });
718
+ }
719
+ function FField(schema) {
720
+ return creator({
721
+ type: "string",
722
+ ...schema
723
+ });
724
+ }
725
+ function FObject(properties, schema) {
726
+ return creator({
727
+ ...schema,
728
+ properties,
729
+ type: "object"
730
+ });
731
+ }
732
+ function FArray(items, schema) {
733
+ return creator({
734
+ ...schema,
735
+ items,
736
+ type: "array"
737
+ });
738
+ }
739
+ function FVoid(properties, schema) {
740
+ return creator({
741
+ ...schema,
742
+ properties,
743
+ type: "void"
744
+ });
745
+ }
746
+ function transform(schema) {
747
+ const loop = (schema) => {
748
+ if (!schema) return;
749
+ const transformProperties = (properties) => {
750
+ if (!properties) return;
751
+ return Object.fromEntries(Object.entries(properties).map(([key, value]) => [key, loop(value)]));
752
+ };
753
+ if (schema.type === "object") {
754
+ const { properties, ...rest } = schema;
755
+ return FObject(transformProperties(properties), rest);
756
+ } else if (schema.type === "array") {
757
+ const { items, properties, ...rest } = schema;
758
+ return FArray(loop(items), {
759
+ ...rest,
760
+ ...properties ? { properties: transformProperties(properties) } : {}
761
+ });
762
+ } else if (schema.type === "void") {
763
+ const { properties, ...rest } = schema;
764
+ return FVoid(transformProperties(properties), rest);
765
+ }
766
+ return FField(schema);
767
+ };
768
+ return loop(schema)?.();
769
+ }
770
+ const fragmentBase = {
771
+ Array: FArray,
772
+ Object: FObject,
773
+ Void: FVoid,
774
+ Field: FField,
775
+ transform
776
+ };
777
+ const createFragmentByType = (type) => {
778
+ if (options.arrayComponentNames?.includes(type)) return (items, schema) => creator({
779
+ ...schema,
780
+ items,
781
+ type: "array",
782
+ component: type
783
+ });
784
+ if (options.voidComponentNames?.includes(type)) return (schema) => creator({
785
+ ...schema,
786
+ type: "void",
787
+ component: type
788
+ });
789
+ return (schema) => {
790
+ return creator({
791
+ ...schema,
792
+ type: "string",
793
+ component: type
794
+ });
795
+ };
796
+ };
797
+ return new Proxy(fragmentBase, { get(target, type, receiver) {
798
+ if (typeof type === "string") {
799
+ if (type in target) return target[type];
800
+ if (type === "toJSON") return () => ({});
801
+ if (type === "then") return;
802
+ return createFragmentByType(type);
803
+ }
804
+ return Reflect.get(target, type, receiver);
805
+ } });
806
+ }
807
+ // src/create-schema.ts
808
+ /**
809
+ * 对象 schema 快捷组装器。
810
+ * 默认不内置任何 patch,creator 使用传入的 patches 展开。
811
+ */
812
+ function createSchema(properties, patches) {
813
+ const result = {
814
+ type: "object",
815
+ properties: {}
816
+ };
817
+ Object.keys(properties).forEach((key) => {
818
+ const generator = properties[key];
819
+ if (typeof generator === "function") result.properties[key] = generator(patches);
820
+ else if (generator && typeof generator === "object") result.properties[key] = generator;
821
+ });
822
+ return result;
823
+ }
824
+ // src/expression.ts
825
+ var variableName = /^[$A-Za-z_][0-9A-Za-z_$]*$/;
826
+ var ExpressionStr = class {
827
+ expression;
828
+ isExp;
829
+ constructor(expression, isExp = false) {
830
+ this.expression = expression;
831
+ this.isExp = isExp;
832
+ }
833
+ getExpression(str) {
834
+ return this.isExp ? `{{${str}}}` : str;
835
+ }
836
+ /**
837
+ * 等于
838
+ * @example
839
+ * objExp.exp.a.eq(1) // obj.a === 1
840
+ * objExp.exp.a.b.c.eq('1') // obj.a.b.c === "1"
841
+ * objExp.exp.a.b.c.eq('$values.d', true) // obj.a.b.c === $values.d
842
+ */
843
+ eq(str, exp) {
844
+ return `${this.expression} === ${exp ? str : JSON.stringify(str)}`;
845
+ }
846
+ /**
847
+ * 不等于
848
+ * @example
849
+ * objExp.exp.a.neq(1) // obj.a !== 1
850
+ * objExp.exp.a.neq('$values.b', true) // obj.a !== $values.b
851
+ */
852
+ neq(str, exp) {
853
+ return `${this.expression} !== ${exp ? str : JSON.stringify(str)}`;
854
+ }
855
+ /**
856
+ * 大于
857
+ * @example
858
+ * objExp.exp.a.gt('1') // obj.a > 1
859
+ * objExp.exp.a.b.c.gt('1') // obj.a.b.c > 1
860
+ */
861
+ gt(str, exp) {
862
+ return `${this.expression} > ${exp ? str : JSON.stringify(str)}`;
863
+ }
864
+ /**
865
+ * @example
866
+ * objExp.exp.a.gte('1') // obj.a >= 1
867
+ * objExp.exp.a.b.c.gte('1') // obj.a.b.c >= 1
868
+ */
869
+ gte(str, exp) {
870
+ return `${this.expression} >= ${exp ? str : JSON.stringify(str)}`;
871
+ }
872
+ /**
873
+ * 小于
874
+ * @example
875
+ * objExp.exp.a.lt('1') // obj.a < 1
876
+ * objExp.exp.a.b.c.lt('1') // obj.a.b.c < 1
877
+ */
878
+ lt(str, exp) {
879
+ return `${this.expression} < ${exp ? str : JSON.stringify(str)}`;
880
+ }
881
+ /**
882
+ * 小于等于
883
+ * @example
884
+ * objExp.exp.a.lte(1) // obj.a <= 1
885
+ * objExp.exp.a.b.c.lte('$values.d', true) // obj.a.b.c <= $values.d
886
+ */
887
+ lte(str, exp) {
888
+ return `${this.expression} <= ${exp ? str : JSON.stringify(str)}`;
889
+ }
890
+ /**
891
+ * 与
892
+ * @example
893
+ * objExp.exp.a.and('1') // obj.a && 1
894
+ */
895
+ and(str, exp) {
896
+ return `${this.expression} && ${exp ? str : JSON.stringify(str)}`;
897
+ }
898
+ /**
899
+ * 或
900
+ * @example
901
+ * objExp.exp.a.or(1) // obj.a || 1
902
+ * objExp.exp.a.b.c.or('1') // obj.a.b.c || '1'
903
+ * objExp.exp.a.or('1 || 2', true) // obj.a || 1 || 2
904
+ * objExp.exp.a.or({b: 1}) // obj.a || {"b": 1}
905
+ */
906
+ or(str, exp) {
907
+ return `${this.expression} || ${exp ? str : JSON.stringify(str)}`;
908
+ }
909
+ /**
910
+ * 取反
911
+ * @example
912
+ * objExp.exp.a.not() // !obj.a
913
+ * objExp.exp.a.b.c.not() // !obj.a.b.c
914
+ */
915
+ not() {
916
+ return `!${this.expression}`;
917
+ }
918
+ /**
919
+ * 取bool值
920
+ * @example
921
+ * objExp.exp.a.bool() // !!obj.a
922
+ * objExp.exp.a.b.c.bool() // !!obj.a.b.c
923
+ */
924
+ bool() {
925
+ return `!!${this.expression}`;
926
+ }
927
+ /**
928
+ * 三元表达式
929
+ * @example
930
+ * objExp.exp.a.ter(1, 2) // obj.a ? 1 : 2
931
+ * objExp.exp.a.b.c.ter('1', '2') // obj.a.b.c ? "1" : "2"
932
+ * objExp.exp.a.ter("obj.a", "abj.b", true) // obj.a ? obj.a : abj.b
933
+ */
934
+ ter(a, b, exp) {
935
+ return `${this.expression} ? ${exp ? a : JSON.stringify(a)} : ${exp ? b : JSON.stringify(b)}`;
936
+ }
937
+ };
938
+ function getExpression(expression, key) {
939
+ return `${expression}${variableName.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`}`;
940
+ }
941
+ function getLastArg(args) {
942
+ const lastArg = args[args.length - 1];
943
+ if (lastArg !== null && typeof lastArg === "object") return lastArg;
944
+ return {};
945
+ }
946
+ function getExpressionFn(expression, key) {
947
+ const funcName = variableName.test(key) ? `__${key}` : "__IS_NOT_VARIABLE_NAME__";
948
+ const expStr = getExpression(expression, key);
949
+ const fn = function(...args) {
950
+ const has$event = args.includes("$event");
951
+ const has$args = args.includes("$args");
952
+ if (has$event && has$args) throw new Error("$event and $args cannot be passed in at the same time");
953
+ const { expand = true, body = "" } = getLastArg(args);
954
+ if (body.includes("return")) throw new Error("body cannot contain return");
955
+ const funcArgs = args.map((arg) => {
956
+ if (arg === "$args") return expand ? "...$args" : "$args";
957
+ if (typeof arg === "string") return arg;
958
+ }).filter(Boolean).join(", ");
959
+ const funcBody = `
960
+ ${body}
961
+ return ${expStr}(${funcArgs})`;
962
+ return `{{function ${funcName}(${has$args ? expand ? "...$args" : "$args" : has$event ? "$event" : ""}) {${funcBody}
963
+ }}}`;
964
+ };
965
+ return new Proxy(fn, {
966
+ get(_, key) {
967
+ if (typeof key !== "string") throw new Error("key must be string");
968
+ return getExpressionFn(expStr, key);
969
+ },
970
+ apply(_, __, args) {
971
+ return fn(...args);
972
+ }
973
+ });
974
+ }
975
+ function createExpressionFn(expression) {
976
+ return new Proxy({}, { get(_, key) {
977
+ if (typeof key !== "string") throw new Error("key must be string");
978
+ return getExpressionFn(expression, key);
979
+ } });
980
+ }
981
+ function createExpressionStr(expression, isExp = false) {
982
+ const expressionStr = new ExpressionStr(expression, isExp);
983
+ const exp = expressionStr.getExpression(expression);
984
+ const str = new String(exp);
985
+ return new Proxy(str, { get(_, key, receiver) {
986
+ if (typeof key === "symbol") {
987
+ if (key === Symbol.toPrimitive) return () => exp;
988
+ if (key === Symbol.toStringTag) return "String";
989
+ return Reflect.get(str, key, receiver).bind(exp);
990
+ }
991
+ if (key.startsWith("__") || key in String.prototype || key in Object.prototype) {
992
+ const result = Reflect.get(str, key, receiver);
993
+ if (typeof result === "function") return result.bind(exp);
994
+ return result;
995
+ }
996
+ if (key === "toJSON") return () => exp;
997
+ if (typeof expressionStr[key] === "function") return function(...args) {
998
+ const result = expressionStr[key](...args);
999
+ return expressionStr.getExpression(result);
1000
+ };
1001
+ return createExpressionStr(getExpression(expression, key), isExp);
1002
+ } });
1003
+ }
1004
+ /**
1005
+ * 返回一个对象的表达式主要方便于类型推导
1006
+ * @param expression 对象表达式 如 'obj'
1007
+ * @example
1008
+ * const objExp = createExpression<{ a: number; b: () => string,'1b': string }>('obj')
1009
+ * objExp.a // {{obj.a}}
1010
+ * objExp['1b'] // {{obj['1b']}}
1011
+ * objExp.fn.b() // {{function __b() {} return obj.b()}}
1012
+ * objExp.fn.b('$args') // {{function __b(...$args) {} return obj.b(...$args)}}
1013
+ * objExp.fn.b('$event') // {{function __b($event) {} return obj.b($event)}}
1014
+ * objExp.fn.b('$self', '$event') // {{function __b($event) {} return obj.b($self, $event)}}
1015
+ * objExp.fn.b('$self', '$args') // {{function __b(...$args) {} return obj.b($self, ...$args)}}
1016
+ */
1017
+ function createExpression(expression) {
1018
+ const obj = {};
1019
+ const fn = createExpressionFn(expression);
1020
+ const exp = createExpressionStr(expression);
1021
+ return new Proxy(obj, { get(_, key, receiver) {
1022
+ if (typeof key === "symbol") {
1023
+ const value = Reflect.get(obj, key, receiver);
1024
+ if (typeof value === "function") return value.bind(obj);
1025
+ return value;
1026
+ }
1027
+ if (key === "fn") return fn;
1028
+ if (key === "exp") return exp;
1029
+ return createExpressionStr(getExpression(expression, key), true);
1030
+ } });
1031
+ }
1032
+ export { Schema, createExpression, createExpressionFn, createFragment, createSchema, getExpression };
1033
+
1034
+ //# sourceMappingURL=index.js.map