asma-core-helpers 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  2. package/lib/collaboration/applyOperation.js +194 -0
  3. package/lib/collaboration/applyOperation.js.map +1 -1
  4. package/lib/collaboration/index.d.ts +1 -0
  5. package/lib/collaboration/index.d.ts.map +1 -1
  6. package/lib/collaboration/index.js +1 -0
  7. package/lib/collaboration/index.js.map +1 -1
  8. package/lib/collaboration/operations.d.ts +98 -0
  9. package/lib/collaboration/operations.d.ts.map +1 -1
  10. package/lib/collaboration/operations.js +4 -0
  11. package/lib/collaboration/operations.js.map +1 -1
  12. package/lib/collaboration/schemas.d.ts +138 -0
  13. package/lib/collaboration/schemas.d.ts.map +1 -1
  14. package/lib/collaboration/schemas.js +198 -10
  15. package/lib/collaboration/schemas.js.map +1 -1
  16. package/lib/collaboration/templateAuthoringMeta.d.ts +424 -0
  17. package/lib/collaboration/templateAuthoringMeta.d.ts.map +1 -0
  18. package/lib/collaboration/templateAuthoringMeta.js +726 -0
  19. package/lib/collaboration/templateAuthoringMeta.js.map +1 -0
  20. package/lib/collaboration/templateDocument.d.ts +136 -14
  21. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  22. package/lib/collaboration/templateDocument.js +19 -0
  23. package/lib/collaboration/templateDocument.js.map +1 -1
  24. package/lib/collaboration/testHelpers/documentGenerator.d.ts.map +1 -1
  25. package/lib/collaboration/testHelpers/documentGenerator.js +53 -0
  26. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  27. package/lib/collaboration/typeContracts.d.ts +139 -0
  28. package/lib/collaboration/typeContracts.d.ts.map +1 -1
  29. package/package.json +1 -1
  30. package/src/collaboration/applyOperation.ts +251 -0
  31. package/src/collaboration/index.ts +1 -0
  32. package/src/collaboration/operations.ts +100 -0
  33. package/src/collaboration/property.test.ts +56 -1
  34. package/src/collaboration/schemas.test.ts +172 -1
  35. package/src/collaboration/schemas.ts +214 -9
  36. package/src/collaboration/templateAuthoringMeta.test.ts +1286 -0
  37. package/src/collaboration/templateAuthoringMeta.ts +1098 -0
  38. package/src/collaboration/templateDocument.ts +139 -14
  39. package/src/collaboration/testHelpers/documentGenerator.ts +60 -0
  40. package/src/collaboration/typeContracts.ts +155 -0
