@memberjunction/realtime-widget 6.3.0-edge.1 → 6.3.0-edge.3

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.
@@ -13,6 +13,7 @@ import {
13
13
  GetGlobalObjectStore,
14
14
  IndexByUUID,
15
15
  IsMemberOverridden,
16
+ IsPlainObject,
16
17
  IsValidBase64,
17
18
  IsValidUUID,
18
19
  IsValueEncrypted,
@@ -49,7 +50,7 @@ import {
49
50
  shareReplay,
50
51
  switchMap,
51
52
  uuidv4
52
- } from "./chunk-KHEWGJIZ.js";
53
+ } from "./chunk-CUZ32HGY.js";
53
54
 
54
55
  // ../../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
55
56
  var require_ms = __commonJS({
@@ -2945,6 +2946,14 @@ var SQLDialect = class extends QueryDialect {
2945
2946
  get MaxColumnCount() {
2946
2947
  return this.DDL.MaxColumnCount;
2947
2948
  }
2949
+ /**
2950
+ * Maximum UTF-16 code units allowed in object/column comment values, or `null` when effectively
2951
+ * unbounded. SQL Server caps `sp_addextendedproperty`'s `sql_variant` `@value` at 7,500 bytes
2952
+ * (3,700 UTF-16 code units with margin); PostgreSQL `COMMENT ON` (`text`) has no practical cap.
2953
+ */
2954
+ get MaxCommentLength() {
2955
+ return this.DDL.MaxCommentLength;
2956
+ }
2948
2957
  /**
2949
2958
  * Minimum in-row byte footprint of a column of the given raw SQL type. Off-row-capable
2950
2959
  * variable-length / LOB types contribute only their in-row pointer; fixed-length types contribute
@@ -3129,18 +3138,25 @@ var SQLDialect = class extends QueryDialect {
3129
3138
  return this.DDL.BatchSeparator();
3130
3139
  }
3131
3140
  /**
3132
- * Splits an oversized SQL batch into individual statements on `;`+EOL
3141
+ * Splits a SQL script on standalone batch separator lines (e.g., `GO` on SQL Server) while
3142
+ * respecting string literals, quoted identifiers, comments, and dollar-quoted blocks per
3143
+ * {@link Lexical} so a separator word inside a description, identifier, or comment never
3144
+ * splits mid-token. On dialects with no batch separator (PostgreSQL), returns the non-empty
3145
+ * script as a single batch.
3146
+ */
3147
+ SplitBatches(sql) {
3148
+ return this.DDL.SplitBatches(sql);
3149
+ }
3150
+ /**
3151
+ * Splits an oversized SQL batch into individual statements on top-level `;`+EOL
3133
3152
  * boundaries so a caller (e.g. the RSU migration executor) can re-group
3134
3153
  * them into smaller chunks that each fit under a client request timeout.
3135
3154
  *
3136
- * Base implementation = the naive `split(/;\s*\n/g)` semantics: split on a
3137
- * `;` followed by optional inline whitespace and a newline, trim each
3138
- * fragment, drop empties, and ensure each returned statement ends with `;`.
3139
- * This is correct for SQL Server (no dollar-quoted blocks).
3140
- *
3141
- * PostgreSQL overrides this with a dollar-quote-aware split that never
3142
- * tears apart `DO $$ … $$` / `$tag$ … $tag$` blocks whose bodies
3143
- * legitimately contain `;`+newline.
3155
+ * Respects string literals (`'...'` with `''` escapes, plus PostgreSQL `E'...'` escape
3156
+ * strings and `$$…$$` / `$tag$…$tag$` dollar-quoted blocks), quoted identifiers (`"..."`,
3157
+ * `[...]`), and line/block comments per {@link Lexical} so `;`+newline inside descriptions,
3158
+ * identifiers, defaults, or procedural bodies never splits mid-statement. Each returned
3159
+ * statement ends with `;`.
3144
3160
  */
3145
3161
  SplitStatements(batch) {
3146
3162
  return this.DDL.SplitStatements(batch);
@@ -3738,8 +3754,9 @@ var AnsiQueryDialect = class extends QueryDialect {
3738
3754
 
3739
3755
  // ../../SQLDialect/dist/dialects/baseSchemaDDL.js
3740
3756
  var BaseSchemaDDL = class {
3741
- constructor(Writer) {
3757
+ constructor(Writer, Lexical = ANSI_LEXICAL) {
3742
3758
  this.Writer = Writer;
3759
+ this.Lexical = Lexical;
3743
3760
  }
3744
3761
  /** No practical declare-time cap on an index key string; a platform overrides it where one exists. */
3745
3762
  get MaxKeyStringLength() {
@@ -3753,6 +3770,19 @@ var BaseSchemaDDL = class {
3753
3770
  get MaxColumnCount() {
3754
3771
  return null;
3755
3772
  }
3773
+ /** No comment-length cap by default (override where the platform enforces one, e.g. SQL Server `sql_variant`). */
3774
+ get MaxCommentLength() {
3775
+ return null;
3776
+ }
3777
+ /**
3778
+ * Strip NUL bytes, cap to {@link MaxCommentLength} UTF-16 code units (surrogate-pair safe)
3779
+ * when the dialect declares a limit, and escape single quotes for SQL string literals.
3780
+ */
3781
+ EscapeComment(comment) {
3782
+ const withoutNulls = comment.replace(/\0/g, "");
3783
+ const capped = this.MaxCommentLength != null ? this.truncateComment(withoutNulls, this.MaxCommentLength) : withoutNulls;
3784
+ return EscapeSQLString(capped);
3785
+ }
3756
3786
  /** A conservative off-row-pointer floor of 24 bytes. */
3757
3787
  EstimateInRowBytes(_rawSqlType) {
3758
3788
  return 24;
@@ -3771,11 +3801,255 @@ var BaseSchemaDDL = class {
3771
3801
  return rawSqlType;
3772
3802
  }
3773
3803
  /**
3774
- * Splits on a `;` followed by optional inline whitespace and a newline, trims each fragment,
3775
- * drops empties, and ends each statement with `;`.
3804
+ * Splits a SQL script on standalone batch separator lines (e.g. `GO` on SQL Server) while
3805
+ * skipping strings, quoted identifiers, comments, and dollar-quoted blocks per {@link Lexical}.
3806
+ * Returns the non-empty script as a single batch when the dialect defines no batch separator.
3807
+ */
3808
+ SplitBatches(sql) {
3809
+ const separator = this.BatchSeparator().trim();
3810
+ if (separator.length === 0) {
3811
+ const trimmed = sql.trim();
3812
+ return trimmed.length > 0 ? [trimmed] : [];
3813
+ }
3814
+ return this.splitOnSeparatorLines(sql, separator);
3815
+ }
3816
+ /**
3817
+ * Splits an oversized SQL batch into individual statements on top-level `;` + end-of-line
3818
+ * boundaries, skipping string literals, quoted identifiers, line/block comments, and
3819
+ * dollar-quoted blocks per {@link Lexical}. Trims each fragment, drops empties, and ensures
3820
+ * every returned statement ends with `;`.
3776
3821
  */
3777
3822
  SplitStatements(batch) {
3778
- return batch.split(/;\s*\n/g).map((s) => s.trim()).filter((s) => s.length > 0).map((s) => s.endsWith(";") ? s : s + ";");
3823
+ const statements = [];
3824
+ let stmtStart = 0;
3825
+ let i = 0;
3826
+ while (i < batch.length) {
3827
+ const tokenEnd = this.scanProtectedTokenEnd(batch, i);
3828
+ if (tokenEnd !== null) {
3829
+ i = tokenEnd;
3830
+ continue;
3831
+ }
3832
+ if (batch[i] === ";") {
3833
+ const boundaryEnd = this.findSemicolonNewlineEnd(batch, i);
3834
+ if (boundaryEnd !== null) {
3835
+ const trimmed = batch.slice(stmtStart, i).trim();
3836
+ if (trimmed.length > 0)
3837
+ statements.push(`${trimmed};`);
3838
+ stmtStart = boundaryEnd;
3839
+ i = boundaryEnd;
3840
+ continue;
3841
+ }
3842
+ }
3843
+ i++;
3844
+ }
3845
+ const tail = batch.slice(stmtStart).trim();
3846
+ if (tail.length > 0) {
3847
+ statements.push(tail.endsWith(";") ? tail : `${tail};`);
3848
+ }
3849
+ return statements;
3850
+ }
3851
+ splitOnSeparatorLines(sql, separator) {
3852
+ const batches = [];
3853
+ let batchStart = 0;
3854
+ let i = 0;
3855
+ let atLineStart = true;
3856
+ while (i < sql.length) {
3857
+ if (atLineStart) {
3858
+ const sepEnd = this.matchBatchSeparatorLine(sql, i, separator);
3859
+ if (sepEnd !== null) {
3860
+ const trimmed = sql.slice(batchStart, i).trim();
3861
+ if (trimmed.length > 0)
3862
+ batches.push(trimmed);
3863
+ batchStart = sepEnd;
3864
+ i = sepEnd;
3865
+ atLineStart = true;
3866
+ continue;
3867
+ }
3868
+ }
3869
+ const tokenEnd = this.scanProtectedTokenEnd(sql, i);
3870
+ if (tokenEnd !== null) {
3871
+ atLineStart = sql[tokenEnd - 1] === "\n";
3872
+ i = tokenEnd;
3873
+ continue;
3874
+ }
3875
+ atLineStart = sql[i] === "\n";
3876
+ i++;
3877
+ }
3878
+ const tail = sql.slice(batchStart).trim();
3879
+ if (tail.length > 0)
3880
+ batches.push(tail);
3881
+ return batches;
3882
+ }
3883
+ scanProtectedTokenEnd(sql, i) {
3884
+ const lineCommentEnd = this.scanLineCommentEnd(sql, i);
3885
+ if (lineCommentEnd !== null)
3886
+ return lineCommentEnd;
3887
+ if (sql[i] === "/" && sql[i + 1] === "*") {
3888
+ return this.scanBlockCommentEnd(sql, i);
3889
+ }
3890
+ const quotedIdEnd = this.scanQuotedIdentifierEnd(sql, i);
3891
+ if (quotedIdEnd !== null)
3892
+ return quotedIdEnd;
3893
+ const stringEnd = this.scanStringLiteralEnd(sql, i);
3894
+ if (stringEnd !== null)
3895
+ return stringEnd;
3896
+ if (this.Lexical.DollarQuotedStrings !== "none" && sql[i] === "$") {
3897
+ return this.scanDollarQuotedEnd(sql, i);
3898
+ }
3899
+ return null;
3900
+ }
3901
+ scanLineCommentEnd(sql, start) {
3902
+ for (const form of this.Lexical.LineComments) {
3903
+ if (!sql.startsWith(form.Opener, start))
3904
+ continue;
3905
+ if (form.RequiresWhitespaceAfter) {
3906
+ const nextCode = sql.charCodeAt(start + form.Opener.length);
3907
+ if (!Number.isNaN(nextCode) && nextCode > 32 && nextCode !== 127)
3908
+ continue;
3909
+ }
3910
+ let i = start + form.Opener.length;
3911
+ while (i < sql.length && sql[i] !== "\n")
3912
+ i++;
3913
+ return i < sql.length ? i + 1 : i;
3914
+ }
3915
+ return null;
3916
+ }
3917
+ scanBlockCommentEnd(sql, start) {
3918
+ const nested = this.Lexical.BlockComments.Nested;
3919
+ let i = start + 2;
3920
+ let depth = 1;
3921
+ while (i < sql.length && depth > 0) {
3922
+ if (nested && sql[i] === "/" && sql[i + 1] === "*") {
3923
+ depth++;
3924
+ i += 2;
3925
+ } else if (sql[i] === "*" && sql[i + 1] === "/") {
3926
+ depth--;
3927
+ i += 2;
3928
+ } else {
3929
+ i++;
3930
+ }
3931
+ }
3932
+ return i;
3933
+ }
3934
+ scanQuotedIdentifierEnd(sql, start) {
3935
+ const ch = sql[start];
3936
+ for (const form of this.Lexical.IdentifierQuotes) {
3937
+ if (ch === form.Open) {
3938
+ return this.scanDelimitedSpan(sql, start, form.Close, form.DoubledCloseEscape, false);
3939
+ }
3940
+ }
3941
+ return null;
3942
+ }
3943
+ scanStringLiteralEnd(sql, quoteIndex) {
3944
+ const form = this.matchStringLiteralForm(sql, quoteIndex, sql[quoteIndex]);
3945
+ if (!form)
3946
+ return null;
3947
+ return this.scanDelimitedSpan(sql, quoteIndex, form.Quote, form.DoubledQuoteEscape, form.BackslashEscape);
3948
+ }
3949
+ matchStringLiteralForm(sql, quoteIndex, quoteChar) {
3950
+ let bestForm = null;
3951
+ let bestPrefixLen = -1;
3952
+ for (const form of this.Lexical.StringLiterals) {
3953
+ if (form.Quote !== quoteChar)
3954
+ continue;
3955
+ for (const prefix of form.Prefixes) {
3956
+ if (prefix.length > bestPrefixLen && this.hasPrefixBefore(sql, quoteIndex, prefix)) {
3957
+ bestPrefixLen = prefix.length;
3958
+ bestForm = form;
3959
+ }
3960
+ }
3961
+ }
3962
+ return bestForm;
3963
+ }
3964
+ hasPrefixBefore(sql, quoteIndex, prefix) {
3965
+ if (prefix.length === 0)
3966
+ return true;
3967
+ const start = quoteIndex - prefix.length;
3968
+ if (start < 0)
3969
+ return false;
3970
+ if (sql.slice(start, quoteIndex).toUpperCase() !== prefix.toUpperCase())
3971
+ return false;
3972
+ return start === 0 || !this.isIdentifierContinueChar(sql[start - 1]);
3973
+ }
3974
+ scanDelimitedSpan(sql, openIndex, closeChar, doubledCloseEscape, backslashEscape) {
3975
+ let i = openIndex + 1;
3976
+ while (i < sql.length) {
3977
+ if (backslashEscape && sql[i] === "\\" && i + 1 < sql.length) {
3978
+ i += 2;
3979
+ continue;
3980
+ }
3981
+ if (sql[i] === closeChar) {
3982
+ if (doubledCloseEscape && sql[i + 1] === closeChar) {
3983
+ i += 2;
3984
+ continue;
3985
+ }
3986
+ return i + 1;
3987
+ }
3988
+ i++;
3989
+ }
3990
+ return sql.length;
3991
+ }
3992
+ scanDollarQuotedEnd(sql, start) {
3993
+ if (start > 0 && this.isIdentifierContinueChar(sql[start - 1]))
3994
+ return null;
3995
+ let j = start + 1;
3996
+ if (this.Lexical.DollarQuotedStrings === "tagged" && j < sql.length && sql[j] !== "$") {
3997
+ if (!this.isTagStartChar(sql[j]))
3998
+ return null;
3999
+ j++;
4000
+ while (j < sql.length && this.isTagContinueChar(sql[j]))
4001
+ j++;
4002
+ }
4003
+ if (j >= sql.length || sql[j] !== "$")
4004
+ return null;
4005
+ const tag = sql.slice(start, j + 1);
4006
+ const closeIdx = sql.indexOf(tag, j + 1);
4007
+ return closeIdx === -1 ? sql.length : closeIdx + tag.length;
4008
+ }
4009
+ findSemicolonNewlineEnd(sql, semiIndex) {
4010
+ let j = semiIndex + 1;
4011
+ while (j < sql.length && (sql[j] === " " || sql[j] === " " || sql[j] === "\r"))
4012
+ j++;
4013
+ return j < sql.length && sql[j] === "\n" ? j + 1 : null;
4014
+ }
4015
+ matchBatchSeparatorLine(sql, lineStart, separator) {
4016
+ let j = lineStart;
4017
+ while (j < sql.length && (sql[j] === " " || sql[j] === " "))
4018
+ j++;
4019
+ if (sql.slice(j, j + separator.length).toUpperCase() !== separator.toUpperCase()) {
4020
+ return null;
4021
+ }
4022
+ j += separator.length;
4023
+ while (j < sql.length && (sql[j] === " " || sql[j] === " " || sql[j] === "\r"))
4024
+ j++;
4025
+ if (j === sql.length)
4026
+ return j;
4027
+ return sql[j] === "\n" ? j + 1 : null;
4028
+ }
4029
+ isTagStartChar(ch) {
4030
+ const code = ch.charCodeAt(0);
4031
+ return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_" || code >= 128;
4032
+ }
4033
+ isTagContinueChar(ch) {
4034
+ return this.isTagStartChar(ch) || ch >= "0" && ch <= "9";
4035
+ }
4036
+ isIdentifierContinueChar(ch) {
4037
+ return this.isTagContinueChar(ch) || ch === "$";
4038
+ }
4039
+ truncateComment(value, maxChars) {
4040
+ if (value.length <= maxChars) {
4041
+ return value;
4042
+ }
4043
+ const ellipsis = "...";
4044
+ if (maxChars <= ellipsis.length) {
4045
+ return value.slice(0, Math.max(0, maxChars));
4046
+ }
4047
+ let cut = maxChars - ellipsis.length;
4048
+ const lastCode = value.charCodeAt(cut - 1);
4049
+ if (lastCode >= 55296 && lastCode <= 56319) {
4050
+ cut--;
4051
+ }
4052
+ return value.slice(0, cut) + ellipsis;
3779
4053
  }
3780
4054
  /** `CREATE TABLE IF NOT EXISTS <fullTable> (...);` as a single statement. */
3781
4055
  CreateTableIfAbsent(fullTable, columnsBody) {
@@ -3924,6 +4198,15 @@ SELECT @@ROWCOUNT AS ${this.Writer.QuoteColumnAlias(alias)}`;
3924
4198
  get MaxColumnCount() {
3925
4199
  return 1024;
3926
4200
  }
4201
+ /**
4202
+ * SQL Server `sp_addextendedproperty` types `@value` as `sql_variant`, which caps payloads at
4203
+ * 7,500 bytes (3,750 UTF-16 code units for `N'...'` literals; >4,000 code units also promotes
4204
+ * the literal to `nvarchar(max)`, which SQL Server refuses to implicitly convert to `sql_variant`).
4205
+ * Cap at 3,700 UTF-16 code units (7,400 bytes) to stay safely under both limits.
4206
+ */
4207
+ get MaxCommentLength() {
4208
+ return 3700;
4209
+ }
3927
4210
  /**
3928
4211
  * Minimum in-row byte footprint of a column. Off-row-capable variable-length / LOB types
3929
4212
  * (incl. `(N)VARCHAR(MAX)`) contribute only a 24-byte in-row pointer; fixed-length types
@@ -4128,14 +4411,14 @@ GO`;
4128
4411
  ALTER COLUMN [${options.columnName}] ${options.newType} ${nullable};`;
4129
4412
  }
4130
4413
  CommentOnColumn(schema, table, column, comment) {
4131
- const escaped = comment.replace(/'/g, "''");
4414
+ const escaped = this.EscapeComment(comment);
4132
4415
  return [
4133
4416
  `EXEC sp_addextendedproperty`,
4134
4417
  ` @name = N'MS_Description',`,
4135
4418
  ` @value = N'${escaped}',`,
4136
- ` @level0type = N'SCHEMA', @level0name = '${schema}',`,
4137
- ` @level1type = N'TABLE', @level1name = '${table}',`,
4138
- ` @level2type = N'COLUMN', @level2name = '${column}';`
4419
+ ` @level0type = N'SCHEMA', @level0name = ${this.escapeUnicodeLiteral(schema)},`,
4420
+ ` @level1type = N'TABLE', @level1name = ${this.escapeUnicodeLiteral(table)},`,
4421
+ ` @level2type = N'COLUMN', @level2name = ${this.escapeUnicodeLiteral(column)};`
4139
4422
  ].join("\n");
4140
4423
  }
4141
4424
  FallbackType() {
@@ -4168,14 +4451,14 @@ GO`;
4168
4451
  return `GRANT ${permission} ON [${schema}].[${object}] TO [${role}]`;
4169
4452
  }
4170
4453
  CommentOnObject(objectType, schema, name, comment) {
4171
- const escapedComment = comment.replace(/'/g, "''");
4454
+ const escapedComment = this.EscapeComment(comment);
4172
4455
  const level1Type = this.objectTypeToLevel1Type(objectType);
4173
4456
  return [
4174
4457
  `EXEC sp_addextendedproperty`,
4175
4458
  ` @name = N'MS_Description',`,
4176
4459
  ` @value = N'${escapedComment}',`,
4177
- ` @level0type = N'SCHEMA', @level0name = N'${schema}',`,
4178
- ` @level1type = N'${level1Type}', @level1name = N'${name}'`
4460
+ ` @level0type = N'SCHEMA', @level0name = ${this.escapeUnicodeLiteral(schema)},`,
4461
+ ` @level1type = ${this.escapeUnicodeLiteral(level1Type)}, @level1name = ${this.escapeUnicodeLiteral(name)}`
4179
4462
  ].join("\n");
4180
4463
  }
4181
4464
  CreateTableIfAbsent(fullTable, columnsBody) {
@@ -4205,13 +4488,13 @@ ${this.IndexDDL(options)};`;
4205
4488
  CommentOnObjectIfAbsent(objectType, schema, name, comment) {
4206
4489
  const level1Type = this.objectTypeToLevel1Type(objectType);
4207
4490
  return [
4208
- `IF NOT EXISTS (SELECT 1 FROM sys.fn_listextendedproperty(N'MS_Description', N'SCHEMA', N'${schema}', N'${level1Type}', N'${name}', NULL, NULL))`,
4491
+ `IF NOT EXISTS (SELECT 1 FROM sys.fn_listextendedproperty(N'MS_Description', N'SCHEMA', ${this.escapeUnicodeLiteral(schema)}, ${this.escapeUnicodeLiteral(level1Type)}, ${this.escapeUnicodeLiteral(name)}, NULL, NULL))`,
4209
4492
  `${this.CommentOnObject(objectType, schema, name, comment)};`
4210
4493
  ].join("\n");
4211
4494
  }
4212
4495
  CommentOnColumnIfAbsent(schema, table, column, comment) {
4213
4496
  return [
4214
- `IF NOT EXISTS (SELECT 1 FROM sys.fn_listextendedproperty(N'MS_Description', N'SCHEMA', N'${schema}', N'TABLE', N'${table}', N'COLUMN', N'${column}'))`,
4497
+ `IF NOT EXISTS (SELECT 1 FROM sys.fn_listextendedproperty(N'MS_Description', N'SCHEMA', ${this.escapeUnicodeLiteral(schema)}, N'TABLE', ${this.escapeUnicodeLiteral(table)}, N'COLUMN', ${this.escapeUnicodeLiteral(column)}))`,
4215
4498
  this.CommentOnColumn(schema, table, column, comment)
4216
4499
  ].join("\n");
4217
4500
  }
@@ -4322,6 +4605,9 @@ COMMIT TRANSACTION;`;
4322
4605
  }
4323
4606
  return "NVARCHAR(255)";
4324
4607
  }
4608
+ escapeUnicodeLiteral(value) {
4609
+ return `N'${EscapeSQLString(value)}'`;
4610
+ }
4325
4611
  objectTypeToLevel1Type(objectType) {
4326
4612
  switch (objectType.toUpperCase()) {
4327
4613
  case "TABLE":
@@ -4520,7 +4806,7 @@ var SQLServerDialect = class extends SQLDialect {
4520
4806
  super(...arguments);
4521
4807
  this.writer = Object.freeze(new SQLServerWriter());
4522
4808
  this.binding = Object.freeze(new SQLServerBinding());
4523
- this.ddl = Object.freeze(new SQLServerSchemaDDL(this.writer));
4809
+ this.ddl = Object.freeze(new SQLServerSchemaDDL(this.writer, SQL_SERVER_LEXICAL));
4524
4810
  }
4525
4811
  get PlatformKey() {
4526
4812
  return "sqlserver";
@@ -4775,59 +5061,6 @@ SELECT COUNT(*)::int AS ${this.Writer.QuoteColumnAlias(alias)} FROM ${this.Write
4775
5061
  RollbackToSavepointSQL(name) {
4776
5062
  return `ROLLBACK TO SAVEPOINT ${name}`;
4777
5063
  }
4778
- /**
4779
- * Splits an oversized SQL batch into individual statements on `;`+EOL
4780
- * boundaries — but NEVER inside a PostgreSQL dollar-quoted block
4781
- * (`$$ … $$` or `$tag$ … $tag$`), whose body legitimately contains
4782
- * `;`+newline (DO blocks, PL/pgSQL function bodies, the integration
4783
- * view-drop guard `$mj_dropviews$`). A naive `split(/;\s*\n/g)` tears
4784
- * those apart. Outside dollar blocks the boundary semantics mirror the
4785
- * base `split(/;\s*\n/g)` (a `;` then optional inline whitespace then a
4786
- * newline). Each returned statement ends with `;`.
4787
- */
4788
- SplitStatements(batch) {
4789
- const statements = [];
4790
- let current = "";
4791
- let dollarTag = null;
4792
- const isTagChar = (c) => c >= "A" && c <= "Z" || c >= "a" && c <= "z" || c >= "0" && c <= "9" || c === "_";
4793
- for (let i = 0; i < batch.length; i++) {
4794
- const ch = batch[i];
4795
- if (ch === "$") {
4796
- let j = i + 1;
4797
- while (j < batch.length && isTagChar(batch[j]))
4798
- j++;
4799
- if (batch[j] === "$") {
4800
- const tag = batch.slice(i, j + 1);
4801
- if (dollarTag === null)
4802
- dollarTag = tag;
4803
- else if (dollarTag === tag)
4804
- dollarTag = null;
4805
- current += tag;
4806
- i = j;
4807
- continue;
4808
- }
4809
- }
4810
- if (ch === ";" && dollarTag === null) {
4811
- let j = i + 1;
4812
- while (j < batch.length && (batch[j] === " " || batch[j] === " " || batch[j] === "\r"))
4813
- j++;
4814
- if (j < batch.length && batch[j] === "\n") {
4815
- current += ";";
4816
- const trimmed = current.trim();
4817
- if (trimmed.length > 0)
4818
- statements.push(trimmed);
4819
- current = "";
4820
- i = j;
4821
- continue;
4822
- }
4823
- }
4824
- current += ch;
4825
- }
4826
- const tail = current.trim();
4827
- if (tail.length > 0)
4828
- statements.push(tail);
4829
- return statements.map((s) => s.endsWith(";") ? s : s + ";");
4830
- }
4831
5064
  ExistenceCheckSQL(objectType, schema, name) {
4832
5065
  const normalizedType = objectType.toUpperCase();
4833
5066
  switch (normalizedType) {
@@ -4926,8 +5159,8 @@ SELECT COUNT(*)::int AS ${this.Writer.QuoteColumnAlias(alias)} FROM ${this.Write
4926
5159
  ALTER COLUMN ${col} ${options.newNullable ? "DROP NOT NULL" : "SET NOT NULL"};`;
4927
5160
  }
4928
5161
  CommentOnColumn(schema, table, column, comment) {
4929
- const escaped = comment.replace(/'/g, "''");
4930
- return `COMMENT ON COLUMN "${schema}"."${table}"."${column}" IS '${escaped}';`;
5162
+ const escaped = this.EscapeComment(comment);
5163
+ return `COMMENT ON COLUMN ${this.Writer.QuoteSchema(schema, table)}.${this.Writer.QuoteIdentifier(column)} IS '${escaped}';`;
4931
5164
  }
4932
5165
  FallbackType() {
4933
5166
  return "TEXT";
@@ -4965,9 +5198,9 @@ SELECT COUNT(*)::int AS ${this.Writer.QuoteColumnAlias(alias)} FROM ${this.Write
4965
5198
  return `GRANT ${permission} ON ${schema}."${object}" TO "${role}"`;
4966
5199
  }
4967
5200
  CommentOnObject(objectType, schema, name, comment) {
4968
- const escapedComment = comment.replace(/'/g, "''");
5201
+ const escapedComment = this.EscapeComment(comment);
4969
5202
  const normalizedType = objectType.toUpperCase();
4970
- return `COMMENT ON ${normalizedType} ${schema}."${name}" IS '${escapedComment}'`;
5203
+ return `COMMENT ON ${normalizedType} ${this.Writer.QuoteSchema(schema, name)} IS '${escapedComment}'`;
4971
5204
  }
4972
5205
  SchemaIntrospectionQueries() {
4973
5206
  return {
@@ -5277,7 +5510,7 @@ var PostgreSQLDialect = class extends SQLDialect {
5277
5510
  super(...arguments);
5278
5511
  this.writer = Object.freeze(new PostgreSQLWriter());
5279
5512
  this.binding = Object.freeze(new PostgreSQLBinding());
5280
- this.ddl = Object.freeze(new PostgreSQLSchemaDDL(this.writer));
5513
+ this.ddl = Object.freeze(new PostgreSQLSchemaDDL(this.writer, POSTGRESQL_LEXICAL));
5281
5514
  }
5282
5515
  get PlatformKey() {
5283
5516
  return "postgresql";
@@ -6377,6 +6610,59 @@ function IsNetworkSQLType(typeName) {
6377
6610
  return NETWORK_TYPE_SET.has(normalize(typeName));
6378
6611
  }
6379
6612
 
6613
+ // ../../SQLDialect/dist/indexCatalog.js
6614
+ function buildPostgreSQLIndexCatalogSQL(whereClauses) {
6615
+ return `
6616
+ SELECT
6617
+ n.nspname AS "SchemaName",
6618
+ t.relname AS "TableName",
6619
+ i.relname AS "IndexName",
6620
+ am.amname AS "NativeType",
6621
+ ix.indisunique AS "IsUnique",
6622
+ ix.indisprimary AS "IsPrimaryKey",
6623
+ ix.indisclustered AS "IsClustered",
6624
+ pg_get_expr(ix.indpred, ix.indrelid) AS "FilterDefinition",
6625
+ (ix.indexprs IS NOT NULL) AS "HasExpressions",
6626
+ CASE WHEN k.attnum = 0 THEN NULL ELSE a.attname::text END AS "ColumnName",
6627
+ CASE WHEN k.attnum = 0 THEN pg_get_indexdef(ix.indexrelid, k.ord::int, true) ELSE NULL END AS "Expression",
6628
+ k.ord::int AS "Sequence",
6629
+ (k.ord > ix.indnkeyatts) AS "IsIncluded",
6630
+ CASE
6631
+ WHEN k.ord <= ix.indnkeyatts THEN ((ix.indoption[k.ord - 1] & 1) = 1)
6632
+ ELSE false
6633
+ END AS "IsDescending"
6634
+ FROM pg_index ix
6635
+ INNER JOIN pg_class i ON i.oid = ix.indexrelid
6636
+ INNER JOIN pg_class t ON t.oid = ix.indrelid
6637
+ INNER JOIN pg_namespace n ON n.oid = t.relnamespace
6638
+ INNER JOIN pg_am am ON am.oid = i.relam
6639
+ LEFT JOIN LATERAL unnest(ix.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord) ON true
6640
+ LEFT JOIN pg_attribute a ON a.attrelid = ix.indrelid AND a.attnum = k.attnum AND k.attnum > 0
6641
+ WHERE ${whereClauses.join("\n AND ")}
6642
+ ORDER BY n.nspname, t.relname, i.relname, k.ord
6643
+ `.trim();
6644
+ }
6645
+ var POSTGRESQL_INDEX_CATALOG_QUERY = buildPostgreSQLIndexCatalogSQL([
6646
+ "n.nspname = $1",
6647
+ "t.relkind IN ('r', 'p')",
6648
+ "ix.indisvalid",
6649
+ "ix.indisready"
6650
+ ]);
6651
+ var MYSQL_INDEX_CATALOG_QUERY = `
6652
+ SELECT
6653
+ TABLE_SCHEMA AS SchemaName,
6654
+ TABLE_NAME AS TableName,
6655
+ INDEX_NAME AS IndexName,
6656
+ NON_UNIQUE AS NonUnique,
6657
+ INDEX_TYPE AS NativeType,
6658
+ COLUMN_NAME AS ColumnName,
6659
+ SEQ_IN_INDEX AS Sequence,
6660
+ COLLATION AS Collation
6661
+ FROM information_schema.STATISTICS
6662
+ WHERE TABLE_SCHEMA = ?
6663
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX
6664
+ `.trim();
6665
+
6380
6666
  // ../../MJCore/dist/generic/util.js
6381
6667
  function CanonicalPrimaryKeyValue(value, isUuid) {
6382
6668
  const text = value.trim();
@@ -6905,6 +7191,18 @@ var UserInfo = class extends BaseInfo {
6905
7191
  set APIKeyActingContext(value) {
6906
7192
  this._aPIKeyActingContext = value;
6907
7193
  }
7194
+ /**
7195
+ * Per-request impersonation attribution context stamped server-side onto cloned `UserInfo`
7196
+ * instances for active impersonation sessions. Consumed by `DatabaseProviderBase.BuildRecordChangePayload`
7197
+ * so `MJ: Record Changes` rows written during `ActAs` record both the target user and the
7198
+ * impersonating actor. Not a DB/GraphQL field and never exposed to clients.
7199
+ */
7200
+ get ImpersonationContext() {
7201
+ return this._impersonationContext;
7202
+ }
7203
+ set ImpersonationContext(value) {
7204
+ this._impersonationContext = value;
7205
+ }
6908
7206
  /**
6909
7207
  * Row-filter bindings for the API key this session authenticated with,
6910
7208
  * resolved per request from the key's scope rules and stamped on the CLONED
@@ -7014,6 +7312,7 @@ var UserInfo = class extends BaseInfo {
7014
7312
  this._tenantContext = void 0;
7015
7313
  this._magicLinkScope = void 0;
7016
7314
  this._aPIKeyActingContext = void 0;
7315
+ this._impersonationContext = void 0;
7017
7316
  this._aPIKeyRowFilters = void 0;
7018
7317
  this._returningVisitorContext = void 0;
7019
7318
  this._widgetGuestContext = void 0;
@@ -7091,14 +7390,15 @@ var RowLevelSecurityFilterInfo = class _RowLevelSecurityFilterInfo extends BaseI
7091
7390
  * @returns {string} The filter text with all user tokens replaced with actual values
7092
7391
  */
7093
7392
  MarkupFilterText(user, options) {
7094
- const ret = this.substituteTokens(this.FilterText, user);
7393
+ const rawFilterText = options?.platform ? this.GetPlatformFilterText(options.platform) : this.FilterText;
7394
+ const ret = this.substituteTokens(rawFilterText, user);
7095
7395
  const unresolvedMatch = ret.match(/\{\{(?:User|Acting)\w+\}\}/);
7096
7396
  if (unresolvedMatch) {
7097
7397
  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);
7398
+ LogError("Row filter has unresolved token after markup \u2014 resolving filter to (1=0): " + unresolvedMatch[0] + " in filter: " + rawFilterText);
7099
7399
  return "(1=0)";
7100
7400
  }
7101
- LogError("RLS filter has unresolved token after markup: " + unresolvedMatch[0] + " in filter: " + this.FilterText);
7401
+ LogError("RLS filter has unresolved token after markup: " + unresolvedMatch[0] + " in filter: " + rawFilterText);
7102
7402
  }
7103
7403
  return ret;
7104
7404
  }
@@ -7120,7 +7420,8 @@ var RowLevelSecurityFilterInfo = class _RowLevelSecurityFilterInfo extends BaseI
7120
7420
  if (!user || literal === "(1=0)" && options?.unresolvedBehavior === "match-nothing") {
7121
7421
  return literal;
7122
7422
  }
7123
- return this.substituteTokens(this.bindWholeLiteralTokens(this.FilterText, user, binder), user);
7423
+ const rawFilterText = options?.platform ? this.GetPlatformFilterText(options.platform) : this.FilterText;
7424
+ return this.substituteTokens(this.bindWholeLiteralTokens(rawFilterText, user, binder), user);
7124
7425
  }
7125
7426
  /** Substitutes every token the user resolves as escaped literal text; unresolved tokens are left in place. */
7126
7427
  substituteTokens(text, user) {
@@ -8098,6 +8399,7 @@ var CONTEXT_TOKENS = [
8098
8399
  "Context.StartOfQuarter",
8099
8400
  "Context.StartOfYear"
8100
8401
  ];
8402
+ var CONTEXT_TOKEN_CONTRACT_VERSION = 1;
8101
8403
  var PROPERTY_VALUE_TYPES = ["string", "number", "boolean", "date", "uuid"];
8102
8404
  var PROPERTY_OFFSET_UNITS = ["day", "week", "month", "quarter", "year"];
8103
8405
  var TIME_ZONE_HEADER = "x-mj-timezone";
@@ -10380,6 +10682,93 @@ var EntityUniqueKeyInfo = class extends BaseInfo {
10380
10682
  }
10381
10683
  }
10382
10684
  };
10685
+ var EntityIndexFieldInfo = class extends BaseInfo {
10686
+ /** True when this key position is an expression rather than a plain base-table column. */
10687
+ get IsExpression() {
10688
+ return this.EntityFieldID == null;
10689
+ }
10690
+ /** True when this entry is a key part (not an INCLUDE column). */
10691
+ get IsKey() {
10692
+ return this.Role === "Key";
10693
+ }
10694
+ /** True when this entry is a non-key INCLUDE column. */
10695
+ get IsInclude() {
10696
+ return this.Role === "Include";
10697
+ }
10698
+ constructor(initData = null) {
10699
+ super();
10700
+ this.ID = null;
10701
+ this.EntityIndexID = null;
10702
+ this.EntityFieldID = null;
10703
+ this.Expression = null;
10704
+ this.Sequence = 0;
10705
+ this.Role = "Key";
10706
+ this.SortDirection = "ASC";
10707
+ this.__mj_CreatedAt = null;
10708
+ this.__mj_UpdatedAt = null;
10709
+ this.EntityIndex = null;
10710
+ this.EntityField = null;
10711
+ if (initData) {
10712
+ this.copyInitData(initData);
10713
+ }
10714
+ }
10715
+ };
10716
+ var EntityIndexInfo = class _EntityIndexInfo extends BaseInfo {
10717
+ static {
10718
+ this.CHILD_INIT_KEYS = /* @__PURE__ */ new Set([
10719
+ "EntityIndexFields",
10720
+ "_Fields",
10721
+ "Fields"
10722
+ ]);
10723
+ }
10724
+ /** All key and INCLUDE entries of this index, sorted by `Sequence`. */
10725
+ get Fields() {
10726
+ return this._fields;
10727
+ }
10728
+ /** Ordered key entries of this index (including expression key parts), sorted by `Sequence`. */
10729
+ get KeyFields() {
10730
+ return this._fields.filter((f) => f.Role === "Key");
10731
+ }
10732
+ /** Ordered non-key INCLUDE entries of this index, sorted by `Sequence`. */
10733
+ get IncludeFields() {
10734
+ return this._fields.filter((f) => f.Role === "Include");
10735
+ }
10736
+ /** True when the index has a non-empty filter/partial predicate. */
10737
+ get IsFiltered() {
10738
+ return this.FilterDefinition != null && this.FilterDefinition.trim().length > 0;
10739
+ }
10740
+ /** True when the index exists in the database (`Status === 'Active'`). */
10741
+ get IsActive() {
10742
+ return this.Status === "Active";
10743
+ }
10744
+ constructor(initData = null) {
10745
+ super();
10746
+ this.ID = null;
10747
+ this.EntityID = null;
10748
+ this.Name = null;
10749
+ this.IndexType = "BTree";
10750
+ this.NativeType = "";
10751
+ this.IsUnique = false;
10752
+ this.IsPrimaryKey = false;
10753
+ this.IsClustered = false;
10754
+ this.FilterDefinition = null;
10755
+ this.HasExpressions = false;
10756
+ this.Source = "Database";
10757
+ this.Status = "Active";
10758
+ this.Description = null;
10759
+ this.__mj_CreatedAt = null;
10760
+ this.__mj_UpdatedAt = null;
10761
+ this.Entity = null;
10762
+ this._fields = [];
10763
+ if (initData) {
10764
+ this.copyInitData(initData, _EntityIndexInfo.CHILD_INIT_KEYS);
10765
+ const rawFields = initData.EntityIndexFields || initData._Fields || initData.Fields;
10766
+ if (Array.isArray(rawFields)) {
10767
+ this._fields = rawFields.map((item) => item instanceof EntityIndexFieldInfo ? item : new EntityIndexFieldInfo(item)).sort((a, b) => a.Sequence - b.Sequence || ordinalCompare(a.ID, b.ID));
10768
+ }
10769
+ }
10770
+ }
10771
+ };
10383
10772
  var EntityAlternateBaseViewInfo = class extends BaseInfo {
10384
10773
  /**
10385
10774
  * The parent alternate base view on the same entity when {@link ParentID} is set,
@@ -11550,6 +11939,54 @@ var EntityFieldInfo = class _EntityFieldInfo extends BaseInfo {
11550
11939
  this._fixedWidthColumnCache = IsFixedWidthStringSQLType(this.Type);
11551
11940
  return this._fixedWidthColumnCache;
11552
11941
  }
11942
+ /**
11943
+ * Records the owning {@link EntityInfo} so field-level index helpers
11944
+ * ({@link IsIndexed}, {@link IsLeadingIndexColumn}) can inspect `EntityInfo.Indexes`
11945
+ * without consulting a global provider.
11946
+ */
11947
+ SetOwningEntity(entity) {
11948
+ this._owningEntity = entity;
11949
+ }
11950
+ matchesIndexField(indexField) {
11951
+ if (indexField.IsExpression) {
11952
+ return false;
11953
+ }
11954
+ if (this.ID && indexField.EntityFieldID) {
11955
+ return UUIDsEqual(this.ID, indexField.EntityFieldID);
11956
+ }
11957
+ if (this.Name && indexField.EntityField) {
11958
+ return this.Name.trim().toLowerCase() === indexField.EntityField.trim().toLowerCase();
11959
+ }
11960
+ return false;
11961
+ }
11962
+ /**
11963
+ * True when this field appears as a `Key` column in at least one `Active` database index
11964
+ * on the owning entity. `Include`-only columns, `Proposed`/`Rejected` indexes, and
11965
+ * expression key parts do not count.
11966
+ */
11967
+ get IsIndexed() {
11968
+ if (!this._owningEntity) {
11969
+ return false;
11970
+ }
11971
+ return this._owningEntity.Indexes.some((idx) => idx.IsActive && idx.KeyFields.some((f) => this.matchesIndexField(f)));
11972
+ }
11973
+ /**
11974
+ * True when this field is the leading (first `Key`) column of at least one `Active`
11975
+ * database index on the owning entity. An index whose first key part is an expression
11976
+ * does not make a subsequent column the leading column.
11977
+ */
11978
+ get IsLeadingIndexColumn() {
11979
+ if (!this._owningEntity) {
11980
+ return false;
11981
+ }
11982
+ return this._owningEntity.Indexes.some((idx) => {
11983
+ if (!idx.IsActive) {
11984
+ return false;
11985
+ }
11986
+ const leading = idx.KeyFields[0];
11987
+ return leading != null && this.matchesIndexField(leading);
11988
+ });
11989
+ }
11553
11990
  /**
11554
11991
  * Returns true if the field has a default value set
11555
11992
  */
@@ -11792,6 +12229,7 @@ var EntityFieldInfo = class _EntityFieldInfo extends BaseInfo {
11792
12229
  this._isDeletedAtFieldCache = void 0;
11793
12230
  this._isUniqueIdentifierCache = void 0;
11794
12231
  this._fixedWidthColumnCache = void 0;
12232
+ this._owningEntity = null;
11795
12233
  this._parsedDefaultValueCache = void 0;
11796
12234
  if (initData) {
11797
12235
  this.copyInitData(initData, _EntityFieldInfo.CHILD_INIT_KEYS);
@@ -12483,6 +12921,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
12483
12921
  if (md) {
12484
12922
  field.SetOwningProvider(md);
12485
12923
  }
12924
+ field.SetOwningEntity(this);
12486
12925
  fields.push(field);
12487
12926
  }
12488
12927
  this._fields = fields;
@@ -13152,6 +13591,28 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13152
13591
  get UniqueKeySets() {
13153
13592
  return this._uniqueKeySets;
13154
13593
  }
13594
+ /**
13595
+ * All database indexes and advisor proposals registered for this entity's base table,
13596
+ * sorted by name. Maintained by CodeGen from the database catalog.
13597
+ * @returns {EntityIndexInfo[]} Array of index definitions
13598
+ */
13599
+ get Indexes() {
13600
+ return this._indexes;
13601
+ }
13602
+ /**
13603
+ * Active database indexes currently present on this entity's base table (`Status === 'Active'`).
13604
+ * @returns {EntityIndexInfo[]} Array of active index definitions
13605
+ */
13606
+ get ActiveIndexes() {
13607
+ return this._indexes.filter((idx) => idx.IsActive);
13608
+ }
13609
+ /**
13610
+ * Replaces the entity's loaded index metadata (sorted deterministically by Name, ID). Used by
13611
+ * `ProviderBase.EnsureEntityIndexesLoaded` to hydrate indexes lazily after initial metadata boot.
13612
+ */
13613
+ SetIndexes(indexes) {
13614
+ this._indexes = [...indexes].sort((a, b) => ordinalCompare(a.Name, b.Name) || ordinalCompare(a.ID, b.ID));
13615
+ }
13155
13616
  /**
13156
13617
  * Whether a row is identified by its values in `fieldNames`: true when the names include every
13157
13618
  * primary key field, a field that is unique on its own ({@link EntityFieldInfo.IsUnique}, which
@@ -13794,27 +14255,41 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13794
14255
  * @param returnPrefix
13795
14256
  * @returns
13796
14257
  */
13797
- GetUserRowLevelSecurityWhereClause(user, type, returnPrefix) {
14258
+ GetUserRowLevelSecurityWhereClause(user, type, returnPrefix, platform) {
13798
14259
  if (this.UserExemptFromRowLevelSecurity(user, type)) {
13799
14260
  return "";
13800
14261
  }
13801
- const sRLSSQL = this.roleRowFilterClause(user, type, null);
14262
+ const sRLSSQL = this.roleRowFilterClause(user, type, null, platform);
13802
14263
  if (sRLSSQL.length === 0) {
13803
14264
  return "";
13804
14265
  }
13805
14266
  return `${returnPrefix && returnPrefix.length > 0 ? returnPrefix + " " : ""}${sRLSSQL}`;
13806
14267
  }
14268
+ /**
14269
+ * Resolves the database platform for RLS filter variant selection: uses an explicit
14270
+ * caller-supplied platform when provided, otherwise reads `PlatformKey` from the
14271
+ * entity's owning metadata provider when available.
14272
+ */
14273
+ resolveRLSPlatform(explicitPlatform) {
14274
+ if (explicitPlatform) {
14275
+ return explicitPlatform;
14276
+ }
14277
+ const provider = MetadataProviderFor(this);
14278
+ return provider?.PlatformKey;
14279
+ }
13807
14280
  /**
13808
14281
  * The role layer of the row filter, '' when no role filter applies. Callers check the
13809
14282
  * role-RLS exemption first. With a `binder`, user values bind as parameters
13810
14283
  * ({@link RowLevelSecurityFilterInfo.MarkupFilterParameterized}).
13811
14284
  */
13812
- roleRowFilterClause(user, type, binder) {
14285
+ roleRowFilterClause(user, type, binder, platform) {
13813
14286
  const userRLS = this.GetUserRowLevelSecurityInfo(user, type);
13814
14287
  if (!userRLS || userRLS.length === 0) {
13815
14288
  return "";
13816
14289
  }
13817
- const terms = userRLS.map((rls) => `(${binder ? rls.MarkupFilterParameterized(user, binder) : rls.MarkupFilterText(user)})`);
14290
+ const resolvedPlatform = this.resolveRLSPlatform(platform);
14291
+ const options = resolvedPlatform ? { platform: resolvedPlatform } : void 0;
14292
+ const terms = userRLS.map((rls) => `(${binder ? rls.MarkupFilterParameterized(user, binder, options) : rls.MarkupFilterText(user, options)})`);
13818
14293
  return terms.length > 1 ? `(${terms.join(" OR ")})` : terms[0];
13819
14294
  }
13820
14295
  /**
@@ -13844,21 +14319,21 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13844
14319
  * must call this without a binder: the literal clause is what keeps two users from sharing
13845
14320
  * a cached result.
13846
14321
  */
13847
- GetEffectiveRowFilterWhereClause(user, type, returnPrefix, binder) {
13848
- const sql = this.effectiveRowFilterClause(user, type, binder ?? null);
14322
+ GetEffectiveRowFilterWhereClause(user, type, returnPrefix, binder, platform) {
14323
+ const sql = this.effectiveRowFilterClause(user, type, binder ?? null, platform);
13849
14324
  if (sql.length === 0) {
13850
14325
  return "";
13851
14326
  }
13852
14327
  return `${returnPrefix && returnPrefix.length > 0 ? returnPrefix + " " : ""}${sql}`;
13853
14328
  }
13854
14329
  /** The composed row-filter clause without a prefix; literal when `binder` is null. */
13855
- effectiveRowFilterClause(user, type, binder) {
14330
+ effectiveRowFilterClause(user, type, binder, platform) {
13856
14331
  const layers = [];
13857
- const roleClause = binder === null ? this.GetUserRowLevelSecurityWhereClause(user, type, "") : this.UserExemptFromRowLevelSecurity(user, type) ? "" : this.roleRowFilterClause(user, type, binder);
14332
+ const roleClause = binder === null ? this.GetUserRowLevelSecurityWhereClause(user, type, "", platform) : this.UserExemptFromRowLevelSecurity(user, type) ? "" : this.roleRowFilterClause(user, type, binder, platform);
13858
14333
  if (roleClause && roleClause.length > 0) {
13859
14334
  layers.push(`(${roleClause})`);
13860
14335
  }
13861
- const keyClause = this.getAPIKeyRowFilterClause(user, type, binder);
14336
+ const keyClause = this.getAPIKeyRowFilterClause(user, type, binder, platform);
13862
14337
  if (keyClause && keyClause.length > 0) {
13863
14338
  layers.push(`(${keyClause})`);
13864
14339
  }
@@ -13872,7 +14347,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13872
14347
  * or unloaded) contributes `(1=0)`, and unresolved tokens inside a filter collapse it
13873
14348
  * to `(1=0)` via the match-nothing markup mode.
13874
14349
  */
13875
- getAPIKeyRowFilterClause(user, type, binder) {
14350
+ getAPIKeyRowFilterClause(user, type, binder, platform) {
13876
14351
  const bindings = user?.APIKeyRowFilters;
13877
14352
  if (!bindings || bindings.length === 0) {
13878
14353
  return "";
@@ -13881,13 +14356,17 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13881
14356
  if (mine.length === 0) {
13882
14357
  return "";
13883
14358
  }
14359
+ const resolvedPlatform = this.resolveRLSPlatform(platform);
13884
14360
  const clauses = [...mine].sort((a, b) => a.FilterID.localeCompare(b.FilterID)).map((b) => {
13885
14361
  const filter2 = MetadataProviderFor(this)?.RowLevelSecurityFilters?.find((f) => UUIDsEqual(f.ID, b.FilterID));
13886
14362
  if (!filter2) {
13887
14363
  LogError(`API-key row filter ${b.FilterID} for entity ${this.Name} not found in metadata \u2014 resolving to (1=0)`);
13888
14364
  return "(1=0)";
13889
14365
  }
13890
- const options = { unresolvedBehavior: "match-nothing" };
14366
+ const options = {
14367
+ unresolvedBehavior: "match-nothing",
14368
+ ...resolvedPlatform ? { platform: resolvedPlatform } : {}
14369
+ };
13891
14370
  return `(${binder ? filter2.MarkupFilterParameterized(user, binder, options) : filter2.MarkupFilterText(user, options)})`;
13892
14371
  });
13893
14372
  return clauses.join(" AND ");
@@ -14182,6 +14661,9 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14182
14661
  "EntityUniqueKeys",
14183
14662
  "_UniqueKeySets",
14184
14663
  "UniqueKeySets",
14664
+ "EntityIndexes",
14665
+ "_Indexes",
14666
+ "Indexes",
14185
14667
  "EntityAlternateBaseViews",
14186
14668
  "_AlternateBaseViews",
14187
14669
  "AlternateBaseViews"
@@ -14285,6 +14767,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14285
14767
  this._fieldCategories = null;
14286
14768
  this._organicKeys = [];
14287
14769
  this._uniqueKeySets = [];
14770
+ this._indexes = [];
14288
14771
  this._alternateBaseViews = [];
14289
14772
  this._lazyHasIdField = void 0;
14290
14773
  this._lazyVirtualCount = void 0;
@@ -14382,6 +14865,14 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
14382
14865
  }
14383
14866
  this._uniqueKeySets.sort((a, b) => ordinalCompare(a.Name, b.Name) || ordinalCompare(a.ID, b.ID));
14384
14867
  }
14868
+ this._indexes = [];
14869
+ const idx = initData.EntityIndexes || initData._Indexes || initData.Indexes;
14870
+ if (idx && Array.isArray(idx)) {
14871
+ for (const item of idx) {
14872
+ this._indexes.push(item instanceof EntityIndexInfo ? item : new EntityIndexInfo(item));
14873
+ }
14874
+ this._indexes.sort((a, b) => ordinalCompare(a.Name, b.Name) || ordinalCompare(a.ID, b.ID));
14875
+ }
14385
14876
  this._alternateBaseViews = [];
14386
14877
  const abv = initData.EntityAlternateBaseViews || initData._AlternateBaseViews || initData.AlternateBaseViews;
14387
14878
  if (abv && Array.isArray(abv)) {
@@ -16741,6 +17232,7 @@ var ClientInputTransportKeys = [
16741
17232
  ReadableFieldsTransportKey,
16742
17233
  "RestoreContext___",
16743
17234
  "CloneContext___",
17235
+ "SyncContext___",
16744
17236
  // The companion payload key, spelled out rather than imported: the module that defines it
16745
17237
  // imports BaseEntity, which imports this module, and this array is built at load time.
16746
17238
  "Companions___",
@@ -19800,6 +20292,19 @@ EntityField = EntityField_1 = __decorate4([
19800
20292
  function SerializeCloneChangeContext(context) {
19801
20293
  return JSON.stringify({ Version: 1, Kind: "Clone", Clone: context });
19802
20294
  }
20295
+ function SerializeSyncChangeContext(context) {
20296
+ return JSON.stringify({
20297
+ Version: 1,
20298
+ Kind: "Sync",
20299
+ Sync: {
20300
+ OriginDeploymentID: context.OriginDeploymentID,
20301
+ PairingID: context.PairingID,
20302
+ RunID: context.RunID,
20303
+ OriginChangeIDs: [...context.OriginChangeIDs],
20304
+ ...context.OriginUserEmail ? { OriginUserEmail: context.OriginUserEmail } : {}
20305
+ }
20306
+ });
20307
+ }
19803
20308
  var DataObjectParams = class {
19804
20309
  constructor(oldValues = false, omitNullValues = false, omitEmptyStrings = false, excludeFields = [], includeRelatedEntityData = false, relatedEntityList = []) {
19805
20310
  this.oldValues = oldValues;
@@ -19992,6 +20497,7 @@ var BaseEntity = class _BaseEntity {
19992
20497
  this._compositeKey = null;
19993
20498
  this._restoreContext = null;
19994
20499
  this._cloneContext = null;
20500
+ this._syncContext = null;
19995
20501
  this._pendingSave$ = null;
19996
20502
  this._isValidating = false;
19997
20503
  this._inSaveValidation = false;
@@ -23632,6 +24138,37 @@ var BaseEntity = class _BaseEntity {
23632
24138
  ClearCloneContext() {
23633
24139
  this._cloneContext = null;
23634
24140
  }
24141
+ /**
24142
+ * Returns the active sync context for the next save or delete, if any.
24143
+ *
24144
+ * Read by the data provider when generating the RecordChange SQL: when
24145
+ * non-null, the resulting RecordChange row is written with
24146
+ * `Source='Sync'`, `IntegrationID` (when provided), and `ChangeContext`
24147
+ * populated with structured JSON provenance. Returns null for ordinary saves.
24148
+ */
24149
+ get SyncContext() {
24150
+ return this._syncContext;
24151
+ }
24152
+ /**
24153
+ * Marks the next Save() or Delete() as part of an MJ Peer Sync operation.
24154
+ *
24155
+ * The provider will write a new RecordChange entry with `Source='Sync'`
24156
+ * and `ChangeContext` populated with structured JSON provenance.
24157
+ *
24158
+ * @param context Structured sync context. Throws if missing required fields.
24159
+ */
24160
+ SetSyncContext(context) {
24161
+ if (!context || !context.OriginDeploymentID || !context.PairingID || !context.RunID || !Array.isArray(context.OriginChangeIDs)) {
24162
+ throw new Error("BaseEntity.SetSyncContext: context is required with OriginDeploymentID, PairingID, RunID, and OriginChangeIDs");
24163
+ }
24164
+ this._syncContext = context;
24165
+ }
24166
+ /**
24167
+ * Clears any pending sync context. Safe to call when no context is set.
24168
+ */
24169
+ ClearSyncContext() {
24170
+ this._syncContext = null;
24171
+ }
23635
24172
  /**
23636
24173
  * Saves the current state of the object to the database. Uses the active provider to handle the actual saving of the record.
23637
24174
  * If the record is new, it will be created, if it already exists, it will be updated.
@@ -30538,14 +31075,16 @@ var LocalCacheManager = class _LocalCacheManager extends BaseSingleton {
30538
31075
  }
30539
31076
  }
30540
31077
  /**
30541
- * True when the registry must stay in this process: the storage is shared with other
30542
- * processes, so a persisted registry would be one key every server overwrites with its own
30543
- * view (and publishes to every peer on each write), and a booting server would adopt another
30544
- * server's accounting. Entries written by other processes are found through the provider's
31078
+ * True when the registry must stay in this process: either the storage is shared across a
31079
+ * multi-server fleet (`SharedAcrossProcesses`), or the provider explicitly requests a
31080
+ * process/tab-local registry (`ProcessLocalRegistry`, e.g. browser tabs sharing IndexedDB
31081
+ * through a SharedWorker without multi-server fleet semantics). Keeping the registry in
31082
+ * memory prevents peers/tabs from overwriting one shared registry key with their own
31083
+ * accounting. Entries written by other processes are found through the provider's
30545
31084
  * per-entity index instead ({@link resolveFingerprintsForEntity}).
30546
31085
  */
30547
31086
  registryIsProcessLocalOnly() {
30548
- return this._storageProvider?.SharedAcrossProcesses === true;
31087
+ return this._storageProvider?.SharedAcrossProcesses === true || this._storageProvider?.ProcessLocalRegistry === true;
30549
31088
  }
30550
31089
  /**
30551
31090
  * Loads the registry from storage.
@@ -32879,6 +33418,70 @@ function memberName(token) {
32879
33418
  return token.slice(QUERY_CONTEXT_NAME.length + 1);
32880
33419
  }
32881
33420
 
33421
+ // ../../MJCore/dist/generic/wellKnownUserSource.js
33422
+ var WellKnownUserSource = class _WellKnownUserSource {
33423
+ static {
33424
+ this._globalStoreKey = "___SINGLETON__WellKnownUserSource";
33425
+ }
33426
+ /**
33427
+ * The registered source for this process, resolved once through the class factory and
33428
+ * stored in the Global Object Store so bundler duplication cannot split the cached instance.
33429
+ *
33430
+ * Cached because {@link IsSystemUser} sits behind permission checks that run per entity and
33431
+ * per user; resolving (and allocating) on every call would be needless churn. Registrations
33432
+ * happen as module-load side effects of importing a data-provider package, which always
33433
+ * precedes any permission evaluation, so caching cannot capture a stale answer in practice.
33434
+ * Tests that register a source after first use should call {@link ResetInstance}.
33435
+ */
33436
+ static get Instance() {
33437
+ const g = GetGlobalObjectStore();
33438
+ if (g) {
33439
+ if (!g[_WellKnownUserSource._globalStoreKey]) {
33440
+ g[_WellKnownUserSource._globalStoreKey] = MJGlobal.Instance.ClassFactory.CreateInstance(_WellKnownUserSource) ?? new _WellKnownUserSource();
33441
+ }
33442
+ return g[_WellKnownUserSource._globalStoreKey];
33443
+ }
33444
+ return MJGlobal.Instance.ClassFactory.CreateInstance(_WellKnownUserSource) ?? new _WellKnownUserSource();
33445
+ }
33446
+ /**
33447
+ * Drops the cached {@link Instance} so the next access re-resolves through the class
33448
+ * factory. Intended for tests that register a source after the cache was populated.
33449
+ */
33450
+ static ResetInstance() {
33451
+ const g = GetGlobalObjectStore();
33452
+ if (g) {
33453
+ delete g[_WellKnownUserSource._globalStoreKey];
33454
+ }
33455
+ }
33456
+ /**
33457
+ * True when `user` is the MJ system user — the server's own service account, not a person.
33458
+ *
33459
+ * Synchronous on purpose: this is consumed by permission checks that cannot await. The base
33460
+ * returns false, which is the right answer anywhere no server-side source is registered —
33461
+ * a browser has no system account, so no user it holds can be one.
33462
+ *
33463
+ * Implementations must be null/undefined-safe so callers can pass an optional user directly.
33464
+ */
33465
+ IsSystemUser(user) {
33466
+ return false;
33467
+ }
33468
+ /**
33469
+ * The MJ system user for the given provider's connection, with `UserRoles` populated, or
33470
+ * null when this process has no such identity to offer.
33471
+ *
33472
+ * Implementations MUST NOT throw — a missing user row, an unconfigured provider, or a
33473
+ * failed lookup all resolve to null so callers can degrade rather than crash. Callers MUST
33474
+ * treat null as "no elevated identity available" and fall back to their existing behavior.
33475
+ *
33476
+ * @param provider The provider whose connection the user is being resolved for. Passed
33477
+ * explicitly (rather than read from a global) so a process holding several connections
33478
+ * resolves the account belonging to the one actually in use.
33479
+ */
33480
+ async GetSystemUser(provider) {
33481
+ return null;
33482
+ }
33483
+ };
33484
+
32882
33485
  // ../../MJCore/dist/generic/providerBase.js
32883
33486
  function MetadataFromSimpleObject(data, md) {
32884
33487
  try {
@@ -33064,9 +33667,16 @@ var ProviderBase = class _ProviderBase {
33064
33667
  this._metadataRefreshRetries = 0;
33065
33668
  this._metadataScopedReloadFailures = 0;
33066
33669
  this._metadataMemberRefreshTimer = null;
33670
+ this._entityIndexesMetadataGeneration = 0;
33671
+ this._entityIndexesLoadedGeneration = -1;
33672
+ this._entityIndexesLoadPromise = null;
33673
+ this._entityIndexesLastFailedAt = 0;
33674
+ this._entityIndexesLastFailedGeneration = -1;
33675
+ this._entityIndexesSystemUserFallbackWarned = false;
33067
33676
  this._peerMetadataNoticeFirstAt = null;
33068
33677
  this._peerMetadataNoticeRetries = 0;
33069
33678
  this._peerMetadataNoticeTimer = null;
33679
+ this._metadataRefreshStampsFresh = false;
33070
33680
  this._metadataWriteEventPending = false;
33071
33681
  this._metadataFullReloadRequested = false;
33072
33682
  this._metadataMemberRefreshWaits = 0;
@@ -33454,6 +34064,140 @@ var ProviderBase = class _ProviderBase {
33454
34064
  get LoadsQueryMetadata() {
33455
34065
  return this._adoptedLoadsQueryMetadata ?? this._ConfigData?.LoadQueryMetadata === true;
33456
34066
  }
34067
+ static {
34068
+ this.EntityIndexesFailureCooldownMs = 3e4;
34069
+ }
34070
+ /**
34071
+ * True when `EntityInfo.Indexes` / `EntityInfo.ActiveIndexes` have been hydrated for the
34072
+ * current metadata generation via {@link EnsureEntityIndexesLoaded}.
34073
+ */
34074
+ get EntityIndexesLoaded() {
34075
+ return this._entityIndexesLoadedGeneration === this._entityIndexesMetadataGeneration;
34076
+ }
34077
+ /**
34078
+ * Resolves the principal used to hydrate shared index metadata (Finding 285):
34079
+ * - On server (`ProviderType.Database`) providers, loads as the MJ system user via
34080
+ * {@link WellKnownUserSource} so a restricted first caller can never cache a partial set
34081
+ * process-wide (falling back to `this.CurrentUser ?? contextUser` only if no system user
34082
+ * source is registered).
34083
+ * - On client (`ProviderType.Network`) providers, uses `contextUser ?? this.CurrentUser`.
34084
+ */
34085
+ async resolveEntityIndexLoadUser(contextUser) {
34086
+ if (this.ProviderType !== ProviderType.Database) {
34087
+ return contextUser ?? this.CurrentUser;
34088
+ }
34089
+ let systemUser = null;
34090
+ try {
34091
+ const source = MJGlobal.Instance.ClassFactory.CreateInstance(WellKnownUserSource);
34092
+ systemUser = await source?.GetSystemUser(this) ?? null;
34093
+ } catch (e) {
34094
+ LogError(`EnsureEntityIndexesLoaded: WellKnownUserSource.GetSystemUser threw: ${e instanceof Error ? e.message : String(e)}`);
34095
+ }
34096
+ if (systemUser) {
34097
+ return systemUser;
34098
+ }
34099
+ if (!this._entityIndexesSystemUserFallbackWarned && contextUser && !this.CurrentUser) {
34100
+ this._entityIndexesSystemUserFallbackWarned = true;
34101
+ LogWarning("EnsureEntityIndexesLoaded: could not resolve the MJ system user for server-side index metadata loading \u2014 falling back to the calling user. Index metadata is cached process-wide, so a restricted caller could leave incomplete data cached.", "Cache");
34102
+ }
34103
+ return this.CurrentUser ?? contextUser;
34104
+ }
34105
+ /**
34106
+ * Lazily loads `MJ: Entity Indices` and `MJ: Entity Index Fields` once per metadata generation
34107
+ * and attaches them to each {@link EntityInfo} via {@link EntityInfo.SetIndexes} (Findings 267, 285).
34108
+ * Single-flight and zero-cost once hydrated; keeps `MJ_Metadata` boot payloads free of ~4,600–5,800
34109
+ * index rows (~8–10% overhead). Failed attempts back off for {@link EntityIndexesFailureCooldownMs}
34110
+ * within the current metadata generation so callers do not retry-storm on every request.
34111
+ */
34112
+ async EnsureEntityIndexesLoaded(contextUser) {
34113
+ if (this.EntityIndexesLoaded) {
34114
+ return;
34115
+ }
34116
+ if (this._entityIndexesLoadPromise) {
34117
+ return this._entityIndexesLoadPromise;
34118
+ }
34119
+ const gen = this._entityIndexesMetadataGeneration;
34120
+ if (this._entityIndexesLastFailedGeneration === gen && _ProviderBase.EntityIndexesFailureCooldownMs > 0 && Date.now() - this._entityIndexesLastFailedAt < _ProviderBase.EntityIndexesFailureCooldownMs) {
34121
+ return;
34122
+ }
34123
+ const loadPromise = (async () => {
34124
+ try {
34125
+ if (!this.EntityByName("MJ: Entity Indices") || !this.EntityByName("MJ: Entity Index Fields")) {
34126
+ if (this._entityIndexesMetadataGeneration === gen) {
34127
+ this._entityIndexesLoadedGeneration = gen;
34128
+ this._entityIndexesLastFailedAt = 0;
34129
+ this._entityIndexesLastFailedGeneration = -1;
34130
+ }
34131
+ return;
34132
+ }
34133
+ const loadUser = await this.resolveEntityIndexLoadUser(contextUser);
34134
+ const results = await this.RunViews([
34135
+ { EntityName: "MJ: Entity Indices", ResultType: "simple", IgnoreMaxRows: true },
34136
+ { EntityName: "MJ: Entity Index Fields", ResultType: "simple", IgnoreMaxRows: true }
34137
+ ], loadUser);
34138
+ if (!results || results.length < 2 || !results[0].Success || !results[1].Success) {
34139
+ if (this._entityIndexesMetadataGeneration === gen) {
34140
+ this._entityIndexesLastFailedGeneration = gen;
34141
+ this._entityIndexesLastFailedAt = Date.now();
34142
+ }
34143
+ LogError(`EnsureEntityIndexesLoaded failed: indices=${results?.[0]?.ErrorMessage ?? "no result"}, fields=${results?.[1]?.ErrorMessage ?? "no result"}`);
34144
+ return;
34145
+ }
34146
+ if (this._entityIndexesMetadataGeneration !== gen) {
34147
+ return;
34148
+ }
34149
+ const fieldsByIndexId = /* @__PURE__ */ new Map();
34150
+ for (const row of results[1].Results ?? []) {
34151
+ const idxId = typeof row.EntityIndexID === "string" ? NormalizeUUID(row.EntityIndexID) : "";
34152
+ if (!idxId) {
34153
+ continue;
34154
+ }
34155
+ let list = fieldsByIndexId.get(idxId);
34156
+ if (!list) {
34157
+ list = [];
34158
+ fieldsByIndexId.set(idxId, list);
34159
+ }
34160
+ list.push(row);
34161
+ }
34162
+ const indexesByEntityId = /* @__PURE__ */ new Map();
34163
+ for (const row of results[0].Results ?? []) {
34164
+ const entityId = typeof row.EntityID === "string" ? NormalizeUUID(row.EntityID) : "";
34165
+ const idxId = typeof row.ID === "string" ? NormalizeUUID(row.ID) : "";
34166
+ if (!entityId || !idxId) {
34167
+ continue;
34168
+ }
34169
+ const idxInfo = new EntityIndexInfo({
34170
+ ...row,
34171
+ EntityIndexFields: fieldsByIndexId.get(idxId) ?? []
34172
+ });
34173
+ let list = indexesByEntityId.get(entityId);
34174
+ if (!list) {
34175
+ list = [];
34176
+ indexesByEntityId.set(entityId, list);
34177
+ }
34178
+ list.push(idxInfo);
34179
+ }
34180
+ for (const entity of this.Entities) {
34181
+ entity.SetIndexes(indexesByEntityId.get(NormalizeUUID(entity.ID)) ?? []);
34182
+ }
34183
+ this._entityIndexesLastFailedAt = 0;
34184
+ this._entityIndexesLastFailedGeneration = -1;
34185
+ this._entityIndexesLoadedGeneration = gen;
34186
+ } catch (e) {
34187
+ if (this._entityIndexesMetadataGeneration === gen) {
34188
+ this._entityIndexesLastFailedGeneration = gen;
34189
+ this._entityIndexesLastFailedAt = Date.now();
34190
+ }
34191
+ LogError(`EnsureEntityIndexesLoaded threw: ${e instanceof Error ? e.message : String(e)}`);
34192
+ } finally {
34193
+ if (this._entityIndexesLoadPromise === loadPromise) {
34194
+ this._entityIndexesLoadPromise = null;
34195
+ }
34196
+ }
34197
+ })();
34198
+ this._entityIndexesLoadPromise = loadPromise;
34199
+ return loadPromise;
34200
+ }
33457
34201
  /**
33458
34202
  * The item filters every read of the MJ_Metadata dataset uses — the data, its status, and the
33459
34203
  * local dataset cache — so all of them describe the same row set. Null when every item is read.
@@ -33708,6 +34452,17 @@ var ProviderBase = class _ProviderBase {
33708
34452
  IsMetadataChangeNotice(event) {
33709
34453
  return (event.Action === "set" || event.Action === "removed") && (event.Category || CacheCategory.Default) === CacheCategory.Default && event.CacheKey === this.LocalStoragePrefix + _ProviderBase.localStorageTimestampsKey;
33710
34454
  }
34455
+ /**
34456
+ * True while a peer metadata notice check must wait rather than run immediately.
34457
+ * Defaults to {@link MetadataMemberRefreshMustWait} for providers whose metadata reads
34458
+ * cannot bypass an open transaction. Database providers whose `MJ_Metadata` reads run on
34459
+ * the connection pool regardless of unrelated ambient transactions (#4514) override this
34460
+ * to `false` unless {@link MetadataReadsJoinTransaction} is set, so unrelated background
34461
+ * writes on the global provider (such as scheduled jobs) do not defer peer metadata sync.
34462
+ */
34463
+ get PeerMetadataNoticeMustWait() {
34464
+ return this.MetadataMemberRefreshMustWait;
34465
+ }
33711
34466
  /**
33712
34467
  * Reacts to another server saving its metadata snapshot: after a short debounce, runs the
33713
34468
  * normal staleness check ({@link RefreshIfNeeded}, bypassing the check throttle). The check
@@ -33716,6 +34471,11 @@ var ProviderBase = class _ProviderBase {
33716
34471
  * poll. A server that is already current does no refresh and saves nothing, so notices do not
33717
34472
  * echo around the fleet.
33718
34473
  *
34474
+ * Random thundering-herd jitter ({@link PeerMetadataNoticeJitterMs}) applies only to `removed`
34475
+ * notices (e.g. `mj migrate` clearing the shared snapshot so every server would otherwise query
34476
+ * the database together). On a `set` notice the peer's updated snapshot is already in shared
34477
+ * storage, so only {@link MetadataDatasetRefreshDebounceMs} is waited.
34478
+ *
33719
34479
  * @returns true when the event was a metadata notice (and a check was scheduled)
33720
34480
  */
33721
34481
  HandlePeerMetadataNotice(event) {
@@ -33730,14 +34490,15 @@ var ProviderBase = class _ProviderBase {
33730
34490
  if (this._peerMetadataNoticeTimer) {
33731
34491
  clearTimeout(this._peerMetadataNoticeTimer);
33732
34492
  }
34493
+ const jitterMs = event.Action === "removed" ? Math.floor(Math.random() * _ProviderBase.PeerMetadataNoticeJitterMs) : 0;
33733
34494
  const timer = setTimeout(() => {
33734
34495
  this._peerMetadataNoticeTimer = null;
33735
- if (this.MetadataMemberRefreshMustWait) {
34496
+ if (this.PeerMetadataNoticeMustWait) {
33736
34497
  this.handlePeerMetadataNoticeRetry();
33737
34498
  return;
33738
34499
  }
33739
34500
  this.runPeerMetadataCheck();
33740
- }, _ProviderBase.MetadataDatasetRefreshDebounceMs + Math.floor(Math.random() * _ProviderBase.PeerMetadataNoticeJitterMs));
34501
+ }, _ProviderBase.MetadataDatasetRefreshDebounceMs + jitterMs);
33741
34502
  if (typeof timer === "object" && timer !== null && "unref" in timer) {
33742
34503
  timer.unref();
33743
34504
  }
@@ -33776,7 +34537,7 @@ var ProviderBase = class _ProviderBase {
33776
34537
  }
33777
34538
  const timer = setTimeout(() => {
33778
34539
  this._peerMetadataNoticeTimer = null;
33779
- if (this.MetadataMemberRefreshMustWait) {
34540
+ if (this.PeerMetadataNoticeMustWait) {
33780
34541
  this.handlePeerMetadataNoticeRetry();
33781
34542
  return;
33782
34543
  }
@@ -33851,7 +34612,12 @@ var ProviderBase = class _ProviderBase {
33851
34612
  return this.ReloadMetadata(true, void 0, true, true);
33852
34613
  }
33853
34614
  LogStatus(`[Metadata] Full reload needed: ${scope.Reason}`);
33854
- return this.Refresh();
34615
+ this._metadataRefreshStampsFresh = true;
34616
+ try {
34617
+ return await this.Refresh();
34618
+ } finally {
34619
+ this._metadataRefreshStampsFresh = false;
34620
+ }
33855
34621
  }
33856
34622
  /**
33857
34623
  * The write-event rule: a refresh prompted by a member-entity write knows something changed, so
@@ -33947,6 +34713,20 @@ var ProviderBase = class _ProviderBase {
33947
34713
  get TrustLocalCacheCompletely() {
33948
34714
  return false;
33949
34715
  }
34716
+ /**
34717
+ * Whether {@link CheckToSeeIfRefreshNeeded} may inspect remote timestamps and adopt a newer
34718
+ * snapshot from shared storage. Defaults to {@link AllowRefresh}.
34719
+ *
34720
+ * Providers that transiently suspend {@link AllowRefresh} while a save is running SQL
34721
+ * (such as `SQLServerDataProvider`) can override this to `true`: metadata status queries run
34722
+ * on the connection pool (`ignoreAmbientTransaction`), and adopting a peer's snapshot from
34723
+ * shared storage atomically replaces `_localMetadata` without mutating any `EntityInfo` held
34724
+ * by an in-flight save. Suspending checks on in-flight saves caused peer metadata notices
34725
+ * arriving during background writes (e.g. scheduled jobs) to be silently dropped.
34726
+ */
34727
+ get AllowRefreshCheck() {
34728
+ return this.AllowRefresh;
34729
+ }
33950
34730
  /**
33951
34731
  * Returns a record's name for synchronous display code, or `undefined` when it is not at hand.
33952
34732
  *
@@ -34109,6 +34889,9 @@ var ProviderBase = class _ProviderBase {
34109
34889
  return this.enqueueCoalescedRunViews(params, contextUser);
34110
34890
  }
34111
34891
  const key = this.generateDedupKey(params, contextUser);
34892
+ if (key === null) {
34893
+ return this.executeRunViewsPipeline(params, contextUser);
34894
+ }
34112
34895
  const existing = this._inflightViews.get(key);
34113
34896
  if (existing?.resolvedResults && existing.resolvedAt) {
34114
34897
  const age = Date.now() - existing.resolvedAt;
@@ -34328,6 +35111,11 @@ var ProviderBase = class _ProviderBase {
34328
35111
  const entryIndices = [];
34329
35112
  for (const param of entry.params) {
34330
35113
  const key = this.generateDedupKey([param], contextUser);
35114
+ if (key === null) {
35115
+ entryIndices.push(uniqueParams.length);
35116
+ uniqueParams.push(param);
35117
+ continue;
35118
+ }
34331
35119
  let idx = uniqueKeys.get(key);
34332
35120
  if (idx === void 0) {
34333
35121
  idx = uniqueParams.length;
@@ -34471,6 +35259,9 @@ var ProviderBase = class _ProviderBase {
34471
35259
  }
34472
35260
  async runViewsUncoalesced(params, contextUser) {
34473
35261
  const key = this.generateDedupKey(params, contextUser);
35262
+ if (key === null) {
35263
+ return this.executeRunViewsPipeline(params, contextUser);
35264
+ }
34474
35265
  const existing = this._inflightViews.get(key);
34475
35266
  if (existing?.resolvedResults && existing.resolvedAt) {
34476
35267
  const age = Date.now() - existing.resolvedAt;
@@ -34686,7 +35477,20 @@ var ProviderBase = class _ProviderBase {
34686
35477
  }
34687
35478
  return result;
34688
35479
  }
35480
+ static {
35481
+ this.UUID_VALUE_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
35482
+ }
35483
+ static normalizeDedupScalarString(value) {
35484
+ const trimmed = value.trim();
35485
+ return _ProviderBase.UUID_VALUE_REGEX.test(trimmed) ? NormalizeUUID(trimmed) : trimmed;
35486
+ }
34689
35487
  generateDedupKey(params, contextUser) {
35488
+ const effectiveUser = contextUser ?? this.CurrentUser;
35489
+ const contextScope = this.ComputeRunViewDedupContextScope(effectiveUser);
35490
+ if (contextScope === null) {
35491
+ return null;
35492
+ }
35493
+ const userIdSegment = contextUser?.ID ? NormalizeUUID(contextUser.ID) : "";
34690
35494
  const parts = params.map((p) => {
34691
35495
  const base = LocalCacheManager.Instance.GenerateRunViewFingerprint(p, this.InstanceConnectionString);
34692
35496
  const extras = [
@@ -34697,11 +35501,81 @@ var ProviderBase = class _ProviderBase {
34697
35501
  p.ViewName ?? "",
34698
35502
  IsExplicitBaseViewOverride(p) ? "abv_override:base" : "",
34699
35503
  p.TimeZone ?? "",
34700
- contextUser?.ID ?? ""
35504
+ userIdSegment
34701
35505
  ].join("|");
34702
35506
  return `${base}|${extras}`;
34703
35507
  });
34704
- return `${parts.join("||")}|||${this.RunViewDedupScope}`;
35508
+ const baseScope = this.RunViewDedupScope;
35509
+ const combinedScope = contextScope ? baseScope ? `${baseScope}|${contextScope}` : contextScope : baseScope;
35510
+ return `${parts.join("||")}|||${combinedScope}`;
35511
+ }
35512
+ /**
35513
+ * Per-call security and tenant scope appended to the RunView dedup key alongside
35514
+ * {@link RunViewDedupScope}. Because request deduplication and the linger window run
35515
+ * before `PreRunView` hooks (which inject tenant filters from `contextUser.TenantContext`)
35516
+ * and before RLS evaluation, two callers sharing the same `contextUser.ID` under different
35517
+ * tenant, magic-link, widget-guest, or API-key scopes must never share an in-flight or
35518
+ * lingering dedup slot.
35519
+ *
35520
+ * Returns `''` when the user carries no per-request isolation context, keeping unscoped
35521
+ * dedup keys unchanged. Returns `null` to bypass deduplication for the call when an
35522
+ * unknown / non-primitive `TenantContext` field shape (e.g. a nested object or array of
35523
+ * objects) is present so isolation is never silently weakened. Subclasses may override
35524
+ * this (calling `super`) to fold in additional per-call scope such as async-local tenant state.
35525
+ */
35526
+ ComputeRunViewDedupContextScope(contextUser) {
35527
+ if (!contextUser)
35528
+ return "";
35529
+ const segments = [];
35530
+ if (contextUser.TenantContext) {
35531
+ const scalarEntries = [];
35532
+ for (const [key, value] of Object.entries(contextUser.TenantContext)) {
35533
+ if (value === void 0 || value === null) {
35534
+ continue;
35535
+ }
35536
+ if (typeof value === "string") {
35537
+ scalarEntries.push(`${key}=${_ProviderBase.normalizeDedupScalarString(value)}`);
35538
+ } else if (typeof value === "number" || typeof value === "boolean") {
35539
+ scalarEntries.push(`${key}=${String(value)}`);
35540
+ } else if (Array.isArray(value) && value.every((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean")) {
35541
+ const serialized = value.map((v) => typeof v === "string" ? _ProviderBase.normalizeDedupScalarString(v) : String(v)).sort().join(",");
35542
+ scalarEntries.push(`${key}=[${serialized}]`);
35543
+ } else {
35544
+ return null;
35545
+ }
35546
+ }
35547
+ scalarEntries.sort();
35548
+ segments.push(`tc:${scalarEntries.join(",")}`);
35549
+ }
35550
+ if (contextUser.MagicLinkScope) {
35551
+ const rt = (contextUser.MagicLinkScope.ResourceType ?? "").trim().toLowerCase();
35552
+ const rid = contextUser.MagicLinkScope.ResourceID ? NormalizeUUID(contextUser.MagicLinkScope.ResourceID) : "";
35553
+ segments.push(`ml:${rt}:${rid}`);
35554
+ }
35555
+ if (contextUser.APIKeyActingContext) {
35556
+ const ak = contextUser.APIKeyActingContext;
35557
+ const orgId = ak.ActingOrganizationID ? NormalizeUUID(ak.ActingOrganizationID) : "";
35558
+ const personId = ak.ActingPersonID ? NormalizeUUID(ak.ActingPersonID) : "";
35559
+ const scopeId = (ak.ActingScopeID ?? "").trim().toLowerCase();
35560
+ const companies = (ak.ActingCompanyIDs ?? []).map((id) => NormalizeUUID(id)).sort().join(",");
35561
+ segments.push(`ak:${orgId}:${personId}:${scopeId}:${companies}`);
35562
+ }
35563
+ if (contextUser.APIKeyRowFilters && contextUser.APIKeyRowFilters.length > 0) {
35564
+ const filters = contextUser.APIKeyRowFilters.map((f) => `${NormalizeUUID(f.EntityID)}:${f.PermissionType}:${NormalizeUUID(f.FilterID)}`).sort().join(",");
35565
+ segments.push(`akf:${filters}`);
35566
+ }
35567
+ if (contextUser.WidgetGuestContext) {
35568
+ const widgetId = contextUser.WidgetGuestContext.WidgetID ? NormalizeUUID(contextUser.WidgetGuestContext.WidgetID) : "";
35569
+ segments.push(`wg:${widgetId}`);
35570
+ }
35571
+ if (contextUser.AnonymousVisitorID) {
35572
+ segments.push(`av:${contextUser.AnonymousVisitorID.trim().toLowerCase()}`);
35573
+ }
35574
+ if (contextUser.IsMagicLinkAnonymous) {
35575
+ const roles = (contextUser.UserRoles ?? []).map((r) => r.RoleID ? NormalizeUUID(r.RoleID) : "").filter(Boolean).sort().join(",");
35576
+ segments.push(`mla:1:${roles}`);
35577
+ }
35578
+ return segments.join("|");
34705
35579
  }
34706
35580
  /**
34707
35581
  * What, besides the request itself and the user, decides whether two identical RunViews may
@@ -37271,10 +38145,12 @@ var ProviderBase = class _ProviderBase {
37271
38145
  await this._metadataReloadInFlight;
37272
38146
  return true;
37273
38147
  }
38148
+ const initialStampsFresh = stampsFresh || this._metadataRefreshStampsFresh;
38149
+ this._metadataRefreshStampsFresh = false;
37274
38150
  this._metadataReloadInFlight = (async () => {
37275
38151
  let effectiveHardRefresh = hardRefresh;
37276
38152
  let tryScoped = scopedFirst;
37277
- let timestampsFresh = stampsFresh;
38153
+ let timestampsFresh = initialStampsFresh;
37278
38154
  do {
37279
38155
  this._metadataReloadQueued = false;
37280
38156
  let timestampsRead = true;
@@ -37910,7 +38786,7 @@ var ProviderBase = class _ProviderBase {
37910
38786
  await this.ClearDatasetCache(_ProviderBase._mjMetadataDatasetName, itemFilters);
37911
38787
  }
37912
38788
  const simpleMetadata = _ProviderBase.metadataAssemblyInput(d);
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);
38789
+ 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, simpleMetadata.EntityIndexes, simpleMetadata.EntityIndexFields);
37914
38790
  simpleMetadata.AllApplications = simpleMetadata.Applications.map((a) => {
37915
38791
  a.ApplicationEntities = simpleMetadata.ApplicationEntities.filter((ae) => UUIDsEqual(ae.ApplicationID, a.ID));
37916
38792
  a.ApplicationSettings = simpleMetadata.ApplicationSettings.filter((as) => UUIDsEqual(as.ApplicationID, a.ID));
@@ -37929,7 +38805,7 @@ var ProviderBase = class _ProviderBase {
37929
38805
  }
37930
38806
  }
37931
38807
  static {
37932
- this._assemblyWrittenItemCodes = /* @__PURE__ */ new Set(["Entities", "EntityFields", "EntityOrganicKeys", "Applications"]);
38808
+ this._assemblyWrittenItemCodes = /* @__PURE__ */ new Set(["Entities", "EntityFields", "EntityOrganicKeys", "EntityIndexes", "Applications"]);
37933
38809
  }
37934
38810
  /**
37935
38811
  * The MJ_Metadata rows keyed by item code, as {@link GetAllMetadata} assembles them: the items
@@ -38006,7 +38882,7 @@ var ProviderBase = class _ProviderBase {
38006
38882
  }
38007
38883
  return map2;
38008
38884
  }
38009
- PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews, uniqueKeys) {
38885
+ PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews, uniqueKeys, entityIndexes, entityIndexFields) {
38010
38886
  const result = [];
38011
38887
  const sortedEntities = entities.sort((a, b) => ordinalCompare(a.Name, b.Name) || ordinalCompare(a.ID, b.ID));
38012
38888
  if (fieldValues && fieldValues.length > 0) {
@@ -38030,6 +38906,12 @@ var ProviderBase = class _ProviderBase {
38030
38906
  ok.EntityOrganicKeyRelatedEntities = okreByOrganicKeyId.get(NormalizeUUID(ok.ID)) || [];
38031
38907
  }
38032
38908
  }
38909
+ if (entityIndexes && entityIndexes.length > 0 && entityIndexFields && entityIndexFields.length > 0) {
38910
+ const fieldsByIndexId = this.groupByNormalizedUUID(entityIndexFields, (f) => f.EntityIndexID);
38911
+ for (const idx of entityIndexes) {
38912
+ idx.EntityIndexFields = fieldsByIndexId.get(NormalizeUUID(idx.ID)) || [];
38913
+ }
38914
+ }
38033
38915
  const fieldsByEntityId = this.groupByNormalizedUUID(fields, (f) => f.EntityID);
38034
38916
  const permissionsByEntityId = this.groupByNormalizedUUID(permissions, (p) => p.EntityID);
38035
38917
  const relationshipsByEntityId = this.groupByNormalizedUUID(relationships, (r) => r.EntityID);
@@ -38037,6 +38919,7 @@ var ProviderBase = class _ProviderBase {
38037
38919
  const activeOrganicKeysByEntityId = organicKeys ? this.groupByNormalizedUUID(organicKeys.filter((ok) => ok.Status === "Active"), (ok) => ok.EntityID) : /* @__PURE__ */ new Map();
38038
38920
  const alternateBaseViewsByEntityId = alternateBaseViews && alternateBaseViews.length > 0 ? this.groupByNormalizedUUID(alternateBaseViews, (abv) => abv.EntityID) : /* @__PURE__ */ new Map();
38039
38921
  const uniqueKeysByEntityId = uniqueKeys && uniqueKeys.length > 0 ? this.groupByNormalizedUUID(uniqueKeys, (uk) => uk.EntityID) : /* @__PURE__ */ new Map();
38922
+ const indexesByEntityId = entityIndexes && entityIndexes.length > 0 ? this.groupByNormalizedUUID(entityIndexes, (idx) => idx.EntityID) : /* @__PURE__ */ new Map();
38040
38923
  for (const e of sortedEntities) {
38041
38924
  const entityIdKey = NormalizeUUID(e.ID);
38042
38925
  const entityFields = fieldsByEntityId.get(entityIdKey) || [];
@@ -38053,6 +38936,9 @@ var ProviderBase = class _ProviderBase {
38053
38936
  if (uniqueKeys) {
38054
38937
  e.EntityUniqueKeys = uniqueKeysByEntityId.get(entityIdKey) || [];
38055
38938
  }
38939
+ if (entityIndexes) {
38940
+ e.EntityIndexes = indexesByEntityId.get(entityIdKey) || [];
38941
+ }
38056
38942
  result.push(new EntityInfo(e, this));
38057
38943
  }
38058
38944
  const distinctSchemas = new Set(result.map((e) => e.SchemaName?.toLowerCase()));
@@ -38323,7 +39209,7 @@ var ProviderBase = class _ProviderBase {
38323
39209
  * {@link preValidateAndRefresh}) already caught it; {@link Config} did not.
38324
39210
  */
38325
39211
  async CheckToSeeIfRefreshNeeded(providerToUse, bypassMinCheckInterval) {
38326
- if (!this.AllowRefresh)
39212
+ if (!this.AllowRefreshCheck)
38327
39213
  return false;
38328
39214
  if (!bypassMinCheckInterval && this._refreshCheckInFlight) {
38329
39215
  LogStatusEx({ message: `[RefreshCheck] Skipped \u2014 a check is already in flight; its caller acts on the answer`, verboseOnly: true });
@@ -38890,6 +39776,13 @@ var ProviderBase = class _ProviderBase {
38890
39776
  */
38891
39777
  UpdateLocalMetadata(res) {
38892
39778
  this._localMetadata = res;
39779
+ this._entityIndexesMetadataGeneration++;
39780
+ this._entityIndexesLoadPromise = null;
39781
+ this._entityIndexesLastFailedAt = 0;
39782
+ this._entityIndexesLastFailedGeneration = -1;
39783
+ if (res?.AllEntities?.some((e) => (e?.Indexes?.length ?? 0) > 0) ?? false) {
39784
+ this._entityIndexesLoadedGeneration = this._entityIndexesMetadataGeneration;
39785
+ }
38893
39786
  this.RebuildEntityMaps();
38894
39787
  }
38895
39788
  /**
@@ -40832,11 +41725,41 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
40832
41725
  */
40833
41726
  async GetRecordChanges(entityName, compositeKey, contextUser) {
40834
41727
  try {
40835
- const safeEntityName = entityName.replace(/'/g, "''");
40836
- const safeRecordID = compositeKey.ToConcatenatedString().replace(/'/g, "''");
41728
+ const safeEntityName = EscapeSQLString(entityName);
41729
+ const safeRecordID = EscapeSQLString(compositeKey.ToConcatenatedString());
40837
41730
  const schema = this.MJCoreSchemaName;
40838
41731
  const sSQL = `SELECT * FROM ${this.QuoteSchemaAndView(schema, "vwRecordChanges")} WHERE ${this.QuoteIdentifier("Entity")}='${safeEntityName}' AND ${this.QuoteIdentifier("RecordID")}='${safeRecordID}' ORDER BY ${this.QuoteIdentifier("ChangedAt")} DESC`;
40839
- return this.ExecuteSQL(sSQL, void 0, void 0, contextUser);
41732
+ const rows = await this.ExecuteSQL(sSQL, void 0, void 0, contextUser);
41733
+ if (!rows || rows.length === 0) {
41734
+ return rows;
41735
+ }
41736
+ const hooks = GetDataHooks("PostRunView");
41737
+ if (hooks.length === 0) {
41738
+ return rows;
41739
+ }
41740
+ const effectiveUser = contextUser ?? this.CurrentUser;
41741
+ const hookParams = {
41742
+ EntityName: "MJ: Record Changes",
41743
+ ExtraFilter: `Entity='${safeEntityName}' AND RecordID='${safeRecordID}'`,
41744
+ ResultType: "simple"
41745
+ };
41746
+ let hookResult = {
41747
+ Success: true,
41748
+ Results: rows,
41749
+ RowCount: rows.length,
41750
+ TotalRowCount: rows.length,
41751
+ ExecutionTime: 0,
41752
+ ErrorMessage: "",
41753
+ UserViewRunID: ""
41754
+ };
41755
+ for (const hook of hooks) {
41756
+ hookResult = await hook(hookParams, hookResult, effectiveUser, this);
41757
+ if (!hookResult.Success) {
41758
+ LogError(`DatabaseProviderBase.GetRecordChanges: PostRunView hook failed for '${entityName}' (${compositeKey.ToConcatenatedString()}): ${hookResult.ErrorMessage || "unknown error"}`);
41759
+ return [];
41760
+ }
41761
+ }
41762
+ return hookResult.Results ?? [];
40840
41763
  } catch (e) {
40841
41764
  LogError(e);
40842
41765
  throw e;
@@ -41250,7 +42173,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
41250
42173
  async OnSaveCompleted(entity, saveSQLResult, user, options, _context) {
41251
42174
  const overlappingChangeData = saveSQLResult.extraData?.overlappingChangeData;
41252
42175
  if (overlappingChangeData && entity.EntityInfo.AllowMultipleSubtypes && entity.EntityInfo.TrackRecordChanges) {
41253
- await this.PropagateRecordChangesToSiblings(entity.EntityInfo, overlappingChangeData, entity.PrimaryKey.Values(), user?.ID ?? "", options.ISAActiveChildEntityName, void 0, entity.CloneContext ? "Clone" : "Internal", entity.CloneContext ? SerializeCloneChangeContext(entity.CloneContext) : null);
42176
+ await this.PropagateRecordChangesToSiblings(entity.EntityInfo, overlappingChangeData, entity.PrimaryKey.Values(), user?.ID ?? "", options.ISAActiveChildEntityName, void 0, entity.CloneContext ? "Clone" : entity.SyncContext ? "Sync" : "Internal", entity.CloneContext ? SerializeCloneChangeContext(entity.CloneContext) : entity.SyncContext ? SerializeSyncChangeContext(entity.SyncContext) : null, entity.SyncContext?.IntegrationID ?? null);
41254
42177
  }
41255
42178
  return null;
41256
42179
  }
@@ -42376,8 +43299,8 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42376
43299
  * @param type The change type
42377
43300
  * @param user The acting user
42378
43301
  */
42379
- async LogRecordChange(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext) {
42380
- const sqlResult = this.BuildRecordChangeSQL(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext);
43302
+ async LogRecordChange(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext, syncContext) {
43303
+ const sqlResult = this.BuildRecordChangeSQL(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext, syncContext);
42381
43304
  if (sqlResult) {
42382
43305
  return await this.ExecuteSQL(sqlResult.sql, sqlResult.parameters ?? void 0, void 0, user);
42383
43306
  }
@@ -42397,7 +43320,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42397
43320
  }
42398
43321
  /**
42399
43322
  * Builds the dialect-agnostic payload for a RecordChange row from the
42400
- * entity's old/new data and an optional restore or clone context. Concrete
43323
+ * entity's old/new data and an optional restore, clone, or sync context. Concrete
42401
43324
  * providers consume the returned payload to render their dialect-specific
42402
43325
  * SQL (SQL Server EXEC, PostgreSQL INSERT, etc.).
42403
43326
  *
@@ -42426,10 +43349,13 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42426
43349
  * @param skipFullRecordJSON When true (because the dialect builds `FullRecordJSON` in SQL
42427
43350
  * from the returned row), skips `EscapeQuotesInProperties` and `JSON.stringify` for
42428
43351
  * `fullRecordJSON`, returning `''`.
43352
+ * @param syncContext When non-null, populates `source='Sync'`, `integrationID`,
43353
+ * and the structured `changeContext` JSON payload.
42429
43354
  */
42430
- BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext, skipFullRecordJSON = false) {
42431
- if (restoreContext && cloneContext) {
42432
- throw new Error("BuildRecordChangePayload: both restoreContext and cloneContext were provided; an operation cannot be both a restore and a clone");
43355
+ BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext, skipFullRecordJSON = false, syncContext) {
43356
+ const activeContexts = [restoreContext, cloneContext, syncContext].filter(Boolean).length;
43357
+ if (activeContexts > 1) {
43358
+ throw new Error("BuildRecordChangePayload: restoreContext, cloneContext, and syncContext are mutually exclusive; at most one may be provided");
42433
43359
  }
42434
43360
  const isCreateOrDelete = oldData === null || newData === null;
42435
43361
  const changes = this.DiffObjects(oldData, newData, entityInfo, quoteToEscape);
@@ -42442,9 +43368,11 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42442
43368
  fullRecordJSON = JSON.stringify(this.EscapeQuotesInProperties(dataForFullJSON, quoteToEscape));
42443
43369
  }
42444
43370
  const changesJSON = changes !== null ? JSON.stringify(changes) : "";
42445
- const changesDescription = oldData && newData ? this.CreateUserDescriptionOfChanges(changes) : !oldData ? "Record Created" : "Record Deleted";
42446
- const source = restoreContext ? "Restore" : cloneContext ? "Clone" : "Internal";
42447
- const changeContext = cloneContext ? SerializeCloneChangeContext(cloneContext) : null;
43371
+ const baseChangesDescription = oldData && newData ? this.CreateUserDescriptionOfChanges(changes) : !oldData ? "Record Created" : "Record Deleted";
43372
+ const impCtx = user?.ImpersonationContext;
43373
+ const changesDescription = impCtx ? `${baseChangesDescription} [Impersonated by ActorUserID=${impCtx.ActorUserID ?? "unknown"}, APIKeyID=${impCtx.APIKeyID}, Mode=${impCtx.Mode}]` : baseChangesDescription;
43374
+ const source = restoreContext ? "Restore" : cloneContext ? "Clone" : syncContext ? "Sync" : "Internal";
43375
+ const changeContext = cloneContext ? SerializeCloneChangeContext(cloneContext) : syncContext ? SerializeSyncChangeContext(syncContext) : null;
42448
43376
  return {
42449
43377
  entityID: entityInfo.ID,
42450
43378
  recordID,
@@ -42456,7 +43384,8 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42456
43384
  fullRecordJSON,
42457
43385
  restoredFromID: restoreContext?.SourceChangeID ?? null,
42458
43386
  restoreReason: restoreContext?.Reason ?? null,
42459
- changeContext
43387
+ changeContext,
43388
+ integrationID: syncContext?.IntegrationID ?? null
42460
43389
  };
42461
43390
  }
42462
43391
  /**
@@ -42473,7 +43402,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42473
43402
  * @param source The source discriminator for the record change row ('Internal' or 'Clone')
42474
43403
  * @param changeContext Optional serialized JSON provenance for clone operations
42475
43404
  */
42476
- async PropagateRecordChangesToSiblings(parentInfo, changeData, pkValue, userId, activeChildEntityName, extraExecOptions, source = "Internal", changeContext = null) {
43405
+ async PropagateRecordChangesToSiblings(parentInfo, changeData, pkValue, userId, activeChildEntityName, extraExecOptions, source = "Internal", changeContext = null, integrationID = null) {
42477
43406
  const sqlParts = [];
42478
43407
  const safePKValue = pkValue.replace(/'/g, "''");
42479
43408
  const safeUserId = userId.replace(/'/g, "''");
@@ -42488,7 +43417,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42488
43417
  if (!entityInTree.TrackRecordChanges)
42489
43418
  continue;
42490
43419
  const varName = `@_rc_prop_${varIndex++}`;
42491
- sqlParts.push(this.BuildSiblingRecordChangeSQL(varName, entityInTree, safeChangesJSON, safeChangesDesc, safePKValue, safeUserId, source, changeContext));
43420
+ sqlParts.push(this.BuildSiblingRecordChangeSQL(varName, entityInTree, safeChangesJSON, safeChangesDesc, safePKValue, safeUserId, source, changeContext, integrationID));
42492
43421
  }
42493
43422
  }
42494
43423
  if (sqlParts.length > 0) {
@@ -42698,70 +43627,6 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42698
43627
  }
42699
43628
  };
42700
43629
 
42701
- // ../../MJCore/dist/generic/wellKnownUserSource.js
42702
- var WellKnownUserSource = class _WellKnownUserSource {
42703
- static {
42704
- this._globalStoreKey = "___SINGLETON__WellKnownUserSource";
42705
- }
42706
- /**
42707
- * The registered source for this process, resolved once through the class factory and
42708
- * stored in the Global Object Store so bundler duplication cannot split the cached instance.
42709
- *
42710
- * Cached because {@link IsSystemUser} sits behind permission checks that run per entity and
42711
- * per user; resolving (and allocating) on every call would be needless churn. Registrations
42712
- * happen as module-load side effects of importing a data-provider package, which always
42713
- * precedes any permission evaluation, so caching cannot capture a stale answer in practice.
42714
- * Tests that register a source after first use should call {@link ResetInstance}.
42715
- */
42716
- static get Instance() {
42717
- const g = GetGlobalObjectStore();
42718
- if (g) {
42719
- if (!g[_WellKnownUserSource._globalStoreKey]) {
42720
- g[_WellKnownUserSource._globalStoreKey] = MJGlobal.Instance.ClassFactory.CreateInstance(_WellKnownUserSource) ?? new _WellKnownUserSource();
42721
- }
42722
- return g[_WellKnownUserSource._globalStoreKey];
42723
- }
42724
- return MJGlobal.Instance.ClassFactory.CreateInstance(_WellKnownUserSource) ?? new _WellKnownUserSource();
42725
- }
42726
- /**
42727
- * Drops the cached {@link Instance} so the next access re-resolves through the class
42728
- * factory. Intended for tests that register a source after the cache was populated.
42729
- */
42730
- static ResetInstance() {
42731
- const g = GetGlobalObjectStore();
42732
- if (g) {
42733
- delete g[_WellKnownUserSource._globalStoreKey];
42734
- }
42735
- }
42736
- /**
42737
- * True when `user` is the MJ system user — the server's own service account, not a person.
42738
- *
42739
- * Synchronous on purpose: this is consumed by permission checks that cannot await. The base
42740
- * returns false, which is the right answer anywhere no server-side source is registered —
42741
- * a browser has no system account, so no user it holds can be one.
42742
- *
42743
- * Implementations must be null/undefined-safe so callers can pass an optional user directly.
42744
- */
42745
- IsSystemUser(user) {
42746
- return false;
42747
- }
42748
- /**
42749
- * The MJ system user for the given provider's connection, with `UserRoles` populated, or
42750
- * null when this process has no such identity to offer.
42751
- *
42752
- * Implementations MUST NOT throw — a missing user row, an unconfigured provider, or a
42753
- * failed lookup all resolve to null so callers can degrade rather than crash. Callers MUST
42754
- * treat null as "no elevated identity available" and fall back to their existing behavior.
42755
- *
42756
- * @param provider The provider whose connection the user is being resolved for. Passed
42757
- * explicitly (rather than read from a global) so a process holding several connections
42758
- * resolves the account belonging to the one actually in use.
42759
- */
42760
- async GetSystemUser(provider) {
42761
- return null;
42762
- }
42763
- };
42764
-
42765
43630
  // ../../MJCore/dist/generic/baseEngine.js
42766
43631
  var primaryKeyIndexes = /* @__PURE__ */ new WeakMap();
42767
43632
  var deltaHeldRowIndexes = /* @__PURE__ */ new WeakMap();
@@ -43410,9 +44275,10 @@ var BaseEngine = class _BaseEngine extends BaseSingleton {
43410
44275
  }
43411
44276
  }
43412
44277
  }
43413
- const newInstance = new subclassConstructor();
43414
- newInstance.SetProvider(provider);
43415
- return newInstance;
44278
+ const singletonCtor = subclassConstructor;
44279
+ const engineInstance = singletonCtor.Instance ?? (typeof singletonCtor.getInstance === "function" ? singletonCtor.getInstance() : new subclassConstructor());
44280
+ engineInstance.SetProvider(provider);
44281
+ return engineInstance;
43416
44282
  }
43417
44283
  /**
43418
44284
  * Removes all cached engine instances for the given connection. Call this when a connection
@@ -46180,15 +47046,16 @@ var BaseEngine = class _BaseEngine extends BaseSingleton {
46180
47046
  * derived state until something else happened to rebuild it.
46181
47047
  *
46182
47048
  * @param propertyName - The name of the property to refresh
47049
+ * @param bypassCache - When `true`, forces a server/database read instead of consulting `LocalCacheManager`
46183
47050
  */
46184
- async RefreshItem(propertyName) {
47051
+ async RefreshItem(propertyName, bypassCache) {
46185
47052
  const config = this._metadataConfigs.find((c) => c.PropertyName === propertyName) || this._dynamicConfigs.get(propertyName);
46186
47053
  if (config) {
46187
47054
  await this.LoadSingleConfig(
46188
47055
  config,
46189
47056
  this._contextUser,
46190
47057
  /*bypassCache*/
46191
- !!config.Expiration,
47058
+ bypassCache ?? !!config.Expiration,
46192
47059
  /*suppressEmit*/
46193
47060
  true
46194
47061
  );
@@ -46922,6 +47789,1197 @@ var AuthorizationEvaluator = class _AuthorizationEvaluator {
46922
47789
  }
46923
47790
  };
46924
47791
 
47792
+ // ../../MJCore/dist/generic/limitsConfig.js
47793
+ var LIMITS_TIER_PRECEDENCE = [
47794
+ "CodeFallback",
47795
+ "MjConfig",
47796
+ "AgentOrWorkflowMetadata",
47797
+ "UserAgentPolicy",
47798
+ "RunOverride"
47799
+ ];
47800
+ function IsTaskGraphIsolationLevel(value) {
47801
+ return value === "InProcess" || value === "Worker" || value === "Process" || value === "Container";
47802
+ }
47803
+ var CODE_FALLBACK_LIMITS = {
47804
+ AgentChannelConsecutiveTurns: 1e3,
47805
+ AgentChannelWakesPerHour: 600,
47806
+ AgentAbsoluteIterations: 1e5,
47807
+ MaxTasksPerAgentGraph: 1e4,
47808
+ WhileLoopMaxIterations: 1e6,
47809
+ ForEachMaxIterations: 1e6,
47810
+ MaxTasksPerGraph: 1e5,
47811
+ BriefingContributorTimeoutMs: 1e4,
47812
+ BriefingMaxContributorChars: 32768,
47813
+ Budgets: {
47814
+ PerRun: {
47815
+ MaxCostUsd: null,
47816
+ MaxWallClockMs: 72e5,
47817
+ MaxTokens: null
47818
+ },
47819
+ PerRoutine: {
47820
+ MaxCostUsd: null,
47821
+ MaxWallClockMs: null
47822
+ },
47823
+ PerUserPerDay: {
47824
+ MaxCostUsd: null,
47825
+ MaxWallClockMs: null,
47826
+ DayBoundaryTimezone: "UTC"
47827
+ },
47828
+ CountPausedTimeTowardsWallClock: false,
47829
+ AllowedInFlightOvershootUsd: 0,
47830
+ AllowedInFlightOvershootMs: 0
47831
+ },
47832
+ ProgressDetector: {
47833
+ Enabled: true,
47834
+ WindowSize: 10,
47835
+ MinIterationsBeforeCheck: 6,
47836
+ DuplicateStepRatioThreshold: 0.75,
47837
+ NoPayloadDeltaWindowCount: 5,
47838
+ RepeatingErrorWindowCount: 4,
47839
+ AmbiguityLowScoreThreshold: 0.25,
47840
+ AmbiguityHighScoreThreshold: 0.65,
47841
+ FastJudgeEnabled: true,
47842
+ FastJudgeTimeoutMs: 200,
47843
+ FastJudgeMinIntervalIterations: 5,
47844
+ FastJudgeMaxInputChars: 8192,
47845
+ FastJudgeFailureFallback: "ContinueWithWarning"
47846
+ },
47847
+ ResourceGuards: {
47848
+ MaxValidationRetries: 10,
47849
+ MaxConsecutiveFailedSteps: 10,
47850
+ MaxConsecutiveUnproductiveRetries: 10,
47851
+ MaxRepeatedFailingStep: 3,
47852
+ MaxConsecutiveReadToolPreemptions: 3,
47853
+ FinalPayloadValidationMaxRetries: 3,
47854
+ MaxRunChainLength: 1e3,
47855
+ MaxAgentRunTreeDepth: 100,
47856
+ MaxHandoffHops: 3,
47857
+ MaxSubAgentConsultRounds: 3,
47858
+ MaxDecisionRequestsPerTurn: 8,
47859
+ MaxDecisionCallsPerTurn: 100,
47860
+ MaxConversationToolCallsPerTurn: 8,
47861
+ MaxSettlementRetryPasses: 20,
47862
+ MaxReinvokeDepth: 5,
47863
+ MaxProviderRaiseAttempts: 3,
47864
+ ClientToolTimeoutMs: 3e4,
47865
+ PipelineDeadlineMs: 12e4,
47866
+ MaxPipelineStages: 20,
47867
+ MaxMapElements: 1e3,
47868
+ MaxLoopConcurrency: 10,
47869
+ MaxRealtimeConsecutiveAgentTurns: 8
47870
+ },
47871
+ Tuning: {
47872
+ MaxPerAgentCacheEntries: 200,
47873
+ MaxClientToolSessions: 1e3,
47874
+ MaxToolsPerSession: 200,
47875
+ CompactionDefaultContextTokens: 8e3,
47876
+ CompactionDefaultTriggerPercent: 75,
47877
+ CompactionDefaultTargetPercent: 30,
47878
+ CompactionMinGainTokens: 500,
47879
+ CompactionMinMessages: 4,
47880
+ CompactionMaxDeltaMessageChars: 1e4,
47881
+ MaxSkillDecisionCandidates: 30,
47882
+ MaxHandoffCandidates: 20,
47883
+ QueryCacheDefaultMaxSize: 1e3,
47884
+ QueryCacheDefaultTtlMinutes: 60,
47885
+ ScratchpadMaxTasks: 50,
47886
+ DecisionsMaxItems: 100,
47887
+ MaxInitialArtifactOperations: 100,
47888
+ MaxDirectInIds: 2500,
47889
+ MaxAgentsOfferedInDraft: 40,
47890
+ MaxStepsPerSignal: 1e3,
47891
+ // A normal fingerprint recording is a read and one row write, far below five seconds; five
47892
+ // seconds is short enough that a run held behind the caller's own row lock returns promptly.
47893
+ QueryApprovalRecordingWaitMs: 5e3
47894
+ },
47895
+ Isolation: {
47896
+ DefaultIsolation: "Worker",
47897
+ DraftDefaultIsolation: "Worker",
47898
+ WorkerMaxOldGenerationSizeMb: 256,
47899
+ WorkerMaxYoungGenerationSizeMb: 64,
47900
+ WorkerTimeoutMs: 12e4,
47901
+ ProcessMaxMemoryMb: 512,
47902
+ ProcessTimeoutMs: 3e5,
47903
+ ContainerMemoryMb: 512,
47904
+ ContainerCpuQuota: 1,
47905
+ ContainerTimeoutMs: 3e5,
47906
+ ContainerImage: "node:20-alpine",
47907
+ ContainerRuntime: "docker"
47908
+ },
47909
+ TaskGraphQueue: {
47910
+ GraphDispatchTopicName: "mj.taskgraph.runs",
47911
+ DefaultEnqueueTopicName: "mj.taskgraph.steps",
47912
+ MaxEnqueuePublishConcurrency: 25,
47913
+ EnqueuePublishBatchSize: 100,
47914
+ MaxConcurrentIsolatedRunners: 16,
47915
+ MaxEnqueueItemsPerFanOut: 1e5,
47916
+ MaxEnqueueRedeliveryAttempts: 5,
47917
+ EnqueuePublishRetryAttempts: 3,
47918
+ CallerNotificationRetentionMs: 864e5
47919
+ },
47920
+ Liveness: {
47921
+ Enabled: true,
47922
+ InactivityTimeoutMs: 9e5,
47923
+ OuterMaxWallClockMs: 2592e5,
47924
+ StreamChunkTouchThrottleMs: 5e3,
47925
+ HttpHeadersTimeoutMs: 18e5,
47926
+ HttpBodyTimeoutMs: 18e5
47927
+ },
47928
+ StuckDetector: {
47929
+ Enabled: true,
47930
+ WindowSize: 10,
47931
+ IdenticalToolCallThreshold: 3,
47932
+ ReadOnlyStepThreshold: 30,
47933
+ ReadOnlyPostDirectiveGraceSteps: 5
47934
+ }
47935
+ };
47936
+ var RESOURCE_GUARD_KEYS = [
47937
+ "MaxValidationRetries",
47938
+ "MaxConsecutiveFailedSteps",
47939
+ "MaxConsecutiveUnproductiveRetries",
47940
+ "MaxRepeatedFailingStep",
47941
+ "MaxConsecutiveReadToolPreemptions",
47942
+ "FinalPayloadValidationMaxRetries",
47943
+ "MaxRunChainLength",
47944
+ "MaxAgentRunTreeDepth",
47945
+ "MaxHandoffHops",
47946
+ "MaxSubAgentConsultRounds",
47947
+ "MaxDecisionRequestsPerTurn",
47948
+ "MaxDecisionCallsPerTurn",
47949
+ "MaxConversationToolCallsPerTurn",
47950
+ "MaxSettlementRetryPasses",
47951
+ "MaxReinvokeDepth",
47952
+ "MaxProviderRaiseAttempts",
47953
+ "ClientToolTimeoutMs",
47954
+ "PipelineDeadlineMs",
47955
+ "MaxPipelineStages",
47956
+ "MaxMapElements",
47957
+ "MaxLoopConcurrency",
47958
+ "MaxRealtimeConsecutiveAgentTurns"
47959
+ ];
47960
+ var TUNING_KEYS = [
47961
+ "MaxPerAgentCacheEntries",
47962
+ "MaxClientToolSessions",
47963
+ "MaxToolsPerSession",
47964
+ "CompactionDefaultContextTokens",
47965
+ "CompactionDefaultTriggerPercent",
47966
+ "CompactionDefaultTargetPercent",
47967
+ "CompactionMinGainTokens",
47968
+ "CompactionMinMessages",
47969
+ "CompactionMaxDeltaMessageChars",
47970
+ "MaxSkillDecisionCandidates",
47971
+ "MaxHandoffCandidates",
47972
+ "QueryCacheDefaultMaxSize",
47973
+ "QueryCacheDefaultTtlMinutes",
47974
+ "ScratchpadMaxTasks",
47975
+ "DecisionsMaxItems",
47976
+ "MaxInitialArtifactOperations",
47977
+ "MaxDirectInIds",
47978
+ "MaxAgentsOfferedInDraft",
47979
+ "MaxStepsPerSignal",
47980
+ "QueryApprovalRecordingWaitMs"
47981
+ ];
47982
+ var ISOLATION_NUMERIC_KEYS = [
47983
+ "WorkerMaxOldGenerationSizeMb",
47984
+ "WorkerMaxYoungGenerationSizeMb",
47985
+ "WorkerTimeoutMs",
47986
+ "ProcessMaxMemoryMb",
47987
+ "ProcessTimeoutMs",
47988
+ "ContainerMemoryMb",
47989
+ "ContainerCpuQuota",
47990
+ "ContainerTimeoutMs"
47991
+ ];
47992
+ var ISOLATION_KEYS = [
47993
+ "DefaultIsolation",
47994
+ "DraftDefaultIsolation",
47995
+ ...ISOLATION_NUMERIC_KEYS,
47996
+ "ContainerImage",
47997
+ "ContainerRuntime"
47998
+ ];
47999
+ var TASK_GRAPH_QUEUE_NUMERIC_KEYS = [
48000
+ "MaxEnqueuePublishConcurrency",
48001
+ "EnqueuePublishBatchSize",
48002
+ "MaxConcurrentIsolatedRunners",
48003
+ "MaxEnqueueItemsPerFanOut",
48004
+ "MaxEnqueueRedeliveryAttempts",
48005
+ "EnqueuePublishRetryAttempts",
48006
+ "CallerNotificationRetentionMs"
48007
+ ];
48008
+ var TASK_GRAPH_QUEUE_KEYS = [
48009
+ "GraphDispatchTopicName",
48010
+ "DefaultEnqueueTopicName",
48011
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS
48012
+ ];
48013
+ var LIVENESS_KEYS = [
48014
+ "Enabled",
48015
+ "InactivityTimeoutMs",
48016
+ "OuterMaxWallClockMs",
48017
+ "StreamChunkTouchThrottleMs",
48018
+ "HttpHeadersTimeoutMs",
48019
+ "HttpBodyTimeoutMs"
48020
+ ];
48021
+ var STUCK_DETECTOR_NUMERIC_KEYS = [
48022
+ "WindowSize",
48023
+ "IdenticalToolCallThreshold",
48024
+ "ReadOnlyStepThreshold",
48025
+ "ReadOnlyPostDirectiveGraceSteps"
48026
+ ];
48027
+ var STUCK_DETECTOR_KEYS = [
48028
+ "Enabled",
48029
+ ...STUCK_DETECTOR_NUMERIC_KEYS
48030
+ ];
48031
+ var LIMITS_KEY_PATHS = [
48032
+ "AgentChannelConsecutiveTurns",
48033
+ "AgentChannelWakesPerHour",
48034
+ "AgentAbsoluteIterations",
48035
+ "MaxTasksPerAgentGraph",
48036
+ "WhileLoopMaxIterations",
48037
+ "ForEachMaxIterations",
48038
+ "MaxTasksPerGraph",
48039
+ "BriefingContributorTimeoutMs",
48040
+ "BriefingMaxContributorChars",
48041
+ "Budgets.PerRun.MaxCostUsd",
48042
+ "Budgets.PerRun.MaxWallClockMs",
48043
+ "Budgets.PerRun.MaxTokens",
48044
+ "Budgets.PerRoutine.MaxCostUsd",
48045
+ "Budgets.PerRoutine.MaxWallClockMs",
48046
+ "Budgets.PerUserPerDay.MaxCostUsd",
48047
+ "Budgets.PerUserPerDay.MaxWallClockMs",
48048
+ "Budgets.PerUserPerDay.DayBoundaryTimezone",
48049
+ "Budgets.CountPausedTimeTowardsWallClock",
48050
+ "Budgets.AllowedInFlightOvershootUsd",
48051
+ "Budgets.AllowedInFlightOvershootMs",
48052
+ "ProgressDetector.Enabled",
48053
+ "ProgressDetector.WindowSize",
48054
+ "ProgressDetector.MinIterationsBeforeCheck",
48055
+ "ProgressDetector.DuplicateStepRatioThreshold",
48056
+ "ProgressDetector.NoPayloadDeltaWindowCount",
48057
+ "ProgressDetector.RepeatingErrorWindowCount",
48058
+ "ProgressDetector.AmbiguityLowScoreThreshold",
48059
+ "ProgressDetector.AmbiguityHighScoreThreshold",
48060
+ "ProgressDetector.FastJudgeEnabled",
48061
+ "ProgressDetector.FastJudgeTimeoutMs",
48062
+ "ProgressDetector.FastJudgeMinIntervalIterations",
48063
+ "ProgressDetector.FastJudgeMaxInputChars",
48064
+ "ProgressDetector.FastJudgeFailureFallback",
48065
+ ...RESOURCE_GUARD_KEYS.map((k) => `ResourceGuards.${k}`),
48066
+ ...TUNING_KEYS.map((k) => `Tuning.${k}`),
48067
+ ...ISOLATION_KEYS.map((k) => `Isolation.${k}`),
48068
+ ...TASK_GRAPH_QUEUE_KEYS.map((k) => `TaskGraphQueue.${k}`),
48069
+ ...LIVENESS_KEYS.map((k) => `Liveness.${k}`),
48070
+ ...STUCK_DETECTOR_KEYS.map((k) => `StuckDetector.${k}`)
48071
+ ];
48072
+ var NUMERIC_CEILING_KEYS = /* @__PURE__ */ new Set([
48073
+ "AgentChannelConsecutiveTurns",
48074
+ "AgentChannelWakesPerHour",
48075
+ "AgentAbsoluteIterations",
48076
+ "MaxTasksPerAgentGraph",
48077
+ "WhileLoopMaxIterations",
48078
+ "ForEachMaxIterations",
48079
+ "MaxTasksPerGraph",
48080
+ "BriefingContributorTimeoutMs",
48081
+ "BriefingMaxContributorChars",
48082
+ "Budgets.PerRun.MaxCostUsd",
48083
+ "Budgets.PerRun.MaxWallClockMs",
48084
+ "Budgets.PerRun.MaxTokens",
48085
+ "Budgets.PerRoutine.MaxCostUsd",
48086
+ "Budgets.PerRoutine.MaxWallClockMs",
48087
+ "Budgets.PerUserPerDay.MaxCostUsd",
48088
+ "Budgets.PerUserPerDay.MaxWallClockMs",
48089
+ "Budgets.AllowedInFlightOvershootUsd",
48090
+ "Budgets.AllowedInFlightOvershootMs",
48091
+ "ProgressDetector.FastJudgeMaxInputChars",
48092
+ ...RESOURCE_GUARD_KEYS.map((k) => `ResourceGuards.${k}`),
48093
+ ...ISOLATION_NUMERIC_KEYS.map((k) => `Isolation.${k}`),
48094
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => `TaskGraphQueue.${k}`),
48095
+ "Liveness.InactivityTimeoutMs",
48096
+ "Liveness.OuterMaxWallClockMs",
48097
+ "StuckDetector.IdenticalToolCallThreshold",
48098
+ "StuckDetector.ReadOnlyStepThreshold",
48099
+ "StuckDetector.ReadOnlyPostDirectiveGraceSteps"
48100
+ ]);
48101
+ var LIMITS_KEY_ROLES = Object.fromEntries(LIMITS_KEY_PATHS.map((key) => [
48102
+ key,
48103
+ NUMERIC_CEILING_KEYS.has(key) ? "PolicyCeiling" : "OverridableDefault"
48104
+ ]));
48105
+ function GetLimitsKeyRole(key) {
48106
+ return LIMITS_KEY_ROLES[key];
48107
+ }
48108
+ var LIMITS_CEILING_OVERRIDE_AUTHORIZATIONS = [
48109
+ "System Administrator",
48110
+ "AI: Manage Agents"
48111
+ ];
48112
+ function CanUserRaiseEnforcedLimitsCeilings(user, provider) {
48113
+ if (!user) {
48114
+ return false;
48115
+ }
48116
+ const userType = typeof user.Type === "string" ? user.Type.trim().toLowerCase() : "";
48117
+ if (userType === "owner") {
48118
+ return true;
48119
+ }
48120
+ const authorizations = provider?.Authorizations ?? [];
48121
+ const allowedSet = new Set(LIMITS_CEILING_OVERRIDE_AUTHORIZATIONS.map((name) => name.toLowerCase()));
48122
+ const evaluator = new AuthorizationEvaluator();
48123
+ for (const auth of authorizations) {
48124
+ const name = auth.Name?.trim().toLowerCase();
48125
+ if (name && allowedSet.has(name) && evaluator.UserCanExecuteWithAncestors(auth, user, authorizations)) {
48126
+ return true;
48127
+ }
48128
+ }
48129
+ return false;
48130
+ }
48131
+ function isLimitsInputObject(raw) {
48132
+ return IsPlainObject(raw);
48133
+ }
48134
+ function readObjectProperty(obj, keys) {
48135
+ for (const key of keys) {
48136
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
48137
+ return obj[key];
48138
+ }
48139
+ }
48140
+ return void 0;
48141
+ }
48142
+ function readFiniteNonNegativeNumber(raw) {
48143
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) {
48144
+ return void 0;
48145
+ }
48146
+ return raw;
48147
+ }
48148
+ function readPositiveInteger(raw) {
48149
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 1) {
48150
+ return void 0;
48151
+ }
48152
+ return Math.trunc(raw);
48153
+ }
48154
+ function readNullableNonNegativeNumber(raw) {
48155
+ if (raw === null) {
48156
+ return null;
48157
+ }
48158
+ return readFiniteNonNegativeNumber(raw);
48159
+ }
48160
+ function readNullablePositiveInteger(raw) {
48161
+ if (raw === null) {
48162
+ return null;
48163
+ }
48164
+ return readPositiveInteger(raw);
48165
+ }
48166
+ function readUnitIntervalNumber(raw) {
48167
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0 || raw > 1) {
48168
+ return void 0;
48169
+ }
48170
+ return raw;
48171
+ }
48172
+ function readBoolean(raw) {
48173
+ return typeof raw === "boolean" ? raw : void 0;
48174
+ }
48175
+ function readNonEmptyString(raw) {
48176
+ if (typeof raw !== "string") {
48177
+ return void 0;
48178
+ }
48179
+ const trimmed = raw.trim();
48180
+ return trimmed.length > 0 ? trimmed : void 0;
48181
+ }
48182
+ function readFastJudgeFallback(raw) {
48183
+ if (raw === "ContinueWithWarning" || raw === "PauseForHuman") {
48184
+ return raw;
48185
+ }
48186
+ return void 0;
48187
+ }
48188
+ function readIsolationLevel(raw) {
48189
+ return IsTaskGraphIsolationLevel(raw) ? raw : void 0;
48190
+ }
48191
+ function normalizeIsolationOverride(raw) {
48192
+ if (!isLimitsInputObject(raw)) {
48193
+ return void 0;
48194
+ }
48195
+ const out = {};
48196
+ const defaultIso = readIsolationLevel(readObjectProperty(raw, ["DefaultIsolation", "defaultIsolation"]));
48197
+ if (defaultIso !== void 0)
48198
+ out.DefaultIsolation = defaultIso;
48199
+ const draftIso = readIsolationLevel(readObjectProperty(raw, ["DraftDefaultIsolation", "draftDefaultIsolation"]));
48200
+ if (draftIso !== void 0)
48201
+ out.DraftDefaultIsolation = draftIso;
48202
+ const numeric = normalizePositiveIntSection(raw, ISOLATION_NUMERIC_KEYS);
48203
+ if (numeric) {
48204
+ Object.assign(out, numeric);
48205
+ }
48206
+ const containerImage = readNonEmptyString(readObjectProperty(raw, ["ContainerImage", "containerImage"]));
48207
+ if (containerImage !== void 0)
48208
+ out.ContainerImage = containerImage;
48209
+ const containerRuntime = readNonEmptyString(readObjectProperty(raw, ["ContainerRuntime", "containerRuntime"]));
48210
+ if (containerRuntime !== void 0)
48211
+ out.ContainerRuntime = containerRuntime;
48212
+ return Object.keys(out).length > 0 ? out : void 0;
48213
+ }
48214
+ function normalizeTaskGraphQueueOverride(raw) {
48215
+ if (!isLimitsInputObject(raw)) {
48216
+ return void 0;
48217
+ }
48218
+ const out = {};
48219
+ const graphTopic = readNonEmptyString(readObjectProperty(raw, ["GraphDispatchTopicName", "graphDispatchTopicName"]));
48220
+ if (graphTopic !== void 0)
48221
+ out.GraphDispatchTopicName = graphTopic;
48222
+ const stepTopic = readNonEmptyString(readObjectProperty(raw, ["DefaultEnqueueTopicName", "defaultEnqueueTopicName"]));
48223
+ if (stepTopic !== void 0)
48224
+ out.DefaultEnqueueTopicName = stepTopic;
48225
+ const numeric = normalizePositiveIntSection(raw, TASK_GRAPH_QUEUE_NUMERIC_KEYS);
48226
+ if (numeric) {
48227
+ Object.assign(out, numeric);
48228
+ }
48229
+ return Object.keys(out).length > 0 ? out : void 0;
48230
+ }
48231
+ function normalizeLivenessOverride(raw) {
48232
+ if (!isLimitsInputObject(raw)) {
48233
+ return void 0;
48234
+ }
48235
+ const out = {};
48236
+ const enabled = readBoolean(readObjectProperty(raw, ["Enabled", "enabled", "LivenessEnabled", "livenessEnabled"]));
48237
+ if (enabled !== void 0)
48238
+ out.Enabled = enabled;
48239
+ const inactivity = readPositiveInteger(readObjectProperty(raw, ["InactivityTimeoutMs", "inactivityTimeoutMs"]));
48240
+ if (inactivity !== void 0)
48241
+ out.InactivityTimeoutMs = inactivity;
48242
+ const outerMax = readPositiveInteger(readObjectProperty(raw, ["OuterMaxWallClockMs", "outerMaxWallClockMs"]));
48243
+ if (outerMax !== void 0)
48244
+ out.OuterMaxWallClockMs = outerMax;
48245
+ const throttle = readFiniteNonNegativeNumber(readObjectProperty(raw, ["StreamChunkTouchThrottleMs", "streamChunkTouchThrottleMs"]));
48246
+ if (throttle !== void 0)
48247
+ out.StreamChunkTouchThrottleMs = Math.trunc(throttle);
48248
+ const headersTimeout = readFiniteNonNegativeNumber(readObjectProperty(raw, ["HttpHeadersTimeoutMs", "httpHeadersTimeoutMs"]));
48249
+ if (headersTimeout !== void 0)
48250
+ out.HttpHeadersTimeoutMs = Math.trunc(headersTimeout);
48251
+ const bodyTimeout = readFiniteNonNegativeNumber(readObjectProperty(raw, ["HttpBodyTimeoutMs", "httpBodyTimeoutMs"]));
48252
+ if (bodyTimeout !== void 0)
48253
+ out.HttpBodyTimeoutMs = Math.trunc(bodyTimeout);
48254
+ return Object.keys(out).length > 0 ? out : void 0;
48255
+ }
48256
+ function normalizeStuckDetectorOverride(raw) {
48257
+ if (!isLimitsInputObject(raw)) {
48258
+ return void 0;
48259
+ }
48260
+ const out = {};
48261
+ const enabled = readBoolean(readObjectProperty(raw, ["Enabled", "enabled"]));
48262
+ if (enabled !== void 0)
48263
+ out.Enabled = enabled;
48264
+ const numeric = normalizePositiveIntSection(raw, STUCK_DETECTOR_NUMERIC_KEYS);
48265
+ if (numeric) {
48266
+ Object.assign(out, numeric);
48267
+ }
48268
+ const legacyIdentical = readPositiveInteger(readObjectProperty(raw, ["RepeatedToolCallThreshold", "repeatedToolCallThreshold"]));
48269
+ if (out.IdenticalToolCallThreshold === void 0 && legacyIdentical !== void 0) {
48270
+ out.IdenticalToolCallThreshold = legacyIdentical;
48271
+ }
48272
+ const legacyReadOnly = readPositiveInteger(readObjectProperty(raw, ["ReadOnlySpiralThreshold", "readOnlySpiralThreshold"]));
48273
+ if (out.ReadOnlyStepThreshold === void 0 && legacyReadOnly !== void 0) {
48274
+ out.ReadOnlyStepThreshold = legacyReadOnly;
48275
+ }
48276
+ return Object.keys(out).length > 0 ? out : void 0;
48277
+ }
48278
+ function normalizeScopeBudgetOverride(raw) {
48279
+ if (!isLimitsInputObject(raw)) {
48280
+ return void 0;
48281
+ }
48282
+ const out = {};
48283
+ const maxCost = readNullableNonNegativeNumber(readObjectProperty(raw, ["MaxCostUsd", "maxCostUsd"]));
48284
+ if (maxCost !== void 0) {
48285
+ out.MaxCostUsd = maxCost;
48286
+ }
48287
+ const maxWall = readNullablePositiveInteger(readObjectProperty(raw, ["MaxWallClockMs", "maxWallClockMs"]));
48288
+ if (maxWall !== void 0) {
48289
+ out.MaxWallClockMs = maxWall;
48290
+ }
48291
+ return Object.keys(out).length > 0 ? out : void 0;
48292
+ }
48293
+ function normalizeRunScopeBudgetOverride(raw) {
48294
+ if (!isLimitsInputObject(raw)) {
48295
+ return void 0;
48296
+ }
48297
+ const base = normalizeScopeBudgetOverride(raw) ?? {};
48298
+ const out = { ...base };
48299
+ const maxTokens = readNullablePositiveInteger(readObjectProperty(raw, ["MaxTokens", "maxTokens"]));
48300
+ if (maxTokens !== void 0) {
48301
+ out.MaxTokens = maxTokens;
48302
+ }
48303
+ return Object.keys(out).length > 0 ? out : void 0;
48304
+ }
48305
+ function normalizeUserDailyScopeBudgetOverride(raw) {
48306
+ if (!isLimitsInputObject(raw)) {
48307
+ return void 0;
48308
+ }
48309
+ const base = normalizeScopeBudgetOverride(raw) ?? {};
48310
+ const out = { ...base };
48311
+ const tz = readNonEmptyString(readObjectProperty(raw, ["DayBoundaryTimezone", "dayBoundaryTimezone"]));
48312
+ if (tz !== void 0) {
48313
+ out.DayBoundaryTimezone = tz;
48314
+ }
48315
+ return Object.keys(out).length > 0 ? out : void 0;
48316
+ }
48317
+ function normalizeBudgetsOverride(raw) {
48318
+ if (!isLimitsInputObject(raw)) {
48319
+ return void 0;
48320
+ }
48321
+ const out = {};
48322
+ const perRun = normalizeRunScopeBudgetOverride(readObjectProperty(raw, ["PerRun", "perRun"]));
48323
+ if (perRun) {
48324
+ out.PerRun = perRun;
48325
+ }
48326
+ const perRoutine = normalizeScopeBudgetOverride(readObjectProperty(raw, ["PerRoutine", "perRoutine"]));
48327
+ if (perRoutine) {
48328
+ out.PerRoutine = perRoutine;
48329
+ }
48330
+ const perUserPerDay = normalizeUserDailyScopeBudgetOverride(readObjectProperty(raw, ["PerUserPerDay", "perUserPerDay"]));
48331
+ if (perUserPerDay) {
48332
+ out.PerUserPerDay = perUserPerDay;
48333
+ }
48334
+ const countPaused = readBoolean(readObjectProperty(raw, ["CountPausedTimeTowardsWallClock", "countPausedTimeTowardsWallClock"]));
48335
+ if (countPaused !== void 0) {
48336
+ out.CountPausedTimeTowardsWallClock = countPaused;
48337
+ }
48338
+ const overshootUsd = readFiniteNonNegativeNumber(readObjectProperty(raw, ["AllowedInFlightOvershootUsd", "allowedInFlightOvershootUsd"]));
48339
+ if (overshootUsd !== void 0) {
48340
+ out.AllowedInFlightOvershootUsd = overshootUsd;
48341
+ }
48342
+ const overshootMs = readFiniteNonNegativeNumber(readObjectProperty(raw, ["AllowedInFlightOvershootMs", "allowedInFlightOvershootMs"]));
48343
+ if (overshootMs !== void 0) {
48344
+ out.AllowedInFlightOvershootMs = overshootMs;
48345
+ }
48346
+ return Object.keys(out).length > 0 ? out : void 0;
48347
+ }
48348
+ function normalizeProgressDetectorOverride(raw) {
48349
+ if (!isLimitsInputObject(raw)) {
48350
+ return void 0;
48351
+ }
48352
+ const out = {};
48353
+ const enabled = readBoolean(readObjectProperty(raw, ["Enabled", "enabled"]));
48354
+ if (enabled !== void 0)
48355
+ out.Enabled = enabled;
48356
+ const windowSize = readPositiveInteger(readObjectProperty(raw, ["WindowSize", "windowSize"]));
48357
+ if (windowSize !== void 0)
48358
+ out.WindowSize = windowSize;
48359
+ const minIterations = readPositiveInteger(readObjectProperty(raw, ["MinIterationsBeforeCheck", "minIterationsBeforeCheck"]));
48360
+ if (minIterations !== void 0)
48361
+ out.MinIterationsBeforeCheck = minIterations;
48362
+ const dupRatio = readUnitIntervalNumber(readObjectProperty(raw, ["DuplicateStepRatioThreshold", "duplicateStepRatioThreshold"]));
48363
+ if (dupRatio !== void 0)
48364
+ out.DuplicateStepRatioThreshold = dupRatio;
48365
+ const noDelta = readPositiveInteger(readObjectProperty(raw, ["NoPayloadDeltaWindowCount", "noPayloadDeltaWindowCount"]));
48366
+ if (noDelta !== void 0)
48367
+ out.NoPayloadDeltaWindowCount = noDelta;
48368
+ const repErr = readPositiveInteger(readObjectProperty(raw, ["RepeatingErrorWindowCount", "repeatingErrorWindowCount"]));
48369
+ if (repErr !== void 0)
48370
+ out.RepeatingErrorWindowCount = repErr;
48371
+ const lowScore = readUnitIntervalNumber(readObjectProperty(raw, ["AmbiguityLowScoreThreshold", "ambiguityLowScoreThreshold"]));
48372
+ if (lowScore !== void 0)
48373
+ out.AmbiguityLowScoreThreshold = lowScore;
48374
+ const highScore = readUnitIntervalNumber(readObjectProperty(raw, ["AmbiguityHighScoreThreshold", "ambiguityHighScoreThreshold"]));
48375
+ if (highScore !== void 0)
48376
+ out.AmbiguityHighScoreThreshold = highScore;
48377
+ const fastJudgeEnabled = readBoolean(readObjectProperty(raw, ["FastJudgeEnabled", "fastJudgeEnabled"]));
48378
+ if (fastJudgeEnabled !== void 0)
48379
+ out.FastJudgeEnabled = fastJudgeEnabled;
48380
+ const fastJudgeTimeoutMs = readPositiveInteger(readObjectProperty(raw, ["FastJudgeTimeoutMs", "fastJudgeTimeoutMs"]));
48381
+ if (fastJudgeTimeoutMs !== void 0)
48382
+ out.FastJudgeTimeoutMs = fastJudgeTimeoutMs;
48383
+ const minInterval = readPositiveInteger(readObjectProperty(raw, ["FastJudgeMinIntervalIterations", "fastJudgeMinIntervalIterations"]));
48384
+ if (minInterval !== void 0)
48385
+ out.FastJudgeMinIntervalIterations = minInterval;
48386
+ const maxInputChars = readPositiveInteger(readObjectProperty(raw, ["FastJudgeMaxInputChars", "fastJudgeMaxInputChars"]));
48387
+ if (maxInputChars !== void 0)
48388
+ out.FastJudgeMaxInputChars = maxInputChars;
48389
+ const fallback = readFastJudgeFallback(readObjectProperty(raw, ["FastJudgeFailureFallback", "fastJudgeFailureFallback"]));
48390
+ if (fallback !== void 0)
48391
+ out.FastJudgeFailureFallback = fallback;
48392
+ return Object.keys(out).length > 0 ? out : void 0;
48393
+ }
48394
+ function normalizePositiveIntSection(raw, keys) {
48395
+ if (!isLimitsInputObject(raw)) {
48396
+ return void 0;
48397
+ }
48398
+ const out = {};
48399
+ for (const key of keys) {
48400
+ const camel = key.charAt(0).toLowerCase() + key.slice(1);
48401
+ const val = readPositiveInteger(readObjectProperty(raw, [key, camel]));
48402
+ if (val !== void 0) {
48403
+ out[key] = val;
48404
+ }
48405
+ }
48406
+ return Object.keys(out).length > 0 ? out : void 0;
48407
+ }
48408
+ function NormalizeLimitsInput(raw) {
48409
+ if (!isLimitsInputObject(raw)) {
48410
+ return {};
48411
+ }
48412
+ const out = {};
48413
+ const turns = readPositiveInteger(readObjectProperty(raw, ["AgentChannelConsecutiveTurns", "agentChannelConsecutiveTurns", "MaxConsecutiveAgentTurns", "maxConsecutiveAgentTurns"]));
48414
+ if (turns !== void 0)
48415
+ out.AgentChannelConsecutiveTurns = turns;
48416
+ const wakes = readPositiveInteger(readObjectProperty(raw, ["AgentChannelWakesPerHour", "agentChannelWakesPerHour", "MaxHourlyWakes", "maxHourlyWakes"]));
48417
+ if (wakes !== void 0)
48418
+ out.AgentChannelWakesPerHour = wakes;
48419
+ const iterations = readPositiveInteger(readObjectProperty(raw, ["AgentAbsoluteIterations", "agentAbsoluteIterations", "absoluteMaxIterations"]));
48420
+ if (iterations !== void 0)
48421
+ out.AgentAbsoluteIterations = iterations;
48422
+ const agentGraph = readPositiveInteger(readObjectProperty(raw, ["MaxTasksPerAgentGraph", "maxTasksPerAgentGraph", "MAX_TASKS_PER_AGENT_GRAPH"]));
48423
+ if (agentGraph !== void 0)
48424
+ out.MaxTasksPerAgentGraph = agentGraph;
48425
+ const whileMax = readPositiveInteger(readObjectProperty(raw, ["WhileLoopMaxIterations", "whileLoopMaxIterations"]));
48426
+ if (whileMax !== void 0)
48427
+ out.WhileLoopMaxIterations = whileMax;
48428
+ const forEachMax = readPositiveInteger(readObjectProperty(raw, ["ForEachMaxIterations", "forEachMaxIterations"]));
48429
+ if (forEachMax !== void 0)
48430
+ out.ForEachMaxIterations = forEachMax;
48431
+ const graphCeiling = readPositiveInteger(readObjectProperty(raw, ["MaxTasksPerGraph", "maxTasksPerGraph", "MAX_TASKS_PER_GRAPH"]));
48432
+ if (graphCeiling !== void 0)
48433
+ out.MaxTasksPerGraph = graphCeiling;
48434
+ const briefingTimeout = readPositiveInteger(readObjectProperty(raw, ["BriefingContributorTimeoutMs", "briefingContributorTimeoutMs", "ContributorTimeoutMs"]));
48435
+ if (briefingTimeout !== void 0)
48436
+ out.BriefingContributorTimeoutMs = briefingTimeout;
48437
+ const briefingChars = readPositiveInteger(readObjectProperty(raw, ["BriefingMaxContributorChars", "briefingMaxContributorChars", "MaxContributorChars"]));
48438
+ if (briefingChars !== void 0)
48439
+ out.BriefingMaxContributorChars = briefingChars;
48440
+ const budgets = normalizeBudgetsOverride(readObjectProperty(raw, ["Budgets", "budgets"]));
48441
+ if (budgets)
48442
+ out.Budgets = budgets;
48443
+ const progressDetector = normalizeProgressDetectorOverride(readObjectProperty(raw, ["ProgressDetector", "progressDetector"]));
48444
+ if (progressDetector)
48445
+ out.ProgressDetector = progressDetector;
48446
+ const resourceGuards = normalizePositiveIntSection(readObjectProperty(raw, ["ResourceGuards", "resourceGuards"]), RESOURCE_GUARD_KEYS);
48447
+ if (resourceGuards)
48448
+ out.ResourceGuards = resourceGuards;
48449
+ const tuning = normalizePositiveIntSection(readObjectProperty(raw, ["Tuning", "tuning"]), TUNING_KEYS);
48450
+ if (tuning)
48451
+ out.Tuning = tuning;
48452
+ const isolation = normalizeIsolationOverride(readObjectProperty(raw, ["Isolation", "isolation"]));
48453
+ if (isolation)
48454
+ out.Isolation = isolation;
48455
+ const taskGraphQueue = normalizeTaskGraphQueueOverride(readObjectProperty(raw, ["TaskGraphQueue", "taskGraphQueue"]));
48456
+ if (taskGraphQueue)
48457
+ out.TaskGraphQueue = taskGraphQueue;
48458
+ const liveness = normalizeLivenessOverride(readObjectProperty(raw, ["Liveness", "liveness"]));
48459
+ if (liveness)
48460
+ out.Liveness = liveness;
48461
+ const stuckDetector = normalizeStuckDetectorOverride(readObjectProperty(raw, ["StuckDetector", "stuckDetector"]));
48462
+ if (stuckDetector)
48463
+ out.StuckDetector = stuckDetector;
48464
+ return out;
48465
+ }
48466
+ function cloneDefaultLimits() {
48467
+ return {
48468
+ ...CODE_FALLBACK_LIMITS,
48469
+ Budgets: {
48470
+ PerRun: { ...CODE_FALLBACK_LIMITS.Budgets.PerRun },
48471
+ PerRoutine: { ...CODE_FALLBACK_LIMITS.Budgets.PerRoutine },
48472
+ PerUserPerDay: { ...CODE_FALLBACK_LIMITS.Budgets.PerUserPerDay },
48473
+ CountPausedTimeTowardsWallClock: CODE_FALLBACK_LIMITS.Budgets.CountPausedTimeTowardsWallClock,
48474
+ AllowedInFlightOvershootUsd: CODE_FALLBACK_LIMITS.Budgets.AllowedInFlightOvershootUsd,
48475
+ AllowedInFlightOvershootMs: CODE_FALLBACK_LIMITS.Budgets.AllowedInFlightOvershootMs
48476
+ },
48477
+ ProgressDetector: { ...CODE_FALLBACK_LIMITS.ProgressDetector },
48478
+ ResourceGuards: { ...CODE_FALLBACK_LIMITS.ResourceGuards },
48479
+ Tuning: { ...CODE_FALLBACK_LIMITS.Tuning },
48480
+ Isolation: { ...CODE_FALLBACK_LIMITS.Isolation },
48481
+ TaskGraphQueue: { ...CODE_FALLBACK_LIMITS.TaskGraphQueue },
48482
+ Liveness: { ...CODE_FALLBACK_LIMITS.Liveness },
48483
+ StuckDetector: { ...CODE_FALLBACK_LIMITS.StuckDetector }
48484
+ };
48485
+ }
48486
+ function extractTierValue(layer, key) {
48487
+ if (key.startsWith("ResourceGuards.")) {
48488
+ const subKey = key.slice("ResourceGuards.".length);
48489
+ return layer.ResourceGuards?.[subKey];
48490
+ }
48491
+ if (key.startsWith("Tuning.")) {
48492
+ const subKey = key.slice("Tuning.".length);
48493
+ return layer.Tuning?.[subKey];
48494
+ }
48495
+ if (key.startsWith("Isolation.")) {
48496
+ const subKey = key.slice("Isolation.".length);
48497
+ return layer.Isolation?.[subKey];
48498
+ }
48499
+ if (key.startsWith("TaskGraphQueue.")) {
48500
+ const subKey = key.slice("TaskGraphQueue.".length);
48501
+ return layer.TaskGraphQueue?.[subKey];
48502
+ }
48503
+ if (key.startsWith("Liveness.")) {
48504
+ const subKey = key.slice("Liveness.".length);
48505
+ return layer.Liveness?.[subKey];
48506
+ }
48507
+ if (key.startsWith("StuckDetector.")) {
48508
+ const subKey = key.slice("StuckDetector.".length);
48509
+ return layer.StuckDetector?.[subKey];
48510
+ }
48511
+ switch (key) {
48512
+ case "AgentChannelConsecutiveTurns":
48513
+ return layer.AgentChannelConsecutiveTurns;
48514
+ case "AgentChannelWakesPerHour":
48515
+ return layer.AgentChannelWakesPerHour;
48516
+ case "AgentAbsoluteIterations":
48517
+ return layer.AgentAbsoluteIterations;
48518
+ case "MaxTasksPerAgentGraph":
48519
+ return layer.MaxTasksPerAgentGraph;
48520
+ case "WhileLoopMaxIterations":
48521
+ return layer.WhileLoopMaxIterations;
48522
+ case "ForEachMaxIterations":
48523
+ return layer.ForEachMaxIterations;
48524
+ case "MaxTasksPerGraph":
48525
+ return layer.MaxTasksPerGraph;
48526
+ case "BriefingContributorTimeoutMs":
48527
+ return layer.BriefingContributorTimeoutMs;
48528
+ case "BriefingMaxContributorChars":
48529
+ return layer.BriefingMaxContributorChars;
48530
+ case "Budgets.PerRun.MaxCostUsd":
48531
+ return layer.Budgets?.PerRun?.MaxCostUsd;
48532
+ case "Budgets.PerRun.MaxWallClockMs":
48533
+ return layer.Budgets?.PerRun?.MaxWallClockMs;
48534
+ case "Budgets.PerRun.MaxTokens":
48535
+ return layer.Budgets?.PerRun?.MaxTokens;
48536
+ case "Budgets.PerRoutine.MaxCostUsd":
48537
+ return layer.Budgets?.PerRoutine?.MaxCostUsd;
48538
+ case "Budgets.PerRoutine.MaxWallClockMs":
48539
+ return layer.Budgets?.PerRoutine?.MaxWallClockMs;
48540
+ case "Budgets.PerUserPerDay.MaxCostUsd":
48541
+ return layer.Budgets?.PerUserPerDay?.MaxCostUsd;
48542
+ case "Budgets.PerUserPerDay.MaxWallClockMs":
48543
+ return layer.Budgets?.PerUserPerDay?.MaxWallClockMs;
48544
+ case "Budgets.PerUserPerDay.DayBoundaryTimezone":
48545
+ return layer.Budgets?.PerUserPerDay?.DayBoundaryTimezone;
48546
+ case "Budgets.CountPausedTimeTowardsWallClock":
48547
+ return layer.Budgets?.CountPausedTimeTowardsWallClock;
48548
+ case "Budgets.AllowedInFlightOvershootUsd":
48549
+ return layer.Budgets?.AllowedInFlightOvershootUsd;
48550
+ case "Budgets.AllowedInFlightOvershootMs":
48551
+ return layer.Budgets?.AllowedInFlightOvershootMs;
48552
+ case "ProgressDetector.Enabled":
48553
+ return layer.ProgressDetector?.Enabled;
48554
+ case "ProgressDetector.WindowSize":
48555
+ return layer.ProgressDetector?.WindowSize;
48556
+ case "ProgressDetector.MinIterationsBeforeCheck":
48557
+ return layer.ProgressDetector?.MinIterationsBeforeCheck;
48558
+ case "ProgressDetector.DuplicateStepRatioThreshold":
48559
+ return layer.ProgressDetector?.DuplicateStepRatioThreshold;
48560
+ case "ProgressDetector.NoPayloadDeltaWindowCount":
48561
+ return layer.ProgressDetector?.NoPayloadDeltaWindowCount;
48562
+ case "ProgressDetector.RepeatingErrorWindowCount":
48563
+ return layer.ProgressDetector?.RepeatingErrorWindowCount;
48564
+ case "ProgressDetector.AmbiguityLowScoreThreshold":
48565
+ return layer.ProgressDetector?.AmbiguityLowScoreThreshold;
48566
+ case "ProgressDetector.AmbiguityHighScoreThreshold":
48567
+ return layer.ProgressDetector?.AmbiguityHighScoreThreshold;
48568
+ case "ProgressDetector.FastJudgeEnabled":
48569
+ return layer.ProgressDetector?.FastJudgeEnabled;
48570
+ case "ProgressDetector.FastJudgeTimeoutMs":
48571
+ return layer.ProgressDetector?.FastJudgeTimeoutMs;
48572
+ case "ProgressDetector.FastJudgeMinIntervalIterations":
48573
+ return layer.ProgressDetector?.FastJudgeMinIntervalIterations;
48574
+ case "ProgressDetector.FastJudgeMaxInputChars":
48575
+ return layer.ProgressDetector?.FastJudgeMaxInputChars;
48576
+ case "ProgressDetector.FastJudgeFailureFallback":
48577
+ return layer.ProgressDetector?.FastJudgeFailureFallback;
48578
+ }
48579
+ }
48580
+ function assignResolvedValue(target, key, value) {
48581
+ if (key.startsWith("ResourceGuards.")) {
48582
+ const subKey = key.slice("ResourceGuards.".length);
48583
+ target.ResourceGuards[subKey] = value;
48584
+ return;
48585
+ }
48586
+ if (key.startsWith("Tuning.")) {
48587
+ const subKey = key.slice("Tuning.".length);
48588
+ target.Tuning[subKey] = value;
48589
+ return;
48590
+ }
48591
+ if (key.startsWith("Isolation.")) {
48592
+ const subKey = key.slice("Isolation.".length);
48593
+ if (subKey === "ContainerImage" || subKey === "ContainerRuntime") {
48594
+ target.Isolation[subKey] = value;
48595
+ } else if (subKey === "DefaultIsolation" || subKey === "DraftDefaultIsolation") {
48596
+ target.Isolation[subKey] = value;
48597
+ } else {
48598
+ target.Isolation[subKey] = value;
48599
+ }
48600
+ return;
48601
+ }
48602
+ if (key.startsWith("TaskGraphQueue.")) {
48603
+ const subKey = key.slice("TaskGraphQueue.".length);
48604
+ if (subKey === "GraphDispatchTopicName" || subKey === "DefaultEnqueueTopicName") {
48605
+ target.TaskGraphQueue[subKey] = value;
48606
+ } else {
48607
+ target.TaskGraphQueue[subKey] = value;
48608
+ }
48609
+ return;
48610
+ }
48611
+ if (key.startsWith("Liveness.")) {
48612
+ const subKey = key.slice("Liveness.".length);
48613
+ if (subKey === "Enabled") {
48614
+ target.Liveness.Enabled = value;
48615
+ } else {
48616
+ target.Liveness[subKey] = value;
48617
+ }
48618
+ return;
48619
+ }
48620
+ if (key.startsWith("StuckDetector.")) {
48621
+ const subKey = key.slice("StuckDetector.".length);
48622
+ if (subKey === "Enabled") {
48623
+ target.StuckDetector.Enabled = value;
48624
+ } else {
48625
+ target.StuckDetector[subKey] = value;
48626
+ }
48627
+ return;
48628
+ }
48629
+ switch (key) {
48630
+ case "AgentChannelConsecutiveTurns":
48631
+ target.AgentChannelConsecutiveTurns = value;
48632
+ break;
48633
+ case "AgentChannelWakesPerHour":
48634
+ target.AgentChannelWakesPerHour = value;
48635
+ break;
48636
+ case "AgentAbsoluteIterations":
48637
+ target.AgentAbsoluteIterations = value;
48638
+ break;
48639
+ case "MaxTasksPerAgentGraph":
48640
+ target.MaxTasksPerAgentGraph = value;
48641
+ break;
48642
+ case "WhileLoopMaxIterations":
48643
+ target.WhileLoopMaxIterations = value;
48644
+ break;
48645
+ case "ForEachMaxIterations":
48646
+ target.ForEachMaxIterations = value;
48647
+ break;
48648
+ case "MaxTasksPerGraph":
48649
+ target.MaxTasksPerGraph = value;
48650
+ break;
48651
+ case "BriefingContributorTimeoutMs":
48652
+ target.BriefingContributorTimeoutMs = value;
48653
+ break;
48654
+ case "BriefingMaxContributorChars":
48655
+ target.BriefingMaxContributorChars = value;
48656
+ break;
48657
+ case "Budgets.PerRun.MaxCostUsd":
48658
+ target.Budgets.PerRun.MaxCostUsd = value;
48659
+ break;
48660
+ case "Budgets.PerRun.MaxWallClockMs":
48661
+ target.Budgets.PerRun.MaxWallClockMs = value;
48662
+ break;
48663
+ case "Budgets.PerRun.MaxTokens":
48664
+ target.Budgets.PerRun.MaxTokens = value;
48665
+ break;
48666
+ case "Budgets.PerRoutine.MaxCostUsd":
48667
+ target.Budgets.PerRoutine.MaxCostUsd = value;
48668
+ break;
48669
+ case "Budgets.PerRoutine.MaxWallClockMs":
48670
+ target.Budgets.PerRoutine.MaxWallClockMs = value;
48671
+ break;
48672
+ case "Budgets.PerUserPerDay.MaxCostUsd":
48673
+ target.Budgets.PerUserPerDay.MaxCostUsd = value;
48674
+ break;
48675
+ case "Budgets.PerUserPerDay.MaxWallClockMs":
48676
+ target.Budgets.PerUserPerDay.MaxWallClockMs = value;
48677
+ break;
48678
+ case "Budgets.PerUserPerDay.DayBoundaryTimezone":
48679
+ target.Budgets.PerUserPerDay.DayBoundaryTimezone = value;
48680
+ break;
48681
+ case "Budgets.CountPausedTimeTowardsWallClock":
48682
+ target.Budgets.CountPausedTimeTowardsWallClock = value;
48683
+ break;
48684
+ case "Budgets.AllowedInFlightOvershootUsd":
48685
+ target.Budgets.AllowedInFlightOvershootUsd = value;
48686
+ break;
48687
+ case "Budgets.AllowedInFlightOvershootMs":
48688
+ target.Budgets.AllowedInFlightOvershootMs = value;
48689
+ break;
48690
+ case "ProgressDetector.Enabled":
48691
+ target.ProgressDetector.Enabled = value;
48692
+ break;
48693
+ case "ProgressDetector.WindowSize":
48694
+ target.ProgressDetector.WindowSize = value;
48695
+ break;
48696
+ case "ProgressDetector.MinIterationsBeforeCheck":
48697
+ target.ProgressDetector.MinIterationsBeforeCheck = value;
48698
+ break;
48699
+ case "ProgressDetector.DuplicateStepRatioThreshold":
48700
+ target.ProgressDetector.DuplicateStepRatioThreshold = value;
48701
+ break;
48702
+ case "ProgressDetector.NoPayloadDeltaWindowCount":
48703
+ target.ProgressDetector.NoPayloadDeltaWindowCount = value;
48704
+ break;
48705
+ case "ProgressDetector.RepeatingErrorWindowCount":
48706
+ target.ProgressDetector.RepeatingErrorWindowCount = value;
48707
+ break;
48708
+ case "ProgressDetector.AmbiguityLowScoreThreshold":
48709
+ target.ProgressDetector.AmbiguityLowScoreThreshold = value;
48710
+ break;
48711
+ case "ProgressDetector.AmbiguityHighScoreThreshold":
48712
+ target.ProgressDetector.AmbiguityHighScoreThreshold = value;
48713
+ break;
48714
+ case "ProgressDetector.FastJudgeEnabled":
48715
+ target.ProgressDetector.FastJudgeEnabled = value;
48716
+ break;
48717
+ case "ProgressDetector.FastJudgeTimeoutMs":
48718
+ target.ProgressDetector.FastJudgeTimeoutMs = value;
48719
+ break;
48720
+ case "ProgressDetector.FastJudgeMinIntervalIterations":
48721
+ target.ProgressDetector.FastJudgeMinIntervalIterations = value;
48722
+ break;
48723
+ case "ProgressDetector.FastJudgeMaxInputChars":
48724
+ target.ProgressDetector.FastJudgeMaxInputChars = value;
48725
+ break;
48726
+ case "ProgressDetector.FastJudgeFailureFallback":
48727
+ target.ProgressDetector.FastJudgeFailureFallback = value;
48728
+ break;
48729
+ }
48730
+ }
48731
+ function shouldClampToPolicyCeiling(key, runVal, policyVal) {
48732
+ if (!NUMERIC_CEILING_KEYS.has(key) || typeof policyVal !== "number" || !Number.isFinite(policyVal)) {
48733
+ return false;
48734
+ }
48735
+ if (runVal === null) {
48736
+ return true;
48737
+ }
48738
+ return typeof runVal === "number" && Number.isFinite(runVal) && runVal > policyVal;
48739
+ }
48740
+ function resolveSingleKey(key, defaults, tiers, enforceUserPolicyCeiling, enforceConfiguredCeilings, callerCanRaiseCeilings) {
48741
+ const codeFallbackBase = extractTierValue(defaults, key) ?? null;
48742
+ const tierValues = {
48743
+ CodeFallback: codeFallbackBase
48744
+ };
48745
+ let preRunValue = codeFallbackBase;
48746
+ let preRunTier = "CodeFallback";
48747
+ let wasClamped = false;
48748
+ for (const tier of LIMITS_TIER_PRECEDENCE) {
48749
+ if (tier === "RunOverride") {
48750
+ continue;
48751
+ }
48752
+ const layer = tiers[tier];
48753
+ if (!layer) {
48754
+ continue;
48755
+ }
48756
+ const candidate = extractTierValue(layer, key);
48757
+ if (candidate !== void 0) {
48758
+ tierValues[tier] = candidate;
48759
+ if (tier === "UserAgentPolicy" && !callerCanRaiseCeilings) {
48760
+ const mjConfigVal = tierValues.MjConfig;
48761
+ const clampAgainstPreRun = enforceConfiguredCeilings && shouldClampToPolicyCeiling(key, candidate, preRunValue);
48762
+ const clampAgainstMjConfig = (enforceConfiguredCeilings || enforceUserPolicyCeiling) && shouldClampToPolicyCeiling(key, candidate, mjConfigVal);
48763
+ if (clampAgainstPreRun || clampAgainstMjConfig) {
48764
+ if (clampAgainstMjConfig && (!clampAgainstPreRun || typeof mjConfigVal === "number" && typeof preRunValue === "number" && mjConfigVal <= preRunValue)) {
48765
+ preRunValue = mjConfigVal;
48766
+ preRunTier = "MjConfig";
48767
+ }
48768
+ wasClamped = true;
48769
+ continue;
48770
+ }
48771
+ }
48772
+ preRunValue = candidate;
48773
+ preRunTier = tier;
48774
+ }
48775
+ }
48776
+ let winningValue = preRunValue;
48777
+ let sourceTier = preRunTier;
48778
+ const runLayer = tiers.RunOverride;
48779
+ const runCandidate = runLayer ? extractTierValue(runLayer, key) : void 0;
48780
+ if (runCandidate !== void 0) {
48781
+ tierValues.RunOverride = runCandidate;
48782
+ winningValue = runCandidate;
48783
+ sourceTier = "RunOverride";
48784
+ if (!callerCanRaiseCeilings) {
48785
+ if (enforceConfiguredCeilings && shouldClampToPolicyCeiling(key, winningValue, preRunValue)) {
48786
+ winningValue = preRunValue;
48787
+ sourceTier = preRunTier;
48788
+ wasClamped = true;
48789
+ } else if (enforceUserPolicyCeiling && tierValues.UserAgentPolicy !== void 0) {
48790
+ const effectivePolicyCeiling = preRunTier === "MjConfig" || preRunTier === "UserAgentPolicy" ? preRunValue : tierValues.UserAgentPolicy;
48791
+ if (shouldClampToPolicyCeiling(key, winningValue, effectivePolicyCeiling)) {
48792
+ winningValue = effectivePolicyCeiling;
48793
+ sourceTier = preRunTier === "MjConfig" ? "MjConfig" : "UserAgentPolicy";
48794
+ wasClamped = true;
48795
+ }
48796
+ }
48797
+ }
48798
+ }
48799
+ return {
48800
+ Key: key,
48801
+ KeyRole: GetLimitsKeyRole(key),
48802
+ Value: winningValue,
48803
+ SourceTier: sourceTier,
48804
+ IsOverridden: sourceTier !== "CodeFallback",
48805
+ TierValues: tierValues,
48806
+ WasClampedByPolicyCeiling: wasClamped
48807
+ };
48808
+ }
48809
+ function ValidateLimitsConfig(config) {
48810
+ const issues = [];
48811
+ const positiveIntChecks = [
48812
+ ["AgentChannelConsecutiveTurns", config.AgentChannelConsecutiveTurns],
48813
+ ["AgentChannelWakesPerHour", config.AgentChannelWakesPerHour],
48814
+ ["AgentAbsoluteIterations", config.AgentAbsoluteIterations],
48815
+ ["MaxTasksPerAgentGraph", config.MaxTasksPerAgentGraph],
48816
+ ["WhileLoopMaxIterations", config.WhileLoopMaxIterations],
48817
+ ["ForEachMaxIterations", config.ForEachMaxIterations],
48818
+ ["MaxTasksPerGraph", config.MaxTasksPerGraph],
48819
+ ["BriefingContributorTimeoutMs", config.BriefingContributorTimeoutMs],
48820
+ ["BriefingMaxContributorChars", config.BriefingMaxContributorChars],
48821
+ ["ProgressDetector.WindowSize", config.ProgressDetector.WindowSize],
48822
+ ["ProgressDetector.MinIterationsBeforeCheck", config.ProgressDetector.MinIterationsBeforeCheck],
48823
+ ["ProgressDetector.NoPayloadDeltaWindowCount", config.ProgressDetector.NoPayloadDeltaWindowCount],
48824
+ ["ProgressDetector.RepeatingErrorWindowCount", config.ProgressDetector.RepeatingErrorWindowCount],
48825
+ ["ProgressDetector.FastJudgeTimeoutMs", config.ProgressDetector.FastJudgeTimeoutMs],
48826
+ ["ProgressDetector.FastJudgeMinIntervalIterations", config.ProgressDetector.FastJudgeMinIntervalIterations],
48827
+ ["ProgressDetector.FastJudgeMaxInputChars", config.ProgressDetector.FastJudgeMaxInputChars],
48828
+ ...RESOURCE_GUARD_KEYS.map((k) => [`ResourceGuards.${k}`, config.ResourceGuards[k]]),
48829
+ ...TUNING_KEYS.map((k) => [`Tuning.${k}`, config.Tuning[k]]),
48830
+ ...ISOLATION_NUMERIC_KEYS.map((k) => [`Isolation.${k}`, config.Isolation[k]]),
48831
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => [`TaskGraphQueue.${k}`, config.TaskGraphQueue[k]]),
48832
+ ["Liveness.InactivityTimeoutMs", config.Liveness.InactivityTimeoutMs],
48833
+ ["Liveness.OuterMaxWallClockMs", config.Liveness.OuterMaxWallClockMs],
48834
+ ...STUCK_DETECTOR_NUMERIC_KEYS.map((k) => [`StuckDetector.${k}`, config.StuckDetector[k]])
48835
+ ];
48836
+ for (const [key, val] of positiveIntChecks) {
48837
+ if (!Number.isFinite(val) || val < 1) {
48838
+ issues.push({ Key: key, Message: `${key} must be a positive number >= 1.` });
48839
+ }
48840
+ }
48841
+ const nonNegativeLivenessChecks = [
48842
+ ["Liveness.StreamChunkTouchThrottleMs", config.Liveness.StreamChunkTouchThrottleMs],
48843
+ ["Liveness.HttpHeadersTimeoutMs", config.Liveness.HttpHeadersTimeoutMs],
48844
+ ["Liveness.HttpBodyTimeoutMs", config.Liveness.HttpBodyTimeoutMs]
48845
+ ];
48846
+ for (const [key, val] of nonNegativeLivenessChecks) {
48847
+ if (!Number.isFinite(val) || val < 0) {
48848
+ issues.push({ Key: key, Message: `${key} must be a non-negative number >= 0.` });
48849
+ }
48850
+ }
48851
+ if (!IsTaskGraphIsolationLevel(config.Isolation.DefaultIsolation)) {
48852
+ issues.push({
48853
+ Key: "Isolation.DefaultIsolation",
48854
+ Message: "Isolation.DefaultIsolation must be one of InProcess, Worker, Process, or Container."
48855
+ });
48856
+ }
48857
+ if (!IsTaskGraphIsolationLevel(config.Isolation.DraftDefaultIsolation)) {
48858
+ issues.push({
48859
+ Key: "Isolation.DraftDefaultIsolation",
48860
+ Message: "Isolation.DraftDefaultIsolation must be one of InProcess, Worker, Process, or Container."
48861
+ });
48862
+ }
48863
+ if (!config.Isolation.ContainerImage || !config.Isolation.ContainerImage.trim()) {
48864
+ issues.push({
48865
+ Key: "Isolation.ContainerImage",
48866
+ Message: "Isolation.ContainerImage must be a non-empty string."
48867
+ });
48868
+ }
48869
+ if (!config.Isolation.ContainerRuntime || !config.Isolation.ContainerRuntime.trim()) {
48870
+ issues.push({
48871
+ Key: "Isolation.ContainerRuntime",
48872
+ Message: "Isolation.ContainerRuntime must be a non-empty string."
48873
+ });
48874
+ }
48875
+ if (!config.TaskGraphQueue.GraphDispatchTopicName || !config.TaskGraphQueue.GraphDispatchTopicName.trim()) {
48876
+ issues.push({
48877
+ Key: "TaskGraphQueue.GraphDispatchTopicName",
48878
+ Message: "TaskGraphQueue.GraphDispatchTopicName must be a non-empty string."
48879
+ });
48880
+ }
48881
+ if (!config.TaskGraphQueue.DefaultEnqueueTopicName || !config.TaskGraphQueue.DefaultEnqueueTopicName.trim()) {
48882
+ issues.push({
48883
+ Key: "TaskGraphQueue.DefaultEnqueueTopicName",
48884
+ Message: "TaskGraphQueue.DefaultEnqueueTopicName must be a non-empty string."
48885
+ });
48886
+ }
48887
+ if (config.MaxTasksPerAgentGraph > config.MaxTasksPerGraph) {
48888
+ issues.push({
48889
+ Key: "MaxTasksPerAgentGraph",
48890
+ Message: "MaxTasksPerAgentGraph cannot exceed MaxTasksPerGraph."
48891
+ });
48892
+ }
48893
+ if (config.ProgressDetector.AmbiguityLowScoreThreshold > config.ProgressDetector.AmbiguityHighScoreThreshold) {
48894
+ issues.push({
48895
+ Key: "ProgressDetector.AmbiguityLowScoreThreshold",
48896
+ Message: "AmbiguityLowScoreThreshold cannot exceed AmbiguityHighScoreThreshold."
48897
+ });
48898
+ }
48899
+ return { Valid: issues.length === 0, Issues: issues };
48900
+ }
48901
+ var LimitsConfigResolver = class _LimitsConfigResolver extends BaseSingleton {
48902
+ constructor() {
48903
+ super();
48904
+ this.registeredMjConfigLimits = null;
48905
+ }
48906
+ /** Returns the process-wide singleton {@link LimitsConfigResolver}. */
48907
+ static get Instance() {
48908
+ return _LimitsConfigResolver.getInstance();
48909
+ }
48910
+ /**
48911
+ * Convenience static entry point delegating to {@link LimitsConfigResolver.Instance.Resolve}.
48912
+ */
48913
+ static Resolve(input, options) {
48914
+ return _LimitsConfigResolver.Instance.Resolve(input, options);
48915
+ }
48916
+ /**
48917
+ * Registers Tier 2 (`MjConfig`) limits loaded from `mj.config.cjs` by a host bootstrapper.
48918
+ * Pass `null` to clear any registered config.
48919
+ */
48920
+ RegisterMjConfigLimits(limits) {
48921
+ if (limits === null) {
48922
+ this.registeredMjConfigLimits = null;
48923
+ return;
48924
+ }
48925
+ this.registeredMjConfigLimits = NormalizeLimitsInput(limits);
48926
+ }
48927
+ /** Returns the currently registered Tier 2 (`MjConfig`) override, or `null` when unset. */
48928
+ GetMjConfigLimits() {
48929
+ return this.registeredMjConfigLimits;
48930
+ }
48931
+ /** Clears any registered Tier 2 (`MjConfig`) override (primarily for unit test isolation). */
48932
+ ClearMjConfigLimits() {
48933
+ this.registeredMjConfigLimits = null;
48934
+ }
48935
+ /**
48936
+ * Resolves all limit keys across the 5 precedence tiers (`CodeFallback` -> `MjConfig` ->
48937
+ * `AgentOrWorkflowMetadata` -> `UserAgentPolicy` -> `RunOverride`), tracking full provenance.
48938
+ */
48939
+ Resolve(input = {}, options = {}) {
48940
+ const defaults = cloneDefaultLimits();
48941
+ const mjConfigTier = input.MjConfig !== void 0 ? input.MjConfig : this.registeredMjConfigLimits;
48942
+ const tiers = {
48943
+ CodeFallback: input.CodeFallback ?? null,
48944
+ MjConfig: mjConfigTier ?? null,
48945
+ AgentOrWorkflowMetadata: input.AgentOrWorkflowMetadata ?? null,
48946
+ UserAgentPolicy: input.UserAgentPolicy ?? null,
48947
+ RunOverride: input.RunOverride ?? null
48948
+ };
48949
+ const resolvedLimits = cloneDefaultLimits();
48950
+ const provenanceEntries = [];
48951
+ const overriddenKeys = [];
48952
+ const clampedKeys = [];
48953
+ const enforceUserPolicyCeiling = options.EnforceUserPolicyAsCeiling === true;
48954
+ const enforceConfiguredCeilings = options.EnforceConfiguredCeilings === true;
48955
+ const callerCanRaiseCeilings = options.AllowAuthorizedCeilingOverride === true && CanUserRaiseEnforcedLimitsCeilings(options.ContextUser, options.Provider);
48956
+ for (const key of LIMITS_KEY_PATHS) {
48957
+ const keyProvenance = resolveSingleKey(key, defaults, tiers, enforceUserPolicyCeiling, enforceConfiguredCeilings, callerCanRaiseCeilings);
48958
+ assignResolvedValue(resolvedLimits, key, keyProvenance.Value);
48959
+ provenanceEntries.push([key, keyProvenance]);
48960
+ if (keyProvenance.IsOverridden) {
48961
+ overriddenKeys.push(key);
48962
+ }
48963
+ if (keyProvenance.WasClampedByPolicyCeiling) {
48964
+ clampedKeys.push(key);
48965
+ }
48966
+ }
48967
+ return {
48968
+ Limits: resolvedLimits,
48969
+ Provenance: Object.fromEntries(provenanceEntries),
48970
+ ResolvedAtISO: options.ResolvedAtISO ?? (/* @__PURE__ */ new Date()).toISOString(),
48971
+ OverriddenKeys: overriddenKeys,
48972
+ ClampedKeys: clampedKeys
48973
+ };
48974
+ }
48975
+ /**
48976
+ * Reads a single resolved limit value from a resolution result by canonical key path.
48977
+ */
48978
+ GetLimitValue(result, key) {
48979
+ return result.Provenance[key].Value;
48980
+ }
48981
+ };
48982
+
46925
48983
  // ../../MJCore/dist/generic/graphqlTypeNames.js
46926
48984
  var MJ_CORE_SCHEMA = "__mj";
46927
48985
  function SanitizeGraphQLName(input) {
@@ -47444,6 +49502,915 @@ var PermissionDeniedError = class _PermissionDeniedError extends Error {
47444
49502
  }
47445
49503
  };
47446
49504
 
49505
+ // ../../MJCore/dist/generic/visibilityContentOrigin.js
49506
+ var CONTENT_ITEMS_ENTITY = "MJ: Content Items";
49507
+ var CONTENT_CHUNKS_ENTITY = "MJ: Content Item Chunks";
49508
+ var ENTITY_RECORD_DOCUMENTS_ENTITY = "MJ: Entity Record Documents";
49509
+ function GetContentFamilyLevel(entity, provider) {
49510
+ const visited = /* @__PURE__ */ new Set();
49511
+ let current = entity;
49512
+ while (current && !visited.has(current.ID)) {
49513
+ if (current.Name === CONTENT_CHUNKS_ENTITY)
49514
+ return "chunk";
49515
+ if (current.Name === CONTENT_ITEMS_ENTITY)
49516
+ return "item";
49517
+ visited.add(current.ID);
49518
+ current = current.ParentID ? safeEntityByID(provider, current.ParentID) : void 0;
49519
+ }
49520
+ return null;
49521
+ }
49522
+ async function EvaluateContentOriginGate(entity, level, items, ctx, narrowOutcome) {
49523
+ const rv = ctx.CreateRunView();
49524
+ const recordIDs = Array.from(new Set(items.map((i) => i.CanonicalRecordID)));
49525
+ let perPrincipalOrigins;
49526
+ try {
49527
+ perPrincipalOrigins = await Promise.all(ctx.Principals.map((principal) => resolveContentOriginsForPrincipal(rv, entity, level, recordIDs, principal, ctx.Provider)));
49528
+ } catch (err) {
49529
+ const msg = err instanceof Error ? err.message : String(err);
49530
+ LogError(`ResolveVisibility: content origin resolution failed for "${entity.Name}": ${msg}`);
49531
+ for (const item of items) {
49532
+ narrowOutcome(item, "Hidden", "DerivedContent", msg);
49533
+ }
49534
+ return;
49535
+ }
49536
+ const originRefsToCheck = [];
49537
+ const originRefByItemKey = /* @__PURE__ */ new Map();
49538
+ for (const item of items) {
49539
+ const firstOrigin = perPrincipalOrigins[0].get(item.CanonicalRecordID);
49540
+ if (firstOrigin === void 0) {
49541
+ narrowOutcome(item, "Hidden", "DerivedContent", "Content origin chain could not be read");
49542
+ continue;
49543
+ }
49544
+ let audienceFailed = false;
49545
+ let resolvedOrigin = firstOrigin;
49546
+ for (let i = 1; i < perPrincipalOrigins.length; i++) {
49547
+ const otherOrigin = perPrincipalOrigins[i].get(item.CanonicalRecordID);
49548
+ if (otherOrigin === void 0) {
49549
+ audienceFailed = true;
49550
+ break;
49551
+ }
49552
+ if (!resolvedOrigin && otherOrigin) {
49553
+ resolvedOrigin = otherOrigin;
49554
+ }
49555
+ }
49556
+ if (audienceFailed) {
49557
+ narrowOutcome(item, "Hidden", "AudienceIntersection", "Content origin chain not readable by all audience readers");
49558
+ continue;
49559
+ }
49560
+ originRefByItemKey.set(item.Key, resolvedOrigin);
49561
+ if (resolvedOrigin) {
49562
+ originRefsToCheck.push(resolvedOrigin);
49563
+ }
49564
+ }
49565
+ if (originRefsToCheck.length === 0) {
49566
+ return;
49567
+ }
49568
+ const originDecisions = await ctx.ResolveSubNodes(originRefsToCheck, { SkipBaseRowCheck: false });
49569
+ for (const item of items) {
49570
+ const origin = originRefByItemKey.get(item.Key);
49571
+ if (!origin) {
49572
+ continue;
49573
+ }
49574
+ const originKey = ctx.NodeKey(origin);
49575
+ const decision = originDecisions.get(originKey);
49576
+ if (!decision || decision.Outcome === "Hidden") {
49577
+ const step = decision?.DecidingStep === "DelegatedDocument" || decision?.DecidingStep === "AudienceIntersection" ? decision.DecidingStep : "DerivedContent";
49578
+ narrowOutcome(item, "Hidden", step, decision?.Reason ?? `Origin record ${origin.EntityName} is hidden`);
49579
+ } else if (decision.Outcome === "Redacted") {
49580
+ narrowOutcome(item, "Redacted", decision.DecidingStep, decision.Reason ?? `Origin record ${origin.EntityName} is redacted`);
49581
+ }
49582
+ }
49583
+ }
49584
+ async function resolveContentOriginsForPrincipal(rv, entity, level, recordIDs, principal, provider) {
49585
+ const itemOfRecord = level === "chunk" ? await lookupChunkItems(rv, entity, recordIDs, principal) : new Map(recordIDs.map((id) => [id, id]));
49586
+ const itemIDs = Array.from(new Set(itemOfRecord.values()));
49587
+ const erdOfItem = await lookupItemOrigins(rv, itemIDs, principal);
49588
+ const erdIDs = Array.from(new Set(Array.from(erdOfItem.values()).filter((id) => id !== null)));
49589
+ const originOfErd = await lookupEntityRecordDocuments(rv, erdIDs, principal, provider);
49590
+ const origins = /* @__PURE__ */ new Map();
49591
+ for (const id of recordIDs) {
49592
+ const itemID = itemOfRecord.get(id);
49593
+ if (itemID === void 0)
49594
+ continue;
49595
+ const erdID = erdOfItem.get(itemID);
49596
+ if (erdID === void 0)
49597
+ continue;
49598
+ if (erdID === null) {
49599
+ origins.set(id, null);
49600
+ continue;
49601
+ }
49602
+ const origin = originOfErd.get(erdID);
49603
+ if (origin) {
49604
+ origins.set(id, origin);
49605
+ }
49606
+ }
49607
+ return origins;
49608
+ }
49609
+ async function lookupChunkItems(rv, entity, chunkIDs, principal) {
49610
+ const pkName = entity.FirstPrimaryKey.Name;
49611
+ const rows = await runStrictLookup(rv, entity.Name, [pkName, "ContentItemID"], pkName, chunkIDs, principal);
49612
+ if (!rows) {
49613
+ throw new Error(`lookup of "${entity.Name}" failed; every chunk depends on it`);
49614
+ }
49615
+ const map2 = /* @__PURE__ */ new Map();
49616
+ for (const row of rows) {
49617
+ const pk = row[pkName];
49618
+ const itemID = row["ContentItemID"];
49619
+ if (typeof pk === "string" && typeof itemID === "string") {
49620
+ map2.set(NormalizeUUID(pk), NormalizeUUID(itemID));
49621
+ }
49622
+ }
49623
+ return map2;
49624
+ }
49625
+ async function lookupItemOrigins(rv, itemIDs, principal) {
49626
+ const fields = ["ID", "ParentID", "RootParentID", "EntityRecordDocumentID"];
49627
+ const rows = await runStrictLookup(rv, CONTENT_ITEMS_ENTITY, fields, "ID", itemIDs, principal);
49628
+ if (!rows) {
49629
+ throw new Error(`lookup of "${CONTENT_ITEMS_ENTITY}" failed; every content row depends on it`);
49630
+ }
49631
+ const map2 = /* @__PURE__ */ new Map();
49632
+ const rootOfChild = /* @__PURE__ */ new Map();
49633
+ for (const row of rows) {
49634
+ const id = NormalizeUUID(row.ID);
49635
+ const root = row.RootParentID ? NormalizeUUID(row.RootParentID) : null;
49636
+ if (row.EntityRecordDocumentID) {
49637
+ map2.set(id, NormalizeUUID(row.EntityRecordDocumentID));
49638
+ } else if (!row.ParentID) {
49639
+ map2.set(id, null);
49640
+ } else if (root && root !== id) {
49641
+ rootOfChild.set(id, root);
49642
+ } else {
49643
+ LogError(`ResolveVisibility: content item ${id} has ParentID without a resolvable RootParentID; hiding.`);
49644
+ }
49645
+ }
49646
+ if (rootOfChild.size === 0) {
49647
+ return map2;
49648
+ }
49649
+ const roots = Array.from(new Set(rootOfChild.values()));
49650
+ const rootRows = await runStrictLookup(rv, CONTENT_ITEMS_ENTITY, fields, "ID", roots, principal) ?? [];
49651
+ const docOfRoot = new Map(rootRows.map((r) => [NormalizeUUID(r.ID), r.EntityRecordDocumentID ? NormalizeUUID(r.EntityRecordDocumentID) : null]));
49652
+ for (const [child, root] of rootOfChild) {
49653
+ const doc = docOfRoot.get(root);
49654
+ if (doc !== void 0) {
49655
+ map2.set(child, doc);
49656
+ }
49657
+ }
49658
+ return map2;
49659
+ }
49660
+ async function lookupEntityRecordDocuments(rv, erdIDs, principal, provider) {
49661
+ const map2 = /* @__PURE__ */ new Map();
49662
+ if (erdIDs.length === 0) {
49663
+ return map2;
49664
+ }
49665
+ const res = await rv.RunView({
49666
+ EntityName: ENTITY_RECORD_DOCUMENTS_ENTITY,
49667
+ Fields: ["ID", "Entity", "EntityID", "RecordID"],
49668
+ ExtraFilter: `ID IN (${erdIDs.map((id) => `'${EscapeSQLString(id)}'`).join(",")})`,
49669
+ ResultType: "simple",
49670
+ MaxRows: erdIDs.length,
49671
+ SkipTotalRowCount: true
49672
+ }, principal);
49673
+ if (!res.Success) {
49674
+ LogError(`ResolveVisibility: lookup of "${ENTITY_RECORD_DOCUMENTS_ENTITY}" failed for user ${principal.ID}: ${res.ErrorMessage ?? "unknown error"}`);
49675
+ return map2;
49676
+ }
49677
+ const rows = res.Results ?? [];
49678
+ for (const row of rows) {
49679
+ const hasId = Object.prototype.hasOwnProperty.call(row, "ID");
49680
+ const hasRecordId = Object.prototype.hasOwnProperty.call(row, "RecordID");
49681
+ const hasEntity = Object.prototype.hasOwnProperty.call(row, "Entity") || Object.prototype.hasOwnProperty.call(row, "EntityID");
49682
+ if (!hasId || !hasRecordId || !hasEntity) {
49683
+ LogError(`ResolveVisibility: lookup of "${ENTITY_RECORD_DOCUMENTS_ENTITY}" omitted required link column for user ${principal.ID} (FLS denial); failing closed.`);
49684
+ return /* @__PURE__ */ new Map();
49685
+ }
49686
+ const originEntity = safeEntityLookup(provider, row.Entity ?? "", row.EntityID ?? void 0);
49687
+ const entityName = originEntity?.Name ?? (row.Entity ?? "");
49688
+ if (entityName && row.RecordID) {
49689
+ map2.set(NormalizeUUID(row.ID), {
49690
+ EntityName: entityName,
49691
+ ...originEntity?.ID ? { EntityID: originEntity.ID } : row.EntityID ? { EntityID: row.EntityID } : {},
49692
+ RecordID: row.RecordID
49693
+ });
49694
+ }
49695
+ }
49696
+ return map2;
49697
+ }
49698
+ async function runStrictLookup(rv, entityName, fields, keyField, ids, principal) {
49699
+ if (ids.length === 0) {
49700
+ return [];
49701
+ }
49702
+ const res = await rv.RunView({
49703
+ EntityName: entityName,
49704
+ Fields: fields,
49705
+ ExtraFilter: `${keyField} IN (${ids.map((id) => `'${EscapeSQLString(id)}'`).join(",")})`,
49706
+ ResultType: "simple",
49707
+ MaxRows: ids.length,
49708
+ SkipTotalRowCount: true
49709
+ }, principal);
49710
+ if (!res.Success) {
49711
+ LogError(`ResolveVisibility: lookup of "${entityName}" failed for user ${principal.ID}: ${res.ErrorMessage ?? "unknown error"}`);
49712
+ return null;
49713
+ }
49714
+ const missing = fields.find((f) => (res.Results ?? []).some((row) => !Object.prototype.hasOwnProperty.call(row, f)));
49715
+ if (missing) {
49716
+ LogError(`ResolveVisibility: lookup of "${entityName}" omitted required column "${missing}" for user ${principal.ID} (FLS denial); failing closed.`);
49717
+ return null;
49718
+ }
49719
+ return res.Results ?? [];
49720
+ }
49721
+ function safeEntityLookup(provider, entityName, entityId) {
49722
+ if (entityId) {
49723
+ const byId = safeEntityByID(provider, entityId);
49724
+ if (byId)
49725
+ return byId;
49726
+ }
49727
+ try {
49728
+ return provider.EntityByName(entityName) ?? void 0;
49729
+ } catch {
49730
+ return void 0;
49731
+ }
49732
+ }
49733
+ function safeEntityByID(provider, entityId) {
49734
+ try {
49735
+ return provider.EntityByID(entityId) ?? void 0;
49736
+ } catch {
49737
+ return void 0;
49738
+ }
49739
+ }
49740
+
49741
+ // ../../MJCore/dist/generic/visibilityAudit.js
49742
+ var VISIBILITY_AUDIT_LOG_TYPE_NAME = "Visibility Evaluation";
49743
+ var VISIBILITY_AUDIT_SINKS_STORE_KEY = "___MJ_VISIBILITY_AUDIT_SINKS___";
49744
+ var VISIBILITY_AUDIT_PENDING_WRITES_KEY = "___MJ_VISIBILITY_AUDIT_PENDING_WRITES___";
49745
+ function EmitConsolidatedVisibilityAuditEvent(caller, principals, decisions, provider) {
49746
+ EmitVisibilityAuditEvent(caller, principals, decisions, provider);
49747
+ }
49748
+ function EmitVisibilityAuditEvent(caller, principals, decisions, provider) {
49749
+ if (decisions.size === 0) {
49750
+ return;
49751
+ }
49752
+ let allowedCount = 0;
49753
+ let redactedCount = 0;
49754
+ let hiddenCount = 0;
49755
+ const entries = [];
49756
+ for (const d of decisions.values()) {
49757
+ if (d.Outcome === "Allowed")
49758
+ allowedCount++;
49759
+ else if (d.Outcome === "Redacted")
49760
+ redactedCount++;
49761
+ else
49762
+ hiddenCount++;
49763
+ entries.push({
49764
+ Key: d.Key,
49765
+ EntityName: d.Ref.EntityName,
49766
+ RecordID: d.Ref.RecordID,
49767
+ Outcome: d.Outcome,
49768
+ DecidingStep: d.DecidingStep
49769
+ });
49770
+ }
49771
+ const event = {
49772
+ Timestamp: /* @__PURE__ */ new Date(),
49773
+ Caller: caller,
49774
+ PrincipalIDs: principals.map((p) => p.ID),
49775
+ NodeCount: entries.length,
49776
+ AllowedCount: allowedCount,
49777
+ RedactedCount: redactedCount,
49778
+ HiddenCount: hiddenCount,
49779
+ Decisions: entries
49780
+ };
49781
+ for (const sink of getVisibilityAuditSinksList()) {
49782
+ try {
49783
+ const maybePromise = sink(event, provider, principals);
49784
+ if (maybePromise && typeof maybePromise.then === "function") {
49785
+ trackBackgroundAuditPromise(Promise.resolve(maybePromise).catch((err) => {
49786
+ LogError(`ResolveVisibility: visibility audit sink threw: ${err instanceof Error ? err.message : String(err)}`);
49787
+ }));
49788
+ }
49789
+ } catch (err) {
49790
+ LogError(`ResolveVisibility: visibility audit sink threw: ${err instanceof Error ? err.message : String(err)}`);
49791
+ }
49792
+ }
49793
+ if (provider instanceof DatabaseProviderBase) {
49794
+ const hasType = provider.AuditLogTypes?.some((a) => a?.Name?.trim().toLowerCase() === VISIBILITY_AUDIT_LOG_TYPE_NAME.toLowerCase());
49795
+ if (hasType) {
49796
+ trackBackgroundAuditPromise(persistVisibilityAuditLog(provider, event, principals));
49797
+ }
49798
+ }
49799
+ }
49800
+ function trackBackgroundAuditPromise(promise) {
49801
+ const pending = getPendingAuditWritesSet();
49802
+ const tracked = promise.finally(() => {
49803
+ pending.delete(tracked);
49804
+ });
49805
+ pending.add(tracked);
49806
+ }
49807
+ async function persistVisibilityAuditLog(provider, event, principals) {
49808
+ try {
49809
+ if (event.Decisions.length === 0) {
49810
+ return;
49811
+ }
49812
+ const distinctEntityNames = /* @__PURE__ */ new Set();
49813
+ let singleEntityName = null;
49814
+ for (const d of event.Decisions) {
49815
+ const norm = d.EntityName?.trim().toLowerCase();
49816
+ if (norm) {
49817
+ distinctEntityNames.add(norm);
49818
+ if (singleEntityName === null) {
49819
+ singleEntityName = d.EntityName.trim();
49820
+ }
49821
+ }
49822
+ }
49823
+ if (distinctEntityNames.size === 1 && distinctEntityNames.has("mj: audit logs")) {
49824
+ return;
49825
+ }
49826
+ let entityId = null;
49827
+ let recordId = null;
49828
+ if (distinctEntityNames.size === 1 && singleEntityName) {
49829
+ const entity = lookupEntityLogged(provider, singleEntityName);
49830
+ entityId = entity?.ID ?? null;
49831
+ recordId = entityId && event.Decisions.length === 1 ? event.Decisions[0].RecordID : null;
49832
+ }
49833
+ const systemUser = await resolveSystemUser(provider);
49834
+ const writerUser = systemUser ?? principals[0];
49835
+ if (!writerUser) {
49836
+ return;
49837
+ }
49838
+ const summary = `Visibility evaluated ${event.NodeCount} node(s) for ${event.PrincipalIDs.length} principal(s) via ${event.Caller}: ${event.AllowedCount} allowed, ${event.RedactedCount} redacted, ${event.HiddenCount} hidden.`;
49839
+ await provider.CreateAuditLogRecord(writerUser, null, VISIBILITY_AUDIT_LOG_TYPE_NAME, "Success", JSON.stringify({
49840
+ caller: event.Caller,
49841
+ principalIds: event.PrincipalIDs,
49842
+ nodeCount: event.NodeCount,
49843
+ allowedCount: event.AllowedCount,
49844
+ redactedCount: event.RedactedCount,
49845
+ hiddenCount: event.HiddenCount,
49846
+ decisions: event.Decisions.slice(0, 200)
49847
+ // Bound audit payload size for large batches
49848
+ }), entityId, recordId, summary, null);
49849
+ } catch (err) {
49850
+ LogError(`ResolveVisibility: failed writing visibility audit log: ${err instanceof Error ? err.message : String(err)}`);
49851
+ }
49852
+ }
49853
+ async function resolveSystemUser(provider) {
49854
+ try {
49855
+ const source = MJGlobal.Instance.ClassFactory.CreateInstance(WellKnownUserSource);
49856
+ return await source?.GetSystemUser(provider) ?? null;
49857
+ } catch (err) {
49858
+ LogError(`ResolveVisibility: failed resolving system user for visibility audit log: ${err instanceof Error ? err.message : String(err)}`);
49859
+ return null;
49860
+ }
49861
+ }
49862
+ function lookupEntityLogged(provider, entityName) {
49863
+ try {
49864
+ return provider.EntityByName(entityName) ?? void 0;
49865
+ } catch (err) {
49866
+ LogError(`ResolveVisibility: EntityByName("${entityName}") failed while writing audit log: ${err instanceof Error ? err.message : String(err)}`);
49867
+ return void 0;
49868
+ }
49869
+ }
49870
+ function getVisibilityAuditSinksList() {
49871
+ const store = GetGlobalObjectStore();
49872
+ if (!Array.isArray(store[VISIBILITY_AUDIT_SINKS_STORE_KEY])) {
49873
+ store[VISIBILITY_AUDIT_SINKS_STORE_KEY] = [];
49874
+ }
49875
+ return store[VISIBILITY_AUDIT_SINKS_STORE_KEY];
49876
+ }
49877
+ function getPendingAuditWritesSet() {
49878
+ const store = GetGlobalObjectStore();
49879
+ if (!(store[VISIBILITY_AUDIT_PENDING_WRITES_KEY] instanceof Set)) {
49880
+ store[VISIBILITY_AUDIT_PENDING_WRITES_KEY] = /* @__PURE__ */ new Set();
49881
+ }
49882
+ return store[VISIBILITY_AUDIT_PENDING_WRITES_KEY];
49883
+ }
49884
+
49885
+ // ../../MJCore/dist/generic/visibility.js
49886
+ var __decorate6 = function(decorators, target, key, desc) {
49887
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
49888
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
49889
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
49890
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
49891
+ };
49892
+ var MAX_VISIBILITY_DEPTH = 6;
49893
+ var BaseVisibilityRule = class BaseVisibilityRule2 {
49894
+ /** When `true`, the rule also applies to IS-A descendant entities of its registered entity name. */
49895
+ get MatchSubtypes() {
49896
+ return false;
49897
+ }
49898
+ /** Default deciding step reported when this rule narrows or hides a node. */
49899
+ get DecidingStep() {
49900
+ return "RecordPermission";
49901
+ }
49902
+ /**
49903
+ * When `true`, this rule authoritatively enforces record-level read visibility (such as
49904
+ * delegated-document fallback on `MJ: Artifacts`) after Step 1 checks entity-level `CanRead`
49905
+ * and any explicit DB RLS filter. When no explicit DB RLS clause applies to any principal,
49906
+ * Step 1 skips its generic `RunView` existence probe so the rule itself decides the batch.
49907
+ */
49908
+ get HandlesBaseRowSecurity() {
49909
+ return false;
49910
+ }
49911
+ /**
49912
+ * When `true`, server `RunView` hooks already enforce this rule for the calling user (e.g.
49913
+ * `GraphConceptReadSecurityHook` on `MJ: Graph Concepts` and `ArtifactReadSecurityHook` on
49914
+ * `MJ: Artifacts`), so `SearchEngine` may skip re-running this rule on self-evident `RunView`
49915
+ * hits for the same user (Finding 390). Defaults to `false` so entities without a `RunView`
49916
+ * read hook (`MJ: AI Agents`, `MJ: AI Skills`, `MJ: Queries`) are always verified.
49917
+ */
49918
+ get EnforcedByRunView() {
49919
+ return false;
49920
+ }
49921
+ };
49922
+ BaseVisibilityRule = __decorate6([
49923
+ RequiresSubclass()
49924
+ ], BaseVisibilityRule);
49925
+ function FormatVisibilityNodeKey(ref, provider) {
49926
+ const entity = safeEntityLookup2(provider, ref.EntityName, ref.EntityID);
49927
+ const entityPart = entity?.ID ? NormalizeUUID(entity.ID) : ref.EntityID ? NormalizeUUID(ref.EntityID) : ref.EntityName.trim().toLowerCase();
49928
+ const recordPart = normalizeRecordIdPart(entity, ref.RecordID);
49929
+ return `${entityPart}|${recordPart}`;
49930
+ }
49931
+ function VisibilityOutcomeSeverity(outcome) {
49932
+ if (outcome === "Hidden")
49933
+ return 2;
49934
+ if (outcome === "Redacted")
49935
+ return 1;
49936
+ return 0;
49937
+ }
49938
+ function IntersectVisibilityOutcomes(a, b) {
49939
+ return VisibilityOutcomeSeverity(a) >= VisibilityOutcomeSeverity(b) ? a : b;
49940
+ }
49941
+ function ResolveVisibilityRuleForEntity(entity, provider) {
49942
+ const visited = /* @__PURE__ */ new Set();
49943
+ let current = entity;
49944
+ let isSubtypeHop = false;
49945
+ while (current && !visited.has(current.ID)) {
49946
+ visited.add(current.ID);
49947
+ const reg = MJGlobal.Instance.ClassFactory.GetRegistration(BaseVisibilityRule, current.Name);
49948
+ if (reg) {
49949
+ const instance = MJGlobal.Instance.ClassFactory.CreateInstance(BaseVisibilityRule, current.Name);
49950
+ if (instance && (!isSubtypeHop || instance.MatchSubtypes)) {
49951
+ return instance;
49952
+ }
49953
+ }
49954
+ isSubtypeHop = true;
49955
+ current = current.ParentID ? safeEntityByID2(provider, current.ParentID) : void 0;
49956
+ }
49957
+ return null;
49958
+ }
49959
+ async function ResolveVisibility(nodes, principals, options) {
49960
+ const depth = options.Depth ?? 0;
49961
+ const provider = options.Provider;
49962
+ const caller = options.Caller?.trim() || "ResolveVisibility";
49963
+ const principalList = deduplicatePrincipals(principals);
49964
+ const items = normalizeAndDeduplicateNodes(nodes, provider);
49965
+ const decisions = /* @__PURE__ */ new Map();
49966
+ if (items.length === 0) {
49967
+ return decisions;
49968
+ }
49969
+ if (depth > MAX_VISIBILITY_DEPTH) {
49970
+ LogError(`ResolveVisibility: exceeded max recursion depth (${MAX_VISIBILITY_DEPTH}); failing closed for ${items.length} node(s).`);
49971
+ for (const item of items) {
49972
+ decisions.set(item.Key, makeDecision(item, "Hidden", "Error", "Maximum visibility recursion depth exceeded"));
49973
+ }
49974
+ return decisions;
49975
+ }
49976
+ if (principalList.length === 0 || principalList.some((p) => !p || !p.ID || p.IsActive === false)) {
49977
+ for (const item of items) {
49978
+ decisions.set(item.Key, makeDecision(item, "Hidden", "EntityPermission", "Invalid or inactive principal"));
49979
+ }
49980
+ recordOrEmitAudit(depth, caller, principalList, decisions, provider, options);
49981
+ return decisions;
49982
+ }
49983
+ const createRunView = () => options.RunViewFactory ? options.RunViewFactory(provider) : RunView.FromMetadataProvider(provider);
49984
+ const working = /* @__PURE__ */ new Map();
49985
+ const byEntity = /* @__PURE__ */ new Map();
49986
+ for (const item of items) {
49987
+ if (!item.Entity || !item.CanonicalRecordID) {
49988
+ working.set(item.Key, makeDecision(item, "Hidden", "EntityPermission", "Unknown entity or empty record ID"));
49989
+ continue;
49990
+ }
49991
+ working.set(item.Key, makeDecision(item, "Allowed", "Allowed"));
49992
+ const bucket = byEntity.get(item.Entity.Name) ?? { Entity: item.Entity, Items: [] };
49993
+ bucket.Items.push(item);
49994
+ byEntity.set(item.Entity.Name, bucket);
49995
+ }
49996
+ if (!options.SkipBaseRowCheck) {
49997
+ await evaluateEntityAndRowSecurity(byEntity, principalList, provider, createRunView, working);
49998
+ } else {
49999
+ for (const [, bucket] of byEntity) {
50000
+ const firstCanRead = Boolean(bucket.Entity.GetUserPermisions(principalList[0])?.CanRead);
50001
+ const allCanRead = firstCanRead && principalList.every((p) => Boolean(bucket.Entity.GetUserPermisions(p)?.CanRead));
50002
+ if (!allCanRead) {
50003
+ const step = firstCanRead ? "AudienceIntersection" : "EntityPermission";
50004
+ for (const item of bucket.Items) {
50005
+ narrowDecision(working, item, "Hidden", step, `User lacks Read permission on ${bucket.Entity.Name}`);
50006
+ }
50007
+ }
50008
+ }
50009
+ }
50010
+ if (options.CheckFields && options.CheckFields.length > 0) {
50011
+ evaluateFieldLevelSecurity(byEntity, principalList, options.CheckFields, working);
50012
+ }
50013
+ const ruleContext = {
50014
+ Principal: principalList[0],
50015
+ Principals: principalList,
50016
+ Provider: provider,
50017
+ IncludeProposed: options.IncludeProposed === true,
50018
+ Caller: caller,
50019
+ Depth: depth,
50020
+ CreateRunView: createRunView,
50021
+ NodeKey: (ref) => FormatVisibilityNodeKey(ref, provider),
50022
+ ResolveSubNodes: async (refs, overrides) => ResolveVisibility(refs, principalList, {
50023
+ Provider: provider,
50024
+ Caller: caller,
50025
+ IncludeProposed: overrides?.IncludeProposed ?? options.IncludeProposed,
50026
+ SkipBaseRowCheck: overrides?.SkipBaseRowCheck ?? false,
50027
+ SkipAuditLog: true,
50028
+ RunViewFactory: options.RunViewFactory,
50029
+ Depth: depth + 1
50030
+ })
50031
+ };
50032
+ for (const [, bucket] of byEntity) {
50033
+ const surviving = bucket.Items.filter((item) => working.get(item.Key)?.Outcome !== "Hidden");
50034
+ if (surviving.length === 0) {
50035
+ continue;
50036
+ }
50037
+ const contentLevel = GetContentFamilyLevel(bucket.Entity, provider);
50038
+ if (contentLevel) {
50039
+ await EvaluateContentOriginGate(bucket.Entity, contentLevel, surviving, ruleContext, (item, outcome, step, reason) => {
50040
+ const fullItem = surviving.find((s) => s.Key === item.Key);
50041
+ if (fullItem) {
50042
+ narrowDecision(working, fullItem, outcome, step, reason);
50043
+ }
50044
+ });
50045
+ }
50046
+ const postContentSurviving = surviving.filter((item) => working.get(item.Key)?.Outcome !== "Hidden");
50047
+ if (postContentSurviving.length === 0) {
50048
+ continue;
50049
+ }
50050
+ const rule = ResolveVisibilityRuleForEntity(bucket.Entity, provider);
50051
+ if (rule) {
50052
+ await applyVisibilityRule(rule, bucket.Entity, postContentSurviving, ruleContext, working);
50053
+ }
50054
+ }
50055
+ for (const item of items) {
50056
+ decisions.set(item.Key, working.get(item.Key) ?? makeDecision(item, "Hidden", "Error", "Missing visibility decision"));
50057
+ }
50058
+ recordOrEmitAudit(depth, caller, principalList, decisions, provider, options);
50059
+ return decisions;
50060
+ }
50061
+ async function evaluateEntityAndRowSecurity(byEntity, principals, provider, createRunView, working) {
50062
+ const readableBuckets = [];
50063
+ for (const [, bucket] of byEntity) {
50064
+ const firstCanRead = Boolean(bucket.Entity.GetUserPermisions(principals[0])?.CanRead);
50065
+ const allCanRead = firstCanRead && principals.every((p) => Boolean(bucket.Entity.GetUserPermisions(p)?.CanRead));
50066
+ if (!allCanRead) {
50067
+ const step = firstCanRead ? "AudienceIntersection" : "EntityPermission";
50068
+ for (const item of bucket.Items) {
50069
+ narrowDecision(working, item, "Hidden", step, `Read denied on ${bucket.Entity.Name}`);
50070
+ }
50071
+ continue;
50072
+ }
50073
+ const registeredRule = ResolveVisibilityRuleForEntity(bucket.Entity, provider);
50074
+ const hasAnyRlsClause = typeof bucket.Entity.GetEffectiveRowFilterWhereClause === "function" && principals.some((p) => Boolean(bucket.Entity.GetEffectiveRowFilterWhereClause(p, EntityPermissionType.Read, "")));
50075
+ if (registeredRule?.HandlesBaseRowSecurity && !hasAnyRlsClause) {
50076
+ continue;
50077
+ }
50078
+ readableBuckets.push(bucket);
50079
+ }
50080
+ if (readableBuckets.length === 0) {
50081
+ return;
50082
+ }
50083
+ const rv = createRunView();
50084
+ const perPrincipalReadable = await Promise.all(principals.map((principal) => readReadableKeysForPrincipal(rv, readableBuckets, principal)));
50085
+ for (const bucket of readableBuckets) {
50086
+ for (const item of bucket.Items) {
50087
+ const canonicalKey = item.ParsedKey ? canonicalKeyValues(bucket.Entity, item.ParsedKey) : "";
50088
+ if (!canonicalKey) {
50089
+ narrowDecision(working, item, "Hidden", "RowLevelSecurity", `Malformed primary key for ${bucket.Entity.Name}`);
50090
+ continue;
50091
+ }
50092
+ const firstSet = perPrincipalReadable[0].get(bucket.Entity.Name);
50093
+ const firstVisible = Boolean(firstSet?.has(canonicalKey));
50094
+ if (!firstVisible) {
50095
+ narrowDecision(working, item, "Hidden", "RowLevelSecurity", `Row not readable in ${bucket.Entity.Name}`);
50096
+ continue;
50097
+ }
50098
+ for (let i = 1; i < perPrincipalReadable.length; i++) {
50099
+ if (!perPrincipalReadable[i].get(bucket.Entity.Name)?.has(canonicalKey)) {
50100
+ narrowDecision(working, item, "Hidden", "AudienceIntersection", `Row not readable by all audience readers in ${bucket.Entity.Name}`);
50101
+ break;
50102
+ }
50103
+ }
50104
+ }
50105
+ }
50106
+ }
50107
+ async function readReadableKeysForPrincipal(rv, buckets, principal) {
50108
+ const out = /* @__PURE__ */ new Map();
50109
+ const checks = [];
50110
+ for (const bucket of buckets) {
50111
+ const rlsClause = typeof bucket.Entity.GetEffectiveRowFilterWhereClause === "function" ? bucket.Entity.GetEffectiveRowFilterWhereClause(principal, EntityPermissionType.Read, "") || void 0 : void 0;
50112
+ const params = buildReadableKeysParams(bucket.Entity, bucket.Items, rlsClause);
50113
+ if (params) {
50114
+ checks.push({ Entity: bucket.Entity, Params: params });
50115
+ }
50116
+ }
50117
+ if (checks.length === 0) {
50118
+ return out;
50119
+ }
50120
+ let results;
50121
+ try {
50122
+ results = await rv.RunViews(checks.map((c) => c.Params), principal);
50123
+ } catch (err) {
50124
+ const msg = err instanceof Error ? err.message : String(err);
50125
+ LogError(`ResolveVisibility: batched RunViews failed for principal ${principal.ID}: ${msg}`);
50126
+ return out;
50127
+ }
50128
+ checks.forEach((check, idx) => {
50129
+ const res = results[idx];
50130
+ if (!res?.Success) {
50131
+ LogError(`ResolveVisibility: read check for "${check.Entity.Name}" failed for principal ${principal.ID}: ${res?.ErrorMessage ?? "unknown error"}`);
50132
+ return;
50133
+ }
50134
+ const pkFields = check.Entity.PrimaryKeys;
50135
+ const set = /* @__PURE__ */ new Set();
50136
+ for (const row of res.Results ?? []) {
50137
+ if (pkFields.some((pk) => !Object.prototype.hasOwnProperty.call(row, pk.Name) || row[pk.Name] == null)) {
50138
+ continue;
50139
+ }
50140
+ const keyStr = pkFields.map((pk) => NormalizeUUID(String(row[pk.Name]))).join("||");
50141
+ set.add(keyStr);
50142
+ }
50143
+ out.set(check.Entity.Name, set);
50144
+ });
50145
+ return out;
50146
+ }
50147
+ function buildReadableKeysParams(entity, items, rlsClause) {
50148
+ const pkFields = entity.PrimaryKeys;
50149
+ if (!pkFields || pkFields.length === 0) {
50150
+ return null;
50151
+ }
50152
+ const validKeys = items.map((i) => i.ParsedKey).filter((k) => k !== null && k.KeyValuePairs.length === pkFields.length);
50153
+ if (validKeys.length === 0) {
50154
+ return null;
50155
+ }
50156
+ let pkFilter;
50157
+ if (pkFields.length === 1) {
50158
+ const pkName = pkFields[0].Name;
50159
+ const distinctValues = Array.from(new Set(validKeys.map((k) => k.KeyValuePairs[0]?.Value).filter((v) => v != null && String(v).trim().length > 0).map((v) => String(v))));
50160
+ if (distinctValues.length === 0) {
50161
+ return null;
50162
+ }
50163
+ pkFilter = `${pkName} IN (${distinctValues.map((v) => `'${EscapeSQLString(v)}'`).join(",")})`;
50164
+ } else {
50165
+ const tuples = validKeys.map((k) => {
50166
+ const parts = pkFields.map((pk) => {
50167
+ const pair = k.KeyValuePairs.find((kv) => kv.FieldName.trim().toLowerCase() === pk.Name.trim().toLowerCase());
50168
+ return `${pk.Name}='${EscapeSQLString(String(pair?.Value ?? ""))}'`;
50169
+ });
50170
+ return `(${parts.join(" AND ")})`;
50171
+ });
50172
+ pkFilter = tuples.length === 1 ? tuples[0] : `(${tuples.join(" OR ")})`;
50173
+ }
50174
+ const extraFilter = rlsClause ? `(${pkFilter}) AND (${rlsClause})` : pkFilter;
50175
+ return {
50176
+ EntityName: entity.Name,
50177
+ Fields: pkFields.map((pk) => pk.Name),
50178
+ ExtraFilter: extraFilter,
50179
+ ResultType: "simple",
50180
+ MaxRows: validKeys.length,
50181
+ SkipTotalRowCount: true
50182
+ };
50183
+ }
50184
+ function evaluateFieldLevelSecurity(byEntity, principals, checkFields, working) {
50185
+ for (const [, bucket] of byEntity) {
50186
+ if (typeof bucket.Entity.IsFieldReadableByUser !== "function") {
50187
+ continue;
50188
+ }
50189
+ const hiddenForFirst = [];
50190
+ const hiddenForAudience = [];
50191
+ for (const fieldName of checkFields) {
50192
+ const firstCanRead = bucket.Entity.IsFieldReadableByUser(fieldName, principals[0]);
50193
+ if (!firstCanRead) {
50194
+ hiddenForFirst.push(fieldName);
50195
+ } else if (principals.slice(1).some((p) => !bucket.Entity.IsFieldReadableByUser(fieldName, p))) {
50196
+ hiddenForAudience.push(fieldName);
50197
+ }
50198
+ }
50199
+ const allHidden = [...hiddenForFirst, ...hiddenForAudience];
50200
+ if (allHidden.length === 0) {
50201
+ continue;
50202
+ }
50203
+ const nameFieldLower = bucket.Entity.NameField?.Name?.trim().toLowerCase();
50204
+ const hidesNameField = nameFieldLower != null && allHidden.some((f) => f.trim().toLowerCase() === nameFieldLower);
50205
+ const step = hiddenForFirst.length > 0 ? "FieldLevelSecurity" : "AudienceIntersection";
50206
+ for (const item of bucket.Items) {
50207
+ const existing = working.get(item.Key);
50208
+ if (!existing || existing.Outcome === "Hidden") {
50209
+ continue;
50210
+ }
50211
+ if (hidesNameField) {
50212
+ working.set(item.Key, {
50213
+ ...existing,
50214
+ Outcome: IntersectVisibilityOutcomes(existing.Outcome, "Redacted"),
50215
+ DecidingStep: existing.Outcome === "Allowed" ? step : existing.DecidingStep,
50216
+ HiddenFields: allHidden,
50217
+ Reason: existing.Reason ?? `Field-level security hides ${allHidden.join(", ")}`
50218
+ });
50219
+ } else {
50220
+ working.set(item.Key, { ...existing, HiddenFields: allHidden });
50221
+ }
50222
+ }
50223
+ }
50224
+ }
50225
+ async function applyVisibilityRule(rule, entity, items, ctx, working) {
50226
+ const inputs = items.map((item) => ({
50227
+ Key: item.Key,
50228
+ Ref: item.Ref,
50229
+ Entity: entity,
50230
+ CanonicalRecordID: item.CanonicalRecordID,
50231
+ CurrentOutcome: working.get(item.Key)?.Outcome ?? "Allowed"
50232
+ }));
50233
+ let outcomes;
50234
+ try {
50235
+ outcomes = await rule.Evaluate(inputs, ctx);
50236
+ } catch (err) {
50237
+ const msg = err instanceof Error ? err.message : String(err);
50238
+ LogError(`ResolveVisibility: visibility rule for "${entity.Name}" threw; failing closed: ${msg}`);
50239
+ for (const item of items) {
50240
+ narrowDecision(working, item, "Hidden", "Error", msg);
50241
+ }
50242
+ return;
50243
+ }
50244
+ for (const item of items) {
50245
+ const res = outcomes.get(item.Key);
50246
+ if (!res) {
50247
+ narrowDecision(working, item, "Hidden", rule.DecidingStep, `Rule for ${entity.Name} omitted decision`);
50248
+ continue;
50249
+ }
50250
+ if (res.Outcome === "Allowed") {
50251
+ continue;
50252
+ }
50253
+ narrowDecision(working, item, res.Outcome, res.DecidingStep ?? rule.DecidingStep, res.Reason, res.HiddenFields);
50254
+ }
50255
+ }
50256
+ function recordOrEmitAudit(depth, caller, principals, decisions, provider, options) {
50257
+ if (depth !== 0 || decisions.size === 0) {
50258
+ return;
50259
+ }
50260
+ if (options.AuditCollector) {
50261
+ for (const [key, decision] of decisions) {
50262
+ const existing = options.AuditCollector.get(key);
50263
+ if (!existing || VisibilityOutcomeSeverity(decision.Outcome) > VisibilityOutcomeSeverity(existing.Outcome)) {
50264
+ options.AuditCollector.set(key, decision);
50265
+ }
50266
+ }
50267
+ return;
50268
+ }
50269
+ if (options.SkipAuditLog === true) {
50270
+ return;
50271
+ }
50272
+ EmitVisibilityAuditEvent(caller, principals, decisions, provider);
50273
+ }
50274
+ function deduplicatePrincipals(principals) {
50275
+ const input = Array.isArray(principals) ? principals : [principals];
50276
+ const out = [];
50277
+ const seen = new UUIDSet();
50278
+ for (const p of input) {
50279
+ if (!p) {
50280
+ continue;
50281
+ }
50282
+ if (p.ID) {
50283
+ if (seen.Has(p.ID)) {
50284
+ continue;
50285
+ }
50286
+ seen.Add(p.ID);
50287
+ }
50288
+ out.push(p);
50289
+ }
50290
+ return out;
50291
+ }
50292
+ function normalizeAndDeduplicateNodes(nodes, provider) {
50293
+ const seen = /* @__PURE__ */ new Set();
50294
+ const out = [];
50295
+ for (const ref of nodes) {
50296
+ if (!ref || !ref.EntityName || !ref.RecordID) {
50297
+ continue;
50298
+ }
50299
+ const entity = safeEntityLookup2(provider, ref.EntityName, ref.EntityID);
50300
+ const key = FormatVisibilityNodeKey(ref, provider);
50301
+ if (seen.has(key)) {
50302
+ continue;
50303
+ }
50304
+ seen.add(key);
50305
+ const parsedKey = entity ? parseNodeCompositeKey(entity, ref.RecordID) : null;
50306
+ const canonicalId = entity && parsedKey ? canonicalKeyValues(entity, parsedKey) : NormalizeUUID(ref.RecordID.trim());
50307
+ out.push({
50308
+ Key: key,
50309
+ Ref: entity ? { EntityName: entity.Name, EntityID: entity.ID, RecordID: ref.RecordID } : ref,
50310
+ Entity: entity ?? null,
50311
+ CanonicalRecordID: canonicalId,
50312
+ ParsedKey: parsedKey
50313
+ });
50314
+ }
50315
+ return out;
50316
+ }
50317
+ function getEntityPrimaryKeys(entity) {
50318
+ if (Array.isArray(entity.PrimaryKeys) && entity.PrimaryKeys.length > 0) {
50319
+ return entity.PrimaryKeys;
50320
+ }
50321
+ return entity.FirstPrimaryKey ? [entity.FirstPrimaryKey] : [];
50322
+ }
50323
+ function parseNodeCompositeKey(entity, recordId) {
50324
+ const trimmed = recordId.trim();
50325
+ const pkFields = getEntityPrimaryKeys(entity);
50326
+ if (!trimmed || pkFields.length === 0) {
50327
+ return null;
50328
+ }
50329
+ try {
50330
+ const key = CompositeKey.FromURLSegment(entity, trimmed);
50331
+ if (key.KeyValuePairs.length === pkFields.length && pkFields.every((pk) => {
50332
+ const pair = key.KeyValuePairs.find((kv) => kv.FieldName.trim().toLowerCase() === pk.Name.trim().toLowerCase());
50333
+ return pair != null && pair.Value != null && String(pair.Value).trim().length > 0;
50334
+ })) {
50335
+ return key;
50336
+ }
50337
+ } catch {
50338
+ }
50339
+ if (pkFields.length === 1 && !trimmed.includes("|")) {
50340
+ return CompositeKey.FromKeyValuePair(pkFields[0].Name, trimmed);
50341
+ }
50342
+ return null;
50343
+ }
50344
+ function normalizeRecordIdPart(entity, recordId) {
50345
+ const trimmed = recordId?.trim() ?? "";
50346
+ if (!entity || !trimmed) {
50347
+ return NormalizeUUID(trimmed);
50348
+ }
50349
+ const parsed = parseNodeCompositeKey(entity, trimmed);
50350
+ if (!parsed) {
50351
+ return NormalizeUUID(trimmed);
50352
+ }
50353
+ return canonicalKeyValues(entity, parsed);
50354
+ }
50355
+ function canonicalKeyValues(entity, key) {
50356
+ return getEntityPrimaryKeys(entity).map((pk) => {
50357
+ const match = key.KeyValuePairs.find((kv) => kv.FieldName.trim().toLowerCase() === pk.Name.trim().toLowerCase());
50358
+ return NormalizeUUID(String(match?.Value ?? ""));
50359
+ }).join("||");
50360
+ }
50361
+ function safeEntityLookup2(provider, entityName, entityId) {
50362
+ if (!provider) {
50363
+ return void 0;
50364
+ }
50365
+ if (entityId) {
50366
+ const byId = safeEntityByID2(provider, entityId);
50367
+ if (byId)
50368
+ return byId;
50369
+ }
50370
+ try {
50371
+ return provider.EntityByName(entityName) ?? void 0;
50372
+ } catch (err) {
50373
+ LogError(`ResolveVisibility: EntityByName("${entityName}") threw: ${err instanceof Error ? err.message : String(err)}`);
50374
+ return void 0;
50375
+ }
50376
+ }
50377
+ function safeEntityByID2(provider, entityId) {
50378
+ try {
50379
+ return provider.EntityByID(entityId) ?? void 0;
50380
+ } catch (err) {
50381
+ LogError(`ResolveVisibility: EntityByID("${entityId}") threw: ${err instanceof Error ? err.message : String(err)}`);
50382
+ return void 0;
50383
+ }
50384
+ }
50385
+ function makeDecision(item, outcome, step, reason, hiddenFields) {
50386
+ return {
50387
+ Key: item.Key,
50388
+ Ref: item.Ref,
50389
+ Outcome: outcome,
50390
+ DecidingStep: step,
50391
+ ...reason ? { Reason: reason } : {},
50392
+ ...hiddenFields && hiddenFields.length > 0 ? { HiddenFields: hiddenFields } : {}
50393
+ };
50394
+ }
50395
+ function narrowDecision(working, item, outcome, step, reason, hiddenFields) {
50396
+ const existing = working.get(item.Key);
50397
+ if (!existing) {
50398
+ working.set(item.Key, makeDecision(item, outcome, step, reason, hiddenFields));
50399
+ return;
50400
+ }
50401
+ if (VisibilityOutcomeSeverity(outcome) > VisibilityOutcomeSeverity(existing.Outcome)) {
50402
+ const mergedFields = mergeHiddenFields(existing.HiddenFields, hiddenFields);
50403
+ working.set(item.Key, makeDecision(item, outcome, step, reason, mergedFields));
50404
+ } else if (hiddenFields && hiddenFields.length > 0) {
50405
+ working.set(item.Key, { ...existing, HiddenFields: mergeHiddenFields(existing.HiddenFields, hiddenFields) });
50406
+ }
50407
+ }
50408
+ function mergeHiddenFields(a, b) {
50409
+ if (!a?.length && !b?.length)
50410
+ return void 0;
50411
+ return Array.from(/* @__PURE__ */ new Set([...a ?? [], ...b ?? []]));
50412
+ }
50413
+
47447
50414
  // ../../MJCore/dist/index.js
47448
50415
  function SetProvider(provider) {
47449
50416
  Metadata.Provider = provider;
@@ -47668,6 +50635,7 @@ export {
47668
50635
  CompositeKey,
47669
50636
  ExtractAlternateBaseViewFromDisplayState,
47670
50637
  GetEffectiveAlternateBaseViewName,
50638
+ CONTEXT_TOKEN_CONTRACT_VERSION,
47671
50639
  TIME_ZONE_HEADER,
47672
50640
  GetLocalTimeZone,
47673
50641
  ValidateUserViewProperties,
@@ -47680,6 +50648,7 @@ export {
47680
50648
  CompositeFilterSQLCompiler,
47681
50649
  RunView,
47682
50650
  Metadata,
50651
+ EntityAlternateBaseViewInfo,
47683
50652
  EntityPermissionType,
47684
50653
  ReadableFieldsTransportKey,
47685
50654
  EntityFieldTSType,
@@ -47700,11 +50669,11 @@ export {
47700
50669
  IsTransportError,
47701
50670
  FieldSecuritySQLGate,
47702
50671
  FindQueryContextTokens,
50672
+ WellKnownUserSource,
47703
50673
  ProviderBase,
47704
50674
  TransactionItem,
47705
50675
  TransactionResult,
47706
50676
  TransactionGroupBase,
47707
- WellKnownUserSource,
47708
50677
  PermissionConstrainedError,
47709
50678
  BaseEngine,
47710
50679
  ResolveEntityEventRow,
@@ -47713,11 +50682,22 @@ export {
47713
50682
  EntityRecordNameCache,
47714
50683
  ResolveMJAPIURL,
47715
50684
  AuthorizationEvaluator,
50685
+ LIMITS_TIER_PRECEDENCE,
50686
+ CODE_FALLBACK_LIMITS,
50687
+ LIMITS_KEY_PATHS,
50688
+ GetLimitsKeyRole,
50689
+ NormalizeLimitsInput,
50690
+ ValidateLimitsConfig,
50691
+ LimitsConfigResolver,
47716
50692
  getGraphQLTypeNameBase,
47717
50693
  RegisterForStartup,
47718
50694
  StartupManager,
47719
50695
  PermissionProviderBase,
47720
50696
  PermissionDeniedError,
50697
+ EmitConsolidatedVisibilityAuditEvent,
50698
+ BaseVisibilityRule,
50699
+ FormatVisibilityNodeKey,
50700
+ ResolveVisibility,
47721
50701
  SetProvider,
47722
50702
  UserViewEngine
47723
50703
  };