@memberjunction/core 6.2.2 → 6.3.0-edge.1

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 (152) hide show
  1. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts +94 -0
  2. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts.map +1 -1
  3. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts +77 -4
  4. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts.map +1 -1
  5. package/dist/generic/appCapabilityRegistry.d.ts +106 -0
  6. package/dist/generic/appCapabilityRegistry.d.ts.map +1 -0
  7. package/dist/generic/appCapabilityRegistry.js +212 -0
  8. package/dist/generic/appCapabilityRegistry.js.map +1 -0
  9. package/dist/generic/baseEngine.d.ts +108 -3
  10. package/dist/generic/baseEngine.d.ts.map +1 -1
  11. package/dist/generic/baseEngine.js +891 -122
  12. package/dist/generic/baseEngine.js.map +1 -1
  13. package/dist/generic/baseEngineRegistry.d.ts +8 -0
  14. package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
  15. package/dist/generic/baseEngineRegistry.js +36 -11
  16. package/dist/generic/baseEngineRegistry.js.map +1 -1
  17. package/dist/generic/baseEntity.d.ts +155 -3
  18. package/dist/generic/baseEntity.d.ts.map +1 -1
  19. package/dist/generic/baseEntity.js +1146 -74
  20. package/dist/generic/baseEntity.js.map +1 -1
  21. package/dist/generic/baseRemotableOperation.d.ts +32 -0
  22. package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
  23. package/dist/generic/baseRemotableOperation.js +29 -0
  24. package/dist/generic/baseRemotableOperation.js.map +1 -1
  25. package/dist/generic/compositeKey.d.ts.map +1 -1
  26. package/dist/generic/compositeKey.js +3 -1
  27. package/dist/generic/compositeKey.js.map +1 -1
  28. package/dist/generic/constraintErrorRedaction.d.ts +26 -0
  29. package/dist/generic/constraintErrorRedaction.d.ts.map +1 -0
  30. package/dist/generic/constraintErrorRedaction.js +166 -0
  31. package/dist/generic/constraintErrorRedaction.js.map +1 -0
  32. package/dist/generic/crossEntityPolicyEngine.d.ts +172 -0
  33. package/dist/generic/crossEntityPolicyEngine.d.ts.map +1 -0
  34. package/dist/generic/crossEntityPolicyEngine.js +667 -0
  35. package/dist/generic/crossEntityPolicyEngine.js.map +1 -0
  36. package/dist/generic/dataHooks.d.ts +41 -4
  37. package/dist/generic/dataHooks.d.ts.map +1 -1
  38. package/dist/generic/dataHooks.js +82 -0
  39. package/dist/generic/dataHooks.js.map +1 -1
  40. package/dist/generic/databaseProviderBase.d.ts +96 -1
  41. package/dist/generic/databaseProviderBase.d.ts.map +1 -1
  42. package/dist/generic/databaseProviderBase.js +414 -44
  43. package/dist/generic/databaseProviderBase.js.map +1 -1
  44. package/dist/generic/documentNumberingEngine.d.ts +190 -0
  45. package/dist/generic/documentNumberingEngine.d.ts.map +1 -0
  46. package/dist/generic/documentNumberingEngine.js +739 -0
  47. package/dist/generic/documentNumberingEngine.js.map +1 -0
  48. package/dist/generic/entityInfo.d.ts +152 -8
  49. package/dist/generic/entityInfo.d.ts.map +1 -1
  50. package/dist/generic/entityInfo.js +507 -71
  51. package/dist/generic/entityInfo.js.map +1 -1
  52. package/dist/generic/entityLifecyclePolicy.d.ts +214 -0
  53. package/dist/generic/entityLifecyclePolicy.d.ts.map +1 -0
  54. package/dist/generic/entityLifecyclePolicy.js +708 -0
  55. package/dist/generic/entityLifecyclePolicy.js.map +1 -0
  56. package/dist/generic/entitySavePlan.d.ts +6 -0
  57. package/dist/generic/entitySavePlan.d.ts.map +1 -1
  58. package/dist/generic/entitySavePlan.js +145 -1
  59. package/dist/generic/entitySavePlan.js.map +1 -1
  60. package/dist/generic/entitySubtypeDriver.d.ts +49 -0
  61. package/dist/generic/entitySubtypeDriver.d.ts.map +1 -0
  62. package/dist/generic/entitySubtypeDriver.js +26 -0
  63. package/dist/generic/entitySubtypeDriver.js.map +1 -0
  64. package/dist/generic/fieldSecuritySQLGate.d.ts +17 -0
  65. package/dist/generic/fieldSecuritySQLGate.d.ts.map +1 -1
  66. package/dist/generic/fieldSecuritySQLGate.js +41 -1
  67. package/dist/generic/fieldSecuritySQLGate.js.map +1 -1
  68. package/dist/generic/filters/compositeFilter.d.ts +5 -1
  69. package/dist/generic/filters/compositeFilter.d.ts.map +1 -1
  70. package/dist/generic/filters/compositeFilter.js +127 -12
  71. package/dist/generic/filters/compositeFilter.js.map +1 -1
  72. package/dist/generic/filters/compositeFilterSQL.d.ts +121 -0
  73. package/dist/generic/filters/compositeFilterSQL.d.ts.map +1 -0
  74. package/dist/generic/filters/compositeFilterSQL.js +489 -0
  75. package/dist/generic/filters/compositeFilterSQL.js.map +1 -0
  76. package/dist/generic/filters/filter.types.d.ts +5 -2
  77. package/dist/generic/filters/filter.types.d.ts.map +1 -1
  78. package/dist/generic/filters/filter.types.js +4 -1
  79. package/dist/generic/filters/filter.types.js.map +1 -1
  80. package/dist/generic/filters/filterBuilder.d.ts +75 -0
  81. package/dist/generic/filters/filterBuilder.d.ts.map +1 -0
  82. package/dist/generic/filters/filterBuilder.js +104 -0
  83. package/dist/generic/filters/filterBuilder.js.map +1 -0
  84. package/dist/generic/filters/index.d.ts +2 -0
  85. package/dist/generic/filters/index.d.ts.map +1 -1
  86. package/dist/generic/filters/index.js +2 -0
  87. package/dist/generic/filters/index.js.map +1 -1
  88. package/dist/generic/interfaces.d.ts +125 -19
  89. package/dist/generic/interfaces.d.ts.map +1 -1
  90. package/dist/generic/interfaces.js +9 -10
  91. package/dist/generic/interfaces.js.map +1 -1
  92. package/dist/generic/localCacheManager.d.ts +54 -14
  93. package/dist/generic/localCacheManager.d.ts.map +1 -1
  94. package/dist/generic/localCacheManager.js +450 -106
  95. package/dist/generic/localCacheManager.js.map +1 -1
  96. package/dist/generic/metadata.d.ts +7 -5
  97. package/dist/generic/metadata.d.ts.map +1 -1
  98. package/dist/generic/metadata.js +29 -10
  99. package/dist/generic/metadata.js.map +1 -1
  100. package/dist/generic/providerBase.d.ts +405 -45
  101. package/dist/generic/providerBase.d.ts.map +1 -1
  102. package/dist/generic/providerBase.js +1107 -200
  103. package/dist/generic/providerBase.js.map +1 -1
  104. package/dist/generic/queryInfo.d.ts +5 -0
  105. package/dist/generic/queryInfo.d.ts.map +1 -1
  106. package/dist/generic/queryInfo.js +5 -0
  107. package/dist/generic/queryInfo.js.map +1 -1
  108. package/dist/generic/queryInfoInterfaces.d.ts +5 -0
  109. package/dist/generic/queryInfoInterfaces.d.ts.map +1 -1
  110. package/dist/generic/queryResultEnricher.d.ts +4 -1
  111. package/dist/generic/queryResultEnricher.d.ts.map +1 -1
  112. package/dist/generic/queryResultEnricher.js.map +1 -1
  113. package/dist/generic/queryTemplateContext.d.ts.map +1 -1
  114. package/dist/generic/queryTemplateContext.js +38 -3
  115. package/dist/generic/queryTemplateContext.js.map +1 -1
  116. package/dist/generic/relatedRecordCollection.d.ts +20 -0
  117. package/dist/generic/relatedRecordCollection.d.ts.map +1 -1
  118. package/dist/generic/relatedRecordCollection.js +257 -22
  119. package/dist/generic/relatedRecordCollection.js.map +1 -1
  120. package/dist/generic/remoteOperationDispatch.d.ts.map +1 -1
  121. package/dist/generic/remoteOperationDispatch.js +13 -1
  122. package/dist/generic/remoteOperationDispatch.js.map +1 -1
  123. package/dist/generic/saveEntityGraphOperation.d.ts +6 -0
  124. package/dist/generic/saveEntityGraphOperation.d.ts.map +1 -1
  125. package/dist/generic/saveEntityGraphOperation.js +8 -0
  126. package/dist/generic/saveEntityGraphOperation.js.map +1 -1
  127. package/dist/generic/securityInfo.d.ts +49 -2
  128. package/dist/generic/securityInfo.d.ts.map +1 -1
  129. package/dist/generic/securityInfo.js +139 -12
  130. package/dist/generic/securityInfo.js.map +1 -1
  131. package/dist/generic/telemetryManager.d.ts +40 -4
  132. package/dist/generic/telemetryManager.d.ts.map +1 -1
  133. package/dist/generic/telemetryManager.js +68 -15
  134. package/dist/generic/telemetryManager.js.map +1 -1
  135. package/dist/generic/transactionGroup.d.ts +66 -23
  136. package/dist/generic/transactionGroup.d.ts.map +1 -1
  137. package/dist/generic/transactionGroup.js +225 -57
  138. package/dist/generic/transactionGroup.js.map +1 -1
  139. package/dist/generic/util.d.ts.map +1 -1
  140. package/dist/generic/util.js +9 -3
  141. package/dist/generic/util.js.map +1 -1
  142. package/dist/index.d.ts +6 -0
  143. package/dist/index.d.ts.map +1 -1
  144. package/dist/index.js +6 -0
  145. package/dist/index.js.map +1 -1
  146. package/dist/tsconfig.tsbuildinfo +1 -0
  147. package/dist/views/runView.d.ts +61 -0
  148. package/dist/views/runView.d.ts.map +1 -1
  149. package/dist/views/runView.js +154 -3
  150. package/dist/views/runView.js.map +1 -1
  151. package/package.json +3 -3
  152. package/readme.md +6 -5
@@ -17,13 +17,14 @@ import { LibraryInfo } from "./libraryInfo.js";
17
17
  import { CompositeKey } from "./compositeKey.js";
18
18
  import { ExplorerNavigationItem } from "./explorerNavigationItem.js";
19
19
  import { Metadata } from "./metadata.js";
20
- import { RunView, IsMaterializedDataSource } from "../views/runView.js";
20
+ import { RunView, IsMaterializedDataSource, ExtractRunViewParameterNames } from "../views/runView.js";
21
21
  import { IsPlatformSQL } from "./platformSQL.js";
22
- import { GetDataHooks } from "./dataHooks.js";
22
+ import { GetDataHooks, IsPostRunViewProtectedEntity } from "./dataHooks.js";
23
23
  import { TransformSimpleObjectToEntityObject } from "./util.js";
24
24
  import { LoadRelatedRecordsBatched } from "./relatedRecordBatchLoader.js";
25
25
  import { GetLocalTimeZone } from "./contextTokens.js";
26
26
  import { FindQueryContextTokens, QueryContextCacheValues } from "./queryTemplateContext.js";
27
+ import { CompositeFilterSQLCompiler } from "./filters/compositeFilterSQL.js";
27
28
  /**
28
29
  * Creates a new instance of AllMetadata from a simple object.
29
30
  * Handles deserialization and proper instantiation of all metadata classes.
@@ -114,6 +115,39 @@ export const AllMetadataArrays = [
114
115
  { key: 'AllLibraries', class: LibraryInfo },
115
116
  { key: 'AllExplorerNavigationItems', class: ExplorerNavigationItem }
116
117
  ];
118
+ /**
119
+ * Produces a canonical, order- and case-insensitive key for a requested `Fields` list, suitable
120
+ * for keying memoized row projections and wire-serialization caches. Returns `''` when no field
121
+ * list is provided.
122
+ */
123
+ export function CanonicalFieldsKey(fields) {
124
+ if (!fields || fields.length === 0) {
125
+ return '';
126
+ }
127
+ const unique = new Set();
128
+ for (const f of fields) {
129
+ const normalized = f.trim().toLowerCase();
130
+ if (normalized.length > 0) {
131
+ unique.add(normalized);
132
+ }
133
+ }
134
+ if (unique.size === 0) {
135
+ return '';
136
+ }
137
+ return Array.from(unique).sort().join(',');
138
+ }
139
+ /**
140
+ * Memoizes frozen subset-projected row objects per `(sourceRow, canonicalFieldsKey)` when
141
+ * `ProjectRowsToFields` runs with `{ PreserveFrozen: true }` on frozen L1/cache rows. Weakly
142
+ * keyed on the source row so entries are automatically garbage-collected when cache slots evict.
143
+ */
144
+ const FrozenProjectedRowCache = new WeakMap();
145
+ /**
146
+ * Memoizes the entire frozen projected result array per `(frozenSourceArray, canonicalFieldsKey)`
147
+ * when `ProjectRowsToFields` runs with `{ PreserveFrozen: true }` on a frozen cached array.
148
+ * Turns repeat N-row subset projections into a single O(1) WeakMap lookup.
149
+ */
150
+ const FrozenProjectedArrayCache = new WeakMap();
117
151
  /**
118
152
  * Projects plain-object rows down to a caller-requested field subset, matching
119
153
  * field names case-insensitively (and ignoring surrounding whitespace).
@@ -130,11 +164,22 @@ export const AllMetadataArrays = [
130
164
  *
131
165
  * @param rows - Plain-object result rows (NOT BaseEntity objects)
132
166
  * @param requestedFields - The caller's original Fields list, or null for "all fields"
167
+ * @param options - Optional mutability/freeze preservation controls
133
168
  */
