@memberjunction/core-entities 6.3.0-edge.1 → 6.3.0-edge.2

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 (113) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/custom/ArtifactPermissionDelegate.d.ts +27 -6
  3. package/dist/custom/ArtifactPermissionDelegate.d.ts.map +1 -1
  4. package/dist/custom/ArtifactPermissionDelegate.js +845 -298
  5. package/dist/custom/ArtifactPermissionDelegate.js.map +1 -1
  6. package/dist/custom/ConversationWriteAccess.d.ts +9 -0
  7. package/dist/custom/ConversationWriteAccess.d.ts.map +1 -1
  8. package/dist/custom/ConversationWriteAccess.js +56 -1
  9. package/dist/custom/ConversationWriteAccess.js.map +1 -1
  10. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts +9 -0
  11. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts.map +1 -1
  12. package/dist/custom/Permissions/BaseShareEntityExtended.js +11 -0
  13. package/dist/custom/Permissions/BaseShareEntityExtended.js.map +1 -1
  14. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts.map +1 -1
  15. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js +15 -3
  16. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js.map +1 -1
  17. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts +1 -0
  18. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts.map +1 -1
  19. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js +45 -13
  20. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js.map +1 -1
  21. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.d.ts +3 -1
  22. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.d.ts.map +1 -1
  23. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.js +83 -19
  24. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.js.map +1 -1
  25. package/dist/custom/Permissions/shareNotification.d.ts +14 -1
  26. package/dist/custom/Permissions/shareNotification.d.ts.map +1 -1
  27. package/dist/custom/Permissions/shareNotification.js +62 -8
  28. package/dist/custom/Permissions/shareNotification.js.map +1 -1
  29. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.d.ts.map +1 -1
  30. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js +120 -38
  31. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js.map +1 -1
  32. package/dist/custom/SlideDeckEngine.d.ts +45 -3
  33. package/dist/custom/SlideDeckEngine.d.ts.map +1 -1
  34. package/dist/custom/SlideDeckEngine.js +509 -10
  35. package/dist/custom/SlideDeckEngine.js.map +1 -1
  36. package/dist/custom/SlideDeckPptxEngine.d.ts.map +1 -1
  37. package/dist/custom/SlideDeckPptxEngine.js +91 -17
  38. package/dist/custom/SlideDeckPptxEngine.js.map +1 -1
  39. package/dist/custom/SpreadsheetEngine.d.ts +7 -0
  40. package/dist/custom/SpreadsheetEngine.d.ts.map +1 -1
  41. package/dist/custom/SpreadsheetEngine.js +72 -0
  42. package/dist/custom/SpreadsheetEngine.js.map +1 -1
  43. package/dist/custom/approvals.d.ts +24 -0
  44. package/dist/custom/approvals.d.ts.map +1 -1
  45. package/dist/custom/approvals.js +34 -1
  46. package/dist/custom/approvals.js.map +1 -1
  47. package/dist/engines/CanonGraphEngine.d.ts +114 -1
  48. package/dist/engines/CanonGraphEngine.d.ts.map +1 -1
  49. package/dist/engines/CanonGraphEngine.js +240 -20
  50. package/dist/engines/CanonGraphEngine.js.map +1 -1
  51. package/dist/engines/conversations.d.ts +20 -4
  52. package/dist/engines/conversations.d.ts.map +1 -1
  53. package/dist/engines/conversations.js +61 -12
  54. package/dist/engines/conversations.js.map +1 -1
  55. package/dist/generated/entities/__mj.d.ts +6973 -399
  56. package/dist/generated/entities/__mj.d.ts.map +1 -1
  57. package/dist/generated/entities/__mj.js +35452 -27348
  58. package/dist/generated/entities/__mj.js.map +1 -1
  59. package/dist/generated/remote_operations.d.ts +745 -65
  60. package/dist/generated/remote_operations.d.ts.map +1 -1
  61. package/dist/generated/remote_operations.js +248 -8
  62. package/dist/generated/remote_operations.js.map +1 -1
  63. package/dist/generated/schemas/__mj.d.ts +2156 -230
  64. package/dist/generated/schemas/__mj.d.ts.map +1 -1
  65. package/dist/generated/schemas/__mj.js +3385 -26
  66. package/dist/generated/schemas/__mj.js.map +1 -1
  67. package/dist/graph/BaseGraphEdgeProvider.d.ts +33 -1
  68. package/dist/graph/BaseGraphEdgeProvider.d.ts.map +1 -1
  69. package/dist/graph/BaseGraphEdgeProvider.js +18 -3
  70. package/dist/graph/BaseGraphEdgeProvider.js.map +1 -1
  71. package/dist/graph/CanonDocumentRenderer.d.ts +43 -0
  72. package/dist/graph/CanonDocumentRenderer.d.ts.map +1 -0
  73. package/dist/graph/CanonDocumentRenderer.js +627 -0
  74. package/dist/graph/CanonDocumentRenderer.js.map +1 -0
  75. package/dist/graph/DomainClustering.d.ts +88 -0
  76. package/dist/graph/DomainClustering.d.ts.map +1 -0
  77. package/dist/graph/DomainClustering.js +327 -0
  78. package/dist/graph/DomainClustering.js.map +1 -0
  79. package/dist/graph/DomainProposalWriter.d.ts +25 -0
  80. package/dist/graph/DomainProposalWriter.d.ts.map +1 -0
  81. package/dist/graph/DomainProposalWriter.js +107 -0
  82. package/dist/graph/DomainProposalWriter.js.map +1 -0
  83. package/dist/graph/GraphAccessPolicy.d.ts +111 -0
  84. package/dist/graph/GraphAccessPolicy.d.ts.map +1 -0
  85. package/dist/graph/GraphAccessPolicy.js +123 -0
  86. package/dist/graph/GraphAccessPolicy.js.map +1 -0
  87. package/dist/graph/GraphEngine.d.ts +99 -10
  88. package/dist/graph/GraphEngine.d.ts.map +1 -1
  89. package/dist/graph/GraphEngine.js +359 -53
  90. package/dist/graph/GraphEngine.js.map +1 -1
  91. package/dist/graph/RecordRelations.d.ts +52 -0
  92. package/dist/graph/RecordRelations.d.ts.map +1 -0
  93. package/dist/graph/RecordRelations.js +90 -0
  94. package/dist/graph/RecordRelations.js.map +1 -0
  95. package/dist/graph/index.d.ts +9 -1
  96. package/dist/graph/index.d.ts.map +1 -1
  97. package/dist/graph/index.js +13 -1
  98. package/dist/graph/index.js.map +1 -1
  99. package/dist/graph/policies/ProvenanceAccessPolicies.d.ts +56 -0
  100. package/dist/graph/policies/ProvenanceAccessPolicies.d.ts.map +1 -0
  101. package/dist/graph/policies/ProvenanceAccessPolicies.js +228 -0
  102. package/dist/graph/policies/ProvenanceAccessPolicies.js.map +1 -0
  103. package/dist/graph/providers/QueryEdgeProvider.d.ts.map +1 -1
  104. package/dist/graph/providers/QueryEdgeProvider.js +2 -2
  105. package/dist/graph/providers/QueryEdgeProvider.js.map +1 -1
  106. package/dist/graph/providers/RecordLinkEdgeProvider.d.ts.map +1 -1
  107. package/dist/graph/providers/RecordLinkEdgeProvider.js +2 -2
  108. package/dist/graph/providers/RecordLinkEdgeProvider.js.map +1 -1
  109. package/dist/graph/providers/SharedConceptEdgeProvider.d.ts +54 -0
  110. package/dist/graph/providers/SharedConceptEdgeProvider.d.ts.map +1 -0
  111. package/dist/graph/providers/SharedConceptEdgeProvider.js +282 -0
  112. package/dist/graph/providers/SharedConceptEdgeProvider.js.map +1 -0
  113. package/package.json +6 -6
@@ -5,7 +5,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
7
  import { LogError, Metadata, RunView, WellKnownUserSource } from '@memberjunction/core';
8
- import { BaseSingleton, EscapeSQLString, GetGlobalObjectStore, IsValidUUID, MJGlobal, NormalizeUUID, RegisterClass, UUIDsEqual } from '@memberjunction/global';
8
+ import { BaseSingleton, EscapeSQLString, GetGlobalObjectStore, IndexByUUID, IsValidUUID, MJGlobal, NormalizeUUID, RegisterClass, UUIDsEqual } from '@memberjunction/global';
9
9
  /**
10
10
  * Base class for `@RegisterClass(BaseArtifactPermissionDelegate, '<EntityName>')` registrations.
11
11
  * Subclasses override {@link CanRead}, {@link CanEdit}, {@link CanDelete}, and/or {@link CanShare}.
@@ -34,6 +34,19 @@ function chunkArray(items, size) {
34
34
  function buildQuotedInList(ids) {
35
35
  return ids.map((id) => `'${EscapeSQLString(id)}'`).join(',');
36
36
  }
37
+ function buildEqOrInFilter(column, ids) {
38
+ return ids.length === 1
39
+ ? `${column}='${EscapeSQLString(ids[0])}'`
40
+ : `${column} IN (${buildQuotedInList(ids)})`;
41
+ }
42
+ function canUseRunViews(provider, rv) {
43
+ if (typeof rv.RunViews !== 'function') {
44
+ return false;
45
+ }
46
+ const providerHasRunViews = typeof provider.RunViews === 'function';
47
+ const rvHasOwnRunViews = Object.prototype.hasOwnProperty.call(rv, 'RunViews');
48
+ return providerHasRunViews || rvHasOwnRunViews;
49
+ }
37
50
  const INTERNAL_PERMISSION_QUERY_PARAMS_STORE_KEY = '___MJ_INTERNAL_ARTIFACT_PERMISSION_QUERY_PARAMS___';
38
51
  const INTERNAL_PERMISSION_QUERY_SYMBOL_STORE_KEY = '___MJ_INTERNAL_ARTIFACT_PERMISSION_QUERY_SYMBOL___';
39
52
  const FALLBACK_INTERNAL_PERMISSION_QUERY_WEAK_SET = new WeakSet();
@@ -252,63 +265,365 @@ export class ArtifactPermissionEngine extends BaseSingleton {
252
265
  }
253
266
  /**
254
267
  * Resolves the full permission set (`CanRead`, `CanEdit`, `CanDelete`, `CanShare`) for `(artifactId, user)`.
268
+ * Delegates to {@link ResolvePermissionsBatch} so single-artifact and batched resolution share
269
+ * one implementation and cannot drift apart.
255
270
  */
