@memberjunction/record-set-processor 6.2.0-edge.4 → 6.2.0-edge.5

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 (60) hide show
  1. package/README.md +36 -1
  2. package/dist/RecordProcessExecutor.d.ts +29 -15
  3. package/dist/RecordProcessExecutor.d.ts.map +1 -1
  4. package/dist/RecordProcessExecutor.js +59 -62
  5. package/dist/RecordProcessExecutor.js.map +1 -1
  6. package/dist/RecordSetProcessor.d.ts +9 -0
  7. package/dist/RecordSetProcessor.d.ts.map +1 -1
  8. package/dist/RecordSetProcessor.js +140 -81
  9. package/dist/RecordSetProcessor.js.map +1 -1
  10. package/dist/index.d.ts +0 -4
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +0 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/operations/RecordProcessControlOperations.d.ts.map +1 -1
  15. package/dist/operations/RecordProcessControlOperations.js +9 -7
  16. package/dist/operations/RecordProcessControlOperations.js.map +1 -1
  17. package/dist/processors/ActionRecordProcessor.js +2 -2
  18. package/dist/processors/AgentRecordProcessor.d.ts.map +1 -1
  19. package/dist/processors/AgentRecordProcessor.js +5 -2
  20. package/dist/processors/AgentRecordProcessor.js.map +1 -1
  21. package/dist/processors/FieldRulesProcessor.d.ts +8 -7
  22. package/dist/processors/FieldRulesProcessor.d.ts.map +1 -1
  23. package/dist/processors/FieldRulesProcessor.js +23 -13
  24. package/dist/processors/FieldRulesProcessor.js.map +1 -1
  25. package/dist/processors/WriteBackProcessor.d.ts +62 -2
  26. package/dist/processors/WriteBackProcessor.d.ts.map +1 -1
  27. package/dist/processors/WriteBackProcessor.js +134 -58
  28. package/dist/processors/WriteBackProcessor.js.map +1 -1
  29. package/dist/trackers/GenericProcessRunTracker.d.ts.map +1 -1
  30. package/dist/trackers/GenericProcessRunTracker.js +5 -0
  31. package/dist/trackers/GenericProcessRunTracker.js.map +1 -1
  32. package/dist/watermark/WatermarkService.d.ts +62 -24
  33. package/dist/watermark/WatermarkService.d.ts.map +1 -1
  34. package/dist/watermark/WatermarkService.js +123 -70
  35. package/dist/watermark/WatermarkService.js.map +1 -1
  36. package/dist/writeBack.d.ts +358 -42
  37. package/dist/writeBack.d.ts.map +1 -1
  38. package/dist/writeBack.js +848 -208
  39. package/dist/writeBack.js.map +1 -1
  40. package/package.json +16 -17
  41. package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.d.ts +0 -92
  42. package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.d.ts.map +0 -1
  43. package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.js +0 -26
  44. package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.js.map +0 -1
  45. package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.d.ts +0 -79
  46. package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.d.ts.map +0 -1
  47. package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.js +0 -257
  48. package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.js.map +0 -1
  49. package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.d.ts +0 -23
  50. package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.d.ts.map +0 -1
  51. package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.js +0 -85
  52. package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.js.map +0 -1
  53. package/dist/processors/FeaturePipelineEscalation.d.ts +0 -155
  54. package/dist/processors/FeaturePipelineEscalation.d.ts.map +0 -1
  55. package/dist/processors/FeaturePipelineEscalation.js +0 -208
  56. package/dist/processors/FeaturePipelineEscalation.js.map +0 -1
  57. package/dist/processors/InferProcessor.d.ts +0 -306
  58. package/dist/processors/InferProcessor.d.ts.map +0 -1
  59. package/dist/processors/InferProcessor.js +0 -1210
  60. package/dist/processors/InferProcessor.js.map +0 -1
package/dist/writeBack.js CHANGED
@@ -1,12 +1,744 @@
1
1
  /**
2
2
  * @fileoverview Output-mapping write-back — applies a work's structured result back onto the data
3
- * model per an `OutputMapping` config: update fields on the processed record and/or create a child
4
- * record. Reads from the result use the generic value-mapping resolver (`$` = the result root).
3
+ * model per an `OutputMapping` config: update fields on the processed record and/or write child
4
+ * records (inserted, or reconciled on their key so a re-run is idempotent), in one entity transaction.
5
+ * Reads from the result use the generic value-mapping resolver (`$` = the result root).
5
6
  * @module @memberjunction/record-set-processor
6
7
  */
7
- import { CompositeKey, LogStatus, Metadata, RunView, LogError } from '@memberjunction/core';
8
- import { EscapeSQLString, UUIDsEqual, resolveMappingRef } from '@memberjunction/global';
8
+ import { CompositeKey, DatabaseProviderBase, EntityFieldTSType, LogStatus, RunInEntityTransaction, RunView, LogError } from '@memberjunction/core';
9
+ import { EscapeSQLString, NormalizeUUID, ResolveMappingRef, UUIDSet, UUIDsEqual } from '@memberjunction/global';
10
+ import { MetadataProviderCapabilities } from '@memberjunction/record-set-processor-base';
9
11
  import { TagEngine } from '@memberjunction/tag-engine';
