@memberjunction/core-entities 6.3.0-edge.0 → 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 (193) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/custom/AnchoredConversationSecurity.d.ts +10 -1
  3. package/dist/custom/AnchoredConversationSecurity.d.ts.map +1 -1
  4. package/dist/custom/AnchoredConversationSecurity.js +15 -0
  5. package/dist/custom/AnchoredConversationSecurity.js.map +1 -1
  6. package/dist/custom/ArtifactLockValidation.d.ts +28 -0
  7. package/dist/custom/ArtifactLockValidation.d.ts.map +1 -0
  8. package/dist/custom/ArtifactLockValidation.js +867 -0
  9. package/dist/custom/ArtifactLockValidation.js.map +1 -0
  10. package/dist/custom/ArtifactPermissionDelegate.d.ts +288 -0
  11. package/dist/custom/ArtifactPermissionDelegate.d.ts.map +1 -0
  12. package/dist/custom/ArtifactPermissionDelegate.js +1779 -0
  13. package/dist/custom/ArtifactPermissionDelegate.js.map +1 -0
  14. package/dist/custom/ArtifactPreviewSnapshot.d.ts +199 -0
  15. package/dist/custom/ArtifactPreviewSnapshot.d.ts.map +1 -0
  16. package/dist/custom/ArtifactPreviewSnapshot.js +772 -0
  17. package/dist/custom/ArtifactPreviewSnapshot.js.map +1 -0
  18. package/dist/custom/ArtifactSynthesisEngine.d.ts +151 -0
  19. package/dist/custom/ArtifactSynthesisEngine.d.ts.map +1 -0
  20. package/dist/custom/ArtifactSynthesisEngine.js +1124 -0
  21. package/dist/custom/ArtifactSynthesisEngine.js.map +1 -0
  22. package/dist/custom/ConversationWriteAccess.d.ts +36 -0
  23. package/dist/custom/ConversationWriteAccess.d.ts.map +1 -1
  24. package/dist/custom/ConversationWriteAccess.js +109 -1
  25. package/dist/custom/ConversationWriteAccess.js.map +1 -1
  26. package/dist/custom/DocumentLiveBlockEngine.d.ts +612 -0
  27. package/dist/custom/DocumentLiveBlockEngine.d.ts.map +1 -0
  28. package/dist/custom/DocumentLiveBlockEngine.js +2352 -0
  29. package/dist/custom/DocumentLiveBlockEngine.js.map +1 -0
  30. package/dist/custom/MJQueryEntityExtended.d.ts.map +1 -1
  31. package/dist/custom/MJQueryEntityExtended.js +27 -11
  32. package/dist/custom/MJQueryEntityExtended.js.map +1 -1
  33. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.d.ts.map +1 -1
  34. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js +31 -7
  35. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js.map +1 -1
  36. package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts +3 -4
  37. package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts.map +1 -1
  38. package/dist/custom/PermissionProviders/CollectionPermissionProvider.js +334 -47
  39. package/dist/custom/PermissionProviders/CollectionPermissionProvider.js.map +1 -1
  40. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts +28 -3
  41. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts.map +1 -1
  42. package/dist/custom/Permissions/BaseShareEntityExtended.js +150 -13
  43. package/dist/custom/Permissions/BaseShareEntityExtended.js.map +1 -1
  44. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts +8 -6
  45. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts.map +1 -1
  46. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js +107 -43
  47. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js.map +1 -1
  48. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts +13 -5
  49. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts.map +1 -1
  50. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js +284 -49
  51. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js.map +1 -1
  52. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.d.ts +3 -1
  53. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.d.ts.map +1 -1
  54. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.js +83 -19
  55. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.js.map +1 -1
  56. package/dist/custom/Permissions/shareNotification.d.ts +14 -1
  57. package/dist/custom/Permissions/shareNotification.d.ts.map +1 -1
  58. package/dist/custom/Permissions/shareNotification.js +62 -8
  59. package/dist/custom/Permissions/shareNotification.js.map +1 -1
  60. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.d.ts.map +1 -1
  61. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js +120 -38
  62. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js.map +1 -1
  63. package/dist/custom/SlideDeckEngine.d.ts +469 -0
  64. package/dist/custom/SlideDeckEngine.d.ts.map +1 -0
  65. package/dist/custom/SlideDeckEngine.js +2168 -0
  66. package/dist/custom/SlideDeckEngine.js.map +1 -0
  67. package/dist/custom/SlideDeckPptxEngine.d.ts +25 -0
  68. package/dist/custom/SlideDeckPptxEngine.d.ts.map +1 -0
  69. package/dist/custom/SlideDeckPptxEngine.js +1311 -0
  70. package/dist/custom/SlideDeckPptxEngine.js.map +1 -0
  71. package/dist/custom/SpreadsheetEngine.d.ts +1377 -0
  72. package/dist/custom/SpreadsheetEngine.d.ts.map +1 -0
  73. package/dist/custom/SpreadsheetEngine.js +17652 -0
  74. package/dist/custom/SpreadsheetEngine.js.map +1 -0
  75. package/dist/custom/approvals.d.ts +31 -1
  76. package/dist/custom/approvals.d.ts.map +1 -1
  77. package/dist/custom/approvals.js +42 -2
  78. package/dist/custom/approvals.js.map +1 -1
  79. package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts +7 -0
  80. package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts.map +1 -0
  81. package/dist/custom/operations/ArtifactComplianceAuditOperation.js +7 -0
  82. package/dist/custom/operations/ArtifactComplianceAuditOperation.js.map +1 -0
  83. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts +7 -0
  84. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts.map +1 -0
  85. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js +7 -0
  86. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js.map +1 -0
  87. package/dist/custom/operations/ArtifactGuestShareOperations.d.ts +60 -0
  88. package/dist/custom/operations/ArtifactGuestShareOperations.d.ts.map +1 -0
  89. package/dist/custom/operations/ArtifactGuestShareOperations.js +6 -0
  90. package/dist/custom/operations/ArtifactGuestShareOperations.js.map +1 -0
  91. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts +7 -0
  92. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts.map +1 -0
  93. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js +7 -0
  94. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js.map +1 -0
  95. package/dist/custom/typedQuery.d.ts +162 -0
  96. package/dist/custom/typedQuery.d.ts.map +1 -0
  97. package/dist/custom/typedQuery.js +296 -0
  98. package/dist/custom/typedQuery.js.map +1 -0
  99. package/dist/engines/CanonGraphEngine.d.ts +115 -2
  100. package/dist/engines/CanonGraphEngine.d.ts.map +1 -1
  101. package/dist/engines/CanonGraphEngine.js +259 -34
  102. package/dist/engines/CanonGraphEngine.js.map +1 -1
  103. package/dist/engines/EncryptionEngineBase.js +2 -2
  104. package/dist/engines/EncryptionEngineBase.js.map +1 -1
  105. package/dist/engines/QueryEngine.js +2 -2
  106. package/dist/engines/QueryEngine.js.map +1 -1
  107. package/dist/engines/SearchEngineBase.d.ts +17 -3
  108. package/dist/engines/SearchEngineBase.d.ts.map +1 -1
  109. package/dist/engines/SearchEngineBase.js +100 -28
  110. package/dist/engines/SearchEngineBase.js.map +1 -1
  111. package/dist/engines/UserInfoEngine.d.ts +8 -0
  112. package/dist/engines/UserInfoEngine.d.ts.map +1 -1
  113. package/dist/engines/UserInfoEngine.js +50 -3
  114. package/dist/engines/UserInfoEngine.js.map +1 -1
  115. package/dist/engines/conversations.d.ts +74 -6
  116. package/dist/engines/conversations.d.ts.map +1 -1
  117. package/dist/engines/conversations.js +205 -24
  118. package/dist/engines/conversations.js.map +1 -1
  119. package/dist/generated/entities/__mj.d.ts +25652 -43408
  120. package/dist/generated/entities/__mj.d.ts.map +1 -1
  121. package/dist/generated/entities/__mj.js +50800 -83602
  122. package/dist/generated/entities/__mj.js.map +1 -1
  123. package/dist/generated/queries/__mj.d.ts +12 -12
  124. package/dist/generated/queries/__mj.d.ts.map +1 -1
  125. package/dist/generated/queries/__mj.js +1 -1
  126. package/dist/generated/queries/__mj.js.map +1 -1
  127. package/dist/generated/remote_operations.d.ts +970 -65
  128. package/dist/generated/remote_operations.d.ts.map +1 -1
  129. package/dist/generated/remote_operations.js +343 -8
  130. package/dist/generated/remote_operations.js.map +1 -1
  131. package/dist/generated/schemas/__mj.d.ts +27415 -0
  132. package/dist/generated/schemas/__mj.d.ts.map +1 -0
  133. package/dist/generated/schemas/__mj.js +45127 -0
  134. package/dist/generated/schemas/__mj.js.map +1 -0
  135. package/dist/generated/schemas.d.ts +2 -0
  136. package/dist/generated/schemas.d.ts.map +1 -0
  137. package/dist/generated/schemas.js +2 -0
  138. package/dist/generated/schemas.js.map +1 -0
  139. package/dist/graph/BaseGraphEdgeProvider.d.ts +33 -1
  140. package/dist/graph/BaseGraphEdgeProvider.d.ts.map +1 -1
  141. package/dist/graph/BaseGraphEdgeProvider.js +18 -3
  142. package/dist/graph/BaseGraphEdgeProvider.js.map +1 -1
  143. package/dist/graph/CanonDocumentRenderer.d.ts +43 -0
  144. package/dist/graph/CanonDocumentRenderer.d.ts.map +1 -0
  145. package/dist/graph/CanonDocumentRenderer.js +627 -0
  146. package/dist/graph/CanonDocumentRenderer.js.map +1 -0
  147. package/dist/graph/DomainClustering.d.ts +88 -0
  148. package/dist/graph/DomainClustering.d.ts.map +1 -0
  149. package/dist/graph/DomainClustering.js +327 -0
  150. package/dist/graph/DomainClustering.js.map +1 -0
  151. package/dist/graph/DomainProposalWriter.d.ts +25 -0
  152. package/dist/graph/DomainProposalWriter.d.ts.map +1 -0
  153. package/dist/graph/DomainProposalWriter.js +107 -0
  154. package/dist/graph/DomainProposalWriter.js.map +1 -0
  155. package/dist/graph/GraphAccessPolicy.d.ts +111 -0
  156. package/dist/graph/GraphAccessPolicy.d.ts.map +1 -0
  157. package/dist/graph/GraphAccessPolicy.js +123 -0
  158. package/dist/graph/GraphAccessPolicy.js.map +1 -0
  159. package/dist/graph/GraphEngine.d.ts +115 -7
  160. package/dist/graph/GraphEngine.d.ts.map +1 -1
  161. package/dist/graph/GraphEngine.js +432 -36
  162. package/dist/graph/GraphEngine.js.map +1 -1
  163. package/dist/graph/RecordRelations.d.ts +52 -0
  164. package/dist/graph/RecordRelations.d.ts.map +1 -0
  165. package/dist/graph/RecordRelations.js +90 -0
  166. package/dist/graph/RecordRelations.js.map +1 -0
  167. package/dist/graph/index.d.ts +9 -1
  168. package/dist/graph/index.d.ts.map +1 -1
  169. package/dist/graph/index.js +13 -1
  170. package/dist/graph/index.js.map +1 -1
  171. package/dist/graph/policies/ProvenanceAccessPolicies.d.ts +56 -0
  172. package/dist/graph/policies/ProvenanceAccessPolicies.d.ts.map +1 -0
  173. package/dist/graph/policies/ProvenanceAccessPolicies.js +228 -0
  174. package/dist/graph/policies/ProvenanceAccessPolicies.js.map +1 -0
  175. package/dist/graph/providers/QueryEdgeProvider.d.ts.map +1 -1
  176. package/dist/graph/providers/QueryEdgeProvider.js +2 -2
  177. package/dist/graph/providers/QueryEdgeProvider.js.map +1 -1
  178. package/dist/graph/providers/RecordLinkEdgeProvider.d.ts.map +1 -1
  179. package/dist/graph/providers/RecordLinkEdgeProvider.js +2 -2
  180. package/dist/graph/providers/RecordLinkEdgeProvider.js.map +1 -1
  181. package/dist/graph/providers/SharedConceptEdgeProvider.d.ts +54 -0
  182. package/dist/graph/providers/SharedConceptEdgeProvider.d.ts.map +1 -0
  183. package/dist/graph/providers/SharedConceptEdgeProvider.js +282 -0
  184. package/dist/graph/providers/SharedConceptEdgeProvider.js.map +1 -0
  185. package/dist/index.d.ts +12 -0
  186. package/dist/index.d.ts.map +1 -1
  187. package/dist/index.js +18 -0
  188. package/dist/index.js.map +1 -1
  189. package/dist/schemas.d.ts +6 -0
  190. package/dist/schemas.d.ts.map +1 -0
  191. package/dist/schemas.js +6 -0
  192. package/dist/schemas.js.map +1 -0
  193. package/package.json +17 -6
