@azx-pbc/axiom-builder 0.0.0-stage → 0.0.6

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 (231) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +648 -2
  3. package/dist/cards/selectors.d.ts +70 -0
  4. package/dist/cards/selectors.d.ts.map +1 -0
  5. package/dist/cards/selectors.js +194 -0
  6. package/dist/cards/selectors.js.map +1 -0
  7. package/dist/definition.d.ts +36 -0
  8. package/dist/definition.d.ts.map +1 -0
  9. package/dist/definition.js +48 -0
  10. package/dist/definition.js.map +1 -0
  11. package/dist/evidence/cases.d.ts +44 -0
  12. package/dist/evidence/cases.d.ts.map +1 -0
  13. package/dist/evidence/cases.js +578 -0
  14. package/dist/evidence/cases.js.map +1 -0
  15. package/dist/evidence/repairs.d.ts +99 -0
  16. package/dist/evidence/repairs.d.ts.map +1 -0
  17. package/dist/evidence/repairs.js +181 -0
  18. package/dist/evidence/repairs.js.map +1 -0
  19. package/dist/evidence/summary.d.ts +35 -0
  20. package/dist/evidence/summary.d.ts.map +1 -0
  21. package/dist/evidence/summary.js +38 -0
  22. package/dist/evidence/summary.js.map +1 -0
  23. package/dist/i18n/gaps.d.ts +3 -0
  24. package/dist/i18n/gaps.d.ts.map +1 -0
  25. package/dist/i18n/gaps.js +2 -0
  26. package/dist/i18n/gaps.js.map +1 -0
  27. package/dist/i18n/message-slots.d.ts +19 -0
  28. package/dist/i18n/message-slots.d.ts.map +1 -0
  29. package/dist/i18n/message-slots.js +101 -0
  30. package/dist/i18n/message-slots.js.map +1 -0
  31. package/dist/i18n/text-locale.d.ts +13 -0
  32. package/dist/i18n/text-locale.d.ts.map +1 -0
  33. package/dist/i18n/text-locale.js +14 -0
  34. package/dist/i18n/text-locale.js.map +1 -0
  35. package/dist/i18n/translations.d.ts +56 -0
  36. package/dist/i18n/translations.d.ts.map +1 -0
  37. package/dist/i18n/translations.js +103 -0
  38. package/dist/i18n/translations.js.map +1 -0
  39. package/dist/impact/references.d.ts +143 -0
  40. package/dist/impact/references.d.ts.map +1 -0
  41. package/dist/impact/references.js +429 -0
  42. package/dist/impact/references.js.map +1 -0
  43. package/dist/index.d.ts +86 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +58 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/preview/compile-preview.d.ts +67 -0
  48. package/dist/preview/compile-preview.d.ts.map +1 -0
  49. package/dist/preview/compile-preview.js +286 -0
  50. package/dist/preview/compile-preview.js.map +1 -0
  51. package/dist/preview/handle.d.ts +119 -0
  52. package/dist/preview/handle.d.ts.map +1 -0
  53. package/dist/preview/handle.js +2 -0
  54. package/dist/preview/handle.js.map +1 -0
  55. package/dist/preview/held.d.ts +39 -0
  56. package/dist/preview/held.d.ts.map +1 -0
  57. package/dist/preview/held.js +15 -0
  58. package/dist/preview/held.js.map +1 -0
  59. package/dist/preview/measurement.d.ts +5 -0
  60. package/dist/preview/measurement.d.ts.map +1 -0
  61. package/dist/preview/measurement.js +18 -0
  62. package/dist/preview/measurement.js.map +1 -0
  63. package/dist/publish/build.d.ts +33 -0
  64. package/dist/publish/build.d.ts.map +1 -0
  65. package/dist/publish/build.js +15 -0
  66. package/dist/publish/build.js.map +1 -0
  67. package/dist/publish/diff.d.ts +208 -0
  68. package/dist/publish/diff.d.ts.map +1 -0
  69. package/dist/publish/diff.js +227 -0
  70. package/dist/publish/diff.js.map +1 -0
  71. package/dist/publish/review.d.ts +41 -0
  72. package/dist/publish/review.d.ts.map +1 -0
  73. package/dist/publish/review.js +22 -0
  74. package/dist/publish/review.js.map +1 -0
  75. package/dist/schema/dataset-input.d.ts +30 -0
  76. package/dist/schema/dataset-input.d.ts.map +1 -0
  77. package/dist/schema/dataset-input.js +58 -0
  78. package/dist/schema/dataset-input.js.map +1 -0
  79. package/dist/schema/dataset.d.ts +166 -0
  80. package/dist/schema/dataset.d.ts.map +1 -0
  81. package/dist/schema/dataset.js +281 -0
  82. package/dist/schema/dataset.js.map +1 -0
  83. package/dist/schema/declarations.d.ts +15 -0
  84. package/dist/schema/declarations.d.ts.map +1 -0
  85. package/dist/schema/declarations.js +47 -0
  86. package/dist/schema/declarations.js.map +1 -0
  87. package/dist/schema/document.d.ts +504 -0
  88. package/dist/schema/document.d.ts.map +1 -0
  89. package/dist/schema/document.js +337 -0
  90. package/dist/schema/document.js.map +1 -0
  91. package/dist/schema/error.d.ts +15 -0
  92. package/dist/schema/error.d.ts.map +1 -0
  93. package/dist/schema/error.js +18 -0
  94. package/dist/schema/error.js.map +1 -0
  95. package/dist/schema/field-id.d.ts +8 -0
  96. package/dist/schema/field-id.d.ts.map +1 -0
  97. package/dist/schema/field-id.js +47 -0
  98. package/dist/schema/field-id.js.map +1 -0
  99. package/dist/schema/layout.d.ts +118 -0
  100. package/dist/schema/layout.d.ts.map +1 -0
  101. package/dist/schema/layout.js +101 -0
  102. package/dist/schema/layout.js.map +1 -0
  103. package/dist/schema/palette.d.ts +103 -0
  104. package/dist/schema/palette.d.ts.map +1 -0
  105. package/dist/schema/palette.js +140 -0
  106. package/dist/schema/palette.js.map +1 -0
  107. package/dist/schema/read.d.ts +49 -0
  108. package/dist/schema/read.d.ts.map +1 -0
  109. package/dist/schema/read.js +942 -0
  110. package/dist/schema/read.js.map +1 -0
  111. package/dist/store/apply-dataset.d.ts +14 -0
  112. package/dist/store/apply-dataset.d.ts.map +1 -0
  113. package/dist/store/apply-dataset.js +513 -0
  114. package/dist/store/apply-dataset.js.map +1 -0
  115. package/dist/store/apply.d.ts +37 -0
  116. package/dist/store/apply.d.ts.map +1 -0
  117. package/dist/store/apply.js +2269 -0
  118. package/dist/store/apply.js.map +1 -0
  119. package/dist/store/candidate.d.ts +37 -0
  120. package/dist/store/candidate.d.ts.map +1 -0
  121. package/dist/store/candidate.js +178 -0
  122. package/dist/store/candidate.js.map +1 -0
  123. package/dist/store/commands/coverage.d.ts +58 -0
  124. package/dist/store/commands/coverage.d.ts.map +1 -0
  125. package/dist/store/commands/coverage.js +354 -0
  126. package/dist/store/commands/coverage.js.map +1 -0
  127. package/dist/store/commands/dataset.d.ts +26 -0
  128. package/dist/store/commands/dataset.d.ts.map +1 -0
  129. package/dist/store/commands/dataset.js +368 -0
  130. package/dist/store/commands/dataset.js.map +1 -0
  131. package/dist/store/commands/document.d.ts +21 -0
  132. package/dist/store/commands/document.d.ts.map +1 -0
  133. package/dist/store/commands/document.js +160 -0
  134. package/dist/store/commands/document.js.map +1 -0
  135. package/dist/store/commands/field.d.ts +32 -0
  136. package/dist/store/commands/field.d.ts.map +1 -0
  137. package/dist/store/commands/field.js +572 -0
  138. package/dist/store/commands/field.js.map +1 -0
  139. package/dist/store/commands/layout.d.ts +16 -0
  140. package/dist/store/commands/layout.d.ts.map +1 -0
  141. package/dist/store/commands/layout.js +70 -0
  142. package/dist/store/commands/layout.js.map +1 -0
  143. package/dist/store/commands/parse.d.ts +19 -0
  144. package/dist/store/commands/parse.d.ts.map +1 -0
  145. package/dist/store/commands/parse.js +328 -0
  146. package/dist/store/commands/parse.js.map +1 -0
  147. package/dist/store/commands/readers.d.ts +198 -0
  148. package/dist/store/commands/readers.d.ts.map +1 -0
  149. package/dist/store/commands/readers.js +711 -0
  150. package/dist/store/commands/readers.js.map +1 -0
  151. package/dist/store/commands/rule.d.ts +24 -0
  152. package/dist/store/commands/rule.d.ts.map +1 -0
  153. package/dist/store/commands/rule.js +379 -0
  154. package/dist/store/commands/rule.js.map +1 -0
  155. package/dist/store/commands/shapes.d.ts +900 -0
  156. package/dist/store/commands/shapes.d.ts.map +1 -0
  157. package/dist/store/commands/shapes.js +166 -0
  158. package/dist/store/commands/shapes.js.map +1 -0
  159. package/dist/store/commands/suggestions.d.ts +37 -0
  160. package/dist/store/commands/suggestions.d.ts.map +1 -0
  161. package/dist/store/commands/suggestions.js +177 -0
  162. package/dist/store/commands/suggestions.js.map +1 -0
  163. package/dist/store/commands.d.ts +16 -0
  164. package/dist/store/commands.d.ts.map +1 -0
  165. package/dist/store/commands.js +13 -0
  166. package/dist/store/commands.js.map +1 -0
  167. package/dist/store/dataset-candidate.d.ts +33 -0
  168. package/dist/store/dataset-candidate.d.ts.map +1 -0
  169. package/dist/store/dataset-candidate.js +31 -0
  170. package/dist/store/dataset-candidate.js.map +1 -0
  171. package/dist/store/dataset-pin.d.ts +93 -0
  172. package/dist/store/dataset-pin.d.ts.map +1 -0
  173. package/dist/store/dataset-pin.js +86 -0
  174. package/dist/store/dataset-pin.js.map +1 -0
  175. package/dist/store/dataset-store.d.ts +96 -0
  176. package/dist/store/dataset-store.d.ts.map +1 -0
  177. package/dist/store/dataset-store.js +112 -0
  178. package/dist/store/dataset-store.js.map +1 -0
  179. package/dist/store/history.d.ts +149 -0
  180. package/dist/store/history.d.ts.map +1 -0
  181. package/dist/store/history.js +173 -0
  182. package/dist/store/history.js.map +1 -0
  183. package/dist/store/measurement.d.ts +5 -0
  184. package/dist/store/measurement.d.ts.map +1 -0
  185. package/dist/store/measurement.js +20 -0
  186. package/dist/store/measurement.js.map +1 -0
  187. package/dist/store/notify.d.ts +11 -0
  188. package/dist/store/notify.d.ts.map +1 -0
  189. package/dist/store/notify.js +26 -0
  190. package/dist/store/notify.js.map +1 -0
  191. package/dist/store/published.d.ts +50 -0
  192. package/dist/store/published.d.ts.map +1 -0
  193. package/dist/store/published.js +27 -0
  194. package/dist/store/published.js.map +1 -0
  195. package/dist/store/refusals.d.ts +175 -0
  196. package/dist/store/refusals.d.ts.map +1 -0
  197. package/dist/store/refusals.js +160 -0
  198. package/dist/store/refusals.js.map +1 -0
  199. package/dist/store/steps.d.ts +14 -0
  200. package/dist/store/steps.d.ts.map +1 -0
  201. package/dist/store/steps.js +124 -0
  202. package/dist/store/steps.js.map +1 -0
  203. package/dist/store/store.d.ts +142 -0
  204. package/dist/store/store.d.ts.map +1 -0
  205. package/dist/store/store.js +136 -0
  206. package/dist/store/store.js.map +1 -0
  207. package/dist/store/unchanged.d.ts +12 -0
  208. package/dist/store/unchanged.d.ts.map +1 -0
  209. package/dist/store/unchanged.js +35 -0
  210. package/dist/store/unchanged.js.map +1 -0
  211. package/dist/visual/emit.d.ts +21 -0
  212. package/dist/visual/emit.d.ts.map +1 -0
  213. package/dist/visual/emit.js +133 -0
  214. package/dist/visual/emit.js.map +1 -0
  215. package/dist/visual/parse.d.ts +32 -0
  216. package/dist/visual/parse.d.ts.map +1 -0
  217. package/dist/visual/parse.js +330 -0
  218. package/dist/visual/parse.js.map +1 -0
  219. package/dist/visual/project.d.ts +40 -0
  220. package/dist/visual/project.d.ts.map +1 -0
  221. package/dist/visual/project.js +349 -0
  222. package/dist/visual/project.js.map +1 -0
  223. package/dist/visual/represent.d.ts +50 -0
  224. package/dist/visual/represent.d.ts.map +1 -0
  225. package/dist/visual/represent.js +66 -0
  226. package/dist/visual/represent.js.map +1 -0
  227. package/dist/visual/vocabulary.d.ts +121 -0
  228. package/dist/visual/vocabulary.d.ts.map +1 -0
  229. package/dist/visual/vocabulary.js +32 -0
  230. package/dist/visual/vocabulary.js.map +1 -0
  231. package/package.json +52 -3
