@memberjunction/realtime-widget 6.3.0-edge.0 → 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.
@@ -9,6 +9,7 @@ import {
9
9
  Float32VectorToBase64,
10
10
  FormatBinaryChangeValue,
11
11
  GeneratePluralName,
12
+ GetClassName,
12
13
  GetGlobalObjectStore,
13
14
  IndexByUUID,
14
15
  IsMemberOverridden,
@@ -48,7 +49,7 @@ import {
48
49
  shareReplay,
49
50
  switchMap,
50
51
  uuidv4
51
- } from "./chunk-3SGPPDAR.js";
52
+ } from "./chunk-KHEWGJIZ.js";
52
53
 
53
54
  // ../../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
54
55
  var require_ms = __commonJS({
@@ -515,6 +516,7 @@ var require_browser = __commonJS({
515
516
 
516
517
  // ../../MJCore/dist/generic/dataHooks.js
517
518
  var DATA_HOOKS_KEY = "__mj_dataHooks";
519
+ var POST_RUNVIEW_PROTECTED_ENTITIES_KEY = "__mj_postRunViewProtectedEntities";
518
520
  var _globalStore = void 0;
519
521
  function globalStore() {
520
522
  if (_globalStore === void 0) {
@@ -529,6 +531,27 @@ function GetDataHooks(hookName) {
529
531
  const store = gos[DATA_HOOKS_KEY];
530
532
  return store?.[hookName] ?? [];
531
533
  }
534
+ function IsPostRunViewProtectedEntity(entityName) {
535
+ const trimmed = entityName?.trim();
536
+ if (!trimmed) {
537
+ return false;
538
+ }
539
+ const gos = globalStore();
540
+ const set = gos?.[POST_RUNVIEW_PROTECTED_ENTITIES_KEY];
541
+ if (!set || set.size === 0) {
542
+ return false;
543
+ }
544
+ if (set.has(trimmed)) {
545
+ return true;
546
+ }
547
+ const lower = trimmed.toLowerCase();
548
+ for (const existing of set) {
549
+ if (existing.toLowerCase() === lower) {
550
+ return true;
551
+ }
552
+ }
553
+ return false;
554
+ }
532
555
 
533
556
  // ../../MJCore/dist/generic/logging.js
534
557
  var import_debug = __toESM(require_browser(), 1);
@@ -7029,7 +7052,7 @@ var RoleInfo = class extends BaseInfo {
7029
7052
  this.copyInitData(initData);
7030
7053
  }
7031
7054
  };
7032
- var RowLevelSecurityFilterInfo = class extends BaseInfo {
7055
+ var RowLevelSecurityFilterInfo = class _RowLevelSecurityFilterInfo extends BaseInfo {
7033
7056
  constructor(initData) {
7034
7057
  super();
7035
7058
  this.ID = null;
@@ -7068,7 +7091,40 @@ var RowLevelSecurityFilterInfo = class extends BaseInfo {
7068
7091
  * @returns {string} The filter text with all user tokens replaced with actual values
7069
7092
  */
7070
7093
  MarkupFilterText(user, options) {
7071
- let ret = this.FilterText;
7094
+ const ret = this.substituteTokens(this.FilterText, user);
7095
+ const unresolvedMatch = ret.match(/\{\{(?:User|Acting)\w+\}\}/);
7096
+ if (unresolvedMatch) {
7097
+ if (options?.unresolvedBehavior === "match-nothing") {
7098
+ LogError("Row filter has unresolved token after markup \u2014 resolving filter to (1=0): " + unresolvedMatch[0] + " in filter: " + this.FilterText);
7099
+ return "(1=0)";
7100
+ }
7101
+ LogError("RLS filter has unresolved token after markup: " + unresolvedMatch[0] + " in filter: " + this.FilterText);
7102
+ }
7103
+ return ret;
7104
+ }
7105
+ /**
7106
+ * {@link MarkupFilterText} with the user's values bound as query parameters where that cannot
7107
+ * change the filter's meaning (#5713): a token that is a whole quoted literal on its own
7108
+ * (`'{{UserID}}'`, `N'{{UserEmail}}'`, `'{{ScopeResourceID}}'`, a scalar `'{{Acting…}}'`) is
7109
+ * replaced, quotes included, by the placeholder `binder` returns. Every other placement (inside a
7110
+ * `LIKE` pattern, unquoted, the `{{ActingCompanyIDs}}` list) keeps literal text, escaped as in
7111
+ * {@link MarkupFilterText}. Unresolved tokens are handled exactly as there, and a filter that
7112
+ * resolves to `(1=0)` binds nothing.
7113
+ *
7114
+ * The text is the same for every user whose tokens resolve, so SQL Server compiles one plan per
7115
+ * query shape instead of one per user. Placeholders follow the order tokens appear in, so the
7116
+ * same filters always produce the same text.
7117
+ */
7118
+ MarkupFilterParameterized(user, binder, options) {
7119
+ const literal = this.MarkupFilterText(user, options);
7120
+ if (!user || literal === "(1=0)" && options?.unresolvedBehavior === "match-nothing") {
7121
+ return literal;
7122
+ }
7123
+ return this.substituteTokens(this.bindWholeLiteralTokens(this.FilterText, user, binder), user);
7124
+ }
7125
+ /** Substitutes every token the user resolves as escaped literal text; unresolved tokens are left in place. */
7126
+ substituteTokens(text, user) {
7127
+ let ret = text;
7072
7128
  if (user) {
7073
7129
  const keys = Object.keys(user);
7074
7130
  for (let i = 0; i < keys.length; i++) {
@@ -7086,15 +7142,105 @@ var RowLevelSecurityFilterInfo = class extends BaseInfo {
7086
7142
  ret = ret.replace(/\{\{ScopeResourceType\}\}/g, () => scopeType);
7087
7143
  ret = this.resolveActingTokens(ret, user);
7088
7144
  }
7089
- const unresolvedMatch = ret.match(/\{\{(?:User|Acting)\w+\}\}/);
7090
- if (unresolvedMatch) {
7091
- if (options?.unresolvedBehavior === "match-nothing") {
7092
- LogError("Row filter has unresolved token after markup \u2014 resolving filter to (1=0): " + unresolvedMatch[0] + " in filter: " + this.FilterText);
7093
- return "(1=0)";
7145
+ return ret;
7146
+ }
7147
+ /**
7148
+ * The value a scalar token resolves to for `user`, unescaped, or undefined when it does not
7149
+ * resolve (or is the list token, which stays literal). Same rules as {@link substituteTokens}.
7150
+ */
7151
+ scalarTokenValue(token, user) {
7152
+ if (token === "ScopeResourceID") {
7153
+ return user.MagicLinkScope?.ResourceID ?? "";
7154
+ }
7155
+ if (token === "ScopeResourceType") {
7156
+ return user.MagicLinkScope?.ResourceType ?? "";
7157
+ }
7158
+ if (token === "ActingOrganizationID" || token === "ActingPersonID" || token === "ActingScopeID") {
7159
+ const value = user.APIKeyActingContext?.[token];
7160
+ return value != null && value.length > 0 ? value : void 0;
7161
+ }
7162
+ if (token.startsWith("User")) {
7163
+ const key = token.slice("User".length);
7164
+ if (!Object.keys(user).includes(key)) {
7165
+ return void 0;
7094
7166
  }
7095
- LogError("RLS filter has unresolved token after markup: " + unresolvedMatch[0] + " in filter: " + this.FilterText);
7167
+ const val = user[key];
7168
+ return val != null && typeof val !== "object" ? String(val) : void 0;
7096
7169
  }
7097
- return ret;
7170
+ return void 0;
7171
+ }
7172
+ /**
7173
+ * Replaces each string literal whose whole content is one resolvable scalar token with the
7174
+ * placeholder `binder` gives for its value. Walks the text the way the SQL parser does (string
7175
+ * literals with `''` escapes, `[...]` and `"..."` identifiers, `--` and block comments), so a
7176
+ * token is bound only where it is a complete literal.
7177
+ */
7178
+ bindWholeLiteralTokens(text, user, binder) {
7179
+ let out = "";
7180
+ let i = 0;
7181
+ while (i < text.length) {
7182
+ const ch = text[i];
7183
+ const skipTo = _RowLevelSecurityFilterInfo.endOfNonLiteralSpan(text, i);
7184
+ if (skipTo > i) {
7185
+ out += text.slice(i, skipTo);
7186
+ i = skipTo;
7187
+ continue;
7188
+ }
7189
+ if (ch !== "'") {
7190
+ out += ch;
7191
+ i++;
7192
+ continue;
7193
+ }
7194
+ let end = i + 1;
7195
+ while (end < text.length) {
7196
+ if (text[end] === "'" && text[end + 1] === "'") {
7197
+ end += 2;
7198
+ } else if (text[end] === "'") {
7199
+ break;
7200
+ } else {
7201
+ end++;
7202
+ }
7203
+ }
7204
+ const literal = text.slice(i, end + 1);
7205
+ const tokenMatch = /^'\{\{(\w+)\}\}'$/.exec(literal);
7206
+ const value = tokenMatch ? this.scalarTokenValue(tokenMatch[1], user) : void 0;
7207
+ const placeholder = tokenMatch && value !== void 0 ? binder.Bind(tokenMatch[1], value) : null;
7208
+ if (placeholder !== null) {
7209
+ if (/[Nn]$/.test(out) && !/[\w@#$]$/.test(out.slice(0, -1))) {
7210
+ out = out.slice(0, -1);
7211
+ }
7212
+ out += placeholder;
7213
+ } else {
7214
+ out += literal;
7215
+ }
7216
+ i = end + 1;
7217
+ }
7218
+ return out;
7219
+ }
7220
+ /**
7221
+ * Where a bracketed or double-quoted identifier or a comment starting at `i` ends; `i` when none
7222
+ * starts there. Inside an identifier a doubled closing character (`]]`, `""`) is an escaped
7223
+ * character of the name, not its end.
7224
+ */
7225
+ static endOfNonLiteralSpan(text, i) {
7226
+ const ch = text[i];
7227
+ if (ch === "[" || ch === '"') {
7228
+ const closeChar = ch === "[" ? "]" : '"';
7229
+ let close = text.indexOf(closeChar, i + 1);
7230
+ while (close >= 0 && text[close + 1] === closeChar) {
7231
+ close = text.indexOf(closeChar, close + 2);
7232
+ }
7233
+ return close < 0 ? text.length : close + 1;
7234
+ }
7235
+ if (ch === "-" && text[i + 1] === "-") {
7236
+ const eol = text.indexOf("\n", i);
7237
+ return eol < 0 ? text.length : eol;
7238
+ }
7239
+ if (ch === "/" && text[i + 1] === "*") {
7240
+ const close = text.indexOf("*/", i + 2);
7241
+ return close < 0 ? text.length : close + 2;
7242
+ }
7243
+ return i;
7098
7244
  }
7099
7245
  /**
7100
7246
  * Resolves the `{{Acting*}}` token family from {@link UserInfo.APIKeyActingContext}.
@@ -9473,19 +9619,19 @@ var Metadata = class _Metadata {
9473
9619
  }
9474
9620
  return this.Entities.find((e) => UUIDsEqual(e.ID, entityID));
9475
9621
  }
9476
- /** @deprecated Use `QueryEngine.Instance.Queries` from `@memberjunction/core-entities` instead. */
9622
+ /** @deprecated Use `QueryEngine.Instance.Queries` from `@memberjunction/core-entities` instead. Empty unless the provider is configured with `LoadQueryMetadata`; removed in 7.0. */
9477
9623
  get Queries() {
9478
9624
  return _Metadata.Provider.Queries;
9479
9625
  }
9480
- /** @deprecated Use `QueryEngine.Instance.Fields` from `@memberjunction/core-entities` instead. */
9626
+ /** @deprecated Use `QueryEngine.Instance.Fields` from `@memberjunction/core-entities` instead. Empty unless the provider is configured with `LoadQueryMetadata`; removed in 7.0. */
9481
9627
  get QueryFields() {
9482
9628
  return _Metadata.Provider.QueryFields;
9483
9629
  }
9484
- /** @deprecated Use `QueryEngine.Instance.Categories` from `@memberjunction/core-entities` instead. */
9630
+ /** @deprecated Use `QueryEngine.Instance.Categories` from `@memberjunction/core-entities` instead. Empty unless the provider is configured with `LoadQueryMetadata`; removed in 7.0. */
9485
9631
  get QueryCategories() {
9486
9632
  return _Metadata.Provider.QueryCategories;
9487
9633
  }
9488
- /** @deprecated Use `QueryEngine.Instance.Permissions` from `@memberjunction/core-entities` instead. */
9634
+ /** @deprecated Use `QueryEngine.Instance.Permissions` from `@memberjunction/core-entities` instead. Empty unless the provider is configured with `LoadQueryMetadata`; removed in 7.0. */
9489
9635
  get QueryPermissions() {
9490
9636
  return _Metadata.Provider.QueryPermissions;
9491
9637
  }
@@ -11625,6 +11771,8 @@ var EntityFieldInfo = class _EntityFieldInfo extends BaseInfo {
11625
11771
  this.RelatedEntityBaseView = null;
11626
11772
  this.RelatedEntityCodeName = null;
11627
11773
  this.RelatedEntityClassName = null;
11774
+ this.IsFloat = false;
11775
+ this.RelatedEntityTableAlias = null;
11628
11776
  this._rawEntityFieldValues = null;
11629
11777
  this._entityFieldValuesConstructed = false;
11630
11778
  this._normalizedValueListValues = void 0;
@@ -12288,6 +12436,88 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12288
12436
  }
12289
12437
  return primary.length > 0 && allowed.has(primary) || secondary.length > 0 && allowed.has(secondary);
12290
12438
  }
12439
+ /**
12440
+ * Whether EntityFieldInfo instances have been materialized for this entity.
12441
+ * True if .Fields or any field-derived getter has been accessed; false if still deferred.
12442
+ */
12443
+ get IsFieldsLoaded() {
12444
+ return this._fieldsLoaded;
12445
+ }
12446
+ /**
12447
+ * Serializes EntityInfo to a plain object without forcing lazy EntityFieldInfo
12448
+ * materialization when fields are still deferred.
12449
+ */
12450
+ toJSON() {
12451
+ if (this._fieldsLoaded) {
12452
+ return super.toJSON();
12453
+ }
12454
+ const savedRaw = this._rawFields;
12455
+ this._fieldsLoaded = true;
12456
+ this._fields = [];
12457
+ let result;
12458
+ try {
12459
+ result = super.toJSON();
12460
+ } finally {
12461
+ this._fieldsLoaded = false;
12462
+ this._rawFields = savedRaw;
12463
+ }
12464
+ result["Fields"] = savedRaw ? savedRaw.map((item) => item instanceof EntityFieldInfo ? item.toJSON() : item) : [];
12465
+ return result;
12466
+ }
12467
+ /**
12468
+ * Ensures EntityFieldInfo instances are created for this entity.
12469
+ * Deferring creation until .Fields or a field-derived getter is accessed
12470
+ * saves allocating thousands of EntityFieldInfo objects at startup.
12471
+ */
12472
+ EnsureFieldsLoaded() {
12473
+ if (this._fieldsLoaded) {
12474
+ return;
12475
+ }
12476
+ this._fieldsLoaded = true;
12477
+ if (this._rawFields && this._rawFields.length > 0) {
12478
+ const md = this.OwningProvider;
12479
+ const fields = [];
12480
+ for (let j = 0; j < this._rawFields.length; j++) {
12481
+ const item = this._rawFields[j];
12482
+ const field = item instanceof EntityFieldInfo ? item : new EntityFieldInfo(item);
12483
+ if (md) {
12484
+ field.SetOwningProvider(md);
12485
+ }
12486
+ fields.push(field);
12487
+ }
12488
+ this._fields = fields;
12489
+ this._rawFields = null;
12490
+ } else if (!this._fields) {
12491
+ this._fields = [];
12492
+ }
12493
+ let virtualCount = 0;
12494
+ let floatCount = 0;
12495
+ let hasIdField = false;
12496
+ for (let j = 0; j < this._fields.length; ++j) {
12497
+ const f = this._fields[j];
12498
+ if (f.Name && f.Name.trim().toUpperCase() === "ID") {
12499
+ hasIdField = true;
12500
+ }
12501
+ virtualCount += f.IsVirtual ? 1 : 0;
12502
+ floatCount += f.IsFloat ? 1 : 0;
12503
+ }
12504
+ if (this._lazyHasIdField === void 0) {
12505
+ this._lazyHasIdField = hasIdField;
12506
+ }
12507
+ if (this._lazyVirtualCount === void 0) {
12508
+ this._lazyVirtualCount = virtualCount;
12509
+ }
12510
+ if (this._lazyFloatCount === void 0) {
12511
+ this._lazyFloatCount = floatCount;
12512
+ }
12513
+ }
12514
+ get HasIdField() {
12515
+ this.EnsureFieldsLoaded();
12516
+ return this._lazyHasIdField ?? false;
12517
+ }
12518
+ set HasIdField(value) {
12519
+ this._lazyHasIdField = value;
12520
+ }
12291
12521
  /** @deprecated Use {@link HasIdField}. */
12292
12522
  get _hasIdField() {
12293
12523
  return this.HasIdField;
@@ -12296,6 +12526,13 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12296
12526
  set _hasIdField(value) {
12297
12527
  this.HasIdField = value;
12298
12528
  }
12529
+ get VirtualCount() {
12530
+ this.EnsureFieldsLoaded();
12531
+ return this._lazyVirtualCount ?? 0;
12532
+ }
12533
+ set VirtualCount(value) {
12534
+ this._lazyVirtualCount = value;
12535
+ }
12299
12536
  /** @deprecated Use {@link VirtualCount}. */
12300
12537
  get _virtualCount() {
12301
12538
  return this.VirtualCount;
@@ -12320,6 +12557,13 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12320
12557
  set _oneToManyCount(value) {
12321
12558
  this.OneToManyCount = value;
12322
12559
  }
12560
+ get FloatCount() {
12561
+ this.EnsureFieldsLoaded();
12562
+ return this._lazyFloatCount ?? 0;
12563
+ }
12564
+ set FloatCount(value) {
12565
+ this._lazyFloatCount = value;
12566
+ }
12323
12567
  /** @deprecated Use {@link FloatCount}. */
12324
12568
  get _floatCount() {
12325
12569
  return this.FloatCount;
@@ -12553,8 +12797,9 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12553
12797
  _entityDeniedFieldsCache.set(this, byUser);
12554
12798
  }
12555
12799
  let entry = byUser.get(user);
12556
- if (!entry || entry.fieldsRef !== this._fields || entry.generation !== generation || !sameAncestors(entry.ancestors, ancestors) || entry.rolesKey !== rolesKey) {
12557
- entry = { fieldsRef: this._fields, generation, ancestors, rolesKey };
12800
+ const fields = this.Fields;
12801
+ if (!entry || entry.fieldsRef !== fields || entry.generation !== generation || !sameAncestors(entry.ancestors, ancestors) || entry.rolesKey !== rolesKey) {
12802
+ entry = { fieldsRef: fields, generation, ancestors, rolesKey };
12558
12803
  byUser.set(user, entry);
12559
12804
  }
12560
12805
  return entry;
@@ -12589,7 +12834,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12589
12834
  getDeniedFields(user, verb, isDenied) {
12590
12835
  const denied = /* @__PURE__ */ new Set();
12591
12836
  if (this.EnableFieldLevelSecurity) {
12592
- for (const field of this._fields) {
12837
+ for (const field of this.Fields) {
12593
12838
  if (isDenied(field.GetUserFieldPermissions(user, true))) {
12594
12839
  this.addDeniedField(denied, field);
12595
12840
  }
@@ -12623,7 +12868,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12623
12868
  if (parentDenied.size === 0) {
12624
12869
  return;
12625
12870
  }
12626
- for (const field of this._fields) {
12871
+ for (const field of this.Fields) {
12627
12872
  const parentField = parent.FieldByName(field.Name);
12628
12873
  if (parentField && parentDenied.has(parentField.Name.trim().toLowerCase())) {
12629
12874
  this.addDeniedField(denied, field);
@@ -12650,7 +12895,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12650
12895
  if (name == null)
12651
12896
  return void 0;
12652
12897
  if (this._fieldByNameMap === null) {
12653
- const fields = this._fields ?? this.Fields ?? [];
12898
+ const fields = this.Fields ?? [];
12654
12899
  const map2 = /* @__PURE__ */ new Map();
12655
12900
  for (const f of fields) {
12656
12901
  if (f.Name != null)
@@ -12661,7 +12906,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12661
12906
  return this._fieldByNameMap.get(name.trim().toLowerCase());
12662
12907
  }
12663
12908
  ensureFieldIndexEntry() {
12664
- const fields = this._fields ?? this.Fields ?? [];
12909
+ const fields = this.Fields ?? [];
12665
12910
  let entry = _entityFieldIndexCache.get(this);
12666
12911
  if (!entry || entry.fieldsRef !== fields || entry.fieldsLen !== fields.length) {
12667
12912
  const byName = /* @__PURE__ */ new Map();
@@ -12713,7 +12958,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12713
12958
  */
12714
12959
  FieldByCodeName(codeName) {
12715
12960
  const idx = this.FieldIndexByCodeName(codeName);
12716
- const fields = this._fields ?? this.Fields;
12961
+ const fields = this.Fields;
12717
12962
  return idx >= 0 && fields ? fields[idx] : void 0;
12718
12963
  }
12719
12964
  /**
@@ -12814,6 +13059,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12814
13059
  * @returns {EntityFieldInfo[]} Array of all entity fields
12815
13060
  */
12816
13061
  get Fields() {
13062
+ this.EnsureFieldsLoaded();
12817
13063
  return this._fields;
12818
13064
  }
12819
13065
  /**
@@ -12829,7 +13075,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12829
13075
  */
12830
13076
  get HasInactiveFields() {
12831
13077
  if (this._hasInactiveFields === void 0) {
12832
- this._hasInactiveFields = this._fields.some((f) => f.Status === "Deprecated" || f.Status === "Disabled");
13078
+ this._hasInactiveFields = this.Fields.some((f) => f.Status === "Deprecated" || f.Status === "Disabled");
12833
13079
  }
12834
13080
  return this._hasInactiveFields;
12835
13081
  }
@@ -12855,7 +13101,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12855
13101
  */
12856
13102
  get HasSearchFields() {
12857
13103
  if (this._hasSearchFields === void 0) {
12858
- this._hasSearchFields = this._fields.some((f) => f.IncludeInUserSearchAPI);
13104
+ this._hasSearchFields = this.Fields.some((f) => f.IncludeInUserSearchAPI);
12859
13105
  }
12860
13106
  return this._hasSearchFields;
12861
13107
  }
@@ -13552,13 +13798,24 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13552
13798
  if (this.UserExemptFromRowLevelSecurity(user, type)) {
13553
13799
  return "";
13554
13800
  }
13801
+ const sRLSSQL = this.roleRowFilterClause(user, type, null);
13802
+ if (sRLSSQL.length === 0) {
13803
+ return "";
13804
+ }
13805
+ return `${returnPrefix && returnPrefix.length > 0 ? returnPrefix + " " : ""}${sRLSSQL}`;
13806
+ }
13807
+ /**
13808
+ * The role layer of the row filter, '' when no role filter applies. Callers check the
13809
+ * role-RLS exemption first. With a `binder`, user values bind as parameters
13810
+ * ({@link RowLevelSecurityFilterInfo.MarkupFilterParameterized}).
13811
+ */
13812
+ roleRowFilterClause(user, type, binder) {
13555
13813
  const userRLS = this.GetUserRowLevelSecurityInfo(user, type);
13556
13814
  if (!userRLS || userRLS.length === 0) {
13557
13815
  return "";
13558
13816
  }
13559
- const terms = userRLS.map((rls) => `(${rls.MarkupFilterText(user)})`);
13560
- const sRLSSQL = terms.length > 1 ? `(${terms.join(" OR ")})` : terms[0];
13561
- return `${returnPrefix && returnPrefix.length > 0 ? returnPrefix + " " : ""}${sRLSSQL}`;
13817
+ const terms = userRLS.map((rls) => `(${binder ? rls.MarkupFilterParameterized(user, binder) : rls.MarkupFilterText(user)})`);
13818
+ return terms.length > 1 ? `(${terms.join(" OR ")})` : terms[0];
13562
13819
  }
13563
13820
  /**
13564
13821
  * The EFFECTIVE row-filter clause for a user + permission type: role RLS (subject to the
@@ -13576,22 +13833,36 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13576
13833
  *
13577
13834
  * The application-ceiling layer (APIApplicationScope.RowFilterID) is deferred to v2 by
13578
13835
  * design decision; the column ships unused and the term composes here when it lands.
13579
- */
13580
- GetEffectiveRowFilterWhereClause(user, type, returnPrefix) {
13836
+ *
13837
+ * With a `binder`, the user's values bind as query parameters (#5713): same layers, same
13838
+ * order, same composition, but each token that is a whole quoted literal is replaced by the
13839
+ * placeholder `binder` returns, so the clause text is the same for every user and the
13840
+ * database reuses one plan per query shape. The binder collects the parameters in
13841
+ * placeholder order, and binds nothing when no layer contributes. The binder is an optional
13842
+ * argument of this method rather than a separate one so that every implementation of the
13843
+ * method, test doubles included, keeps answering the call. The RunView cache fingerprint
13844
+ * must call this without a binder: the literal clause is what keeps two users from sharing
13845
+ * a cached result.
13846
+ */
13847
+ GetEffectiveRowFilterWhereClause(user, type, returnPrefix, binder) {
13848
+ const sql = this.effectiveRowFilterClause(user, type, binder ?? null);
13849
+ if (sql.length === 0) {
13850
+ return "";
13851
+ }
13852
+ return `${returnPrefix && returnPrefix.length > 0 ? returnPrefix + " " : ""}${sql}`;
13853
+ }
13854
+ /** The composed row-filter clause without a prefix; literal when `binder` is null. */
13855
+ effectiveRowFilterClause(user, type, binder) {
13581
13856
  const layers = [];
13582
- const roleClause = this.GetUserRowLevelSecurityWhereClause(user, type, "");
13857
+ const roleClause = binder === null ? this.GetUserRowLevelSecurityWhereClause(user, type, "") : this.UserExemptFromRowLevelSecurity(user, type) ? "" : this.roleRowFilterClause(user, type, binder);
13583
13858
  if (roleClause && roleClause.length > 0) {
13584
13859
  layers.push(`(${roleClause})`);
13585
13860
  }
13586
- const keyClause = this.getAPIKeyRowFilterClause(user, type);
13861
+ const keyClause = this.getAPIKeyRowFilterClause(user, type, binder);
13587
13862
  if (keyClause && keyClause.length > 0) {
13588
13863
  layers.push(`(${keyClause})`);
13589
13864
  }
13590
- if (layers.length === 0) {
13591
- return "";
13592
- }
13593
- const sql = layers.join(" AND ");
13594
- return `${returnPrefix && returnPrefix.length > 0 ? returnPrefix + " " : ""}${sql}`;
13865
+ return layers.join(" AND ");
13595
13866
  }
13596
13867
  /**
13597
13868
  * Resolves the API-key row-filter clause for this entity + permission type from the
@@ -13601,7 +13872,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13601
13872
  * or unloaded) contributes `(1=0)`, and unresolved tokens inside a filter collapse it
13602
13873
  * to `(1=0)` via the match-nothing markup mode.
13603
13874
  */
13604
- getAPIKeyRowFilterClause(user, type) {
13875
+ getAPIKeyRowFilterClause(user, type, binder) {
13605
13876
  const bindings = user?.APIKeyRowFilters;
13606
13877
  if (!bindings || bindings.length === 0) {
13607
13878
  return "";
@@ -13616,7 +13887,8 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13616
13887
  LogError(`API-key row filter ${b.FilterID} for entity ${this.Name} not found in metadata \u2014 resolving to (1=0)`);
13617
13888
  return "(1=0)";
13618
13889
  }
13619
- return `(${filter2.MarkupFilterText(user, { unresolvedBehavior: "match-nothing" })})`;
13890
+ const options = { unresolvedBehavior: "match-nothing" };
13891
+ return `(${binder ? filter2.MarkupFilterParameterized(user, binder, options) : filter2.MarkupFilterText(user, options)})`;
13620
13892
  });
13621
13893
  return clauses.join(" AND ");
13622
13894
  }
@@ -14007,15 +14279,18 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14007
14279
  this.ParentEntity = null;
14008
14280
  this.ParentBaseTable = null;
14009
14281
  this.ParentBaseView = null;
14282
+ this._fields = [];
14283
+ this._fieldsLoaded = false;
14284
+ this._rawFields = null;
14010
14285
  this._fieldCategories = null;
14011
14286
  this._organicKeys = [];
14012
14287
  this._uniqueKeySets = [];
14013
14288
  this._alternateBaseViews = [];
14014
- this.HasIdField = false;
14015
- this.VirtualCount = 0;
14289
+ this._lazyHasIdField = void 0;
14290
+ this._lazyVirtualCount = void 0;
14016
14291
  this.ManyToManyCount = 0;
14017
14292
  this.OneToManyCount = 0;
14018
- this.FloatCount = 0;
14293
+ this._lazyFloatCount = void 0;
14019
14294
  this._fieldByNameMap = null;
14020
14295
  this._firstPrimaryKeyCache = void 0;
14021
14296
  this._primaryKeysCache = null;
@@ -14036,6 +14311,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14036
14311
  if (initData) {
14037
14312
  this.copyInitData(initData, _EntityInfo.CHILD_INIT_KEYS);
14038
14313
  this._fields = [];
14314
+ this._fieldsLoaded = false;
14039
14315
  this._fieldByNameMap = null;
14040
14316
  this._firstPrimaryKeyCache = void 0;
14041
14317
  this._primaryKeysCache = null;
@@ -14047,13 +14323,15 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14047
14323
  this._nameFieldCache = void 0;
14048
14324
  this._hasSearchFields = void 0;
14049
14325
  this._hasInactiveFields = void 0;
14326
+ this._lazyHasIdField = void 0;
14327
+ this._lazyVirtualCount = void 0;
14328
+ this._lazyFloatCount = void 0;
14050
14329
  const ef = initData.EntityFields || initData._Fields || initData.Fields;
14051
- if (ef) {
14052
- for (let j = 0; j < ef.length; j++) {
14053
- const field = new EntityFieldInfo(ef[j]);
14054
- field.SetOwningProvider(md);
14055
- this._fields.push(field);
14056
- }
14330
+ if (ef && ef.length > 0) {
14331
+ this._rawFields = ef;
14332
+ } else {
14333
+ this._rawFields = null;
14334
+ this._fieldsLoaded = true;
14057
14335
  }
14058
14336
  this._permissions = [];
14059
14337
  const ep = initData.EntityPermissions || initData._Permissions || initData.Permissions;
@@ -14119,29 +14397,16 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14119
14397
  });
14120
14398
  EntityAlternateBaseViewInfo.LinkHierarchy(this._alternateBaseViews, this.SchemaName);
14121
14399
  }
14122
- this.prepareSpecialFields();
14400
+ this.prepareRelationshipCounts();
14123
14401
  }
14124
14402
  }
14125
- prepareSpecialFields() {
14403
+ prepareRelationshipCounts() {
14126
14404
  try {
14127
- let virtualCount = 0;
14128
14405
  let manyToManyCount = 0;
14129
14406
  let oneToManyCount = 0;
14130
- let floatCount = 0;
14131
- let hasIdField = false;
14132
- for (let j = 0; j < this.Fields.length; ++j) {
14133
- const f = this.Fields[j];
14134
- if (f.Name.trim().toUpperCase() === "ID")
14135
- hasIdField = true;
14136
- virtualCount += f.IsVirtual ? 1 : 0;
14137
- floatCount += f.IsFloat ? 1 : 0;
14138
- }
14139
- this.HasIdField = hasIdField;
14140
- this.FloatCount = floatCount;
14141
- this.VirtualCount = virtualCount;
14142
14407
  for (let j = 0; j < this.RelatedEntities.length; ++j) {
14143
14408
  const r = this.RelatedEntities[j];
14144
- if (r.Type.trim().toUpperCase() === "ONE TO MANY")
14409
+ if (r.Type && r.Type.trim().toUpperCase() === "ONE TO MANY")
14145
14410
  oneToManyCount++;
14146
14411
  else
14147
14412
  manyToManyCount++;
@@ -14152,6 +14417,10 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14152
14417
  LogError(e);
14153
14418
  }
14154
14419
  }
14420
+ prepareSpecialFields() {
14421
+ this.prepareRelationshipCounts();
14422
+ this.EnsureFieldsLoaded();
14423
+ }
14155
14424
  /**
14156
14425
  * Parses FieldCategoryInfo from EntitySettings, with legacy FieldCategoryIcons fallback.
14157
14426
  * Called once during construction so the result is cached on _FieldCategories.
@@ -14251,6 +14520,9 @@ EntitySubtypeDriverBase = __decorate2([
14251
14520
 
14252
14521
  // ../../MJCore/dist/generic/baseEngineRegistry.js
14253
14522
  var BaseEngineRegistry = class _BaseEngineRegistry extends BaseSingleton {
14523
+ static {
14524
+ this.MAX_NAME_COLLISIONS = 1e3;
14525
+ }
14254
14526
  /**
14255
14527
  * Returns the singleton instance of BaseEngineRegistry
14256
14528
  */
@@ -14289,7 +14561,7 @@ var BaseEngineRegistry = class _BaseEngineRegistry extends BaseSingleton {
14289
14561
  * @param className - Optional class name override (uses constructor name by default)
14290
14562
  */
14291
14563
  RegisterEngine(engine, className) {
14292
- const name = className || engine.constructor.name;
14564
+ const name = className || this.registrationKeyFor(engine);
14293
14565
  const existingInfo = this._engines.get(name);
14294
14566
  if (existingInfo) {
14295
14567
  existingInfo.instance = engine;
@@ -14309,16 +14581,32 @@ var BaseEngineRegistry = class _BaseEngineRegistry extends BaseSingleton {
14309
14581
  });
14310
14582
  }
14311
14583
  }
14584
+ /**
14585
+ * The registry key for an engine: its class name, or `Name#2`, `Name#3`… when a different engine
14586
+ * class already holds that name. Minified builds rename classes to `e`, `t` and so on, so unrelated
14587
+ * engines share names there; without this they would overwrite each other's registration and drop
14588
+ * out of `FindCachedEntity` / `FindEnginesDeclaringEntity`. The same instance or class keeps its slot.
14589
+ */
14590
+ registrationKeyFor(engine) {
14591
+ const name = GetClassName(engine.constructor);
14592
+ for (let n = 1; n <= _BaseEngineRegistry.MAX_NAME_COLLISIONS; n++) {
14593
+ const key = n === 1 ? name : `${name}#${n}`;
14594
+ const holder = this._engines.get(key)?.instance;
14595
+ if (holder === void 0 || holder === engine || holder.constructor === engine.constructor) {
14596
+ return key;
14597
+ }
14598
+ }
14599
+ throw new Error(`BaseEngineRegistry: more than ${_BaseEngineRegistry.MAX_NAME_COLLISIONS} engine classes share the name '${name}'`);
14600
+ }
14312
14601
  /**
14313
14602
  * Unregister an engine from the registry
14314
14603
  *
14315
14604
  * @param engine - The engine instance to unregister
14316
14605
  */
14317
14606
  UnregisterEngine(engine) {
14318
- const name = engine.constructor.name;
14319
- this._engines.delete(name);
14607
+ const ctor = engine.constructor;
14320
14608
  for (const [k, v] of this._engines) {
14321
- if (v.instance === engine) {
14609
+ if (v.instance === engine || v.instance?.constructor === ctor) {
14322
14610
  this._engines.delete(k);
14323
14611
  }
14324
14612
  }
@@ -14356,7 +14644,7 @@ var BaseEngineRegistry = class _BaseEngineRegistry extends BaseSingleton {
14356
14644
  * @returns Memory statistics object
14357
14645
  */
14358
14646
  GetMemoryStats() {
14359
- for (const [name, info] of this._engines) {
14647
+ for (const info of this._engines.values()) {
14360
14648
  info.isLoaded = this.checkEngineLoaded(info.instance);
14361
14649
  info.estimatedMemoryBytes = this.estimateEngineMemory(info.instance);
14362
14650
  info.itemCount = this.countEngineItems(info.instance);
@@ -14398,7 +14686,7 @@ var BaseEngineRegistry = class _BaseEngineRegistry extends BaseSingleton {
14398
14686
  * @param engine - The engine that was loaded
14399
14687
  */
14400
14688
  NotifyEngineLoaded(engine) {
14401
- const name = engine.constructor.name;
14689
+ const name = this.registrationKeyFor(engine);
14402
14690
  const info = this._engines.get(name);
14403
14691
  if (info) {
14404
14692
  info.lastLoadedAt = /* @__PURE__ */ new Date();
@@ -14480,7 +14768,7 @@ var BaseEngineRegistry = class _BaseEngineRegistry extends BaseSingleton {
14480
14768
  if ("_dataMap" in engineObj) {
14481
14769
  const dataMap = engineObj._dataMap;
14482
14770
  if (dataMap && dataMap instanceof Map) {
14483
- for (const [key, value] of dataMap) {
14771
+ for (const value of dataMap.values()) {
14484
14772
  if (value && Array.isArray(value.data)) {
14485
14773
  totalBytes += this.estimateArraySize(value.data);
14486
14774
  }
@@ -14512,7 +14800,7 @@ var BaseEngineRegistry = class _BaseEngineRegistry extends BaseSingleton {
14512
14800
  if ("_dataMap" in engineObj) {
14513
14801
  const dataMap = engineObj._dataMap;
14514
14802
  if (dataMap && dataMap instanceof Map) {
14515
- for (const [key, value] of dataMap) {
14803
+ for (const value of dataMap.values()) {
14516
14804
  if (value && Array.isArray(value.data)) {
14517
14805
  totalItems += value.data.length;
14518
14806
  }
@@ -14644,7 +14932,7 @@ var BaseEngineRegistry = class _BaseEngineRegistry extends BaseSingleton {
14644
14932
  return;
14645
14933
  }
14646
14934
  this._recordedEngineInstances.add(engine);
14647
- const engineClassName = engine.constructor.name;
14935
+ const engineClassName = this.registrationKeyFor(engine);
14648
14936
  for (const entityName of entityNames) {
14649
14937
  this.RecordEntityLoad(engineClassName, entityName);
14650
14938
  }
@@ -15199,18 +15487,29 @@ var DEFAULT_SETTINGS = {
15199
15487
  }
15200
15488
  };
15201
15489
  var SENSITIVE_TELEMETRY_KEYS = /(?:token|password|secret|authorization|apikey|api_key|connectionstring|connection_string)/i;
15490
+ var SAFE_NUMERIC_TOKEN_KEYS = /* @__PURE__ */ new Set([
15491
+ "inputTokens",
15492
+ "outputTokens",
15493
+ "promptTokens",
15494
+ "completionTokens",
15495
+ "totalTokens",
15496
+ "cachedInputTokens"
15497
+ ]);
15202
15498
  function sanitizeTelemetryParams(params) {
15203
15499
  if (!params || typeof params !== "object") {
15204
15500
  return params;
15205
15501
  }
15206
15502
  let cloned = null;
15207
15503
  const record = params;
15208
- for (const key of Object.keys(record)) {
15209
- if (SENSITIVE_TELEMETRY_KEYS.test(key) && record[key] != null) {
15210
- if (!cloned) {
15211
- cloned = { ...record };
15504
+ for (const [key, val] of Object.entries(record)) {
15505
+ if (SENSITIVE_TELEMETRY_KEYS.test(key) && val !== void 0 && val !== null) {
15506
+ const isSafeNumericToken = SAFE_NUMERIC_TOKEN_KEYS.has(key) && typeof val === "number" && Number.isFinite(val);
15507
+ if (!isSafeNumericToken) {
15508
+ if (!cloned) {
15509
+ cloned = { ...record };
15510
+ }
15511
+ cloned[key] = "[REDACTED]";
15212
15512
  }
15213
- cloned[key] = "[REDACTED]";
15214
15513
  }
15215
15514
  }
15216
15515
  return cloned ?? params;
@@ -15218,12 +15517,29 @@ function sanitizeTelemetryParams(params) {
15218
15517
  var DEEP_TRIM_INTERVAL_MS = 6e4;
15219
15518
  var TelemetryManager = class _TelemetryManager extends BaseSingleton {
15220
15519
  /**
15221
- * Subscribe to completed telemetry events in real time (zero-polling flight recorder hook).
15222
- * @returns Unsubscribe function.
15520
+ * Subscribe to telemetry events as they start and complete (zero-polling flight recorder /
15521
+ * OpenTelemetry span-bridge hook).
15522
+ *
15523
+ * - **2-arg listeners** `(event, type) => ...`: receive balanced `'start'` and `'end'` notifications
15524
+ * from both `StartEvent`+`EndEvent` and `RecordEvent` (which fires both in immediate succession).
15525
+ * - **1-arg listeners** `(event) => ...`: fire **only once** on `'end'` (when `elapsedMs` is populated)
15526
+ * for both `StartEvent`+`EndEvent` and `RecordEvent`.
15527
+ * - Listeners can explicitly select phases by passing `{ Phases: ['start', 'end'] }` (or `['start']`, `['end']`).
15528
+ *
15529
+ * Exceptions thrown by `listener` are caught and swallowed — an observer must never disrupt
15530
+ * the producer it is observing. Notification is skipped entirely while diagnostic capture is
15531
+ * suppressed ({@link IsDiagnosticCaptureSuppressed}).
15532
+ *
15533
+ * @returns An idempotent unsubscribe function.
15223
15534
  */
15224
- OnEvent(listener) {
15225
- this._listeners.add(listener);
15535
+ OnEvent(listener, options) {
15536
+ const phases = options?.Phases ? new Set(options.Phases) : listener.length >= 2 ? /* @__PURE__ */ new Set(["start", "end"]) : /* @__PURE__ */ new Set(["end"]);
15537
+ this._listeners.set(listener, phases);
15538
+ let unsubscribed = false;
15226
15539
  return () => {
15540
+ if (unsubscribed)
15541
+ return;
15542
+ unsubscribed = true;
15227
15543
  this._listeners.delete(listener);
15228
15544
  };
15229
15545
  }
@@ -15237,13 +15553,16 @@ var TelemetryManager = class _TelemetryManager extends BaseSingleton {
15237
15553
  }
15238
15554
  return 0;
15239
15555
  }
15240
- notifyEventListeners(event) {
15556
+ notifyEventListeners(event, type) {
15241
15557
  if (this._listeners.size === 0 || IsDiagnosticCaptureSuppressed()) {
15242
15558
  return;
15243
15559
  }
15244
- for (const listener of this._listeners) {
15560
+ for (const [listener, phases] of this._listeners) {
15561
+ if (!phases.has(type)) {
15562
+ continue;
15563
+ }
15245
15564
  try {
15246
- listener(event);
15565
+ listener(event, type);
15247
15566
  } catch {
15248
15567
  }
15249
15568
  }
@@ -15262,7 +15581,7 @@ var TelemetryManager = class _TelemetryManager extends BaseSingleton {
15262
15581
  this._analyzers = [];
15263
15582
  this._insights = [];
15264
15583
  this._insightDedupeWindow = /* @__PURE__ */ new Map();
15265
- this._listeners = /* @__PURE__ */ new Set();
15584
+ this._listeners = /* @__PURE__ */ new Map();
15266
15585
  this._lastDeepTrimAt = 0;
15267
15586
  this._settings = this.loadSettings();
15268
15587
  this.registerBuiltInAnalyzers();
@@ -15345,10 +15664,17 @@ var TelemetryManager = class _TelemetryManager extends BaseSingleton {
15345
15664
  if (this._settings.autoTrim.enabled && maxActive > 0 && this._activeEvents.size >= maxActive) {
15346
15665
  const oldestKey = this._activeEvents.keys().next().value;
15347
15666
  if (oldestKey !== void 0) {
15667
+ const evicted = this._activeEvents.get(oldestKey);
15348
15668
  this._activeEvents.delete(oldestKey);
15669
+ if (evicted) {
15670
+ evicted.endTime = this.getTimestamp();
15671
+ evicted.elapsedMs = evicted.endTime - evicted.startTime;
15672
+ this.notifyEventListeners(evicted, "end");
15673
+ }
15349
15674
  }
15350
15675
  }
15351
15676
  this._activeEvents.set(event.id, event);
15677
+ this.notifyEventListeners(event, "start");
15352
15678
  return event.id;
15353
15679
  }
15354
15680
  /**
@@ -15381,7 +15707,7 @@ var TelemetryManager = class _TelemetryManager extends BaseSingleton {
15381
15707
  this.updatePattern(event);
15382
15708
  this.runAnalyzers(event);
15383
15709
  this.trimIfNeeded();
15384
- this.notifyEventListeners(event);
15710
+ this.notifyEventListeners(event, "end");
15385
15711
  return event;
15386
15712
  }
15387
15713
  /**
@@ -15414,7 +15740,8 @@ var TelemetryManager = class _TelemetryManager extends BaseSingleton {
15414
15740
  this.updatePattern(event);
15415
15741
  this.runAnalyzers(event);
15416
15742
  this.trimIfNeeded();
15417
- this.notifyEventListeners(event);
15743
+ this.notifyEventListeners(event, "start");
15744
+ this.notifyEventListeners(event, "end");
15418
15745
  }
15419
15746
  // ========== PATTERN DETECTION ==========
15420
15747
  updatePattern(event) {
@@ -16378,6 +16705,37 @@ function deniedReadFieldsFor(entityInfo, user) {
16378
16705
  const denied = entityInfo.GetDeniedReadFields(user);
16379
16706
  return denied.size > 0 ? denied : null;
16380
16707
  }
16708
+ function readableFieldNames(entityInfo, denied) {
16709
+ return entityInfo.Fields.filter((f) => !denied.has(f.Name.trim().toLowerCase())).map((f) => f.Name);
16710
+ }
16711
+ function narrowRow(row, denied, readable) {
16712
+ const narrowed = OmitDeniedFieldKeys(row, denied);
16713
+ if (!readable) {
16714
+ return narrowed;
16715
+ }
16716
+ const withMarker = narrowed === row ? { ...row } : narrowed;
16717
+ withMarker[ReadableFieldsTransportKey] = readable;
16718
+ return withMarker;
16719
+ }
16720
+ function ProjectEntityValueRowsForUser(provider, entityInfo, rows, user, options) {
16721
+ if (!rows?.length || !entityInfo || !user) {
16722
+ return rows;
16723
+ }
16724
+ const denied = deniedReadFieldsFor(entityInfo, user);
16725
+ const isRecordChanges = RecordChangeFieldSecurityProjector.IsRecordChangesEntity(entityInfo);
16726
+ if (!denied && !isRecordChanges) {
16727
+ return rows;
16728
+ }
16729
+ let projected = rows;
16730
+ if (denied) {
16731
+ const readable = options?.includeReadableFields ? readableFieldNames(entityInfo, denied) : null;
16732
+ projected = rows.map((row) => narrowRow(row, denied, readable));
16733
+ }
16734
+ if (isRecordChanges) {
16735
+ projected = new RecordChangeFieldSecurityProjector(provider, user).ProjectRows(projected);
16736
+ }
16737
+ return projected.some((row, i) => row !== rows[i]) ? projected : rows;
16738
+ }
16381
16739
  var ClientInputTransportKeys = [
16382
16740
  "OldValues___",
16383
16741
  ReadableFieldsTransportKey,
@@ -16437,7 +16795,10 @@ function AssertClientInputWritableForUser(entityInfo, values, user, options) {
16437
16795
  }
16438
16796
 
16439
16797
  // ../../MJCore/dist/generic/relatedRecordCollection.js
16440
- var RelatedRecordCollection = class extends EntityCompanion {
16798
+ var RelatedRecordCollection = class _RelatedRecordCollection extends EntityCompanion {
16799
+ static {
16800
+ this._donorJoinIndex = /* @__PURE__ */ new WeakMap();
16801
+ }
16441
16802
  /**
16442
16803
  * @param owner - The parent entity.
16443
16804
  * @param options - The collection declaration.
@@ -16866,10 +17227,10 @@ var RelatedRecordCollection = class extends EntityCompanion {
16866
17227
  }
16867
17228
  const joinField = this.RelatedEntityJoinField;
16868
17229
  const records = current;
16869
- const mine = records.filter((r) => UUIDsEqual(String(r.Get(joinField) ?? ""), String(parentKey)));
17230
+ const mine = this.filterAndSortCachedRecords(records, joinField, String(parentKey));
16870
17231
  this.cacheDonor.array = records;
16871
17232
  this.cacheDonor.length = records.length;
16872
- this.adoptEngineInstances(this.sortLikeOrderBy(mine));
17233
+ this.adoptEngineInstances(mine);
16873
17234
  }
16874
17235
  /**
16875
17236
  * Populates a `'lazy'` collection from cache, or throws explaining why it could not.
@@ -16972,8 +17333,44 @@ var RelatedRecordCollection = class extends EntityCompanion {
16972
17333
  };
16973
17334
  }
16974
17335
  const joinField = this.RelatedEntityJoinField;
16975
- const mine = donor.records.filter((r) => UUIDsEqual(String(r.Get(joinField) ?? ""), String(parentKey)));
16976
- return this.sortLikeOrderBy(mine);
17336
+ return this.filterAndSortCachedRecords(donor.records, joinField, String(parentKey));
17337
+ }
17338
+ /**
17339
+ * Looks up cached donor rows matching `joinField === parentKey` in O(1) using the
17340
+ * lazily built WeakMap index keyed by `(records array -> joinField -> NormalizeUUID(fk))`,
17341
+ * then returns a sorted defensive copy via {@link sortLikeOrderBy}.
17342
+ */
17343
+ filterAndSortCachedRecords(records, joinField, parentKey) {
17344
+ const recordCount = records.length;
17345
+ let cacheEntry = _RelatedRecordCollection._donorJoinIndex.get(records);
17346
+ const first = recordCount > 0 ? records[0] : void 0;
17347
+ const last = recordCount > 0 ? records[recordCount - 1] : void 0;
17348
+ if (!cacheEntry || cacheEntry.length !== recordCount || cacheEntry.first !== first || cacheEntry.last !== last) {
17349
+ cacheEntry = {
17350
+ length: recordCount,
17351
+ first,
17352
+ last,
17353
+ byJoinField: /* @__PURE__ */ new Map()
17354
+ };
17355
+ _RelatedRecordCollection._donorJoinIndex.set(records, cacheEntry);
17356
+ }
17357
+ let fieldBuckets = cacheEntry.byJoinField.get(joinField);
17358
+ if (!fieldBuckets) {
17359
+ fieldBuckets = /* @__PURE__ */ new Map();
17360
+ for (let i = 0; i < recordCount; i++) {
17361
+ const record = records[i];
17362
+ const normalizedKey = NormalizeUUID(String(record.Get(joinField) ?? ""));
17363
+ let bucket = fieldBuckets.get(normalizedKey);
17364
+ if (!bucket) {
17365
+ bucket = [];
17366
+ fieldBuckets.set(normalizedKey, bucket);
17367
+ }
17368
+ bucket.push(record);
17369
+ }
17370
+ cacheEntry.byJoinField.set(joinField, fieldBuckets);
17371
+ }
17372
+ const mine = fieldBuckets.get(NormalizeUUID(parentKey));
17373
+ return this.sortLikeOrderBy(mine ? mine.slice() : []);
16977
17374
  }
16978
17375
  /**
16979
17376
  * Applies the declared `OrderBy` to cache-sourced records.
@@ -17221,10 +17618,25 @@ var RelatedRecordCollection = class extends EntityCompanion {
17221
17618
  * @returns Rehydrated child entities.
17222
17619
  */
17223
17620
  async rehydrateItems(provider, rows, mode) {
17224
- const out = [];
17621
+ if (rows.length === 0) {
17622
+ return [];
17623
+ }
17624
+ const prepared = [];
17625
+ const existingTargets = [];
17225
17626
  for (const row of rows) {
17226
17627
  const entityName = row.EntityName || this.RelatedEntityName;
17227
17628
  const child = await provider.GetEntityObject(entityName, this.Owner.ContextCurrentUser);
17629
+ if (mode === "result" || row.IsNew) {
17630
+ prepared.push({ row, entityName, child, key: null });
17631
+ } else {
17632
+ const key = new CompositeKey(child.EntityInfo.PrimaryKeys.map((pk) => new KeyValuePair(pk.Name, row.Fields[pk.Name])));
17633
+ prepared.push({ row, entityName, child, key });
17634
+ existingTargets.push({ child, entityName, key, fieldsForKey: row.Fields });
17635
+ }
17636
+ }
17637
+ const { prefetchedRows, batchedChildren } = await this.prefetchExistingRows(provider, existingTargets);
17638
+ const out = [];
17639
+ for (const { row, entityName, child, key } of prepared) {
17228
17640
  if (mode === "result") {
17229
17641
  await child.LoadFromData(row.Fields, true);
17230
17642
  if (row.Companions && row.Companions.length > 0) {
@@ -17238,10 +17650,16 @@ var RelatedRecordCollection = class extends EntityCompanion {
17238
17650
  child.NewRecord();
17239
17651
  child.SetMany(row.Fields, true);
17240
17652
  } else {
17241
- const key = new CompositeKey(child.EntityInfo.PrimaryKeys.map((pk) => new KeyValuePair(pk.Name, row.Fields[pk.Name])));
17242
- const loaded = await child.InnerLoad(key);
17243
- if (!loaded) {
17653
+ const prefetched = prefetchedRows.get(child);
17654
+ if (prefetched) {
17655
+ await child.HydrateFromRow(prefetched, key);
17656
+ } else if (batchedChildren.has(child)) {
17244
17657
  throw new Error(`RelatedRecordCollection '${this.Name}': cannot load existing ${entityName} record ${key.ToString()} referenced by the incoming payload.`);
17658
+ } else {
17659
+ const loaded = await child.InnerLoad(key);
17660
+ if (!loaded) {
17661
+ throw new Error(`RelatedRecordCollection '${this.Name}': cannot load existing ${entityName} record ${key.ToString()} referenced by the incoming payload.`);
17662
+ }
17245
17663
  }
17246
17664
  child.SetMany(row.Fields, true);
17247
17665
  }
@@ -17264,17 +17682,133 @@ var RelatedRecordCollection = class extends EntityCompanion {
17264
17682
  * @returns Loaded child entities to delete.
17265
17683
  */
17266
17684
  async rehydrateRemovals(provider, rows) {
17267
- const out = [];
17685
+ if (rows.length === 0) {
17686
+ return [];
17687
+ }
17688
+ const targets = [];
17268
17689
  for (const row of rows) {
17269
17690
  const entityName = row["__entityName"] || this.RelatedEntityName;
17270
17691
  const child = await provider.GetEntityObject(entityName, this.Owner.ContextCurrentUser);
17271
17692
  const key = new CompositeKey(child.EntityInfo.PrimaryKeys.map((pk) => new KeyValuePair(pk.Name, row[pk.Name])));
17272
- if (await child.InnerLoad(key)) {
17273
- out.push(child);
17693
+ targets.push({ child, entityName, key, fieldsForKey: row });
17694
+ }
17695
+ const { prefetchedRows, batchedChildren } = await this.prefetchExistingRows(provider, targets);
17696
+ const out = [];
17697
+ for (const { child, key } of targets) {
17698
+ const prefetched = prefetchedRows.get(child);
17699
+ if (prefetched) {
17700
+ if (await child.HydrateFromRow(prefetched, key)) {
17701
+ out.push(child);
17702
+ }
17703
+ } else if (!batchedChildren.has(child)) {
17704
+ if (await child.InnerLoad(key)) {
17705
+ out.push(child);
17706
+ }
17274
17707
  }
17275
17708
  }
17276
17709
  return out;
17277
17710
  }
17711
+ /**
17712
+ * Batch-loads existing rows by primary key via chunked `RunView` queries so wire deserialization
17713
+ * of N edited/removed children costs O(1) queries per entity type instead of N serial `InnerLoad` calls.
17714
+ * Falls back per-entity whenever `RunView` is unavailable, a subclass overrides `InnerLoad`, or a
17715
+ * group has fewer than 2 eligible rows.
17716
+ */
17717
+ async prefetchExistingRows(provider, targets) {
17718
+ const prefetchedRows = /* @__PURE__ */ new Map();
17719
+ const batchedChildren = /* @__PURE__ */ new Set();
17720
+ if (targets.length < 2) {
17721
+ return { prefetchedRows, batchedChildren };
17722
+ }
17723
+ const rvProvider = provider;
17724
+ if (typeof rvProvider.RunView !== "function") {
17725
+ return { prefetchedRows, batchedChildren };
17726
+ }
17727
+ const byEntity = /* @__PURE__ */ new Map();
17728
+ for (const target of targets) {
17729
+ let list = byEntity.get(target.entityName);
17730
+ if (!list) {
17731
+ list = [];
17732
+ byEntity.set(target.entityName, list);
17733
+ }
17734
+ list.push(target);
17735
+ }
17736
+ for (const [entityName, group] of byEntity) {
17737
+ if (group.length < 2) {
17738
+ continue;
17739
+ }
17740
+ const pks = group[0].child.EntityInfo?.PrimaryKeys;
17741
+ if (!pks || pks.length === 0) {
17742
+ continue;
17743
+ }
17744
+ if (!group.every((t) => typeof t.child.HydrateFromRow === "function" && !hasCustomInnerLoadOverride(t.child) && t.key.Validate()?.IsValid === true)) {
17745
+ continue;
17746
+ }
17747
+ const predicates = [];
17748
+ let allFormattable = true;
17749
+ for (const target of group) {
17750
+ if (pks.length === 1) {
17751
+ const lit = formatPrimaryKeySQLValue(pks[0], target.fieldsForKey[pks[0].Name]);
17752
+ if (lit === null) {
17753
+ allFormattable = false;
17754
+ break;
17755
+ }
17756
+ predicates.push(lit);
17757
+ } else {
17758
+ const parts = [];
17759
+ for (const pk of pks) {
17760
+ const lit = formatPrimaryKeySQLValue(pk, target.fieldsForKey[pk.Name]);
17761
+ if (lit === null) {
17762
+ allFormattable = false;
17763
+ break;
17764
+ }
17765
+ parts.push(`[${pk.Name}]=${lit}`);
17766
+ }
17767
+ if (!allFormattable) {
17768
+ break;
17769
+ }
17770
+ predicates.push(`(${parts.join(" AND ")})`);
17771
+ }
17772
+ }
17773
+ if (!allFormattable) {
17774
+ continue;
17775
+ }
17776
+ const chunkSize = pks.length === 1 ? 200 : 100;
17777
+ const rowByLookupKey = /* @__PURE__ */ new Map();
17778
+ let batchSucceeded = true;
17779
+ for (let start = 0; start < group.length; start += chunkSize) {
17780
+ const slicePreds = predicates.slice(start, start + chunkSize);
17781
+ const extraFilter = pks.length === 1 ? `[${pks[0].Name}] IN (${slicePreds.join(",")})` : slicePreds.join(" OR ");
17782
+ const res = await rvProvider.RunView({
17783
+ EntityName: entityName,
17784
+ ExtraFilter: extraFilter,
17785
+ ResultType: "simple",
17786
+ BypassCache: true,
17787
+ SkipTotalRowCount: true,
17788
+ MaxRows: slicePreds.length,
17789
+ IgnoreMaxRows: true
17790
+ }, this.Owner.ContextCurrentUser);
17791
+ if (!res?.Success) {
17792
+ batchSucceeded = false;
17793
+ break;
17794
+ }
17795
+ for (const row of res.Results ?? []) {
17796
+ rowByLookupKey.set(normalizePrimaryKeyLookup(pks, row), row);
17797
+ }
17798
+ }
17799
+ if (!batchSucceeded) {
17800
+ continue;
17801
+ }
17802
+ for (const target of group) {
17803
+ batchedChildren.add(target.child);
17804
+ const match = rowByLookupKey.get(normalizePrimaryKeyLookup(pks, target.fieldsForKey));
17805
+ if (match) {
17806
+ prefetchedRows.set(target.child, match);
17807
+ }
17808
+ }
17809
+ }
17810
+ return { prefetchedRows, batchedChildren };
17811
+ }
17278
17812
  /**
17279
17813
  * Extracts just the primary-key fields of a child, for the `Removed` payload.
17280
17814
  *
@@ -17348,6 +17882,49 @@ var RelatedRecordCollection = class extends EntityCompanion {
17348
17882
  }
17349
17883
  }
17350
17884
  };
17885
+ function hasCustomInnerLoadOverride(entity) {
17886
+ if (Object.prototype.hasOwnProperty.call(entity, "InnerLoad")) {
17887
+ return true;
17888
+ }
17889
+ let proto = Object.getPrototypeOf(entity);
17890
+ while (proto && proto !== Object.prototype) {
17891
+ const parent = Object.getPrototypeOf(proto);
17892
+ if (Object.prototype.hasOwnProperty.call(proto, "InnerLoad") && parent !== null && "InnerLoad" in parent) {
17893
+ return true;
17894
+ }
17895
+ proto = parent;
17896
+ }
17897
+ return false;
17898
+ }
17899
+ function formatPrimaryKeySQLValue(pkField, value) {
17900
+ if (value === null || value === void 0) {
17901
+ return null;
17902
+ }
17903
+ if (!pkField.NeedsQuotes) {
17904
+ const trimmed = String(value).trim();
17905
+ return /^-?\d+(\.\d+)?$/.test(trimmed) ? trimmed : null;
17906
+ }
17907
+ return `'${EscapeSQLString(String(value))}'`;
17908
+ }
17909
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17910
+ function normalizePrimaryKeyLookup(pks, record) {
17911
+ if (pks.length === 1) {
17912
+ const raw = record[pks[0].Name];
17913
+ if (raw === null || raw === void 0) {
17914
+ return "";
17915
+ }
17916
+ const str = String(raw);
17917
+ return pks[0].IsUniqueIdentifier || UUID_PATTERN.test(str) ? NormalizeUUID(str) : str;
17918
+ }
17919
+ return pks.map((pk) => {
17920
+ const raw = record[pk.Name];
17921
+ if (raw === null || raw === void 0) {
17922
+ return "";
17923
+ }
17924
+ const str = String(raw);
17925
+ return pk.IsUniqueIdentifier || UUID_PATTERN.test(str) ? NormalizeUUID(str) : str;
17926
+ }).join("\0");
17927
+ }
17351
17928
 
17352
17929
  // ../../MJCore/dist/generic/embeddedRecord.js
17353
17930
  var EmbeddedRecord = class extends EntityCompanion {
@@ -17794,7 +18371,23 @@ async function ExecuteEntitySavePlan(plan, options = {}) {
17794
18371
  visited.add(rootKey);
17795
18372
  }
17796
18373
  try {
17797
- for (const node of plan.Nodes) {
18374
+ let idx = 0;
18375
+ while (idx < plan.Nodes.length) {
18376
+ const batchRun = collectContiguousLeafBatch(plan.Nodes, idx, options, visited);
18377
+ if (batchRun) {
18378
+ const batchOutcome = await executeLeafBatch(batchRun.nodes, batchRun.provider, options, visited);
18379
+ nodeResults.push(...batchOutcome.results);
18380
+ if (!batchOutcome.success) {
18381
+ return {
18382
+ Success: false,
18383
+ NodeResults: nodeResults,
18384
+ ErrorMessage: batchOutcome.errorMessage
18385
+ };
18386
+ }
18387
+ idx += batchRun.nodes.length;
18388
+ continue;
18389
+ }
18390
+ const node = plan.Nodes[idx];
17798
18391
  if (!node.SelfOnly) {
17799
18392
  const key = GraphNodeKey(node.Entity);
17800
18393
  if (key && visited.has(key)) {
@@ -17811,6 +18404,7 @@ async function ExecuteEntitySavePlan(plan, options = {}) {
17811
18404
  if (!outcome.Success) {
17812
18405
  return { Success: false, NodeResults: nodeResults, ErrorMessage: outcome.ErrorMessage };
17813
18406
  }
18407
+ idx++;
17814
18408
  }
17815
18409
  return { Success: true, NodeResults: nodeResults };
17816
18410
  } finally {
@@ -17819,6 +18413,125 @@ async function ExecuteEntitySavePlan(plan, options = {}) {
17819
18413
  }
17820
18414
  }
17821
18415
  }
18416
+ function getBatchableProvider(entity) {
18417
+ const provider = entity.ProviderToUse;
18418
+ if (!provider || typeof provider.CreateTransactionGroup !== "function") {
18419
+ return null;
18420
+ }
18421
+ return provider;
18422
+ }
18423
+ function isBatchEligibleLeafNode(node, expectedProvider, options, visited, batchKeys) {
18424
+ if (node.SelfOnly) {
18425
+ return null;
18426
+ }
18427
+ const entity = node.Entity;
18428
+ if (!entity || entity.HasCompanions || entity.TransactionGroup) {
18429
+ return null;
18430
+ }
18431
+ if (entity.EntityInfo?.IsParentType || entity.EntityInfo?.IsChildType) {
18432
+ return null;
18433
+ }
18434
+ if (options.CanBatchLeaf && !options.CanBatchLeaf(entity, node.Operation)) {
18435
+ return null;
18436
+ }
18437
+ const provider = getBatchableProvider(entity);
18438
+ if (!provider || expectedProvider !== null && provider !== expectedProvider) {
18439
+ return null;
18440
+ }
18441
+ const key = GraphNodeKey(entity);
18442
+ if (key && (visited.has(key) || batchKeys.has(key))) {
18443
+ return null;
18444
+ }
18445
+ return provider;
18446
+ }
18447
+ function collectContiguousLeafBatch(nodes, startIndex, options, visited) {
18448
+ const batchKeys = /* @__PURE__ */ new Set();
18449
+ const firstNode = nodes[startIndex];
18450
+ const provider = isBatchEligibleLeafNode(firstNode, null, options, visited, batchKeys);
18451
+ if (!provider) {
18452
+ return null;
18453
+ }
18454
+ const firstKey = GraphNodeKey(firstNode.Entity);
18455
+ if (firstKey) {
18456
+ batchKeys.add(firstKey);
18457
+ }
18458
+ const collected = [firstNode];
18459
+ for (let i = startIndex + 1; i < nodes.length; i++) {
18460
+ const candidate = nodes[i];
18461
+ if (!isBatchEligibleLeafNode(candidate, provider, options, visited, batchKeys)) {
18462
+ break;
18463
+ }
18464
+ const candidateKey = GraphNodeKey(candidate.Entity);
18465
+ if (candidateKey) {
18466
+ batchKeys.add(candidateKey);
18467
+ }
18468
+ collected.push(candidate);
18469
+ }
18470
+ return collected.length >= 2 ? { nodes: collected, provider } : null;
18471
+ }
18472
+ async function executeLeafBatch(nodes, provider, options, visited) {
18473
+ const tg = await provider.CreateTransactionGroup();
18474
+ tg.BatchedSubmit = true;
18475
+ const attached = [];
18476
+ const results = [];
18477
+ const initialResultCounts = [];
18478
+ try {
18479
+ for (const node of nodes) {
18480
+ if (node.Prepare) {
18481
+ node.Prepare();
18482
+ }
18483
+ initialResultCounts.push(node.Entity.ResultHistory?.length ?? 0);
18484
+ attached.push({ entity: node.Entity, previousGroup: node.Entity.TransactionGroup ?? null });
18485
+ node.Entity.TransactionGroup = tg;
18486
+ const outcome = await executePlanNode(node, { ...options, Visited: visited });
18487
+ if (!outcome.Success) {
18488
+ results.push(outcome);
18489
+ return { success: false, results, errorMessage: outcome.ErrorMessage };
18490
+ }
18491
+ }
18492
+ const committed = await tg.Submit();
18493
+ if (committed) {
18494
+ for (const node of nodes) {
18495
+ results.push({ Node: node, Success: true });
18496
+ }
18497
+ return { success: true, results };
18498
+ }
18499
+ let firstFailureMessage;
18500
+ for (let i = 0; i < nodes.length; i++) {
18501
+ const node = nodes[i];
18502
+ const history = node.Entity.ResultHistory;
18503
+ const latest = node.Entity.LatestResult;
18504
+ const failed = Boolean(history && history.length > initialResultCounts[i] && latest && !latest.Success);
18505
+ if (failed) {
18506
+ const detail = latest?.CompleteMessage ?? "batch transaction failed";
18507
+ const errorMessage = `${node.Operation} failed for ${node.Label} (${node.Entity.EntityInfo?.Name}): ${detail}`;
18508
+ if (!firstFailureMessage) {
18509
+ firstFailureMessage = errorMessage;
18510
+ }
18511
+ results.push({ Node: node, Success: false, ErrorMessage: errorMessage });
18512
+ } else {
18513
+ results.push({ Node: node, Success: false, ErrorMessage: firstFailureMessage ?? "Transaction batch rolled back" });
18514
+ }
18515
+ }
18516
+ if (!firstFailureMessage) {
18517
+ const firstNode = nodes[0];
18518
+ firstFailureMessage = `${firstNode.Operation} failed for ${firstNode.Label} (${firstNode.Entity.EntityInfo?.Name}): Transaction batch failed`;
18519
+ }
18520
+ return { success: false, results, errorMessage: firstFailureMessage };
18521
+ } catch (e) {
18522
+ const detail = e instanceof Error ? e.message : String(e);
18523
+ LogError(`EntitySavePlan batch failed: ${detail}`);
18524
+ const firstNode = nodes[0];
18525
+ const errorMessage = `${firstNode.Operation} threw during batch for ${firstNode.Label} (${firstNode.Entity.EntityInfo?.Name}): ${detail}`;
18526
+ results.push({ Node: firstNode, Success: false, ErrorMessage: errorMessage });
18527
+ return { success: false, results, errorMessage };
18528
+ } finally {
18529
+ for (let i = attached.length - 1; i >= 0; i--) {
18530
+ attached[i].entity.TransactionGroup = attached[i].previousGroup;
18531
+ }
18532
+ CrossEntityPolicyEngine.Instance.ClearTransactionGroupScope(tg);
18533
+ }
18534
+ }
17822
18535
  async function executePlanNode(node, options) {
17823
18536
  try {
17824
18537
  const ok = node.Operation === "Save" ? await executeSaveNode(node, options) : await executeDeleteNode(node, options);
@@ -18301,6 +19014,24 @@ var BaseRemotableOperation = class _BaseRemotableOperation {
18301
19014
  get GrantsServerWriteAuthority() {
18302
19015
  return true;
18303
19016
  }
19017
+ /**
19018
+ * When `true`, {@link ExecuteRemoteOperationResolver} refuses scoped/anonymous Magic Link
19019
+ * sessions (`IsMagicLinkAnonymous || MagicLinkScope`) before invoking this operation.
19020
+ * Defaults to `false` so Open Apps visitor operations can execute over scoped Magic Links;
19021
+ * artifact and other high-privilege operations override this to `true`.
19022
+ */
19023
+ get DisallowMagicLinkScope() {
19024
+ return false;
19025
+ }
19026
+ /**
19027
+ * Returns the resource identifiers checked against API-key scope authorization when
19028
+ * {@link RequiredScope} is set (default: `[this.OperationKey]`). Operations that target
19029
+ * specific resources (artifacts, collections, etc.) override this to declare all authoritative
19030
+ * scope resource IDs from the validated input rather than relying on heuristic field guessing.
19031
+ */
19032
+ GetScopeResourceIds(_input, _context) {
19033
+ return [this.OperationKey];
19034
+ }
18304
19035
  /**
18305
19036
  * Discovers all ClassFactory-registered {@link BaseRemotableOperation} subclasses that opt into
18306
19037
  * AI Agent (`ExposeAsAgentTool`) and/or MCP (`ExposeAsMCPTool`) tool exposure.
@@ -21403,7 +22134,8 @@ var BaseEntity = class _BaseEntity {
21403
22134
  DeleteOptions: childDeleteOptions,
21404
22135
  Visited: visited,
21405
22136
  SaveSelfOnly: (entity, opts) => entity.saveAsGraphNode(opts),
21406
- DeleteSelfOnly: (entity, opts) => entity.deleteAsGraphNode(opts)
22137
+ DeleteSelfOnly: (entity, opts) => entity.deleteAsGraphNode(opts),
22138
+ CanBatchLeaf: (entity, op) => op === "Save" ? entity.Save === _BaseEntity.prototype.Save : entity.Delete === _BaseEntity.prototype.Delete
21407
22139
  });
21408
22140
  if (!result.Success) {
21409
22141
  await scope?.Rollback();
@@ -23940,7 +24672,7 @@ var BaseEntity = class _BaseEntity {
23940
24672
  if (!this.IsSaved) {
23941
24673
  this.init();
23942
24674
  }
23943
- let data = await this.readRowForLoad(CompositeKey2, EntityRelationshipsToLoad);
24675
+ const data = await this.readRowForLoad(CompositeKey2, EntityRelationshipsToLoad);
23944
24676
  this.discardJSONFieldObjects();
23945
24677
  if (!data) {
23946
24678
  if (!this._subtypeHintProbe) {
@@ -23948,34 +24680,64 @@ var BaseEntity = class _BaseEntity {
23948
24680
  }
23949
24681
  return false;
23950
24682
  }
23951
- data = this.narrowHydrationSource(data);
23952
- if (this._parentEntity && !this._skipParentChainHydration) {
23953
- this._parentEntity.Hydrate(data);
23954
- }
23955
- for (const f of this.Fields) {
23956
- f.ResetNeverSetFlag();
23957
- }
23958
- this.SetMany(data, false, true, true);
23959
- this.markFieldsOmittedBySourceAsNotLoaded(data);
23960
- if (EntityRelationshipsToLoad) {
23961
- for (let relationship of EntityRelationshipsToLoad) {
23962
- if (data[relationship]) {
23963
- this[relationship] = data[relationship];
23964
- }
23965
- }
24683
+ return await this.applyLoadedRowData(data, CompositeKey2, EntityRelationshipsToLoad);
24684
+ } finally {
24685
+ this._isLoading = false;
24686
+ }
24687
+ }
24688
+ /**
24689
+ * Hydrates this entity from an already-fetched database row using the exact same permission,
24690
+ * FLS-narrowing, IS-A parent/child, and eager-companion contract as {@link InnerLoad}.
24691
+ * Used by batched loaders (e.g. `RelatedRecordCollection.Deserialize`) to avoid N individual queries.
24692
+ */
24693
+ async HydrateFromRow(data, compositeKey, entityRelationshipsToLoad = null) {
24694
+ if (!this.ProviderToUse) {
24695
+ throw new Error("No provider set");
24696
+ }
24697
+ const valResult = compositeKey.Validate();
24698
+ if (!valResult || !valResult.IsValid) {
24699
+ throw new Error(`Invalid CompositeKey passed to BaseEntity.HydrateFromRow(${this.EntityInfo.Name}): ${valResult.ErrorMessage}`);
24700
+ }
24701
+ this.CheckPermissions(EntityPermissionType.Read, true);
24702
+ this._isLoading = true;
24703
+ this.RaiseEvent("load_started", { CompositeKey: compositeKey });
24704
+ try {
24705
+ if (!this.IsSaved) {
24706
+ this.init();
23966
24707
  }
23967
- this._recordLoaded = true;
23968
- this._everSaved = true;
23969
- this._compositeKey = CompositeKey2;
23970
- this.cacheRecordName();
23971
- await this.InitializeChildEntity();
23972
- await this.loadEagerCompanions();
23973
- this.RaiseEvent("load_complete", { CompositeKey: CompositeKey2 });
23974
- return true;
24708
+ this.discardJSONFieldObjects();
24709
+ return await this.applyLoadedRowData(data, compositeKey, entityRelationshipsToLoad);
23975
24710
  } finally {
23976
24711
  this._isLoading = false;
23977
24712
  }
23978
24713
  }
24714
+ /** Shared post-read hydration used by both {@link InnerLoad} and {@link HydrateFromRow}. */
24715
+ async applyLoadedRowData(rawData, compositeKey, entityRelationshipsToLoad = null) {
24716
+ const data = this.narrowHydrationSource(rawData);
24717
+ if (this._parentEntity && !this._skipParentChainHydration) {
24718
+ this._parentEntity.Hydrate(data);
24719
+ }
24720
+ for (const f of this.Fields) {
24721
+ f.ResetNeverSetFlag();
24722
+ }
24723
+ this.SetMany(data, false, true, true);
24724
+ this.markFieldsOmittedBySourceAsNotLoaded(data);
24725
+ if (entityRelationshipsToLoad) {
24726
+ for (const relationship of entityRelationshipsToLoad) {
24727
+ if (data[relationship]) {
24728
+ this[relationship] = data[relationship];
24729
+ }
24730
+ }
24731
+ }
24732
+ this._recordLoaded = true;
24733
+ this._everSaved = true;
24734
+ this._compositeKey = compositeKey;
24735
+ this.cacheRecordName();
24736
+ await this.InitializeChildEntity();
24737
+ await this.loadEagerCompanions();
24738
+ this.RaiseEvent("load_complete", { CompositeKey: compositeKey });
24739
+ return true;
24740
+ }
23979
24741
  /**
23980
24742
  * The provider's read of the row {@link InnerLoad} loads. While this record is a subtype-hint
23981
24743
  * probe, a throw from the read is recorded on the probe before it propagates, so the parent
@@ -26010,6 +26772,14 @@ var BaseEntity = class _BaseEntity {
26010
26772
  };
26011
26773
 
26012
26774
  // ../../MJCore/dist/generic/runQuery.js
26775
+ var SERVER_ONLY_RUN_QUERY_PARAMS = ["TimeZone", "ServerParameters", "RequireApproved"];
26776
+ function StripServerOnlyRunQueryParams(params) {
26777
+ const copy = { ...params };
26778
+ for (const key of SERVER_ONLY_RUN_QUERY_PARAMS) {
26779
+ delete copy[key];
26780
+ }
26781
+ return copy;
26782
+ }
26013
26783
  var RunQuery = class _RunQuery {
26014
26784
  /**
26015
26785
  * Optionally, you can pass in a provider to use for running the query. If not provided, the static provider will be used.
@@ -26090,6 +26860,62 @@ var RunQuery = class _RunQuery {
26090
26860
  }
26091
26861
  };
26092
26862
 
26863
+ // ../../MJCore/dist/generic/InMemoryLocalStorageProvider.js
26864
+ var InMemoryLocalStorageProvider = class _InMemoryLocalStorageProvider {
26865
+ constructor() {
26866
+ this._storage = /* @__PURE__ */ new Map();
26867
+ this.SharesReferences = true;
26868
+ this.SupportsCrossProcessPersistence = false;
26869
+ }
26870
+ static {
26871
+ this.DEFAULT_CATEGORY = "default";
26872
+ }
26873
+ /**
26874
+ * Gets or creates a category map
26875
+ */
26876
+ getCategoryMap(category) {
26877
+ const cat = category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY;
26878
+ let categoryMap = this._storage.get(cat);
26879
+ if (!categoryMap) {
26880
+ categoryMap = /* @__PURE__ */ new Map();
26881
+ this._storage.set(cat, categoryMap);
26882
+ }
26883
+ return categoryMap;
26884
+ }
26885
+ async GetItem(key, category) {
26886
+ const categoryMap = this.getCategoryMap(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
26887
+ const value = categoryMap.get(key);
26888
+ return value === void 0 ? null : value;
26889
+ }
26890
+ async GetItems(keys, category) {
26891
+ const out = /* @__PURE__ */ new Map();
26892
+ if (keys.length === 0)
26893
+ return out;
26894
+ const categoryMap = this.getCategoryMap(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
26895
+ for (const key of new Set(keys)) {
26896
+ const value = categoryMap.get(key);
26897
+ out.set(key, value === void 0 ? null : value);
26898
+ }
26899
+ return out;
26900
+ }
26901
+ async SetItem(key, value, category) {
26902
+ const categoryMap = this.getCategoryMap(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
26903
+ categoryMap.set(key, value);
26904
+ }
26905
+ async Remove(key, category) {
26906
+ const categoryMap = this.getCategoryMap(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
26907
+ categoryMap.delete(key);
26908
+ }
26909
+ async ClearCategory(category) {
26910
+ const cat = category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY;
26911
+ this._storage.delete(cat);
26912
+ }
26913
+ async GetCategoryKeys(category) {
26914
+ const categoryMap = this._storage.get(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
26915
+ return categoryMap ? Array.from(categoryMap.keys()) : [];
26916
+ }
26917
+ };
26918
+
26093
26919
  // ../../MJCore/dist/generic/entityEventBatch.js
26094
26920
  var MAX_BUFFERED_ENTITY_CHANGES = 2e4;
26095
26921
  var EntityEventBatch = class {
@@ -26308,6 +27134,7 @@ function markResultsFullyFrozen(payload) {
26308
27134
  fullyFrozenResultArrays.add(payload.results);
26309
27135
  }
26310
27136
  }
27137
+ var cachedResultPkIndexes = /* @__PURE__ */ new WeakMap();
26311
27138
  var EVICTION_THRASH_FLOOR_PERCENT = 10;
26312
27139
  var SINGLE_ENTRY_RESERVE_PERCENT = 25;
26313
27140
  var HARD_MAX_ENTRY_PERCENT = 100 - EVICTION_THRASH_FLOOR_PERCENT;
@@ -26399,7 +27226,8 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
26399
27226
  this.UpdateConfig(config);
26400
27227
  }) : this._initializePromise;
26401
27228
  }
26402
- this._initializePromise = this.doInitialize(storageProvider, config);
27229
+ const effectiveProvider = storageProvider ?? this._storageProvider ?? new InMemoryLocalStorageProvider();
27230
+ this._initializePromise = this.doInitialize(effectiveProvider, config);
26403
27231
  return this._initializePromise;
26404
27232
  }
26405
27233
  /**
@@ -26970,6 +27798,22 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
26970
27798
  }
26971
27799
  return max === Number.NEGATIVE_INFINITY ? "" : new Date(max).toISOString();
26972
27800
  }
27801
+ /**
27802
+ * Resolves the primary key field names for a given entity name against the provided or default metadata provider.
27803
+ */
27804
+ resolveEntityPrimaryKeyFields(entityName, provider) {
27805
+ if (!entityName)
27806
+ return void 0;
27807
+ try {
27808
+ const md = provider ?? new Metadata();
27809
+ const entity = md.EntityByName(entityName);
27810
+ if (entity?.PrimaryKeys && entity.PrimaryKeys.length > 0) {
27811
+ return entity.PrimaryKeys.map((pk) => pk.Name);
27812
+ }
27813
+ } catch {
27814
+ }
27815
+ return void 0;
27816
+ }
26973
27817
  /**
26974
27818
  * Storage write options for a RunView slot: the entity name as index group, so a shared
26975
27819
  * provider can find the slot from any process, and the time left before the slot's own expiry
@@ -26977,8 +27821,10 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
26977
27821
  *
26978
27822
  * @param fingerprint - The slot key
26979
27823
  * @param expiresAt - Absolute expiry (ms since epoch), when the slot has one
27824
+ * @param pubSubOverride - Compact row-delta payload and action when broadcasting row updates
27825
+ * @param primaryKeyFields - Ordered primary-key field names for the entity
26980
27826
  */
26981
- runViewWriteOptions(fingerprint, expiresAt, pubSubOverride) {
27827
+ runViewWriteOptions(fingerprint, expiresAt, pubSubOverride, primaryKeyFields) {
26982
27828
  const options = {};
26983
27829
  const entity = this.extractEntityFromFingerprint(fingerprint);
26984
27830
  if (entity) {
@@ -26991,6 +27837,9 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
26991
27837
  options.pubSubAction = pubSubOverride.pubSubAction;
26992
27838
  options.pubSubData = pubSubOverride.pubSubData;
26993
27839
  }
27840
+ if (primaryKeyFields && primaryKeyFields.length > 0) {
27841
+ options.PrimaryKeyFields = primaryKeyFields;
27842
+ }
26994
27843
  return options;
26995
27844
  }
26996
27845
  /** Storage write options for any registry entry; only RunView slots are indexed. */
@@ -28539,7 +29388,8 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
28539
29388
  try {
28540
29389
  const writeNow = Date.now();
28541
29390
  const expiresAt = ttlMs ? writeNow + ttlMs : void 0;
28542
- await this._storageProvider.SetItem(fingerprint, data, CacheCategory.RunViewCache, this.runViewWriteOptions(fingerprint, expiresAt));
29391
+ const primaryKeyFields = this.resolveEntityPrimaryKeyFields(params.EntityName, provider);
29392
+ await this._storageProvider.SetItem(fingerprint, data, CacheCategory.RunViewCache, this.runViewWriteOptions(fingerprint, expiresAt, void 0, primaryKeyFields));
28543
29393
  this._lastVerifiedAt.set(fingerprint, writeNow);
28544
29394
  this.registerEntry({
28545
29395
  key: fingerprint,
@@ -28929,72 +29779,138 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
28929
29779
  return false;
28930
29780
  }
28931
29781
  const pkFieldNames = changes[0].Key.KeyValuePairs.map((kv) => kv.FieldName);
28932
- const resultMap = this.indexRowsByKey(cached.results, pkFieldNames);
28933
- const deltaChanges = this.applyChangesToRowMap(resultMap, changes);
28934
- if (!deltaChanges.changed) {
29782
+ const pkSignature = pkFieldNames.join("");
29783
+ let pkIndex = cachedResultPkIndexes.get(cached.results);
29784
+ if (!pkIndex || pkIndex.PkSignature !== pkSignature) {
29785
+ const indexByKey = /* @__PURE__ */ new Map();
29786
+ const nullPkIndices = [];
29787
+ for (let i = 0; i < cached.results.length; i++) {
29788
+ const rowObj = cached.results[i];
29789
+ if (pkFieldNames.some((fn) => rowObj[fn] == null)) {
29790
+ nullPkIndices.push(i);
29791
+ continue;
29792
+ }
29793
+ indexByKey.set(this.cheapRowKey(rowObj, pkFieldNames), i);
29794
+ }
29795
+ pkIndex = { PkSignature: pkSignature, IndexByKey: indexByKey, NullPkIndices: nullPkIndices };
29796
+ cachedResultPkIndexes.set(cached.results, pkIndex);
29797
+ }
29798
+ let changed = false;
29799
+ let displacedMaxTimestamp = pkIndex.NullPkIndices.length > 0;
29800
+ const upsertsByKey = /* @__PURE__ */ new Map();
29801
+ const deletesByKey = /* @__PURE__ */ new Map();
29802
+ const deletedOriginalIndices = new Set(pkIndex.NullPkIndices);
29803
+ const updatedRowByIndex = /* @__PURE__ */ new Map();
29804
+ for (const change of changes) {
29805
+ const keyStr = this.cheapKeyFromCompositeKey(change.Key);
29806
+ const existingIdx = pkIndex.IndexByKey.get(keyStr);
29807
+ const oldRow = existingIdx !== void 0 ? cached.results[existingIdx] : void 0;
29808
+ if (change.Row) {
29809
+ const rowObj = change.Row;
29810
+ if (oldRow && cached.maxUpdatedAt && oldRow.__mj_UpdatedAt === cached.maxUpdatedAt) {
29811
+ displacedMaxTimestamp = true;
29812
+ }
29813
+ upsertsByKey.set(keyStr, rowObj);
29814
+ deletesByKey.delete(keyStr);
29815
+ if (existingIdx !== void 0 && !deletedOriginalIndices.has(existingIdx)) {
29816
+ updatedRowByIndex.set(existingIdx, rowObj);
29817
+ }
29818
+ changed = true;
29819
+ } else {
29820
+ let wasPresent = false;
29821
+ if (upsertsByKey.has(keyStr)) {
29822
+ upsertsByKey.delete(keyStr);
29823
+ wasPresent = true;
29824
+ }
29825
+ if (existingIdx !== void 0 && !deletedOriginalIndices.has(existingIdx)) {
29826
+ deletedOriginalIndices.add(existingIdx);
29827
+ updatedRowByIndex.delete(existingIdx);
29828
+ wasPresent = true;
29829
+ }
29830
+ if (wasPresent) {
29831
+ if (oldRow && cached.maxUpdatedAt && oldRow.__mj_UpdatedAt === cached.maxUpdatedAt) {
29832
+ displacedMaxTimestamp = true;
29833
+ }
29834
+ if (existingIdx !== void 0) {
29835
+ const pkRecord = {};
29836
+ for (const kv of change.Key.KeyValuePairs) {
29837
+ const v = kv.Value;
29838
+ pkRecord[kv.FieldName] = typeof v === "string" || typeof v === "number" || typeof v === "boolean" || v === null ? v : String(v);
29839
+ }
29840
+ deletesByKey.set(keyStr, pkRecord);
29841
+ }
29842
+ changed = true;
29843
+ }
29844
+ }
29845
+ }
29846
+ if (!changed) {
28935
29847
  return true;
28936
29848
  }
28937
- return await this.storeCachedResults(fingerprint, Array.from(resultMap.values()), newMaxUpdatedAt, {
29849
+ let nextResults;
29850
+ let nextIndexByKey;
29851
+ if (deletedOriginalIndices.size === 0) {
29852
+ nextResults = cached.results.slice();
29853
+ nextIndexByKey = new Map(pkIndex.IndexByKey);
29854
+ for (const [keyStr, rowObj] of upsertsByKey) {
29855
+ const existingIdx = nextIndexByKey.get(keyStr);
29856
+ if (existingIdx !== void 0) {
29857
+ nextResults[existingIdx] = rowObj;
29858
+ } else {
29859
+ const newIdx = nextResults.length;
29860
+ nextResults.push(rowObj);
29861
+ nextIndexByKey.set(keyStr, newIdx);
29862
+ }
29863
+ }
29864
+ } else {
29865
+ nextResults = [];
29866
+ nextIndexByKey = /* @__PURE__ */ new Map();
29867
+ const indexMap = new Int32Array(cached.results.length);
29868
+ let nextIdx = 0;
29869
+ for (let i = 0; i < cached.results.length; i++) {
29870
+ if (deletedOriginalIndices.has(i)) {
29871
+ indexMap[i] = -1;
29872
+ } else {
29873
+ indexMap[i] = nextIdx++;
29874
+ const updated = updatedRowByIndex.get(i);
29875
+ nextResults.push(updated ?? cached.results[i]);
29876
+ }
29877
+ }
29878
+ for (const [k, oldIdx] of pkIndex.IndexByKey) {
29879
+ const newIdx = indexMap[oldIdx];
29880
+ if (newIdx !== -1) {
29881
+ nextIndexByKey.set(k, newIdx);
29882
+ }
29883
+ }
29884
+ for (const [keyStr, rowObj] of upsertsByKey) {
29885
+ if (!nextIndexByKey.has(keyStr)) {
29886
+ const newIdx = nextResults.length;
29887
+ nextResults.push(rowObj);
29888
+ nextIndexByKey.set(keyStr, newIdx);
29889
+ }
29890
+ }
29891
+ }
29892
+ cachedResultPkIndexes.set(nextResults, { PkSignature: pkSignature, IndexByKey: nextIndexByKey, NullPkIndices: [] });
29893
+ const upsertedRows = Array.from(upsertsByKey.values());
29894
+ const deletedPrimaryKeys = Array.from(deletesByKey.values());
29895
+ return await this.storeCachedResults(fingerprint, nextResults, newMaxUpdatedAt, {
28938
29896
  totalRowCount: cached.totalRowCount,
28939
29897
  rowCount: cached.results.length,
28940
29898
  schemaHash: cached.schemaHash,
28941
29899
  schemaStamp: cached.schemaStamp,
28942
- providerInternalScaffolding: cached.providerInternalScaffolding
29900
+ providerInternalScaffolding: cached.providerInternalScaffolding,
29901
+ priorMaxUpdatedAt: cached.maxUpdatedAt,
29902
+ displacedMaxTimestamp
28943
29903
  }, cached.providerInternalScaffolding ? void 0 : {
28944
- upsertedRows: deltaChanges.upsertedRows,
28945
- deletedPrimaryKeys: deltaChanges.deletedPrimaryKeys,
29904
+ upsertedRows,
29905
+ deletedPrimaryKeys,
28946
29906
  primaryKeyFields: pkFieldNames
28947
- }, { priorResults: cached.results, changedRows: deltaChanges.upsertedRows });
29907
+ }, { priorResults: cached.results, changedRows: upsertedRows });
28948
29908
  } catch (e) {
28949
29909
  LogError(`LocalCacheManager.ApplyRowChanges failed: ${e}`);
28950
29910
  return false;
28951
29911
  }
28952
29912
  });
28953
29913
  }
28954
- /**
28955
- * Rows keyed by a cheap delimiter-joined PK string (no per-row CompositeKey/KeyValuePair
28956
- * allocation); matching is consistent because {@link cheapKeyFromCompositeKey} uses the same
28957
- * format. Rows missing a PK value are dropped.
28958
- */
28959
- indexRowsByKey(rows, pkFieldNames) {
28960
- const resultMap = /* @__PURE__ */ new Map();
28961
- for (const row of rows) {
28962
- const rowObj = row;
28963
- if (pkFieldNames.some((fn) => rowObj[fn] == null))
28964
- continue;
28965
- resultMap.set(this.cheapRowKey(rowObj, pkFieldNames), row);
28966
- }
28967
- return resultMap;
28968
- }
28969
- /** Applies `changes` to `rows` in order and collects the collapsed net row delta for pub/sub. */
28970
- applyChangesToRowMap(rows, changes) {
28971
- let changed = false;
28972
- const upsertsByKey = /* @__PURE__ */ new Map();
28973
- const deletesByKey = /* @__PURE__ */ new Map();
28974
- for (const change of changes) {
28975
- const keyStr = this.cheapKeyFromCompositeKey(change.Key);
28976
- if (change.Row) {
28977
- rows.set(keyStr, change.Row);
28978
- deletesByKey.delete(keyStr);
28979
- upsertsByKey.set(keyStr, change.Row);
28980
- changed = true;
28981
- } else if (rows.delete(keyStr)) {
28982
- upsertsByKey.delete(keyStr);
28983
- const pkRecord = {};
28984
- for (const kv of change.Key.KeyValuePairs) {
28985
- const v = kv.Value;
28986
- pkRecord[kv.FieldName] = typeof v === "string" || typeof v === "number" || typeof v === "boolean" || v === null ? v : String(v);
28987
- }
28988
- deletesByKey.set(keyStr, pkRecord);
28989
- changed = true;
28990
- }
28991
- }
28992
- return {
28993
- changed,
28994
- upsertedRows: Array.from(upsertsByKey.values()),
28995
- deletedPrimaryKeys: Array.from(deletesByKey.values())
28996
- };
28997
- }
28998
29914
  /**
28999
29915
  * Freezes an in-place rewrite of a slot without re-walking the rows it carries forward.
29000
29916
  *
@@ -29037,7 +29953,24 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
29037
29953
  * correct total.
29038
29954
  */
29039
29955
  async storeCachedResults(fingerprint, updatedResults, newMaxUpdatedAt, prior, rowDelta, freezeHint) {
29040
- const maxUpdatedAt = _LocalCacheManager.MaxUpdatedAtOfRows(updatedResults) ?? newMaxUpdatedAt;
29956
+ let maxUpdatedAt;
29957
+ if (rowDelta && prior?.priorMaxUpdatedAt && !prior.displacedMaxTimestamp) {
29958
+ const priorEpoch = Date.parse(prior.priorMaxUpdatedAt);
29959
+ if (!Number.isNaN(priorEpoch)) {
29960
+ const deltaMax = _LocalCacheManager.MaxUpdatedAtOfRows(rowDelta.upsertedRows);
29961
+ if (deltaMax) {
29962
+ const deltaEpoch = Date.parse(deltaMax);
29963
+ if (!Number.isNaN(deltaEpoch)) {
29964
+ maxUpdatedAt = deltaEpoch > priorEpoch ? deltaMax : prior.priorMaxUpdatedAt;
29965
+ }
29966
+ } else {
29967
+ maxUpdatedAt = prior.priorMaxUpdatedAt;
29968
+ }
29969
+ }
29970
+ }
29971
+ if (!maxUpdatedAt) {
29972
+ maxUpdatedAt = _LocalCacheManager.MaxUpdatedAtOfRows(updatedResults) ?? newMaxUpdatedAt;
29973
+ }
29041
29974
  const now = Date.now();
29042
29975
  const existingEntry = this._registry.get(fingerprint);
29043
29976
  const data = {
@@ -29079,7 +30012,14 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
29079
30012
  pubSubData: JSON.stringify(deltaPayload)
29080
30013
  };
29081
30014
  }
29082
- await this._storageProvider.SetItem(fingerprint, data, CacheCategory.RunViewCache, this.runViewWriteOptions(fingerprint, existingEntry?.expiresAt, pubSubOverride));
30015
+ const writeOpts = this.runViewWriteOptions(fingerprint, existingEntry?.expiresAt, pubSubOverride, rowDelta?.primaryKeyFields);
30016
+ let appliedDelta = false;
30017
+ if (pubSubOverride && typeof this._storageProvider.ApplyRunViewRowDelta === "function") {
30018
+ appliedDelta = await this._storageProvider.ApplyRunViewRowDelta(fingerprint, pubSubOverride.pubSubData, data, writeOpts);
30019
+ }
30020
+ if (!appliedDelta) {
30021
+ await this._storageProvider.SetItem(fingerprint, data, CacheCategory.RunViewCache, writeOpts);
30022
+ }
29083
30023
  this._lastVerifiedAt.set(fingerprint, now);
29084
30024
  if (existingEntry) {
29085
30025
  existingEntry.maxUpdatedAt = maxUpdatedAt;
@@ -31859,14 +32799,14 @@ function normalizeKey(value) {
31859
32799
 
31860
32800
  // ../../MJCore/dist/generic/queryTemplateContext.js
31861
32801
  var QUERY_CONTEXT_NAME = "Context";
31862
- var TEMPLATE_TAG = /\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}/g;
32802
+ var TEMPLATE_TAG_DELIMITERS = [["{{", "}}"], ["{%", "%}"]];
31863
32803
  var CONTEXT_WORD = /\bContext\b/g;
31864
32804
  var CONTEXT_MEMBER = /\bContext\s*\.\s*([A-Za-z_]\w*)/g;
31865
32805
  function FindTemplateContextTokens(sql) {
31866
32806
  const named = /* @__PURE__ */ new Set();
31867
32807
  let mentions = 0;
31868
32808
  let namedMentions = 0;
31869
- for (const tag of (sql ?? "").match(TEMPLATE_TAG) ?? []) {
32809
+ for (const tag of templateTags(sql ?? "")) {
31870
32810
  mentions += (tag.match(CONTEXT_WORD) ?? []).length;
31871
32811
  for (const match of tag.matchAll(CONTEXT_MEMBER)) {
31872
32812
  named.add(match[1]);
@@ -31878,6 +32818,32 @@ function FindTemplateContextTokens(sql) {
31878
32818
  }
31879
32819
  return CONTEXT_TOKENS.filter((token) => named.has(memberName(token)));
31880
32820
  }
32821
+ function templateTags(sql) {
32822
+ const tags = [];
32823
+ const unclosed = /* @__PURE__ */ new Set();
32824
+ let pos = sql.indexOf("{");
32825
+ while (pos !== -1) {
32826
+ const end = templateTagEndAt(sql, pos, unclosed);
32827
+ if (end === -1) {
32828
+ pos = sql.indexOf("{", pos + 1);
32829
+ } else {
32830
+ tags.push(sql.substring(pos, end));
32831
+ pos = sql.indexOf("{", end);
32832
+ }
32833
+ }
32834
+ return tags;
32835
+ }
32836
+ function templateTagEndAt(sql, pos, unclosed) {
32837
+ for (const [open, close] of TEMPLATE_TAG_DELIMITERS) {
32838
+ if (unclosed.has(open) || !sql.startsWith(open, pos))
32839
+ continue;
32840
+ const at = sql.indexOf(close, pos + open.length);
32841
+ if (at !== -1)
32842
+ return at + close.length;
32843
+ unclosed.add(open);
32844
+ }
32845
+ return -1;
32846
+ }
31881
32847
  function FindQueryContextTokens(queryID, sqlTextsOf, composedIDsOf) {
31882
32848
  const found = /* @__PURE__ */ new Set();
31883
32849
  const visited = new UUIDSet();
@@ -31980,10 +32946,37 @@ var AllMetadataArrays = [
31980
32946
  { key: "AllLibraries", class: LibraryInfo },
31981
32947
  { key: "AllExplorerNavigationItems", class: ExplorerNavigationItem }
31982
32948
  ];
31983
- function ProjectRowsToFields(rows, requestedFields) {
32949
+ function CanonicalFieldsKey(fields) {
32950
+ if (!fields || fields.length === 0) {
32951
+ return "";
32952
+ }
32953
+ const unique = /* @__PURE__ */ new Set();
32954
+ for (const f of fields) {
32955
+ const normalized = f.trim().toLowerCase();
32956
+ if (normalized.length > 0) {
32957
+ unique.add(normalized);
32958
+ }
32959
+ }
32960
+ if (unique.size === 0) {
32961
+ return "";
32962
+ }
32963
+ return Array.from(unique).sort().join(",");
32964
+ }
32965
+ var FrozenProjectedRowCache = /* @__PURE__ */ new WeakMap();
32966
+ var FrozenProjectedArrayCache = /* @__PURE__ */ new WeakMap();
32967
+ function ProjectRowsToFields(rows, requestedFields, options) {
31984
32968
  if (!requestedFields || requestedFields.length === 0 || !rows || rows.length === 0) {
31985
32969
  return rows;
31986
32970
  }
32971
+ const preserveFrozen = Boolean(options?.PreserveFrozen);
32972
+ const rowsAreFrozen = Object.isFrozen(rows);
32973
+ const canonicalKey = preserveFrozen ? CanonicalFieldsKey(requestedFields) : "";
32974
+ if (preserveFrozen && rowsAreFrozen && canonicalKey.length > 0) {
32975
+ const cachedArray = FrozenProjectedArrayCache.get(rows)?.get(canonicalKey);
32976
+ if (cachedArray) {
32977
+ return cachedArray;
32978
+ }
32979
+ }
31987
32980
  const requestedFieldSet = new Set(requestedFields.map((f) => f.trim().toLowerCase()));
31988
32981
  const probe = rows[0];
31989
32982
  if (probe && typeof probe === "object") {
@@ -31995,14 +32988,21 @@ function ProjectRowsToFields(rows, requestedFields) {
31995
32988
  }
31996
32989
  }
31997
32990
  if (allKept) {
31998
- if (!Object.isFrozen(rows)) {
32991
+ if (preserveFrozen || !rowsAreFrozen) {
31999
32992
  return rows;
32000
32993
  }
32001
32994
  }
32002
32995
  }
32003
32996
  const keyCache = /* @__PURE__ */ new Map();
32004
- return rows.map((row) => {
32997
+ const projected = rows.map((row) => {
32005
32998
  const source = row;
32999
+ const canMemoizeFrozen = preserveFrozen && canonicalKey.length > 0 && source !== null && typeof source === "object" && Object.isFrozen(source);
33000
+ if (canMemoizeFrozen) {
33001
+ const cachedProjected = FrozenProjectedRowCache.get(source)?.get(canonicalKey);
33002
+ if (cachedProjected) {
33003
+ return cachedProjected;
33004
+ }
33005
+ }
32006
33006
  const filtered = {};
32007
33007
  for (const key of Object.keys(source)) {
32008
33008
  let keep = keyCache.get(key);
@@ -32014,8 +33014,27 @@ function ProjectRowsToFields(rows, requestedFields) {
32014
33014
  filtered[key] = source[key];
32015
33015
  }
32016
33016
  }
33017
+ if (canMemoizeFrozen) {
33018
+ Object.freeze(filtered);
33019
+ let fieldMap = FrozenProjectedRowCache.get(source);
33020
+ if (!fieldMap) {
33021
+ fieldMap = /* @__PURE__ */ new Map();
33022
+ FrozenProjectedRowCache.set(source, fieldMap);
33023
+ }
33024
+ fieldMap.set(canonicalKey, filtered);
33025
+ }
32017
33026
  return filtered;
32018
33027
  });
33028
+ if (preserveFrozen && rowsAreFrozen && canonicalKey.length > 0) {
33029
+ Object.freeze(projected);
33030
+ let arrayMap = FrozenProjectedArrayCache.get(rows);
33031
+ if (!arrayMap) {
33032
+ arrayMap = /* @__PURE__ */ new Map();
33033
+ FrozenProjectedArrayCache.set(rows, arrayMap);
33034
+ }
33035
+ arrayMap.set(canonicalKey, projected);
33036
+ }
33037
+ return projected;
32019
33038
  }
32020
33039
  var ProviderBase = class _ProviderBase {
32021
33040
  constructor() {
@@ -32036,6 +33055,7 @@ var ProviderBase = class _ProviderBase {
32036
33055
  this._coalesceMicrotaskScheduled = false;
32037
33056
  this._inflightViews = /* @__PURE__ */ new Map();
32038
33057
  this._lingerInvalidationWired = false;
33058
+ this._invalidationTargetRef = null;
32039
33059
  this._entityMutationVersions = /* @__PURE__ */ new Map();
32040
33060
  this._metadataMemberMutationSeq = 0;
32041
33061
  this._metadataDatasetEntityNames = null;
@@ -32055,6 +33075,9 @@ var ProviderBase = class _ProviderBase {
32055
33075
  this._cachedVisibleExplorerNavigationItems = null;
32056
33076
  this._lastRemoteTimestampReadReached = true;
32057
33077
  this._metadataSnapshotSkipLogged = false;
33078
+ this._metadataSaveTimer = null;
33079
+ this._inFlightMetadataSave = null;
33080
+ this._hasPendingMetadataSaveWhileInFlight = false;
32058
33081
  }
32059
33082
  /**
32060
33083
  * Whether this provider can execute a multi-record unit of work atomically, in-process.
@@ -32211,19 +33234,35 @@ var ProviderBase = class _ProviderBase {
32211
33234
  return results;
32212
33235
  }
32213
33236
  /**
32214
- * Lazily registers this instance (once per provider instance) for write-invalidation
32215
- * of in-flight/lingered RunView entries touching a written entity. Deleting an IN-FLIGHT
32216
- * entry is deliberate: late joiners must not share a query that may have read pre-commit
32217
- * data; the original caller still gets its own result, and the orphaned promise's stash
32218
- * step no-ops safely.
33237
+ * Number of live/uncollected `ProviderBase` instances currently registered for in-flight
33238
+ * view invalidation callbacks.
33239
+ */
33240
+ static get ActiveInvalidationTargetCount() {
33241
+ return _ProviderBase._invalidationTargets.size;
33242
+ }
33243
+ /**
33244
+ * Immediately removes this provider instance from the global in-flight invalidation target set
33245
+ * and clears per-instance mutation state. Call on short-lived per-request server providers
33246
+ * when the HTTP response closes so `_invalidationTargets` does not accumulate thousands of
33247
+ * `WeakRef`s between major garbage collections.
32219
33248
  */
33249
+ DetachInvalidationListeners() {
33250
+ if (this._invalidationTargetRef) {
33251
+ _ProviderBase._invalidationTargets.delete(this._invalidationTargetRef);
33252
+ this._invalidationTargetRef = null;
33253
+ }
33254
+ this._lingerInvalidationWired = false;
33255
+ this._entityMutationVersions.clear();
33256
+ }
32220
33257
  ensureInflightViewInvalidation() {
32221
33258
  _ProviderBase.ensureStaticInvalidationSubscription();
32222
33259
  if (this._lingerInvalidationWired) {
32223
33260
  return;
32224
33261
  }
32225
33262
  this._lingerInvalidationWired = true;
32226
- _ProviderBase._invalidationTargets.add(new WeakRef(this));
33263
+ const ref = new WeakRef(this);
33264
+ this._invalidationTargetRef = ref;
33265
+ _ProviderBase._invalidationTargets.add(ref);
32227
33266
  }
32228
33267
  /**
32229
33268
  * Returns the current monotonic mutation version for `entityName` (case-insensitive).
@@ -32382,6 +33421,9 @@ var ProviderBase = class _ProviderBase {
32382
33421
  names.add(n);
32383
33422
  }
32384
33423
  }
33424
+ for (const skipped of this.skippedMetadataEntityNames(dataset.Results ?? [])) {
33425
+ names.delete(skipped);
33426
+ }
32385
33427
  if (names.size === 0) {
32386
33428
  return;
32387
33429
  }
@@ -32395,6 +33437,93 @@ var ProviderBase = class _ProviderBase {
32395
33437
  }));
32396
33438
  this.ensureInflightViewInvalidation();
32397
33439
  }
33440
+ /**
33441
+ * The MJ_Metadata item codes that hold the saved-query metadata: the saved-query family (see
33442
+ * {@link PartialRefreshMetadataItemCodes}) and the SQL dialects. They are read only when the
33443
+ * provider is configured with {@link ProviderConfigDataBase.LoadQueryMetadata}.
33444
+ */
33445
+ static get QueryMetadataItemCodes() {
33446
+ return [..._ProviderBase._queryFamilyItemCodes, "SQLDialects"];
33447
+ }
33448
+ /**
33449
+ * Whether this provider loads the saved-query metadata into its metadata object (see
33450
+ * {@link ProviderConfigDataBase.LoadQueryMetadata}). False unless the configuration says true.
33451
+ * A provider that adopted the global provider's metadata reports the global provider's
33452
+ * setting instead, since that is what decided whether the adopted metadata holds queries.
33453
+ */
33454
+ get LoadsQueryMetadata() {
33455
+ return this._adoptedLoadsQueryMetadata ?? this._ConfigData?.LoadQueryMetadata === true;
33456
+ }
33457
+ /**
33458
+ * The item filters every read of the MJ_Metadata dataset uses — the data, its status, and the
33459
+ * local dataset cache — so all of them describe the same row set. Null when every item is read.
33460
+ * Otherwise each item this provider does not load gets a `1=0` filter: the server runs no SQL
33461
+ * for it, and its status is constant, so writes to it never make the metadata look stale.
33462
+ */
33463
+ get MetadataDatasetItemFilters() {
33464
+ if (this.LoadsQueryMetadata) {
33465
+ return null;
33466
+ }
33467
+ return _ProviderBase.QueryMetadataItemCodes.map((code) => ({ ItemCode: code, Filter: "1=0" }));
33468
+ }
33469
+ /**
33470
+ * The MJ_Metadata item codes THIS provider builds its metadata from: {@link MetadataBuildItemCodes}
33471
+ * without the items it does not read (see {@link MetadataDatasetItemFilters}). A change only to
33472
+ * the others needs no reload, as for any item the build never reads.
33473
+ */
33474
+ get BuiltMetadataItemCodes() {
33475
+ if (this.LoadsQueryMetadata) {
33476
+ return _ProviderBase.MetadataBuildItemCodes;
33477
+ }
33478
+ const built = new Set(_ProviderBase.MetadataBuildItemCodes);
33479
+ for (const code of _ProviderBase.QueryMetadataItemCodes) {
33480
+ built.delete(code);
33481
+ }
33482
+ return built;
33483
+ }
33484
+ /**
33485
+ * Empties the query-metadata arrays of `metadata` when this provider does not load them. A stored
33486
+ * snapshot written by a process that did load them would otherwise hold those rows in memory for
33487
+ * the life of this process, behind getters that return nothing.
33488
+ */
33489
+ dropUnloadedQueryMetadata(metadata) {
33490
+ if (this.LoadsQueryMetadata) {
33491
+ return;
33492
+ }
33493
+ metadata.AllQueryCategories = [];
33494
+ metadata.AllQueries = [];
33495
+ metadata.AllQueryFields = [];
33496
+ metadata.AllQueryPermissions = [];
33497
+ metadata.AllQueryEntities = [];
33498
+ metadata.AllQueryParameters = [];
33499
+ metadata.AllQueryDependencies = [];
33500
+ metadata.AllSQLDialects = [];
33501
+ metadata.AllQuerySQLs = [];
33502
+ }
33503
+ /** Whether `code` is an MJ_Metadata item this provider does not read (see {@link MetadataDatasetItemFilters}). */
33504
+ isSkippedMetadataItem(code) {
33505
+ return !!code && !this.LoadsQueryMetadata && _ProviderBase.QueryMetadataItemCodes.includes(code);
33506
+ }
33507
+ /**
33508
+ * Lowercased names of the entities that back only items this provider does not read. A write to
33509
+ * one of them cannot change this provider's metadata, so they are left out of the membership set
33510
+ * — otherwise each such write would schedule a refresh that finds no timestamp moved and falls
33511
+ * back to a full reload.
33512
+ */
33513
+ skippedMetadataEntityNames(items) {
33514
+ const skipped = /* @__PURE__ */ new Set();
33515
+ const read = /* @__PURE__ */ new Set();
33516
+ for (const item of items) {
33517
+ const name = item.EntityName?.trim().toLowerCase();
33518
+ if (name) {
33519
+ (this.isSkippedMetadataItem(item.Code) ? skipped : read).add(name);
33520
+ }
33521
+ }
33522
+ for (const name of read) {
33523
+ skipped.delete(name);
33524
+ }
33525
+ return skipped;
33526
+ }
32398
33527
  static {
32399
33528
  this.MetadataSweepSkipped = { Declared: [], Checked: false, Refreshed: false };
32400
33529
  }
@@ -32935,25 +34064,26 @@ var ProviderBase = class _ProviderBase {
32935
34064
  params = { ...params };
32936
34065
  if (this.TrustLocalCacheCompletely && !params.BypassCache && !params.AfterKey) {
32937
34066
  const preResult = await this.PreRunView(params, contextUser);
34067
+ const effectiveParams = preResult.effectiveParams ?? params;
32938
34068
  if (preResult.cachedResult) {
32939
- LogStatusEx({ message: ` \u2705 [Cache HIT] RunView "${params.EntityName || params.ViewName || "unknown"}" \u2014 ${preResult.cachedResult.Results?.length ?? 0} rows from cache, no DB query`, verboseOnly: true });
32940
- await this.TransformSimpleObjectToEntityObject(params, preResult.cachedResult, contextUser);
32941
- await this.ApplyPostRunViewHooksToCacheHit(params, preResult.cachedResult, contextUser);
34069
+ LogStatusEx({ message: ` \u2705 [Cache HIT] RunView "${effectiveParams.EntityName || effectiveParams.ViewName || "unknown"}" \u2014 ${preResult.cachedResult.Results?.length ?? 0} rows from cache, no DB query`, verboseOnly: true });
34070
+ await this.TransformSimpleObjectToEntityObject(effectiveParams, preResult.cachedResult, contextUser);
34071
+ await this.ApplyPostRunViewHooksToCacheHit(effectiveParams, preResult.cachedResult, contextUser);
32942
34072
  TelemetryManager.Instance.EndEvent(preResult.telemetryEventId, {
32943
34073
  cacheHit: true,
32944
34074
  cacheStatus: preResult.cacheStatus,
32945
34075
  resultCount: preResult.cachedResult.Results?.length ?? 0
32946
34076
  });
32947
- if (params.OnDataChanged && preResult.fingerprint) {
32948
- preResult.cachedResult.Unsubscribe = LocalCacheManager.Instance.RegisterChangeCallback(preResult.fingerprint, params.OnDataChanged);
34077
+ if (effectiveParams.OnDataChanged && preResult.fingerprint) {
34078
+ preResult.cachedResult.Unsubscribe = LocalCacheManager.Instance.RegisterChangeCallback(preResult.fingerprint, effectiveParams.OnDataChanged);
32949
34079
  }
32950
- _ProviderBase.clearSkippedTotalRowCount(params, preResult.cachedResult);
34080
+ _ProviderBase.clearSkippedTotalRowCount(effectiveParams, preResult.cachedResult);
32951
34081
  return preResult.cachedResult;
32952
34082
  }
32953
- LogStatusEx({ message: ` \u{1F50D} [Cache MISS] RunView "${params.EntityName || params.ViewName || "unknown"}" \u2014 querying database`, verboseOnly: true });
32954
- const result = await this.InternalRunView(params, contextUser);
32955
- await this.PostRunView(result, params, preResult, contextUser);
32956
- _ProviderBase.clearSkippedTotalRowCount(params, result);
34083
+ LogStatusEx({ message: ` \u{1F50D} [Cache MISS] RunView "${effectiveParams.EntityName || effectiveParams.ViewName || "unknown"}" \u2014 querying database`, verboseOnly: true });
34084
+ const result = await this.InternalRunView(effectiveParams, contextUser);
34085
+ await this.PostRunView(result, effectiveParams, preResult, contextUser);
34086
+ _ProviderBase.clearSkippedTotalRowCount(effectiveParams, result);
32957
34087
  return result;
32958
34088
  }
32959
34089
  const results = await this.RunViews([params], contextUser);
@@ -33922,7 +35052,10 @@ var ProviderBase = class _ProviderBase {
33922
35052
  * `resolvable` is true.
33923
35053
  *
33924
35054
  * The BASE implementation resolves from the metadata `Queries` cache and enforces the
33925
- * ROLES-ONLY `QueryInfo.UserCanRun` — the strongest check available at this layer.
35055
+ * ROLES-ONLY `QueryInfo.UserCanRun` — the strongest check available at this layer. That cache
35056
+ * is loaded only when the provider is configured with `LoadQueryMetadata`; otherwise every
35057
+ * request is unresolvable here, so a provider that executes or caches saved queries overrides
35058
+ * this to resolve from `QueryEngine`.
33926
35059
  * Providers with richer query metadata MUST override this to enforce the SAME authorization
33927
35060
  * their miss path enforces (`GenericDatabaseProvider` overrides with
33928
35061
  * `MJQueryEntityExtended.UserCanRun`, which adds entity CanRead + recursive composition
@@ -33932,6 +35065,9 @@ var ProviderBase = class _ProviderBase {
33932
35065
  * the miss path also checked entity read permissions).
33933
35066
  */
33934
35067
  ResolveQueryCacheAuthorization(params, user) {
35068
+ if (!this.LoadsQueryMetadata) {
35069
+ return { resolvable: false, authorized: false };
35070
+ }
33935
35071
  const requestedPath = params.CategoryPath?.trim().toLowerCase();
33936
35072
  const qInfo = this.Queries.find((q) => params.QueryID && UUIDsEqual(q.ID, params.QueryID) || !params.QueryID && params.QueryName && q.Name?.trim().toLowerCase() === params.QueryName.trim().toLowerCase() && (!requestedPath || q.CategoryPath?.trim().toLowerCase() === requestedPath));
33937
35073
  if (!qInfo) {
@@ -34795,7 +35931,8 @@ var ProviderBase = class _ProviderBase {
34795
35931
  // Only non-null when params.Fields was actually widened for cache population — tells
34796
35932
  // PostRunView to project cache-miss DB results back to the caller's shape
34797
35933
  callerRequestedFields: callerRequestedFieldsForPost,
34798
- populateCache: willPopulateCache
35934
+ populateCache: willPopulateCache,
35935
+ effectiveParams: params
34799
35936
  };
34800
35937
  }
34801
35938
  /**
@@ -35457,7 +36594,7 @@ var ProviderBase = class _ProviderBase {
35457
36594
  async RunPreRunViewHooks(params, contextUser) {
35458
36595
  const hooks = GetDataHooks("PreRunView");
35459
36596
  for (const hook of hooks) {
35460
- params = await hook(params, contextUser);
36597
+ params = await hook(params, contextUser, this);
35461
36598
  }
35462
36599
  return params;
35463
36600
  }
@@ -35475,7 +36612,7 @@ var ProviderBase = class _ProviderBase {
35475
36612
  async RunPostRunViewHooks(params, result, contextUser) {
35476
36613
  const hooks = GetDataHooks("PostRunView");
35477
36614
  for (const hook of hooks) {
35478
- result = await hook(params, result, contextUser);
36615
+ result = await hook(params, result, contextUser, this);
35479
36616
  }
35480
36617
  return result;
35481
36618
  }
@@ -35599,6 +36736,8 @@ var ProviderBase = class _ProviderBase {
35599
36736
  return false;
35600
36737
  if (entity.ExternalDataSourceID)
35601
36738
  return false;
36739
+ if (IsPostRunViewProtectedEntity(entity.Name))
36740
+ return false;
35602
36741
  return entity.TrustServerCacheCompletely !== false;
35603
36742
  }
35604
36743
  shouldAutoCache(params, result, contextUser) {
@@ -36058,8 +37197,23 @@ var ProviderBase = class _ProviderBase {
36058
37197
  * @param data - Configuration including schema filters and connection info
36059
37198
  * @returns True if configuration was successful
36060
37199
  */
37200
+ /**
37201
+ * Synchronously configures this provider from an already-initialized global `Metadata.Provider`
37202
+ * without allocating promises or awaiting async cache initialization. Returns `false` if global
37203
+ * metadata or `LocalCacheManager` has not finished initializing yet.
37204
+ */
37205
+ ConfigureFromGlobalMetadataSync(data) {
37206
+ if (!Metadata.Provider || data.IgnoreExistingMetadata || this._refresh || !LocalCacheManager.Instance.IsInitialized) {
37207
+ return false;
37208
+ }
37209
+ this._ConfigData = data;
37210
+ this._adoptedLoadsQueryMetadata = void 0;
37211
+ this._configLoadedFromServer = false;
37212
+ return this.CopyMetadataFromGlobalProvider();
37213
+ }
36061
37214
  async Config(data, providerToUse) {
36062
37215
  this._ConfigData = data;
37216
+ this._adoptedLoadsQueryMetadata = void 0;
36063
37217
  this._configLoadedFromServer = false;
36064
37218
  const localCacheInitPromise = !LocalCacheManager.Instance.IsInitialized ? LocalCacheManager.Instance.Initialize(this.LocalStorageProvider) : Promise.resolve();
36065
37219
  if (Metadata.Provider && !data.IgnoreExistingMetadata && !this._refresh) {
@@ -36230,7 +37384,7 @@ var ProviderBase = class _ProviderBase {
36230
37384
  const rollup = norm(_ProviderBase._allMetadataTypeName);
36231
37385
  const prevLocal = this._latestLocalMetadataTimestamps ?? [];
36232
37386
  const datasetItems = this._metadataDatasetItems;
36233
- const built = _ProviderBase.MetadataBuildItemCodes;
37387
+ const built = this.BuiltMetadataItemCodes;
36234
37388
  const resRecord = res;
36235
37389
  let hasMismatch = false;
36236
37390
  const reconciled = [];
@@ -36296,7 +37450,7 @@ var ProviderBase = class _ProviderBase {
36296
37450
  if (!hasMismatch) {
36297
37451
  return remote;
36298
37452
  }
36299
- this.ClearDatasetCache(_ProviderBase._mjMetadataDatasetName).catch(() => {
37453
+ this.ClearDatasetCache(_ProviderBase._mjMetadataDatasetName, this.MetadataDatasetItemFilters).catch(() => {
36300
37454
  });
36301
37455
  const remoteRollup = remote.find((r) => norm(r.Type) === rollup);
36302
37456
  if (remoteRollup) {
@@ -36338,7 +37492,7 @@ var ProviderBase = class _ProviderBase {
36338
37492
  return { Kind: "full", Reason: "the metadata timestamps are not known" };
36339
37493
  }
36340
37494
  const family = new Set(_ProviderBase.PartialRefreshMetadataItemCodes);
36341
- const built = _ProviderBase.MetadataBuildItemCodes;
37495
+ const built = this.BuiltMetadataItemCodes;
36342
37496
  const norm = (v) => (v ?? "").trim().toLowerCase();
36343
37497
  const rollup = norm(_ProviderBase._allMetadataTypeName);
36344
37498
  let anyItemChanged = false;
@@ -36421,7 +37575,7 @@ var ProviderBase = class _ProviderBase {
36421
37575
  }
36422
37576
  try {
36423
37577
  const keep = new Set(codes);
36424
- const skipOthers = items.filter((item) => !keep.has(item.Code)).map((item) => ({ ItemCode: item.Code, Filter: "1=0" }));
37578
+ const skipOthers = items.filter((item) => !keep.has(item.Code) || this.isSkippedMetadataItem(item.Code)).map((item) => ({ ItemCode: item.Code, Filter: "1=0" }));
36425
37579
  const start = Date.now();
36426
37580
  const d = await this.GetDatasetByName(_ProviderBase._mjMetadataDatasetName, skipOthers, this.CurrentUser, providerToUse, true);
36427
37581
  if (!d?.Success) {
@@ -36650,6 +37804,9 @@ var ProviderBase = class _ProviderBase {
36650
37804
  } else {
36651
37805
  this.UpdateLocalMetadata(adopted);
36652
37806
  }
37807
+ if (globalProvider instanceof _ProviderBase) {
37808
+ this._adoptedLoadsQueryMetadata = globalProvider.LoadsQueryMetadata;
37809
+ }
36653
37810
  return true;
36654
37811
  }
36655
37812
  return false;
@@ -36738,7 +37895,8 @@ var ProviderBase = class _ProviderBase {
36738
37895
  async GetAllMetadata(providerToUse, forceRefresh) {
36739
37896
  try {
36740
37897
  const mutationSeqAtStart = this._metadataMemberMutationSeq;
36741
- const d = await this.GetDatasetByName(_ProviderBase._mjMetadataDatasetName, null, this.CurrentUser, providerToUse, forceRefresh);
37898
+ const itemFilters = this.MetadataDatasetItemFilters;
37899
+ const d = await this.GetDatasetByName(_ProviderBase._mjMetadataDatasetName, itemFilters, this.CurrentUser, providerToUse, forceRefresh);
36742
37900
  const entitiesItem = d?.Success ? d.Results?.find((r) => r.Code === "Entities") : void 0;
36743
37901
  const hasEntities = Array.isArray(entitiesItem?.Results) && entitiesItem.Results.length > 0;
36744
37902
  if (d && d.Success && !hasEntities) {
@@ -36747,14 +37905,11 @@ var ProviderBase = class _ProviderBase {
36747
37905
  this.registerMetadataDatasetMembership(d);
36748
37906
  const mutatedDuringLoad = this._metadataReloadQueued || this._metadataMemberMutationSeq !== mutationSeqAtStart || this.hasDatasetRemoteRowCountMismatch(d);
36749
37907
  if (!mutatedDuringLoad) {
36750
- await this.CacheDataset(_ProviderBase._mjMetadataDatasetName, null, d);
37908
+ await this.CacheDataset(_ProviderBase._mjMetadataDatasetName, itemFilters, d);
36751
37909
  } else {
36752
- await this.ClearDatasetCache(_ProviderBase._mjMetadataDatasetName);
36753
- }
36754
- const simpleMetadata = {};
36755
- for (let r of d.Results) {
36756
- simpleMetadata[r.Code] = r.Results;
37910
+ await this.ClearDatasetCache(_ProviderBase._mjMetadataDatasetName, itemFilters);
36757
37911
  }
37912
+ const simpleMetadata = _ProviderBase.metadataAssemblyInput(d);
36758
37913
  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);
36759
37914
  simpleMetadata.AllApplications = simpleMetadata.Applications.map((a) => {
36760
37915
  a.ApplicationEntities = simpleMetadata.ApplicationEntities.filter((ae) => UUIDsEqual(ae.ApplicationID, a.ID));
@@ -36773,6 +37928,25 @@ var ProviderBase = class _ProviderBase {
36773
37928
  this._lastMetadataLoadError = e instanceof Error ? e : new Error(String(e));
36774
37929
  }
36775
37930
  }
37931
+ static {
37932
+ this._assemblyWrittenItemCodes = /* @__PURE__ */ new Set(["Entities", "EntityFields", "EntityOrganicKeys", "Applications"]);
37933
+ }
37934
+ /**
37935
+ * The MJ_Metadata rows keyed by item code, as {@link GetAllMetadata} assembles them: the items
37936
+ * the assembly writes to are shallow copies (a new array of new row objects), the rest are the
37937
+ * dataset's own arrays. The dataset's rows are the ones the dataset cache holds and serves to
37938
+ * every later reader — on a server, every client's metadata request — so writing child
37939
+ * collections onto them would send each entity's fields, permissions and relationships a second
37940
+ * time, nested inside the entity rows, with every response.
37941
+ */
37942
+ static metadataAssemblyInput(dataset) {
37943
+ const input = {};
37944
+ for (const item of dataset.Results ?? []) {
37945
+ const rows = Array.isArray(item.Results) ? item.Results : [];
37946
+ input[item.Code] = _ProviderBase._assemblyWrittenItemCodes.has(item.Code) ? rows.map((row) => ({ ...row })) : rows;
37947
+ }
37948
+ return input;
37949
+ }
36776
37950
  /** Logs a failed metadata download and keeps it for {@link LastMetadataLoadError}. */
36777
37951
  recordMetadataLoadFailure(error) {
36778
37952
  LogError(error.message);
@@ -36790,7 +37964,11 @@ var ProviderBase = class _ProviderBase {
36790
37964
  const previousUserJson = this._localMetadata.CurrentUser ? JSON.stringify(this._localMetadata.CurrentUser) : null;
36791
37965
  this._localMetadata.CurrentUser = user;
36792
37966
  if (previousUserJson !== JSON.stringify(user)) {
36793
- void this.SaveLocalMetadataToStorage();
37967
+ if (Object.prototype.hasOwnProperty.call(this, "SaveLocalMetadataToStorage")) {
37968
+ void this.SaveLocalMetadataToStorage();
37969
+ } else {
37970
+ this.ScheduleSaveLocalMetadataToStorage();
37971
+ }
36794
37972
  }
36795
37973
  return user;
36796
37974
  }
@@ -36967,41 +38145,86 @@ var ProviderBase = class _ProviderBase {
36967
38145
  get AuthorizationRoles() {
36968
38146
  return this._localMetadata.AllAuthorizationRoles;
36969
38147
  }
36970
- /** @deprecated Use `QueryEngine.Instance.Queries` from `@memberjunction/core-entities`. Will be removed in v6.x. */
38148
+ static {
38149
+ this._queryMetadataWarningLogged = false;
38150
+ }
38151
+ /**
38152
+ * What a deprecated query-metadata getter returns: the loaded array when the provider loads query
38153
+ * metadata, otherwise an empty array and a warning, logged once per process, naming the
38154
+ * replacement.
38155
+ */
38156
+ deprecatedQueryMetadata(items, getterName) {
38157
+ if (this.LoadsQueryMetadata) {
38158
+ return items;
38159
+ }
38160
+ if (!_ProviderBase._queryMetadataWarningLogged) {
38161
+ _ProviderBase._queryMetadataWarningLogged = true;
38162
+ LogWarning(`Metadata.${getterName} and the other query-metadata getters are empty: query metadata is not loaded into the metadata object. Use QueryEngine from @memberjunction/core-entities, or set LoadQueryMetadata (databaseSettings.loadQueryMetadata on MJAPI) until the code is migrated.`, "Metadata");
38163
+ }
38164
+ return [];
38165
+ }
38166
+ /**
38167
+ * @deprecated Use `QueryEngine.Instance.Queries` from `@memberjunction/core-entities`. Empty unless the
38168
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
38169
+ */
36971
38170
  get Queries() {
36972
- return this._localMetadata.AllQueries;
38171
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueries, "Queries");
36973
38172
  }
36974
- /** @deprecated Use `QueryEngine.Instance.Categories` from `@memberjunction/core-entities`. Will be removed in v6.x. */
38173
+ /**
38174
+ * @deprecated Use `QueryEngine.Instance.Categories` from `@memberjunction/core-entities`. Empty unless the
38175
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
38176
+ */
36975
38177
  get QueryCategories() {
36976
- return this._localMetadata.AllQueryCategories;
38178
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryCategories, "QueryCategories");
36977
38179
  }
36978
- /** @deprecated Use `QueryEngine.Instance.Fields` from `@memberjunction/core-entities`. Will be removed in v6.x. */
38180
+ /**
38181
+ * @deprecated Use `QueryEngine.Instance.Fields` from `@memberjunction/core-entities`. Empty unless the
38182
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
38183
+ */
36979
38184
  get QueryFields() {
36980
- return this._localMetadata.AllQueryFields;
38185
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryFields, "QueryFields");
36981
38186
  }
36982
- /** @deprecated Use `QueryEngine.Instance.Permissions` from `@memberjunction/core-entities`. Will be removed in v6.x. */
38187
+ /**
38188
+ * @deprecated Use `QueryEngine.Instance.Permissions` from `@memberjunction/core-entities`. Empty unless the
38189
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
38190
+ */
36983
38191
  get QueryPermissions() {
36984
- return this._localMetadata.AllQueryPermissions;
38192
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryPermissions, "QueryPermissions");
36985
38193
  }
36986
- /** @deprecated Use `QueryEngine.Instance.QueryEntities` from `@memberjunction/core-entities`. Will be removed in v6.x. */
38194
+ /**
38195
+ * @deprecated Use `QueryEngine.Instance.QueryEntities` from `@memberjunction/core-entities`. Empty unless the
38196
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
38197
+ */
36987
38198
  get QueryEntities() {
36988
- return this._localMetadata.AllQueryEntities;
38199
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryEntities, "QueryEntities");
36989
38200
  }
36990
- /** @deprecated Use `QueryEngine.Instance.Parameters` from `@memberjunction/core-entities`. Will be removed in v6.x. */
38201
+ /**
38202
+ * @deprecated Use `QueryEngine.Instance.Parameters` from `@memberjunction/core-entities`. Empty unless the
38203
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
38204
+ */
36991
38205
  get QueryParameters() {
36992
- return this._localMetadata.AllQueryParameters;
38206
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryParameters, "QueryParameters");
36993
38207
  }
36994
- /** @deprecated Use `QueryEngine.Instance.Dependencies` from `@memberjunction/core-entities`. Will be removed in v6.x. */
38208
+ /**
38209
+ * @deprecated Use `QueryEngine.Instance.Dependencies` from `@memberjunction/core-entities`. Empty unless the
38210
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
38211
+ */
36995
38212
  get QueryDependencies() {
36996
- return this._localMetadata.AllQueryDependencies;
38213
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQueryDependencies, "QueryDependencies");
36997
38214
  }
36998
- /** @deprecated Use `QueryEngine.Instance.SQLDialects` from `@memberjunction/core-entities`. Will be removed in v6.x. */
38215
+ /**
38216
+ * @deprecated Use `QueryEngine.Instance.SQLDialects` from `@memberjunction/core-entities`. Empty unless the
38217
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
38218
+ */
36999
38219
  get SQLDialects() {
37000
- return this._localMetadata.AllSQLDialects;
38220
+ return this.deprecatedQueryMetadata(this._localMetadata.AllSQLDialects, "SQLDialects");
37001
38221
  }
37002
- /** @deprecated Use `QueryEngine.Instance.QuerySQLs` from `@memberjunction/core-entities`. Will be removed in v6.x. */
38222
+ /**
38223
+ * @deprecated Use `QueryEngine.Instance.QuerySQLs` from `@memberjunction/core-entities`. Empty unless the
38224
+ * provider is configured with `LoadQueryMetadata`; removed in 7.0.
38225
+ */
37003
38226
  get QuerySQLs() {
37004
- return this._localMetadata.AllQuerySQLs;
38227
+ return this.deprecatedQueryMetadata(this._localMetadata.AllQuerySQLs, "QuerySQLs");
37005
38228
  }
37006
38229
  /**
37007
38230
  * Gets all library definitions in the system.
@@ -37578,7 +38801,7 @@ var ProviderBase = class _ProviderBase {
37578
38801
  async ReadRemoteMetadataTimestamps(providerToUse) {
37579
38802
  let d;
37580
38803
  try {
37581
- d = await this.GetDatasetStatusByName(_ProviderBase._mjMetadataDatasetName, null, this.CurrentUser, providerToUse);
38804
+ d = await this.GetDatasetStatusByName(_ProviderBase._mjMetadataDatasetName, this.MetadataDatasetItemFilters, this.CurrentUser, providerToUse);
37582
38805
  } catch (e) {
37583
38806
  if (!IsTransportError(e)) {
37584
38807
  throw e;
@@ -37716,13 +38939,46 @@ var ProviderBase = class _ProviderBase {
37716
38939
  const membershipKey = this.LocalStoragePrefix + _ProviderBase.localStorageDatasetMembershipKey;
37717
38940
  const itemsKey = this.LocalStoragePrefix + _ProviderBase.localStorageDatasetItemsKey;
37718
38941
  const readStart = Date.now();
37719
- const all = await ls.GetItems([tsKey, fmtKey, dataKey, membershipKey, itemsKey]);
38942
+ let raw = null;
38943
+ let tsRaw = null;
38944
+ let format = null;
38945
+ let membershipRaw = null;
38946
+ let itemsRaw = null;
38947
+ if (typeof ls.GetObject === "function") {
38948
+ const otherKeys = [tsKey, fmtKey, membershipKey, itemsKey];
38949
+ const [metadataObj, otherItems] = await Promise.all([
38950
+ ls.GetObject(dataKey),
38951
+ typeof ls.GetItems === "function" ? ls.GetItems(otherKeys) : null
38952
+ ]);
38953
+ raw = metadataObj !== null && metadataObj !== void 0 ? metadataObj : await ls.GetItem(dataKey);
38954
+ if (otherItems) {
38955
+ tsRaw = otherItems.get(tsKey) ?? null;
38956
+ format = otherItems.get(fmtKey) ?? null;
38957
+ membershipRaw = otherItems.get(membershipKey) ?? null;
38958
+ itemsRaw = otherItems.get(itemsKey) ?? null;
38959
+ } else {
38960
+ tsRaw = await ls.GetItem(tsKey);
38961
+ format = await ls.GetItem(fmtKey);
38962
+ membershipRaw = await ls.GetItem(membershipKey);
38963
+ itemsRaw = await ls.GetItem(itemsKey);
38964
+ }
38965
+ } else {
38966
+ const all = typeof ls.GetItems === "function" ? await ls.GetItems([tsKey, fmtKey, dataKey, membershipKey, itemsKey]) : null;
38967
+ if (all) {
38968
+ tsRaw = all.get(tsKey) ?? null;
38969
+ format = all.get(fmtKey) ?? null;
38970
+ raw = all.get(dataKey) ?? null;
38971
+ membershipRaw = all.get(membershipKey) ?? null;
38972
+ itemsRaw = all.get(itemsKey) ?? null;
38973
+ } else {
38974
+ tsRaw = await ls.GetItem(tsKey);
38975
+ format = await ls.GetItem(fmtKey);
38976
+ raw = await ls.GetItem(dataKey);
38977
+ membershipRaw = await ls.GetItem(membershipKey);
38978
+ itemsRaw = await ls.GetItem(itemsKey);
38979
+ }
38980
+ }
37720
38981
  const readMs = Date.now() - readStart;
37721
- const tsRaw = all.get(tsKey) ?? null;
37722
- const format = all.get(fmtKey) ?? null;
37723
- const raw = all.get(dataKey) ?? null;
37724
- const membershipRaw = all.get(membershipKey) ?? null;
37725
- const itemsRaw = all.get(itemsKey) ?? null;
37726
38982
  const claimUsable = !!tsRaw && !!raw;
37727
38983
  if (claimUsable) {
37728
38984
  this._latestLocalMetadataTimestamps = JSON.parse(tsRaw);
@@ -37733,20 +38989,12 @@ var ProviderBase = class _ProviderBase {
37733
38989
  if (tsRaw && !raw) {
37734
38990
  LogStatusEx({ message: "[Metadata Cache] stored timestamps have no payload behind them (the payload expired or was cleared first) \u2014 ignoring the claim and checking the database", verboseOnly: true });
37735
38991
  }
37736
- if (membershipRaw) {
37737
- try {
37738
- const names = JSON.parse(membershipRaw);
37739
- if (Array.isArray(names) && names.length > 0) {
37740
- this._metadataDatasetEntityNames = new Set(names);
37741
- this.ensureInflightViewInvalidation();
37742
- }
37743
- } catch (membershipErr) {
37744
- LogError(`[Metadata Cache] Failed to restore dataset membership: ${membershipErr instanceof Error ? membershipErr.message : String(membershipErr)}`);
37745
- }
37746
- }
37747
38992
  if (itemsRaw) {
37748
38993
  this.restoreMetadataDatasetItems(itemsRaw);
37749
38994
  }
38995
+ if (membershipRaw) {
38996
+ this.restoreMetadataDatasetMembership(membershipRaw);
38997
+ }
37750
38998
  if (!raw)
37751
38999
  return;
37752
39000
  const parseStart = Date.now();
@@ -37758,8 +39006,10 @@ var ProviderBase = class _ProviderBase {
37758
39006
  const decompressedStream = blob.stream().pipeThrough(ds);
37759
39007
  const jsonString = await new Response(decompressedStream).text();
37760
39008
  temp = JSON.parse(jsonString);
37761
- } else {
37762
- temp = typeof raw === "string" ? JSON.parse(raw) : raw;
39009
+ } else if (typeof raw === "string") {
39010
+ temp = JSON.parse(raw);
39011
+ } else if (typeof raw === "object" && raw !== null) {
39012
+ temp = raw;
37763
39013
  }
37764
39014
  const parseMs = Date.now() - parseStart;
37765
39015
  if (!temp)
@@ -37768,6 +39018,7 @@ var ProviderBase = class _ProviderBase {
37768
39018
  const metadata = MetadataFromSimpleObject(temp, this);
37769
39019
  const deserializeMs = Date.now() - deserializeStart;
37770
39020
  if (metadata) {
39021
+ this.dropUnloadedQueryMetadata(metadata);
37771
39022
  this.UpdateLocalMetadata(metadata);
37772
39023
  const totalMs = Date.now() - overallStart;
37773
39024
  LogStatusEx({
@@ -37808,6 +39059,29 @@ var ProviderBase = class _ProviderBase {
37808
39059
  _ProviderBase.localStorageDatasetItemsKey
37809
39060
  ];
37810
39061
  }
39062
+ /**
39063
+ * Adopts a stored metadata-member entity set. The entities that back only items this provider
39064
+ * does not read are removed, so a snapshot saved by a process configured to read them cannot
39065
+ * make writes to them schedule refreshes here.
39066
+ */
39067
+ restoreMetadataDatasetMembership(membershipRaw) {
39068
+ try {
39069
+ const names = JSON.parse(membershipRaw);
39070
+ if (!Array.isArray(names) || names.length === 0) {
39071
+ return;
39072
+ }
39073
+ const restored = new Set(names.filter((n) => typeof n === "string"));
39074
+ for (const skipped of this.skippedMetadataEntityNames(this._metadataDatasetItems ?? [])) {
39075
+ restored.delete(skipped);
39076
+ }
39077
+ if (restored.size > 0) {
39078
+ this._metadataDatasetEntityNames = restored;
39079
+ this.ensureInflightViewInvalidation();
39080
+ }
39081
+ } catch (membershipErr) {
39082
+ LogError(`[Metadata Cache] Failed to restore dataset membership: ${membershipErr instanceof Error ? membershipErr.message : String(membershipErr)}`);
39083
+ }
39084
+ }
37811
39085
  /**
37812
39086
  * Adopts a stored dataset item list. Only a well-formed list replaces the one held: a damaged or
37813
39087
  * empty value must not erase the list a load already recorded.
@@ -37915,6 +39189,114 @@ var ProviderBase = class _ProviderBase {
37915
39189
  verboseOnly: false
37916
39190
  });
37917
39191
  }
39192
+ static {
39193
+ this.MetadataSnapshotSaveDebounceMs = 250;
39194
+ }
39195
+ /**
39196
+ * Schedules a trailing-edge coalesced background call to `SaveLocalMetadataToStorage()`,
39197
+ * deduplicating rapid back-to-back calls within the window and serializing execution if an
39198
+ * in-flight save is already running.
39199
+ *
39200
+ * @param delayMs - Debounce window duration in milliseconds (defaults to `ProviderBase.MetadataSnapshotSaveDebounceMs`)
39201
+ */
39202
+ ScheduleSaveLocalMetadataToStorage(delayMs = _ProviderBase.MetadataSnapshotSaveDebounceMs) {
39203
+ if (!this.LocalStorageProvider)
39204
+ return;
39205
+ if (!this.MetadataSnapshotPersistenceEnabled) {
39206
+ this.logMetadataSnapshotDisabledOnce();
39207
+ return;
39208
+ }
39209
+ if (this._inFlightMetadataSave) {
39210
+ this._hasPendingMetadataSaveWhileInFlight = true;
39211
+ return;
39212
+ }
39213
+ if (this._metadataSaveTimer) {
39214
+ clearTimeout(this._metadataSaveTimer);
39215
+ }
39216
+ this._metadataSaveTimer = setTimeout(() => {
39217
+ this._metadataSaveTimer = null;
39218
+ void this.triggerSerializedMetadataSave();
39219
+ }, delayMs);
39220
+ if (typeof this._metadataSaveTimer?.unref === "function") {
39221
+ this._metadataSaveTimer.unref();
39222
+ }
39223
+ }
39224
+ /**
39225
+ * Cancels any pending debounce timer and awaits `SaveLocalMetadataToStorage()` immediately
39226
+ * (or awaits any in-flight save plus trailing save), so tests and shutdown hooks can
39227
+ * deterministically flush pending writes.
39228
+ */
39229
+ async FlushPendingMetadataStorageSave() {
39230
+ if (this._metadataSaveTimer) {
39231
+ clearTimeout(this._metadataSaveTimer);
39232
+ this._metadataSaveTimer = null;
39233
+ this._hasPendingMetadataSaveWhileInFlight = true;
39234
+ }
39235
+ if (this._inFlightMetadataSave) {
39236
+ await this._inFlightMetadataSave;
39237
+ return;
39238
+ }
39239
+ if (this._hasPendingMetadataSaveWhileInFlight) {
39240
+ await this.triggerSerializedMetadataSave();
39241
+ }
39242
+ }
39243
+ /**
39244
+ * Clears any pending metadata snapshot save timer without saving.
39245
+ */
39246
+ CancelPendingMetadataStorageSave() {
39247
+ if (this._metadataSaveTimer) {
39248
+ clearTimeout(this._metadataSaveTimer);
39249
+ this._metadataSaveTimer = null;
39250
+ }
39251
+ this._hasPendingMetadataSaveWhileInFlight = false;
39252
+ }
39253
+ triggerSerializedMetadataSave() {
39254
+ if (!this._inFlightMetadataSave) {
39255
+ this._inFlightMetadataSave = this.executeSerializedMetadataSave().finally(() => {
39256
+ this._inFlightMetadataSave = null;
39257
+ });
39258
+ }
39259
+ return this._inFlightMetadataSave;
39260
+ }
39261
+ async executeSerializedMetadataSave() {
39262
+ do {
39263
+ this._hasPendingMetadataSaveWhileInFlight = false;
39264
+ try {
39265
+ await this.SaveLocalMetadataToStorage();
39266
+ } catch {
39267
+ }
39268
+ } while (this._hasPendingMetadataSaveWhileInFlight);
39269
+ }
39270
+ /**
39271
+ * Converts BaseInfo instances and nested objects into plain structured-cloneable
39272
+ * objects without JSON.stringify/JSON.parse, stripping functions and WeakRefs.
39273
+ */
39274
+ static toCloneableValue(val) {
39275
+ if (val == null || typeof val !== "object") {
39276
+ return val;
39277
+ }
39278
+ if (val instanceof Date || val instanceof RegExp || val instanceof ArrayBuffer || ArrayBuffer.isView(val)) {
39279
+ return val;
39280
+ }
39281
+ if (Array.isArray(val)) {
39282
+ const out2 = new Array(val.length);
39283
+ for (let i = 0; i < val.length; i++) {
39284
+ out2[i] = _ProviderBase.toCloneableValue(val[i]);
39285
+ }
39286
+ return out2;
39287
+ }
39288
+ const maybeToJson = val;
39289
+ if (typeof maybeToJson.toJSON === "function") {
39290
+ return _ProviderBase.toCloneableValue(maybeToJson.toJSON());
39291
+ }
39292
+ const out = {};
39293
+ for (const [k, v] of Object.entries(val)) {
39294
+ if (typeof v !== "function" && !(typeof WeakRef !== "undefined" && v instanceof WeakRef)) {
39295
+ out[k] = _ProviderBase.toCloneableValue(v);
39296
+ }
39297
+ }
39298
+ return out;
39299
+ }
37918
39300
  /**
37919
39301
  * Saves current metadata to local storage for caching.
37920
39302
  * Serializes both timestamps and full metadata collections.
@@ -37929,8 +39311,18 @@ var ProviderBase = class _ProviderBase {
37929
39311
  return;
37930
39312
  }
37931
39313
  const start = Date.now();
37932
- const jsonString = JSON.stringify(this._localMetadata);
37933
- const snapshot = await this.writeMetadataSnapshot(ls, jsonString);
39314
+ const dataKey = this.LocalStoragePrefix + _ProviderBase.localStorageAllMetadataKey;
39315
+ const formatKey = this.LocalStoragePrefix + _ProviderBase.localStorageFormatKey;
39316
+ let snapshot;
39317
+ if (typeof ls.SetObject === "function") {
39318
+ const cloneableMetadata = _ProviderBase.toCloneableValue(this._localMetadata);
39319
+ await ls.SetObject(dataKey, cloneableMetadata);
39320
+ await ls.SetItem(formatKey, "structured-clone");
39321
+ snapshot = { compressed: false, storedLength: 0 };
39322
+ } else {
39323
+ const jsonString = JSON.stringify(this._localMetadata);
39324
+ snapshot = await this.writeMetadataSnapshot(ls, jsonString);
39325
+ }
37934
39326
  if (this._metadataDatasetEntityNames?.size) {
37935
39327
  await ls.SetItem(this.LocalStoragePrefix + _ProviderBase.localStorageDatasetMembershipKey, JSON.stringify([...this._metadataDatasetEntityNames]));
37936
39328
  }
@@ -37940,7 +39332,7 @@ var ProviderBase = class _ProviderBase {
37940
39332
  const timestampsRaw = JSON.stringify(this._latestLocalMetadataTimestamps);
37941
39333
  await ls.SetItem(this.LocalStoragePrefix + _ProviderBase.localStorageTimestampsKey, timestampsRaw);
37942
39334
  this._storedTimestampsRaw = timestampsRaw;
37943
- this.logMetadataSaveComplete(Date.now() - start, jsonString.length, snapshot);
39335
+ this.logMetadataSaveComplete(Date.now() - start, snapshot.storedLength, snapshot);
37944
39336
  } catch (e) {
37945
39337
  LogError(`[Metadata Cache] SaveLocalMetadataToStorage failed: ${e instanceof Error ? e.message : String(e)}`);
37946
39338
  }
@@ -37981,6 +39373,11 @@ var ProviderBase = class _ProviderBase {
37981
39373
  message: `[Metadata Cache] Save complete: ${elapsedMs}ms, raw=${mb(rawLength)}MB, compressed=${mb(snapshot.storedLength)}MB (${ratio}%)`,
37982
39374
  verboseOnly: true
37983
39375
  });
39376
+ } else if (snapshot.storedLength === 0) {
39377
+ LogStatusEx({
39378
+ message: `[Metadata Cache] Save complete (structured-clone): ${elapsedMs}ms`,
39379
+ verboseOnly: true
39380
+ });
37984
39381
  } else {
37985
39382
  LogStatusEx({
37986
39383
  message: `[Metadata Cache] Save complete (uncompressed): ${elapsedMs}ms, size=${mb(rawLength)}MB`,
@@ -38273,32 +39670,65 @@ var TransactionGroupBase = class {
38273
39670
  }
38274
39671
  }
38275
39672
  this._status = "In Progress";
39673
+ let committed = false;
39674
+ let rolledBack = false;
39675
+ const rollbackGroupOnce = async () => {
39676
+ if (committed || rolledBack) {
39677
+ return;
39678
+ }
39679
+ rolledBack = true;
39680
+ try {
39681
+ await this.RollbackGroupTransaction();
39682
+ } catch (rollbackErr) {
39683
+ LogError(rollbackErr);
39684
+ }
39685
+ this.revertPendingTransactions();
39686
+ };
38276
39687
  try {
38277
39688
  await this.waitForPreprocessing();
38278
39689
  if (this._pendingTransactions.length > 0) {
38279
39690
  await this.preEvaluateCrossEntityPolicies();
38280
39691
  await this.BeginGroupTransaction();
38281
39692
  await this.preparePendingTransactions();
39693
+ if (!await this.checkPendingTransactions()) {
39694
+ await rollbackGroupOnce();
39695
+ await this.failRejectedGroup();
39696
+ return false;
39697
+ }
38282
39698
  const results = await this.HandleSubmit();
38283
39699
  const overallSuccess = results.every((r) => r.Success);
38284
- if (overallSuccess) {
38285
- await this.completeSubmittedResults(results, true);
38286
- await this.CommitGroupTransaction();
38287
- this._status = "Complete";
38288
- return true;
38289
- } else {
38290
- try {
38291
- await this.completeSubmittedResults(results, false);
38292
- } finally {
39700
+ const cache = LocalCacheManager.Instance;
39701
+ const owners = cache.IsInitialized ? this.entityProviders(results) : [];
39702
+ for (const owner of owners) {
39703
+ cache.BeginEntityEventBatch(owner);
39704
+ }
39705
+ let batchCommitted = false;
39706
+ try {
39707
+ if (overallSuccess) {
39708
+ await this.runInTransactionResults(results, true);
39709
+ await this.CommitGroupTransaction();
39710
+ committed = true;
39711
+ this.notifyTransactionStatus(true, results);
39712
+ batchCommitted = true;
39713
+ this._status = "Complete";
39714
+ return true;
39715
+ } else {
39716
+ await rollbackGroupOnce();
38293
39717
  try {
38294
- await this.RollbackGroupTransaction();
38295
- } catch (rollbackErr) {
38296
- LogError(rollbackErr);
39718
+ await this.runInTransactionResults(results, false);
39719
+ this.notifyTransactionStatus(false, results);
39720
+ } finally {
39721
+ this._status = "Failed";
38297
39722
  }
38298
- this.revertPendingTransactions();
38299
- this._status = "Failed";
39723
+ return false;
39724
+ }
39725
+ } catch (innerErr) {
39726
+ await rollbackGroupOnce();
39727
+ throw innerErr;
39728
+ } finally {
39729
+ for (const owner of owners) {
39730
+ await cache.EndEntityEventBatch(owner, batchCommitted);
38300
39731
  }
38301
- return false;
38302
39732
  }
38303
39733
  } else {
38304
39734
  LogStatus("No transactions to submit, switching status back to Pending");
@@ -38306,11 +39736,14 @@ var TransactionGroupBase = class {
38306
39736
  return true;
38307
39737
  }
38308
39738
  } catch (err) {
38309
- await this.RollbackGroupTransaction();
38310
- this.revertPendingTransactions();
39739
+ await rollbackGroupOnce();
38311
39740
  console.error(err);
38312
39741
  for (let i = 0; i < this._pendingTransactions.length; i++) {
38313
- await this._pendingTransactions[i].CallBack(err, false);
39742
+ try {
39743
+ await this._pendingTransactions[i].CallBack(err, false);
39744
+ } catch (cbErr) {
39745
+ LogError(cbErr);
39746
+ }
38314
39747
  }
38315
39748
  this.notifyTransactionStatus(false, void 0, err);
38316
39749
  this._status = "Failed";
@@ -38333,7 +39766,8 @@ var TransactionGroupBase = class {
38333
39766
  }
38334
39767
  /**
38335
39768
  * Optional hook for database-backed subclasses to commit the transaction opened in
38336
- * {@link BeginGroupTransaction} after {@link completeSubmittedResults} finishes.
39769
+ * {@link BeginGroupTransaction} after {@link runInTransactionResults} finishes and before
39770
+ * entity finalization notifications and cache batch flushing run.
38337
39771
  */
38338
39772
  async CommitGroupTransaction() {
38339
39773
  }
@@ -38344,60 +39778,32 @@ var TransactionGroupBase = class {
38344
39778
  async RollbackGroupTransaction() {
38345
39779
  }
38346
39780
  /**
38347
- * Finishes a submitted group: calls each result's callback, then notifies subscribers of the
38348
- * outcome. Each entity in the group listens for that notification and finalizes there, which
38349
- * is when it raises its save or delete event.
39781
+ * Runs each result's per-item callback and any registered in-transaction subtype AfterSave
39782
+ * hooks while the group transaction is still open (when `groupSucceeded === true`), or invokes
39783
+ * per-item failure callbacks after rollback (when `groupSucceeded === false`).
38350
39784
  *
38351
- * Both steps run inside an entity-event batch for every provider the group's entities save
38352
- * through, so the local cache applies the whole group to each cached result set once, rather
38353
- * than rewriting (and on a shared cache, republishing) each result set once per row. When the
38354
- * group did not fully succeed, or a callback throws, the batches close as failed and the
38355
- * affected result sets are invalidated instead of being given part of the group.
38356
- *
38357
- * A group submitted inside a provider transaction joins that transaction's open batch, which
38358
- * then applies when the transaction settles.
38359
- *
38360
- * `Submit()` waits for each batch to close, so its result now includes the cache maintenance
38361
- * (slot reads and writes, and any wait on a shared cache's cross-process lock) that per-row
38362
- * maintenance used to run without waiting. That is one wait per provider per group.
38363
- *
38364
- * Batches are keyed by provider, not by group. Any save raised for the same provider while the
38365
- * callbacks and notification run joins this group's batch, and is invalidated rather than
38366
- * applied if the group fails. In a browser every entity shares one provider, so an unrelated
38367
- * save in that window is affected. Invalidating is the safe direction: the slot reloads on its
38368
- * next read.
39785
+ * Entity finalization (`notifyTransactionStatus`) and `LocalCacheManager.EndEntityEventBatch`
39786
+ * intentionally run in {@link Submit} *after* {@link CommitGroupTransaction} /
39787
+ * {@link RollbackGroupTransaction} settles so database locks are never held across post-save
39788
+ * hooks or cross-process cache locks.
38369
39789
  */
38370
- async completeSubmittedResults(results, groupSucceeded) {
38371
- const cache = LocalCacheManager.Instance;
38372
- const owners = cache.IsInitialized ? this.entityProviders(results) : [];
38373
- for (const owner of owners) {
38374
- cache.BeginEntityEventBatch(owner);
39790
+ async runInTransactionResults(results, groupSucceeded) {
39791
+ for (const result of results) {
39792
+ const effectiveSuccess = groupSucceeded && result.Success;
39793
+ await result.Transaction.CallBack(result.Result, effectiveSuccess);
38375
39794
  }
38376
- let completed = false;
38377
- try {
39795
+ if (groupSucceeded) {
38378
39796
  for (const result of results) {
38379
- const effectiveSuccess = groupSucceeded && result.Success;
38380
- await result.Transaction.CallBack(result.Result, effectiveSuccess);
38381
- }
38382
- if (groupSucceeded) {
38383
- for (const result of results) {
38384
- if (!result.Success || result.Transaction.OperationType === "Delete") {
38385
- continue;
38386
- }
38387
- const hooks = this._inTransactionAfterSaveHooks.get(result.Transaction.BaseEntity);
38388
- if (hooks) {
38389
- for (const hook of hooks) {
38390
- await hook(result.Result);
38391
- }
39797
+ if (!result.Success || result.Transaction.OperationType === "Delete") {
39798
+ continue;
39799
+ }
39800
+ const hooks = this._inTransactionAfterSaveHooks.get(result.Transaction.BaseEntity);
39801
+ if (hooks) {
39802
+ for (const hook of hooks) {
39803
+ await hook(result.Result);
38392
39804
  }
38393
39805
  }
38394
39806
  }
38395
- this.notifyTransactionStatus(groupSucceeded, results);
38396
- completed = true;
38397
- } finally {
38398
- for (const owner of owners) {
38399
- await cache.EndEntityEventBatch(owner, groupSucceeded && completed);
38400
- }
38401
39807
  }
38402
39808
  }
38403
39809
  /** The distinct providers the entities behind `results` save through. */
@@ -38422,6 +39828,48 @@ var TransactionGroupBase = class {
38422
39828
  }
38423
39829
  }
38424
39830
  }
39831
+ /**
39832
+ * Runs every item's {@link TransactionItem.CheckBeforeSubmit} inside the open group transaction.
39833
+ * Every check runs even after one returns `false`, so each rejected item reports its own reason.
39834
+ * A check that throws stops here: the error (for example a lost connection or a deadlock during
39835
+ * the locked read) usually leaves the transaction unusable, so it goes to `Submit()`'s failure
39836
+ * path, which rolls back and fails every item with that error.
39837
+ *
39838
+ * @returns `true` when every check passed (or no item has one)
39839
+ */
39840
+ async checkPendingTransactions() {
39841
+ let allPassed = true;
39842
+ for (const pending of this._pendingTransactions) {
39843
+ if (pending.CheckBeforeSubmit && !await pending.CheckBeforeSubmit()) {
39844
+ allPassed = false;
39845
+ }
39846
+ }
39847
+ return allPassed;
39848
+ }
39849
+ /**
39850
+ * Fails every item of a group that a {@link TransactionItem.CheckBeforeSubmit} rejected before
39851
+ * any statement ran. Items whose check failed keep the reason the check recorded; the others
39852
+ * are told the group was rolled back because of another item.
39853
+ *
39854
+ * Each callback is called exactly once: one that throws is logged and the rest still run, so
39855
+ * the error never reaches `Submit()`'s outer failure path, which would call them all again.
39856
+ */
39857
+ async failRejectedGroup() {
39858
+ const reason = new Error("The transaction group was rolled back because another item in the group failed its pre-submit check.");
39859
+ const results = this._pendingTransactions.map((pending) => new TransactionResult(pending, reason, false));
39860
+ try {
39861
+ for (const result of results) {
39862
+ try {
39863
+ await result.Transaction.CallBack(result.Result, false);
39864
+ } catch (callbackError) {
39865
+ LogError(callbackError);
39866
+ }
39867
+ }
39868
+ this.notifyTransactionStatus(false, results);
39869
+ } finally {
39870
+ this._status = "Failed";
39871
+ }
39872
+ }
38425
39873
  /**
38426
39874
  * Runs per-item rollback cleanup hooks (such as reverting auto-assigned numbers on entities)
38427
39875
  * when the group transaction rolls back.
@@ -38518,12 +39966,141 @@ var TransactionGroupBase = class {
38518
39966
  }
38519
39967
  };
38520
39968
 
39969
+ // ../../MJCore/dist/generic/constraintErrorRedaction.js
39970
+ var REDACTED_CONSTRAINT_VALUES = "(values withheld)";
39971
+ var VALUE_LIST_RULES = [
39972
+ { Label: "The duplicate key value is ", Open: "(", Close: ")" },
39973
+ { Label: "Truncated value: ", Open: "'", Close: "'" },
39974
+ { Label: "Key (", Open: "(", Close: ")", KeyColumns: true, Suffixes: ["already exists", "is not present", "is still referenced"] },
39975
+ { Label: "Failing row contains ", Open: "(", Close: ")" }
39976
+ ];
39977
+ function RedactConstraintValues(message) {
39978
+ if (!message) {
39979
+ return message;
39980
+ }
39981
+ const lines = message.split("\n");
39982
+ const out = [];
39983
+ for (const line of lines) {
39984
+ const redacted = VALUE_LIST_RULES.reduce((current, rule) => redactLine(current, rule), line);
39985
+ const unclosedAt = findUnclosedValueList(redacted);
39986
+ if (unclosedAt >= 0) {
39987
+ out.push(redacted.slice(0, unclosedAt) + REDACTED_CONSTRAINT_VALUES);
39988
+ break;
39989
+ }
39990
+ out.push(redacted);
39991
+ }
39992
+ return out.join("\n");
39993
+ }
39994
+ function findUnclosedValueList(line) {
39995
+ let first = -1;
39996
+ for (const rule of VALUE_LIST_RULES) {
39997
+ let searchFrom = 0;
39998
+ while (searchFrom < line.length) {
39999
+ const labelAt = line.indexOf(rule.Label, searchFrom);
40000
+ if (labelAt < 0) {
40001
+ break;
40002
+ }
40003
+ const opened = findValueListOpen(line, labelAt, rule);
40004
+ if (opened.OpenAt >= 0 && !line.startsWith(REDACTED_CONSTRAINT_VALUES, opened.OpenAt)) {
40005
+ if (first < 0 || opened.OpenAt < first) {
40006
+ first = opened.OpenAt;
40007
+ }
40008
+ break;
40009
+ }
40010
+ searchFrom = opened.ResumeAt;
40011
+ }
40012
+ }
40013
+ return first;
40014
+ }
40015
+ function redactLine(line, rule) {
40016
+ const closeAt = findLastValueListClose(line, rule);
40017
+ let searchFrom = 0;
40018
+ while (closeAt >= 0 && searchFrom < closeAt) {
40019
+ const labelAt = line.indexOf(rule.Label, searchFrom);
40020
+ if (labelAt < 0 || labelAt >= closeAt) {
40021
+ return line;
40022
+ }
40023
+ const opened = findValueListOpen(line, labelAt, rule);
40024
+ if (opened.OpenAt >= 0 && opened.OpenAt < closeAt) {
40025
+ return line.slice(0, opened.OpenAt) + REDACTED_CONSTRAINT_VALUES + line.slice(closeAt + 1);
40026
+ }
40027
+ if (opened.OpenAt >= closeAt) {
40028
+ return line;
40029
+ }
40030
+ searchFrom = opened.ResumeAt;
40031
+ }
40032
+ return line;
40033
+ }
40034
+ function findValueListOpen(line, labelAt, rule) {
40035
+ const afterLabel = labelAt + rule.Label.length;
40036
+ if (rule.KeyColumns) {
40037
+ const columnsClose = line.indexOf(")=" + rule.Open, afterLabel);
40038
+ if (columnsClose < 0) {
40039
+ return { OpenAt: -1, ResumeAt: line.length };
40040
+ }
40041
+ return { OpenAt: columnsClose + 2, ResumeAt: columnsClose + 1 };
40042
+ }
40043
+ return { OpenAt: line.startsWith(rule.Open, afterLabel) ? afterLabel : -1, ResumeAt: afterLabel };
40044
+ }
40045
+ function findLastValueListClose(line, rule) {
40046
+ let closeAt = line.lastIndexOf(rule.Close);
40047
+ while (closeAt >= 0) {
40048
+ if (!rule.Suffixes || closeIsFollowedBySuffix(line, closeAt, rule.Suffixes)) {
40049
+ return closeAt;
40050
+ }
40051
+ closeAt = closeAt > 0 ? line.lastIndexOf(rule.Close, closeAt - 1) : -1;
40052
+ }
40053
+ return -1;
40054
+ }
40055
+ function closeIsFollowedBySuffix(line, closeAt, suffixes) {
40056
+ let at = closeAt + 1;
40057
+ while (at < line.length && /\s/.test(line[at])) {
40058
+ at++;
40059
+ }
40060
+ if (at === closeAt + 1) {
40061
+ return false;
40062
+ }
40063
+ return suffixes.some((suffix) => line.startsWith(suffix, at));
40064
+ }
40065
+ function SaveErrorMessageForUser(message, entityInfo, user) {
40066
+ if (!entityInfo?.FieldLevelSecurityApplies) {
40067
+ return message;
40068
+ }
40069
+ if (user && entityInfo.GetDeniedReadFields(user).size === 0) {
40070
+ return message;
40071
+ }
40072
+ return RedactConstraintValues(StripExecutedSQL(message));
40073
+ }
40074
+ function StripExecutedSQL(message) {
40075
+ if (!message) {
40076
+ return message;
40077
+ }
40078
+ let cut = message.length;
40079
+ const match = /^[ \t]*(?:Query|Parameters):/m.exec(message);
40080
+ if (match) {
40081
+ cut = match.index;
40082
+ }
40083
+ for (const leadIn of INLINE_SQL_LEAD_INS) {
40084
+ const at = message.indexOf(leadIn);
40085
+ if (at >= 0 && at + leadIn.length < cut) {
40086
+ cut = at + leadIn.length;
40087
+ }
40088
+ }
40089
+ return cut < message.length ? message.slice(0, cut).trimEnd() : message;
40090
+ }
40091
+ var INLINE_SQL_LEAD_INS = [
40092
+ "no rows returned from SQL:",
40093
+ "no MATCHING rows found within the database:"
40094
+ ];
40095
+
38521
40096
  // ../../MJCore/dist/generic/databaseProviderBase.js
38522
40097
  var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
38523
40098
  constructor() {
38524
40099
  super(...arguments);
38525
40100
  this._providerInstanceId = _DatabaseProviderBase._nextProviderInstanceId++;
38526
40101
  this._transactionEpoch = 0;
40102
+ this._detachedCoalescedTasks = /* @__PURE__ */ new Map();
40103
+ this._detachedCoalesceScheduled = false;
38527
40104
  this._dialect = null;
38528
40105
  }
38529
40106
  static {
@@ -38702,6 +40279,44 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
38702
40279
  CapturePostCommitToken() {
38703
40280
  return void 0;
38704
40281
  }
40282
+ /**
40283
+ * Enqueues post-commit work coalesced by `coalesceKey`.
40284
+ *
40285
+ * Outside an open transaction (on transactional providers) or on non-transactional providers,
40286
+ * registrations sharing a `coalesceKey` within the same microtask turn collapse per `mode`
40287
+ * (`'last-wins'` by default) before flushing once on a microtask. Inside a transaction,
40288
+ * transactional providers bind each registration to the caller's ambient frame (or `token`)
40289
+ * so rolled-back savepoints drop their entries cleanly while surviving entries coalesce at commit.
40290
+ */
40291
+ ScheduleAfterCommit(coalesceKey, task, description = "post-commit task", token, mode = "last-wins") {
40292
+ if (!coalesceKey) {
40293
+ this.RunAfterCommit(task, description, token);
40294
+ return;
40295
+ }
40296
+ this.EnqueueDetachedCoalescedTask(coalesceKey, task, description, mode);
40297
+ }
40298
+ /** Runs a detached post-commit task safely; transactional subclasses detach transaction affinity here. */
40299
+ ExecuteDetachedPostCommitTask(task, description) {
40300
+ void this.RunPostCommitTaskSafely(task, description);
40301
+ }
40302
+ /** Coalesces detached post-commit registrations onto a single microtask flush per turn. */
40303
+ EnqueueDetachedCoalescedTask(coalesceKey, task, description, mode) {
40304
+ if (mode !== "first-wins" || !this._detachedCoalescedTasks.has(coalesceKey)) {
40305
+ this._detachedCoalescedTasks.set(coalesceKey, { Task: task, Description: description });
40306
+ }
40307
+ if (this._detachedCoalesceScheduled) {
40308
+ return;
40309
+ }
40310
+ this._detachedCoalesceScheduled = true;
40311
+ queueMicrotask(() => {
40312
+ const entries = [...this._detachedCoalescedTasks.values()];
40313
+ this._detachedCoalescedTasks.clear();
40314
+ this._detachedCoalesceScheduled = false;
40315
+ for (const entry of entries) {
40316
+ this.ExecuteDetachedPostCommitTask(entry.Task, entry.Description);
40317
+ }
40318
+ });
40319
+ }
38705
40320
  /**
38706
40321
  * Await one post-commit task, logging (never rethrowing) its failure. Shared by the immediate
38707
40322
  * path of {@link RunAfterCommit} and by subclasses that drain a queue after commit.
@@ -39546,6 +41161,21 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
39546
41161
  async CheckUpdateConcurrency(_entity, _user, _options, _entityResult) {
39547
41162
  return true;
39548
41163
  }
41164
+ /**
41165
+ * The `TransactionGroup` counterpart of {@link CheckUpdateConcurrency}, called when an UPDATE is
41166
+ * queued into a group. The values the check compares (each changed field's baseline and new
41167
+ * value) are captured now, when the save's SQL is generated; the returned function performs the
41168
+ * locked row read and comparison later, inside the group's transaction before any of the
41169
+ * group's statements run.
41170
+ *
41171
+ * The returned function resolves `true` when the save may proceed, or `false` when it is
41172
+ * rejected (after populating `entityResult` the same way {@link CheckUpdateConcurrency} does).
41173
+ *
41174
+ * Default: `null`, meaning no check (and no extra work at submit).
41175
+ */
41176
+ PrepareQueuedUpdateConcurrencyCheck(_entity, _user, _options, _entityResult) {
41177
+ return null;
41178
+ }
39549
41179
  /**
39550
41180
  * Awaited immediately after the save SQL succeeds (inside direct `Save()`'s
39551
41181
  * {@link EntityTransactionScope} before commit, or inside a `TransactionGroup` item's completion
@@ -40133,6 +41763,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40133
41763
  }
40134
41764
  }
40135
41765
  }
41766
+ const preHookFieldSnapshot = !bReplay && bNewRecord ? this.CaptureEntityFieldSnapshot(entity) : null;
40136
41767
  if (!bReplay) {
40137
41768
  await this.OnBeforeSaveExecute(entity, user, options, saveContext);
40138
41769
  }
@@ -40154,12 +41785,15 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40154
41785
  }
40155
41786
  if (!bReplay) {
40156
41787
  if (bNewRecord) {
40157
- const postHookCreatePass = await this.CheckCreateRLS(entity, user);
40158
- if (!postHookCreatePass) {
40159
- entityResult.Success = false;
40160
- entityResult.EndedAt = /* @__PURE__ */ new Date();
40161
- entityResult.Message = `Access denied for new ${entity.EntityInfo.Name} record: a before-save hook produced field values that no longer pass row-level security`;
40162
- throw new Error(entityResult.Message);
41788
+ const fieldsMutated = preHookFieldSnapshot === null || this.HasEntityFieldStateMutated(entity, preHookFieldSnapshot);
41789
+ if (fieldsMutated) {
41790
+ const postHookCreatePass = await this.CheckCreateRLS(entity, user);
41791
+ if (!postHookCreatePass) {
41792
+ entityResult.Success = false;
41793
+ entityResult.EndedAt = /* @__PURE__ */ new Date();
41794
+ entityResult.Message = `Access denied for new ${entity.EntityInfo.Name} record: a before-save hook produced field values that no longer pass row-level security`;
41795
+ throw new Error(entityResult.Message);
41796
+ }
40163
41797
  }
40164
41798
  } else {
40165
41799
  const postImagePass = await this.CheckUpdateRLSPostImage(entity, user);
@@ -40184,9 +41818,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40184
41818
  return snapshot;
40185
41819
  };
40186
41820
  if (entity.TransactionGroup && !bReplay) {
40187
- if (!bNewRecord && !bReplay && (options?.ConcurrencyBaseline !== void 0 || options?.ConcurrencyCheck === "enforce")) {
40188
- LogWarning(`DatabaseProviderBase.Save: entity "${entity.EntityInfo.Name}" is queued in a TransactionGroup; per-save concurrency checking (ConcurrencyBaseline / ConcurrencyCheck: 'enforce') is bypassed for TransactionGroup items.`);
40189
- }
41821
+ const concurrencyCheck = bNewRecord ? null : this.PrepareQueuedUpdateConcurrencyCheck(entity, user, options, entityResult);
40190
41822
  let sqlDetails = await this.GenerateSaveSQL(entity, bNewRecord, user, options);
40191
41823
  const preSaveValues = capturePreSaveValues();
40192
41824
  entity.RaiseReadyForTransaction();
@@ -40242,7 +41874,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40242
41874
  } else {
40243
41875
  entityResult.Success = false;
40244
41876
  if (!entityResult.Message) {
40245
- entityResult.Message = transactionResult instanceof Error ? transactionResult.message : "Transaction Failed";
41877
+ entityResult.Message = transactionResult instanceof Error ? SaveErrorMessageForUser(transactionResult.message, entity.EntityInfo, user) : "Transaction Failed";
40246
41878
  }
40247
41879
  }
40248
41880
  });
@@ -40266,6 +41898,9 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40266
41898
  }
40267
41899
  };
40268
41900
  }
41901
+ if (concurrencyCheck) {
41902
+ txItem.CheckBeforeSubmit = concurrencyCheck;
41903
+ }
40269
41904
  entity.TransactionGroup.AddTransaction(txItem);
40270
41905
  return true;
40271
41906
  } else {
@@ -40377,7 +42012,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40377
42012
  }
40378
42013
  resumeRefresh();
40379
42014
  entityResult.EndedAt = /* @__PURE__ */ new Date();
40380
- entityResult.Message = e.message;
42015
+ entityResult.Message = SaveErrorMessageForUser(e.message, entity.EntityInfo, user);
40381
42016
  LogError(e);
40382
42017
  throw e;
40383
42018
  } finally {
@@ -40474,7 +42109,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40474
42109
  } else {
40475
42110
  entityResult.Success = false;
40476
42111
  if (!entityResult.Message) {
40477
- entityResult.Message = transactionResult instanceof Error ? transactionResult.message : "Transaction failed to commit";
42112
+ entityResult.Message = transactionResult instanceof Error ? SaveErrorMessageForUser(transactionResult.message, entity.EntityInfo, user) : "Transaction failed to commit";
40478
42113
  }
40479
42114
  }
40480
42115
  }));
@@ -40505,7 +42140,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40505
42140
  }
40506
42141
  } catch (e) {
40507
42142
  LogError(e);
40508
- entityResult.Message = e.message;
42143
+ entityResult.Message = SaveErrorMessageForUser(e.message, entity.EntityInfo, user);
40509
42144
  entityResult.Success = false;
40510
42145
  entityResult.EndedAt = /* @__PURE__ */ new Date();
40511
42146
  return false;
@@ -40515,6 +42150,99 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40515
42150
  }
40516
42151
  }
40517
42152
  }
42153
+ /**
42154
+ * Captures an immutable snapshot of an entity's fields (name, value, dirty status)
42155
+ * so we can detect whether before-save hooks mutated any field (including in-place
42156
+ * Date, Uint8Array, or JSON object mutations and case-sensitive string changes).
42157
+ */
42158
+ CaptureEntityFieldSnapshot(entity) {
42159
+ return entity.Fields.map((f) => this.snapshotSingleFieldState(f.Name, f.Value, f.Dirty));
42160
+ }
42161
+ snapshotSingleFieldState(name, val, dirty) {
42162
+ if (val === null) {
42163
+ return { Name: name, Kind: "primitive", PrimitiveValue: null, Dirty: dirty };
42164
+ }
42165
+ if (val === void 0) {
42166
+ return { Name: name, Kind: "primitive", PrimitiveValue: void 0, Dirty: dirty };
42167
+ }
42168
+ if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
42169
+ return { Name: name, Kind: "primitive", PrimitiveValue: val, Dirty: dirty };
42170
+ }
42171
+ if (val instanceof Date) {
42172
+ return { Name: name, Kind: "date", DateMs: val.getTime(), Dirty: dirty };
42173
+ }
42174
+ if (val instanceof Uint8Array) {
42175
+ return { Name: name, Kind: "bytes", BytesCopy: val.slice(), Dirty: dirty };
42176
+ }
42177
+ if (typeof val === "object") {
42178
+ try {
42179
+ return { Name: name, Kind: "json", SerializedJson: JSON.stringify(val), Dirty: dirty };
42180
+ } catch {
42181
+ return { Name: name, Kind: "uncomparable", Dirty: dirty };
42182
+ }
42183
+ }
42184
+ return { Name: name, Kind: "uncomparable", Dirty: dirty };
42185
+ }
42186
+ /**
42187
+ * Checks whether an entity's field values or dirty flags have mutated compared to a previous snapshot.
42188
+ */
42189
+ HasEntityFieldStateMutated(entity, snapshot) {
42190
+ const currentFields = entity.Fields;
42191
+ if (snapshot.length !== currentFields.length) {
42192
+ return true;
42193
+ }
42194
+ for (let i = 0; i < snapshot.length; i++) {
42195
+ const prev = snapshot[i];
42196
+ const curr = currentFields[i];
42197
+ if (prev.Name !== curr.Name || prev.Dirty !== curr.Dirty) {
42198
+ return true;
42199
+ }
42200
+ if (!this.matchesFieldSnapshot(prev, curr.Value)) {
42201
+ return true;
42202
+ }
42203
+ }
42204
+ return false;
42205
+ }
42206
+ matchesFieldSnapshot(prev, curr) {
42207
+ if (prev.Kind === "uncomparable") {
42208
+ return false;
42209
+ }
42210
+ if (prev.Kind === "primitive") {
42211
+ if (typeof prev.PrimitiveValue === "number" && typeof curr === "number" && Number.isNaN(prev.PrimitiveValue) && Number.isNaN(curr)) {
42212
+ return true;
42213
+ }
42214
+ return prev.PrimitiveValue === curr;
42215
+ }
42216
+ if (prev.Kind === "date") {
42217
+ if (!(curr instanceof Date)) {
42218
+ return false;
42219
+ }
42220
+ const currMs = curr.getTime();
42221
+ return Number.isNaN(prev.DateMs) && Number.isNaN(currMs) || prev.DateMs === currMs;
42222
+ }
42223
+ if (prev.Kind === "bytes") {
42224
+ if (!(curr instanceof Uint8Array) || !prev.BytesCopy || prev.BytesCopy.length !== curr.length) {
42225
+ return false;
42226
+ }
42227
+ for (let i = 0; i < curr.length; i++) {
42228
+ if (prev.BytesCopy[i] !== curr[i]) {
42229
+ return false;
42230
+ }
42231
+ }
42232
+ return true;
42233
+ }
42234
+ if (prev.Kind === "json") {
42235
+ if (curr === null || typeof curr !== "object" || curr instanceof Date || curr instanceof Uint8Array) {
42236
+ return false;
42237
+ }
42238
+ try {
42239
+ return prev.SerializedJson === JSON.stringify(curr);
42240
+ } catch {
42241
+ return false;
42242
+ }
42243
+ }
42244
+ return false;
42245
+ }
40518
42246
  /**************************************************************************/
40519
42247
  // END ---- Save/Delete Orchestration
40520
42248
  /**************************************************************************/
@@ -40695,8 +42423,11 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40695
42423
  * `DiffObjects`. Defaults to single quote.
40696
42424
  * @param cloneContext When non-null, populates `source='Clone'` and the
40697
42425
  * structured `changeContext` JSON payload.
42426
+ * @param skipFullRecordJSON When true (because the dialect builds `FullRecordJSON` in SQL
42427
+ * from the returned row), skips `EscapeQuotesInProperties` and `JSON.stringify` for
42428
+ * `fullRecordJSON`, returning `''`.
40698
42429
  */
40699
- BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext) {
42430
+ BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext, skipFullRecordJSON = false) {
40700
42431
  if (restoreContext && cloneContext) {
40701
42432
  throw new Error("BuildRecordChangePayload: both restoreContext and cloneContext were provided; an operation cannot be both a restore and a clone");
40702
42433
  }
@@ -40705,8 +42436,11 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40705
42436
  const changesKeys = changes ? Object.keys(changes) : [];
40706
42437
  if (changesKeys.length === 0 && !isCreateOrDelete)
40707
42438
  return null;
40708
- const dataForFullJSON = newData ?? oldData;
40709
- const fullRecordJSON = JSON.stringify(this.EscapeQuotesInProperties(dataForFullJSON, quoteToEscape));
42439
+ let fullRecordJSON = "";
42440
+ if (!skipFullRecordJSON) {
42441
+ const dataForFullJSON = newData ?? oldData;
42442
+ fullRecordJSON = JSON.stringify(this.EscapeQuotesInProperties(dataForFullJSON, quoteToEscape));
42443
+ }
40710
42444
  const changesJSON = changes !== null ? JSON.stringify(changes) : "";
40711
42445
  const changesDescription = oldData && newData ? this.CreateUserDescriptionOfChanges(changes) : !oldData ? "Record Created" : "Record Deleted";
40712
42446
  const source = restoreContext ? "Restore" : cloneContext ? "Clone" : "Internal";
@@ -44318,10 +46052,17 @@ var BaseEngine = class _BaseEngine extends BaseSingleton {
44318
46052
  * path performs, and enforces in this direction the same type-homogeneity invariant
44319
46053
  * {@link canUseImmediateMutation} enforces for the sibling mutation path.
44320
46054
  *
46055
+ * Server caches hold encrypted fields as ciphertext at rest, and only the provider's cache-read
46056
+ * path decrypts them. A payload carrying ciphertext is therefore never assigned: the reload it
46057
+ * falls back to reads the same slot through that path and gets the decrypted values.
46058
+ *
44321
46059
  * @returns the rows to assign, or null when they cannot be safely materialized (caller should
44322
46060
  * fall back to a full reload).
44323
46061
  */
44324
46062
  async materializeCacheEventRows(config, rows) {
46063
+ if (this.cacheEventRowsCarryCiphertext(config, rows)) {
46064
+ return null;
46065
+ }
44325
46066
  const effectiveResultType = config.ResultType || this.EngineDefaultResultType;
44326
46067
  if (effectiveResultType === "simple") {
44327
46068
  return rows;
@@ -44331,6 +46072,21 @@ var BaseEngine = class _BaseEngine extends BaseSingleton {
44331
46072
  }
44332
46073
  return TransformSimpleObjectToEntityObject(this.ProviderToUse, config.EntityName, rows, this._contextUser);
44333
46074
  }
46075
+ /**
46076
+ * True when any payload row holds ciphertext (`$ENC$…`) on one of the entity's encrypted
46077
+ * fields. Applying such a row would hand consumers the stored ciphertext as the field's value.
46078
+ */
46079
+ cacheEventRowsCarryCiphertext(config, rows) {
46080
+ const entityInfo = config.EntityName ? this.ProviderToUse?.EntityByName?.(config.EntityName) : void 0;
46081
+ const encryptedFields = entityInfo?.EncryptedFields ?? [];
46082
+ if (encryptedFields.length === 0) {
46083
+ return false;
46084
+ }
46085
+ return rows.some((row) => encryptedFields.some((field) => {
46086
+ const value = row[field.Name];
46087
+ return typeof value === "string" && IsValueEncrypted(value);
46088
+ }));
46089
+ }
44334
46090
  /**
44335
46091
  * Sets an expiration timer for a metadata property.
44336
46092
  * @param propertyName - The name of the property
@@ -44523,282 +46279,6 @@ var BaseEngine = class _BaseEngine extends BaseSingleton {
44523
46279
  }
44524
46280
  };
44525
46281
 
44526
- // ../../MJCore/dist/generic/typedQuery.js
44527
- var TypedQueryDriftError = class extends Error {
44528
- constructor(queryId, path, expectedSignature, actualSignature) {
44529
- super(`TypedQuery signature drift detected for '${path}' (QueryID: ${queryId}): generated wrapper expects '${expectedSignature}', but live query metadata has '${actualSignature}'. Re-run CodeGen to update the generated query wrapper.`);
44530
- this.name = "TypedQueryDriftError";
44531
- this.QueryID = queryId;
44532
- this.Path = path;
44533
- this.ExpectedSignature = expectedSignature;
44534
- this.ActualSignature = actualSignature;
44535
- }
44536
- };
44537
- var GLOBAL_STATE_KEY = "___MJ_TYPED_QUERY_STATE___";
44538
- function getGlobalTypedQueryState() {
44539
- const store = GetGlobalObjectStore();
44540
- if (!store) {
44541
- return { driftMode: "warn", warnedQueryIds: /* @__PURE__ */ new Set(), validateRows: null };
44542
- }
44543
- let state = store[GLOBAL_STATE_KEY];
44544
- if (!state) {
44545
- state = {
44546
- driftMode: "warn",
44547
- warnedQueryIds: /* @__PURE__ */ new Set(),
44548
- validateRows: null
44549
- };
44550
- store[GLOBAL_STATE_KEY] = state;
44551
- }
44552
- return state;
44553
- }
44554
- function isRowValidationEnabled() {
44555
- const state = getGlobalTypedQueryState();
44556
- if (state.validateRows !== null) {
44557
- return state.validateRows;
44558
- }
44559
- const g = globalThis;
44560
- return g.process?.env?.["MJ_TYPED_QUERY_VALIDATE"] === "1";
44561
- }
44562
- function ComputeTypedQuerySignature(source) {
44563
- const params = (source.Parameters ?? []).filter((p) => p != null && !p.IsServerSet && typeof p.Name === "string" && p.Name.trim().length > 0).map((p) => {
44564
- const name = p.Name.trim();
44565
- const type = normalizeSignatureParamType(p.Type);
44566
- const hasDefault = p.DefaultValue != null && String(p.DefaultValue).trim().length > 0;
44567
- const required = Boolean(p.IsRequired) && !hasDefault;
44568
- return {
44569
- sortKey: name.toLowerCase(),
44570
- entry: `${name}:${type}:${required ? "1" : "0"}`
44571
- };
44572
- }).sort((a, b) => a.sortKey < b.sortKey ? -1 : a.sortKey > b.sortKey ? 1 : 0).map((p) => p.entry);
44573
- const fields = (source.Fields ?? []).filter((f) => f != null && typeof f.Name === "string" && f.Name.trim().length > 0).map((f) => {
44574
- const name = f.Name.trim();
44575
- const sqlType = normalizeSignatureFieldType(f.SQLBaseType);
44576
- const inAllBranches = f.InAllBranchVariants !== false;
44577
- return {
44578
- sortKey: name.toLowerCase(),
44579
- entry: `${name}:${sqlType}:${inAllBranches ? "1" : "0"}`
44580
- };
44581
- }).sort((a, b) => a.sortKey < b.sortKey ? -1 : a.sortKey > b.sortKey ? 1 : 0).map((f) => f.entry);
44582
- const payload = `params=[${params.join(",")}];fields=[${fields.join(",")}]`;
44583
- return `sha256:${sha256Hex(payload)}`;
44584
- }
44585
- function normalizeSignatureParamType(rawType) {
44586
- const cleaned = (rawType ?? "unknown").trim().toLowerCase();
44587
- if (!cleaned)
44588
- return "unknown";
44589
- return cleaned;
44590
- }
44591
- function normalizeSignatureFieldType(rawSqlType) {
44592
- const raw = rawSqlType ?? "";
44593
- const parenIdx = raw.indexOf("(");
44594
- const cleaned = (parenIdx >= 0 ? raw.slice(0, parenIdx) : raw).trim().toLowerCase();
44595
- return cleaned || "unknown";
44596
- }
44597
- var TypedQuery = class {
44598
- constructor(definition) {
44599
- this.QueryID = definition.QueryID;
44600
- this.Path = definition.Path;
44601
- this.Signature = definition.Signature;
44602
- this.RowSchema = definition.RowSchema;
44603
- }
44604
- /**
44605
- * Executes the query with compile-time-checked parameters and returns a {@link TypedQueryResult}
44606
- * whose `Results` array is typed as `TRow[]`.
44607
- */
44608
- async Run(...args) {
44609
- const [params, options] = args;
44610
- this.checkSignatureDrift(options);
44611
- const { contextUser, provider, metadataProvider: _metadataProvider, driftMode: _driftMode, validateMaxRows, ...passThroughOptions } = options ?? {};
44612
- const runParams = {
44613
- ...passThroughOptions,
44614
- QueryID: this.QueryID,
44615
- Parameters: params ?? {}
44616
- };
44617
- const rq = new RunQuery(provider ?? null);
44618
- const rawResult = await rq.RunQuery(runParams, contextUser);
44619
- const typedResult = rawResult;
44620
- if (typedResult?.Success && Array.isArray(typedResult.Results) && this.RowSchema && isRowValidationEnabled()) {
44621
- const limit = Math.min(typedResult.Results.length, validateMaxRows ?? 10);
44622
- for (let i = 0; i < limit; i++) {
44623
- const parsed = this.RowSchema.safeParse(typedResult.Results[i]);
44624
- if (!parsed.success) {
44625
- LogWarning(`TypedQuery row validation warning for '${this.Path}' (row ${i}): ${parsed.error?.message ?? "schema mismatch"}`);
44626
- break;
44627
- }
44628
- }
44629
- }
44630
- return typedResult;
44631
- }
44632
- checkSignatureDrift(options) {
44633
- if (!this.Signature)
44634
- return;
44635
- const liveQuery = this.resolveLiveQueryInfo(options?.metadataProvider);
44636
- if (!liveQuery)
44637
- return;
44638
- const actualSignature = ComputeTypedQuerySignature(liveQuery);
44639
- if (actualSignature === this.Signature) {
44640
- return;
44641
- }
44642
- const state = getGlobalTypedQueryState();
44643
- const mode = options?.driftMode ?? state.driftMode;
44644
- if (mode === "throw") {
44645
- throw new TypedQueryDriftError(this.QueryID, this.Path, this.Signature, actualSignature);
44646
- }
44647
- const normalizedId = this.QueryID.trim().toLowerCase();
44648
- if (!state.warnedQueryIds.has(normalizedId)) {
44649
- state.warnedQueryIds.add(normalizedId);
44650
- LogWarning(`TypedQuery signature drift detected for '${this.Path}' (QueryID: ${this.QueryID}): expected ${this.Signature}, found ${actualSignature}. Re-run CodeGen to synchronize generated query types.`);
44651
- }
44652
- }
44653
- resolveLiveQueryInfo(explicitProvider) {
44654
- const provider = explicitProvider ?? Metadata.Provider;
44655
- const queries = provider?.Queries;
44656
- if (!Array.isArray(queries) || queries.length === 0) {
44657
- return void 0;
44658
- }
44659
- return queries.find((q) => UUIDsEqual(q.ID, this.QueryID));
44660
- }
44661
- };
44662
- function DefineTypedQuery(definition) {
44663
- return new TypedQuery(definition);
44664
- }
44665
- var SHA256_K = [
44666
- 1116352408,
44667
- 1899447441,
44668
- 3049323471,
44669
- 3921009573,
44670
- 961987163,
44671
- 1508970993,
44672
- 2453635748,
44673
- 2870763221,
44674
- 3624381080,
44675
- 310598401,
44676
- 607225278,
44677
- 1426881987,
44678
- 1925078388,
44679
- 2162078206,
44680
- 2614888103,
44681
- 3248222580,
44682
- 3835390401,
44683
- 4022224774,
44684
- 264347078,
44685
- 604807628,
44686
- 770255983,
44687
- 1249150122,
44688
- 1555081692,
44689
- 1996064986,
44690
- 2554220882,
44691
- 2821834349,
44692
- 2952996808,
44693
- 3210313671,
44694
- 3336571891,
44695
- 3584528711,
44696
- 113926993,
44697
- 338241895,
44698
- 666307205,
44699
- 773529912,
44700
- 1294757372,
44701
- 1396182291,
44702
- 1695183700,
44703
- 1986661051,
44704
- 2177026350,
44705
- 2456956037,
44706
- 2730485921,
44707
- 2820302411,
44708
- 3259730800,
44709
- 3345764771,
44710
- 3516065817,
44711
- 3600352804,
44712
- 4094571909,
44713
- 275423344,
44714
- 430227734,
44715
- 506948616,
44716
- 659060556,
44717
- 883997877,
44718
- 958139571,
44719
- 1322822218,
44720
- 1537002063,
44721
- 1747873779,
44722
- 1955562222,
44723
- 2024104815,
44724
- 2227730452,
44725
- 2361852424,
44726
- 2428436474,
44727
- 2756734187,
44728
- 3204031479,
44729
- 3329325298
44730
- ];
44731
- function rotr(n, x) {
44732
- return x >>> n | x << 32 - n;
44733
- }
44734
- function utf8Bytes(str) {
44735
- return Array.from(new TextEncoder().encode(str));
44736
- }
44737
- function sha256Hex(asciiOrUtf8) {
44738
- const bytes = utf8Bytes(asciiOrUtf8);
44739
- const bitLenHi = Math.floor(bytes.length * 8 / 4294967296);
44740
- const bitLenLo = bytes.length * 8 >>> 0;
44741
- bytes.push(128);
44742
- while (bytes.length % 64 !== 56) {
44743
- bytes.push(0);
44744
- }
44745
- bytes.push(bitLenHi >>> 24 & 255, bitLenHi >>> 16 & 255, bitLenHi >>> 8 & 255, bitLenHi & 255, bitLenLo >>> 24 & 255, bitLenLo >>> 16 & 255, bitLenLo >>> 8 & 255, bitLenLo & 255);
44746
- let h0 = 1779033703;
44747
- let h1 = 3144134277;
44748
- let h2 = 1013904242;
44749
- let h3 = 2773480762;
44750
- let h4 = 1359893119;
44751
- let h5 = 2600822924;
44752
- let h6 = 528734635;
44753
- let h7 = 1541459225;
44754
- const w = new Array(64);
44755
- for (let offset = 0; offset < bytes.length; offset += 64) {
44756
- for (let i = 0; i < 16; i++) {
44757
- const j = offset + i * 4;
44758
- w[i] = (bytes[j] << 24 | bytes[j + 1] << 16 | bytes[j + 2] << 8 | bytes[j + 3]) >>> 0;
44759
- }
44760
- for (let i = 16; i < 64; i++) {
44761
- const s0 = (rotr(7, w[i - 15]) ^ rotr(18, w[i - 15]) ^ w[i - 15] >>> 3) >>> 0;
44762
- const s1 = (rotr(17, w[i - 2]) ^ rotr(19, w[i - 2]) ^ w[i - 2] >>> 10) >>> 0;
44763
- w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
44764
- }
44765
- let a = h0;
44766
- let b = h1;
44767
- let c = h2;
44768
- let d = h3;
44769
- let e = h4;
44770
- let f = h5;
44771
- let g = h6;
44772
- let h = h7;
44773
- for (let i = 0; i < 64; i++) {
44774
- const S1 = (rotr(6, e) ^ rotr(11, e) ^ rotr(25, e)) >>> 0;
44775
- const ch = (e & f ^ ~e & g) >>> 0;
44776
- const temp1 = h + S1 + ch + SHA256_K[i] + w[i] >>> 0;
44777
- const S0 = (rotr(2, a) ^ rotr(13, a) ^ rotr(22, a)) >>> 0;
44778
- const maj = (a & b ^ a & c ^ b & c) >>> 0;
44779
- const temp2 = S0 + maj >>> 0;
44780
- h = g;
44781
- g = f;
44782
- f = e;
44783
- e = d + temp1 >>> 0;
44784
- d = c;
44785
- c = b;
44786
- b = a;
44787
- a = temp1 + temp2 >>> 0;
44788
- }
44789
- h0 = h0 + a >>> 0;
44790
- h1 = h1 + b >>> 0;
44791
- h2 = h2 + c >>> 0;
44792
- h3 = h3 + d >>> 0;
44793
- h4 = h4 + e >>> 0;
44794
- h5 = h5 + f >>> 0;
44795
- h6 = h6 + g >>> 0;
44796
- h7 = h7 + h >>> 0;
44797
- }
44798
- const toHex = (n) => (n >>> 0).toString(16).padStart(8, "0");
44799
- return `${toHex(h0)}${toHex(h1)}${toHex(h2)}${toHex(h3)}${toHex(h4)}${toHex(h5)}${toHex(h6)}${toHex(h7)}`;
44800
- }
44801
-
44802
46282
  // ../../MJCore/dist/generic/remoteEventRow.js
44803
46283
  async function ResolveEntityEventRow(event, provider, contextUser) {
44804
46284
  if (event.baseEntity) {
@@ -45807,62 +47287,6 @@ ${lines.join("\n")}`, verboseOnly: true });
45807
47287
  }
45808
47288
  };
45809
47289
 
45810
- // ../../MJCore/dist/generic/InMemoryLocalStorageProvider.js
45811
- var InMemoryLocalStorageProvider = class _InMemoryLocalStorageProvider {
45812
- constructor() {
45813
- this._storage = /* @__PURE__ */ new Map();
45814
- this.SharesReferences = true;
45815
- this.SupportsCrossProcessPersistence = false;
45816
- }
45817
- static {
45818
- this.DEFAULT_CATEGORY = "default";
45819
- }
45820
- /**
45821
- * Gets or creates a category map
45822
- */
45823
- getCategoryMap(category) {
45824
- const cat = category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY;
45825
- let categoryMap = this._storage.get(cat);
45826
- if (!categoryMap) {
45827
- categoryMap = /* @__PURE__ */ new Map();
45828
- this._storage.set(cat, categoryMap);
45829
- }
45830
- return categoryMap;
45831
- }
45832
- async GetItem(key, category) {
45833
- const categoryMap = this.getCategoryMap(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
45834
- const value = categoryMap.get(key);
45835
- return value === void 0 ? null : value;
45836
- }
45837
- async GetItems(keys, category) {
45838
- const out = /* @__PURE__ */ new Map();
45839
- if (keys.length === 0)
45840
- return out;
45841
- const categoryMap = this.getCategoryMap(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
45842
- for (const key of new Set(keys)) {
45843
- const value = categoryMap.get(key);
45844
- out.set(key, value === void 0 ? null : value);
45845
- }
45846
- return out;
45847
- }
45848
- async SetItem(key, value, category) {
45849
- const categoryMap = this.getCategoryMap(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
45850
- categoryMap.set(key, value);
45851
- }
45852
- async Remove(key, category) {
45853
- const categoryMap = this.getCategoryMap(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
45854
- categoryMap.delete(key);
45855
- }
45856
- async ClearCategory(category) {
45857
- const cat = category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY;
45858
- this._storage.delete(cat);
45859
- }
45860
- async GetCategoryKeys(category) {
45861
- const categoryMap = this._storage.get(category || _InMemoryLocalStorageProvider.DEFAULT_CATEGORY);
45862
- return categoryMap ? Array.from(categoryMap.keys()) : [];
45863
- }
45864
- };
45865
-
45866
47290
  // ../../MJCore/dist/generic/permissionInterfaces.js
45867
47291
  var __decorate5 = function(decorators, target, key, desc) {
45868
47292
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -46230,6 +47654,7 @@ export {
46230
47654
  GetDiagnosticContext,
46231
47655
  IsDiagnosticCaptureSuppressed,
46232
47656
  LogErrorEx,
47657
+ LogWarning,
46233
47658
  LogError,
46234
47659
  LogStatusEx,
46235
47660
  IsVerboseLoggingEnabled,
@@ -46263,14 +47688,18 @@ export {
46263
47688
  ProviderConfigDataBase,
46264
47689
  ProviderType,
46265
47690
  TelemetryManager,
47691
+ ProjectEntityValueRowsForUser,
46266
47692
  ComputeRemoteOperationContractFingerprint,
46267
47693
  BaseRemotableOperation,
46268
47694
  BaseEntityResult,
46269
47695
  BaseEntity,
47696
+ StripServerOnlyRunQueryParams,
46270
47697
  RunQuery,
47698
+ InMemoryLocalStorageProvider,
46271
47699
  LocalCacheManager,
46272
47700
  IsTransportError,
46273
47701
  FieldSecuritySQLGate,
47702
+ FindQueryContextTokens,
46274
47703
  ProviderBase,
46275
47704
  TransactionItem,
46276
47705
  TransactionResult,
@@ -46278,7 +47707,6 @@ export {
46278
47707
  WellKnownUserSource,
46279
47708
  PermissionConstrainedError,
46280
47709
  BaseEngine,
46281
- DefineTypedQuery,
46282
47710
  ResolveEntityEventRow,
46283
47711
  EntityEventRowIsFree,
46284
47712
  ResolveEntityEventKey,
@@ -46288,7 +47716,6 @@ export {
46288
47716
  getGraphQLTypeNameBase,
46289
47717
  RegisterForStartup,
46290
47718
  StartupManager,
46291
- InMemoryLocalStorageProvider,
46292
47719
  PermissionProviderBase,
46293
47720
  PermissionDeniedError,
46294
47721
  SetProvider,