12
+ /** Membership checks on {@link WithheldWriteBackTargets}. */
13
+ export class WithheldTargets {
14
+ /** Whether `field` is withheld (case-insensitive); false without withheld targets. */
15
+ static HasField(withheld, field) {
16
+ return WithheldTargets.includes(withheld?.Fields, field);
17
+ }
18
+ /** Whether the entity's column `field` does not allow null (names compare case-insensitively); false for an undeclared field. */
19
+ static ColumnRequiresValue(entity, field) {
20
+ const wanted = field.trim().toLowerCase();
21
+ return entity.Fields.find((f) => f.Name.toLowerCase() === wanted)?.AllowsNull === false;
22
+ }
23
+ /** Whether the child entity `entity` is withheld (case-insensitive); false without withheld targets. */
24
+ static HasChildEntity(withheld, entity) {
25
+ return WithheldTargets.includes(withheld?.ChildEntities, entity);
26
+ }
27
+ /** Whether a name list holds `name`, trimmed and case-insensitively, as metadata names compare. */
28
+ static includes(names, name) {
29
+ const wanted = name.trim().toLowerCase();
30
+ return (names || []).some((n) => n.trim().toLowerCase() === wanted);
31
+ }
32
+ }
33
+ /** A value that is already a key, not a match string: a UUID in any case, surrounding whitespace allowed. */
34
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
35
+ /** SQL types whose values are stored rounded to the column's scale. */
36
+ const SCALED_DECIMAL_TYPES = new Set(['decimal', 'numeric', 'money', 'smallmoney']);
37
+ /** Writes one record's resolved output mapping: child rows (inserted, or reconciled on their key), then the record's own fields. */
38
+ export class OutputMappingWriter {
39
+ constructor(Options) {
40
+ this.Options = Options;
41
+ }
42
+ /** Whether the metadata provider can also run views (narrows the type without a cast). */
43
+ static IsRunViewProvider(p) {
44
+ return 'RunView' in p && typeof p.RunView === 'function';
45
+ }
46
+ /**
47
+ * Normalises one part of a reconcile key as a case-insensitive key column compares it: null is '', a
48
+ * uniqueidentifier is `NormalizeUUID`d, anything else is lower-cased with trailing spaces removed.
49
+ * @param field - the key field's metadata, when the entity declares it
50
+ * @param v - a mapped value or an entity field value; `unknown` because config-named fields carry no compile-time type
51
+ */
52
+ static NormalizeKeyPart(field, v) {
53
+ if (v === null || v === undefined) {
54
+ return '';
55
+ }
56
+ return field?.IsUniqueIdentifier ? NormalizeUUID(String(v)) : String(v).trimEnd().toLowerCase();
57
+ }
58
+ /**
59
+ * Whether a stored field value already equals a proposed one, by the field's type: UUIDs case-insensitively, dates
60
+ * by instant, decimals at the column's scale, numbers numerically, booleans by truth, anything else as exact text.
61
+ * @param stored - the record's current value (`BaseEntity.Get`)
62
+ * @param proposed - the mapped value; both `unknown` for the reason given on {@link NormalizeKeyPart}
63
+ */
64
+ static ValuesEqual(field, stored, proposed) {
65
+ const storedMissing = stored === null || stored === undefined;
66
+ const proposedMissing = proposed === null || proposed === undefined;
67
+ if (storedMissing || proposedMissing) {
68
+ return storedMissing && proposedMissing;
69
+ }
70
+ if (field?.IsUniqueIdentifier) {
71
+ return UUIDsEqual(String(stored), String(proposed));
72
+ }
73
+ switch (field?.TSType) {
74
+ case EntityFieldTSType.Date:
75
+ return OutputMappingWriter.DatesEqual(stored, proposed);
76
+ case EntityFieldTSType.Number:
77
+ return OutputMappingWriter.NumbersEqual(field, stored, proposed);
78
+ case EntityFieldTSType.Boolean:
79
+ return OutputMappingWriter.TruthOf(stored) === OutputMappingWriter.TruthOf(proposed);
80
+ default:
81
+ return String(stored) === String(proposed);
82
+ }
83
+ }
84
+ /** Dates compare by instant; a value that is not a date compares as exact text. */
85
+ static DatesEqual(stored, proposed) {
86
+ const a = stored instanceof Date ? stored.getTime() : new Date(String(stored)).getTime();
87
+ const b = proposed instanceof Date ? proposed.getTime() : new Date(String(proposed)).getTime();
88
+ return Number.isNaN(a) || Number.isNaN(b) ? String(stored) === String(proposed) : a === b;
89
+ }
90
+ /** Numbers compare numerically, rounded to the column's scale for scaled decimal types. */
91
+ static NumbersEqual(field, stored, proposed) {
92
+ const a = Number(stored);
93
+ const b = Number(proposed);
94
+ if (Number.isNaN(a) || Number.isNaN(b)) {
95
+ return String(stored) === String(proposed);
96
+ }
97
+ const scale = field.Scale;
98
+ if (SCALED_DECIMAL_TYPES.has(field.Type.trim().toLowerCase()) && scale !== null && scale !== undefined) {
99
+ return OutputMappingWriter.RoundToScale(a, scale) === OutputMappingWriter.RoundToScale(b, scale);
100
+ }
101
+ return a === b;
102
+ }
103
+ /** Rounds half away from zero to `scale` digits, as SQL Server stores it (the epsilon corrects binary halves). */
104
+ static RoundToScale(x, scale) {
105
+ const factor = 10 ** scale;
106
+ return Math.sign(x) * Math.round(Math.abs(x) * factor * (1 + Number.EPSILON)) / factor;
107
+ }
108
+ /** A bit value's truth: true, 1, '1' and 'true' (any case) are true. */
109
+ static TruthOf(v) {
110
+ return v === true || v === 1 || (typeof v === 'string' && ['1', 'true'].includes(v.trim().toLowerCase()));
111
+ }
112
+ /** Writes every answered child mapping: reconciled mappings on their key, the others as inserts. */
113
+ async WriteChildren(answers) {
114
+ const created = new Map();
115
+ for (const answer of answers) {
116
+ if (answer.Config.reconcile) {
117
+ await this.ReconcileChildren(answer.Config, answer.Config.reconcile, answer.Rows, created);
118
+ continue;
119
+ }
120
+ for (const item of answer.Rows) {
121
+ created.set(item, await this.InsertChild(item));
122
+ }
123
+ }
124
+ this.RecordCreated(answers.flatMap((a) => a.Rows), created);
125
+ }
126
+ /**
127
+ * Saves the record's mapped fields that differ from its current values and hold no value a person entered. A run
128
+ * that overwrites human values then retires the Human value of every mapped field.
129
+ * @param entity - the processed record's entity
130
+ * @param fields - the resolved field values (foreign keys already resolved)
131
+ */
132
+ async WriteRecordFields(entity, fields) {
133
+ const obj = await this.LoadRecord(entity);
134
+ if (!obj) {
135
+ throw new Error(`applyOutputMapping: record '${this.Options.Record.RecordID}' of '${entity.Name}' not found`);
136
+ }
137
+ const changes = await this.FieldChanges(entity, obj, fields, true);
138
+ if (changes.length > 0) {
139
+ for (const [field, value] of changes) {
140
+ obj.Set(field, value); // config-driven field names: no compile-time property exists
141
+ }
142
+ if (!(await obj.Save())) {
143
+ throw new Error(`applyOutputMapping: failed updating '${entity.Name}' record '${this.Options.Record.RecordID}': ${obj.LatestResult?.CompleteMessage || 'unknown error'}`);
144
+ }
145
+ this.Options.Result.updatedRecord = true;
146
+ this.Options.Result.changed = true;
147
+ }
148
+ // a withheld field's abstention is no answer, so it never retires the field's Human value
149
+ await this.RetireHumanValues(Object.keys(fields).filter((f) => !WithheldTargets.HasField(this.Options.Withheld, f)));
150
+ }
151
+ /** The processed record, loaded on the writer's provider; null when it does not exist. */
152
+ async LoadRecord(entity) {
153
+ const obj = await this.Options.Provider.GetEntityObject(entity.Name, this.Options.ContextUser);
154
+ // RecordID is the compact CompositeKey segment (bare value for a single column, "F1|v1||F2|v2" for composite).
155
+ return (await obj.InnerLoad(CompositeKey.FromURLSegment(entity, this.Options.Record.RecordID))) ? obj : null;
156
+ }
157
+ /** On a run that overwrites human values, retires each mapped field's Human value (sequentially, in the unit's transaction). */
158
+ async RetireHumanValues(fieldNames) {
159
+ const guard = this.Options.HumanGuard;
160
+ if (!guard || !this.Options.OverwriteHumanValues) {
161
+ return;
162
+ }
163
+ for (const field of fieldNames) {
164
+ if (await guard.RetireHumanValue(field, this.Options.Provider)) {
165
+ (this.Options.Result.retiredHumanFields ||= []).push(field);
166
+ this.Options.Result.changed = true;
167
+ }
168
+ }
169
+ }
170
+ /**
171
+ * The mapped fields whose value differs from the record's ({@link ValuesEqual}) and holds no value a person entered,
172
+ * for the real write and the dry-run preview ({@link PreviewFields}).
173
+ * @param recordPreserved - record each preserved human value (the real write); false for the preview
174
+ */
175
+ async FieldChanges(entity, obj, fields, recordPreserved) {
176
+ const changes = [];
177
+ for (const [field, value] of Object.entries(fields)) {
178
+ const current = obj.Get(field); // config-driven field name
179
+ if (OutputMappingWriter.ValuesEqual(this.FieldInfoOf(entity, field), current, value)) {
180
+ continue;
181
+ }
182
+ if (await this.PreservesHumanValue(entity, field, current, recordPreserved)) {
183
+ continue;
184
+ }
185
+ changes.push([field, value]);
186
+ }
187
+ return changes;
188
+ }
189
+ /**
190
+ * True when the field holds a value a person entered and the run does not overwrite it (see
191
+ * {@link OutputMappingWriterOptions.Withheld}); with `recordPreserved` the value is recorded and reported. An empty
192
+ * field is never asked about.
193
+ */
194
+ async PreservesHumanValue(entity, field, current, recordPreserved) {
195
+ const guard = this.Options.HumanGuard;
196
+ const fieldInfo = this.FieldInfoOf(entity, field);
197
+ // an abstention clears only a value the guard says the pipeline owns, even on a run that overwrites human values
198
+ const withheld = WithheldTargets.HasField(this.Options.Withheld, field);
199
+ if (OutputMappingWriter.NormalizeKeyPart(fieldInfo, current) === '') {
200
+ return false;
201
+ }
202
+ if (!guard) {
203
+ return withheld;
204
+ }
205
+ if (this.Options.OverwriteHumanValues && !withheld) {
206
+ return false;
207
+ }
208
+ const owned = await guard.IsHumanOwned({
209
+ FieldName: field, CurrentValue: current, Provider: this.Options.Provider,
210
+ Resolve: (v) => this.ResolveStoredForm(entity, field, v),
211
+ Equals: (stored, resolved) => OutputMappingWriter.OwnedValuesEqual(fieldInfo, stored, resolved),
212
+ });
213
+ if (!owned) {
214
+ return false;
215
+ }
216
+ if (recordPreserved) {
217
+ (this.Options.Result.preservedHumanFields ||= []).push(field);
218
+ await guard.RecordPreserved(field, current, this.Options.Provider);
219
+ }
220
+ return true;
221
+ }
222
+ /**
223
+ * Whether a stored value equals a value the pipeline wrote, for the ownership question: typed fields by
224
+ * {@link ValuesEqual}, text (and undeclared fields) with case and trailing spaces ignored, as the collation compares.
225
+ * @param stored - the field's value; `unknown` for the reason given on {@link NormalizeKeyPart}
226
+ * @param resolved - the pipeline's resolved value; likewise `unknown`
227
+ */
228
+ static OwnedValuesEqual(field, stored, resolved) {
229
+ const typed = field && (field.IsUniqueIdentifier || field.TSType === EntityFieldTSType.Date
230
+ || field.TSType === EntityFieldTSType.Number || field.TSType === EntityFieldTSType.Boolean);
231
+ if (typed) {
232
+ return OutputMappingWriter.ValuesEqual(field, stored, resolved);
233
+ }
234
+ if (stored === null || stored === undefined || resolved === null || resolved === undefined) {
235
+ return (stored === null || stored === undefined) && (resolved === null || resolved === undefined);
236
+ }
237
+ return OutputMappingWriter.NormalizeKeyPart(field, stored) === OutputMappingWriter.NormalizeKeyPart(field, resolved);
238
+ }
239
+ /**
240
+ * The stored form of one mapped field value: a match string becomes the related row's key by the mapping's lookup
241
+ * rules; a UUID, or a value of a field that is not a foreign key, is returned unchanged.
242
+ * @param val - the mapped value; `unknown` because it comes from `ResolveMappingRef`
243
+ */
244
+ async ResolveFieldValue(entity, field, val) {
245
+ return this.ResolveKey(entity, field, val, false);
246
+ }
247
+ /**
248
+ * The stored form of a value the pipeline wrote earlier, read-only: any lookup miss is null; nothing is created.
249
+ * @param val - an earlier pipeline answer (a stored Feature Value); `unknown` as on {@link ResolveFieldValue}
250
+ */
251
+ async ResolveStoredForm(entity, field, val) {
252
+ return this.ResolveKey(entity, field, val, true);
253
+ }
254
+ /**
255
+ * Shared body of {@link ResolveFieldValue} and {@link ResolveStoredForm} (`readOnly`: every miss is null).
256
+ * @param val - a mapped value or an earlier pipeline answer; `unknown` because config-named refs carry no type
257
+ */
258
+ async ResolveKey(entity, field, val, readOnly) {
259
+ if (val === null || val === undefined) {
260
+ return val;
261
+ }
262
+ const fieldInfo = this.FieldInfoOf(entity, field);
263
+ const lookup = this.Options.FieldLookups?.[field];
264
+ if (!lookup && !fieldInfo?.RelatedEntity && !fieldInfo?.RelatedEntityID) {
265
+ return val; // not a foreign key
266
+ }
267
+ if (typeof val === 'string' && UUID_PATTERN.test(val.trim())) {
268
+ return val.trim(); // already a key: no lookup
269
+ }
270
+ const onMiss = readOnly ? 'null' : lookup?.onLookupMiss || 'null';
271
+ const match = OutputMappingWriter.MatchValueOf(val);
272
+ if (match === null) {
273
+ return this.UnresolvedKey(field, onMiss, `value is not a string or number (${Array.isArray(val) ? 'array' : typeof val})`);
274
+ }
275
+ const text = String(match).trim();
276
+ if (text.length === 0) {
277
+ return this.UnresolvedKey(field, onMiss, 'value resolved to an empty string');
278
+ }
279
+ const related = this.RelatedEntityNameOf(fieldInfo, lookup);
280
+ if (!related) {
281
+ return this.UnresolvedKey(field, onMiss, 'related entity unknown in metadata');
282
+ }
283
+ const matchField = lookup?.matchField || 'Name';
284
+ if (!/^[a-zA-Z0-9_]+$/.test(matchField)) {
285
+ throw new Error(`applyOutputMapping: invalid matchField identifier '${matchField}' for entity '${related}'`);
286
+ }
287
+ const cached = this.CanCacheLookups ? this.Options.LookupCache.get(`${related}|${matchField}|${text}`) : undefined;
288
+ return cached !== undefined ? cached : this.LookupRelatedKey(field, related, matchField, text, onMiss);
289
+ }
290
+ /** Whether the run-wide lookup cache may be used: not inside a caller's transaction, whose rollback would undo a cached row. */
291
+ get CanCacheLookups() {
292
+ const provider = this.Options.LookupProvider;
293
+ return !(provider instanceof DatabaseProviderBase && (provider.CapturePostCommitToken()?.Epoch ?? null) !== null);
294
+ }
295
+ /** The match value inside a mapped value (an array's first element, an object's `Name`); null when not a string or number. */
296
+ static MatchValueOf(val) {
297
+ const first = Array.isArray(val) && val.length > 0 ? val[0] : val; // unknown: an element of an untyped array
298
+ const match = first !== null && typeof first === 'object' && 'Name' in first ? first.Name : first; // unknown: an untyped object's Name
299
+ return typeof match === 'string' || typeof match === 'number' ? match : null;
300
+ }
301
+ /** A foreign key that cannot be resolved: null, or an error under `onLookupMiss: 'fail'`. */
302
+ UnresolvedKey(field, onMiss, reason) {
303
+ if (onMiss === 'fail') {
304
+ throw new Error(`applyOutputMapping: cannot resolve foreign key for field '${field}': ${reason}`);
305
+ }
306
+ return null;
307
+ }
308
+ /** The entity a foreign-key field points at: the lookup's `relatedEntity`, else the field's metadata. */
309
+ RelatedEntityNameOf(fieldInfo, lookup) {
310
+ return OutputMappingWriter.RelatedEntityNameFor(this.Options.LookupProvider, fieldInfo, lookup);
311
+ }
312
+ /** The entity a foreign-key field points at: the lookup's `relatedEntity`, else the field's metadata; undefined for a non-key. */
313
+ static RelatedEntityNameFor(provider, fieldInfo, lookup) {
314
+ return lookup?.relatedEntity
315
+ || fieldInfo?.RelatedEntity
316
+ || (fieldInfo?.RelatedEntityID ? provider.EntityByID(fieldInfo.RelatedEntityID)?.Name : undefined);
317
+ }
318
+ /** The key column of a lookup's related entity; throws when it is not in metadata or has no primary key. */
319
+ PrimaryKeyNameOf(related) {
320
+ const key = this.Options.LookupProvider.EntityByName(related)?.FirstPrimaryKey; // first-pk-ok: a foreign key references a single-column primary key
321
+ if (!key) {
322
+ throw new Error(`applyOutputMapping: related entity '${related}' is not in metadata or has no primary key`);
323
+ }
324
+ return key.Name;
325
+ }
326
+ /**
327
+ * Looks up the related row whose match field equals `text` and returns its key (a hit is cached for the run); a miss
328
+ * follows `onMiss`: null (never cached), an error, or a new row.
329
+ */
330
+ async LookupRelatedKey(field, related, matchField, text, onMiss) {
331
+ const provider = this.Options.LookupProvider;
332
+ // Lookups run on the caller's provider only: one that cannot run views fails loudly
333
+ // rather than falling back to the process-global connection.
334
+ if (!OutputMappingWriter.IsRunViewProvider(provider)) {
335
+ throw new Error(`applyOutputMapping: cannot resolve foreign key for field '${field}': RunView provider is unavailable`);
336
+ }
337
+ const keyName = this.PrimaryKeyNameOf(related);
338
+ const res = await RunView.FromMetadataProvider(provider).RunView({
339
+ EntityName: related,
340
+ ExtraFilter: `[${matchField}] = '${EscapeSQLString(text)}'`,
341
+ Fields: [keyName],
342
+ MaxRows: 1,
343
+ }, this.Options.ContextUser);
344
+ if (!res.Success) {
345
+ throw new Error(`applyOutputMapping: RunView failed for lookup on '${related}': ${res.ErrorMessage || 'unknown error'}`);
346
+ }
347
+ const cacheKey = `${related}|${matchField}|${text}`;
348
+ const row = res.Results?.[0];
349
+ if (row) {
350
+ const key = row[keyName]; // config-named key column
351
+ if (typeof key !== 'string' && typeof key !== 'number') {
352
+ throw new Error(`applyOutputMapping: lookup on '${related}' for field '${field}' found a row without a '${keyName}' key`);
353
+ }
354
+ this.CacheLookup(cacheKey, key);
355
+ return key;
356
+ }
357
+ if (onMiss === 'fail') {
358
+ throw new Error(`applyOutputMapping: lookup for '${field}' on entity '${related}' where [${matchField}]='${text}' matched 0 rows (OnLookupMiss=fail)`);
359
+ }
360
+ return onMiss === 'create' ? this.CreateLookupRow(related, matchField, text, keyName, cacheKey) : null;
361
+ }
362
+ /** Caches a lookup's key for the run, when {@link CanCacheLookups} allows. */
363
+ CacheLookup(cacheKey, key) {
364
+ if (this.CanCacheLookups) {
365
+ this.Options.LookupCache.set(cacheKey, key);
366
+ }
367
+ }
368
+ /** Creates the related row a `create` miss asks for (match field only) and caches its key; a dry run returns a preview key. */
369
+ async CreateLookupRow(related, matchField, text, keyName, cacheKey) {
370
+ if (this.Options.DryRun) {
371
+ return `preview-new-${related}-${text}`;
372
+ }
373
+ const row = await this.Options.LookupProvider.GetEntityObject(related, this.Options.ContextUser);
374
+ row.NewRecord();
375
+ row.Set(matchField, text); // config-driven match field
376
+ if (!(await row.Save())) {
377
+ throw new Error(`applyOutputMapping: failed creating new record in '${related}' with ${matchField}='${text}': ${row.LatestResult?.CompleteMessage || 'unknown error'}`);
378
+ }
379
+ const id = row.Get(keyName); // config-named key column
380
+ const key = typeof id === 'string' || typeof id === 'number' ? id : row.PrimaryKey.ToCompactURLSegment();
381
+ this.Options.Result.changed = true; // the lookup row was written
382
+ this.CacheLookup(cacheKey, key);
383
+ return key;
384
+ }
385
+ /** A config-named field's metadata (names compare case-insensitively), or undefined when the entity does not declare it. */
386
+ FieldInfoOf(entity, field) {
387
+ return OutputMappingWriter.FieldInfoFor(entity, field);
388
+ }
389
+ /** A config-named field's metadata, names compared case-insensitively; undefined when the entity does not declare it. */
390
+ static FieldInfoFor(entity, field) {
391
+ const name = field.toLowerCase();
392
+ return entity?.Fields?.find((f) => f.Name.toLowerCase() === name);
393
+ }
394
+ /** Every child mapping of an output mapping, in write order: the single `childRecord` (flagged) first, then `childRecords`. */
395
+ static ChildMappingsOf(outputMapping) {
396
+ const mappings = [];
397
+ if (outputMapping.childRecord) {
398
+ mappings.push({ Config: outputMapping.childRecord, IsLegacySingle: true });
399
+ }
400
+ if (outputMapping.childRecords && Array.isArray(outputMapping.childRecords)) {
401
+ for (const c of outputMapping.childRecords) {
402
+ mappings.push({ Config: c, IsLegacySingle: false });
403
+ }
404
+ }
405
+ return mappings;
406
+ }
407
+ /**
408
+ * A child mapping's parent field, checked to be a plain identifier (it is written into a view filter).
409
+ * @throws Error when the parent field is not a plain identifier
410
+ */
411
+ static ParentFieldOf(config) {
412
+ if (!/^[A-Za-z0-9_]+$/.test(config.parentField)) {
413
+ throw new Error(`invalid parentField identifier '${config.parentField}' for '${config.entity}'`);
414
+ }
415
+ return config.parentField;
416
+ }
417
+ /** The entity a mapping's tags are linked on (its `taggedEntityName`'s, else the record's); undefined when unknown. */
418
+ static TaggedEntityIDOf(provider, mapping, record) {
419
+ return mapping.taggedEntityName ? provider.EntityByName(mapping.taggedEntityName)?.ID : record.EntityID;
420
+ }
421
+ /** Inserts one child row; throws with the save's CompleteMessage when the save fails. */
422
+ async InsertChild(item) {
423
+ const child = await this.Options.Provider.GetEntityObject(item.Entity, this.Options.ContextUser);
424
+ child.NewRecord();
425
+ for (const [field, value] of Object.entries(item.Data)) {
426
+ child.Set(field, value); // config-driven field names
427
+ }
428
+ if (!(await child.Save())) {
429
+ throw new Error(`applyOutputMapping: failed creating '${item.Entity}' child: ${child.LatestResult?.CompleteMessage || 'unknown error'}`);
430
+ }
431
+ return child.PrimaryKey.ToCompactURLSegment();
432
+ }
433
+ /** Reports the inserted rows on the result (`createdChildID` = the single legacy mapping's row). */
434
+ RecordCreated(items, created) {
435
+ if (created.size === 0) {
436
+ return;
437
+ }
438
+ this.Options.Result.createdChildIDs = [...created.values()];
439
+ const single = items.find((i) => i.IsLegacySingle && created.has(i));
440
+ if (single) {
441
+ this.Options.Result.createdChildID = created.get(single);
442
+ }
443
+ this.Options.Result.changed = true;
444
+ }
445
+ /**
446
+ * Reconciles one mapping's proposed rows with the parent's existing rows: inserts new keys, updates or keeps existing
447
+ * ones (human rows only when overwriting), then deletes stale pipeline rows.
448
+ */
449
+ async ReconcileChildren(config, rc, items, created) {
450
+ this.ValidateReconcileConfig(config, rc);
451
+ const childEntity = this.Options.Provider.EntityByName(config.entity);
452
+ const keyed = this.KeyProposals(config, rc, childEntity, items);
453
+ const { Existing, Matches } = await this.MatchExisting(config, rc, childEntity, keyed);
454
+ for (const { Item, Row } of Matches) {
455
+ if (Row) {
456
+ await this.ReconcileRow(config, Row, this.RowDecision(rc, childEntity, Row, Item.Data));
457
+ }
458
+ else {
459
+ created.set(Item, await this.InsertChild(Item));
460
+ }
461
+ }
462
+ await this.DeleteStaleChildren(config, rc, childEntity, Existing, new Set(keyed.keys()));
463
+ }
464
+ /** The parent's existing rows of a mapping, and each keyed proposal paired with the existing row of its key. */
465
+ async MatchExisting(config, rc, childEntity, keyed) {
466
+ const existing = await this.LoadExistingChildren(config);
467
+ const byKey = new Map(existing.map((row) => [this.KeyOfRow(rc, childEntity, row), row]));
468
+ return { Existing: existing, Matches: [...keyed].map(([key, item]) => ({ Item: item, Row: byKey.get(key) })) };
469
+ }
470
+ /** Refuses a reconcile config that cannot work: no key fields, a key field the map does not set, or `deleteStale` without a source. */
471
+ ValidateReconcileConfig(config, rc) {
472
+ if (!rc.keyFields || rc.keyFields.length === 0) {
473
+ throw new Error(`applyOutputMapping: reconcile on '${config.entity}' needs at least one keyFields entry`);
474
+ }
475
+ const unmapped = rc.keyFields.filter((f) => !(f in config.map));
476
+ if (unmapped.length > 0) {
477
+ throw new Error(`applyOutputMapping: reconcile key field(s) ${unmapped.join(', ')} of '${config.entity}' are not set by its map`);
478
+ }
479
+ if (rc.deleteStale !== false && (!rc.sourceField || !rc.derivedSourceValue)) {
480
+ throw new Error(`applyOutputMapping: reconcile on '${config.entity}' deletes stale rows, so it needs sourceField and derivedSourceValue to tell pipeline rows from human rows (or set deleteStale: false)`);
481
+ }
482
+ }
483
+ /** The proposals keyed by their reconcile key; throws when the answer proposes one key twice (it would hit the unique key). */
484
+ KeyProposals(config, rc, childEntity, items) {
485
+ const { Keyed, Repeated } = this.KeyedProposals(rc, childEntity, items);
486
+ if (Repeated.length > 0) {
487
+ throw new Error(`applyOutputMapping: the answer for '${config.entity}' proposes the reconcile key '${Repeated[0]}' more than once`);
488
+ }
489
+ return Keyed;
490
+ }
491
+ /** The proposals keyed by their reconcile key (the first of a key kept), and each key proposed more than once. */
492
+ KeyedProposals(rc, childEntity, items) {
493
+ const keyed = new Map();
494
+ const repeated = new Set();
495
+ for (const item of items) {
496
+ const key = this.KeyOfData(rc, childEntity, item.Data);
497
+ if (keyed.has(key)) {
498
+ repeated.add(key);
499
+ continue;
500
+ }
501
+ keyed.set(key, item);
502
+ }
503
+ return { Keyed: keyed, Repeated: [...repeated] };
504
+ }
505
+ /** The parent's existing rows of a child mapping, read fresh (they are updated or deleted in this transaction). */
506
+ async LoadExistingChildren(config) {
507
+ const res = await RunView.FromMetadataProvider(this.Options.Provider).RunView({
508
+ EntityName: config.entity,
509
+ ExtraFilter: `${OutputMappingWriter.ParentFieldOf(config)} = '${EscapeSQLString(this.Options.Record.RecordID)}'`,
510
+ ResultType: 'entity_object', // the rows are saved or deleted below
511
+ BypassCache: true, // a cached read could miss a row this run's transaction must update or delete
512
+ }, this.Options.ContextUser);
513
+ if (!res.Success) {
514
+ throw new Error(`applyOutputMapping: reading existing '${config.entity}' rows failed: ${res.ErrorMessage}`);
515
+ }
516
+ return res.Results || [];
517
+ }
518
+ /** A row's key within its parent: its key fields, normalised and joined. */
519
+ KeyOfRow(rc, childEntity, row) {
520
+ return rc.keyFields.map((f) => OutputMappingWriter.NormalizeKeyPart(this.FieldInfoOf(childEntity, f), row.Get(f))).join('|'); // config-driven field names
521
+ }
522
+ /** A proposed row's key within its parent. */
523
+ KeyOfData(rc, childEntity, data) {
524
+ return rc.keyFields.map((f) => OutputMappingWriter.NormalizeKeyPart(this.FieldInfoOf(childEntity, f), data[f])).join('|');
525
+ }
526
+ /** Whether a person owns the row: its source field holds anything but the pipeline's value (exact, as stored). */
527
+ IsHumanRow(rc, childEntity, row) {
528
+ return !!rc.sourceField
529
+ && !OutputMappingWriter.ValuesEqual(this.FieldInfoOf(childEntity, rc.sourceField), row.Get(rc.sourceField), rc.derivedSourceValue); // config-driven field name
530
+ }
531
+ /**
532
+ * What the write does with an existing row a proposal matches: leaves a human row alone (unless overwriting),
533
+ * keeps an identical row, or updates the differing fields. Shared by the write and {@link PlanChildren}.
534
+ */
535
+ RowDecision(rc, childEntity, row, data) {
536
+ if (this.IsHumanRow(rc, childEntity, row) && !this.Options.OverwriteHumanValues) {
537
+ return { Kind: 'human' };
538
+ }
539
+ const differing = Object.entries(data).filter(([f, v]) => !OutputMappingWriter.ValuesEqual(this.FieldInfoOf(childEntity, f), row.Get(f), v)); // config-driven field names
540
+ return differing.length === 0 ? { Kind: 'unchanged' } : { Kind: 'update', Changes: differing };
541
+ }
542
+ /** Applies a {@link RowDecision}: records a preserved human row or an unchanged row, or saves the differing fields. */
543
+ async ReconcileRow(config, row, decision) {
544
+ const id = row.PrimaryKey.ToCompactURLSegment();
545
+ const result = this.Options.Result;
546
+ if (decision.Kind === 'human') {
547
+ (result.preservedHumanChildIDs ||= []).push(id);
548
+ return;
549
+ }
550
+ if (decision.Kind === 'unchanged') {
551
+ (result.unchangedChildIDs ||= []).push(id);
552
+ return;
553
+ }
554
+ for (const [f, v] of decision.Changes) {
555
+ row.Set(f, v); // config-driven field names
556
+ }
557
+ if (!(await row.Save())) {
558
+ throw new Error(`applyOutputMapping: failed updating '${config.entity}' row '${id}': ${row.LatestResult?.CompleteMessage || 'unknown error'}`);
559
+ }
560
+ (result.updatedChildIDs ||= []).push(id);
561
+ result.changed = true;
562
+ }
563
+ /** The existing pipeline rows (never human rows) whose key the result no longer proposes; none with `deleteStale: false`. */
564
+ StaleRows(rc, childEntity, existing, proposed) {
565
+ if (rc.deleteStale === false) {
566
+ return [];
567
+ }
568
+ return existing.filter((row) => !proposed.has(this.KeyOfRow(rc, childEntity, row)) && !this.IsHumanRow(rc, childEntity, row));
569
+ }
570
+ /** Deletes the pipeline's rows the new result no longer proposes (sequentially, in the unit's transaction). */
571
+ async DeleteStaleChildren(config, rc, childEntity, existing, proposed) {
572
+ for (const row of this.StaleRows(rc, childEntity, existing, proposed)) {
573
+ const id = row.PrimaryKey.ToCompactURLSegment();
574
+ if (!(await row.Delete())) {
575
+ throw new Error(`applyOutputMapping: failed deleting stale '${config.entity}' row '${id}': ${row.LatestResult?.CompleteMessage || 'unknown error'}`);
576
+ }
577
+ (this.Options.Result.deletedChildIDs ||= []).push(id);
578
+ this.Options.Result.changed = true;
579
+ }
580
+ }
581
+ /**
582
+ * The child values the real write stores ({@link PlanChildren}) and what it would fail on: a reconcile key proposed
583
+ * twice, or a stored value with no row in its related entity ({@link MissingForeignKeys}). Writes nothing.
584
+ */
585
+ async PreviewChildren(answers) {
586
+ const problems = this.DuplicateKeyProblems(answers);
587
+ const writes = await this.PlanChildren(answers);
588
+ const targets = this.CollectForeignKeyRefs(writes, problems);
589
+ problems.push(...(await this.MissingForeignKeyProblems(targets)));
590
+ return { Writes: writes, Problems: problems };
591
+ }
592
+ /**
593
+ * The record's fields the real write changes ({@link FieldChanges}) and what it would fail on: a changed UUID value
594
+ * with no row in its related entity, or a record that does not exist. Writes nothing.
595
+ */
596
+ async PreviewFields(entity, fields) {
597
+ const obj = await this.LoadRecord(entity);
598
+ if (!obj) {
599
+ return { Changes: {}, Problems: [`record '${this.Options.Record.RecordID}' of '${entity.Name}' not found (the real write fails loading it)`] };
600
+ }
601
+ const problems = [];
602
+ const targets = new Map();
603
+ const changes = await this.FieldChanges(entity, obj, fields, false);
604
+ for (const [field, value] of changes) {
605
+ const fieldInfo = this.FieldInfoOf(entity, field);
606
+ if (typeof value === 'string' && UUID_PATTERN.test(value.trim()) && this.IsConstrainedForeignKey(fieldInfo)) {
607
+ this.AddForeignKeyRef(targets, problems, fieldInfo, { Entity: entity.Name, Field: field, Value: value });
608
+ }
609
+ }
610
+ problems.push(...(await this.MissingForeignKeyProblems(targets)));
611
+ return { Changes: Object.fromEntries(changes), Problems: problems };
612
+ }
613
+ /** Reconcile keys a mapping's answer proposes more than once: the real write refuses them (unique key). */
614
+ DuplicateKeyProblems(answers) {
615
+ const problems = [];
616
+ for (const { Config: config, Rows: rows } of answers) {
617
+ const rc = config.reconcile;
618
+ if (!rc) {
619
+ continue;
620
+ }
621
+ this.ValidateReconcileConfig(config, rc);
622
+ const { Repeated } = this.KeyedProposals(rc, this.Options.Provider.EntityByName(config.entity), rows);
623
+ for (const key of Repeated) {
624
+ problems.push(`'${config.entity}' would receive the reconcile key (${rc.keyFields.join(', ')}) = '${key}' twice (the real write fails on its unique key)`);
625
+ }
626
+ }
627
+ return problems;
628
+ }
629
+ /**
630
+ * The child values the real write stores, by its own decisions: every row of a plain mapping; a reconciled
631
+ * proposal's values when no existing row has its key, else only the fields {@link RowDecision} updates.
632
+ */
633
+ async PlanChildren(answers) {
634
+ const writes = [];
635
+ for (const { Config: config, Rows: rows } of answers) {
636
+ const rc = config.reconcile;
637
+ if (!rc) {
638
+ writes.push(...rows.map((item) => ({ Item: item, Values: item.Data })));
639
+ continue;
640
+ }
641
+ const childEntity = this.Options.Provider.EntityByName(config.entity);
642
+ const { Matches } = await this.MatchExisting(config, rc, childEntity, this.KeyedProposals(rc, childEntity, rows).Keyed);
643
+ for (const { Item, Row } of Matches) {
644
+ const decision = Row ? this.RowDecision(rc, childEntity, Row, Item.Data) : undefined;
645
+ if (!decision) {
646
+ writes.push({ Item, Values: Item.Data });
647
+ }
648
+ else if (decision.Kind === 'update') {
649
+ writes.push({ Item, Values: Object.fromEntries(decision.Changes) });
650
+ }
651
+ }
652
+ }
653
+ return writes;
654
+ }
655
+ /** Every written child value of a constrained foreign-key field (the parent key excepted), grouped by related column. */
656
+ CollectForeignKeyRefs(writes, problems) {
657
+ const targets = new Map();
658
+ const unknownEntities = new Set();
659
+ for (const { Item: item, Values: values } of writes) {
660
+ const info = this.Options.Provider.EntityByName(item.Entity);
661
+ if (!info) {
662
+ unknownEntities.add(item.Entity);
663
+ continue;
664
+ }
665
+ for (const [field, value] of Object.entries(values)) {
666
+ const fieldInfo = this.FieldInfoOf(info, field);
667
+ if (value === null || value === undefined || field === item.Config.parentField || !this.IsConstrainedForeignKey(fieldInfo)) {
668
+ continue;
669
+ }
670
+ if (typeof value !== 'string' && typeof value !== 'number') {
671
+ problems.push(`'${item.Entity}.${field}' holds a value of type ${Array.isArray(value) ? 'array' : typeof value}, which cannot be a key of '${this.RelatedEntityNameOf(fieldInfo, undefined)}'`);
672
+ continue;
673
+ }
674
+ this.AddForeignKeyRef(targets, problems, fieldInfo, { Entity: item.Entity, Field: field, Value: value });
675
+ }
676
+ }
677
+ problems.push(...[...unknownEntities].map((e) => `child entity '${e}' is not in metadata`));
678
+ return targets;
679
+ }
680
+ /** Whether the database checks the field with a foreign-key constraint (a related entity in metadata, not a soft key). */
681
+ IsConstrainedForeignKey(fieldInfo) {
682
+ return !!fieldInfo && fieldInfo.IsSoftForeignKey !== true && !!this.RelatedEntityNameOf(fieldInfo, undefined);
683
+ }
684
+ /** Adds a written value to the group of the related column its constraint references, or reports a missing one. */
685
+ AddForeignKeyRef(targets, problems, fieldInfo, ref) {
686
+ const relatedName = this.RelatedEntityNameOf(fieldInfo, undefined) || '';
687
+ const related = this.Options.LookupProvider.EntityByName(relatedName);
688
+ const column = fieldInfo.RelatedEntityFieldName || related?.FirstPrimaryKey?.Name; // first-pk-ok: a foreign key without a named related column references the related primary key (one column)
689
+ if (!related || !column) {
690
+ problems.push(`'${ref.Entity}.${ref.Field}' references '${relatedName}', which is not in metadata or has no key column`);
691
+ return;
692
+ }
693
+ const groupKey = `${related.Name}|${column}`;
694
+ const target = targets.get(groupKey) || { Related: related, Column: column, Refs: [] };
695
+ target.Refs.push(ref);
696
+ targets.set(groupKey, target);
697
+ }
698
+ /** {@link MissingForeignKeys} of every related column, in parallel. */
699
+ async MissingForeignKeyProblems(targets) {
700
+ const perTarget = await Promise.all([...targets.values()].map((t) => this.MissingForeignKeys(t)));
701
+ return perTarget.flat();
702
+ }
703
+ /**
704
+ * The written values with no row in their related entity: one `RunView` of the related column per entity. A value
705
+ * that is not a UUID cannot be a key of a uniqueidentifier column; a related column of another type is not checked.
706
+ */
707
+ async MissingForeignKeys(target) {
708
+ if (!this.FieldInfoOf(target.Related, target.Column)?.IsUniqueIdentifier) {
709
+ return [];
710
+ }
711
+ const related = target.Related.Name;
712
+ const problems = [];
713
+ const keyed = target.Refs.filter((ref) => {
714
+ const isKey = UUID_PATTERN.test(String(ref.Value).trim());
715
+ if (!isKey) {
716
+ problems.push(`'${ref.Entity}.${ref.Field}' = '${ref.Value}' is not a valid key of '${related}' (the real write fails converting it)`);
717
+ }
718
+ return isKey;
719
+ });
720
+ if (keyed.length === 0) {
721
+ return problems;
722
+ }
723
+ const ids = [...new Set(keyed.map((ref) => String(ref.Value).trim()))];
724
+ const result = await RunView.FromMetadataProvider(this.Options.LookupProvider).RunView({
725
+ EntityName: related,
726
+ ExtraFilter: `${target.Column} IN (${ids.map((id) => `'${id}'`).join(',')})`,
727
+ Fields: [target.Column],
728
+ ResultType: 'simple',
729
+ }, this.Options.ContextUser);
730
+ if (!result.Success) {
731
+ return [...problems, `checking '${related}' for the written values failed: ${result.ErrorMessage}`];
732
+ }
733
+ const found = new UUIDSet(result.Results.map((r) => r[target.Column]));
734
+ for (const ref of keyed) {
735
+ if (!found.Has(String(ref.Value).trim())) {
736
+ problems.push(`'${ref.Entity}.${ref.Field}' = '${ref.Value}' does not exist in '${related}' (the real write fails on its foreign key)`);
737
+ }
738
+ }
739
+ return problems;
740
+ }
741
+ }
10
742
  /**
11
743
  * Computes the depth of a tag relative to a root tag.
12
744
  * Returns 0 if tagID === rootTagID, 1 for direct children, 2 for grandchildren, etc.
@@ -36,15 +768,15 @@ function computeTagDepth(tagID, rootTagID, tagEngine) {
36
768
  }
37
769
  /**
38
770
  * Applies an {@link OutputMappingConfig} against a work result.
39
- * Supports updating fields (both single-key and composite-key entities), creating child records
40
- * (with array fan-out), and linking/creating tags via TagEngine.
771
+ * Supports updating fields (both single-key and composite-key entities), writing child records
772
+ * (with array fan-out; a `reconcile` mapping is matched to existing rows on its key), and linking/creating
773
+ * tags via TagEngine. `unitWork`, the child rows and the fields are written in one entity transaction on its
774
+ * own provider instance; tags after it. A field a person entered is kept unless `overwriteHumanValues` is set.
41
775
  *
42
776
  * Values resolve from `$` (result), `record` (parent row) and `$run` (provenance).
43
777
  */
