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
@@ -1 +1 @@
1
- {"version":3,"file":"applyOperation.d.ts","sourceRoot":"","sources":["../../src/collaboration/applyOperation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,KAAK,EAKR,eAAe,EAYf,mBAAmB,EAEtB,MAAM,uBAAuB,CAAA;AAuB9B;;;;;;;;;;;;;;;;GAgBG;AAEH;;;;;;GAMG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IACzC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IAErB,YAAY,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAK5D;CACJ;AAED,qBAAa,qBAAsB,SAAQ,kBAAkB;IACzD,YAAY,IAAI,EAAE,MAAM,EAEvB;CACJ;AAED,qBAAa,sBAAuB,SAAQ,kBAAkB;IAC1D,YAAY,OAAO,EAAE,MAAM,EAE1B;CACJ;AA+KD;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,UAAW,MAAM,KAAG,MAAM,GAAG,SAQ5D,CAAA;AA6ID;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,SAAU,eAAe,SAAS,MAAM,KAAG,MAAM,GAAG,SAuBvF,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,UAAW,MAAM,SAAS,OAAO,KAAG,MAAM,GAAG,SAWhF,CAAA;AAs2BD,eAAO,MAAM,cAAc,aAAc,mBAAmB,MAAM,UAAU,KAAG,mBAG9E,CAAA"}
1
+ {"version":3,"file":"applyOperation.d.ts","sourceRoot":"","sources":["../../src/collaboration/applyOperation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,KAAK,EAKR,eAAe,EAYf,mBAAmB,EAGtB,MAAM,uBAAuB,CAAA;AAsC9B;;;;;;;;;;;;;;;;GAgBG;AAEH;;;;;;GAMG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IACzC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IAErB,YAAY,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAK5D;CACJ;AAED,qBAAa,qBAAsB,SAAQ,kBAAkB;IACzD,YAAY,IAAI,EAAE,MAAM,EAEvB;CACJ;AAED,qBAAa,sBAAuB,SAAQ,kBAAkB;IAC1D,YAAY,OAAO,EAAE,MAAM,EAE1B;CACJ;AAmUD;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,UAAW,MAAM,KAAG,MAAM,GAAG,SAQ5D,CAAA;AA6ID;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,SAAU,eAAe,SAAS,MAAM,KAAG,MAAM,GAAG,SAuBvF,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,UAAW,MAAM,SAAS,OAAO,KAAG,MAAM,GAAG,SAWhF,CAAA;AAs2BD,eAAO,MAAM,cAAc,aAAc,mBAAmB,MAAM,UAAU,KAAG,mBAG9E,CAAA"}
@@ -1,3 +1,4 @@
1
+ import { isCompatibilityCollection, isMetaField, isSettingField, isTemplateAuthoringDefault, metaFieldPath, normalizeCompatibilityId, normalizeCompatibilityIds, parseCompatibilityOperationId, parseMetaFieldValue, settingFieldPath, templateAliasPathsOf, } from './templateAuthoringMeta.js';
1
2
  import { ACTION_TYPES, BINDING_OPTION_DEFAULTS, MAPPING_FILTER_OPERATORS, bindingTargetKey, isKnownActionKind, makeExpressionAlternativeToken, makeExpressionTargetToken, parseLegacyBindingOverride, } from './templateDocument.js';
2
3
  /** Runtime narrowing for the two closed vocabularies the reducer must re-check on replay. */
3
4
  const isActionType = (value) => typeof value === 'string' && ACTION_TYPES.includes(value);
@@ -80,6 +81,134 @@ const writeField = (record, field, value) => {
80
81
  next[head] = nested;
81
82
  return next;
82
83
  };
84
+ // ─────────────── ASMA-8339: the typed metadata/settings write boundary ───────────────
85
+ /** A container the reducer may descend into. `null` and an array are neither. */
86
+ const isPlainRecord = (value) => {
87
+ if (typeof value !== 'object' || value === null)
88
+ return false;
89
+ const proto = Object.getPrototypeOf(value);
90
+ return proto === Object.prototype || proto === null;
91
+ };
92
+ /**
93
+ * Refuses an operation carrying a payload member outside its closed vocabulary.
94
+ *
95
+ * Re-checked in the reducer and not only at the wire schema, for the reason the ASMA-7683 hardening
96
+ * pass recorded: bunjs replays a stored `collab_ops` log without re-validating each op, so anything
97
+ * the reducer alone permits is reachable by an op written by an older or bypassed client — and unlike
98
+ * a rejected request, it lands in a document and then in an immutable artifact.
99
+ *
100
+ * Keys holding `undefined` are ignored. They carry nothing, cannot survive JSON transport, and
101
+ * refusing them would reject an ordinary `{...base, patch: undefined}` spread.
102
+ */
103
+ const assertClosedPayload = (op, allowed) => {
104
+ const carried = Object.entries(op).filter(([, value]) => value !== undefined);
105
+ const extra = carried.map(([key]) => key).filter((key) => !allowed.includes(key));
106
+ if (extra.length > 0) {
107
+ throw new OperationConflictError(`Operation "${String(op['type'])}" carries unrecognized payload member(s): ${extra
108
+ .map((key) => `"${key}"`)
109
+ .join(', ')}`);
110
+ }
111
+ };
112
+ /**
113
+ * Canonical loci are document-absolute; the reducer writes into `meta` itself.
114
+ *
115
+ * The guard is not ceremony. A bare `slice(5)` turns a meta-RELATIVE path into silent nonsense
116
+ * (`settings.refresh_button` becomes `ngs.refresh_button`), which then writes to a path no reader
117
+ * looks at and clears no alias — a mutation seeded during review survived the suite for exactly this
118
+ * reason. Failing loudly makes a mis-anchored path a refusal instead of a quiet no-op.
119
+ */
120
+ const metaRelativePath = (documentPath) => {
121
+ if (!documentPath.startsWith('meta.')) {
122
+ throw new OperationConflictError(`"${documentPath}" is not a document-absolute metadata path`);
123
+ }
124
+ return documentPath.slice('meta.'.length);
125
+ };
126
+ /**
127
+ * Refuses a typed write whose owned ancestor holds something that is not a container.
128
+ *
129
+ * `writeField` creates intermediate objects, so it would REPLACE an imported scalar or array sitting
130
+ * at `meta.settings.rendering` — silently destroying residue this contract is required to preserve.
131
+ * Repairing a malformed owned container is import/publication work, and the released open
132
+ * `template.updateMeta`/`template.updateSettings` arms remain available to clear it, so refusing here
133
+ * loses no capability and is the only non-destructive answer.
134
+ */
135
+ const assertWritableMetaAncestors = (meta, relativePath) => {
136
+ const segments = relativePath.split('.');
137
+ let current = meta;
138
+ let walked = 'meta';
139
+ for (const segment of segments.slice(0, -1)) {
140
+ walked = `${walked}.${segment}`;
141
+ if (!Object.hasOwn(current, segment))
142
+ return;
143
+ const child = current[segment];
144
+ if (child === undefined)
145
+ return;
146
+ if (!isPlainRecord(child)) {
147
+ throw new OperationConflictError(`"${walked}" holds ${Array.isArray(child) ? 'an array' : `a ${typeof child}`}, not a container; ` +
148
+ `the typed metadata operations refuse to overwrite imported residue`);
149
+ }
150
+ current = child;
151
+ }
152
+ };
153
+ /**
154
+ * Writes one canonical metadata leaf: clears its recognized old spellings, then stores the value or
155
+ * omits it.
156
+ *
157
+ * **Alias clearing happens first and unconditionally, and that ordering is the whole point.** Writing
158
+ * `recipient.requires_phone_number: false` stores nothing, because `false` is the declared default —
159
+ * so without the clear a stale `ask_for_phone_nr: true` would still be in the document and the total
160
+ * reader's alias fallback would read the requirement back ON, silently reversing the author's
161
+ * explicit "off". Only the field's OWN recognized aliases are touched: every unrelated unknown member
162
+ * of the same bag is left exactly where the import put it.
163
+ *
164
+ * Restoring a default and an explicit `null` are the same write, because DOC-LAW-2 makes absence the
165
+ * only encoding of "not set" — an author who clicks back to `coordinator` and an author who never
166
+ * touched the control must produce byte-identical documents, or one authored state would carry two
167
+ * `document_hash` values.
168
+ */
169
+ const writeCanonicalMetaLeaf = (meta, canonicalPath, value) => {
170
+ const relative = metaRelativePath(canonicalPath);
171
+ const aliasPaths = templateAliasPathsOf(canonicalPath).map(metaRelativePath);
172
+ for (const path of [relative, ...aliasPaths])
173
+ assertWritableMetaAncestors(meta, path);
174
+ let next = meta;
175
+ for (const path of aliasPaths)
176
+ next = writeField(next, path, null);
177
+ const stored = value === null || isTemplateAuthoringDefault(canonicalPath, value) ? null : value;
178
+ return writeField(next, relative, stored);
179
+ };
180
+ /**
181
+ * The stored soft-id set as canonical members, or a refusal.
182
+ *
183
+ * Refuses rather than repairs when the collection is not an array, or carries a member that is not a
184
+ * soft id (an object, `null`, a non-finite number, an empty string). Normalising around such a member
185
+ * would drop it, which is silent data loss in a hashed document; the total reader reports the same
186
+ * condition as a `malformed-collection` finding, so an author sees why the control is blocked.
187
+ */
188
+ const readCompatibilitySet = (meta, collection) => {
189
+ const compatibility = meta['compatibility'];
190
+ if (compatibility === undefined)
191
+ return [];
192
+ if (!isPlainRecord(compatibility)) {
193
+ throw new OperationConflictError(`"meta.compatibility" holds a ${typeof compatibility}, not a container`);
194
+ }
195
+ const stored = compatibility[collection];
196
+ if (stored === undefined)
197
+ return [];
198
+ if (!Array.isArray(stored)) {
199
+ throw new OperationConflictError(`"meta.compatibility.${collection}" holds a ${typeof stored}, not an array of soft ids`);
200
+ }
201
+ return stored.map((member, index) => {
202
+ const normalized = normalizeCompatibilityId(member);
203
+ if (normalized === undefined) {
204
+ throw new OperationConflictError(`"meta.compatibility.${collection}.${index}" is not a soft id; the typed membership ` +
205
+ `operations refuse to normalize a malformed imported set`);
206
+ }
207
+ return normalized;
208
+ });
209
+ };
210
+ /** Stores a soft-id set in canonical form, or drops the key when the last member left (DOC-LAW-2). */
211
+ const writeCompatibilitySet = (meta, collection, ids) => writeField(meta, `compatibility.${collection}`, ids.length === 0 ? null : [...ids]);
83
212
  /** Inserts `id` at `index`, clamped into range. Absent index appends. */
84
213
  const insertAt = (order, id, index) => {
85
214
  const next = [...order];
@@ -1202,6 +1331,71 @@ const reduce = (doc, op) => {
1202
1331
  meta.settings = settings;
1203
1332
  return { ...doc, meta };
1204
1333
  }
1334
+ case 'template.setMetaFieldTyped': {
1335
+ assertClosedPayload(op, ['type', 'field', 'value']);
1336
+ // Re-validated on replay: the closed path and its correlated value type live in the
1337
+ // registry, and an op from an older or bypassed client reaches this switch with no
1338
+ // validator in front of it.
1339
+ if (!isMetaField(op.field)) {
1340
+ throw new OperationConflictError(`"${String(op.field)}" is not an editable template metadata field`);
1341
+ }
1342
+ if (op.value !== null && parseMetaFieldValue(op.field, op.value) === undefined) {
1343
+ throw new OperationConflictError(`${JSON.stringify(op.value)} is not a valid value for metadata field "${op.field}"`);
1344
+ }
1345
+ const meta = writeCanonicalMetaLeaf({ ...(doc.meta ?? {}) }, metaFieldPath(op.field), op.value);
1346
+ return { ...doc, meta };
1347
+ }
1348
+ case 'template.setSettingTyped': {
1349
+ assertClosedPayload(op, ['type', 'field', 'value']);
1350
+ if (!isSettingField(op.field)) {
1351
+ throw new OperationConflictError(`"${String(op.field)}" is not a template settings leaf`);
1352
+ }
1353
+ // Explicitly type-checked rather than coerced: a legacy `'false'` string is a MALFORMED
1354
+ // known value, and JavaScript truthiness would read it as the opposite of what it says.
1355
+ if (op.value !== null && typeof op.value !== 'boolean') {
1356
+ throw new OperationConflictError(`Setting "${op.field}" takes a boolean or null, not ${typeof op.value}`);
1357
+ }
1358
+ const meta = writeCanonicalMetaLeaf({ ...(doc.meta ?? {}) }, settingFieldPath(op.field), op.value);
1359
+ return { ...doc, meta };
1360
+ }
1361
+ case 'template.addCompatibilityId': {
1362
+ assertClosedPayload(op, ['type', 'collection', 'id']);
1363
+ if (!isCompatibilityCollection(op.collection)) {
1364
+ throw new OperationConflictError(`"${String(op.collection)}" is not a compatibility collection`);
1365
+ }
1366
+ // Strict on a NEW payload, where the wire schema says `string > 0`: a numeric id is
1367
+ // tolerated only when READING a stored legacy member. Accepting one here would let an op
1368
+ // the schema refuses land anyway through a replayed log.
1369
+ const id = parseCompatibilityOperationId(op.id);
1370
+ if (id === undefined) {
1371
+ throw new OperationConflictError(`template.addCompatibilityId requires a nonempty string soft id, not ${typeof op.id}`);
1372
+ }
1373
+ const meta = { ...(doc.meta ?? {}) };
1374
+ // Adding an id already present yields the identical set: content-idempotent, so no new
1375
+ // canonical bytes and no spurious version.
1376
+ const members = normalizeCompatibilityIds([...readCompatibilitySet(meta, op.collection), id]);
1377
+ return { ...doc, meta: writeCompatibilitySet(meta, op.collection, members) };
1378
+ }
1379
+ case 'template.removeCompatibilityId': {
1380
+ assertClosedPayload(op, ['type', 'collection', 'id']);
1381
+ if (!isCompatibilityCollection(op.collection)) {
1382
+ throw new OperationConflictError(`"${String(op.collection)}" is not a compatibility collection`);
1383
+ }
1384
+ // Strict on a NEW payload, where the wire schema says `string > 0`: a numeric id is
1385
+ // tolerated only when READING a stored legacy member. Accepting one here would let an op
1386
+ // the schema refuses land anyway through a replayed log.
1387
+ const id = parseCompatibilityOperationId(op.id);
1388
+ if (id === undefined) {
1389
+ throw new OperationConflictError(`template.removeCompatibilityId requires a nonempty string soft id, not ${typeof op.id}`);
1390
+ }
1391
+ const meta = { ...(doc.meta ?? {}) };
1392
+ // Removing an absent id is a no-op, which is what makes remove/remove of one id converge.
1393
+ const members = readCompatibilitySet(meta, op.collection).filter((member) => member !== id);
1394
+ return {
1395
+ ...doc,
1396
+ meta: writeCompatibilitySet(meta, op.collection, normalizeCompatibilityIds(members)),
1397
+ };
1398
+ }
1205
1399
  case 'question.create': {
1206
1400
  if (doc.questionsById?.[op.questionId]) {
1207
1401
  throw new OperationConflictError(`Question "${op.questionId}" already exists`);