@atscript/ui 0.1.163 → 0.1.164

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/client-factory.cjs +27 -0
  2. package/dist/client-factory.d.cts +53 -0
  3. package/dist/client-factory.d.mts +53 -0
  4. package/dist/client-factory.mjs +25 -0
  5. package/dist/form/apply.cjs +38 -0
  6. package/dist/form/apply.d.cts +36 -0
  7. package/dist/form/apply.d.mts +36 -0
  8. package/dist/form/apply.mjs +38 -0
  9. package/dist/form/clone.cjs +30 -0
  10. package/dist/form/clone.d.cts +23 -0
  11. package/dist/form/clone.d.mts +23 -0
  12. package/dist/form/clone.mjs +30 -0
  13. package/dist/form/create-form-def.cjs +440 -0
  14. package/dist/form/create-form-def.d.cts +67 -0
  15. package/dist/form/create-form-def.d.mts +67 -0
  16. package/dist/form/create-form-def.mjs +438 -0
  17. package/dist/form/decimal-format.cjs +324 -0
  18. package/dist/form/decimal-format.d.cts +86 -0
  19. package/dist/form/decimal-format.d.mts +86 -0
  20. package/dist/form/decimal-format.mjs +315 -0
  21. package/dist/form/diff.cjs +458 -0
  22. package/dist/form/diff.d.cts +80 -0
  23. package/dist/form/diff.d.mts +80 -0
  24. package/dist/form/diff.mjs +457 -0
  25. package/dist/form/dirty.cjs +65 -0
  26. package/dist/form/dirty.d.cts +47 -0
  27. package/dist/form/dirty.d.mts +47 -0
  28. package/dist/form/dirty.mjs +64 -0
  29. package/dist/form/error-utils.cjs +97 -0
  30. package/dist/form/error-utils.d.cts +58 -0
  31. package/dist/form/error-utils.d.mts +58 -0
  32. package/dist/form/error-utils.mjs +92 -0
  33. package/dist/form/form-actions.cjs +30 -0
  34. package/dist/form/form-actions.d.cts +17 -0
  35. package/dist/form/form-actions.d.mts +17 -0
  36. package/dist/form/form-actions.mjs +30 -0
  37. package/dist/form/grid.cjs +69 -0
  38. package/dist/form/grid.d.cts +49 -0
  39. package/dist/form/grid.d.mts +49 -0
  40. package/dist/form/grid.mjs +64 -0
  41. package/dist/form/labels.cjs +10 -0
  42. package/dist/form/labels.d.cts +7 -0
  43. package/dist/form/labels.d.mts +7 -0
  44. package/dist/form/labels.mjs +10 -0
  45. package/dist/form/measurement.cjs +20 -0
  46. package/dist/form/measurement.d.cts +29 -0
  47. package/dist/form/measurement.d.mts +29 -0
  48. package/dist/form/measurement.mjs +20 -0
  49. package/dist/form/path-utils.cjs +182 -0
  50. package/dist/form/path-utils.d.cts +47 -0
  51. package/dist/form/path-utils.d.mts +47 -0
  52. package/dist/form/path-utils.mjs +175 -0
  53. package/dist/form/rebase.cjs +89 -0
  54. package/dist/form/rebase.d.cts +61 -0
  55. package/dist/form/rebase.d.mts +61 -0
  56. package/dist/form/rebase.mjs +89 -0
  57. package/dist/form/skipped-nav.cjs +100 -0
  58. package/dist/form/skipped-nav.d.cts +13 -0
  59. package/dist/form/skipped-nav.d.mts +13 -0
  60. package/dist/form/skipped-nav.mjs +98 -0
  61. package/dist/form/types.cjs +40 -0
  62. package/dist/form/types.d.cts +133 -0
  63. package/dist/form/types.d.mts +133 -0
  64. package/dist/form/types.mjs +36 -0
  65. package/dist/form/union-detect.cjs +46 -0
  66. package/dist/form/union-detect.d.cts +22 -0
  67. package/dist/form/union-detect.d.mts +22 -0
  68. package/dist/form/union-detect.mjs +46 -0
  69. package/dist/form/validate.cjs +150 -0
  70. package/dist/form/validate.d.cts +50 -0
  71. package/dist/form/validate.d.mts +50 -0
  72. package/dist/form/validate.mjs +147 -0
  73. package/dist/index.cjs +217 -3360
  74. package/dist/index.d.cts +38 -1693
  75. package/dist/index.d.mts +38 -1693
  76. package/dist/index.mjs +35 -3179
  77. package/dist/nav/model-routes.cjs +59 -0
  78. package/dist/nav/model-routes.d.cts +33 -0
  79. package/dist/nav/model-routes.d.mts +33 -0
  80. package/dist/nav/model-routes.mjs +59 -0
  81. package/dist/plugin/annotations.cjs +577 -0
  82. package/dist/plugin/annotations.mjs +577 -0
  83. package/dist/plugin/primitives.cjs +30 -0
  84. package/dist/plugin/primitives.mjs +30 -0
  85. package/dist/plugin/value-help-validation.cjs +419 -0
  86. package/dist/plugin/value-help-validation.mjs +413 -0
  87. package/dist/plugin.cjs +4 -1001
  88. package/dist/plugin.mjs +2 -999
  89. package/dist/shared/annotation-keys.cjs +189 -0
  90. package/dist/shared/annotation-keys.d.cts +82 -0
  91. package/dist/shared/annotation-keys.d.mts +82 -0
  92. package/dist/shared/annotation-keys.mjs +97 -0
  93. package/dist/shared/field-resolver.cjs +123 -0
  94. package/dist/shared/field-resolver.d.cts +77 -0
  95. package/dist/shared/field-resolver.d.mts +77 -0
  96. package/dist/shared/field-resolver.mjs +110 -0
  97. package/dist/shared/meta-cache.cjs +244 -0
  98. package/dist/shared/meta-cache.d.cts +110 -0
  99. package/dist/shared/meta-cache.d.mts +110 -0
  100. package/dist/shared/meta-cache.mjs +237 -0
  101. package/dist/shared/str.cjs +19 -0
  102. package/dist/shared/str.d.cts +7 -0
  103. package/dist/shared/str.d.mts +7 -0
  104. package/dist/shared/str.mjs +17 -0
  105. package/dist/table/column-resolver.cjs +17 -0
  106. package/dist/table/column-resolver.d.cts +11 -0
  107. package/dist/table/column-resolver.d.mts +11 -0
  108. package/dist/table/column-resolver.mjs +15 -0
  109. package/dist/table/create-table-def.cjs +233 -0
  110. package/dist/table/create-table-def.d.cts +15 -0
  111. package/dist/table/create-table-def.d.mts +15 -0
  112. package/dist/table/create-table-def.mjs +233 -0
  113. package/dist/table/navigate-href.cjs +45 -0
  114. package/dist/table/navigate-href.d.cts +31 -0
  115. package/dist/table/navigate-href.d.mts +31 -0
  116. package/dist/table/navigate-href.mjs +45 -0
  117. package/dist/table/types.d.cts +287 -0
  118. package/dist/table/types.d.mts +287 -0
  119. package/dist/table/value-kind.cjs +20 -0
  120. package/dist/table/value-kind.d.cts +15 -0
  121. package/dist/table/value-kind.d.mts +15 -0
  122. package/dist/table/value-kind.mjs +19 -0
  123. package/dist/value-help/dict-paths.cjs +17 -0
  124. package/dist/value-help/dict-paths.d.cts +11 -0
  125. package/dist/value-help/dict-paths.d.mts +11 -0
  126. package/dist/value-help/dict-paths.mjs +17 -0
  127. package/dist/value-help/distinct-client.cjs +51 -0
  128. package/dist/value-help/distinct-client.d.cts +40 -0
  129. package/dist/value-help/distinct-client.d.mts +40 -0
  130. package/dist/value-help/distinct-client.mjs +50 -0
  131. package/dist/value-help/extract-literals.cjs +76 -0
  132. package/dist/value-help/extract-literals.d.cts +32 -0
  133. package/dist/value-help/extract-literals.d.mts +32 -0
  134. package/dist/value-help/extract-literals.mjs +74 -0
  135. package/dist/value-help/extract-ref.cjs +100 -0
  136. package/dist/value-help/extract-ref.d.cts +37 -0
  137. package/dist/value-help/extract-ref.d.mts +37 -0
  138. package/dist/value-help/extract-ref.mjs +100 -0
  139. package/dist/value-help/filter-tree.cjs +45 -0
  140. package/dist/value-help/filter-tree.mjs +45 -0
  141. package/dist/value-help/index.d.mts +8 -0
  142. package/dist/value-help/resolve-options.cjs +64 -0
  143. package/dist/value-help/resolve-options.d.cts +35 -0
  144. package/dist/value-help/resolve-options.d.mts +35 -0
  145. package/dist/value-help/resolve-options.mjs +60 -0
  146. package/dist/value-help/resolve.cjs +62 -0
  147. package/dist/value-help/resolve.d.cts +31 -0
  148. package/dist/value-help/resolve.d.mts +31 -0
  149. package/dist/value-help/resolve.mjs +61 -0
  150. package/dist/value-help/types.d.cts +36 -0
  151. package/dist/value-help/types.d.mts +36 -0
  152. package/dist/value-help/value-help-client.cjs +136 -0
  153. package/dist/value-help/value-help-client.d.cts +67 -0
  154. package/dist/value-help/value-help-client.d.mts +67 -0
  155. package/dist/value-help/value-help-client.mjs +134 -0
  156. package/package.json +10 -10