44
778
  export async function ApplyOutputMapping(opts) {
45
- const { outputMapping, result, record, contextUser, dryRun, run } = opts;
46
- const provider = opts.provider ?? Metadata.Provider;
47
- const lookupCache = opts.lookupCache ?? new Map();
779
+ const { outputMapping, result, record, contextUser, dryRun, run, provider } = opts;
48
780
  let payload = result;
49
781
  if (typeof payload === 'string') {
50
782
  try {
@@ -59,178 +791,73 @@ export async function ApplyOutputMapping(opts) {
59
791
  record: record.Record ?? {},
60
792
  $run: run ?? {},
61
793
  };
62
- const out = { updatedRecord: false };
794
+ const out = { updatedRecord: false, changed: false };
63
795
  if (dryRun) {
64
796
  out.dryRun = true;
65
797
  }
66
- // 1) Update fields on the processed record.
798
+ // Field resolution runs on the caller's provider; the write unit below gets the same options on its unit provider.
799
+ const writerOptions = {
800
+ Record: record, Provider: provider, LookupProvider: provider, ContextUser: contextUser, Result: out,
801
+ OverwriteHumanValues: opts.overwriteHumanValues === true, HumanGuard: opts.humanGuard,
802
+ FieldLookups: outputMapping.fieldLookups, LookupCache: opts.lookupCache || new Map(), DryRun: dryRun === true,
803
+ Withheld: opts.withheld,
804
+ };
805
+ const writer = new OutputMappingWriter(writerOptions);
806
+ // Set when there are field mappings: the processed record's entity and its resolved values, written in step 3.
807
+ let fieldEntity;
808
+ let fieldsToWrite;
809
+ // On a dry run: what the real write would fail on (WriteBackResult.previewErrors).
810
+ const previewErrors = [];
811
+ // 1) Resolve the fields of the processed record.
67
812
  if (outputMapping.fields && Object.keys(outputMapping.fields).length > 0) {
68
813
  const entity = provider.EntityByID(record.EntityID);
69
814
  if (!entity) {
70
815
  throw new Error(`applyOutputMapping: entity '${record.EntityID}' not found in metadata`);
71
816
  }
72
- // Resolve the mapped values once — shared by the dry-run preview and the real apply.
817
+ // Resolve the mapped values once — shared by the dry-run preview and the real apply. A withheld field (the
818
+ // answer abstained) maps to null: the human-value guard keeps a person's value, and clears one the pipeline wrote.
73
819
  const resolved = {};
74
820
  for (const [field, ref] of Object.entries(outputMapping.fields)) {
75
- resolved[field] = resolveMappingRef(ref, sources);
76
- }
77
- // Resolve foreign-key fields where the mapped value is a match string (e.g. 'Director') instead of an ID
78
- for (const [field, val] of Object.entries(resolved)) {
79
- if (val === null || val === undefined) {
80
- continue;
81
- }
82
- const fieldInfo = entity.Fields?.find((f) => f.Name.toLowerCase() === field.toLowerCase());
83
- const lookupConfig = outputMapping.fieldLookups?.[field];
84
- const isFK = Boolean(lookupConfig || fieldInfo?.RelatedEntity || fieldInfo?.RelatedEntityID);
85
- if (!isFK) {
86
- continue;
87
- }
88
- // If the value is already a valid UUID, no lookup is required.
89
- const isUUID = typeof val === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(val.trim());
90
- if (isUUID) {
91
- resolved[field] = val.trim();
92
- continue;
93
- }
94
- const onLookupMiss = lookupConfig?.onLookupMiss || 'null';
95
- let matchValue = val;
96
- if (Array.isArray(matchValue) && matchValue.length > 0) {
97
- matchValue = matchValue[0];
98
- }
99
- if (matchValue && typeof matchValue === 'object' && 'Name' in matchValue) {
100
- matchValue = matchValue.Name;
101
- }
102
- if (typeof matchValue !== 'string' && typeof matchValue !== 'number') {
103
- if (onLookupMiss === 'fail') {
104
- throw new Error(`applyOutputMapping: cannot resolve foreign key for field '${field}': value is not a string or number (${typeof matchValue})`);
105
- }
106
- resolved[field] = null;
107
- continue;
108
- }
109
- const strVal = String(matchValue).trim();
110
- if (strVal.length === 0) {
111
- if (onLookupMiss === 'fail') {
112
- throw new Error(`applyOutputMapping: cannot resolve foreign key for field '${field}': value resolved to an empty string`);
113
- }
114
- resolved[field] = null;
115
- continue;
116
- }
117
- const relatedEntityName = lookupConfig?.relatedEntity ||
118
- fieldInfo?.RelatedEntity ||
119
- (fieldInfo?.RelatedEntityID ? provider.EntityByID(fieldInfo.RelatedEntityID)?.Name : undefined);
120
- if (!relatedEntityName) {
121
- if (onLookupMiss === 'fail') {
122
- throw new Error(`applyOutputMapping: cannot resolve foreign key for field '${field}': related entity unknown in metadata`);
123
- }
124
- resolved[field] = null;
125
- continue;
126
- }
127
- const matchField = lookupConfig?.matchField || 'Name';
128
- if (!/^[a-zA-Z0-9_]+$/.test(matchField)) {
129
- throw new Error(`applyOutputMapping: invalid matchField identifier '${matchField}' for entity '${relatedEntityName}'`);
130
- }
131
- const cacheKey = `${relatedEntityName}|${matchField}|${strVal}`;
132
- if (lookupCache.has(cacheKey)) {
133
- resolved[field] = lookupCache.get(cacheKey);
134
- continue;
135
- }
136
- const rv = provider && typeof provider.RunView === 'function'
137
- ? RunView.FromMetadataProvider(provider)
138
- : (RunView.Provider ? new RunView() : undefined);
139
- if (!rv) {
140
- throw new Error(`applyOutputMapping: cannot resolve foreign key for field '${field}': RunView provider is unavailable`);
141
- }
142
- const escapedVal = EscapeSQLString(strVal);
143
- const viewRes = await rv.RunView({
144
- EntityName: relatedEntityName,
145
- ExtraFilter: `[${matchField}] = '${escapedVal}'`,
146
- MaxRows: 1,
147
- }, contextUser);
148
- if (viewRes.Success && viewRes.Results && viewRes.Results.length > 0) {
149
- const matchRow = viewRes.Results[0];
150
- const relEntity = provider.EntityByName(relatedEntityName);
151
- const pkFieldName = relEntity?.FirstPrimaryKey?.Name ?? 'ID'; // first-pk-ok: FK target PK resolution
152
- const resolvedID = matchRow[pkFieldName] ?? matchRow.ID;
153
- resolved[field] = resolvedID;
154
- if (typeof resolvedID === 'string' || typeof resolvedID === 'number') {
155
- lookupCache.set(cacheKey, resolvedID);
156
- }
157
- }
158
- else if (!viewRes.Success) {
159
- throw new Error(`applyOutputMapping: RunView failed for lookup on '${relatedEntityName}': ${viewRes.ErrorMessage ?? 'unknown error'}`);
160
- }
161
- else {
162
- // Zero-row lookup miss
163
- if (onLookupMiss === 'null') {
164
- resolved[field] = null;
165
- // Do not cache null — keeps positive hits only and prevents downgrading policies (e.g. 'fail' or 'create') across records
166
- }
167
- else if (onLookupMiss === 'fail') {
168
- throw new Error(`applyOutputMapping: lookup for '${field}' on entity '${relatedEntityName}' where [${matchField}]='${strVal}' matched 0 rows (OnLookupMiss=fail)`);
169
- }
170
- else if (onLookupMiss === 'create') {
171
- if (dryRun) {
172
- resolved[field] = `preview-new-${relatedEntityName}-${strVal}`;
173
- }
174
- else {
175
- const newObj = await provider.GetEntityObject(relatedEntityName, contextUser);
176
- newObj.NewRecord();
177
- // Dynamic, config-driven match field — legitimate use of Set()
178
- newObj.Set(matchField, strVal);
179
- const created = await newObj.Save();
180
- if (!created) {
181
- throw new Error(`applyOutputMapping: failed creating new record in '${relatedEntityName}' with ${matchField}='${strVal}': ${newObj.LatestResult?.CompleteMessage ?? 'unknown error'}`);
182
- }
183
- const relEntity = provider.EntityByName(relatedEntityName);
184
- const pkFieldName = relEntity?.FirstPrimaryKey?.Name ?? 'ID'; // first-pk-ok: FK target PK resolution
185
- const createdVal = newObj.FirstPrimaryKey?.Value ?? (typeof newObj.Get === 'function' ? newObj.Get(pkFieldName) : undefined); // first-pk-ok: FK target entity single-column PK resolution
186
- const resolvedPk = typeof createdVal === 'string' || typeof createdVal === 'number'
187
- ? createdVal
188
- : newObj.PrimaryKey.ToCompactURLSegment();
189
- resolved[field] = resolvedPk;
190
- if (typeof resolvedPk === 'string' || typeof resolvedPk === 'number') {
191
- lookupCache.set(cacheKey, resolvedPk);
192
- }
193
- }
821
+ const withheld = WithheldTargets.HasField(opts.withheld, field);
822
+ if (withheld) {
823
+ (out.withheldFields ||= []).push(field);
824
+ if (WithheldTargets.ColumnRequiresValue(entity, field)) {
825
+ // A column that does not allow null cannot be cleared: its value stays, and the result says why
826
+ (out.withheldKeptFields ||= []).push(field);
827
+ continue;
194
828
  }
195
829
  }
830
+ resolved[field] = withheld ? null : ResolveMappingRef(ref, sources);
831
+ }
832
+ // Foreign-key fields whose mapped value is a match string (e.g. 'Director') resolve to the related row's key.
833
+ for (const [field, val] of Object.entries(resolved)) {
834
+ resolved[field] = await writer.ResolveFieldValue(entity, field, val);
196
835
  }
197
836
  if (dryRun) {
198
- // Compute-only: surface what an apply WOULD write, persist nothing.
199
- out.previewFields = resolved;
837
+ // Compute-only: surface the fields an apply WOULD change, and what it would fail on; persist nothing.
838
+ const preview = await writer.PreviewFields(entity, resolved);
839
+ out.previewFields = preview.Changes;
840
+ previewErrors.push(...preview.Problems);
200
841
  }
201
842
  else {
202
- const obj = await provider.GetEntityObject(entity.Name, contextUser);
203
- // RecordID is the compact CompositeKey segment (bare value for a single column, "F1|v1||F2|v2" for composite).
204
- const loaded = await obj.InnerLoad(CompositeKey.FromURLSegment(entity, record.RecordID));
205
- if (!loaded) {
206
- throw new Error(`applyOutputMapping: record '${record.RecordID}' of '${entity.Name}' not found`);
207
- }
208
- for (const [field, value] of Object.entries(resolved)) {
209
- // Dynamic, config-driven field names — legitimate use of Set() (no compile-time property).
210
- obj.Set(field, value);
211
- }
212
- const saved = await obj.Save();
213
- if (!saved) {
214
- throw new Error(`applyOutputMapping: failed updating '${entity.Name}' record '${record.RecordID}': ${obj.LatestResult?.CompleteMessage ?? 'unknown error'}`);
215
- }
216
- out.updatedRecord = true;
217
- }
218
- }
219
- // 2) Create child records (single childRecord and/or childRecords with fan-out).
220
- const childConfigs = [];
221
- if (outputMapping.childRecord) {
222
- childConfigs.push({ config: outputMapping.childRecord, isLegacySingle: true });
223
- }
224
- if (outputMapping.childRecords && Array.isArray(outputMapping.childRecords)) {
225
- for (const c of outputMapping.childRecords) {
226
- childConfigs.push({ config: c, isLegacySingle: false });
843
+ fieldEntity = entity;
844
+ fieldsToWrite = resolved;
227
845
  }
228
846
  }
847
+ // 2) Resolve the child records (single childRecord and/or childRecords with fan-out). Each mapping with an answer
848
+ // becomes one ChildMappingAnswer; an empty array is an answer ("none"), a missing/null fan-out value is not.
849
+ const childAnswers = [];
850
+ const childConfigs = OutputMappingWriter.ChildMappingsOf(outputMapping);
229
851
  if (childConfigs.length > 0) {
230
- const childRecordsToCreate = [];
231
- for (const { config: childConfig, isLegacySingle } of childConfigs) {
852
+ for (const { Config: childConfig, IsLegacySingle: isLegacySingle } of childConfigs) {
853
+ if (WithheldTargets.HasChildEntity(opts.withheld, childConfig.entity)) {
854
+ // Withheld: not an answer, so nothing of this mapping changes (a reconcile mapping deletes nothing)
855
+ (out.withheldChildEntities ||= []).push(childConfig.entity);
856
+ continue;
857
+ }
858
+ const rows = [];
232
859
  if (childConfig.fanOutRef) {
233
- const fanOutVal = resolveMappingRef(childConfig.fanOutRef, sources);
860
+ const fanOutVal = ResolveMappingRef(childConfig.fanOutRef, sources);
234
861
  let items;
235
862
  if (Array.isArray(fanOutVal)) {
236
863
  items = fanOutVal;
@@ -239,10 +866,12 @@ export async function ApplyOutputMapping(opts) {
239
866
  items = [fanOutVal];
240
867
  }
241
868
  else {
242
- items = [];
869
+ // No answer for this mapping (missing, null, or not a list): nothing of it changes — in particular a
870
+ // reconcile mapping deletes nothing, because "not answered" is not "none".
243
871
  if (fanOutVal !== null && fanOutVal !== undefined) {
244
872
  LogStatus(`applyOutputMapping: fanOutRef '${childConfig.fanOutRef}' resolved to non-array/non-object value of type '${typeof fanOutVal}'`);
245
873
  }
874
+ continue;
246
875
  }
247
876
  for (const item of items) {
248
877
  const itemSources = {
@@ -254,62 +883,61 @@ export async function ApplyOutputMapping(opts) {
254
883
  };
255
884
  const childMap = { [childConfig.parentField]: record.RecordID };
256
885
  for (const [field, ref] of Object.entries(childConfig.map)) {
257
- childMap[field] = resolveMappingRef(ref, itemSources);
886
+ childMap[field] = ResolveMappingRef(ref, itemSources);
258
887
  }
259
- childRecordsToCreate.push({ entity: childConfig.entity, data: childMap, isLegacySingle });
888
+ rows.push({ Entity: childConfig.entity, Data: childMap, IsLegacySingle: isLegacySingle, Config: childConfig });
260
889
  }
261
890
  }
262
891
  else {
263
892
  const childMap = { [childConfig.parentField]: record.RecordID };
264
893
  for (const [field, ref] of Object.entries(childConfig.map)) {
265
- childMap[field] = resolveMappingRef(ref, sources);
894
+ childMap[field] = ResolveMappingRef(ref, sources);
266
895
  }
267
- childRecordsToCreate.push({ entity: childConfig.entity, data: childMap, isLegacySingle });
896
+ rows.push({ Entity: childConfig.entity, Data: childMap, IsLegacySingle: isLegacySingle, Config: childConfig });
268
897
  }
898
+ childAnswers.push({ Config: childConfig, Rows: rows });
269
899
  }
270
- if (childRecordsToCreate.length > 0) {
271
- if (dryRun) {
272
- out.previewChildren = childRecordsToCreate.map((c) => c.data);
273
- const singleChild = childRecordsToCreate.find((c) => c.isLegacySingle);
900
+ if (dryRun) {
901
+ // Only the child values the real write stores: an identical or human-kept row previews nothing
902
+ const preview = await writer.PreviewChildren(childAnswers);
903
+ previewErrors.push(...preview.Problems);
904
+ if (preview.Writes.length > 0) {
905
+ out.previewChildren = preview.Writes.map((w) => w.Values);
906
+ const singleChild = preview.Writes.find((w) => w.Item.IsLegacySingle);
274
907
  if (singleChild) {
275
- out.previewChild = singleChild.data;
908
+ out.previewChild = singleChild.Values;
276
909
  }
277
910
  }
278
- else {
279
- const createdIDs = [];
280
- let singleChildID;
281
- for (const item of childRecordsToCreate) {
282
- const child = await provider.GetEntityObject(item.entity, contextUser);
283
- child.NewRecord();
284
- for (const [field, value] of Object.entries(item.data)) {
285
- child.Set(field, value);
286
- }
287
- const saved = await child.Save();
288
- if (!saved) {
289
- throw new Error(`applyOutputMapping: failed creating '${item.entity}' child: ${child.LatestResult?.CompleteMessage ?? 'unknown error'}`);
290
- }
291
- const childKey = child.PrimaryKey.ToCompactURLSegment();
292
- if (childKey && childKey.length > 0) {
293
- createdIDs.push(childKey);
294
- if (item.isLegacySingle && !singleChildID) {
295
- singleChildID = childKey;
296
- }
297
- }
911
+ }
912
+ }
913
+ // 3) Write the unit work, children, then the record's fields, as one unit of work: a failed write rolls back and
914
+ // leaves the parent field (and the Feature Values) unwritten, so a half-written record never looks complete.
915
+ // The unit runs on its own provider instance so its transaction is its alone.
916
+ if (!dryRun) {
917
+ await MetadataProviderCapabilities.RunIsolated(provider, async (unitProvider) => {
918
+ const unitWriter = new OutputMappingWriter({ ...writerOptions, Provider: unitProvider });
919
+ // A provider without the transaction capability (a client provider) runs the work untransacted, per
920
+ // RunInEntityTransaction's contract for a null provider.
921
+ await RunInEntityTransaction(MetadataProviderCapabilities.IsTransactionalProvider(unitProvider) ? unitProvider : null, async () => {
922
+ if (opts.unitWork) {
923
+ await opts.unitWork(unitProvider);
298
924
  }
299
- out.createdChildIDs = createdIDs;
300
- if (singleChildID) {
301
- out.createdChildID = singleChildID;
925
+ if (childAnswers.length > 0) {
926
+ await unitWriter.WriteChildren(childAnswers);
302
927
  }
303
- }
304
- }
928
+ if (fieldEntity && fieldsToWrite) {
929
+ await unitWriter.WriteRecordFields(fieldEntity, fieldsToWrite);
930
+ }
931
+ });
932
+ });
305
933
  }
306
- // 3) Apply tags via MJ Tagging system.
934
+ // 4) Apply tags via MJ Tagging system (after the commit above).
307
935
  if (outputMapping.tags && outputMapping.tags.length > 0) {
308
936
  const previewTags = [];
309
937
  const createdTaggedItemIDs = [];
310
938
  await TagEngine.Instance.Config(false, contextUser);
311
939
  for (const tagMapping of outputMapping.tags) {
312
- const rawTagVal = resolveMappingRef(tagMapping.ref, sources);
940
+ const rawTagVal = ResolveMappingRef(tagMapping.ref, sources);
313
941
  const tagNames = [];
314
942
  if (typeof rawTagVal === 'string') {
315
943
  tagNames.push(rawTagVal);
@@ -324,6 +952,11 @@ export async function ApplyOutputMapping(opts) {
324
952
  }
325
953
  }
326
954
  }
955
+ const taggedEntityID = OutputMappingWriter.TaggedEntityIDOf(provider, tagMapping, record);
956
+ if (dryRun && !taggedEntityID && tagNames.some((t) => t.trim().length > 0)) {
957
+ // The real write refuses it when it links this mapping's first tag.
958
+ previewErrors.push(`taggedEntityName '${tagMapping.taggedEntityName}' not found in metadata`);
959
+ }
327
960
  const growthMode = (tagMapping.growth ?? 'constrained');
328
961
  const matchThreshold = tagMapping.matchThreshold ?? 0.8;
329
962
  for (const tagName of tagNames) {
@@ -343,7 +976,6 @@ export async function ApplyOutputMapping(opts) {
343
976
  if (matchedTag) {
344
977
  const depth = computeTagDepth(matchedTag.ID, tagMapping.rootTagId, TagEngine.Instance);
345
978
  const isNonDescendant = depth < 0;
346
- const exceedsMaxDepth = isNonDescendant || (tagMapping.maxDepth !== undefined && depth > tagMapping.maxDepth);
347
979
  const errorMsg = isNonDescendant
348
980
  ? `Matched tag '${matchedTag.Name}' is not a descendant of root tag '${tagMapping.rootTagId}'`
349
981
  : (tagMapping.maxDepth !== undefined && depth > tagMapping.maxDepth)
@@ -359,19 +991,26 @@ export async function ApplyOutputMapping(opts) {
359
991
  depth,
360
992
  error: errorMsg,
361
993
  });
994
+ if (errorMsg) {
995
+ previewErrors.push(`tag '${trimmedName}': ${errorMsg}`); // the real write throws on both
996
+ }
362
997
  }
363
998
  else {
364
999
  if (growthMode === 'auto-grow') {
365
1000
  const depth = 1;
366
1001
  const exceedsMaxDepth = tagMapping.maxDepth !== undefined && depth > tagMapping.maxDepth;
1002
+ const createdError = exceedsMaxDepth ? `Created tag exceeds maxDepth (${depth} > ${tagMapping.maxDepth})` : undefined;
367
1003
  previewTags.push({
368
1004
  tagText: trimmedName,
369
1005
  matched: false,
370
1006
  created: true,
371
1007
  rootTagID: tagMapping.rootTagId,
372
1008
  depth,
373
- error: exceedsMaxDepth ? `Created tag exceeds maxDepth (${depth} > ${tagMapping.maxDepth})` : undefined,
1009
+ error: createdError,
374
1010
  });
1011
+ if (createdError) {
1012
+ previewErrors.push(`tag '${trimmedName}': ${createdError}`); // the real write throws on it
1013
+ }
375
1014
  }
376
1015
  else {
377
1016
  previewTags.push({
@@ -400,15 +1039,10 @@ export async function ApplyOutputMapping(opts) {
400
1039
  if (tagMapping.maxDepth !== undefined && depth > tagMapping.maxDepth) {
401
1040
  throw new Error(`applyOutputMapping: tag '${resolvedTag.Name}' depth (${depth}) exceeds maxDepth (${tagMapping.maxDepth}) under root '${tagMapping.rootTagId}'`);
402
1041
  }
403
- let targetEntityID = record.EntityID;
404
- if (tagMapping.taggedEntityName) {
405
- const taggedEntity = provider.EntityByName(tagMapping.taggedEntityName);
406
- if (!taggedEntity) {
407
- throw new Error(`applyOutputMapping: taggedEntityName '${tagMapping.taggedEntityName}' not found in metadata`);
408
- }
409
- targetEntityID = taggedEntity.ID;
1042
+ if (!taggedEntityID) {
1043
+ throw new Error(`applyOutputMapping: taggedEntityName '${tagMapping.taggedEntityName}' not found in metadata`);
410
1044
  }
411
- const taggedItem = await TagEngine.Instance.CreateTaggedItem(resolvedTag.ID, targetEntityID, record.RecordID, 1.0, contextUser);
1045
+ const taggedItem = await TagEngine.Instance.CreateTaggedItem(resolvedTag.ID, taggedEntityID, record.RecordID, 1.0, contextUser);
412
1046
  if (taggedItem) {
413
1047
  const itemKey = taggedItem.PrimaryKey.ToCompactURLSegment();
414
1048
  createdTaggedItemIDs.push(itemKey.length > 0 ? itemKey : taggedItem.ID);
@@ -421,8 +1055,14 @@ export async function ApplyOutputMapping(opts) {
421
1055
  }
422
1056
  else {
423
1057
  out.createdTaggedItemIDs = createdTaggedItemIDs;
1058
+ if (createdTaggedItemIDs.length > 0) {
1059
+ out.changed = true;
1060
+ }
424
1061
  }
425
1062
  }
1063
+ if (previewErrors.length > 0) {
1064
+ out.previewErrors = previewErrors;
1065
+ }
426
1066
  return out;
427
1067
  }
428
1068
  /** @deprecated Use {@link ApplyOutputMapping}. */