@memberjunction/core 6.2.0 → 6.3.0-edge.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 (130) hide show
  1. package/dist/generic/BaseEntitySaveQueue.d.ts +11 -0
  2. package/dist/generic/BaseEntitySaveQueue.d.ts.map +1 -1
  3. package/dist/generic/BaseEntitySaveQueue.js +17 -1
  4. package/dist/generic/BaseEntitySaveQueue.js.map +1 -1
  5. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts +94 -0
  6. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts.map +1 -1
  7. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts +77 -4
  8. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts.map +1 -1
  9. package/dist/generic/appCapabilityRegistry.d.ts +106 -0
  10. package/dist/generic/appCapabilityRegistry.d.ts.map +1 -0
  11. package/dist/generic/appCapabilityRegistry.js +212 -0
  12. package/dist/generic/appCapabilityRegistry.js.map +1 -0
  13. package/dist/generic/baseEngine.d.ts +108 -3
  14. package/dist/generic/baseEngine.d.ts.map +1 -1
  15. package/dist/generic/baseEngine.js +891 -122
  16. package/dist/generic/baseEngine.js.map +1 -1
  17. package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
  18. package/dist/generic/baseEngineRegistry.js +8 -1
  19. package/dist/generic/baseEngineRegistry.js.map +1 -1
  20. package/dist/generic/baseEntity.d.ts +147 -3
  21. package/dist/generic/baseEntity.d.ts.map +1 -1
  22. package/dist/generic/baseEntity.js +1063 -25
  23. package/dist/generic/baseEntity.js.map +1 -1
  24. package/dist/generic/baseRemotableOperation.d.ts +15 -0
  25. package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
  26. package/dist/generic/baseRemotableOperation.js +11 -0
  27. package/dist/generic/baseRemotableOperation.js.map +1 -1
  28. package/dist/generic/compositeKey.d.ts.map +1 -1
  29. package/dist/generic/compositeKey.js +3 -1
  30. package/dist/generic/compositeKey.js.map +1 -1
  31. package/dist/generic/crossEntityPolicyEngine.d.ts +172 -0
  32. package/dist/generic/crossEntityPolicyEngine.d.ts.map +1 -0
  33. package/dist/generic/crossEntityPolicyEngine.js +667 -0
  34. package/dist/generic/crossEntityPolicyEngine.js.map +1 -0
  35. package/dist/generic/dataHooks.d.ts +14 -1
  36. package/dist/generic/dataHooks.d.ts.map +1 -1
  37. package/dist/generic/dataHooks.js.map +1 -1
  38. package/dist/generic/databaseProviderBase.d.ts +37 -0
  39. package/dist/generic/databaseProviderBase.d.ts.map +1 -1
  40. package/dist/generic/databaseProviderBase.js +220 -24
  41. package/dist/generic/databaseProviderBase.js.map +1 -1
  42. package/dist/generic/documentNumberingEngine.d.ts +190 -0
  43. package/dist/generic/documentNumberingEngine.d.ts.map +1 -0
  44. package/dist/generic/documentNumberingEngine.js +739 -0
  45. package/dist/generic/documentNumberingEngine.js.map +1 -0
  46. package/dist/generic/entityInfo.d.ts +104 -3
  47. package/dist/generic/entityInfo.d.ts.map +1 -1
  48. package/dist/generic/entityInfo.js +326 -22
  49. package/dist/generic/entityInfo.js.map +1 -1
  50. package/dist/generic/entityLifecyclePolicy.d.ts +214 -0
  51. package/dist/generic/entityLifecyclePolicy.d.ts.map +1 -0
  52. package/dist/generic/entityLifecyclePolicy.js +708 -0
  53. package/dist/generic/entityLifecyclePolicy.js.map +1 -0
  54. package/dist/generic/entitySubtypeDriver.d.ts +49 -0
  55. package/dist/generic/entitySubtypeDriver.d.ts.map +1 -0
  56. package/dist/generic/entitySubtypeDriver.js +26 -0
  57. package/dist/generic/entitySubtypeDriver.js.map +1 -0
  58. package/dist/generic/fieldSecuritySQLGate.d.ts +17 -0
  59. package/dist/generic/fieldSecuritySQLGate.d.ts.map +1 -1
  60. package/dist/generic/fieldSecuritySQLGate.js +41 -1
  61. package/dist/generic/fieldSecuritySQLGate.js.map +1 -1
  62. package/dist/generic/filters/compositeFilter.d.ts +5 -1
  63. package/dist/generic/filters/compositeFilter.d.ts.map +1 -1
  64. package/dist/generic/filters/compositeFilter.js +127 -12
  65. package/dist/generic/filters/compositeFilter.js.map +1 -1
  66. package/dist/generic/filters/compositeFilterSQL.d.ts +121 -0
  67. package/dist/generic/filters/compositeFilterSQL.d.ts.map +1 -0
  68. package/dist/generic/filters/compositeFilterSQL.js +489 -0
  69. package/dist/generic/filters/compositeFilterSQL.js.map +1 -0
  70. package/dist/generic/filters/filter.types.d.ts +5 -2
  71. package/dist/generic/filters/filter.types.d.ts.map +1 -1
  72. package/dist/generic/filters/filter.types.js +4 -1
  73. package/dist/generic/filters/filter.types.js.map +1 -1
  74. package/dist/generic/filters/filterBuilder.d.ts +75 -0
  75. package/dist/generic/filters/filterBuilder.d.ts.map +1 -0
  76. package/dist/generic/filters/filterBuilder.js +104 -0
  77. package/dist/generic/filters/filterBuilder.js.map +1 -0
  78. package/dist/generic/filters/index.d.ts +2 -0
  79. package/dist/generic/filters/index.d.ts.map +1 -1
  80. package/dist/generic/filters/index.js +2 -0
  81. package/dist/generic/filters/index.js.map +1 -1
  82. package/dist/generic/interfaces.d.ts +74 -1
  83. package/dist/generic/interfaces.d.ts.map +1 -1
  84. package/dist/generic/interfaces.js +0 -1
  85. package/dist/generic/interfaces.js.map +1 -1
  86. package/dist/generic/localCacheManager.d.ts +46 -3
  87. package/dist/generic/localCacheManager.d.ts.map +1 -1
  88. package/dist/generic/localCacheManager.js +267 -45
  89. package/dist/generic/localCacheManager.js.map +1 -1
  90. package/dist/generic/metadata.d.ts +3 -1
  91. package/dist/generic/metadata.d.ts.map +1 -1
  92. package/dist/generic/metadata.js +25 -6
  93. package/dist/generic/metadata.js.map +1 -1
  94. package/dist/generic/providerBase.d.ts +212 -33
  95. package/dist/generic/providerBase.d.ts.map +1 -1
  96. package/dist/generic/providerBase.js +543 -117
  97. package/dist/generic/providerBase.js.map +1 -1
  98. package/dist/generic/queryInfo.d.ts +5 -0
  99. package/dist/generic/queryInfo.d.ts.map +1 -1
  100. package/dist/generic/queryInfo.js +5 -0
  101. package/dist/generic/queryInfo.js.map +1 -1
  102. package/dist/generic/queryInfoInterfaces.d.ts +5 -0
  103. package/dist/generic/queryInfoInterfaces.d.ts.map +1 -1
  104. package/dist/generic/remoteOperationDispatch.d.ts.map +1 -1
  105. package/dist/generic/remoteOperationDispatch.js +13 -1
  106. package/dist/generic/remoteOperationDispatch.js.map +1 -1
  107. package/dist/generic/saveEntityGraphOperation.d.ts +6 -0
  108. package/dist/generic/saveEntityGraphOperation.d.ts.map +1 -1
  109. package/dist/generic/saveEntityGraphOperation.js +8 -0
  110. package/dist/generic/saveEntityGraphOperation.js.map +1 -1
  111. package/dist/generic/transactionGroup.d.ts +25 -0
  112. package/dist/generic/transactionGroup.d.ts.map +1 -1
  113. package/dist/generic/transactionGroup.js +105 -0
  114. package/dist/generic/transactionGroup.js.map +1 -1
  115. package/dist/generic/typedQuery.d.ts +151 -0
  116. package/dist/generic/typedQuery.d.ts.map +1 -0
  117. package/dist/generic/typedQuery.js +286 -0
  118. package/dist/generic/typedQuery.js.map +1 -0
  119. package/dist/generic/util.d.ts.map +1 -1
  120. package/dist/generic/util.js +9 -3
  121. package/dist/generic/util.js.map +1 -1
  122. package/dist/index.d.ts +6 -0
  123. package/dist/index.d.ts.map +1 -1
  124. package/dist/index.js +6 -0
  125. package/dist/index.js.map +1 -1
  126. package/dist/views/runView.d.ts +53 -0
  127. package/dist/views/runView.d.ts.map +1 -1
  128. package/dist/views/runView.js +134 -0
  129. package/dist/views/runView.js.map +1 -1
  130. package/package.json +3 -3
