@atscript/ui 0.1.163 → 0.1.165

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 (164) hide show
  1. package/dist/client-factory.cjs +27 -0
  2. package/dist/client-factory.d.cts +58 -0
  3. package/dist/client-factory.d.mts +58 -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 +462 -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 +460 -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 +13 -0
  42. package/dist/form/labels.d.cts +11 -0
  43. package/dist/form/labels.d.mts +11 -0
  44. package/dist/form/labels.mjs +13 -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 +147 -0
  63. package/dist/form/types.d.mts +147 -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 +186 -0
  70. package/dist/form/validate.d.cts +81 -0
  71. package/dist/form/validate.d.mts +81 -0
  72. package/dist/form/validate.mjs +182 -0
  73. package/dist/i18n/ui-texts.cjs +135 -0
  74. package/dist/i18n/ui-texts.d.cts +81 -0
  75. package/dist/i18n/ui-texts.d.mts +81 -0
  76. package/dist/i18n/ui-texts.mjs +132 -0
  77. package/dist/index.cjs +223 -3360
  78. package/dist/index.d.cts +39 -1693
  79. package/dist/index.d.mts +39 -1693
  80. package/dist/index.mjs +36 -3179
  81. package/dist/messages.cjs +301 -0
  82. package/dist/messages.d.cts +302 -0
  83. package/dist/messages.d.mts +302 -0
  84. package/dist/messages.mjs +300 -0
  85. package/dist/nav/model-routes.cjs +59 -0
  86. package/dist/nav/model-routes.d.cts +33 -0
  87. package/dist/nav/model-routes.d.mts +33 -0
  88. package/dist/nav/model-routes.mjs +59 -0
  89. package/dist/plugin/annotations.cjs +592 -0
  90. package/dist/plugin/annotations.mjs +592 -0
  91. package/dist/plugin/primitives.cjs +30 -0
  92. package/dist/plugin/primitives.mjs +30 -0
  93. package/dist/plugin/value-help-validation.cjs +429 -0
  94. package/dist/plugin/value-help-validation.mjs +423 -0
  95. package/dist/plugin.cjs +4 -1001
  96. package/dist/plugin.mjs +2 -999
  97. package/dist/shared/annotation-keys.cjs +189 -0
  98. package/dist/shared/annotation-keys.d.cts +82 -0
  99. package/dist/shared/annotation-keys.d.mts +82 -0
  100. package/dist/shared/annotation-keys.mjs +97 -0
  101. package/dist/shared/field-resolver.cjs +123 -0
  102. package/dist/shared/field-resolver.d.cts +77 -0
  103. package/dist/shared/field-resolver.d.mts +77 -0
  104. package/dist/shared/field-resolver.mjs +110 -0
  105. package/dist/shared/meta-cache.cjs +282 -0
  106. package/dist/shared/meta-cache.d.cts +130 -0
  107. package/dist/shared/meta-cache.d.mts +130 -0
  108. package/dist/shared/meta-cache.mjs +275 -0
  109. package/dist/shared/str.cjs +19 -0
  110. package/dist/shared/str.d.cts +7 -0
  111. package/dist/shared/str.d.mts +7 -0
  112. package/dist/shared/str.mjs +17 -0
  113. package/dist/table/column-resolver.cjs +17 -0
  114. package/dist/table/column-resolver.d.cts +11 -0
  115. package/dist/table/column-resolver.d.mts +11 -0
  116. package/dist/table/column-resolver.mjs +15 -0
  117. package/dist/table/create-table-def.cjs +242 -0
  118. package/dist/table/create-table-def.d.cts +19 -0
  119. package/dist/table/create-table-def.d.mts +19 -0
  120. package/dist/table/create-table-def.mjs +242 -0
  121. package/dist/table/navigate-href.cjs +45 -0
  122. package/dist/table/navigate-href.d.cts +31 -0
  123. package/dist/table/navigate-href.d.mts +31 -0
  124. package/dist/table/navigate-href.mjs +45 -0
  125. package/dist/table/types.d.cts +290 -0
  126. package/dist/table/types.d.mts +290 -0
  127. package/dist/table/value-kind.cjs +20 -0
  128. package/dist/table/value-kind.d.cts +16 -0
  129. package/dist/table/value-kind.d.mts +16 -0
  130. package/dist/table/value-kind.mjs +19 -0
  131. package/dist/value-help/dict-paths.cjs +17 -0
  132. package/dist/value-help/dict-paths.d.cts +11 -0
  133. package/dist/value-help/dict-paths.d.mts +11 -0
  134. package/dist/value-help/dict-paths.mjs +17 -0
  135. package/dist/value-help/distinct-client.cjs +51 -0
  136. package/dist/value-help/distinct-client.d.cts +40 -0
  137. package/dist/value-help/distinct-client.d.mts +40 -0
  138. package/dist/value-help/distinct-client.mjs +50 -0
  139. package/dist/value-help/extract-literals.cjs +115 -0
  140. package/dist/value-help/extract-literals.d.cts +44 -0
  141. package/dist/value-help/extract-literals.d.mts +44 -0
  142. package/dist/value-help/extract-literals.mjs +111 -0
  143. package/dist/value-help/extract-ref.cjs +100 -0
  144. package/dist/value-help/extract-ref.d.cts +37 -0
  145. package/dist/value-help/extract-ref.d.mts +37 -0
  146. package/dist/value-help/extract-ref.mjs +100 -0
  147. package/dist/value-help/filter-tree.cjs +45 -0
  148. package/dist/value-help/filter-tree.mjs +45 -0
  149. package/dist/value-help/index.d.mts +8 -0
  150. package/dist/value-help/resolve-options.cjs +68 -0
  151. package/dist/value-help/resolve-options.d.cts +40 -0
  152. package/dist/value-help/resolve-options.d.mts +40 -0
  153. package/dist/value-help/resolve-options.mjs +64 -0
  154. package/dist/value-help/resolve.cjs +66 -0
  155. package/dist/value-help/resolve.d.cts +36 -0
  156. package/dist/value-help/resolve.d.mts +36 -0
  157. package/dist/value-help/resolve.mjs +65 -0
  158. package/dist/value-help/types.d.cts +41 -0
  159. package/dist/value-help/types.d.mts +41 -0
  160. package/dist/value-help/value-help-client.cjs +136 -0
  161. package/dist/value-help/value-help-client.d.cts +67 -0
  162. package/dist/value-help/value-help-client.d.mts +67 -0
  163. package/dist/value-help/value-help-client.mjs +134 -0
  164. package/package.json +15 -10
