asma-core-helpers 0.28.0 → 0.29.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.
@@ -6,7 +6,13 @@ import { IMPLEMENTED_ANSWER_OP_TYPES } from './answerOperations.js'
6
6
  import { IMPLEMENTED_OP_TYPES } from './operations.js'
7
7
  import { QUESTION_TYPES } from './questionTypes.js'
8
8
  import type { BindingTarget, QnrTemplateDocument } from './templateDocument.js'
9
- import { bindingTargetKey } from './templateDocument.js'
9
+ import {
10
+ BINDING_CARDINALITIES,
11
+ BINDING_ON_MANY,
12
+ BINDING_ON_MISSING,
13
+ BINDING_OPTION_DEFAULTS,
14
+ bindingTargetKey,
15
+ } from './templateDocument.js'
10
16
 
11
17
  /**
12
18
  * The ArkType schemas for the two hashed documents and both op vocabularies (plan TASK-003),
@@ -55,6 +61,8 @@ const recordOf = <T extends Type>(value: T): { '[string]': T } => ({ '[string]':
55
61
  const ruleConditionSchema = type({
56
62
  sourceQuestionId: 'string',
57
63
  alternativeId: 'string?',
64
+ /** M-067: the legacy conditional matches a SET of alternatives, which the singular id cannot carry. */
65
+ alternativeIds: 'string[]?',
58
66
  operator: 'string?',
59
67
  "value?": docScalar,
60
68
  ...({ '[string]': 'unknown' } as const),