@@ -0,0 +1,2269 @@
1
+ import { declaredRuleOrigins } from '@azx-pbc/axiom-compiler';
2
+ import { assertNever, isRecord } from '@azx-pbc/axiom-runtime';
3
+ import { admitsLocale, authoredField, declaredMembers, fieldDeclarationMessageKeys, fieldMessageKey, gateItemMessageKey, optionAvailabilityMessageKey, optionMessageKey, ruleMessageKey, screenReasonMessageKey, suggestionMessageKey, titleMessageKey, undeclaredLocaleDetail, } from '../schema/document.js';
4
+ import { namedMessageKeyCounts, namedMessageKeys } from '../i18n/message-slots.js';
5
+ import { documentTextLocale } from '../i18n/text-locale.js';
6
+ import { importTranslations } from '../i18n/translations.js';
7
+ import { authoringRefusal } from './refusals.js';
8
+ import { representVisual } from '../visual/represent.js';
9
+ import { documentIndex } from '../schema/declarations.js';
10
+ import { OPTION_DOMAIN_CONTROLS } from '../schema/palette.js';
11
+ import { referencesOf } from '../impact/references.js';
12
+ import { unchanged } from './unchanged.js';
13
+ function refuse(code, path, detail) {
14
+ return { ok: false, refusal: authoringRefusal(code, path, detail) };
15
+ }
16
+ function applied(document, clamped = []) {
17
+ return { ok: true, applied: { document, clamped } };
18
+ }
19
+ /**
20
+ * Why a declaration's control has nothing to offer, or `undefined` when it has a domain.
21
+ *
22
+ * A chooser asks the user to pick one of a declared set, and a rating or Likert scale reads its
23
+ * point count from the same domain; without a domain the control renders nothing the user can
24
+ * choose. The compiler refuses such a document, so the store refuses the command that would build
25
+ * one — at the command, with a repair that says which member to state, rather than letting the
26
+ * candidate gate report a compile code the author did not write.
27
+ */
28
+ function missingOptionDomain(fieldId, spec) {
29
+ const control = spec.control;
30
+ if (control === undefined)
31
+ return undefined;
32
+ if (!OPTION_DOMAIN_CONTROLS.has(control))
33
+ return undefined;
34
+ if ((spec.options?.length ?? 0) > 0 || spec.optionSource !== undefined)
35
+ return undefined;
36
+ return authoringRefusal('MISSING_OPTION_DOMAIN', '$.fields', `field \`${fieldId}\` declares control \`${control}\`, which offers a declared domain, but states neither \`options\` nor \`optionSource\`; add the field with the options it offers`);
37
+ }
38
+ /** The first member of a container tree whose control states no domain. */
39
+ function memberDomainRefusal(members) {
40
+ for (const member of members) {
41
+ if (member.kind === 'field') {
42
+ const refusal = missingOptionDomain(member.field.fieldId, member.field);
43
+ if (refusal !== undefined)
44
+ return refusal;
45
+ continue;
46
+ }
47
+ const nested = memberDomainRefusal(member.members);
48
+ if (nested !== undefined)
49
+ return nested;
50
+ }
51
+ return undefined;
52
+ }
53
+ /**
54
+ * A record declaration and its members' minted messages.
55
+ *
56
+ * `buildMember` and `addField` both author a record, so both build it here: the members are
57
+ * built against the record's own trail and the record carries no label of its own, because what
58
+ * a reader sees is its members' labels.
59
+ */
60
+ function recordFromSpec(recordId, members, trail) {
61
+ const built = members.map((member) => buildMember(member, [...trail, recordId]));
62
+ return {
63
+ field: {
64
+ fieldId: recordId,
65
+ primitive: 'record',
66
+ fields: built.map((entry) => entry.field),
67
+ },
68
+ messages: built.flatMap((entry) => entry.messages),
69
+ };
70
+ }
71
+ /**
72
+ * A declaration's value bounds, with the sentence each raises minted under the field's own key.
73
+ *
74
+ * A bound is presentation copy *and* the validate rule it compiles to, so the metaschema requires
75
+ * its sentence wherever the bound is stated. The store mints `field.<trail>.minimum` and
76
+ * `field.<trail>.maximum` from the field's trail exactly as it mints a label from `label`, so a
77
+ * caller states the author's words without deriving a key from an id it may not know.
78
+ */
79
+ function boundMembers(spec, key) {
80
+ const messages = [];
81
+ const bound = {};
82
+ const minimumKey = `${key}.minimum`;
83
+ if (spec.minimum !== undefined) {
84
+ bound.minimum = spec.minimum;
85
+ if (spec.minimumMessage !== undefined) {
86
+ bound.minimumMessageKey = minimumKey;
87
+ messages.push([minimumKey, spec.minimumMessage]);
88
+ }
89
+ }
90
+ const maximumKey = `${key}.maximum`;
91
+ if (spec.maximum !== undefined) {
92
+ bound.maximum = spec.maximum;
93
+ if (spec.maximumMessage !== undefined) {
94
+ bound.maximumMessageKey = maximumKey;
95
+ messages.push([maximumKey, spec.maximumMessage]);
96
+ }
97
+ }
98
+ return { bound, messages };
99
+ }
100
+ /**
101
+ * A built declaration and its messages, with a domain carried to the item where it belongs: a
102
+ * `money`, `quantity` or `duration` array states its currency, scale, units or unit on the item
103
+ * declaration, because every element shares one domain.
104
+ */
105
+ function fieldFromSpec(spec, trail) {
106
+ if (spec.primitive === 'record') {
107
+ // A record states its own label like every other declaration `addField` authors; what it
108
+ // shows a reader is its members' labels, and a container title is the author's choice. A
109
+ // domain it states travels with it so the metaschema gets to refuse it.
110
+ const built = recordFromSpec(spec.fieldId, spec.members ?? [], trail);
111
+ const key = fieldMessageKey([...trail, spec.fieldId]);
112
+ const { bound, messages } = boundMembers(spec, key);
113
+ return {
114
+ field: {
115
+ ...built.field,
116
+ labelKey: key,
117
+ ...(spec.currency === undefined ? {} : { currency: spec.currency }),
118
+ ...(spec.scale === undefined ? {} : { scale: spec.scale }),
119
+ ...(spec.units === undefined ? {} : { units: spec.units }),
120
+ ...(spec.unit === undefined ? {} : { unit: spec.unit }),
121
+ ...(spec.step === undefined ? {} : { step: spec.step }),
122
+ ...bound,
123
+ ...(spec.covers === undefined ? {} : { covers: spec.covers }),
124
+ },
125
+ messages: [[key, spec.label], ...messages, ...built.messages],
126
+ };
127
+ }
128
+ const ownTrail = [...trail, spec.fieldId];
129
+ const key = fieldMessageKey(ownTrail);
130
+ const itemHoldsMoney = spec.items === 'money';
131
+ const itemHoldsQuantity = spec.items === 'quantity';
132
+ const itemHoldsDuration = spec.items === 'duration';
133
+ const item = spec.items === undefined
134
+ ? undefined
135
+ : {
136
+ primitive: spec.items,
137
+ ...(itemHoldsMoney && spec.currency !== undefined ? { currency: spec.currency } : {}),
138
+ ...(itemHoldsMoney && spec.scale !== undefined ? { scale: spec.scale } : {}),
139
+ ...(itemHoldsQuantity && spec.units !== undefined ? { units: spec.units } : {}),
140
+ ...(itemHoldsDuration && spec.unit !== undefined ? { unit: spec.unit } : {}),
141
+ };
142
+ const options = spec.options?.map((option) => ({
143
+ code: option.code,
144
+ labelKey: optionMessageKey(ownTrail, option.code),
145
+ }));
146
+ // A domain the field states belongs to the declaration that holds the value. The item that
147
+ // took it states it there, and only that member is suppressed on the field; a member the item
148
+ // did not take is written on the field, which is how the closed metaschema gets to refuse
149
+ // `currency`/`scale`/`units`/`unit` on a declaration that cannot hold them at the document path
150
+ // instead of the store dropping an author's mistake.
151
+ const { bound, messages: boundMessages } = boundMembers(spec, key);
152
+ return {
153
+ field: {
154
+ fieldId: spec.fieldId,
155
+ primitive: spec.primitive,
156
+ labelKey: key,
157
+ ...(spec.control === undefined ? {} : { control: spec.control }),
158
+ ...(itemHoldsMoney || spec.currency === undefined ? {} : { currency: spec.currency }),
159
+ ...(itemHoldsMoney || spec.scale === undefined ? {} : { scale: spec.scale }),
160
+ ...(itemHoldsQuantity || spec.units === undefined ? {} : { units: spec.units }),
161
+ ...(itemHoldsDuration || spec.unit === undefined ? {} : { unit: spec.unit }),
162
+ ...(spec.step === undefined ? {} : { step: spec.step }),
163
+ ...bound,
164
+ ...(item === undefined ? {} : { items: item }),
165
+ ...(spec.rowKey === undefined ? {} : { rowKey: spec.rowKey }),
166
+ ...(options === undefined ? {} : { options }),
167
+ ...(spec.optionSource === undefined ? {} : { optionSource: spec.optionSource }),
168
+ ...(spec.covers === undefined ? {} : { covers: spec.covers }),
169
+ ...(spec.annotations === undefined ? {} : { annotations: spec.annotations }),
170
+ },
171
+ messages: [
172
+ [key, spec.label],
173
+ ...boundMessages,
174
+ ...(spec.options ?? []).map((option) => [optionMessageKey(ownTrail, option.code), option.label]),
175
+ ],
176
+ };
177
+ }
178
+ function collidingKey(document, messages) {
179
+ const seen = new Set();
180
+ for (const [key] of messages) {
181
+ if (Object.hasOwn(document.messages, key))
182
+ return { key, scope: 'catalogue' };
183
+ if (seen.has(key))
184
+ return { key, scope: 'command' };
185
+ seen.add(key);
186
+ }
187
+ return undefined;
188
+ }
189
+ /** The refusal a minted-key collision earns, at the location the command would have written. */
190
+ function refuseCollision(collision, path) {
191
+ return refuse('DUPLICATE_ID', path, collision.scope === 'catalogue'
192
+ ? `the message key \`${collision.key}\` this command mints is already in the catalogue`
193
+ : `this command mints the message key \`${collision.key}\` twice; two ids, codes or labels that slug alike file one text`);
194
+ }
195
+ function buildMember(member, trail) {
196
+ switch (member.kind) {
197
+ case 'field':
198
+ return fieldFromSpec(member.field, trail);
199
+ case 'record':
200
+ return recordFromSpec(member.recordId, member.members, trail);
201
+ default:
202
+ return assertNever(member);
203
+ }
204
+ }
205
+ function withMintedText(document, minted) {
206
+ if (minted.length === 0)
207
+ return { ok: true, messages: document.messages };
208
+ const locale = documentTextLocale(document);
209
+ if (locale === undefined) {
210
+ return {
211
+ ok: false,
212
+ refusal: authoringRefusal('MALFORMED_COMMAND', '$.defaultLocale', 'the document declares no default locale, so a minted label has nowhere to be written; start it with `createEmptySchema` or declare `defaultLocale`'),
213
+ };
214
+ }
215
+ const next = { ...document.messages };
216
+ for (const [key, text] of minted) {
217
+ const entry = next[key] ?? {};
218
+ next[key] = { ...entry, [locale]: text };
219
+ }
220
+ return { ok: true, messages: next };
221
+ }
222
+ /** The layout node at `path`, narrowed to its members. */
223
+ function nodeAt(layout, path) {
224
+ let nodes = layout;
225
+ let found;
226
+ for (const step of path) {
227
+ const node = nodes[step];
228
+ if (node === undefined)
229
+ return undefined;
230
+ found = node;
231
+ const children = node['children'];
232
+ nodes = Array.isArray(children) ? children.filter(isRecord) : [];
233
+ }
234
+ return found;
235
+ }
236
+ /** The child nodes a layout node holds, as the read-only list the rewrite rebuilds. */
237
+ function childrenOf(node) {
238
+ const children = node['children'];
239
+ return Array.isArray(children) ? children.filter(isRecord) : [];
240
+ }
241
+ /**
242
+ * Every message key one layout node subtree names: its title, description and text, and each
243
+ * summary readout's label.
244
+ *
245
+ * These are exactly the slots `namedMessageKeys` counts through the compiler's `readLayout`, so a
246
+ * key this walk reports is one the removed subtree owned and no other member may keep alive.
247
+ */
248
+ function layoutNodeOwnedMessageKeys(node) {
249
+ const keys = [];
250
+ const visit = (current) => {
251
+ for (const member of ['titleKey', 'descriptionKey', 'textKey']) {
252
+ const key = current[member];
253
+ if (typeof key === 'string')
254
+ keys.push(key);
255
+ }
256
+ const readouts = current['readouts'];
257
+ if (Array.isArray(readouts)) {
258
+ for (const readout of readouts) {
259
+ if (!isRecord(readout))
260
+ continue;
261
+ const labelKey = readout['labelKey'];
262
+ if (typeof labelKey === 'string')
263
+ keys.push(labelKey);
264
+ }
265
+ }
266
+ for (const child of childrenOf(current))
267
+ visit(child);
268
+ };
269
+ visit(node);
270
+ return keys;
271
+ }
272
+ /**
273
+ * Whether a node holds a tree at all.
274
+ *
275
+ * A leaf kind (`field`, `heading`, `callout`, `divider`, `sop_block`, `summary_card`) admits no
276
+ * `children` member, and the closed metaschema requires the member on every kind that does hold
277
+ * one — so the node's own shape answers the question for every document the store can hold. A
278
+ * rewrite that wrote `children` onto a leaf would be a document the closed walk refuses.
279
+ */
280
+ function holdsChildren(node) {
281
+ return Array.isArray(node['children']);
282
+ }
283
+ /**
284
+ * A new layout tree with the node at `path` replaced by `update(node)`.
285
+ *
286
+ * The one walk both layout rewrites share: an index addresses a child of the record children a
287
+ * node holds (`childrenOf`), and a path that names no node answers `undefined` rather than a
288
+ * silently unchanged tree, so a caller can refuse with the path that missed. Every level above
289
+ * the target is rebuilt and every other subtree is shared with the tree before it.
290
+ */
291
+ function replaceLayoutNode(nodes, path, update) {
292
+ const [step, ...rest] = path;
293
+ if (step === undefined)
294
+ return undefined;
295
+ const node = nodes[step];
296
+ if (node === undefined)
297
+ return undefined;
298
+ const next = [...nodes];
299
+ if (rest.length === 0) {
300
+ next[step] = update(node);
301
+ return next;
302
+ }
303
+ const rebuilt = replaceLayoutNode(childrenOf(node), rest, update);
304
+ if (rebuilt === undefined)
305
+ return undefined;
306
+ next[step] = { ...node, children: rebuilt };
307
+ return next;
308
+ }
309
+ /**
310
+ * A new layout tree with `child` appended under `parent`, or at the top level when absent.
311
+ *
312
+ * A placement refuses rather than rewriting a node that cannot hold it: a leaf kind (`field`,
313
+ * `heading`, `callout`, `divider`, `sop_block`, `summary_card`) admits no `children` member, so
314
+ * writing one onto it would produce a document the closed layout grammar refuses at the top of a
315
+ * later stage. One answer here is what gives every placing command the same refusal for the same
316
+ * mistake.
317
+ */
318
+ function appendLayoutChild(layout, parent, child) {
319
+ const parentPath = parent === undefined || parent.length === 0 ? undefined : parent;
320
+ if (parentPath === undefined)
321
+ return { ok: true, layout: [...layout, child] };
322
+ const unknownParent = () => ({
323
+ ok: false,
324
+ refusal: authoringRefusal('UNKNOWN_LAYOUT', '$.layout', `the parent path ${JSON.stringify(parentPath)} names no layout node`),
325
+ });
326
+ const target = nodeAt(layout, parentPath);
327
+ if (target === undefined)
328
+ return unknownParent();
329
+ if (!holdsChildren(target)) {
330
+ return {
331
+ ok: false,
332
+ refusal: authoringRefusal('INVALID_LAYOUT', '$.layout', `the node at ${JSON.stringify(parentPath)} is a \`${String(target['kind'])}\`, which holds no children; add a section, group or step and place this node inside it`),
333
+ };
334
+ }
335
+ const placed = replaceLayoutNode(layout, parentPath, (node) => ({
336
+ ...node,
337
+ children: [...childrenOf(node), child],
338
+ }));
339
+ // Both walks read the same children, so a parent this one found is one that walk rebuilds. The
340
+ // arm stays because the alternative — returning the old tree — would report a lost placement as
341
+ // a success.
342
+ return placed === undefined ? unknownParent() : { ok: true, layout: placed };
343
+ }
344
+ /** The layout leaf one field addition places. */
345
+ function fieldLeaf(fieldId, colSpan) {
346
+ return { kind: 'field', fieldId, ...(colSpan === undefined ? {} : { colSpan }) };
347
+ }
348
+ /** A new fields list with one declaration replaced by id, rebuilding only the branch above it. */
349
+ function updateField(fields, fieldId, update) {
350
+ let changed = false;
351
+ const next = fields.map((field) => {
352
+ if (field.fieldId === fieldId) {
353
+ changed = true;
354
+ return update(field);
355
+ }
356
+ if (field.fields === undefined)
357
+ return field;
358
+ const members = updateField(field.fields, fieldId, update);
359
+ if (members === undefined)
360
+ return field;
361
+ changed = true;
362
+ return { ...field, fields: members };
363
+ });
364
+ return changed ? next : undefined;
365
+ }
366
+ function withUpdatedField(document, fieldId, update) {
367
+ return updateField(document.fields, fieldId, update);
368
+ }
369
+ /** The declaration at a document path, for a refusal that names where the addition would land. */
370
+ function additionPath(document) {
371
+ return `$.fields[${String(document.fields.length)}]`;
372
+ }
373
+ function addFieldToDocument(document, spec) {
374
+ if (authoredField(document, spec.fieldId) !== undefined) {
375
+ return refuse('DUPLICATE_ID', additionPath(document), `field \`${spec.fieldId}\` is already declared; a field id is unique across the document`);
376
+ }
377
+ const domain = missingOptionDomain(spec.fieldId, spec);
378
+ if (domain !== undefined)
379
+ return { ok: false, refusal: domain };
380
+ if (spec.members !== undefined) {
381
+ const memberDomain = memberDomainRefusal(spec.members);
382
+ if (memberDomain !== undefined)
383
+ return { ok: false, refusal: memberDomain };
384
+ }
385
+ const built = fieldFromSpec(spec, []);
386
+ const collision = collidingKey(document, built.messages);
387
+ if (collision !== undefined)
388
+ return refuseCollision(collision, additionPath(document));
389
+ let layout = document.layout;
390
+ if (spec.placement !== 'none') {
391
+ // `index` is the "immediately after the row I copied" contract; an absent index is the
392
+ // palette's append, which stays the default so no existing caller changes meaning.
393
+ const placement = spec.index === undefined
394
+ ? appendLayoutChild(document.layout, spec.parent, fieldLeaf(spec.fieldId, spec.colSpan))
395
+ : insertLayoutChild(document.layout, spec.parent, spec.index, fieldLeaf(spec.fieldId, spec.colSpan));
396
+ if (!placement.ok)
397
+ return placement;
398
+ layout = placement.layout;
399
+ }
400
+ const messages = withMintedText(document, built.messages);
401
+ if (!messages.ok)
402
+ return messages;
403
+ return applied({
404
+ ...document,
405
+ fields: [...document.fields, built.field],
406
+ layout,
407
+ messages: messages.messages,
408
+ });
409
+ }
410
+ /**
411
+ * The refusal a code names that a field's option domain does not declare.
412
+ *
413
+ * The detail states the domain the field does declare, so an author repairing the command reads
414
+ * the codes that exist rather than only the one that does not.
415
+ */
416
+ function unknownOption(fieldId, code, options) {
417
+ return authoringRefusal('UNKNOWN_OPTION', '$.fields', options.length === 0
418
+ ? `field \`${fieldId}\` declares no option domain, so it has no option \`${String(code)}\``
419
+ : `field \`${fieldId}\` declares no option \`${String(code)}\`; its domain is ${options.map((declared) => `\`${String(declared.code)}\``).join(', ')}`);
420
+ }
421
+ /**
422
+ * One alternative list as the document stores it.
423
+ *
424
+ * Each new label is minted from its text under the owner's own namespace. An unchanged label
425
+ * reuses its prior key, so a translated alternative keeps its sentence through edits and reorder;
426
+ * relabelling one rewrites one entry. A prior key another member also names stays theirs: matching
427
+ * its text would claim a shared sentence, and the edit would then refuse it as a foreign key even
428
+ * though the canonical key was free. The operations are the author's expressions as written: the
429
+ * compiler's parser is the authority on what each one means, and the store preserves an unfinished
430
+ * one as draft source.
431
+ *
432
+ * The list is stated by a parsed command, which has already refused an empty one, so nothing here
433
+ * can fail: a refusal this function invented would be a second authority on the same shape.
434
+ */
435
+ function buildSuggestions(document, specs, owner, prior) {
436
+ const suggestions = [];
437
+ const written = [];
438
+ const unmatched = [...prior];
439
+ const locale = documentTextLocale(document);
440
+ const keyCounts = namedMessageKeyCounts(document);
441
+ for (const spec of specs) {
442
+ // Text is the alternative's identity. Reuse the matching prior key, including one a
443
+ // hand-authored document chose, so an operation edit or reorder carries every translation.
444
+ const matchAt = locale === undefined
445
+ ? -1
446
+ : unmatched.findIndex((candidate) => keyCounts.get(candidate.labelKey) === 1 &&
447
+ document.messages[candidate.labelKey]?.[locale] === spec.label);
448
+ const match = matchAt === -1 ? undefined : unmatched.splice(matchAt, 1)[0];
449
+ const labelKey = match?.labelKey ?? suggestionMessageKey(owner, spec.label);
450
+ written.push([labelKey, spec.label]);
451
+ suggestions.push({ labelKey, operations: spec.operations });
452
+ }
453
+ return { suggestions, written };
454
+ }
455
+ /** One declared option with its availability replaced by `availability`, identity and label kept. */
456
+ function optionWithAvailability(option, availability) {
457
+ return {
458
+ code: option.code,
459
+ labelKey: option.labelKey,
460
+ ...(option.deprecated === undefined ? {} : { deprecated: option.deprecated }),
461
+ ...availability,
462
+ };
463
+ }
464
+ /** Every availability message key one declared option owns, excluding its identity label. */
465
+ function optionAvailabilityMessageKeys(option) {
466
+ return [
467
+ ...(option.unavailableMessageKey === undefined ? [] : [option.unavailableMessageKey]),
468
+ ...(option.suggests ?? []).map((suggestion) => suggestion.labelKey),
469
+ ];
470
+ }
471
+ /** Every message key one declared option owns: its label, its reason and its alternatives' labels. */
472
+ function optionOwnedMessageKeys(option) {
473
+ return [option.labelKey, ...optionAvailabilityMessageKeys(option)];
474
+ }
475
+ /**
476
+ * Every message key one declaration subtree owns.
477
+ *
478
+ * The canonical `field.<trail>` and `option.<trail>.<code>` names are included beside the keys the
479
+ * declaration actually states, because `namedMessageKeys` names both: a hand-authored document may
480
+ * file a label under a key it chose, while the derived name is still one this declaration owns.
481
+ */
482
+ function fieldOwnedMessageKeys(declaration) {
483
+ const keys = [];
484
+ const visit = (field, trail) => {
485
+ keys.push(fieldMessageKey(trail));
486
+ for (const key of [field.labelKey, field.descriptionKey, field.placeholderKey]) {
487
+ if (key !== undefined)
488
+ keys.push(key);
489
+ }
490
+ keys.push(...fieldDeclarationMessageKeys(field));
491
+ for (const option of field.options ?? []) {
492
+ keys.push(optionMessageKey(trail, option.code), ...optionOwnedMessageKeys(option));
493
+ }
494
+ for (const member of field.fields ?? [])
495
+ visit(member, [...trail, member.fieldId]);
496
+ };
497
+ visit(declaration.field, declaration.trail);
498
+ return keys;
499
+ }
500
+ /**
501
+ * One declared option's availability stated, replaced or cleared, `RULES-7.1.3`.
502
+ *
503
+ * The option keeps its code and its label: they are its identity, and a record, a rule or a
504
+ * signature names the code. Whether an option may be chosen is what a device evaluates, so a
505
+ * published declaration states its availability in a new edition instead.
506
+ */
507
+ function setOptionAvailabilityIn(document, command, published) {
508
+ const declaration = authoredField(document, command.fieldId);
509
+ if (declaration === undefined) {
510
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.fieldId}\` is not declared`);
511
+ }
512
+ const options = declaration.field.options ?? [];
513
+ const option = options.find((declared) => declared.code === command.code);
514
+ if (option === undefined) {
515
+ return { ok: false, refusal: unknownOption(command.fieldId, command.code, options) };
516
+ }
517
+ if (published.fields.has(command.fieldId)) {
518
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${command.fieldId}\` is published; a device already reads which of its options are available, so change availability in a new edition`);
519
+ }
520
+ const spec = command.availability;
521
+ const written = [];
522
+ let availability = {};
523
+ if (spec !== null) {
524
+ const keyCounts = namedMessageKeyCounts(document);
525
+ const priorReasonKey = option.unavailableMessageKey;
526
+ const reason = spec.reason === undefined
527
+ ? undefined
528
+ : {
529
+ // The option's reason is one stable slot. Reuse its imported key so an edit keeps
530
+ // every translation; a key another member also names is theirs, so this option moves
531
+ // to the canonical key rather than rewrite their sentence.
532
+ key: priorReasonKey !== undefined && keyCounts.get(priorReasonKey) === 1
533
+ ? priorReasonKey
534
+ : optionAvailabilityMessageKey(declaration.trail, command.code),
535
+ text: spec.reason,
536
+ };
537
+ if (reason !== undefined)
538
+ written.push([reason.key, reason.text]);
539
+ const built = spec.suggests === undefined
540
+ ? undefined
541
+ : buildSuggestions(document, spec.suggests, optionMessageKey(declaration.trail, command.code), option.suggests ?? []);
542
+ if (built !== undefined)
543
+ written.push(...built.written);
544
+ availability = {
545
+ availableWhen: spec.availableWhen,
546
+ ...(reason === undefined ? {} : { unavailableMessageKey: reason.key }),
547
+ ...(spec.params === undefined ? {} : { unavailableParams: spec.params }),
548
+ ...(built === undefined ? {} : { suggests: built.suggestions }),
549
+ };
550
+ }
551
+ // Availability keys this option already owns are not a collision, but its label is not being
552
+ // edited. Even a shared prior key stays protected when the label still names it.
553
+ const allowed = new Set(optionAvailabilityMessageKeys(option).filter((key) => key !== option.labelKey));
554
+ const collision = foreignKeyCollision(document, written, allowed);
555
+ if (collision !== undefined)
556
+ return refuseCollision(collision, '$.fields');
557
+ const fields = withUpdatedField(document, command.fieldId, (field) => ({
558
+ ...field,
559
+ options: (field.options ?? []).map((declared) => declared.code === command.code ? optionWithAvailability(declared, availability) : declared),
560
+ }));
561
+ if (fields === undefined) {
562
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.fieldId}\` is not declared`);
563
+ }
564
+ const messages = withMintedText(document, written);
565
+ if (!messages.ok)
566
+ return messages;
567
+ const nextDocument = { ...document, fields, messages: messages.messages };
568
+ // A key this option no longer names is dropped, so clearing an availability leaves no sentence
569
+ // behind; a key another declaration still names stays.
570
+ const stillNamed = namedMessageKeys(nextDocument);
571
+ const pruned = new Set(optionOwnedMessageKeys(option).filter((key) => !stillNamed.has(key)));
572
+ const next = { ...nextDocument, messages: withoutMessages(nextDocument, pruned) };
573
+ // A restated availability can be byte-identical, for example when the editor trims outer
574
+ // condition whitespace. The command returns the rebuilt tree and `applyCommand` hands back the
575
+ // current document when nothing moved, so a content-keyed preview keeps its artifact too.
576
+ return applied(next);
577
+ }
578
+ function addOptionToDocument(document, fieldId, code, label, published) {
579
+ const declaration = authoredField(document, fieldId);
580
+ if (declaration === undefined) {
581
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
582
+ }
583
+ const primitive = declaration.field.primitive;
584
+ const holdsOptions = primitive === 'string' ||
585
+ primitive === 'integer' ||
586
+ primitive === 'boolean' ||
587
+ primitive === 'array';
588
+ if (!holdsOptions) {
589
+ return refuse('MALFORMED_COMMAND', '$.fields', `field \`${fieldId}\` holds \`${primitive}\` values, so it declares no option domain`);
590
+ }
591
+ if (declaration.field.rowKey !== undefined) {
592
+ return refuse('MALFORMED_COMMAND', '$.fields', `array \`${fieldId}\` is identified by its \`rowKey\`, so its rows are values rather than an option domain; declare the domain when the array is added`);
593
+ }
594
+ if (published.fields.has(fieldId)) {
595
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${fieldId}\` is published; its options are part of what a device reads, so it cannot gain one`);
596
+ }
597
+ if ((declaration.field.options ?? []).some((option) => option.code === code)) {
598
+ return refuse('DUPLICATE_ID', '$.fields', `field \`${fieldId}\` already declares option \`${String(code)}\``);
599
+ }
600
+ const key = optionMessageKey(declaration.trail, code);
601
+ const minted = [[key, label]];
602
+ const collision = collidingKey(document, minted);
603
+ if (collision !== undefined)
604
+ return refuseCollision(collision, '$.fields');
605
+ const fields = withUpdatedField(document, fieldId, (field) => ({
606
+ ...field,
607
+ options: [...(field.options ?? []), { code, labelKey: key }],
608
+ }));
609
+ if (fields === undefined) {
610
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
611
+ }
612
+ const messages = withMintedText(document, minted);
613
+ if (!messages.ok)
614
+ return messages;
615
+ return applied({ ...document, fields, messages: messages.messages });
616
+ }
617
+ function addRuleToDocument(document, rule) {
618
+ const spec = rule.rule;
619
+ const targets = [
620
+ spec.fieldId,
621
+ spec.targetFieldId,
622
+ spec.overrideFieldId,
623
+ ...(spec.fieldIds ?? []),
624
+ ];
625
+ for (const fieldId of targets) {
626
+ if (fieldId === undefined)
627
+ continue;
628
+ const target = authoredField(document, fieldId);
629
+ if (target?.field.annotations?.['deprecated'] === true) {
630
+ return refuse('INVALID_STRUCTURE', '$.rules', `field \`${fieldId}\` is deprecated; a retired field cannot acquire a new rule`);
631
+ }
632
+ }
633
+ if ((document.rules ?? []).some((declared) => declared.ruleId === spec.ruleId)) {
634
+ return refuse('DUPLICATE_ID', `$.rules`, `rule \`${spec.ruleId}\` is already declared; a rule id is unique across the document`);
635
+ }
636
+ const target = { kind: spec.kind, scope: spec.scope, fieldId: spec.fieldId };
637
+ const stored = storeExpression(document, spec.expression, target);
638
+ if (!stored.ok)
639
+ return stored;
640
+ const minted = [];
641
+ const messageKey = spec.message === undefined ? undefined : ruleMessageKey(spec.ruleId);
642
+ if (messageKey !== undefined && spec.message !== undefined) {
643
+ minted.push([messageKey, spec.message]);
644
+ }
645
+ let gate;
646
+ if (spec.gate !== undefined) {
647
+ const items = [];
648
+ for (const item of spec.gate.items) {
649
+ const itemSource = storeExpression(document, item.expression, target);
650
+ if (!itemSource.ok)
651
+ return itemSource;
652
+ const itemKey = gateItemMessageKey(spec.ruleId, item.itemId);
653
+ minted.push([itemKey, item.message]);
654
+ items.push({
655
+ itemId: item.itemId,
656
+ expr: itemSource.source,
657
+ messageKey: itemKey,
658
+ ...(item.params === undefined ? {} : { params: item.params }),
659
+ });
660
+ }
661
+ const activeWhen = spec.gate.activeWhen === undefined
662
+ ? undefined
663
+ : storeExpression(document, spec.gate.activeWhen, target);
664
+ if (activeWhen !== undefined && !activeWhen.ok)
665
+ return activeWhen;
666
+ gate = {
667
+ items,
668
+ hard: spec.gate.hard,
669
+ ...(activeWhen === undefined || !activeWhen.ok ? {} : { activeWhen: activeWhen.source }),
670
+ ...(spec.gate.onReadOnlyError === undefined
671
+ ? {}
672
+ : { onReadOnlyError: spec.gate.onReadOnlyError }),
673
+ };
674
+ }
675
+ const referWhen = spec.referWhen === undefined
676
+ ? undefined
677
+ : storeExpression(document, spec.referWhen, { ...target, kind: 'screen' });
678
+ if (referWhen !== undefined && !referWhen.ok)
679
+ return referWhen;
680
+ const reasons = [];
681
+ for (const reason of spec.reasons ?? []) {
682
+ const when = storeExpression(document, reason.when, { ...target, kind: 'screen' });
683
+ if (!when.ok)
684
+ return when;
685
+ const reasonKey = screenReasonMessageKey(spec.ruleId, reason.code);
686
+ minted.push([reasonKey, reason.message]);
687
+ reasons.push({
688
+ code: reason.code,
689
+ messageKey: reasonKey,
690
+ when: when.source,
691
+ ...(reason.params === undefined ? {} : { params: reason.params }),
692
+ });
693
+ }
694
+ const builtSuggestions = spec.suggests === undefined
695
+ ? undefined
696
+ : buildSuggestions(document, spec.suggests, ruleMessageKey(spec.ruleId), []);
697
+ if (builtSuggestions !== undefined)
698
+ minted.push(...builtSuggestions.written);
699
+ const collision = collidingKey(document, minted);
700
+ if (collision !== undefined)
701
+ return refuseCollision(collision, '$.rules');
702
+ // A validate rule defaults to `block`: the metaschema requires it to state a severity, and a
703
+ // validation that only warns is a deliberate downgrade the author states.
704
+ const severity = spec.severity ?? (spec.kind === 'validate' ? 'block' : undefined);
705
+ const compiled = {
706
+ ruleId: spec.ruleId,
707
+ kind: spec.kind,
708
+ scope: spec.scope,
709
+ evaluateOn: spec.evaluateOn ?? 'client',
710
+ expr: stored.source,
711
+ ...(spec.note === undefined ? {} : { note: spec.note }),
712
+ ...(severity === undefined ? {} : { severity }),
713
+ ...(spec.fieldId === undefined ? {} : { fieldId: spec.fieldId }),
714
+ ...(spec.fieldIds === undefined ? {} : { fieldIds: spec.fieldIds }),
715
+ ...(spec.targetFieldId === undefined ? {} : { targetFieldId: spec.targetFieldId }),
716
+ ...(messageKey === undefined ? {} : { messageKey }),
717
+ ...(spec.params === undefined ? {} : { params: spec.params }),
718
+ ...(referWhen === undefined || !referWhen.ok ? {} : { referWhen: referWhen.source }),
719
+ ...(reasons.length === 0 ? {} : { reasons }),
720
+ ...(spec.overrideFieldId === undefined ? {} : { overrideFieldId: spec.overrideFieldId }),
721
+ ...(gate === undefined ? {} : { gate }),
722
+ ...(builtSuggestions === undefined ? {} : { suggests: builtSuggestions.suggestions }),
723
+ ...(spec.testCases === undefined ? {} : { testCases: spec.testCases }),
724
+ };
725
+ const messages = withMintedText(document, minted);
726
+ if (!messages.ok)
727
+ return messages;
728
+ return applied({
729
+ ...document,
730
+ rules: [...(document.rules ?? []), compiled],
731
+ messages: messages.messages,
732
+ // A document that declares a gate or a screen designates exactly one; the first one an
733
+ // author adds is the primary until `setPrimary` says otherwise.
734
+ ...(spec.kind === 'gate' && document.primaryGateId === undefined
735
+ ? { primaryGateId: spec.ruleId }
736
+ : {}),
737
+ ...(spec.kind === 'screen' && document.primaryScreenId === undefined
738
+ ? { primaryScreenId: spec.ruleId }
739
+ : {}),
740
+ });
741
+ }
742
+ /** A new rules list with one rule replaced by id. */
743
+ function withUpdatedRule(document, ruleId, update) {
744
+ const rules = document.rules ?? [];
745
+ const index = rules.findIndex((rule) => rule.ruleId === ruleId);
746
+ if (index < 0)
747
+ return undefined;
748
+ return rules.map((rule, at) => (at === index ? update(rule) : rule));
749
+ }
750
+ function addRuleTestCaseIn(document, command) {
751
+ const rule = (document.rules ?? []).find((declared) => declared.ruleId === command.ruleId);
752
+ if (rule === undefined) {
753
+ // A declaration compiles to a rule the document does not list, but the rule is in the
754
+ // artifact and the author may address it by id: the compiler says which declaration produced
755
+ // it, so the case lands in that declaration's evidence member instead of a rule entry.
756
+ const origin = declaredRuleOrigins(document).find((candidate) => candidate.ruleId === command.ruleId);
757
+ if (origin !== undefined)
758
+ return addDeclarationTestCaseIn(document, origin, command);
759
+ return refuse('UNKNOWN_RULE', '$.rules', `rule \`${command.ruleId}\` is not declared`);
760
+ }
761
+ if ((rule.testCases ?? []).some((testCase) => testCase.caseId === command.testCase.caseId)) {
762
+ return refuse('DUPLICATE_ID', '$.rules', `rule \`${command.ruleId}\` already embeds a case \`${command.testCase.caseId}\`; a case id identifies one vector`);
763
+ }
764
+ const rules = withUpdatedRule(document, command.ruleId, (declared) => ({
765
+ ...declared,
766
+ testCases: [...(declared.testCases ?? []), command.testCase],
767
+ }));
768
+ if (rules === undefined) {
769
+ return refuse('UNKNOWN_RULE', '$.rules', `rule \`${command.ruleId}\` is not declared`);
770
+ }
771
+ return applied({ ...document, rules });
772
+ }
773
+ /**
774
+ * One case appended to the evidence of a declaration-generated rule.
775
+ *
776
+ * The rule has no entry under `rules`, so its evidence lives on the declaration that produced
777
+ * it — the same member the compiler copies onto the rule. The origin is the compiler's, so the
778
+ * store cannot invent a generated rule or guess which member carries its cases.
779
+ */
780
+ function addDeclarationTestCaseIn(document, origin, command) {
781
+ const authored = authoredField(document, origin.fieldId);
782
+ if (authored === undefined) {
783
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${origin.fieldId}\` is not declared`);
784
+ }
785
+ const member = origin.evidenceMember;
786
+ const evidence = authored.field[member] ?? [];
787
+ if (evidence.some((testCase) => testCase.caseId === command.testCase.caseId)) {
788
+ return refuse('DUPLICATE_ID', origin.path, `field \`${origin.fieldId}\` already embeds a case \`${command.testCase.caseId}\` in \`${member}\`; a case id identifies one vector`);
789
+ }
790
+ const fields = withUpdatedField(document, origin.fieldId, (field) => ({
791
+ ...field,
792
+ [member]: [...(field[member] ?? []), command.testCase],
793
+ }));
794
+ if (fields === undefined) {
795
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${origin.fieldId}\` is not declared`);
796
+ }
797
+ return applied({ ...document, fields });
798
+ }
799
+ function expressionRefusal(code, detail) {
800
+ return { ok: false, refusal: authoringRefusal(code, '$.rules', detail) };
801
+ }
802
+ /**
803
+ * The source text one rule expression stores.
804
+ *
805
+ * The source arm stores the bytes it was given, so an advanced formula is never reprinted and a
806
+ * half-typed one is a draft as before. The visual arm is the vocabulary's: the form has to read
807
+ * back from this document at this rule's scope, and its text is the printer's canonical output,
808
+ * which is why the builder owns no second emitter. A `defaultCompute` expression is outside the
809
+ * vocabulary by definition — an author overrides a computed value — so it stores source only.
810
+ */
811
+ function storeExpression(document, expression, target) {
812
+ if (expression.mode === 'advanced')
813
+ return { ok: true, source: expression.source };
814
+ if (target.kind === 'defaultCompute') {
815
+ return expressionRefusal('UNREPRESENTABLE_EXPRESSION', 'a `defaultCompute` rule states its writer as source; the visual vocabulary has no form for a default writer');
816
+ }
817
+ const represented = representVisual(expression.visual, documentIndex(document), target.scope === 'item' ? target.fieldId : undefined);
818
+ return represented.ok
819
+ ? { ok: true, source: represented.source }
820
+ : expressionRefusal('UNREPRESENTABLE_EXPRESSION', represented.refusal.detail);
821
+ }
822
+ function setRuleExprIn(document, command) {
823
+ const rules = document.rules ?? [];
824
+ const index = rules.findIndex((rule) => rule.ruleId === command.ruleId);
825
+ const rule = rules[index];
826
+ if (rule === undefined) {
827
+ return refuse('UNKNOWN_RULE', '$.rules', `rule \`${command.ruleId}\` is not declared`);
828
+ }
829
+ const stored = storeExpression(document, command.expression, rule);
830
+ if (!stored.ok)
831
+ return stored;
832
+ return applied({
833
+ ...document,
834
+ rules: rules.map((declared, at) => at === index ? { ...declared, expr: stored.source } : declared),
835
+ });
836
+ }
837
+ function setRuleNoteIn(document, command) {
838
+ const rules = document.rules ?? [];
839
+ const index = rules.findIndex((rule) => rule.ruleId === command.ruleId);
840
+ if (index < 0) {
841
+ return refuse('UNKNOWN_RULE', '$.rules', `rule \`${command.ruleId}\` is not declared`);
842
+ }
843
+ return applied({
844
+ ...document,
845
+ rules: rules.map((declared, at) => at === index ? { ...declared, note: command.note } : declared),
846
+ });
847
+ }
848
+ /** Every message key one rule owns outside its alternatives. */
849
+ function ruleNonSuggestionMessageKeys(rule) {
850
+ return [
851
+ ...(rule.messageKey === undefined ? [] : [rule.messageKey]),
852
+ ...(rule.gate?.items ?? []).map((item) => item.messageKey),
853
+ ...(rule.reasons ?? []).map((reason) => reason.messageKey),
854
+ ];
855
+ }
856
+ /** Every message key one rule owns: its own text, its gate items, its screen reasons and its
857
+ * alternatives. */
858
+ function ruleOwnedMessageKeys(rule) {
859
+ return [
860
+ ...ruleNonSuggestionMessageKeys(rule),
861
+ ...(rule.suggests ?? []).map((suggestion) => suggestion.labelKey),
862
+ ];
863
+ }
864
+ /** The catalogue without the keys a rewrite dropped; an entry is never left empty. */
865
+ function withoutMessages(document, keys) {
866
+ if (keys.size === 0)
867
+ return document.messages;
868
+ const next = [];
869
+ for (const [key, entry] of Object.entries(document.messages)) {
870
+ if (!keys.has(key))
871
+ next.push([key, entry]);
872
+ }
873
+ return Object.fromEntries(next);
874
+ }
875
+ /**
876
+ * The message keys a rewrite minted that the catalogue already holds under another owner.
877
+ *
878
+ * Unlike `collidingKey`, a key the edited slot already owns is not a collision: an edited gate
879
+ * item keeps its id and therefore its key, and writing the author's new text under it is the
880
+ * edit. The allowed set is exactly the prior keys the command is entitled to rewrite; every
881
+ * unchanged slot's keys stay foreign.
882
+ */
883
+ function foreignKeyCollision(document, written, allowed) {
884
+ const seen = new Set();
885
+ for (const [key] of written) {
886
+ if (Object.hasOwn(document.messages, key) && !allowed.has(key)) {
887
+ return { key, scope: 'catalogue' };
888
+ }
889
+ if (seen.has(key))
890
+ return { key, scope: 'command' };
891
+ seen.add(key);
892
+ }
893
+ return undefined;
894
+ }
895
+ function buildGate(document, rule, spec, target) {
896
+ const prior = new Map((rule.gate?.items ?? []).map((item) => [item.itemId, item.messageKey]));
897
+ const items = [];
898
+ const written = [];
899
+ for (const item of spec.items) {
900
+ const itemSource = storeExpression(document, item.expression, target);
901
+ if (!itemSource.ok)
902
+ return itemSource;
903
+ const itemKey = prior.get(item.itemId) ?? gateItemMessageKey(rule.ruleId, item.itemId);
904
+ written.push([itemKey, item.message]);
905
+ items.push({
906
+ itemId: item.itemId,
907
+ expr: itemSource.source,
908
+ messageKey: itemKey,
909
+ ...(item.params === undefined ? {} : { params: item.params }),
910
+ });
911
+ }
912
+ let activeWhenSource;
913
+ if (spec.activeWhen !== undefined && spec.activeWhen !== null) {
914
+ const stored = storeExpression(document, spec.activeWhen, target);
915
+ if (!stored.ok)
916
+ return stored;
917
+ activeWhenSource = stored.source;
918
+ }
919
+ return {
920
+ ok: true,
921
+ gate: {
922
+ items,
923
+ hard: spec.hard,
924
+ ...(activeWhenSource === undefined ? {} : { activeWhen: activeWhenSource }),
925
+ ...(spec.onReadOnlyError === undefined || spec.onReadOnlyError === null
926
+ ? {}
927
+ : { onReadOnlyError: spec.onReadOnlyError }),
928
+ },
929
+ written,
930
+ };
931
+ }
932
+ /** The target fields an edit states, checked the way `addRule` checks them. */
933
+ function retiredTarget(document, rule) {
934
+ const targets = [
935
+ rule.fieldId,
936
+ rule.targetFieldId,
937
+ rule.overrideFieldId,
938
+ ...(rule.fieldIds ?? []),
939
+ ];
940
+ for (const fieldId of targets) {
941
+ if (typeof fieldId !== 'string')
942
+ continue;
943
+ if (authoredField(document, fieldId)?.field.annotations?.['deprecated'] === true)
944
+ return fieldId;
945
+ }
946
+ return undefined;
947
+ }
948
+ /**
949
+ * One rule after an edit: identity kept, each stated member replaced, `null` removed.
950
+ *
951
+ * A rule's kind, scope and id are not editable — a rule whose behaviour belongs to another kind is
952
+ * a second rule with its own id — so the edit cannot make two rules share an id. The result is
953
+ * still checked for uniqueness: that invariant is what a case, a gate override and a layout step
954
+ * rely on when they name the rule, and a command that could break it must not commit.
955
+ */
956
+ function editRuleIn(document, command) {
957
+ const rules = document.rules ?? [];
958
+ const index = rules.findIndex((rule) => rule.ruleId === command.ruleId);
959
+ const rule = rules[index];
960
+ if (rule === undefined) {
961
+ return refuse('UNKNOWN_RULE', '$.rules', `rule \`${command.ruleId}\` is not declared`);
962
+ }
963
+ const spec = command.rule;
964
+ const retired = retiredTarget(document, spec);
965
+ if (retired !== undefined) {
966
+ return refuse('INVALID_STRUCTURE', '$.rules', `field \`${retired}\` is deprecated; a retired field cannot acquire or change a rule`);
967
+ }
968
+ if (spec.gate !== undefined && rule.kind !== 'gate') {
969
+ return refuse('MALFORMED_COMMAND', '$.rules', `rule \`${rule.ruleId}\` is a \`${rule.kind}\`; only a \`gate\` rule states \`gate\``);
970
+ }
971
+ if (rule.kind === 'gate' && spec.gate === null) {
972
+ return refuse('MALFORMED_COMMAND', '$.rules', `rule \`${rule.ruleId}\` is a gate and states its items in \`gate\`; state the gate rather than removing it`);
973
+ }
974
+ if ((spec.reasons !== undefined || spec.referWhen !== undefined) && rule.kind !== 'screen') {
975
+ return refuse('MALFORMED_COMMAND', '$.rules', `rule \`${rule.ruleId}\` is a \`${rule.kind}\`; only a \`screen\` rule states \`reasons\` or \`referWhen\``);
976
+ }
977
+ if (spec.overrideFieldId !== undefined && rule.kind !== 'defaultCompute') {
978
+ return refuse('MALFORMED_COMMAND', '$.rules', `rule \`${rule.ruleId}\` is a \`${rule.kind}\`; only a \`defaultCompute\` rule states \`overrideFieldId\``);
979
+ }
980
+ if (spec.fieldIds !== undefined && spec.fieldIds !== null) {
981
+ if (rule.kind !== 'visible' && rule.kind !== 'enabled') {
982
+ return refuse('MALFORMED_COMMAND', '$.rules', `rule \`${rule.ruleId}\` is a \`${rule.kind}\`; only a \`visible\` or \`enabled\` rule decides \`fieldIds\``);
983
+ }
984
+ if (rule.scope !== 'record') {
985
+ return refuse('MALFORMED_COMMAND', '$.rules', 'a rule that names `fieldIds` is record-scoped; this rule is field-scoped');
986
+ }
987
+ }
988
+ const fieldId = editedMember(rule.fieldId, spec.fieldId);
989
+ const target = { kind: rule.kind, scope: rule.scope, fieldId };
990
+ const expr = spec.expression === undefined
991
+ ? { ok: true, source: rule.expr }
992
+ : storeExpression(document, spec.expression, target);
993
+ if (!expr.ok)
994
+ return expr;
995
+ const written = [];
996
+ let messageKey = rule.messageKey;
997
+ if (spec.message !== undefined) {
998
+ if (spec.message === null) {
999
+ if (rule.kind === 'validate' || rule.kind === 'gate' || rule.kind === 'screen') {
1000
+ return refuse('INVALID_STRUCTURE', '$.rules', `rule \`${rule.ruleId}\` is a \`${rule.kind}\` and states the text a reader sees; a rule that needs a message keeps its \`messageKey\``);
1001
+ }
1002
+ messageKey = undefined;
1003
+ }
1004
+ else {
1005
+ messageKey ??= ruleMessageKey(rule.ruleId);
1006
+ written.push([messageKey, spec.message]);
1007
+ }
1008
+ }
1009
+ let gate;
1010
+ if (spec.gate !== undefined && spec.gate !== null) {
1011
+ const built = buildGate(document, rule, spec.gate, target);
1012
+ if (!built.ok)
1013
+ return built;
1014
+ gate = built.gate;
1015
+ written.push(...built.written);
1016
+ }
1017
+ else if (spec.gate === undefined) {
1018
+ gate = rule.gate;
1019
+ }
1020
+ const priorReasonKeys = new Map((rule.reasons ?? []).map((reason) => [reason.code, reason.messageKey]));
1021
+ let reasons;
1022
+ if (spec.reasons !== undefined) {
1023
+ if (spec.reasons === null) {
1024
+ reasons = undefined;
1025
+ }
1026
+ else {
1027
+ const built = [];
1028
+ for (const reason of spec.reasons) {
1029
+ const when = storeExpression(document, reason.when, { ...target, kind: 'screen' });
1030
+ if (!when.ok)
1031
+ return when;
1032
+ const reasonKey = priorReasonKeys.get(reason.code) ?? screenReasonMessageKey(rule.ruleId, reason.code);
1033
+ written.push([reasonKey, reason.message]);
1034
+ built.push({
1035
+ code: reason.code,
1036
+ messageKey: reasonKey,
1037
+ when: when.source,
1038
+ ...(reason.params === undefined ? {} : { params: reason.params }),
1039
+ });
1040
+ }
1041
+ reasons = built;
1042
+ }
1043
+ }
1044
+ else {
1045
+ reasons = rule.reasons;
1046
+ }
1047
+ let suggests;
1048
+ if (spec.suggests === undefined) {
1049
+ suggests = rule.suggests;
1050
+ }
1051
+ else {
1052
+ // Both arms are the same malformed command on a rule that can never state a verdict:
1053
+ // clearing a list that cannot exist is no more meaningful than stating one.
1054
+ if (rule.kind !== 'validate') {
1055
+ return refuse('MALFORMED_COMMAND', '$.rules', `rule \`${rule.ruleId}\` is a \`${rule.kind}\`; only a \`validate\` rule offers alternatives, because the other kinds state a branch rather than a verdict`);
1056
+ }
1057
+ if (spec.suggests === null) {
1058
+ suggests = undefined;
1059
+ }
1060
+ else {
1061
+ const built = buildSuggestions(document, spec.suggests, ruleMessageKey(rule.ruleId), rule.suggests ?? []);
1062
+ written.push(...built.written);
1063
+ suggests = built.suggestions;
1064
+ }
1065
+ }
1066
+ let referWhen = rule.referWhen;
1067
+ if (spec.referWhen !== undefined) {
1068
+ if (spec.referWhen === null) {
1069
+ referWhen = undefined;
1070
+ }
1071
+ else {
1072
+ const stored = storeExpression(document, spec.referWhen, { ...target, kind: 'screen' });
1073
+ if (!stored.ok)
1074
+ return stored;
1075
+ referWhen = stored.source;
1076
+ }
1077
+ }
1078
+ // A prior key is reusable only by a slot this edit replaces. Keys belonging to an unchanged
1079
+ // slot stay foreign, including a key shared with the slot being edited, so no text is overwritten
1080
+ // by accident.
1081
+ const protectedKeys = new Set();
1082
+ if (spec.message === undefined && rule.messageKey !== undefined) {
1083
+ protectedKeys.add(rule.messageKey);
1084
+ }
1085
+ if (spec.gate === undefined) {
1086
+ for (const item of rule.gate?.items ?? [])
1087
+ protectedKeys.add(item.messageKey);
1088
+ }
1089
+ if (spec.reasons === undefined) {
1090
+ for (const reason of rule.reasons ?? [])
1091
+ protectedKeys.add(reason.messageKey);
1092
+ }
1093
+ if (spec.suggests === undefined) {
1094
+ for (const suggestion of rule.suggests ?? [])
1095
+ protectedKeys.add(suggestion.labelKey);
1096
+ }
1097
+ const allowed = new Set(ruleOwnedMessageKeys(rule).filter((key) => !protectedKeys.has(key)));
1098
+ const collision = foreignKeyCollision(document, written, allowed);
1099
+ if (collision !== undefined)
1100
+ return refuseCollision(collision, '$.rules');
1101
+ const severity = editedMember(rule.severity, spec.severity);
1102
+ if (severity === undefined && rule.kind === 'validate') {
1103
+ return refuse('INVALID_STRUCTURE', '$.rules', `rule \`${rule.ruleId}\` is a \`validate\` rule and states the severity of its verdict; the closed metaschema requires one`);
1104
+ }
1105
+ const fieldIds = spec.fieldIds === undefined ? rule.fieldIds : (spec.fieldIds ?? undefined);
1106
+ const targetFieldId = editedMember(rule.targetFieldId, spec.targetFieldId);
1107
+ const params = spec.params === undefined ? rule.params : (spec.params ?? undefined);
1108
+ const overrideFieldId = editedMember(rule.overrideFieldId, spec.overrideFieldId);
1109
+ const testCases = spec.testCases === undefined ? rule.testCases : (spec.testCases ?? undefined);
1110
+ const edited = {
1111
+ ruleId: rule.ruleId,
1112
+ kind: rule.kind,
1113
+ scope: rule.scope,
1114
+ evaluateOn: spec.evaluateOn ?? rule.evaluateOn,
1115
+ expr: expr.source,
1116
+ // A note documents why the rule exists, so an edit of any other member keeps it.
1117
+ ...(rule.note === undefined ? {} : { note: rule.note }),
1118
+ ...(severity === undefined ? {} : { severity }),
1119
+ ...(fieldId === undefined ? {} : { fieldId }),
1120
+ ...(fieldIds === undefined ? {} : { fieldIds }),
1121
+ ...(targetFieldId === undefined ? {} : { targetFieldId }),
1122
+ ...(messageKey === undefined ? {} : { messageKey }),
1123
+ ...(params === undefined ? {} : { params }),
1124
+ ...(referWhen === undefined ? {} : { referWhen }),
1125
+ ...(reasons === undefined ? {} : { reasons }),
1126
+ ...(overrideFieldId === undefined ? {} : { overrideFieldId }),
1127
+ ...(gate === undefined ? {} : { gate }),
1128
+ ...(suggests === undefined ? {} : { suggests }),
1129
+ ...(testCases === undefined ? {} : { testCases }),
1130
+ };
1131
+ const nextRules = rules.map((declared, at) => (at === index ? edited : declared));
1132
+ const ids = nextRules.map((declared) => declared.ruleId);
1133
+ if (new Set(ids).size !== ids.length) {
1134
+ return refuse('DUPLICATE_ID', '$.rules', 'the edit would declare two rules under one id');
1135
+ }
1136
+ const messages = withMintedText(document, written);
1137
+ if (!messages.ok)
1138
+ return messages;
1139
+ const nextDocument = {
1140
+ ...document,
1141
+ rules: nextRules,
1142
+ messages: messages.messages,
1143
+ };
1144
+ // A key another declaration or rule still names is not this edit's to remove, even when the
1145
+ // rule owned it too: two slots may share one catalogue entry in a hand-authored document.
1146
+ const stillNamed = namedMessageKeys(nextDocument);
1147
+ const pruned = new Set(ruleOwnedMessageKeys(rule).filter((key) => !stillNamed.has(key)));
1148
+ return applied({ ...nextDocument, messages: withoutMessages(nextDocument, pruned) });
1149
+ }
1150
+ /** One rule removed, with its own texts and the primary designation it held. */
1151
+ function removeRuleIn(document, ruleId, published) {
1152
+ const rules = document.rules ?? [];
1153
+ const rule = rules.find((declared) => declared.ruleId === ruleId);
1154
+ if (rule === undefined) {
1155
+ return refuse('UNKNOWN_RULE', '$.rules', `rule \`${ruleId}\` is not declared`);
1156
+ }
1157
+ if (published.rules.has(ruleId)) {
1158
+ return refuse('PUBLISHED_FIELD', '$.rules', `rule \`${ruleId}\` is published; a rule id is permanent, so a published rule is edited rather than removed`);
1159
+ }
1160
+ const nextRules = rules.filter((declared) => declared.ruleId !== ruleId);
1161
+ const nextOfKind = (kind) => nextRules.find((declared) => declared.kind === kind)?.ruleId;
1162
+ const { primaryGateId: priorGate, primaryScreenId: priorScreen, rules: _priorRules, ...rest } = document;
1163
+ const primaryGateId = priorGate === ruleId ? nextOfKind('gate') : priorGate;
1164
+ const primaryScreenId = priorScreen === ruleId ? nextOfKind('screen') : priorScreen;
1165
+ const nextDocument = {
1166
+ ...rest,
1167
+ ...(nextRules.length === 0 ? {} : { rules: nextRules }),
1168
+ ...(primaryGateId === undefined ? {} : { primaryGateId }),
1169
+ ...(primaryScreenId === undefined ? {} : { primaryScreenId }),
1170
+ };
1171
+ const stillNamed = namedMessageKeys(nextDocument);
1172
+ const pruned = new Set(ruleOwnedMessageKeys(rule).filter((key) => !stillNamed.has(key)));
1173
+ return applied({ ...nextDocument, messages: withoutMessages(document, pruned) });
1174
+ }
1175
+ function setMessageTextIn(document, messageKey, locale, text) {
1176
+ // A text is written for a slot the draft can render, or for an entry it already holds: an
1177
+ // unreachable key is invisible to every renderer and would reserve the slot against the
1178
+ // declaration that a typo was meant to name.
1179
+ if (!Object.hasOwn(document.messages, messageKey) &&
1180
+ !namedMessageKeys(document).has(messageKey)) {
1181
+ return refuse('UNKNOWN_MESSAGE', '$.messages', `message key \`${messageKey}\` is named by no declaration, rule or layout node in this draft`);
1182
+ }
1183
+ // A text is written in a locale the catalogue owns for the same reason: an entry under an
1184
+ // undeclared tag renders nowhere, and the compile reports it as `MESSAGE_LOCALE` on a document
1185
+ // the author did not mean to break. `importTranslations` states the same rule.
1186
+ if (!admitsLocale(document, locale)) {
1187
+ return refuse('UNDECLARED_LOCALE', '$.locales', undeclaredLocaleDetail(document, locale));
1188
+ }
1189
+ const entry = document.messages[messageKey] ?? {};
1190
+ return applied({
1191
+ ...document,
1192
+ messages: { ...document.messages, [messageKey]: { ...entry, [locale]: text } },
1193
+ });
1194
+ }
1195
+ /**
1196
+ * The document at a new edition.
1197
+ *
1198
+ * A version identifies an artifact: the same `schemaVersion` with different declarations is a
1199
+ * second artifact claiming to be the first, so the only move is forward. A published field's
1200
+ * retirement is what a new edition is for, and this is the command that states it.
1201
+ */
1202
+ function setSchemaVersionIn(document, schemaVersion) {
1203
+ if (schemaVersion <= document.schemaVersion) {
1204
+ return refuse('MALFORMED_COMMAND', '$.schemaVersion', `\`schemaVersion\` is ${String(schemaVersion)}; the draft already states ${String(document.schemaVersion)}, and an edition only moves forward`);
1205
+ }
1206
+ return applied({ ...document, schemaVersion });
1207
+ }
1208
+ function withoutFieldPlacements(nodes, fieldId) {
1209
+ let removed = false;
1210
+ const next = [];
1211
+ for (const node of nodes) {
1212
+ if (node['kind'] === 'field' && node['fieldId'] === fieldId) {
1213
+ removed = true;
1214
+ continue;
1215
+ }
1216
+ let rebuilt = node;
1217
+ const children = childrenOf(node);
1218
+ if (children.length > 0) {
1219
+ const stripped = withoutFieldPlacements(children, fieldId);
1220
+ if (stripped.removed) {
1221
+ removed = true;
1222
+ rebuilt = { ...rebuilt, children: stripped.nodes };
1223
+ }
1224
+ }
1225
+ const listed = node['fields'];
1226
+ if (Array.isArray(listed) && listed.some((entry) => entry === fieldId)) {
1227
+ removed = true;
1228
+ rebuilt = { ...rebuilt, fields: listed.filter((entry) => entry !== fieldId) };
1229
+ }
1230
+ next.push(rebuilt);
1231
+ }
1232
+ return { nodes: removed ? next : nodes, removed };
1233
+ }
1234
+ /**
1235
+ * One declaration marked retired, with every layout reference to it dropped.
1236
+ *
1237
+ * `deprecateField` keeps the declaration — `EVOL-3.1.2` forbids deleting a `fieldId` a published
1238
+ * revision states, and a recorded value stays readable under it — but a retired field is not one
1239
+ * the form presents any more, so its leaf (and a summary readout naming it) goes. The change is
1240
+ * presentation only: the behaviour identity does not see layout, so it publishes without an
1241
+ * edition.
1242
+ */
1243
+ function deprecateIn(document, fieldId) {
1244
+ const declaration = authoredField(document, fieldId);
1245
+ if (declaration === undefined) {
1246
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1247
+ }
1248
+ if (declaration.field.annotations?.['deprecated'] === true) {
1249
+ return refuse('ALREADY_DEPRECATED', '$.fields', `field \`${fieldId}\` is already deprecated`);
1250
+ }
1251
+ const fields = withUpdatedField(document, fieldId, (field) => ({
1252
+ ...field,
1253
+ annotations: { ...(field.annotations ?? {}), deprecated: true },
1254
+ }));
1255
+ if (fields === undefined) {
1256
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1257
+ }
1258
+ const stripped = withoutFieldPlacements(document.layout, fieldId);
1259
+ return applied({ ...document, fields, layout: stripped.nodes });
1260
+ }
1261
+ function addLayoutNodeTo(document, node, parent) {
1262
+ const placement = appendLayoutChild(document.layout, parent, node);
1263
+ if (!placement.ok)
1264
+ return placement;
1265
+ return applied({ ...document, layout: placement.layout });
1266
+ }
1267
+ /**
1268
+ * One field after an edit: the member an edit set, cleared, or left exactly as it was.
1269
+ *
1270
+ * `undefined` is "no opinion" and `null` is "remove it", so the two are the same value here and
1271
+ * the caller decides which by whether it spreads the result. An edit that states a member therefore
1272
+ * cannot be confused with one that states `null`.
1273
+ */
1274
+ function editedMember(current, edit) {
1275
+ return edit === undefined ? current : (edit ?? undefined);
1276
+ }
1277
+ function editFieldIn(document, fieldId, spec, published) {
1278
+ const declaration = authoredField(document, fieldId);
1279
+ if (declaration === undefined) {
1280
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1281
+ }
1282
+ // `descriptionKey` and `placeholderKey` are copy: the behaviour identity strips message text, so
1283
+ // `diffAgainstPublished` classifies a revision that moves only them as presentation-only. They
1284
+ // stay the author's on a published declaration for the same reason a message text does. Every
1285
+ // other member is what a device reads a value through, so it is refused.
1286
+ const rewrite = spec.control !== undefined || spec.onHide !== undefined || spec.annotations !== undefined;
1287
+ if (published.fields.has(fieldId) && rewrite) {
1288
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${fieldId}\` is published; a device reads its control, hiding policy and annotations, so retire it and add the declaration you need. Its help text and placeholder may still change.`);
1289
+ }
1290
+ const { control: priorControl, descriptionKey: priorDescription, placeholderKey: priorPlaceholder, onHide: priorOnHide, annotations: priorAnnotations, ...rest } = declaration.field;
1291
+ const control = editedMember(priorControl, spec.control);
1292
+ const descriptionKey = editedMember(priorDescription, spec.descriptionKey);
1293
+ const placeholderKey = editedMember(priorPlaceholder, spec.placeholderKey);
1294
+ const onHide = editedMember(priorOnHide, spec.onHide);
1295
+ const annotations = editedMember(priorAnnotations, spec.annotations);
1296
+ const fields = withUpdatedField(document, fieldId, () => ({
1297
+ ...rest,
1298
+ ...(control === undefined ? {} : { control }),
1299
+ ...(descriptionKey === undefined ? {} : { descriptionKey }),
1300
+ ...(placeholderKey === undefined ? {} : { placeholderKey }),
1301
+ ...(onHide === undefined ? {} : { onHide }),
1302
+ ...(annotations === undefined ? {} : { annotations }),
1303
+ }));
1304
+ if (fields === undefined) {
1305
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1306
+ }
1307
+ return applied({ ...document, fields });
1308
+ }
1309
+ /** Every declaration id in one field's subtree, the field itself first. */
1310
+ function subtreeIds(field) {
1311
+ return [field.fieldId, ...(field.fields ?? []).flatMap(subtreeIds)];
1312
+ }
1313
+ /** The first container in a field list that would declare no members, if a removal emptied one. */
1314
+ function emptiedContainer(fields) {
1315
+ for (const field of fields) {
1316
+ if (field.fields !== undefined) {
1317
+ if (field.fields.length === 0)
1318
+ return field.fieldId;
1319
+ const emptied = emptiedContainer(field.fields);
1320
+ if (emptied !== undefined)
1321
+ return emptied;
1322
+ }
1323
+ }
1324
+ return undefined;
1325
+ }
1326
+ /**
1327
+ * One declaration list without a field, or `undefined` when the field is not in it.
1328
+ *
1329
+ * A container's own members are searched too: a member is a declaration like any other, and the
1330
+ * store removes it from the record that holds it rather than rewriting the record.
1331
+ */
1332
+ function withoutField(fields, fieldId) {
1333
+ if (fields.some((field) => field.fieldId === fieldId)) {
1334
+ return fields.filter((field) => field.fieldId !== fieldId);
1335
+ }
1336
+ let removed = false;
1337
+ const next = fields.map((field) => {
1338
+ if (field.fields === undefined)
1339
+ return field;
1340
+ const members = withoutField(field.fields, fieldId);
1341
+ if (members === undefined)
1342
+ return field;
1343
+ removed = true;
1344
+ return { ...field, fields: members };
1345
+ });
1346
+ return removed ? next : undefined;
1347
+ }
1348
+ /**
1349
+ * Why nothing else may still name this declaration, or `undefined` when removal is safe.
1350
+ *
1351
+ * A field is a value's identity, so removal is only offered where no rule reads or targets it, no
1352
+ * signature covers it, no other field derives from it, and no expression slot is unreadable. The
1353
+ * layout references to the field are not an obstacle: they are what the same command strips. An
1354
+ * unparseable slot could read any field, so while one exists no removal is proven safe.
1355
+ */
1356
+ function removalObstacle(document, fieldIds) {
1357
+ for (const fieldId of fieldIds) {
1358
+ const references = referencesOf(document, fieldId);
1359
+ // A declaration's own conditions and alternatives are removed with it. Only a slot in a rule,
1360
+ // the layout or another declaration can be left behind to name the missing field.
1361
+ const ownedByRemovedField = (source, sourceId) => source === 'field' && fieldIds.includes(sourceId);
1362
+ const unreadable = references.unparseable.find((entry) => !ownedByRemovedField(entry.source, entry.sourceId));
1363
+ if (unreadable !== undefined) {
1364
+ return authoringRefusal('INVALID_STRUCTURE', unreadable.path, `\`${unreadable.path}\` holds an expression that does not parse, so no field is proven unreferenced; repair it before removing \`${fieldId}\``);
1365
+ }
1366
+ const read = references.dependencyReads.find((entry) => !ownedByRemovedField(entry.source, entry.sourceId));
1367
+ if (read !== undefined) {
1368
+ return authoringRefusal('INVALID_STRUCTURE', read.path, `\`${read.path}\` in \`${read.sourceId}\` reads \`${fieldId}\`; remove or rewrite that expression before removing the field`);
1369
+ }
1370
+ const reference = references.references.find((entry) => entry.kind !== 'layout_field' &&
1371
+ !(entry.sourceFieldId !== undefined && fieldIds.includes(entry.sourceFieldId)));
1372
+ if (reference !== undefined) {
1373
+ const rule = reference.ruleId === undefined ? '' : ` (rule \`${reference.ruleId}\`)`;
1374
+ return authoringRefusal('INVALID_STRUCTURE', reference.path, `\`${reference.path}\`${rule} still names \`${fieldId}\`; remove that reference before removing the field`);
1375
+ }
1376
+ }
1377
+ return undefined;
1378
+ }
1379
+ /**
1380
+ * Moves one option within its field's domain.
1381
+ *
1382
+ * The declaration keeps its identity, its codes and its labels; only the order of the members
1383
+ * changes, because presentation order is not part of a value. A code the domain does not declare
1384
+ * is refused rather than inserted, and the index is clamped as the layout move clamps its own.
1385
+ */
1386
+ function moveOptionIn(document, fieldId, code, index, published) {
1387
+ const declaration = authoredField(document, fieldId);
1388
+ if (declaration === undefined) {
1389
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1390
+ }
1391
+ const options = declaration.field.options ?? [];
1392
+ const from = options.findIndex((option) => option.code === code);
1393
+ if (from === -1) {
1394
+ return { ok: false, refusal: unknownOption(fieldId, code, options) };
1395
+ }
1396
+ if (published.fields.has(fieldId)) {
1397
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${fieldId}\` is published; its option domain is what a device reads a value against, so a published order is a new edition rather than an in-place move`);
1398
+ }
1399
+ const at = Math.min(Math.max(index, 0), options.length - 1);
1400
+ const moved = options[from];
1401
+ if (moved === undefined) {
1402
+ return refuse('UNKNOWN_OPTION', '$.fields', `field \`${fieldId}\` has no option to move`);
1403
+ }
1404
+ const without = options.filter((_option, position) => position !== from);
1405
+ const reordered = [...without.slice(0, at), moved, ...without.slice(at)];
1406
+ const fields = withUpdatedField(document, fieldId, (field) => ({
1407
+ ...field,
1408
+ options: reordered,
1409
+ }));
1410
+ if (fields === undefined) {
1411
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1412
+ }
1413
+ return applied({ ...document, fields });
1414
+ }
1415
+ /**
1416
+ * One declared field removed, with its layout leaves and summary readouts.
1417
+ *
1418
+ * The catalogue text the declaration minted goes with it: a label filed under a key nothing names
1419
+ * renders nowhere, ships in the compiled artifact's `messages`, and reserves that key against the
1420
+ * declaration a later add would mint. A key another declaration, rule or layout node still names
1421
+ * stays, exactly as `removeRuleIn` treats a shared slot. What is not kept is the declaration, which
1422
+ * is why a field the published baseline names is refused: `EVOL-3.1.2` carries a recorded value
1423
+ * only to a declaration both revisions state, so removing one would orphan stored values rather
1424
+ * than migrate them. The publish diff states the same refusal (`removal_forbidden`) if a document
1425
+ * reaches it another way.
1426
+ */
1427
+ function removeFieldIn(document, command, published) {
1428
+ const declaration = authoredField(document, command.fieldId);
1429
+ if (declaration === undefined) {
1430
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.fieldId}\` is not declared`);
1431
+ }
1432
+ if (published.fields.has(command.fieldId)) {
1433
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${command.fieldId}\` is published; a published declaration is retired with \`deprecateField\` so the values recorded under its id stay readable, rather than removed`);
1434
+ }
1435
+ const fields = withoutField(document.fields, command.fieldId);
1436
+ if (fields === undefined) {
1437
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.fieldId}\` is not declared`);
1438
+ }
1439
+ const emptied = emptiedContainer(fields);
1440
+ if (emptied !== undefined) {
1441
+ return refuse('INVALID_STRUCTURE', '$.fields', `removing \`${command.fieldId}\` would leave container \`${emptied}\` with no members, which the metaschema refuses; remove the container instead`);
1442
+ }
1443
+ const obstacle = removalObstacle(document, subtreeIds(declaration.field));
1444
+ if (obstacle !== undefined)
1445
+ return { ok: false, refusal: obstacle };
1446
+ const nextDocument = {
1447
+ ...document,
1448
+ fields,
1449
+ layout: withoutFieldPlacements(document.layout, command.fieldId).nodes,
1450
+ };
1451
+ // The declaration minted its own label, its members' labels and its options' sentences. A key
1452
+ // nothing else names is unreachable now, and leaving it would reserve the slot against the
1453
+ // declaration that repeats this id.
1454
+ const stillNamed = namedMessageKeys(nextDocument);
1455
+ const pruned = new Set(fieldOwnedMessageKeys(declaration).filter((key) => !stillNamed.has(key)));
1456
+ return applied({ ...nextDocument, messages: withoutMessages(nextDocument, pruned) });
1457
+ }
1458
+ /**
1459
+ * One declaration's value domain replaced, keeping its id, copy and placement.
1460
+ *
1461
+ * The field is not published (a device reads the old domain), is not a container (its members are
1462
+ * its declaration), and the command states the whole new domain, so no member of the old one can
1463
+ * survive into a shape the metaschema refuses. Declaration members that compiled into rules are
1464
+ * cleared because they belonged to the old domain; the label catalogue, help text, placeholder,
1465
+ * annotations, hiding policy and layout leaf stay, and an option code the new domain keeps keeps
1466
+ * what it states about itself.
1467
+ */
1468
+ function setFieldPrimitiveIn(document, command, published) {
1469
+ const declaration = authoredField(document, command.fieldId);
1470
+ if (declaration === undefined) {
1471
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.fieldId}\` is not declared`);
1472
+ }
1473
+ if (published.fields.has(command.fieldId)) {
1474
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${command.fieldId}\` is published; its value domain is what a device reads, so a published declaration is retired and a new one added rather than retyped`);
1475
+ }
1476
+ if (declaration.field.fields !== undefined) {
1477
+ return refuse('MALFORMED_COMMAND', '$.fields', `field \`${command.fieldId}\` is a container and its members are its declaration; remove it with \`removeField\` and add the new declaration instead`);
1478
+ }
1479
+ const spec = command.field;
1480
+ const domain = missingOptionDomain(command.fieldId, spec);
1481
+ if (domain !== undefined)
1482
+ return { ok: false, refusal: domain };
1483
+ const priorOptions = new Map((declaration.field.options ?? []).map((option) => [option.code, option]));
1484
+ const written = [];
1485
+ const options = spec.options?.map((option) => {
1486
+ // A code that survives the retype keeps everything it states about itself: its label, whether
1487
+ // it is retired, and the availability with the reason and the alternatives that belong to it.
1488
+ // The command restates the domain, not each code's metadata, so re-minting the option here
1489
+ // would delete what the author had written with no command left to say it again.
1490
+ const prior = priorOptions.get(option.code);
1491
+ if (prior !== undefined)
1492
+ return prior;
1493
+ const key = optionMessageKey(declaration.trail, option.code);
1494
+ written.push([key, option.label]);
1495
+ return { code: option.code, labelKey: key };
1496
+ });
1497
+ const collision = foreignKeyCollision(document, written, new Set([...priorOptions.values()].map((option) => option.labelKey)));
1498
+ if (collision !== undefined)
1499
+ return refuseCollision(collision, '$.fields');
1500
+ const covers = spec.covers ?? (spec.primitive === 'signature_ref' ? declaration.field.covers : undefined);
1501
+ if (spec.primitive === 'signature_ref' && (covers === undefined || covers.length === 0)) {
1502
+ return refuse('MALFORMED_COMMAND', '$.fields', `field \`${command.fieldId}\` becomes a \`signature_ref\`; state \`covers\`, the fields its signature signs, because a capture that binds nothing does not compile`);
1503
+ }
1504
+ const { labelKey: priorLabel, descriptionKey: priorDescription, placeholderKey: priorPlaceholder, onHide: priorOnHide, annotations: priorAnnotations, } = declaration.field;
1505
+ const itemHoldsMoney = spec.items === 'money';
1506
+ const itemHoldsQuantity = spec.items === 'quantity';
1507
+ const itemHoldsDuration = spec.items === 'duration';
1508
+ const item = spec.items === undefined
1509
+ ? undefined
1510
+ : {
1511
+ primitive: spec.items,
1512
+ ...(itemHoldsMoney && spec.currency !== undefined ? { currency: spec.currency } : {}),
1513
+ ...(itemHoldsMoney && spec.scale !== undefined ? { scale: spec.scale } : {}),
1514
+ ...(itemHoldsQuantity && spec.units !== undefined ? { units: spec.units } : {}),
1515
+ ...(itemHoldsDuration && spec.unit !== undefined ? { unit: spec.unit } : {}),
1516
+ };
1517
+ // The domain belongs to the declaration that holds the value: a money, quantity or duration
1518
+ // item takes its members, and every other shape carries them on the field so the closed
1519
+ // metaschema gets to refuse a domain that cannot sit there.
1520
+ const fields = withUpdatedField(document, command.fieldId, () => ({
1521
+ fieldId: command.fieldId,
1522
+ primitive: spec.primitive,
1523
+ ...(priorLabel === undefined ? {} : { labelKey: priorLabel }),
1524
+ ...(priorDescription === undefined ? {} : { descriptionKey: priorDescription }),
1525
+ ...(priorPlaceholder === undefined ? {} : { placeholderKey: priorPlaceholder }),
1526
+ ...(priorOnHide === undefined ? {} : { onHide: priorOnHide }),
1527
+ ...(priorAnnotations === undefined ? {} : { annotations: priorAnnotations }),
1528
+ ...(spec.control === undefined ? {} : { control: spec.control }),
1529
+ ...(item === undefined ? {} : { items: item }),
1530
+ ...(itemHoldsMoney || spec.currency === undefined ? {} : { currency: spec.currency }),
1531
+ ...(itemHoldsMoney || spec.scale === undefined ? {} : { scale: spec.scale }),
1532
+ ...(itemHoldsQuantity || spec.units === undefined ? {} : { units: spec.units }),
1533
+ ...(itemHoldsDuration || spec.unit === undefined ? {} : { unit: spec.unit }),
1534
+ ...(spec.rowKey === undefined ? {} : { rowKey: spec.rowKey }),
1535
+ ...(options === undefined ? {} : { options }),
1536
+ ...(covers === undefined ? {} : { covers }),
1537
+ }));
1538
+ if (fields === undefined) {
1539
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.fieldId}\` is not declared`);
1540
+ }
1541
+ const messages = withMintedText(document, written);
1542
+ if (!messages.ok)
1543
+ return messages;
1544
+ const nextDocument = { ...document, fields, messages: messages.messages };
1545
+ // A code the new domain does not keep takes its label, its reason and its alternatives' labels
1546
+ // with it, unless another declaration still names one of them.
1547
+ const keptCodes = new Set((options ?? []).map((option) => option.code));
1548
+ const dropped = new Set([...priorOptions.values()]
1549
+ .filter((option) => !keptCodes.has(option.code))
1550
+ .flatMap(optionOwnedMessageKeys));
1551
+ const stillNamed = namedMessageKeys(nextDocument);
1552
+ const pruned = new Set([...dropped].filter((key) => !stillNamed.has(key)));
1553
+ return applied({ ...nextDocument, messages: withoutMessages(nextDocument, pruned) });
1554
+ }
1555
+ /**
1556
+ * One field after a declaration edit: each member the command states replaces what was there,
1557
+ * `null` removes it, and an absent member keeps its prior value.
1558
+ *
1559
+ * These members compile into the rules a device evaluates, so they are the declaration's
1560
+ * behaviour rather than its copy: a published field is retired instead of rewritten. The
1561
+ * relations among them — a bound needs its message key, `required` excludes `requiredWhen` —
1562
+ * are the metaschema's and the compiler's, so a half-stated pair is refused at the candidate
1563
+ * gate with the member the author wrote.
1564
+ */
1565
+ function setFieldDeclarationIn(document, fieldId, spec, published) {
1566
+ const declaration = authoredField(document, fieldId);
1567
+ if (declaration === undefined) {
1568
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1569
+ }
1570
+ if (published.fields.has(fieldId)) {
1571
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${fieldId}\` is published; its requirement, visibility and bounds compile into rules a device evaluates, so a published declaration is retired rather than rewritten`);
1572
+ }
1573
+ const fields = withUpdatedField(document, fieldId, (field) => {
1574
+ const { required: priorRequired, requiredMessageKey: priorRequiredMessageKey, requiredWhen: priorRequiredWhen, visibleWhen: priorVisibleWhen, minLength: priorMinLength, maxLength: priorMaxLength, minLengthMessageKey: priorMinLengthMessageKey, maxLengthMessageKey: priorMaxLengthMessageKey, minItems: priorMinItems, maxItems: priorMaxItems, maxScale: priorMaxScale, maxScaleMessageKey: priorMaxScaleMessageKey, minimum: priorMinimum, maximum: priorMaximum, minimumMessageKey: priorMinimumMessageKey, maximumMessageKey: priorMaximumMessageKey, step: priorStep, accept: priorAccept, minBytes: priorMinBytes, maxBytes: priorMaxBytes, rowsFrom: priorRowsFrom, requiredTestCases: priorRequiredTestCases, visibleWhenTestCases: priorVisibleWhenTestCases, minimumTestCases: priorMinimumTestCases, maximumTestCases: priorMaximumTestCases, minLengthTestCases: priorMinLengthTestCases, maxLengthTestCases: priorMaxLengthTestCases, ...rest } = field;
1575
+ const required = editedMember(priorRequired, spec.required);
1576
+ const requiredMessageKey = editedMember(priorRequiredMessageKey, spec.requiredMessageKey);
1577
+ const requiredWhen = editedMember(priorRequiredWhen, spec.requiredWhen);
1578
+ const visibleWhen = editedMember(priorVisibleWhen, spec.visibleWhen);
1579
+ const minLength = editedMember(priorMinLength, spec.minLength);
1580
+ const maxLength = editedMember(priorMaxLength, spec.maxLength);
1581
+ const minLengthMessageKey = editedMember(priorMinLengthMessageKey, spec.minLengthMessageKey);
1582
+ const maxLengthMessageKey = editedMember(priorMaxLengthMessageKey, spec.maxLengthMessageKey);
1583
+ const minItems = editedMember(priorMinItems, spec.minItems);
1584
+ const maxItems = editedMember(priorMaxItems, spec.maxItems);
1585
+ const maxScale = editedMember(priorMaxScale, spec.maxScale);
1586
+ const maxScaleMessageKey = editedMember(priorMaxScaleMessageKey, spec.maxScaleMessageKey);
1587
+ const minimum = editedMember(priorMinimum, spec.minimum);
1588
+ const maximum = editedMember(priorMaximum, spec.maximum);
1589
+ const minimumMessageKey = editedMember(priorMinimumMessageKey, spec.minimumMessageKey);
1590
+ const maximumMessageKey = editedMember(priorMaximumMessageKey, spec.maximumMessageKey);
1591
+ const step = editedMember(priorStep, spec.step);
1592
+ const accept = editedMember(priorAccept, spec.accept);
1593
+ const minBytes = editedMember(priorMinBytes, spec.minBytes);
1594
+ const maxBytes = editedMember(priorMaxBytes, spec.maxBytes);
1595
+ const rowsFrom = editedMember(priorRowsFrom, spec.rowsFrom);
1596
+ const requiredTestCases = editedMember(priorRequiredTestCases, spec.requiredTestCases);
1597
+ const visibleWhenTestCases = editedMember(priorVisibleWhenTestCases, spec.visibleWhenTestCases);
1598
+ const minimumTestCases = editedMember(priorMinimumTestCases, spec.minimumTestCases);
1599
+ const maximumTestCases = editedMember(priorMaximumTestCases, spec.maximumTestCases);
1600
+ const minLengthTestCases = editedMember(priorMinLengthTestCases, spec.minLengthTestCases);
1601
+ const maxLengthTestCases = editedMember(priorMaxLengthTestCases, spec.maxLengthTestCases);
1602
+ return {
1603
+ ...rest,
1604
+ ...(required === undefined ? {} : { required }),
1605
+ ...(requiredMessageKey === undefined ? {} : { requiredMessageKey }),
1606
+ ...(requiredWhen === undefined ? {} : { requiredWhen }),
1607
+ ...(visibleWhen === undefined ? {} : { visibleWhen }),
1608
+ ...(minLength === undefined ? {} : { minLength }),
1609
+ ...(maxLength === undefined ? {} : { maxLength }),
1610
+ ...(minLengthMessageKey === undefined ? {} : { minLengthMessageKey }),
1611
+ ...(maxLengthMessageKey === undefined ? {} : { maxLengthMessageKey }),
1612
+ ...(minItems === undefined ? {} : { minItems }),
1613
+ ...(maxItems === undefined ? {} : { maxItems }),
1614
+ ...(maxScale === undefined ? {} : { maxScale }),
1615
+ ...(maxScaleMessageKey === undefined ? {} : { maxScaleMessageKey }),
1616
+ ...(minimum === undefined ? {} : { minimum }),
1617
+ ...(maximum === undefined ? {} : { maximum }),
1618
+ ...(minimumMessageKey === undefined ? {} : { minimumMessageKey }),
1619
+ ...(maximumMessageKey === undefined ? {} : { maximumMessageKey }),
1620
+ ...(step === undefined ? {} : { step }),
1621
+ ...(accept === undefined ? {} : { accept }),
1622
+ ...(minBytes === undefined ? {} : { minBytes }),
1623
+ ...(maxBytes === undefined ? {} : { maxBytes }),
1624
+ ...(rowsFrom === undefined ? {} : { rowsFrom }),
1625
+ ...(requiredTestCases === undefined ? {} : { requiredTestCases }),
1626
+ ...(visibleWhenTestCases === undefined ? {} : { visibleWhenTestCases }),
1627
+ ...(minimumTestCases === undefined ? {} : { minimumTestCases }),
1628
+ ...(maximumTestCases === undefined ? {} : { maximumTestCases }),
1629
+ ...(minLengthTestCases === undefined ? {} : { minLengthTestCases }),
1630
+ ...(maxLengthTestCases === undefined ? {} : { maxLengthTestCases }),
1631
+ };
1632
+ });
1633
+ if (fields === undefined) {
1634
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1635
+ }
1636
+ return applied({ ...document, fields });
1637
+ }
1638
+ function deprecateOptionIn(document, fieldId, code, published) {
1639
+ const declaration = authoredField(document, fieldId);
1640
+ if (declaration === undefined) {
1641
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1642
+ }
1643
+ const options = declaration.field.options ?? [];
1644
+ const option = options.find((declared) => declared.code === code);
1645
+ if (option === undefined) {
1646
+ return { ok: false, refusal: unknownOption(fieldId, code, options) };
1647
+ }
1648
+ if (option.deprecated === true) {
1649
+ return refuse('ALREADY_DEPRECATED', '$.fields', `option \`${String(code)}\` of field \`${fieldId}\` is already deprecated`);
1650
+ }
1651
+ if (published.fields.has(fieldId)) {
1652
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${fieldId}\` is published; its option domain is what a device reads a value against, so a published option is retired by a new edition rather than rewritten`);
1653
+ }
1654
+ const fields = withUpdatedField(document, fieldId, (field) => ({
1655
+ ...field,
1656
+ options: (field.options ?? []).map((declared) => declared.code === code ? { ...declared, deprecated: true } : declared),
1657
+ }));
1658
+ if (fields === undefined) {
1659
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1660
+ }
1661
+ return applied({ ...document, fields });
1662
+ }
1663
+ /**
1664
+ * Merges one node's new members over the node at a path.
1665
+ *
1666
+ * A node states its own members and holds its children separately, so the merge writes members
1667
+ * and keeps the tree below it: a caller iterating "what did the author change" cannot lose a
1668
+ * wizard's steps by forgetting a member the command never meant to carry. `kind` is the node's
1669
+ * identity and is checked rather than replaced, and a member the edit states as `null` is removed
1670
+ * rather than written (see `mergedLayoutNode`).
1671
+ */
1672
+ function editLayoutNodeIn(document, path, node) {
1673
+ const target = nodeAt(document.layout, path);
1674
+ if (target === undefined) {
1675
+ return refuse('UNKNOWN_LAYOUT', '$.layout', `the path ${JSON.stringify(path)} names no layout node`);
1676
+ }
1677
+ const statedKind = node['kind'];
1678
+ if (statedKind !== undefined && statedKind !== target['kind']) {
1679
+ return refuse('INVALID_LAYOUT', '$.layout', `the node at ${JSON.stringify(path)} is a \`${String(target['kind'])}\` and the edit states \`${String(statedKind)}\`; a node keeps its kind, and a node of another kind is added and the old one removed`);
1680
+ }
1681
+ const layout = replaceLayoutNode(document.layout, path, (existing) => mergedLayoutNode(existing, node));
1682
+ if (layout === undefined) {
1683
+ return refuse('UNKNOWN_LAYOUT', '$.layout', `the path ${JSON.stringify(path)} names no layout node`);
1684
+ }
1685
+ return applied({ ...document, layout });
1686
+ }
1687
+ /**
1688
+ * One node's members after an edit: stated members replaced, `null` members removed, and the tree
1689
+ * below kept.
1690
+ *
1691
+ * An absent member means "no opinion" and a `null` means "remove it", the same three-state
1692
+ * reading `editField` gives its members, so an author can clear a conditional or a label they set
1693
+ * earlier instead of removing the node and everything under it. The tree below the node is carried
1694
+ * only where one stands: `holdsChildren` is what keeps an edit of a leaf from writing the member a
1695
+ * leaf kind does not admit.
1696
+ */
1697
+ function mergedLayoutNode(existing, edit) {
1698
+ const members = [];
1699
+ for (const [member, value] of Object.entries(existing)) {
1700
+ if (Object.hasOwn(edit, member) && edit[member] === null)
1701
+ continue;
1702
+ members.push([member, value]);
1703
+ }
1704
+ for (const [member, value] of Object.entries(edit)) {
1705
+ if (value === null)
1706
+ continue;
1707
+ members.push([member, value]);
1708
+ }
1709
+ // Define own properties rather than assigning them, so a `__proto__` member reaches the closed
1710
+ // validator as data instead of changing the merged node's prototype and vanishing from its keys.
1711
+ const merged = Object.fromEntries(members);
1712
+ return holdsChildren(existing) ? { ...merged, children: childrenOf(existing) } : merged;
1713
+ }
1714
+ /** The layout with the node at `path` removed, everything it contained, and the text it owned. */
1715
+ function removeLayoutNodeIn(document, path) {
1716
+ const [step, ...rest] = path;
1717
+ if (step === undefined) {
1718
+ return refuse('INVALID_LAYOUT', '$.layout', 'a removal names a node inside `layout`; remove nodes inside `layout`, not the `layout` list itself');
1719
+ }
1720
+ const target = nodeAt(document.layout, path);
1721
+ const removed = withoutNode(document.layout, step, rest);
1722
+ if (removed === undefined || target === undefined) {
1723
+ return refuse('UNKNOWN_LAYOUT', '$.layout', `the path ${JSON.stringify(path)} names no layout node`);
1724
+ }
1725
+ const nextDocument = { ...document, layout: removed };
1726
+ // A node's title, text and readout labels render only through that node. Removing it leaves
1727
+ // those keys unreachable, so the text goes in the same undo step; a key another member names
1728
+ // stays, as it does for a removed field or rule.
1729
+ const stillNamed = namedMessageKeys(nextDocument);
1730
+ const pruned = new Set(layoutNodeOwnedMessageKeys(target).filter((key) => !stillNamed.has(key)));
1731
+ return applied({ ...nextDocument, messages: withoutMessages(nextDocument, pruned) });
1732
+ }
1733
+ /**
1734
+ * `nodes` with the child at `index` removed, or the child at `rest` inside it when `rest` is not
1735
+ * empty. `undefined` when the path names no node, so a caller refuses with the path that missed.
1736
+ */
1737
+ function withoutNode(nodes, index, rest) {
1738
+ const node = nodes[index];
1739
+ if (node === undefined)
1740
+ return undefined;
1741
+ if (rest.length === 0)
1742
+ return [...nodes.slice(0, index), ...nodes.slice(index + 1)];
1743
+ const [step, ...deeper] = rest;
1744
+ if (step === undefined)
1745
+ return undefined;
1746
+ const children = withoutNode(childrenOf(node), step, deeper);
1747
+ if (children === undefined)
1748
+ return undefined;
1749
+ const next = [...nodes];
1750
+ next[index] = { ...node, children };
1751
+ return next;
1752
+ }
1753
+ /**
1754
+ * The document under a new locale policy.
1755
+ *
1756
+ * A text filed under a locale the document no longer declares renders nowhere, and the compile
1757
+ * reports it as a catalogue defect rather than as a translation nobody needs, so the removal takes
1758
+ * those texts with it — in the same undo step, so a language dropped by mistake is one undo away.
1759
+ * An entry left with no texts is dropped: `messageEntry` states at least one, so keeping an empty
1760
+ * object would be a document the metaschema refuses.
1761
+ */
1762
+ function setLocalesIn(document, locales, defaultLocale) {
1763
+ const declared = new Set(locales);
1764
+ const messages = [];
1765
+ for (const [key, entry] of Object.entries(document.messages)) {
1766
+ const kept = Object.entries(entry).filter(([locale]) => declared.has(locale));
1767
+ if (kept.length === 0)
1768
+ continue;
1769
+ // Define own properties rather than assigning them, so a `__proto__` key stays data.
1770
+ messages.push([key, Object.fromEntries(kept)]);
1771
+ }
1772
+ return applied({
1773
+ ...document,
1774
+ messages: Object.fromEntries(messages),
1775
+ locales,
1776
+ defaultLocale,
1777
+ });
1778
+ }
1779
+ /**
1780
+ * Sets a group's column count and narrows every field child that no longer fits.
1781
+ *
1782
+ * The group's `columns` governs its own direct children, so those are the declarations a narrower
1783
+ * group makes illegal; each narrowed span is reported rather than silently rewritten, because an
1784
+ * author who laid a field out across four columns needs to know it is now two.
1785
+ */
1786
+ function setGroupColumnsIn(document, path, columns) {
1787
+ const node = nodeAt(document.layout, path);
1788
+ if (node === undefined) {
1789
+ return refuse('UNKNOWN_LAYOUT', '$.layout', `the path ${JSON.stringify(path)} names no layout node`);
1790
+ }
1791
+ if (node['kind'] !== 'group') {
1792
+ return refuse('INVALID_LAYOUT', `$.layout`, `the node at ${JSON.stringify(path)} is a \`${String(node['kind'])}\`; only a group lays out columns`);
1793
+ }
1794
+ const clamped = [];
1795
+ const children = childrenOf(node).map((child) => {
1796
+ const span = child['colSpan'];
1797
+ const fieldId = child['fieldId'];
1798
+ if (typeof span !== 'number' || span <= columns || typeof fieldId !== 'string')
1799
+ return child;
1800
+ clamped.push({ fieldId, from: span, to: columns });
1801
+ return { ...child, colSpan: columns };
1802
+ });
1803
+ const layout = replaceLayoutNode(document.layout, path, (target) => ({
1804
+ ...target,
1805
+ columns,
1806
+ children,
1807
+ }));
1808
+ if (layout === undefined) {
1809
+ return refuse('UNKNOWN_LAYOUT', '$.layout', `the path ${JSON.stringify(path)} names no layout node`);
1810
+ }
1811
+ return applied({ ...document, layout }, clamped);
1812
+ }
1813
+ function addRecordArrayTo(document, command) {
1814
+ const spec = command.array;
1815
+ if (authoredField(document, spec.fieldId) !== undefined) {
1816
+ return refuse('DUPLICATE_ID', additionPath(document), `field \`${spec.fieldId}\` is already declared; a field id is unique across the document`);
1817
+ }
1818
+ const memberDomain = memberDomainRefusal(spec.members);
1819
+ if (memberDomain !== undefined)
1820
+ return { ok: false, refusal: memberDomain };
1821
+ const built = spec.members.map((member) => buildMember(member, [spec.fieldId]));
1822
+ // The table names itself the way every authored field does: the label is a literal the
1823
+ // command mints a message key for, so a renderer has a title rather than the field id. A
1824
+ // command that states none keeps the declaration it had, which is what older callers do.
1825
+ const label = spec.label;
1826
+ const labelKey = label === undefined ? undefined : fieldMessageKey([spec.fieldId]);
1827
+ const messages = [
1828
+ ...(labelKey === undefined || label === undefined ? [] : [[labelKey, label]]),
1829
+ ...built.flatMap((entry) => entry.messages),
1830
+ ];
1831
+ const collision = collidingKey(document, messages);
1832
+ if (collision !== undefined)
1833
+ return refuseCollision(collision, additionPath(document));
1834
+ const duplicate = firstDuplicateId(document, built.map((entry) => entry.field));
1835
+ if (duplicate !== undefined) {
1836
+ return refuse('DUPLICATE_ID', additionPath(document), `field \`${duplicate}\` is already declared, or declared twice by this command; a field id is unique across the document`);
1837
+ }
1838
+ const placement = appendLayoutChild(document.layout, spec.parent, fieldLeaf(spec.fieldId, spec.colSpan));
1839
+ let layout = document.layout;
1840
+ if (spec.placement !== 'none') {
1841
+ if (!placement.ok)
1842
+ return placement;
1843
+ layout = placement.layout;
1844
+ }
1845
+ const catalogue = withMintedText(document, messages);
1846
+ if (!catalogue.ok)
1847
+ return catalogue;
1848
+ return applied({
1849
+ ...document,
1850
+ fields: [
1851
+ ...document.fields,
1852
+ {
1853
+ fieldId: spec.fieldId,
1854
+ primitive: 'array',
1855
+ ...(labelKey === undefined ? {} : { labelKey }),
1856
+ rowKey: spec.rowKey,
1857
+ fields: built.map((entry) => entry.field),
1858
+ },
1859
+ ],
1860
+ layout,
1861
+ messages: catalogue.messages,
1862
+ });
1863
+ }
1864
+ /**
1865
+ * The first id the document already declares, or that the command declares twice.
1866
+ *
1867
+ * A container command adds a tree at once, so uniqueness is over the declarations it brings as
1868
+ * well as the ones already there: two members named alike in one row would pass a check that only
1869
+ * looked at the document.
1870
+ */
1871
+ function firstDuplicateId(document, fields) {
1872
+ const added = new Set();
1873
+ for (const entry of declaredMembers(fields)) {
1874
+ const id = entry.field.fieldId;
1875
+ if (added.has(id) || authoredField(document, id) !== undefined)
1876
+ return id;
1877
+ added.add(id);
1878
+ }
1879
+ return undefined;
1880
+ }
1881
+ /** Which container a declaration is, or `undefined` when it holds no members at all. */
1882
+ function containerKindOf(field) {
1883
+ if (field.primitive === 'record')
1884
+ return 'record';
1885
+ if (field.primitive === 'array' && field.items === undefined)
1886
+ return 'record_array';
1887
+ return undefined;
1888
+ }
1889
+ function addMemberTo(document, container, member, published, expected) {
1890
+ const kind = containerKindOf(container.field);
1891
+ if (kind !== expected) {
1892
+ return refuse('MALFORMED_COMMAND', '$.fields', kind === undefined
1893
+ ? `field \`${container.field.fieldId}\` is a \`${container.field.primitive}\` ${container.field.primitive === 'array' ? 'of items' : 'field'}; only a record or a record array declares members`
1894
+ : `\`${expected === 'record' ? 'addRecordMember' : 'addRowMember'}\` extends a ${expected === 'record' ? 'record' : 'record array'}, and \`${container.field.fieldId}\` is a ${kind === 'record' ? 'record' : 'record array'}; use \`${kind === 'record' ? 'addRecordMember' : 'addRowMember'}\``);
1895
+ }
1896
+ if (published.fields.has(container.field.fieldId)) {
1897
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${container.field.fieldId}\` is published; its members are part of what a device reads, so it cannot gain one`);
1898
+ }
1899
+ const memberDomain = memberDomainRefusal([member]);
1900
+ if (memberDomain !== undefined)
1901
+ return { ok: false, refusal: memberDomain };
1902
+ const built = buildMember(member, container.trail);
1903
+ const collision = collidingKey(document, built.messages);
1904
+ if (collision !== undefined)
1905
+ return refuseCollision(collision, '$.fields');
1906
+ const duplicate = firstDuplicateId(document, [built.field]);
1907
+ if (duplicate !== undefined) {
1908
+ return refuse('DUPLICATE_ID', '$.fields', `field \`${duplicate}\` is already declared, or declared twice by this command; a field id is unique across the document`);
1909
+ }
1910
+ const fields = withUpdatedField(document, container.field.fieldId, (field) => ({
1911
+ ...field,
1912
+ fields: [...(field.fields ?? []), built.field],
1913
+ }));
1914
+ if (fields === undefined) {
1915
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${container.field.fieldId}\` is not declared`);
1916
+ }
1917
+ const messages = withMintedText(document, built.messages);
1918
+ if (!messages.ok)
1919
+ return messages;
1920
+ return applied({ ...document, fields, messages: messages.messages });
1921
+ }
1922
+ function setRowKeyIn(document, fieldId, rowKey, published) {
1923
+ const declaration = authoredField(document, fieldId);
1924
+ if (declaration === undefined) {
1925
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1926
+ }
1927
+ if (declaration.field.primitive !== 'array' || declaration.field.items !== undefined) {
1928
+ return refuse('MALFORMED_COMMAND', '$.fields', `field \`${fieldId}\` is not a record array; only an array of records identifies its rows`);
1929
+ }
1930
+ if (declaration.field.options !== undefined) {
1931
+ return refuse('MALFORMED_COMMAND', '$.fields', `array \`${fieldId}\` declares an option domain, so its rows are identified by their values; a freeform array is the one that states a \`rowKey\``);
1932
+ }
1933
+ if (published.fields.has(fieldId)) {
1934
+ return refuse('PUBLISHED_FIELD', '$.fields', `array \`${fieldId}\` is published; its row identity is what existing records are keyed by, so it cannot move`);
1935
+ }
1936
+ const fields = withUpdatedField(document, fieldId, (field) => ({ ...field, rowKey }));
1937
+ if (fields === undefined) {
1938
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${fieldId}\` is not declared`);
1939
+ }
1940
+ return applied({ ...document, fields });
1941
+ }
1942
+ /** Declares or repoints a section's primary designation. */
1943
+ function setPrimaryIn(document, command) {
1944
+ const rule = (document.rules ?? []).find((declared) => declared.ruleId === command.ruleId);
1945
+ const code = command.ruleKind === 'gate' ? 'UNKNOWN_GATE' : 'UNKNOWN_SCREEN';
1946
+ if (rule === undefined) {
1947
+ return refuse(code, '$.rules', `rule \`${command.ruleId}\` is not declared`);
1948
+ }
1949
+ if (rule.kind !== command.ruleKind) {
1950
+ return refuse(code, '$.rules', `rule \`${command.ruleId}\` is a \`${rule.kind}\`, not a \`${command.ruleKind}\`; the primary of a section names a rule of that kind`);
1951
+ }
1952
+ return applied({
1953
+ ...document,
1954
+ ...(command.ruleKind === 'gate'
1955
+ ? { primaryGateId: command.ruleId }
1956
+ : { primaryScreenId: command.ruleId }),
1957
+ });
1958
+ }
1959
+ /** Declares or moves a table pin, keeping declaration order stable. */
1960
+ function pinDatasetIn(document, pin) {
1961
+ const datasets = document.datasets ?? [];
1962
+ const nextPin = {
1963
+ tableId: pin.tableId,
1964
+ tableVersion: pin.tableVersion,
1965
+ };
1966
+ const index = datasets.findIndex((declared) => declared.tableId === pin.tableId);
1967
+ const next = index < 0
1968
+ ? [...datasets, nextPin]
1969
+ : datasets.map((entry, at) => (at === index ? nextPin : entry));
1970
+ return applied({ ...document, datasets: next });
1971
+ }
1972
+ function unpinDatasetIn(document, tableId) {
1973
+ const datasets = document.datasets ?? [];
1974
+ const next = datasets.filter((entry) => entry.tableId !== tableId);
1975
+ if (next.length === datasets.length) {
1976
+ return refuse('UNKNOWN_DATASET', '$.datasets', `this document pins no table \`${tableId}\``);
1977
+ }
1978
+ if (next.length > 0)
1979
+ return applied({ ...document, datasets: next });
1980
+ const { datasets: _removed, ...rest } = document;
1981
+ return applied(rest);
1982
+ }
1983
+ /** Declares or replaces one read-only evaluation root, keyed by its own path. */
1984
+ function setContextRootIn(document, root) {
1985
+ const roots = document.context?.roots ?? [];
1986
+ const index = roots.findIndex((declared) => declared.path === root.path);
1987
+ const next = index < 0 ? [...roots, root] : roots.map((entry, at) => (at === index ? root : entry));
1988
+ return applied({ ...document, context: { roots: next } });
1989
+ }
1990
+ function removeContextRootIn(document, path) {
1991
+ const roots = document.context?.roots ?? [];
1992
+ const next = roots.filter((root) => root.path !== path);
1993
+ if (next.length === roots.length) {
1994
+ return refuse('UNKNOWN_CONTEXT_ROOT', '$.context.roots', `this document declares no context root \`${path}\``);
1995
+ }
1996
+ if (next.length > 0)
1997
+ return applied({ ...document, context: { roots: next } });
1998
+ const { context: _removed, ...rest } = document;
1999
+ return applied(rest);
2000
+ }
2001
+ function setOnHideIn(document, onHide) {
2002
+ if (onHide !== null)
2003
+ return applied({ ...document, onHide });
2004
+ const { onHide: _removed, ...rest } = document;
2005
+ return applied(rest);
2006
+ }
2007
+ function setDocumentTitleIn(document, text) {
2008
+ const key = titleMessageKey();
2009
+ const messages = withMintedText(document, [[key, text]]);
2010
+ if (!messages.ok)
2011
+ return messages;
2012
+ return applied({ ...document, titleKey: key, messages: messages.messages });
2013
+ }
2014
+ function setSignatureCoversIn(document, command, published) {
2015
+ const declaration = authoredField(document, command.fieldId);
2016
+ if (declaration === undefined) {
2017
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.fieldId}\` is not declared`);
2018
+ }
2019
+ if (declaration.field.primitive !== 'signature_ref') {
2020
+ return refuse('MALFORMED_COMMAND', '$.fields', `field \`${command.fieldId}\` is a \`${declaration.field.primitive}\`; only a \`signature_ref\` field binds the values its signature covers`);
2021
+ }
2022
+ if (published.fields.has(command.fieldId)) {
2023
+ return refuse('PUBLISHED_FIELD', '$.fields', `field \`${command.fieldId}\` is published; the targets its signature binds are part of what a device verifies, so a published declaration is retired rather than rewritten`);
2024
+ }
2025
+ if (command.covers.includes(command.fieldId)) {
2026
+ return refuse('MALFORMED_COMMAND', '$.fields', `field \`${command.fieldId}\` cannot cover itself; name the fields the signature signs`);
2027
+ }
2028
+ const fields = withUpdatedField(document, command.fieldId, (field) => ({
2029
+ ...field,
2030
+ covers: command.covers,
2031
+ }));
2032
+ if (fields === undefined) {
2033
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.fieldId}\` is not declared`);
2034
+ }
2035
+ return applied({ ...document, fields });
2036
+ }
2037
+ /** Whether any layout leaf places `fieldId`. */
2038
+ function layoutPlacesField(nodes, fieldId) {
2039
+ for (const node of nodes) {
2040
+ if (node['kind'] === 'field' && node['fieldId'] === fieldId)
2041
+ return true;
2042
+ if (layoutPlacesField(childrenOf(node), fieldId))
2043
+ return true;
2044
+ }
2045
+ return false;
2046
+ }
2047
+ function placeFieldIn(document, command) {
2048
+ const declaration = authoredField(document, command.fieldId);
2049
+ if (declaration === undefined) {
2050
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.fieldId}\` is not declared`);
2051
+ }
2052
+ if (declaration.trail.length !== 1) {
2053
+ return refuse('MALFORMED_COMMAND', '$.layout', `field \`${command.fieldId}\` is a member of a container, not a top-level declaration; its container's layout leaf places it`);
2054
+ }
2055
+ if (layoutPlacesField(document.layout, command.fieldId)) {
2056
+ return refuse('DUPLICATE_ID', '$.layout', `field \`${command.fieldId}\` already has a placement; move its leaf with \`moveLayoutNode\` rather than placing it twice`);
2057
+ }
2058
+ const placement = appendLayoutChild(document.layout, command.parent, fieldLeaf(command.fieldId, command.colSpan));
2059
+ if (!placement.ok)
2060
+ return placement;
2061
+ return applied({ ...document, layout: placement.layout });
2062
+ }
2063
+ /** Whether `prefix` names `path` or an ancestor of it. */
2064
+ function isPathPrefix(prefix, path) {
2065
+ return prefix.length <= path.length && prefix.every((step, index) => path[index] === step);
2066
+ }
2067
+ /**
2068
+ * A destination path after the node at `removed` has left the tree.
2069
+ *
2070
+ * Only the removed node's own parent loses a child index, so only a destination that names a
2071
+ * later sibling *of that parent* moves down by one. A destination in another subtree — even one
2072
+ * whose top-level index is greater — is untouched: removing a child of `[0]` does not renumber
2073
+ * the top-level nodes beside it. A path that names the removed node or a descendant answers
2074
+ * `undefined`: a node cannot be moved inside itself.
2075
+ */
2076
+ function adjustPathAfterRemoval(destination, removed) {
2077
+ if (isPathPrefix(removed, destination))
2078
+ return undefined;
2079
+ const parent = removed.slice(0, -1);
2080
+ const removedIndex = removed[removed.length - 1];
2081
+ if (removedIndex === undefined || destination.length <= parent.length)
2082
+ return destination;
2083
+ const sharesParent = parent.every((step, index) => destination[index] === step);
2084
+ if (!sharesParent)
2085
+ return destination;
2086
+ const at = parent.length;
2087
+ const sibling = destination[at];
2088
+ if (sibling === undefined || removedIndex >= sibling)
2089
+ return destination;
2090
+ const adjusted = [...destination];
2091
+ adjusted[at] = sibling - 1;
2092
+ return adjusted;
2093
+ }
2094
+ /** A new layout tree with `child` inserted under `parent` at `index` (append when absent). */
2095
+ function insertLayoutChild(layout, parent, index, child) {
2096
+ const parentPath = parent === undefined || parent.length === 0 ? undefined : parent;
2097
+ if (parentPath === undefined) {
2098
+ const at = index === undefined ? layout.length : Math.min(Math.max(index, 0), layout.length);
2099
+ return { ok: true, layout: [...layout.slice(0, at), child, ...layout.slice(at)] };
2100
+ }
2101
+ const target = nodeAt(layout, parentPath);
2102
+ if (target === undefined) {
2103
+ return {
2104
+ ok: false,
2105
+ refusal: authoringRefusal('UNKNOWN_LAYOUT', '$.layout', `the parent path ${JSON.stringify(parentPath)} names no layout node`),
2106
+ };
2107
+ }
2108
+ if (!holdsChildren(target)) {
2109
+ return {
2110
+ ok: false,
2111
+ refusal: authoringRefusal('INVALID_LAYOUT', '$.layout', `the node at ${JSON.stringify(parentPath)} is a \`${String(target['kind'])}\`, which holds no children; add a section, group or step and place this node inside it`),
2112
+ };
2113
+ }
2114
+ const placed = replaceLayoutNode(layout, parentPath, (node) => {
2115
+ const children = childrenOf(node);
2116
+ const at = index === undefined ? children.length : Math.min(Math.max(index, 0), children.length);
2117
+ return { ...node, children: [...children.slice(0, at), child, ...children.slice(at)] };
2118
+ });
2119
+ return placed === undefined
2120
+ ? {
2121
+ ok: false,
2122
+ refusal: authoringRefusal('UNKNOWN_LAYOUT', '$.layout', `the parent path ${JSON.stringify(parentPath)} names no layout node`),
2123
+ }
2124
+ : { ok: true, layout: placed };
2125
+ }
2126
+ function moveLayoutNodeIn(document, command) {
2127
+ const node = nodeAt(document.layout, command.target);
2128
+ if (node === undefined) {
2129
+ return refuse('UNKNOWN_LAYOUT', '$.layout', `the path ${JSON.stringify(command.target)} names no layout node`);
2130
+ }
2131
+ const [head, ...rest] = command.target;
2132
+ if (head === undefined) {
2133
+ return refuse('INVALID_LAYOUT', '$.layout', 'a move names a node inside `layout`');
2134
+ }
2135
+ if (command.parent !== undefined && isPathPrefix(command.target, command.parent)) {
2136
+ return refuse('INVALID_LAYOUT', '$.layout', `the destination ${JSON.stringify(command.parent)} is inside the node being moved; a node cannot contain itself`);
2137
+ }
2138
+ const removed = withoutNode(document.layout, head, rest);
2139
+ if (removed === undefined) {
2140
+ return refuse('UNKNOWN_LAYOUT', '$.layout', `the path ${JSON.stringify(command.target)} names no layout node`);
2141
+ }
2142
+ const parent = command.parent === undefined
2143
+ ? undefined
2144
+ : adjustPathAfterRemoval(command.parent, command.target);
2145
+ if (parent === undefined && command.parent !== undefined) {
2146
+ return refuse('INVALID_LAYOUT', '$.layout', `the destination ${JSON.stringify(command.parent)} is inside the node being moved; a node cannot contain itself`);
2147
+ }
2148
+ const index = command.index;
2149
+ const placement = insertLayoutChild(removed, parent, index, node);
2150
+ if (!placement.ok)
2151
+ return placement;
2152
+ return applied({ ...document, layout: placement.layout });
2153
+ }
2154
+ /** Applies one validated command to one document. */
2155
+ export function applyCommand(document, command, published) {
2156
+ const result = applyCommandToDocument(document, command, published);
2157
+ if (!result.ok || result.applied.document === document)
2158
+ return result;
2159
+ // A command that restates a member builds a new tree with identical content. Return the document
2160
+ // it was handed so the store's no-edit guard sees one snapshot: the commit would otherwise add an
2161
+ // undo step between two byte-identical documents. The walk stops at every untouched subtree, so
2162
+ // the cost is the path the command touched rather than a serialisation of the whole document.
2163
+ if (!unchanged(result.applied.document, document))
2164
+ return result;
2165
+ return { ok: true, applied: { document, clamped: result.applied.clamped } };
2166
+ }
2167
+ function applyCommandToDocument(document, command, published) {
2168
+ switch (command.kind) {
2169
+ case 'addField':
2170
+ return addFieldToDocument(document, command.field);
2171
+ case 'addOption':
2172
+ return addOptionToDocument(document, command.fieldId, command.code, command.label, published);
2173
+ case 'editField':
2174
+ return editFieldIn(document, command.fieldId, command.field, published);
2175
+ case 'setFieldDeclaration':
2176
+ return setFieldDeclarationIn(document, command.fieldId, command.declaration, published);
2177
+ case 'deprecateOption':
2178
+ return deprecateOptionIn(document, command.fieldId, command.code, published);
2179
+ case 'moveOption':
2180
+ return moveOptionIn(document, command.fieldId, command.code, command.index, published);
2181
+ case 'setOptionAvailability':
2182
+ return setOptionAvailabilityIn(document, command, published);
2183
+ case 'addRule':
2184
+ return addRuleToDocument(document, command);
2185
+ case 'addRuleTestCase':
2186
+ return addRuleTestCaseIn(document, command);
2187
+ case 'setRuleExpr':
2188
+ return setRuleExprIn(document, command);
2189
+ case 'setRuleNote':
2190
+ return setRuleNoteIn(document, command);
2191
+ case 'setRuleSuggests':
2192
+ // One command in the union for the host and the history, one implementation of the edit:
2193
+ // `editRule` already states this member and owns the kind check, key reuse and pruning.
2194
+ return editRuleIn(document, {
2195
+ kind: 'editRule',
2196
+ ruleId: command.ruleId,
2197
+ rule: { suggests: command.suggests },
2198
+ });
2199
+ case 'editRule':
2200
+ return editRuleIn(document, command);
2201
+ case 'removeRule':
2202
+ return removeRuleIn(document, command.ruleId, published);
2203
+ case 'setMessageText':
2204
+ return setMessageTextIn(document, command.messageKey, command.locale, command.text);
2205
+ case 'deprecateField':
2206
+ return deprecateIn(document, command.fieldId);
2207
+ case 'removeField':
2208
+ return removeFieldIn(document, command, published);
2209
+ case 'setFieldPrimitive':
2210
+ return setFieldPrimitiveIn(document, command, published);
2211
+ case 'addLayoutNode':
2212
+ return addLayoutNodeTo(document, command.node, command.parent);
2213
+ case 'editLayoutNode':
2214
+ return editLayoutNodeIn(document, command.target, command.node);
2215
+ case 'removeLayoutNode':
2216
+ return removeLayoutNodeIn(document, command.target);
2217
+ case 'placeField':
2218
+ return placeFieldIn(document, command);
2219
+ case 'moveLayoutNode':
2220
+ return moveLayoutNodeIn(document, command);
2221
+ case 'setLocales':
2222
+ return setLocalesIn(document, command.locales, command.defaultLocale);
2223
+ case 'setGroupColumns':
2224
+ return setGroupColumnsIn(document, command.group, command.columns);
2225
+ case 'addRecordArray':
2226
+ return addRecordArrayTo(document, command);
2227
+ case 'addRowMember': {
2228
+ const container = authoredField(document, command.arrayFieldId);
2229
+ if (container === undefined) {
2230
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.arrayFieldId}\` is not declared`);
2231
+ }
2232
+ return addMemberTo(document, container, command.member, published, 'record_array');
2233
+ }
2234
+ case 'addRecordMember': {
2235
+ const container = authoredField(document, command.parentFieldId);
2236
+ if (container === undefined) {
2237
+ return refuse('UNKNOWN_FIELD', '$.fields', `field \`${command.parentFieldId}\` is not declared`);
2238
+ }
2239
+ return addMemberTo(document, container, command.member, published, 'record');
2240
+ }
2241
+ case 'setRowKey':
2242
+ return setRowKeyIn(document, command.fieldId, command.rowKey, published);
2243
+ case 'setSchemaVersion':
2244
+ return setSchemaVersionIn(document, command.schemaVersion);
2245
+ case 'importTranslations': {
2246
+ const imported = importTranslations(document, command.translations);
2247
+ return imported.ok ? applied(imported.document) : { ok: false, refusal: imported.refusal };
2248
+ }
2249
+ case 'setPrimary':
2250
+ return setPrimaryIn(document, command);
2251
+ case 'pinDataset':
2252
+ return pinDatasetIn(document, command);
2253
+ case 'unpinDataset':
2254
+ return unpinDatasetIn(document, command.tableId);
2255
+ case 'setContextRoot':
2256
+ return setContextRootIn(document, command.root);
2257
+ case 'removeContextRoot':
2258
+ return removeContextRootIn(document, command.path);
2259
+ case 'setOnHide':
2260
+ return setOnHideIn(document, command.onHide);
2261
+ case 'setDocumentTitle':
2262
+ return setDocumentTitleIn(document, command.text);
2263
+ case 'setSignatureCovers':
2264
+ return setSignatureCoversIn(document, command, published);
2265
+ default:
2266
+ return assertNever(command);
2267
+ }
2268
+ }
2269
+ //# sourceMappingURL=apply.js.map