@@ -0,0 +1,458 @@
1
+ require("../shared/annotation-keys.cjs");
2
+ const require_types = require("./types.cjs");
3
+ const require_field_resolver = require("../shared/field-resolver.cjs");
4
+ const require_path_utils = require("./path-utils.cjs");
5
+ const require_skipped_nav = require("./skipped-nav.cjs");
6
+ const require_create_form_def = require("./create-form-def.cjs");
7
+ //#region src/form/diff.ts
8
+ /**
9
+ * Diffs a form's `current` data against its `baseline` snapshot, producing both
10
+ * a changed-fields list and an `@atscript/db` patch object.
11
+ *
12
+ * Both `baseline` and `current` are the WRAPPED form-data container
13
+ * (`{ value: domainData }`) so this reuses {@link getByPath}.
14
+ *
15
+ * Revert-aware: a value edited back to its baseline produces no change and no
16
+ * patch entry.
17
+ *
18
+ * Snapshot contract: the result is NOT a deep copy. `$insert` items, `$replace`
19
+ * arrays, scalar leaf values, and `changes[].before/after` all hold live
20
+ * references into `baseline` / `current`. Callers that keep editing the form
21
+ * after building the patch must snapshot first (e.g. build the patch at submit
22
+ * time on a frozen clone). This is the common Vue v-model flow.
23
+ */
24
+ function buildFormDiff(def, baseline, current, opts) {
25
+ const changes = [];
26
+ const patch = {};
27
+ if (require_skipped_nav.hasNestedSkippedNavFields(def)) {
28
+ baseline = {
29
+ ...baseline,
30
+ value: require_skipped_nav.omitSkippedNavFields(def, baseline.value)
31
+ };
32
+ current = {
33
+ ...current,
34
+ value: require_skipped_nav.omitSkippedNavFields(def, current.value)
35
+ };
36
+ }
37
+ const versionColumn = require_create_form_def.findVersionColumn(def.flatMap);
38
+ diffFields(def.fields, "", baseline, current, changes, patch, versionColumn, def.flatMap);
39
+ if ((opts?.cas ?? true) && versionColumn && Object.keys(patch).length > 0) {
40
+ const baselineVersion = require_path_utils.getByPath(baseline, versionColumn);
41
+ if (typeof baselineVersion === "number" && Number.isInteger(baselineVersion)) patch.$cas = { [versionColumn]: baselineVersion };
42
+ }
43
+ return {
44
+ isDirty: changes.length > 0,
45
+ changes,
46
+ patch
47
+ };
48
+ }
49
+ /**
50
+ * Diffs a list of sibling fields. `prefix` is the dot-path of the parent
51
+ * context relative to the form root (used only for the change list `path`);
52
+ * patch entries are written into the local `patch` object so callers can place
53
+ * the whole sub-object as a nested partial.
54
+ *
55
+ * `versionColumn` is the top-level `@db.column.version` field name (or
56
+ * undefined). When set, the matching top-level field is skipped entirely — it
57
+ * is server-managed and may only be round-tripped via `$cas`.
58
+ *
59
+ * `inlineFlatMap` is the form's `flatMap`, supplied only at the top-level walk.
60
+ * It lets {@link diffScalarField} read `@db.patch.strategy` off the object
61
+ * ancestors of an INLINED leaf (a dotted-path leaf with no `FormObjectFieldDef`
62
+ * node — `createFormDef` dissolves unlabelled objects into dot-paths). At a
63
+ * default (replace) ancestor the whole sub-object must be emitted. It is
64
+ * intentionally NOT propagated into `diffObjectField` recursion, where the
65
+ * strategy decision is already made per structured object.
66
+ */
67
+ function diffFields(fields, prefix, baseline, current, changes, patch, versionColumn, inlineFlatMap) {
68
+ for (const field of fields) {
69
+ if (field.path === "" && fields.length === 1) {
70
+ diffLeafRoot(field, baseline, current, changes, patch);
71
+ continue;
72
+ }
73
+ if (field.phantom || field.derived || versionColumn !== void 0 && !prefix && field.path === versionColumn) continue;
74
+ const fullPath = prefix ? `${prefix}.${field.path}` : field.path;
75
+ if (require_types.isArrayField(field)) {
76
+ diffArrayField(field, fullPath, baseline, current, changes, patch, inlineFlatMap);
77
+ continue;
78
+ }
79
+ if (require_types.isObjectField(field)) {
80
+ diffObjectField(field, fullPath, baseline, current, changes, patch);
81
+ continue;
82
+ }
83
+ diffScalarField(field, fullPath, baseline, current, changes, patch, inlineFlatMap);
84
+ }
85
+ }
86
+ /** Single-leaf root form (non-object root). Whole value is the patch. */
87
+ function diffLeafRoot(field, baseline, current, changes, patch) {
88
+ const before = require_path_utils.getByPath(baseline, "");
89
+ const after = require_path_utils.getByPath(current, "");
90
+ if (deepEqual(before, after)) return;
91
+ if (require_types.isArrayField(field)) {
92
+ const arrayPatch = diffArray(field, before, after);
93
+ if (arrayPatch === void 0) return;
94
+ changes.push({
95
+ path: "",
96
+ kind: "array",
97
+ before,
98
+ after
99
+ });
100
+ patch.value = arrayPatch;
101
+ } else {
102
+ changes.push({
103
+ path: "",
104
+ kind: "set",
105
+ before,
106
+ after
107
+ });
108
+ patch.value = after === void 0 ? null : after;
109
+ }
110
+ }
111
+ /** Scalar / union / tuple / ref field — whole-value compare; clear → null. */
112
+ function diffScalarField(field, fullPath, baseline, current, changes, patch, inlineFlatMap) {
113
+ const before = require_path_utils.getByPath(baseline, fullPath);
114
+ const after = require_path_utils.getByPath(current, fullPath);
115
+ if (deepEqual(before, after)) return;
116
+ changes.push({
117
+ path: fullPath,
118
+ kind: "set",
119
+ before,
120
+ after
121
+ });
122
+ if (setInlinedCutoff(field, fullPath, current, patch, inlineFlatMap)) return;
123
+ setPatchLeaf(patch, field.path, after === void 0 ? null : after);
124
+ }
125
+ /**
126
+ * Inlined-object replace cutoff: a dotted leaf came from an object that
127
+ * `createFormDef` dissolved into dot-paths. atscript-db's default nested
128
+ * strategy is `replace` (the whole sub-object must be present), and a
129
+ * `@db.json` object is stored as one value, so the whole sub-object is emitted
130
+ * at the SHALLOWEST such ancestor. Merge ancestors pass through (partial);
131
+ * `@db.column.version` exclusion already happened. Returns whether it did.
132
+ */
133
+ function setInlinedCutoff(field, fullPath, current, patch, inlineFlatMap) {
134
+ if (!inlineFlatMap || !field.path.includes(".")) return false;
135
+ const cutoff = inlinedReplaceCutoff(field.path, inlineFlatMap);
136
+ if (cutoff === void 0) return false;
137
+ const prefixLen = fullPath.length - field.path.length;
138
+ const sub = require_path_utils.getByPath(current, prefixLen > 0 ? fullPath.slice(0, prefixLen) + cutoff : cutoff);
139
+ setPatchLeaf(patch, cutoff, sub === void 0 ? null : sub);
140
+ return true;
141
+ }
142
+ /**
143
+ * For a dotted INLINED leaf path, returns the path of the shallowest object
144
+ * ancestor whose `@db.patch.strategy` is the default (`replace`) or that is
145
+ * `@db.json`, or undefined when every ancestor is a plain `merge` one (then the
146
+ * leaf partial is correct). At such an ancestor the whole sub-object must be
147
+ * present in the patch.
148
+ *
149
+ * Walks ancestor segments (`a`, `a.b`, … but not the leaf itself); the first
150
+ * one that is an object AND not merge is the cutoff. merge does NOT propagate,
151
+ * so a default-replace level below a merge level still cuts off there.
152
+ */
153
+ function inlinedReplaceCutoff(leafPath, flatMap) {
154
+ const segs = leafPath.split(".");
155
+ let acc = "";
156
+ for (let i = 0; i < segs.length - 1; i++) {
157
+ acc = acc ? `${acc}.${segs[i]}` : segs[i];
158
+ const prop = flatMap.get(acc);
159
+ if (!prop || prop.type.kind !== "object") continue;
160
+ if (!isMergePatched(prop)) return acc;
161
+ }
162
+ }
163
+ /**
164
+ * Inlined-or-structured object field — recurse, emit a nested partial OR the
165
+ * whole sub-object depending on the field's `@db.patch.strategy`.
166
+ *
167
+ * atscript-db's DEFAULT nested-object patch strategy is `replace` (strict —
168
+ * every required child must be present, else 400; omitted optionals are
169
+ * null-filled). A changed-leaves-only partial is a valid patch ONLY when the
170
+ * object field carries `@db.patch.strategy 'merge'`. For the default (replace)
171
+ * case we therefore emit the WHOLE current sub-object so the validator passes
172
+ * and no optional leaf is silently nulled. `merge` does NOT propagate, so a
173
+ * descendant object without its own `merge` again emits its full sub-object
174
+ * (handled by recursion — `diffFields` re-enters this function per child).
175
+ *
176
+ * Wholesale-clear: if the sub-object was a defined object in `baseline` but is
177
+ * now undefined/null, emit `field: null` (object removed) instead of a partial
178
+ * of nulled leaves.
179
+ */
180
+ function diffObjectField(field, fullPath, baseline, current, changes, patch) {
181
+ const beforeObj = require_path_utils.getByPath(baseline, fullPath);
182
+ const afterObj = require_path_utils.getByPath(current, fullPath);
183
+ if (!require_path_utils.isPlainObject(beforeObj) && !require_path_utils.isPlainObject(afterObj)) return;
184
+ const nested = {};
185
+ diffFields(field.objectDef.fields, fullPath, baseline, current, changes, nested, void 0, field.objectDef.flatMap);
186
+ if ((afterObj === void 0 || afterObj === null) && require_path_utils.isPlainObject(beforeObj)) {
187
+ setPatchLeaf(patch, field.path, null);
188
+ return;
189
+ }
190
+ if (Object.keys(nested).length === 0) return;
191
+ if (isMergePatched(field.prop)) setPatchLeaf(patch, field.path, nested);
192
+ else setPatchLeaf(patch, field.path, afterObj === void 0 ? null : afterObj);
193
+ }
194
+ /**
195
+ * Whether an object's patch may carry only its changed leaves: a
196
+ * `@db.patch.strategy 'merge'` object that is not `@db.json` (a JSON value is
197
+ * stored, and so replaced, whole).
198
+ */
199
+ function isMergePatched(prop) {
200
+ return require_field_resolver.getFieldMeta(prop, "db.patch.strategy") === "merge" && require_field_resolver.getFieldMeta(prop, "db.json") === void 0;
201
+ }
202
+ /**
203
+ * Array field — keyed → $update/$insert/$remove; unkeyed → $replace. A
204
+ * `@db.json` array is stored as one JSON value, which takes no array
205
+ * operations: it is sent whole (`null` when cleared). An array inside an
206
+ * inlined replace / `@db.json` object is sent with its whole sub-object, like
207
+ * any leaf there.
208
+ */
209
+ function diffArrayField(field, fullPath, baseline, current, changes, patch, inlineFlatMap) {
210
+ const before = require_path_utils.getByPath(baseline, fullPath);
211
+ const after = require_path_utils.getByPath(current, fullPath);
212
+ if (deepEqual(before, after)) return;
213
+ const value = require_field_resolver.getFieldMeta(field.prop, "db.json") !== void 0 ? after ?? null : diffArray(field, before, after);
214
+ if (value === void 0) return;
215
+ changes.push({
216
+ path: fullPath,
217
+ kind: "array",
218
+ before,
219
+ after
220
+ });
221
+ if (setInlinedCutoff(field, fullPath, current, patch, inlineFlatMap)) return;
222
+ setPatchLeaf(patch, field.path, value);
223
+ }
224
+ /**
225
+ * Produces a `TArrayPatch` value for one array field, or `undefined` when no
226
+ * real op results (the caller then skips the field entirely).
227
+ *
228
+ * - Keyed arrays (item object has `@expect.array.key`): emit `$update`
229
+ * (key + changed leaves), `$insert` (wholly-new items, whole), `$remove`
230
+ * (key only). Reorder-only (same key membership, same content, different
231
+ * order) → `$replace` (key-ops can't express a pure reorder).
232
+ * Ambiguous keys (duplicate or missing key values) → `$replace` (the only
233
+ * faithful op when key identity is unreliable).
234
+ * - Unkeyed object arrays / primitive arrays: `$replace` with the whole array.
235
+ * Primitive arrays with `@expect.array.uniqueItems` use by-value
236
+ * `$insert` / `$remove` (set semantics).
237
+ *
238
+ * Deliberate `$insert`-not-`$upsert`: wholly-new keyed items use `$insert`
239
+ * (pure append) rather than `$upsert`. This is safe because `$insert` is only
240
+ * ever used for keys ABSENT from baseline; existing keys go through `$update`.
241
+ * `$upsert` would dedupe-by-key, which we don't need given that invariant.
242
+ */
243
+ function diffArray(field, before, after) {
244
+ const beforeArr = Array.isArray(before) ? before : [];
245
+ const afterArr = Array.isArray(after) ? after : [];
246
+ const keyProps = getArrayKeyProps(field.itemType);
247
+ if (keyProps.length > 0) return diffKeyedArray(beforeArr, afterArr, keyProps);
248
+ if (require_field_resolver.getFieldMeta(field.prop, "expect.array.uniqueItems") !== void 0 && isPrimitiveItem(field)) {
249
+ const setPatch = diffUniqueArray(beforeArr, afterArr);
250
+ if (setPatch) return setPatch;
251
+ }
252
+ return { $replace: afterArr };
253
+ }
254
+ /**
255
+ * Keyed array diff. Reorder-only (same membership) falls back to $replace.
256
+ *
257
+ * Returns `undefined` when no $update/$insert/$remove op is produced (so the
258
+ * caller skips the field rather than emitting a malformed empty `{}`).
259
+ *
260
+ * Ambiguity fallback: if either side has DUPLICATE key buckets, or ANY element
261
+ * is missing all of its key values, key identity is unreliable — fall back to
262
+ * `{ $replace: after }`, the only faithful op (last-write-wins collapse would
263
+ * silently drop items, and a key-less `$update` is unmatchable by the DB).
264
+ */
265
+ function diffKeyedArray(before, after, keyProps) {
266
+ if (hasKeylessItem(before, keyProps) || hasKeylessItem(after, keyProps)) return { $replace: after };
267
+ const beforeByKey = /* @__PURE__ */ new Map();
268
+ for (const el of before) if (require_path_utils.isPlainObject(el)) beforeByKey.set(keyOf(el, keyProps), el);
269
+ const afterByKey = /* @__PURE__ */ new Map();
270
+ for (const el of after) if (require_path_utils.isPlainObject(el)) afterByKey.set(keyOf(el, keyProps), el);
271
+ if (beforeByKey.size !== before.length || afterByKey.size !== after.length) return { $replace: after };
272
+ const $insert = [];
273
+ const $update = [];
274
+ const $remove = [];
275
+ let contentChanged = false;
276
+ for (const [k, el] of afterByKey) {
277
+ const prev = beforeByKey.get(k);
278
+ if (prev === void 0) {
279
+ $insert.push(el);
280
+ continue;
281
+ }
282
+ if (!deepEqual(prev, el)) {
283
+ contentChanged = true;
284
+ const partial = buildKeyedUpdate(prev, el, keyProps);
285
+ if (partial) $update.push(partial);
286
+ }
287
+ }
288
+ if (beforeByKey.size === afterByKey.size && $insert.length === 0 && !contentChanged) return { $replace: after };
289
+ for (const [k, el] of beforeByKey) if (!afterByKey.has(k)) $remove.push(pickKeys(el, keyProps));
290
+ return arrayOps({
291
+ $update,
292
+ $insert,
293
+ $remove
294
+ });
295
+ }
296
+ /** Builds a `$update` partial: key fields + changed leaves only. */
297
+ function buildKeyedUpdate(prev, next, keyProps) {
298
+ const partial = {};
299
+ for (const k of keyProps) partial[k] = next[k];
300
+ let changed = false;
301
+ const allKeys = new Set([...Object.keys(prev), ...Object.keys(next)]);
302
+ for (const k of allKeys) {
303
+ if (keyProps.includes(k)) continue;
304
+ const a = prev[k];
305
+ const b = next[k];
306
+ if (!deepEqual(a, b)) {
307
+ partial[k] = b === void 0 ? null : b;
308
+ changed = true;
309
+ }
310
+ }
311
+ return changed ? partial : void 0;
312
+ }
313
+ /** Primitive uniqueItems set diff. Returns undefined if neither side differs. */
314
+ function diffUniqueArray(before, after) {
315
+ const beforeSet = new Set(before.map((v) => stableKey(v)));
316
+ const afterSet = new Set(after.map((v) => stableKey(v)));
317
+ const $insert = [];
318
+ const $remove = [];
319
+ const seenInsert = /* @__PURE__ */ new Set();
320
+ const seenRemove = /* @__PURE__ */ new Set();
321
+ for (const v of after) {
322
+ const k = stableKey(v);
323
+ if (!beforeSet.has(k) && !seenInsert.has(k)) {
324
+ $insert.push(v);
325
+ seenInsert.add(k);
326
+ }
327
+ }
328
+ for (const v of before) {
329
+ const k = stableKey(v);
330
+ if (!afterSet.has(k) && !seenRemove.has(k)) {
331
+ $remove.push(v);
332
+ seenRemove.add(k);
333
+ }
334
+ }
335
+ return arrayOps({
336
+ $insert,
337
+ $remove
338
+ });
339
+ }
340
+ /**
341
+ * Assembles a `TArrayPatch` from named op-arrays, dropping empty ones. Returns
342
+ * `undefined` when no op carries any item, so the caller skips the field rather
343
+ * than emitting a malformed empty `{}`.
344
+ */
345
+ function arrayOps(ops) {
346
+ const result = {};
347
+ for (const k in ops) if (ops[k].length > 0) result[k] = ops[k];
348
+ return Object.keys(result).length > 0 ? result : void 0;
349
+ }
350
+ /** Reads `@expect.array.key` props from an array item's object type. */
351
+ function getArrayKeyProps(itemType) {
352
+ if (itemType.type.kind !== "object") return [];
353
+ const props = itemType.type.props;
354
+ const keys = [];
355
+ for (const [name, prop] of props.entries()) if (require_field_resolver.getFieldMeta(prop, "expect.array.key") !== void 0) keys.push(name);
356
+ return keys;
357
+ }
358
+ /** True when the array's item type is a primitive (designType, kind === ''). */
359
+ function isPrimitiveItem(field) {
360
+ return field.itemType.type.kind === "";
361
+ }
362
+ /** True when any element lacks ALL of its key values (un-keyable identity). */
363
+ function hasKeylessItem(arr, keyProps) {
364
+ for (const el of arr) {
365
+ if (!require_path_utils.isPlainObject(el)) return true;
366
+ let hasAnyKey = false;
367
+ for (const k of keyProps) {
368
+ const v = el[k];
369
+ if (v !== void 0 && v !== null) {
370
+ hasAnyKey = true;
371
+ break;
372
+ }
373
+ }
374
+ if (!hasAnyKey) return true;
375
+ }
376
+ return false;
377
+ }
378
+ /** Composite key string for a keyed-array element. */
379
+ function keyOf(el, keyProps) {
380
+ if (keyProps.length === 1) return stableKey(el[keyProps[0]]);
381
+ return keyProps.map((k) => stableKey(el[k])).join(" ");
382
+ }
383
+ /** Picks only the key fields from an element (for $remove). */
384
+ function pickKeys(el, keyProps) {
385
+ const out = {};
386
+ for (const k of keyProps) out[k] = el[k];
387
+ return out;
388
+ }
389
+ /** Writes a value into a (possibly dotted) leaf path on a local patch object. */
390
+ function setPatchLeaf(patch, path, value) {
391
+ if (!path.includes(".")) {
392
+ patch[path] = value;
393
+ return;
394
+ }
395
+ const keys = path.split(".");
396
+ const last = keys.pop();
397
+ let cur = patch;
398
+ for (const k of keys) {
399
+ let next = cur[k];
400
+ if (next === void 0 || next === null || typeof next !== "object") {
401
+ next = {};
402
+ cur[k] = next;
403
+ }
404
+ cur = next;
405
+ }
406
+ cur[last] = value;
407
+ }
408
+ /**
409
+ * Stable string key for primitives / values (used for set membership).
410
+ *
411
+ * Key equality is TYPE-STRICT: a number `1` and a string `'1'` produce
412
+ * distinct keys, so a keyed-array item whose key changes JS representation
413
+ * between baseline and current is treated as a remove + insert. Callers that
414
+ * round-trip keys with loose typing should normalise the key type first.
415
+ */
416
+ function stableKey(v) {
417
+ if (typeof v === "string") return `s:${v}`;
418
+ if (typeof v === "number" || typeof v === "boolean") return `p:${String(v)}`;
419
+ if (v === null) return "null";
420
+ if (v === void 0) return "undef";
421
+ return `j:${JSON.stringify(v)}`;
422
+ }
423
+ /**
424
+ * Structural deep equality (order-sensitive for arrays). `NaN` equals `NaN`
425
+ * (revert-aware for NaN scalars) while `0` / `-0` stay equal (matches DB
426
+ * intent — `===` treats them equal, only NaN is special-cased).
427
+ *
428
+ * The single comparator shared across the form engine: diff, conflict
429
+ * detection ({@link buildFormRebase}), and apply all route through this — never
430
+ * reimplement equality elsewhere.
431
+ */
432
+ function deepEqual(a, b) {
433
+ if (a === b) return true;
434
+ if (typeof a === "number" && typeof b === "number") return Number.isNaN(a) && Number.isNaN(b);
435
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
436
+ if (typeof a !== "object" || typeof b !== "object") return false;
437
+ const aIsArr = Array.isArray(a);
438
+ const bIsArr = Array.isArray(b);
439
+ if (aIsArr !== bIsArr) return false;
440
+ if (aIsArr && bIsArr) {
441
+ if (a.length !== b.length) return false;
442
+ for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;
443
+ return true;
444
+ }
445
+ const ao = a;
446
+ const bo = b;
447
+ const aKeys = Object.keys(ao);
448
+ const bKeys = Object.keys(bo);
449
+ if (aKeys.length !== bKeys.length) return false;
450
+ for (const k of aKeys) {
451
+ if (!Object.prototype.hasOwnProperty.call(bo, k)) return false;
452
+ if (!deepEqual(ao[k], bo[k])) return false;
453
+ }
454
+ return true;
455
+ }
456
+ //#endregion
457
+ exports.buildFormDiff = buildFormDiff;
458
+ exports.deepEqual = deepEqual;
@@ -0,0 +1,80 @@
1
+ import { FormDef } from "./types.cjs";
2
+
3
+ //#region src/form/diff.d.ts
4
+ /**
5
+ * One field that differs between baseline and current.
6
+ *
7
+ * - `kind: 'set'` — scalar / object / union / tuple field whose value changed
8
+ * (including a clear-to-`null`). `before` / `after` are the whole values at
9
+ * `path`.
10
+ * - `kind: 'array'` — array field whose membership or item content changed.
11
+ * `before` / `after` are the whole arrays.
12
+ *
13
+ * NOTE: `before` / `after` hold live references into the supplied `baseline` /
14
+ * `current` containers — see {@link buildFormDiff} for the snapshot contract.
15
+ */
16
+ interface FormFieldChange {
17
+ /** Dot-separated path relative to the form root (matches FormFieldDef.path). */
18
+ path: string;
19
+ kind: "set" | "array";
20
+ before: unknown;
21
+ after: unknown;
22
+ }
23
+ /** Options for {@link buildFormDiff}. */
24
+ interface FormDiffOptions {
25
+ /**
26
+ * Optimistic-concurrency control. When `true` (default), a top-level
27
+ * `$cas: { [versionColumn]: baselineVersion }` sibling is auto-included in
28
+ * the patch whenever the form has a `@db.column.version` column AND the
29
+ * patch is non-empty AND a baseline version value exists. `false` suppresses
30
+ * it entirely.
31
+ *
32
+ * Independent of `$cas`, the `@db.column.version` column is ALWAYS excluded
33
+ * from the SET diff: it is server-managed, and a direct write to it is
34
+ * rejected by `@atscript/db` (`DbError('VERSION_COLUMN_WRITE')`). It is only
35
+ * ever round-tripped through `$cas`.
36
+ */
37
+ cas?: boolean;
38
+ }
39
+ /** Result of {@link buildFormDiff}. */
40
+ interface FormDiffResult {
41
+ /** True when at least one field changed (revert-aware). */
42
+ isDirty: boolean;
43
+ /** Per-field changes (revert-aware — reverted fields are absent). */
44
+ changes: FormFieldChange[];
45
+ /**
46
+ * `@atscript/db` patch object — flat, keyed by field name. Empty `{}` when
47
+ * nothing changed. Carries a top-level `$cas` sibling when `opts.cas` is on
48
+ * and a version column exists.
49
+ */
50
+ patch: Record<string, unknown>;
51
+ }
52
+ /**
53
+ * Diffs a form's `current` data against its `baseline` snapshot, producing both
54
+ * a changed-fields list and an `@atscript/db` patch object.
55
+ *
56
+ * Both `baseline` and `current` are the WRAPPED form-data container
57
+ * (`{ value: domainData }`) so this reuses {@link getByPath}.
58
+ *
59
+ * Revert-aware: a value edited back to its baseline produces no change and no
60
+ * patch entry.
61
+ *
62
+ * Snapshot contract: the result is NOT a deep copy. `$insert` items, `$replace`
63
+ * arrays, scalar leaf values, and `changes[].before/after` all hold live
64
+ * references into `baseline` / `current`. Callers that keep editing the form
65
+ * after building the patch must snapshot first (e.g. build the patch at submit
66
+ * time on a frozen clone). This is the common Vue v-model flow.
67
+ */
68
+ declare function buildFormDiff(def: FormDef, baseline: Record<string, unknown>, current: Record<string, unknown>, opts?: FormDiffOptions): FormDiffResult;
69
+ /**
70
+ * Structural deep equality (order-sensitive for arrays). `NaN` equals `NaN`
71
+ * (revert-aware for NaN scalars) while `0` / `-0` stay equal (matches DB
72
+ * intent — `===` treats them equal, only NaN is special-cased).
73
+ *
74
+ * The single comparator shared across the form engine: diff, conflict
75
+ * detection ({@link buildFormRebase}), and apply all route through this — never
76
+ * reimplement equality elsewhere.
77
+ */
78
+ declare function deepEqual(a: unknown, b: unknown): boolean;
79
+ //#endregion
80
+ export { FormDiffOptions, FormDiffResult, FormFieldChange, buildFormDiff, deepEqual };
@@ -0,0 +1,80 @@
1
+ import { FormDef } from "./types.mjs";
2
+
3
+ //#region src/form/diff.d.ts
4
+ /**
5
+ * One field that differs between baseline and current.
6
+ *
7
+ * - `kind: 'set'` — scalar / object / union / tuple field whose value changed
8
+ * (including a clear-to-`null`). `before` / `after` are the whole values at
9
+ * `path`.
10
+ * - `kind: 'array'` — array field whose membership or item content changed.
11
+ * `before` / `after` are the whole arrays.
12
+ *
13
+ * NOTE: `before` / `after` hold live references into the supplied `baseline` /
14
+ * `current` containers — see {@link buildFormDiff} for the snapshot contract.
15
+ */
16
+ interface FormFieldChange {
17
+ /** Dot-separated path relative to the form root (matches FormFieldDef.path). */
18
+ path: string;
19
+ kind: "set" | "array";
20
+ before: unknown;
21
+ after: unknown;
22
+ }
23
+ /** Options for {@link buildFormDiff}. */
24
+ interface FormDiffOptions {
25
+ /**
26
+ * Optimistic-concurrency control. When `true` (default), a top-level
27
+ * `$cas: { [versionColumn]: baselineVersion }` sibling is auto-included in
28
+ * the patch whenever the form has a `@db.column.version` column AND the
29
+ * patch is non-empty AND a baseline version value exists. `false` suppresses
30
+ * it entirely.
31
+ *
32
+ * Independent of `$cas`, the `@db.column.version` column is ALWAYS excluded
33
+ * from the SET diff: it is server-managed, and a direct write to it is
34
+ * rejected by `@atscript/db` (`DbError('VERSION_COLUMN_WRITE')`). It is only
35
+ * ever round-tripped through `$cas`.
36
+ */
37
+ cas?: boolean;
38
+ }
39
+ /** Result of {@link buildFormDiff}. */
40
+ interface FormDiffResult {
41
+ /** True when at least one field changed (revert-aware). */
42
+ isDirty: boolean;
43
+ /** Per-field changes (revert-aware — reverted fields are absent). */
44
+ changes: FormFieldChange[];
45
+ /**
46
+ * `@atscript/db` patch object — flat, keyed by field name. Empty `{}` when
47
+ * nothing changed. Carries a top-level `$cas` sibling when `opts.cas` is on
48
+ * and a version column exists.
49
+ */
50
+ patch: Record<string, unknown>;
51
+ }
52
+ /**
53
+ * Diffs a form's `current` data against its `baseline` snapshot, producing both
54
+ * a changed-fields list and an `@atscript/db` patch object.
55
+ *
56
+ * Both `baseline` and `current` are the WRAPPED form-data container
57
+ * (`{ value: domainData }`) so this reuses {@link getByPath}.
58
+ *
59
+ * Revert-aware: a value edited back to its baseline produces no change and no
60
+ * patch entry.
61
+ *
62
+ * Snapshot contract: the result is NOT a deep copy. `$insert` items, `$replace`
63
+ * arrays, scalar leaf values, and `changes[].before/after` all hold live
64
+ * references into `baseline` / `current`. Callers that keep editing the form
65
+ * after building the patch must snapshot first (e.g. build the patch at submit
66
+ * time on a frozen clone). This is the common Vue v-model flow.
67
+ */
68
+ declare function buildFormDiff(def: FormDef, baseline: Record<string, unknown>, current: Record<string, unknown>, opts?: FormDiffOptions): FormDiffResult;
69
+ /**
70
+ * Structural deep equality (order-sensitive for arrays). `NaN` equals `NaN`
71
+ * (revert-aware for NaN scalars) while `0` / `-0` stay equal (matches DB
72
+ * intent — `===` treats them equal, only NaN is special-cased).
73
+ *
74
+ * The single comparator shared across the form engine: diff, conflict
75
+ * detection ({@link buildFormRebase}), and apply all route through this — never
76
+ * reimplement equality elsewhere.
77
+ */
78
+ declare function deepEqual(a: unknown, b: unknown): boolean;
79
+ //#endregion
80
+ export { FormDiffOptions, FormDiffResult, FormFieldChange, buildFormDiff, deepEqual };