134
- export function ProjectRowsToFields(rows, requestedFields) {
169
+ export function ProjectRowsToFields(rows, requestedFields, options) {
135
170
  if (!requestedFields || requestedFields.length === 0 || !rows || rows.length === 0) {
136
171
  return rows;
137
172
  }
173
+ const preserveFrozen = Boolean(options?.PreserveFrozen);
174
+ const rowsAreFrozen = Object.isFrozen(rows);
175
+ const canonicalKey = preserveFrozen ? CanonicalFieldsKey(requestedFields) : '';
176
+ // O(1) array-level hit for repeat subset projections over the same frozen cached array.
177
+ if (preserveFrozen && rowsAreFrozen && canonicalKey.length > 0) {
178
+ const cachedArray = FrozenProjectedArrayCache.get(rows)?.get(canonicalKey);
179
+ if (cachedArray) {
180
+ return cachedArray;
181
+ }
182
+ }
138
183
  const requestedFieldSet = new Set(requestedFields.map(f => f.trim().toLowerCase()));
139
184
  // No-op probe: SQL result rows are uniform (same SELECT list), so if every key of
140
185
  // the first row is requested, the projection would copy every row unchanged —
@@ -154,18 +199,28 @@ export function ProjectRowsToFields(rows, requestedFields) {
154
199
  // to yield a per-caller row set the caller may mutate, and full coverage is not a
155
200
  // narrower promise than partial coverage — it just happens to project to the same
156
201
  // shape. Frozen input means `rows` is the cache's shared array, so returning it here
157
- // would quietly hand a Fields caller immutable rows and break that contract for the
158
- // one field list that covers everything. Fall through to the copy path in that case;
159
- // unfrozen input (the DB-miss path) keeps the allocation-free fast path.
160
- if (!Object.isFrozen(rows)) {
202
+ // would quietly hand a Fields caller immutable rows and break that contract unless
203
+ // the caller explicitly opts into `PreserveFrozen: true` (read-only wire transport).
204
+ if (preserveFrozen || !rowsAreFrozen) {
161
205
  return rows;
162
206
  }
163
207
  }
164
208
  }
165
209
  // Cache lowercase key→keep decisions across rows to avoid repeated allocations
166
210
  const keyCache = new Map();
167
- return rows.map((row) => {
211
+ const projected = rows.map((row) => {
168
212
  const source = row;
213
+ const canMemoizeFrozen = preserveFrozen &&
214
+ canonicalKey.length > 0 &&
215
+ source !== null &&
216
+ typeof source === 'object' &&
217
+ Object.isFrozen(source);
218
+ if (canMemoizeFrozen) {
219
+ const cachedProjected = FrozenProjectedRowCache.get(source)?.get(canonicalKey);
220
+ if (cachedProjected) {
221
+ return cachedProjected;
222
+ }
223
+ }
169
224
  const filtered = {};
170
225
  for (const key of Object.keys(source)) {
171
226
  let keep = keyCache.get(key);
@@ -177,8 +232,27 @@ export function ProjectRowsToFields(rows, requestedFields) {
177
232
  filtered[key] = source[key];
178
233
  }
179
234
  }
235
+ if (canMemoizeFrozen) {
236
+ Object.freeze(filtered);
237
+ let fieldMap = FrozenProjectedRowCache.get(source);
238
+ if (!fieldMap) {
239
+ fieldMap = new Map();
240
+ FrozenProjectedRowCache.set(source, fieldMap);
241
+ }
242
+ fieldMap.set(canonicalKey, filtered);
243
+ }
180
244
  return filtered;
181
245
  });
246
+ if (preserveFrozen && rowsAreFrozen && canonicalKey.length > 0) {
247
+ Object.freeze(projected);
248
+ let arrayMap = FrozenProjectedArrayCache.get(rows);
249
+ if (!arrayMap) {
250
+ arrayMap = new Map();
251
+ FrozenProjectedArrayCache.set(rows, arrayMap);
252
+ }
253
+ arrayMap.set(canonicalKey, projected);
254
+ }
255
+ return projected;
182
256
  }
183
257
  /**
184
258
  * Base class for all metadata providers in MemberJunction.
@@ -209,6 +283,14 @@ export class ProviderBase {
209
283
  * acts on its answer. Held as the promise (not a flag) so only its owner clears it.
210
284
  */
211
285
  this._refreshCheckInFlight = null;
286
+ /**
287
+ * The remote timestamps stored by the last refresh check whose status read succeeded; null after
288
+ * a check whose read failed. {@link RefreshIfNeeded} reuses the stored remote timestamps for its
289
+ * scoped reload only while they are this array, so a check whose read failed is followed by a
290
+ * fresh read. This prefers fresher stamps; it is not needed for correctness, because any stored
291
+ * stamps were read before the scoped dataset read starts.
292
+ */
293
+ this._checkedRemoteMetadataTimestamps = null;
212
294
  /**
213
295
  * Set when Config() adopts a snapshot it loaded from the server (which fetched the current user
214
296
  * with it); consumed by the next {@link preValidateAndRefresh}, which then has nothing to check.
@@ -221,8 +303,10 @@ export class ProviderBase {
221
303
  * so the caller's promise resolves with only their slice of results.
222
304
  */
223
305
  this._coalesceQueue = [];
224
- /** Timer handle for the coalesce flush */
306
+ /** Timer handle for the coalesce flush (when `CoalesceUseMicrotask === false`) */
225
307
  this._coalesceTimer = null;
308
+ /** True while a microtask-drain coalesce flush is scheduled */
309
+ this._coalesceMicrotaskScheduled = false;
226
310
  /**
227
311
  * In-flight + linger cache keyed by a deterministic fingerprint of
228
312
  * the RunViewParams batch. While a request is in-flight, concurrent
@@ -238,6 +322,14 @@ export class ProviderBase {
238
322
  */
239
323
  this._inflightViews = new Map();
240
324
  this._lingerInvalidationWired = false;
325
+ /**
326
+ * Lazily registers this instance (once per provider instance) for write-invalidation
327
+ * of in-flight/lingered RunView entries touching a written entity. Deleting an IN-FLIGHT
328
+ * entry is deliberate: late joiners must not share a query that may have read pre-commit
329
+ * data; the original caller still gets its own result, and the orphaned promise's stash
330
+ * step no-ops safely.
331
+ */
332
+ this._invalidationTargetRef = null;
241
333
  /**
242
334
  * Per-entity monotonic mutation counter incremented whenever an entity receives a
243
335
  * BaseEntity save/delete/remote-invalidate or an explicit {@link InvalidateRunViewDedupCache}
@@ -268,14 +360,19 @@ export class ProviderBase {
268
360
  */
269
361
  this._metadataReadsJoinTransaction = false;
270
362
  /**
271
- * The MJ_Metadata dataset items (code + entity name + row count) as of the last load. The remote
272
- * timestamps ({@link GetLatestMetadataUpdates}) are keyed by entity name while a dataset
273
- * read is scoped by item code, so this is the bridge that lets a staleness check be turned
274
- * into a scoped reload (see {@link PartialRefreshItemCodes}) and lets {@link adoptServerMetadata}
275
- * verify that the received dataset items' row counts match `_latestRemoteMetadataTimestamps`.
363
+ * The MJ_Metadata dataset items (code + entity name + row count) as of the last load, or as
364
+ * stored beside the snapshot a warm boot restored. The remote timestamps
365
+ * ({@link GetLatestMetadataUpdates}) are keyed by entity name while a dataset read is scoped by
366
+ * item code, so this is the bridge that lets a staleness check be turned into a scoped reload
367
+ * (see {@link MetadataRefreshScope}) and lets {@link adoptServerMetadata} verify that the
368
+ * received dataset items' row counts match `_latestRemoteMetadataTimestamps`.
276
369
  */
277
370
  this._metadataDatasetItems = null;
278
- /** Debounce timer for {@link scheduleMetadataMemberRefresh}. */
371
+ /** Failed refresh attempts in a row; picks the next delay from {@link MetadataRefreshRetryDelaysMs}. */
372
+ this._metadataRefreshRetries = 0;
373
+ /** Failed scoped reloads in a row; see {@link MetadataScopedReloadAttempts}. */
374
+ this._metadataScopedReloadFailures = 0;
375
+ /** Debounce timer for {@link scheduleMetadataMemberRefresh}, and for {@link scheduleMetadataRefreshRetry}. */
279
376
  this._metadataMemberRefreshTimer = null;
280
377
  // ── Metadata change notices from other servers ─────────────────────
281
378
  /** When the current run of undebounced peer notices began; caps how long the check is deferred. */
@@ -284,6 +381,17 @@ export class ProviderBase {
284
381
  this._peerMetadataNoticeRetries = 0;
285
382
  /** Debounce timer for {@link HandlePeerMetadataNotice}. */
286
383
  this._peerMetadataNoticeTimer = null;
384
+ /**
385
+ * Set by a write-event refresh that found a reload in flight and queued a follow-up pass; that
386
+ * pass consumes it and applies {@link applyWriteEventRule}. Without it the follow-up would take
387
+ * "no item moved" as "nothing changed", and the writer could miss its own write.
388
+ */
389
+ this._metadataWriteEventPending = false;
390
+ /**
391
+ * Set by an explicit full reload (a `Refresh()`) that found a reload in flight and queued a
392
+ * follow-up pass; that pass consumes it and runs in full, so the promise of a full reload holds.
393
+ */
394
+ this._metadataFullReloadRequested = false;
287
395
  this._metadataMemberRefreshWaits = 0;
288
396
  this._clientFingerprintMemo = new WeakMap();
289
397
  this._requestDeniedReadFields = new WeakMap();
@@ -298,6 +406,9 @@ export class ProviderBase {
298
406
  this._lastRemoteTimestampReadReached = true;
299
407
  /** Guard for {@link logMetadataSnapshotDisabledOnce}. */
300
408
  this._metadataSnapshotSkipLogged = false;
409
+ this._metadataSaveTimer = null;
410
+ this._inFlightMetadataSave = null;
411
+ this._hasPendingMetadataSaveWhileInFlight = false;
301
412
  }
302
413
  /**
303
414
  * Whether this provider can execute a multi-record unit of work atomically, in-process.
@@ -364,6 +475,17 @@ export class ProviderBase {
364
475
  * all engines that fire in the same tick, without adding perceptible delay.
365
476
  */
366
477
  static { this.CoalesceWindowMs = 10; }
478
+ /**
479
+ * Controls whether `RunViews` coalescing drains via microtasks (`queueMicrotask`) instead
480
+ * of a wall-clock `setTimeout(..., CoalesceWindowMs)` timer when `CoalesceWindowMs > 0`.
481
+ *
482
+ * When `true` (default), concurrent calls in the same synchronous turn or immediate
483
+ * `Promise` / `BaseEngine.Load` microtask hops coalesce into one mega-batch and flush as
484
+ * soon as the microtask queue stabilizes (bounded at 8 hops), eliminating the 10–16ms timer
485
+ * floor (and ~1,000ms background-tab timer throttling) on isolated queries. Set to `false`
486
+ * to use the fixed `setTimeout(..., CoalesceWindowMs)` timer window.
487
+ */
488
+ static { this.CoalesceUseMicrotask = true; }
367
489
  // ── Request Deduplication + Linger Window ──────────────────────────
368
490
  /**
369
491
  * How long (ms) a resolved RunViews result stays available for instant
@@ -514,12 +636,26 @@ export class ProviderBase {
514
636
  return results;
515
637
  }
516
638
  /**
517
- * Lazily registers this instance (once per provider instance) for write-invalidation
518
- * of in-flight/lingered RunView entries touching a written entity. Deleting an IN-FLIGHT
519
- * entry is deliberate: late joiners must not share a query that may have read pre-commit
520
- * data; the original caller still gets its own result, and the orphaned promise's stash
521
- * step no-ops safely.
639
+ * Number of live/uncollected `ProviderBase` instances currently registered for in-flight
640
+ * view invalidation callbacks.
641
+ */
642
+ static get ActiveInvalidationTargetCount() {
643
+ return ProviderBase._invalidationTargets.size;
644
+ }
645
+ /**
646
+ * Immediately removes this provider instance from the global in-flight invalidation target set
647
+ * and clears per-instance mutation state. Call on short-lived per-request server providers
648
+ * when the HTTP response closes so `_invalidationTargets` does not accumulate thousands of
649
+ * `WeakRef`s between major garbage collections.
522
650
  */
651
+ DetachInvalidationListeners() {
652
+ if (this._invalidationTargetRef) {
653
+ ProviderBase._invalidationTargets.delete(this._invalidationTargetRef);
654
+ this._invalidationTargetRef = null;
655
+ }
656
+ this._lingerInvalidationWired = false;
657
+ this._entityMutationVersions.clear();
658
+ }
523
659
  ensureInflightViewInvalidation() {
524
660
  // Deliberately ABOVE the per-instance guard: the static wiring is re-checked on every call,
525
661
  // not just the first. A long-lived provider (Explorer's client provider, MJServer's system
@@ -531,7 +667,9 @@ export class ProviderBase {
531
667
  return;
532
668
  }
533
669
  this._lingerInvalidationWired = true;
534
- ProviderBase._invalidationTargets.add(new WeakRef(this));
670
+ const ref = new WeakRef(this);
671
+ this._invalidationTargetRef = ref;
672
+ ProviderBase._invalidationTargets.add(ref);
535
673
  }
536
674
  /**
537
675
  * Returns the current monotonic mutation version for `entityName` (case-insensitive).
@@ -636,6 +774,33 @@ export class ProviderBase {
636
774
  static { this._queryFamilyItemCodes = [
637
775
  'QueryCategories', 'Queries', 'QueryFields', 'QueryPermissions', 'QueryEntities', 'QueryParameters', 'QueryDependencies', 'QuerySQLs',
638
776
  ]; }
777
+ /**
778
+ * MJ_Metadata item codes that {@link GetAllMetadata} reads to build the metadata: every
779
+ * {@link AllMetadataArrays} item, plus the items it folds into entities and applications. The
780
+ * shipped dataset also carries items the build never reads (`Dashboards`,
781
+ * `Dashboard_Categories`); a change to one of those cannot change the built metadata, so it
782
+ * needs no reload (see {@link MetadataRefreshScope}).
783
+ */
784
+ static get MetadataBuildItemCodes() {
785
+ return ProviderBase._metadataBuildItemCodes;
786
+ }
787
+ /** The items {@link GetAllMetadata} folds into entities (PostProcessEntityMetadata) and applications. */
788
+ static { this._metadataFoldedItemCodes = [
789
+ 'EntityFields', 'EntityFieldValues', 'EntityPermissions', 'EntityRelationships', 'EntitySettings', 'EntityOrganicKeys',
790
+ 'EntityOrganicKeyRelatedEntities', 'EntityFieldPermissions', 'EntityAlternateBaseViews', 'EntityUniqueKeys',
791
+ 'ApplicationEntities', 'ApplicationSettings',
792
+ ]; }
793
+ static { this._metadataBuildItemCodes = new Set([...AllMetadataArrays.map(m => m.key.substring(3)), ...ProviderBase._metadataFoldedItemCodes]); }
794
+ /**
795
+ * Delays, in milliseconds, before each retry of a metadata refresh that failed; the last one
796
+ * repeats. A failed timestamp read, a failed scoped reload and a failed full reload all keep
797
+ * the metadata already loaded and try again later. None of them escalates to a full reload:
798
+ * that is the most expensive read the provider makes, and these failures come when the server
799
+ * is busiest (an exhausted connection pool, a timed-out status query).
800
+ */
801
+ static { this.MetadataRefreshRetryDelaysMs = [15000, 30000, 60000, 120000, 300000]; }
802
+ /** Failed scoped reloads in a row before the full reload is used instead. */
803
+ static { this.MetadataScopedReloadAttempts = 3; }
639
804
  /** The synthetic roll-up row {@link GetLatestMetadataUpdates} appends to the per-entity timestamps. */
640
805
  static { this._allMetadataTypeName = 'All Entity Metadata'; }
641
806
  /**
@@ -652,6 +817,9 @@ export class ProviderBase {
652
817
  names.add(n);
653
818
  }
654
819
  }
820
+ for (const skipped of this.skippedMetadataEntityNames(dataset.Results ?? [])) {
821
+ names.delete(skipped);
822
+ }
655
823
  if (names.size === 0) {
656
824
  return; // a failed/empty load must not erase a previously recorded set
657
825
  }
@@ -667,6 +835,93 @@ export class ProviderBase {
667
835
  }));
668
836
  this.ensureInflightViewInvalidation();
669
837
  }
838
+ /**
839
+ * The MJ_Metadata item codes that hold the saved-query metadata: the saved-query family (see
840
+ * {@link PartialRefreshMetadataItemCodes}) and the SQL dialects. They are read only when the
841
+ * provider is configured with {@link ProviderConfigDataBase.LoadQueryMetadata}.
842
+ */
843
+ static get QueryMetadataItemCodes() {
844
+ return [...ProviderBase._queryFamilyItemCodes, 'SQLDialects'];
845
+ }
846
+ /**
847
+ * Whether this provider loads the saved-query metadata into its metadata object (see
848
+ * {@link ProviderConfigDataBase.LoadQueryMetadata}). False unless the configuration says true.
849
+ * A provider that adopted the global provider's metadata reports the global provider's
850
+ * setting instead, since that is what decided whether the adopted metadata holds queries.
851
+ */
852
+ get LoadsQueryMetadata() {
853
+ return this._adoptedLoadsQueryMetadata ?? this._ConfigData?.LoadQueryMetadata === true;
854
+ }
855
+ /**
856
+ * The item filters every read of the MJ_Metadata dataset uses — the data, its status, and the
857
+ * local dataset cache — so all of them describe the same row set. Null when every item is read.
858
+ * Otherwise each item this provider does not load gets a `1=0` filter: the server runs no SQL
859
+ * for it, and its status is constant, so writes to it never make the metadata look stale.
860
+ */
861
+ get MetadataDatasetItemFilters() {
862
+ if (this.LoadsQueryMetadata) {
863
+ return null;
864
+ }
865
+ return ProviderBase.QueryMetadataItemCodes.map(code => ({ ItemCode: code, Filter: '1=0' }));
866
+ }
867
+ /**
868
+ * The MJ_Metadata item codes THIS provider builds its metadata from: {@link MetadataBuildItemCodes}
869
+ * without the items it does not read (see {@link MetadataDatasetItemFilters}). A change only to
870
+ * the others needs no reload, as for any item the build never reads.
871
+ */
872
+ get BuiltMetadataItemCodes() {
873
+ if (this.LoadsQueryMetadata) {
874
+ return ProviderBase.MetadataBuildItemCodes;
875
+ }
876
+ const built = new Set(ProviderBase.MetadataBuildItemCodes);
877
+ for (const code of ProviderBase.QueryMetadataItemCodes) {
878
+ built.delete(code);
879
+ }
880
+ return built;
881
+ }
882
+ /**
883
+ * Empties the query-metadata arrays of `metadata` when this provider does not load them. A stored
884
+ * snapshot written by a process that did load them would otherwise hold those rows in memory for
885
+ * the life of this process, behind getters that return nothing.
886
+ */
887
+ dropUnloadedQueryMetadata(metadata) {
888
+ if (this.LoadsQueryMetadata) {
889
+ return;
890
+ }
891
+ metadata.AllQueryCategories = [];
892
+ metadata.AllQueries = [];
893
+ metadata.AllQueryFields = [];
894
+ metadata.AllQueryPermissions = [];
895
+ metadata.AllQueryEntities = [];
896
+ metadata.AllQueryParameters = [];
897
+ metadata.AllQueryDependencies = [];
898
+ metadata.AllSQLDialects = [];
899
+ metadata.AllQuerySQLs = [];
900
+ }
901
+ /** Whether `code` is an MJ_Metadata item this provider does not read (see {@link MetadataDatasetItemFilters}). */
902
+ isSkippedMetadataItem(code) {
903
+ return !!code && !this.LoadsQueryMetadata && ProviderBase.QueryMetadataItemCodes.includes(code);
904
+ }
905
+ /**
906
+ * Lowercased names of the entities that back only items this provider does not read. A write to
907
+ * one of them cannot change this provider's metadata, so they are left out of the membership set
908
+ * — otherwise each such write would schedule a refresh that finds no timestamp moved and falls
909
+ * back to a full reload.
910
+ */
911
+ skippedMetadataEntityNames(items) {
912
+ const skipped = new Set();
913
+ const read = new Set();
914
+ for (const item of items) {
915
+ const name = item.EntityName?.trim().toLowerCase();
916
+ if (name) {
917
+ (this.isSkippedMetadataItem(item.Code) ? skipped : read).add(name);
918
+ }
919
+ }
920
+ for (const name of read) {
921
+ skipped.delete(name);
922
+ }
923
+ return skipped;
924
+ }
670
925
  /**
671
926
  * Result of {@link SweepMetadataAgainstDatabase}.
672
927
  */
@@ -955,12 +1210,27 @@ export class ProviderBase {
955
1210
  this._peerMetadataNoticeTimer = timer;
956
1211
  }
957
1212
  /**
958
- * How this provider refreshes after a metadata member entity changed. The base behavior is a
959
- * hard {@link Refresh} — correct for database providers, where the process that PERFORMED the
960
- * write is the one refreshing, so re-checking staleness first is wasted work and the re-read
961
- * must bypass every cache layer. Transport providers (GraphQL) override this with a staleness
962
- * check so a browser doesn't re-pull the full metadata graph for a change the server-side
963
- * timestamp comparison can disconfirm.
1213
+ * How this provider refreshes after a metadata member entity changed. The base behavior
1214
+ * re-reads the authoritative timestamps once (the status query is read from the database
1215
+ * every time, never from a cache layer) and reloads only what they show changed — see
1216
+ * {@link MetadataRefreshScope}: nothing, the saved-query family (through
1217
+ * {@link ReloadMetadata}, which reuses that read instead of reading the timestamps again), or
1218
+ * everything (a hard {@link Refresh}, which bypasses every cache layer).
1219
+ *
1220
+ * The caller holds positive evidence that a member entity was written, so "no item moved" is
1221
+ * NOT taken as "nothing changed" here: a write committed with a stamp older than the item's
1222
+ * current max — on PostgreSQL `NOW()` is the transaction start, so any in-place edit inside a
1223
+ * transaction that outlived a peer's later write; on SQL Server the statement-to-commit
1224
+ * window — leaves both the max stamp and the row count where they were. Only a change the
1225
+ * timestamps positively attribute to items the metadata build never reads (`Dashboards`) is
1226
+ * answered without a reload. The same rule governs the follow-up pass that a write arriving
1227
+ * mid-reload queues (see `_metadataWriteEventPending`).
1228
+ *
1229
+ * A timestamp read that fails while metadata is loaded is retried on
1230
+ * {@link MetadataRefreshRetryDelaysMs}; it is not a reason for a full reload. With nothing
1231
+ * loaded there is nothing to keep serving, so the full load runs. Transport providers
1232
+ * (GraphQL) override this with a staleness check so a browser doesn't re-pull the full
1233
+ * metadata graph for a change the server-side timestamp comparison can disconfirm.
964
1234
  */
965
1235
  async RefreshAfterMetadataMemberChange() {
966
1236
  if (this.MetadataMemberRefreshMustWait) {
@@ -984,26 +1254,99 @@ export class ProviderBase {
984
1254
  // concurrently here, because that mutates _latestRemoteMetadataTimestamps out from under
985
1255
  // the in-flight pass before it runs adoptServerMetadata(). Instead, delegate directly to
986
1256
  // ReloadMetadata, which sets _metadataReloadQueued = true and re-reads authoritative
987
- // remote timestamps at the start of the queued follow-up pass.
1257
+ // remote timestamps at the start of the queued follow-up pass. That pass must apply the
1258
+ // write-event rule (no item moved ⇒ full reload), so the evidence is handed to it.
1259
+ this._metadataWriteEventPending = true;
988
1260
  return this.ReloadMetadata(true, undefined, true);
989
1261
  }
1262
+ if (!this.AllowRefresh) {
1263
+ return this.Refresh();
1264
+ }
990
1265
  // The writer holds positive evidence, so the timestamps are re-read from the authoritative
991
- // status query. When they attribute the change entirely to the saved-query family (see
992
- // PartialRefreshMetadataItemCodes) only that family is reloaded, cache layers bypassed as a
993
- // hard refresh would. Anything that cannot be attributed — another item moved, the status
994
- // read failed, or it claims nothing changed — keeps the base policy: a HARD Refresh().
995
- let scoped = false;
1266
+ // status query, and only what they show changed is reloaded (see MetadataRefreshScope). A
1267
+ // change only to items the build never reads needs no reload. But "no item moved at all"
1268
+ // is not trusted here: a committed write can leave the max stamp and the row count where
1269
+ // they were (see the method doc), and the writer must see its own write.
1270
+ let timestampsRead = false;
996
1271
  try {
997
- scoped = this.AllowRefresh && await this.RefreshRemoteMetadataTimestamps() && this.PartialRefreshItemCodes() !== null;
1272
+ timestampsRead = await this.RefreshRemoteMetadataTimestamps();
998
1273
  }
999
1274
  catch (e) {
1000
- LogError(`Metadata refresh after a member-entity change could not read the timestamps; running a full refresh: ${e instanceof Error ? e.message : String(e)}`);
1275
+ LogError(`[Metadata] A refresh after a metadata change could not read the timestamps: ${e instanceof Error ? e.message : String(e)}`);
1001
1276
  }
1002
- if (scoped) {
1003
- return this.ReloadMetadata(true, undefined, true);
1277
+ if (!timestampsRead) {
1278
+ if (this.holdsMetadata) {
1279
+ this.scheduleMetadataRefreshRetry('the metadata timestamps could not be read');
1280
+ return true;
1281
+ }
1282
+ return this.Refresh(); // nothing loaded to keep serving
1283
+ }
1284
+ const scope = ProviderBase.applyWriteEventRule(this.MetadataRefreshScope());
1285
+ if (scope.Kind === 'none') {
1286
+ this.markMetadataCurrent();
1287
+ return true;
1004
1288
  }
1289
+ if (scope.Kind === 'scoped') {
1290
+ return this.ReloadMetadata(true, undefined, true, true);
1291
+ }
1292
+ LogStatus(`[Metadata] Full reload needed: ${scope.Reason}`);
1005
1293
  return this.Refresh();
1006
1294
  }
1295
+ /**
1296
+ * The write-event rule: a refresh prompted by a member-entity write knows something changed, so
1297
+ * a `none` scope in which no item moved at all becomes a full reload. A `none` in which only
1298
+ * items the build never reads moved stands — the timestamps positively attribute the change.
1299
+ */
1300
+ static applyWriteEventRule(scope) {
1301
+ if (scope.Kind === 'none' && !scope.AnyItemMoved) {
1302
+ return { Kind: 'full', Reason: 'a metadata member entity was written, but no item timestamp moved' };
1303
+ }
1304
+ return scope;
1305
+ }
1306
+ /** True when this provider holds metadata it can keep serving while a refresh is retried. */
1307
+ get holdsMetadata() {
1308
+ return (this._localMetadata?.AllEntities?.length ?? 0) > 0;
1309
+ }
1310
+ /**
1311
+ * Runs {@link RefreshAfterMetadataMemberChange} again after the next delay in
1312
+ * {@link MetadataRefreshRetryDelaysMs}. The retry shares the member-change timer: a refresh
1313
+ * that is already pending covers it, a new write re-arms it with the short debounce, and
1314
+ * {@link CancelPendingMetadataMemberRefresh} cancels it. The timer does not keep a Node
1315
+ * process alive.
1316
+ */
1317
+ scheduleMetadataRefreshRetry(reason) {
1318
+ if (this._metadataMemberRefreshTimer) {
1319
+ return;
1320
+ }
1321
+ const delays = ProviderBase.MetadataRefreshRetryDelaysMs;
1322
+ const delay = delays.length > 0 ? delays[Math.min(this._metadataRefreshRetries, delays.length - 1)] : 0;
1323
+ this._metadataRefreshRetries++;
1324
+ LogStatus(`[Metadata] Refresh postponed (${reason}); trying again in ${Math.round(delay / 1000)} s`);
1325
+ const timer = setTimeout(() => {
1326
+ this._metadataMemberRefreshTimer = null;
1327
+ this.RefreshAfterMetadataMemberChange().catch((e) => {
1328
+ LogError(`Metadata refresh retry failed: ${e instanceof Error ? e.message : String(e)}`);
1329
+ });
1330
+ }, delay);
1331
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
1332
+ timer.unref();
1333
+ }
1334
+ this._metadataMemberRefreshTimer = timer;
1335
+ }
1336
+ /**
1337
+ * The timestamps show nothing the metadata build reads has changed: stamp the held snapshot
1338
+ * with them, so the next check agrees. Only the in-memory stamp moves; re-saving the snapshot
1339
+ * would serialize the whole graph for a change it does not contain.
1340
+ */
1341
+ markMetadataCurrent() {
1342
+ this._latestLocalMetadataTimestamps = this._latestRemoteMetadataTimestamps;
1343
+ this.resetMetadataRefreshFailures();
1344
+ }
1345
+ /** The metadata is current again: the next failure starts at the first retry delay. */
1346
+ resetMetadataRefreshFailures() {
1347
+ this._metadataRefreshRetries = 0;
1348
+ this._metadataScopedReloadFailures = 0;
1349
+ }
1007
1350
  /**
1008
1351
  * How many consecutive windows a member-change refresh may wait on
1009
1352
  * {@link MetadataMemberRefreshMustWait} before it is dropped. At the default 500ms window
@@ -1180,29 +1523,30 @@ export class ProviderBase {
1180
1523
  // BypassCache skips this entirely — used by maintenance actions that need
1181
1524
  // to see the true DB state after direct SQL inserts.
1182
1525
  const preResult = await this.PreRunView(params, contextUser);
1526
+ const effectiveParams = preResult.effectiveParams ?? params;
1183
1527
  if (preResult.cachedResult) {
1184
1528
  // Cache hit — transform and return directly
1185
- LogStatusEx({ message: ` ✅ [Cache HIT] RunView "${params.EntityName || params.ViewName || 'unknown'}" — ${preResult.cachedResult.Results?.length ?? 0} rows from cache, no DB query`, verboseOnly: true });
1186
- await this.TransformSimpleObjectToEntityObject(params, preResult.cachedResult, contextUser);
1187
- await this.ApplyPostRunViewHooksToCacheHit(params, preResult.cachedResult, contextUser);
1529
+ LogStatusEx({ message: ` ✅ [Cache HIT] RunView "${effectiveParams.EntityName || effectiveParams.ViewName || 'unknown'}" — ${preResult.cachedResult.Results?.length ?? 0} rows from cache, no DB query`, verboseOnly: true });
1530
+ await this.TransformSimpleObjectToEntityObject(effectiveParams, preResult.cachedResult, contextUser);
1531
+ await this.ApplyPostRunViewHooksToCacheHit(effectiveParams, preResult.cachedResult, contextUser);
1188
1532
  TelemetryManager.Instance.EndEvent(preResult.telemetryEventId, {
1189
1533
  cacheHit: true,
1190
1534
  cacheStatus: preResult.cacheStatus,
1191
1535
  resultCount: preResult.cachedResult.Results?.length ?? 0
1192
1536
  });
1193
- if (params.OnDataChanged && preResult.fingerprint) {
1194
- preResult.cachedResult.Unsubscribe = LocalCacheManager.Instance.RegisterChangeCallback(preResult.fingerprint, params.OnDataChanged);
1537
+ if (effectiveParams.OnDataChanged && preResult.fingerprint) {
1538
+ preResult.cachedResult.Unsubscribe = LocalCacheManager.Instance.RegisterChangeCallback(preResult.fingerprint, effectiveParams.OnDataChanged);
1195
1539
  }
1196
- ProviderBase.clearSkippedTotalRowCount(params, preResult.cachedResult);
1540
+ ProviderBase.clearSkippedTotalRowCount(effectiveParams, preResult.cachedResult);
1197
1541
  return preResult.cachedResult;
1198
1542
  }
1199
1543
  // Cache miss — execute query, then post-process (stores in cache)
1200
- LogStatusEx({ message: ` 🔍 [Cache MISS] RunView "${params.EntityName || params.ViewName || 'unknown'}" — querying database`, verboseOnly: true });
1201
- const result = await this.InternalRunView(params, contextUser);
1544
+ LogStatusEx({ message: ` 🔍 [Cache MISS] RunView "${effectiveParams.EntityName || effectiveParams.ViewName || 'unknown'}" — querying database`, verboseOnly: true });
1545
+ const result = await this.InternalRunView(effectiveParams, contextUser);
1202
1546
  // PostRunView copies any hook-supplied replacement onto `result` in place, so this
1203
1547
  // reference reflects the hook chain's output.
1204
- await this.PostRunView(result, params, preResult, contextUser);
1205
- ProviderBase.clearSkippedTotalRowCount(params, result);
1548
+ await this.PostRunView(result, effectiveParams, preResult, contextUser);
1549
+ ProviderBase.clearSkippedTotalRowCount(effectiveParams, result);
1206
1550
  return result;
1207
1551
  }
1208
1552
  // Delegate to RunViews, which uses the smart cache check (lightweight maxUpdatedAt +
@@ -1428,18 +1772,46 @@ export class ProviderBase {
1428
1772
  resolve: resolve,
1429
1773
  reject
1430
1774
  });
1431
- // Start the coalesce timer if not already running
1432
- if (!this._coalesceTimer) {
1775
+ if (ProviderBase.CoalesceUseMicrotask) {
1776
+ if (!this._coalesceMicrotaskScheduled && !this._coalesceTimer) {
1777
+ this._coalesceMicrotaskScheduled = true;
1778
+ this.scheduleMicrotaskCoalesceDrain(this._coalesceQueue.length, 0);
1779
+ }
1780
+ }
1781
+ else if (!this._coalesceTimer && !this._coalesceMicrotaskScheduled) {
1782
+ // Start the coalesce timer if not already running
1433
1783
  this._coalesceTimer = setTimeout(() => this.flushCoalesceQueue(), ProviderBase.CoalesceWindowMs);
1434
1784
  }
1435
1785
  });
1436
1786
  }
1787
+ /**
1788
+ * Drains the coalesce queue via `queueMicrotask`. Yields a minimum of 6 microtask hops
1789
+ * (~4µs) so sibling `StartupManager` engines finishing their initial `ResolveContextUser`
1790
+ * and `PreRunViews` awaits reach the queue, and continues yielding (bounded at 16 hops)
1791
+ * while queue length is still growing; flushes immediately once queue growth settles.
1792
+ */
1793
+ scheduleMicrotaskCoalesceDrain(seenLength, hop) {
1794
+ queueMicrotask(() => {
1795
+ const currentLength = this._coalesceQueue.length;
1796
+ if (currentLength === 0) {
1797
+ this._coalesceMicrotaskScheduled = false;
1798
+ return;
1799
+ }
1800
+ if (hop < 6 || (currentLength > seenLength && hop < 16)) {
1801
+ this.scheduleMicrotaskCoalesceDrain(currentLength, hop + 1);
1802
+ return;
1803
+ }
1804
+ this._coalesceMicrotaskScheduled = false;
1805
+ void this.flushCoalesceQueue();
1806
+ });
1807
+ }
1437
1808
  /**
1438
1809
  * Flushes the coalesce queue: merges all pending RunViews params into one
1439
1810
  * mega-batch, executes it, then splits results back to each original caller.
1440
1811
  */
1441
1812
  async flushCoalesceQueue() {
1442
1813
  this._coalesceTimer = null;
1814
+ this._coalesceMicrotaskScheduled = false;
1443
1815
  // Grab and clear the queue atomically
1444
1816
  const queue = this._coalesceQueue.splice(0);
1445
1817
  if (queue.length === 0)
@@ -1737,7 +2109,24 @@ export class ProviderBase {
1737
2109
  * widens and caches.
1738
2110
  */
1739
2111
  shouldWidenAndPopulateCache(param) {
1740
- return this.runViewCacheEligible(param);
2112
+ if (!this.runViewCacheEligible(param)) {
2113
+ return false;
2114
+ }
2115
+ // On the server, when the caller requested a narrow `Fields` projection without
2116
+ // explicitly asking for `CacheLocal: true`, do not widen to `SELECT *` when:
2117
+ // 1. `UserSearchString` is populated (ad-hoc search-as-you-type queries would otherwise
2118
+ // pull every wide NVARCHAR(MAX) column and allocate per-keystroke cache slots), or
2119
+ // 2. `LocalCacheManager` is currently batching writes for this provider (`SetRunViewResult`
2120
+ // drops cache writes while a write batch is open, so widening would be pure waste).
2121
+ if (this.TrustLocalCacheCompletely && param.CacheLocal !== true && this.hasNarrowFieldsOverride(param)) {
2122
+ if ((param.UserSearchString ?? '').trim().length > 0) {
2123
+ return false;
2124
+ }
2125
+ if (LocalCacheManager.Instance.IsInitialized && LocalCacheManager.Instance.IsBatchingEntityEvents(this)) {
2126
+ return false;
2127
+ }
2128
+ }
2129
+ return true;
1741
2130
  }
1742
2131
  /**
1743
2132
  * True when the request targets an `AlternateBaseView` (explicitly on `param.AlternateBaseView`
@@ -2309,7 +2698,10 @@ export class ProviderBase {
2309
2698
  * `resolvable` is true.
2310
2699
  *
2311
2700
  * The BASE implementation resolves from the metadata `Queries` cache and enforces the
2312
- * ROLES-ONLY `QueryInfo.UserCanRun` — the strongest check available at this layer.
2701
+ * ROLES-ONLY `QueryInfo.UserCanRun` — the strongest check available at this layer. That cache
2702
+ * is loaded only when the provider is configured with `LoadQueryMetadata`; otherwise every
2703
+ * request is unresolvable here, so a provider that executes or caches saved queries overrides
2704
+ * this to resolve from `QueryEngine`.
2313
2705
  * Providers with richer query metadata MUST override this to enforce the SAME authorization
2314
2706
  * their miss path enforces (`GenericDatabaseProvider` overrides with
2315
2707
  * `MJQueryEntityExtended.UserCanRun`, which adds entity CanRead + recursive composition
@@ -2319,6 +2711,9 @@ export class ProviderBase {
2319
2711
  * the miss path also checked entity read permissions).
2320
2712
  */
2321
2713
  ResolveQueryCacheAuthorization(params, user) {
2714
+ if (!this.LoadsQueryMetadata) {
2715
+ return { resolvable: false, authorized: false };
2716
+ }
2322
2717
  const requestedPath = params.CategoryPath?.trim().toLowerCase();
2323
2718
  const qInfo = this.Queries.find(q => (params.QueryID && UUIDsEqual(q.ID, params.QueryID))
2324
2719
  || (!params.QueryID && params.QueryName
@@ -2950,9 +3345,16 @@ export class ProviderBase {
2950
3345
  if (!entity) {
2951
3346
  return;
2952
3347
  }
3348
+ if (params.Filter) {
3349
+ CompositeFilterSQLCompiler.AssertFieldsAllowed(params.Filter, entity, contextUser);
3350
+ }
2953
3351
  const view = params.ViewEntity;
3352
+ const parameterNames = ExtractRunViewParameterNames(params.Parameters);
3353
+ if (parameterNames.size > 0) {
3354
+ this.AssertClausesRespectFieldSecurityForEntity(entity, [params.ExtraFilter], contextUser, parameterNames);
3355
+ }
2954
3356
  this.AssertClausesRespectFieldSecurityForEntity(entity, [
2955
- params.ExtraFilter,
3357
+ ...(parameterNames.size > 0 ? [] : [params.ExtraFilter]),
2956
3358
  params.OverrideExcludeFilter,
2957
3359
  ...(params.Aggregates ?? []).map(a => a?.expression),
2958
3360
  view ? view.Get('WhereClause') : undefined,
@@ -2971,8 +3373,8 @@ export class ProviderBase {
2971
3373
  * The shared entry point for every clause slot a provider runs: RunView parameters, a saved
2972
3374
  * view's stored clauses, dataset item filters, user-search text spliced as SQL.
2973
3375
  */
2974
- AssertClausesRespectFieldSecurityForEntity(entity, clauses, user) {
2975
- this.assertFragmentsAllowed(entity, clauses, user, (sql, context) => FieldSecuritySQLGate.FindViolation(sql, context));
3376
+ AssertClausesRespectFieldSecurityForEntity(entity, clauses, user, parameterNames) {
3377
+ this.assertFragmentsAllowed(entity, clauses, user, (sql, context) => FieldSecuritySQLGate.FindViolation(sql, context), parameterNames);
2976
3378
  }
2977
3379
  /**
2978
3380
  * {@link AssertClausesRespectFieldSecurityForEntity} for ORDER BY fragments, which also refuses
@@ -2983,8 +3385,14 @@ export class ProviderBase {
2983
3385
  this.assertFragmentsAllowed(entity, orderBys, user, (sql, context) => FieldSecuritySQLGate.FindSortViolation(sql, context));
2984
3386
  }
2985
3387
  /** Throws the field-security error for the first of `fragments` that `find` refuses. */
2986
- assertFragmentsAllowed(entity, fragments, user, find) {
2987
- const context = { User: user, Dialect: this.PlatformKey, Catalog: this.Entities, TargetEntity: entity };
3388
+ assertFragmentsAllowed(entity, fragments, user, find, parameterNames) {
3389
+ const context = {
3390
+ User: user,
3391
+ Dialect: this.PlatformKey,
3392
+ Catalog: this.Entities,
3393
+ TargetEntity: entity,
3394
+ ParameterNames: parameterNames,
3395
+ };
2988
3396
  for (const clause of fragments) {
2989
3397
  if (typeof clause !== 'string' || clause.trim().length === 0) {
2990
3398
  continue;
@@ -3330,6 +3738,7 @@ export class ProviderBase {
3330
3738
  // PostRunView to project cache-miss DB results back to the caller's shape
3331
3739
  callerRequestedFields: callerRequestedFieldsForPost,
3332
3740
  populateCache: willPopulateCache,
3741
+ effectiveParams: params,
3333
3742
  };
3334
3743
  }
3335
3744
  /**
@@ -4162,7 +4571,7 @@ export class ProviderBase {
4162
4571
  async RunPreRunViewHooks(params, contextUser) {
4163
4572
  const hooks = GetDataHooks('PreRunView');
4164
4573
  for (const hook of hooks) {
4165
- params = await hook(params, contextUser);
4574
+ params = await hook(params, contextUser, this);
4166
4575
  }
4167
4576
  return params;
4168
4577
  }
@@ -4180,7 +4589,7 @@ export class ProviderBase {
4180
4589
  async RunPostRunViewHooks(params, result, contextUser) {
4181
4590
  const hooks = GetDataHooks('PostRunView');
4182
4591
  for (const hook of hooks) {
4183
- result = await hook(params, result, contextUser);
4592
+ result = await hook(params, result, contextUser, this);
4184
4593
  }
4185
4594
  return result;
4186
4595
  }
@@ -4322,6 +4731,16 @@ export class ProviderBase {
4322
4731
  // bypass in runViewCacheEligible; this covers the query-materialization Live-read path.)
4323
4732
  if (entity.VirtualEntity && entity.BaseView && entity.BaseView.toLowerCase().startsWith('materialized_vw'))
4324
4733
  return false;
4734
+ // External data-source entities (federated REST/SQL connectors) are never event-invalidated
4735
+ // and `LocalCacheManager.SetRunViewResult` skips them unless an explicit `ttlMs` is passed
4736
+ // (`PostRunView` never passes `ttlMs`), so treating them as server-cacheable only forces
4737
+ // wasted `Fields` widening and futile cache lookups.
4738
+ if (entity.ExternalDataSourceID)
4739
+ return false;
4740
+ // PostRunView-protected entities enforce per-caller ACL filtering inside PostRunView hooks
4741
+ // from sibling permission tables whose mutations never change this entity's table timestamps.
4742
+ if (IsPostRunViewProtectedEntity(entity.Name))
4743
+ return false;
4325
4744
  return entity.TrustServerCacheCompletely !== false;
4326
4745
  }
4327
4746
  shouldAutoCache(params, result, contextUser) {
@@ -4837,8 +5256,23 @@ export class ProviderBase {
4837
5256
  * @param data - Configuration including schema filters and connection info
4838
5257
  * @returns True if configuration was successful
4839
5258
  */
5259
+ /**
5260
+ * Synchronously configures this provider from an already-initialized global `Metadata.Provider`
5261
+ * without allocating promises or awaiting async cache initialization. Returns `false` if global
5262
+ * metadata or `LocalCacheManager` has not finished initializing yet.
5263
+ */
5264
+ ConfigureFromGlobalMetadataSync(data) {
5265
+ if (!Metadata.Provider || data.IgnoreExistingMetadata || this._refresh || !LocalCacheManager.Instance.IsInitialized) { // global-provider-ok: bootstrap checks for an existing global registration
5266
+ return false;
5267
+ }
5268
+ this._ConfigData = data;
5269
+ this._adoptedLoadsQueryMetadata = undefined;
5270
+ this._configLoadedFromServer = false;
5271
+ return this.CopyMetadataFromGlobalProvider();
5272
+ }
4840
5273
  async Config(data, providerToUse) {
4841
5274
  this._ConfigData = data;
5275
+ this._adoptedLoadsQueryMetadata = undefined;
4842
5276
  // Describes THIS Config only: a flag left by an earlier Refresh() must not make the
4843
5277
  // pre-validation that follows a Config which loaded nothing skip its check.
4844
5278
  this._configLoadedFromServer = false;
@@ -4908,12 +5342,18 @@ export class ProviderBase {
4908
5342
  /**
4909
5343
  * Reloads this provider's metadata. Single-flight: at most one reload runs at a time, and a
4910
5344
  * request arriving mid-reload queues exactly one follow-up pass.
4911
- * @param hardRefresh - re-read the remote timestamps first and bypass every cache layer
4912
- * @param scopedFirst - try the scoped reload of the saved-query family (see
4913
- * {@link PartialRefreshMetadataItemCodes}) before the full one. Defaults to true unless
4914
- * hardRefresh: an explicit Refresh() is always a full reload.
4915
- */
4916
- async ReloadMetadata(hardRefresh, providerToUse, scopedFirst = !hardRefresh) {
5345
+ * @param hardRefresh - re-read the remote timestamps first (unless `stampsFresh`) and bypass
5346
+ * every cache layer
5347
+ * @param scopedFirst - reload only what the timestamps show changed (see
5348
+ * {@link MetadataRefreshScope}): nothing, the saved-query family (see
5349
+ * {@link PartialRefreshMetadataItemCodes}), or everything. Defaults to true unless
5350
+ * hardRefresh: an explicit Refresh() is always a full reload, and so is one that joins a
5351
+ * reload already in flight — the follow-up pass it queues runs in full. A pass that may be
5352
+ * scoped but cannot read the timestamps keeps the metadata loaded and is retried later.
5353
+ * @param stampsFresh - the caller read the remote timestamps just before this call. The first
5354
+ * hard pass then uses them instead of reading them again; a queued follow-up pass still reads.
5355
+ */
5356
+ async ReloadMetadata(hardRefresh, providerToUse, scopedFirst = !hardRefresh, stampsFresh = false) {
4917
5357
  // first, make sure we reset the flag to false so that if another call to this function happens
4918
5358
  // while we are waiting for the async call to finish, we dont do it again
4919
5359
  this._refresh = false;
@@ -4926,6 +5366,10 @@ export class ProviderBase {
4926
5366
  // guaranteeing the final swap comes from a read that started after the last request.
4927
5367
  if (this._metadataReloadInFlight) {
4928
5368
  this._metadataReloadQueued = true;
5369
+ if (!scopedFirst) {
5370
+ // An explicit Refresh() promises a full reload; the follow-up pass keeps that promise.
5371
+ this._metadataFullReloadRequested = true;
5372
+ }
4929
5373
  if (this._metadataReadsJoinTransaction) {
4930
5374
  // Caller owns an open database transaction (RefreshWithinTransaction) and is
4931
5375
  // waiting for this reload before it can COMMIT or ROLLBACK. An in-flight pool
@@ -4948,6 +5392,7 @@ export class ProviderBase {
4948
5392
  this._metadataReloadInFlight = (async () => {
4949
5393
  let effectiveHardRefresh = hardRefresh;
4950
5394
  let tryScoped = scopedFirst;
5395
+ let timestampsFresh = stampsFresh;
4951
5396
  do {
4952
5397
  this._metadataReloadQueued = false;
4953
5398
  // The local timestamps must describe the snapshot about to be loaded. On the
@@ -4957,29 +5402,34 @@ export class ProviderBase {
4957
5402
  // them (one cheap status query, authoritative) BEFORE the load, not after:
4958
5403
  // a write landing DURING the load then leaves the stamped timestamps looking
4959
5404
  // stale and the next tick reloads — the safe direction. Reading after could
4960
- // stamp the snapshot as containing a write it does not.
4961
- if (effectiveHardRefresh) {
4962
- await this.RefreshRemoteMetadataTimestamps(providerToUse);
5405
+ // stamp the snapshot as containing a write it does not. When the caller has just
5406
+ // read them (stampsFresh), the first pass uses that read.
5407
+ let timestampsRead = true;
5408
+ if (effectiveHardRefresh && !timestampsFresh) {
5409
+ timestampsRead = await this.RefreshRemoteMetadataTimestamps(providerToUse);
4963
5410
  }
4964
- // SCOPED FIRST: when the staleness is attributable entirely to the saved-query family
4965
- // (see PartialRefreshMetadataItemCodes), reload just that family and keep every other
4966
- // array as is. Anything else — or a failed scoped read — takes the full reload below.
4967
- const scopedDone = tryScoped && await this.TryPartialMetadataReload(providerToUse);
4968
- if (!scopedDone) {
4969
- // Fetch new metadata without clearing current metadata
4970
- // This ensures readers always see valid data (old until new is ready)
4971
- const start = new Date().getTime();
4972
- const res = await this.GetAllMetadata(providerToUse, effectiveHardRefresh);
4973
- const end = new Date().getTime();
4974
- LogStatus(`GetAllMetadata() took ${end - start} ms`);
4975
- if (res) {
4976
- await this.adoptServerMetadata(res);
4977
- this._configLoadedFromServer = true;
4978
- }
4979
- else {
4980
- // GetAllMetadata failed - log error but keep existing metadata
4981
- LogError('GetAllMetadata() returned undefined - metadata not updated');
4982
- }
5411
+ // SCOPED FIRST: reload only what the timestamps show changed (see
5412
+ // MetadataRefreshScope) — nothing, the saved-query family with every other array kept
5413
+ // as is, or everything. A pass that may be scoped but could not read the timestamps
5414
+ // has no basis for choosing, so it keeps what is loaded and is retried later. A pass
5415
+ // that stands in for a write-event refresh applies the write-event rule (see
5416
+ // RefreshAfterMetadataMemberChange); one that stands in for an explicit Refresh()
5417
+ // runs in full.
5418
+ const fullRequested = this._metadataFullReloadRequested;
5419
+ this._metadataFullReloadRequested = false;
5420
+ const writeEvent = this._metadataWriteEventPending;
5421
+ this._metadataWriteEventPending = false;
5422
+ let scope = (!tryScoped || fullRequested)
5423
+ ? { Kind: 'full', Reason: 'a full reload was requested' }
5424
+ : (timestampsRead || !this.holdsMetadata) ? this.MetadataRefreshScope() : null;
5425
+ if (scope && writeEvent) {
5426
+ scope = ProviderBase.applyWriteEventRule(scope);
5427
+ }
5428
+ if (!scope) {
5429
+ this.scheduleMetadataRefreshRetry('the metadata timestamps could not be read');
5430
+ }
5431
+ else if (await this.applyMetadataRefreshScope(scope, providerToUse, effectiveHardRefresh)) {
5432
+ this._configLoadedFromServer = true;
4983
5433
  }
4984
5434
  // A queued follow-up exists only because another refresh request arrived
4985
5435
  // mid-reload; rerun hard so the re-read cannot be served by any cache layer.
@@ -4987,6 +5437,7 @@ export class ProviderBase {
4987
5437
  // The follow-up re-reads the timestamps first, so it may still be attributed to the
4988
5438
  // saved-query family — and a scoped read never trusts a cache layer either.
4989
5439
  tryScoped = true;
5440
+ timestampsFresh = false;
4990
5441
  } while (this._metadataReloadQueued);
4991
5442
  })();
4992
5443
  try {
@@ -4997,6 +5448,55 @@ export class ProviderBase {
4997
5448
  }
4998
5449
  return true;
4999
5450
  }
5451
+ /**
5452
+ * Carries out one reload pass for `scope`. A failed scoped reload is retried later; only the
5453
+ * {@link MetadataScopedReloadAttempts}-th failure in a row runs the full reload instead.
5454
+ * @returns true when a full snapshot was loaded from the server and adopted
5455
+ */
5456
+ async applyMetadataRefreshScope(scope, providerToUse, forceRefresh) {
5457
+ if (scope.Kind === 'none') {
5458
+ this.markMetadataCurrent();
5459
+ return false;
5460
+ }
5461
+ if (scope.Kind === 'full') {
5462
+ return this.reloadAllMetadata(providerToUse, forceRefresh, scope.Reason);
5463
+ }
5464
+ if (await this.TryPartialMetadataReload(providerToUse)) {
5465
+ this.resetMetadataRefreshFailures();
5466
+ return false;
5467
+ }
5468
+ const failures = ++this._metadataScopedReloadFailures;
5469
+ const limit = ProviderBase.MetadataScopedReloadAttempts;
5470
+ if (failures < limit) {
5471
+ this.scheduleMetadataRefreshRetry(`the scoped reload failed, ${failures} of ${limit}`);
5472
+ return false;
5473
+ }
5474
+ this._metadataScopedReloadFailures = 0;
5475
+ // A scoped read never trusts a cache layer, so neither does the reload that replaces it.
5476
+ return this.reloadAllMetadata(providerToUse, true, `the scoped reload failed ${limit} times in a row`);
5477
+ }
5478
+ /**
5479
+ * The full reload: fetches all metadata and adopts it. Readers keep the current metadata until
5480
+ * the new snapshot is ready, and keep it if the fetch fails; a failure while metadata is loaded
5481
+ * is retried later. Every full reload is logged with its reason and duration.
5482
+ * @returns true when the snapshot was loaded and adopted
5483
+ */
5484
+ async reloadAllMetadata(providerToUse, forceRefresh, reason) {
5485
+ const start = Date.now();
5486
+ const res = await this.GetAllMetadata(providerToUse, forceRefresh);
5487
+ if (!res) {
5488
+ // GetAllMetadata failed - log error but keep existing metadata
5489
+ LogError('GetAllMetadata() returned undefined - metadata not updated');
5490
+ if (this.holdsMetadata) {
5491
+ this.scheduleMetadataRefreshRetry('the full reload failed');
5492
+ }
5493
+ return false;
5494
+ }
5495
+ await this.adoptServerMetadata(res);
5496
+ this.resetMetadataRefreshFailures();
5497
+ LogStatus(`[Metadata] Full reload (${reason}) took ${Date.now() - start} ms`);
5498
+ return true;
5499
+ }
5000
5500
  /**
5001
5501
  * Adopts a metadata snapshot just loaded from the server: swaps it in, records that the
5002
5502
  * local copy now matches the server's timestamps (verified per item against the received
@@ -5028,6 +5528,7 @@ export class ProviderBase {
5028
5528
  const rollup = norm(ProviderBase._allMetadataTypeName);
5029
5529
  const prevLocal = this._latestLocalMetadataTimestamps ?? [];
5030
5530
  const datasetItems = this._metadataDatasetItems;
5531
+ const built = this.BuiltMetadataItemCodes;
5031
5532
  const resRecord = res;
5032
5533
  let hasMismatch = false;
5033
5534
  const reconciled = [];
@@ -5052,7 +5553,10 @@ export class ProviderBase {
5052
5553
  if (datasetItems && datasetItems.length > 0) {
5053
5554
  const match = (remoteEntry.ID ? datasetItemsByEntityID?.Get(remoteEntry.ID) : undefined)
5054
5555
  ?? datasetItemsByNameOrCode.get(norm(remoteEntry.Type));
5055
- if (match && match.RowCount !== undefined) {
5556
+ // Only items the build reads have a received count to check. The others (Dashboards)
5557
+ // are never read, so their recorded count is whatever the last full load saw; after a
5558
+ // scoped reload it would be stale and would report a mismatch that is not one.
5559
+ if (match && match.RowCount !== undefined && built.has(match.Code)) {
5056
5560
  receivedRowCount = match.RowCount;
5057
5561
  receivedUpdateDate = match.LatestUpdateDate;
5058
5562
  }
@@ -5109,7 +5613,7 @@ export class ProviderBase {
5109
5613
  if (!hasMismatch) {
5110
5614
  return remote;
5111
5615
  }
5112
- this.ClearDatasetCache(ProviderBase._mjMetadataDatasetName).catch(() => { });
5616
+ this.ClearDatasetCache(ProviderBase._mjMetadataDatasetName, this.MetadataDatasetItemFilters).catch(() => { });
5113
5617
  const remoteRollup = remote.find(r => norm(r.Type) === rollup);
5114
5618
  if (remoteRollup) {
5115
5619
  const priorRollup = prevLocal.find(m => norm(m.Type) === rollup);
@@ -5123,24 +5627,38 @@ export class ProviderBase {
5123
5627
  return reconciled;
5124
5628
  }
5125
5629
  /**
5126
- * Decides whether the current staleness can be served by a scoped reload of the saved-query
5127
- * family. Compares local and remote timestamps item by item (the same test as
5128
- * {@link LocalMetadataObsolete}) and maps each stale entity back to its MJ_Metadata item code.
5129
- * @returns the family's item codes (the whole family — the query classes are swapped as a set)
5130
- * when every stale item belongs to it; null when anything else is stale, nothing is, or the
5131
- * inputs needed to attribute the change are missing — the full reload is then the answer.
5132
- */
5133
- PartialRefreshItemCodes() {
5630
+ * What a metadata refresh must reload, from the local and remote timestamps. Compares them
5631
+ * item by item (the same test as {@link LocalMetadataObsolete}) and maps each stale entity
5632
+ * back to its MJ_Metadata item code:
5633
+ *
5634
+ * - `none` — nothing {@link MetadataBuildItemCodes} names has changed. Either nothing moved,
5635
+ * or only items the metadata build never reads did (`Dashboards`).
5636
+ * - `scoped` — every change the build reads is in the saved-query family (see
5637
+ * {@link PartialRefreshMetadataItemCodes}); `Codes` is the whole family, since the query
5638
+ * classes are swapped as a set.
5639
+ * - `full` — anything else changed, or the change cannot be attributed (an unknown item, an
5640
+ * item that left the dataset, the roll-up moving with no item, or the inputs to compare are
5641
+ * missing). `Reason` says which, for the log.
5642
+ */
5643
+ MetadataRefreshScope() {
5134
5644
  const items = this._metadataDatasetItems;
5135
5645
  const local = this.LatestLocalMetadata;
5136
5646
  const remote = this.LatestRemoteMetadata;
5137
- if (!items?.length || !this._localMetadata?.AllEntities?.length || !local?.length || !remote?.length) {
5138
- return null;
5647
+ if (!this.holdsMetadata) {
5648
+ return { Kind: 'full', Reason: 'no metadata is loaded yet' };
5649
+ }
5650
+ if (!items?.length) {
5651
+ return { Kind: 'full', Reason: 'the metadata dataset items are not known' };
5652
+ }
5653
+ if (!local?.length || !remote?.length) {
5654
+ return { Kind: 'full', Reason: 'the metadata timestamps are not known' };
5139
5655
  }
5140
5656
  const family = new Set(ProviderBase.PartialRefreshMetadataItemCodes);
5657
+ const built = this.BuiltMetadataItemCodes;
5141
5658
  const norm = (v) => (v ?? '').trim().toLowerCase();
5142
5659
  const rollup = norm(ProviderBase._allMetadataTypeName);
5143
- let stale = 0;
5660
+ let anyItemChanged = false;
5661
+ let familyChanged = false;
5144
5662
  for (const r of remote) {
5145
5663
  if (norm(r.Type) === rollup) {
5146
5664
  continue; // the roll-up moves with any item; the per-item rows decide
@@ -5149,20 +5667,45 @@ export class ProviderBase {
5149
5667
  if (l && !ProviderBase.metadataStampChanged(l, r)) {
5150
5668
  continue;
5151
5669
  }
5670
+ anyItemChanged = true;
5152
5671
  const owners = items.filter(i => norm(i.EntityName) === norm(r.Type));
5153
- if (owners.length === 0 || owners.some(o => !family.has(o.Code))) {
5154
- return null; // something outside the family moved, or a new item appeared
5672
+ if (owners.length === 0) {
5673
+ return { Kind: 'full', Reason: `${r.Type} changed and is not a known metadata dataset item` };
5155
5674
  }
5156
- stale++;
5675
+ const read = owners.filter(o => built.has(o.Code));
5676
+ if (read.length === 0) {
5677
+ continue; // an item the metadata build never reads
5678
+ }
5679
+ if (read.some(o => !family.has(o.Code))) {
5680
+ return { Kind: 'full', Reason: `${r.Type} changed` };
5681
+ }
5682
+ familyChanged = true;
5157
5683
  }
5158
- if (local.some(l => norm(l.Type) !== rollup && !remote.some(r => norm(r.Type) === norm(l.Type)))) {
5159
- return null; // an item left the dataset
5684
+ const removed = local.find(l => norm(l.Type) !== rollup && !remote.some(r => norm(r.Type) === norm(l.Type)));
5685
+ if (removed) {
5686
+ return { Kind: 'full', Reason: `${removed.Type} is no longer in the metadata dataset` };
5160
5687
  }
5161
- if (stale === 0) {
5162
- return null; // nothing attributable — the caller's own policy decides
5688
+ if (familyChanged) {
5689
+ const codes = [...new Set(items.map(i => i.Code).filter(c => family.has(c)))];
5690
+ return { Kind: 'scoped', Codes: codes };
5163
5691
  }
5164
- const codes = [...new Set(items.map(i => i.Code).filter(c => family.has(c)))];
5165
- return codes.length > 0 ? codes : null;
5692
+ if (!anyItemChanged) {
5693
+ const localRollup = local.find(m => norm(m.Type) === rollup);
5694
+ const remoteRollup = remote.find(m => norm(m.Type) === rollup);
5695
+ if (remoteRollup && (!localRollup || ProviderBase.metadataStampChanged(localRollup, remoteRollup))) {
5696
+ return { Kind: 'full', Reason: 'the metadata timestamp moved, but no item did' };
5697
+ }
5698
+ }
5699
+ return { Kind: 'none', AnyItemMoved: anyItemChanged };
5700
+ }
5701
+ /**
5702
+ * The saved-query family's item codes when the current staleness can be served by a scoped
5703
+ * reload; null otherwise.
5704
+ * @deprecated Use {@link MetadataRefreshScope}, which also says when nothing needs reloading.
5705
+ */
5706
+ PartialRefreshItemCodes() {
5707
+ const scope = this.MetadataRefreshScope();
5708
+ return scope.Kind === 'scoped' ? [...scope.Codes] : null;
5166
5709
  }
5167
5710
  static metadataStampChanged(local, remote) {
5168
5711
  if (!local.UpdatedAt && !remote.UpdatedAt) {
@@ -5180,10 +5723,13 @@ export class ProviderBase {
5180
5723
  * requested with a `1=0` filter, so it reads nothing. Always bypasses cache layers — the read
5181
5724
  * is small, and a cached answer is exactly what a staleness check cannot trust.
5182
5725
  * @returns true when the scoped reload was applied; false when it does not apply or any part
5183
- * of it failed — the caller then runs the full reload, so a failure never leaves stale queries.
5726
+ * of it failed — the caller then retries it later, and after
5727
+ * {@link MetadataScopedReloadAttempts} failures in a row runs the full reload, so a failure
5728
+ * never leaves stale queries for good.
5184
5729
  */
5185
5730
  async TryPartialMetadataReload(providerToUse) {
5186
- const codes = this.PartialRefreshItemCodes();
5731
+ const scope = this.MetadataRefreshScope();
5732
+ const codes = scope.Kind === 'scoped' ? scope.Codes : null;
5187
5733
  const current = this._localMetadata;
5188
5734
  const items = this._metadataDatasetItems;
5189
5735
  if (!codes || !current || !items) {
@@ -5191,20 +5737,21 @@ export class ProviderBase {
5191
5737
  }
5192
5738
  try {
5193
5739
  const keep = new Set(codes);
5740
+ // Items this provider does not load stay unread even when they are in the family.
5194
5741
  const skipOthers = items
5195
- .filter(item => !keep.has(item.Code))
5742
+ .filter(item => !keep.has(item.Code) || this.isSkippedMetadataItem(item.Code))
5196
5743
  .map(item => ({ ItemCode: item.Code, Filter: '1=0' }));
5197
5744
  const start = Date.now();
5198
5745
  const d = await this.GetDatasetByName(ProviderBase._mjMetadataDatasetName, skipOthers, this.CurrentUser, providerToUse, true);
5199
5746
  if (!d?.Success) {
5200
- LogStatusEx({ message: `[Metadata] Scoped reload of ${codes.join(', ')} failed (${d?.Status ?? 'no result'}); running the full reload`, verboseOnly: true });
5747
+ LogStatus(`[Metadata] Scoped reload of ${codes.join(', ')} failed (${d?.Status ?? 'no result'})`);
5201
5748
  return false;
5202
5749
  }
5203
5750
  const simple = {};
5204
5751
  for (const code of codes) {
5205
5752
  const item = d.Results?.find(r => r.Code === code);
5206
5753
  if (!item || item.Success === false || !Array.isArray(item.Results)) {
5207
- LogStatusEx({ message: `[Metadata] Scoped reload: item ${code} ${item ? `failed (${item.Status ?? 'no rows'})` : 'missing'}; running the full reload`, verboseOnly: true });
5754
+ LogStatus(`[Metadata] Scoped reload: item ${code} ${item ? `failed (${item.Status ?? 'no rows'})` : 'missing'}`);
5208
5755
  return false;
5209
5756
  }
5210
5757
  simple[code] = item.Results;
@@ -5242,15 +5789,15 @@ export class ProviderBase {
5242
5789
  return true;
5243
5790
  }
5244
5791
  catch (e) {
5245
- LogError(`[Metadata] Scoped reload failed; running the full reload: ${e instanceof Error ? e.message : String(e)}`);
5792
+ LogError(`[Metadata] Scoped reload failed: ${e instanceof Error ? e.message : String(e)}`);
5246
5793
  return false;
5247
5794
  }
5248
5795
  }
5249
5796
  /**
5250
5797
  * Background validation for the stale-while-revalidate fast-start pattern.
5251
- * Checks if local metadata is still current; if stale, fetches fresh metadata
5252
- * and atomically swaps it in. The app continues operating on cached data
5253
- * during this process — no blocking.
5798
+ * Checks if local metadata is still current; if stale, reloads only what changed (see
5799
+ * {@link MetadataRefreshScope}) and atomically swaps it in. The app continues operating on
5800
+ * cached data during this process — no blocking.
5254
5801
  */
5255
5802
  async backgroundValidateAndRefresh(providerToUse) {
5256
5803
  try {
@@ -5258,12 +5805,8 @@ export class ProviderBase {
5258
5805
  if (needsRefresh) {
5259
5806
  LogStatusEx({ message: `⚡ [Metadata Cache] Background check: metadata is stale — refreshing...`, verboseOnly: true });
5260
5807
  const start = Date.now();
5261
- const res = await this.GetAllMetadata(providerToUse, false);
5262
- const elapsed = Date.now() - start;
5263
- if (res) {
5264
- await this.adoptServerMetadata(res);
5265
- LogStatusEx({ message: `⚡ [Metadata Cache] Background refresh complete (${elapsed}ms) — metadata updated in place`, verboseOnly: true });
5266
- }
5808
+ await this.reloadStaleCachedMetadata(providerToUse, true);
5809
+ LogStatusEx({ message: `⚡ [Metadata Cache] Background refresh complete (${Date.now() - start}ms) — metadata updated in place`, verboseOnly: true });
5267
5810
  }
5268
5811
  else {
5269
5812
  LogStatusEx({ message: `⚡ [Metadata Cache] Background check: metadata is current — no refresh needed`, verboseOnly: true });
@@ -5289,8 +5832,9 @@ export class ProviderBase {
5289
5832
  * engines start, then proceed normally.
5290
5833
  *
5291
5834
  * Cost on the warm-current path is one batched timestamp fetch (~50–200 ms depending
5292
- * on RTT). On the warm-stale path we additionally pay the full metadata fetch but
5293
- * avoid serving stale data to the UI in the first place.
5835
+ * on RTT). On the warm-stale path we additionally reload what changed — the saved-query
5836
+ * family alone when only saved queries moved, everything otherwise — but avoid serving
5837
+ * stale data to the UI in the first place.
5294
5838
  *
5295
5839
  * On a cold boot, where Config() just loaded the graph (and the current user) from the
5296
5840
  * server, the first call after that load returns immediately — no check, no current-user
@@ -5318,12 +5862,9 @@ export class ProviderBase {
5318
5862
  if (needsRefresh) {
5319
5863
  LogStatus(`⚡ [Metadata Cache] Pre-validation: metadata is stale — refreshing before engine startup`);
5320
5864
  const start = Date.now();
5321
- const res = await this.GetAllMetadata(providerToUse, false);
5322
- const elapsed = Date.now() - start;
5323
- if (res) {
5324
- await this.adoptServerMetadata(res);
5325
- LogStatus(`⚡ [Metadata Cache] Pre-validation refresh complete (${elapsed}ms)`);
5326
- }
5865
+ // The current user was refreshed beside the check above.
5866
+ await this.reloadStaleCachedMetadata(providerToUse, false);
5867
+ LogStatus(`⚡ [Metadata Cache] Pre-validation refresh complete (${Date.now() - start}ms)`);
5327
5868
  }
5328
5869
  else {
5329
5870
  LogStatus(`⚡ [Metadata Cache] Pre-validation: metadata is current`);
@@ -5333,6 +5874,25 @@ export class ProviderBase {
5333
5874
  LogError(`[Metadata Cache] Pre-validation failed: ${e instanceof Error ? e.message : String(e)} — engines will smart-cache-check`);
5334
5875
  }
5335
5876
  }
5877
+ /**
5878
+ * Brings cached metadata that a staleness check just found stale up to date, reloading only
5879
+ * what changed (see {@link MetadataRefreshScope}). The full reload replaces the snapshot
5880
+ * wholesale and fetches the current user with it; it is not {@link Config}'s load, so it does
5881
+ * not claim the cold-boot pre-validation skip. A scoped reload merges into the current
5882
+ * snapshot, so it runs inside {@link ReloadMetadata}'s single flight, where no other reload can
5883
+ * swap the snapshot out from under it; it fetches no user, so `refreshCurrentUser` asks for one.
5884
+ */
5885
+ async reloadStaleCachedMetadata(providerToUse, refreshCurrentUser) {
5886
+ const scope = this.MetadataRefreshScope();
5887
+ if (scope.Kind === 'full') {
5888
+ await this.reloadAllMetadata(providerToUse, false, scope.Reason);
5889
+ return;
5890
+ }
5891
+ await this.ReloadMetadata(false, providerToUse, true);
5892
+ if (refreshCurrentUser) {
5893
+ await this.RefreshCurrentUser();
5894
+ }
5895
+ }
5336
5896
  /**
5337
5897
  * @deprecated The reuse-global fast path now builds a shared shell instead — see
5338
5898
  * {@link CreateSharedMetadataShell}. The metadata graph is immutable after Config,
@@ -5443,6 +6003,9 @@ export class ProviderBase {
5443
6003
  else {
5444
6004
  this.UpdateLocalMetadata(adopted);
5445
6005
  }
6006
+ if (globalProvider instanceof ProviderBase) {
6007
+ this._adoptedLoadsQueryMetadata = globalProvider.LoadsQueryMetadata;
6008
+ }
5446
6009
  return true;
5447
6010
  }
5448
6011
  return false;
@@ -5540,9 +6103,10 @@ export class ProviderBase {
5540
6103
  // NOTE: Schema filters (IncludeSchemas/ExcludeSchemas) are for CodeGen only, not for runtime
5541
6104
  // metadata loading. We always load all schemas — there are no sys/staging entities in metadata anyway.
5542
6105
  const mutationSeqAtStart = this._metadataMemberMutationSeq;
6106
+ const itemFilters = this.MetadataDatasetItemFilters;
5543
6107
  // Get the dataset and cache it for anyone else who wants to use it
5544
6108
  // When forceRefresh is true (from a hard Refresh() call), bypass LocalCacheManager
5545
- const d = await this.GetDatasetByName(ProviderBase._mjMetadataDatasetName, null, this.CurrentUser, providerToUse, forceRefresh);
6109
+ const d = await this.GetDatasetByName(ProviderBase._mjMetadataDatasetName, itemFilters, this.CurrentUser, providerToUse, forceRefresh);
5546
6110
  // A dataset with no entities is a failed read, whatever its Success flag says: there
5547
6111
  // is no deployment in which MJ_Metadata legitimately holds zero entities. Returning
5548
6112
  // undefined here keeps the metadata already loaded (Config() treats undefined as
@@ -5567,18 +6131,17 @@ export class ProviderBase {
5567
6131
  this._metadataMemberMutationSeq !== mutationSeqAtStart ||
5568
6132
  this.hasDatasetRemoteRowCountMismatch(d);
5569
6133
  if (!mutatedDuringLoad) {
5570
- await this.CacheDataset(ProviderBase._mjMetadataDatasetName, null, d);
6134
+ await this.CacheDataset(ProviderBase._mjMetadataDatasetName, itemFilters, d);
5571
6135
  }
5572
6136
  else {
5573
- await this.ClearDatasetCache(ProviderBase._mjMetadataDatasetName);
5574
- }
5575
- // got the results, let's build our response in the format we need
5576
- const simpleMetadata = {};
5577
- for (let r of d.Results) {
5578
- simpleMetadata[r.Code] = r.Results;
6137
+ await this.ClearDatasetCache(ProviderBase._mjMetadataDatasetName, itemFilters);
5579
6138
  }
6139
+ // got the results, let's build our response in the format we need. The assembly
6140
+ // below attaches child collections to rows, so it works on copies of those rows:
6141
+ // the dataset's own rows stay exactly as read (see metadataAssemblyInput).
6142
+ const simpleMetadata = ProviderBase.metadataAssemblyInput(d);
5580
6143
  // Post Process Entities because there's some special handling of the sub-objects
5581
- simpleMetadata.AllEntities = this.PostProcessEntityMetadata(simpleMetadata.Entities, simpleMetadata.EntityFields, simpleMetadata.EntityFieldValues, simpleMetadata.EntityPermissions, simpleMetadata.EntityRelationships, simpleMetadata.EntitySettings, simpleMetadata.EntityOrganicKeys, simpleMetadata.EntityOrganicKeyRelatedEntities, simpleMetadata.EntityFieldPermissions, simpleMetadata.EntityAlternateBaseViews);
6144
+ simpleMetadata.AllEntities = this.PostProcessEntityMetadata(simpleMetadata.Entities, simpleMetadata.EntityFields, simpleMetadata.EntityFieldValues, simpleMetadata.EntityPermissions, simpleMetadata.EntityRelationships, simpleMetadata.EntitySettings, simpleMetadata.EntityOrganicKeys, simpleMetadata.EntityOrganicKeyRelatedEntities, simpleMetadata.EntityFieldPermissions, simpleMetadata.EntityAlternateBaseViews, simpleMetadata.EntityUniqueKeys);
5582
6145
  // Post Process the Applications, because we want to handle the sub-objects properly.
5583
6146
  simpleMetadata.AllApplications = simpleMetadata.Applications.map((a) => {
5584
6147
  a.ApplicationEntities = simpleMetadata.ApplicationEntities.filter((ae) => UUIDsEqual(ae.ApplicationID, a.ID));
@@ -5603,6 +6166,31 @@ export class ProviderBase {
5603
6166
  this._lastMetadataLoadError = e instanceof Error ? e : new Error(String(e));
5604
6167
  }
5605
6168
  }
6169
+ /**
6170
+ * The MJ_Metadata item codes whose rows the metadata assembly writes to: entity rows get their
6171
+ * fields, permissions, relationships, settings, organic keys, alternate views and unique keys;
6172
+ * field rows their values and field permissions; organic keys their related entities;
6173
+ * applications their entities and settings. The entity array is also sorted.
6174
+ */
6175
+ static { this._assemblyWrittenItemCodes = new Set(['Entities', 'EntityFields', 'EntityOrganicKeys', 'Applications']); }
6176
+ /**
6177
+ * The MJ_Metadata rows keyed by item code, as {@link GetAllMetadata} assembles them: the items
6178
+ * the assembly writes to are shallow copies (a new array of new row objects), the rest are the
6179
+ * dataset's own arrays. The dataset's rows are the ones the dataset cache holds and serves to
6180
+ * every later reader — on a server, every client's metadata request — so writing child
6181
+ * collections onto them would send each entity's fields, permissions and relationships a second
6182
+ * time, nested inside the entity rows, with every response.
6183
+ */
6184
+ static metadataAssemblyInput(dataset) {
6185
+ const input = {};
6186
+ for (const item of dataset.Results ?? []) {
6187
+ const rows = Array.isArray(item.Results) ? item.Results : [];
6188
+ input[item.Code] = ProviderBase._assemblyWrittenItemCodes.has(item.Code)
6189
+ ? rows.map(row => ({ ...row }))
6190
+ : rows;
6191
+ }
6192
+ return input;
6193
+ }
5606
6194
  /** Logs a failed metadata download and keeps it for {@link LastMetadataLoadError}. */
5607
6195
  recordMetadataLoadFailure(error) {
5608
6196
  LogError(error.message);
@@ -5626,7 +6214,12 @@ export class ProviderBase {
5626
6214
  // SaveLocalMetadataToStorage avoids a multi-MB JSON.stringify + gzip + IDB
5627
6215
  // write pass on the main thread during startup.
5628
6216
  if (previousUserJson !== JSON.stringify(user)) {
5629
- void this.SaveLocalMetadataToStorage();
6217
+ if (Object.prototype.hasOwnProperty.call(this, 'SaveLocalMetadataToStorage')) {
6218
+ void this.SaveLocalMetadataToStorage();
6219
+ }
6220
+ else {
6221
+ this.ScheduleSaveLocalMetadataToStorage();
6222
+ }
5630
6223
  }
5631
6224
  return user;
5632
6225
  }
@@ -5665,7 +6258,7 @@ export class ProviderBase {
5665
6258
  }
5666
6259
  return map;
5667
6260
  }
5668
- PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews) {
6261
+ PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews, uniqueKeys) {
5669
6262
  const result = [];
5670
6263
  // Sort entities alphabetically by name to ensure deterministic ordering
5671
6264
  // This prevents non-deterministic output in CodeGen and other metadata consumers
@@ -5706,6 +6299,9 @@ export class ProviderBase {
5706
6299
  const alternateBaseViewsByEntityId = alternateBaseViews && alternateBaseViews.length > 0
5707
6300
  ? this.groupByNormalizedUUID(alternateBaseViews, abv => abv.EntityID)
5708
6301
  : new Map();
6302
+ const uniqueKeysByEntityId = uniqueKeys && uniqueKeys.length > 0
6303
+ ? this.groupByNormalizedUUID(uniqueKeys, uk => uk.EntityID)
6304
+ : new Map();
5709
6305
  for (const e of sortedEntities) {
5710
6306
  const entityIdKey = NormalizeUUID(e.ID);
5711
6307
  const entityFields = fieldsByEntityId.get(entityIdKey) || [];
@@ -5720,6 +6316,9 @@ export class ProviderBase {
5720
6316
  if (alternateBaseViews) {
5721
6317
  e.EntityAlternateBaseViews = alternateBaseViewsByEntityId.get(entityIdKey) || [];
5722
6318
  }
6319
+ if (uniqueKeys) {
6320
+ e.EntityUniqueKeys = uniqueKeysByEntityId.get(entityIdKey) || [];
6321
+ }
5723
6322
  result.push(new EntityInfo(e, this));
5724
6323
  }
5725
6324
  // Check for schema name collision: if both 'MJ' and 'MJCustom' schemas exist,
@@ -5821,41 +6420,87 @@ export class ProviderBase {
5821
6420
  get AuthorizationRoles() {
5822
6421
  return this._localMetadata.AllAuthorizationRoles;
5823
6422
  }
5824
- /** @deprecated Use `QueryEngine.Instance.Queries` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6423
+ /** Whether {@link deprecatedQueryMetadata} has logged its warning in this process. */
6424
+ static { this._queryMetadataWarningLogged = false; }
6425
+ /**
6426
+ * What a deprecated query-metadata getter returns: the loaded array when the provider loads query
6427
+ * metadata, otherwise an empty array and a warning, logged once per process, naming the
6428
+ * replacement.
6429
+ */
6430
+ deprecatedQueryMetadata(items, getterName) {
6431
+ if (this.LoadsQueryMetadata) {
6432
+ return items;
6433
+ }
6434
+ if (!ProviderBase._queryMetadataWarningLogged) {
6435
+ ProviderBase._queryMetadataWarningLogged = true;
6436
+ LogWarning(`Metadata.${getterName} and the other query-metadata getters are empty: query metadata is not loaded into the ` +
6437
+ `metadata object. Use QueryEngine from @memberjunction/core-entities, or set LoadQueryMetadata ` +
6438
+ `(databaseSettings.loadQueryMetadata on MJAPI) until the code is migrated.`, 'Metadata');
6439
+ }
6440
+ return [];
6441
+ }
6442
+ /**
6443
+ * @deprecated Use `QueryEngine.Instance.Queries` from `@memberjunction/core-entities`. Empty unless the
6444
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6445
+ */
5825
6446
  get Queries() {
5826
- return this._localMetadata.AllQueries;
6447
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueries, 'Queries');
5827
6448
  }
5828
- /** @deprecated Use `QueryEngine.Instance.Categories` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6449
+ /**
6450
+ * @deprecated Use `QueryEngine.Instance.Categories` from `@memberjunction/core-entities`. Empty unless the
6451
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6452
+ */
5829
6453
  get QueryCategories() {
5830
- return this._localMetadata.AllQueryCategories;
6454
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryCategories, 'QueryCategories');
5831
6455
  }
5832
- /** @deprecated Use `QueryEngine.Instance.Fields` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6456
+ /**
6457
+ * @deprecated Use `QueryEngine.Instance.Fields` from `@memberjunction/core-entities`. Empty unless the
6458
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6459
+ */
5833
6460
  get QueryFields() {
5834
- return this._localMetadata.AllQueryFields;
6461
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryFields, 'QueryFields');
5835
6462
  }
5836
- /** @deprecated Use `QueryEngine.Instance.Permissions` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6463
+ /**
6464
+ * @deprecated Use `QueryEngine.Instance.Permissions` from `@memberjunction/core-entities`. Empty unless the
6465
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6466
+ */
5837
6467
  get QueryPermissions() {
5838
- return this._localMetadata.AllQueryPermissions;
6468
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryPermissions, 'QueryPermissions');
5839
6469
  }
5840
- /** @deprecated Use `QueryEngine.Instance.QueryEntities` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6470
+ /**
6471
+ * @deprecated Use `QueryEngine.Instance.QueryEntities` from `@memberjunction/core-entities`. Empty unless the
6472
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6473
+ */
5841
6474
  get QueryEntities() {
5842
- return this._localMetadata.AllQueryEntities;
6475
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryEntities, 'QueryEntities');
5843
6476
  }
5844
- /** @deprecated Use `QueryEngine.Instance.Parameters` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6477
+ /**
6478
+ * @deprecated Use `QueryEngine.Instance.Parameters` from `@memberjunction/core-entities`. Empty unless the
6479
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6480
+ */
5845
6481
  get QueryParameters() {
5846
- return this._localMetadata.AllQueryParameters;
6482
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryParameters, 'QueryParameters');
5847
6483
  }
5848
- /** @deprecated Use `QueryEngine.Instance.Dependencies` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6484
+ /**
6485
+ * @deprecated Use `QueryEngine.Instance.Dependencies` from `@memberjunction/core-entities`. Empty unless the
6486
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6487
+ */
5849
6488
  get QueryDependencies() {
5850
- return this._localMetadata.AllQueryDependencies;
6489
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryDependencies, 'QueryDependencies');
5851
6490
  }
5852
- /** @deprecated Use `QueryEngine.Instance.SQLDialects` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6491
+ /**
6492
+ * @deprecated Use `QueryEngine.Instance.SQLDialects` from `@memberjunction/core-entities`. Empty unless the
6493
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6494
+ */
5853
6495
  get SQLDialects() {
5854
- return this._localMetadata.AllSQLDialects;
6496
+ return this.deprecatedQueryMetadata(this._localMetadata.AllSQLDialects, 'SQLDialects');
5855
6497
  }
5856
- /** @deprecated Use `QueryEngine.Instance.QuerySQLs` from `@memberjunction/core-entities`. Will be removed in v6.x. */
6498
+ /**
6499
+ * @deprecated Use `QueryEngine.Instance.QuerySQLs` from `@memberjunction/core-entities`. Empty unless the
6500
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
6501
+ */
5857
6502
  get QuerySQLs() {
5858
- return this._localMetadata.AllQuerySQLs;
6503
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQuerySQLs, 'QuerySQLs');
5859
6504
  }
5860
6505
  /**
5861
6506
  * Gets all library definitions in the system.
@@ -5997,6 +6642,7 @@ export class ProviderBase {
5997
6642
  // Read the reachability flag in the SAME synchronous turn the await above resumed in —
5998
6643
  // before the next await can let a concurrent check overwrite it.
5999
6644
  const serverReached = this._lastRemoteTimestampReadReached;
6645
+ this._checkedRemoteMetadataTimestamps = gotTimestamps ? this._latestRemoteMetadataTimestamps : null;
6000
6646
  if (gotTimestamps) {
6001
6647
  this._lastRefreshCheckAt = Date.now();
6002
6648
  }
@@ -6055,33 +6701,58 @@ export class ProviderBase {
6055
6701
  */
6056
6702
  async RefreshIfNeeded(providerToUse, bypassMinCheckInterval) {
6057
6703
  if (await this.CheckToSeeIfRefreshNeeded(providerToUse, bypassMinCheckInterval)) {
6058
- // Stale only in the saved-query family → reload just that family (fresh timestamps, no
6059
- // cache layer), falling back to the full hard reload if the scoped read fails.
6060
- if (this.PartialRefreshItemCodes() !== null)
6061
- return this.ReloadMetadata(true, providerToUse, true);
6704
+ // Reload only what changed (see MetadataRefreshScope): nothing, the saved-query family
6705
+ // (fresh timestamps, no cache layer; a failed read is retried), or everything (a hard
6706
+ // Refresh()).
6707
+ const scope = this.MetadataRefreshScope();
6708
+ if (scope.Kind === 'none') {
6709
+ this.markMetadataCurrent();
6710
+ return true;
6711
+ }
6712
+ if (scope.Kind === 'scoped') {
6713
+ // Reuse the stored stamps while they come from the latest successful check; after a
6714
+ // failed check read, or a read stored by another caller, the pass reads them again.
6715
+ const stampsFresh = this._checkedRemoteMetadataTimestamps != null
6716
+ && this._checkedRemoteMetadataTimestamps === this._latestRemoteMetadataTimestamps;
6717
+ return this.ReloadMetadata(true, providerToUse, true, stampsFresh);
6718
+ }
6719
+ LogStatus(`[Metadata] Full reload needed: ${scope.Reason}`);
6062
6720
  return this.Refresh(providerToUse);
6063
6721
  }
6064
6722
  else
6065
6723
  return true;
6066
6724
  }
6067
- async GetEntityObject(entityName, loadKeyOrContextUser, contextUser) {
6725
+ static isGetEntityObjectOptions(value) {
6726
+ return (typeof value === 'object' &&
6727
+ value !== null &&
6728
+ !(value instanceof CompositeKey) &&
6729
+ !(value instanceof UserInfo) &&
6730
+ 'SkipNewRecord' in value);
6731
+ }
6732
+ async GetEntityObject(entityName, loadKeyOrOptionsOrContextUser, contextUser) {
6068
6733
  try {
6069
6734
  // Determine which overload was called
6070
6735
  let actualLoadKey;
6736
+ let actualOptions;
6071
6737
  let actualContextUser;
6072
- if (loadKeyOrContextUser instanceof CompositeKey) {
6073
- // Second overload: entityName, loadKey, contextUser
6074
- actualLoadKey = loadKeyOrContextUser;
6738
+ if (loadKeyOrOptionsOrContextUser instanceof CompositeKey) {
6739
+ // Overload: entityName, loadKey, contextUser
6740
+ actualLoadKey = loadKeyOrOptionsOrContextUser;
6741
+ actualContextUser = contextUser;
6742
+ }
6743
+ else if (ProviderBase.isGetEntityObjectOptions(loadKeyOrOptionsOrContextUser)) {
6744
+ // Overload: entityName, options, contextUser
6745
+ actualOptions = loadKeyOrOptionsOrContextUser;
6075
6746
  actualContextUser = contextUser;
6076
6747
  }
6077
6748
  else if (contextUser !== undefined) {
6078
- // Second overload with null/undefined loadKey: entityName, null/undefined, contextUser
6749
+ // Overload with null/undefined loadKey: entityName, null/undefined, contextUser
6079
6750
  actualLoadKey = undefined;
6080
6751
  actualContextUser = contextUser;
6081
6752
  }
6082
6753
  else {
6083
6754
  // First overload: entityName, contextUser
6084
- actualContextUser = loadKeyOrContextUser;
6755
+ actualContextUser = loadKeyOrOptionsOrContextUser;
6085
6756
  }
6086
6757
  const entity = this.EntityByName(entityName);
6087
6758
  if (entity) {
@@ -6129,7 +6800,7 @@ export class ProviderBase {
6129
6800
  throw new Error(`Failed to load ${entityName} with key: ${actualLoadKey.ToString()}`);
6130
6801
  }
6131
6802
  }
6132
- else {
6803
+ else if (!actualOptions?.SkipNewRecord) {
6133
6804
  // whenever we create a new object we want it to start
6134
6805
  // out as a new record, so we call NewRecord() on it
6135
6806
  newObject.NewRecord();
@@ -6149,6 +6820,13 @@ export class ProviderBase {
6149
6820
  return null;
6150
6821
  }
6151
6822
  }
6823
+ /**
6824
+ * Instantiates a `BaseEntity` subclass using explicit {@link GetEntityObjectOptions}
6825
+ * (for example `{ SkipNewRecord: true }` prior to `LoadFromData`).
6826
+ */
6827
+ GetEntityObjectWithOptions(entityName, options, contextUser) {
6828
+ return this.GetEntityObject(entityName, options, contextUser);
6829
+ }
6152
6830
  /**
6153
6831
  * Returns a list of entity dependencies, basically metadata that tells you the links to this entity from all other entities.
6154
6832
  * @param entityName
@@ -6537,7 +7215,7 @@ export class ProviderBase {
6537
7215
  let d;
6538
7216
  try {
6539
7217
  // No schema filters for metadata — see comment in GetAllMetadata
6540
- d = await this.GetDatasetStatusByName(ProviderBase._mjMetadataDatasetName, null, this.CurrentUser, providerToUse);
7218
+ d = await this.GetDatasetStatusByName(ProviderBase._mjMetadataDatasetName, this.MetadataDatasetItemFilters, this.CurrentUser, providerToUse);
6541
7219
  }
6542
7220
  catch (e) {
6543
7221
  if (!IsTransportError(e)) {
@@ -6701,13 +7379,55 @@ export class ProviderBase {
6701
7379
  const fmtKey = this.LocalStoragePrefix + ProviderBase.localStorageFormatKey;
6702
7380
  const dataKey = this.LocalStoragePrefix + ProviderBase.localStorageAllMetadataKey;
6703
7381
  const membershipKey = this.LocalStoragePrefix + ProviderBase.localStorageDatasetMembershipKey;
7382
+ const itemsKey = this.LocalStoragePrefix + ProviderBase.localStorageDatasetItemsKey;
6704
7383
  const readStart = Date.now();
6705
- const all = await ls.GetItems([tsKey, fmtKey, dataKey, membershipKey]);
7384
+ let raw = null;
7385
+ let tsRaw = null;
7386
+ let format = null;
7387
+ let membershipRaw = null;
7388
+ let itemsRaw = null;
7389
+ if (typeof ls.GetObject === 'function') {
7390
+ const otherKeys = [tsKey, fmtKey, membershipKey, itemsKey];
7391
+ const [metadataObj, otherItems] = await Promise.all([
7392
+ ls.GetObject(dataKey),
7393
+ typeof ls.GetItems === 'function' ? ls.GetItems(otherKeys) : null
7394
+ ]);
7395
+ raw = metadataObj !== null && metadataObj !== undefined
7396
+ ? metadataObj
7397
+ : await ls.GetItem(dataKey);
7398
+ if (otherItems) {
7399
+ tsRaw = otherItems.get(tsKey) ?? null;
7400
+ format = otherItems.get(fmtKey) ?? null;
7401
+ membershipRaw = otherItems.get(membershipKey) ?? null;
7402
+ itemsRaw = otherItems.get(itemsKey) ?? null;
7403
+ }
7404
+ else {
7405
+ tsRaw = await ls.GetItem(tsKey);
7406
+ format = await ls.GetItem(fmtKey);
7407
+ membershipRaw = await ls.GetItem(membershipKey);
7408
+ itemsRaw = await ls.GetItem(itemsKey);
7409
+ }
7410
+ }
7411
+ else {
7412
+ const all = typeof ls.GetItems === 'function'
7413
+ ? await ls.GetItems([tsKey, fmtKey, dataKey, membershipKey, itemsKey])
7414
+ : null;
7415
+ if (all) {
7416
+ tsRaw = all.get(tsKey) ?? null;
7417
+ format = all.get(fmtKey) ?? null;
7418
+ raw = all.get(dataKey) ?? null;
7419
+ membershipRaw = all.get(membershipKey) ?? null;
7420
+ itemsRaw = all.get(itemsKey) ?? null;
7421
+ }
7422
+ else {
7423
+ tsRaw = await ls.GetItem(tsKey);
7424
+ format = await ls.GetItem(fmtKey);
7425
+ raw = await ls.GetItem(dataKey);
7426
+ membershipRaw = await ls.GetItem(membershipKey);
7427
+ itemsRaw = await ls.GetItem(itemsKey);
7428
+ }
7429
+ }
6706
7430
  const readMs = Date.now() - readStart;
6707
- const tsRaw = all.get(tsKey) ?? null;
6708
- const format = all.get(fmtKey) ?? null;
6709
- const raw = all.get(dataKey) ?? null;
6710
- const membershipRaw = all.get(membershipKey) ?? null;
6711
7431
  // The timestamps are a freshness claim FOR THE PAYLOAD, so they are only adopted when the
6712
7432
  // payload is there to adopt with them. Timestamps without a payload happen whenever the
6713
7433
  // two keys do not disappear together: the timestamps key is written last (and removed
@@ -6733,21 +7453,19 @@ export class ProviderBase {
6733
7453
  // boot that never calls GetAllMetadata (the stale-while-revalidate fast start). The
6734
7454
  // set is only stored after a successful dataset load, so restoring it is exactly as
6735
7455
  // trustworthy as restoring the metadata itself.
7456
+ // Restore the dataset item list the same way, so a warm boot can attribute a change to
7457
+ // its item and reload only what changed (see MetadataRefreshScope). Without it, every
7458
+ // change seen by a process that started from the snapshot was a full reload. Restored
7459
+ // first: the membership below is narrowed by it.
7460
+ if (itemsRaw) {
7461
+ this.restoreMetadataDatasetItems(itemsRaw);
7462
+ }
6736
7463
  if (membershipRaw) {
6737
- try {
6738
- const names = JSON.parse(membershipRaw);
6739
- if (Array.isArray(names) && names.length > 0) {
6740
- this._metadataDatasetEntityNames = new Set(names);
6741
- this.ensureInflightViewInvalidation();
6742
- }
6743
- }
6744
- catch (membershipErr) {
6745
- LogError(`[Metadata Cache] Failed to restore dataset membership: ${membershipErr instanceof Error ? membershipErr.message : String(membershipErr)}`);
6746
- }
7464
+ this.restoreMetadataDatasetMembership(membershipRaw);
6747
7465
  }
6748
7466
  if (!raw)
6749
7467
  return;
6750
- // Decompress if stored in compressed format, otherwise parse directly
7468
+ // Decompress if stored in compressed format, otherwise parse directly or adopt object directly
6751
7469
  const parseStart = Date.now();
6752
7470
  let temp;
6753
7471
  if (format === 'gzip' && typeof raw === 'string') {
@@ -6759,9 +7477,13 @@ export class ProviderBase {
6759
7477
  const jsonString = await new Response(decompressedStream).text();
6760
7478
  temp = JSON.parse(jsonString);
6761
7479
  }
6762
- else {
6763
- // Legacy uncompressed path
6764
- temp = typeof raw === 'string' ? JSON.parse(raw) : raw;
7480
+ else if (typeof raw === 'string') {
7481
+ // Legacy uncompressed string path
7482
+ temp = JSON.parse(raw);
7483
+ }
7484
+ else if (typeof raw === 'object' && raw !== null) {
7485
+ // Structured clone object path: directly adopt the cloned object
7486
+ temp = raw;
6765
7487
  }
6766
7488
  const parseMs = Date.now() - parseStart;
6767
7489
  if (!temp)
@@ -6771,6 +7493,7 @@ export class ProviderBase {
6771
7493
  const metadata = MetadataFromSimpleObject(temp, this);
6772
7494
  const deserializeMs = Date.now() - deserializeStart;
6773
7495
  if (metadata) {
7496
+ this.dropUnloadedQueryMetadata(metadata);
6774
7497
  this.UpdateLocalMetadata(metadata);
6775
7498
  const totalMs = Date.now() - overallStart;
6776
7499
  LogStatusEx({
@@ -6791,12 +7514,69 @@ export class ProviderBase {
6791
7514
  static { this.localStorageAllMetadataKey = this.localStorageRootKey + '_AllMetadata'; }
6792
7515
  static { this.localStorageFormatKey = this.localStorageRootKey + '_Format'; }
6793
7516
  static { this.localStorageDatasetMembershipKey = this.localStorageRootKey + '_DatasetMembership'; }
7517
+ /** The MJ_Metadata dataset items (see `_metadataDatasetItems`) of the stored snapshot. */
7518
+ static { this.localStorageDatasetItemsKey = this.localStorageRootKey + '_DatasetItems'; }
6794
7519
  static { this.localStorageKeys = [
6795
7520
  ProviderBase.localStorageTimestampsKey,
6796
7521
  ProviderBase.localStorageAllMetadataKey,
6797
7522
  ProviderBase.localStorageFormatKey,
6798
7523
  ProviderBase.localStorageDatasetMembershipKey,
7524
+ ProviderBase.localStorageDatasetItemsKey,
6799
7525
  ]; }
7526
+ /**
7527
+ * Adopts a stored metadata-member entity set. The entities that back only items this provider
7528
+ * does not read are removed, so a snapshot saved by a process configured to read them cannot
7529
+ * make writes to them schedule refreshes here.
7530
+ */
7531
+ restoreMetadataDatasetMembership(membershipRaw) {
7532
+ try {
7533
+ const names = JSON.parse(membershipRaw);
7534
+ if (!Array.isArray(names) || names.length === 0) {
7535
+ return;
7536
+ }
7537
+ const restored = new Set(names.filter((n) => typeof n === 'string'));
7538
+ for (const skipped of this.skippedMetadataEntityNames(this._metadataDatasetItems ?? [])) {
7539
+ restored.delete(skipped);
7540
+ }
7541
+ if (restored.size > 0) {
7542
+ this._metadataDatasetEntityNames = restored;
7543
+ this.ensureInflightViewInvalidation();
7544
+ }
7545
+ }
7546
+ catch (membershipErr) {
7547
+ LogError(`[Metadata Cache] Failed to restore dataset membership: ${membershipErr instanceof Error ? membershipErr.message : String(membershipErr)}`);
7548
+ }
7549
+ }
7550
+ /**
7551
+ * Adopts a stored dataset item list. Only a well-formed list replaces the one held: a damaged or
7552
+ * empty value must not erase the list a load already recorded.
7553
+ */
7554
+ restoreMetadataDatasetItems(itemsRaw) {
7555
+ try {
7556
+ const parsed = JSON.parse(itemsRaw);
7557
+ if (!Array.isArray(parsed) || parsed.length === 0) {
7558
+ return;
7559
+ }
7560
+ const restored = [];
7561
+ for (const entry of parsed) {
7562
+ if (typeof entry?.Code !== 'string' || typeof entry.EntityName !== 'string' || !entry.Code || !entry.EntityName) {
7563
+ return;
7564
+ }
7565
+ const latest = typeof entry.LatestUpdateDate === 'string' ? new Date(entry.LatestUpdateDate) : undefined;
7566
+ restored.push({
7567
+ Code: entry.Code,
7568
+ EntityName: entry.EntityName,
7569
+ EntityID: typeof entry.EntityID === 'string' ? entry.EntityID : undefined,
7570
+ RowCount: typeof entry.RowCount === 'number' ? entry.RowCount : undefined,
7571
+ LatestUpdateDate: latest && !isNaN(latest.getTime()) ? latest : undefined,
7572
+ });
7573
+ }
7574
+ this._metadataDatasetItems = restored;
7575
+ }
7576
+ catch (itemsErr) {
7577
+ LogError(`[Metadata Cache] Failed to restore the dataset item list: ${itemsErr instanceof Error ? itemsErr.message : String(itemsErr)}`);
7578
+ }
7579
+ }
6800
7580
  /**
6801
7581
  * Converts a base64-encoded string to an ArrayBuffer.
6802
7582
  * Used for compressed metadata storage/retrieval.
@@ -6883,6 +7663,115 @@ export class ProviderBase {
6883
7663
  verboseOnly: false
6884
7664
  });
6885
7665
  }
7666
+ /** Default debounce duration in milliseconds for coalesced metadata snapshot writes to local storage. */
7667
+ static { this.MetadataSnapshotSaveDebounceMs = 250; }
7668
+ /**
7669
+ * Schedules a trailing-edge coalesced background call to `SaveLocalMetadataToStorage()`,
7670
+ * deduplicating rapid back-to-back calls within the window and serializing execution if an
7671
+ * in-flight save is already running.
7672
+ *
7673
+ * @param delayMs - Debounce window duration in milliseconds (defaults to `ProviderBase.MetadataSnapshotSaveDebounceMs`)
7674
+ */
7675
+ ScheduleSaveLocalMetadataToStorage(delayMs = ProviderBase.MetadataSnapshotSaveDebounceMs) {
7676
+ if (!this.LocalStorageProvider)
7677
+ return;
7678
+ if (!this.MetadataSnapshotPersistenceEnabled) {
7679
+ this.logMetadataSnapshotDisabledOnce();
7680
+ return;
7681
+ }
7682
+ if (this._inFlightMetadataSave) {
7683
+ this._hasPendingMetadataSaveWhileInFlight = true;
7684
+ return;
7685
+ }
7686
+ if (this._metadataSaveTimer) {
7687
+ clearTimeout(this._metadataSaveTimer);
7688
+ }
7689
+ this._metadataSaveTimer = setTimeout(() => {
7690
+ this._metadataSaveTimer = null;
7691
+ void this.triggerSerializedMetadataSave();
7692
+ }, delayMs);
7693
+ if (typeof this._metadataSaveTimer?.unref === 'function') {
7694
+ this._metadataSaveTimer.unref();
7695
+ }
7696
+ }
7697
+ /**
7698
+ * Cancels any pending debounce timer and awaits `SaveLocalMetadataToStorage()` immediately
7699
+ * (or awaits any in-flight save plus trailing save), so tests and shutdown hooks can
7700
+ * deterministically flush pending writes.
7701
+ */
7702
+ async FlushPendingMetadataStorageSave() {
7703
+ if (this._metadataSaveTimer) {
7704
+ clearTimeout(this._metadataSaveTimer);
7705
+ this._metadataSaveTimer = null;
7706
+ this._hasPendingMetadataSaveWhileInFlight = true;
7707
+ }
7708
+ if (this._inFlightMetadataSave) {
7709
+ await this._inFlightMetadataSave;
7710
+ return;
7711
+ }
7712
+ if (this._hasPendingMetadataSaveWhileInFlight) {
7713
+ await this.triggerSerializedMetadataSave();
7714
+ }
7715
+ }
7716
+ /**
7717
+ * Clears any pending metadata snapshot save timer without saving.
7718
+ */
7719
+ CancelPendingMetadataStorageSave() {
7720
+ if (this._metadataSaveTimer) {
7721
+ clearTimeout(this._metadataSaveTimer);
7722
+ this._metadataSaveTimer = null;
7723
+ }
7724
+ this._hasPendingMetadataSaveWhileInFlight = false;
7725
+ }
7726
+ triggerSerializedMetadataSave() {
7727
+ if (!this._inFlightMetadataSave) {
7728
+ this._inFlightMetadataSave = this.executeSerializedMetadataSave().finally(() => {
7729
+ this._inFlightMetadataSave = null;
7730
+ });
7731
+ }
7732
+ return this._inFlightMetadataSave;
7733
+ }
7734
+ async executeSerializedMetadataSave() {
7735
+ do {
7736
+ this._hasPendingMetadataSaveWhileInFlight = false;
7737
+ try {
7738
+ await this.SaveLocalMetadataToStorage();
7739
+ }
7740
+ catch {
7741
+ // SaveLocalMetadataToStorage catches its own errors; guard here as well
7742
+ }
7743
+ } while (this._hasPendingMetadataSaveWhileInFlight);
7744
+ }
7745
+ /**
7746
+ * Converts BaseInfo instances and nested objects into plain structured-cloneable
7747
+ * objects without JSON.stringify/JSON.parse, stripping functions and WeakRefs.
7748
+ */
7749
+ static toCloneableValue(val) {
7750
+ if (val == null || typeof val !== 'object') {
7751
+ return val;
7752
+ }
7753
+ if (val instanceof Date || val instanceof RegExp || val instanceof ArrayBuffer || ArrayBuffer.isView(val)) {
7754
+ return val;
7755
+ }
7756
+ if (Array.isArray(val)) {
7757
+ const out = new Array(val.length);
7758
+ for (let i = 0; i < val.length; i++) {
7759
+ out[i] = ProviderBase.toCloneableValue(val[i]);
7760
+ }
7761
+ return out;
7762
+ }
7763
+ const maybeToJson = val;
7764
+ if (typeof maybeToJson.toJSON === 'function') {
7765
+ return ProviderBase.toCloneableValue(maybeToJson.toJSON());
7766
+ }
7767
+ const out = {};
7768
+ for (const [k, v] of Object.entries(val)) {
7769
+ if (typeof v !== 'function' && !(typeof WeakRef !== 'undefined' && v instanceof WeakRef)) {
7770
+ out[k] = ProviderBase.toCloneableValue(v);
7771
+ }
7772
+ }
7773
+ return out;
7774
+ }
6886
7775
  /**
6887
7776
  * Saves current metadata to local storage for caching.
6888
7777
  * Serializes both timestamps and full metadata collections.
@@ -6899,25 +7788,37 @@ export class ProviderBase {
6899
7788
  return;
6900
7789
  }
6901
7790
  const start = Date.now();
6902
- // Serialize the AllMetadata object FIRST. If this throws (or the payload write below
6903
- // fails), nothing else has been written yet, so the previously stored timestamps still
6904
- // describe the previously stored payload and LocalMetadataObsolete() will report
6905
- // obsolete on the next boot — which is what makes the save retry. Writing timestamps
6906
- // before the payload left the cache claiming freshness with no payload behind it, and
6907
- // that state was never retried.
6908
- const jsonString = JSON.stringify(this._localMetadata);
6909
- const snapshot = await this.writeMetadataSnapshot(ls, jsonString);
7791
+ const dataKey = this.LocalStoragePrefix + ProviderBase.localStorageAllMetadataKey;
7792
+ const formatKey = this.LocalStoragePrefix + ProviderBase.localStorageFormatKey;
7793
+ let snapshot;
7794
+ if (typeof ls.SetObject === 'function') {
7795
+ // Structured-clone path: convert BaseInfo instances to plain cloneable objects (stripping
7796
+ // WeakRef/provider back-references without JSON.stringify/gzip/JSON.parse or lazy field hydration)
7797
+ const cloneableMetadata = ProviderBase.toCloneableValue(this._localMetadata);
7798
+ await ls.SetObject(dataKey, cloneableMetadata);
7799
+ await ls.SetItem(formatKey, 'structured-clone');
7800
+ snapshot = { compressed: false, storedLength: 0 };
7801
+ }
7802
+ else {
7803
+ // Serialized string path (JSON.stringify + gzip/base64 when CompressionStream is available)
7804
+ const jsonString = JSON.stringify(this._localMetadata);
7805
+ snapshot = await this.writeMetadataSnapshot(ls, jsonString);
7806
+ }
6910
7807
  // Persist the metadata-member entity set beside the snapshot it belongs to, so the
6911
7808
  // event-driven refresh survives a warm boot (see LoadLocalMetadataFromStorage).
6912
7809
  if (this._metadataDatasetEntityNames?.size) {
6913
7810
  await ls.SetItem(this.LocalStoragePrefix + ProviderBase.localStorageDatasetMembershipKey, JSON.stringify([...this._metadataDatasetEntityNames]));
6914
7811
  }
7812
+ // And the dataset item list, so a warm boot can reload only what changed.
7813
+ if (this._metadataDatasetItems?.length) {
7814
+ await ls.SetItem(this.LocalStoragePrefix + ProviderBase.localStorageDatasetItemsKey, JSON.stringify(this._metadataDatasetItems));
7815
+ }
6915
7816
  // Timestamps LAST: they are the freshness claim for everything written above, so they
6916
7817
  // must be the final thing to land.
6917
7818
  const timestampsRaw = JSON.stringify(this._latestLocalMetadataTimestamps);
6918
7819
  await ls.SetItem(this.LocalStoragePrefix + ProviderBase.localStorageTimestampsKey, timestampsRaw);
6919
7820
  this._storedTimestampsRaw = timestampsRaw;
6920
- this.logMetadataSaveComplete(Date.now() - start, jsonString.length, snapshot);
7821
+ this.logMetadataSaveComplete(Date.now() - start, snapshot.storedLength, snapshot);
6921
7822
  }
6922
7823
  catch (e) {
6923
7824
  LogError(`[Metadata Cache] SaveLocalMetadataToStorage failed: ${e instanceof Error ? e.message : String(e)}`);
@@ -6964,6 +7865,12 @@ export class ProviderBase {
6964
7865
  verboseOnly: true
6965
7866
  });
6966
7867
  }
7868
+ else if (snapshot.storedLength === 0) {
7869
+ LogStatusEx({
7870
+ message: `[Metadata Cache] Save complete (structured-clone): ${elapsedMs}ms`,
7871
+ verboseOnly: true
7872
+ });
7873
+ }
6967
7874
  else {
6968
7875
  LogStatusEx({
6969
7876
  message: `[Metadata Cache] Save complete (uncompressed): ${elapsedMs}ms, size=${mb(rawLength)}MB`,