@@ -0,0 +1,2352 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { LogError, Metadata, ProjectEntityValueRowsForUser, RunQuery, RunView, StripServerOnlyRunQueryParams } from '@memberjunction/core';
8
+ import { BaseSingleton, EscapeSQLString, IndexByUUID, MJGlobal, NormalizeUUID, RegisterClass, UUIDsEqual } from '@memberjunction/global';
9
+ import { ArtifactPermissionEngine } from './ArtifactPermissionDelegate.js';
10
+ import { QueryEngine } from '../engines/QueryEngine.js';
11
+ /**
12
+ * Normalizes a {@link FrozenSnapshotIdentityBinding} for deterministic HMAC hashing and comparison.
13
+ */
14
+ export function NormalizeFrozenSnapshotIdentityBinding(binding) {
15
+ if (!binding || typeof binding !== 'object') {
16
+ return undefined;
17
+ }
18
+ const out = {};
19
+ if (typeof binding.ArtifactID === 'string' && binding.ArtifactID.trim().length > 0) {
20
+ out.ArtifactID = NormalizeUUID(binding.ArtifactID);
21
+ }
22
+ if (typeof binding.BlockID === 'string' && binding.BlockID.trim().length > 0) {
23
+ out.BlockID = binding.BlockID.trim();
24
+ }
25
+ if (typeof binding.Kind === 'string' && binding.Kind.trim().length > 0) {
26
+ out.Kind = binding.Kind.trim();
27
+ }
28
+ if (typeof binding.SourceTargetID === 'string' && binding.SourceTargetID.trim().length > 0) {
29
+ out.SourceTargetID = NormalizeUUID(binding.SourceTargetID);
30
+ }
31
+ return Object.keys(out).length > 0 ? out : undefined;
32
+ }
33
+ /**
34
+ * Builds the canonical {@link FrozenSnapshotIdentityBinding} for a {@link DocumentBlockSpec} (`S3`).
35
+ */
36
+ export function BuildBlockIdentityBinding(spec, hostArtifactId) {
37
+ let sourceTargetId;
38
+ switch (spec.Kind) {
39
+ case 'SavedQuery':
40
+ sourceTargetId = spec.QueryID?.trim() || spec.QueryName?.trim() || undefined;
41
+ break;
42
+ case 'EntityView':
43
+ sourceTargetId = spec.ViewID?.trim() || spec.EntityName?.trim() || spec.ViewName?.trim() || undefined;
44
+ break;
45
+ case 'DashboardPart':
46
+ sourceTargetId = spec.DashboardID?.trim() || spec.DashboardName?.trim() || undefined;
47
+ break;
48
+ case 'InteractiveComponent':
49
+ sourceTargetId = spec.ComponentID?.trim() || spec.ComponentName?.trim() || undefined;
50
+ break;
51
+ case 'Artifact':
52
+ sourceTargetId = spec.ArtifactID?.trim() || undefined;
53
+ break;
54
+ }
55
+ return NormalizeFrozenSnapshotIdentityBinding({
56
+ ...(hostArtifactId && hostArtifactId.trim().length > 0 ? { ArtifactID: hostArtifactId } : {}),
57
+ BlockID: spec.BlockID,
58
+ Kind: spec.Kind,
59
+ ...(sourceTargetId ? { SourceTargetID: sourceTargetId } : {})
60
+ }) ?? {};
61
+ }
62
+ /**
63
+ * Base class for pluggable block handlers registered via `@RegisterClass(BaseDocumentBlock, '<Kind>')`.
64
+ */
65
+ export class BaseDocumentBlock {
66
+ }
67
+ /**
68
+ * Handler for `Kind === 'EntityView'` live blocks.
69
+ * Enforces entity `CanRead`, Row-Level Security (via `RunView`), and Field-Level Security
70
+ * (via `ProjectEntityValueRowsForUser` + column header filtering).
71
+ */
72
+ let EntityViewDocumentBlock = class EntityViewDocumentBlock extends BaseDocumentBlock {
73
+ constructor() {
74
+ super(...arguments);
75
+ this.Kind = 'EntityView';
76
+ }
77
+ ValidateSpec(spec) {
78
+ if (!spec.EntityName && !spec.ViewID && !spec.ViewName) {
79
+ return {
80
+ Valid: false,
81
+ ErrorMessage: 'EntityView block requires at least one of EntityName, ViewID, or ViewName.'
82
+ };
83
+ }
84
+ return { Valid: true };
85
+ }
86
+ async Execute(spec, provider, user) {
87
+ if (spec.Mode === 'Frozen') {
88
+ return buildFrozenExecutionResult(spec);
89
+ }
90
+ const validation = this.ValidateSpec(spec);
91
+ if (!validation.Valid) {
92
+ return buildErrorResult(spec, validation.ErrorMessage ?? 'Invalid EntityView specification.');
93
+ }
94
+ let targetEntityName = (spec.EntityName ?? '').trim();
95
+ let resolvedViewId = spec.ViewID;
96
+ const rv = RunView.FromMetadataProvider(provider);
97
+ // If ViewID or ViewName is provided without EntityName, look up the UserView's Entity first.
98
+ if (!targetEntityName && (spec.ViewID || spec.ViewName)) {
99
+ const viewFilter = spec.ViewID
100
+ ? `ID='${EscapeSQLString(spec.ViewID)}'`
101
+ : `Name='${EscapeSQLString(spec.ViewName ?? '')}'`;
102
+ const viewLookup = await rv.RunView({
103
+ EntityName: 'MJ: User Views',
104
+ ExtraFilter: viewFilter,
105
+ Fields: ['ID', 'Entity', 'EntityID'],
106
+ MaxRows: 1,
107
+ SkipTotalRowCount: true,
108
+ ResultType: 'simple'
109
+ }, user);
110
+ if (viewLookup.Success && viewLookup.Results && viewLookup.Results.length > 0) {
111
+ const matchedView = viewLookup.Results[0];
112
+ targetEntityName = (matchedView.Entity ?? '').trim();
113
+ if (!targetEntityName && matchedView.EntityID) {
114
+ const matchedEntity = provider.EntityByID(matchedView.EntityID);
115
+ if (matchedEntity) {
116
+ targetEntityName = matchedEntity.Name;
117
+ }
118
+ }
119
+ if (!resolvedViewId && matchedView.ID) {
120
+ resolvedViewId = matchedView.ID;
121
+ }
122
+ }
123
+ }
124
+ const entityInfo = targetEntityName ? provider.EntityByName(targetEntityName) : undefined;
125
+ if (!entityInfo) {
126
+ return buildErrorResult(spec, `Entity '${targetEntityName || spec.ViewName || spec.ViewID}' was not found.`);
127
+ }
128
+ const perms = entityInfo.GetUserPermisions(user);
129
+ if (!perms?.CanRead) {
130
+ return {
131
+ BlockID: spec.BlockID,
132
+ Kind: spec.Kind,
133
+ Mode: 'Live',
134
+ Success: false,
135
+ AccessDenied: true,
136
+ ErrorMessage: `You do not have permission to read ${entityInfo.DisplayNameOrName} records.`,
137
+ Columns: [],
138
+ Rows: [],
139
+ TotalRowCount: 0
140
+ };
141
+ }
142
+ // Determine allowed fields after FLS denied-read filtering
143
+ // fls-guard: filter EntityView live block columns and rows using GetDeniedReadFields + ProjectEntityValueRowsForUser
144
+ const deniedFields = entityInfo.FieldLevelSecurityApplies
145
+ ? new Set(Array.from(entityInfo.GetDeniedReadFields(user)).map((f) => f.trim().toLowerCase()))
146
+ : new Set();
147
+ if (typeof spec.OrderBy === 'string' && spec.OrderBy.trim().length > 0) {
148
+ const orderCheck = validateEntityViewOrderBy(spec.OrderBy, entityInfo, deniedFields);
149
+ if (!orderCheck.Valid) {
150
+ return {
151
+ BlockID: spec.BlockID,
152
+ Kind: spec.Kind,
153
+ Mode: 'Live',
154
+ Success: false,
155
+ AccessDenied: true,
156
+ ErrorMessage: orderCheck.ErrorMessage ?? 'Invalid or unauthorized OrderBy expression.',
157
+ Columns: [],
158
+ Rows: [],
159
+ TotalRowCount: 0
160
+ };
161
+ }
162
+ }
163
+ if (typeof spec.ExtraFilter === 'string' && spec.ExtraFilter.trim().length > 0) {
164
+ const filterCheck = validateEntityViewExtraFilter(spec.ExtraFilter, entityInfo, deniedFields);
165
+ if (!filterCheck.Valid) {
166
+ return {
167
+ BlockID: spec.BlockID,
168
+ Kind: spec.Kind,
169
+ Mode: 'Live',
170
+ Success: false,
171
+ AccessDenied: true,
172
+ ErrorMessage: filterCheck.ErrorMessage ?? 'Invalid or unauthorized ExtraFilter expression.',
173
+ Columns: [],
174
+ Rows: [],
175
+ TotalRowCount: 0
176
+ };
177
+ }
178
+ }
179
+ let requestedFields = [];
180
+ if (Array.isArray(spec.Fields) && spec.Fields.length > 0) {
181
+ requestedFields = spec.Fields;
182
+ }
183
+ else {
184
+ const defaultInView = entityInfo.Fields.filter((f) => f.DefaultInView && !f.IsBinaryFieldType);
185
+ if (defaultInView.length > 0) {
186
+ requestedFields = defaultInView.slice(0, 12).map((f) => f.Name);
187
+ }
188
+ else {
189
+ const nonSystemFields = entityInfo.Fields.filter((f) => !f.IsBinaryFieldType && !f.Name.startsWith('__mj_') && f.Name !== 'ID');
190
+ requestedFields = (nonSystemFields.length > 0 ? nonSystemFields : entityInfo.Fields.filter((f) => !f.IsBinaryFieldType))
191
+ .slice(0, 8)
192
+ .map((f) => f.Name);
193
+ }
194
+ }
195
+ const visibleFieldNames = requestedFields.filter((f) => !deniedFields.has(f.trim().toLowerCase()));
196
+ // Ensure Primary Key and companion FK ID columns are fetched so PK/FK cells are linkable
197
+ const primaryKeys = entityInfo.PrimaryKeys ?? [];
198
+ const singlePkFieldName = primaryKeys.length === 1 ? entityInfo.FirstPrimaryKey?.Name : primaryKeys.length === 0 ? 'ID' : undefined; // first-pk-ok: guarded by primaryKeys.length === 1
199
+ const pkFieldNames = primaryKeys.length > 0 ? primaryKeys.map((pk) => pk.Name) : ['ID'];
200
+ const fetchFieldSet = new Set(visibleFieldNames);
201
+ for (const pkName of pkFieldNames) {
202
+ if (!deniedFields.has(pkName.trim().toLowerCase())) {
203
+ fetchFieldSet.add(pkName);
204
+ }
205
+ }
206
+ for (const fName of visibleFieldNames) {
207
+ const companionFk = entityInfo.Fields.find((f) => f.Name.trim().toLowerCase() === `${fName.trim().toLowerCase()}id` && Boolean(f.RelatedEntity));
208
+ if (companionFk && !deniedFields.has(companionFk.Name.trim().toLowerCase())) {
209
+ fetchFieldSet.add(companionFk.Name);
210
+ }
211
+ }
212
+ const fetchFields = Array.from(fetchFieldSet);
213
+ const runParams = {
214
+ EntityName: entityInfo.Name,
215
+ ViewID: resolvedViewId,
216
+ ViewName: spec.ViewName,
217
+ ExtraFilter: spec.ExtraFilter,
218
+ OrderBy: spec.OrderBy,
219
+ Fields: fetchFields.length > 0 ? fetchFields : undefined,
220
+ MaxRows: clampBlockMaxRows(spec.MaxRows),
221
+ ResultType: 'simple'
222
+ };
223
+ const viewResult = await rv.RunView(runParams, user);
224
+ if (!viewResult.Success) {
225
+ return buildErrorResult(spec, viewResult.ErrorMessage || `Failed to run view on ${entityInfo.Name}.`);
226
+ }
227
+ const rawRows = viewResult.Results ?? [];
228
+ // fls-guard: project EntityView live block rows for viewer FLS
229
+ const projectedRows = (ProjectEntityValueRowsForUser(provider, entityInfo, rawRows, user) ?? []);
230
+ const columns = visibleFieldNames.map((fieldName) => {
231
+ const fInfo = entityInfo.Fields.find((f) => f.Name.trim().toLowerCase() === fieldName.trim().toLowerCase());
232
+ const isPk = Boolean(fInfo?.IsPrimaryKey) ||
233
+ Boolean(singlePkFieldName && fieldName.trim().toLowerCase() === singlePkFieldName.toLowerCase());
234
+ const isNameField = Boolean(fInfo?.IsNameField) || fieldName.trim().toLowerCase() === 'name';
235
+ const directFkEntity = fInfo?.RelatedEntity ? fInfo.RelatedEntity : undefined;
236
+ const companionFkField = !directFkEntity
237
+ ? entityInfo.Fields.find((f) => f.Name.trim().toLowerCase() === `${fieldName.trim().toLowerCase()}id` &&
238
+ Boolean(f.RelatedEntity))
239
+ : undefined;
240
+ const isFk = Boolean(directFkEntity || companionFkField?.RelatedEntity);
241
+ const targetEntityName = isFk
242
+ ? directFkEntity || companionFkField?.RelatedEntity
243
+ : (isPk || isNameField) && singlePkFieldName
244
+ ? entityInfo.Name
245
+ : undefined;
246
+ const recordIdFieldName = isFk
247
+ ? fInfo?.Name && directFkEntity
248
+ ? fInfo.Name
249
+ : companionFkField?.Name
250
+ : isPk || isNameField
251
+ ? singlePkFieldName
252
+ : undefined;
253
+ return {
254
+ Name: fInfo?.Name ?? fieldName,
255
+ DisplayName: fInfo?.DisplayNameOrName ?? fieldName,
256
+ Type: fInfo?.TSType?.toLowerCase() ?? 'string',
257
+ IsPrimaryKey: isPk || undefined,
258
+ IsNameField: isNameField || undefined,
259
+ IsForeignKey: isFk || undefined,
260
+ TargetEntityName: targetEntityName,
261
+ RecordIDFieldName: recordIdFieldName,
262
+ TargetEntityIcon: entityInfo.Icon || undefined
263
+ };
264
+ });
265
+ return {
266
+ BlockID: spec.BlockID,
267
+ Kind: spec.Kind,
268
+ Mode: 'Live',
269
+ Success: true,
270
+ Columns: columns,
271
+ Rows: projectedRows,
272
+ TotalRowCount: viewResult.TotalRowCount ?? projectedRows.length
273
+ };
274
+ }
275
+ };
276
+ EntityViewDocumentBlock = __decorate([
277
+ RegisterClass(BaseDocumentBlock, 'EntityView')
278
+ ], EntityViewDocumentBlock);
279
+ export { EntityViewDocumentBlock };
280
+ /**
281
+ * Handler for `Kind === 'SavedQuery'` live blocks.
282
+ * Enforces query execution permissions, strips `SERVER_ONLY_RUN_QUERY_PARAMS` and any parameter
283
+ * marked `IsServerSet === true` on `MJ: Query Parameters`, and applies FLS output projection
284
+ * across any entities referenced by the query (its `QueryEntities` rows).
285
+ */
286
+ let SavedQueryDocumentBlock = class SavedQueryDocumentBlock extends BaseDocumentBlock {
287
+ constructor() {
288
+ super(...arguments);
289
+ this.Kind = 'SavedQuery';
290
+ }
291
+ ValidateSpec(spec) {
292
+ if (!spec.QueryID && !spec.QueryName) {
293
+ return {
294
+ Valid: false,
295
+ ErrorMessage: 'SavedQuery block requires either QueryID or QueryName.'
296
+ };
297
+ }
298
+ return { Valid: true };
299
+ }
300
+ async Execute(spec, provider, user, serverParameters) {
301
+ if (spec.Mode === 'Frozen') {
302
+ return buildFrozenExecutionResult(spec);
303
+ }
304
+ const validation = this.ValidateSpec(spec);
305
+ if (!validation.Valid) {
306
+ return buildErrorResult(spec, validation.ErrorMessage ?? 'Invalid SavedQuery specification.');
307
+ }
308
+ const queryInfo = await resolveSavedQuery(provider, user, spec.QueryID, spec.QueryName, spec.CategoryPath);
309
+ if (!queryInfo) {
310
+ return {
311
+ BlockID: spec.BlockID,
312
+ Kind: spec.Kind,
313
+ Mode: 'Live',
314
+ Success: false,
315
+ AccessDenied: true,
316
+ ErrorMessage: 'SavedQuery was not found or access is denied.',
317
+ Columns: [],
318
+ Rows: [],
319
+ TotalRowCount: 0
320
+ };
321
+ }
322
+ if (!queryInfo.UserCanRun(user).canRun) {
323
+ return {
324
+ BlockID: spec.BlockID,
325
+ Kind: spec.Kind,
326
+ Mode: 'Live',
327
+ Success: false,
328
+ AccessDenied: true,
329
+ ErrorMessage: `You do not have permission to run query '${queryInfo.Name}'.`,
330
+ Columns: [],
331
+ Rows: [],
332
+ TotalRowCount: 0
333
+ };
334
+ }
335
+ const { cleanParameters, strippedNames } = sanitizeClientQueryParameters(queryInfo, spec.Parameters);
336
+ const baseRunParams = StripServerOnlyRunQueryParams({
337
+ QueryID: queryInfo.ID,
338
+ Parameters: cleanParameters,
339
+ MaxRows: clampBlockMaxRows(spec.MaxRows)
340
+ });
341
+ const finalRunParams = serverParameters && Object.keys(serverParameters).length > 0
342
+ ? { ...baseRunParams, ServerParameters: serverParameters }
343
+ : baseRunParams;
344
+ const rq = new RunQuery(resolveRunQueryProvider(provider));
345
+ const queryResult = await rq.RunQuery(finalRunParams, user);
346
+ if (!queryResult.Success) {
347
+ return {
348
+ BlockID: spec.BlockID,
349
+ Kind: spec.Kind,
350
+ Mode: 'Live',
351
+ Success: false,
352
+ ErrorMessage: queryResult.ErrorMessage || 'SavedQuery execution failed.',
353
+ Columns: [],
354
+ Rows: [],
355
+ TotalRowCount: 0,
356
+ StrippedServerSetParameters: strippedNames
357
+ };
358
+ }
359
+ let rows = (queryResult.Results ?? []);
360
+ // Apply FLS output projection for every entity referenced by the query
361
+ const referencedEntities = resolveReferencedEntitiesForQuery(provider, queryInfo);
362
+ const deniedColumnNames = new Set();
363
+ for (const entityInfo of referencedEntities) {
364
+ // fls-guard: project SavedQuery live block rows against referenced entity FLS
365
+ if (entityInfo.FieldLevelSecurityApplies) {
366
+ for (const denied of entityInfo.GetDeniedReadFields(user)) {
367
+ deniedColumnNames.add(denied.trim().toLowerCase());
368
+ }
369
+ rows = (ProjectEntityValueRowsForUser(provider, entityInfo, rows, user) ?? []);
370
+ }
371
+ }
372
+ if (deniedColumnNames.size > 0) {
373
+ rows = rows.map((row) => {
374
+ const filteredRow = {};
375
+ for (const [k, v] of Object.entries(row)) {
376
+ if (!deniedColumnNames.has(k.trim().toLowerCase())) {
377
+ filteredRow[k] = v;
378
+ }
379
+ }
380
+ return filteredRow;
381
+ });
382
+ }
383
+ const firstRow = rows[0] ?? {};
384
+ const columnKeys = Object.keys(firstRow).filter((k) => !deniedColumnNames.has(k.trim().toLowerCase()));
385
+ const primaryQueryEntity = referencedEntities[0];
386
+ const hasIdCol = columnKeys.some((k) => k.trim().toLowerCase() === 'id');
387
+ const columns = columnKeys.map((key) => {
388
+ const lowerKey = key.trim().toLowerCase();
389
+ let isPk = false;
390
+ let isName = false;
391
+ let isFk = false;
392
+ let targetEntityName;
393
+ let recordIdFieldName;
394
+ if (primaryQueryEntity) {
395
+ const matchField = primaryQueryEntity.Fields.find((f) => f.Name.trim().toLowerCase() === lowerKey);
396
+ if (matchField?.IsPrimaryKey || lowerKey === 'id') {
397
+ isPk = true;
398
+ targetEntityName = primaryQueryEntity.Name;
399
+ recordIdFieldName = key;
400
+ }
401
+ else if ((matchField?.IsNameField || lowerKey === 'name') && hasIdCol) {
402
+ isName = true;
403
+ targetEntityName = primaryQueryEntity.Name;
404
+ recordIdFieldName = columnKeys.find((k) => k.trim().toLowerCase() === 'id') ?? 'ID';
405
+ }
406
+ else if (matchField?.RelatedEntity) {
407
+ isFk = true;
408
+ targetEntityName = matchField.RelatedEntity;
409
+ recordIdFieldName = key;
410
+ }
411
+ else {
412
+ const companionFk = primaryQueryEntity.Fields.find((f) => f.Name.trim().toLowerCase() === `${lowerKey}id` && Boolean(f.RelatedEntity));
413
+ const companionColKey = companionFk
414
+ ? columnKeys.find((k) => k.trim().toLowerCase() === companionFk.Name.trim().toLowerCase())
415
+ : undefined;
416
+ if (companionFk?.RelatedEntity && companionColKey) {
417
+ isFk = true;
418
+ targetEntityName = companionFk.RelatedEntity;
419
+ recordIdFieldName = companionColKey;
420
+ }
421
+ }
422
+ }
423
+ return {
424
+ Name: key,
425
+ DisplayName: key,
426
+ Type: typeof firstRow[key] === 'number'
427
+ ? 'number'
428
+ : typeof firstRow[key] === 'boolean'
429
+ ? 'boolean'
430
+ : 'string',
431
+ IsPrimaryKey: isPk || undefined,
432
+ IsNameField: isName || undefined,
433
+ IsForeignKey: isFk || undefined,
434
+ TargetEntityName: targetEntityName,
435
+ RecordIDFieldName: recordIdFieldName
436
+ };
437
+ });
438
+ return {
439
+ BlockID: spec.BlockID,
440
+ Kind: spec.Kind,
441
+ Mode: 'Live',
442
+ Success: true,
443
+ Columns: columns,
444
+ Rows: rows,
445
+ TotalRowCount: queryResult.TotalRowCount ?? rows.length,
446
+ StrippedServerSetParameters: strippedNames
447
+ };
448
+ }
449
+ };
450
+ SavedQueryDocumentBlock = __decorate([
451
+ RegisterClass(BaseDocumentBlock, 'SavedQuery')
452
+ ], SavedQueryDocumentBlock);
453
+ export { SavedQueryDocumentBlock };
454
+ /**
455
+ * Handler for `Kind === 'DashboardPart'` blocks.
456
+ */
457
+ let DashboardPartDocumentBlock = class DashboardPartDocumentBlock extends BaseDocumentBlock {
458
+ constructor() {
459
+ super(...arguments);
460
+ this.Kind = 'DashboardPart';
461
+ }
462
+ ValidateSpec(spec) {
463
+ if (!spec.DashboardID && !spec.DashboardName) {
464
+ return { Valid: false, ErrorMessage: 'DashboardPart block requires DashboardID or DashboardName.' };
465
+ }
466
+ return { Valid: true };
467
+ }
468
+ async Execute(spec, provider, user) {
469
+ if (spec.Mode === 'Frozen') {
470
+ return buildFrozenExecutionResult(spec);
471
+ }
472
+ const validation = this.ValidateSpec(spec);
473
+ if (!validation.Valid) {
474
+ return buildErrorResult(spec, validation.ErrorMessage ?? 'Invalid DashboardPart specification.');
475
+ }
476
+ const rv = RunView.FromMetadataProvider(provider);
477
+ const filter = spec.DashboardID
478
+ ? `ID='${EscapeSQLString(spec.DashboardID)}'`
479
+ : `Name='${EscapeSQLString(spec.DashboardName ?? '')}'`;
480
+ const res = await rv.RunView({
481
+ EntityName: 'MJ: Dashboards',
482
+ ExtraFilter: filter,
483
+ Fields: ['ID', 'Name', 'Description'],
484
+ MaxRows: 1,
485
+ SkipTotalRowCount: true,
486
+ ResultType: 'simple'
487
+ }, user);
488
+ if (!res.Success || !res.Results || res.Results.length === 0) {
489
+ return {
490
+ BlockID: spec.BlockID,
491
+ Kind: spec.Kind,
492
+ Mode: 'Live',
493
+ Success: false,
494
+ AccessDenied: true,
495
+ ErrorMessage: 'Dashboard not found or access denied.',
496
+ Columns: [],
497
+ Rows: [],
498
+ TotalRowCount: 0
499
+ };
500
+ }
501
+ const dash = res.Results[0];
502
+ return {
503
+ BlockID: spec.BlockID,
504
+ Kind: spec.Kind,
505
+ Mode: 'Live',
506
+ Success: true,
507
+ Columns: [
508
+ { Name: 'ID', DisplayName: 'Dashboard ID' },
509
+ { Name: 'Name', DisplayName: 'Dashboard Name' },
510
+ { Name: 'PartID', DisplayName: 'Part ID' }
511
+ ],
512
+ Rows: [{ ID: dash.ID, Name: dash.Name, PartID: spec.DashboardPartID ?? 'default' }],
513
+ TotalRowCount: 1
514
+ };
515
+ }
516
+ };
517
+ DashboardPartDocumentBlock = __decorate([
518
+ RegisterClass(BaseDocumentBlock, 'DashboardPart')
519
+ ], DashboardPartDocumentBlock);
520
+ export { DashboardPartDocumentBlock };
521
+ /**
522
+ * Handler for `Kind === 'InteractiveComponent'` blocks.
523
+ */
524
+ let InteractiveComponentDocumentBlock = class InteractiveComponentDocumentBlock extends BaseDocumentBlock {
525
+ constructor() {
526
+ super(...arguments);
527
+ this.Kind = 'InteractiveComponent';
528
+ }
529
+ ValidateSpec(spec) {
530
+ if (!spec.ComponentID && !spec.ComponentName && !spec.ComponentSpec) {
531
+ return {
532
+ Valid: false,
533
+ ErrorMessage: 'InteractiveComponent block requires ComponentID, ComponentName, or ComponentSpec.'
534
+ };
535
+ }
536
+ return { Valid: true };
537
+ }
538
+ async Execute(spec, provider, user) {
539
+ if (spec.Mode === 'Frozen') {
540
+ return buildFrozenExecutionResult(spec);
541
+ }
542
+ const validation = this.ValidateSpec(spec);
543
+ if (!validation.Valid) {
544
+ return buildErrorResult(spec, validation.ErrorMessage ?? 'Invalid InteractiveComponent specification.');
545
+ }
546
+ const compEntity = provider.EntityByName('MJ: Components');
547
+ if (compEntity) {
548
+ const perms = compEntity.GetUserPermisions(user);
549
+ if (!perms?.CanRead) {
550
+ return {
551
+ BlockID: spec.BlockID,
552
+ Kind: spec.Kind,
553
+ Mode: 'Live',
554
+ Success: false,
555
+ AccessDenied: true,
556
+ ErrorMessage: 'You do not have permission to access MJ: Components.',
557
+ Columns: [],
558
+ Rows: [],
559
+ TotalRowCount: 0
560
+ };
561
+ }
562
+ }
563
+ let resolvedComponentId = spec.ComponentID ?? null;
564
+ let resolvedComponentName = spec.ComponentName ?? 'Interactive Component';
565
+ if (spec.ComponentID || spec.ComponentName) {
566
+ const rv = RunView.FromMetadataProvider(provider);
567
+ const filter = spec.ComponentID
568
+ ? `ID='${EscapeSQLString(spec.ComponentID)}'`
569
+ : `Name='${EscapeSQLString(spec.ComponentName)}'`;
570
+ const compResult = await rv.RunView({
571
+ EntityName: 'MJ: Components',
572
+ ExtraFilter: filter,
573
+ Fields: ['ID', 'Name'],
574
+ MaxRows: 1,
575
+ SkipTotalRowCount: true,
576
+ ResultType: 'simple'
577
+ }, user);
578
+ const matchedComp = compResult.Success ? compResult.Results?.[0] : undefined;
579
+ if (!compResult.Success || !matchedComp) {
580
+ return {
581
+ BlockID: spec.BlockID,
582
+ Kind: spec.Kind,
583
+ Mode: 'Live',
584
+ Success: false,
585
+ AccessDenied: true,
586
+ ErrorMessage: `Interactive component '${spec.ComponentName || spec.ComponentID}' was not found or access is denied.`,
587
+ Columns: [],
588
+ Rows: [],
589
+ TotalRowCount: 0
590
+ };
591
+ }
592
+ resolvedComponentId = matchedComp.ID;
593
+ resolvedComponentName = matchedComp.Name ?? resolvedComponentName;
594
+ }
595
+ return {
596
+ BlockID: spec.BlockID,
597
+ Kind: spec.Kind,
598
+ Mode: 'Live',
599
+ Success: true,
600
+ Columns: [{ Name: 'ComponentName', DisplayName: 'Component' }],
601
+ Rows: [{ ComponentID: resolvedComponentId, ComponentName: resolvedComponentName }],
602
+ TotalRowCount: 1
603
+ };
604
+ }
605
+ };
606
+ InteractiveComponentDocumentBlock = __decorate([
607
+ RegisterClass(BaseDocumentBlock, 'InteractiveComponent')
608
+ ], InteractiveComponentDocumentBlock);
609
+ export { InteractiveComponentDocumentBlock };
610
+ /**
611
+ * Handler for `Kind === 'Artifact'` ("MS OLE" Inline Artifact Blocks, § 3.4.1).
612
+ * Evaluates viewer permissions on the target artifact via {@link ArtifactPermissionEngine}
613
+ * (including parent-artifact delegation for inline Whiteboards) and loads the pinned or latest
614
+ * `MJ: Artifact Versions` payload.
615
+ */
616
+ let ArtifactDocumentBlock = class ArtifactDocumentBlock extends BaseDocumentBlock {
617
+ constructor() {
618
+ super(...arguments);
619
+ this.Kind = 'Artifact';
620
+ }
621
+ ValidateSpec(spec) {
622
+ if (!spec.ArtifactID) {
623
+ return { Valid: false, ErrorMessage: 'Artifact block requires an ArtifactID.' };
624
+ }
625
+ return { Valid: true };
626
+ }
627
+ async Execute(spec, provider, user) {
628
+ if (spec.Mode === 'Frozen') {
629
+ return buildFrozenExecutionResult(spec);
630
+ }
631
+ const validation = this.ValidateSpec(spec);
632
+ if (!validation.Valid) {
633
+ return buildErrorResult(spec, validation.ErrorMessage ?? 'Invalid Artifact block specification.');
634
+ }
635
+ const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(provider, spec.ArtifactID, user);
636
+ if (!perms.CanRead) {
637
+ return {
638
+ BlockID: spec.BlockID,
639
+ Kind: spec.Kind,
640
+ Mode: 'Live',
641
+ Success: false,
642
+ AccessDenied: true,
643
+ ErrorMessage: perms.Reason || 'You do not have permission to view this embedded artifact.',
644
+ Columns: [],
645
+ Rows: [],
646
+ TotalRowCount: 0
647
+ };
648
+ }
649
+ const rv = RunView.FromMetadataProvider(provider);
650
+ const safeArtifactId = EscapeSQLString(spec.ArtifactID);
651
+ const versionFilter = spec.VersionID
652
+ ? `ArtifactID='${safeArtifactId}' AND ID='${EscapeSQLString(spec.VersionID)}'`
653
+ : `ArtifactID='${safeArtifactId}'`;
654
+ const [artifactRes, versionRes] = await rv.RunViews([
655
+ {
656
+ EntityName: 'MJ: Artifacts',
657
+ ExtraFilter: `ID='${safeArtifactId}'`,
658
+ Fields: ['ID', 'Name', 'Type'],
659
+ MaxRows: 1,
660
+ SkipTotalRowCount: true,
661
+ ResultType: 'simple'
662
+ },
663
+ {
664
+ EntityName: 'MJ: Artifact Versions',
665
+ ExtraFilter: versionFilter,
666
+ OrderBy: 'VersionNumber DESC',
667
+ Fields: ['ID', 'ArtifactID', 'VersionNumber', 'ContentMode', 'FileID', 'Content', 'Configuration'],
668
+ MaxRows: 1,
669
+ SkipTotalRowCount: true,
670
+ ResultType: 'simple'
671
+ }
672
+ ], user);
673
+ const artifactRow = artifactRes.Results?.[0] ?? null;
674
+ const versionRow = versionRes.Results?.[0] ?? null;
675
+ if (!artifactRow) {
676
+ return buildErrorResult(spec, `Embedded artifact '${spec.ArtifactID}' was not found.`);
677
+ }
678
+ const resolvedType = artifactRow.Type || spec.ArtifactType || '';
679
+ let resolvedContent = versionRow?.Content ?? '';
680
+ let skipChartReEvaluate = false;
681
+ if (versionRow?.ContentMode === 'File' && !resolvedContent) {
682
+ const fileBytes = versionRow.FileID
683
+ ? await DocumentLiveBlockEngine.Instance.LoadArtifactFileBytes(versionRow.FileID, user, provider)
684
+ : null;
685
+ if (fileBytes) {
686
+ if (spec.SheetChartID || spec.SheetRange) {
687
+ const dataset = await DocumentLiveBlockEngine.Instance.ExtractSpreadsheetXlsxChartDatasetAsync(fileBytes, versionRow.Configuration ?? null, spec.SheetID, spec.SheetChartID, spec.SheetRange);
688
+ if (!dataset) {
689
+ return buildErrorResult(spec, `Requested spreadsheet chart or range (${spec.SheetChartID || spec.SheetRange}) could not be extracted from File-backed workbook.`);
690
+ }
691
+ const slicedPayload = JSON.stringify({
692
+ Kind: 'SpreadsheetSlice',
693
+ SheetID: spec.SheetID ?? null,
694
+ ChartID: spec.SheetChartID ?? null,
695
+ Range: spec.SheetRange ?? null,
696
+ Columns: dataset.Columns,
697
+ Rows: dataset.Rows
698
+ });
699
+ return {
700
+ BlockID: spec.BlockID,
701
+ Kind: spec.Kind,
702
+ Mode: 'Live',
703
+ Success: true,
704
+ Columns: dataset.Columns,
705
+ Rows: dataset.Rows,
706
+ TotalRowCount: dataset.Rows.length,
707
+ ArtifactContent: slicedPayload,
708
+ ArtifactType: resolvedType,
709
+ ArtifactName: artifactRow.Name,
710
+ ArtifactVersionNumber: versionRow.VersionNumber ?? 1,
711
+ CanEditArtifact: perms.CanEdit && !spec.VersionID
712
+ };
713
+ }
714
+ const materializedJson = await DocumentLiveBlockEngine.Instance.ExtractSpreadsheetXlsxWorkbookJsonAsync(fileBytes, versionRow.Configuration ?? null);
715
+ if (materializedJson) {
716
+ resolvedContent = materializedJson;
717
+ skipChartReEvaluate = true;
718
+ }
719
+ }
720
+ if (!resolvedContent) {
721
+ return {
722
+ BlockID: spec.BlockID,
723
+ Kind: spec.Kind,
724
+ Mode: 'Live',
725
+ Success: false,
726
+ ErrorMessage: 'File-backed artifact versions (ContentMode=File) cannot be embedded or sliced inline without materialized content.',
727
+ Columns: [],
728
+ Rows: [],
729
+ TotalRowCount: 0,
730
+ ArtifactType: resolvedType,
731
+ ArtifactName: artifactRow.Name,
732
+ ArtifactVersionNumber: versionRow.VersionNumber ?? 1,
733
+ CanEditArtifact: perms.CanEdit && !spec.VersionID
734
+ };
735
+ }
736
+ }
737
+ if (spec.SheetChartID || spec.SheetRange) {
738
+ const dataset = await DocumentLiveBlockEngine.Instance.ExtractSpreadsheetChartDatasetAsync(resolvedContent, versionRow?.Configuration ?? null, spec.SheetID, spec.SheetChartID, spec.SheetRange, skipChartReEvaluate ? { skipEvaluate: true } : undefined);
739
+ if (!dataset) {
740
+ return buildErrorResult(spec, `Requested spreadsheet chart or range (${spec.SheetChartID || spec.SheetRange}) could not be extracted.`);
741
+ }
742
+ const slicedPayload = JSON.stringify({
743
+ Kind: 'SpreadsheetSlice',
744
+ SheetID: spec.SheetID ?? null,
745
+ ChartID: spec.SheetChartID ?? null,
746
+ Range: spec.SheetRange ?? null,
747
+ Columns: dataset.Columns,
748
+ Rows: dataset.Rows
749
+ });
750
+ return {
751
+ BlockID: spec.BlockID,
752
+ Kind: spec.Kind,
753
+ Mode: 'Live',
754
+ Success: true,
755
+ Columns: dataset.Columns,
756
+ Rows: dataset.Rows,
757
+ TotalRowCount: dataset.Rows.length,
758
+ ArtifactContent: slicedPayload,
759
+ ArtifactType: resolvedType,
760
+ ArtifactName: artifactRow.Name,
761
+ ArtifactVersionNumber: versionRow?.VersionNumber ?? 1,
762
+ CanEditArtifact: perms.CanEdit && !spec.VersionID
763
+ };
764
+ }
765
+ return {
766
+ BlockID: spec.BlockID,
767
+ Kind: spec.Kind,
768
+ Mode: 'Live',
769
+ Success: true,
770
+ Columns: [
771
+ { Name: 'ArtifactID', DisplayName: 'Artifact ID' },
772
+ { Name: 'Name', DisplayName: 'Name' },
773
+ { Name: 'Type', DisplayName: 'Type' },
774
+ { Name: 'VersionNumber', DisplayName: 'Version' }
775
+ ],
776
+ Rows: [
777
+ {
778
+ ArtifactID: artifactRow.ID,
779
+ Name: artifactRow.Name,
780
+ Type: artifactRow.Type,
781
+ VersionNumber: versionRow?.VersionNumber ?? 1
782
+ }
783
+ ],
784
+ TotalRowCount: 1,
785
+ ArtifactContent: versionRow?.Content ?? '',
786
+ ArtifactType: artifactRow.Type || spec.ArtifactType,
787
+ ArtifactName: artifactRow.Name,
788
+ ArtifactVersionNumber: versionRow?.VersionNumber ?? 1,
789
+ CanEditArtifact: perms.CanEdit && !spec.VersionID
790
+ };
791
+ }
792
+ };
793
+ ArtifactDocumentBlock = __decorate([
794
+ RegisterClass(BaseDocumentBlock, 'Artifact')
795
+ ], ArtifactDocumentBlock);
796
+ export { ArtifactDocumentBlock };
797
+ /**
798
+ * Central engine for validating, executing, freezing, unfreezing, and serializing
799
+ * embedded MJ blocks (`EntityView`, `SavedQuery`, `DashboardPart`, `InteractiveComponent`, `Artifact`)
800
+ * across MJ Docs, Slides, and Sheets.
801
+ */
802
+ export class DocumentLiveBlockEngine extends BaseSingleton {
803
+ constructor() {
804
+ super();
805
+ this._spreadsheetChartExtractor = null;
806
+ this._spreadsheetChartExtractorAsync = null;
807
+ this._spreadsheetXlsxChartExtractor = null;
808
+ this._spreadsheetXlsxChartExtractorAsync = null;
809
+ this._spreadsheetXlsxWorkbookExtractor = null;
810
+ this._spreadsheetXlsxWorkbookExtractorAsync = null;
811
+ this._artifactFileBytesLoader = null;
812
+ this._signingSecret = null;
813
+ }
814
+ /** Returns the process-wide singleton instance of {@link DocumentLiveBlockEngine}. */
815
+ static get Instance() {
816
+ return super.getInstance();
817
+ }
818
+ /**
819
+ * Configures an explicit server HMAC signing secret for {@link FreezeBlock},
820
+ * {@link ComputeFrozenSnapshotHash}, and {@link ValidateFrozenBlockSnapshot} (`B7`).
821
+ */
822
+ SetSigningSecret(secret) {
823
+ const trimmed = secret?.trim() || '';
824
+ this._signingSecret = trimmed.length > 0 ? trimmed : null;
825
+ }
826
+ /**
827
+ * Returns the explicitly configured server HMAC signing secret, if any (`B7`).
828
+ */
829
+ GetSigningSecret() {
830
+ return this._signingSecret;
831
+ }
832
+ /**
833
+ * Resolves the active `>= 32`-byte HMAC signing secret using consistent `.trim() || ...` fallback
834
+ * semantics across explicit secret, configured secret, `MJ_FROZEN_BLOCK_HMAC_SECRET`, and
835
+ * `MJ_FROZEN_SNAPSHOT_SECRET` (`R5-8`).
836
+ */
837
+ ResolveSigningSecret(explicitSecret) {
838
+ return this.getSigningSecret(explicitSecret);
839
+ }
840
+ /**
841
+ * Checks whether a valid `>= 32`-byte frozen-block HMAC signing secret is configured at startup (`E1` / `R5-8`),
842
+ * using the exact same `.trim() || ...` resolution rules as runtime signing/verification so empty or
843
+ * whitespace-only environment variables are treated identically as unset.
844
+ */
845
+ CheckStartupSecrets() {
846
+ const warnings = [];
847
+ const secret = this.getSigningSecret();
848
+ const frozenBlockSecretConfigured = secret !== null;
849
+ if (!frozenBlockSecretConfigured) {
850
+ warnings.push('[DocumentLiveBlockEngine] Startup warning: MJ_FROZEN_BLOCK_HMAC_SECRET is unset or shorter than 32 UTF-8 bytes; frozen-snapshot signing is disabled until a >= 32-byte secret is configured.');
851
+ }
852
+ return {
853
+ FrozenBlockSecretConfigured: frozenBlockSecretConfigured,
854
+ Warnings: warnings
855
+ };
856
+ }
857
+ getSigningSecret(explicitSecret) {
858
+ return resolveFrozenSnapshotSigningSecret(explicitSecret);
859
+ }
860
+ /**
861
+ * Registers the spreadsheet chart/range dataset extractor (`SpreadsheetEngine`), avoiding a circular
862
+ * module import between `DocumentLiveBlockEngine` and `SpreadsheetEngine` (`D5`).
863
+ */
864
+ RegisterSpreadsheetChartExtractor(fn) {
865
+ this._spreadsheetChartExtractor = fn;
866
+ }
867
+ /**
868
+ * Registers an async worker-isolated spreadsheet chart/range dataset extractor (`R9-2`).
869
+ */
870
+ RegisterSpreadsheetChartExtractorAsync(fn) {
871
+ this._spreadsheetChartExtractorAsync = fn;
872
+ }
873
+ /**
874
+ * Invokes the registered spreadsheet chart/range dataset extractor if available (`D5`).
875
+ */
876
+ ExtractSpreadsheetChartDataset(content, configuration, sheetId, chartId, sheetRange) {
877
+ if (!this._spreadsheetChartExtractor) {
878
+ return null;
879
+ }
880
+ return this._spreadsheetChartExtractor(content, configuration, sheetId, chartId, sheetRange);
881
+ }
882
+ /**
883
+ * Async worker-isolated chart/range dataset extraction (`R9-2`).
884
+ */
885
+ async ExtractSpreadsheetChartDatasetAsync(content, configuration, sheetId, chartId, sheetRange, options) {
886
+ if (this._spreadsheetChartExtractorAsync) {
887
+ return this._spreadsheetChartExtractorAsync(content, configuration, sheetId, chartId, sheetRange, options);
888
+ }
889
+ return this.ExtractSpreadsheetChartDataset(content, configuration, sheetId, chartId, sheetRange);
890
+ }
891
+ /**
892
+ * Registers a binary `.xlsx` chart/range dataset extractor (`SpreadsheetEngine`).
893
+ */
894
+ RegisterSpreadsheetXlsxChartExtractor(fn) {
895
+ this._spreadsheetXlsxChartExtractor = fn;
896
+ }
897
+ /**
898
+ * Registers an async binary `.xlsx` chart/range dataset extractor (`SpreadsheetEngine`).
899
+ */
900
+ RegisterSpreadsheetXlsxChartExtractorAsync(fn) {
901
+ this._spreadsheetXlsxChartExtractorAsync = fn;
902
+ }
903
+ /**
904
+ * Extracts a chart or range dataset from `.xlsx` binary bytes using the registered extractor.
905
+ */
906
+ ExtractSpreadsheetXlsxChartDataset(bytes, configuration, sheetId, chartId, sheetRange) {
907
+ if (!this._spreadsheetXlsxChartExtractor) {
908
+ return null;
909
+ }
910
+ return this._spreadsheetXlsxChartExtractor(bytes, configuration, sheetId, chartId, sheetRange);
911
+ }
912
+ /**
913
+ * Async worker-isolated extraction of a chart or range dataset from `.xlsx` bytes (`R6-1`).
914
+ */
915
+ async ExtractSpreadsheetXlsxChartDatasetAsync(bytes, configuration, sheetId, chartId, sheetRange) {
916
+ if (this._spreadsheetXlsxChartExtractorAsync) {
917
+ return this._spreadsheetXlsxChartExtractorAsync(bytes, configuration, sheetId, chartId, sheetRange);
918
+ }
919
+ return this.ExtractSpreadsheetXlsxChartDataset(bytes, configuration, sheetId, chartId, sheetRange);
920
+ }
921
+ /**
922
+ * Registers a binary `.xlsx` workbook-JSON extractor (`SpreadsheetEngine`).
923
+ */
924
+ RegisterSpreadsheetXlsxWorkbookExtractor(fn) {
925
+ this._spreadsheetXlsxWorkbookExtractor = fn;
926
+ }
927
+ /**
928
+ * Registers an async binary `.xlsx` workbook-JSON extractor (`SpreadsheetEngine`).
929
+ */
930
+ RegisterSpreadsheetXlsxWorkbookExtractorAsync(fn) {
931
+ this._spreadsheetXlsxWorkbookExtractorAsync = fn;
932
+ }
933
+ /**
934
+ * Materializes serialized workbook JSON from `.xlsx` binary bytes using the registered extractor.
935
+ */
936
+ ExtractSpreadsheetXlsxWorkbookJson(bytes, configuration) {
937
+ if (!this._spreadsheetXlsxWorkbookExtractor) {
938
+ return null;
939
+ }
940
+ return this._spreadsheetXlsxWorkbookExtractor(bytes, configuration);
941
+ }
942
+ /**
943
+ * Async worker-isolated materialization of serialized workbook JSON from `.xlsx` bytes (`R6-1`).
944
+ */
945
+ async ExtractSpreadsheetXlsxWorkbookJsonAsync(bytes, configuration) {
946
+ if (this._spreadsheetXlsxWorkbookExtractorAsync) {
947
+ return this._spreadsheetXlsxWorkbookExtractorAsync(bytes, configuration);
948
+ }
949
+ return this.ExtractSpreadsheetXlsxWorkbookJson(bytes, configuration);
950
+ }
951
+ /**
952
+ * Registers a host loader callback for `ContentMode = 'File'` binary artifact payloads (`MJ: Files`).
953
+ */
954
+ RegisterArtifactFileBytesLoader(fn) {
955
+ this._artifactFileBytesLoader = fn;
956
+ }
957
+ /**
958
+ * Loads binary bytes for `fileId` via the registered host file-bytes loader, or `null` when unset.
959
+ */
960
+ async LoadArtifactFileBytes(fileId, user, provider) {
961
+ if (!this._artifactFileBytesLoader || !fileId) {
962
+ return null;
963
+ }
964
+ return this._artifactFileBytesLoader(fileId, user, provider);
965
+ }
966
+ /**
967
+ * Resolves the registered {@link BaseDocumentBlock} handler for `kind`.
968
+ */
969
+ GetBlockHandler(kind) {
970
+ const instance = MJGlobal.Instance.ClassFactory.CreateInstance(BaseDocumentBlock, kind);
971
+ if (instance && instance.constructor !== BaseDocumentBlock) {
972
+ return instance;
973
+ }
974
+ switch (kind) {
975
+ case 'EntityView':
976
+ return new EntityViewDocumentBlock();
977
+ case 'SavedQuery':
978
+ return new SavedQueryDocumentBlock();
979
+ case 'DashboardPart':
980
+ return new DashboardPartDocumentBlock();
981
+ case 'InteractiveComponent':
982
+ return new InteractiveComponentDocumentBlock();
983
+ case 'Artifact':
984
+ return new ArtifactDocumentBlock();
985
+ default:
986
+ return null;
987
+ }
988
+ }
989
+ /**
990
+ * Executes a {@link DocumentBlockSpec} as `user` with full RLS, FLS, and `IsServerSet` parameter protection.
991
+ */
992
+ async ExecuteBlock(spec, user, provider, serverParameters) {
993
+ if (!user) {
994
+ return buildErrorResult(spec, 'Authenticated user context is required to execute a block.');
995
+ }
996
+ if (spec.Mode === 'Frozen') {
997
+ return buildFrozenExecutionResult(spec);
998
+ }
999
+ const activeProvider = provider ?? Metadata.Provider;
1000
+ if (!activeProvider) {
1001
+ return buildErrorResult(spec, 'Metadata provider is not initialized.');
1002
+ }
1003
+ const handler = this.GetBlockHandler(spec.Kind);
1004
+ if (!handler) {
1005
+ return buildErrorResult(spec, `Unsupported block kind '${spec.Kind}'.`);
1006
+ }
1007
+ return await handler.Execute(spec, activeProvider, user, serverParameters);
1008
+ }
1009
+ /**
1010
+ * Freezes a live block into a point-in-time snapshot (`Mode = 'Frozen'`, `O5`).
1011
+ *
1012
+ * Requires `acknowledgeSecurityWarning === true` to confirm the user accepted the modal
1013
+ * warning that freezing bakes their currently visible rows into the artifact.
1014
+ */
1015
+ async FreezeBlock(spec, user, acknowledgeSecurityWarning, provider, signingSecret, hostArtifactId) {
1016
+ if (!acknowledgeSecurityWarning) {
1017
+ return {
1018
+ Success: false,
1019
+ ErrorMessage: 'Freezing a live block requires explicit acknowledgment (acknowledgeSecurityWarning = true) because frozen data is visible to all readers of this artifact.'
1020
+ };
1021
+ }
1022
+ const liveSpec = { ...spec, Mode: 'Live' };
1023
+ const result = await this.ExecuteBlock(liveSpec, user, provider);
1024
+ if (!result.Success) {
1025
+ return {
1026
+ Success: false,
1027
+ ErrorMessage: result.ErrorMessage || 'Cannot freeze block because live execution failed.'
1028
+ };
1029
+ }
1030
+ const binding = BuildBlockIdentityBinding(spec, hostArtifactId);
1031
+ const snapshotBase = {
1032
+ FrozenAt: new Date().toISOString(),
1033
+ FrozenByUserID: user.ID,
1034
+ FrozenByUserName: user.Name || user.Email || user.ID,
1035
+ Columns: result.Columns,
1036
+ Rows: result.Rows,
1037
+ TotalRowCount: result.TotalRowCount,
1038
+ ArtifactContentSnapshot: result.ArtifactContent,
1039
+ ArtifactTypeSnapshot: result.ArtifactType,
1040
+ SecurityWarningAcknowledged: true,
1041
+ Binding: binding
1042
+ };
1043
+ const snapshot = {
1044
+ ...snapshotBase,
1045
+ SnapshotContentHash: ComputeFrozenSnapshotHash(snapshotBase, signingSecret)
1046
+ };
1047
+ return {
1048
+ Success: true,
1049
+ UpdatedSpec: {
1050
+ ...spec,
1051
+ Mode: 'Frozen',
1052
+ FrozenSnapshot: snapshot
1053
+ }
1054
+ };
1055
+ }
1056
+ /**
1057
+ * Converts a frozen block back to `'Live'` mode, clearing its static `FrozenSnapshot`.
1058
+ */
1059
+ UnfreezeBlock(spec) {
1060
+ const copy = {
1061
+ ...spec,
1062
+ Mode: 'Live'
1063
+ };
1064
+ delete copy.FrozenSnapshot;
1065
+ return copy;
1066
+ }
1067
+ /**
1068
+ * Serializes a {@link DocumentBlockSpec} into a canonical Markdown `:::mj-block` fenced directive.
1069
+ */
1070
+ SerializeBlockToMarkdownDirective(spec) {
1071
+ const json = JSON.stringify(spec, null, 2);
1072
+ return `:::mj-block\n${json}\n:::`;
1073
+ }
1074
+ /**
1075
+ * Parses `<!-- mj-lock: owner-only -->` directives, `<!-- /mj-lock -->` spans, heading section locks,
1076
+ * and `"Locked": true` `:::mj-block` specs into 1-based {@link DocumentLockedRange} entries (`§6.2`).
1077
+ */
1078
+ ParseDocumentLocks(markdown) {
1079
+ const lines = (markdown ?? '').replace(/\r\n/g, '\n').split('\n');
1080
+ const locks = [];
1081
+ const lockDirectiveRe = /^\s*<!--\s*mj-lock\s*:\s*([a-zA-Z0-9_-]+)(?:\s+user=([^\s>]+))?\s*-->\s*$/i;
1082
+ const unlockDirectiveRe = /^\s*<!--\s*\/mj-lock\s*-->\s*$/i;
1083
+ const headingRe = /^(#{1,6})\s+([^\n]*)$/;
1084
+ const openFenceRe = /^\s*(`{3,}|~{3,})/;
1085
+ const advanceFenceState = (line, current) => {
1086
+ const trimmed = line.trim();
1087
+ if (!current) {
1088
+ const m = openFenceRe.exec(trimmed);
1089
+ if (m) {
1090
+ const ch = m[1][0] === '~' ? '~' : '`';
1091
+ return { next: { char: ch, len: m[1].length }, isFenceBoundary: true };
1092
+ }
1093
+ return { next: null, isFenceBoundary: false };
1094
+ }
1095
+ const closeRe = new RegExp(`^\\s*${current.char}{${current.len},}\\s*$`);
1096
+ if (closeRe.test(trimmed)) {
1097
+ return { next: null, isFenceBoundary: true };
1098
+ }
1099
+ return { next: current, isFenceBoundary: false };
1100
+ };
1101
+ let inCodeFence = null;
1102
+ let i = 0;
1103
+ while (i < lines.length) {
1104
+ const fenceStep = advanceFenceState(lines[i], inCodeFence);
1105
+ inCodeFence = fenceStep.next;
1106
+ if (fenceStep.isFenceBoundary || inCodeFence) {
1107
+ i++;
1108
+ continue;
1109
+ }
1110
+ const match = lockDirectiveRe.exec(lines[i]);
1111
+ if (!match) {
1112
+ i++;
1113
+ continue;
1114
+ }
1115
+ const rawScope = match[1].toLowerCase();
1116
+ const scope = rawScope === 'editors-allowed' ? 'editors-allowed' : 'owner-only';
1117
+ const lockedByUserId = match[2]?.trim() || undefined;
1118
+ const startLine = i + 1;
1119
+ // Check if there is a closing <!-- /mj-lock --> ahead (ignoring code fences)
1120
+ let explicitCloseIdx = -1;
1121
+ let scanFence = null;
1122
+ for (let j = i + 1; j < lines.length; j++) {
1123
+ const innerStep = advanceFenceState(lines[j], scanFence);
1124
+ scanFence = innerStep.next;
1125
+ if (innerStep.isFenceBoundary || scanFence) {
1126
+ continue;
1127
+ }
1128
+ if (unlockDirectiveRe.test(lines[j])) {
1129
+ explicitCloseIdx = j;
1130
+ break;
1131
+ }
1132
+ }
1133
+ if (explicitCloseIdx >= 0) {
1134
+ locks.push({
1135
+ StartLine: startLine,
1136
+ EndLine: explicitCloseIdx + 1,
1137
+ Scope: scope,
1138
+ LockedByUserID: lockedByUserId,
1139
+ Kind: 'fenced',
1140
+ Label: `lines ${startLine}-${explicitCloseIdx + 1}`
1141
+ });
1142
+ i = explicitCloseIdx + 1;
1143
+ continue;
1144
+ }
1145
+ // Otherwise check next non-empty line: heading -> lock entire section; :::mj-block -> lock block
1146
+ let nextIdx = i + 1;
1147
+ while (nextIdx < lines.length && lines[nextIdx].trim() === '') {
1148
+ nextIdx++;
1149
+ }
1150
+ const nextLine = nextIdx < lines.length ? lines[nextIdx] : '';
1151
+ const headingMatch = headingRe.exec(nextLine);
1152
+ if (headingMatch) {
1153
+ const headingLevel = headingMatch[1].length;
1154
+ let endIdx = lines.length - 1;
1155
+ let headingFence = null;
1156
+ for (let j = nextIdx + 1; j < lines.length; j++) {
1157
+ const innerStep = advanceFenceState(lines[j], headingFence);
1158
+ headingFence = innerStep.next;
1159
+ if (innerStep.isFenceBoundary || headingFence) {
1160
+ continue;
1161
+ }
1162
+ const h = headingRe.exec(lines[j]);
1163
+ if (h && h[1].length <= headingLevel) {
1164
+ endIdx = j - 1;
1165
+ break;
1166
+ }
1167
+ }
1168
+ locks.push({
1169
+ StartLine: startLine,
1170
+ EndLine: endIdx + 1,
1171
+ Scope: scope,
1172
+ LockedByUserID: lockedByUserId,
1173
+ Kind: 'heading',
1174
+ Label: headingMatch[2].trim()
1175
+ });
1176
+ i = endIdx + 1;
1177
+ continue;
1178
+ }
1179
+ if (nextLine.trim().startsWith(':::mj-block')) {
1180
+ let endIdx = nextIdx;
1181
+ let blockFence = null;
1182
+ for (let j = nextIdx + 1; j < lines.length; j++) {
1183
+ const innerStep = advanceFenceState(lines[j], blockFence);
1184
+ blockFence = innerStep.next;
1185
+ if (innerStep.isFenceBoundary || blockFence) {
1186
+ continue;
1187
+ }
1188
+ if (lines[j].trim() === ':::') {
1189
+ endIdx = j;
1190
+ break;
1191
+ }
1192
+ }
1193
+ locks.push({
1194
+ StartLine: startLine,
1195
+ EndLine: endIdx + 1,
1196
+ Scope: scope,
1197
+ LockedByUserID: lockedByUserId,
1198
+ Kind: 'block',
1199
+ Label: `block at line ${nextIdx + 1}`
1200
+ });
1201
+ i = endIdx + 1;
1202
+ continue;
1203
+ }
1204
+ // Fallback: single-line / trailing paragraph lock
1205
+ locks.push({
1206
+ StartLine: startLine,
1207
+ EndLine: Math.min(lines.length, nextIdx + 1),
1208
+ Scope: scope,
1209
+ LockedByUserID: lockedByUserId,
1210
+ Kind: 'fenced',
1211
+ Label: `line ${startLine}`
1212
+ });
1213
+ i = Math.max(i + 1, nextIdx + 1);
1214
+ }
1215
+ // Also detect JSON-level `"Locked": true` inside :::mj-block segments
1216
+ const segments = this.ParseMarkdownDirectives(markdown);
1217
+ for (const seg of segments) {
1218
+ if (seg.Type === 'mj-block' && seg.BlockSpec?.Locked) {
1219
+ const alreadyCovered = locks.some((l) => seg.StartLine >= l.StartLine && seg.EndLine <= l.EndLine);
1220
+ if (!alreadyCovered) {
1221
+ locks.push({
1222
+ StartLine: seg.StartLine,
1223
+ EndLine: seg.EndLine,
1224
+ Scope: 'owner-only',
1225
+ LockedByUserID: seg.BlockSpec.LockedByUserID,
1226
+ Kind: 'block',
1227
+ Label: seg.BlockSpec.Title || seg.BlockSpec.BlockID
1228
+ });
1229
+ }
1230
+ }
1231
+ }
1232
+ return locks;
1233
+ }
1234
+ /**
1235
+ * Checks whether a given actor can edit a parsed {@link DocumentLockedRange}.
1236
+ */
1237
+ CanActorEditLockedRange(lock, actorUserId, ownerUserId, isEditor = false) {
1238
+ const actor = (actorUserId ?? '').trim();
1239
+ if (actor && ownerUserId && UUIDsEqual(actor, ownerUserId)) {
1240
+ return true;
1241
+ }
1242
+ if (actor && lock.LockedByUserID && UUIDsEqual(actor, lock.LockedByUserID)) {
1243
+ return true;
1244
+ }
1245
+ if (lock.Scope === 'editors-allowed' && isEditor) {
1246
+ return true;
1247
+ }
1248
+ return false;
1249
+ }
1250
+ /**
1251
+ * Verifies that an edit transitioning `originalMarkdown` -> `nextMarkdown` does not alter
1252
+ * any locked section or strip any `<!-- mj-lock -->` marker without owner permission (`§6.2`).
1253
+ */
1254
+ ValidateDocumentEditAgainstLocks(originalMarkdown, nextMarkdown, actorUserId, ownerUserId, isEditor = false) {
1255
+ const originalLocks = this.ParseDocumentLocks(originalMarkdown);
1256
+ if (originalLocks.length === 0) {
1257
+ return { Allowed: true };
1258
+ }
1259
+ const origLines = (originalMarkdown ?? '').replace(/\r\n/g, '\n').split('\n');
1260
+ const nextNormalized = (nextMarkdown ?? '').replace(/\r\n/g, '\n');
1261
+ const nextLines = nextNormalized.split('\n');
1262
+ const nextLocks = this.ParseDocumentLocks(nextNormalized);
1263
+ // Enforce ordered 1-to-1 multiplicity matching so duplicate locked sections cannot be
1264
+ // removed, reordered, or stripped of lock directives/scope.
1265
+ let searchFromIdx = 0;
1266
+ for (const lock of originalLocks) {
1267
+ if (this.CanActorEditLockedRange(lock, actorUserId, ownerUserId, isEditor)) {
1268
+ continue;
1269
+ }
1270
+ const lockedSlice = origLines.slice(lock.StartLine - 1, lock.EndLine).join('\n');
1271
+ let matchedIdx = -1;
1272
+ for (let k = searchFromIdx; k < nextLocks.length; k++) {
1273
+ const nl = nextLocks[k];
1274
+ if (nl.Kind !== lock.Kind ||
1275
+ nl.Scope !== lock.Scope ||
1276
+ !UUIDsEqual(nl.LockedByUserID ?? null, lock.LockedByUserID ?? null)) {
1277
+ continue;
1278
+ }
1279
+ const nlSlice = nextLines.slice(nl.StartLine - 1, nl.EndLine).join('\n');
1280
+ if (nlSlice === lockedSlice) {
1281
+ matchedIdx = k;
1282
+ break;
1283
+ }
1284
+ }
1285
+ if (matchedIdx < 0) {
1286
+ return {
1287
+ Allowed: false,
1288
+ ViolationReason: `Cannot modify, reorder, or unlock protected region '${lock.Label}' (${lock.Scope}).`,
1289
+ ViolatedLock: lock
1290
+ };
1291
+ }
1292
+ searchFromIdx = matchedIdx + 1;
1293
+ }
1294
+ return { Allowed: true };
1295
+ }
1296
+ /**
1297
+ * Toggles `<!-- mj-lock: owner-only -->` immediately above a 1-based heading line in Markdown (`§6.2`).
1298
+ * Removing an existing lock requires `CanActorEditLockedRange` permission (throws on unauthorized removal).
1299
+ */
1300
+ ToggleHeadingLockInMarkdown(markdown, headingLineNumber, locked, actorUserId, ownerUserId, isEditor = false) {
1301
+ const lines = (markdown ?? '').replace(/\r\n/g, '\n').split('\n');
1302
+ const idx = headingLineNumber - 1;
1303
+ if (idx < 0 || idx >= lines.length) {
1304
+ return markdown;
1305
+ }
1306
+ const lockRe = /^\s*<!--\s*mj-lock\s*:/i;
1307
+ const prevIsLock = idx > 0 && lockRe.test(lines[idx - 1]);
1308
+ if (locked && !prevIsLock) {
1309
+ const directive = actorUserId
1310
+ ? `<!-- mj-lock: owner-only user=${actorUserId} -->`
1311
+ : '<!-- mj-lock: owner-only -->';
1312
+ lines.splice(idx, 0, directive);
1313
+ }
1314
+ else if (!locked && prevIsLock) {
1315
+ const existingLocks = this.ParseDocumentLocks(markdown);
1316
+ const targetLock = existingLocks.find((l) => l.StartLine === idx) ??
1317
+ existingLocks.find((l) => headingLineNumber >= l.StartLine && headingLineNumber <= l.EndLine);
1318
+ if (targetLock && !this.CanActorEditLockedRange(targetLock, actorUserId, ownerUserId, isEditor)) {
1319
+ throw new Error(`Unauthorized: user cannot remove lock on '${targetLock.Label}' (${targetLock.Scope}).`);
1320
+ }
1321
+ lines.splice(idx - 1, 1);
1322
+ }
1323
+ return lines.join('\n');
1324
+ }
1325
+ /**
1326
+ * Parses structured comment/suggestion anchor metadata across Markdown, Spreadsheet,
1327
+ * Presentation, and Whiteboard artifacts (`NW-3`).
1328
+ */
1329
+ ParseArtifactCommentAnchor(raw) {
1330
+ if (!raw) {
1331
+ return null;
1332
+ }
1333
+ let parsed = null;
1334
+ if (typeof raw === 'string') {
1335
+ try {
1336
+ const candidate = JSON.parse(raw);
1337
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
1338
+ parsed = candidate;
1339
+ }
1340
+ }
1341
+ catch {
1342
+ return null;
1343
+ }
1344
+ }
1345
+ else if (typeof raw === 'object' && !Array.isArray(raw)) {
1346
+ parsed = raw;
1347
+ }
1348
+ if (!parsed) {
1349
+ return null;
1350
+ }
1351
+ const rawDomain = typeof parsed.Domain === 'string' ? parsed.Domain : typeof parsed.domain === 'string' ? parsed.domain : '';
1352
+ const domainLower = rawDomain.trim().toLowerCase();
1353
+ if (domainLower !== 'doc' && domainLower !== 'sheet' && domainLower !== 'slide' && domainLower !== 'whiteboard') {
1354
+ return null;
1355
+ }
1356
+ const readStr = (pascal, camel) => {
1357
+ const val = parsed[pascal] ?? parsed[camel];
1358
+ return typeof val === 'string' && val.trim().length > 0 ? val.trim() : undefined;
1359
+ };
1360
+ return {
1361
+ Domain: domainLower,
1362
+ SegmentID: readStr('SegmentID', 'segmentId'),
1363
+ BlockID: readStr('BlockID', 'blockId'),
1364
+ SheetID: readStr('SheetID', 'sheetId'),
1365
+ Range: readStr('Range', 'range'),
1366
+ SlideID: readStr('SlideID', 'slideId'),
1367
+ RegionID: readStr('RegionID', 'regionId')
1368
+ };
1369
+ }
1370
+ /**
1371
+ * Parses a Markdown document into alternating `'markdown'` prose segments and `'mj-block'`
1372
+ * embedded block segments.
1373
+ *
1374
+ * Respects fenced code blocks (` ``` ` / ` ~~~ ` of length >= 3) so example `:::mj-block`
1375
+ * snippets inside code fences are never parsed as live directives, and treats unterminated
1376
+ * `:::mj-block` fences as plain `'markdown'` without fabricating a closing `:::` (`D6`).
1377
+ */
1378
+ ParseMarkdownDirectives(markdown) {
1379
+ const lines = (markdown ?? '').split(/\r?\n/);
1380
+ const segments = [];
1381
+ let proseLines = [];
1382
+ let proseStartLine = 1;
1383
+ let activeFenceChar = null;
1384
+ let activeFenceLen = 0;
1385
+ let i = 0;
1386
+ while (i < lines.length) {
1387
+ const rawLine = lines[i];
1388
+ const trimmed = rawLine.trim();
1389
+ if (activeFenceChar !== null) {
1390
+ if (proseLines.length === 0) {
1391
+ proseStartLine = i + 1;
1392
+ }
1393
+ proseLines.push(rawLine);
1394
+ const closeFenceMatch = /^\s*(`{3,}|~{3,})\s*$/.exec(rawLine);
1395
+ if (closeFenceMatch &&
1396
+ closeFenceMatch[1][0] === activeFenceChar &&
1397
+ closeFenceMatch[1].length >= activeFenceLen) {
1398
+ activeFenceChar = null;
1399
+ activeFenceLen = 0;
1400
+ }
1401
+ i++;
1402
+ continue;
1403
+ }
1404
+ const openFenceMatch = /^\s*(`{3,}|~{3,})/.exec(rawLine);
1405
+ if (openFenceMatch) {
1406
+ activeFenceChar = openFenceMatch[1][0];
1407
+ activeFenceLen = openFenceMatch[1].length;
1408
+ if (proseLines.length === 0) {
1409
+ proseStartLine = i + 1;
1410
+ }
1411
+ proseLines.push(rawLine);
1412
+ i++;
1413
+ continue;
1414
+ }
1415
+ if (trimmed === ':::mj-block' || trimmed.startsWith(':::mj-block ')) {
1416
+ // Scan ahead to verify a matching closing ':::' exists before EOF
1417
+ let closeIdx = i + 1;
1418
+ while (closeIdx < lines.length && lines[closeIdx].trim() !== ':::') {
1419
+ closeIdx++;
1420
+ }
1421
+ // Unterminated :::mj-block reaching EOF: emit raw lines verbatim as markdown without fabricating ':::'
1422
+ if (closeIdx >= lines.length) {
1423
+ if (proseLines.length === 0) {
1424
+ proseStartLine = i + 1;
1425
+ }
1426
+ while (i < lines.length) {
1427
+ proseLines.push(lines[i]);
1428
+ i++;
1429
+ }
1430
+ break;
1431
+ }
1432
+ if (proseLines.length > 0) {
1433
+ segments.push({
1434
+ Type: 'markdown',
1435
+ RawText: proseLines.join('\n'),
1436
+ StartLine: proseStartLine,
1437
+ EndLine: i
1438
+ });
1439
+ proseLines = [];
1440
+ }
1441
+ const blockStartLine = i + 1;
1442
+ const blockJsonLines = lines.slice(i + 1, closeIdx);
1443
+ const blockEndLine = closeIdx + 1;
1444
+ const rawJson = blockJsonLines.join('\n').trim();
1445
+ let parsedSpec;
1446
+ try {
1447
+ const candidate = JSON.parse(rawJson);
1448
+ if (candidate && typeof candidate === 'object' && candidate.BlockID && candidate.Kind) {
1449
+ parsedSpec = candidate;
1450
+ }
1451
+ }
1452
+ catch {
1453
+ parsedSpec = undefined;
1454
+ }
1455
+ const rawDirective = [rawLine, ...blockJsonLines, lines[closeIdx]].join('\n');
1456
+ if (parsedSpec) {
1457
+ segments.push({
1458
+ Type: 'mj-block',
1459
+ RawText: rawDirective,
1460
+ BlockSpec: parsedSpec,
1461
+ StartLine: blockStartLine,
1462
+ EndLine: blockEndLine
1463
+ });
1464
+ }
1465
+ else {
1466
+ segments.push({
1467
+ Type: 'markdown',
1468
+ RawText: rawDirective,
1469
+ StartLine: blockStartLine,
1470
+ EndLine: blockEndLine
1471
+ });
1472
+ }
1473
+ i = closeIdx + 1;
1474
+ proseStartLine = i + 1;
1475
+ }
1476
+ else {
1477
+ if (proseLines.length === 0) {
1478
+ proseStartLine = i + 1;
1479
+ }
1480
+ proseLines.push(rawLine);
1481
+ i++;
1482
+ }
1483
+ }
1484
+ if (proseLines.length > 0) {
1485
+ segments.push({
1486
+ Type: 'markdown',
1487
+ RawText: proseLines.join('\n'),
1488
+ StartLine: proseStartLine,
1489
+ EndLine: lines.length
1490
+ });
1491
+ }
1492
+ return segments;
1493
+ }
1494
+ /**
1495
+ * Replaces or deletes an embedded `:::mj-block` in `markdown` by `blockId`.
1496
+ */
1497
+ UpdateBlockInMarkdown(markdown, blockId, updatedSpec) {
1498
+ const segments = this.ParseMarkdownDirectives(markdown);
1499
+ let found = false;
1500
+ const outputParts = [];
1501
+ for (const seg of segments) {
1502
+ if (seg.Type === 'mj-block' && seg.BlockSpec && seg.BlockSpec.BlockID === blockId) {
1503
+ found = true;
1504
+ if (updatedSpec) {
1505
+ outputParts.push(this.SerializeBlockToMarkdownDirective(updatedSpec));
1506
+ }
1507
+ }
1508
+ else {
1509
+ outputParts.push(seg.RawText);
1510
+ }
1511
+ }
1512
+ return {
1513
+ Found: found,
1514
+ Markdown: outputParts.join('\n')
1515
+ };
1516
+ }
1517
+ /**
1518
+ * Validates an `EntityView` `ExtraFilter` predicate against SQL injection, disallowed SQL globals/functions
1519
+ * (on either side of an operator), reserved niladic SQL keywords (`R8-5`), and optional entity/FLS field allowlists.
1520
+ */
1521
+ ValidateExtraFilter(extraFilter, entityInfo, deniedFields = new Set()) {
1522
+ return validateEntityViewExtraFilter(extraFilter, entityInfo, deniedFields);
1523
+ }
1524
+ /**
1525
+ * Validates an `EntityView` `OrderBy` clause against SQL injection, reserved unbracketed niladic SQL keywords
1526
+ * (`USER`, `CURRENT_USER`, `SESSION_USER`, `SYSTEM_USER`), and entity/FLS field allowlists (`R8-5`).
1527
+ */
1528
+ ValidateOrderBy(orderBy, entityInfo, deniedFields = new Set()) {
1529
+ return validateEntityViewOrderBy(orderBy, entityInfo, deniedFields);
1530
+ }
1531
+ }
1532
+ /**
1533
+ * Validates the structure, security acknowledgement, and HMAC-SHA256 signature of a {@link FrozenBlockSnapshot} (`B7`).
1534
+ */
1535
+ export function ValidateFrozenBlockSnapshot(snap, signingSecret, expectedBinding) {
1536
+ if (!snap || typeof snap !== 'object') {
1537
+ return {
1538
+ Valid: false,
1539
+ SnapshotVerified: false,
1540
+ ErrorMessage: 'Frozen block is missing a valid FrozenSnapshot payload.'
1541
+ };
1542
+ }
1543
+ if (snap.SecurityWarningAcknowledged !== true) {
1544
+ return {
1545
+ Valid: false,
1546
+ SnapshotVerified: false,
1547
+ ErrorMessage: 'Security violation: Frozen block snapshots require explicit acknowledgement of the RLS/FLS security warning (SecurityWarningAcknowledged: true).'
1548
+ };
1549
+ }
1550
+ if (typeof snap.FrozenByUserID !== 'string' || snap.FrozenByUserID.trim().length === 0) {
1551
+ return {
1552
+ Valid: false,
1553
+ SnapshotVerified: false,
1554
+ ErrorMessage: 'Invalid FrozenSnapshot: FrozenByUserID is required.'
1555
+ };
1556
+ }
1557
+ if (typeof snap.FrozenAt !== 'string' ||
1558
+ !/^\d{4}-\d{2}-\d{2}T/.test(snap.FrozenAt.trim()) ||
1559
+ Number.isNaN(Date.parse(snap.FrozenAt))) {
1560
+ return {
1561
+ Valid: false,
1562
+ SnapshotVerified: false,
1563
+ ErrorMessage: 'Invalid FrozenSnapshot: FrozenAt must be a valid ISO 8601 timestamp.'
1564
+ };
1565
+ }
1566
+ if (!Array.isArray(snap.Columns) || !Array.isArray(snap.Rows)) {
1567
+ return {
1568
+ Valid: false,
1569
+ SnapshotVerified: false,
1570
+ ErrorMessage: 'Invalid FrozenSnapshot: Columns and Rows must be arrays.'
1571
+ };
1572
+ }
1573
+ const secret = resolveFrozenSnapshotSigningSecret(signingSecret);
1574
+ if (!secret) {
1575
+ return {
1576
+ Valid: false,
1577
+ SnapshotVerified: false,
1578
+ ErrorMessage: 'Cannot verify FrozenSnapshot HMAC signature: MJ_FROZEN_BLOCK_HMAC_SECRET is not configured or shorter than 32 bytes.'
1579
+ };
1580
+ }
1581
+ if (typeof snap.SnapshotContentHash !== 'string' ||
1582
+ !snap.SnapshotContentHash.startsWith('hmac-sha256:')) {
1583
+ return {
1584
+ Valid: false,
1585
+ SnapshotVerified: false,
1586
+ ErrorMessage: 'FrozenSnapshot HMAC signature is required when a signing secret is configured.'
1587
+ };
1588
+ }
1589
+ const expectedHash = ComputeFrozenSnapshotHash(snap, secret);
1590
+ const snapshotVerified = constantTimeStringEqual(snap.SnapshotContentHash, expectedHash);
1591
+ if (!snapshotVerified) {
1592
+ return {
1593
+ Valid: false,
1594
+ SnapshotVerified: false,
1595
+ ErrorMessage: 'FrozenSnapshot HMAC verification failed: snapshot payload may have been tampered.'
1596
+ };
1597
+ }
1598
+ if (expectedBinding) {
1599
+ const normExpected = NormalizeFrozenSnapshotIdentityBinding(expectedBinding);
1600
+ const normActual = NormalizeFrozenSnapshotIdentityBinding(snap.Binding);
1601
+ if (normExpected) {
1602
+ if (!normActual) {
1603
+ return {
1604
+ Valid: false,
1605
+ SnapshotVerified: false,
1606
+ ErrorMessage: 'FrozenSnapshot is missing required identity Binding metadata.'
1607
+ };
1608
+ }
1609
+ if (normExpected.ArtifactID) {
1610
+ if (!normActual.ArtifactID || !UUIDsEqual(normExpected.ArtifactID, normActual.ArtifactID)) {
1611
+ return {
1612
+ Valid: false,
1613
+ SnapshotVerified: false,
1614
+ ErrorMessage: 'FrozenSnapshot ArtifactID binding mismatch.'
1615
+ };
1616
+ }
1617
+ }
1618
+ if (normExpected.BlockID && normActual.BlockID !== normExpected.BlockID) {
1619
+ return {
1620
+ Valid: false,
1621
+ SnapshotVerified: false,
1622
+ ErrorMessage: 'FrozenSnapshot BlockID binding mismatch.'
1623
+ };
1624
+ }
1625
+ if (normExpected.Kind && normActual.Kind !== normExpected.Kind) {
1626
+ return {
1627
+ Valid: false,
1628
+ SnapshotVerified: false,
1629
+ ErrorMessage: 'FrozenSnapshot Kind binding mismatch.'
1630
+ };
1631
+ }
1632
+ if (normExpected.SourceTargetID !== normActual.SourceTargetID) {
1633
+ return {
1634
+ Valid: false,
1635
+ SnapshotVerified: false,
1636
+ ErrorMessage: 'FrozenSnapshot SourceTargetID binding mismatch.'
1637
+ };
1638
+ }
1639
+ }
1640
+ }
1641
+ return {
1642
+ Valid: true,
1643
+ SnapshotVerified: true
1644
+ };
1645
+ }
1646
+ /**
1647
+ * Computes an HMAC-SHA256 signature (`'hmac-sha256:<hex>'`) over the canonical payload of a
1648
+ * {@link FrozenBlockSnapshot}, including `FrozenByUserName` (`B7`) and optional identity `Binding` (`S3`).
1649
+ */
1650
+ export function ComputeFrozenSnapshotHash(snap, signingSecret) {
1651
+ const secret = resolveFrozenSnapshotSigningSecret(signingSecret);
1652
+ if (!secret) {
1653
+ throw new Error('MJ_FROZEN_BLOCK_HMAC_SECRET (>= 32 bytes) must be configured on the server before signing or verifying frozen block snapshots.');
1654
+ }
1655
+ const normalizedBinding = NormalizeFrozenSnapshotIdentityBinding(snap.Binding);
1656
+ const payload = canonicalizeForHash({
1657
+ FrozenAt: snap.FrozenAt,
1658
+ FrozenByUserID: snap.FrozenByUserID,
1659
+ FrozenByUserName: snap.FrozenByUserName ?? null,
1660
+ Columns: snap.Columns,
1661
+ Rows: snap.Rows,
1662
+ TotalRowCount: snap.TotalRowCount,
1663
+ ArtifactContentSnapshot: snap.ArtifactContentSnapshot ?? null,
1664
+ ArtifactTypeSnapshot: snap.ArtifactTypeSnapshot ?? null,
1665
+ SecurityWarningAcknowledged: snap.SecurityWarningAcknowledged === true,
1666
+ ...(normalizedBinding ? { Binding: normalizedBinding } : {})
1667
+ });
1668
+ return `hmac-sha256:${hmacSha256HexUtf8(secret, payload)}`;
1669
+ }
1670
+ const MIN_FROZEN_SNAPSHOT_SECRET_BYTES = 32;
1671
+ /**
1672
+ * Pure-ECMAScript WHATWG-compliant UTF-8 encoder fallback for bare VMs without `TextEncoder` or `Buffer`.
1673
+ * Replaces any lone high or low UTF-16 surrogate with `0xEF 0xBF 0xBD` (`U+FFFD`).
1674
+ */
1675
+ export function EncodeDocumentUtf8Fallback(str) {
1676
+ const out = [];
1677
+ for (let i = 0; i < str.length; i++) {
1678
+ const code = str.charCodeAt(i);
1679
+ if (code < 0x80) {
1680
+ out.push(code);
1681
+ }
1682
+ else if (code < 0x800) {
1683
+ out.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f));
1684
+ }
1685
+ else if (code >= 0xd800 && code <= 0xdbff) {
1686
+ if (i + 1 < str.length) {
1687
+ const next = str.charCodeAt(i + 1);
1688
+ if (next >= 0xdc00 && next <= 0xdfff) {
1689
+ const cp = 0x10000 + (((code & 0x3ff) << 10) | (next & 0x3ff));
1690
+ out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
1691
+ i++;
1692
+ continue;
1693
+ }
1694
+ }
1695
+ out.push(0xef, 0xbf, 0xbd);
1696
+ }
1697
+ else if (code >= 0xdc00 && code <= 0xdfff) {
1698
+ out.push(0xef, 0xbf, 0xbd);
1699
+ }
1700
+ else {
1701
+ out.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f));
1702
+ }
1703
+ }
1704
+ return new Uint8Array(out);
1705
+ }
1706
+ /**
1707
+ * Pure-ECMAScript WHATWG §8.1.1 UTF-8 decoder fallback (`fatal: false`) for bare VMs without `TextDecoder` or `Buffer`.
1708
+ * Validates continuation bytes, rejects overlongs, UTF-16 surrogates, and `> U+10FFFF`, emitting `\uFFFD` per
1709
+ * invalid maximal subpart without consuming valid follow bytes.
1710
+ */
1711
+ export function DecodeDocumentUtf8Fallback(bytes) {
1712
+ const chunks = [];
1713
+ let chunk = '';
1714
+ let codePoint = 0;
1715
+ let bytesSeen = 0;
1716
+ let bytesNeeded = 0;
1717
+ let lowerBoundary = 0x80;
1718
+ let upperBoundary = 0xbf;
1719
+ for (let i = 0; i < bytes.length; i++) {
1720
+ const byte = bytes[i];
1721
+ if (bytesNeeded === 0) {
1722
+ if (byte <= 0x7f) {
1723
+ chunk += String.fromCharCode(byte);
1724
+ }
1725
+ else if (byte >= 0xc2 && byte <= 0xdf) {
1726
+ bytesNeeded = 1;
1727
+ codePoint = byte & 0x1f;
1728
+ }
1729
+ else if (byte >= 0xe0 && byte <= 0xef) {
1730
+ if (byte === 0xe0)
1731
+ lowerBoundary = 0xa0;
1732
+ else if (byte === 0xed)
1733
+ upperBoundary = 0x9f;
1734
+ bytesNeeded = 2;
1735
+ codePoint = byte & 0x0f;
1736
+ }
1737
+ else if (byte >= 0xf0 && byte <= 0xf4) {
1738
+ if (byte === 0xf0)
1739
+ lowerBoundary = 0x90;
1740
+ else if (byte === 0xf4)
1741
+ upperBoundary = 0x8f;
1742
+ bytesNeeded = 3;
1743
+ codePoint = byte & 0x07;
1744
+ }
1745
+ else {
1746
+ chunk += '\ufffd';
1747
+ }
1748
+ }
1749
+ else if (byte < lowerBoundary || byte > upperBoundary) {
1750
+ codePoint = 0;
1751
+ bytesNeeded = 0;
1752
+ bytesSeen = 0;
1753
+ lowerBoundary = 0x80;
1754
+ upperBoundary = 0xbf;
1755
+ chunk += '\ufffd';
1756
+ i--;
1757
+ }
1758
+ else {
1759
+ lowerBoundary = 0x80;
1760
+ upperBoundary = 0xbf;
1761
+ codePoint = (codePoint << 6) | (byte & 0x3f);
1762
+ bytesSeen++;
1763
+ if (bytesSeen === bytesNeeded) {
1764
+ chunk += codePoint <= 0xffff ? String.fromCharCode(codePoint) : String.fromCodePoint(codePoint);
1765
+ codePoint = 0;
1766
+ bytesNeeded = 0;
1767
+ bytesSeen = 0;
1768
+ }
1769
+ }
1770
+ if (chunk.length >= 8192) {
1771
+ chunks.push(chunk);
1772
+ chunk = '';
1773
+ }
1774
+ }
1775
+ if (bytesNeeded !== 0) {
1776
+ chunk += '\ufffd';
1777
+ }
1778
+ if (chunk.length > 0) {
1779
+ chunks.push(chunk);
1780
+ }
1781
+ return chunks.join('');
1782
+ }
1783
+ function utf8EncodeBytes(str) {
1784
+ if (typeof TextEncoder !== 'undefined') {
1785
+ return new TextEncoder().encode(str);
1786
+ }
1787
+ if (typeof Buffer !== 'undefined') {
1788
+ return new Uint8Array(Buffer.from(str, 'utf8'));
1789
+ }
1790
+ return EncodeDocumentUtf8Fallback(str);
1791
+ }
1792
+ function resolveFrozenSnapshotSigningSecret(explicitSecret) {
1793
+ const explicitTrimmed = explicitSecret?.trim() || '';
1794
+ if (explicitTrimmed.length > 0) {
1795
+ return utf8EncodeBytes(explicitTrimmed).length >= MIN_FROZEN_SNAPSHOT_SECRET_BYTES ? explicitTrimmed : null;
1796
+ }
1797
+ const configuredTrimmed = DocumentLiveBlockEngine.Instance.GetSigningSecret()?.trim() || '';
1798
+ if (configuredTrimmed.length > 0) {
1799
+ return utf8EncodeBytes(configuredTrimmed).length >= MIN_FROZEN_SNAPSHOT_SECRET_BYTES ? configuredTrimmed : null;
1800
+ }
1801
+ const env = typeof globalThis !== 'undefined' && 'process' in globalThis
1802
+ ? globalThis.process?.env
1803
+ : undefined;
1804
+ const candidate = env?.MJ_FROZEN_BLOCK_HMAC_SECRET?.trim() || env?.MJ_FROZEN_SNAPSHOT_SECRET?.trim() || '';
1805
+ if (utf8EncodeBytes(candidate).length < MIN_FROZEN_SNAPSHOT_SECRET_BYTES) {
1806
+ return null;
1807
+ }
1808
+ return candidate;
1809
+ }
1810
+ function constantTimeStringEqual(a, b) {
1811
+ const aBytes = utf8EncodeBytes(a);
1812
+ const bBytes = utf8EncodeBytes(b);
1813
+ if (aBytes.length !== bBytes.length) {
1814
+ return false;
1815
+ }
1816
+ let diff = 0;
1817
+ for (let i = 0; i < aBytes.length; i++) {
1818
+ diff |= aBytes[i] ^ bBytes[i];
1819
+ }
1820
+ return diff === 0;
1821
+ }
1822
+ function canonicalizeForHash(value) {
1823
+ if (value === null || value === undefined) {
1824
+ return 'null';
1825
+ }
1826
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string') {
1827
+ return JSON.stringify(value);
1828
+ }
1829
+ if (Array.isArray(value)) {
1830
+ return `[${value.map((item) => canonicalizeForHash(item)).join(',')}]`;
1831
+ }
1832
+ if (typeof value === 'object') {
1833
+ const rec = value;
1834
+ const keys = Object.keys(rec)
1835
+ .filter((k) => rec[k] !== undefined)
1836
+ .sort();
1837
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalizeForHash(rec[k])}`).join(',')}}`;
1838
+ }
1839
+ return JSON.stringify(String(value));
1840
+ }
1841
+ const SHA256_K = [
1842
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
1843
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
1844
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
1845
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
1846
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
1847
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
1848
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
1849
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
1850
+ ];
1851
+ function sha256Bytes(bytes) {
1852
+ const bitLenHi = Math.floor((bytes.length * 8) / 0x100000000);
1853
+ const bitLenLo = (bytes.length * 8) >>> 0;
1854
+ const paddedLen = ((bytes.length + 9 + 63) >>> 6) << 6;
1855
+ const buf = new Uint8Array(paddedLen);
1856
+ buf.set(bytes, 0);
1857
+ buf[bytes.length] = 0x80;
1858
+ const dv = new DataView(buf.buffer);
1859
+ dv.setUint32(paddedLen - 8, bitLenHi, false);
1860
+ dv.setUint32(paddedLen - 4, bitLenLo, false);
1861
+ let h0 = 0x6a09e667;
1862
+ let h1 = 0xbb67ae85;
1863
+ let h2 = 0x3c6ef372;
1864
+ let h3 = 0xa54ff53a;
1865
+ let h4 = 0x510e527f;
1866
+ let h5 = 0x9b05688c;
1867
+ let h6 = 0x1f83d9ab;
1868
+ let h7 = 0x5be0cd19;
1869
+ const w = new Uint32Array(64);
1870
+ const rotr = (x, n) => ((x >>> n) | (x << (32 - n))) >>> 0;
1871
+ for (let offset = 0; offset < paddedLen; offset += 64) {
1872
+ for (let i = 0; i < 16; i++) {
1873
+ w[i] = dv.getUint32(offset + i * 4, false);
1874
+ }
1875
+ for (let i = 16; i < 64; i++) {
1876
+ const s0 = (rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3)) >>> 0;
1877
+ const s1 = (rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10)) >>> 0;
1878
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
1879
+ }
1880
+ let a = h0;
1881
+ let b = h1;
1882
+ let c = h2;
1883
+ let d = h3;
1884
+ let e = h4;
1885
+ let f = h5;
1886
+ let g = h6;
1887
+ let h = h7;
1888
+ for (let i = 0; i < 64; i++) {
1889
+ const S1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
1890
+ const ch = ((e & f) ^ (~e & g)) >>> 0;
1891
+ const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0;
1892
+ const S0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
1893
+ const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0;
1894
+ const temp2 = (S0 + maj) >>> 0;
1895
+ h = g;
1896
+ g = f;
1897
+ f = e;
1898
+ e = (d + temp1) >>> 0;
1899
+ d = c;
1900
+ c = b;
1901
+ b = a;
1902
+ a = (temp1 + temp2) >>> 0;
1903
+ }
1904
+ h0 = (h0 + a) >>> 0;
1905
+ h1 = (h1 + b) >>> 0;
1906
+ h2 = (h2 + c) >>> 0;
1907
+ h3 = (h3 + d) >>> 0;
1908
+ h4 = (h4 + e) >>> 0;
1909
+ h5 = (h5 + f) >>> 0;
1910
+ h6 = (h6 + g) >>> 0;
1911
+ h7 = (h7 + h) >>> 0;
1912
+ }
1913
+ const digest = new Uint8Array(32);
1914
+ const outView = new DataView(digest.buffer);
1915
+ outView.setUint32(0, h0, false);
1916
+ outView.setUint32(4, h1, false);
1917
+ outView.setUint32(8, h2, false);
1918
+ outView.setUint32(12, h3, false);
1919
+ outView.setUint32(16, h4, false);
1920
+ outView.setUint32(20, h5, false);
1921
+ outView.setUint32(24, h6, false);
1922
+ outView.setUint32(28, h7, false);
1923
+ return digest;
1924
+ }
1925
+ function hmacSha256HexUtf8(key, message) {
1926
+ const rawKey = utf8EncodeBytes(key);
1927
+ const msgBytes = utf8EncodeBytes(message);
1928
+ const keyBlock = new Uint8Array(64);
1929
+ if (rawKey.length > 64) {
1930
+ keyBlock.set(sha256Bytes(rawKey), 0);
1931
+ }
1932
+ else {
1933
+ keyBlock.set(rawKey, 0);
1934
+ }
1935
+ const ipadMsg = new Uint8Array(64 + msgBytes.length);
1936
+ const opadInner = new Uint8Array(64 + 32);
1937
+ for (let i = 0; i < 64; i++) {
1938
+ ipadMsg[i] = keyBlock[i] ^ 0x36;
1939
+ opadInner[i] = keyBlock[i] ^ 0x5c;
1940
+ }
1941
+ ipadMsg.set(msgBytes, 64);
1942
+ const innerDigest = sha256Bytes(ipadMsg);
1943
+ opadInner.set(innerDigest, 64);
1944
+ const finalDigest = sha256Bytes(opadInner);
1945
+ return Array.from(finalDigest, (b) => b.toString(16).padStart(2, '0')).join('');
1946
+ }
1947
+ function clampBlockMaxRows(rawMaxRows) {
1948
+ if (typeof rawMaxRows !== 'number' || !Number.isFinite(rawMaxRows) || rawMaxRows <= 0) {
1949
+ return 100;
1950
+ }
1951
+ return Math.min(500, Math.max(1, Math.floor(rawMaxRows)));
1952
+ }
1953
+ const NILADIC_SQL_PRINCIPAL_KEYWORDS = new Set([
1954
+ 'user',
1955
+ 'current_user',
1956
+ 'session_user',
1957
+ 'system_user',
1958
+ 'current_role',
1959
+ 'current_catalog',
1960
+ 'current_schema'
1961
+ ]);
1962
+ function validateEntityViewOrderBy(orderBy, entityInfo, deniedFields) {
1963
+ const allowedFieldNames = new Set(entityInfo.Fields.map((f) => f.Name.trim().toLowerCase()));
1964
+ const clauses = orderBy.split(',');
1965
+ for (const rawClause of clauses) {
1966
+ const clause = rawClause.trim();
1967
+ if (!clause) {
1968
+ return { Valid: false, ErrorMessage: 'Invalid empty clause in OrderBy.' };
1969
+ }
1970
+ const match = /^(?:\[((?:\]\]|[^\]])+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s+(ASC|DESC))?$/i.exec(clause);
1971
+ if (!match) {
1972
+ return { Valid: false, ErrorMessage: `Invalid OrderBy clause '${clause}'.` };
1973
+ }
1974
+ const isBracketed = match[1] !== undefined;
1975
+ const rawField = isBracketed ? match[1].replace(/\]\]/g, () => ']') : match[2];
1976
+ const fieldName = rawField.trim().toLowerCase();
1977
+ if (!isBracketed && NILADIC_SQL_PRINCIPAL_KEYWORDS.has(fieldName)) {
1978
+ return {
1979
+ Valid: false,
1980
+ ErrorMessage: `Reserved SQL niladic keyword '${rawField}' must be bracketed (e.g. '[${rawField}]') in OrderBy.`
1981
+ };
1982
+ }
1983
+ if (!allowedFieldNames.has(fieldName) || deniedFields.has(fieldName)) {
1984
+ return {
1985
+ Valid: false,
1986
+ ErrorMessage: `Field '${rawField}' is not permitted or does not exist in OrderBy.`
1987
+ };
1988
+ }
1989
+ }
1990
+ return { Valid: true };
1991
+ }
1992
+ function hasQualifiedSqlIdentifier(maskedSql) {
1993
+ let searchFrom = 0;
1994
+ while (searchFrom < maskedSql.length) {
1995
+ const dotIdx = maskedSql.indexOf('.', searchFrom);
1996
+ if (dotIdx === -1) {
1997
+ return false;
1998
+ }
1999
+ let left = dotIdx - 1;
2000
+ while (left >= 0 && /\s/.test(maskedSql[left])) {
2001
+ left--;
2002
+ }
2003
+ let right = dotIdx + 1;
2004
+ while (right < maskedSql.length && /\s/.test(maskedSql[right])) {
2005
+ right++;
2006
+ }
2007
+ if (left >= 0 && right < maskedSql.length && /[A-Za-z_]/.test(maskedSql[right])) {
2008
+ let identStart = left;
2009
+ while (identStart > 0 && /[A-Za-z0-9_]/.test(maskedSql[identStart - 1])) {
2010
+ identStart--;
2011
+ }
2012
+ if (/[A-Za-z_]/.test(maskedSql[identStart]) && identStart <= left) {
2013
+ return true;
2014
+ }
2015
+ }
2016
+ searchFrom = dotIdx + 1;
2017
+ }
2018
+ return false;
2019
+ }
2020
+ function validateEntityViewExtraFilter(extraFilter, entityInfo, deniedFields = new Set()) {
2021
+ // Character-by-character scan to mask bracketed column identifiers (`[First Name]`),
2022
+ // Unicode string literals (`N'Renée'`), and standard single-quoted literals (`'Ada'`),
2023
+ // verifying balanced quotes and brackets before inspecting SQL tokens (`R7-9`).
2024
+ const bracketedIdents = [];
2025
+ let masked = '';
2026
+ for (let i = 0; i < extraFilter.length; i++) {
2027
+ const ch = extraFilter[i];
2028
+ if (ch === '[') {
2029
+ let j = i + 1;
2030
+ let closed = false;
2031
+ let inner = '';
2032
+ while (j < extraFilter.length) {
2033
+ if (extraFilter[j] === ']') {
2034
+ if (j + 1 < extraFilter.length && extraFilter[j + 1] === ']') {
2035
+ inner += ']';
2036
+ j += 2;
2037
+ continue;
2038
+ }
2039
+ closed = true;
2040
+ break;
2041
+ }
2042
+ inner += extraFilter[j];
2043
+ j++;
2044
+ }
2045
+ if (!closed || inner.trim().length === 0) {
2046
+ return { Valid: false, ErrorMessage: 'Invalid or unclosed bracketed identifier in ExtraFilter.' };
2047
+ }
2048
+ const idx = bracketedIdents.length;
2049
+ bracketedIdents.push(inner);
2050
+ masked += `__BRACKET_ID_${idx}__`;
2051
+ i = j;
2052
+ }
2053
+ else if ((ch === 'N' || ch === 'n') &&
2054
+ i + 1 < extraFilter.length &&
2055
+ extraFilter[i + 1] === "'" &&
2056
+ (i === 0 || !/[A-Za-z0-9_]/.test(extraFilter[i - 1]))) {
2057
+ let j = i + 2;
2058
+ let closed = false;
2059
+ while (j < extraFilter.length) {
2060
+ if (extraFilter[j] === "'") {
2061
+ if (j + 1 < extraFilter.length && extraFilter[j + 1] === "'") {
2062
+ j += 2;
2063
+ continue;
2064
+ }
2065
+ closed = true;
2066
+ break;
2067
+ }
2068
+ j++;
2069
+ }
2070
+ if (!closed) {
2071
+ return { Valid: false, ErrorMessage: 'Unclosed Unicode string literal in ExtraFilter.' };
2072
+ }
2073
+ masked += "'__STR__'";
2074
+ i = j;
2075
+ }
2076
+ else if (ch === "'") {
2077
+ let j = i + 1;
2078
+ let closed = false;
2079
+ while (j < extraFilter.length) {
2080
+ if (extraFilter[j] === "'") {
2081
+ if (j + 1 < extraFilter.length && extraFilter[j + 1] === "'") {
2082
+ j += 2;
2083
+ continue;
2084
+ }
2085
+ closed = true;
2086
+ break;
2087
+ }
2088
+ j++;
2089
+ }
2090
+ if (!closed) {
2091
+ return { Valid: false, ErrorMessage: 'Unclosed string literal in ExtraFilter.' };
2092
+ }
2093
+ masked += "'__STR__'";
2094
+ i = j;
2095
+ }
2096
+ else {
2097
+ masked += ch;
2098
+ }
2099
+ }
2100
+ if (/--|\/\*|\*\/|;/.test(masked)) {
2101
+ return { Valid: false, ErrorMessage: 'SQL comments and statement terminators are not permitted in ExtraFilter.' };
2102
+ }
2103
+ if (/\b(SELECT|UNION|DROP|DELETE|UPDATE|INSERT|EXEC|EXECUTE|ALTER|CREATE|TRUNCATE|MERGE|GRANT|REVOKE|WAITFOR|OPENROWSET|OPENQUERY|OPENDATASOURCE)\b/i.test(masked) ||
2104
+ /\bxp_[A-Za-z0-9_]*/i.test(masked)) {
2105
+ return { Valid: false, ErrorMessage: 'Subqueries, DDL, DML, and system procedures are not permitted in ExtraFilter.' };
2106
+ }
2107
+ // Reject SQL global/local variables anywhere outside string literals (e.g. 'M' < @@VERSION, @@SERVERNAME, @var)
2108
+ if (/@@?[A-Za-z_]/.test(masked)) {
2109
+ return {
2110
+ Valid: false,
2111
+ ErrorMessage: 'SQL global and local variables (e.g. @@VERSION) are not permitted in ExtraFilter.'
2112
+ };
2113
+ }
2114
+ // Reject schema/table-qualified identifiers (e.g. __mj.fnSecret(ID), dbo.Users.ID, or [dbo].[Users]) and SQL function calls
2115
+ if (hasQualifiedSqlIdentifier(masked)) {
2116
+ return {
2117
+ Valid: false,
2118
+ ErrorMessage: 'Schema- or table-qualified identifiers and user-defined functions are not permitted in ExtraFilter.'
2119
+ };
2120
+ }
2121
+ const allowedLogicalParenKeywords = new Set(['AND', 'OR', 'NOT', 'IN']);
2122
+ if (/__BRACKET_ID_\d+__\s*\(/.test(masked)) {
2123
+ return {
2124
+ Valid: false,
2125
+ ErrorMessage: 'Scalar or user-defined SQL function calls are not permitted in ExtraFilter.'
2126
+ };
2127
+ }
2128
+ const fnCallRegex = /\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/g;
2129
+ let fnMatch;
2130
+ while ((fnMatch = fnCallRegex.exec(masked)) !== null) {
2131
+ if (!allowedLogicalParenKeywords.has(fnMatch[1].toUpperCase())) {
2132
+ return {
2133
+ Valid: false,
2134
+ ErrorMessage: 'Scalar or user-defined SQL function calls are not permitted in ExtraFilter.'
2135
+ };
2136
+ }
2137
+ }
2138
+ const allowedSqlPredicateKeywords = new Set([
2139
+ 'and',
2140
+ 'or',
2141
+ 'not',
2142
+ 'in',
2143
+ 'is',
2144
+ 'null',
2145
+ 'like',
2146
+ 'between',
2147
+ 'escape',
2148
+ 'true',
2149
+ 'false'
2150
+ ]);
2151
+ const allowedFieldNames = entityInfo
2152
+ ? new Set(entityInfo.Fields.map((f) => f.Name.trim().toLowerCase()))
2153
+ : null;
2154
+ const standaloneDisallowedBuiltinTokens = new Set([
2155
+ 'suser_sname',
2156
+ 'suser_name',
2157
+ 'suser_id',
2158
+ 'suser_sid',
2159
+ 'original_login',
2160
+ 'user_name',
2161
+ 'user_id',
2162
+ 'host_name',
2163
+ 'host_id',
2164
+ 'object_name',
2165
+ 'object_id',
2166
+ 'schema_name',
2167
+ 'permissions',
2168
+ 'has_perms_by_name',
2169
+ 'is_member',
2170
+ 'is_srvrolemember'
2171
+ ]);
2172
+ // Verify EVERY identifier token anywhere outside string literals (both LHS and RHS) against FLS deniedFields and entityInfo.Fields
2173
+ const allIdentsRegex = /__BRACKET_ID_(\d+)__|(?<![0-9])([A-Za-z_][A-Za-z0-9_]*)/g;
2174
+ let identMatch;
2175
+ while ((identMatch = allIdentsRegex.exec(masked)) !== null) {
2176
+ const isBracketed = identMatch[1] !== undefined;
2177
+ const rawIdent = isBracketed
2178
+ ? (bracketedIdents[Number(identMatch[1])] ?? '')
2179
+ : identMatch[2];
2180
+ const token = rawIdent.trim().toLowerCase();
2181
+ if (!isBracketed && token === '__str__')
2182
+ continue;
2183
+ if (!isBracketed && allowedSqlPredicateKeywords.has(token))
2184
+ continue;
2185
+ if (!isBracketed && NILADIC_SQL_PRINCIPAL_KEYWORDS.has(token)) {
2186
+ return {
2187
+ Valid: false,
2188
+ ErrorMessage: `Disallowed unbracketed SQL niladic keyword '${rawIdent}' in ExtraFilter; bracket entity columns as '[${rawIdent}]'.`
2189
+ };
2190
+ }
2191
+ if (isBracketed && NILADIC_SQL_PRINCIPAL_KEYWORDS.has(token) && (!allowedFieldNames || !allowedFieldNames.has(token))) {
2192
+ return {
2193
+ Valid: false,
2194
+ ErrorMessage: `Bracketed niladic keyword '[${rawIdent}]' is only permitted when '${rawIdent}' exists on ${entityInfo?.Name ?? 'entity'}.`
2195
+ };
2196
+ }
2197
+ if (!isBracketed && !allowedFieldNames && standaloneDisallowedBuiltinTokens.has(token)) {
2198
+ return {
2199
+ Valid: false,
2200
+ ErrorMessage: 'Disallowed SQL system globals and functions (e.g. SYSTEM_USER) are not permitted in ExtraFilter.'
2201
+ };
2202
+ }
2203
+ if (deniedFields.has(token)) {
2204
+ return {
2205
+ Valid: false,
2206
+ ErrorMessage: `Access denied: ExtraFilter cannot reference restricted field '${rawIdent}'.`
2207
+ };
2208
+ }
2209
+ if (allowedFieldNames && !allowedFieldNames.has(token)) {
2210
+ return {
2211
+ Valid: false,
2212
+ ErrorMessage: `Field '${rawIdent}' in ExtraFilter does not exist on ${entityInfo?.Name ?? 'entity'} or access is denied.`
2213
+ };
2214
+ }
2215
+ }
2216
+ return { Valid: true };
2217
+ }
2218
+ function buildFrozenExecutionResult(spec) {
2219
+ const validation = ValidateFrozenBlockSnapshot(spec.FrozenSnapshot, undefined, BuildBlockIdentityBinding(spec));
2220
+ if (!validation.Valid || !spec.FrozenSnapshot) {
2221
+ return {
2222
+ BlockID: spec.BlockID,
2223
+ Kind: spec.Kind,
2224
+ Mode: 'Frozen',
2225
+ Success: false,
2226
+ ErrorMessage: validation.ErrorMessage ?? 'Invalid FrozenSnapshot.',
2227
+ Columns: [],
2228
+ Rows: [],
2229
+ TotalRowCount: 0
2230
+ };
2231
+ }
2232
+ const snap = spec.FrozenSnapshot;
2233
+ const frozenByUserName = snap.FrozenByUserName || snap.FrozenByUserID;
2234
+ return {
2235
+ BlockID: spec.BlockID,
2236
+ Kind: spec.Kind,
2237
+ Mode: 'Frozen',
2238
+ Success: true,
2239
+ Columns: snap.Columns,
2240
+ Rows: snap.Rows,
2241
+ TotalRowCount: snap.TotalRowCount ?? snap.Rows.length,
2242
+ ArtifactContent: snap.ArtifactContentSnapshot,
2243
+ ArtifactType: snap.ArtifactTypeSnapshot ?? spec.ArtifactType,
2244
+ CanEditArtifact: false,
2245
+ FrozenMetadata: {
2246
+ FrozenAt: snap.FrozenAt,
2247
+ FrozenByUserID: snap.FrozenByUserID,
2248
+ FrozenByUserName: frozenByUserName,
2249
+ SnapshotVerified: validation.SnapshotVerified
2250
+ },
2251
+ FrozenSnapshot: {
2252
+ SnapshotVerified: validation.SnapshotVerified,
2253
+ FrozenAt: snap.FrozenAt,
2254
+ FrozenByUserID: snap.FrozenByUserID,
2255
+ FrozenByUserName: frozenByUserName,
2256
+ SnapshotContentHash: snap.SnapshotContentHash
2257
+ }
2258
+ };
2259
+ }
2260
+ function buildErrorResult(spec, message) {
2261
+ return {
2262
+ BlockID: spec.BlockID,
2263
+ Kind: spec.Kind,
2264
+ Mode: spec.Mode ?? 'Live',
2265
+ Success: false,
2266
+ ErrorMessage: message,
2267
+ Columns: [],
2268
+ Rows: [],
2269
+ TotalRowCount: 0
2270
+ };
2271
+ }
2272
+ function resolveRunQueryProvider(provider) {
2273
+ if ('RunQuery' in provider && typeof provider.RunQuery === 'function') {
2274
+ return provider;
2275
+ }
2276
+ return null;
2277
+ }
2278
+ /**
2279
+ * The saved query a block names — by ID, else by name (narrowed by category path when given) — from the
2280
+ * `QueryEngine` bound to `provider`, loaded as `user`. Returns `undefined` when the engine cannot load, so
2281
+ * the block fails closed with the same result as a query that does not exist.
2282
+ */
2283
+ async function resolveSavedQuery(provider, user, queryId, queryName, categoryPath) {
2284
+ const engine = QueryEngine.GetProviderInstance(provider, QueryEngine);
2285
+ try {
2286
+ await engine.Config(false, user, provider);
2287
+ }
2288
+ catch (error) {
2289
+ LogError(`DocumentLiveBlockEngine: saved queries could not be loaded: ${error instanceof Error ? error.message : String(error)}`);
2290
+ return undefined;
2291
+ }
2292
+ const queries = engine.Queries;
2293
+ if (queryId) {
2294
+ return queries.find((q) => UUIDsEqual(q.ID, queryId));
2295
+ }
2296
+ if (queryName) {
2297
+ const lowerName = queryName.trim().toLowerCase();
2298
+ if (categoryPath) {
2299
+ const lowerCat = categoryPath.trim().toLowerCase();
2300
+ return queries.find((q) => q.Name.trim().toLowerCase() === lowerName && (q.CategoryPath ?? '').trim().toLowerCase() === lowerCat);
2301
+ }
2302
+ return queries.find((q) => q.Name.trim().toLowerCase() === lowerName);
2303
+ }
2304
+ return undefined;
2305
+ }
2306
+ function sanitizeClientQueryParameters(queryInfo, rawParameters) {
2307
+ if (!rawParameters || typeof rawParameters !== 'object') {
2308
+ return { cleanParameters: {}, strippedNames: [] };
2309
+ }
2310
+ const serverSetNamesLower = new Set(['context']);
2311
+ if (queryInfo) {
2312
+ for (const param of queryInfo.QueryParameters) {
2313
+ if (param.IsServerSet) {
2314
+ serverSetNamesLower.add(param.Name.trim().toLowerCase());
2315
+ }
2316
+ }
2317
+ }
2318
+ const cleanParameters = {};
2319
+ const strippedNames = [];
2320
+ for (const [key, value] of Object.entries(rawParameters)) {
2321
+ if (serverSetNamesLower.has(key.trim().toLowerCase())) {
2322
+ strippedNames.push(key);
2323
+ }
2324
+ else {
2325
+ cleanParameters[key] = value;
2326
+ }
2327
+ }
2328
+ return { cleanParameters, strippedNames };
2329
+ }
2330
+ function resolveReferencedEntitiesForQuery(provider, queryInfo) {
2331
+ if (!queryInfo || !provider.Entities) {
2332
+ return [];
2333
+ }
2334
+ const entityById = IndexByUUID(provider.Entities);
2335
+ const entityByName = new Map();
2336
+ for (const e of provider.Entities) {
2337
+ entityByName.set(e.Name, e);
2338
+ }
2339
+ const results = [];
2340
+ for (const qe of queryInfo.QueryEntities) {
2341
+ const found = (qe.EntityID ? entityById.Get(qe.EntityID) : undefined) ?? entityByName.get(qe.Entity);
2342
+ if (found) {
2343
+ results.push(found);
2344
+ }
2345
+ }
2346
+ return results;
2347
+ }
2348
+ /** Tree-shaking prevention loader for {@link BaseDocumentBlock} registrations. */
2349
+ export function LoadDocumentLiveBlocks() {
2350
+ // Intentionally empty — ensures @RegisterClass decorators in this module execute.
2351
+ }
2352
+ //# sourceMappingURL=DocumentLiveBlockEngine.js.map