256
271
  async ResolvePermissions(provider, artifactId, user, depth = 0, visitedArtifactIds, memo, strictThrowOnQueryError = false) {
257
- return this.resolvePermissionsCore(provider, artifactId, user, depth, visitedArtifactIds, memo, strictThrowOnQueryError);
258
- }
259
- async resolvePermissionsCore(provider, artifactId, user, depth, visitedArtifactIds, memo, strictThrowOnQueryError) {
260
272
  const normalizedArtifactId = (artifactId ?? '').trim();
261
- if (!normalizedArtifactId || !user) {
262
- return this.buildDenied(normalizedArtifactId, 'Artifact ID and authenticated user context are required.');
273
+ const batch = await this.ResolvePermissionsBatch(provider, [normalizedArtifactId], user, depth, visitedArtifactIds, memo, strictThrowOnQueryError);
274
+ return (batch.get(normalizedArtifactId) ??
275
+ this.buildDenied(normalizedArtifactId, 'Artifact permission resolution failed.'));
276
+ }
277
+ /**
278
+ * Resolves permissions for many artifacts in a staged batched pass instead of per-artifact queries:
279
+ * - Loads only `MJ: Artifacts` headers first (`ID IN (...)`, `BypassCache: true`) so owned, missing,
280
+ * unregistered-delegate, and parent-delegated artifacts settle without extra permission/version queries.
281
+ * - Loads `MJ: Artifact Permissions` (`ArtifactID IN (...)`) and `MJ: Artifact Versions` (`ArtifactID IN (...)`)
282
+ * only for non-owned artifacts that still require fallback evaluation (in 1 `RunViews` call on Network
283
+ * providers, or `user` + `systemUser` in parallel on Database providers).
284
+ * - Walks `MJ: Collection Artifacts` -> `MJ: Collections` ancestry level-by-level (one batched query per
285
+ * depth level across all artifacts) and loads `MJ: Collection Permissions` once.
286
+ * - Evaluates custom delegates (deferring fallback loading to a single batch only for non-owner defers)
287
+ * and `ParentArtifactPermissionDelegate` chains with exact accumulated `Depth` and `VisitedArtifactIDs`.
288
+ *
289
+ * Returns a `Map` keyed by each input ID in `artifactIds`.
290
+ */
291
+ async ResolvePermissionsBatch(provider, artifactIds, user, depth = 0, visitedArtifactIds, memo, strictThrowOnQueryError = false) {
292
+ const results = new Map();
293
+ if (!artifactIds || artifactIds.length === 0) {
294
+ return results;
295
+ }
296
+ const fillAllDenied = (reason) => {
297
+ for (const rawId of artifactIds) {
298
+ results.set(rawId, this.buildDenied((rawId ?? '').trim(), reason));
299
+ }
300
+ return results;
301
+ };
302
+ if (!user) {
303
+ return fillAllDenied('Artifact ID and authenticated user context are required.');
263
304
  }
264
305
  if (user.IsMagicLinkAnonymous || user.MagicLinkScope) {
265
- return this.buildDenied(normalizedArtifactId, 'Scope-limited or anonymous magic-link principals cannot access governed artifact permissions.');
306
+ return fillAllDenied('Scope-limited or anonymous magic-link principals cannot access governed artifact permissions.');
266
307
  }
267
- if (!IsValidUUID(normalizedArtifactId) || !IsValidUUID(user.ID)) {
268
- return this.buildDenied(normalizedArtifactId, 'Artifact ID and user ID must be valid UUIDs.');
308
+ if (!IsValidUUID(user.ID)) {
309
+ return fillAllDenied('Artifact ID and user ID must be valid UUIDs.');
269
310
  }
270
311
  if (depth > MAX_DELEGATE_DEPTH) {
271
- return this.buildDenied(normalizedArtifactId, 'Maximum artifact permission delegation depth exceeded.');
272
- }
273
- const visited = new Set(visitedArtifactIds ?? []);
274
- const normArtifactId = NormalizeUUID(normalizedArtifactId);
275
- if (visited.has(normArtifactId)) {
276
- return this.buildDenied(normalizedArtifactId, 'Circular artifact permission delegation detected.');
312
+ return fillAllDenied('Maximum artifact permission delegation depth exceeded.');
277
313
  }
278
- visited.add(normArtifactId);
279
314
  const activeProvider = provider ?? Metadata.Provider;
280
315
  if (!activeProvider) {
281
- return this.buildDenied(normalizedArtifactId, 'Metadata provider is not available.');
316
+ return fillAllDenied('Metadata provider is not available.');
282
317
  }
318
+ const visited = new Set(visitedArtifactIds ?? []);
283
319
  const normUserId = NormalizeUUID(user.ID ?? '');
284
320
  const activeMemo = memo ?? new Map();
285
- const memoKey = `${normArtifactId}::${normUserId}`;
286
- if (!strictThrowOnQueryError) {
287
- const cachedPromise = activeMemo.get(memoKey);
288
- if (cachedPromise) {
289
- return cachedPromise;
321
+ const memoHits = [];
322
+ const toFetchByNorm = new Map();
323
+ for (const rawId of artifactIds) {
324
+ const trimmed = (rawId ?? '').trim();
325
+ if (!trimmed) {
326
+ results.set(rawId, this.buildDenied(trimmed, 'Artifact ID and authenticated user context are required.'));
327
+ continue;
328
+ }
329
+ if (!IsValidUUID(trimmed)) {
330
+ results.set(rawId, this.buildDenied(trimmed, 'Artifact ID and user ID must be valid UUIDs.'));
331
+ continue;
332
+ }
333
+ const normId = NormalizeUUID(trimmed);
334
+ if (visited.has(normId)) {
335
+ results.set(rawId, this.buildDenied(trimmed, 'Circular artifact permission delegation detected.'));
336
+ continue;
337
+ }
338
+ const memoKey = `${normId}::${normUserId}`;
339
+ if (!strictThrowOnQueryError) {
340
+ const cachedPromise = activeMemo.get(memoKey);
341
+ if (cachedPromise) {
342
+ memoHits.push({ rawId, promise: cachedPromise });
343
+ continue;
344
+ }
345
+ }
346
+ let entry = toFetchByNorm.get(normId);
347
+ if (!entry) {
348
+ entry = { normId, id: trimmed, rawKeys: [] };
349
+ toFetchByNorm.set(normId, entry);
350
+ }
351
+ entry.rawKeys.push(rawId);
352
+ }
353
+ const toFetch = Array.from(toFetchByNorm.values());
354
+ if (toFetch.length > 0) {
355
+ const resolvedByNorm = await this.resolveBatchInternal(activeProvider, toFetch, user, depth, visited, activeMemo, strictThrowOnQueryError);
356
+ for (const item of toFetch) {
357
+ const resolved = resolvedByNorm.get(item.normId) ??
358
+ this.buildDenied(item.id, `Artifact '${item.id}' was not found.`);
359
+ for (const rawKey of item.rawKeys) {
360
+ results.set(rawKey, resolved);
361
+ }
362
+ if (!strictThrowOnQueryError) {
363
+ activeMemo.set(`${item.normId}::${normUserId}`, Promise.resolve(resolved));
364
+ }
365
+ }
366
+ }
367
+ if (memoHits.length > 0) {
368
+ const settled = await Promise.all(memoHits.map((h) => h.promise));
369
+ for (let i = 0; i < memoHits.length; i++) {
370
+ results.set(memoHits[i].rawId, settled[i]);
371
+ }
372
+ }
373
+ return results;
374
+ }
375
+ lookupEntityInfo(provider, entityId, entitiesById) {
376
+ if (typeof provider.EntityByID === 'function') {
377
+ return provider.EntityByID(entityId);
378
+ }
379
+ return entitiesById?.Get(entityId);
380
+ }
381
+ async resolveBatchInternal(provider, initialItems, user, depth, visited, memo, strictThrowOnQueryError) {
382
+ const entitiesById = typeof provider.EntityByID !== 'function' && Array.isArray(provider.Entities)
383
+ ? IndexByUUID(provider.Entities, (e) => e.ID)
384
+ : null;
385
+ const normUserId = NormalizeUUID(user.ID ?? '');
386
+ const resolvedByNorm = new Map();
387
+ const loadedNormIds = new Set();
388
+ const parentDelegateMetaByNormId = new Map();
389
+ const customDelegatedByNormId = new Map();
390
+ // Iterative wave loading: each wave loads ONLY MJ: Artifacts first so owned, missing, unregistered-delegate,
391
+ // and parent-delegated artifacts settle without querying MJ: Artifact Permissions or MJ: Artifact Versions.
392
+ let waveItems = initialItems.map((i) => ({ normId: i.normId, id: i.id }));
393
+ const maxExtraWaves = Math.max(0, MAX_DELEGATE_DEPTH - depth);
394
+ for (let wave = 0; wave <= maxExtraWaves && waveItems.length > 0; wave++) {
395
+ for (const w of waveItems) {
396
+ loadedNormIds.add(w.normId);
397
+ }
398
+ const artifactsInWave = await this.loadArtifactRowsBatch(provider, waveItems, user, strictThrowOnQueryError);
399
+ const nonDelegatedNonOwners = [];
400
+ const nextWaveParentsByNorm = new Map();
401
+ for (const w of waveItems) {
402
+ const artifact = artifactsInWave.get(w.normId);
403
+ if (!artifact) {
404
+ resolvedByNorm.set(w.normId, this.buildDenied(w.id, `Artifact '${w.id}' was not found.`));
405
+ continue;
406
+ }
407
+ const isOwner = Boolean(artifact.UserID && UUIDsEqual(artifact.UserID, user.ID));
408
+ if (artifact.DelegateEntityID && artifact.DelegateRecordID) {
409
+ const entityInfo = this.lookupEntityInfo(provider, artifact.DelegateEntityID, entitiesById);
410
+ const delegateEntityName = entityInfo?.Name ?? '';
411
+ const delegate = this.resolveDelegateInstance(artifact.DelegateEntityID, delegateEntityName);
412
+ if (!delegate) {
413
+ const entityLabel = delegateEntityName || artifact.DelegateEntityID;
414
+ LogError(`No permission delegate is registered for delegating entity '${entityLabel}' (${artifact.DelegateRecordID}) on artifact '${artifact.ID}'.`);
415
+ resolvedByNorm.set(w.normId, this.buildDenied(artifact.ID, `No permission delegate is registered for delegating entity '${entityLabel}' (${artifact.DelegateRecordID}).`));
416
+ continue;
417
+ }
418
+ if (delegate instanceof ParentArtifactPermissionDelegate) {
419
+ parentDelegateMetaByNormId.set(w.normId, {
420
+ Artifact: artifact,
421
+ DelegateEntityName: delegateEntityName,
422
+ DelegateEntityId: artifact.DelegateEntityID,
423
+ DelegateRecordId: artifact.DelegateRecordID
424
+ });
425
+ const parentTrimmed = artifact.DelegateRecordID.trim();
426
+ if (wave < maxExtraWaves && IsValidUUID(parentTrimmed)) {
427
+ const parentNorm = NormalizeUUID(parentTrimmed);
428
+ const parentMemoKey = `${parentNorm}::${normUserId}`;
429
+ const hasMemoHit = !strictThrowOnQueryError && memo.has(parentMemoKey);
430
+ if (!loadedNormIds.has(parentNorm) && !visited.has(parentNorm) && !hasMemoHit) {
431
+ nextWaveParentsByNorm.set(parentNorm, { normId: parentNorm, id: parentTrimmed });
432
+ }
433
+ }
434
+ }
435
+ else {
436
+ customDelegatedByNormId.set(w.normId, {
437
+ normId: w.normId,
438
+ id: w.id,
439
+ Artifact: artifact,
440
+ Delegate: delegate,
441
+ DelegateEntityName: delegateEntityName,
442
+ DelegateEntityId: artifact.DelegateEntityID,
443
+ DelegateRecordId: artifact.DelegateRecordID
444
+ });
445
+ }
446
+ }
447
+ else if (isOwner) {
448
+ resolvedByNorm.set(w.normId, this.evaluateNonDelegatedArtifact(artifact, user, [], []));
449
+ }
450
+ else {
451
+ nonDelegatedNonOwners.push({ normId: w.normId, id: w.id, Artifact: artifact });
452
+ }
290
453
  }
454
+ if (nonDelegatedNonOwners.length > 0) {
455
+ const { DirectPermsByNormArtifactId, CollectionPermsByNormArtifactId } = await this.loadDirectAndCollectionBatch(provider, nonDelegatedNonOwners, user, strictThrowOnQueryError);
456
+ for (const item of nonDelegatedNonOwners) {
457
+ resolvedByNorm.set(item.normId, this.evaluateNonDelegatedArtifact(item.Artifact, user, DirectPermsByNormArtifactId.get(item.normId) ?? [], CollectionPermsByNormArtifactId.get(item.normId) ?? []));
458
+ }
459
+ }
460
+ waveItems = Array.from(nextWaveParentsByNorm.values());
291
461
  }
292
- const resolutionPromise = this.resolvePermissionsInternal(activeProvider, normalizedArtifactId, user, depth, visited, activeMemo, strictThrowOnQueryError);
462
+ // Seed a child memo with already-settled entries (never unresolved promises) so custom delegates cannot deadlock
463
+ const settledMemo = new Map(memo);
293
464
  if (!strictThrowOnQueryError) {
294
- activeMemo.set(memoKey, resolutionPromise);
465
+ for (const [normId, resolved] of resolvedByNorm.entries()) {
466
+ settledMemo.set(`${normId}::${normUserId}`, Promise.resolve(resolved));
467
+ }
295
468
  }
296
- return resolutionPromise;
469
+ const parentResolvedByNorm = new Map();
470
+ const pendingCustomInvocations = [];
471
+ const pendingMemoParentChains = [];
472
+ // Walk parent-delegate chains for initialItems, capturing exact accumulated Depth & VisitedArtifactIDs
473
+ // whenever a chain terminates at a custom-delegated artifact.
474
+ for (const item of initialItems) {
475
+ if (customDelegatedByNormId.has(item.normId)) {
476
+ const directVisited = new Set(visited);
477
+ directVisited.add(item.normId);
478
+ pendingCustomInvocations.push({
479
+ Kind: 'direct',
480
+ StartNormId: item.normId,
481
+ TargetNormId: item.normId,
482
+ Depth: depth,
483
+ Visited: directVisited
484
+ });
485
+ continue;
486
+ }
487
+ const startMeta = parentDelegateMetaByNormId.get(item.normId);
488
+ if (!startMeta) {
489
+ continue;
490
+ }
491
+ const walk = this.walkParentDelegateChain(item.normId, startMeta, depth, visited, normUserId, strictThrowOnQueryError, parentDelegateMetaByNormId, customDelegatedByNormId, resolvedByNorm, memo);
492
+ if (walk.Kind === 'resolved') {
493
+ parentResolvedByNorm.set(item.normId, walk.Result);
494
+ }
495
+ else if (walk.Kind === 'memo') {
496
+ pendingMemoParentChains.push({
497
+ StartNormId: item.normId,
498
+ StartMeta: startMeta,
499
+ Promise: walk.Promise
500
+ });
501
+ }
502
+ else {
503
+ pendingCustomInvocations.push({
504
+ Kind: 'parent-chain',
505
+ StartNormId: item.normId,
506
+ StartMeta: startMeta,
507
+ TargetNormId: walk.CustomNormId,
508
+ Depth: walk.Depth,
509
+ Visited: walk.Visited
510
+ });
511
+ }
512
+ }
513
+ if (pendingMemoParentChains.length > 0) {
514
+ const memoParents = await Promise.all(pendingMemoParentChains.map((p) => p.Promise));
515
+ for (let i = 0; i < pendingMemoParentChains.length; i++) {
516
+ const entry = pendingMemoParentChains[i];
517
+ parentResolvedByNorm.set(entry.StartNormId, this.formatParentDelegateResult(entry.StartMeta, memoParents[i]));
518
+ }
519
+ }
520
+ // Evaluate custom delegates in parallel with exact accumulated Depth & VisitedArtifactIDs;
521
+ // batch-load direct + collection fallback rows ONCE only for non-owner invocations that returned 'Defer'.
522
+ if (pendingCustomInvocations.length > 0) {
523
+ const evaluated = await Promise.all(pendingCustomInvocations.map(async (inv) => {
524
+ const target = customDelegatedByNormId.get(inv.TargetNormId);
525
+ const decisions = await this.evaluateCustomDelegateDecisions(provider, target.Delegate, target.Artifact, target.DelegateEntityId, target.DelegateEntityName, target.DelegateRecordId, user, inv.Depth, inv.Visited, settledMemo);
526
+ return { inv, target, decisions };
527
+ }));
528
+ const customNeedingFallback = new Map();
529
+ for (const { target, decisions } of evaluated) {
530
+ const isOwner = Boolean(target.Artifact.UserID && UUIDsEqual(target.Artifact.UserID, user.ID));
531
+ if (decisions.NeedsFallback && !isOwner) {
532
+ customNeedingFallback.set(target.normId, { normId: target.normId, id: target.id });
533
+ }
534
+ }
535
+ let fallbackDirect = new Map();
536
+ let fallbackCollections = new Map();
537
+ if (customNeedingFallback.size > 0) {
538
+ const loadedFallback = await this.loadDirectAndCollectionBatch(provider, Array.from(customNeedingFallback.values()), user, strictThrowOnQueryError);
539
+ fallbackDirect = loadedFallback.DirectPermsByNormArtifactId;
540
+ fallbackCollections = loadedFallback.CollectionPermsByNormArtifactId;
541
+ }
542
+ for (const { inv, target, decisions } of evaluated) {
543
+ const finalized = this.finalizeCustomDelegateDecisions(target.Artifact, target.DelegateEntityId, target.DelegateEntityName, target.DelegateRecordId, decisions, user, fallbackDirect.get(target.normId) ?? [], fallbackCollections.get(target.normId) ?? []);
544
+ if (inv.Kind === 'direct') {
545
+ resolvedByNorm.set(inv.StartNormId, finalized);
546
+ }
547
+ else {
548
+ parentResolvedByNorm.set(inv.StartNormId, this.formatParentDelegateResult(inv.StartMeta, finalized));
549
+ }
550
+ }
551
+ }
552
+ for (const [normId, result] of parentResolvedByNorm.entries()) {
553
+ resolvedByNorm.set(normId, result);
554
+ }
555
+ return resolvedByNorm;
297
556
  }
298
- async resolvePermissionsInternal(activeProvider, normalizedArtifactId, user, depth, visited, memo, strictThrowOnQueryError = false) {
299
- const artifact = await this.loadArtifactRow(activeProvider, normalizedArtifactId, user, strictThrowOnQueryError);
300
- if (!artifact) {
301
- return this.buildDenied(normalizedArtifactId, `Artifact '${normalizedArtifactId}' was not found.`);
557
+ formatParentDelegateResult(startMeta, parentPerms) {
558
+ if (!parentPerms.CanRead) {
559
+ return this.buildDenied(startMeta.Artifact.ID, `Access denied by delegate entity '${startMeta.DelegateEntityName || startMeta.DelegateEntityId}' (${startMeta.DelegateRecordId}).`);
302
560
  }
303
- // 1. Artifact owner always has full permissions unless an explicit host delegate denies access.
304
- const isOwner = Boolean(artifact.UserID && UUIDsEqual(artifact.UserID, user.ID));
305
- // 2. Evaluate DelegateEntityID + DelegateRecordID when bound.
306
- if (artifact.DelegateEntityID && artifact.DelegateRecordID) {
307
- const delegateResult = await this.evaluateDelegate(activeProvider, artifact, user, depth, visited, memo, strictThrowOnQueryError);
308
- if (delegateResult) {
309
- return delegateResult;
561
+ return {
562
+ ArtifactID: startMeta.Artifact.ID,
563
+ CanRead: parentPerms.CanRead,
564
+ CanEdit: parentPerms.CanEdit,
565
+ CanDelete: parentPerms.CanDelete,
566
+ CanShare: parentPerms.CanShare,
567
+ Source: 'Delegate',
568
+ Reason: `Permissions resolved via delegate '${startMeta.DelegateEntityName || startMeta.DelegateEntityId}' (${startMeta.DelegateRecordId}).`
569
+ };
570
+ }
571
+ walkParentDelegateChain(startNormId, startMeta, baseDepth, baseVisited, normUserId, strictThrowOnQueryError, parentDelegateMetaByNormId, customDelegatedByNormId, resolvedByNorm, memo) {
572
+ const localVisited = new Set(baseVisited);
573
+ localVisited.add(startNormId);
574
+ let currentMeta = startMeta;
575
+ let currentDepth = baseDepth;
576
+ while (true) {
577
+ const nextDepth = currentDepth + 1;
578
+ const parentTrimmed = currentMeta.DelegateRecordId.trim();
579
+ if (!parentTrimmed || !IsValidUUID(parentTrimmed)) {
580
+ return {
581
+ Kind: 'resolved',
582
+ Result: this.formatParentDelegateResult(startMeta, this.buildDenied(parentTrimmed, 'Artifact ID and user ID must be valid UUIDs.'))
583
+ };
310
584
  }
585
+ if (nextDepth > MAX_DELEGATE_DEPTH) {
586
+ return {
587
+ Kind: 'resolved',
588
+ Result: this.formatParentDelegateResult(startMeta, this.buildDenied(parentTrimmed, 'Maximum artifact permission delegation depth exceeded.'))
589
+ };
590
+ }
591
+ const parentNorm = NormalizeUUID(parentTrimmed);
592
+ if (localVisited.has(parentNorm)) {
593
+ return {
594
+ Kind: 'resolved',
595
+ Result: this.formatParentDelegateResult(startMeta, this.buildDenied(parentTrimmed, 'Circular artifact permission delegation detected.'))
596
+ };
597
+ }
598
+ const settledParent = resolvedByNorm.get(parentNorm);
599
+ if (settledParent) {
600
+ return { Kind: 'resolved', Result: this.formatParentDelegateResult(startMeta, settledParent) };
601
+ }
602
+ if (customDelegatedByNormId.has(parentNorm)) {
603
+ localVisited.add(parentNorm);
604
+ return { Kind: 'custom', CustomNormId: parentNorm, Depth: nextDepth, Visited: localVisited };
605
+ }
606
+ const nextParentMeta = parentDelegateMetaByNormId.get(parentNorm);
607
+ if (nextParentMeta) {
608
+ localVisited.add(parentNorm);
609
+ currentMeta = nextParentMeta;
610
+ currentDepth = nextDepth;
611
+ continue;
612
+ }
613
+ if (!strictThrowOnQueryError) {
614
+ const memoPromise = memo.get(`${parentNorm}::${normUserId}`);
615
+ if (memoPromise) {
616
+ return { Kind: 'memo', Promise: memoPromise };
617
+ }
618
+ }
619
+ return {
620
+ Kind: 'resolved',
621
+ Result: this.formatParentDelegateResult(startMeta, this.buildDenied(parentTrimmed, `Artifact '${parentTrimmed}' was not found.`))
622
+ };
311
623
  }
624
+ }
625
+ evaluateNonDelegatedArtifact(artifact, user, directRows, collectionPerms) {
626
+ const isOwner = Boolean(artifact.UserID && UUIDsEqual(artifact.UserID, user.ID));
312
627
  if (isOwner) {
313
628
  return {
314
629
  ArtifactID: artifact.ID,
@@ -320,12 +635,6 @@ export class ArtifactPermissionEngine extends BaseSingleton {
320
635
  Reason: 'User is the owner of the artifact.'
321
636
  };
322
637
  }
323
- // 3 & 4. Union direct MJ: Artifact Permissions rows AND cascaded MJ: Collection Permissions
324
- // rows so a direct read-only share never masks higher grants inherited from a collection.
325
- const [directRows, collectionPerms] = await Promise.all([
326
- this.loadDirectPermissionRows(activeProvider, artifact.ID, user, strictThrowOnQueryError),
327
- this.loadCollectionPermissionRows(activeProvider, artifact.ID, user, strictThrowOnQueryError),
328
- ]);
329
638
  const directCanEdit = directRows.some((r) => Boolean(r.CanEdit));
330
639
  const directCanDelete = directRows.some((r) => Boolean(r.CanDelete));
331
640
  const directCanShare = directRows.some((r) => Boolean(r.CanShare));
@@ -359,34 +668,478 @@ export class ArtifactPermissionEngine extends BaseSingleton {
359
668
  }
360
669
  return this.buildDenied(artifact.ID, `User '${user.ID}' has no permission grant on artifact '${artifact.ID}'.`);
361
670
  }
362
- async evaluateDelegate(provider, artifact, user, depth, visited, memo, strictThrowOnQueryError = false) {
363
- const delegateEntityId = artifact.DelegateEntityID;
364
- const delegateRecordId = artifact.DelegateRecordID;
365
- const entityInfo = provider.EntityByID(delegateEntityId);
366
- const delegateEntityName = entityInfo?.Name ?? '';
367
- const delegate = this.resolveDelegateInstance(delegateEntityId, delegateEntityName);
368
- if (!delegate) {
369
- const entityLabel = delegateEntityName || delegateEntityId;
370
- LogError(`No permission delegate is registered for delegating entity '${entityLabel}' (${delegateRecordId}) on artifact '${artifact.ID}'.`);
371
- return this.buildDenied(artifact.ID, `No permission delegate is registered for delegating entity '${entityLabel}' (${delegateRecordId}).`);
372
- }
373
- // Fast O(depth) path for parent-artifact delegation ('MJ: Artifacts'): resolve the parent once per hop
374
- // instead of invoking 4 independent recursive calls across CanRead/CanEdit/CanDelete/CanShare.
375
- if (delegate instanceof ParentArtifactPermissionDelegate) {
376
- const parentPerms = await this.ResolvePermissions(provider, delegateRecordId, user, depth + 1, visited, memo, strictThrowOnQueryError);
377
- if (!parentPerms.CanRead) {
378
- return this.buildDenied(artifact.ID, `Access denied by delegate entity '${delegateEntityName || delegateEntityId}' (${delegateRecordId}).`);
671
+ async loadArtifactRowsBatch(provider, items, user, strictThrowOnQueryError) {
672
+ const artifactsByNormId = new Map();
673
+ if (items.length === 0) {
674
+ return artifactsByNormId;
675
+ }
676
+ const ids = items.map((i) => i.id);
677
+ const contextLabel = ids.length === 1 ? `artifact '${ids[0]}'` : `batch of ${ids.length} artifacts`;
678
+ const rv = RunView.FromMetadataProvider(provider);
679
+ const artifactQueries = chunkArray(ids, IN_CLAUSE_CHUNK_SIZE).map((chunk) => {
680
+ const artParams = {
681
+ EntityName: 'MJ: Artifacts',
682
+ ExtraFilter: buildEqOrInFilter('ID', chunk),
683
+ Fields: ['ID', 'UserID', 'DelegateEntityID', 'DelegateRecordID'],
684
+ ...(chunk.length === 1 ? { MaxRows: 1 } : { IgnoreMaxRows: true }),
685
+ SkipTotalRowCount: true,
686
+ BypassCache: true,
687
+ ResultType: 'simple'
688
+ };
689
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(artParams);
690
+ return artParams;
691
+ });
692
+ const ingest = (res) => {
693
+ if (!res?.Success) {
694
+ if (strictThrowOnQueryError) {
695
+ throw new Error(res?.ErrorMessage || `Failed loading artifact rows for ${contextLabel}.`);
696
+ }
697
+ return;
698
+ }
699
+ for (const row of (res.Results ?? [])) {
700
+ if (row?.ID) {
701
+ artifactsByNormId.set(NormalizeUUID(row.ID), row);
702
+ }
703
+ }
704
+ };
705
+ try {
706
+ const results = canUseRunViews(provider, rv)
707
+ ? await rv.RunViews(artifactQueries, user)
708
+ : await Promise.all(artifactQueries.map((q) => rv.RunView(q, user)));
709
+ for (const res of results) {
710
+ ingest(res);
379
711
  }
712
+ }
713
+ catch (err) {
714
+ LogError(`ArtifactPermissionEngine.loadArtifactRowsBatch error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
715
+ if (strictThrowOnQueryError) {
716
+ throw err;
717
+ }
718
+ }
719
+ return artifactsByNormId;
720
+ }
721
+ async loadDirectAndCollectionBatch(provider, items, user, strictThrowOnQueryError) {
722
+ const directPermsByNormArtifactId = new Map();
723
+ const versionIdsByNormArtifactId = new Map();
724
+ if (items.length === 0) {
380
725
  return {
381
- ArtifactID: artifact.ID,
382
- CanRead: parentPerms.CanRead,
383
- CanEdit: parentPerms.CanEdit,
384
- CanDelete: parentPerms.CanDelete,
385
- CanShare: parentPerms.CanShare,
386
- Source: 'Delegate',
387
- Reason: `Permissions resolved via delegate '${delegateEntityName || delegateEntityId}' (${delegateRecordId}).`
726
+ DirectPermsByNormArtifactId: directPermsByNormArtifactId,
727
+ CollectionPermsByNormArtifactId: new Map()
728
+ };
729
+ }
730
+ let directQueryError = null;
731
+ let versionQueryError = null;
732
+ const ids = items.map((i) => i.id);
733
+ const contextLabel = ids.length === 1 ? `artifact '${ids[0]}'` : `batch of ${ids.length} artifacts`;
734
+ const queryActor = await this.resolvePermissionQueryActor(provider, user, contextLabel);
735
+ const rv = RunView.FromMetadataProvider(provider);
736
+ const safeUserId = EscapeSQLString(user.ID);
737
+ const chunks = chunkArray(ids, IN_CLAUSE_CHUNK_SIZE);
738
+ const directQueries = [];
739
+ const versionQueries = [];
740
+ for (const chunk of chunks) {
741
+ const directParams = {
742
+ EntityName: 'MJ: Artifact Permissions',
743
+ ExtraFilter: `${buildEqOrInFilter('ArtifactID', chunk)} AND UserID='${safeUserId}'`,
744
+ Fields: ['ID', 'ArtifactID', 'UserID', 'CanRead', 'CanEdit', 'CanDelete', 'CanShare'],
745
+ IgnoreMaxRows: true,
746
+ SkipTotalRowCount: true,
747
+ BypassCache: true,
748
+ ResultType: 'simple'
388
749
  };
750
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(directParams);
751
+ directQueries.push(directParams);
752
+ if (queryActor) {
753
+ const verParams = {
754
+ EntityName: 'MJ: Artifact Versions',
755
+ ExtraFilter: buildEqOrInFilter('ArtifactID', chunk),
756
+ Fields: ['ID', 'ArtifactID'],
757
+ IgnoreMaxRows: true,
758
+ SkipTotalRowCount: true,
759
+ BypassCache: true,
760
+ ResultType: 'simple'
761
+ };
762
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(verParams);
763
+ versionQueries.push(verParams);
764
+ }
765
+ }
766
+ const singleNormFallback = items.length === 1 ? items[0].normId : null;
767
+ const ingestDirectResult = (res) => {
768
+ if (!res?.Success) {
769
+ if (!directQueryError) {
770
+ directQueryError = new Error(res?.ErrorMessage || `Failed loading direct permissions for ${contextLabel}.`);
771
+ }
772
+ return;
773
+ }
774
+ for (const row of (res.Results ?? [])) {
775
+ const artId = row?.ArtifactID;
776
+ const normArtId = artId ? NormalizeUUID(artId) : singleNormFallback;
777
+ if (!normArtId) {
778
+ continue;
779
+ }
780
+ let list = directPermsByNormArtifactId.get(normArtId);
781
+ if (!list) {
782
+ list = [];
783
+ directPermsByNormArtifactId.set(normArtId, list);
784
+ }
785
+ list.push(row);
786
+ }
787
+ };
788
+ const ingestVersionResult = (res) => {
789
+ if (!res?.Success) {
790
+ if (!versionQueryError) {
791
+ versionQueryError = new Error(res?.ErrorMessage || `Failed loading versions for ${contextLabel}.`);
792
+ }
793
+ return;
794
+ }
795
+ for (const row of (res.Results ?? [])) {
796
+ if (!row?.ID) {
797
+ continue;
798
+ }
799
+ const normArtId = row.ArtifactID ? NormalizeUUID(row.ArtifactID) : singleNormFallback;
800
+ if (!normArtId) {
801
+ continue;
802
+ }
803
+ let list = versionIdsByNormArtifactId.get(normArtId);
804
+ if (!list) {
805
+ list = [];
806
+ versionIdsByNormArtifactId.set(normArtId, list);
807
+ }
808
+ list.push(row.ID);
809
+ }
810
+ };
811
+ if (canUseRunViews(provider, rv)) {
812
+ if (provider.ProviderType !== 'Database') {
813
+ // On Network/GraphQL providers, queryActor === user: send Direct Perms + Versions in ONE RunViews call.
814
+ const combined = [...directQueries, ...versionQueries];
815
+ try {
816
+ const batchRes = await rv.RunViews(combined, user);
817
+ const directCount = directQueries.length;
818
+ for (let i = 0; i < directCount; i++) {
819
+ ingestDirectResult(batchRes[i]);
820
+ }
821
+ for (let i = 0; i < versionQueries.length; i++) {
822
+ ingestVersionResult(batchRes[directCount + i]);
823
+ }
824
+ }
825
+ catch (err) {
826
+ LogError(`ArtifactPermissionEngine.loadDirectAndCollectionBatch error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
827
+ if (strictThrowOnQueryError) {
828
+ throw err;
829
+ }
830
+ }
831
+ }
832
+ else {
833
+ // On Database providers, run MJ: Artifact Permissions as `user` (preserving entity CanRead and RLS)
834
+ // and MJ: Artifact Versions as `queryActor` (systemUser, avoiding ArtifactVersionPostRunViewHook recursion) in parallel.
835
+ const runDirectBatch = async () => {
836
+ try {
837
+ const resList = directQueries.length === 1
838
+ ? [await rv.RunView(directQueries[0], user)]
839
+ : await rv.RunViews(directQueries, user);
840
+ for (const res of resList) {
841
+ ingestDirectResult(res);
842
+ }
843
+ }
844
+ catch (err) {
845
+ LogError(`ArtifactPermissionEngine.loadDirectPermissionRows error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
846
+ if (!directQueryError) {
847
+ directQueryError = err instanceof Error ? err : new Error(String(err));
848
+ }
849
+ }
850
+ };
851
+ const runVersionBatch = async () => {
852
+ if (versionQueries.length === 0 || !queryActor) {
853
+ return;
854
+ }
855
+ try {
856
+ const verRes = versionQueries.length === 1
857
+ ? [await rv.RunView(versionQueries[0], queryActor)]
858
+ : await rv.RunViews(versionQueries, queryActor);
859
+ for (const res of verRes) {
860
+ ingestVersionResult(res);
861
+ }
862
+ }
863
+ catch (err) {
864
+ LogError(`ArtifactPermissionEngine.loadCollectionPermissionRows error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
865
+ if (!versionQueryError) {
866
+ versionQueryError = err instanceof Error ? err : new Error(String(err));
867
+ }
868
+ }
869
+ };
870
+ await Promise.all([runDirectBatch(), runVersionBatch()]);
871
+ }
389
872
  }
873
+ else {
874
+ // Fallback for test doubles that stub only RunView without RunViews
875
+ await Promise.all([
876
+ ...directQueries.map(async (q) => {
877
+ try {
878
+ ingestDirectResult(await rv.RunView(q, user));
879
+ }
880
+ catch (err) {
881
+ LogError(`ArtifactPermissionEngine.loadDirectPermissionRows error: ${err instanceof Error ? err.message : String(err)}`);
882
+ if (!directQueryError) {
883
+ directQueryError = err instanceof Error ? err : new Error(String(err));
884
+ }
885
+ }
886
+ }),
887
+ ...versionQueries.map(async (q) => {
888
+ try {
889
+ ingestVersionResult(await rv.RunView(q, queryActor));
890
+ }
891
+ catch (err) {
892
+ LogError(`ArtifactPermissionEngine.loadCollectionPermissionRows error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
893
+ if (!versionQueryError) {
894
+ versionQueryError = err instanceof Error ? err : new Error(String(err));
895
+ }
896
+ }
897
+ })
898
+ ]);
899
+ }
900
+ if (strictThrowOnQueryError) {
901
+ if (directQueryError) {
902
+ throw directQueryError;
903
+ }
904
+ if (versionQueryError) {
905
+ throw versionQueryError;
906
+ }
907
+ }
908
+ const artifactsNeedingCollections = new Set(items.map((i) => i.normId));
909
+ const collectionPermsByNormArtifactId = await this.loadBatchedCollectionPermissions(provider, items, artifactsNeedingCollections, versionIdsByNormArtifactId, queryActor, user, strictThrowOnQueryError);
910
+ return {
911
+ DirectPermsByNormArtifactId: directPermsByNormArtifactId,
912
+ CollectionPermsByNormArtifactId: collectionPermsByNormArtifactId
913
+ };
914
+ }
915
+ async loadBatchedCollectionPermissions(provider, items, artifactsNeedingCollections, versionIdsByNormArtifactId, queryActor, user, strictThrowOnQueryError) {
916
+ const resultByNormArtifactId = new Map();
917
+ if (artifactsNeedingCollections.size === 0) {
918
+ return resultByNormArtifactId;
919
+ }
920
+ const contextLabel = items.length === 1 ? `artifact '${items[0].id}'` : `batch of ${items.length} artifacts`;
921
+ if (!queryActor) {
922
+ if (strictThrowOnQueryError) {
923
+ throw new Error(`System user is unavailable for collection lookup on ${contextLabel}.`);
924
+ }
925
+ return resultByNormArtifactId;
926
+ }
927
+ // Collect all unique version IDs across artifacts needing collection resolution
928
+ const versionNormToArtifactNorms = new Map();
929
+ const uniqueVersionIds = [];
930
+ for (const normArtId of artifactsNeedingCollections) {
931
+ const verIds = versionIdsByNormArtifactId.get(normArtId) ?? [];
932
+ for (const verId of verIds) {
933
+ const normVerId = NormalizeUUID(verId);
934
+ let owners = versionNormToArtifactNorms.get(normVerId);
935
+ if (!owners) {
936
+ owners = new Set();
937
+ versionNormToArtifactNorms.set(normVerId, owners);
938
+ uniqueVersionIds.push(verId);
939
+ }
940
+ owners.add(normArtId);
941
+ }
942
+ }
943
+ if (uniqueVersionIds.length === 0) {
944
+ return resultByNormArtifactId;
945
+ }
946
+ try {
947
+ const rv = RunView.FromMetadataProvider(provider);
948
+ const runBatch = async (paramsList) => {
949
+ for (const p of paramsList) {
950
+ ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(p);
951
+ }
952
+ if (paramsList.length === 0) {
953
+ return [];
954
+ }
955
+ if (paramsList.length === 1) {
956
+ return [await rv.RunView(paramsList[0], queryActor)];
957
+ }
958
+ if (canUseRunViews(provider, rv)) {
959
+ return await rv.RunViews(paramsList, queryActor);
960
+ }
961
+ return await Promise.all(paramsList.map((p) => rv.RunView(p, queryActor)));
962
+ };
963
+ // 1. Batched MJ: Collection Artifacts lookup
964
+ const colArtQueries = chunkArray(uniqueVersionIds, IN_CLAUSE_CHUNK_SIZE).map((verChunk) => ({
965
+ EntityName: 'MJ: Collection Artifacts',
966
+ ExtraFilter: `ArtifactVersionID IN (${buildQuotedInList(verChunk)})`,
967
+ Fields: ['ArtifactVersionID', 'CollectionID'],
968
+ IgnoreMaxRows: true,
969
+ SkipTotalRowCount: true,
970
+ BypassCache: true,
971
+ ResultType: 'simple'
972
+ }));
973
+ const colArtResults = await runBatch(colArtQueries);
974
+ const directColsByNormArtifactId = new Map();
975
+ const seenColNormIds = new Set();
976
+ const directCollectionIds = [];
977
+ const singleFallbackArtNorm = artifactsNeedingCollections.size === 1 ? Array.from(artifactsNeedingCollections)[0] : null;
978
+ for (const res of colArtResults) {
979
+ if (!res?.Success) {
980
+ if (strictThrowOnQueryError) {
981
+ throw new Error(res?.ErrorMessage || `Failed loading collection links for ${contextLabel}.`);
982
+ }
983
+ continue;
984
+ }
985
+ for (const row of (res.Results ?? [])) {
986
+ if (!row?.CollectionID) {
987
+ continue;
988
+ }
989
+ const normColId = NormalizeUUID(row.CollectionID);
990
+ const targetArts = row.ArtifactVersionID
991
+ ? versionNormToArtifactNorms.get(NormalizeUUID(row.ArtifactVersionID))
992
+ : singleFallbackArtNorm
993
+ ? new Set([singleFallbackArtNorm])
994
+ : undefined;
995
+ if (!targetArts) {
996
+ continue;
997
+ }
998
+ if (!seenColNormIds.has(normColId)) {
999
+ seenColNormIds.add(normColId);
1000
+ directCollectionIds.push(row.CollectionID);
1001
+ }
1002
+ for (const normArtId of targetArts) {
1003
+ let colSet = directColsByNormArtifactId.get(normArtId);
1004
+ if (!colSet) {
1005
+ colSet = new Set();
1006
+ directColsByNormArtifactId.set(normArtId, colSet);
1007
+ }
1008
+ colSet.add(normColId);
1009
+ }
1010
+ }
1011
+ }
1012
+ if (directCollectionIds.length === 0) {
1013
+ return resultByNormArtifactId;
1014
+ }
1015
+ // 2. Walk collection ancestry level-by-level across ALL collections (1 batched query per depth level)
1016
+ const collectionMetaByNormId = new Map();
1017
+ const allCollectionIds = [...directCollectionIds];
1018
+ let frontier = [...directCollectionIds];
1019
+ for (let level = 0; level < MAX_COLLECTION_ANCESTRY_DEPTH && frontier.length > 0; level++) {
1020
+ const colMetaQueries = chunkArray(frontier, IN_CLAUSE_CHUNK_SIZE).map((colChunk) => ({
1021
+ EntityName: 'MJ: Collections',
1022
+ ExtraFilter: `ID IN (${buildQuotedInList(colChunk)})`,
1023
+ Fields: ['ID', 'OwnerID', 'ParentID'],
1024
+ IgnoreMaxRows: true,
1025
+ SkipTotalRowCount: true,
1026
+ BypassCache: true,
1027
+ ResultType: 'simple'
1028
+ }));
1029
+ const colMetaResults = await runBatch(colMetaQueries);
1030
+ const nextFrontier = [];
1031
+ for (const res of colMetaResults) {
1032
+ if (!res?.Success && strictThrowOnQueryError) {
1033
+ throw new Error(res?.ErrorMessage || `Failed loading collections for ${contextLabel}.`);
1034
+ }
1035
+ if (!res?.Success || !res.Results) {
1036
+ continue;
1037
+ }
1038
+ for (const col of res.Results) {
1039
+ if (!col?.ID) {
1040
+ continue;
1041
+ }
1042
+ collectionMetaByNormId.set(NormalizeUUID(col.ID), col);
1043
+ if (level + 1 >= MAX_COLLECTION_ANCESTRY_DEPTH) {
1044
+ continue;
1045
+ }
1046
+ const parentId = col.ParentID?.trim();
1047
+ if (parentId && IsValidUUID(parentId)) {
1048
+ const normParent = NormalizeUUID(parentId);
1049
+ if (!seenColNormIds.has(normParent)) {
1050
+ seenColNormIds.add(normParent);
1051
+ allCollectionIds.push(parentId);
1052
+ nextFrontier.push(parentId);
1053
+ }
1054
+ }
1055
+ }
1056
+ }
1057
+ frontier = nextFrontier;
1058
+ }
1059
+ // 3. Load MJ: Collection Permissions once for ALL discovered collections across the batch
1060
+ const safeUserId = EscapeSQLString(user.ID);
1061
+ const permQueries = chunkArray(allCollectionIds, IN_CLAUSE_CHUNK_SIZE).map((colChunk) => ({
1062
+ EntityName: 'MJ: Collection Permissions',
1063
+ ExtraFilter: `CollectionID IN (${buildQuotedInList(colChunk)}) AND UserID='${safeUserId}'`,
1064
+ Fields: ['CollectionID', 'CanRead', 'CanEdit', 'CanDelete', 'CanShare'],
1065
+ IgnoreMaxRows: true,
1066
+ SkipTotalRowCount: true,
1067
+ BypassCache: true,
1068
+ ResultType: 'simple'
1069
+ }));
1070
+ const permResults = await runBatch(permQueries);
1071
+ const permsByNormColId = new Map();
1072
+ const unkeyedPermRows = [];
1073
+ for (const res of permResults) {
1074
+ if (!res?.Success && strictThrowOnQueryError) {
1075
+ throw new Error(res?.ErrorMessage || `Failed loading collection permissions for ${contextLabel}.`);
1076
+ }
1077
+ if (!res?.Success || !res.Results) {
1078
+ continue;
1079
+ }
1080
+ for (const row of res.Results) {
1081
+ if (row.CollectionID) {
1082
+ const normColId = NormalizeUUID(row.CollectionID);
1083
+ let list = permsByNormColId.get(normColId);
1084
+ if (!list) {
1085
+ list = [];
1086
+ permsByNormColId.set(normColId, list);
1087
+ }
1088
+ list.push(row);
1089
+ }
1090
+ else if (artifactsNeedingCollections.size === 1) {
1091
+ unkeyedPermRows.push(row);
1092
+ }
1093
+ }
1094
+ }
1095
+ // 4. Assemble each artifact's effective collection permission rows in memory (cycle-guarded, depth-bounded)
1096
+ for (const [normArtId, directColNorms] of directColsByNormArtifactId.entries()) {
1097
+ const artRows = [...unkeyedPermRows];
1098
+ const visitedForArt = new Set();
1099
+ let artFrontier = Array.from(directColNorms);
1100
+ for (let level = 0; level < MAX_COLLECTION_ANCESTRY_DEPTH && artFrontier.length > 0; level++) {
1101
+ const nextArtFrontier = [];
1102
+ for (const normColId of artFrontier) {
1103
+ if (visitedForArt.has(normColId)) {
1104
+ continue;
1105
+ }
1106
+ visitedForArt.add(normColId);
1107
+ const col = collectionMetaByNormId.get(normColId);
1108
+ if (col?.OwnerID && UUIDsEqual(col.OwnerID, user.ID)) {
1109
+ artRows.push({
1110
+ CollectionID: col.ID,
1111
+ CanRead: true,
1112
+ CanEdit: true,
1113
+ CanDelete: true,
1114
+ CanShare: true
1115
+ });
1116
+ }
1117
+ const colPermRows = permsByNormColId.get(normColId);
1118
+ if (colPermRows) {
1119
+ artRows.push(...colPermRows);
1120
+ }
1121
+ if (level + 1 < MAX_COLLECTION_ANCESTRY_DEPTH && col?.ParentID?.trim()) {
1122
+ const normParent = NormalizeUUID(col.ParentID.trim());
1123
+ if (!visitedForArt.has(normParent)) {
1124
+ nextArtFrontier.push(normParent);
1125
+ }
1126
+ }
1127
+ }
1128
+ artFrontier = nextArtFrontier;
1129
+ }
1130
+ resultByNormArtifactId.set(normArtId, artRows);
1131
+ }
1132
+ return resultByNormArtifactId;
1133
+ }
1134
+ catch (err) {
1135
+ LogError(`ArtifactPermissionEngine.loadCollectionPermissionRows error for ${contextLabel} (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
1136
+ if (strictThrowOnQueryError) {
1137
+ throw err;
1138
+ }
1139
+ return resultByNormArtifactId;
1140
+ }
1141
+ }
1142
+ async evaluateCustomDelegateDecisions(provider, delegate, artifact, delegateEntityId, delegateEntityName, delegateRecordId, user, depth, visited, memo) {
390
1143
  const context = {
391
1144
  ArtifactID: artifact.ID,
392
1145
  ArtifactOwnerUserID: artifact.UserID,
@@ -408,9 +1161,21 @@ export class ArtifactPermissionEngine extends BaseSingleton {
408
1161
  const normEdit = normalizeDecision(editDec);
409
1162
  const normDelete = normalizeDecision(deleteDec);
410
1163
  const normShare = normalizeDecision(shareDec);
411
- // If every action deferred, fall through to owner / MJ: Artifact Permissions.
1164
+ const needsFallback = normRead !== 'Deny' &&
1165
+ (normRead === 'Defer' || normEdit === 'Defer' || normDelete === 'Defer' || normShare === 'Defer');
1166
+ return {
1167
+ NormRead: normRead,
1168
+ NormEdit: normEdit,
1169
+ NormDelete: normDelete,
1170
+ NormShare: normShare,
1171
+ NeedsFallback: needsFallback
1172
+ };
1173
+ }
1174
+ finalizeCustomDelegateDecisions(artifact, delegateEntityId, delegateEntityName, delegateRecordId, decisions, user, directRows, collectionRows) {
1175
+ const { NormRead: normRead, NormEdit: normEdit, NormDelete: normDelete, NormShare: normShare } = decisions;
1176
+ // If every action deferred, fall through to owner / MJ: Artifact Permissions / Collection Permissions.
412
1177
  if (normRead === 'Defer' && normEdit === 'Defer' && normDelete === 'Defer' && normShare === 'Defer') {
413
- return null;
1178
+ return this.evaluateNonDelegatedArtifact(artifact, user, directRows, collectionRows);
414
1179
  }
415
1180
  // If the delegate explicitly denied Read, deny all actions immediately.
416
1181
  if (normRead === 'Deny') {
@@ -423,10 +1188,6 @@ export class ArtifactPermissionEngine extends BaseSingleton {
423
1188
  let fallbackShare = isOwner;
424
1189
  let fallbackRead = isOwner;
425
1190
  if (!isOwner && (normRead === 'Defer' || normEdit === 'Defer' || normDelete === 'Defer' || normShare === 'Defer')) {
426
- const [directRows, collectionRows] = await Promise.all([
427
- this.loadDirectPermissionRows(provider, artifact.ID, user),
428
- this.loadCollectionPermissionRows(provider, artifact.ID, user)
429
- ]);
430
1191
  const fallbackRows = [...directRows, ...collectionRows];
431
1192
  fallbackEdit = fallbackRows.some((r) => Boolean(r.CanEdit));
432
1193
  fallbackDelete = fallbackRows.some((r) => Boolean(r.CanDelete));
@@ -469,75 +1230,6 @@ export class ArtifactPermissionEngine extends BaseSingleton {
469
1230
  }
470
1231
  return null;
471
1232
  }
472
- async loadArtifactRow(provider, artifactId, user, strictThrowOnQueryError = false) {
473
- if (!IsValidUUID(artifactId)) {
474
- return null;
475
- }
476
- try {
477
- const rv = RunView.FromMetadataProvider(provider);
478
- const safeId = EscapeSQLString(artifactId);
479
- const artifactParams = {
480
- EntityName: 'MJ: Artifacts',
481
- ExtraFilter: `ID='${safeId}'`,
482
- Fields: ['ID', 'UserID', 'DelegateEntityID', 'DelegateRecordID'],
483
- MaxRows: 1,
484
- SkipTotalRowCount: true,
485
- ResultType: 'simple'
486
- };
487
- ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(artifactParams);
488
- const result = await rv.RunView(artifactParams, user);
489
- if (!result.Success) {
490
- if (strictThrowOnQueryError) {
491
- throw new Error(result.ErrorMessage || `Failed loading artifact row '${artifactId}'.`);
492
- }
493
- return null;
494
- }
495
- if (!result.Results || result.Results.length === 0) {
496
- return null;
497
- }
498
- return result.Results[0];
499
- }
500
- catch (err) {
501
- LogError(`ArtifactPermissionEngine.loadArtifactRow error: ${err instanceof Error ? err.message : String(err)}`);
502
- if (strictThrowOnQueryError) {
503
- throw err;
504
- }
505
- return null;
506
- }
507
- }
508
- async loadDirectPermissionRows(provider, artifactId, user, strictThrowOnQueryError = false) {
509
- if (!IsValidUUID(artifactId) || !IsValidUUID(user.ID)) {
510
- return [];
511
- }
512
- try {
513
- const rv = RunView.FromMetadataProvider(provider);
514
- const safeArtifactId = EscapeSQLString(artifactId);
515
- const safeUserId = EscapeSQLString(user.ID);
516
- const directParams = {
517
- EntityName: 'MJ: Artifact Permissions',
518
- ExtraFilter: `ArtifactID='${safeArtifactId}' AND UserID='${safeUserId}'`,
519
- Fields: ['ID', 'ArtifactID', 'UserID', 'CanRead', 'CanEdit', 'CanDelete', 'CanShare'],
520
- SkipTotalRowCount: true,
521
- ResultType: 'simple'
522
- };
523
- ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(directParams);
524
- const result = await rv.RunView(directParams, user);
525
- if (!result.Success) {
526
- if (strictThrowOnQueryError) {
527
- throw new Error(result.ErrorMessage || `Failed loading direct permissions for artifact '${artifactId}'.`);
528
- }
529
- return [];
530
- }
531
- return result.Results ?? [];
532
- }
533
- catch (err) {
534
- LogError(`ArtifactPermissionEngine.loadDirectPermissionRows error: ${err instanceof Error ? err.message : String(err)}`);
535
- if (strictThrowOnQueryError) {
536
- throw err;
537
- }
538
- return [];
539
- }
540
- }
541
1233
  /**
542
1234
  * Resolves effective collection permissions for `(collectionId, user)` by walking `ParentID`
543
1235
  * ancestry up to depth 16 (cycle-guarded) and unioning `OwnerID` ownership with direct and
@@ -1023,18 +1715,19 @@ export class ArtifactPermissionEngine extends BaseSingleton {
1023
1715
  }
1024
1716
  }
1025
1717
  }
1026
- // 4. Verify each candidate through ResolvePermissions (with shared memo) so delegate 'Deny' overrides are honored
1027
- const resolveMemo = new Map();
1718
+ // 4. Verify all candidates in one batched ResolvePermissionsBatch call (chunked internally at
1719
+ // IN_CLAUSE_CHUNK_SIZE) so delegate 'Deny' overrides are honored in O(1) round trips.
1028
1720
  const candidateValues = Array.from(candidates.entries());
1029
- for (const batch of chunkArray(candidateValues, 20)) {
1030
- const resolvedBatch = await Promise.all(batch.map(async ([normId, rawId]) => ({
1031
- normId,
1032
- perms: await this.ResolvePermissions(provider, rawId, user, 0, undefined, resolveMemo, throwOnQueryFailure)
1033
- })));
1034
- for (const entry of resolvedBatch) {
1035
- const matches = predicate ? predicate(entry.perms) : entry.perms.CanRead;
1036
- if (entry.perms.CanRead && matches) {
1037
- readable.add(entry.normId);
1721
+ if (candidateValues.length > 0) {
1722
+ const resolveMemo = new Map();
1723
+ const resolvedBatch = await this.ResolvePermissionsBatch(provider, candidateValues.map(([, rawId]) => rawId), user, 0, undefined, resolveMemo, throwOnQueryFailure);
1724
+ for (const [normId, rawId] of candidateValues) {
1725
+ const perms = resolvedBatch.get(rawId);
1726
+ if (perms && perms.CanRead) {
1727
+ const matches = predicate ? predicate(perms) : perms.CanRead;
1728
+ if (matches) {
1729
+ readable.add(normId);
1730
+ }
1038
1731
  }
1039
1732
  }
1040
1733
  }
@@ -1056,152 +1749,6 @@ export class ArtifactPermissionEngine extends BaseSingleton {
1056
1749
  }
1057
1750
  return user;
1058
1751
  }
1059
- async loadCollectionPermissionRows(provider, artifactId, user, strictThrowOnQueryError = false) {
1060
- try {
1061
- // On Database providers, run the version/collection membership lookup strictly as the system
1062
- // user so `ArtifactVersionPostRunViewHook` does not recurse back into `ResolvePermissions`
1063
- // while resolving collection-shared grants for `user` (`B3`, `R7-2`). If `GetSystemUser()`
1064
- // is unavailable on a Database provider, fail closed on this inner collection lookup rather
1065
- // than falling back to `user` (which would recurse) or using a process-wide set (which denies
1066
- // concurrent parallel resolutions for the same artifact/user).
1067
- const queryActor = await this.resolvePermissionQueryActor(provider, user, `artifact '${artifactId}'`);
1068
- if (!queryActor) {
1069
- if (strictThrowOnQueryError) {
1070
- throw new Error(`System user is unavailable for collection lookup on artifact '${artifactId}'.`);
1071
- }
1072
- return [];
1073
- }
1074
- const rv = RunView.FromMetadataProvider(provider);
1075
- const safeArtifactId = EscapeSQLString(artifactId);
1076
- const safeUserId = EscapeSQLString(user.ID);
1077
- const versionsParams = {
1078
- EntityName: 'MJ: Artifact Versions',
1079
- ExtraFilter: `ArtifactID='${safeArtifactId}'`,
1080
- Fields: ['ID'],
1081
- IgnoreMaxRows: true,
1082
- SkipTotalRowCount: true,
1083
- ResultType: 'simple'
1084
- };
1085
- ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(versionsParams);
1086
- const versionsResult = await rv.RunView(versionsParams, queryActor);
1087
- if (!versionsResult.Success) {
1088
- if (strictThrowOnQueryError) {
1089
- throw new Error(versionsResult.ErrorMessage || `Failed loading versions for artifact '${artifactId}'.`);
1090
- }
1091
- return [];
1092
- }
1093
- const versionIds = Array.from(new Set((versionsResult.Results ?? []).map((v) => v.ID).filter(Boolean)));
1094
- if (versionIds.length === 0) {
1095
- return [];
1096
- }
1097
- const directCollectionIds = [];
1098
- const seenCollectionIds = new Set();
1099
- for (const verChunk of chunkArray(versionIds, IN_CLAUSE_CHUNK_SIZE)) {
1100
- const colParams = {
1101
- EntityName: 'MJ: Collection Artifacts',
1102
- ExtraFilter: `ArtifactVersionID IN (${buildQuotedInList(verChunk)})`,
1103
- Fields: ['CollectionID'],
1104
- IgnoreMaxRows: true,
1105
- SkipTotalRowCount: true,
1106
- ResultType: 'simple'
1107
- };
1108
- ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(colParams);
1109
- const colResult = await rv.RunView(colParams, queryActor);
1110
- if (!colResult.Success) {
1111
- if (strictThrowOnQueryError) {
1112
- throw new Error(colResult.ErrorMessage || `Failed loading collection links for artifact '${artifactId}'.`);
1113
- }
1114
- continue;
1115
- }
1116
- for (const row of colResult.Results ?? []) {
1117
- if (row.CollectionID) {
1118
- const norm = NormalizeUUID(row.CollectionID);
1119
- if (!seenCollectionIds.has(norm)) {
1120
- seenCollectionIds.add(norm);
1121
- directCollectionIds.push(row.CollectionID);
1122
- }
1123
- }
1124
- }
1125
- }
1126
- if (directCollectionIds.length === 0) {
1127
- return [];
1128
- }
1129
- // Walk ParentID ancestry across 16 total levels (depth 0..15, cycle-guarded) and include collection OwnerID grants
1130
- const allCollectionIds = [...directCollectionIds];
1131
- const rows = [];
1132
- let frontier = [...directCollectionIds];
1133
- for (let depth = 0; depth < MAX_COLLECTION_ANCESTRY_DEPTH && frontier.length > 0; depth++) {
1134
- const nextFrontier = [];
1135
- for (const colChunk of chunkArray(frontier, IN_CLAUSE_CHUNK_SIZE)) {
1136
- const colMetaParams = {
1137
- EntityName: 'MJ: Collections',
1138
- ExtraFilter: `ID IN (${buildQuotedInList(colChunk)})`,
1139
- Fields: ['ID', 'OwnerID', 'ParentID'],
1140
- IgnoreMaxRows: true,
1141
- SkipTotalRowCount: true,
1142
- ResultType: 'simple'
1143
- };
1144
- ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(colMetaParams);
1145
- const colMetaRes = await rv.RunView(colMetaParams, queryActor);
1146
- if (!colMetaRes.Success && strictThrowOnQueryError) {
1147
- throw new Error(colMetaRes.ErrorMessage || `Failed loading collections for artifact '${artifactId}'.`);
1148
- }
1149
- if (colMetaRes.Success && colMetaRes.Results) {
1150
- for (const col of colMetaRes.Results) {
1151
- if (col.OwnerID && UUIDsEqual(col.OwnerID, user.ID)) {
1152
- rows.push({
1153
- CollectionID: col.ID,
1154
- CanRead: true,
1155
- CanEdit: true,
1156
- CanDelete: true,
1157
- CanShare: true
1158
- });
1159
- }
1160
- if (depth + 1 >= MAX_COLLECTION_ANCESTRY_DEPTH) {
1161
- continue;
1162
- }
1163
- const parentId = col.ParentID?.trim();
1164
- if (parentId) {
1165
- const normParent = NormalizeUUID(parentId);
1166
- if (!seenCollectionIds.has(normParent)) {
1167
- seenCollectionIds.add(normParent);
1168
- allCollectionIds.push(parentId);
1169
- nextFrontier.push(parentId);
1170
- }
1171
- }
1172
- }
1173
- }
1174
- }
1175
- frontier = nextFrontier;
1176
- }
1177
- for (const colChunk of chunkArray(allCollectionIds, IN_CLAUSE_CHUNK_SIZE)) {
1178
- const permParams = {
1179
- EntityName: 'MJ: Collection Permissions',
1180
- ExtraFilter: `CollectionID IN (${buildQuotedInList(colChunk)}) AND UserID='${safeUserId}'`,
1181
- Fields: ['CollectionID', 'CanRead', 'CanEdit', 'CanDelete', 'CanShare'],
1182
- IgnoreMaxRows: true,
1183
- SkipTotalRowCount: true,
1184
- ResultType: 'simple'
1185
- };
1186
- ArtifactPermissionEngine.MarkPermissionResolutionRecursionGuard(permParams);
1187
- const permResult = await rv.RunView(permParams, queryActor);
1188
- if (!permResult.Success && strictThrowOnQueryError) {
1189
- throw new Error(permResult.ErrorMessage || `Failed loading collection permissions for artifact '${artifactId}'.`);
1190
- }
1191
- if (permResult.Success && permResult.Results) {
1192
- rows.push(...permResult.Results);
1193
- }
1194
- }
1195
- return rows;
1196
- }
1197
- catch (err) {
1198
- LogError(`ArtifactPermissionEngine.loadCollectionPermissionRows error for artifact '${artifactId}' (user '${user.ID}'): ${err instanceof Error ? err.message : String(err)}`);
1199
- if (strictThrowOnQueryError) {
1200
- throw err;
1201
- }
1202
- return [];
1203
- }
1204
- }
1205
1752
  buildDeniedCollection(collectionId, reason) {
1206
1753
  return {
1207
1754
  CollectionID: collectionId,