package/dist/index.mjs CHANGED
@@ -1,3179 +1,35 @@
1
- import { Validator, createDataFromAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType } from "@atscript/typescript/utils";
2
- import { createDbValidatorPlugin, isServerStampedOnUpdate } from "@atscript/db/validator";
3
- import { Client, actionIdentifier, clearMetaStore, defaultMetaStore, encodeNavigateId } from "@atscript/db-client";
4
- //#region src/shared/annotation-keys.ts
5
- const UI_TYPE = "ui.type";
6
- const UI_FORM_PLACEHOLDER = "ui.form.placeholder";
7
- const UI_FORM_HINT = "ui.form.hint";
8
- const UI_FORM_CLASSES = "ui.form.classes";
9
- const UI_FORM_STYLES = "ui.form.styles";
10
- const UI_FORM_AUTOCOMPLETE = "ui.form.autocomplete";
11
- const UI_FORM_DISABLED = "ui.form.disabled";
12
- const UI_FORM_OPTIONS = "ui.form.options";
13
- const UI_FORM_ORDER = "ui.form.order";
14
- const UI_FORM_TYPE = "ui.form.type";
15
- const UI_FORM_COMPONENT = "ui.form.component";
16
- const UI_FORM_HIDDEN = "ui.form.hidden";
17
- const UI_FORM_PUSH_DOWN = "ui.form.pushDown";
18
- const UI_FORM_ATTR = "ui.form.attr";
19
- const UI_FORM_GRID_COL_SPAN = "ui.form.grid.colSpan";
20
- const UI_FORM_GRID_ROW_SPAN = "ui.form.grid.rowSpan";
21
- const UI_FORM_SUBMIT_TEXT = "ui.form.submit.text";
22
- const UI_FORM_LABEL_SINGULAR = "ui.form.label.singular";
23
- const UI_FORM_ACTION = "ui.form.action";
24
- const UI_FORM_PREFIX = "ui.form.prefix";
25
- const UI_FORM_PREFIX_REF = "ui.form.prefix.ref";
26
- const UI_FORM_PREFIX_ICON = "ui.form.prefix.icon";
27
- const UI_FORM_SUFFIX = "ui.form.suffix";
28
- const UI_FORM_SUFFIX_REF = "ui.form.suffix.ref";
29
- const UI_FORM_SUFFIX_ICON = "ui.form.suffix.icon";
30
- const UI_TABLE_WIDTH = "ui.table.width";
31
- const UI_TABLE_COMPONENT = "ui.table.component";
32
- const UI_TABLE_SELECT_WITH = "ui.table.selectWith";
33
- const UI_TABLE_EXCLUDE = "ui.table.exclude";
34
- const UI_TABLE_ATTR = "ui.table.attr";
35
- const UI_TABLE_CLASSES = "ui.table.classes";
36
- const UI_TABLE_STYLES = "ui.table.styles";
37
- const UI_TABLE_TYPE = "ui.table.type";
38
- const UI_TABLE_ORDER = "ui.table.order";
39
- const UI_DICT_LABEL = "ui.dict.label";
40
- const UI_DICT_DESCR = "ui.dict.descr";
41
- const UI_DICT_ATTR = "ui.dict.attr";
42
- const UI_DICT_FILTERABLE = "ui.dict.filterable";
43
- const UI_DICT_SORTABLE = "ui.dict.sortable";
44
- const UI_DICT_SEARCHABLE = "ui.dict.searchable";
45
- const UI_VALUE_HELP = "ui.valueHelp";
46
- const UI_NAV_GROUP = "ui.nav.group";
47
- const UI_NAV_ORDER = "ui.nav.order";
48
- const UI_NAV_HIDDEN = "ui.nav.hidden";
49
- const DB_REL_FK = "db.rel.FK";
50
- const DB_TABLE = "db.table";
51
- const DB_VIEW = "db.view";
52
- const DB_HTTP_PATH = "db.http.path";
53
- const DB_AMOUNT_CURRENCY = "db.amount.currency";
54
- const DB_AMOUNT_CURRENCY_REF = "db.amount.currency.ref";
55
- const DB_UNIT = "db.unit";
56
- const DB_UNIT_REF = "db.unit.ref";
57
- const DB_COLUMN_PRECISION = "db.column.precision";
58
- const WF_ACTION_WITH_DATA = "wf.action.withData";
59
- const META_LABEL = "meta.label";
60
- const META_ID = "meta.id";
61
- const META_DESCRIPTION = "meta.description";
62
- const META_READONLY = "meta.readonly";
63
- const META_REQUIRED = "meta.required";
64
- const META_DEFAULT = "meta.default";
65
- const META_SENSITIVE = "meta.sensitive";
66
- const EXPECT_MAX_LENGTH = "expect.maxLength";
67
- const UI_FORM_FN_PREFIX = "ui.form.fn.";
68
- const UI_FORM_FN_LABEL = "ui.form.fn.label";
69
- const UI_FORM_FN_PLACEHOLDER = "ui.form.fn.placeholder";
70
- const UI_FORM_FN_DESCRIPTION = "ui.form.fn.description";
71
- const UI_FORM_FN_HINT = "ui.form.fn.hint";
72
- const UI_FORM_FN_HIDDEN = "ui.form.fn.hidden";
73
- const UI_FORM_FN_DISABLED = "ui.form.fn.disabled";
74
- const UI_FORM_FN_READONLY = "ui.form.fn.readonly";
75
- const UI_FORM_FN_OPTIONS = "ui.form.fn.options";
76
- const UI_FORM_FN_ATTR = "ui.form.fn.attr";
77
- const UI_FORM_FN_VALUE = "ui.form.fn.value";
78
- const UI_FORM_FN_CLASSES = "ui.form.fn.classes";
79
- const UI_FORM_FN_STYLES = "ui.form.fn.styles";
80
- const UI_FORM_FN_TITLE = "ui.form.fn.title";
81
- const UI_FORM_FN_SUBMIT_TEXT = "ui.form.fn.submit.text";
82
- const UI_FORM_FN_SUBMIT_DISABLED = "ui.form.fn.submit.disabled";
83
- const UI_TABLE_FN_PREFIX = "ui.table.fn.";
84
- const UI_TABLE_FN_ATTR = "ui.table.fn.attr";
85
- const UI_TABLE_FN_CLASSES = "ui.table.fn.classes";
86
- const UI_TABLE_FN_STYLES = "ui.table.fn.styles";
87
- const UI_FORM_VALIDATE = "ui.form.validate";
88
- //#endregion
89
- //#region src/form/types.ts
90
- /** Type guard: checks if a field def is an array field. */
91
- function isArrayField(field) {
92
- return field.type === "array";
93
- }
94
- /** Type guard: checks if a field def is an object field. */
95
- function isObjectField(field) {
96
- return field.type === "object";
97
- }
98
- /** Type guard: checks if a field def is a union field. */
99
- function isUnionField(field) {
100
- return field.type === "union";
101
- }
102
- /** Type guard: checks if a field def is a tuple field. */
103
- function isTupleField(field) {
104
- return field.type === "tuple";
105
- }
106
- //#endregion
107
- //#region src/shared/field-resolver.ts
108
- /** Static resolver — ignores fn keys, reads only static metadata. */
109
- var StaticFieldResolver = class {
110
- resolveFieldProp(prop, _fnKey, staticKey, _scope, opts) {
111
- return resolveStatic(prop.metadata, staticKey, opts);
112
- }
113
- resolveFormProp(type, _fnKey, staticKey, _scope, opts) {
114
- return resolveStatic(type.metadata, staticKey, opts);
115
- }
116
- hasComputedAnnotations(_prop) {
117
- return false;
118
- }
119
- };
120
- /** Resolves a static metadata value. Exported for reuse by dynamic resolvers. */
121
- function resolveStatic(metadata, staticKey, opts) {
122
- if (staticKey === void 0) return void 0;
123
- const staticVal = metadata.get(staticKey);
124
- if (staticVal !== void 0) {
125
- if (opts?.staticAsBoolean) return true;
126
- if (opts?.transform) return opts.transform(staticVal);
127
- return staticVal;
128
- }
129
- }
130
- /** Default static resolver instance. */
131
- const defaultResolver = new StaticFieldResolver();
132
- let activeResolver = defaultResolver;
133
- /** Replace the active resolver (called by ui-fns to install dynamic resolution). */
134
- function setResolver(resolver) {
135
- activeResolver = resolver;
136
- }
137
- /** Get the current active resolver. */
138
- function getResolver() {
139
- return activeResolver;
140
- }
141
- /** Resolve a field-level metadata property via the active resolver. */
142
- function resolveFieldProp(prop, fnKey, staticKey, scope, opts) {
143
- return activeResolver.resolveFieldProp(prop, fnKey, staticKey, scope, opts);
144
- }
145
- /** Resolve a form-level metadata property via the active resolver. */
146
- function resolveFormProp(type, fnKey, staticKey, scope, opts) {
147
- return activeResolver.resolveFormProp(type, fnKey, staticKey, scope, opts);
148
- }
149
- /** Check if a prop has dynamic annotations via the active resolver. */
150
- function hasComputedAnnotations(prop) {
151
- return activeResolver.hasComputedAnnotations(prop);
152
- }
153
- /**
154
- * SSOT for field hidden resolution — resolves `@ui.form.fn.hidden`
155
- * (dynamic, via the active resolver) with static `@ui.form.hidden`
156
- * presence as the fallback. Absent both → `false` (visible).
157
- */
158
- function isFieldHidden(prop, scope) {
159
- return resolveFieldProp(prop, "ui.form.fn.hidden", "ui.form.hidden", scope, { staticAsBoolean: true }) ?? false;
160
- }
161
- function getFieldMeta(prop, key) {
162
- return prop.metadata.get(key);
163
- }
164
- /** Checks whether a metadata key is present on an ATScript prop. */
165
- function hasFieldMeta(prop, key) {
166
- return prop.metadata.has(key);
167
- }
168
- /** Ensures a value is an array — returns as-is if already one, wraps in `[x]` otherwise. */
169
- function asArray(x) {
170
- return Array.isArray(x) ? x : [x];
171
- }
172
- /**
173
- * Parses static `ui.attr` metadata into a key-value record.
174
- * Exported so ui-fns can reuse this without duplicating the parsing logic.
175
- */
176
- function parseStaticAttrs(staticAttrs) {
177
- if (!staticAttrs) return void 0;
178
- const result = {};
179
- let hasAttrs = false;
180
- for (const item of asArray(staticAttrs)) if (typeof item === "object" && item !== null && "name" in item && "value" in item) {
181
- const { name, value } = item;
182
- result[name] = value;
183
- hasAttrs = true;
184
- }
185
- return hasAttrs ? result : void 0;
186
- }
187
- /**
188
- * Resolves `<staticKey>` + `<fnKey>` attr metadata on demand.
189
- * Defaults read `ui.form.attr` + `ui.form.fn.attr`; pass `{ staticKey, fnKey }` to read
190
- * the table-side pair (`ui.table.attr` + `ui.table.fn.attr`) or any other surface.
191
- */
192
- function resolveAttrs(prop, scope, keys = {}) {
193
- const staticKey = keys.staticKey ?? "ui.form.attr";
194
- const fnKey = keys.fnKey ?? "ui.form.fn.attr";
195
- const staticAttrs = getFieldMeta(prop, staticKey);
196
- const fnAttrs = getFieldMeta(prop, fnKey);
197
- if (!staticAttrs && !fnAttrs) return void 0;
198
- const result = {};
199
- let hasAttrs = false;
200
- const parsed = parseStaticAttrs(staticAttrs);
201
- if (parsed) {
202
- Object.assign(result, parsed);
203
- hasAttrs = true;
204
- }
205
- if (fnAttrs) {
206
- const resolved = resolveFieldProp(prop, fnKey, void 0, scope);
207
- if (resolved) {
208
- Object.assign(result, resolved);
209
- hasAttrs = true;
210
- }
211
- }
212
- return hasAttrs ? result : void 0;
213
- }
214
- //#endregion
215
- //#region src/value-help/extract-literals.ts
216
- /**
217
- * Extracts options from a union of literal types (e.g. 'a' | 'b' | 'c').
218
- * Returns undefined if the type is not a pure union of literals.
219
- *
220
- * Handles nested unions created by flattenAnnotatedType, which recurses
221
- * into union items and produces synthetic unions containing both individual
222
- * literals and the original union type as nested items.
223
- */
224
- function extractLiteralOptions(prop, outer) {
225
- if (prop.type.kind !== "union") return void 0;
226
- const result = collectLiterals(prop.type.items, /* @__PURE__ */ new Set());
227
- if (!result || result.length === 0) return void 0;
228
- const labels = [prop, outer].flatMap((node) => node?.metadata.get("ui.literalLabel") ?? []);
229
- if (labels.length) {
230
- const byValue = new Map(labels.map((l) => [l.value, l.label]));
231
- for (const option of result) option.label = byValue.get(option.key) ?? option.label;
232
- }
233
- return result;
234
- }
235
- /**
236
- * The literal options of a field: a literal union's, or those of an array of one
237
- * (`tags: Tag[]`), where the array prop's own `@ui.literalLabel` labels win over the
238
- * element type's. `undefined` when the field is neither. Since 0.1.148.
239
- */
240
- function extractFieldLiteralOptions(prop) {
241
- if (prop.type.kind === "array") return extractLiteralOptions(prop.type.of, prop);
242
- return extractLiteralOptions(prop);
243
- }
244
- /** Returns true when the annotated type is a union composed entirely of literal values. */
245
- function isPureLiteralUnion(prop) {
246
- if (prop.type.kind !== "union") return false;
247
- return checkAllLiterals(prop.type.items);
248
- }
249
- /** Walks union items returning true only if every leaf is a literal value. */
250
- function checkAllLiterals(items) {
251
- for (const item of items) {
252
- if (item.type.kind === "" && item.type.value !== void 0) continue;
253
- if (item.type.kind === "union") {
254
- if (!checkAllLiterals(item.type.items)) return false;
255
- continue;
256
- }
257
- return false;
258
- }
259
- return items.length > 0;
260
- }
261
- /**
262
- * Recursively collects literal values from union items.
263
- * Returns null if any non-literal, non-union item is found (invalid union).
264
- * Returns empty array when all items are valid but already seen (deduped).
265
- */
266
- function collectLiterals(items, seen) {
267
- const result = [];
268
- for (const item of items) if (item.type.kind === "" && item.type.value !== void 0) {
269
- const raw = item.type.value;
270
- const val = String(raw);
271
- if (!seen.has(val)) {
272
- seen.add(val);
273
- result.push({
274
- key: val,
275
- label: val,
276
- value: raw
277
- });
278
- }
279
- } else if (item.type.kind === "union") {
280
- const nested = collectLiterals(item.type.items, seen);
281
- if (nested === null) return null;
282
- result.push(...nested);
283
- } else return null;
284
- return result;
285
- }
286
- //#endregion
287
- //#region src/value-help/filter-tree.ts
288
- function isFieldRef(value) {
289
- return value !== null && typeof value === "object" && "field" in value;
290
- }
291
- /**
292
- * A deliberate copy of `translateQueryTree` from `@atscript/db`: that module is a
293
- * server-side runtime, and importing it would pull `@atscript/db` into the browser
294
- * bundle. `filter-tree.spec.ts` guards the two against drift.
295
- */
296
- function translate(node) {
297
- if (Array.isArray(node.$and)) return { $and: node.$and.map(translate) };
298
- if (Array.isArray(node.$or)) return { $or: node.$or.map(translate) };
299
- if (node.$not && typeof node.$not === "object") return { $not: translate(node.$not) };
300
- const left = node.left.field;
301
- const op = node.op;
302
- const right = node.right;
303
- if (isFieldRef(right)) return { [left]: { [op]: { $field: right.field } } };
304
- if (op === "$exists") return { [left]: { $exists: right !== false } };
305
- return { [left]: { [op]: right } };
306
- }
307
- /**
308
- * Fields the tree pins to one value (`=` comparison against a literal) at its top-level
309
- * `and` chain. The runtime twin of `pinnedFields` in `plugin/value-help-validation.ts`
310
- * (which reads the source predicate) — keep the two rules in step.
311
- */
312
- function pinnedOf(node, out) {
313
- if (Array.isArray(node.$and)) for (const n of node.$and) pinnedOf(n, out);
314
- else if (node.left && node.op === "$eq" && !isFieldRef(node.right)) out.push(node.left.field);
315
- }
316
- /**
317
- * Translates the static `filter` of a `@ui.valueHelp` binding into a Uniquery
318
- * `FilterExpr` (mirrors `translateQueryTree` of `@atscript/db`, with refs
319
- * resolved to the plain field path), plus the target fields it pins with `=` —
320
- * constant inside the picker, so their columns are hidden. Since 0.1.148.
321
- */
322
- function valueHelpFilter(tree) {
323
- const pinned = [];
324
- pinnedOf(tree, pinned);
325
- return {
326
- filter: translate(tree),
327
- pinned: [...new Set(pinned)]
328
- };
329
- }
330
- //#endregion
331
- //#region src/value-help/extract-ref.ts
332
- /**
333
- * Hard cap on how many `.ref` hops the chain walk follows. Real chains are one
334
- * or two hops (view field → table field → dictionary); the cap is a backstop,
335
- * not a modelling limit — and it is also what terminates a cyclic chain.
336
- */
337
- const MAX_REF_CHAIN_DEPTH = 8;
338
- /**
339
- * `@db.http.path` of a binding target. Two producers, two shapes — `/meta`
340
- * deserialization does not normalize annotation values, so both are read here:
341
- *
342
- * - compiled `.as` (the atscript runtime): the annotated type itself (a class
343
- * with a `metadata` Map) or a getter `() => Type` for a cross-file ref;
344
- * - `/meta` (the serialized type): a shallow target `{ id, metadata }` whose
345
- * `metadata` is a plain record.
346
- *
347
- * Also accepts `{ type: () => Type }`.
348
- */
349
- function bindingTargetPath(target) {
350
- if (target === null || typeof target !== "object" && typeof target !== "function") return;
351
- const t = target;
352
- if (typeof target === "function" && t.metadata === void 0) return bindingTargetPath(target());
353
- if (t.metadata instanceof Map) return t.metadata.get(DB_HTTP_PATH);
354
- if (t.metadata && typeof t.metadata === "object") return t.metadata[DB_HTTP_PATH];
355
- return t.type === void 0 ? void 0 : bindingTargetPath(t.type);
356
- }
357
- /**
358
- * The `@ui.valueHelp` binding of a node, when its target is served by a
359
- * controller (`@db.http.path`). Without a path the binding is ignored and the
360
- * caller falls back to the FK walk.
361
- */
362
- function bindingInfo(node) {
363
- const binding = node.metadata.get(UI_VALUE_HELP);
364
- if (!binding?.field) return void 0;
365
- const url = bindingTargetPath(binding.target);
366
- if (!url) return void 0;
367
- const info = {
368
- url,
369
- targetField: binding.field
370
- };
371
- if (binding.filter) {
372
- const { filter, pinned } = valueHelpFilter(binding.filter);
373
- info.filter = filter;
374
- if (pinned.length > 0) info.pinned = pinned;
375
- }
376
- return info;
377
- }
378
- /**
379
- * Synchronous probe. Returns `{ url, targetField }` for the first link of the
380
- * reference chain starting at `prop` that carries a `@ui.valueHelp` binding
381
- * (since 0.1.148 — an explicit binding beats `@db.rel.FK`, and also supplies
382
- * the static `filter` / `pinned` fields), or that satisfies all three conditions:
383
- *
384
- * 1. the link carries `@db.rel.FK`,
385
- * 2. the link has a `.ref`,
386
- * 3. the ref's target metadata carries `@db.http.path`.
387
- *
388
- * Since 0.1.134 the probe follows **reference chains**: when a link does not
389
- * qualify, it hops onto the referenced field (`ref.type()` → that object's
390
- * `props[ref.field]`) and re-tests. A view field declared as
391
- * `errorCode: Issue.errorCode`, where `Issue.errorCode: ErrorCode.code` is the
392
- * link carrying `@db.rel.FK`, therefore keeps its value help instead of losing
393
- * the dictionary.
394
- *
395
- * This mirrors what the server already does on the `/meta` path: since
396
- * `@atscript/db` 0.1.128 the serialized meta collapses such chains onto the
397
- * terminal field (`ref` → terminal, `db.rel.FK: true`), so a form def built
398
- * from `/meta` and one built from the compiled `.as` type land on the same
399
- * dictionary.
400
- *
401
- * The walk is bounded ({@link MAX_REF_CHAIN_DEPTH}), which is also what makes a
402
- * cyclic chain terminate (it runs out of hops and gives up instead of looping).
403
- * It stops as soon as a link has no `.ref`, or the referenced
404
- * field cannot be found — e.g. behind a shallow `{ id, metadata }` ref target
405
- * from `/meta`, which carries no props (and needs none: the server already
406
- * resolved the chain).
407
- */
408
- function extractValueHelp(prop) {
409
- let node = prop;
410
- for (let depth = 0; node && depth < MAX_REF_CHAIN_DEPTH; depth++) {
411
- const bound = bindingInfo(node);
412
- if (bound) return bound;
413
- const ref = node.ref;
414
- if (!ref) return void 0;
415
- const target = ref.type();
416
- if (!target) return void 0;
417
- if (node.metadata.has("db.rel.FK")) {
418
- const url = target.metadata.get(DB_HTTP_PATH);
419
- if (url) return {
420
- url,
421
- targetField: ref.field
422
- };
423
- }
424
- node = (target.type.kind === "object" ? target.type : void 0)?.props.get(ref.field);
425
- }
426
- }
427
- //#endregion
428
- //#region src/form/create-form-def.ts
429
- /** Known atscript primitive extension tags that map directly to field types. */
430
- const UI_TAGS = new Set([
431
- "action",
432
- "paragraph",
433
- "select",
434
- "radio",
435
- "checkbox"
436
- ]);
437
- const EDIT = { mode: "edit" };
438
- /**
439
- * Converts an ATScript annotated type into a FormDef.
440
- *
441
- * - **Object types** (`kind === 'object'`): produces an object root with nested fields.
442
- * - **Non-object types** (primitive, array, union, etc.): produces a single leaf root field
443
- * with `path: ''`.
444
- *
445
- * A `@db.column.derived` field is marked `derived` straight from its metadata;
446
- * a computed view column, from `opts.metaFields`; an update-stamped field
447
- * (see `CreateFormDefOptions.mode`), when `opts.mode` is `"edit"`.
448
- */
449
- function createFormDef(type, opts) {
450
- const edit = opts?.mode === "edit";
451
- if (type.type.kind !== "object") {
452
- const rootField = createFieldDef("", type, edit);
453
- const fields = [rootField];
454
- return {
455
- type,
456
- rootField,
457
- fields,
458
- mainFields: fields,
459
- pushDownFields: [],
460
- flatMap: /* @__PURE__ */ new Map()
461
- };
462
- }
463
- const objectType = type;
464
- const flatMap = flattenAnnotatedType(objectType, { excludePhantomTypes: false });
465
- const fields = [];
466
- const structuredPrefixes = /* @__PURE__ */ new Set();
467
- for (const [path, prop] of flatMap.entries()) {
468
- if (path === "") continue;
469
- if (path === opts?.versionColumn) continue;
470
- if (isChildOfStructured(path, structuredPrefixes)) continue;
471
- const originalProp = resolveOriginalProp(objectType, path) ?? prop;
472
- const kind = originalProp.type.kind;
473
- if (kind === "object" && !isStructuredObject(originalProp)) continue;
474
- if (kind === "array") {
475
- if (originalProp.type.of.type.kind === "array" && !getFieldMeta(originalProp, "ui.form.component")) continue;
476
- }
477
- if (kind === "array" || kind === "object" || kind === "union" || kind === "tuple") structuredPrefixes.add(path + ".");
478
- const field = createFieldDef(path, originalProp, edit);
479
- if (opts?.metaFields?.[path]?.computed) field.derived = true;
480
- fields.push(field);
481
- }
482
- const orderMap = new Map(fields.map((f) => [f, getFieldMeta(f.prop, "ui.form.order") ?? Infinity]));
483
- fields.sort((a, b) => orderMap.get(a) - orderMap.get(b));
484
- const rootField = {
485
- path: "",
486
- prop: type,
487
- type: "object",
488
- phantom: false,
489
- name: "",
490
- allStatic: false,
491
- pushDown: false
492
- };
493
- let mainFields = fields;
494
- const pushDownFields = [];
495
- if (fields.some((f) => f.pushDown)) {
496
- mainFields = [];
497
- for (const f of fields) (f.pushDown ? pushDownFields : mainFields).push(f);
498
- }
499
- const def = {
500
- type,
501
- rootField,
502
- fields,
503
- mainFields,
504
- pushDownFields,
505
- flatMap
506
- };
507
- rootField.objectDef = def;
508
- return def;
509
- }
510
- /**
511
- * Creates a FormFieldDef from any ATScript annotated type. `edit`: the form
512
- * edits a stored row (`CreateFormDefOptions.mode`).
513
- */
514
- function createFieldDef(path, prop, edit = false) {
515
- const kind = prop.type.kind;
516
- const name = path.slice(path.lastIndexOf(".") + 1);
517
- const allStatic = !hasComputedAnnotations(prop);
518
- const uiType = getFieldMeta(prop, "ui.form.type") ?? getFieldMeta(prop, "ui.type");
519
- const pushDown = getFieldMeta(prop, UI_FORM_PUSH_DOWN) !== void 0;
520
- const valueHelpInfo = extractValueHelp(prop);
521
- const derived = getFieldMeta(prop, "db.column.derived") !== void 0 || edit && path !== "" && isUpdateStamped(prop);
522
- const base = {
523
- path,
524
- prop,
525
- phantom: false,
526
- name,
527
- allStatic,
528
- pushDown,
529
- valueHelpInfo,
530
- ...derived && { derived: true }
531
- };
532
- const customType = uiType;
533
- if (kind === "array") {
534
- const arrayType = prop.type;
535
- const isMultiselect = customType === "multiselect" || getFieldMeta(prop, "ui.form.options") !== void 0 || getFieldMeta(prop, "ui.form.fn.options") !== void 0 || isPureLiteralUnion(arrayType.of);
536
- return {
537
- ...base,
538
- type: "array",
539
- customType: isMultiselect ? "multiselect" : customType,
540
- itemType: arrayType.of,
541
- itemField: createFieldDef("", arrayType.of, edit)
542
- };
543
- }
544
- if (kind === "object") return {
545
- ...base,
546
- type: "object",
547
- customType,
548
- objectDef: createFormDef(prop, edit ? EDIT : void 0)
549
- };
550
- if (kind === "union") {
551
- if (isPureLiteralUnion(prop)) return {
552
- ...base,
553
- type: uiType ?? "select"
554
- };
555
- const unionVariants = createUnionVariants(prop, edit && soleValueMember(prop) !== void 0);
556
- if (unionVariants.length > 1) return {
557
- ...base,
558
- type: "union",
559
- customType,
560
- unionVariants
561
- };
562
- const v = unionVariants[0];
563
- if (v?.itemField) return {
564
- ...v.itemField,
565
- path,
566
- name,
567
- allStatic,
568
- pushDown,
569
- ...derived && { derived: true }
570
- };
571
- if (v?.def) return {
572
- ...base,
573
- type: "object",
574
- customType,
575
- objectDef: v.def
576
- };
577
- }
578
- if (kind === "tuple") {
579
- const tupleType = prop.type;
580
- return {
581
- ...base,
582
- type: "tuple",
583
- customType,
584
- itemFields: tupleType.items.map((item, i) => {
585
- const field = createFieldDef(String(i), item);
586
- field.name = "";
587
- return field;
588
- })
589
- };
590
- }
591
- if (valueHelpInfo) return {
592
- ...base,
593
- type: uiType ?? "ref"
594
- };
595
- const tags = kind === "" ? prop.type.tags : void 0;
596
- let uiTag;
597
- let isTimestamp = false;
598
- if (tags) for (const t of tags) {
599
- if (uiTag === void 0 && UI_TAGS.has(t)) uiTag = t;
600
- if (t === "timestamp") isTimestamp = true;
601
- }
602
- const dt = kind === "" ? prop.type.designType : void 0;
603
- let numericType;
604
- if (kind === "") {
605
- const hasCurrency = getFieldMeta(prop, "db.amount.currency") !== void 0 || getFieldMeta(prop, "db.amount.currency.ref") !== void 0;
606
- const isDecimalDesign = dt === "decimal";
607
- if (hasCurrency) numericType = "decimal";
608
- else if (isDecimalDesign) numericType = "decimal";
609
- else if (dt === "number") {
610
- const hasUnit = getFieldMeta(prop, "db.unit") !== void 0 || getFieldMeta(prop, "db.unit.ref") !== void 0;
611
- const hasPrefix = getFieldMeta(prop, "ui.form.prefix") !== void 0 || getFieldMeta(prop, "ui.form.prefix.ref") !== void 0 || getFieldMeta(prop, "ui.form.prefix.icon") !== void 0;
612
- const hasSuffix = getFieldMeta(prop, "ui.form.suffix") !== void 0 || getFieldMeta(prop, "ui.form.suffix.ref") !== void 0 || getFieldMeta(prop, "ui.form.suffix.icon") !== void 0;
613
- if (hasUnit || hasPrefix || hasSuffix) numericType = "number";
614
- }
615
- }
616
- const tagType = isTimestamp ? "datetime" : void 0;
617
- return {
618
- ...base,
619
- type: uiType ?? uiTag ?? numericType ?? tagType ?? (dt === "number" ? "number" : dt === "boolean" ? "checkbox" : "text"),
620
- phantom: kind === "" && dt === "phantom"
621
- };
622
- }
623
- /** Non-`ui.form.*` keys that still address the object itself. */
624
- const OBJECT_IDENTITY_KEYS = new Set([
625
- META_LABEL,
626
- META_DESCRIPTION,
627
- UI_TYPE
628
- ]);
629
- const UI_FORM_NS = "ui.form.";
630
- /** `ui.form.*` keys that place a field rather than give it an identity. */
631
- const UI_FORM_PLACEMENT_NS = "ui.form.grid.";
632
- /**
633
- * Whether an object prop renders as a field of its own rather than being
634
- * flattened into its parent.
635
- *
636
- * Any `@ui.form.*` annotation (plus `@meta.label` / `@meta.description` /
637
- * `@ui.type`) means the author addressed the object itself, so it needs a
638
- * field to carry that instruction to a renderer — a collapsible section, or
639
- * whatever `@ui.form.component` / `@ui.form.type` names. An object with none
640
- * of them is a pure namespace: it is dropped and its children render inline
641
- * in the parent grid, which keeps DB-flattened structs (`addr.street` stored
642
- * as `addr__street`) from growing chrome nobody asked for. `@db.*`,
643
- * `@expect.*` and the rest of `@meta.*` stay out for exactly that reason —
644
- * they are what such a struct carries.
645
- *
646
- * Placement keys (`@ui.form.order`, `@ui.form.grid.*`) are excluded: they
647
- * position a field among its siblings, and a namespace has no position of its
648
- * own — its children carry their own.
649
- *
650
- * A prefix rule rather than a list because the list was wrong the moment it
651
- * was written. Matching on `@meta.label` and `@ui.form.component` alone left
652
- * every other key to be read off a prop that never became a field: a
653
- * `@meta.description` went missing, a `@ui.form.type` component silently
654
- * never mounted, `@ui.form.pushDown` never pushed down, and — the one that
655
- * mattered — `@ui.form.hidden` on a struct left every child on screen.
656
- */
657
- function isStructuredObject(prop) {
658
- for (const key of prop.metadata.keys()) {
659
- if (OBJECT_IDENTITY_KEYS.has(key)) return true;
660
- if (!key.startsWith(UI_FORM_NS)) continue;
661
- if (key === "ui.form.order" || key.startsWith(UI_FORM_PLACEMENT_NS)) continue;
662
- return true;
663
- }
664
- return false;
665
- }
666
- /** Resolves the original annotated type from the type hierarchy by path. */
667
- function resolveOriginalProp(type, path) {
668
- const parts = path.split(".");
669
- let current = type.type;
670
- for (let i = 0; i < parts.length - 1; i++) {
671
- const prop = current.props.get(parts[i]);
672
- if (!prop || prop.type.kind !== "object") return void 0;
673
- current = prop.type;
674
- }
675
- return current.props.get(parts[parts.length - 1]);
676
- }
677
- /** Check if a path is a child of any structured prefix (prefixes are pre-suffixed with "."). */
678
- function isChildOfStructured(path, prefixes) {
679
- for (const prefix of prefixes) if (path.startsWith(prefix)) return true;
680
- return false;
681
- }
682
- /**
683
- * Builds union variant definitions from a union annotated type.
684
- * Iterates top-level items directly — one variant per item.
685
- */
686
- function buildUnionVariants(typeDef) {
687
- return createUnionVariants(typeDef, false);
688
- }
689
- function createUnionVariants(typeDef, edit) {
690
- const items = typeDef.type.items ?? [typeDef];
691
- const variants = [];
692
- for (const item of items) {
693
- const v = createVariant(item, edit);
694
- if (items.length > 1) v.label = `${String(variants.length + 1)}. ${v.label}`;
695
- variants.push(v);
696
- }
697
- return variants;
698
- }
699
- /** Creates a single union variant from an annotated type item. */
700
- function createVariant(def, edit) {
701
- const kind = def.type.kind;
702
- if (kind === "object") {
703
- const label = getFieldMeta(def, "meta.label") ?? "Object";
704
- const hasComponent = getFieldMeta(def, UI_FORM_COMPONENT) !== void 0;
705
- return {
706
- label,
707
- type: def,
708
- def: createFormDef(def, edit ? EDIT : void 0),
709
- itemField: hasComponent ? createFieldDef("", def, edit) : void 0
710
- };
711
- }
712
- if (kind === "") {
713
- const dt = def.type.designType;
714
- return {
715
- label: capitalize(dt === "phantom" ? "item" : dt),
716
- type: def,
717
- itemField: createFieldDef("", def, edit),
718
- designType: dt
719
- };
720
- }
721
- return {
722
- label: capitalize(kind),
723
- type: def,
724
- itemField: createFieldDef("", def, edit)
725
- };
726
- }
727
- /**
728
- * An update-stamped field (see `CreateFormDefOptions.mode`). Read off the prop,
729
- * or — as `@atscript/db` does — off the one value member of `T | null`, unless
730
- * the prop references another field.
731
- */
732
- function isUpdateStamped(prop) {
733
- if (isServerStampedOnUpdate(prop.metadata)) return true;
734
- const member = prop.ref?.field ? void 0 : soleValueMember(prop);
735
- return member !== void 0 && isServerStampedOnUpdate(member.metadata);
736
- }
737
- /** The one non-`null` / `undefined` member of a (nested) union, if there is exactly one. */
738
- function soleValueMember(prop) {
739
- if (prop.type.kind !== "union") return void 0;
740
- const members = /* @__PURE__ */ new Set();
741
- const visit = (t) => {
742
- if (t.type.kind === "union") for (const item of t.type.items) visit(item);
743
- else if (t.type.kind !== "" || t.type.designType !== "null" && t.type.designType !== "undefined") members.add(t);
744
- };
745
- visit(prop);
746
- return members.size === 1 ? members.values().next().value : void 0;
747
- }
748
- function capitalize(s) {
749
- return s.charAt(0).toUpperCase() + s.slice(1);
750
- }
751
- //#endregion
752
- //#region src/form/form-actions.ts
753
- /**
754
- * Declared actions of a form — the union of `@ui.form.action` ids and
755
- * `@wf.action.withData` ids across all fields. `withData` distinguishes a
756
- * data-carrying workflow action (sends the current form payload) from a plain
757
- * stateless action. Single source of truth for "what actions can a host fire".
758
- */
759
- function getDeclaredFormActions(def) {
760
- const out = [];
761
- for (const field of def.fields) {
762
- const withData = getFieldMeta(field.prop, WF_ACTION_WITH_DATA);
763
- if (withData) {
764
- out.push({
765
- id: withData,
766
- withData: true
767
- });
768
- continue;
769
- }
770
- const plain = getFieldMeta(field.prop, UI_FORM_ACTION);
771
- if (plain?.id) out.push({
772
- id: plain.id,
773
- withData: false
774
- });
775
- }
776
- return out;
777
- }
778
- //#endregion
779
- //#region src/value-help/dict-paths.ts
780
- /**
781
- * Paths that make up the "dict view" of a value-help target:
782
- * PKs + label + descr + attr fields. Used by filter dialogs to clamp
783
- * visible columns to the dictionary subset.
784
- */
785
- function valueHelpDictPaths(resolved) {
786
- const paths = [
787
- ...resolved.primaryKeys,
788
- resolved.labelField,
789
- ...resolved.attrFields
790
- ];
791
- if (resolved.descrField) paths.push(resolved.descrField);
792
- return new Set(paths);
793
- }
794
- //#endregion
795
- //#region src/value-help/resolve-options.ts
796
- /** Extracts the key from an option entry. */
797
- function optKey(opt) {
798
- return typeof opt === "string" ? opt : opt.key;
799
- }
800
- /** Extracts the display label from an option entry. */
801
- function optLabel(opt) {
802
- return typeof opt === "string" ? opt : opt.label;
803
- }
804
- const labelMaps = /* @__PURE__ */ new WeakMap();
805
- /**
806
- * The display label of a literal-union column's option (`@ui.literalLabel`) for
807
- * `value` — `undefined` when the column has no options or none matches. Map-backed
808
- * per options array, so rendering a table does not scan the options per cell.
809
- * The one lookup behind the table cell, the filter chips, export and a custom cell.
810
- * Since 0.1.148.
811
- */
812
- function optionLabel(column, value) {
813
- const options = column.options;
814
- if (!options?.length) return void 0;
815
- if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") return;
816
- let labels = labelMaps.get(options);
817
- if (!labels) {
818
- labels = new Map(options.map((o) => [o.key, o.label]));
819
- labelMaps.set(options, labels);
820
- }
821
- return labels.get(String(value));
822
- }
823
- /**
824
- * Converts raw option annotation value to a normalized array.
825
- */
826
- function parseStaticOptions(raw) {
827
- return asArray(raw).map((item) => {
828
- if (typeof item === "object" && item !== null && "label" in item) {
829
- const { label, value } = item;
830
- return value !== void 0 ? {
831
- key: value,
832
- label
833
- } : label;
834
- }
835
- return String(item);
836
- });
837
- }
838
- /**
839
- * Resolves options from metadata with a fallback chain:
840
- * 1. `@ui.form.fn.options` (dynamic, compiled by ui-fns)
841
- * 2. `@ui.form.options` (static annotation)
842
- * 3. Literal union type extraction (auto-derived from type)
843
- * 4. Future: dictionary / value-help lookup
844
- */
845
- function resolveOptions(prop, scope) {
846
- const resolved = resolveFieldProp(prop, UI_FORM_FN_OPTIONS, UI_FORM_OPTIONS, scope, { transform: parseStaticOptions });
847
- if (resolved !== void 0) return resolved;
848
- return extractFieldLiteralOptions(prop);
849
- }
850
- //#endregion
851
- //#region src/shared/str.ts
852
- /** Converts a dot-path to a human-readable label (e.g. 'firstName' → 'First Name'). */
853
- function humanizePath(path) {
854
- return path.slice(path.lastIndexOf(".") + 1).replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, (s) => s.toUpperCase());
855
- }
856
- /** Escape special regex characters in user input for safe embedding in a `$regex` filter. */
857
- function escapeRegex(input) {
858
- return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
859
- }
860
- /** Safely convert an unknown value to a string without triggering no-base-to-string lint errors. */
861
- function str(value) {
862
- if (typeof value === "string") return value;
863
- if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return `${value}`;
864
- return JSON.stringify(value) ?? "";
865
- }
866
- //#endregion
867
- //#region src/value-help/value-help-client.ts
868
- let cacheTtl = 5e3;
869
- let searches = /* @__PURE__ */ new WeakMap();
870
- /**
871
- * How long (ms) a settled value-help search is reused for an identical
872
- * search on the same client. Default 5000. `0` shares only searches still in
873
- * flight; a negative value turns sharing off. Server-side rendering never
874
- * shares (one process serves many viewers).
875
- */
876
- function setValueHelpCacheTtl(ms) {
877
- cacheTtl = ms;
878
- }
879
- /**
880
- * Drop shared value-help search results — for one `client`, or for every
881
- * client when omitted. Call after writing to a dictionary outside the
882
- * built-in table actions to make pickers refetch at once.
883
- */
884
- function invalidateValueHelpCache(client) {
885
- if (client) searches.get(client)?.clear();
886
- else searches = /* @__PURE__ */ new WeakMap();
887
- }
888
- function now() {
889
- return typeof performance === "undefined" ? Date.now() : performance.now();
890
- }
891
- /** Cache key of a plain-JSON request; `undefined` when it holds anything else (never shared). */
892
- function requestKey(request) {
893
- let plain = true;
894
- try {
895
- const key = JSON.stringify(request, (_k, v) => {
896
- if (typeof v === "function" || typeof v === "symbol") plain = false;
897
- else if (v !== null && typeof v === "object" && !Array.isArray(v)) {
898
- const proto = Object.getPrototypeOf(v);
899
- if (proto !== Object.prototype && proto !== null) plain = false;
900
- }
901
- return v;
902
- });
903
- return plain ? key : void 0;
904
- } catch {
905
- return;
906
- }
907
- }
908
- function sharedQuery(client, request) {
909
- const run = () => client.query(request);
910
- if (cacheTtl < 0 || typeof window === "undefined") return run();
911
- const key = requestKey(request);
912
- if (key === void 0) return run();
913
- let byKey = searches.get(client);
914
- if (!byKey) searches.set(client, byKey = /* @__PURE__ */ new Map());
915
- const hit = byKey.get(key);
916
- if (hit && (hit.settledAt === void 0 || now() - hit.settledAt < cacheTtl)) return hit.promise;
917
- const entry = { promise: run().then((items) => {
918
- entry.settledAt = now();
919
- return items;
920
- }, (err) => {
921
- if (byKey.get(key) === entry) byKey.delete(key);
922
- throw err;
923
- }) };
924
- byKey.set(key, entry);
925
- return entry.promise;
926
- }
927
- /**
928
- * Value-help query client. Wraps a `Client` from `@atscript/db-client`
929
- * with FK-specific search logic (regex fallback for non-searchable tables,
930
- * $select scoping).
931
- *
932
- * Consumers resolve the target's metadata once via `resolveValueHelp(url)`
933
- * and pass the resulting `ResolvedValueHelp` to `search()`. Label resolution
934
- * for cells is deliberately unsupported — cells always display raw ids.
935
- *
936
- * Identical searches on the same `Client` are shared (see
937
- * {@link setValueHelpCacheTtl}).
938
- */
939
- var ValueHelpClient = class {
940
- _client;
941
- constructor(client) {
942
- this._client = client;
943
- }
944
- /**
945
- * Search the target with value-help semantics.
946
- *
947
- * - If target is searchable → sends `$search` (server full-text)
948
- * - If not searchable → sends `$or` regex across select fields + exact PK match
949
- */
950
- async search(resolved, opts) {
951
- const mode = opts?.mode ?? "form";
952
- const limit = opts?.limit ?? 20;
953
- const valueField = opts?.valueField;
954
- const selectFields = opts?.select ?? computeSelectFields(resolved, mode, valueField);
955
- const text = opts?.text;
956
- const scope = opts?.filter;
957
- const controls = {
958
- $select: selectFields,
959
- $limit: limit
960
- };
961
- let filter = scope;
962
- if (text) if (resolved.searchable) controls.$search = text;
963
- else {
964
- const search = buildOrFilter(text, selectFields, valueField ?? resolved.primaryKeys[0] ?? resolved.labelField);
965
- filter = scope ? { $and: [scope, search] } : search;
966
- }
967
- const items = await sharedQuery(this._client, {
968
- ...filter && { filter },
969
- controls
970
- });
971
- return { items: Array.isArray(items) ? items.slice() : items };
972
- }
973
- };
974
- /**
975
- * Compute the $select fields for a value-help query — always including the
976
- * `valueField` the picker commits (a unique non-PK field is otherwise never fetched).
977
- */
978
- function computeSelectFields(resolved, mode, valueField) {
979
- const fields = [...resolved.primaryKeys, resolved.labelField];
980
- if (valueField) fields.push(valueField);
981
- if (resolved.descrField) fields.push(resolved.descrField);
982
- if (mode === "filter") fields.push(...resolved.attrFields);
983
- return [...new Set(fields)];
984
- }
985
- /**
986
- * Build a Uniquery `$or` filter for value-help search across multiple fields.
987
- * Uses regex startsWith (case-insensitive) on text fields + exact match on PK.
988
- */
989
- function buildOrFilter(text, fields, pkField) {
990
- const escaped = escapeRegex(text);
991
- const conditions = [];
992
- for (const field of fields) if (field !== pkField) conditions.push({ [field]: { $regex: `/^${escaped}/i` } });
993
- const asNum = Number(text);
994
- if (!Number.isNaN(asNum)) conditions.push({ [pkField]: asNum });
995
- else conditions.push({ [pkField]: text });
996
- return { $or: conditions };
997
- }
998
- //#endregion
999
- //#region src/value-help/distinct-client.ts
1000
- /**
1001
- * `true` for a 4xx answer — the server declined this picker (gate, ARBAC, unknown field).
1002
- * @internal Shared with `@atscript/vue-table`.
1003
- */
1004
- function isPickerDeclined(err) {
1005
- const status = err?.status;
1006
- return typeof status === "number" && status >= 400 && status < 500;
1007
- }
1008
- /**
1009
- * Distinct values of one column of the table behind `client`, via
1010
- * `/query?$groupBy=<field>`. All server gates (hidden field, ARBAC `$groupBy`
1011
- * control, row scope, write-only, encrypted) apply as for any grouped read; a
1012
- * 4xx rejects with a `ClientError` — see {@link isPickerDeclined}.
1013
- * `hasMore` tells whether another page follows.
1014
- *
1015
- * @internal Backs the distinct-values picker of `@atscript/vue-table`.
1016
- */
1017
- async function fetchDistinctValues(client, field, opts = {}) {
1018
- const limit = opts.limit ?? 50;
1019
- const text = opts.text?.trim();
1020
- const conditions = [];
1021
- if (opts.filter) conditions.push(opts.filter);
1022
- if (text) if (opts.numeric) {
1023
- const n = Number(text);
1024
- if (!Number.isFinite(n)) return {
1025
- items: [],
1026
- hasMore: false
1027
- };
1028
- conditions.push({ [field]: n });
1029
- } else conditions.push({ [field]: { $regex: `/^${escapeRegex(text)}/i` } });
1030
- const filter = conditions.length > 1 ? { $and: conditions } : conditions[0];
1031
- const rows = await client.aggregate({
1032
- ...filter && { filter },
1033
- controls: {
1034
- $groupBy: [field],
1035
- $select: [field],
1036
- ...opts.sortable && { $sort: { [field]: 1 } },
1037
- $limit: limit + 1,
1038
- $skip: opts.skip ?? 0
1039
- }
1040
- });
1041
- return {
1042
- items: rows.slice(0, limit).map((r) => r[field]).filter((v) => v !== null && v !== void 0),
1043
- hasMore: rows.length > limit
1044
- };
1045
- }
1046
- //#endregion
1047
- //#region src/client-factory.ts
1048
- const builtin = (url, options) => new Client(url, options);
1049
- let _default = builtin;
1050
- /**
1051
- * Override the app-wide default factory. Call once at startup (e.g. in
1052
- * `entry-client.ts`) to wire shared fetch, credentials, error handling, etc.
1053
- * Every table, value-help picker, and other client consumer will pick it up.
1054
- */
1055
- function setDefaultClientFactory(factory) {
1056
- _default = factory;
1057
- }
1058
- /** Current app-wide default factory. Falls back to `new Client(url, options)`. */
1059
- function getDefaultClientFactory() {
1060
- return _default;
1061
- }
1062
- /** Reset the default factory to the built-in one (primarily for tests). */
1063
- function resetDefaultClientFactory() {
1064
- _default = builtin;
1065
- }
1066
- //#endregion
1067
- //#region src/form/measurement.ts
1068
- /**
1069
- * Read measurement annotations off a single field prop. Returns `undefined`
1070
- * for any annotation that's absent — callers can spread the result into a
1071
- * larger record.
1072
- */
1073
- function extractMeasurement(prop) {
1074
- const precisionMeta = getFieldMeta(prop, DB_COLUMN_PRECISION);
1075
- return {
1076
- currencyCode: getFieldMeta(prop, DB_AMOUNT_CURRENCY),
1077
- currencyRefField: getFieldMeta(prop, DB_AMOUNT_CURRENCY_REF),
1078
- unitCode: getFieldMeta(prop, DB_UNIT),
1079
- unitRefField: getFieldMeta(prop, DB_UNIT_REF),
1080
- precisionScale: precisionMeta?.scale
1081
- };
1082
- }
1083
- //#endregion
1084
- //#region src/table/create-table-def.ts
1085
- /**
1086
- * Builds a TableDef from a moost-db MetaResponse.
1087
- *
1088
- * 1. Deserializes `meta.type` into a live TAtscriptAnnotatedType
1089
- * 2. Flattens to discover all field paths
1090
- * 3. Builds ColumnDef per field using annotations + meta.fields capabilities
1091
- * 4. Sorts by @ui.table.order
1092
- */
1093
- function createTableDef(meta, preDeserializedType) {
1094
- const type = preDeserializedType ?? deserializeAnnotatedType(meta.type);
1095
- const flatMap = type.type.kind === "object" ? flattenAnnotatedType(type, { excludePhantomTypes: true }) : /* @__PURE__ */ new Map();
1096
- const columns = [];
1097
- for (const [path, prop] of flatMap.entries()) {
1098
- if (path === "") continue;
1099
- if (path === meta.versionColumn) continue;
1100
- const fieldMeta = meta.fields[path];
1101
- if (!isReadable(fieldMeta)) continue;
1102
- if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
1103
- const options = extractFieldLiteralOptions(prop);
1104
- const valueHelpInfo = extractValueHelp(prop);
1105
- let distinct;
1106
- if (!valueHelpInfo && !options && fieldMeta.groupable && fieldMeta.filterable) {
1107
- const url = type.metadata.get(DB_HTTP_PATH);
1108
- if (url && getFieldMeta(prop, "ui.valueHelp.distinct") !== void 0) distinct = {
1109
- url,
1110
- field: path
1111
- };
1112
- }
1113
- columns.push(buildColumn(path, prop, fieldMeta, {
1114
- options,
1115
- valueHelpInfo,
1116
- distinct
1117
- }));
1118
- }
1119
- if (meta.decorations) {
1120
- const decoType = deserializeAnnotatedType(meta.decorations);
1121
- if (decoType.type.kind === "object") for (const [path, prop] of decoType.type.props) {
1122
- const fieldMeta = meta.fields[path];
1123
- if (!fieldMeta?.decoration || flatMap.has(path)) continue;
1124
- if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
1125
- flatMap.set(path, prop);
1126
- columns.push(buildColumn(path, prop, fieldMeta, { options: extractFieldLiteralOptions(prop) }));
1127
- }
1128
- }
1129
- columns.sort((a, b) => a.order - b.order);
1130
- const actions = groupActions(meta.actions ?? []);
1131
- const crud = meta.crud ?? {};
1132
- const preferredId = meta.preferredId ?? meta.primaryKeys;
1133
- return {
1134
- type,
1135
- columns,
1136
- flatMap,
1137
- fetchableFields: new Set(Object.keys(meta.fields).filter((p) => isReadable(meta.fields[p]))),
1138
- primaryKeys: meta.primaryKeys,
1139
- preferredId,
1140
- identifierFields: identifierFieldsOf(preferredId, meta.actions ?? []),
1141
- versionColumn: meta.versionColumn,
1142
- crud,
1143
- canRemove: "remove" in crud,
1144
- actions,
1145
- searchable: meta.searchable,
1146
- vectorSearchable: meta.vectorSearchable,
1147
- searchIndexes: meta.searchIndexes,
1148
- relations: meta.relations
1149
- };
1150
- }
1151
- /**
1152
- * One column. A server-declared display-only column (`fieldMeta.decoration`)
1153
- * is never sortable, filterable or groupable and always nullable (a decoration
1154
- * can be absent); an ordinary one takes its capabilities from `/meta`.
1155
- */
1156
- function buildColumn(path, prop, fieldMeta, resolved) {
1157
- const { options, valueHelpInfo, distinct } = resolved;
1158
- const maxLengthMeta = getFieldMeta(prop, EXPECT_MAX_LENGTH);
1159
- const tableType = getFieldMeta(prop, UI_TABLE_TYPE);
1160
- const sharedType = getFieldMeta(prop, UI_TYPE);
1161
- const tableComponent = getFieldMeta(prop, UI_TABLE_COMPONENT);
1162
- const decoration = fieldMeta.decoration === true;
1163
- const filterOps = decoration ? void 0 : fieldMeta.filterOps;
1164
- return {
1165
- path,
1166
- label: getFieldMeta(prop, "meta.label") ?? humanizePath(path),
1167
- type: tableType ?? sharedType ?? (valueHelpInfo ? "ref" : inferDisplayType(prop, options)),
1168
- valueKind: inferValueKind(prop),
1169
- component: tableComponent,
1170
- selectWith: getFieldMeta(prop, UI_TABLE_SELECT_WITH),
1171
- sortable: !decoration && (fieldMeta.sortable ?? false),
1172
- filterable: !decoration && (fieldMeta.filterable ?? false),
1173
- ...filterOps && { filterOps: [...filterOps] },
1174
- nullable: decoration || prop.optional === true,
1175
- width: getFieldMeta(prop, UI_TABLE_WIDTH),
1176
- maxLen: maxLengthMeta?.length,
1177
- order: getFieldMeta(prop, "ui.table.order") ?? Infinity,
1178
- options,
1179
- valueHelpInfo,
1180
- ...distinct && { distinct },
1181
- ...extractMeasurement(prop)
1182
- };
1183
- }
1184
- /**
1185
- * `preferredId` ∪ every delegated action's `idMap` paths, in that order —
1186
- * the same array when no action carries an `idMap`.
1187
- */
1188
- function identifierFieldsOf(preferredId, actions) {
1189
- let out;
1190
- for (const a of actions) {
1191
- if (!a.idMap) continue;
1192
- for (const path of Object.values(a.idMap)) {
1193
- if (preferredId.includes(path) || out?.includes(path)) continue;
1194
- (out ??= [...preferredId]).push(path);
1195
- }
1196
- }
1197
- return out ?? preferredId;
1198
- }
1199
- /** A field the caller may read: listed in `meta.fields` and not write-only. */
1200
- function isReadable(field) {
1201
- return field !== void 0 && field.writeOnly !== true;
1202
- }
1203
- /** Sort by (order ?? 0). `toSorted` is stable per spec, so ties preserve declaration order. */
1204
- function byOrder(xs) {
1205
- return xs.toSorted((x, y) => (x.order ?? 0) - (y.order ?? 0));
1206
- }
1207
- /**
1208
- * Partition actions by `level`, sort each group by `(order ?? 0)` then
1209
- * declaration order, and pick the first `default: true` entry per level.
1210
- * The synthesised `__remove` UI action lives outside this set and is never
1211
- * a candidate for `default.row`.
1212
- */
1213
- function groupActions(actions) {
1214
- const table = [];
1215
- const row = [];
1216
- const rows = [];
1217
- for (const a of actions) if (a.level === "table") table.push(a);
1218
- else if (a.level === "row") row.push(a);
1219
- else if (a.level === "rows") rows.push(a);
1220
- const tableSorted = byOrder(table);
1221
- const rowSorted = byOrder(row);
1222
- const rowsSorted = byOrder(rows);
1223
- return {
1224
- table: tableSorted,
1225
- row: rowSorted,
1226
- rows: rowsSorted,
1227
- default: {
1228
- table: tableSorted.find((a) => a.default === true),
1229
- row: rowSorted.find((a) => a.default === true),
1230
- rows: rowsSorted.find((a) => a.default === true)
1231
- }
1232
- };
1233
- }
1234
- /** Infers a display type string from the annotated type's kind and designType. */
1235
- function inferDisplayType(prop, literalOpts) {
1236
- const kind = prop.type.kind;
1237
- if (kind === "array") return "array";
1238
- if (kind === "object") return "object";
1239
- if (kind === "union") return literalOpts !== void 0 ? "enum" : "union";
1240
- if (kind === "") {
1241
- const final = prop.type;
1242
- const dt = final.designType;
1243
- if (dt === "number") return final.tags?.has("timestamp") ? "datetime" : "number";
1244
- if (dt === "decimal") return "number";
1245
- if (dt === "boolean") return "boolean";
1246
- return "text";
1247
- }
1248
- return "text";
1249
- }
1250
- /**
1251
- * Number metadata that makes the server treat a plain `number` column as an
1252
- * integer (mirrors the db layer's `valueTypeOf`), beside the `int` / `expect.int` tags.
1253
- */
1254
- const INTEGER_NUMBER_META = [
1255
- "expect.int",
1256
- "db.default.increment",
1257
- "db.default.now",
1258
- "db.agg.count",
1259
- "db.agg.countDistinct"
1260
- ];
1261
- /** The kind of one scalar leaf, or `undefined` for a non-scalar / unknown design type. */
1262
- function scalarValueKind(prop) {
1263
- const final = prop.type;
1264
- const tags = final.tags;
1265
- switch (final.designType) {
1266
- case "string": return tags?.has("isoDate") ? "isoDate" : tags?.has("date") ? "date" : "string";
1267
- case "number":
1268
- if (tags?.has("timestamp")) return "timestamp";
1269
- if (tags?.has("int") || INTEGER_NUMBER_META.some((k) => prop.metadata.has(k))) return "integer";
1270
- return "number";
1271
- case "decimal": return "decimal";
1272
- case "boolean": return "boolean";
1273
- default: return;
1274
- }
1275
- }
1276
- /** Kinds of every non-null leaf of a (possibly nested) union; `null` when one is not a scalar. */
1277
- function collectUnionKinds(items, out) {
1278
- for (const item of items) {
1279
- if (item.type.kind === "union") {
1280
- collectUnionKinds(item.type.items, out);
1281
- continue;
1282
- }
1283
- if (item.type.kind === "") {
1284
- const dt = item.type.designType;
1285
- if (dt === "null" || dt === "undefined") continue;
1286
- out.add(scalarValueKind(item));
1287
- continue;
1288
- }
1289
- out.add(void 0);
1290
- }
1291
- }
1292
- /**
1293
- * Scalar storage kind of the column's value — what the server's filter guard
1294
- * checks. A scalar maps to its kind; a union that agrees on one kind across
1295
- * its non-null members (`'a' | 'b'`, `1 | 2`, `number.timestamp | null`)
1296
- * takes it; arrays, objects, JSON and mixed unions have none (`undefined`),
1297
- * which means no value coercion.
1298
- */
1299
- function inferValueKind(prop) {
1300
- const kind = prop.type.kind;
1301
- if (kind === "") return scalarValueKind(prop);
1302
- if (kind !== "union") return void 0;
1303
- const kinds = /* @__PURE__ */ new Set();
1304
- collectUnionKinds(prop.type.items, kinds);
1305
- if (kinds.size !== 1) return void 0;
1306
- return [...kinds][0];
1307
- }
1308
- //#endregion
1309
- //#region src/shared/meta-cache.ts
1310
- /**
1311
- * Enough for every URL a page touches — a table, the dictionaries its
1312
- * filters and forms pick from — plus the recent navigation history, so going
1313
- * back is instant; small enough to cap a long session at a few MB of parsed
1314
- * `/meta`. Twice the `@atscript/db-client` `MetaStore` body limit, since
1315
- * parametric URLs share bodies.
1316
- */
1317
- const DEFAULT_MAX_ENTRIES = 100;
1318
- let maxEntries = DEFAULT_MAX_ENTRIES;
1319
- /** Per-URL entries, least recently used first. Browser only. */
1320
- const cache = /* @__PURE__ */ new Map();
1321
- const slots = /* @__PURE__ */ new WeakMap();
1322
- /** Derived shapes per `ETag`, counted by the cached entries that use them. Browser only. */
1323
- const derivedByEtag = /* @__PURE__ */ new Map();
1324
- /** Custom `/meta` stores of cached clients, counted by the entries that use them. */
1325
- const customStores = /* @__PURE__ */ new Map();
1326
- /** `undefined` until the first `setMetaCacheIdentity` call; `null` = anonymous. */
1327
- let identity;
1328
- const resetListeners = /* @__PURE__ */ new Set();
1329
- /**
1330
- * Get or create the cache entry for `url`. First caller's `factory` (and
1331
- * `options.metaKey`) seeds the `Client`; subsequent callers reuse it. On
1332
- * `meta` rejection, the entry is evicted so the next call retries. A hit
1333
- * marks the URL most recently used; hold an entry you keep using with
1334
- * {@link retainMetaEntry}. Without a browser `window` nothing is cached and
1335
- * the client is asked for `metaStore: false`.
1336
- */
1337
- function getMetaEntry(url, factory, options) {
1338
- const browser = typeof window !== "undefined";
1339
- const existing = browser ? cache.get(url) : void 0;
1340
- if (existing) {
1341
- touch(url, existing);
1342
- return existing;
1343
- }
1344
- const f = factory ?? getDefaultClientFactory();
1345
- let client;
1346
- if (!browser) client = f(url, { metaStore: false });
1347
- else if (options?.metaKey) client = f(url, { metaKey: options.metaKey });
1348
- else client = f(url);
1349
- const meta = client.meta().catch((err) => {
1350
- if (cache.get(url) === entry) evict(url, entry);
1351
- throw err;
1352
- });
1353
- const derived = meta.then((m) => derive(entry, client, m));
1354
- const type = derived.then((d) => d.type);
1355
- type.catch(() => {});
1356
- const entry = {
1357
- client,
1358
- meta,
1359
- type
1360
- };
1361
- const slot = {
1362
- url,
1363
- derived,
1364
- holds: 0
1365
- };
1366
- slots.set(entry, slot);
1367
- if (browser) {
1368
- slot.store = customStoreOf(client);
1369
- if (slot.store) customStores.set(slot.store, (customStores.get(slot.store) ?? 0) + 1);
1370
- cache.set(url, entry);
1371
- trim(entry);
1372
- }
1373
- return entry;
1374
- }
1375
- /**
1376
- * Keep `entry` in the cache while it is in use: a held entry is never
1377
- * evicted by the size limit ({@link setMetaCacheMaxEntries}), so later
1378
- * `getMetaEntry` / `resolveValueHelp` calls for its URL keep returning it.
1379
- * Call the returned function (idempotent) once done — `useTable` and the
1380
- * form value-help do this for their component's lifetime. A reset still
1381
- * drops held entries. Since 0.1.154.
1382
- */
1383
- function retainMetaEntry(entry) {
1384
- const slot = slots.get(entry);
1385
- if (!slot) return () => {};
1386
- slot.holds++;
1387
- let released = false;
1388
- return () => {
1389
- if (released) return;
1390
- released = true;
1391
- slot.holds--;
1392
- if (slot.holds === 0 && cache.get(slot.url) === entry) {
1393
- touch(slot.url, entry);
1394
- trim();
1395
- }
1396
- };
1397
- }
1398
- /**
1399
- * How many URLs the meta cache keeps (default `100`). Least recently used
1400
- * entries beyond it are dropped — entries held with {@link retainMetaEntry}
1401
- * (every mounted table and form value-help) never are, and may exceed it.
1402
- * At least `1`; `Infinity` turns the limit off; no argument restores the
1403
- * default. Since 0.1.154.
1404
- */
1405
- function setMetaCacheMaxEntries(max) {
1406
- maxEntries = max === void 0 ? DEFAULT_MAX_ENTRIES : max >= 1 ? max : 1;
1407
- trim();
1408
- }
1409
- function touch(url, entry) {
1410
- cache.delete(url);
1411
- cache.set(url, entry);
1412
- }
1413
- /**
1414
- * Drop least recently used entries nothing holds until the cache fits.
1415
- * `spare` — the entry just handed out, about to be retained by its caller.
1416
- */
1417
- function trim(spare) {
1418
- if (cache.size <= maxEntries) return;
1419
- for (const [url, entry] of cache) {
1420
- if (entry !== spare && slots.get(entry).holds === 0) evict(url, entry);
1421
- if (cache.size <= maxEntries) return;
1422
- }
1423
- }
1424
- /**
1425
- * Remove `entry` and release what only it kept: its shared `Derived` and
1426
- * custom store. A reset no longer reaches its client, so the client's memoized
1427
- * `/meta` goes now — a factory that reuses clients per URL would otherwise
1428
- * hand it to the next viewer.
1429
- */
1430
- function evict(url, entry) {
1431
- cache.delete(url);
1432
- entry.client.invalidateMeta?.();
1433
- const slot = slots.get(entry);
1434
- if (slot.etag !== void 0 && --derivedByEtag.get(slot.etag).refs === 0) derivedByEtag.delete(slot.etag);
1435
- if (slot.store) {
1436
- const refs = customStores.get(slot.store);
1437
- if (refs > 1) customStores.set(slot.store, refs - 1);
1438
- else {
1439
- slot.store.clear();
1440
- customStores.delete(slot.store);
1441
- }
1442
- }
1443
- }
1444
- /**
1445
- * The `TableDef` for a cache entry, built once per entry — and once per
1446
- * `/meta` `ETag` across entries. Since 0.1.153.
1447
- */
1448
- function getMetaTableDef(entry) {
1449
- if (!entry.tableDef) {
1450
- const derived = slots.get(entry)?.derived;
1451
- entry.tableDef = derived ? Promise.all([entry.meta, derived]).then(([meta, d]) => d.tableDef ??= createTableDef(meta, d.type)) : Promise.all([entry.meta, entry.type]).then(([meta, type]) => createTableDef(meta, type));
1452
- }
1453
- return entry.tableDef;
1454
- }
1455
- /**
1456
- * Shares the `Derived` of one `ETag` among the cached entries that loaded it;
1457
- * an entry no longer cached (evicted, reset, server render) keeps its own.
1458
- */
1459
- function derive(entry, client, meta) {
1460
- const slot = slots.get(entry);
1461
- const etag = cache.get(slot.url) === entry ? client.metaEtag?.() : void 0;
1462
- if (etag === void 0) return { type: deserializeAnnotatedType(meta.type) };
1463
- let shared = derivedByEtag.get(etag);
1464
- if (shared) shared.refs++;
1465
- else {
1466
- shared = {
1467
- derived: { type: deserializeAnnotatedType(meta.type) },
1468
- refs: 1
1469
- };
1470
- derivedByEtag.set(etag, shared);
1471
- }
1472
- slot.etag = etag;
1473
- return shared.derived;
1474
- }
1475
- /**
1476
- * The custom `/meta` store a factory gave `client`, so a reset (and the
1477
- * eviction of its last cached client) can clear it. The shared
1478
- * `defaultMetaStore` is skipped: a reset clears it through
1479
- * `clearMetaStore()`, and an eviction must not drop the ETags of every
1480
- * other URL. A store-less client (`metaStore: false`) is skipped too.
1481
- */
1482
- function customStoreOf(client) {
1483
- const store = client.metaStore;
1484
- return store && store !== defaultMetaStore ? store : void 0;
1485
- }
1486
- /**
1487
- * Drop every cached `/meta` — including the copy each cached `Client`
1488
- * memoizes and the `@atscript/db-client` meta stores used to revalidate it
1489
- * (the shared default one and any custom one a factory supplied) — the
1490
- * value-help searches shared under them, and everything registered through
1491
- * {@link onMetaCacheReset} (e.g. the table-presets cache). Entries already
1492
- * handed out keep working; the next `getMetaEntry` refetches.
1493
- */
1494
- function resetMetaCache() {
1495
- const entries = [...cache.values()];
1496
- cache.clear();
1497
- derivedByEtag.clear();
1498
- for (const entry of entries) entry.client.invalidateMeta?.();
1499
- clearMetaStore();
1500
- for (const store of customStores.keys()) store.clear();
1501
- customStores.clear();
1502
- invalidateValueHelpCache();
1503
- for (const listener of resetListeners) listener();
1504
- }
1505
- /**
1506
- * Bind the meta cache to the current viewer. Call it whenever the signed-in
1507
- * user or their role may have changed — after login, after logout and on
1508
- * every reload of the current user. A key that differs from the previous
1509
- * one resets the cache (`resetMetaCache`); the same key keeps it. `null` /
1510
- * `undefined` = anonymous.
1511
- *
1512
- * Binding an identity also turns on caches that are only safe when the app
1513
- * reports sign-in changes, such as the table-presets cache.
1514
- */
1515
- function setMetaCacheIdentity(key) {
1516
- const next = key ?? null;
1517
- if (next === identity) return;
1518
- identity = next;
1519
- resetMetaCache();
1520
- }
1521
- /**
1522
- * The identity last passed to {@link setMetaCacheIdentity}: `undefined` when
1523
- * the app never bound one, `null` for anonymous. Since 0.1.153.
1524
- */
1525
- function getMetaCacheIdentity() {
1526
- return identity;
1527
- }
1528
- /**
1529
- * Run `listener` on every {@link resetMetaCache} (and so on every identity
1530
- * change). For caches that belong to the signed-in viewer. Returns an
1531
- * unsubscribe function. Since 0.1.153.
1532
- */
1533
- function onMetaCacheReset(listener) {
1534
- resetListeners.add(listener);
1535
- return () => {
1536
- resetListeners.delete(listener);
1537
- };
1538
- }
1539
- //#endregion
1540
- //#region src/value-help/resolve.ts
1541
- /**
1542
- * Lazily fetch and extract value-help metadata for the given URL.
1543
- *
1544
- * - Issues exactly one `GET {url}/meta` per URL across the session (shared via meta-cache).
1545
- * - Concurrent callers with the same URL share the in-flight promise.
1546
- * - If the underlying fetch rejects, the cache entry is evicted so a later
1547
- * retry performs a fresh fetch.
1548
- */
1549
- function resolveValueHelp(url) {
1550
- const entry = getMetaEntry(url);
1551
- if (entry.resolved) return entry.resolved;
1552
- entry.resolved = Promise.all([entry.meta, entry.type]).then(([meta, type]) => buildResolved(url, meta, type));
1553
- return entry.resolved;
1554
- }
1555
- /** Thin alias over `resetMetaCache` — retained so existing test code keeps working. */
1556
- function resetValueHelpCache() {
1557
- resetMetaCache();
1558
- }
1559
- function buildResolved(url, meta, targetType) {
1560
- const objectType = targetType.type.kind === "object" ? targetType.type : void 0;
1561
- const versionColumn = meta.versionColumn;
1562
- const primaryKeys = [];
1563
- let labelField;
1564
- let descrField;
1565
- const attrFields = [];
1566
- let firstStringField;
1567
- if (objectType) for (const [name, fieldProp] of objectType.props) {
1568
- if (name === versionColumn) continue;
1569
- const isPK = fieldProp.metadata.has(META_ID);
1570
- if (isPK) primaryKeys.push(name);
1571
- if (fieldProp.metadata.has("ui.dict.label")) labelField = name;
1572
- if (fieldProp.metadata.has("ui.dict.descr")) descrField = name;
1573
- if (fieldProp.metadata.has("ui.dict.attr")) attrFields.push(name);
1574
- if (!firstStringField && !isPK && fieldProp.type.kind === "" && fieldProp.type.designType === "string") firstStringField = name;
1575
- }
1576
- if (!labelField) labelField = firstStringField;
1577
- if (!labelField) labelField = primaryKeys[0] ?? "id";
1578
- const filterableFields = [];
1579
- const sortableFields = [];
1580
- if (meta.fields) for (const [name, fm] of Object.entries(meta.fields)) {
1581
- if (name === versionColumn) continue;
1582
- if (fm?.filterable) filterableFields.push(name);
1583
- if (fm?.sortable) sortableFields.push(name);
1584
- }
1585
- return {
1586
- url,
1587
- primaryKeys,
1588
- labelField,
1589
- descrField,
1590
- attrFields,
1591
- filterableFields,
1592
- sortableFields,
1593
- searchable: !!meta.searchable,
1594
- targetType
1595
- };
1596
- }
1597
- //#endregion
1598
- //#region src/form/path-utils.ts
1599
- /**
1600
- * Joins a dot-separated path prefix with a segment. Empty-safe on both
1601
- * sides: an empty segment returns the prefix as-is, an empty prefix
1602
- * returns the segment as-is (no leading/trailing dots).
1603
- */
1604
- function joinPath(prefix, segment) {
1605
- if (!segment) return prefix;
1606
- return prefix ? `${prefix}.${segment}` : segment;
1607
- }
1608
- /**
1609
- * Gets a nested value by dot-separated path.
1610
- * Always dereferences `obj.value` first (form data is wrapped in `{ value: domainData }`).
1611
- * When `path` is empty, returns the root domain data (`obj.value`).
1612
- */
1613
- function getByPath(obj, path) {
1614
- const root = obj.value;
1615
- if (!path) return root;
1616
- const keys = path.split(".");
1617
- let current = root;
1618
- for (const key of keys) {
1619
- if (current === null || current === void 0 || typeof current !== "object") return void 0;
1620
- current = current[key];
1621
- }
1622
- return current;
1623
- }
1624
- /**
1625
- * Sets a nested value by dot-separated path.
1626
- * Always dereferences `obj.value` first (form data is wrapped in `{ value: domainData }`).
1627
- * When `path` is empty, sets the root domain data (`obj.value = value`).
1628
- * Creates intermediate objects if they do not exist.
1629
- */
1630
- function setByPath(obj, path, value) {
1631
- if (!path) {
1632
- obj.value = value;
1633
- return;
1634
- }
1635
- const keys = path.split(".");
1636
- const last = keys.pop();
1637
- if (last === void 0) return;
1638
- let current = obj.value;
1639
- for (const key of keys) {
1640
- if (current[key] === null || current[key] === void 0 || typeof current[key] !== "object") current[key] = {};
1641
- current = current[key];
1642
- }
1643
- current[last] = value;
1644
- }
1645
- /**
1646
- * Deletes the own key at a dot-separated path (form-data wrapper aware — derefs
1647
- * `obj.value` first). Walks to the parent WITHOUT vivifying intermediate nodes:
1648
- * if any ancestor is missing, the call is a no-op (nothing to delete).
1649
- *
1650
- * Unlike `setByPath(obj, path, undefined)`, this leaves NO own key behind — the
1651
- * leaf reads as absent (`'k' in parent === false`), which keeps `deepEqual`
1652
- * structural comparisons in sync (a present `undefined` own-key and an absent
1653
- * key are NOT structurally equal under the own-key walk). Used by
1654
- * {@link applyFormChanges} to apply a clear-to-`undefined` change as a delete.
1655
- *
1656
- * Empty path clears the root domain value (`obj.value = undefined`).
1657
- */
1658
- function deleteByPath(obj, path) {
1659
- if (!path) {
1660
- obj.value = void 0;
1661
- return;
1662
- }
1663
- const keys = path.split(".");
1664
- const last = keys.pop();
1665
- if (last === void 0) return;
1666
- let current = obj.value;
1667
- for (const key of keys) {
1668
- if (current === null || current === void 0 || typeof current !== "object") return;
1669
- current = current[key];
1670
- }
1671
- if (current === null || current === void 0 || typeof current !== "object") return;
1672
- delete current[last];
1673
- }
1674
- function parseStaticDefault(raw, prop) {
1675
- if (typeof raw !== "string") return raw;
1676
- if (prop.type.kind === "" && prop.type.designType === "string") return raw;
1677
- try {
1678
- return JSON.parse(raw);
1679
- } catch {
1680
- return;
1681
- }
1682
- }
1683
- /** Cached default resolver — reused when no resolver is provided. */
1684
- const defaultValueResolver = createFormValueResolver();
1685
- function createFormValueResolver(data = {}, context = {}) {
1686
- return (prop, _path) => {
1687
- return resolveFieldProp(prop, UI_FORM_FN_VALUE, META_DEFAULT, {
1688
- v: void 0,
1689
- data,
1690
- context,
1691
- entry: void 0
1692
- }, { transform: (raw) => parseStaticDefault(raw, prop) });
1693
- };
1694
- }
1695
- /**
1696
- * Type-appropriate "defined-but-empty" fallback for primitive design types
1697
- * whose structural default in atscript's `finalDefault` table is
1698
- * `undefined`. Without this, `createFormData` on an optional `decimal`
1699
- * field (or any other primitive missed by atscript's table) returns
1700
- * `undefined` — but `createFormData` is called from "explicit add"
1701
- * contexts (optional-toggle, array-add, tuple-pad, union-pick) where the
1702
- * caller's intent is "give me a value the renderer can edit", not "no
1703
- * value yet". Returning `undefined` leaves the empty-state placeholder
1704
- * stuck in AsFieldShell.
1705
- *
1706
- * `decimal → "0"` mirrors the `number → 0` default — the atscript runtime
1707
- * validator (≥ 0.1.54) rejects `""` for decimal fields, so committing the
1708
- * canonical zero is the only init that survives a submit-without-edit.
1709
- * `useAsDecimal` pads the display to the field's effective scale, so the
1710
- * user sees `0.00` / `0.000` per the `@db.column.precision` annotation.
1711
- */
1712
- function primitiveInitFallback(prop) {
1713
- if (prop.type.kind !== "") return void 0;
1714
- switch (prop.type.designType) {
1715
- case "decimal": return "0";
1716
- default: return;
1717
- }
1718
- }
1719
- function createFormData(type, resolver) {
1720
- let value = createDataFromAnnotatedType(type, { mode: resolver ?? defaultValueResolver });
1721
- if (value === void 0) value = primitiveInitFallback(type);
1722
- return { value };
1723
- }
1724
- const variantValidatorCache = /* @__PURE__ */ new WeakMap();
1725
- function getVariantValidator(variant) {
1726
- let v = variantValidatorCache.get(variant.type);
1727
- if (!v) {
1728
- v = variant.type.validator();
1729
- variantValidatorCache.set(variant.type, v);
1730
- }
1731
- return v;
1732
- }
1733
- const variantsDiscriminatorCache = /* @__PURE__ */ new WeakMap();
1734
- function getVariantsDiscriminator(variants) {
1735
- let cached = variantsDiscriminatorCache.get(variants);
1736
- if (cached === void 0) {
1737
- cached = detectDiscriminator(variants.map((v) => v.type));
1738
- variantsDiscriminatorCache.set(variants, cached);
1739
- }
1740
- return cached;
1741
- }
1742
- function detectUnionVariant(value, variants) {
1743
- if (variants.length <= 1) return 0;
1744
- const disc = getVariantsDiscriminator(variants);
1745
- if (disc && value !== null && typeof value === "object") {
1746
- const tag = value[disc.propertyName];
1747
- const key = String(tag);
1748
- if (Object.prototype.hasOwnProperty.call(disc.indexMapping, key)) {
1749
- const idx = disc.indexMapping[key];
1750
- if (idx !== void 0) return idx;
1751
- }
1752
- }
1753
- for (let i = 0; i < variants.length; i++) try {
1754
- if (getVariantValidator(variants[i]).validate(value, true)) return i;
1755
- } catch {}
1756
- return 0;
1757
- }
1758
- //#endregion
1759
- //#region src/form/clone.ts
1760
- /**
1761
- * Structural deep clone of plain JSON-ish data (objects / arrays / primitives /
1762
- * `Date`). Walks OWN-ENUMERABLE keys only (matches the own-key discipline in
1763
- * `diff.ts` — never copies an accidental prototype) and copies leaves by value.
1764
- *
1765
- * `structuredClone` is deliberately NOT used: it throws on functions and on Vue
1766
- * reactive proxies. The optional `unwrap` hook lets a framework caller
1767
- * de-proxy each value first (vue-form passes `toRaw`); the core omits it.
1768
- *
1769
- * The SINGLE deep-clone primitive for the form engine — used by
1770
- * `applyFormChanges`, `buildFormRebase`, and vue-form's baseline snapshot. Do
1771
- * not reimplement structural cloning elsewhere.
1772
- */
1773
- function deepClone(value, unwrap) {
1774
- const v = unwrap ? unwrap(value) : value;
1775
- if (v === null || typeof v !== "object") return v;
1776
- if (v instanceof Date) return new Date(v.getTime());
1777
- if (Array.isArray(v)) {
1778
- const out = [];
1779
- for (let i = 0; i < v.length; i++) out.push(deepClone(v[i], unwrap));
1780
- return out;
1781
- }
1782
- const src = v;
1783
- const out = {};
1784
- for (const k of Object.keys(src)) out[k] = deepClone(src[k], unwrap);
1785
- return out;
1786
- }
1787
- //#endregion
1788
- //#region src/form/error-utils.ts
1789
- /**
1790
- * Framework-agnostic helpers for working with form-error maps keyed by
1791
- * dotted path. Used by AsForm to drive error badges and auto-open
1792
- * collapsed sections; safe to share with React (or any other) bindings.
1793
- *
1794
- * Convention:
1795
- * - Keys are dotted paths (`a.b.c`); empty string and `__form` denote
1796
- * the form-level error.
1797
- * - Values may be `string | undefined`; falsy entries are dropped on
1798
- * merge.
1799
- */
1800
- /** Error-map key of the form-level error. */
1801
- const FORM_ERROR_KEY = "__form";
1802
- /**
1803
- * Turn a validator's error list into an error map keyed by path. A
1804
- * root-level error (empty path) becomes the form-level error
1805
- * ({@link FORM_ERROR_KEY}). The first error per path wins: a failing
1806
- * container rule is reported before the container's own shape / length
1807
- * checks at the same path.
1808
- */
1809
- function validatorErrorsToMap(errors) {
1810
- const out = {};
1811
- for (const err of errors) out[err.path || "__form"] ??= err.message;
1812
- return out;
1813
- }
1814
- /**
1815
- * Merge any number of partial error maps into a single dense
1816
- * `Record<path, message>`. Falsy values are skipped — later sources do
1817
- * NOT overwrite earlier ones with an empty value.
1818
- */
1819
- function mergeErrorMaps(...maps) {
1820
- const merged = {};
1821
- for (const m of maps) {
1822
- if (!m) continue;
1823
- for (const k of Object.keys(m)) {
1824
- const v = m[k];
1825
- if (v) merged[k] = v;
1826
- }
1827
- }
1828
- return merged;
1829
- }
1830
- /**
1831
- * Return `errors` without the entries whose key is in `paths`.
1832
- *
1833
- * Identity-preserving: when no key matches, the ORIGINAL `errors` object
1834
- * is returned unchanged — callers compare `result !== errors` to detect
1835
- * that something was pruned and skip spurious reactive writes.
1836
- */
1837
- function omitPaths(errors, paths) {
1838
- let pruned = null;
1839
- for (const key in errors) if (paths.has(key)) {
1840
- pruned ??= { ...errors };
1841
- delete pruned[key];
1842
- }
1843
- return pruned ?? errors;
1844
- }
1845
- /**
1846
- * Yield every ancestor prefix of a dotted path, longest-first
1847
- * (`a.b.c` → `a.b.c`, `a.b`, `a`). Returns the path itself first so
1848
- * callers can include it in the iteration without a special case.
1849
- *
1850
- * Empty paths and the form-level key (`__form`) yield nothing.
1851
- */
1852
- function* iteratePathAncestors(path) {
1853
- if (!path || path === "__form") return;
1854
- let pos = path.length;
1855
- while (pos > 0) {
1856
- yield path.slice(0, pos);
1857
- const dot = path.lastIndexOf(".", pos - 1);
1858
- if (dot < 0) return;
1859
- pos = dot;
1860
- }
1861
- }
1862
- /**
1863
- * Build an indexed `Map<absolutePath, descendantErrorCount>` so each
1864
- * struct in the tree can render an error-count badge in O(1).
1865
- *
1866
- * For every error path, the count is incremented on the path itself
1867
- * AND every dotted-path ancestor — so a struct at `a.b` reports the
1868
- * total of all errors at `a.b` or below.
1869
- */
1870
- function buildDescendantErrorCounts(errors) {
1871
- const map = /* @__PURE__ */ new Map();
1872
- for (const errPath of Object.keys(errors)) {
1873
- if (!errors[errPath]) continue;
1874
- for (const prefix of iteratePathAncestors(errPath)) map.set(prefix, (map.get(prefix) ?? 0) + 1);
1875
- }
1876
- return map;
1877
- }
1878
- //#endregion
1879
- //#region src/form/validate.ts
1880
- const dbPlugin = createDbValidatorPlugin();
1881
- const INSERT_CONTEXT = { mode: "insert" };
1882
- /**
1883
- * Always-on plugin for fields the server fills in, so a create form is not
1884
- * blocked on them:
1885
- * - `@db.column.derived` — read-only and server-computed: never validated
1886
- * (not even a loaded value, which the user could not fix).
1887
- * - an absent `@db.default*` / `@db.column.version` / `@db.onUpdate.inc` value
1888
- * — delegated to `@atscript/db`'s own insert-mode rule, so the key list has
1889
- * one owner.
1890
- * `db.rel.FK` is kept out: a form fills the FK itself (no nested nav
1891
- * object), so an empty required FK must still fail.
1892
- *
1893
- * The db plugin reads its mode from the validation context, which here
1894
- * carries the form's `{ data, context }` — it gets a view of `ctx` with the
1895
- * insert context instead.
1896
- */
1897
- const serverManagedPlugin = (ctx, def, value) => {
1898
- if (def.metadata.has("db.column.derived")) return true;
1899
- if (value !== void 0 || def.metadata.has("db.rel.FK")) return void 0;
1900
- return dbPlugin(Object.create(ctx, { context: { value: INSERT_CONTEXT } }), def, value);
1901
- };
1902
- /**
1903
- * The props of the fields `createFormDef` marked `derived`, at any depth — a
1904
- * computed view column (`metaFields`) or an edit form's update-stamped field
1905
- * (see `CreateFormDefOptions.mode`) carries no annotation the plugin above
1906
- * could read. The validator matches by prop, so a prop that is also used where
1907
- * it is not derived (an interface's stamp below a union of several types, too)
1908
- * stays validated.
1909
- */
1910
- function collectDerivedProps(def) {
1911
- const derived = /* @__PURE__ */ new Set();
1912
- const kept = /* @__PURE__ */ new Set();
1913
- const walk = (fields) => {
1914
- for (const field of fields) {
1915
- if (field.derived) {
1916
- derived.add(field.prop);
1917
- continue;
1918
- }
1919
- kept.add(field.prop);
1920
- if (isObjectField(field)) walk(field.objectDef.fields);
1921
- else if (isArrayField(field)) walk([field.itemField]);
1922
- else if (isTupleField(field)) walk(field.itemFields);
1923
- else if (isUnionField(field)) for (const v of field.unionVariants) {
1924
- if (v.def) walk(v.def.fields);
1925
- if (v.itemField) walk([v.itemField]);
1926
- }
1927
- }
1928
- };
1929
- walk(def.fields);
1930
- for (const prop of kept) derived.delete(prop);
1931
- return derived;
1932
- }
1933
- let defaultValidatorPlugins = [];
1934
- /** Replace the default validator plugins applied to every form/field validator. */
1935
- function setDefaultValidatorPlugins(plugins) {
1936
- defaultValidatorPlugins = plugins;
1937
- }
1938
- /** Get the currently registered default validator plugins. */
1939
- function getDefaultValidatorPlugins() {
1940
- return defaultValidatorPlugins;
1941
- }
1942
- /**
1943
- * Returns a reusable validator function for a whole FormDef.
1944
- *
1945
- * Validator is created once and reused on every call.
1946
- * ATScript's @expect.* validation runs automatically; server-managed db
1947
- * fields (every `derived` field, absent `@db.default*` / version) pass.
1948
- * For custom `ui.fn.*` validators, install ui-fns and pass its plugin via `opts.plugins`.
1949
- *
1950
- * Errors are keyed by dotted path. A root-level error (a failing
1951
- * `@ui.form.validate` on the form's interface) is keyed `__form`.
1952
- */
1953
- function getFormValidator(def, opts) {
1954
- const derived = collectDerivedProps(def);
1955
- const derivedPlugin = (_ctx, prop) => derived.has(prop) ? true : void 0;
1956
- const validator = new Validator(def.type, {
1957
- unknownProps: "ignore",
1958
- ...opts,
1959
- plugins: [
1960
- ...derived.size > 0 ? [derivedPlugin] : [],
1961
- serverManagedPlugin,
1962
- ...defaultValidatorPlugins,
1963
- ...opts?.plugins ?? []
1964
- ]
1965
- });
1966
- return (callOpts) => {
1967
- if (validator.validate(callOpts.data, true, {
1968
- data: callOpts.data,
1969
- context: callOpts.context ?? {}
1970
- })) return {};
1971
- return validatorErrorsToMap(validator.errors);
1972
- };
1973
- }
1974
- /**
1975
- * Root-only plugin: passes every descendant without visiting it. Only
1976
- * `object` / `array` / `tuple` roots use it — their root-path errors (shape,
1977
- * length, a container-level `@ui.form.validate`) are all decided before the
1978
- * walk descends, so skipping the children cannot change the root error. A
1979
- * union or intersection root evaluates its branches AT the root path, where
1980
- * a branch's verdict depends on its children — those keep the full walk.
1981
- */
1982
- const skipDescendantsPlugin = (ctx) => ctx.path === "" ? void 0 : true;
1983
- /**
1984
- * Whether a type kind is a container that carries its own children:
1985
- * `object`, `array` or `tuple`. Union / intersection kinds are not
1986
- * containers — they evaluate their branches at their own path.
1987
- */
1988
- function isContainerKind(kind) {
1989
- return kind === "object" || kind === "array" || kind === "tuple";
1990
- }
1991
- /**
1992
- * Creates a cached validator function for a single ATScript prop.
1993
- *
1994
- * The `Validator` instance is created lazily on first call and reused.
1995
- * Returns `true` when valid, or the first error message string when invalid.
1996
- * With `rootOnly`, an object / array / tuple prop is validated at its root
1997
- * only (descendants are not walked — their errors would be discarded anyway).
1998
- */
1999
- function createFieldValidator(prop, opts) {
2000
- let cached;
2001
- return (value, externalCtx) => {
2002
- cached ??= new Validator(prop, { plugins: opts?.rootOnly && isContainerKind(prop.type.kind) ? [
2003
- skipDescendantsPlugin,
2004
- serverManagedPlugin,
2005
- ...defaultValidatorPlugins
2006
- ] : [serverManagedPlugin, ...defaultValidatorPlugins] });
2007
- if (!cached.validate(value, true, externalCtx)) {
2008
- if (opts?.rootOnly) {
2009
- const rootError = cached.errors?.find((e) => e.path === "");
2010
- if (rootError) return rootError.message;
2011
- return true;
2012
- }
2013
- return cached.errors?.[0]?.message || "Invalid value";
2014
- }
2015
- return true;
2016
- };
2017
- }
2018
- //#endregion
2019
- //#region src/form/diff.ts
2020
- /**
2021
- * Diffs a form's `current` data against its `baseline` snapshot, producing both
2022
- * a changed-fields list and an `@atscript/db` patch object.
2023
- *
2024
- * Both `baseline` and `current` are the WRAPPED form-data container
2025
- * (`{ value: domainData }`) so this reuses {@link getByPath}.
2026
- *
2027
- * Revert-aware: a value edited back to its baseline produces no change and no
2028
- * patch entry.
2029
- *
2030
- * Snapshot contract: the result is NOT a deep copy. `$insert` items, `$replace`
2031
- * arrays, scalar leaf values, and `changes[].before/after` all hold live
2032
- * references into `baseline` / `current`. Callers that keep editing the form
2033
- * after building the patch must snapshot first (e.g. build the patch at submit
2034
- * time on a frozen clone). This is the common Vue v-model flow.
2035
- */
2036
- function buildFormDiff(def, baseline, current, opts) {
2037
- const changes = [];
2038
- const patch = {};
2039
- const versionColumn = findVersionColumn(def);
2040
- diffFields(def.fields, "", baseline, current, changes, patch, versionColumn, def.flatMap);
2041
- if ((opts?.cas ?? true) && versionColumn && Object.keys(patch).length > 0) {
2042
- const baselineVersion = getByPath(baseline, versionColumn);
2043
- if (typeof baselineVersion === "number" && Number.isInteger(baselineVersion)) patch.$cas = { [versionColumn]: baselineVersion };
2044
- }
2045
- return {
2046
- isDirty: changes.length > 0,
2047
- changes,
2048
- patch
2049
- };
2050
- }
2051
- /**
2052
- * Diffs a list of sibling fields. `prefix` is the dot-path of the parent
2053
- * context relative to the form root (used only for the change list `path`);
2054
- * patch entries are written into the local `patch` object so callers can place
2055
- * the whole sub-object as a nested partial.
2056
- *
2057
- * `versionColumn` is the top-level `@db.column.version` field name (or
2058
- * undefined). When set, the matching top-level field is skipped entirely — it
2059
- * is server-managed and may only be round-tripped via `$cas`.
2060
- *
2061
- * `inlineFlatMap` is the form's `flatMap`, supplied only at the top-level walk.
2062
- * It lets {@link diffScalarField} read `@db.patch.strategy` off the object
2063
- * ancestors of an INLINED leaf (a dotted-path leaf with no `FormObjectFieldDef`
2064
- * node — `createFormDef` dissolves unlabelled objects into dot-paths). At a
2065
- * default (replace) ancestor the whole sub-object must be emitted. It is
2066
- * intentionally NOT propagated into `diffObjectField` recursion, where the
2067
- * strategy decision is already made per structured object.
2068
- */
2069
- function diffFields(fields, prefix, baseline, current, changes, patch, versionColumn, inlineFlatMap) {
2070
- for (const field of fields) {
2071
- if (field.path === "" && fields.length === 1) {
2072
- diffLeafRoot(field, baseline, current, changes, patch);
2073
- continue;
2074
- }
2075
- if (field.phantom || field.derived || versionColumn !== void 0 && !prefix && field.path === versionColumn) continue;
2076
- const fullPath = prefix ? `${prefix}.${field.path}` : field.path;
2077
- if (isArrayField(field)) {
2078
- diffArrayField(field, fullPath, baseline, current, changes, patch);
2079
- continue;
2080
- }
2081
- if (isObjectField(field)) {
2082
- diffObjectField(field, fullPath, baseline, current, changes, patch);
2083
- continue;
2084
- }
2085
- diffScalarField(field, fullPath, baseline, current, changes, patch, inlineFlatMap);
2086
- }
2087
- }
2088
- /** Single-leaf root form (non-object root). Whole value is the patch. */
2089
- function diffLeafRoot(field, baseline, current, changes, patch) {
2090
- const before = getByPath(baseline, "");
2091
- const after = getByPath(current, "");
2092
- if (deepEqual(before, after)) return;
2093
- if (isArrayField(field)) {
2094
- const arrayPatch = diffArray(field, before, after);
2095
- if (arrayPatch === void 0) return;
2096
- changes.push({
2097
- path: "",
2098
- kind: "array",
2099
- before,
2100
- after
2101
- });
2102
- patch.value = arrayPatch;
2103
- } else {
2104
- changes.push({
2105
- path: "",
2106
- kind: "set",
2107
- before,
2108
- after
2109
- });
2110
- patch.value = after === void 0 ? null : after;
2111
- }
2112
- }
2113
- /** Scalar / union / tuple / ref field — whole-value compare; clear → null. */
2114
- function diffScalarField(field, fullPath, baseline, current, changes, patch, inlineFlatMap) {
2115
- const before = getByPath(baseline, fullPath);
2116
- const after = getByPath(current, fullPath);
2117
- if (deepEqual(before, after)) return;
2118
- changes.push({
2119
- path: fullPath,
2120
- kind: "set",
2121
- before,
2122
- after
2123
- });
2124
- if (inlineFlatMap && field.path.includes(".")) {
2125
- const cutoff = inlinedReplaceCutoff(field.path, inlineFlatMap);
2126
- if (cutoff !== void 0) {
2127
- const prefixLen = fullPath.length - field.path.length;
2128
- const sub = getByPath(current, prefixLen > 0 ? fullPath.slice(0, prefixLen) + cutoff : cutoff);
2129
- setPatchLeaf(patch, cutoff, sub === void 0 ? null : sub);
2130
- return;
2131
- }
2132
- }
2133
- setPatchLeaf(patch, field.path, after === void 0 ? null : after);
2134
- }
2135
- /**
2136
- * For a dotted INLINED leaf path, returns the path of the shallowest object
2137
- * ancestor whose `@db.patch.strategy` is the default (`replace`), or undefined
2138
- * when every ancestor is `merge` (then the leaf partial is correct). At a
2139
- * replace ancestor the whole sub-object must be present in the patch.
2140
- *
2141
- * Walks ancestor segments (`a`, `a.b`, … but not the leaf itself); the first
2142
- * one that is an object AND not merge is the cutoff. merge does NOT propagate,
2143
- * so a default-replace level below a merge level still cuts off there.
2144
- */
2145
- function inlinedReplaceCutoff(leafPath, flatMap) {
2146
- const segs = leafPath.split(".");
2147
- let acc = "";
2148
- for (let i = 0; i < segs.length - 1; i++) {
2149
- acc = acc ? `${acc}.${segs[i]}` : segs[i];
2150
- const prop = flatMap.get(acc);
2151
- if (!prop || prop.type.kind !== "object") continue;
2152
- if (getFieldMeta(prop, "db.patch.strategy") !== "merge") return acc;
2153
- }
2154
- }
2155
- /**
2156
- * Inlined-or-structured object field — recurse, emit a nested partial OR the
2157
- * whole sub-object depending on the field's `@db.patch.strategy`.
2158
- *
2159
- * atscript-db's DEFAULT nested-object patch strategy is `replace` (strict —
2160
- * every required child must be present, else 400; omitted optionals are
2161
- * null-filled). A changed-leaves-only partial is a valid patch ONLY when the
2162
- * object field carries `@db.patch.strategy 'merge'`. For the default (replace)
2163
- * case we therefore emit the WHOLE current sub-object so the validator passes
2164
- * and no optional leaf is silently nulled. `merge` does NOT propagate, so a
2165
- * descendant object without its own `merge` again emits its full sub-object
2166
- * (handled by recursion — `diffFields` re-enters this function per child).
2167
- *
2168
- * Wholesale-clear: if the sub-object was a defined object in `baseline` but is
2169
- * now undefined/null, emit `field: null` (object removed) instead of a partial
2170
- * of nulled leaves.
2171
- */
2172
- function diffObjectField(field, fullPath, baseline, current, changes, patch) {
2173
- const beforeObj = getByPath(baseline, fullPath);
2174
- const afterObj = getByPath(current, fullPath);
2175
- const nested = {};
2176
- diffFields(field.objectDef.fields, fullPath, baseline, current, changes, nested, void 0, field.objectDef.flatMap);
2177
- if ((afterObj === void 0 || afterObj === null) && isPlainObject(beforeObj)) {
2178
- setPatchLeaf(patch, field.path, null);
2179
- return;
2180
- }
2181
- if (Object.keys(nested).length === 0) return;
2182
- if (getFieldMeta(field.prop, "db.patch.strategy") === "merge") setPatchLeaf(patch, field.path, nested);
2183
- else setPatchLeaf(patch, field.path, afterObj === void 0 ? null : afterObj);
2184
- }
2185
- /** Array field — keyed → $update/$insert/$remove; unkeyed → $replace. */
2186
- function diffArrayField(field, fullPath, baseline, current, changes, patch) {
2187
- const before = getByPath(baseline, fullPath);
2188
- const after = getByPath(current, fullPath);
2189
- if (deepEqual(before, after)) return;
2190
- const arrayPatch = diffArray(field, before, after);
2191
- if (arrayPatch === void 0) return;
2192
- changes.push({
2193
- path: fullPath,
2194
- kind: "array",
2195
- before,
2196
- after
2197
- });
2198
- setPatchLeaf(patch, field.path, arrayPatch);
2199
- }
2200
- /**
2201
- * Produces a `TArrayPatch` value for one array field, or `undefined` when no
2202
- * real op results (the caller then skips the field entirely).
2203
- *
2204
- * - Keyed arrays (item object has `@expect.array.key`): emit `$update`
2205
- * (key + changed leaves), `$insert` (wholly-new items, whole), `$remove`
2206
- * (key only). Reorder-only (same key membership, same content, different
2207
- * order) → `$replace` (key-ops can't express a pure reorder).
2208
- * Ambiguous keys (duplicate or missing key values) → `$replace` (the only
2209
- * faithful op when key identity is unreliable).
2210
- * - Unkeyed object arrays / primitive arrays: `$replace` with the whole array.
2211
- * Primitive arrays with `@expect.array.uniqueItems` use by-value
2212
- * `$insert` / `$remove` (set semantics).
2213
- *
2214
- * Deliberate `$insert`-not-`$upsert`: wholly-new keyed items use `$insert`
2215
- * (pure append) rather than `$upsert`. This is safe because `$insert` is only
2216
- * ever used for keys ABSENT from baseline; existing keys go through `$update`.
2217
- * `$upsert` would dedupe-by-key, which we don't need given that invariant.
2218
- */
2219
- function diffArray(field, before, after) {
2220
- const beforeArr = Array.isArray(before) ? before : [];
2221
- const afterArr = Array.isArray(after) ? after : [];
2222
- const keyProps = getArrayKeyProps(field.itemType);
2223
- if (keyProps.length > 0) return diffKeyedArray(beforeArr, afterArr, keyProps);
2224
- if (getFieldMeta(field.prop, "expect.array.uniqueItems") !== void 0 && isPrimitiveItem(field)) {
2225
- const setPatch = diffUniqueArray(beforeArr, afterArr);
2226
- if (setPatch) return setPatch;
2227
- }
2228
- return { $replace: afterArr };
2229
- }
2230
- /**
2231
- * Keyed array diff. Reorder-only (same membership) falls back to $replace.
2232
- *
2233
- * Returns `undefined` when no $update/$insert/$remove op is produced (so the
2234
- * caller skips the field rather than emitting a malformed empty `{}`).
2235
- *
2236
- * Ambiguity fallback: if either side has DUPLICATE key buckets, or ANY element
2237
- * is missing all of its key values, key identity is unreliable — fall back to
2238
- * `{ $replace: after }`, the only faithful op (last-write-wins collapse would
2239
- * silently drop items, and a key-less `$update` is unmatchable by the DB).
2240
- */
2241
- function diffKeyedArray(before, after, keyProps) {
2242
- if (hasKeylessItem(before, keyProps) || hasKeylessItem(after, keyProps)) return { $replace: after };
2243
- const beforeByKey = /* @__PURE__ */ new Map();
2244
- for (const el of before) if (isPlainObject(el)) beforeByKey.set(keyOf(el, keyProps), el);
2245
- const afterByKey = /* @__PURE__ */ new Map();
2246
- for (const el of after) if (isPlainObject(el)) afterByKey.set(keyOf(el, keyProps), el);
2247
- if (beforeByKey.size !== before.length || afterByKey.size !== after.length) return { $replace: after };
2248
- const $insert = [];
2249
- const $update = [];
2250
- const $remove = [];
2251
- let contentChanged = false;
2252
- for (const [k, el] of afterByKey) {
2253
- const prev = beforeByKey.get(k);
2254
- if (prev === void 0) {
2255
- $insert.push(el);
2256
- continue;
2257
- }
2258
- if (!deepEqual(prev, el)) {
2259
- contentChanged = true;
2260
- const partial = buildKeyedUpdate(prev, el, keyProps);
2261
- if (partial) $update.push(partial);
2262
- }
2263
- }
2264
- if (beforeByKey.size === afterByKey.size && $insert.length === 0 && !contentChanged) return { $replace: after };
2265
- for (const [k, el] of beforeByKey) if (!afterByKey.has(k)) $remove.push(pickKeys(el, keyProps));
2266
- return arrayOps({
2267
- $update,
2268
- $insert,
2269
- $remove
2270
- });
2271
- }
2272
- /** Builds a `$update` partial: key fields + changed leaves only. */
2273
- function buildKeyedUpdate(prev, next, keyProps) {
2274
- const partial = {};
2275
- for (const k of keyProps) partial[k] = next[k];
2276
- let changed = false;
2277
- const allKeys = new Set([...Object.keys(prev), ...Object.keys(next)]);
2278
- for (const k of allKeys) {
2279
- if (keyProps.includes(k)) continue;
2280
- const a = prev[k];
2281
- const b = next[k];
2282
- if (!deepEqual(a, b)) {
2283
- partial[k] = b === void 0 ? null : b;
2284
- changed = true;
2285
- }
2286
- }
2287
- return changed ? partial : void 0;
2288
- }
2289
- /** Primitive uniqueItems set diff. Returns undefined if neither side differs. */
2290
- function diffUniqueArray(before, after) {
2291
- const beforeSet = new Set(before.map((v) => stableKey(v)));
2292
- const afterSet = new Set(after.map((v) => stableKey(v)));
2293
- const $insert = [];
2294
- const $remove = [];
2295
- const seenInsert = /* @__PURE__ */ new Set();
2296
- const seenRemove = /* @__PURE__ */ new Set();
2297
- for (const v of after) {
2298
- const k = stableKey(v);
2299
- if (!beforeSet.has(k) && !seenInsert.has(k)) {
2300
- $insert.push(v);
2301
- seenInsert.add(k);
2302
- }
2303
- }
2304
- for (const v of before) {
2305
- const k = stableKey(v);
2306
- if (!afterSet.has(k) && !seenRemove.has(k)) {
2307
- $remove.push(v);
2308
- seenRemove.add(k);
2309
- }
2310
- }
2311
- return arrayOps({
2312
- $insert,
2313
- $remove
2314
- });
2315
- }
2316
- /**
2317
- * Assembles a `TArrayPatch` from named op-arrays, dropping empty ones. Returns
2318
- * `undefined` when no op carries any item, so the caller skips the field rather
2319
- * than emitting a malformed empty `{}`.
2320
- */
2321
- function arrayOps(ops) {
2322
- const result = {};
2323
- for (const k in ops) if (ops[k].length > 0) result[k] = ops[k];
2324
- return Object.keys(result).length > 0 ? result : void 0;
2325
- }
2326
- /** Reads `@expect.array.key` props from an array item's object type. */
2327
- function getArrayKeyProps(itemType) {
2328
- if (itemType.type.kind !== "object") return [];
2329
- const props = itemType.type.props;
2330
- const keys = [];
2331
- for (const [name, prop] of props.entries()) if (getFieldMeta(prop, "expect.array.key") !== void 0) keys.push(name);
2332
- return keys;
2333
- }
2334
- /** True when the array's item type is a primitive (designType, kind === ''). */
2335
- function isPrimitiveItem(field) {
2336
- return field.itemType.type.kind === "";
2337
- }
2338
- /** Finds the form's `@db.column.version` column name, if any (top-level only). */
2339
- function findVersionColumn(def) {
2340
- for (const [path, prop] of def.flatMap.entries()) {
2341
- if (!path || path.includes(".")) continue;
2342
- if (getFieldMeta(prop, "db.column.version") !== void 0) return path;
2343
- }
2344
- }
2345
- /** True when any element lacks ALL of its key values (un-keyable identity). */
2346
- function hasKeylessItem(arr, keyProps) {
2347
- for (const el of arr) {
2348
- if (!isPlainObject(el)) return true;
2349
- let hasAnyKey = false;
2350
- for (const k of keyProps) {
2351
- const v = el[k];
2352
- if (v !== void 0 && v !== null) {
2353
- hasAnyKey = true;
2354
- break;
2355
- }
2356
- }
2357
- if (!hasAnyKey) return true;
2358
- }
2359
- return false;
2360
- }
2361
- /** Composite key string for a keyed-array element. */
2362
- function keyOf(el, keyProps) {
2363
- if (keyProps.length === 1) return stableKey(el[keyProps[0]]);
2364
- return keyProps.map((k) => stableKey(el[k])).join(" ");
2365
- }
2366
- /** Picks only the key fields from an element (for $remove). */
2367
- function pickKeys(el, keyProps) {
2368
- const out = {};
2369
- for (const k of keyProps) out[k] = el[k];
2370
- return out;
2371
- }
2372
- /** Writes a value into a (possibly dotted) leaf path on a local patch object. */
2373
- function setPatchLeaf(patch, path, value) {
2374
- if (!path.includes(".")) {
2375
- patch[path] = value;
2376
- return;
2377
- }
2378
- const keys = path.split(".");
2379
- const last = keys.pop();
2380
- let cur = patch;
2381
- for (const k of keys) {
2382
- let next = cur[k];
2383
- if (next === void 0 || next === null || typeof next !== "object") {
2384
- next = {};
2385
- cur[k] = next;
2386
- }
2387
- cur = next;
2388
- }
2389
- cur[last] = value;
2390
- }
2391
- function isPlainObject(v) {
2392
- return typeof v === "object" && v !== null && !Array.isArray(v);
2393
- }
2394
- /**
2395
- * Stable string key for primitives / values (used for set membership).
2396
- *
2397
- * Key equality is TYPE-STRICT: a number `1` and a string `'1'` produce
2398
- * distinct keys, so a keyed-array item whose key changes JS representation
2399
- * between baseline and current is treated as a remove + insert. Callers that
2400
- * round-trip keys with loose typing should normalise the key type first.
2401
- */
2402
- function stableKey(v) {
2403
- if (typeof v === "string") return `s:${v}`;
2404
- if (typeof v === "number" || typeof v === "boolean") return `p:${String(v)}`;
2405
- if (v === null) return "null";
2406
- if (v === void 0) return "undef";
2407
- return `j:${JSON.stringify(v)}`;
2408
- }
2409
- /**
2410
- * Structural deep equality (order-sensitive for arrays). `NaN` equals `NaN`
2411
- * (revert-aware for NaN scalars) while `0` / `-0` stay equal (matches DB
2412
- * intent — `===` treats them equal, only NaN is special-cased).
2413
- *
2414
- * The single comparator shared across the form engine: diff, conflict
2415
- * detection ({@link buildFormRebase}), and apply all route through this — never
2416
- * reimplement equality elsewhere.
2417
- */
2418
- function deepEqual(a, b) {
2419
- if (a === b) return true;
2420
- if (typeof a === "number" && typeof b === "number") return Number.isNaN(a) && Number.isNaN(b);
2421
- if (a === null || b === null || a === void 0 || b === void 0) return false;
2422
- if (typeof a !== "object" || typeof b !== "object") return false;
2423
- const aIsArr = Array.isArray(a);
2424
- const bIsArr = Array.isArray(b);
2425
- if (aIsArr !== bIsArr) return false;
2426
- if (aIsArr && bIsArr) {
2427
- if (a.length !== b.length) return false;
2428
- for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;
2429
- return true;
2430
- }
2431
- const ao = a;
2432
- const bo = b;
2433
- const aKeys = Object.keys(ao);
2434
- const bKeys = Object.keys(bo);
2435
- if (aKeys.length !== bKeys.length) return false;
2436
- for (const k of aKeys) {
2437
- if (!Object.prototype.hasOwnProperty.call(bo, k)) return false;
2438
- if (!deepEqual(ao[k], bo[k])) return false;
2439
- }
2440
- return true;
2441
- }
2442
- //#endregion
2443
- //#region src/form/dirty.ts
2444
- /**
2445
- * True when the field at dot-path `path` is dirty given a {@link FormFieldChange}
2446
- * list (as produced by {@link buildFormDiff}).
2447
- *
2448
- * The change list is leaf-grained for scalars/objects but WHOLE-ARRAY for arrays,
2449
- * so a field at `path` is dirty iff some change path equals `path` OR starts with
2450
- * `path + "."`:
2451
- *
2452
- * - scalar / leaf field (incl. nested `address.city`) → exact match.
2453
- * - object / section container → no entry at its own path, only its leaves →
2454
- * matched by the PREFIX branch.
2455
- * - whole-array field → one entry at the array root → exact match.
2456
- * - a field rendered for an array-ITEM leaf (e.g. `items.0.qty`) → NOT detectable:
2457
- * the array diff emits a single whole-array change at the array root, never
2458
- * per-item leaf paths, so this correctly returns false (the array container
2459
- * lights up instead). This is a known, documented limitation.
2460
- *
2461
- * The prefix uses `path + "."` so field `item` never matches a change at `items`
2462
- * (no false positives).
2463
- *
2464
- * Empty `path` `''` is the wrapped form root — every change is nested under it,
2465
- * so it is considered dirty iff there are ANY changes.
2466
- */
2467
- function isPathDirty(changes, path) {
2468
- if (path === "") return changes.length > 0;
2469
- const prefix = `${path}.`;
2470
- for (const change of changes) if (change.path === path || change.path.startsWith(prefix)) return true;
2471
- return false;
2472
- }
2473
- /**
2474
- * Precomputes the set of ALL dirty paths from a {@link FormFieldChange} list so
2475
- * that membership is an O(1) `Set.has(path)` instead of {@link isPathDirty}'s
2476
- * per-call O(changes) prefix scan. Callers that probe many fields against the
2477
- * same change list (e.g. a form rendering one field per leaf) build this once
2478
- * and query it per field.
2479
- *
2480
- * For each change path `C` it adds `C` AND every dot-prefix ancestor of `C`
2481
- * (so `'address.city'` adds both `'address.city'` and `'address'`), matching
2482
- * `isPathDirty`'s "exact OR `path + '.'` prefix" predicate — an ancestor
2483
- * container is dirty exactly when some change is nested under it. The wrapped
2484
- * root `''` is added iff there are ANY changes, mirroring `isPathDirty('')`.
2485
- *
2486
- * INVARIANT (locked, tested): for EVERY path `P`,
2487
- * `collectDirtyPaths(changes).has(P) === isPathDirty(changes, P)`. This is a
2488
- * precompute of the SAME predicate, not a second one — keep them in lockstep.
2489
- */
2490
- function collectDirtyPaths(changes) {
2491
- const dirty = /* @__PURE__ */ new Set();
2492
- if (changes.length === 0) return dirty;
2493
- dirty.add("");
2494
- for (const change of changes) {
2495
- const path = change.path;
2496
- dirty.add(path);
2497
- let dot = path.indexOf(".");
2498
- while (dot !== -1) {
2499
- dirty.add(path.slice(0, dot));
2500
- dot = path.indexOf(".", dot + 1);
2501
- }
2502
- }
2503
- return dirty;
2504
- }
2505
- //#endregion
2506
- //#region src/form/apply.ts
2507
- /**
2508
- * Applies a {@link FormFieldChange} list onto a WRAPPED form-data container
2509
- * (`{ value: domainData }`), mutating it in place and returning the same
2510
- * reference. The inverse direction of {@link buildFormDiff}: where the diff
2511
- * READS `(baseline, current)` into changes, this WRITES changes onto data.
2512
- *
2513
- * IMPORTANT: pass a CLONE, never the live fetched row — every write mutates
2514
- * `data` directly. Callers that need the original intact should
2515
- * `deepClone(data)` first (see {@link deepClone}).
2516
- *
2517
- * Per-change semantics (the single place the apply rules live, so
2518
- * {@link buildFormRebase} stays consistent):
2519
- *
2520
- * - `kind: 'set'`:
2521
- * - `change.after === undefined` → DELETE the own key at `change.path` (walk
2522
- * to parent, `delete`). A cleared field must read as ABSENT, not as a
2523
- * present `undefined` own-key — otherwise a re-diff sees a structural
2524
- * mismatch where the form intends "no value". `setByPath(…, undefined)`
2525
- * leaves an own key behind, so we use {@link deleteByPath} instead.
2526
- * - otherwise → `setByPath(data, change.path, change.after)`.
2527
- * - `kind: 'array'`: whole-array set via `setByPath(data, change.path,
2528
- * change.after)` (LOCKED Option A — no per-element merge; the diff already
2529
- * carried the full after-array).
2530
- *
2531
- * The `def` is currently unused by the apply walk (paths fully describe the
2532
- * write target) but is part of the signature for parity with
2533
- * `buildFormDiff`/`buildFormRebase`, so the rebase engine threads one `def`
2534
- * uniformly through diff + apply.
2535
- */
2536
- function applyFormChanges(_def, data, changes) {
2537
- for (const change of changes) if (change.kind === "set" && change.after === void 0) deleteByPath(data, change.path);
2538
- else setByPath(data, change.path, change.after);
2539
- return data;
2540
- }
2541
- //#endregion
2542
- //#region src/form/rebase.ts
2543
- /**
2544
- * Pure 3-way rebase for a change-tracked form. Given the current baseline `B0`,
2545
- * the live form `C`, and a fresh upstream `U`, produces the form rewritten as
2546
- * `U` + the local diff (`C` vs `B0`) reapplied on top:
2547
- *
2548
- * - Fields the user never touched adopt upstream's value.
2549
- * - Local edits survive (reapplied onto the upstream clone).
2550
- * - Fields changed on BOTH sides to different values are conflicts, resolved by
2551
- * `opts.conflict` (`'ours'` keeps local, `'theirs'` takes upstream).
2552
- *
2553
- * All inputs are WRAPPED form-data containers (`{ value: domainData }`). The
2554
- * result `next` is a fresh container; no input is mutated.
2555
- *
2556
- * `diffOptions` are forwarded to BOTH internal `buildFormDiff` passes so the
2557
- * same field exclusions apply (notably the `@db.column.version` column and the
2558
- * `$cas` policy) on the local and upstream sides — keep them identical to the
2559
- * options the caller uses for its own change tracking.
2560
- */
2561
- function buildFormRebase(def, baseline, current, upstream, opts, diffOptions) {
2562
- const conflictMode = opts?.conflict ?? "ours";
2563
- const local = buildFormDiff(def, baseline, current, diffOptions).changes;
2564
- const upstreamChanges = buildFormDiff(def, baseline, upstream, diffOptions).changes;
2565
- const upstreamByPath = /* @__PURE__ */ new Map();
2566
- for (const uc of upstreamChanges) upstreamByPath.set(uc.path, uc);
2567
- const next = deepClone(upstream);
2568
- const conflicts = [];
2569
- for (const lc of local) {
2570
- const clearedAncestor = findClearedAncestor(lc.path, baseline, upstream);
2571
- if (clearedAncestor !== void 0) {
2572
- conflicts.push(clearedAncestor);
2573
- if (conflictMode === "ours") setByPath(next, clearedAncestor, deepClone(getByPath(current, clearedAncestor)));
2574
- continue;
2575
- }
2576
- const uc = upstreamByPath.get(lc.path);
2577
- if (uc !== void 0) {
2578
- if (deepEqual(lc.after, uc.after)) continue;
2579
- conflicts.push(lc.path);
2580
- if (conflictMode === "ours") reapply(def, next, lc);
2581
- continue;
2582
- }
2583
- reapply(def, next, lc);
2584
- }
2585
- const reapplied = buildFormDiff(def, upstream, deepClone(next), diffOptions).changes;
2586
- return {
2587
- next,
2588
- conflicts: [...new Set(conflicts)],
2589
- reapplied
2590
- };
2591
- }
2592
- /**
2593
- * Reapplies a single local change onto `next`, DEEP-CLONING its `after` value
2594
- * first. `lc.after` is a LIVE reference into `current` (buildFormDiff holds live
2595
- * refs), so for a `kind:'array'` or whole-object/union `set` change a raw apply
2596
- * would make `next.value`'s node `===` `current.value`'s node — violating the
2597
- * `FormRebaseResult.next` contract ("never aliases any input container"). The
2598
- * ancestor-clear branch already deep-clones before writing; this keeps the two
2599
- * leaf-reapply sites consistent.
2600
- */
2601
- function reapply(def, next, lc) {
2602
- applyFormChanges(def, next, [{
2603
- ...lc,
2604
- after: deepClone(lc.after)
2605
- }]);
2606
- }
2607
- /**
2608
- * Returns the SHALLOWEST strict ancestor of `leafPath` that was an object/array
2609
- * in `baseline` but is `null`/`undefined` in `upstream` (upstream cleared the
2610
- * subtree), or `undefined` when no ancestor was cleared. The leaf path itself is
2611
- * never considered an ancestor.
2612
- */
2613
- function findClearedAncestor(leafPath, baseline, upstream) {
2614
- if (!leafPath.includes(".")) return void 0;
2615
- const segs = leafPath.split(".");
2616
- let acc = "";
2617
- for (let i = 0; i < segs.length - 1; i++) {
2618
- acc = acc ? `${acc}.${segs[i]}` : segs[i];
2619
- const base = getByPath(baseline, acc);
2620
- if (typeof base !== "object" || base === null) continue;
2621
- const up = getByPath(upstream, acc);
2622
- if (up === null || up === void 0) return acc;
2623
- }
2624
- }
2625
- //#endregion
2626
- //#region src/form/union-detect.ts
2627
- /**
2628
- * True when ANY union field in the form resolves to a DIFFERENT discriminated
2629
- * variant between two wrapped data containers. A variant picker typically
2630
- * detects its variant index once at setup and keys the variant subtree on it,
2631
- * so a rebase that lands a different variant (via conflict OR an upstream-only
2632
- * switch) needs a remount to re-detect. This walks union + nested-object fields
2633
- * and compares `detectUnionVariant` at each union path.
2634
- *
2635
- * Scope note (pragmatic): walks standalone + nested-OBJECT union fields. Unions
2636
- * nested INSIDE array items are not walked — an array renderer that keeps a
2637
- * stable per-item key across in-place value mutations would not remount an
2638
- * existing row's picker on an upstream-driven variant flip, but that collision
2639
- * (a 3-way rebase landing a different union variant inside an unchanged array
2640
- * row) is a rare edge. TODO: extend to array-item unions if a real consumer
2641
- * hits a stuck picker inside an array row.
2642
- */
2643
- function unionVariantChanged(def, before, after) {
2644
- return walkUnionFields(def.fields, "", before, after);
2645
- }
2646
- function walkUnionFields(fields, prefix, before, after) {
2647
- for (const field of fields) {
2648
- if (field.phantom) continue;
2649
- const fullPath = field.path ? prefix ? `${prefix}.${field.path}` : field.path : prefix;
2650
- if (isUnionField(field)) {
2651
- const variants = field.unionVariants;
2652
- if (variants.length > 1) {
2653
- if (detectUnionVariant(getByPath(before, fullPath), variants) !== detectUnionVariant(getByPath(after, fullPath), variants)) return true;
2654
- }
2655
- continue;
2656
- }
2657
- if (isObjectField(field)) {
2658
- const objectDef = field.objectDef;
2659
- if (walkUnionFields(objectDef.fields, fullPath, before, after)) return true;
2660
- }
2661
- }
2662
- return false;
2663
- }
2664
- //#endregion
2665
- //#region src/form/grid.ts
2666
- /** Grid layout parsing for `@ui.form.grid.colSpan` / `@ui.form.grid.rowSpan`. */
2667
- const DEFAULT_COL_SPAN = 12;
2668
- const DEFAULT_ROW_SPAN = 1;
2669
- const COL_SPAN_ALIASES = {
2670
- full: 12,
2671
- half: 6,
2672
- third: 4
2673
- };
2674
- /** Accepts "1"-"12" and the aliases "full" (12), "half" (6), "third" (4). */
2675
- function parseColSpan(raw) {
2676
- if (!raw) return void 0;
2677
- const aliased = COL_SPAN_ALIASES[raw];
2678
- if (aliased !== void 0) return aliased;
2679
- const n = Number.parseInt(raw, 10);
2680
- if (Number.isFinite(n) && n >= 1 && n <= 12 && String(n) === raw) return n;
2681
- }
2682
- /** Accepts numeric strings "1"+; rejects "0", negatives, decimals, aliases. */
2683
- function parseRowSpan(raw) {
2684
- if (!raw) return void 0;
2685
- const n = Number.parseInt(raw, 10);
2686
- if (Number.isFinite(n) && n >= 1 && String(n) === raw) return n;
2687
- }
2688
- /**
2689
- * Resolve a field's grid footprint. Narrow defaults to full-width / single-row
2690
- * regardless of the desktop value, so authors can opt into a narrow override
2691
- * via the second annotation arg without it inheriting an unintended desktop span.
2692
- */
2693
- function resolveGridSpec(colSpan, rowSpan) {
2694
- return {
2695
- col: {
2696
- desktop: parseColSpan(colSpan?.desktop) ?? 12,
2697
- narrow: parseColSpan(colSpan?.narrow) ?? 12
2698
- },
2699
- row: {
2700
- desktop: parseRowSpan(rowSpan?.desktop) ?? 1,
2701
- narrow: parseRowSpan(rowSpan?.narrow) ?? 1
2702
- }
2703
- };
2704
- }
2705
- /**
2706
- * Build the UnoCSS class string for a field's grid footprint.
2707
- *
2708
- * - Skips desktop classes that match the default (`as-grid-item` already
2709
- * covers `col-span-full row-span-1`).
2710
- * - Skips narrow overrides that match the desktop value (no override needed).
2711
- * - The narrow variant uses the custom `as-narrow:` prefix, which the
2712
- * atscript-ui UnoCSS preset rewrites to `@container as-grid (max-width:
2713
- * 480px) { ... }`. The parent grid is registered as
2714
- * `container-name: as-grid` via the `as-form-grid` shortcut, so the
2715
- * rule resolves against the actual grid's inline size — not the viewport.
2716
- *
2717
- * Returned string is space-separated, ready to drop into a Vue class binding.
2718
- */
2719
- function buildGridClasses(spec) {
2720
- const out = [];
2721
- if (spec.col.desktop !== 12) out.push(`col-span-${spec.col.desktop}`);
2722
- if (spec.row.desktop !== 1) out.push(`row-span-${spec.row.desktop}`);
2723
- if (spec.col.narrow !== spec.col.desktop) out.push(`as-narrow:col-span-${spec.col.narrow}`);
2724
- if (spec.row.narrow !== spec.row.desktop) out.push(`as-narrow:row-span-${spec.row.narrow}`);
2725
- return out.join(" ");
2726
- }
2727
- //#endregion
2728
- //#region src/form/labels.ts
2729
- /** Singular label for an array field (used by AsArray for "Add <singular>"). */
2730
- function resolveSingularLabel(meta) {
2731
- if (!meta) return "item";
2732
- return getFieldMeta(meta, "ui.form.label.singular") || "item";
2733
- }
2734
- //#endregion
2735
- //#region src/form/decimal-format.ts
2736
- const WHITESPACE_GROUP_RE = /[   ]/g;
2737
- const numberFormatCache = /* @__PURE__ */ new Map();
2738
- function getNumberFormat(locale, opts) {
2739
- const key = `${locale ?? ""}|${opts.style ?? ""}|${opts.currency ?? ""}|${opts.currencyDisplay ?? ""}|${opts.useGrouping ?? ""}|${opts.minimumFractionDigits ?? ""}|${opts.maximumFractionDigits ?? ""}`;
2740
- let f = numberFormatCache.get(key);
2741
- if (!f) {
2742
- f = new Intl.NumberFormat(locale, opts);
2743
- numberFormatCache.set(key, f);
2744
- }
2745
- return f;
2746
- }
2747
- const decimalSeparatorCache = /* @__PURE__ */ new Map();
2748
- const thousandsSeparatorCache = /* @__PURE__ */ new Map();
2749
- const currencyDisplayCache = /* @__PURE__ */ new Map();
2750
- const currencyDecimalsCache = /* @__PURE__ */ new Map();
2751
- /** "." in en-US, "," in fr-FR. Returns "." when locale is undefined. */
2752
- function getDecimalSeparator(locale) {
2753
- const key = locale ?? "";
2754
- const cached = decimalSeparatorCache.get(key);
2755
- if (cached !== void 0) return cached;
2756
- let out = ".";
2757
- try {
2758
- out = getNumberFormat(locale, { useGrouping: false }).formatToParts(1.1).find((p) => p.type === "decimal")?.value ?? ".";
2759
- } catch {}
2760
- decimalSeparatorCache.set(key, out);
2761
- return out;
2762
- }
2763
- /**
2764
- * "," in en-US, NNBSP (U+202F) in fr-FR. Returns "" when no grouping is
2765
- * applied (or when Intl rejects the locale).
2766
- */
2767
- function getThousandsSeparator(locale) {
2768
- const key = locale ?? "";
2769
- const cached = thousandsSeparatorCache.get(key);
2770
- if (cached !== void 0) return cached;
2771
- let out = "";
2772
- try {
2773
- out = getNumberFormat(locale, { useGrouping: true }).formatToParts(1e6).find((p) => p.type === "group")?.value ?? "";
2774
- } catch {}
2775
- thousandsSeparatorCache.set(key, out);
2776
- return out;
2777
- }
2778
- function getCurrencyDisplayParts(code, locale) {
2779
- const key = `${locale ?? ""}|${code}`;
2780
- const cached = currencyDisplayCache.get(key);
2781
- if (cached) return cached;
2782
- let out = {
2783
- symbol: code,
2784
- position: "prefix"
2785
- };
2786
- try {
2787
- const parts = getNumberFormat(locale, {
2788
- style: "currency",
2789
- currency: code,
2790
- currencyDisplay: "narrowSymbol"
2791
- }).formatToParts(0);
2792
- const idxCur = parts.findIndex((p) => p.type === "currency");
2793
- const idxInt = parts.findIndex((p) => p.type === "integer");
2794
- out = {
2795
- symbol: parts[idxCur]?.value ?? code,
2796
- position: idxInt === -1 || idxCur < idxInt ? "prefix" : "suffix"
2797
- };
2798
- } catch {}
2799
- currencyDisplayCache.set(key, out);
2800
- return out;
2801
- }
2802
- /**
2803
- * Currency's natural decimal count via Intl. JPY=0, USD/EUR=2, BHD/KWD=3.
2804
- * Returns `undefined` for codes Intl doesn't know — caller falls back to
2805
- * `dbPrecisionScale`.
2806
- */
2807
- function getCurrencyDecimals(code, locale) {
2808
- if (!code) return void 0;
2809
- const key = `${locale ?? ""}|${code}`;
2810
- if (currencyDecimalsCache.has(key)) return currencyDecimalsCache.get(key);
2811
- let out;
2812
- try {
2813
- const max = getNumberFormat(locale, {
2814
- style: "currency",
2815
- currency: code
2816
- }).resolvedOptions().maximumFractionDigits;
2817
- out = typeof max === "number" ? max : void 0;
2818
- } catch {
2819
- out = void 0;
2820
- }
2821
- currencyDecimalsCache.set(key, out);
2822
- return out;
2823
- }
2824
- /**
2825
- * Parse a user-typed decimal string. Returns the canonical decimal
2826
- * (no thousands separator, "." as decimal separator) or `null` if invalid.
2827
- * Accepts both "." and "," as the decimal separator (locale-aware).
2828
- * Strips the locale thousands separator. Preserves sign. Does NOT
2829
- * enforce scale.
2830
- */
2831
- function parseDecimalInput(raw, locale) {
2832
- if (typeof raw !== "string") return null;
2833
- const trimmed = raw.trim();
2834
- if (trimmed === "") return null;
2835
- const decSep = getDecimalSeparator(locale);
2836
- const thouSep = getThousandsSeparator(locale);
2837
- let sign = "";
2838
- let body = trimmed;
2839
- if (body.startsWith("-")) {
2840
- sign = "-";
2841
- body = body.slice(1);
2842
- } else if (body.startsWith("+")) body = body.slice(1);
2843
- if (body.length === 0) return null;
2844
- if (body.includes("-") || body.includes("+")) return null;
2845
- if (thouSep && body.includes(thouSep)) {
2846
- const decIdx = body.indexOf(decSep);
2847
- const headRaw = decIdx === -1 ? body : body.slice(0, decIdx);
2848
- const tail = decIdx === -1 ? "" : body.slice(decIdx);
2849
- if (tail.includes(thouSep)) return null;
2850
- if (headRaw.includes(thouSep)) {
2851
- const groups = headRaw.split(thouSep);
2852
- const first = groups[0];
2853
- if (first.length < 1 || first.length > 3 || !/^\d+$/.test(first)) return null;
2854
- for (let i = 1; i < groups.length; i += 1) if (!/^\d{3}$/.test(groups[i])) return null;
2855
- }
2856
- body = `${headRaw.split(thouSep).join("")}${tail}`;
2857
- }
2858
- body = body.replace(WHITESPACE_GROUP_RE, "");
2859
- if (decSep !== ".") {
2860
- if ((body.match(/,/g)?.length ?? 0) > 1) return null;
2861
- if (body.includes(".") && body.includes(",")) return null;
2862
- if (body.includes(",")) body = body.replace(",", ".");
2863
- } else if (body.includes(",")) {
2864
- if (body.includes(".")) return null;
2865
- if ((body.match(/,/g)?.length ?? 0) > 1) return null;
2866
- body = body.replace(",", ".");
2867
- }
2868
- if (!/^\d*\.?\d*$/.test(body)) return null;
2869
- if (body === "" || body === ".") return null;
2870
- if (body.endsWith(".")) body = body.slice(0, -1);
2871
- if (body.startsWith(".")) body = `0${body}`;
2872
- const dot = body.indexOf(".");
2873
- if (dot === -1) body = body.replace(/^0+(\d)/, "$1");
2874
- else {
2875
- const head = body.slice(0, dot);
2876
- const tail = body.slice(dot);
2877
- body = `${head.replace(/^0+(\d)/, "$1")}${tail}`;
2878
- }
2879
- if (sign === "-" && /^0+(\.0+)?$/.test(body)) sign = "";
2880
- return `${sign}${body}`;
2881
- }
2882
- /**
2883
- * Enforce a fractional-digit count by truncating or padding. String-only —
2884
- * no float arithmetic. Default behaviour truncates (no rounding) so digits
2885
- * the user typed can't silently shift. Pass `roundHalfUp: true` to round.
2886
- *
2887
- * enforceScale("12.345", 2) → "12.34" (truncate)
2888
- * enforceScale("12.3", 4) → "12.3000" (pad)
2889
- * enforceScale("12", 0) → "12"
2890
- * enforceScale("12.99", 0) → "12" (no rounding)
2891
- */
2892
- function enforceScale(s, scale, opts) {
2893
- if (typeof s !== "string" || s === "") return s;
2894
- if (scale === void 0 || scale < 0) return s;
2895
- const parts = splitDecimalString(s);
2896
- if (scale === 0) {
2897
- if (opts?.roundHalfUp && parts.decimal.length > 0 && parts.decimal[0] >= "5") {
2898
- const bumped = addOne(parts.integer);
2899
- return joinDecimalString({
2900
- sign: parts.sign,
2901
- integer: bumped,
2902
- decimal: ""
2903
- });
2904
- }
2905
- return joinDecimalString({
2906
- sign: parts.sign,
2907
- integer: parts.integer,
2908
- decimal: ""
2909
- });
2910
- }
2911
- if (parts.decimal.length === scale) return joinDecimalString(parts);
2912
- if (parts.decimal.length < scale) return joinDecimalString({
2913
- sign: parts.sign,
2914
- integer: parts.integer,
2915
- decimal: parts.decimal.padEnd(scale, "0")
2916
- });
2917
- let head = parts.decimal.slice(0, scale);
2918
- const dropped = parts.decimal.slice(scale);
2919
- let integer = parts.integer;
2920
- if (opts?.roundHalfUp && dropped.length > 0 && dropped[0] >= "5") {
2921
- const bumpedFrac = addOne(head);
2922
- if (bumpedFrac.length > head.length) {
2923
- integer = addOne(integer);
2924
- head = "0".repeat(scale);
2925
- } else head = bumpedFrac;
2926
- }
2927
- return joinDecimalString({
2928
- sign: parts.sign,
2929
- integer,
2930
- decimal: head
2931
- });
2932
- }
2933
- function addOne(digits) {
2934
- if (digits === "") return "1";
2935
- const out = digits.split("");
2936
- let i = out.length - 1;
2937
- let carry = 1;
2938
- while (i >= 0 && carry > 0) {
2939
- const d = out[i].charCodeAt(0) - 48 + carry | 0;
2940
- if (d >= 10) {
2941
- out[i] = "0";
2942
- carry = 1;
2943
- } else {
2944
- out[i] = String.fromCharCode(d + 48);
2945
- carry = 0;
2946
- }
2947
- i -= 1;
2948
- }
2949
- if (carry > 0) out.unshift("1");
2950
- return out.join("");
2951
- }
2952
- function splitDecimalString(s) {
2953
- if (typeof s !== "string" || s === "") return {
2954
- sign: "",
2955
- integer: "0",
2956
- decimal: ""
2957
- };
2958
- let sign = "";
2959
- let body = s;
2960
- if (body.startsWith("-")) {
2961
- sign = "-";
2962
- body = body.slice(1);
2963
- } else if (body.startsWith("+")) body = body.slice(1);
2964
- if (body === "") return {
2965
- sign: "",
2966
- integer: "0",
2967
- decimal: ""
2968
- };
2969
- const dot = body.indexOf(".");
2970
- let integer;
2971
- let decimal;
2972
- if (dot === -1) {
2973
- integer = body;
2974
- decimal = "";
2975
- } else {
2976
- integer = body.slice(0, dot);
2977
- decimal = body.slice(dot + 1);
2978
- }
2979
- if (integer === "") integer = "0";
2980
- integer = integer.replace(/^0+(\d)/, "$1");
2981
- if (sign === "-" && integer === "0" && !decimal.replace(/0/g, "")) sign = "";
2982
- return {
2983
- sign,
2984
- integer,
2985
- decimal
2986
- };
2987
- }
2988
- function joinDecimalString(parts) {
2989
- const integer = parts.integer === "" ? "0" : parts.integer;
2990
- const decimal = parts.decimal;
2991
- const body = decimal === "" ? integer : `${integer}.${decimal}`;
2992
- return `${parts.sign}${body}`;
2993
- }
2994
- function formatDecimalForDisplay(opts) {
2995
- const { value, scale, locale, currency, unit, useGrouping = currency !== void 0 || unit !== void 0 || scale !== void 0 } = opts;
2996
- if (value === null || value === void 0 || value === "") return "";
2997
- let canonical;
2998
- if (typeof value === "number") {
2999
- if (!Number.isFinite(value)) return "";
3000
- canonical = String(value);
3001
- } else canonical = value;
3002
- if (!/^[+-]?\d*(\.\d*)?$/.test(canonical) || canonical === "." || canonical === "-") return canonical;
3003
- if (scale !== void 0 && scale >= 0) canonical = enforceScale(canonical, scale);
3004
- const parts = splitDecimalString(canonical);
3005
- const asNumber = Number(canonical);
3006
- const intlSafe = Number.isFinite(asNumber);
3007
- if (currency) {
3008
- try {
3009
- const fmt = getNumberFormat(locale, {
3010
- style: "currency",
3011
- currency,
3012
- currencyDisplay: "narrowSymbol",
3013
- minimumFractionDigits: scale,
3014
- maximumFractionDigits: scale,
3015
- useGrouping
3016
- });
3017
- if (intlSafe) return fmt.format(asNumber);
3018
- } catch {}
3019
- return `${currency} ${formatPlain(parts, scale, locale, useGrouping)}`;
3020
- }
3021
- const base = formatPlain(parts, scale, locale, useGrouping);
3022
- return unit ? `${base} ${unit}` : base;
3023
- }
3024
- function formatPlain(parts, scale, locale, useGrouping) {
3025
- const intStr = useGrouping ? groupInteger(parts.integer, locale) : parts.integer;
3026
- const decStr = scale !== void 0 && scale >= 0 ? parts.decimal.padEnd(scale, "0").slice(0, scale) : parts.decimal;
3027
- const decSep = getDecimalSeparator(locale);
3028
- const body = decStr.length > 0 ? `${intStr}${decSep}${decStr}` : intStr;
3029
- return `${parts.sign}${body}`;
3030
- }
3031
- /**
3032
- * Insert the locale's thousands separator into a plain integer string.
3033
- * Pure string-based — no float math, handles arbitrary length.
3034
- */
3035
- function groupInteger(integer, locale) {
3036
- const sep = getThousandsSeparator(locale);
3037
- if (!sep) return integer;
3038
- if (integer.length <= 3) return integer;
3039
- const out = [];
3040
- let i = integer.length;
3041
- while (i > 3) {
3042
- out.unshift(integer.slice(i - 3, i));
3043
- i -= 3;
3044
- }
3045
- out.unshift(integer.slice(0, i));
3046
- return out.join(sep);
3047
- }
3048
- //#endregion
3049
- //#region src/table/value-kind.ts
3050
- /** Storage kinds that hold plain numbers (a `timestamp` is epoch ms, but filters treat it as a date). */
3051
- const NUMERIC_VALUE_KINDS = new Set([
3052
- "number",
3053
- "integer",
3054
- "decimal"
3055
- ]);
3056
- /**
3057
- * The typed value of one of a column's `options` — the literal itself
3058
- * (`true`, `3`, `'a'`), falling back to the string `key` for a hand-built
3059
- * column that has no `value`.
3060
- *
3061
- * @internal Shared with `@atscript/vue-table`.
3062
- */
3063
- function optionValue(option) {
3064
- return option.value ?? option.key;
3065
- }
3066
- //#endregion
3067
- //#region src/table/column-resolver.ts
3068
- /** Get sortable columns. */
3069
- function getSortableColumns(def) {
3070
- return def.columns.filter((c) => c.sortable);
3071
- }
3072
- /** Get filterable columns. */
3073
- function getFilterableColumns(def) {
3074
- return def.columns.filter((c) => c.filterable);
3075
- }
3076
- /** Find a column by path. */
3077
- function getColumn(def, path) {
3078
- return def.columns.find((c) => c.path === path);
3079
- }
3080
- //#endregion
3081
- //#region src/table/navigate-href.ts
3082
- /**
3083
- * Compute the href a `processor: 'navigate'` action would open — synchronously,
3084
- * at render time. Mirrors the interpolation `Client` performs when the action
3085
- * is invoked (`action.value` with every `$1` replaced by the URL-encoded,
3086
- * `/`-joined `preferredId` fields — see `encodeNavigateId`), so tables can
3087
- * render navigate actions as real `<a href>` anchors and native link behaviour
3088
- * (middle-click → new tab, copy link, hover preview) just works.
3089
- *
3090
- * Returns `undefined` when no link is possible — the caller should fall back to
3091
- * a button and let `Client` handle the invoke:
3092
- *
3093
- * - `action.processor !== 'navigate'` — backend/custom actions stay buttons;
3094
- * - row-level action with `id === undefined` — the row is not identifiable
3095
- * (note this deliberately differs from `Client`, which navigates to the raw
3096
- * template in that case; a raw-template href would be a broken link);
3097
- * - row-level action with an empty `preferredId` — `$1` has nothing to encode.
3098
- *
3099
- * Table/rows-level navigate actions carry no `$1` placeholder and return
3100
- * `action.value` verbatim.
3101
- *
3102
- * A delegated action (`action.idMap`, since 0.1.147) reads `id` as one of THIS
3103
- * table's rows (or identifiers) and encodes the owner's identification it maps
3104
- * to, in `Object.keys(idMap)` order — the same as `Client`. A row the map
3105
- * cannot address (a missing path) has no link.
3106
- */
3107
- function navigateHrefFor(action, id, preferredId) {
3108
- if (action.processor !== "navigate") return void 0;
3109
- if (action.level !== "row") return action.value;
3110
- if (id === void 0) return void 0;
3111
- if (action.idMap) {
3112
- let mapped;
3113
- try {
3114
- mapped = actionIdentifier(action, id, []);
3115
- } catch {
3116
- return;
3117
- }
3118
- return action.value.replace(/\$1/g, encodeNavigateId(mapped, Object.keys(action.idMap)));
3119
- }
3120
- if (preferredId.length === 0) return void 0;
3121
- return action.value.replace(/\$1/g, encodeNavigateId(id, preferredId));
3122
- }
3123
- //#endregion
3124
- //#region src/nav/model-routes.ts
3125
- /**
3126
- * Derives navigable routes from DB-backed models' metadata.
3127
- *
3128
- * A model is included only when it is a DB entity (`@db.table`, `@db.view`,
3129
- * or `@db.view.for`) AND a path can be derived: `@db.http.path` first, then
3130
- * the string value of `@db.table` / `@db.view`, then the type's own id
3131
- * as-is. Models where none of these yield a non-empty path are omitted.
3132
- *
3133
- * Routes are sorted by `order` ascending (undefined last, ties keep input
3134
- * order). Hidden models are returned with `hidden: true` — filtering and
3135
- * grouping are left to the consumer.
3136
- */
3137
- function buildModelRoutes(models) {
3138
- const routes = [];
3139
- for (const model of models) {
3140
- const table = getFieldMeta(model, DB_TABLE);
3141
- const view = getFieldMeta(model, DB_VIEW);
3142
- const isView = view !== void 0 || hasFieldMeta(model, "db.view.for");
3143
- if (table === void 0 && !isView) continue;
3144
- const path = resolvePath(model, table, view);
3145
- if (path === void 0) continue;
3146
- const route = {
3147
- model,
3148
- path,
3149
- label: getFieldMeta(model, "meta.label") ?? humanizePath(path.slice(path.lastIndexOf("/") + 1)),
3150
- kind: isView ? "view" : "table"
3151
- };
3152
- const group = getFieldMeta(model, UI_NAV_GROUP);
3153
- if (typeof group === "string") route.group = group;
3154
- const order = getFieldMeta(model, UI_NAV_ORDER);
3155
- if (typeof order === "number") route.order = order;
3156
- if (getFieldMeta(model, "ui.nav.hidden") === true) route.hidden = true;
3157
- routes.push(route);
3158
- }
3159
- routes.sort((a, b) => {
3160
- const ao = a.order ?? Number.POSITIVE_INFINITY;
3161
- const bo = b.order ?? Number.POSITIVE_INFINITY;
3162
- return ao === bo ? 0 : ao - bo;
3163
- });
3164
- return routes;
3165
- }
3166
- /** `db.http.path` > string `db.table`/`db.view` name > type id — mirrors moost-db's controller prefix resolution, so the path matches the HTTP mount of a token-bound controller. */
3167
- function resolvePath(model, table, view) {
3168
- const http = getFieldMeta(model, DB_HTTP_PATH);
3169
- let raw;
3170
- if (typeof http === "string") raw = http;
3171
- else if (typeof table === "string") raw = table;
3172
- else if (typeof view === "string") raw = view;
3173
- else if (typeof model.id === "string") raw = model.id;
3174
- if (!raw) return void 0;
3175
- const path = raw.replace(/^\/+|\/+$/g, "");
3176
- return path.length > 0 ? path : void 0;
3177
- }
3178
- //#endregion
3179
- export { DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, EXPECT_MAX_LENGTH, FORM_ERROR_KEY, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, NUMERIC_VALUE_KINDS, StaticFieldResolver, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaCacheIdentity, getMetaEntry, getMetaTableDef, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isContainerKind, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, onMetaCacheReset, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, retainMetaEntry, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setMetaCacheMaxEntries, setResolver, setValueHelpCacheTtl, splitDecimalString, str, unionVariantChanged, validatorErrorsToMap, valueHelpDictPaths };
1
+ import { DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, EXPECT_MAX_LENGTH, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, WF_ACTION_WITH_DATA } from "./shared/annotation-keys.mjs";
2
+ import { isArrayField, isObjectField, isTupleField, isUnionField } from "./form/types.mjs";
3
+ import { StaticFieldResolver, asArray, defaultResolver, getFieldMeta, getResolver, hasComputedAnnotations, hasFieldMeta, isFieldHidden, parseStaticAttrs, resolveAttrs, resolveFieldProp, resolveFormProp, resolveStatic, setResolver } from "./shared/field-resolver.mjs";
4
+ import { extractFieldLiteralOptions, extractLiteralOptions, isPureLiteralUnion } from "./value-help/extract-literals.mjs";
5
+ import { extractValueHelp } from "./value-help/extract-ref.mjs";
6
+ import { deepClone } from "./form/clone.mjs";
7
+ import { createFormData, createFormValueResolver, deleteByPath, detectUnionVariant, getByPath, joinPath, setByPath } from "./form/path-utils.mjs";
8
+ import { omitSkippedNavFields } from "./form/skipped-nav.mjs";
9
+ import { buildUnionVariants, createFormDef } from "./form/create-form-def.mjs";
10
+ import { getDeclaredFormActions } from "./form/form-actions.mjs";
11
+ import { valueHelpDictPaths } from "./value-help/dict-paths.mjs";
12
+ import { optKey, optLabel, optionLabel, parseStaticOptions, resolveOptions } from "./value-help/resolve-options.mjs";
13
+ import { escapeRegex, str } from "./shared/str.mjs";
14
+ import { ValueHelpClient, invalidateValueHelpCache, setValueHelpCacheTtl } from "./value-help/value-help-client.mjs";
15
+ import { fetchDistinctValues, isPickerDeclined } from "./value-help/distinct-client.mjs";
16
+ import { getDefaultClientFactory, resetDefaultClientFactory, setDefaultClientFactory } from "./client-factory.mjs";
17
+ import { extractMeasurement } from "./form/measurement.mjs";
18
+ import { createTableDef } from "./table/create-table-def.mjs";
19
+ import { getMetaCacheIdentity, getMetaEntry, getMetaTableDef, onMetaCacheReset, resetMetaCache, retainMetaEntry, setMetaCacheIdentity, setMetaCacheMaxEntries } from "./shared/meta-cache.mjs";
20
+ import { resetValueHelpCache, resolveValueHelp } from "./value-help/resolve.mjs";
21
+ import { FORM_ERROR_KEY, buildDescendantErrorCounts, iteratePathAncestors, mergeErrorMaps, omitPaths, validatorErrorsToMap } from "./form/error-utils.mjs";
22
+ import { createFieldValidator, getDefaultValidatorPlugins, getFormValidator, isContainerKind, setDefaultValidatorPlugins } from "./form/validate.mjs";
23
+ import { buildFormDiff, deepEqual } from "./form/diff.mjs";
24
+ import { collectDirtyPaths, isPathDirty } from "./form/dirty.mjs";
25
+ import { applyFormChanges } from "./form/apply.mjs";
26
+ import { buildFormRebase } from "./form/rebase.mjs";
27
+ import { unionVariantChanged } from "./form/union-detect.mjs";
28
+ import { DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, buildGridClasses, parseColSpan, parseRowSpan, resolveGridSpec } from "./form/grid.mjs";
29
+ import { resolveSingularLabel } from "./form/labels.mjs";
30
+ import { enforceScale, formatDecimalForDisplay, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getThousandsSeparator, groupInteger, joinDecimalString, parseDecimalInput, splitDecimalString } from "./form/decimal-format.mjs";
31
+ import { NUMERIC_VALUE_KINDS, optionValue } from "./table/value-kind.mjs";
32
+ import { getColumn, getFilterableColumns, getSortableColumns } from "./table/column-resolver.mjs";
33
+ import { navigateHrefFor } from "./table/navigate-href.mjs";
34
+ import { buildModelRoutes } from "./nav/model-routes.mjs";
35
+ export { DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, EXPECT_MAX_LENGTH, FORM_ERROR_KEY, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, NUMERIC_VALUE_KINDS, StaticFieldResolver, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaCacheIdentity, getMetaEntry, getMetaTableDef, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isContainerKind, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, omitSkippedNavFields, onMetaCacheReset, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, retainMetaEntry, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setMetaCacheMaxEntries, setResolver, setValueHelpCacheTtl, splitDecimalString, str, unionVariantChanged, validatorErrorsToMap, valueHelpDictPaths };