@@ -0,0 +1,708 @@
1
+ /**
2
+ * @fileoverview Declarative Entity Lifecycle Policy Engine — State Machines, Field-Freeze, and WriteAuthority.
3
+ *
4
+ * Centralizes entity lifecycle invariants across both client (`BaseEntity.Validate()`) and server
5
+ * (`BaseEntity._innerSave` / `_innerDelete`, `DatabaseProviderBase.Save` / `Delete`, `ResolverBase`):
6
+ *
7
+ * 1. **Declarative State Machine**: initial states on create, directed state transitions (with role gates,
8
+ * required-server-operation gates, required fields on enter, cleared fields on transition), and terminal states.
9
+ * 2. **Field-Freeze & Post-Create Immutability**: `immutableAfterCreateFields`, `editableFieldsByState`,
10
+ * `frozenFieldsByState` (keyed by stored pre-save state or `'*'`), and `fieldFreezeExemptOperations`.
11
+ * 3. **WriteAuthority (`'Standard' | 'AppendOnly' | 'ServerOperationOnly'`)**:
12
+ * - `'AppendOnly'` permits initial creation (`!entity.IsSaved`) and unconditionally refuses updates and deletes.
13
+ * - `'ServerOperationOnly'` blocks direct client CRUD (`ResolverBase`, `TransactionGroupResolver`,
14
+ * `EntityCRUDHandler`, `MJ.SaveEntityGraph`) and unscoped saves, succeeding only inside an authorized
15
+ * {@link ServerOperationScopeManager} frame (automatically established for domain `BaseRemotableOperation`
16
+ * executions where `GrantsServerWriteAuthority === true`).
17
+ *
18
+ * Policies may be authored declaratively in `EntityInfo.Settings` (`'LifecyclePolicy'`, `'StateMachinePolicy'`,
19
+ * `'WriteAuthorityPolicy'`), in `IEntityConfiguration.Lifecycle` (`MJ: Entities.Configuration`), or registered
20
+ * programmatically via {@link EntityLifecyclePolicyEngine.RegisterPolicy}.
21
+ *
22
+ * @module @memberjunction/core
23
+ */
24
+ import { BaseSingleton, SafeJSONParse, UUIDsEqual, UUIDSet, ValidationErrorInfo, ValidationErrorType, } from '@memberjunction/global';
25
+ import { DocumentNumberingEngine } from './documentNumberingEngine.js';
26
+ import { LogError } from './logging.js';
27
+ export const CLIENT_DIRECT_CRUD_BOUNDARY_KEY = '__MJ_CLIENT_DIRECT_CRUD__';
28
+ /**
29
+ * The frame {@link ServerOperationScopeManager.RunAsServerWork} enters. It names no entities and no
30
+ * policy allows its key, so it grants no write authority; it only ends the client CRUD boundary
31
+ * around it, so the work inside does not read as the client's own request.
32
+ */
33
+ export const SERVER_WORK_OPERATION_KEY = '__MJ_SERVER_WORK__';
34
+ export const DOCUMENT_SEQUENCE_SQL_STORE_OPERATION_KEY = '__MJ_INTERNAL_DOCUMENT_SEQUENCE_SQL_STORE__';
35
+ function isPromiseLike(value) {
36
+ return (value !== null &&
37
+ value !== undefined &&
38
+ (typeof value === 'object' || typeof value === 'function') &&
39
+ 'then' in value &&
40
+ typeof value.then === 'function');
41
+ }
42
+ /**
43
+ * Browser-safe default synchronous/single-chain stack tracker used when Node's `AsyncLocalStorage`
44
+ * tracker has not been installed (e.g. Angular browser runtime or lightweight MJCore unit tests).
45
+ * On Node servers, `@memberjunction/generic-database-provider` installs `NodeAsyncServerOperationScopeTracker`.
46
+ */
47
+ export class StackServerOperationScopeTracker {
48
+ constructor() {
49
+ this.IsAsyncSafe = false;
50
+ this._stack = [];
51
+ }
52
+ RunInScope(frame, fn) {
53
+ this._stack.push(frame);
54
+ let asyncPending = false;
55
+ try {
56
+ const out = fn();
57
+ if (isPromiseLike(out)) {
58
+ asyncPending = true;
59
+ const popFrame = () => {
60
+ const idx = this._stack.lastIndexOf(frame);
61
+ if (idx >= 0) {
62
+ this._stack.splice(idx, 1);
63
+ }
64
+ };
65
+ return out.then((resolved) => {
66
+ popFrame();
67
+ return resolved;
68
+ }, (err) => {
69
+ popFrame();
70
+ throw err;
71
+ });
72
+ }
73
+ return out;
74
+ }
75
+ finally {
76
+ if (!asyncPending) {
77
+ const idx = this._stack.lastIndexOf(frame);
78
+ if (idx >= 0) {
79
+ this._stack.splice(idx, 1);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ RunWithoutAuthority(fn) {
85
+ return this.RunInScope({
86
+ operationKey: CLIENT_DIRECT_CRUD_BOUNDARY_KEY,
87
+ source: 'ClientCrudBoundary',
88
+ allowedEntities: [],
89
+ }, fn);
90
+ }
91
+ GetActiveFrames() {
92
+ return [...this._stack];
93
+ }
94
+ }
95
+ /**
96
+ * Process-wide singleton managing active server operation authority frames.
97
+ * Domain `BaseRemotableOperation` executions (`GrantsServerWriteAuthority === true`) and trusted server
98
+ * engines wrap their mutations in {@link RunWithAuthority}, while client CRUD entry points (`ResolverBase`,
99
+ * `TransactionGroupResolver`, `EntityCRUDHandler`, `SaveEntityGraphOperation`) wrap theirs in
100
+ * {@link RunInClientCrudBoundary} so outer ambient authority can never leak into direct client CRUD.
101
+ */
102
+ export class ServerOperationScopeManager extends BaseSingleton {
103
+ constructor() {
104
+ super();
105
+ this._tracker = new StackServerOperationScopeTracker();
106
+ }
107
+ static get Instance() {
108
+ return super.getInstance();
109
+ }
110
+ SetTracker(tracker) {
111
+ this._tracker = tracker;
112
+ }
113
+ GetTracker() {
114
+ return this._tracker;
115
+ }
116
+ RunWithAuthority(frame, fn) {
117
+ if (!frame.operationKey || frame.operationKey === CLIENT_DIRECT_CRUD_BOUNDARY_KEY) {
118
+ throw new Error('ServerOperationScopeManager.RunWithAuthority requires a valid domain operationKey.');
119
+ }
120
+ return this._tracker.RunInScope(frame, fn);
121
+ }
122
+ /**
123
+ * Marks `fn` as executing inside a direct client-originated CRUD boundary. Any outer server-operation
124
+ * authority frame above this boundary is masked until a nested domain {@link RunWithAuthority} is entered.
125
+ */
126
+ RunInClientCrudBoundary(fn) {
127
+ return this._tracker.RunInScope({
128
+ operationKey: CLIENT_DIRECT_CRUD_BOUNDARY_KEY,
129
+ source: 'ClientCrudBoundary',
130
+ allowedEntities: [],
131
+ }, fn);
132
+ }
133
+ /**
134
+ * Executes `fn` with all outer authority frames cleared/masked (using `AsyncLocalStorage.run([], fn)`
135
+ * when `NodeAsyncServerOperationScopeTracker` is installed).
136
+ */
137
+ RunWithoutAuthority(fn) {
138
+ if (this._tracker.RunWithoutAuthority) {
139
+ return this._tracker.RunWithoutAuthority(fn);
140
+ }
141
+ return this.RunInClientCrudBoundary(fn);
142
+ }
143
+ /**
144
+ * Returns the effective active authority frames since the innermost {@link RunInClientCrudBoundary}
145
+ * (if any). Frames outside a client CRUD boundary are masked.
146
+ */
147
+ GetEffectiveAuthorityFrames() {
148
+ const all = this._tracker.GetActiveFrames();
149
+ let boundaryIdx = -1;
150
+ for (let i = all.length - 1; i >= 0; i--) {
151
+ if (all[i].operationKey === CLIENT_DIRECT_CRUD_BOUNDARY_KEY || all[i].source === 'ClientCrudBoundary') {
152
+ boundaryIdx = i;
153
+ break;
154
+ }
155
+ }
156
+ return boundaryIdx >= 0 ? all.slice(boundaryIdx + 1) : all;
157
+ }
158
+ /**
159
+ * Whether the code running now is a client's own CRUD request: inside a {@link RunInClientCrudBoundary}
160
+ * with no frame entered since, neither server authority nor {@link RunAsServerWork}. A save made here
161
+ * is the requesting user's own act; any other save is server code acting as that user.
162
+ */
163
+ IsInDirectClientCrud() {
164
+ const all = this._tracker.GetActiveFrames();
165
+ const innermost = all[all.length - 1];
166
+ return innermost?.operationKey === CLIENT_DIRECT_CRUD_BOUNDARY_KEY || innermost?.source === 'ClientCrudBoundary';
167
+ }
168
+ /**
169
+ * Runs `fn` as server work: when called inside a client's own CRUD request ({@link IsInDirectClientCrud}),
170
+ * `fn` runs under a frame that grants nothing ({@link SERVER_WORK_OPERATION_KEY}), so saves it makes,
171
+ * and work it starts and leaves running, never read as the client's own. Agent runs and the task-graph
172
+ * dispatcher's passes run this way: the async scope follows them out of the request that started them.
173
+ * Elsewhere `fn` runs as is.
174
+ */
175
+ RunAsServerWork(fn) {
176
+ if (!this.IsInDirectClientCrud()) {
177
+ return fn();
178
+ }
179
+ return this._tracker.RunInScope({ operationKey: SERVER_WORK_OPERATION_KEY, source: 'ServerEngine', allowedEntities: [] }, fn);
180
+ }
181
+ IsOperationActive(allowedOperations, entityName, actingUser) {
182
+ const frames = this.GetEffectiveAuthorityFrames();
183
+ if (frames.length === 0) {
184
+ return false;
185
+ }
186
+ const normalizedEntity = entityName?.trim().toLowerCase();
187
+ const normalizedAllowedOps = allowedOperations && allowedOperations.length > 0
188
+ ? new Set(allowedOperations.map((k) => k.trim().toLowerCase()))
189
+ : null;
190
+ const hasAllowedOps = normalizedAllowedOps !== null && normalizedAllowedOps.size > 0;
191
+ for (let i = frames.length - 1; i >= 0; i--) {
192
+ const frame = frames[i];
193
+ if (frame.userId && actingUser?.ID && !UUIDsEqual(frame.userId, actingUser.ID)) {
194
+ continue;
195
+ }
196
+ if (hasAllowedOps && !normalizedAllowedOps.has(frame.operationKey.trim().toLowerCase())) {
197
+ continue;
198
+ }
199
+ const hasFrameEntities = Boolean(frame.allowedEntities && frame.allowedEntities.length > 0);
200
+ if (!hasAllowedOps && !hasFrameEntities) {
201
+ // Fail closed when neither the policy's allowedOperations nor the frame's allowedEntities scopes the authority.
202
+ continue;
203
+ }
204
+ if (normalizedEntity && hasFrameEntities && frame.allowedEntities) {
205
+ const coversAll = frame.allowedEntities.some((e) => e.trim() === '*');
206
+ const coversEntity = frame.allowedEntities.some((e) => e.trim().toLowerCase() === normalizedEntity);
207
+ if (!coversAll && !coversEntity) {
208
+ continue;
209
+ }
210
+ }
211
+ return true;
212
+ }
213
+ return false;
214
+ }
215
+ }
216
+ /**
217
+ * Evaluates declarative and programmatic entity lifecycle policies (state machines, field-freeze rules,
218
+ * post-create immutability, and `WriteAuthority` gates).
219
+ */
220
+ export class EntityLifecyclePolicyEngine extends BaseSingleton {
221
+ static { this.LIFECYCLE_SETTING_NAME = 'LifecyclePolicy'; }
222
+ static { this.STATE_MACHINE_SETTING_NAME = 'StateMachinePolicy'; }
223
+ static { this.WRITE_AUTHORITY_SETTING_NAME = 'WriteAuthorityPolicy'; }
224
+ static { this.DOCUMENT_SEQUENCE_COUNTERS_ENTITY_NAME = 'MJ: Document Sequence Counters'; }
225
+ constructor() {
226
+ super();
227
+ this._programmaticPolicies = new Map();
228
+ this._metadataCache = new Map();
229
+ this.seedBuiltInPolicies();
230
+ }
231
+ static get Instance() {
232
+ return super.getInstance();
233
+ }
234
+ RegisterPolicy(entityName, policy) {
235
+ const key = entityName.trim().toLowerCase();
236
+ if (!key) {
237
+ throw new Error('EntityLifecyclePolicyEngine.RegisterPolicy: entityName must be non-empty.');
238
+ }
239
+ this._programmaticPolicies.set(key, policy);
240
+ }
241
+ UnregisterPolicy(entityName) {
242
+ this._programmaticPolicies.delete(entityName.trim().toLowerCase());
243
+ }
244
+ ClearProgrammaticPolicies() {
245
+ this._programmaticPolicies.clear();
246
+ this._metadataCache.clear();
247
+ this.seedBuiltInPolicies();
248
+ }
249
+ seedBuiltInPolicies() {
250
+ const counterPolicy = {
251
+ writeAuthority: {
252
+ mode: 'ServerOperationOnly',
253
+ allowedOperations: [DOCUMENT_SEQUENCE_SQL_STORE_OPERATION_KEY],
254
+ errorMessage: 'MJ: Document Sequence Counters is a system counter table and can only be mutated via DocumentNumberingEngine.',
255
+ },
256
+ };
257
+ this._programmaticPolicies.set(EntityLifecyclePolicyEngine.DOCUMENT_SEQUENCE_COUNTERS_ENTITY_NAME.toLowerCase(), counterPolicy);
258
+ this._programmaticPolicies.set('document sequence counters', counterPolicy);
259
+ }
260
+ ResolvePolicy(entityInfo) {
261
+ if (!entityInfo || !entityInfo.Name) {
262
+ return null;
263
+ }
264
+ const fromMetadata = this.resolveMetadataPolicy(entityInfo);
265
+ const programmatic = this._programmaticPolicies.get(entityInfo.Name.trim().toLowerCase()) ?? null;
266
+ if (!fromMetadata && !programmatic) {
267
+ return null;
268
+ }
269
+ if (fromMetadata && !programmatic) {
270
+ return fromMetadata;
271
+ }
272
+ if (!fromMetadata && programmatic) {
273
+ return programmatic;
274
+ }
275
+ return {
276
+ stateMachine: programmatic?.stateMachine ?? fromMetadata?.stateMachine,
277
+ writeAuthority: programmatic?.writeAuthority ?? fromMetadata?.writeAuthority,
278
+ };
279
+ }
280
+ /**
281
+ * Whether `ResolverBase.UpdateRecord` MUST load the authoritative stored row from the database
282
+ * rather than hydrating from client-supplied `OldValues___` (preventing status/frozen-field spoofing
283
+ * on entities where `TrackRecordChanges === false`).
284
+ */
285
+ RequiresStoredTruthOnUpdate(entityInfo) {
286
+ return (this.ResolvePolicy(entityInfo) !== null ||
287
+ DocumentNumberingEngine.Instance.RequiresStoredTruthOnUpdate(entityInfo));
288
+ }
289
+ /**
290
+ * Checks coarse write-authority and delete-state gates before saving or deleting `entity`.
291
+ * Returns `null` when permitted, or a human-readable refusal message when denied.
292
+ */
293
+ CheckWritePermissionGate(entity, operation, user, isServerProvider) {
294
+ const policy = this.ResolvePolicy(entity.EntityInfo);
295
+ if (!policy) {
296
+ return null;
297
+ }
298
+ const effectiveMode = this.resolveWriteAuthorityMode(policy.writeAuthority, operation);
299
+ if (effectiveMode === 'AppendOnly' && (operation === 'Update' || operation === 'Delete')) {
300
+ return (policy.writeAuthority?.errorMessage ??
301
+ `${entity.EntityInfo.Name} is append-only and cannot be ${operation === 'Update' ? 'modified' : 'deleted'} once created.`);
302
+ }
303
+ if (effectiveMode === 'ServerOperationOnly') {
304
+ if (!isServerProvider) {
305
+ return (policy.writeAuthority?.errorMessage ??
306
+ `${entity.EntityInfo.Name} cannot be ${operation.toLowerCase()}d directly; invoke the designated domain Remote Operation.`);
307
+ }
308
+ const allowed = ServerOperationScopeManager.Instance.IsOperationActive(policy.writeAuthority?.allowedOperations, entity.EntityInfo.Name, user);
309
+ if (!allowed) {
310
+ const opsHint = policy.writeAuthority?.allowedOperations && policy.writeAuthority.allowedOperations.length > 0
311
+ ? ` Allowed operations: ${policy.writeAuthority.allowedOperations.join(', ')}.`
312
+ : '';
313
+ return (policy.writeAuthority?.errorMessage ??
314
+ `${entity.EntityInfo.Name} requires an authorized server operation for ${operation}.${opsHint}`);
315
+ }
316
+ }
317
+ if (operation === 'Delete' && policy.stateMachine) {
318
+ const sm = policy.stateMachine;
319
+ const statusField = entity.GetFieldByName(sm.statusField);
320
+ if (!statusField) {
321
+ LogError(`EntityLifecyclePolicyEngine: configured statusField '${sm.statusField}' does not exist on entity '${entity.EntityInfo.Name}'.`);
322
+ return `Lifecycle policy error on ${entity.EntityInfo.Name}: configured statusField '${sm.statusField}' does not exist.`;
323
+ }
324
+ const currentStatus = this.stringifyStatusValue(statusField.Dirty ? statusField.OldValue : statusField.Value);
325
+ if (sm.terminalStates?.includes(currentStatus) &&
326
+ sm.freezeAllFieldsInTerminalStates !== false &&
327
+ !sm.deletableInStates?.includes(currentStatus)) {
328
+ return `Cannot delete ${entity.EntityInfo.Name} while ${sm.statusField} is in terminal state '${currentStatus}'.`;
329
+ }
330
+ if (sm.nonDeletableStates?.includes(currentStatus)) {
331
+ return `Cannot delete ${entity.EntityInfo.Name} while ${sm.statusField} is '${currentStatus}'.`;
332
+ }
333
+ if (sm.deletableInStates && sm.deletableInStates.length > 0 && !sm.deletableInStates.includes(currentStatus)) {
334
+ return (`Cannot delete ${entity.EntityInfo.Name} while ${sm.statusField} is '${currentStatus}'. ` +
335
+ `Deletable states: ${sm.deletableInStates.join(', ')}.`);
336
+ }
337
+ }
338
+ return null;
339
+ }
340
+ /**
341
+ * Evaluates synchronous lifecycle invariants (append-only update guard, initial state on create,
342
+ * state transitions, role/operation transition gates, post-create field immutability, and per-state
343
+ * field-freeze rules) and appends any violations to `result`.
344
+ */
345
+ ValidateLifecycleOnEntity(entity, user, result) {
346
+ const policy = this.ResolvePolicy(entity.EntityInfo);
347
+ if (!policy) {
348
+ return;
349
+ }
350
+ if (entity.IsSaved) {
351
+ const updateMode = this.resolveWriteAuthorityMode(policy.writeAuthority, 'Update');
352
+ if (updateMode === 'AppendOnly' && entity.Dirty) {
353
+ this.failValidation(result, entity.EntityInfo.Name, policy.writeAuthority?.errorMessage ??
354
+ `${entity.EntityInfo.Name} is append-only and cannot be modified once created.`, null);
355
+ return;
356
+ }
357
+ }
358
+ const sm = policy.stateMachine;
359
+ if (!sm) {
360
+ return;
361
+ }
362
+ const statusField = entity.GetFieldByName(sm.statusField);
363
+ if (!statusField) {
364
+ LogError(`EntityLifecyclePolicyEngine: configured statusField '${sm.statusField}' does not exist on entity '${entity.EntityInfo.Name}'.`);
365
+ this.failValidation(result, sm.statusField, `Lifecycle policy error on ${entity.EntityInfo.Name}: configured statusField '${sm.statusField}' does not exist.`, null);
366
+ return;
367
+ }
368
+ if (!entity.IsSaved) {
369
+ if (sm.initialStates && sm.initialStates.length > 0) {
370
+ const initialVal = this.stringifyStatusValue(statusField.Value);
371
+ if (!sm.initialStates.includes(initialVal)) {
372
+ this.failValidation(result, sm.statusField, `New ${entity.EntityInfo.Name} records must start with ${sm.statusField} in [${sm.initialStates.join(', ')}] (received '${initialVal || '(empty)'}').`, initialVal);
373
+ }
374
+ }
375
+ return;
376
+ }
377
+ // Saved record (Update): evaluate transition from stored (OldValue) status to pending (Value) status.
378
+ const priorStatus = this.stringifyStatusValue(statusField.Dirty ? statusField.OldValue : statusField.Value);
379
+ const nextStatus = this.stringifyStatusValue(statusField.Value);
380
+ const isStatusTransition = statusField.Dirty && priorStatus !== nextStatus;
381
+ let matchedTransitionRule = null;
382
+ if (isStatusTransition) {
383
+ matchedTransitionRule = this.validateStateTransition(entity, sm, priorStatus, nextStatus, user, result);
384
+ }
385
+ // Post-create immutable fields cannot change on any saved record.
386
+ if (sm.immutableAfterCreateFields && sm.immutableAfterCreateFields.length > 0) {
387
+ for (const fieldName of sm.immutableAfterCreateFields) {
388
+ const field = entity.GetFieldByName(fieldName);
389
+ if (field && field.Dirty && !this.valuesEqual(field.OldValue, field.Value)) {
390
+ this.failValidation(result, field.Name, `Field '${field.Name}' on ${entity.EntityInfo.Name} cannot be modified after creation.`, this.toDiagnosticScalar(field.Value));
391
+ }
392
+ }
393
+ }
394
+ // Per-state field-freeze rules evaluated against the stored pre-save state (`priorStatus`).
395
+ const freezeExempt = sm.fieldFreezeExemptOperations &&
396
+ sm.fieldFreezeExemptOperations.length > 0 &&
397
+ ServerOperationScopeManager.Instance.IsOperationActive(sm.fieldFreezeExemptOperations, entity.EntityInfo.Name, user);
398
+ if (!freezeExempt) {
399
+ this.validateFieldFreezeForState(entity, sm, priorStatus, result, matchedTransitionRule);
400
+ }
401
+ }
402
+ validateStateTransition(entity, sm, priorStatus, nextStatus, user, result) {
403
+ if (sm.terminalStates?.includes(priorStatus)) {
404
+ this.failValidation(result, sm.statusField, `Cannot transition ${entity.EntityInfo.Name}.${sm.statusField} out of terminal state '${priorStatus}' to '${nextStatus}'.`, nextStatus);
405
+ return null;
406
+ }
407
+ const matchingRules = sm.transitions.filter((edge) => (edge.from === priorStatus || edge.from === '*') && edge.to === nextStatus);
408
+ if (matchingRules.length === 0) {
409
+ const validTargets = Array.from(new Set(sm.transitions
410
+ .filter((edge) => edge.from === priorStatus || edge.from === '*')
411
+ .map((edge) => edge.to)));
412
+ const targetHint = validTargets.length > 0
413
+ ? ` Valid transitions from '${priorStatus}': [${validTargets.join(', ')}].`
414
+ : ` No transitions are configured from '${priorStatus}'.`;
415
+ this.failValidation(result, sm.statusField, `Invalid state transition on ${entity.EntityInfo.Name}.${sm.statusField}: '${priorStatus}' -> '${nextStatus}'.${targetHint}`, nextStatus);
416
+ return null;
417
+ }
418
+ // Prefer an exact `from === priorStatus` rule over wildcard `from === '*'` if both exist,
419
+ // and succeed if at least one matching edge satisfies all role/operation/field guards.
420
+ const exactRules = matchingRules.filter((r) => r.from === priorStatus);
421
+ const candidates = exactRules.length > 0 ? exactRules : matchingRules;
422
+ let firstFailureMessage = null;
423
+ let firstFailureField = sm.statusField;
424
+ for (const rule of candidates) {
425
+ const ruleFailure = this.evaluateTransitionRuleGuards(entity, sm, rule, user);
426
+ if (!ruleFailure) {
427
+ return rule; // This edge satisfied every guard!
428
+ }
429
+ if (firstFailureMessage === null) {
430
+ firstFailureMessage = ruleFailure.message;
431
+ firstFailureField = ruleFailure.field;
432
+ }
433
+ }
434
+ if (firstFailureMessage !== null) {
435
+ this.failValidation(result, firstFailureField, firstFailureMessage, nextStatus);
436
+ }
437
+ return null;
438
+ }
439
+ evaluateTransitionRuleGuards(entity, sm, rule, user) {
440
+ if (rule.allowedRoles && rule.allowedRoles.length > 0) {
441
+ if (!this.userHasAnyRole(user, rule.allowedRoles)) {
442
+ return {
443
+ field: sm.statusField,
444
+ message: rule.errorMessage ??
445
+ `Transition '${rule.from}' -> '${rule.to}' on ${entity.EntityInfo.Name}.${sm.statusField} requires one of roles: [${rule.allowedRoles.join(', ')}].`,
446
+ };
447
+ }
448
+ }
449
+ if (rule.requireServerOperation || (rule.allowedOperations && rule.allowedOperations.length > 0)) {
450
+ const opAllowed = ServerOperationScopeManager.Instance.IsOperationActive(rule.allowedOperations, entity.EntityInfo.Name, user);
451
+ if (!opAllowed) {
452
+ return {
453
+ field: sm.statusField,
454
+ message: rule.errorMessage ??
455
+ `Transition '${rule.from}' -> '${rule.to}' on ${entity.EntityInfo.Name}.${sm.statusField} requires an authorized server operation.`,
456
+ };
457
+ }
458
+ }
459
+ if (rule.requiredFieldsOnEnter && rule.requiredFieldsOnEnter.length > 0) {
460
+ for (const reqFieldName of rule.requiredFieldsOnEnter) {
461
+ const reqField = entity.GetFieldByName(reqFieldName);
462
+ const val = reqField?.Value;
463
+ if (val === null || val === undefined || (typeof val === 'string' && val.trim().length === 0)) {
464
+ return {
465
+ field: reqFieldName,
466
+ message: rule.errorMessage ??
467
+ `Field '${reqFieldName}' is required when transitioning ${entity.EntityInfo.Name}.${sm.statusField} to '${rule.to}'.`,
468
+ };
469
+ }
470
+ }
471
+ }
472
+ if (rule.clearedFieldsOnTransition && rule.clearedFieldsOnTransition.length > 0) {
473
+ for (const clearFieldName of rule.clearedFieldsOnTransition) {
474
+ const clearField = entity.GetFieldByName(clearFieldName);
475
+ const val = clearField?.Value;
476
+ if (val !== null && val !== undefined && !(typeof val === 'string' && val.trim().length === 0)) {
477
+ return {
478
+ field: clearFieldName,
479
+ message: rule.errorMessage ??
480
+ `Field '${clearFieldName}' must be cleared when transitioning ${entity.EntityInfo.Name}.${sm.statusField} to '${rule.to}'.`,
481
+ };
482
+ }
483
+ }
484
+ }
485
+ return null;
486
+ }
487
+ validateFieldFreezeForState(entity, sm, priorStatus, result, matchedTransitionRule = null) {
488
+ const statusKeyLower = sm.statusField.trim().toLowerCase();
489
+ const transitionExemptFields = new Set([statusKeyLower]);
490
+ if (matchedTransitionRule) {
491
+ for (const req of matchedTransitionRule.requiredFieldsOnEnter ?? []) {
492
+ transitionExemptFields.add(req.trim().toLowerCase());
493
+ }
494
+ for (const clr of matchedTransitionRule.clearedFieldsOnTransition ?? []) {
495
+ transitionExemptFields.add(clr.trim().toLowerCase());
496
+ }
497
+ }
498
+ if (sm.terminalStates?.includes(priorStatus) && sm.freezeAllFieldsInTerminalStates !== false) {
499
+ for (const field of entity.Fields) {
500
+ if (this.isUserMutatedDataField(field) &&
501
+ !transitionExemptFields.has(field.Name.trim().toLowerCase())) {
502
+ this.failValidation(result, field.Name, `Field '${field.Name}' on ${entity.EntityInfo.Name} is frozen because ${sm.statusField} is in terminal state '${priorStatus}'.`, this.toDiagnosticScalar(field.Value));
503
+ }
504
+ }
505
+ return;
506
+ }
507
+ const editableList = sm.editableFieldsByState?.[priorStatus];
508
+ if (editableList) {
509
+ const allowedSet = new Set(editableList.map((f) => f.trim().toLowerCase()));
510
+ for (const exempt of transitionExemptFields) {
511
+ allowedSet.add(exempt);
512
+ }
513
+ for (const field of entity.Fields) {
514
+ if (!this.isUserMutatedDataField(field)) {
515
+ continue;
516
+ }
517
+ if (!allowedSet.has(field.Name.trim().toLowerCase())) {
518
+ this.failValidation(result, field.Name, `Field '${field.Name}' on ${entity.EntityInfo.Name} cannot be modified while ${sm.statusField} is '${priorStatus}'.`, this.toDiagnosticScalar(field.Value));
519
+ }
520
+ }
521
+ }
522
+ const globalFrozen = sm.frozenFieldsByState?.['*'] ?? [];
523
+ const stateFrozen = sm.frozenFieldsByState?.[priorStatus] ?? [];
524
+ if (globalFrozen.length > 0 || stateFrozen.length > 0) {
525
+ const frozenSet = new Set([...globalFrozen, ...stateFrozen].map((f) => f.trim().toLowerCase()));
526
+ for (const exempt of transitionExemptFields) {
527
+ frozenSet.delete(exempt);
528
+ }
529
+ for (const field of entity.Fields) {
530
+ if (!this.isUserMutatedDataField(field)) {
531
+ continue;
532
+ }
533
+ if (frozenSet.has(field.Name.trim().toLowerCase())) {
534
+ this.failValidation(result, field.Name, `Field '${field.Name}' on ${entity.EntityInfo.Name} is frozen while ${sm.statusField} is '${priorStatus}'.`, this.toDiagnosticScalar(field.Value));
535
+ }
536
+ }
537
+ }
538
+ }
539
+ isUserMutatedDataField(field) {
540
+ if (!field.Dirty) {
541
+ return false;
542
+ }
543
+ const info = field.EntityFieldInfo;
544
+ if (info.IsVirtual || info.IsPrimaryKey || info.IsSpecialDateField) {
545
+ return false;
546
+ }
547
+ return !this.valuesEqual(field.OldValue, field.Value);
548
+ }
549
+ resolveWriteAuthorityMode(writeAuthority, operation) {
550
+ if (!writeAuthority) {
551
+ return 'Standard';
552
+ }
553
+ return writeAuthority.perOperationMode?.[operation] ?? writeAuthority.mode ?? 'Standard';
554
+ }
555
+ resolveMetadataPolicy(entityInfo) {
556
+ const settings = entityInfo.Settings ?? [];
557
+ const lifecycleSetting = settings.find((s) => s.Name?.trim().toLowerCase() === EntityLifecyclePolicyEngine.LIFECYCLE_SETTING_NAME.toLowerCase());
558
+ const smSetting = settings.find((s) => s.Name?.trim().toLowerCase() === EntityLifecyclePolicyEngine.STATE_MACHINE_SETTING_NAME.toLowerCase());
559
+ const waSetting = settings.find((s) => s.Name?.trim().toLowerCase() === EntityLifecyclePolicyEngine.WRITE_AUTHORITY_SETTING_NAME.toLowerCase());
560
+ const configLifecycle = entityInfo.ConfigurationObject?.Lifecycle;
561
+ const signature = `${lifecycleSetting?.Value ?? ''}|${smSetting?.Value ?? ''}|${waSetting?.Value ?? ''}|${configLifecycle ? JSON.stringify(configLifecycle) : ''}`;
562
+ if (signature === '|||') {
563
+ return null;
564
+ }
565
+ const cacheKey = entityInfo.ID || entityInfo.Name;
566
+ const cached = this._metadataCache.get(cacheKey);
567
+ if (cached && cached.signature === signature) {
568
+ return cached.policy;
569
+ }
570
+ let parseFailed = false;
571
+ const parseSettingJson = (settingName, rawVal) => {
572
+ if (!rawVal || rawVal.trim().length === 0) {
573
+ return null;
574
+ }
575
+ const parsed = SafeJSONParse(rawVal, false);
576
+ if (!parsed || typeof parsed !== 'object') {
577
+ LogError(`EntityLifecyclePolicyEngine: invalid JSON in EntitySetting '${settingName}' on entity '${entityInfo.Name}'; failing closed.`);
578
+ parseFailed = true;
579
+ return null;
580
+ }
581
+ return parsed;
582
+ };
583
+ const rawUnified = parseSettingJson(EntityLifecyclePolicyEngine.LIFECYCLE_SETTING_NAME, lifecycleSetting?.Value);
584
+ const rawSm = parseSettingJson(EntityLifecyclePolicyEngine.STATE_MACHINE_SETTING_NAME, smSetting?.Value);
585
+ const rawWa = parseSettingJson(EntityLifecyclePolicyEngine.WRITE_AUTHORITY_SETTING_NAME, waSetting?.Value);
586
+ if (parseFailed) {
587
+ const failClosedPolicy = {
588
+ writeAuthority: {
589
+ mode: 'ServerOperationOnly',
590
+ allowedOperations: ['__MJ_MALFORMED_METADATA_LIFECYCLE_POLICY__'],
591
+ errorMessage: `Lifecycle policy metadata JSON on ${entityInfo.Name} is malformed; writes are blocked until repaired.`,
592
+ },
593
+ };
594
+ this._metadataCache.set(cacheKey, { signature, policy: failClosedPolicy });
595
+ return failClosedPolicy;
596
+ }
597
+ const rawConfigLifecycle = configLifecycle;
598
+ const unifiedSmObj = (rawUnified?.stateMachine ?? rawUnified?.StateMachine);
599
+ const unifiedWaObj = (rawUnified?.writeAuthority ?? rawUnified?.WriteAuthority);
600
+ const configSmObj = (rawConfigLifecycle?.stateMachine ?? rawConfigLifecycle?.StateMachine);
601
+ const configWaObj = (rawConfigLifecycle?.writeAuthority ?? rawConfigLifecycle?.WriteAuthority);
602
+ const stateMachineSource = rawSm ?? unifiedSmObj ?? configSmObj;
603
+ const writeAuthoritySource = rawWa ?? unifiedWaObj ?? configWaObj;
604
+ const stateMachine = stateMachineSource ? this.normalizeStateMachinePolicy(stateMachineSource) : undefined;
605
+ const writeAuthority = writeAuthoritySource ? this.normalizeWriteAuthorityPolicy(writeAuthoritySource) : undefined;
606
+ const policy = stateMachine || writeAuthority
607
+ ? {
608
+ ...(stateMachine ? { stateMachine } : {}),
609
+ ...(writeAuthority ? { writeAuthority } : {}),
610
+ }
611
+ : null;
612
+ this._metadataCache.set(cacheKey, { signature, policy });
613
+ return policy;
614
+ }
615
+ normalizeStateMachinePolicy(raw) {
616
+ const rawTransitions = (raw.transitions ?? raw.Transitions);
617
+ const transitions = Array.isArray(rawTransitions)
618
+ ? rawTransitions.map((t) => ({
619
+ from: String(t.from ?? t.From ?? ''),
620
+ to: String(t.to ?? t.To ?? ''),
621
+ allowedRoles: (t.allowedRoles ?? t.AllowedRoles),
622
+ requireServerOperation: (t.requireServerOperation ?? t.RequireServerOperation),
623
+ allowedOperations: (t.allowedOperations ?? t.AllowedOperations),
624
+ requiredFieldsOnEnter: (t.requiredFieldsOnEnter ?? t.RequiredFieldsOnEnter),
625
+ clearedFieldsOnTransition: (t.clearedFieldsOnTransition ?? t.ClearedFieldsOnTransition),
626
+ errorMessage: (t.errorMessage ?? t.ErrorMessage),
627
+ }))
628
+ : [];
629
+ return {
630
+ statusField: String(raw.statusField ?? raw.StatusField ?? ''),
631
+ initialStates: (raw.initialStates ?? raw.InitialStates),
632
+ transitions,
633
+ terminalStates: (raw.terminalStates ?? raw.TerminalStates),
634
+ freezeAllFieldsInTerminalStates: (raw.freezeAllFieldsInTerminalStates ??
635
+ raw.FreezeAllFieldsInTerminalStates),
636
+ immutableAfterCreateFields: (raw.immutableAfterCreateFields ??
637
+ raw.ImmutableAfterCreateFields),
638
+ editableFieldsByState: (raw.editableFieldsByState ?? raw.EditableFieldsByState),
639
+ frozenFieldsByState: (raw.frozenFieldsByState ?? raw.FrozenFieldsByState),
640
+ deletableInStates: (raw.deletableInStates ?? raw.DeletableInStates),
641
+ nonDeletableStates: (raw.nonDeletableStates ?? raw.NonDeletableStates),
642
+ fieldFreezeExemptOperations: (raw.fieldFreezeExemptOperations ??
643
+ raw.FieldFreezeExemptOperations),
644
+ };
645
+ }
646
+ normalizeWriteAuthorityPolicy(raw) {
647
+ return {
648
+ mode: (raw.mode ?? raw.Mode) ?? 'Standard',
649
+ perOperationMode: (raw.perOperationMode ?? raw.PerOperationMode),
650
+ allowedOperations: (raw.allowedOperations ?? raw.AllowedOperations),
651
+ errorMessage: (raw.errorMessage ?? raw.ErrorMessage),
652
+ };
653
+ }
654
+ userHasAnyRole(user, allowedRoles) {
655
+ if (!user || !user.UserRoles || user.UserRoles.length === 0) {
656
+ return false;
657
+ }
658
+ const roleIdSet = new UUIDSet();
659
+ const roleNameSet = new Set();
660
+ for (const ur of user.UserRoles) {
661
+ if (typeof ur.Role === 'string') {
662
+ roleNameSet.add(ur.Role.trim().toLowerCase());
663
+ }
664
+ if (typeof ur.RoleID === 'string' && ur.RoleID.trim().length > 0) {
665
+ roleIdSet.Add(ur.RoleID);
666
+ }
667
+ }
668
+ for (const allowed of allowedRoles) {
669
+ const wanted = allowed.trim();
670
+ if (roleNameSet.has(wanted.toLowerCase()) || roleIdSet.Has(wanted)) {
671
+ return true;
672
+ }
673
+ }
674
+ return false;
675
+ }
676
+ stringifyStatusValue(value) {
677
+ if (value === null || value === undefined) {
678
+ return '';
679
+ }
680
+ return String(value).trim();
681
+ }
682
+ valuesEqual(left, right) {
683
+ if (left === right) {
684
+ return true;
685
+ }
686
+ if (left instanceof Date && right instanceof Date) {
687
+ return left.getTime() === right.getTime();
688
+ }
689
+ return false;
690
+ }
691
+ toDiagnosticScalar(value) {
692
+ if (value === null || value === undefined) {
693
+ return null;
694
+ }
695
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
696
+ return value;
697
+ }
698
+ if (value instanceof Date) {
699
+ return isNaN(value.getTime()) ? null : value.toISOString();
700
+ }
701
+ return String(value);
702
+ }
703
+ failValidation(result, fieldName, message, value) {
704
+ result.Success = false;
705
+ result.Errors.push(new ValidationErrorInfo(fieldName, message, value, ValidationErrorType.Failure));
706
+ }
707
+ }
708
+ //# sourceMappingURL=entityLifecyclePolicy.js.map