@katlux/providers 0.1.1-alpha.134 → 0.1.1-alpha.135

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.
package/dist/index.mjs CHANGED
@@ -1253,6 +1253,12 @@ function foldAscii(value) {
1253
1253
  if (!value) return "";
1254
1254
  return value.replace(/\u0419/g, "\uE000").replace(/\u0439/g, "\uE001").replace(EXTENDED_LATIN_CHARS, (ch) => EXTENDED_LATIN_FOLD_MAP[ch] || ch).normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/\uE000/g, "\u0439").replace(/\uE001/g, "\u0439").toLowerCase().replace(/\u0307/g, "").replace(/\u03C2/g, "\u03C3").normalize("NFKC");
1255
1255
  }
1256
+ function isAsciiString(str) {
1257
+ for (let i = 0; i < str.length; i++) {
1258
+ if (str.charCodeAt(i) > 127) return false;
1259
+ }
1260
+ return true;
1261
+ }
1256
1262
  function normalizeFilterValue(value, options) {
1257
1263
  if (value === null || value === void 0) {
1258
1264
  return "";
@@ -1260,6 +1266,9 @@ function normalizeFilterValue(value, options) {
1260
1266
  if (typeof value === "function" || typeof value === "symbol") {
1261
1267
  throw new TypeError(`[normalizeFilterValue] Unsupported non-serializable filter value of type "${typeof value}".`);
1262
1268
  }
1269
+ if (typeof value === "string" && !options?.locale && !options?.normalizer && isAsciiString(value)) {
1270
+ return value.trim().toLowerCase();
1271
+ }
1263
1272
  let rawStr;
1264
1273
  if (typeof value === "object") {
1265
1274
  if (value instanceof Date) {
@@ -4422,6 +4431,12 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
4422
4431
  this._keyringCache.clear();
4423
4432
  this._inflightKeyCache.clear();
4424
4433
  }
4434
+ setKeyring(keys, activeKid) {
4435
+ super.setKeyring(keys, activeKid);
4436
+ this._decryptSaltCache.clear();
4437
+ this._keyringCache.clear();
4438
+ this._inflightKeyCache.clear();
4439
+ }
4425
4440
  constructor(key, options) {
4426
4441
  super(key, options);
4427
4442
  if (options) {
@@ -4798,6 +4813,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4798
4813
  _cachedKeyId;
4799
4814
  _kdfOptions;
4800
4815
  _decryptSaltCache = /* @__PURE__ */ new Map();
4816
+ _inflightKeyCache = /* @__PURE__ */ new Map();
4801
4817
  constructor(key, options) {
4802
4818
  if (key && typeof key === "object" && !("algorithm" in key) && !("publicKey" in key) && !ArrayBuffer.isView(key) && !(key instanceof ArrayBuffer) && (key.keys || key.activeKid || key.allowedKids || key.kdf)) {
4803
4819
  options = key;
@@ -4831,6 +4847,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4831
4847
  this._cachedHash = void 0;
4832
4848
  this._cachedKeyId = void 0;
4833
4849
  this._decryptSaltCache.clear();
4850
+ this._inflightKeyCache.clear();
4834
4851
  }
4835
4852
  clearKeys() {
4836
4853
  super.clearKeys();
@@ -4842,6 +4859,19 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4842
4859
  this._cachedHash = void 0;
4843
4860
  this._cachedKeyId = void 0;
4844
4861
  this._decryptSaltCache.clear();
4862
+ this._inflightKeyCache.clear();
4863
+ }
4864
+ setKeyring(keys, activeKid) {
4865
+ super.setKeyring(keys, activeKid);
4866
+ this._cachedEncKey = void 0;
4867
+ this._cachedMacKey = void 0;
4868
+ this._cachedSalt = void 0;
4869
+ this._cachedKdf = void 0;
4870
+ this._cachedIter = void 0;
4871
+ this._cachedHash = void 0;
4872
+ this._cachedKeyId = void 0;
4873
+ this._decryptSaltCache.clear();
4874
+ this._inflightKeyCache.clear();
4845
4875
  }
4846
4876
  async warmupKey(options) {
4847
4877
  const res = await this.resolveCBCKeys(options?.key, void 0, void 0, options);
@@ -4900,15 +4930,15 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4900
4930
  }
4901
4931
  }
4902
4932
  if (rawKey && typeof rawKey === "object" && "encKey" in rawKey && "macKey" in rawKey && rawKey.encKey?.algorithm && rawKey.macKey?.algorithm) {
4903
- const encKey2 = rawKey.encKey;
4904
- const macKey2 = rawKey.macKey;
4933
+ const encKey = rawKey.encKey;
4934
+ const macKey = rawKey.macKey;
4905
4935
  if (!keyProvider) {
4906
- this._cachedEncKey = encKey2;
4907
- this._cachedMacKey = macKey2;
4936
+ this._cachedEncKey = encKey;
4937
+ this._cachedMacKey = macKey;
4908
4938
  this._cachedKdf = "direct-pair";
4909
4939
  this._cachedKeyId = currentKeyId;
4910
4940
  }
4911
- return { encKey: encKey2, macKey: macKey2, kdf: "direct-pair", keyId: currentKeyId };
4941
+ return { encKey, macKey, kdf: "direct-pair", keyId: currentKeyId };
4912
4942
  }
4913
4943
  if (typeof rawKey !== "string" && rawKey.algorithm) {
4914
4944
  const cryptoKey = rawKey;
@@ -4924,14 +4954,14 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4924
4954
  } finally {
4925
4955
  new Uint8Array(rawBits).fill(0);
4926
4956
  }
4927
- const encKey2 = await subtle.deriveKey(
4957
+ const encKey = await subtle.deriveKey(
4928
4958
  { name: "HKDF", salt: new Uint8Array(0), info: textEncoder.encode("katlux-cbc-enc"), hash: "SHA-256" },
4929
4959
  hkdfBase,
4930
4960
  { name: "AES-CBC", length: 256 },
4931
4961
  false,
4932
4962
  ["encrypt", "decrypt"]
4933
4963
  );
4934
- const macKey2 = await subtle.deriveKey(
4964
+ const macKey = await subtle.deriveKey(
4935
4965
  { name: "HKDF", salt: new Uint8Array(0), info: textEncoder.encode("katlux-cbc-mac"), hash: "SHA-256" },
4936
4966
  hkdfBase,
4937
4967
  { name: "HMAC", hash: "SHA-256" },
@@ -4939,61 +4969,61 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4939
4969
  ["sign", "verify"]
4940
4970
  );
4941
4971
  if (!keyProvider) {
4942
- this._cachedEncKey = encKey2;
4943
- this._cachedMacKey = macKey2;
4972
+ this._cachedEncKey = encKey;
4973
+ this._cachedMacKey = macKey;
4944
4974
  this._cachedKdf = "hkdf-direct";
4945
4975
  this._cachedKeyId = currentKeyId;
4946
4976
  }
4947
- return { encKey: encKey2, macKey: macKey2, kdf: "hkdf-direct", keyId: currentKeyId };
4977
+ return { encKey, macKey, kdf: "hkdf-direct", keyId: currentKeyId };
4948
4978
  }
4949
4979
  if (rawKey instanceof Uint8Array || rawKey instanceof ArrayBuffer) {
4950
4980
  const rawBytes = rawKey instanceof Uint8Array ? rawKey : new Uint8Array(rawKey);
4951
4981
  if (rawBytes.length === 64) {
4952
- const encKeyBytes2 = rawBytes.slice(0, 32);
4953
- const macKeyBytes2 = rawBytes.slice(32, 64);
4954
- let encKey2;
4955
- let macKey2;
4982
+ const encKeyBytes = rawBytes.slice(0, 32);
4983
+ const macKeyBytes = rawBytes.slice(32, 64);
4984
+ let encKey;
4985
+ let macKey;
4956
4986
  try {
4957
- encKey2 = await subtle.importKey(
4987
+ encKey = await subtle.importKey(
4958
4988
  "raw",
4959
- encKeyBytes2,
4989
+ encKeyBytes,
4960
4990
  { name: "AES-CBC" },
4961
4991
  false,
4962
4992
  ["encrypt", "decrypt"]
4963
4993
  );
4964
- macKey2 = await subtle.importKey(
4994
+ macKey = await subtle.importKey(
4965
4995
  "raw",
4966
- macKeyBytes2,
4996
+ macKeyBytes,
4967
4997
  { name: "HMAC", hash: "SHA-256" },
4968
4998
  false,
4969
4999
  ["sign", "verify"]
4970
5000
  );
4971
5001
  } finally {
4972
- encKeyBytes2.fill(0);
4973
- macKeyBytes2.fill(0);
5002
+ encKeyBytes.fill(0);
5003
+ macKeyBytes.fill(0);
4974
5004
  }
4975
5005
  if (!keyProvider) {
4976
- this._cachedEncKey = encKey2;
4977
- this._cachedMacKey = macKey2;
5006
+ this._cachedEncKey = encKey;
5007
+ this._cachedMacKey = macKey;
4978
5008
  this._cachedKdf = "raw";
4979
5009
  this._cachedKeyId = currentKeyId;
4980
5010
  }
4981
- return { encKey: encKey2, macKey: macKey2, kdf: "raw", keyId: currentKeyId };
5011
+ return { encKey, macKey, kdf: "raw", keyId: currentKeyId };
4982
5012
  }
4983
5013
  if (rawBytes.length === 32) {
4984
5014
  const rawBytesCopy = rawBytes.slice();
4985
- let encKey2;
4986
- let macKey2;
5015
+ let encKey;
5016
+ let macKey;
4987
5017
  try {
4988
5018
  const hkdfBase = await subtle.importKey("raw", rawBytesCopy, "HKDF", false, ["deriveKey"]);
4989
- encKey2 = await subtle.deriveKey(
5019
+ encKey = await subtle.deriveKey(
4990
5020
  { name: "HKDF", salt: new Uint8Array(0), info: textEncoder.encode("katlux-cbc-enc"), hash: "SHA-256" },
4991
5021
  hkdfBase,
4992
5022
  { name: "AES-CBC", length: 256 },
4993
5023
  false,
4994
5024
  ["encrypt", "decrypt"]
4995
5025
  );
4996
- macKey2 = await subtle.deriveKey(
5026
+ macKey = await subtle.deriveKey(
4997
5027
  { name: "HKDF", salt: new Uint8Array(0), info: textEncoder.encode("katlux-cbc-mac"), hash: "SHA-256" },
4998
5028
  hkdfBase,
4999
5029
  { name: "HMAC", hash: "SHA-256" },
@@ -5004,133 +5034,154 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
5004
5034
  rawBytesCopy.fill(0);
5005
5035
  }
5006
5036
  if (!keyProvider) {
5007
- this._cachedEncKey = encKey2;
5008
- this._cachedMacKey = macKey2;
5037
+ this._cachedEncKey = encKey;
5038
+ this._cachedMacKey = macKey;
5009
5039
  this._cachedKdf = "raw";
5010
5040
  this._cachedKeyId = currentKeyId;
5011
5041
  }
5012
- return { encKey: encKey2, macKey: macKey2, kdf: "raw", keyId: currentKeyId };
5042
+ return { encKey, macKey, kdf: "raw", keyId: currentKeyId };
5013
5043
  }
5014
5044
  throw new Error(
5015
5045
  `[CWebCryptoAESCBCProvider] AES-CBC requires a 32-byte or 64-byte key. Received a binary key of ${rawBytes.length} bytes. Provide exactly 32 bytes (for HKDF companion key derivation) or 64 bytes (split AES/HMAC), or a string passphrase.`
5016
5046
  );
5017
5047
  }
5018
- const passphraseBytes = textEncoder.encode(rawKey);
5019
5048
  const kdf = (kdfOverride || options?.kdf || this._defaultKdf || "pbkdf2").toLowerCase();
5020
- if (kdf === "hkdf" && typeof rawKey === "string") {
5021
- console.warn(
5022
- '[CWebCryptoAESCBCProvider] ADVISORY: HKDF is designed for high-entropy input key material (IKM), not low-entropy human passphrases. Use "pbkdf2" for password-derived encryption.'
5023
- );
5024
- }
5025
- let raw512;
5026
- let saltStr;
5027
- let kdfType;
5028
- let iterNum;
5029
- try {
5030
- if (kdf === "pbkdf2") {
5031
- const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
5032
- const saltBytes = CKeyManager.resolveSalt(s);
5033
- saltStr = CKeyManager.toBase64(saltBytes);
5034
- kdfType = "PBKDF2";
5035
- const iterations = resolveAndClampPbkdf2Iterations({
5036
- iterationsOverride,
5037
- optionsIterations: options?.kdfIterations,
5038
- defaultIterations: this._kdfOptions?.iterations,
5039
- optionsMaxAllowed: options?.maxAllowedIterations,
5040
- providerMaxAllowed: this._maxAllowedIterations,
5041
- context: "[CWebCryptoAESCBCProvider]"
5042
- });
5043
- iterNum = iterations;
5044
- const baseKey = await subtle.importKey(
5049
+ const canDedupeInflight = !saltOverride && !options?.kdfSalt && kdf === "pbkdf2";
5050
+ const targetIterForKey = iterationsOverride || options?.kdfIterations || this._kdfOptions?.iterations || "";
5051
+ const targetHashForKey = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
5052
+ const inflightKey = canDedupeInflight ? `${currentKeyId}:pbkdf2:${targetIterForKey}:${targetHashForKey}` : "";
5053
+ if (canDedupeInflight) {
5054
+ const existingInflight = this._inflightKeyCache.get(inflightKey);
5055
+ if (existingInflight) {
5056
+ return await existingInflight;
5057
+ }
5058
+ }
5059
+ const derivePromise = (async () => {
5060
+ const passphraseBytes = textEncoder.encode(rawKey);
5061
+ if (kdf === "hkdf" && typeof rawKey === "string") {
5062
+ console.warn(
5063
+ '[CWebCryptoAESCBCProvider] ADVISORY: HKDF is designed for high-entropy input key material (IKM), not low-entropy human passphrases. Use "pbkdf2" for password-derived encryption.'
5064
+ );
5065
+ }
5066
+ let raw512;
5067
+ let saltStr;
5068
+ let kdfType;
5069
+ let iterNum;
5070
+ try {
5071
+ if (kdf === "pbkdf2") {
5072
+ const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
5073
+ const saltBytes = CKeyManager.resolveSalt(s);
5074
+ saltStr = CKeyManager.toBase64(saltBytes);
5075
+ kdfType = "PBKDF2";
5076
+ const iterations = resolveAndClampPbkdf2Iterations({
5077
+ iterationsOverride,
5078
+ optionsIterations: options?.kdfIterations,
5079
+ defaultIterations: this._kdfOptions?.iterations,
5080
+ optionsMaxAllowed: options?.maxAllowedIterations,
5081
+ providerMaxAllowed: this._maxAllowedIterations,
5082
+ context: "[CWebCryptoAESCBCProvider]"
5083
+ });
5084
+ iterNum = iterations;
5085
+ const baseKey = await subtle.importKey(
5086
+ "raw",
5087
+ passphraseBytes,
5088
+ "PBKDF2",
5089
+ false,
5090
+ ["deriveBits"]
5091
+ );
5092
+ raw512 = await subtle.deriveBits(
5093
+ {
5094
+ name: "PBKDF2",
5095
+ salt: saltBytes,
5096
+ iterations,
5097
+ hash: options?.kdfHash || this._kdfOptions?.hash || "SHA-512"
5098
+ },
5099
+ baseKey,
5100
+ 512
5101
+ );
5102
+ } else if (kdf === "hkdf") {
5103
+ const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
5104
+ const saltBytes = CKeyManager.resolveSalt(s);
5105
+ saltStr = CKeyManager.toBase64(saltBytes);
5106
+ kdfType = "HKDF";
5107
+ const baseKey = await subtle.importKey(
5108
+ "raw",
5109
+ passphraseBytes,
5110
+ "HKDF",
5111
+ false,
5112
+ ["deriveBits"]
5113
+ );
5114
+ raw512 = await subtle.deriveBits(
5115
+ {
5116
+ name: "HKDF",
5117
+ salt: saltBytes,
5118
+ info: resolveInfoBytes(options?.info || this._kdfOptions?.info, "katlux-aescbc-hmac-key"),
5119
+ hash: options?.kdfHash || this._kdfOptions?.hash || "SHA-512"
5120
+ },
5121
+ baseKey,
5122
+ 512
5123
+ );
5124
+ } else {
5125
+ raw512 = await subtle.digest("SHA-512", passphraseBytes);
5126
+ }
5127
+ } finally {
5128
+ if (typeof rawKey === "string") {
5129
+ passphraseBytes.fill(0);
5130
+ }
5131
+ }
5132
+ const bytes = new Uint8Array(raw512);
5133
+ const encKeyBytes = bytes.slice(0, 32);
5134
+ const macKeyBytes = bytes.slice(32, 64);
5135
+ let encKey;
5136
+ let macKey;
5137
+ try {
5138
+ encKey = await subtle.importKey(
5045
5139
  "raw",
5046
- passphraseBytes,
5047
- "PBKDF2",
5140
+ encKeyBytes,
5141
+ { name: "AES-CBC" },
5048
5142
  false,
5049
- ["deriveBits"]
5050
- );
5051
- raw512 = await subtle.deriveBits(
5052
- {
5053
- name: "PBKDF2",
5054
- salt: saltBytes,
5055
- iterations,
5056
- hash: options?.kdfHash || this._kdfOptions?.hash || "SHA-512"
5057
- },
5058
- baseKey,
5059
- 512
5143
+ ["encrypt", "decrypt"]
5060
5144
  );
5061
- } else if (kdf === "hkdf") {
5062
- const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
5063
- const saltBytes = CKeyManager.resolveSalt(s);
5064
- saltStr = CKeyManager.toBase64(saltBytes);
5065
- kdfType = "HKDF";
5066
- const baseKey = await subtle.importKey(
5145
+ macKey = await subtle.importKey(
5067
5146
  "raw",
5068
- passphraseBytes,
5069
- "HKDF",
5147
+ macKeyBytes,
5148
+ { name: "HMAC", hash: "SHA-256" },
5070
5149
  false,
5071
- ["deriveBits"]
5072
- );
5073
- raw512 = await subtle.deriveBits(
5074
- {
5075
- name: "HKDF",
5076
- salt: saltBytes,
5077
- info: resolveInfoBytes(options?.info || this._kdfOptions?.info, "katlux-aescbc-hmac-key"),
5078
- hash: options?.kdfHash || this._kdfOptions?.hash || "SHA-512"
5079
- },
5080
- baseKey,
5081
- 512
5150
+ ["sign", "verify"]
5082
5151
  );
5083
- } else {
5084
- raw512 = await subtle.digest("SHA-512", passphraseBytes);
5152
+ } finally {
5153
+ bytes.fill(0);
5154
+ encKeyBytes.fill(0);
5155
+ macKeyBytes.fill(0);
5156
+ new Uint8Array(raw512).fill(0);
5157
+ }
5158
+ if (!keyProvider && !saltOverride && !options?.kdfSalt) {
5159
+ this._cachedEncKey = encKey;
5160
+ this._cachedMacKey = macKey;
5161
+ this._cachedSalt = saltStr;
5162
+ this._cachedKdf = kdfType || "none";
5163
+ this._cachedIter = iterNum;
5164
+ this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
5165
+ this._cachedKeyId = currentKeyId;
5085
5166
  }
5086
- } finally {
5087
- if (typeof rawKey === "string") {
5088
- passphraseBytes.fill(0);
5167
+ return {
5168
+ encKey,
5169
+ macKey,
5170
+ salt: saltStr,
5171
+ kdf: kdfType,
5172
+ iter: iterNum,
5173
+ keyId: currentKeyId
5174
+ };
5175
+ })();
5176
+ if (canDedupeInflight) {
5177
+ this._inflightKeyCache.set(inflightKey, derivePromise);
5178
+ try {
5179
+ return await derivePromise;
5180
+ } finally {
5181
+ this._inflightKeyCache.delete(inflightKey);
5089
5182
  }
5090
5183
  }
5091
- const bytes = new Uint8Array(raw512);
5092
- const encKeyBytes = bytes.slice(0, 32);
5093
- const macKeyBytes = bytes.slice(32, 64);
5094
- let encKey;
5095
- let macKey;
5096
- try {
5097
- encKey = await subtle.importKey(
5098
- "raw",
5099
- encKeyBytes,
5100
- { name: "AES-CBC" },
5101
- false,
5102
- ["encrypt", "decrypt"]
5103
- );
5104
- macKey = await subtle.importKey(
5105
- "raw",
5106
- macKeyBytes,
5107
- { name: "HMAC", hash: "SHA-256" },
5108
- false,
5109
- ["sign", "verify"]
5110
- );
5111
- } finally {
5112
- bytes.fill(0);
5113
- encKeyBytes.fill(0);
5114
- macKeyBytes.fill(0);
5115
- new Uint8Array(raw512).fill(0);
5116
- }
5117
- if (!keyProvider && !saltOverride && !options?.kdfSalt) {
5118
- this._cachedEncKey = encKey;
5119
- this._cachedMacKey = macKey;
5120
- this._cachedSalt = saltStr;
5121
- this._cachedKdf = kdfType || "none";
5122
- this._cachedIter = iterNum;
5123
- this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
5124
- this._cachedKeyId = currentKeyId;
5125
- }
5126
- return {
5127
- encKey,
5128
- macKey,
5129
- salt: saltStr,
5130
- kdf: kdfType,
5131
- iter: iterNum,
5132
- keyId: currentKeyId
5133
- };
5184
+ return await derivePromise;
5134
5185
  }
5135
5186
  static isEncrypted(payload) {
5136
5187
  if (!payload || typeof payload !== "object") return false;
@@ -6007,12 +6058,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
6007
6058
  }
6008
6059
  setKeyring(keys, activeKid) {
6009
6060
  super.setKeyring(keys, activeKid);
6010
- for (const entry of this._decryptSaltCache.values()) {
6011
- if (entry.key !== this._cachedKey) entry.key.fill(0);
6012
- }
6013
- this._decryptSaltCache.clear();
6014
- this._inFlightSaltDerivations.clear();
6015
- this._keyringCache.clear();
6061
+ this._wipeCachedBuffers();
6016
6062
  }
6017
6063
  _setPrimaryCached(res, keyId, options) {
6018
6064
  this._cachedKey = res.key;
@@ -9460,6 +9506,153 @@ const normalizeFilter = (filter) => {
9460
9506
  }
9461
9507
  return null;
9462
9508
  };
9509
+ const compileFilter = (filter, options) => {
9510
+ if (!filter || filter.active === false) return () => true;
9511
+ const norm = normalizeFilter(filter);
9512
+ if (!norm || norm.active === false) return () => true;
9513
+ const compileNode = (node) => {
9514
+ if (!node || node.active === false) return () => true;
9515
+ const op = node.operator;
9516
+ if (op === "not") {
9517
+ const childFn = compileNode(node.field);
9518
+ return (row) => !childFn(row);
9519
+ }
9520
+ if (op === EDataFilterOperator.And || op === EDataFilterOperator.Or || op === EDataFilterOperator.Nand || op === EDataFilterOperator.Nor) {
9521
+ const subFilters = Array.isArray(node.field) ? node.field : [];
9522
+ const compiled = subFilters.map(compileNode);
9523
+ const count = compiled.length;
9524
+ if (op === EDataFilterOperator.And) {
9525
+ if (count === 0) return () => true;
9526
+ if (count === 1) return compiled[0];
9527
+ if (count === 2) {
9528
+ const f0 = compiled[0];
9529
+ const f1 = compiled[1];
9530
+ return (row) => f0(row) && f1(row);
9531
+ }
9532
+ return (row) => {
9533
+ for (let i = 0; i < count; i++) {
9534
+ if (!compiled[i](row)) return false;
9535
+ }
9536
+ return true;
9537
+ };
9538
+ }
9539
+ if (op === EDataFilterOperator.Or) {
9540
+ if (count === 0) return () => false;
9541
+ if (count === 1) return compiled[0];
9542
+ if (count === 2) {
9543
+ const f0 = compiled[0];
9544
+ const f1 = compiled[1];
9545
+ return (row) => f0(row) || f1(row);
9546
+ }
9547
+ return (row) => {
9548
+ for (let i = 0; i < count; i++) {
9549
+ if (compiled[i](row)) return true;
9550
+ }
9551
+ return false;
9552
+ };
9553
+ }
9554
+ if (op === EDataFilterOperator.Nand) {
9555
+ if (count === 0) return () => false;
9556
+ return (row) => {
9557
+ for (let i = 0; i < count; i++) {
9558
+ if (!compiled[i](row)) return true;
9559
+ }
9560
+ return false;
9561
+ };
9562
+ }
9563
+ if (count === 0) return () => true;
9564
+ return (row) => {
9565
+ for (let i = 0; i < count; i++) {
9566
+ if (compiled[i](row)) return false;
9567
+ }
9568
+ return true;
9569
+ };
9570
+ }
9571
+ const field = node.field;
9572
+ if (!field || typeof field !== "object") return () => true;
9573
+ const entries = Object.entries(field);
9574
+ if (entries.length === 0) return () => true;
9575
+ const predicates = entries.map(([key, filterValue]) => {
9576
+ if (op === EDataFilterOperator.Equal || op === EDataFilterOperator.NotEqual) {
9577
+ const negate = op === EDataFilterOperator.NotEqual;
9578
+ if (typeof filterValue === "string") {
9579
+ const normFilter = normalizeFilterValue(filterValue, options);
9580
+ return (row) => {
9581
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9582
+ const match = typeof rv === "string" ? normalizeFilterValue(rv, options) === normFilter : compareEqual(rv, filterValue, options);
9583
+ return negate ? !match : match;
9584
+ };
9585
+ }
9586
+ return (row) => {
9587
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9588
+ const match = compareEqual(rv, filterValue, options);
9589
+ return negate ? !match : match;
9590
+ };
9591
+ } else if (op === EDataFilterOperator.Contains) {
9592
+ const negate = false;
9593
+ if (filterValue === null || filterValue === void 0 || filterValue === "") {
9594
+ return () => !negate;
9595
+ }
9596
+ if (typeof filterValue === "string") {
9597
+ const normFilter = normalizeFilterValue(filterValue, options);
9598
+ return (row) => {
9599
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9600
+ if (rv === null || rv === void 0) return negate;
9601
+ if (typeof rv === "string") {
9602
+ const match2 = normalizeFilterValue(rv, options).includes(normFilter);
9603
+ return match2;
9604
+ }
9605
+ const match = compareContains(rv, filterValue, options);
9606
+ return match;
9607
+ };
9608
+ }
9609
+ return (row) => {
9610
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9611
+ if (rv === null || rv === void 0) return negate;
9612
+ const match = compareContains(rv, filterValue, options);
9613
+ return match;
9614
+ };
9615
+ } else if (op === EDataFilterOperator.In || op === EDataFilterOperator.NotIn) {
9616
+ const negate = op === EDataFilterOperator.NotIn;
9617
+ if (Array.isArray(filterValue) || filterValue instanceof Set) {
9618
+ const normStrings = /* @__PURE__ */ new Set();
9619
+ const rawValues = /* @__PURE__ */ new Set();
9620
+ for (const item of filterValue) {
9621
+ if (typeof item === "string") {
9622
+ normStrings.add(normalizeFilterValue(item, options));
9623
+ } else {
9624
+ rawValues.add(item);
9625
+ }
9626
+ }
9627
+ return (row) => {
9628
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9629
+ if (typeof rv === "string") {
9630
+ const match2 = normStrings.has(normalizeFilterValue(rv, options)) || rawValues.size > 0 && compareIn(rv, filterValue, options);
9631
+ return negate ? !match2 : match2;
9632
+ }
9633
+ if (rv !== null && typeof rv !== "object" && rawValues.has(rv)) {
9634
+ return !negate;
9635
+ }
9636
+ const match = compareIn(rv, filterValue, options);
9637
+ return negate ? !match : match;
9638
+ };
9639
+ }
9640
+ }
9641
+ return (row) => {
9642
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9643
+ return applyOperator(op, rv, filterValue, options);
9644
+ };
9645
+ });
9646
+ if (predicates.length === 1) return predicates[0];
9647
+ return (row) => {
9648
+ for (let i = 0; i < predicates.length; i++) {
9649
+ if (!predicates[i](row)) return false;
9650
+ }
9651
+ return true;
9652
+ };
9653
+ };
9654
+ return compileNode(norm);
9655
+ };
9463
9656
  const evaluateFilter = (filter, row, options) => {
9464
9657
  if (!filter || filter.active === false) return true;
9465
9658
  const norm = normalizeFilter(filter);
@@ -9500,9 +9693,10 @@ const filterTreeData = (nodes, filter, options) => {
9500
9693
  const matchingNodeIds = /* @__PURE__ */ new Set();
9501
9694
  const expandedNodes = /* @__PURE__ */ new Set();
9502
9695
  const visibleNodeIds = /* @__PURE__ */ new Set();
9696
+ const evaluator = compileFilter(filter, normalizeOptions);
9503
9697
  nodes.forEach((node) => {
9504
9698
  const evalRow = node.data ? { ...node.data, ...node } : node;
9505
- if (evaluateFilter(filter, evalRow, normalizeOptions)) {
9699
+ if (evaluator(evalRow)) {
9506
9700
  matchingNodeIds.add(node[idKey]);
9507
9701
  }
9508
9702
  });
@@ -9566,7 +9760,7 @@ const filterData = (data, filter, options) => {
9566
9760
  }
9567
9761
  }
9568
9762
  }
9569
- const evaluator = options?.rowEvaluator ? options.rowEvaluator : (item) => evaluateFilter(filter, item, options?.normalizeOptions);
9763
+ const evaluator = options?.rowEvaluator ? options.rowEvaluator : compileFilter(filter, options?.normalizeOptions);
9570
9764
  for (let i = 0; i < len; i++) {
9571
9765
  const item = data[i];
9572
9766
  if (item === void 0 || item === null) continue;
@@ -11467,11 +11661,49 @@ class CSearchIndex {
11467
11661
  }
11468
11662
  }
11469
11663
 
11664
+ class CLruMap extends Map {
11665
+ maxSize;
11666
+ _onEvict;
11667
+ constructor(maxSize = 5e3, onEvict) {
11668
+ super();
11669
+ this.maxSize = Math.max(1, Math.floor(maxSize));
11670
+ this._onEvict = onEvict;
11671
+ }
11672
+ get(key) {
11673
+ if (!super.has(key)) return void 0;
11674
+ const value = super.get(key);
11675
+ super.delete(key);
11676
+ super.set(key, value);
11677
+ return value;
11678
+ }
11679
+ set(key, value) {
11680
+ if (super.has(key)) {
11681
+ super.delete(key);
11682
+ }
11683
+ super.set(key, value);
11684
+ while (super.size > this.maxSize) {
11685
+ const first = super.entries().next().value;
11686
+ if (!first) break;
11687
+ const [oldestKey, oldestValue] = first;
11688
+ super.delete(oldestKey);
11689
+ this._onEvict?.(oldestKey, oldestValue);
11690
+ }
11691
+ return this;
11692
+ }
11693
+ }
11694
+
11470
11695
  class AEncryptedClientProvider extends ADataProvider {
11471
11696
  encryption;
11472
11697
  _searchIndex;
11473
- _decryptedCache = /* @__PURE__ */ new Map();
11474
11698
  _decryptedRefCache = /* @__PURE__ */ new WeakMap();
11699
+ _idToEncryptedRef = /* @__PURE__ */ new Map();
11700
+ _decryptedCache = new CLruMap(5e3, (evictedId) => {
11701
+ const ref = this._idToEncryptedRef.get(evictedId);
11702
+ if (ref) {
11703
+ this._decryptedRefCache.delete(ref);
11704
+ this._idToEncryptedRef.delete(evictedId);
11705
+ }
11706
+ });
11475
11707
  constructor(options) {
11476
11708
  super(options);
11477
11709
  if (options?.encryption) {
@@ -11533,6 +11765,7 @@ class AEncryptedClientProvider extends ADataProvider {
11533
11765
  this._decryptedRefCache.set(rowOrId, decryptedRow);
11534
11766
  const id = rowOrId[this.idKey] ?? rowOrId.id ?? rowOrId._id;
11535
11767
  if (id !== void 0 && id !== null) {
11768
+ this._idToEncryptedRef.set(id, rowOrId);
11536
11769
  this._decryptedCache.set(id, decryptedRow);
11537
11770
  }
11538
11771
  } else if (rowOrId !== void 0 && rowOrId !== null) {
@@ -11541,6 +11774,7 @@ class AEncryptedClientProvider extends ADataProvider {
11541
11774
  }
11542
11775
  clearDecryptedCache() {
11543
11776
  this._decryptedCache.clear();
11777
+ this._idToEncryptedRef.clear();
11544
11778
  this._decryptedRefCache = /* @__PURE__ */ new WeakMap();
11545
11779
  }
11546
11780
  /**
@@ -11555,8 +11789,16 @@ class AEncryptedClientProvider extends ADataProvider {
11555
11789
  const idKey = this.idKey || "id";
11556
11790
  const rowId = rowOrId[idKey] ?? rowOrId.id ?? rowOrId._id;
11557
11791
  this._deleteCacheIdVariants(this._decryptedCache, rowId);
11792
+ if (rowId !== void 0 && rowId !== null) {
11793
+ this._idToEncryptedRef.delete(rowId);
11794
+ }
11558
11795
  return;
11559
11796
  }
11797
+ const ref = this._idToEncryptedRef.get(rowOrId);
11798
+ if (ref) {
11799
+ this._decryptedRefCache.delete(ref);
11800
+ this._idToEncryptedRef.delete(rowOrId);
11801
+ }
11560
11802
  this._deleteCacheIdVariants(this._decryptedCache, rowOrId);
11561
11803
  }
11562
11804
  /**
@@ -11565,15 +11807,30 @@ class AEncryptedClientProvider extends ADataProvider {
11565
11807
  evictDecryptedRow(rowOrId) {
11566
11808
  this.invalidateDecryptedRow(rowOrId);
11567
11809
  }
11568
- async populateDecryptedCache(rows) {
11810
+ async _forEachChunk(items, options, fn) {
11811
+ const chunkSize = options?.chunkSize ?? 100;
11812
+ for (let offset = 0; offset < items.length; offset += chunkSize) {
11813
+ if (options?.isStale?.()) return;
11814
+ const chunk = items.slice(offset, offset + chunkSize);
11815
+ await fn(chunk);
11816
+ if (options?.isStale?.()) return;
11817
+ if (offset + chunkSize < items.length) {
11818
+ await new Promise((resolve) => setTimeout(resolve, 0));
11819
+ }
11820
+ }
11821
+ }
11822
+ async populateDecryptedCache(rows, options) {
11569
11823
  if (!this.isEncryptionEnabled || !rows || rows.length === 0) return;
11570
11824
  try {
11571
- const { rows: decrypted, decrypted: success } = await this.decryptRows(rows);
11572
- if (success && decrypted) {
11573
- for (let i = 0; i < rows.length; i++) {
11574
- this.cacheDecryptedRow(rows[i], decrypted[i]);
11825
+ await this._forEachChunk(rows, options, async (chunk) => {
11826
+ const { rows: decrypted, decrypted: success } = await this.decryptRows(chunk);
11827
+ if (options?.isStale?.()) return;
11828
+ if (success && decrypted) {
11829
+ for (let i = 0; i < chunk.length; i++) {
11830
+ this.cacheDecryptedRow(chunk[i], decrypted[i]);
11831
+ }
11575
11832
  }
11576
- }
11833
+ });
11577
11834
  } catch (err) {
11578
11835
  console.warn("[Katlux Providers] Failed to populate decrypted cache:", err);
11579
11836
  }
@@ -11684,28 +11941,35 @@ class AEncryptedClientProvider extends ADataProvider {
11684
11941
  this._searchIndex = void 0;
11685
11942
  this.clearDecryptedCache();
11686
11943
  }
11944
+ _getApiUrl() {
11945
+ return void 0;
11946
+ }
11947
+ _extractPlainFields(row, fields) {
11948
+ const plainFields = {};
11949
+ if (!row || typeof row !== "object") return plainFields;
11950
+ const targetFields = fields && fields.length > 0 ? fields : Object.keys(row);
11951
+ for (const f of targetFields) {
11952
+ if (row[f] !== void 0) {
11953
+ plainFields[f] = row[f];
11954
+ }
11955
+ }
11956
+ return plainFields;
11957
+ }
11958
+ async _indexEncryptedRows(encryptedRows, plainRows) {
11959
+ if (!this._searchIndex) return;
11960
+ await Promise.all(encryptedRows.map((encRow, idx) => {
11961
+ const plainFields = this._extractPlainFields(plainRows[idx], this.encryption?.fields);
11962
+ return this._searchIndex.indexRow(encRow, plainFields);
11963
+ }));
11964
+ }
11687
11965
  async encryptRows(rows) {
11688
11966
  if (!this.isEncryptionEnabled || !rows || rows.length === 0) {
11689
11967
  return rows;
11690
11968
  }
11691
- const plainMap = /* @__PURE__ */ new Map();
11692
- if (this._searchIndex) {
11693
- for (const r of rows) {
11694
- const plainFields = {};
11695
- const allKeys = /* @__PURE__ */ new Set([...Object.keys(r || {}), ...this.encryption?.fields || []]);
11696
- for (const f of allKeys) {
11697
- plainFields[f] = r[f];
11698
- }
11699
- plainMap.set(r, plainFields);
11700
- }
11701
- }
11702
- const url = this.apiUrl || void 0;
11703
- const encryptedRows = await encryptRows(rows, this.encryption, url, this.idKey);
11969
+ const plainRows = this._searchIndex ? rows.map((r) => this._extractPlainFields(r, this.encryption?.fields)) : [];
11970
+ const encryptedRows = await encryptRows(rows, this.encryption, this._getApiUrl(), this.idKey);
11704
11971
  if (this._searchIndex) {
11705
- await Promise.all(encryptedRows.map((encRow, i) => {
11706
- const plain = plainMap.get(rows[i]);
11707
- return this._searchIndex.indexRow(encRow, plain);
11708
- }));
11972
+ await this._indexEncryptedRows(encryptedRows, plainRows);
11709
11973
  }
11710
11974
  return encryptedRows;
11711
11975
  }
@@ -11715,57 +11979,37 @@ class AEncryptedClientProvider extends ADataProvider {
11715
11979
  return rows;
11716
11980
  }
11717
11981
  const indexChunk = this._searchIndex ? async (chunkPlain, chunkEncrypted) => {
11718
- const plainMap = /* @__PURE__ */ new Map();
11719
- for (const r of chunkPlain) {
11720
- const plainFields = {};
11721
- for (const f of this.encryption?.fields || Object.keys(r)) {
11722
- plainFields[f] = r[f];
11723
- }
11724
- plainMap.set(r, plainFields);
11725
- }
11726
- await Promise.all(chunkEncrypted.map((encRow, idx) => {
11727
- const plain = plainMap.get(chunkPlain[idx]);
11728
- return this._searchIndex.indexRow(encRow, plain);
11729
- }));
11982
+ await this._indexEncryptedRows(chunkEncrypted, chunkPlain);
11730
11983
  } : void 0;
11731
- return await encryptRowsChunked(rows, this.encryption, options, void 0, this.idKey, indexChunk);
11984
+ return await encryptRowsChunked(rows, this.encryption, options, this._getApiUrl(), this.idKey, indexChunk);
11732
11985
  }
11733
11986
  /**
11734
11987
  * Indexes pre-encrypted rows by performing a transient in-memory decryption pass
11735
11988
  * on search fields to populate CSearchIndex without mutating underlying encrypted records in allData.
11736
11989
  */
11737
- async indexPreEncryptedRows(rows) {
11990
+ async indexPreEncryptedRows(rows, options) {
11738
11991
  if (!this.isEncryptionEnabled || !this._searchIndex || !rows || rows.length === 0) {
11739
11992
  return;
11740
11993
  }
11741
11994
  const cipher = getCipherProvider(this.encryption);
11742
11995
  if (!cipher) return;
11743
- const ctx = buildEncryptionContext(this.encryption, this.apiUrl, this.idKey);
11744
- let decryptedRows = [];
11996
+ const ctx = buildEncryptionContext(this.encryption, this._getApiUrl(), this.idKey);
11745
11997
  try {
11746
- const decResult = await cipher.decrypt(rows, ctx);
11747
- decryptedRows = Array.isArray(decResult) ? decResult : [decResult];
11998
+ await this._forEachChunk(rows, options, async (chunk) => {
11999
+ const decResult = await cipher.decrypt(chunk, ctx);
12000
+ if (options?.isStale?.()) return;
12001
+ const decryptedRows = Array.isArray(decResult) ? decResult : [decResult];
12002
+ await this._indexEncryptedRows(chunk, decryptedRows);
12003
+ });
11748
12004
  } catch (err) {
11749
12005
  console.warn("[Katlux Providers] indexPreEncryptedRows: Decryption failed during search index build", err);
11750
- return;
11751
12006
  }
11752
- await Promise.all(rows.map((row, idx) => {
11753
- const decRow = decryptedRows[idx];
11754
- const plainFields = {};
11755
- for (const f of this.encryption?.fields || Object.keys(decRow || {})) {
11756
- if (decRow && decRow[f] !== void 0) {
11757
- plainFields[f] = decRow[f];
11758
- }
11759
- }
11760
- return this._searchIndex.indexRow(row, plainFields);
11761
- }));
11762
12007
  }
11763
12008
  async decryptRows(rows) {
11764
12009
  if (!this.isEncryptionEnabled || !rows || rows.length === 0) {
11765
12010
  return { rows, decrypted: false };
11766
12011
  }
11767
- const url = this.apiUrl || void 0;
11768
- return await decryptPageRows(rows, this.encryption, url, this.idKey);
12012
+ return await decryptPageRows(rows, this.encryption, this._getApiUrl(), this.idKey);
11769
12013
  }
11770
12014
  async setDataChunked(data, options) {
11771
12015
  const ret = this.setData(data);
@@ -11910,14 +12154,15 @@ async function prepareIncomingEncryptedRows(host, rows, options) {
11910
12154
  }
11911
12155
  if (isPreEnc) {
11912
12156
  if (host.searchIndex) {
11913
- await host.indexPreEncryptedRows(rows);
12157
+ await host.indexPreEncryptedRows(rows, { isStale: options?.isStale });
11914
12158
  if (options?.isStale?.()) return { rows, preEncrypted: true, stale: true };
11915
12159
  }
11916
12160
  if (options?.populateCache && host.encryption?.decryptedCache) {
11917
- await host.populateDecryptedCache(rows);
12161
+ await host.populateDecryptedCache(rows, { isStale: options?.isStale });
12162
+ if (options?.isStale?.()) return { rows, preEncrypted: true, stale: true };
11918
12163
  if (options?.decryptedNodeMap) {
11919
- for (const r of rows) {
11920
- recordDecryptedNodeMap(options.decryptedNodeMap, host.idKey, r, host.getDecryptedRow(r));
12164
+ for (let i = 0; i < rows.length; i++) {
12165
+ recordDecryptedNodeMap(options.decryptedNodeMap, host.idKey, rows[i], host.getDecryptedRow(rows[i]));
11921
12166
  }
11922
12167
  }
11923
12168
  }
@@ -12118,12 +12363,14 @@ function areAllBatchesLoaded(batchSize, totalRows, loadedCount) {
12118
12363
  const totalBatches = Math.ceil(totalRows / batchSize);
12119
12364
  return loadedCount >= totalBatches;
12120
12365
  }
12121
- async function applyOnDemandPolicy(policy, contextLabel, ingestAllFn, batchNoun = "batches") {
12366
+ async function applyOnDemandPolicy(policy, contextLabel, ingestAllFn, batchNoun = "batches", onComplete) {
12122
12367
  if (policy === "ingestAll") {
12123
12368
  console.warn(
12124
12369
  `[Katlux Providers] ${contextLabel} applied with partial on-demand ${batchNoun}. Ingesting all remaining batches in background to ensure accurate results.`
12125
12370
  );
12126
- await ingestAllFn();
12371
+ void Promise.resolve(ingestAllFn()).then(() => onComplete?.()).catch((err) => {
12372
+ console.error(`[Katlux Providers] Background ${batchNoun} ingestion failed during ${contextLabel}:`, err);
12373
+ });
12127
12374
  } else {
12128
12375
  console.warn(
12129
12376
  `[Katlux Providers] ${contextLabel} applied while on-demand ${batchNoun} are partially loaded. Some matching records may not be in memory.`
@@ -12240,6 +12487,7 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12240
12487
  batchSize = false;
12241
12488
  batchLoad = "initially";
12242
12489
  onDemandFilterPolicy = "ingestAll";
12490
+ maxCachedBatches;
12243
12491
  onBatchLoaded;
12244
12492
  loadedBatches = /* @__PURE__ */ new Set();
12245
12493
  _rawSourceData;
@@ -12270,8 +12518,34 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12270
12518
  if (options?.batchSize !== void 0) this.batchSize = options.batchSize;
12271
12519
  if (options?.batchLoad) this.batchLoad = options.batchLoad;
12272
12520
  if (options?.onDemandFilterPolicy) this.onDemandFilterPolicy = options.onDemandFilterPolicy;
12521
+ if (options?.maxCachedBatches !== void 0) this.maxCachedBatches = options.maxCachedBatches;
12273
12522
  if (options?.onBatchLoaded) this.onBatchLoaded = options.onBatchLoaded;
12274
12523
  }
12524
+ /**
12525
+ * Evicts oldest loaded batches when maxCachedBatches is configured and exceeded,
12526
+ * clearing their slots in _allData so they can be re-fetched on demand.
12527
+ */
12528
+ _evictOldestBatchesIfNeeded(activeBatch) {
12529
+ if (this.maxCachedBatches === void 0 || this.maxCachedBatches <= 0) return;
12530
+ if (typeof this.batchSize !== "number" || this.batchSize <= 0) return;
12531
+ while (this.loadedBatches.size > this.maxCachedBatches) {
12532
+ let evicted;
12533
+ for (const b of this.loadedBatches) {
12534
+ if (b !== activeBatch) {
12535
+ evicted = b;
12536
+ break;
12537
+ }
12538
+ }
12539
+ if (evicted === void 0) break;
12540
+ this.loadedBatches.delete(evicted);
12541
+ const start = (evicted - 1) * this.batchSize;
12542
+ const end = Math.min(evicted * this.batchSize, this._allData.length);
12543
+ for (let i = start; i < end; i++) {
12544
+ this._allData[i] = void 0;
12545
+ }
12546
+ this._isSparse = true;
12547
+ }
12548
+ }
12275
12549
  _assignAllData(data, preserveDecryptedCache = false) {
12276
12550
  this._allData = Array.isArray(data) ? data : [];
12277
12551
  this._filterDirty = true;
@@ -12350,7 +12624,9 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12350
12624
  }
12351
12625
  this._filterDirty = true;
12352
12626
  this._sortDirty = true;
12353
- await this.loadPageData();
12627
+ if (!(this.pageSize > 0 && (this.pageData?.length ?? 0) >= this.pageSize)) {
12628
+ await this.loadPageData();
12629
+ }
12354
12630
  emitBatchLoaded(this.onBatchLoaded, { pageNumber: pageNum, rows: nextChunk, totalLoaded: this.allData.length, rowCount: total });
12355
12631
  this.loadedBatches.add(pageNum);
12356
12632
  this.batchProgress = computeBatchProgress(this.allData.length, total);
@@ -12358,6 +12634,10 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12358
12634
  pageNum++;
12359
12635
  }
12360
12636
  if (batchGen === this._batchGeneration) {
12637
+ if (this._filterDirty || this._sortDirty) {
12638
+ await this.loadPageData();
12639
+ if (batchGen !== this._batchGeneration) return;
12640
+ }
12361
12641
  this.isBatchLoading = false;
12362
12642
  this.batchProgress = { loaded: this.allData.length, total, percent: 100 };
12363
12643
  this.notify();
@@ -12631,7 +12911,8 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12631
12911
  this.error = null;
12632
12912
  try {
12633
12913
  if (this.encryption?.decryptedCache && this.sortList.length > 0) {
12634
- if (this.sortList.some((s) => this.isFieldEncrypted(s.field, this.allData))) {
12914
+ const rangeBuckets = this.encryption?.rangeBuckets || this.encryption?.shadowBuckets;
12915
+ if (this.sortList.some((s) => this.isFieldEncrypted(s.field, this.allData) && !rangeBuckets?.[s.field])) {
12635
12916
  const uncached = this.allData.filter((r) => r !== void 0 && r !== null && !this.getDecryptedRow(r));
12636
12917
  if (uncached.length > 0) await this.populateDecryptedCache(uncached);
12637
12918
  }
@@ -12824,6 +13105,9 @@ class CAPIFlatClientDataProvider extends CFlatClientDataProvider {
12824
13105
  _lastDataReceivedPromise = null;
12825
13106
  _lastBatch1CallbackGen = -1;
12826
13107
  _suppressOnDemandWarn = false;
13108
+ _getApiUrl() {
13109
+ return this.apiUrl || void 0;
13110
+ }
12827
13111
  setData(data) {
12828
13112
  this._bumpRequestGeneration();
12829
13113
  this._isStreamingBatches = false;
@@ -15578,17 +15862,6 @@ function computeRetainedExpandedNodes(staticNodes, expandedNodes, expandedByDefa
15578
15862
  const parentIds = staticNodes.filter((n) => n.hasChildren).map((n) => n.id);
15579
15863
  return /* @__PURE__ */ new Set([...validExisting, ...parentIds]);
15580
15864
  }
15581
- function mergeUniqueTreeRows(existingData, incomingRows, idKey) {
15582
- const existingIds = new Set(
15583
- existingData.map((r) => r && typeof r === "object" ? r[idKey] : void 0).filter((id) => id !== void 0 && id !== null)
15584
- );
15585
- const uniqueIncoming = existingIds.size > 0 ? incomingRows.filter((r) => {
15586
- const id = r && typeof r === "object" ? r[idKey] : void 0;
15587
- return id === void 0 || id === null || !existingIds.has(id);
15588
- }) : incomingRows;
15589
- if (uniqueIncoming.length === 0) return null;
15590
- return [...existingData, ...uniqueIncoming];
15591
- }
15592
15865
 
15593
15866
  class CTreeClientDataProvider extends CFlatClientDataProvider {
15594
15867
  parentKey = "parentId";
@@ -15601,7 +15874,8 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15601
15874
  _sortedNodeIdsCache = null;
15602
15875
  _filteredNodesCache = null;
15603
15876
  _allVisibleRowsCache = null;
15604
- _decryptedNodeMap = /* @__PURE__ */ new Map();
15877
+ _decryptedNodeMap = new CLruMap(5e3);
15878
+ _knownIds = /* @__PURE__ */ new Set();
15605
15879
  clearDecryptedCache() {
15606
15880
  super.clearDecryptedCache();
15607
15881
  this._decryptedNodeMap.clear();
@@ -15625,8 +15899,36 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15625
15899
  _assignAllData(data, preserveDecryptedCache = false) {
15626
15900
  super._assignAllData(data, preserveDecryptedCache);
15627
15901
  if (!preserveDecryptedCache) this._decryptedNodeMap.clear();
15902
+ this._knownIds.clear();
15903
+ const idKey = this.idKey || "id";
15904
+ for (let i = 0; i < this.allData.length; i++) {
15905
+ const id = this.allData[i]?.[idKey];
15906
+ if (id !== void 0 && id !== null) this._knownIds.add(id);
15907
+ }
15628
15908
  this.invalidateStaticCache();
15629
15909
  }
15910
+ /** Appends unique rows in-place using _knownIds without cloning allData. */
15911
+ _appendUniqueTreeRows(rows) {
15912
+ if (!Array.isArray(rows) || rows.length === 0) return false;
15913
+ const idKey = this.idKey || "id";
15914
+ let appended = false;
15915
+ for (let i = 0; i < rows.length; i++) {
15916
+ const row = rows[i];
15917
+ const id = row?.[idKey];
15918
+ if (id === void 0 || id === null || !this._knownIds.has(id)) {
15919
+ if (id !== void 0 && id !== null) this._knownIds.add(id);
15920
+ this.allData.push(row);
15921
+ appended = true;
15922
+ }
15923
+ }
15924
+ if (appended) {
15925
+ this.invalidateStaticCache();
15926
+ this._filterDirty = true;
15927
+ this._sortDirty = true;
15928
+ this.expandedNodes = computeRetainedExpandedNodes(this._staticNodes, this.expandedNodes, this.expandedByDefault);
15929
+ }
15930
+ return appended;
15931
+ }
15630
15932
  get allData() {
15631
15933
  return super.allData;
15632
15934
  }
@@ -15771,11 +16073,13 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15771
16073
  if (batchGen !== this._batchGeneration) return;
15772
16074
  const nextChunk = data.slice(i, i + batchSize);
15773
16075
  const processedRes = await prepareIncomingEncryptedRows(this._getEncryptionHost(), nextChunk, { populateCache: true });
15774
- this._applyTreeData([...this.allData, ...processedRes.rows], true);
16076
+ this._appendUniqueTreeRows(processedRes.rows);
15775
16077
  if (this.isEncryptionEnabled && this.encryption?.decryptedCache) {
15776
16078
  for (const [id, dec] of this._decryptedCache.entries()) this._decryptedNodeMap.set(id, dec);
15777
16079
  }
15778
- await this.loadPageData();
16080
+ if (!(this.pageSize > 0 && (this.pageData?.length ?? 0) >= this.pageSize)) {
16081
+ await this.loadPageData();
16082
+ }
15779
16083
  emitBatchLoaded(this.onBatchLoaded, { pageNumber: pageNum, rows: nextChunk, totalLoaded: this.allData.length, rowCount: total });
15780
16084
  this.loadedBatches.add(pageNum);
15781
16085
  this.batchProgress = computeBatchProgress(this.allData.length, total);
@@ -15783,6 +16087,10 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15783
16087
  pageNum++;
15784
16088
  }
15785
16089
  if (batchGen === this._batchGeneration) {
16090
+ if (this._filterDirty || this._sortDirty) {
16091
+ await this.loadPageData();
16092
+ if (batchGen !== this._batchGeneration) return;
16093
+ }
15786
16094
  this.isBatchLoading = false;
15787
16095
  this.batchProgress = { loaded: this.allData.length, total, percent: 100 };
15788
16096
  this.notify();
@@ -15935,10 +16243,13 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15935
16243
  this.loading = true;
15936
16244
  this.error = null;
15937
16245
  try {
15938
- if (this.encryption?.decryptedCache && this.sortList.length > 0 && this.sortList.some((s) => this.isFieldEncrypted(s.field, this.allData))) {
15939
- const uncached = this._staticNodes.filter((n) => !this._decryptedNodeMap.has(n.id) && !this.getDecryptedRow(n.data));
15940
- if (await this._decryptAndCacheTreeNodes(uncached)) {
15941
- this._sortedNodeIdsCache = null;
16246
+ if (this.encryption?.decryptedCache && this.sortList.length > 0) {
16247
+ const rangeBuckets = this.encryption?.rangeBuckets || this.encryption?.shadowBuckets;
16248
+ if (this.sortList.some((s) => this.isFieldEncrypted(s.field, this.allData) && !rangeBuckets?.[s.field])) {
16249
+ const uncached = this._staticNodes.filter((n) => !this._decryptedNodeMap.has(n.id) && !this.getDecryptedRow(n.data));
16250
+ if (await this._decryptAndCacheTreeNodes(uncached)) {
16251
+ this._sortedNodeIdsCache = null;
16252
+ }
15942
16253
  }
15943
16254
  }
15944
16255
  const needsVerification = Boolean(
@@ -16118,6 +16429,9 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16118
16429
  _abortController;
16119
16430
  _lastDataReceivedPromise = null;
16120
16431
  _lastBatch1CallbackGen = -1;
16432
+ _getApiUrl() {
16433
+ return this.apiUrl || void 0;
16434
+ }
16121
16435
  setData(data) {
16122
16436
  this._bumpRequestGeneration();
16123
16437
  this._isAccumulating = false;
@@ -16211,8 +16525,7 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16211
16525
  }
16212
16526
  /** Deduplicates incoming tree rows by idKey and appends them to the existing tree buffer. */
16213
16527
  _mergeTreeRows(rows) {
16214
- const merged = mergeUniqueTreeRows(this.allData, rows, this.idKey || "id");
16215
- if (merged) this._applyTreeData(merged, true);
16528
+ this._appendUniqueTreeRows(rows);
16216
16529
  }
16217
16530
  setEncryption(encryption) {
16218
16531
  super.setEncryption(encryption);
@@ -16490,7 +16803,7 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16490
16803
  this.notify();
16491
16804
  }
16492
16805
  }
16493
- async loadBatch(batchNumber) {
16806
+ async loadBatch(batchNumber, options) {
16494
16807
  if (typeof this.batchSize !== "number" || this.batchSize <= 0 || this.loadedBatches.has(batchNumber)) return;
16495
16808
  if (this._inFlightBatches.has(batchNumber)) return this._inFlightBatches.get(batchNumber);
16496
16809
  const reqGen = this._requestGeneration;
@@ -16532,8 +16845,10 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16532
16845
  this.loadedBatches.add(batchNumber);
16533
16846
  this._filterDirty = true;
16534
16847
  this._sortDirty = true;
16535
- await super.loadPageData();
16536
- if (isStale()) return;
16848
+ if (!options?.skipPageLoad) {
16849
+ await super.loadPageData();
16850
+ if (isStale()) return;
16851
+ }
16537
16852
  const totalExpected = this._expectedRowCount ?? this.rowCount;
16538
16853
  emitBatchLoaded(this.onBatchLoaded, { pageNumber: batchNumber, rows: rawRows, totalLoaded: this.allData.length, rowCount: totalExpected });
16539
16854
  this.batchProgress = computeBatchProgress(this.allData.length, totalExpected);
@@ -16580,8 +16895,15 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16580
16895
  const total = this._expectedRowCount ?? this.rowCount;
16581
16896
  if (total <= 0) return;
16582
16897
  const totalBatches = Math.ceil(total / this.batchSize);
16898
+ let loadedAny = false;
16583
16899
  for (let b = 1; b <= totalBatches; b++) {
16584
- if (!this.loadedBatches.has(b)) await this.loadBatch(b);
16900
+ if (!this.loadedBatches.has(b)) {
16901
+ await this.loadBatch(b, { skipPageLoad: true });
16902
+ loadedAny = true;
16903
+ }
16904
+ }
16905
+ if (loadedAny && (this._filterDirty || this._sortDirty)) {
16906
+ await super.loadPageData();
16585
16907
  }
16586
16908
  }
16587
16909
  async setFilter(filter, immediate = false) {
@@ -20560,4 +20882,4 @@ function isEncrypted(payload) {
20560
20882
  return AEncryptionProvider.isEncrypted(payload);
20561
20883
  }
20562
20884
 
20563
- export { AAPIDataProvider, ADataProvider, AEncryptedClientProvider, AEncryptionProvider, BLIND_INDEX_FRAMING_VERSION, CAPIFlatClientDataProvider, CAPIFlatServerDataProvider, CAPITreeClientDataProvider, CAPITreeServerDataProvider, CApplicationCache, CBrowserSessionCache, CCookieCache, CECDHEncryptionProvider, CFlatClientDataProvider, CFlatServerDataProvider, CIndexedDBCache, CIndexedDBKeyPinningStore, CKeyManager, CKeyPinningStore, CLocalStorageCache, CLocalStorageKeyPinningStore, CMemoryCache, CMemoryKeyPinningStore, CNodeCryptoEncryptionProvider, CRSAEncryptionProvider, CSearchIndex, CServerSessionCache, CTreeClientDataProvider, CTreeServerDataProvider, CWebCryptoAESCBCProvider, CWebCryptoEncryptionProvider, CWebCryptoStreamCipher, CacheProviderFactory, DECRYPT_ERROR_SENTINEL, DEFAULT_KEY_CACHE_MAX_SIZE, DEFAULT_MAX_ALLOWED_ITERATIONS, DEFAULT_MAX_SALT_DERIVATIONS, DEFAULT_MIN_BUCKET_STEP, DEFAULT_PBKDF2_ITERATIONS, DefaultHydrationAdapter, ECacheStrategy, EDataFilterOperator, ENCRYPTION_CONTEXT_KEYS, EQueueStorage, ERR_AUTH_UNAUTHORIZED, ERR_CRYPTO_AUTH_FAILED, ERR_CRYPTO_DECRYPT_FAILED, ERR_CRYPTO_TAG_MISMATCH, KatluxIndexedDB, PROVIDER_CONSTRUCTOR_OPTION_KEYS, QueueStorageFactory, RANGE_BUCKET_POLICY, RequestProvider, RequestProviderRegistry, RequestQueue, SEARCH_FILTER_NOT_OPERATOR, SENSITIVE_HEADER_KEYS, SENSITIVE_RANGE_BUCKET_FIELDS, _bidxHmacKeyCache, aadToBytes, acquireSaltDerivationSlot, applyOperator, areKeysIdentical, assertMaxAllowedIterations, attachSaltDerivationBudget, buildAadString, buildCanonicalFieldAad, buildEncryptionContext, canonicalizeJson, claimSaltDerivationSlotSync, clearBlindIndexKeyCache, clearCachedCipherProvider, clearSSRData, combineCiphertextAndTag, compareAnd, compareContains, compareEqual, compareIn, compareOr, compareRangeBuckets, compareSteppedBuckets, compareValues, computeBlindIndex, computeBlindIndexSchemeId, computeDateBucket, computeMultiBlindIndex, computeRangeBucket, computeRangeBucketUnchecked, computeSteppedBucket, computeTierBucket, computeWriteBlindIndex, createDecryptionStream, createEncryptionProvider, createEncryptionStream, debounce, decryptBlob, decryptPageRows, decryptPayload, deriveAuthAndEncryptionKeys, deriveBlindIndexHmacKey, deriveKey, deriveKeyFromSecret, encryptBlob, encryptPayload, encryptRows, encryptRowsChunked, escapeAadComponent, evaluateFilter, exportAESKey, exportPrivateKey, exportPrivateKeyToPEM, exportPublicKey, exportPublicKeyToPEM, extractDefaultRowId, extractFilterFieldNames, extractTrigrams, fastKeyHash, fetchWithSSR, filterData, filterTreeData, foldAscii, fromBase64, generateAESKey, generateAccountDataKey, generateECDHKeyPair, generateECDSAKeyPair, generateRSAKeyPair, generateSigningKeyPair, getAppRoute, getAppRouter, getCipherProvider, getDateBucketRange, getGlobalDataProviderConfig, getHydrationAdapter, getKeyFingerprint, getKeyIdentifier, getLruCacheEntry, getPlatformApp, getRandomValues, getRangeBucketRange, getSSRData, getSSRPayload, getSafeKeyIdentifier, getSaltDerivationBudget, getSteppedBucketRange, getSubtleCrypto, getTierBucketRange, importAESKey, importECDSAPrivateKeyFromPEM, importECDSAPublicKeyFromPEM, importPrivateKey, importPrivateKeyFromPEM, importPublicKey, importPublicKeyFromPEM, invertFilterOperator, isAuthOrDecryptionError, isDataEncrypted, isEncrypted, isEncryptedPayload, isFieldBlindIndexStale, isIntervalFullyMatchingOperator, isIntervalMatchingOperator, negateFilterNode, normalizeDecryptError, normalizeFilter, normalizeFilterValue, normalizeIndexTerm, normalizeUrl, onPlatformReady, parseDateValue, parseDecryptedJsonSafely, parseNumericValue, pickEncryptionContext, pickProviderOptions, randomBytes, rangeBucketPolicy, reencryptBatch, reencryptDataset, rekeyEncryptedPayload, rekeyUserKeypair, resolveAndClampPbkdf2Iterations, resolveAuthorityCryptoKey, resolveBucketsForRange, resolveBucketsForRangeUnchecked, resolveCachedSaltDerivation, resolveInfoBytes, resolveSalt, rewrapAccountKeyForUser, rewriteEncryptedFilters, runWithSaltDerivationSlot, safeSetProperty, serializeAadFieldValue, serializePlaintextToBytes, setGlobalDataProviderConfig, setHydrationAdapter, setLruCacheEntry, sign, signGrant, signKeyResetAttestation, sortData, textDecoder, textEncoder, toBase64$1 as toBase64, unwrapAccountKeyForUser, unwrapHMACKeyForUser, unwrapKey, useDebounce, useFilterLogic, useSortLogic, validateBlindIndexKeyring, validateRangeBucketConfig, verify, verifyAndPinKey, verifyAttestation, verifyGrant, wrapAccountKeyForUser, wrapHMACKeyForUser, wrapKey };
20885
+ export { AAPIDataProvider, ADataProvider, AEncryptedClientProvider, AEncryptionProvider, BLIND_INDEX_FRAMING_VERSION, CAPIFlatClientDataProvider, CAPIFlatServerDataProvider, CAPITreeClientDataProvider, CAPITreeServerDataProvider, CApplicationCache, CBrowserSessionCache, CCookieCache, CECDHEncryptionProvider, CFlatClientDataProvider, CFlatServerDataProvider, CIndexedDBCache, CIndexedDBKeyPinningStore, CKeyManager, CKeyPinningStore, CLocalStorageCache, CLocalStorageKeyPinningStore, CMemoryCache, CMemoryKeyPinningStore, CNodeCryptoEncryptionProvider, CRSAEncryptionProvider, CSearchIndex, CServerSessionCache, CTreeClientDataProvider, CTreeServerDataProvider, CWebCryptoAESCBCProvider, CWebCryptoEncryptionProvider, CWebCryptoStreamCipher, CacheProviderFactory, DECRYPT_ERROR_SENTINEL, DEFAULT_KEY_CACHE_MAX_SIZE, DEFAULT_MAX_ALLOWED_ITERATIONS, DEFAULT_MAX_SALT_DERIVATIONS, DEFAULT_MIN_BUCKET_STEP, DEFAULT_PBKDF2_ITERATIONS, DefaultHydrationAdapter, ECacheStrategy, EDataFilterOperator, ENCRYPTION_CONTEXT_KEYS, EQueueStorage, ERR_AUTH_UNAUTHORIZED, ERR_CRYPTO_AUTH_FAILED, ERR_CRYPTO_DECRYPT_FAILED, ERR_CRYPTO_TAG_MISMATCH, KatluxIndexedDB, PROVIDER_CONSTRUCTOR_OPTION_KEYS, QueueStorageFactory, RANGE_BUCKET_POLICY, RequestProvider, RequestProviderRegistry, RequestQueue, SEARCH_FILTER_NOT_OPERATOR, SENSITIVE_HEADER_KEYS, SENSITIVE_RANGE_BUCKET_FIELDS, _bidxHmacKeyCache, aadToBytes, acquireSaltDerivationSlot, applyOperator, areKeysIdentical, assertMaxAllowedIterations, attachSaltDerivationBudget, buildAadString, buildCanonicalFieldAad, buildEncryptionContext, canonicalizeJson, claimSaltDerivationSlotSync, clearBlindIndexKeyCache, clearCachedCipherProvider, clearSSRData, combineCiphertextAndTag, compareAnd, compareContains, compareEqual, compareIn, compareOr, compareRangeBuckets, compareSteppedBuckets, compareValues, compileFilter, computeBlindIndex, computeBlindIndexSchemeId, computeDateBucket, computeMultiBlindIndex, computeRangeBucket, computeRangeBucketUnchecked, computeSteppedBucket, computeTierBucket, computeWriteBlindIndex, createDecryptionStream, createEncryptionProvider, createEncryptionStream, debounce, decryptBlob, decryptPageRows, decryptPayload, deriveAuthAndEncryptionKeys, deriveBlindIndexHmacKey, deriveKey, deriveKeyFromSecret, encryptBlob, encryptPayload, encryptRows, encryptRowsChunked, escapeAadComponent, evaluateFilter, exportAESKey, exportPrivateKey, exportPrivateKeyToPEM, exportPublicKey, exportPublicKeyToPEM, extractDefaultRowId, extractFilterFieldNames, extractTrigrams, fastKeyHash, fetchWithSSR, filterData, filterTreeData, foldAscii, fromBase64, generateAESKey, generateAccountDataKey, generateECDHKeyPair, generateECDSAKeyPair, generateRSAKeyPair, generateSigningKeyPair, getAppRoute, getAppRouter, getCipherProvider, getDateBucketRange, getGlobalDataProviderConfig, getHydrationAdapter, getKeyFingerprint, getKeyIdentifier, getLruCacheEntry, getPlatformApp, getRandomValues, getRangeBucketRange, getSSRData, getSSRPayload, getSafeKeyIdentifier, getSaltDerivationBudget, getSteppedBucketRange, getSubtleCrypto, getTierBucketRange, importAESKey, importECDSAPrivateKeyFromPEM, importECDSAPublicKeyFromPEM, importPrivateKey, importPrivateKeyFromPEM, importPublicKey, importPublicKeyFromPEM, invertFilterOperator, isAuthOrDecryptionError, isDataEncrypted, isEncrypted, isEncryptedPayload, isFieldBlindIndexStale, isIntervalFullyMatchingOperator, isIntervalMatchingOperator, negateFilterNode, normalizeDecryptError, normalizeFilter, normalizeFilterValue, normalizeIndexTerm, normalizeUrl, onPlatformReady, parseDateValue, parseDecryptedJsonSafely, parseNumericValue, pickEncryptionContext, pickProviderOptions, randomBytes, rangeBucketPolicy, reencryptBatch, reencryptDataset, rekeyEncryptedPayload, rekeyUserKeypair, resolveAndClampPbkdf2Iterations, resolveAuthorityCryptoKey, resolveBucketsForRange, resolveBucketsForRangeUnchecked, resolveCachedSaltDerivation, resolveInfoBytes, resolveSalt, rewrapAccountKeyForUser, rewriteEncryptedFilters, runWithSaltDerivationSlot, safeSetProperty, serializeAadFieldValue, serializePlaintextToBytes, setGlobalDataProviderConfig, setHydrationAdapter, setLruCacheEntry, sign, signGrant, signKeyResetAttestation, sortData, textDecoder, textEncoder, toBase64$1 as toBase64, unwrapAccountKeyForUser, unwrapHMACKeyForUser, unwrapKey, useDebounce, useFilterLogic, useSortLogic, validateBlindIndexKeyring, validateRangeBucketConfig, verify, verifyAndPinKey, verifyAttestation, verifyGrant, wrapAccountKeyForUser, wrapHMACKeyForUser, wrapKey };