@@ -0,0 +1,726 @@
1
+ import { INITIATORS, TEMPLATE_UPDATE_MODES, TEMPLATE_VISIBILITIES } from './templateDocument.js';
2
+ /**
3
+ * The 23 settings leaves, as group-relative paths under `meta.settings`.
4
+ *
5
+ * Grouped by the surface they configure rather than flattened, because the groups are what make the
6
+ * minimal form prunable: unsetting the last leaf of `rendering` removes `rendering`, and unsetting
7
+ * the last group removes `settings` (DOC-LAW-2). Every leaf is a boolean; the only non-false default
8
+ * is `rendering.refresh_button`.
9
+ */
10
+ export const TEMPLATE_SETTING_FIELDS = [
11
+ 'journal.auto_import',
12
+ 'journal.requires_activity_id',
13
+ 'journal.register_new_activity',
14
+ 'journal.user_context_me',
15
+ 'pdf.import',
16
+ 'pdf.generate_for_participant',
17
+ 'pdf.send_to_journal',
18
+ 'rendering.tabs',
19
+ 'rendering.continuous',
20
+ 'rendering.multi_step',
21
+ 'rendering.collapse_all',
22
+ 'rendering.top_level_actions',
23
+ 'rendering.refresh_button',
24
+ 'rendering.filter_document_reports_on_tab',
25
+ 'rendering.hide_recipient_info',
26
+ 'lifecycle.rejectable',
27
+ 'lifecycle.shareable',
28
+ 'lifecycle.allow_multiple',
29
+ 'lifecycle.generate_on_start',
30
+ 'recipient.requires_phone_number',
31
+ 'highlight.enabled',
32
+ 'highlight.show_to_recipient',
33
+ 'distribution.mirror_to_advoca',
34
+ ];
35
+ /** The seven metadata paths as a runtime list, so a consumer can iterate the vocabulary it renders. */
36
+ export const TEMPLATE_META_FIELDS = [
37
+ 'title',
38
+ 'description',
39
+ 'visibility',
40
+ 'instancePolicy.requiredAccessLevel',
41
+ 'instancePolicy.invitationRequired',
42
+ 'instancePolicy.initiator',
43
+ 'instancePolicy.template_update_mode',
44
+ ];
45
+ /**
46
+ * The owner-domain soft-reference sets (REQ-013): ids only, no bodies, no FK validation.
47
+ *
48
+ * Authored by membership add/remove rather than whole-array writes, for DOC-LAW-1's reason: two
49
+ * authors adding different ids concurrently produce two member edits that both survive, where two
50
+ * whole-array patches would have the second discard the first.
51
+ */
52
+ export const COMPATIBILITY_COLLECTIONS = ['consentTemplateIds', 'smsTemplateIds'];
53
+ export const isMetaField = (value) => typeof value === 'string' && TEMPLATE_META_FIELDS.includes(value);
54
+ export const isSettingField = (value) => typeof value === 'string' && TEMPLATE_SETTING_FIELDS.includes(value);
55
+ export const isCompatibilityCollection = (value) => typeof value === 'string' && COMPATIBILITY_COLLECTIONS.includes(value);
56
+ // ─────────────────────────────── defaults, by exact path ───────────────────────────────
57
+ /** The metadata defaults, keyed by document-absolute path. Absent is the only encoding of each. */
58
+ export const TEMPLATE_META_DEFAULTS = {
59
+ title: '',
60
+ description: '',
61
+ visibility: 'visible',
62
+ 'instancePolicy.requiredAccessLevel': 4,
63
+ 'instancePolicy.invitationRequired': false,
64
+ 'instancePolicy.initiator': 'coordinator',
65
+ 'instancePolicy.template_update_mode': 'never',
66
+ };
67
+ /**
68
+ * The settings defaults.
69
+ *
70
+ * `rendering.refresh_button` is the one `true`: legacy's flag model initialises it on, so a template
71
+ * that never mentions it still shows the refresh control. Evidence is
72
+ * `asma-app-editor/src/mst/models/flags/QnrFlagsBase.model.ts`. Getting this one wrong is not a
73
+ * cosmetic defect — it flips a control for every imported template that omits the flag.
74
+ */
75
+ export const TEMPLATE_SETTING_DEFAULTS = {
76
+ 'journal.auto_import': false,
77
+ 'journal.requires_activity_id': false,
78
+ 'journal.register_new_activity': false,
79
+ 'journal.user_context_me': false,
80
+ 'pdf.import': false,
81
+ 'pdf.generate_for_participant': false,
82
+ 'pdf.send_to_journal': false,
83
+ 'rendering.tabs': false,
84
+ 'rendering.continuous': false,
85
+ 'rendering.multi_step': false,
86
+ 'rendering.collapse_all': false,
87
+ 'rendering.top_level_actions': false,
88
+ 'rendering.refresh_button': true,
89
+ 'rendering.filter_document_reports_on_tab': false,
90
+ 'rendering.hide_recipient_info': false,
91
+ 'lifecycle.rejectable': false,
92
+ 'lifecycle.shareable': false,
93
+ 'lifecycle.allow_multiple': false,
94
+ 'lifecycle.generate_on_start': false,
95
+ 'recipient.requires_phone_number': false,
96
+ 'highlight.enabled': false,
97
+ 'highlight.show_to_recipient': false,
98
+ 'distribution.mirror_to_advoca': false,
99
+ };
100
+ /** `meta.<field>` — the document-absolute path (and canonical conflict locus) of a metadata field. */
101
+ export const metaFieldPath = (field) => `meta.${field}`;
102
+ /** `meta.settings.<field>` — the document-absolute path (and locus) of a settings leaf. */
103
+ export const settingFieldPath = (field) => `meta.settings.${field}`;
104
+ /** `meta.compatibility.<collection>` — the whole set, which overlaps every one of its members. */
105
+ export const compatibilityCollectionPath = (collection) => `meta.compatibility.${collection}`;
106
+ /**
107
+ * The locus of ONE member of a soft-id set.
108
+ *
109
+ * The id is an opaque bracketed member, not a dotted path segment: a soft id may legitimately contain
110
+ * a `.` (and legacy numeric ids stringify to anything), so `meta.compatibility.consentTemplateIds.a.b`
111
+ * would be ambiguous between the id `a.b` and a nested path. `JSON.stringify` escapes quotes and
112
+ * backslashes, which makes the encoding injective — two different ids can never produce one locus,
113
+ * and a locus can never be mistaken for an ancestor of another member.
114
+ *
115
+ * NFC-normalised for the same reason the stored set is (see `normalizeCompatibilityId`): the canonical
116
+ * serializer normalises strings, so two NFC-equivalent spellings are ONE member and must be ONE locus.
117
+ */
118
+ export const compatibilityIdPath = (collection, id) => `${compatibilityCollectionPath(collection)}[${JSON.stringify(id.normalize('NFC'))}]`;
119
+ /**
120
+ * Every default this surface declares, by exact document-absolute path.
121
+ *
122
+ * A `Map` rather than an object so a path containing a `__proto__`-shaped segment cannot reach
123
+ * `Object.prototype` during lookup.
124
+ */
125
+ export const TEMPLATE_AUTHORING_DEFAULTS = new Map([
126
+ ...TEMPLATE_META_FIELDS.map((field) => [metaFieldPath(field), TEMPLATE_META_DEFAULTS[field]]),
127
+ ...TEMPLATE_SETTING_FIELDS.map((field) => [settingFieldPath(field), TEMPLATE_SETTING_DEFAULTS[field]]),
128
+ ]);
129
+ /**
130
+ * Whether `value` at `path` is this surface's declared default and must therefore be omitted.
131
+ *
132
+ * Exact-path only, by design — see the module header. Feeds `templateAuthoringIsDefault`, which is
133
+ * the canonical-write predicate; it is deliberately NOT part of the released
134
+ * `templateDocumentIsDefault` used to verify historical stored snapshots.
135
+ */
136
+ export const isTemplateAuthoringDefault = (path, value) => TEMPLATE_AUTHORING_DEFAULTS.has(path) && TEMPLATE_AUTHORING_DEFAULTS.get(path) === value;
137
+ /** The declared default of a metadata field — total, so a reader never spells one itself. */
138
+ export const templateMetaDefault = (field) => TEMPLATE_META_DEFAULTS[field];
139
+ /** The declared default of a settings leaf. */
140
+ export const templateSettingDefault = (field) => TEMPLATE_SETTING_DEFAULTS[field];
141
+ /** `meta.settings.<name>` — where legacy's flat flag bag landed on import. */
142
+ const flatSettingAlias = (name) => `meta.settings.${name}`;
143
+ /**
144
+ * The recognized alias spellings, keyed by canonical document-absolute path.
145
+ *
146
+ * Closed and explicit: a spelling absent here is an ordinary unknown member that this surface must
147
+ * leave alone, not a value it may read or clear. Extending the table is the only way to recognize a
148
+ * new legacy spelling, which is what keeps "recognized alias" from becoming "anything that looks
149
+ * related".
150
+ */
151
+ export const TEMPLATE_AUTHORING_ALIASES = new Map([
152
+ // M-008: the field map's `doc.meta.initiator` is a location drift. The canonical producer home is
153
+ // `meta.instancePolicy.initiator`; the root spelling is readable, never written, and cleared on a
154
+ // typed write so choosing the omitted default cannot resurrect it.
155
+ ['meta.instancePolicy.initiator', { aliasPaths: ['meta.initiator'], strategy: 'canonical-first' }],
156
+ // M-009: legacy's assurance tier arrived as `meta.security_level`. Every explicit tier is preserved
157
+ // without binary remapping, so the alias is read as a tier and not as "authenticated yes/no".
158
+ [
159
+ 'meta.instancePolicy.requiredAccessLevel',
160
+ { aliasPaths: ['meta.security_level'], strategy: 'canonical-first' },
161
+ ],
162
+ // M-023: `is_auto_importable` is the accepted second spelling.
163
+ [
164
+ 'meta.settings.journal.auto_import',
165
+ { aliasPaths: [flatSettingAlias('auto_import'), flatSettingAlias('is_auto_importable')], strategy: 'or' },
166
+ ],
167
+ // M-024/025: three legacy spellings of one requirement, the third a preserved misspelling.
168
+ [
169
+ 'meta.settings.journal.requires_activity_id',
170
+ {
171
+ aliasPaths: [
172
+ flatSettingAlias('activityId_required'),
173
+ flatSettingAlias('soknadid_required'),
174
+ flatSettingAlias('sokndaid_required'),
175
+ ],
176
+ strategy: 'or',
177
+ },
178
+ ],
179
+ ['meta.settings.journal.register_new_activity', { aliasPaths: [flatSettingAlias('reg_new_activity')], strategy: 'canonical-first' }],
180
+ ['meta.settings.journal.user_context_me', { aliasPaths: [flatSettingAlias('user_context_me')], strategy: 'canonical-first' }],
181
+ ['meta.settings.pdf.import', { aliasPaths: [flatSettingAlias('import_pdf')], strategy: 'canonical-first' }],
182
+ ['meta.settings.pdf.generate_for_participant', { aliasPaths: [flatSettingAlias('generate_pdf_for_participant')], strategy: 'canonical-first' }],
183
+ ['meta.settings.pdf.send_to_journal', { aliasPaths: [flatSettingAlias('send_pdf_to_journal')], strategy: 'canonical-first' }],
184
+ ['meta.settings.rendering.tabs', { aliasPaths: [flatSettingAlias('tab_mode')], strategy: 'canonical-first' }],
185
+ ['meta.settings.rendering.continuous', { aliasPaths: [flatSettingAlias('continuous')], strategy: 'canonical-first' }],
186
+ ['meta.settings.rendering.multi_step', { aliasPaths: [flatSettingAlias('multi_step_questionnaire')], strategy: 'canonical-first' }],
187
+ ['meta.settings.rendering.collapse_all', { aliasPaths: [flatSettingAlias('collapse_all')], strategy: 'canonical-first' }],
188
+ ['meta.settings.rendering.top_level_actions', { aliasPaths: [flatSettingAlias('top_level_actions')], strategy: 'canonical-first' }],
189
+ ['meta.settings.rendering.refresh_button', { aliasPaths: [flatSettingAlias('refresh_button')], strategy: 'canonical-first' }],
190
+ ['meta.settings.rendering.filter_document_reports_on_tab', { aliasPaths: [flatSettingAlias('filter_document_reports_on_tab')], strategy: 'canonical-first' }],
191
+ // M-038: legacy `hide_external_key` hides recipient-identifying columns; the v2 name states what is
192
+ // hidden rather than preserving the legacy key's name for a thing that is not a key.
193
+ ['meta.settings.rendering.hide_recipient_info', { aliasPaths: [flatSettingAlias('hide_external_key')], strategy: 'canonical-first' }],
194
+ ['meta.settings.lifecycle.rejectable', { aliasPaths: [flatSettingAlias('rejectable')], strategy: 'canonical-first' }],
195
+ ['meta.settings.lifecycle.shareable', { aliasPaths: [flatSettingAlias('shareable')], strategy: 'canonical-first' }],
196
+ ['meta.settings.lifecycle.allow_multiple', { aliasPaths: [flatSettingAlias('allow_multiple')], strategy: 'canonical-first' }],
197
+ ['meta.settings.lifecycle.generate_on_start', { aliasPaths: [flatSettingAlias('generate_on_start')], strategy: 'canonical-first' }],
198
+ // M-043: the released typed spelling `settings.recipient.ask_for_phone_nr` is itself now an alias —
199
+ // it shipped, so documents carry it and it must stay readable and replayable (ADR-0008 DEC-006).
200
+ // The flat legacy spelling is the second alias. New producers write only `requires_phone_number`.
201
+ [
202
+ 'meta.settings.recipient.requires_phone_number',
203
+ {
204
+ aliasPaths: ['meta.settings.recipient.ask_for_phone_nr', flatSettingAlias('ask_for_phone_nr')],
205
+ strategy: 'canonical-first',
206
+ },
207
+ ],
208
+ ['meta.settings.highlight.enabled', { aliasPaths: [flatSettingAlias('highlight_rule')], strategy: 'canonical-first' }],
209
+ ['meta.settings.highlight.show_to_recipient', { aliasPaths: [flatSettingAlias('show_highlight_rule_to_patient')], strategy: 'canonical-first' }],
210
+ ['meta.settings.distribution.mirror_to_advoca', { aliasPaths: [flatSettingAlias('mirror_to_advoca')], strategy: 'canonical-first' }],
211
+ ]);
212
+ /** The recognized alias paths of one canonical path, or none. */
213
+ export const templateAliasPathsOf = (canonicalPath) => TEMPLATE_AUTHORING_ALIASES.get(canonicalPath)?.aliasPaths ?? [];
214
+ /**
215
+ * The canonical paths a write at `path` reaches through the recognized alias table.
216
+ *
217
+ * **Overlap, not equality**, and that distinction was a reproduced defect. An open patch writing
218
+ * `initiator.unresolved` is writing INSIDE the recognized alias `meta.initiator`: it makes that path
219
+ * an object, and the next typed initiator write deletes the alias wholesale — taking the intervening
220
+ * data with it. Matching the alias exactly classified the two as disjoint, so the orders produced
221
+ * different documents with no conflict raised, which is precisely the lost update the locus
222
+ * machinery exists to catch. Ancestor and descendant both count, the same way they do for canonical
223
+ * loci.
224
+ *
225
+ * Plural because one legacy spelling could in principle serve two canonical fields; the lookup is a
226
+ * scan rather than a reverse index so the forward table stays the single declaration.
227
+ */
228
+ export const templateCanonicalPathsTouchedByAlias = (path) => [...TEMPLATE_AUTHORING_ALIASES.entries()]
229
+ .filter(([, rule]) => rule.aliasPaths.some((aliasPath) => templateLociOverlap(path, aliasPath)))
230
+ .map(([canonicalPath]) => canonicalPath);
231
+ const ABSENT = { status: 'absent' };
232
+ const isPlainObject = (value) => {
233
+ if (typeof value !== 'object' || value === null)
234
+ return false;
235
+ const proto = Object.getPrototypeOf(value);
236
+ return proto === Object.prototype || proto === null;
237
+ };
238
+ /**
239
+ * Reads a dotted path by OWN properties only.
240
+ *
241
+ * `in` and plain member access would both walk the prototype chain, so a path ending in `constructor`
242
+ * or `toString` would report a value no document stores. `Object.hasOwn` is the check that makes
243
+ * "the document says so" the only way a value is present.
244
+ */
245
+ const readOwnPath = (root, path) => {
246
+ const segments = path.split('.');
247
+ let current = root;
248
+ let walked = '';
249
+ for (const segment of segments) {
250
+ // `undefined` is ABSENCE at every depth, never a blocked container: the reader is handed
251
+ // `{ meta: undefined }` for a brand-new family that carries no `meta` key at all, and calling
252
+ // that malformed would put a finding on every field of an empty document.
253
+ if (current === undefined)
254
+ return ABSENT;
255
+ if (!isPlainObject(current))
256
+ return { status: 'blocked', blockedAt: walked, value: current };
257
+ if (!Object.hasOwn(current, segment))
258
+ return ABSENT;
259
+ current = current[segment];
260
+ walked = walked === '' ? segment : `${walked}.${segment}`;
261
+ }
262
+ return current === undefined ? ABSENT : { status: 'present', value: current };
263
+ };
264
+ const readBoolean = (value) => (typeof value === 'boolean' ? value : undefined);
265
+ const readString = (value) => (typeof value === 'string' ? value : undefined);
266
+ const readEnumerated = (allowed) => (value) => typeof value === 'string' && allowed.includes(value) ? value : undefined;
267
+ const REQUIRED_ACCESS_LEVELS = [1, 2, 3, 4];
268
+ const readAccessLevel = (value) => REQUIRED_ACCESS_LEVELS.find((level) => level === value);
269
+ /**
270
+ * What each metadata field accepts — the SINGLE declaration, read by both the total reader and the
271
+ * reducer's replay re-validation.
272
+ *
273
+ * One table rather than a validator per consumer: the reducer must re-check a replayed op (a stored
274
+ * log replays with no validator in front of it), and if it spelled the check itself that spelling
275
+ * would be free to drift from the reader's. `satisfies` keeps each entry's precise value type, so a
276
+ * reader wired to the wrong field is a compile error.
277
+ */
278
+ const META_FIELD_READERS = {
279
+ title: readString,
280
+ description: readString,
281
+ visibility: readEnumerated(TEMPLATE_VISIBILITIES),
282
+ 'instancePolicy.requiredAccessLevel': readAccessLevel,
283
+ 'instancePolicy.invitationRequired': readBoolean,
284
+ 'instancePolicy.initiator': readEnumerated(INITIATORS),
285
+ 'instancePolicy.template_update_mode': readEnumerated(TEMPLATE_UPDATE_MODES),
286
+ };
287
+ /**
288
+ * The value a metadata field accepts, or `undefined` when the candidate is not one.
289
+ *
290
+ * The cast is the one place a union of precise readers has to be called through a dynamic field: each
291
+ * entry accepts `unknown` and returns its own field's value type, so widening the return to
292
+ * `MetaFieldValue` is sound — it is the union of exactly those types.
293
+ */
294
+ export const parseMetaFieldValue = (field, value) => META_FIELD_READERS[field](value);
295
+ /**
296
+ * Resolves one field from its canonical path and recognized aliases, collecting findings.
297
+ *
298
+ * The four outcomes a caller must be able to tell apart, and why each needs its own treatment:
299
+ * absent (use the default, say nothing), canonical present (use it), alias-only present (use it and
300
+ * say so, because the next typed write will replace the spelling), and malformed (use the default but
301
+ * record that the document disagrees — the one case where showing the default silently would be a
302
+ * lie).
303
+ */
304
+ const resolveField = (root, canonicalPath, fallback, read, findings, combine) => {
305
+ const rule = TEMPLATE_AUTHORING_ALIASES.get(canonicalPath);
306
+ /**
307
+ * One spelling's contribution: the parsed value when the document holds a usable one, plus
308
+ * whether the document holds an own property there AT ALL.
309
+ *
310
+ * The two are separate because a malformed value is PRESENT. Collapsing them is what let a stale
311
+ * `ask_for_phone_nr: true` outvote an explicit canonical `requires_phone_number: 'false'` — the
312
+ * canonical property existed, so no alias should have been consulted, but a malformed parse looked
313
+ * exactly like absence.
314
+ */
315
+ const readSpelling = (path) => {
316
+ const raw = readOwnPath(root, path);
317
+ if (raw.status === 'absent')
318
+ return { present: false, value: undefined };
319
+ if (raw.status === 'blocked') {
320
+ findings.push({
321
+ kind: 'malformed-ancestor',
322
+ locus: canonicalPath,
323
+ paths: [raw.blockedAt],
324
+ detail: `"${raw.blockedAt}" holds ${describeContainer(raw.value)}, not a container, so ` +
325
+ `"${path}" cannot be read; the typed operations refuse to write through it`,
326
+ });
327
+ // Blocked is NOT presence: there is no own property to defend, and the field has no
328
+ // trustworthy value. The finding is what keeps the returned default distinguishable from
329
+ // an authored one.
330
+ return { present: false, value: undefined };
331
+ }
332
+ const parsed = read(raw.value);
333
+ if (parsed === undefined) {
334
+ findings.push({
335
+ kind: 'malformed-value',
336
+ locus: canonicalPath,
337
+ paths: [path],
338
+ detail: `stored value ${JSON.stringify(raw.value) ?? String(raw.value)} is not a valid value for this field`,
339
+ });
340
+ }
341
+ return { present: true, value: parsed };
342
+ };
343
+ const canonical = readSpelling(canonicalPath);
344
+ /**
345
+ * Aliases are always READ, because a stale spelling is worth REPORTING even when it cannot win.
346
+ * What the strategy below decides is only whether one may supply the effective value.
347
+ */
348
+ const aliasValues = (rule?.aliasPaths ?? [])
349
+ .map((path) => ({ path, value: readSpelling(path).value }))
350
+ .filter((entry) => entry.value !== undefined);
351
+ // The OR strategy folds canonical and aliases together: any spelling asserting `true` wins, and a
352
+ // disagreement is reported rather than resolved by key order.
353
+ //
354
+ // **This is deliberately NOT the canonical-first rule below, and the frozen contract says so in
355
+ // both directions.** The two journal fields unify several legacy spellings of ONE requirement
356
+ // written by different code paths over the years, so a template that set any of them required an
357
+ // activity id; resolving to the canonical `false` while `soknadid_required: true` is still stored
358
+ // would silently drop that requirement. Phone is the explicit counter-case — it "never ORs
359
+ // competing canonical/old phone keys" — which is why it uses canonical-first and this does not.
360
+ // The suite pins that only these two boolean settings leaves use `or`.
361
+ //
362
+ // `combine` is supplied by the caller rather than carried on the rule, because a combiner on the
363
+ // rule would have to be typed over every field's value type at once. Every `or` rule in the table
364
+ // is a boolean settings leaf, which is what makes one `||` combiner sufficient — and that
365
+ // invariant is asserted in the suite rather than left as a comment, so a future `or` rule on a
366
+ // non-boolean field is a red test and not a silent fall-through to canonical-first.
367
+ if (rule?.strategy === 'or' && combine !== undefined) {
368
+ const contributors = [
369
+ ...(canonical.value === undefined ? [] : [{ path: canonicalPath, value: canonical.value }]),
370
+ ...aliasValues,
371
+ ];
372
+ if (contributors.length === 0)
373
+ return fallback;
374
+ const folded = contributors.reduce((acc, entry) => combine(acc, entry.value), contributors[0].value);
375
+ if (contributors.some((entry) => entry.value !== folded)) {
376
+ findings.push({
377
+ kind: 'alias-disagreement',
378
+ locus: canonicalPath,
379
+ paths: contributors.map((entry) => entry.path),
380
+ detail: `recognized spellings disagree; resolved conservatively to ${JSON.stringify(folded)}`,
381
+ });
382
+ }
383
+ return folded;
384
+ }
385
+ /**
386
+ * **Canonical-first: an alias may supply the value ONLY while the canonical property is absent.**
387
+ *
388
+ * The malformed half is the one that was wrong and is reproduced in the suite: a canonical
389
+ * `requires_phone_number: 'false'` is PRESENT — the author wrote this field, here — and a stale
390
+ * `ask_for_phone_nr: true` must not be allowed to re-decide it just because the stored value does
391
+ * not parse. Treating "unusable" as "absent" is what let the old spelling win. A malformed
392
+ * canonical therefore resolves to the declared default, with the `malformed-value` finding already
393
+ * recorded above so the default is never mistaken for an authored one.
394
+ */
395
+ if (canonical.present) {
396
+ if (canonical.value === undefined)
397
+ return fallback;
398
+ // A disagreeing alias is still a classified finding: it is a stale value a reader on an older
399
+ // contract could pick up, and the next typed write is what clears it.
400
+ const disagreeing = aliasValues.filter((entry) => entry.value !== canonical.value);
401
+ if (disagreeing.length > 0) {
402
+ findings.push({
403
+ kind: 'alias-disagreement',
404
+ locus: canonicalPath,
405
+ paths: [canonicalPath, ...disagreeing.map((entry) => entry.path)],
406
+ detail: `canonical value ${JSON.stringify(canonical.value)} wins over ${disagreeing
407
+ .map((entry) => `${entry.path}=${JSON.stringify(entry.value)}`)
408
+ .join(', ')}`,
409
+ });
410
+ }
411
+ return canonical.value;
412
+ }
413
+ const first = aliasValues[0];
414
+ if (first !== undefined) {
415
+ findings.push({
416
+ kind: 'legacy-alias-read',
417
+ locus: canonicalPath,
418
+ paths: [first.path],
419
+ detail: `effective value read from the recognized legacy spelling "${first.path}"`,
420
+ });
421
+ const disagreeing = aliasValues.slice(1).filter((entry) => entry.value !== first.value);
422
+ if (disagreeing.length > 0) {
423
+ findings.push({
424
+ kind: 'alias-disagreement',
425
+ locus: canonicalPath,
426
+ paths: [first.path, ...disagreeing.map((entry) => entry.path)],
427
+ detail: 'recognized legacy spellings disagree; the first recognized one wins',
428
+ });
429
+ }
430
+ return first.value;
431
+ }
432
+ return fallback;
433
+ };
434
+ /** Names what a blocking value actually is, so a finding reads as evidence rather than a category. */
435
+ const describeContainer = (value) => value === null ? 'null' : Array.isArray(value) ? 'an array' : `a ${typeof value}`;
436
+ /**
437
+ * The canonical member form of one soft id.
438
+ *
439
+ * Two normalisations, each for a stated reason:
440
+ *
441
+ * - **A legacy numeric id becomes its lossless decimal string.** The sets are declared `string[]`, and
442
+ * legacy template ids are integers; `String(n)` round-trips every JS number that can be an id, so
443
+ * the port keeps the identity instead of dropping the association.
444
+ * - **NFC.** `canonicalJson` NFC-normalises strings, so two NFC-equivalent spellings of one id
445
+ * serialise to the same bytes. Deduplicating on the raw strings would therefore store two members
446
+ * that canonicalize to one, which is a duplicate inside a *set* and a second encoding of one state.
447
+ */
448
+ export const normalizeCompatibilityId = (value) => {
449
+ if (typeof value === 'string')
450
+ return value.length === 0 ? undefined : value.normalize('NFC');
451
+ if (typeof value === 'number' && Number.isFinite(value))
452
+ return String(value);
453
+ return undefined;
454
+ };
455
+ /**
456
+ * The id a NEW typed membership operation may carry: a nonempty string, NFC-normalised. Never a number.
457
+ *
458
+ * Separate from {@link normalizeCompatibilityId} on purpose, and the separation is the point. Numeric
459
+ * tolerance exists for **stored legacy members** — ids the port inherited and must not drop. A new
460
+ * operation is authored today against a contract whose wire schema says `string > 0`, so accepting
461
+ * `id: 42` in the reducer would mean the schema and the replay path disagree about what the vocabulary
462
+ * is: an op refused at the boundary would still land when replayed from a log. One spelling for new
463
+ * producers, full tolerance for old data.
464
+ */
465
+ export const parseCompatibilityOperationId = (value) => typeof value === 'string' && value.length > 0 ? value.normalize('NFC') : undefined;
466
+ /**
467
+ * The canonical stored form of a touched soft-id set: sorted, unique, NFC.
468
+ *
469
+ * Sorted by UTF-16 code unit, which is the same comparison `canonicalJson` uses for object keys —
470
+ * one ordering rule in the contract rather than two. Sorting at all is what makes the set's identity
471
+ * independent of the order members were added in: two authors who add the same two ids in opposite
472
+ * orders must produce one document, not two hashes.
473
+ */
474
+ export const normalizeCompatibilityIds = (ids) => [...new Set(ids)].sort();
475
+ /** A stored collection, read with its malformed members reported rather than silently dropped. */
476
+ const resolveCompatibilityCollection = (root, collection, findings) => {
477
+ const locus = compatibilityCollectionPath(collection);
478
+ const raw = readOwnPath(root, locus);
479
+ if (raw.status === 'absent')
480
+ return [];
481
+ if (raw.status === 'blocked') {
482
+ findings.push({
483
+ kind: 'malformed-ancestor',
484
+ locus,
485
+ paths: [raw.blockedAt],
486
+ detail: `"${raw.blockedAt}" holds ${describeContainer(raw.value)}, not a container, so ` +
487
+ `"${locus}" cannot be read; the typed membership operations refuse to write through it`,
488
+ });
489
+ return [];
490
+ }
491
+ if (!Array.isArray(raw.value)) {
492
+ findings.push({
493
+ kind: 'malformed-collection',
494
+ locus,
495
+ paths: [locus],
496
+ detail: `stored value is ${describeContainer(raw.value)}, not an array of soft ids`,
497
+ });
498
+ return [];
499
+ }
500
+ const members = [];
501
+ raw.value.forEach((member, index) => {
502
+ const normalized = normalizeCompatibilityId(member);
503
+ if (normalized === undefined) {
504
+ findings.push({
505
+ kind: 'malformed-collection',
506
+ locus,
507
+ paths: [`${locus}.${index}`],
508
+ detail: `member ${index} is not a nonempty soft id`,
509
+ });
510
+ return;
511
+ }
512
+ members.push(normalized);
513
+ });
514
+ return normalizeCompatibilityIds(members);
515
+ };
516
+ /**
517
+ * The one total reader over the stored metadata — the single declaration of what this surface means.
518
+ *
519
+ * **Non-mutating, and that is load-bearing rather than hygiene.** The caller is usually holding the
520
+ * live document the reducer also holds, so a reader that filled in a default would change the hashed
521
+ * bytes of a document nobody edited — minting a version from a page load. Nothing here writes to
522
+ * `meta`, and the returned `compatibility` arrays are fresh.
523
+ *
524
+ * Accepts `undefined` so a brand-new family (no `meta` key at all, DOC-LAW-2) resolves to the same
525
+ * total object as a document that spelled every default out.
526
+ */
527
+ export const resolveTemplateAuthoringMeta = (meta) => {
528
+ const findings = [];
529
+ const root = { meta };
530
+ const orBoolean = (left, right) => left || right;
531
+ const settings = Object.fromEntries(TEMPLATE_SETTING_FIELDS.map((field) => [
532
+ field,
533
+ resolveField(root, settingFieldPath(field), TEMPLATE_SETTING_DEFAULTS[field], readBoolean, findings, orBoolean),
534
+ ]));
535
+ const resolved = {
536
+ title: resolveField(root, 'meta.title', TEMPLATE_META_DEFAULTS.title, META_FIELD_READERS.title, findings),
537
+ description: resolveField(root, 'meta.description', TEMPLATE_META_DEFAULTS.description, META_FIELD_READERS.description, findings),
538
+ visibility: resolveField(root, 'meta.visibility', TEMPLATE_META_DEFAULTS.visibility, META_FIELD_READERS.visibility, findings),
539
+ instancePolicy: {
540
+ requiredAccessLevel: resolveField(root, 'meta.instancePolicy.requiredAccessLevel', TEMPLATE_META_DEFAULTS['instancePolicy.requiredAccessLevel'], META_FIELD_READERS['instancePolicy.requiredAccessLevel'], findings),
541
+ invitationRequired: resolveField(root, 'meta.instancePolicy.invitationRequired', TEMPLATE_META_DEFAULTS['instancePolicy.invitationRequired'], META_FIELD_READERS['instancePolicy.invitationRequired'], findings),
542
+ initiator: resolveField(root, 'meta.instancePolicy.initiator', TEMPLATE_META_DEFAULTS['instancePolicy.initiator'], META_FIELD_READERS['instancePolicy.initiator'], findings),
543
+ template_update_mode: resolveField(root, 'meta.instancePolicy.template_update_mode', TEMPLATE_META_DEFAULTS['instancePolicy.template_update_mode'], META_FIELD_READERS['instancePolicy.template_update_mode'], findings),
544
+ },
545
+ settings,
546
+ compatibility: {
547
+ consentTemplateIds: resolveCompatibilityCollection(root, 'consentTemplateIds', findings),
548
+ smsTemplateIds: resolveCompatibilityCollection(root, 'smsTemplateIds', findings),
549
+ },
550
+ findings,
551
+ };
552
+ const legacy = readOwnPath(root, 'meta.legacy');
553
+ if (legacy.status === 'absent')
554
+ return resolved;
555
+ if (legacy.status === 'blocked') {
556
+ findings.push({
557
+ kind: 'malformed-ancestor',
558
+ locus: 'meta.legacy',
559
+ paths: [legacy.blockedAt],
560
+ detail: `"${legacy.blockedAt}" holds ${describeContainer(legacy.value)}, not a container`,
561
+ });
562
+ return resolved;
563
+ }
564
+ if (!isPlainObject(legacy.value)) {
565
+ findings.push({
566
+ kind: 'malformed-value',
567
+ locus: 'meta.legacy',
568
+ paths: ['meta.legacy'],
569
+ detail: `stored residue is ${describeContainer(legacy.value)}, not a container`,
570
+ });
571
+ return resolved;
572
+ }
573
+ // Shallow-copied so a consumer cannot reach into the live document through the result.
574
+ return { ...resolved, legacy: { ...legacy.value } };
575
+ };
576
+ // ─────────────────────────────── canonical loci and concurrent intent ───────────────────────────────
577
+ /**
578
+ * Whether two loci name overlapping state.
579
+ *
580
+ * Both directions count, because the log a new submission is checked against contains ancestor writes:
581
+ * a released `template.updateMeta` patch on `instancePolicy` overlaps a typed write to
582
+ * `instancePolicy.initiator`, and a whole-set write to `compatibility.consentTemplateIds` overlaps
583
+ * every member of that set. Treating only equal strings as overlapping is exactly the missed check
584
+ * that lets a catch-up op silently overwrite another author's intent.
585
+ */
586
+ export const templateLociOverlap = (left, right) => left === right || isAncestorLocus(left, right) || isAncestorLocus(right, left);
587
+ /** `[` as well as `.`, so a collection locus is an ancestor of its bracketed member loci. */
588
+ const isAncestorLocus = (ancestor, descendant) => descendant.startsWith(`${ancestor}.`) || descendant.startsWith(`${ancestor}[`);
589
+ /** The canonical stored leaf value a typed write lands: `null` when it restores the default. */
590
+ const storedLeafValue = (path, value) => value === null || isTemplateAuthoringDefault(path, value) ? null : value;
591
+ /**
592
+ * Which canonical loci an operation touches, and what it intends there.
593
+ *
594
+ * The four typed arms report determinate intents. The two released open arms report `opaque` intents
595
+ * for every canonical locus their patch keys reach — by exact path, by ancestor, by descendant, and
596
+ * through the recognized alias table, because a patch that writes `settings.ask_for_phone_nr` is
597
+ * writing the phone requirement whatever it spells it. Every other operation touches no metadata and
598
+ * returns nothing, which is what makes "disjoint loci commute" true by construction for the rest of
599
+ * the vocabulary.
600
+ */
601
+ export const templateAuthoringIntentsOf = (op) => {
602
+ switch (op.type) {
603
+ case 'template.setMetaFieldTyped': {
604
+ const path = metaFieldPath(op.field);
605
+ return [{ locus: path, kind: 'set', value: storedLeafValue(path, op.value) }];
606
+ }
607
+ case 'template.setSettingTyped': {
608
+ const path = settingFieldPath(op.field);
609
+ return [{ locus: path, kind: 'set', value: storedLeafValue(path, op.value) }];
610
+ }
611
+ case 'template.addCompatibilityId': {
612
+ // The strict parser, matching the reducer: an op the reducer refuses must claim no locus,
613
+ // or a refused write would still be able to block a valid concurrent one.
614
+ const id = parseCompatibilityOperationId(op.id);
615
+ if (id === undefined)
616
+ return [];
617
+ return [{ locus: compatibilityIdPath(op.collection, id), kind: 'set', value: id }];
618
+ }
619
+ case 'template.removeCompatibilityId': {
620
+ const id = parseCompatibilityOperationId(op.id);
621
+ if (id === undefined)
622
+ return [];
623
+ return [{ locus: compatibilityIdPath(op.collection, id), kind: 'set', value: null }];
624
+ }
625
+ case 'template.updateMeta':
626
+ return openPatchIntents(op.patch, 'meta');
627
+ case 'template.updateSettings':
628
+ return openPatchIntents(op.patch, 'meta.settings');
629
+ default:
630
+ return [];
631
+ }
632
+ };
633
+ /**
634
+ * Every canonical locus known to this surface — the set an open patch key is matched against.
635
+ *
636
+ * Collection loci rather than member loci, deliberately: a collection locus is an ancestor of each of
637
+ * its `[...]` members, so one entry covers "this patch replaces the whole set" and "this patch touches
638
+ * member X" at once, which is what makes a whole-set write overlap a concurrent membership edit.
639
+ */
640
+ const CANONICAL_LOCI = [
641
+ ...TEMPLATE_META_FIELDS.map(metaFieldPath),
642
+ ...TEMPLATE_SETTING_FIELDS.map(settingFieldPath),
643
+ ...COMPATIBILITY_COLLECTIONS.map(compatibilityCollectionPath),
644
+ ];
645
+ const openPatchIntents = (patch, root) => {
646
+ const loci = new Set();
647
+ for (const key of Object.keys(patch)) {
648
+ // A patch key whose FIRST segment is empty writes nothing: `writeField` returns the record
649
+ // unchanged on an empty head, so `''` and `'.title'` are both historical no-ops. Mapping them
650
+ // to the patch root was a reproduced defect — the root is an ancestor of every canonical
651
+ // locus, so one inert key made an old patch conflict with every typed field in the document.
652
+ const [head] = key.split('.');
653
+ if (head === undefined || head === '')
654
+ continue;
655
+ const written = `${root}.${key}`;
656
+ for (const locus of CANONICAL_LOCI) {
657
+ if (templateLociOverlap(written, locus))
658
+ loci.add(locus);
659
+ }
660
+ for (const canonicalPath of templateCanonicalPathsTouchedByAlias(written))
661
+ loci.add(canonicalPath);
662
+ }
663
+ return [...loci].map((locus) => ({ locus, kind: 'opaque' }));
664
+ };
665
+ export const classifyTemplateAuthoringOverlap = (left, right) => {
666
+ const leftIntents = templateAuthoringIntentsOf(left);
667
+ const rightIntents = templateAuthoringIntentsOf(right);
668
+ const overlapping = new Set();
669
+ let converges = true;
670
+ for (const mine of leftIntents) {
671
+ for (const theirs of rightIntents) {
672
+ if (!templateLociOverlap(mine.locus, theirs.locus))
673
+ continue;
674
+ overlapping.add(mine.locus);
675
+ overlapping.add(theirs.locus);
676
+ if (mine.kind !== 'set' || theirs.kind !== 'set' || mine.value !== theirs.value)
677
+ converges = false;
678
+ }
679
+ }
680
+ if (overlapping.size === 0)
681
+ return { status: 'disjoint' };
682
+ const loci = [...overlapping].sort();
683
+ return converges ? { status: 'convergent', loci } : { status: 'conflict', loci };
684
+ };
685
+ /**
686
+ * The value a document currently holds at a locus, `null` when absent.
687
+ *
688
+ * Exists so the conflict record's base and current values come from one implementation rather than
689
+ * each caller's own traversal: a generic "read the structure" fallback is what produced markers whose
690
+ * base and left values were the same current value, which tells a resolver nothing. `null` for absent
691
+ * is deliberate and legal — conflict records are outside the template's DOC-LAW-2.
692
+ *
693
+ * A bracketed member locus answers membership: the id when the set contains it, `null` when not.
694
+ */
695
+ export const readTemplateAuthoringLocus = (document, locus) => {
696
+ const member = /^(?<collection>meta\.compatibility\.[^.[]+)\[(?<id>.*)\]$/u.exec(locus);
697
+ if (member?.groups !== undefined) {
698
+ const parsedId = JSON.parse(member.groups['id']);
699
+ if (typeof parsedId !== 'string')
700
+ return null;
701
+ const set = readOwnPath(document, member.groups['collection']);
702
+ if (set.status !== 'present' || !Array.isArray(set.value))
703
+ return null;
704
+ return set.value.some((entry) => normalizeCompatibilityId(entry) === parsedId)
705
+ ? parsedId
706
+ : null;
707
+ }
708
+ // A blocked read is reported as absence here on purpose: a conflict record carries values, and a
709
+ // scalar sitting where a container belongs is not the value of the locus that was asked for. The
710
+ // reader above is where that condition is classified and surfaced.
711
+ const read = readOwnPath(document, locus);
712
+ return read.status === 'present' ? read.value : null;
713
+ };
714
+ /**
715
+ * Where a template metadata conflict is recorded on the released marker shape.
716
+ *
717
+ * The document IS the entity for this surface — there is no per-field entity id — so the locus is the
718
+ * marker's `fieldPath` and the family document its `entityId`. Spelling that convention here keeps
719
+ * the real path in the record instead of a generic `_structure` placeholder.
720
+ */
721
+ export const templateAuthoringConflictTarget = (documentId, locus) => ({
722
+ entityType: 'template',
723
+ entityId: documentId,
724
+ fieldPath: locus,
725
+ });
726
+ //# sourceMappingURL=templateAuthoringMeta.js.map