@@ -67,9 +75,19 @@ const visibilityRuleSchema = type({
67
75
 
68
76
  const highlightRuleSchema = type({
69
77
  condition: ruleConditionSchema,
78
+ /** M-067 authored outputs. `is_highlighted`/`highlight_state` stay runtime and are absent by design. */
79
+ state: 'number?',
80
+ highlight: 'boolean?',
81
+ showLink: 'boolean?',
70
82
  ...({ '[string]': 'unknown' } as const),
71
83
  })
72
84
 
85
+ /** M-067 per-question narrative settings. `true`-only: DOC-LAW-2 makes `false` and absent the same. */
86
+ const highlightRuleSettingsSchema = type({
87
+ enabled: 'true?',
88
+ requiredAll: 'true?',
89
+ })
90
+
73
91
  const narrativeRuleSchema = type({
74
92
  condition: ruleConditionSchema,
75
93
  ...({ '[string]': 'unknown' } as const),
@@ -81,6 +99,16 @@ const qnrRuleSchema = type({
81
99
  '+': 'reject',
82
100
  })
83
101
 
102
+ /**
103
+ * M-068 answer prefill. No `condition`: the rule propagates a value rather than evaluating an
104
+ * operator, which is exactly why it is not a `visibilityRule`.
105
+ */
106
+ const prefillRuleSchema = type({
107
+ sourceQuestionId: 'string',
108
+ sourceParentQuestionId: 'string?',
109
+ ...({ '[string]': 'unknown' } as const),
110
+ })
111
+
84
112
  const questionGridConfigSchema = type({
85
113
  columnIds: 'string[]?',
86
114
  minRows: 'number?',
@@ -178,13 +206,24 @@ const bindingTargetSchema = type.or(
178
206
  type({ kind: '"gridColumn"', gridQuestionId: 'string', columnQuestionId: 'string' }),
179
207
  )
180
208
 
209
+ /**
210
+ * The three behaviour vocabularies, derived from the single declaration in `templateDocument.ts`
211
+ * rather than re-spelled — a second list of literals here could drift from the one the reducer and
212
+ * the UI branch on, and the drift would only show up as a validation refusal in production.
213
+ */
214
+ const bindingCardinalitySchema = type.enumerated(...BINDING_CARDINALITIES)
215
+ const bindingOnMissingSchema = type.enumerated(...BINDING_ON_MISSING)
216
+ const bindingOnManySchema = type.enumerated(...BINDING_ON_MANY)
217
+
181
218
  const mappingBindingSchema = type({
182
219
  nodeId: 'string',
183
220
  fieldId: 'string',
184
221
  target: bindingTargetSchema,
185
- cardinality: 'string?',
186
- onMissing: 'string?',
187
- onMany: 'string?',
222
+ // Closed sets, not `string?`: these compile into an immutable artifact, so a typo that validates
223
+ // here is a wrong prefill nobody can fix in place afterwards.
224
+ 'cardinality?': bindingCardinalitySchema,
225
+ 'onMissing?': bindingOnMissingSchema,
226
+ 'onMany?': bindingOnManySchema,
188
227
  ...({ '[string]': 'unknown' } as const),
189
228
  })
190
229
 
@@ -247,6 +286,9 @@ export const qnrTemplateDocumentSchema = type({
247
286
  narrativeRuleOrderByQuestionId: 'Record<string, string[]>?',
248
287
  "qnrRulesById?": recordOf(qnrRuleSchema),
249
288
  qnrRuleOrderByQuestionId: 'Record<string, string[]>?',
289
+ "prefillRulesById?": recordOf(prefillRuleSchema),
290
+ prefillRuleOrderByQuestionId: 'Record<string, string[]>?',
291
+ "highlightRuleSettingsByQuestionId?": recordOf(highlightRuleSettingsSchema),
250
292
  "dataMappingsById?": recordOf(dataMappingSchema),
251
293
  "mappingNodesById?": recordOf(mappingNodeSchema),
252
294
  "mappingBindingsById?": recordOf(mappingBindingSchema),
@@ -351,14 +393,23 @@ export const templateOpSchema = type.or(
351
393
  nodeId: 'string',
352
394
  fieldId: 'string',
353
395
  target: bindingTargetSchema,
396
+ 'cardinality?': bindingCardinalitySchema,
397
+ 'onMissing?': bindingOnMissingSchema,
398
+ 'onMany?': bindingOnManySchema,
354
399
  }),
355
400
  type({
356
401
  type: '"mappingBinding.update"',
357
402
  bindingId: 'string',
403
+ // `| null` on the three behaviours only: the op layer is where the absent-vs-cleared
404
+ // tri-state lives (operations.ts header), so returning a behaviour to its default is
405
+ // expressible without making "leave it alone" and "reset it" the same patch.
358
406
  patch: type({
359
407
  nodeId: 'string?',
360
408
  fieldId: 'string?',
361
- "target?": bindingTargetSchema,
409
+ 'target?': bindingTargetSchema,
410
+ 'cardinality?': bindingCardinalitySchema.or(type.null),
411
+ 'onMissing?': bindingOnMissingSchema.or(type.null),
412
+ 'onMany?': bindingOnManySchema.or(type.null),
362
413
  }),
363
414
  }),
364
415
  type({ type: '"mappingBinding.delete"', bindingId: 'string' }),
@@ -580,8 +631,26 @@ const TEMPLATE_DOCUMENT_DEFAULT_PATHS: readonly string[] = [
580
631
  'timestamps', // question.grid (legacy composite `row_timestamps`)
581
632
  ]
582
633
 
583
- export const templateDocumentIsDefault: IsDefault = (path, value) =>
584
- value === false && TEMPLATE_DOCUMENT_DEFAULT_PATHS.some((name) => path.endsWith(`.${name}`))
634
+ /**
635
+ * The binding behaviours, whose default is a **value** rather than `false` and whose path must
636
+ * therefore be matched exactly rather than by suffix.
637
+ *
638
+ * Anchored on `mappingBindingsById.<id>.<key>` on purpose: a mapping **node** may also carry a
639
+ * `cardinality`, and its default is the catalog relation's — not a literal. A suffix rule would
640
+ * read a node's deliberately-narrowed `cardinality: '0..1'` over a `0..*` relation as an omittable
641
+ * default and drop the one member that made the node take a single row.
642
+ */
643
+ const BINDING_OPTION_DEFAULT_PATH = /^mappingBindingsById\.[^.]+\.(cardinality|onMissing|onMany)$/
644
+
645
+ export const templateDocumentIsDefault: IsDefault = (path, value) => {
646
+ const option = BINDING_OPTION_DEFAULT_PATH.exec(path)?.[1]
647
+
648
+ if (option !== undefined) {
649
+ return value === BINDING_OPTION_DEFAULTS[option as keyof typeof BINDING_OPTION_DEFAULTS]
650
+ }
651
+
652
+ return value === false && TEMPLATE_DOCUMENT_DEFAULT_PATHS.some((name) => path.endsWith(`.${name}`))
653
+ }
585
654
 
586
655
  /**
587
656
  * The instance-side half of the default lint: every present-and-default field on a stored
@@ -27,6 +27,7 @@ export type VisibilityRuleId = string
27
27
  export type HighlightRuleId = string
28
28
  export type NarrativeRuleId = string
29
29
  export type QnrRuleId = string
30
+ export type PrefillRuleId = string
30
31
 
31
32
  /** A scalar a document may carry. Deliberately not `any`: DOC-LAW-2 bans `null`. */
32
33
  export type DocScalar = string | number | boolean
@@ -175,13 +176,45 @@ export type QnrAction = { kind?: string; [key: string]: unknown }
175
176
  export type RuleCondition = {
176
177
  sourceQuestionId: QuestionId
177
178
  alternativeId?: AltId
179
+ /**
180
+ * The legacy conditional matches the source answer against a **set** of alternatives
181
+ * (`condition.alternatives[]`), which the singular `alternativeId` cannot express (M-067). A
182
+ * primitive id array rather than a keyed collection because identity lives in the values and a
183
+ * member carrying nothing else reduces to `{}` under DOC-LAW-2 — the same reasoning that made
184
+ * `normalizeAlternativeRefs` emit a primitive array.
185
+ */
186
+ alternativeIds?: AltId[]
178
187
  operator?: string
179
188
  value?: DocScalar
180
189
  [key: string]: unknown
181
190
  }
182
191
 
183
192
  export type VisibilityRule = { condition: RuleCondition; [key: string]: unknown }
184
- export type HighlightRule = { condition: RuleCondition; [key: string]: unknown }
193
+ /**
194
+ * A highlight conditional (M-067). The three widened members are the authored outputs legacy stores
195
+ * on each rule: `state` is the highlight severity `setHighlightState` applies when the condition
196
+ * matches, `highlight` routes a highlighting rule from a plain conditional, and `showLink` is the
197
+ * per-rule link toggle. `is_highlighted`/`highlight_state` are deliberately absent — they are
198
+ * instance-computed runtime state, not authored content.
199
+ */
200
+ export type HighlightRule = {
201
+ condition: RuleCondition
202
+ state?: number
203
+ highlight?: boolean
204
+ showLink?: boolean
205
+ [key: string]: unknown
206
+ }
207
+
208
+ /**
209
+ * Per-question narrative settings (M-067), a separate collection rather than fields denormalized
210
+ * onto every rule: they are per-question, and `enabled` must survive on a question whose rules are
211
+ * stored but switched off — legacy's `toggleNarrative` flips `have_narrative` **without** clearing
212
+ * `conditional[]`, so "disabled but not cleared" is a real stored state.
213
+ *
214
+ * Both members are `true`-only: DOC-LAW-2 makes `false` and absent the same thing, so writing
215
+ * `false` would be a second encoding of "not set" and would change `document_hash`.
216
+ */
217
+ export type HighlightRuleSettings = { enabled?: true; requiredAll?: true }
185
218
  export type NarrativeRule = { condition: RuleCondition; [key: string]: unknown }
186
219
  export type QnrRule = {
187
220
  condition: RuleCondition
@@ -189,6 +222,27 @@ export type QnrRule = {
189
222
  templateFamilyId: string
190
223
  }
191
224
 
225
+ /**
226
+ * An answer-prefill rule (M-068): when the source question has an answer and this rule's target is
227
+ * still empty, the target is filled from it.
228
+ *
229
+ * **Not a visibility rule**, which is the whole reason it is its own collection: legacy
230
+ * `dependent_questions` propagates a *value*, so mapping it onto `visibilityRules` would make v2
231
+ * *hide* a question legacy merely *prefilled*. Carries no `condition` for the same reason — there is
232
+ * no operator to evaluate, only a source address.
233
+ *
234
+ * The address is two-level because a source inside a grid needs its enclosing grid to be resolvable:
235
+ * `sourceParentQuestionId` is that grid, absent for a top-level source.
236
+ *
237
+ * Evaluation (fill once, never overwrite an existing answer) is runtime behaviour owned by
238
+ * ASMA-7935; the document only preserves the authored rule.
239
+ */
240
+ export type PrefillRule = {
241
+ sourceQuestionId: QuestionId
242
+ sourceParentQuestionId?: QuestionId
243
+ [key: string]: unknown
244
+ }
245
+
192
246
  /** One traversal step. Many questions off one entity share a single node (§2.2a). */
193
247
  export type MappingNode = {
194
248
  entityId: string
@@ -212,16 +266,84 @@ export const bindingTargetKey = (target: BindingTarget): string =>
212
266
  ? `question:${target.questionId}`
213
267
  : `gridColumn:${target.gridQuestionId}:${target.columnQuestionId}`
214
268
 
269
+ /**
270
+ * A binding's expected cardinality (§13.1). Closed rather than a loose string because the compiler
271
+ * branches on it: `0..1`/`1` fill one slot, `0..*`/`1..*` feed a grid's rows, and a typo would compile
272
+ * into an artifact that is immutable forever.
273
+ *
274
+ * `0..1` is the default, so DOC-LAW-2 means it is **never stored** — a binding that takes at most one
275
+ * value carries no `cardinality` key at all.
276
+ *
277
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-15-20-38-analysis-qnr-external-data-mapping-options.md:840 — the four values
278
+ */
279
+ export const BINDING_CARDINALITIES = ['0..1', '1', '0..*', '1..*'] as const
280
+ export type BindingCardinality = (typeof BINDING_CARDINALITIES)[number]
281
+
282
+ /**
283
+ * What the runtime does when the source yields **no** value for a binding. `omit` leaves the question
284
+ * unfilled (the default); `error` makes the absence a prefill failure the author wants surfaced rather
285
+ * than silently tolerated.
286
+ */
287
+ export const BINDING_ON_MISSING = ['omit', 'error'] as const
288
+ export type BindingOnMissing = (typeof BINDING_ON_MISSING)[number]
289
+
290
+ /**
291
+ * What the runtime does when the source yields **many** values for a binding expecting one. `error` is
292
+ * the default — an ambiguous prefill is a real defect — and `first` is the deliberate opt-in, which is
293
+ * why the node's `orderBy` must make "first" deterministic before it means anything.
294
+ */
295
+ export const BINDING_ON_MANY = ['error', 'first'] as const
296
+ export type BindingOnMany = (typeof BINDING_ON_MANY)[number]
297
+
298
+ /**
299
+ * The three binding behaviours and their defaults, in one place because two rules depend on it: the
300
+ * reducer omits a chosen value that equals its default (DOC-LAW-2 — a key present with its own default
301
+ * is a second encoding of "not set", and the hash is computed on the minimal form), and every reader
302
+ * hydrates the absent key back to the same value.
303
+ *
304
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-15-20-38-analysis-qnr-external-data-mapping-options.md:832 — absent because they equal their defaults
305
+ */
306
+ /** The binding behaviours a reader sees — total, because the stored document is minimal. */
307
+ export type ResolvedBindingOptions = {
308
+ cardinality: BindingCardinality
309
+ onMissing: BindingOnMissing
310
+ onMany: BindingOnMany
311
+ }
312
+
313
+ export const BINDING_OPTION_DEFAULTS = {
314
+ cardinality: '0..1',
315
+ onMissing: 'omit',
316
+ onMany: 'error',
317
+ } as const satisfies ResolvedBindingOptions
318
+
215
319
  export type MappingBinding = {
216
320
  nodeId: NodeId
217
321
  fieldId: string
218
322
  target: BindingTarget
219
- cardinality?: string
220
- onMissing?: string
221
- onMany?: string
323
+ /** Absent means `0..1` (BINDING_OPTION_DEFAULTS) — never stored at its default. */
324
+ cardinality?: BindingCardinality
325
+ /** Absent means `omit`. */
326
+ onMissing?: BindingOnMissing
327
+ /** Absent means `error`. */
328
+ onMany?: BindingOnMany
222
329
  [key: string]: unknown
223
330
  }
224
331
 
332
+ /**
333
+ * Hydrates a stored binding's behaviours to the total set (§2.2a: "the hydrated in-memory binding is
334
+ * a total object"). One place rather than `?? 'omit'` at each use site — a reader that spelled the
335
+ * fallback itself would be a second declaration of the default, free to drift from the reducer's.
336
+ */
337
+ export const resolveBindingOptions = (binding: MappingBinding): ResolvedBindingOptions => ({
338
+ cardinality: binding.cardinality ?? BINDING_OPTION_DEFAULTS.cardinality,
339
+ onMissing: binding.onMissing ?? BINDING_OPTION_DEFAULTS.onMissing,
340
+ onMany: binding.onMany ?? BINDING_OPTION_DEFAULTS.onMany,
341
+ })
342
+
343
+ /** Whether a binding's cardinality means "many values", i.e. it feeds a grid's rows rather than one slot. */
344
+ export const bindingIsMultiValued = (binding: MappingBinding): boolean =>
345
+ resolveBindingOptions(binding).cardinality.endsWith('*')
346
+
225
347
  /** Carries no `nodeId` back-pointer: the node already lists it (§2.2a). */
226
348
  export type MappingFilter = {
227
349
  fieldId: string
@@ -261,6 +383,11 @@ export type QnrTemplateDocument = {
261
383
  narrativeRuleOrderByQuestionId?: Record<QuestionId, NarrativeRuleId[]>
262
384
  qnrRulesById?: Record<QnrRuleId, QnrRule>
263
385
  qnrRuleOrderByQuestionId?: Record<QuestionId, QnrRuleId[]>
386
+ /** Keyed by the **target** question — the one that gets filled (M-068). */
387
+ prefillRulesById?: Record<PrefillRuleId, PrefillRule>
388
+ prefillRuleOrderByQuestionId?: Record<QuestionId, PrefillRuleId[]>
389
+ /** Only for a question that actually sets one of them; an all-default entry is omitted. */
390
+ highlightRuleSettingsByQuestionId?: Record<QuestionId, HighlightRuleSettings>
264
391
  dataMappingsById?: Record<MappingId, QnrDataMapping>
265
392
  mappingNodesById?: Record<NodeId, MappingNode>
266
393
  mappingBindingsById?: Record<BindingId, MappingBinding>