@dcupl/common 2.0.0-beta.6 → 2.0.0-beta.8
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/esm/index.d.ts +1 -0
- package/dist/esm/index.js +566 -540
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/resource-id.d.ts +43 -0
- package/dist/esm/types/app-loader.types.d.ts +73 -0
- package/dist/esm/types/model.types.d.ts +24 -1
- package/dist/node/index.cjs +2 -2
- package/dist/node/index.cjs.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** Authored `resource.key` values are namespaced so they can never collide with a derived hash. */
|
|
2
|
+
export declare const AUTHORED_RESOURCE_ID_PREFIX = "k:";
|
|
3
|
+
export declare const DERIVED_RESOURCE_ID_PREFIX = "h:";
|
|
4
|
+
/**
|
|
5
|
+
* The fields a resource identity is derived from.
|
|
6
|
+
*
|
|
7
|
+
* Structural rather than `AppLoaderConfiguration.Resource` so the same function serves a raw config
|
|
8
|
+
* entry and a runtime progress item — `model` only exists on data resources, `rawUrl` only at runtime.
|
|
9
|
+
*/
|
|
10
|
+
export type ResourceIdentityInput = {
|
|
11
|
+
key?: string;
|
|
12
|
+
type: string;
|
|
13
|
+
url: string;
|
|
14
|
+
rawUrl?: string;
|
|
15
|
+
model?: string;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* A stable id for one resource.
|
|
19
|
+
*
|
|
20
|
+
* An authored `key` wins and is used verbatim — that id survives a url edit, which is the reason to
|
|
21
|
+
* author keys at all. Otherwise the id is a hash of the RAW url plus type/model. Deriving from the
|
|
22
|
+
* raw url (never the resolved one) is what makes the id identical on both sides of the config↔runtime
|
|
23
|
+
* boundary, since `${variable}` substitution happens only on the runtime side.
|
|
24
|
+
*
|
|
25
|
+
* A derived id therefore changes when the url, type or model changes. That is the accepted limit:
|
|
26
|
+
* it is stable across runs, not across edits.
|
|
27
|
+
*
|
|
28
|
+
* `occurrence` disambiguates config entries that are identical in type/url/model. Prefer
|
|
29
|
+
* `resolveResourceIds` for a list — it assigns occurrences in document order, so reordering the
|
|
30
|
+
* config does not churn ids.
|
|
31
|
+
*/
|
|
32
|
+
export declare function resolveResourceId(resource: ResourceIdentityInput, occurrence?: number): string;
|
|
33
|
+
/**
|
|
34
|
+
* Ids for a resource list, positionally aligned with the input, guaranteed unique.
|
|
35
|
+
*
|
|
36
|
+
* Uniqueness is enforced on the OUTPUT, not just on the (type, url, model) basis, because two other
|
|
37
|
+
* things can collide: two entries authored with the same `key` (nothing in the config validates key
|
|
38
|
+
* uniqueness — `loader.resources.get()` simply returns the first match), and a hash collision, which
|
|
39
|
+
* `generateObjectHash` admits by construction since it is a 32-bit rolling hash. Random collisions
|
|
40
|
+
* are vanishingly rare at realistic config sizes, but a duplicate id silently merges two nodes in a
|
|
41
|
+
* consumer's graph, so it is worth ruling out rather than reasoning about.
|
|
42
|
+
*/
|
|
43
|
+
export declare function resolveResourceIds(resources: readonly ResourceIdentityInput[]): string[];
|
|
@@ -208,6 +208,45 @@ export declare namespace AppLoaderConfiguration {
|
|
|
208
208
|
key: string;
|
|
209
209
|
value: string;
|
|
210
210
|
};
|
|
211
|
+
/** Why a declared resource was not scheduled for a run. */
|
|
212
|
+
export type SkipReason =
|
|
213
|
+
/** The run filters by resourceTags, and the resource carries no tags at all. */
|
|
214
|
+
'no-tags'
|
|
215
|
+
/** The run filters by resourceTags, and none of them matched the resource's tags. */
|
|
216
|
+
| 'tag-mismatch';
|
|
217
|
+
export type SkippedResource = {
|
|
218
|
+
resource: Resource;
|
|
219
|
+
reason: SkipReason;
|
|
220
|
+
/**
|
|
221
|
+
* The same identity a scheduled item would carry — see `AppLoaderProgress.ResourceItem.id`.
|
|
222
|
+
*
|
|
223
|
+
* Assigned here rather than left to the consumer because ids are allotted over the FULL declared
|
|
224
|
+
* list: recomputing one in isolation cannot know its occurrence index, so duplicate entries would
|
|
225
|
+
* come out with a different id than the SDK gave them.
|
|
226
|
+
*/
|
|
227
|
+
id?: string;
|
|
228
|
+
};
|
|
229
|
+
/**
|
|
230
|
+
* The outcome of resolving a configuration against process options, WITHOUT fetching anything.
|
|
231
|
+
*
|
|
232
|
+
* `scheduled` is what a `process()` call would actually load (tag-filtered, urls resolved);
|
|
233
|
+
* `skipped` is every declared resource that dropped out, with the reason. Together they cover
|
|
234
|
+
* `config.resources` exactly, which is what lets a consumer show "declared but not in this app"
|
|
235
|
+
* without re-implementing the filter.
|
|
236
|
+
*/
|
|
237
|
+
export type ResourcePlan = {
|
|
238
|
+
scheduled: AppLoaderProgress.ResourceItem[];
|
|
239
|
+
skipped: SkippedResource[];
|
|
240
|
+
/** The variables the scheduled urls were resolved with. */
|
|
241
|
+
variables: EnvironmentVariableAsObject;
|
|
242
|
+
/** The process options the plan was built for. */
|
|
243
|
+
run: RunContext;
|
|
244
|
+
};
|
|
245
|
+
export type RunContext = {
|
|
246
|
+
applicationKey?: string;
|
|
247
|
+
resourceTags?: StringOrStringArray;
|
|
248
|
+
environmentKeys?: string[];
|
|
249
|
+
};
|
|
211
250
|
export {};
|
|
212
251
|
}
|
|
213
252
|
export type FilesApiStatusResponse = {
|
|
@@ -222,6 +261,30 @@ export declare namespace AppLoaderProgress {
|
|
|
222
261
|
type ResourceItem = AppLoaderConfiguration.Resource & {
|
|
223
262
|
success?: boolean;
|
|
224
263
|
status?: number;
|
|
264
|
+
/**
|
|
265
|
+
* Stable identity for this resource, derived once at plan time.
|
|
266
|
+
*
|
|
267
|
+
* Authored `resource.key` wins (`k:<key>`); otherwise a deterministic hash of the resource's
|
|
268
|
+
* RAW url plus type/model (`h:<hash>`). Because it is derived from the raw url it is the same
|
|
269
|
+
* value a consumer computes from the config file, which is what makes declared↔runtime joins
|
|
270
|
+
* possible without url matching. See `resolveResourceId`.
|
|
271
|
+
*/
|
|
272
|
+
id?: string;
|
|
273
|
+
/**
|
|
274
|
+
* The url as authored in the config, BEFORE `${variable}` substitution.
|
|
275
|
+
*
|
|
276
|
+
* `url` is overwritten with the resolved value at plan time; without this the template — and
|
|
277
|
+
* therefore the link back to the config entry — would be unrecoverable at runtime.
|
|
278
|
+
*/
|
|
279
|
+
rawUrl?: string;
|
|
280
|
+
/**
|
|
281
|
+
* Variables referenced by `rawUrl` that had no value at resolve time.
|
|
282
|
+
*
|
|
283
|
+
* `evaluateTemplate` substitutes an unknown variable with an empty string, so an unset
|
|
284
|
+
* `${baseUrl}` silently yields a mangled url and a download failure that looks like a missing
|
|
285
|
+
* file. A non-empty array here is the difference between "file is gone" and "config is wrong".
|
|
286
|
+
*/
|
|
287
|
+
unresolvedVariables?: string[];
|
|
225
288
|
};
|
|
226
289
|
type ProgressItem = {
|
|
227
290
|
total: number;
|
|
@@ -230,11 +293,21 @@ export declare namespace AppLoaderProgress {
|
|
|
230
293
|
progress: number;
|
|
231
294
|
context: string;
|
|
232
295
|
currentItem: ResourceItem;
|
|
296
|
+
/** The resources SCHEDULED for this run — already tag-filtered and url-resolved. */
|
|
233
297
|
totalItems: ResourceItem[];
|
|
234
298
|
processedItems: ResourceItem[];
|
|
235
299
|
downloadedItems: ResourceItem[];
|
|
236
300
|
failedItems: ResourceItem[];
|
|
237
301
|
remainingItems: ResourceItem[];
|
|
302
|
+
/**
|
|
303
|
+
* Declared resources that this run never scheduled, with the reason.
|
|
304
|
+
*
|
|
305
|
+
* `totalItems` covers only what the run's resourceTags selected, so on its own it cannot
|
|
306
|
+
* distinguish "loaded everything" from "loaded everything it was allowed to see".
|
|
307
|
+
*/
|
|
308
|
+
skippedItems?: AppLoaderConfiguration.SkippedResource[];
|
|
309
|
+
/** The application/tags/environments this run resolved against. */
|
|
310
|
+
run?: AppLoaderConfiguration.RunContext;
|
|
238
311
|
};
|
|
239
312
|
type CallbackFunction = (item: ProgressItem) => void;
|
|
240
313
|
}
|
|
@@ -326,8 +326,19 @@ export type ValueMappingConfig = {
|
|
|
326
326
|
};
|
|
327
327
|
export type ModelAttribute = Property | Reference;
|
|
328
328
|
export type ModelQualityConfig = {
|
|
329
|
+
/**
|
|
330
|
+
* Master switch for quality checks on this model. Default: true.
|
|
331
|
+
* Checks only run when error tracking is also enabled globally
|
|
332
|
+
* (two-tier enablement).
|
|
333
|
+
*/
|
|
329
334
|
enabled?: boolean;
|
|
330
|
-
|
|
335
|
+
/**
|
|
336
|
+
* Model-wide defaults for the attribute quality FLAGS
|
|
337
|
+
* (required / nullable / forceStrictDataType / validatorHandling),
|
|
338
|
+
* merged under each attribute's own `quality`.
|
|
339
|
+
* Concrete `validators` are per-attribute only and cannot be set here.
|
|
340
|
+
*/
|
|
341
|
+
attributes?: Omit<AttributeQualityConfig, 'validators'>;
|
|
331
342
|
};
|
|
332
343
|
export type ValidatorErrorType = 'loose' | 'strict';
|
|
333
344
|
export type ValidatorConfig = {
|
|
@@ -351,6 +362,18 @@ export type AttributeValidatorConfig = {
|
|
|
351
362
|
unique?: ValidatorConfig;
|
|
352
363
|
startsWith?: ValidatorConfig;
|
|
353
364
|
};
|
|
365
|
+
/**
|
|
366
|
+
* Quality rules for a single property or reference.
|
|
367
|
+
*
|
|
368
|
+
* Defaults: required: true, nullable: false, forceStrictDataType: false,
|
|
369
|
+
* validatorHandling: 'loose'.
|
|
370
|
+
*
|
|
371
|
+
* validatorHandling decides what happens when a validator fails:
|
|
372
|
+
* 'loose' (default) reports an InvalidValidator error and keeps the value;
|
|
373
|
+
* 'strict' reports AND drops the value from the loaded data.
|
|
374
|
+
* forceStrictDataType: true disables type coercion — wrong-typed raw
|
|
375
|
+
* values are reported as WrongDataType and dropped.
|
|
376
|
+
*/
|
|
354
377
|
export type AttributeQualityConfig = {
|
|
355
378
|
required?: boolean;
|
|
356
379
|
nullable?: boolean;
|
package/dist/node/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("lodash-es");function N(n){const e=Q(n);return te(e)}function Q(n){if(typeof n!="object"||n===null)return String(n);if(Array.isArray(n))return"["+n.map(Q).join(",")+"]";const e=Object.keys(n).sort();let t="{";for(let r=0;r<e.length;r++){const s=e[r];t+=s+":"+Q(n[s]),r<e.length-1&&(t+=",")}return t+="}",t}function te(n){let e=0;for(let t=0;t<n.length;t++){const r=n.charCodeAt(t);e=(e<<5)-e+r,e|=0}return e.toString(16)}const A={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:n=>{typeof performance<"u"&&performance.mark&&performance.mark(n)},measure:(n,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(n,e,t)},getEntriesByName(n){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(n)},getEntriesByType(n){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(n)}};class re{data;enabled=!1;constructor(){}init(e){this.data=new Map,this.enabled=e}set(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context);return this.data.set(t,e.value),this.data.get(t)}mark(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),r={name:e.name,type:"mark",value:A.now(),createdAt:Date.now()};return this.data.set(t,r),r}measure(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),r=this.data.get(this.getKey(e.start,e.context)),s=this.data.get(this.getKey(e.end,e.context));if(!r||!s)return;const o=s.value-r.value,i=Math.round(o*100)/100,a=this.data.get(t);if(a&&e.sum){const c=a.value+i,f={...a,value:c};return this.data.set(t,f),f}const u={name:e.name,type:"measure",value:i,createdAt:Date.now()};return e.detail&&(u.detail=e.detail),this.data.set(t,u),u}update(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context),r=this.data.get(t);if(r){const s={...r,...e.value};this.data.set(t,s)}else this.data.set(t,e.value);return this.data.get(t)}getResourceInfosFromPerformanceAPI(){return typeof performance>"u"?[]:A.getEntriesByType("resource")}get(e){const t=this.getKey(e.name,e.context);return this.data.get(t)}getByType(e){return Array.from(this.data.values()).filter(t=>t.type===e)}getByName(e){return Array.from(this.data.values()).filter(t=>t.name===e)}clear(){this.data.clear()}getKey(e,t){if(!t)return e;const r=N(t);return e+"_"+r}}let F=class G{nodes;edges;nodeKinds=new Map;nodeMeta=new Map;edgePolicy;constructor(){this.nodes=new Set,this.edges=new Map}addNode(e,t){this.nodes.has(e)||(this.nodes.add(e),this.edges.set(e,new Set)),t?.kind!==void 0&&this.nodeKinds.set(e,t.kind),t?.meta!==void 0&&this.nodeMeta.set(e,t.meta)}addDependency(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))throw new Error("Both nodes must exist before adding a dependency.");if(this.edgePolicy&&!this.edgePolicy({name:e,kind:this.nodeKinds.get(e)},{name:t,kind:this.nodeKinds.get(t)}))throw new Error(`Edge policy rejected dependency from "${e}" to "${t}".`);this.edges.get(e).add(t)}setEdgePolicy(e){this.edgePolicy=e}setNodeKind(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");t===void 0?this.nodeKinds.delete(e):this.nodeKinds.set(e,t)}getNodeKind(e){return this.nodeKinds.get(e)}setNodeMeta(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodeMeta.set(e,t)}getNodeMeta(e){return this.nodeMeta.get(e)}removeNode(e){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodes.delete(e),this.edges.delete(e);for(let t of this.edges.values())t.delete(e)}removeDependency(e,t){if(!this.edges.has(e))throw new Error("From node does not exist.");this.edges.get(e).delete(t)}hasNode(e){return this.nodes.has(e)}hasDependency(e,t){return this.edges.has(e)?this.edges.get(e).has(t):!1}getDependencies(e){if(!this.edges.has(e))throw new Error("Node does not exist.");return Array.from(this.edges.get(e))}getDependents(e){const t=[];for(let[r,s]of this.edges)s.has(e)&&t.push(r);return t}isCyclic(){const e=new Set,t=new Set,r=s=>{if(e.has(s))return!1;if(t.has(s))return!0;t.add(s);const o=this.edges.get(s);if(o){for(let i of o)if(r(i))return!0}return t.delete(s),e.add(s),!1};for(let s of this.nodes)if(r(s))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,r=[],s=o=>{if(e.has(o))return null;if(t.has(o)){const a=r.indexOf(o);return r.slice(a).concat([o])}t.add(o),r.push(o);const i=this.edges.get(o);if(i)for(let a of i){const u=s(a);if(u)return u}return r.pop(),t.delete(o),e.add(o),null};for(let o of this.nodes){const i=s(o);if(i)return{hasCycle:!0,path:i}}return{hasCycle:!1}}order(e){const t=new Set,r=new Set,s=[],o=e?.allowCycles??!1,i=a=>{if(t.has(a))return;if(r.has(a)){if(o)return;throw new Error("Graph has a cycle.")}r.add(a);const u=this.edges.get(a);if(u)for(let c of u)i(c);r.delete(a),t.add(a),s.push(a)};for(let a of this.nodes)t.has(a)||i(a);return s}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,r]of this.edges)for(let s of r)e.push([t,s]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const r of this.edges.values())for(const s of r)e.add(s);const t=[];for(const r of this.nodes)e.has(r)||t.push(r);return t}getNodesByKind(e){const t=[];for(const r of this.nodes)this.nodeKinds.get(r)===e&&t.push(r);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),r=Array.from(t);return e?r.filter(s=>this.nodeKinds.get(s)===e):r}getLeavesByKind(e){const t=[];for(const r of this.nodes){const s=this.edges.get(r);(!s||s.size===0)&&(!e||this.nodeKinds.get(r)===e)&&t.push(r)}return t}getDependenciesOfKind(e,t){return this.getDependencies(e).filter(s=>this.nodeKinds.get(s)===t)}getDependentsOfKind(e,t){return this.getDependents(e).filter(s=>this.nodeKinds.get(s)===t)}plan(e){const t=new Map;for(const i of this.nodes)t.set(i,0);for(const i of this.edges.values())for(const a of i)t.set(a,(t.get(a)||0)+1);const r=[];let s=Array.from(this.nodes).filter(i=>(t.get(i)||0)===0);const o=new Set;for(;s.length>0;){const i=s.slice();r.push(i),s=[];for(const a of i){if(o.has(a))continue;o.add(a);const u=this.edges.get(a);if(u)for(const c of u)t.set(c,(t.get(c)||0)-1),(t.get(c)||0)===0&&s.push(c)}}if(o.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const i=new Set(e.filterKinds);return{batches:r.map(a=>a.filter(u=>i.has(this.nodeKinds.get(u))))}}return{batches:r}}getImpactedNodes(e,t="downstream",r){const s=new Set(e),o=c=>!r||r.length===0||r.includes(this.nodeKinds.get(c)??void 0),i=()=>{const c=new Set,f=Array.from(s);for(;f.length;){const l=f.shift();for(const[d,h]of this.edges)h.has(l)&&!c.has(d)&&(c.add(d),f.push(d))}return c},a=()=>{const c=new Set,f=Array.from(s);for(;f.length;){const l=f.shift(),d=this.edges.get(l);if(d)for(const h of d)c.has(h)||(c.add(h),f.push(h))}return c};let u;return t==="both"?u=new Set([...i(),...a()]):t==="upstream"?u=a():u=i(),Array.from(u).filter(o)}toJSON(){const e=Array.from(this.nodes).map(r=>({name:r,kind:this.nodeKinds.get(r),meta:this.nodeMeta.get(r)})),t=this.getAllEdges().map(([r,s])=>({from:r,to:s}));return{nodes:e,edges:t}}static fromJSON(e){const t=new G;for(const r of e.nodes)t.addNode(r.name,{kind:r.kind,meta:r.meta});for(const r of e.edges)t.addDependency(r.from,r.to);return t}diff(e){const t=new Set(this.getNodes()),r=new Set(e.getNodes()),s=Array.from(r).filter(l=>!t.has(l)),o=Array.from(t).filter(l=>!r.has(l)),i=new Set(this.getAllEdges().map(l=>l.join("→"))),a=new Set(e.getAllEdges().map(l=>l.join("→"))),u=Array.from(a).filter(l=>!i.has(l)).map(l=>l.split("→")),c=Array.from(i).filter(l=>!a.has(l)).map(l=>l.split("→")),f=[];for(const l of new Set([...t,...r])){const d=this.nodeKinds.get(l),h=e.nodeKinds.get(l);d!==h&&f.push({name:l,from:d,to:h})}return{addedNodes:s,removedNodes:o,addedEdges:u,removedEdges:c,kindChanges:f}}};class se{graph;nodeIndex;constructor(){this.graph=new F,this.nodeIndex=new Map}getNodeId(e,t){return`${e}.${t}`}parseNodeId(e){const t=e.split(".");return{modelKey:t[0],attributeKey:t.slice(1).join(".")}}addAttribute(e){const t=this.getNodeId(e.modelKey,e.attributeKey);this.nodeIndex.has(t)||(this.graph.addNode(t,{meta:e}),this.nodeIndex.set(t,e))}addAttributeDependency(e,t){this.addAttribute(e),this.addAttribute(t);const r=this.getNodeId(e.modelKey,e.attributeKey),s=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(r,s)||this.graph.addDependency(r,s)}getImpactedAttributes(e){const t=e.map(a=>this.getNodeId(a.modelKey,a.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(a=>this.nodeIndex.get(a)).filter(a=>a!==void 0),o=[...e,...s],i=new Set;return o.filter(a=>{const u=this.getNodeId(a.modelKey,a.attributeKey);return i.has(u)?!1:(i.add(u),!0)})}getProcessingOrder(e){const t=new Map,r=[...e].sort((s,o)=>s.processingStep-o.processingStep);for(const s of r){const{modelKey:o,attributeKey:i,processingStep:a}=s;t.has(o)||t.set(o,new Map);const u=t.get(o);u.has(a)||u.set(a,new Set),u.get(a).add(i)}return t}getAttributesForModel(e){const t=[];for(const r of this.nodeIndex.values())r.modelKey===e&&t.push(r);return t}getDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}getDependents(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependents(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}hasDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).length>0:!1}hasNode(e){return this.nodeIndex.has(e)}getAllAttributes(){return Array.from(this.nodeIndex.values())}getMaxDepth(){let e=0;const t=(r,s=new Set)=>{if(s.has(r))return 0;s.add(r);const o=this.graph.getDependencies(r);if(o.length===0)return 1;let i=0;for(const a of o){const u=t(a,new Set(s));i=Math.max(i,u)}return i+1};for(const r of this.graph.getNodes()){const s=t(r);e=Math.max(e,s)}return e}validateCompleteness(e){const t=[];for(const[r,s]of e)for(const o of s){const i=this.getNodeId(r,o);this.hasNode(i)||t.push({modelKey:r,attributeKey:o})}return{isComplete:t.length===0,missing:t}}clear(){this.graph.clear(),this.nodeIndex.clear()}getStats(){const e=new Map,t=new Map;for(const r of this.nodeIndex.values())e.set(r.modelKey,(e.get(r.modelKey)||0)+1),t.set(r.processingStep,(t.get(r.processingStep)||0)+1);return{totalAttributes:this.nodeIndex.size,totalDependencies:this.graph.getAllEdges().length,maxDepth:this.getMaxDepth(),attributesByModel:e,attributesByStep:t}}toJSON(){return{nodes:Array.from(this.nodeIndex.values()),edges:this.graph.getAllEdges().map(([e,t])=>{const r=this.parseNodeId(e),s=this.parseNodeId(t);return{from:r,to:s}})}}}const q={silent:0,error:1,warn:2,info:3,debug:4};class g{config;static globalConfig={};constructor(e={}){this.config={level:e.level??g.globalConfig.level??this.getDefaultLevel(),format:e.format??g.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??g.globalConfig.onLog,onTrackError:e.onTrackError??g.globalConfig.onTrackError}}static setGlobalConfig(e){g.globalConfig={...g.globalConfig,...e}}static getGlobalConfig(){return{...g.globalConfig}}static setModuleLevel(e,t){g.globalConfig.onLog||(g.globalConfig.onLog=void 0),g._moduleOverrides||(g._moduleOverrides=new Map),g._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!g._moduleOverrides))return g._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=g.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return q[e]<=q[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),r=e.prefix?`[${e.prefix}]`:"",s=this.getLevelIcon(e.level),o=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${s} ${r} ${e.message}${o}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,r,s){if(!this.shouldLog(e))return;const o={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:r,error:s};if(this.config.onLog){this.config.onLog(o);return}const i=this.formatMessage(o);if(typeof console<"u")switch(e){case"error":s?console.error(i,s):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,r){const s=t instanceof Error?t:void 0,o=t instanceof Error?r:t;this.log("error",e,o,s)}trackError(e,t,r){if(this.error(e,t,r?.context),this.config.onTrackError){const s={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:r?.context,error:t,errorType:r?.errorType,errorGroup:r?.errorGroup};this.config.onTrackError(s)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new g(t)}configure(e){Object.assign(this.config,e)}}const B=new g;class ne{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}cache;cacheDependencies;hitCount=0;missCount=0;log=B.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const r=this.getCacheName(e,t);return this.cache.has(r)?this.hitCount++:this.missCount++,this.cache.get(r)}set(e,t,r,s){if(!this.enabled)return;const o=this.getCacheName(e,t);this.cache.set(o,r),s?this.cacheDependencies.set(o,s):this.log.debug(`Cache entry '${e}' stored without dependencies. This prevents granular invalidation and may cause stale data.`)}has(e,t){return this.cache.has(this.getCacheName(e,t))}clear(){this.cache.clear(),this.cacheDependencies.clear(),this.hitCount=0,this.missCount=0}invalidateByDependencies(e){if(!this.enabled)return;const t=[];for(const[r,s]of this.cacheDependencies){let o=!1;for(const[i,a]of e){if(s.models.has(i))if(s.modelAttributes.has(i)){const u=s.modelAttributes.get(i);for(const c of a)if(u.has(c)){o=!0;break}}else o=!0;if(o)break}o&&t.push(r)}for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),r=[];for(const[s,o]of this.cacheDependencies)for(const i of t)if(o.models.has(i)){r.push(s);break}for(const s of r)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const r of this.cache.keys())r.startsWith(e+"_")&&t.push(r);for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const r=new Map;r.set(e,new Set([t])),this.invalidateByDependencies(r)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const r of this.cache.keys())e(r)&&t.push(r);for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}generateContext(e){try{return p.cloneDeep(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const r=N(t);return e+"_"+r}getStats(){const e=this.hitCount+this.missCount,t=e>0?this.hitCount/e:0;return{size:this.cache.size,hitRate:t,totalEntries:this.cache.size,entriesWithDependencies:this.cacheDependencies.size,hits:this.hitCount,misses:this.missCount}}}const ie=(n,e="")=>`${n}#${e}`,oe=n=>`${n.gt}_${n.gte}_${n.lt}_${n.lte}_${n.eq}_${n.ne}`,ae=n=>`${n.gt}_${n.gte}_${n.lt}_${n.lte}_${n.eq}_${n.ne}`,ue=(n,e)=>{const t=typeof e=="function"?e:r=>r[e];return[...n.reduce((r,s)=>{const o=s==null?s:t(s);return r.has(o)||r.set(o,s),r},new Map).values()]},ce=(n,e)=>n.reduce(function(t,r){const s=typeof e=="function"?e(r):r[e];return Object.prototype.hasOwnProperty.call(t,s)||(t[s]=[]),t[s].push(r),t},{});function z(n=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let r=0;r<n;r++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}const fe=n=>n.replace(/\/+$/,""),P=n=>typeof n!="string"?"":n.replace(/[[\]{}()*+?.,\\^$|#]/g,"\\$&"),le=n=>typeof n!="string"?"":n.replace(/\\([[\]{}()*+?.,\\^$|#])/g,"$1"),de=(n,e)=>{try{return R(n,e)>=0}catch{return!1}},R=(n,e)=>{if(!K(n)||!K(e))throw new Error(`Invalid version format: v1="${n}", v2="${e}". Expected format: "x.y.z"`);const t=n.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<3;s++){const o=t[s]||0,i=r[s]||0;if(o>i)return 1;if(o<i)return-1}return 0},K=n=>/^\d+(\.\d+){0,2}$/.test(n);class he{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=A.now(),e.duration=e.start-e.end),this.updateListener.forEach(t=>{t(e)})}on(e){return this.updateListener.add(e),()=>{this.updateListener.delete(e)}}}const k=(n,e)=>e?typeof structuredClone<"u"?structuredClone(n):p.cloneDeep(n):n,O=(n,e,t,r,s,o)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=k(o,i);if(t.scope==="list"&&(t.listKey=n.cdRef?.key||n.key,t.modelKey=n.model?.key||n.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const u=A.now(),c=u-r,f=Math.round(c*1e3)/1e3;t.duration=f,t.start=r,t.end=u;const l={duration:t.duration};return t.modelKey&&(l.model=t.modelKey),t.connectMessageResult&&(t.result=a),t.args&&(l.args=t.args),e?.trigger(t),e.analyticsController.mark({name:`${t.type}:end`,context:s}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:s,detail:l}),a}catch{return o}},pe=n=>(t,r,s)=>{const o=s.value;return s.value=function(...i){const a=A.now(),u=this.cdRef,c=k(n,!0);c.key||(u.increaseCounter(),c.key=u.getCounter());const f=z();u.analyticsController.mark({name:`${c.type}:start`,context:f});const l=this.model?.key;!c.originCdRefKey&&u.key&&(c.originCdRefKey=u.key),l&&(c.modelKey=l);const d=o.apply(this,i);return c.method=r,c.args=i,d&&typeof d=="object"&&"then"in d?d.then(h=>O(this,u,c,a,f,h)):O(this,u,c,a,f,d)},s};function ge(n,e,t,r){t.max||(t.max=20);const s=[],o=t.transform?r.transformValue(t.value,t.transform):t.value;for(const[i,a]of e.entries()){const u=Array.from(a).some(f=>n.has(f)),c=t.transform?r.transformValue(i,t.transform):i;if(!(t.excludeUndefineds&&typeof i>"u")&&!(t.excludeNulls&&i===null)){if(u&&(o===""||o==="//")){const f={value:i,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}else if(u&&typeof o=="string"&&o.startsWith("/")&&o.endsWith("/")){if(r.queryFind(c,o,"some")){const f={value:i,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}}else if(u&&typeof o=="string"){const f=String(c??""),l=o;if(f.toLowerCase().startsWith(l.toLowerCase())){const d={value:i,keys:t.calculateResultKeys?Array.from(a):[]};s.push(d)}}else if(u&&r.queryFind(c,o,"some")){const f={value:i,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}if(s.length===t.max)break}}return s}function j(n){return n instanceof Date}function _(n){return n instanceof Date&&!isNaN(n.getTime())}const ye={yyyy:{type:"year",pattern:"yyyy",regex:"(\\d{4})"},yy:{type:"year",pattern:"yy",regex:"(\\d{2})"},MM:{type:"month",pattern:"MM",regex:"(\\d{2})"},M:{type:"month",pattern:"M",regex:"(\\d{1,2})"},dd:{type:"day",pattern:"dd",regex:"(\\d{2})"},d:{type:"day",pattern:"d",regex:"(\\d{1,2})"},HH:{type:"hour",pattern:"HH",regex:"(\\d{2})"},H:{type:"hour",pattern:"H",regex:"(\\d{1,2})"},mm:{type:"minute",pattern:"mm",regex:"(\\d{2})"},m:{type:"minute",pattern:"m",regex:"(\\d{1,2})"},ss:{type:"second",pattern:"ss",regex:"(\\d{2})"},s:{type:"second",pattern:"s",regex:"(\\d{1,2})"},SSS:{type:"millisecond",pattern:"SSS",regex:"(\\d{3})"}};function me(n){let e="^";const t=[];let r=n;const s=Object.entries(ye).sort((o,i)=>i[0].length-o[0].length);for(;r.length>0;){let o=!1;for(const[i,a]of s)if(r.startsWith(i)){e+=a.regex,t.push({type:a.type,pattern:i}),r=r.slice(i.length),o=!0;break}if(!o){const i=r[0];if(!i)break;e+=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=r.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function ve(n,e){const t={year:1970,month:1,day:1,hour:0,minute:0,second:0,millisecond:0};for(let r=0;r<e.length;r++){const s=n[r+1];if(!s)continue;const o=parseInt(s,10),i=e[r];i&&(i.type==="year"&&i.pattern==="yy"?t.year=2e3+o:t[i.type]=o)}return t}function we(n){if(n.month<1||n.month>12)return new Date(NaN);if(n.day<1||n.day>31)return new Date(NaN);if(n.hour<0||n.hour>23)return new Date(NaN);if(n.minute<0||n.minute>59)return new Date(NaN);if(n.second<0||n.second>59)return new Date(NaN);if(n.millisecond<0||n.millisecond>999)return new Date(NaN);const e=new Date(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return _(e)?e.getFullYear()!==n.year||e.getMonth()!==n.month-1||e.getDate()!==n.day?new Date(NaN):e:new Date(NaN)}function xe(n,e,t){if(n=n.trim(),e==="t"){const a=Number(n);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(n);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:r,tokenOrder:s}=me(e),o=n.match(r);if(!o)return new Date(NaN);const i=ve(o,s);return we(i)}class Ae{cache;maxSize;accessOrder;constructor(e){this.cache=new Map,this.maxSize=e,this.accessOrder=[]}get(e){const t=this.cache.get(e);return t!==void 0&&this.updateAccessOrder(e),t}set(e,t){if(this.cache.has(e))this.cache.set(e,t),this.updateAccessOrder(e);else{if(this.cache.size>=this.maxSize){const r=this.accessOrder.shift();r!==void 0&&this.cache.delete(r)}this.cache.set(e,t),this.accessOrder.push(e)}}has(e){return this.cache.has(e)}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}getStats(){return{size:this.cache.size,maxSize:this.maxSize}}}class be{graph;constructor(){this.graph=new Map}addDependency(e,t){this.graph.has(e)||this.graph.set(e,new Set),this.graph.get(e).add(t)}hasCycle(e){if(e.length===0)return!1;const t=new Set,r=new Set,s=o=>{t.add(o),r.add(o);const i=this.graph.get(o);if(i){for(const a of i)if(t.has(a)){if(r.has(a))return!0}else if(s(a))return!0}return r.delete(o),!1};for(let o=0;o<e.length-1;o++){const i=e[o],a=e[o+1];i&&a&&this.addDependency(i,a)}for(const o of e)if(!t.has(o)&&s(o))return!0;return!1}clear(){this.graph.clear()}}class W{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new Ae(e),this.circularRefDetector=new be}parse(e){if(this.parseCache.has(e))return this.cacheHits++,this.parseCache.get(e);this.cacheMisses++;let t,r;const s=e.includes("."),o=e.includes("["),i=s||o;if(i)if(r=e.split(/[.[]/)[0],o){const u=e.indexOf("]");if(u>-1){const c=e.indexOf(".",u+1);c>-1?t=e.substring(c+1):t=void 0}else s&&(t=e.substring(e.indexOf(".")+1))}else s&&(t=e.substring(e.indexOf(".")+1));const a={attribute:e,isDeepQuery:i};return r&&(a.reference=r),typeof t<"u"&&t!==""&&(a.referenceAttribute=t),this.parseCache.set(e,a),a}detectCircular(e){return e.length===0?!1:new Set(e).size!==e.length?!0:this.circularRefDetector.hasCycle(e)}validatePath(e,t=10){const r=[];if(!e||e.trim().length===0)return r.push("Attribute path cannot be empty"),{valid:!1,errors:r};(e.startsWith(".")||e.endsWith("."))&&r.push(`Invalid path: Leading or trailing dots are not allowed: ${e}`),e.includes("..")&&r.push(`Invalid path: Consecutive dots are not allowed: ${e}`);const s=(e.match(/\[/g)||[]).length,o=(e.match(/]/g)||[]).length;s!==o&&r.push(`Invalid bracket notation: Mismatched brackets in ${e}`),e.includes("[]")&&r.push(`Invalid bracket notation: Empty brackets not allowed: ${e}`);const i=/\[([^\]]+)\]/g;let a;for(;(a=i.exec(e))!==null;){const f=a[1];f&&f!=="*"&&!/^\d+$/.test(f)&&r.push(`Invalid bracket content: Must be a number or '*', got '${f}' in ${e}`)}const u=(e.match(/\./g)||[]).length+1;u>t&&r.push(`Path too deep: Maximum depth is ${t}, got ${u} in ${e}`);const c=e.match(/[^a-zA-Z0-9._[\]*-]/g);return c&&r.push(`Invalid characters in path: ${c.join(", ")} in ${e}`),{valid:r.length===0,errors:r.length>0?r:void 0}}clearCache(){this.parseCache.clear(),this.cacheHits=0,this.cacheMisses=0}clearCircularDetector(){this.circularRefDetector.clear()}getCacheStats(){const e=this.parseCache.getStats(),t=this.cacheHits+this.cacheMisses,r=t>0?this.cacheHits/t:0;return{...e,hits:this.cacheHits,misses:this.cacheMisses,hitRate:r}}getPathSegments(e){return e.replace(/\[[^\]]+\]/g,"").split(".").filter(r=>r.length>0)}getPathDepth(e){return this.getPathSegments(e).length}}const m=new W;function w(n,e){if(e.includes("[*]")){const o=e.indexOf("[*]"),i=e.substring(0,o),a=e.substring(o+3),u=i?p.get(n,i):n;if(!Array.isArray(u))return[];const c=[];for(const f of u)!a||a===""?f!==void 0&&c.push(f):a.startsWith(".")&&c.push(...w(f,a.slice(1)));return c}const t=e.split(".");let r=[n];for(const o of t){const i=[];for(const a of r)if(a!=null)if(Array.isArray(a))for(const u of a){if(u==null)continue;const c=u[o];c!==void 0&&i.push(c)}else{const u=a[o];u!==void 0&&i.push(u)}if(r=i,r.length===0)return[]}const s=[];for(const o of r)if(Array.isArray(o))for(const i of o)i!==void 0&&s.push(i);else o!==void 0&&s.push(o);return s}function I(n){let e=0;for(let t of n){const r=t.toString().split(".")[1];r&&(e=Math.max(e,r.length))}return Math.pow(10,e)}function $(n,e,t){return(n*t+e*t)/t}function De(n,e,t){return n*t/(e*t)}const S=(n,e,t,r)=>{if(!r)throw new Error("Attribute not found");const s={attribute:r,types:n.types};let o;(s.types.includes("sum")||s.types.includes("avg"))&&(o=Ke(r,e));let i;return(s.types.includes("min")||s.types.includes("max"))&&(i=Ie(r,e)),n.types.forEach(a=>{a==="sum"?s.sum=o?.sum:a==="avg"?s.avg=o?.average:a==="count"?s.count=Se(r,e):a==="min"?s.min=i&&i[0]:a==="max"?s.max=i&&i[1]:a==="distinct"?s.distinct=L(n,e,t):a==="group"&&(s.group=Qe(n,e))}),s},Se=(n,e)=>{const r=m.parse(n).isDeepQuery;let s=0;for(const o of e.values())if(o)if(r)s+=w(o,n).filter(i=>i!=null).length;else{const i=o[n];if(i==null)continue;Array.isArray(i)?s+=i.filter(a=>a!=null).length:s++}return s},Ie=(n,e)=>{let t,r;const o=m.parse(n).isDeepQuery;for(const i of e.values()){if(!i)continue;let a;if(o)a=w(i,n);else{const u=i[n];u===void 0?a=[]:Array.isArray(u)?a=u.filter(c=>c!==void 0):a=[u]}for(const u of a)u==null||typeof u=="object"||((t===void 0||u<t)&&(t=u),(r===void 0||u>r)&&(r=u))}if(!(t===void 0||r===void 0))return[t,r]},Qe=(n,e)=>{const t=[];n.groupOptions?.groups?.forEach(i=>{t.push({option:i,count:0,keys:[]})});const r={option:{value:["$dcupl_not_found"]},count:0,keys:[]},o=m.parse(n.attribute).isDeepQuery;for(const i of e.values()){let a;o?a=w(i,n.attribute):a=[i[n.attribute]];let u=!1;for(const c of a)for(const f of t)(typeof f.option.value<"u"&&f.option.value.includes(c)||typeof f.option.from<"u"&&f.option.from<c&&typeof f.option.to<"u"&&f.option.to>c)&&(f.keys.includes(i.key)||(f.count++,f.keys.push(i.key)),u=!0);!u&&n?.groupOptions?.calculateNotFound&&(r.count++,r.keys.push(i.key))}return n?.groupOptions?.calculateNotFound&&t.push(r),t},Ke=(n,e)=>{let t=0,r=0;const o=m.parse(n).isDeepQuery;for(const a of e.values()){if(!a)continue;let u;if(o)u=w(a,n);else{const c=a[n];c===void 0?u=[]:Array.isArray(c)?u=c:u=[c]}for(const c of u)if(Array.isArray(c))for(const f of c)typeof f=="number"&&(t=$(t,f,I([t,f])),r++);else typeof c=="number"&&(t=$(t,c,I([t,c])),r++)}return r===0?void 0:{average:De(t,r,I([t,r])),count:r,sum:t}},L=(n,e,t)=>{const r=[];for(const[s,o]of t)if(!(n.excludeUndefineds&&typeof s>"u")&&Array.from(o).find(i=>e.has(i))){const i={value:s,count:o.size};if(n.distinctOptions?.skipKeys||(i.keys=Array.from(o)),r.push(i),n.distinctOptions?.limit&&r.length>=n.distinctOptions.limit)break}return r};class b extends Error{query;constructor(e,t){const r=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(r),this.query=t,this.name="DcuplQueryError"}}class C{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=p.cloneDeep(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||m}init(e){this._initOptions=p.cloneDeep(e),this.currentQuery=p.cloneDeep(this._defaultQueryOptions),this.currentQuery.modelKey=e.modelKey,"queries"in e&&Array.isArray(e.queries)&&(e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&(this.currentQuery.queries=p.cloneDeep(e.queries)),e.count!==void 0&&(this.currentQuery.count=e.count),e.start!==void 0&&(this.currentQuery.start=e.start),e.sort&&(this.currentQuery.sort=e.sort),e.projection&&(this.currentQuery.projection=e.projection))}reset(){return this.init(this._initOptions),this.getQuery()}isQuery(e){return"attribute"in e}isQueryGroup(e){return"groupKey"in e}isRootQueryGroup(e){return this.isQueryGroup(e)&&e.groupKey==="root"}getQueryGroup(e){return this.currentQuery.queries.find(t=>this.isQueryGroup(t)&&t.groupKey===e)}getQuery(){return p.cloneDeep(this.currentQuery)}hasQueryGroup(e){return this.currentQuery.queries.some(t=>this.isQueryGroup(t)&&t.groupKey===e)}has(e){if(e.groupKey&&e.queryKey){const t=this.getQueryGroup(e.groupKey);if(t)return t.queries.some(r=>this.isQuery(r)&&r.queryKey===e.queryKey)}else if(e.groupKey)return this.hasQueryGroup(e.groupKey);return!1}validate(e){const t=e.queries.map(s=>this.validateQuery(s));return{valid:p.every(t,s=>s.valid),errors:t.map(s=>s.errors).flat()}}applyOptions(e,t="update"){return t==="set"?(this.currentQuery.count=e.count,this.currentQuery.start=e.start,this.currentQuery.sort=e.sort,this.currentQuery.projection=e.projection):(typeof e?.sort<"u"&&(this.currentQuery.sort=e.sort),typeof e?.count<"u"&&(this.currentQuery.count=e.count),typeof e?.start<"u"&&(this.currentQuery.start=e?.start),typeof e?.projection<"u"&&(this.currentQuery.projection=e?.projection)),this.getQuery()}applyQuery(e,t,r){if(r||(r=this.currentQuery),Array.isArray(e))for(const s of e)this.applyQuery(s,t,r);else if(this.isRootQueryGroup(e))e.groupType&&(r.groupType=e.groupType),t?.mode==="set"?r.queries=e.queries:r.queries=[...r.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const s=r.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.attribute);if(s>-1){const o=r.queries[s];t?.mode==="set"?o.queries=[e]:o.queries.push(e)}else r.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const s=r.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.groupKey);if(s>-1){const o=r.queries[s];e.groupType&&(o.groupType=e.groupType),t?.mode==="set"?r.queries[s]=e:o.queries=[...o.queries,...e.queries]}else r.queries.push({groupKey:e.groupKey,groupType:e.groupType||"or",queries:e.queries})}return r}removeAllQueries(){return this.currentQuery.queries=[],this.getQuery()}removeQuery(e,t){if(t||(t=this.currentQuery),this.isQuery(e)){const r=t.queries.findIndex(s=>this.isQueryGroup(s)&&s.groupKey===e.attribute);if(r>-1){const s=t.queries[r],o=p.findIndex(s.queries,e);o>-1&&s.queries.splice(o,1),s.queries.length===0&&t.queries.splice(r,1)}}else if(this.isQueryGroup(e)){const r=t.queries.findIndex(s=>this.isQueryGroup(s)&&s.groupKey===e.groupKey);if(r>-1)if(!e.queries)t.queries.splice(r,1);else{const s=t.queries[r];for(const o of e.queries){const i=p.findIndex(s.queries,o);i>-1&&s.queries.splice(i,1)}s.queries.length===0&&t.queries.splice(r,1)}}return t}validateQuery(e){const t=[];if(this.isQuery(e))return e.attribute||t.push(new b("Missing attribute",e)),e.operator||t.push(new b("Missing operator",e)),typeof e.value>"u"&&t.push(new b("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new b("find operator cannot have array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const o=e.queries.map(i=>this.validateQuery(i)).filter(i=>!i.valid).map(i=>i.errors).flat();return o.length>0?{valid:!1,errors:o}:{valid:!0}}return t.push(new b("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],r=new Set,s=o=>{for(const i of o)this.isQuery(i)?i.attribute&&!r.has(i.attribute)&&(t.push(i.attribute),r.add(i.attribute)):this.isQueryGroup(i)&&s(i.queries)};return s(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],r=new Set,s=o=>{for(const i of o)if(this.isQuery(i)){if(i.attribute&&!r.has(i.attribute)){const a=this.getQueryAttributeForString(i.attribute);t.push(a),r.add(i.attribute)}}else this.isQueryGroup(i)&&s(i.queries)};return s(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(r=>{t[r]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(r=>{if(r.isDeepQuery){if(r.reference)if(r.referenceAttribute&&r.referenceAttribute.length>0){t[r.reference]||(t[r.reference]={$:!0});const s=this.deepQueryService.parse(r.referenceAttribute);if(s.isDeepQuery&&r.reference){const o=this.getProjectionForAttributeEntries([s]);Object.keys(o).forEach(i=>{i!=="$"&&r.reference&&(t[r.reference][i]=o[i])})}else r.reference&&(t[r.reference][r.referenceAttribute]=!0)}else t[r.reference]=!0}else t[r.attribute]=!0}),t}getAttributeNames(e){return this.getQueryAttributes(e)}getAttributeDetails(e){return this.extractQueryAttributes(e||this.currentQuery)}getCurrentAttributeNames(){return this.getAttributeNames(this.currentQuery)}getCurrentAttributeDetails(){return this.getAttributeDetails(this.currentQuery)}addCondition(e){return this.applyQuery(e,{mode:"add"})}addGroup(e){return this.applyQuery(e,{mode:"add"})}setCondition(e){return this.applyQuery(e,{mode:"set"})}setGroup(e){return this.applyQuery(e,{mode:"set"})}mergeQuery(e){if(e.queries&&Array.isArray(e.queries))for(const t of e.queries)this.applyQuery(t,{mode:"add"});return this.currentQuery}replaceQuery(e){return this.currentQuery.queries=[],e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&Array.isArray(e.queries)&&(this.currentQuery.queries=e.queries),this.currentQuery}clear(){return this.reset()}clearConditions(){return this.removeAllQueries()}getCurrentQuery(){return this.getQuery()}isEmpty(){return this.currentQuery.queries.length===0}hasCondition(e){const t=r=>{for(const s of r)if(this.isQuery(s)){let o=!0;for(const i in e)if(s[i]!==e[i]){o=!1;break}if(o)return!0}else if(this.isQueryGroup(s)&&t(s.queries))return!0;return!1};return t(this.currentQuery.queries)}hasGroup(e){return this.hasQueryGroup(e)}getUsedAttributes(){return this.getAttributeNames()}getDeepQueryAttributes(){return this.getAttributeDetails().filter(t=>t.isDeepQuery)}getGroups(){return this.currentQuery.queries.filter(e=>this.isQueryGroup(e))}getTopLevelConditions(){return this.currentQuery.queries.filter(e=>this.isQuery(e))}getGroup(e){return this.getQueryGroup(e)}getConditionCount(){const e=t=>{let r=0;for(const s of t)this.isQuery(s)?r++:this.isQueryGroup(s)&&(r+=e(s.queries));return r};return e(this.currentQuery.queries)}}const M=new C;function Me(n,e,t,r,s,o,i){const a=M.removeQuery({groupKey:s},p.cloneDeep(r)),u=i.queryData(n,a,!1,o),c=e?[...e.keys()]:[],f=new Set(c),l=o.get(s);if(!t.excludeUnresolved)for(const h of l.keys())f.add(h);if(t.excludeUndefineds?f.delete(void 0):f.add(void 0),t.sort){const h=[];for(const v of f.values())h.push(T(v,l,u,e,s,r,!0));const y=t.excludeZeros?h.filter(v=>v.size>0):h;return y.sort(Ne(t.sort)),t.count?y.slice(0,t.count):y}const d=[];for(const h of f.values()){const y=T(h,l,u,e,s,r,!!t?.calculateFacets);if(!(t?.excludeZeros&&y.size===0)){if(t?.count&&d.length===t?.count)return d;d.push(y)}}return d}function T(n,e,t,r,s,o,i){const a=new Map,u=e.get(n)||new Set;for(const c of u){const f=t.get(c);if(f&&(a.set(c,f),!i))break}return{key:String(n),value:n,selected:ke(s,n,o),enabled:a.size>0,size:a.size,entry:r.get(n),resultKeys:Array.from(a.keys())}}function D(n,e){if(n===void 0&&e===void 0)return 0;if(n===void 0)return 1;if(e===void 0)return-1;const t=typeof n,r=typeof e;if(t!==r)return t<r?-1:1;if(t==="number")return n-e;if(t==="string")return n.localeCompare(e);const s=String(n),o=String(e);return s<o?-1:s>o?1:0}function Ne(n){switch(n){case"size-desc":return(e,t)=>t.size-e.size||D(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||D(e.value,t.value);case"value-asc":return(e,t)=>D(e.value,t.value);case"value-desc":return(e,t)=>e.value===void 0&&t.value===void 0?0:e.value===void 0?1:t.value===void 0?-1:-D(e.value,t.value)}}const ke=(n,e,t)=>{const r=t.queries.findIndex(s=>M.isQueryGroup(s)&&s.groupKey===n);return r>-1?!!t.queries[r].queries.find(o=>{if(M.isQuery(o)){const i=o.value?.key||o.value;return o.attribute===n&&i===e}return!1}):!1};class V{indexMap=new Map;dataMap=new Map;indexMetadata=new Map;constructor(){}reset(e){e?(this.indexMap.delete(e),this.dataMap.delete(e),this.indexMetadata.delete(e)):(this.indexMap.clear(),this.dataMap.clear(),this.indexMetadata.clear())}fillDataMap(e,t){let r=this.dataMap.get(e);r||(r=new Map,this.dataMap.set(e,r));for(const s of t){let o;if(typeof s=="object"&&s&&s.key)o=s.key;else if(Array.isArray(s)){for(const a of s)this.fillDataMap(e,[a]);return}else s instanceof Date?o=s.toISOString():o=s;let i=r.get(o);i||(i={key:o},this.dataMap.get(e)?.set(o,i))}}fillInverseIndex(e,t,r){if(!e||!t||!r||!Array.isArray(r))return;const s=this.indexMap.get(e)||new Map;for(const o of r){let i;if(typeof o=="object"&&o&&o.key)i=o.key;else if(Array.isArray(o)){for(const u of o)this.fillInverseIndex(e,t,[u]);return}else o instanceof Date?i=o.toISOString():i=o;let a=s.get(i);a||(a=new Set,s.set(i,a)),a.add(t)}this.indexMap.set(e,s)}getIndex(e,t){const r=this.getIndexName(e,t);return this.indexMap.get(r)}getData(e,t){const r=this.getIndexName(e,t);return this.dataMap.get(r)}getOrCreateIndex(e,t,r){const s=this.getIndexName(e,r);let o=this.getIndex(s);const i=this.indexMetadata.get(s);if(i)i.lastAccessedAt=Date.now();else if(!o){const u=m.parse(e).isDeepQuery??!1;this.indexMetadata.set(s,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:r,type:u?"deep":"shallow"})}if(!o){this.reset(s),this.indexMap.set(s,new Map);const u=m.parse(e).isDeepQuery;for(const c of t.values()){let f;u?(f=w(c,e),f.length===0&&(f=[void 0])):f=[c[e]],this.fillInverseIndex(s,c.key,f),this.fillDataMap(s,f)}o=this.getIndex(s)||new Map}return o}getIndexName(e,t){return t?e+"_"+N(t):e}removeFromInverseIndex(e,t,r){const s=this.indexMap.get(e);if(s)for(const o of r){let i;if(typeof o=="object"&&o&&o.key)i=o.key;else if(Array.isArray(o)){for(const u of o)this.removeFromInverseIndex(e,t,[u]);return}else o instanceof Date?i=o.toISOString():i=o;const a=s.get(i);a&&(a.delete(t),a.size===0&&s.delete(i))}}updateInverseIndex(e,t,r,s){this.removeFromInverseIndex(e,t,r),this.fillInverseIndex(e,t,s)}removeFromDataMap(e,t){const r=this.dataMap.get(e);if(r)for(const s of t){let o;if(typeof s=="object"&&s&&s.key)o=s.key;else if(Array.isArray(s)){for(const i of s)this.removeFromDataMap(e,[i]);return}else s instanceof Date?o=s.toISOString():o=s;r.delete(o)}}updateDataMap(e,t,r){this.removeFromDataMap(e,t),this.fillDataMap(e,r)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[r,s]of t)s.delete(e)&&s.size===0&&t.delete(r);for(const t of this.dataMap.values())t.has(e)&&t.delete(e)}resetAttributes(e){for(const t of e)this.reset(t)}isDeepQueryIndex(e){const t=e.includes("_")?e.split("_")[0]:e;try{return m.parse(t).isDeepQuery??!1}catch{return!1}}getDeepIndexKeys(){const e=[];for(const t of this.indexMap.keys())this.isDeepQueryIndex(t)&&e.push(t);return e}resetAllDeepIndices(){const e=this.getDeepIndexKeys();for(const t of e)this.indexMap.delete(t),this.dataMap.delete(t)}getIndexCount(){let e=0,t=0;for(const r of this.indexMap.keys())this.isDeepQueryIndex(r)?t++:e++;return{shallow:e,deep:t,total:e+t}}cleanupStaleIndices(e=300*1e3){const t=Date.now();let r=0;for(const[s,o]of this.indexMetadata)t-o.lastAccessedAt>e&&(this.reset(s),r++);return r}getStats(){const e=this.getIndexCount(),t=Date.now();let r=0,s=0;for(const i of this.indexMetadata.values()){const a=t-i.createdAt;r+=a,a>s&&(s=a)}const o=this.indexMetadata.size>0?r/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:s,avgAge:o}}}const x="__";function E(n,e,t={key:"root"},r="root",s=new V,o){const i=o||n;for(const a of e.columns)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,i));for(const a of e.rows)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,i));for(const a of e.values)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,i));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=Ce(n,e.rows[0],e,s,r,o);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=H(n,e.columns[0],e,s,r,o);t.columns.push(a)}if(t.key==="root")for(const a of e.values){if(t.values=t.values||[],r==="root"&&e.options?.calculateTotals===!1)continue;const u=S(a,n,s.getIndex(a.attribute),a.attribute);t.values.push(u)}return t}function Ce(n,e,t,r,s="",o){const i={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return i;for(const[u,c]of a.entries()){const f={key:u,value:u},l=new Map;for(const d of c)n.has(d)&&l.set(d,n.get(d));if(l.size){for(const d of t.values){if(f.values=f.values||[],s==="root"&&e?.calculateTotals===!1)continue;const h=S(d,l,r.getIndex(d.attribute),d.attribute);f.values.push(h)}if(i.rows=i.rows||[],i.rows.push(f),t.rows.length>1){const d={...t,rows:t.rows.slice(1)};E(l,d,f,s+x+e.attribute+x+u,r,o)}else if(t.columns)for(const d of t.columns){f.columns=f.columns||[];const h=H(l,d,t,r,s+x+e.attribute+x+u,o);f.columns.push(h)}}}return i}function H(n,e,t,r,s="",o){const i={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return i;for(const[u,c]of a.entries()){const f={key:u,value:u},l=new Map;for(const d of c)n.has(d)&&l.set(d,n.get(d));if(l.size){for(const d of t.values){if(f.values=f.values||[],s==="root"&&e?.calculateTotals===!1)continue;const h=S(d,l,r.getIndex(d.attribute),d.attribute);f.values.push(h)}if(i.columns=i.columns||[],i.columns.push(f),t.columns.length>1){const d={...t,columns:t.columns.slice(1)};E(l,d,f,s+x+e.attribute+x+u,r,o)}}}return i}const Ee=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,qe=/^-?\d+$/,Oe=/^-?\d+\.\d+$/,$e=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,U=n=>n==="true"||n==="false"?"boolean":qe.test(n)?"int":Oe.test(n)?"float":Ee.test(n)&&!Number.isNaN(Date.parse(n))?"date":"string",J=n=>$e.test(n),Te=n=>n==null||n==="",Fe=n=>{const e=[...n];return e.length<=1?{type:e[0]??"any",conflict:!1}:e.every(t=>t==="int"||t==="float")?{type:"float",conflict:!1}:{type:"any",conflict:!0}},Z=(n,e={})=>{const r=e.deep??(e.sampleSize!==void 0&&e.sampleSize>1)?e.sampleSize??1/0:1,s=e.coerceStrings??!0,o=new Map,i=[],a=Math.min(n.length,r);for(let f=0;f<a;f++){const l=n[f];if(l)for(const[d,h]of Object.entries(l)){let y=o.get(d);if(y||(y={observed:new Set,empty:0,scanned:0},o.set(d,y),i.push(d)),y.scanned++,Te(h)){y.empty++;continue}let v;typeof h=="string"&&s?(v=U(h),v==="string"&&!y.hint&&J(h)&&(y.hint="column looks date-like (non-ISO) — review manually")):v=ee(h),y.observed.add(v)}}const u=[],c=[];for(const f of i){const l=o.get(f),{type:d,conflict:h}=Fe(l.observed.size?l.observed:new Set(["string"]));u.push({key:f,type:d}),c.push({column:f,inferredType:d,observedTypes:[...l.observed].sort(),emptyRate:l.scanned===0?0:l.empty/l.scanned,conflict:h,hint:l.hint})}return{properties:u,diagnostics:c}},Ge=(n,e=!1)=>Z(n,typeof e=="boolean"?{deep:e}:e).properties,Y=n=>Number(n)===n&&n%1===0,X=n=>Number(n)===n&&n%1!==0,ee=n=>{switch(typeof n){case"string":return"string";case"number":return Y(n)?"int":X(n)?"float":"any";case"boolean":return"boolean";case"object":return j(n)?"date":"json";default:return"any"}},Be=(n,e)=>{const t=P(n.text||""),r=e?.attributeKey||n.filterKey;let s;const o=e?.comparisonType||"containsIgnoreCase";return o==="containsIgnoreCase"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["lowercase"]}}]}:o==="containsIgnoreCaseAndWhitespace"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["removeWhitespace","lowercase"]}}]}:o==="contains"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:`/${t}/`,operator:"find"}]}:o==="equal"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:n.text,operator:"eq"}]}:o==="equalIgnoreCase"&&(s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:n.text,operator:"eq",options:{transform:["lowercase"]}}]}),s},ze=(n,e)=>{const t=e?.attributeKey||n.filterKey;return{groupKey:n.filterKey,queries:[{queryKey:n.value,attribute:t,value:n.value,operator:"eq"}]}},Pe=(n,e)=>{const t=e?.attributeKey||n.filterKey,r={groupKey:n.filterKey,queries:[]};return typeof n.eq<"u"&&(r.groupType="or",Array.isArray(n.eq)?n.eq.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq"})}):r.queries.push({attribute:t,value:n.eq,operator:"eq"})),typeof n.ne<"u"&&(r.groupType="and",Array.isArray(n.ne)?n.ne.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq",options:{invert:!0}})}):r.queries.push({attribute:t,value:n.ne,operator:"eq",options:{invert:!0}})),typeof n.gt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.gt,operator:"gt"})),typeof n.lt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.lt,operator:"lt"})),typeof n.gte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.gte,operator:"gte"})),typeof n.lte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.lte,operator:"lte"})),r},Re=(n,e)=>{const t=e?.attributeKey||n.filterKey,r={groupKey:n.filterKey,queries:[]};return n.itemKeys.forEach(s=>{r.queries.push({queryKey:s,attribute:t,value:{key:s},operator:"eq"})}),r},je=n=>!(typeof n.modelKey!="string"||!Array.isArray(n.queries));class _e{constructor(e,t,r){this.scriptController=e,this.globalItemService=t,this.modelParser=r}registeredCustomOperator=new Map;queryBuilder=new C;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(r=>this.transformValue(r,t));if(typeof e!="string")return e;for(const r of t)r==="lowercase"?e=e.toLowerCase():r==="trim"?e=e.trim():r==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let r,s=e.value;const o=e.options?.arrayValueHandling||"some";if(Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(s=this.transformValue(s,e.options.transform)),e.attribute.includes(".")||e.attribute.includes("[")?r=p.get(t,e.attribute):r=t[e.attribute],Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(r=this.transformValue(r,e.options.transform)),(typeof r>"u"||r===null)&&!["typeof","isTruthy","eq"].includes(e.operator))return!1;switch(e.operator){case"eq":return e.options?.invert?!p.isEqual(r,s):p.isEqual(r,s);case"find":return e.options?.invert?!this.queryFind(r,s,o):this.queryFind(r,s,o);case"lt":return Array.isArray(r)?o==="some"?r.some(i=>i<s):r.every(i=>i<s):r<s;case"gt":return Array.isArray(r)?o==="some"?r.some(i=>i>s):r.every(i=>i>s):r>s;case"lte":return Array.isArray(r)?o==="some"?r.some(i=>i<=s):r.every(i=>i<=s):r<=s;case"gte":return Array.isArray(r)?o==="some"?r.some(i=>i>=s):r.every(i=>i>=s):r>=s;case"typeof":return e.options?.invert?typeof r!==s:Array.isArray(r)?o==="some"?r.some(i=>typeof i===s):r.every(i=>typeof i===s):typeof r===s;case"isTruthy":return s===!0?Array.isArray(r)?o==="some"?r.some(i=>typeof!!i):r.every(i=>typeof!!i):!!r:!r;case"size":return typeof r=="string"?r.length===s:p.size(r)===s;default:if(this.scriptController.hasScript(e.operator))return this.scriptController.executeScript(e.operator,"operator",{query:e,item:t});if(this.registeredCustomOperator.has(e.operator)){const i=this.registeredCustomOperator.get(e.operator);if(typeof i=="function")return i(e,t)}}return!1}evaluateEqOperator(e,t,r,s){const o=new Map,i=s.get(t.attribute);if(i){let a;if(typeof t.value=="string"?a=t.value:t.value?.key&&Object.keys(t.value).length===1&&(a=t.value.key),typeof a<"u"){const u=i.get(a);if(u)if(u.forEach(c=>{r.has(c)&&o.set(c,r.get(c))}),t.options?.invert){const c=p.differenceBy(Array.from(r.values()),Array.from(o.values()),"key"),f=new Map;return c.forEach(l=>{f.set(l.key,l)}),f}else return o}}for(let[a,u]of r){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(f=>f.isDeepQuery)){const f=this.queryBuilder.getProjectionForAttributeEntries(c.filter(l=>l.isDeepQuery));u=this.globalItemService.getProjectedData(f,this.modelParser.models.get(e.modelKey),u)}this.evaluateQuery(t,u)&&o.set(a,u)}return o}equalRegexFn(e,t){if(typeof t=="string"&&p.startsWith(t,"/")&&p.endsWith(t,"/"))try{return new RegExp(t.slice(1,-1)).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(r=>p.isEqualWith(r,t,this.equalRegexFn)):typeof t=="object"?p.isMatch(e,t):e===t}queryFind(e,t,r){return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?r==="some"?e.some(s=>p.isEqualWith(s,t,this.equalRegexFn)):e.every(s=>p.isEqualWith(s,t,this.equalRegexFn)):!!p.find(e,t):p.isEqualWith(e,t,this.equalRegexFn)}validateQuery(e){if(this.queryBuilder.isQuery(e)){if(!e.attribute||!e.operator)throw new Error("invalid query - missing attribute or operator");if(e.operator==="find"&&Array.isArray(e.value))throw new Error("invalid query - find operator cannot have array value");return!0}else{if(this.queryBuilder.isQueryGroup(e))return p.every(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,r,s){const o=new Map;if(t.attribute.includes("[*]")){const i=t.options?.invert===!0,a=new Set;for(let u of r.values()){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(d=>d.isDeepQuery)){const d=this.queryBuilder.getProjectionForAttributeEntries(c.filter(h=>h.isDeepQuery));u=this.globalItemService.getProjectedData(d,this.modelParser.models.get(e.modelKey),u)}const f=this.handleArrayStarQuery(t,u);let l=!1;for(const d of f.queries){const h={...d,options:{...d.options,invert:!1}};if(this.evaluateQuery(h,u)){l=!0;break}}l&&(a.add(u.key),i||o.set(u.key,u))}if(i)for(const[u,c]of r)a.has(u)||o.set(u,c)}else{if(t.operator==="eq")return this.evaluateEqOperator(e,t,r,s);for(let[i,a]of r){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(c=>c.isDeepQuery)){const c=this.queryBuilder.getProjectionForAttributeEntries(u.filter(f=>f.isDeepQuery));a=this.globalItemService.getProjectedData(c,this.modelParser.models.get(e.modelKey),a)}this.evaluateQuery(t,a)&&o.set(i,a)}}return o}handleArrayStarQuery(e,t){const r=e.attribute.indexOf("[*]"),s={groupKey:e.queryKey||e.attribute+"[*]",groupType:"or",queries:[]};if(r!==-1){const o=e.attribute.substring(0,r),i=o.includes(".")?p.get(t,o):t[o];if(Array.isArray(i))for(let a=0;a<i.length;a++){const u=e.attribute.replace("[*]",`[${a}]`);s.queries.push({attribute:u,operator:e.operator,value:e.value,options:e.options})}}return s}evaluateQueryGroup(e,t,r,s,o){let i=new Map,a=r;if(!t.queries||t.queries?.length===0)return a;for(const u of t.queries){let c=new Map;if(this.queryBuilder.isQuery(u)?c=this.getEvaluatedQueryDataset(e,u,a,o):c=this.evaluateQueryGroup(e,u,a,s,o),i.size===0&&(i=c),t.groupType==="or")c.forEach(f=>{i.set(f.key,f)});else{const f=p.differenceBy(Array.from(i.values()),Array.from(c.values()),"key");for(const l of f)i.delete(l.key)}t.groupType==="and"?a=i:a=r}return i}queryData(e,t,r,s){const o=new Map(e);return t.queries.length===0?e:(t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,o,r,s))}}class We{scripts=new Map;scriptFunctions=new Map;constructor(){}keys(){return Array.from(this.scripts.keys())}setScript(e,t){this.scripts.set(e,t)}removeScript(e){this.scripts.delete(e)}getScript(e){return this.scripts.get(e)}hasScript(e){return this.scripts.has(e)}getScriptAsFn(e,t){if(this.scriptFunctions.has(e))return this.scriptFunctions.get(e);const r=this.getScript(e);if(!r)throw new Error(`Script ${e} not found`);const s=this.getWrapperScript(r),o=new Function("script_type",...t,s);return this.scriptFunctions.set(e,o),o}getWrapperScript(e){return`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("lodash-es");function I(n){const e=E(n);return ne(e)}function E(n){if(typeof n!="object"||n===null)return String(n);if(Array.isArray(n))return"["+n.map(E).join(",")+"]";const e=Object.keys(n).sort();let t="{";for(let r=0;r<e.length;r++){const s=e[r];t+=s+":"+E(n[s]),r<e.length-1&&(t+=",")}return t+="}",t}function ne(n){let e=0;for(let t=0;t<n.length;t++){const r=n.charCodeAt(t);e=(e<<5)-e+r,e|=0}return e.toString(16)}const A={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:n=>{typeof performance<"u"&&performance.mark&&performance.mark(n)},measure:(n,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(n,e,t)},getEntriesByName(n){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(n)},getEntriesByType(n){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(n)}};class ie{data;enabled=!1;constructor(){}init(e){this.data=new Map,this.enabled=e}set(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context);return this.data.set(t,e.value),this.data.get(t)}mark(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),r={name:e.name,type:"mark",value:A.now(),createdAt:Date.now()};return this.data.set(t,r),r}measure(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),r=this.data.get(this.getKey(e.start,e.context)),s=this.data.get(this.getKey(e.end,e.context));if(!r||!s)return;const i=s.value-r.value,o=Math.round(i*100)/100,a=this.data.get(t);if(a&&e.sum){const c=a.value+o,f={...a,value:c};return this.data.set(t,f),f}const u={name:e.name,type:"measure",value:o,createdAt:Date.now()};return e.detail&&(u.detail=e.detail),this.data.set(t,u),u}update(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context),r=this.data.get(t);if(r){const s={...r,...e.value};this.data.set(t,s)}else this.data.set(t,e.value);return this.data.get(t)}getResourceInfosFromPerformanceAPI(){return typeof performance>"u"?[]:A.getEntriesByType("resource")}get(e){const t=this.getKey(e.name,e.context);return this.data.get(t)}getByType(e){return Array.from(this.data.values()).filter(t=>t.type===e)}getByName(e){return Array.from(this.data.values()).filter(t=>t.name===e)}clear(){this.data.clear()}getKey(e,t){if(!t)return e;const r=I(t);return e+"_"+r}}let T=class _{nodes;edges;nodeKinds=new Map;nodeMeta=new Map;edgePolicy;constructor(){this.nodes=new Set,this.edges=new Map}addNode(e,t){this.nodes.has(e)||(this.nodes.add(e),this.edges.set(e,new Set)),t?.kind!==void 0&&this.nodeKinds.set(e,t.kind),t?.meta!==void 0&&this.nodeMeta.set(e,t.meta)}addDependency(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))throw new Error("Both nodes must exist before adding a dependency.");if(this.edgePolicy&&!this.edgePolicy({name:e,kind:this.nodeKinds.get(e)},{name:t,kind:this.nodeKinds.get(t)}))throw new Error(`Edge policy rejected dependency from "${e}" to "${t}".`);this.edges.get(e).add(t)}setEdgePolicy(e){this.edgePolicy=e}setNodeKind(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");t===void 0?this.nodeKinds.delete(e):this.nodeKinds.set(e,t)}getNodeKind(e){return this.nodeKinds.get(e)}setNodeMeta(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodeMeta.set(e,t)}getNodeMeta(e){return this.nodeMeta.get(e)}removeNode(e){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodes.delete(e),this.edges.delete(e);for(let t of this.edges.values())t.delete(e)}removeDependency(e,t){if(!this.edges.has(e))throw new Error("From node does not exist.");this.edges.get(e).delete(t)}hasNode(e){return this.nodes.has(e)}hasDependency(e,t){return this.edges.has(e)?this.edges.get(e).has(t):!1}getDependencies(e){if(!this.edges.has(e))throw new Error("Node does not exist.");return Array.from(this.edges.get(e))}getDependents(e){const t=[];for(let[r,s]of this.edges)s.has(e)&&t.push(r);return t}isCyclic(){const e=new Set,t=new Set,r=s=>{if(e.has(s))return!1;if(t.has(s))return!0;t.add(s);const i=this.edges.get(s);if(i){for(let o of i)if(r(o))return!0}return t.delete(s),e.add(s),!1};for(let s of this.nodes)if(r(s))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,r=[],s=i=>{if(e.has(i))return null;if(t.has(i)){const a=r.indexOf(i);return r.slice(a).concat([i])}t.add(i),r.push(i);const o=this.edges.get(i);if(o)for(let a of o){const u=s(a);if(u)return u}return r.pop(),t.delete(i),e.add(i),null};for(let i of this.nodes){const o=s(i);if(o)return{hasCycle:!0,path:o}}return{hasCycle:!1}}order(e){const t=new Set,r=new Set,s=[],i=e?.allowCycles??!1,o=a=>{if(t.has(a))return;if(r.has(a)){if(i)return;throw new Error("Graph has a cycle.")}r.add(a);const u=this.edges.get(a);if(u)for(let c of u)o(c);r.delete(a),t.add(a),s.push(a)};for(let a of this.nodes)t.has(a)||o(a);return s}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,r]of this.edges)for(let s of r)e.push([t,s]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const r of this.edges.values())for(const s of r)e.add(s);const t=[];for(const r of this.nodes)e.has(r)||t.push(r);return t}getNodesByKind(e){const t=[];for(const r of this.nodes)this.nodeKinds.get(r)===e&&t.push(r);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),r=Array.from(t);return e?r.filter(s=>this.nodeKinds.get(s)===e):r}getLeavesByKind(e){const t=[];for(const r of this.nodes){const s=this.edges.get(r);(!s||s.size===0)&&(!e||this.nodeKinds.get(r)===e)&&t.push(r)}return t}getDependenciesOfKind(e,t){return this.getDependencies(e).filter(s=>this.nodeKinds.get(s)===t)}getDependentsOfKind(e,t){return this.getDependents(e).filter(s=>this.nodeKinds.get(s)===t)}plan(e){const t=new Map;for(const o of this.nodes)t.set(o,0);for(const o of this.edges.values())for(const a of o)t.set(a,(t.get(a)||0)+1);const r=[];let s=Array.from(this.nodes).filter(o=>(t.get(o)||0)===0);const i=new Set;for(;s.length>0;){const o=s.slice();r.push(o),s=[];for(const a of o){if(i.has(a))continue;i.add(a);const u=this.edges.get(a);if(u)for(const c of u)t.set(c,(t.get(c)||0)-1),(t.get(c)||0)===0&&s.push(c)}}if(i.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const o=new Set(e.filterKinds);return{batches:r.map(a=>a.filter(u=>o.has(this.nodeKinds.get(u))))}}return{batches:r}}getImpactedNodes(e,t="downstream",r){const s=new Set(e),i=c=>!r||r.length===0||r.includes(this.nodeKinds.get(c)??void 0),o=()=>{const c=new Set,f=Array.from(s);for(;f.length;){const l=f.shift();for(const[d,h]of this.edges)h.has(l)&&!c.has(d)&&(c.add(d),f.push(d))}return c},a=()=>{const c=new Set,f=Array.from(s);for(;f.length;){const l=f.shift(),d=this.edges.get(l);if(d)for(const h of d)c.has(h)||(c.add(h),f.push(h))}return c};let u;return t==="both"?u=new Set([...o(),...a()]):t==="upstream"?u=a():u=o(),Array.from(u).filter(i)}toJSON(){const e=Array.from(this.nodes).map(r=>({name:r,kind:this.nodeKinds.get(r),meta:this.nodeMeta.get(r)})),t=this.getAllEdges().map(([r,s])=>({from:r,to:s}));return{nodes:e,edges:t}}static fromJSON(e){const t=new _;for(const r of e.nodes)t.addNode(r.name,{kind:r.kind,meta:r.meta});for(const r of e.edges)t.addDependency(r.from,r.to);return t}diff(e){const t=new Set(this.getNodes()),r=new Set(e.getNodes()),s=Array.from(r).filter(l=>!t.has(l)),i=Array.from(t).filter(l=>!r.has(l)),o=new Set(this.getAllEdges().map(l=>l.join("→"))),a=new Set(e.getAllEdges().map(l=>l.join("→"))),u=Array.from(a).filter(l=>!o.has(l)).map(l=>l.split("→")),c=Array.from(o).filter(l=>!a.has(l)).map(l=>l.split("→")),f=[];for(const l of new Set([...t,...r])){const d=this.nodeKinds.get(l),h=e.nodeKinds.get(l);d!==h&&f.push({name:l,from:d,to:h})}return{addedNodes:s,removedNodes:i,addedEdges:u,removedEdges:c,kindChanges:f}}};class oe{graph;nodeIndex;constructor(){this.graph=new T,this.nodeIndex=new Map}getNodeId(e,t){return`${e}.${t}`}parseNodeId(e){const t=e.split(".");return{modelKey:t[0],attributeKey:t.slice(1).join(".")}}addAttribute(e){const t=this.getNodeId(e.modelKey,e.attributeKey);this.nodeIndex.has(t)||(this.graph.addNode(t,{meta:e}),this.nodeIndex.set(t,e))}addAttributeDependency(e,t){this.addAttribute(e),this.addAttribute(t);const r=this.getNodeId(e.modelKey,e.attributeKey),s=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(r,s)||this.graph.addDependency(r,s)}getImpactedAttributes(e){const t=e.map(a=>this.getNodeId(a.modelKey,a.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(a=>this.nodeIndex.get(a)).filter(a=>a!==void 0),i=[...e,...s],o=new Set;return i.filter(a=>{const u=this.getNodeId(a.modelKey,a.attributeKey);return o.has(u)?!1:(o.add(u),!0)})}getProcessingOrder(e){const t=new Map,r=[...e].sort((s,i)=>s.processingStep-i.processingStep);for(const s of r){const{modelKey:i,attributeKey:o,processingStep:a}=s;t.has(i)||t.set(i,new Map);const u=t.get(i);u.has(a)||u.set(a,new Set),u.get(a).add(o)}return t}getAttributesForModel(e){const t=[];for(const r of this.nodeIndex.values())r.modelKey===e&&t.push(r);return t}getDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}getDependents(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependents(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}hasDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).length>0:!1}hasNode(e){return this.nodeIndex.has(e)}getAllAttributes(){return Array.from(this.nodeIndex.values())}getMaxDepth(){let e=0;const t=(r,s=new Set)=>{if(s.has(r))return 0;s.add(r);const i=this.graph.getDependencies(r);if(i.length===0)return 1;let o=0;for(const a of i){const u=t(a,new Set(s));o=Math.max(o,u)}return o+1};for(const r of this.graph.getNodes()){const s=t(r);e=Math.max(e,s)}return e}validateCompleteness(e){const t=[];for(const[r,s]of e)for(const i of s){const o=this.getNodeId(r,i);this.hasNode(o)||t.push({modelKey:r,attributeKey:i})}return{isComplete:t.length===0,missing:t}}clear(){this.graph.clear(),this.nodeIndex.clear()}getStats(){const e=new Map,t=new Map;for(const r of this.nodeIndex.values())e.set(r.modelKey,(e.get(r.modelKey)||0)+1),t.set(r.processingStep,(t.get(r.processingStep)||0)+1);return{totalAttributes:this.nodeIndex.size,totalDependencies:this.graph.getAllEdges().length,maxDepth:this.getMaxDepth(),attributesByModel:e,attributesByStep:t}}toJSON(){return{nodes:Array.from(this.nodeIndex.values()),edges:this.graph.getAllEdges().map(([e,t])=>{const r=this.parseNodeId(e),s=this.parseNodeId(t);return{from:r,to:s}})}}}const $={silent:0,error:1,warn:2,info:3,debug:4};class g{config;static globalConfig={};constructor(e={}){this.config={level:e.level??g.globalConfig.level??this.getDefaultLevel(),format:e.format??g.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??g.globalConfig.onLog,onTrackError:e.onTrackError??g.globalConfig.onTrackError}}static setGlobalConfig(e){g.globalConfig={...g.globalConfig,...e}}static getGlobalConfig(){return{...g.globalConfig}}static setModuleLevel(e,t){g.globalConfig.onLog||(g.globalConfig.onLog=void 0),g._moduleOverrides||(g._moduleOverrides=new Map),g._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!g._moduleOverrides))return g._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=g.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return $[e]<=$[t]}formatMessage(e){if(this.config.format==="json"){const o={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(o.module=e.prefix),e.context&&(o.context=e.context),e.error&&(o.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(o)}const t=new Date(e.timestamp).toISOString().substring(11,23),r=e.prefix?`[${e.prefix}]`:"",s=this.getLevelIcon(e.level),i=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${s} ${r} ${e.message}${i}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,r,s){if(!this.shouldLog(e))return;const i={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:r,error:s};if(this.config.onLog){this.config.onLog(i);return}const o=this.formatMessage(i);if(typeof console<"u")switch(e){case"error":s?console.error(o,s):console.error(o);break;case"warn":console.warn(o);break;case"debug":console.debug?console.debug(o):console.log(o);break;default:console.log(o)}}error(e,t,r){const s=t instanceof Error?t:void 0,i=t instanceof Error?r:t;this.log("error",e,i,s)}trackError(e,t,r){if(this.error(e,t,r?.context),this.config.onTrackError){const s={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:r?.context,error:t,errorType:r?.errorType,errorGroup:r?.errorGroup};this.config.onTrackError(s)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new g(t)}configure(e){Object.assign(this.config,e)}}const P=new g;class ae{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}cache;cacheDependencies;hitCount=0;missCount=0;log=P.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const r=this.getCacheName(e,t);return this.cache.has(r)?this.hitCount++:this.missCount++,this.cache.get(r)}set(e,t,r,s){if(!this.enabled)return;const i=this.getCacheName(e,t);this.cache.set(i,r),s?this.cacheDependencies.set(i,s):this.log.debug(`Cache entry '${e}' stored without dependencies. This prevents granular invalidation and may cause stale data.`)}has(e,t){return this.cache.has(this.getCacheName(e,t))}clear(){this.cache.clear(),this.cacheDependencies.clear(),this.hitCount=0,this.missCount=0}invalidateByDependencies(e){if(!this.enabled)return;const t=[];for(const[r,s]of this.cacheDependencies){let i=!1;for(const[o,a]of e){if(s.models.has(o))if(s.modelAttributes.has(o)){const u=s.modelAttributes.get(o);for(const c of a)if(u.has(c)){i=!0;break}}else i=!0;if(i)break}i&&t.push(r)}for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),r=[];for(const[s,i]of this.cacheDependencies)for(const o of t)if(i.models.has(o)){r.push(s);break}for(const s of r)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const r of this.cache.keys())r.startsWith(e+"_")&&t.push(r);for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const r=new Map;r.set(e,new Set([t])),this.invalidateByDependencies(r)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const r of this.cache.keys())e(r)&&t.push(r);for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}generateContext(e){try{return p.cloneDeep(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const r=I(t);return e+"_"+r}getStats(){const e=this.hitCount+this.missCount,t=e>0?this.hitCount/e:0;return{size:this.cache.size,hitRate:t,totalEntries:this.cache.size,entriesWithDependencies:this.cacheDependencies.size,hits:this.hitCount,misses:this.missCount}}}const ue=(n,e="")=>`${n}#${e}`,ce=n=>`${n.gt}_${n.gte}_${n.lt}_${n.lte}_${n.eq}_${n.ne}`,fe=n=>`${n.gt}_${n.gte}_${n.lt}_${n.lte}_${n.eq}_${n.ne}`,le=(n,e)=>{const t=typeof e=="function"?e:r=>r[e];return[...n.reduce((r,s)=>{const i=s==null?s:t(s);return r.has(i)||r.set(i,s),r},new Map).values()]},de=(n,e)=>n.reduce(function(t,r){const s=typeof e=="function"?e(r):r[e];return Object.prototype.hasOwnProperty.call(t,s)||(t[s]=[]),t[s].push(r),t},{});function G(n=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let r=0;r<n;r++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}const he=n=>n.replace(/\/+$/,""),B=n=>typeof n!="string"?"":n.replace(/[[\]{}()*+?.,\\^$|#]/g,"\\$&"),pe=n=>typeof n!="string"?"":n.replace(/\\([[\]{}()*+?.,\\^$|#])/g,"$1"),ge=(n,e)=>{try{return z(n,e)>=0}catch{return!1}},z=(n,e)=>{if(!M(n)||!M(e))throw new Error(`Invalid version format: v1="${n}", v2="${e}". Expected format: "x.y.z"`);const t=n.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<3;s++){const i=t[s]||0,o=r[s]||0;if(i>o)return 1;if(i<o)return-1}return 0},M=n=>/^\d+(\.\d+){0,2}$/.test(n);class ye{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=A.now(),e.duration=e.start-e.end),this.updateListener.forEach(t=>{t(e)})}on(e){return this.updateListener.add(e),()=>{this.updateListener.delete(e)}}}const k=(n,e)=>e?typeof structuredClone<"u"?structuredClone(n):p.cloneDeep(n):n,q=(n,e,t,r,s,i)=>{try{const o=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=k(i,o);if(t.scope==="list"&&(t.listKey=n.cdRef?.key||n.key,t.modelKey=n.model?.key||n.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const u=A.now(),c=u-r,f=Math.round(c*1e3)/1e3;t.duration=f,t.start=r,t.end=u;const l={duration:t.duration};return t.modelKey&&(l.model=t.modelKey),t.connectMessageResult&&(t.result=a),t.args&&(l.args=t.args),e?.trigger(t),e.analyticsController.mark({name:`${t.type}:end`,context:s}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:s,detail:l}),a}catch{return i}},me=n=>(t,r,s)=>{const i=s.value;return s.value=function(...o){const a=A.now(),u=this.cdRef,c=k(n,!0);c.key||(u.increaseCounter(),c.key=u.getCounter());const f=G();u.analyticsController.mark({name:`${c.type}:start`,context:f});const l=this.model?.key;!c.originCdRefKey&&u.key&&(c.originCdRefKey=u.key),l&&(c.modelKey=l);const d=i.apply(this,o);return c.method=r,c.args=o,d&&typeof d=="object"&&"then"in d?d.then(h=>q(this,u,c,a,f,h)):q(this,u,c,a,f,d)},s};function ve(n,e,t,r){t.max||(t.max=20);const s=[],i=t.transform?r.transformValue(t.value,t.transform):t.value;for(const[o,a]of e.entries()){const u=Array.from(a).some(f=>n.has(f)),c=t.transform?r.transformValue(o,t.transform):o;if(!(t.excludeUndefineds&&typeof o>"u")&&!(t.excludeNulls&&o===null)){if(u&&(i===""||i==="//")){const f={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}else if(u&&typeof i=="string"&&i.startsWith("/")&&i.endsWith("/")){if(r.queryFind(c,i,"some")){const f={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}}else if(u&&typeof i=="string"){const f=String(c??""),l=i;if(f.toLowerCase().startsWith(l.toLowerCase())){const d={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(d)}}else if(u&&r.queryFind(c,i,"some")){const f={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}if(s.length===t.max)break}}return s}function j(n){return n instanceof Date}function W(n){return n instanceof Date&&!isNaN(n.getTime())}const we={yyyy:{type:"year",pattern:"yyyy",regex:"(\\d{4})"},yy:{type:"year",pattern:"yy",regex:"(\\d{2})"},MM:{type:"month",pattern:"MM",regex:"(\\d{2})"},M:{type:"month",pattern:"M",regex:"(\\d{1,2})"},dd:{type:"day",pattern:"dd",regex:"(\\d{2})"},d:{type:"day",pattern:"d",regex:"(\\d{1,2})"},HH:{type:"hour",pattern:"HH",regex:"(\\d{2})"},H:{type:"hour",pattern:"H",regex:"(\\d{1,2})"},mm:{type:"minute",pattern:"mm",regex:"(\\d{2})"},m:{type:"minute",pattern:"m",regex:"(\\d{1,2})"},ss:{type:"second",pattern:"ss",regex:"(\\d{2})"},s:{type:"second",pattern:"s",regex:"(\\d{1,2})"},SSS:{type:"millisecond",pattern:"SSS",regex:"(\\d{3})"}};function xe(n){let e="^";const t=[];let r=n;const s=Object.entries(we).sort((i,o)=>o[0].length-i[0].length);for(;r.length>0;){let i=!1;for(const[o,a]of s)if(r.startsWith(o)){e+=a.regex,t.push({type:a.type,pattern:o}),r=r.slice(o.length),i=!0;break}if(!i){const o=r[0];if(!o)break;e+=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=r.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function Ae(n,e){const t={year:1970,month:1,day:1,hour:0,minute:0,second:0,millisecond:0};for(let r=0;r<e.length;r++){const s=n[r+1];if(!s)continue;const i=parseInt(s,10),o=e[r];o&&(o.type==="year"&&o.pattern==="yy"?t.year=2e3+i:t[o.type]=i)}return t}function be(n){if(n.month<1||n.month>12)return new Date(NaN);if(n.day<1||n.day>31)return new Date(NaN);if(n.hour<0||n.hour>23)return new Date(NaN);if(n.minute<0||n.minute>59)return new Date(NaN);if(n.second<0||n.second>59)return new Date(NaN);if(n.millisecond<0||n.millisecond>999)return new Date(NaN);const e=new Date(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return W(e)?e.getFullYear()!==n.year||e.getMonth()!==n.month-1||e.getDate()!==n.day?new Date(NaN):e:new Date(NaN)}function De(n,e,t){if(n=n.trim(),e==="t"){const a=Number(n);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(n);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:r,tokenOrder:s}=xe(e),i=n.match(r);if(!i)return new Date(NaN);const o=Ae(i,s);return be(o)}class Se{cache;maxSize;accessOrder;constructor(e){this.cache=new Map,this.maxSize=e,this.accessOrder=[]}get(e){const t=this.cache.get(e);return t!==void 0&&this.updateAccessOrder(e),t}set(e,t){if(this.cache.has(e))this.cache.set(e,t),this.updateAccessOrder(e);else{if(this.cache.size>=this.maxSize){const r=this.accessOrder.shift();r!==void 0&&this.cache.delete(r)}this.cache.set(e,t),this.accessOrder.push(e)}}has(e){return this.cache.has(e)}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}getStats(){return{size:this.cache.size,maxSize:this.maxSize}}}class Ie{graph;constructor(){this.graph=new Map}addDependency(e,t){this.graph.has(e)||this.graph.set(e,new Set),this.graph.get(e).add(t)}hasCycle(e){if(e.length===0)return!1;const t=new Set,r=new Set,s=i=>{t.add(i),r.add(i);const o=this.graph.get(i);if(o){for(const a of o)if(t.has(a)){if(r.has(a))return!0}else if(s(a))return!0}return r.delete(i),!1};for(let i=0;i<e.length-1;i++){const o=e[i],a=e[i+1];o&&a&&this.addDependency(o,a)}for(const i of e)if(!t.has(i)&&s(i))return!0;return!1}clear(){this.graph.clear()}}class L{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new Se(e),this.circularRefDetector=new Ie}parse(e){if(this.parseCache.has(e))return this.cacheHits++,this.parseCache.get(e);this.cacheMisses++;let t,r;const s=e.includes("."),i=e.includes("["),o=s||i;if(o)if(r=e.split(/[.[]/)[0],i){const u=e.indexOf("]");if(u>-1){const c=e.indexOf(".",u+1);c>-1?t=e.substring(c+1):t=void 0}else s&&(t=e.substring(e.indexOf(".")+1))}else s&&(t=e.substring(e.indexOf(".")+1));const a={attribute:e,isDeepQuery:o};return r&&(a.reference=r),typeof t<"u"&&t!==""&&(a.referenceAttribute=t),this.parseCache.set(e,a),a}detectCircular(e){return e.length===0?!1:new Set(e).size!==e.length?!0:this.circularRefDetector.hasCycle(e)}validatePath(e,t=10){const r=[];if(!e||e.trim().length===0)return r.push("Attribute path cannot be empty"),{valid:!1,errors:r};(e.startsWith(".")||e.endsWith("."))&&r.push(`Invalid path: Leading or trailing dots are not allowed: ${e}`),e.includes("..")&&r.push(`Invalid path: Consecutive dots are not allowed: ${e}`);const s=(e.match(/\[/g)||[]).length,i=(e.match(/]/g)||[]).length;s!==i&&r.push(`Invalid bracket notation: Mismatched brackets in ${e}`),e.includes("[]")&&r.push(`Invalid bracket notation: Empty brackets not allowed: ${e}`);const o=/\[([^\]]+)\]/g;let a;for(;(a=o.exec(e))!==null;){const f=a[1];f&&f!=="*"&&!/^\d+$/.test(f)&&r.push(`Invalid bracket content: Must be a number or '*', got '${f}' in ${e}`)}const u=(e.match(/\./g)||[]).length+1;u>t&&r.push(`Path too deep: Maximum depth is ${t}, got ${u} in ${e}`);const c=e.match(/[^a-zA-Z0-9._[\]*-]/g);return c&&r.push(`Invalid characters in path: ${c.join(", ")} in ${e}`),{valid:r.length===0,errors:r.length>0?r:void 0}}clearCache(){this.parseCache.clear(),this.cacheHits=0,this.cacheMisses=0}clearCircularDetector(){this.circularRefDetector.clear()}getCacheStats(){const e=this.parseCache.getStats(),t=this.cacheHits+this.cacheMisses,r=t>0?this.cacheHits/t:0;return{...e,hits:this.cacheHits,misses:this.cacheMisses,hitRate:r}}getPathSegments(e){return e.replace(/\[[^\]]+\]/g,"").split(".").filter(r=>r.length>0)}getPathDepth(e){return this.getPathSegments(e).length}}const m=new L;function w(n,e){if(e.includes("[*]")){const i=e.indexOf("[*]"),o=e.substring(0,i),a=e.substring(i+3),u=o?p.get(n,o):n;if(!Array.isArray(u))return[];const c=[];for(const f of u)!a||a===""?f!==void 0&&c.push(f):a.startsWith(".")&&c.push(...w(f,a.slice(1)));return c}const t=e.split(".");let r=[n];for(const i of t){const o=[];for(const a of r)if(a!=null)if(Array.isArray(a))for(const u of a){if(u==null)continue;const c=u[i];c!==void 0&&o.push(c)}else{const u=a[i];u!==void 0&&o.push(u)}if(r=o,r.length===0)return[]}const s=[];for(const i of r)if(Array.isArray(i))for(const o of i)o!==void 0&&s.push(o);else i!==void 0&&s.push(i);return s}function K(n){let e=0;for(let t of n){const r=t.toString().split(".")[1];r&&(e=Math.max(e,r.length))}return Math.pow(10,e)}function R(n,e,t){return(n*t+e*t)/t}function Qe(n,e,t){return n*t/(e*t)}const Q=(n,e,t,r)=>{if(!r)throw new Error("Attribute not found");const s={attribute:r,types:n.types};let i;(s.types.includes("sum")||s.types.includes("avg"))&&(i=Ne(r,e));let o;return(s.types.includes("min")||s.types.includes("max"))&&(o=Ee(r,e)),n.types.forEach(a=>{a==="sum"?s.sum=i?.sum:a==="avg"?s.avg=i?.average:a==="count"?s.count=Ke(r,e):a==="min"?s.min=o&&o[0]:a==="max"?s.max=o&&o[1]:a==="distinct"?s.distinct=V(n,e,t):a==="group"&&(s.group=Me(n,e))}),s},Ke=(n,e)=>{const r=m.parse(n).isDeepQuery;let s=0;for(const i of e.values())if(i)if(r)s+=w(i,n).filter(o=>o!=null).length;else{const o=i[n];if(o==null)continue;Array.isArray(o)?s+=o.filter(a=>a!=null).length:s++}return s},Ee=(n,e)=>{let t,r;const i=m.parse(n).isDeepQuery;for(const o of e.values()){if(!o)continue;let a;if(i)a=w(o,n);else{const u=o[n];u===void 0?a=[]:Array.isArray(u)?a=u.filter(c=>c!==void 0):a=[u]}for(const u of a)u==null||typeof u=="object"||((t===void 0||u<t)&&(t=u),(r===void 0||u>r)&&(r=u))}if(!(t===void 0||r===void 0))return[t,r]},Me=(n,e)=>{const t=[];n.groupOptions?.groups?.forEach(o=>{t.push({option:o,count:0,keys:[]})});const r={option:{value:["$dcupl_not_found"]},count:0,keys:[]},i=m.parse(n.attribute).isDeepQuery;for(const o of e.values()){let a;i?a=w(o,n.attribute):a=[o[n.attribute]];let u=!1;for(const c of a)for(const f of t)(typeof f.option.value<"u"&&f.option.value.includes(c)||typeof f.option.from<"u"&&f.option.from<c&&typeof f.option.to<"u"&&f.option.to>c)&&(f.keys.includes(o.key)||(f.count++,f.keys.push(o.key)),u=!0);!u&&n?.groupOptions?.calculateNotFound&&(r.count++,r.keys.push(o.key))}return n?.groupOptions?.calculateNotFound&&t.push(r),t},Ne=(n,e)=>{let t=0,r=0;const i=m.parse(n).isDeepQuery;for(const a of e.values()){if(!a)continue;let u;if(i)u=w(a,n);else{const c=a[n];c===void 0?u=[]:Array.isArray(c)?u=c:u=[c]}for(const c of u)if(Array.isArray(c))for(const f of c)typeof f=="number"&&(t=R(t,f,K([t,f])),r++);else typeof c=="number"&&(t=R(t,c,K([t,c])),r++)}return r===0?void 0:{average:Qe(t,r,K([t,r])),count:r,sum:t}},V=(n,e,t)=>{const r=[];for(const[s,i]of t)if(!(n.excludeUndefineds&&typeof s>"u")&&Array.from(i).find(o=>e.has(o))){const o={value:s,count:i.size};if(n.distinctOptions?.skipKeys||(o.keys=Array.from(i)),r.push(o),n.distinctOptions?.limit&&r.length>=n.distinctOptions.limit)break}return r};class b extends Error{query;constructor(e,t){const r=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(r),this.query=t,this.name="DcuplQueryError"}}class C{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=p.cloneDeep(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||m}init(e){this._initOptions=p.cloneDeep(e),this.currentQuery=p.cloneDeep(this._defaultQueryOptions),this.currentQuery.modelKey=e.modelKey,"queries"in e&&Array.isArray(e.queries)&&(e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&(this.currentQuery.queries=p.cloneDeep(e.queries)),e.count!==void 0&&(this.currentQuery.count=e.count),e.start!==void 0&&(this.currentQuery.start=e.start),e.sort&&(this.currentQuery.sort=e.sort),e.projection&&(this.currentQuery.projection=e.projection))}reset(){return this.init(this._initOptions),this.getQuery()}isQuery(e){return"attribute"in e}isQueryGroup(e){return"groupKey"in e}isRootQueryGroup(e){return this.isQueryGroup(e)&&e.groupKey==="root"}getQueryGroup(e){return this.currentQuery.queries.find(t=>this.isQueryGroup(t)&&t.groupKey===e)}getQuery(){return p.cloneDeep(this.currentQuery)}hasQueryGroup(e){return this.currentQuery.queries.some(t=>this.isQueryGroup(t)&&t.groupKey===e)}has(e){if(e.groupKey&&e.queryKey){const t=this.getQueryGroup(e.groupKey);if(t)return t.queries.some(r=>this.isQuery(r)&&r.queryKey===e.queryKey)}else if(e.groupKey)return this.hasQueryGroup(e.groupKey);return!1}validate(e){const t=e.queries.map(s=>this.validateQuery(s));return{valid:p.every(t,s=>s.valid),errors:t.map(s=>s.errors).flat()}}applyOptions(e,t="update"){return t==="set"?(this.currentQuery.count=e.count,this.currentQuery.start=e.start,this.currentQuery.sort=e.sort,this.currentQuery.projection=e.projection):(typeof e?.sort<"u"&&(this.currentQuery.sort=e.sort),typeof e?.count<"u"&&(this.currentQuery.count=e.count),typeof e?.start<"u"&&(this.currentQuery.start=e?.start),typeof e?.projection<"u"&&(this.currentQuery.projection=e?.projection)),this.getQuery()}applyQuery(e,t,r){if(r||(r=this.currentQuery),Array.isArray(e))for(const s of e)this.applyQuery(s,t,r);else if(this.isRootQueryGroup(e))e.groupType&&(r.groupType=e.groupType),t?.mode==="set"?r.queries=e.queries:r.queries=[...r.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const s=r.queries.findIndex(i=>this.isQueryGroup(i)&&i.groupKey===e.attribute);if(s>-1){const i=r.queries[s];t?.mode==="set"?i.queries=[e]:i.queries.push(e)}else r.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const s=r.queries.findIndex(i=>this.isQueryGroup(i)&&i.groupKey===e.groupKey);if(s>-1){const i=r.queries[s];e.groupType&&(i.groupType=e.groupType),t?.mode==="set"?r.queries[s]=e:i.queries=[...i.queries,...e.queries]}else r.queries.push({groupKey:e.groupKey,groupType:e.groupType||"or",queries:e.queries})}return r}removeAllQueries(){return this.currentQuery.queries=[],this.getQuery()}removeQuery(e,t){if(t||(t=this.currentQuery),this.isQuery(e)){const r=t.queries.findIndex(s=>this.isQueryGroup(s)&&s.groupKey===e.attribute);if(r>-1){const s=t.queries[r],i=p.findIndex(s.queries,e);i>-1&&s.queries.splice(i,1),s.queries.length===0&&t.queries.splice(r,1)}}else if(this.isQueryGroup(e)){const r=t.queries.findIndex(s=>this.isQueryGroup(s)&&s.groupKey===e.groupKey);if(r>-1)if(!e.queries)t.queries.splice(r,1);else{const s=t.queries[r];for(const i of e.queries){const o=p.findIndex(s.queries,i);o>-1&&s.queries.splice(o,1)}s.queries.length===0&&t.queries.splice(r,1)}}return t}validateQuery(e){const t=[];if(this.isQuery(e))return e.attribute||t.push(new b("Missing attribute",e)),e.operator||t.push(new b("Missing operator",e)),typeof e.value>"u"&&t.push(new b("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new b("find operator cannot have array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const i=e.queries.map(o=>this.validateQuery(o)).filter(o=>!o.valid).map(o=>o.errors).flat();return i.length>0?{valid:!1,errors:i}:{valid:!0}}return t.push(new b("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],r=new Set,s=i=>{for(const o of i)this.isQuery(o)?o.attribute&&!r.has(o.attribute)&&(t.push(o.attribute),r.add(o.attribute)):this.isQueryGroup(o)&&s(o.queries)};return s(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],r=new Set,s=i=>{for(const o of i)if(this.isQuery(o)){if(o.attribute&&!r.has(o.attribute)){const a=this.getQueryAttributeForString(o.attribute);t.push(a),r.add(o.attribute)}}else this.isQueryGroup(o)&&s(o.queries)};return s(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(r=>{t[r]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(r=>{if(r.isDeepQuery){if(r.reference)if(r.referenceAttribute&&r.referenceAttribute.length>0){t[r.reference]||(t[r.reference]={$:!0});const s=this.deepQueryService.parse(r.referenceAttribute);if(s.isDeepQuery&&r.reference){const i=this.getProjectionForAttributeEntries([s]);Object.keys(i).forEach(o=>{o!=="$"&&r.reference&&(t[r.reference][o]=i[o])})}else r.reference&&(t[r.reference][r.referenceAttribute]=!0)}else t[r.reference]=!0}else t[r.attribute]=!0}),t}getAttributeNames(e){return this.getQueryAttributes(e)}getAttributeDetails(e){return this.extractQueryAttributes(e||this.currentQuery)}getCurrentAttributeNames(){return this.getAttributeNames(this.currentQuery)}getCurrentAttributeDetails(){return this.getAttributeDetails(this.currentQuery)}addCondition(e){return this.applyQuery(e,{mode:"add"})}addGroup(e){return this.applyQuery(e,{mode:"add"})}setCondition(e){return this.applyQuery(e,{mode:"set"})}setGroup(e){return this.applyQuery(e,{mode:"set"})}mergeQuery(e){if(e.queries&&Array.isArray(e.queries))for(const t of e.queries)this.applyQuery(t,{mode:"add"});return this.currentQuery}replaceQuery(e){return this.currentQuery.queries=[],e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&Array.isArray(e.queries)&&(this.currentQuery.queries=e.queries),this.currentQuery}clear(){return this.reset()}clearConditions(){return this.removeAllQueries()}getCurrentQuery(){return this.getQuery()}isEmpty(){return this.currentQuery.queries.length===0}hasCondition(e){const t=r=>{for(const s of r)if(this.isQuery(s)){let i=!0;for(const o in e)if(s[o]!==e[o]){i=!1;break}if(i)return!0}else if(this.isQueryGroup(s)&&t(s.queries))return!0;return!1};return t(this.currentQuery.queries)}hasGroup(e){return this.hasQueryGroup(e)}getUsedAttributes(){return this.getAttributeNames()}getDeepQueryAttributes(){return this.getAttributeDetails().filter(t=>t.isDeepQuery)}getGroups(){return this.currentQuery.queries.filter(e=>this.isQueryGroup(e))}getTopLevelConditions(){return this.currentQuery.queries.filter(e=>this.isQuery(e))}getGroup(e){return this.getQueryGroup(e)}getConditionCount(){const e=t=>{let r=0;for(const s of t)this.isQuery(s)?r++:this.isQueryGroup(s)&&(r+=e(s.queries));return r};return e(this.currentQuery.queries)}}const N=new C;function ke(n,e,t,r,s,i,o){const a=N.removeQuery({groupKey:s},p.cloneDeep(r)),u=o.queryData(n,a,!1,i),c=e?[...e.keys()]:[],f=new Set(c),l=i.get(s);if(!t.excludeUnresolved)for(const h of l.keys())f.add(h);if(t.excludeUndefineds?f.delete(void 0):f.add(void 0),t.sort){const h=[];for(const v of f.values())h.push(F(v,l,u,e,s,r,!0));const y=t.excludeZeros?h.filter(v=>v.size>0):h;return y.sort(Ce(t.sort)),t.count?y.slice(0,t.count):y}const d=[];for(const h of f.values()){const y=F(h,l,u,e,s,r,!!t?.calculateFacets);if(!(t?.excludeZeros&&y.size===0)){if(t?.count&&d.length===t?.count)return d;d.push(y)}}return d}function F(n,e,t,r,s,i,o){const a=new Map,u=e.get(n)||new Set;for(const c of u){const f=t.get(c);if(f&&(a.set(c,f),!o))break}return{key:String(n),value:n,selected:Oe(s,n,i),enabled:a.size>0,size:a.size,entry:r.get(n),resultKeys:Array.from(a.keys())}}function D(n,e){if(n===void 0&&e===void 0)return 0;if(n===void 0)return 1;if(e===void 0)return-1;const t=typeof n,r=typeof e;if(t!==r)return t<r?-1:1;if(t==="number")return n-e;if(t==="string")return n.localeCompare(e);const s=String(n),i=String(e);return s<i?-1:s>i?1:0}function Ce(n){switch(n){case"size-desc":return(e,t)=>t.size-e.size||D(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||D(e.value,t.value);case"value-asc":return(e,t)=>D(e.value,t.value);case"value-desc":return(e,t)=>e.value===void 0&&t.value===void 0?0:e.value===void 0?1:t.value===void 0?-1:-D(e.value,t.value)}}const Oe=(n,e,t)=>{const r=t.queries.findIndex(s=>N.isQueryGroup(s)&&s.groupKey===n);return r>-1?!!t.queries[r].queries.find(i=>{if(N.isQuery(i)){const o=i.value?.key||i.value;return i.attribute===n&&o===e}return!1}):!1};class U{indexMap=new Map;dataMap=new Map;indexMetadata=new Map;constructor(){}reset(e){e?(this.indexMap.delete(e),this.dataMap.delete(e),this.indexMetadata.delete(e)):(this.indexMap.clear(),this.dataMap.clear(),this.indexMetadata.clear())}fillDataMap(e,t){let r=this.dataMap.get(e);r||(r=new Map,this.dataMap.set(e,r));for(const s of t){let i;if(typeof s=="object"&&s&&s.key)i=s.key;else if(Array.isArray(s)){for(const a of s)this.fillDataMap(e,[a]);return}else s instanceof Date?i=s.toISOString():i=s;let o=r.get(i);o||(o={key:i},this.dataMap.get(e)?.set(i,o))}}fillInverseIndex(e,t,r){if(!e||!t||!r||!Array.isArray(r))return;const s=this.indexMap.get(e)||new Map;for(const i of r){let o;if(typeof i=="object"&&i&&i.key)o=i.key;else if(Array.isArray(i)){for(const u of i)this.fillInverseIndex(e,t,[u]);return}else i instanceof Date?o=i.toISOString():o=i;let a=s.get(o);a||(a=new Set,s.set(o,a)),a.add(t)}this.indexMap.set(e,s)}getIndex(e,t){const r=this.getIndexName(e,t);return this.indexMap.get(r)}getData(e,t){const r=this.getIndexName(e,t);return this.dataMap.get(r)}getOrCreateIndex(e,t,r){const s=this.getIndexName(e,r);let i=this.getIndex(s);const o=this.indexMetadata.get(s);if(o)o.lastAccessedAt=Date.now();else if(!i){const u=m.parse(e).isDeepQuery??!1;this.indexMetadata.set(s,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:r,type:u?"deep":"shallow"})}if(!i){this.reset(s),this.indexMap.set(s,new Map);const u=m.parse(e).isDeepQuery;for(const c of t.values()){let f;u?(f=w(c,e),f.length===0&&(f=[void 0])):f=[c[e]],this.fillInverseIndex(s,c.key,f),this.fillDataMap(s,f)}i=this.getIndex(s)||new Map}return i}getIndexName(e,t){return t?e+"_"+I(t):e}removeFromInverseIndex(e,t,r){const s=this.indexMap.get(e);if(s)for(const i of r){let o;if(typeof i=="object"&&i&&i.key)o=i.key;else if(Array.isArray(i)){for(const u of i)this.removeFromInverseIndex(e,t,[u]);return}else i instanceof Date?o=i.toISOString():o=i;const a=s.get(o);a&&(a.delete(t),a.size===0&&s.delete(o))}}updateInverseIndex(e,t,r,s){this.removeFromInverseIndex(e,t,r),this.fillInverseIndex(e,t,s)}removeFromDataMap(e,t){const r=this.dataMap.get(e);if(r)for(const s of t){let i;if(typeof s=="object"&&s&&s.key)i=s.key;else if(Array.isArray(s)){for(const o of s)this.removeFromDataMap(e,[o]);return}else s instanceof Date?i=s.toISOString():i=s;r.delete(i)}}updateDataMap(e,t,r){this.removeFromDataMap(e,t),this.fillDataMap(e,r)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[r,s]of t)s.delete(e)&&s.size===0&&t.delete(r);for(const t of this.dataMap.values())t.has(e)&&t.delete(e)}resetAttributes(e){for(const t of e)this.reset(t)}isDeepQueryIndex(e){const t=e.includes("_")?e.split("_")[0]:e;try{return m.parse(t).isDeepQuery??!1}catch{return!1}}getDeepIndexKeys(){const e=[];for(const t of this.indexMap.keys())this.isDeepQueryIndex(t)&&e.push(t);return e}resetAllDeepIndices(){const e=this.getDeepIndexKeys();for(const t of e)this.indexMap.delete(t),this.dataMap.delete(t)}getIndexCount(){let e=0,t=0;for(const r of this.indexMap.keys())this.isDeepQueryIndex(r)?t++:e++;return{shallow:e,deep:t,total:e+t}}cleanupStaleIndices(e=300*1e3){const t=Date.now();let r=0;for(const[s,i]of this.indexMetadata)t-i.lastAccessedAt>e&&(this.reset(s),r++);return r}getStats(){const e=this.getIndexCount(),t=Date.now();let r=0,s=0;for(const o of this.indexMetadata.values()){const a=t-o.createdAt;r+=a,a>s&&(s=a)}const i=this.indexMetadata.size>0?r/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:s,avgAge:i}}}const x="__";function O(n,e,t={key:"root"},r="root",s=new U,i){const o=i||n;for(const a of e.columns)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,o));for(const a of e.rows)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,o));for(const a of e.values)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,o));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=$e(n,e.rows[0],e,s,r,i);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=H(n,e.columns[0],e,s,r,i);t.columns.push(a)}if(t.key==="root")for(const a of e.values){if(t.values=t.values||[],r==="root"&&e.options?.calculateTotals===!1)continue;const u=Q(a,n,s.getIndex(a.attribute),a.attribute);t.values.push(u)}return t}function $e(n,e,t,r,s="",i){const o={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return o;for(const[u,c]of a.entries()){const f={key:u,value:u},l=new Map;for(const d of c)n.has(d)&&l.set(d,n.get(d));if(l.size){for(const d of t.values){if(f.values=f.values||[],s==="root"&&e?.calculateTotals===!1)continue;const h=Q(d,l,r.getIndex(d.attribute),d.attribute);f.values.push(h)}if(o.rows=o.rows||[],o.rows.push(f),t.rows.length>1){const d={...t,rows:t.rows.slice(1)};O(l,d,f,s+x+e.attribute+x+u,r,i)}else if(t.columns)for(const d of t.columns){f.columns=f.columns||[];const h=H(l,d,t,r,s+x+e.attribute+x+u,i);f.columns.push(h)}}}return o}function H(n,e,t,r,s="",i){const o={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return o;for(const[u,c]of a.entries()){const f={key:u,value:u},l=new Map;for(const d of c)n.has(d)&&l.set(d,n.get(d));if(l.size){for(const d of t.values){if(f.values=f.values||[],s==="root"&&e?.calculateTotals===!1)continue;const h=Q(d,l,r.getIndex(d.attribute),d.attribute);f.values.push(h)}if(o.columns=o.columns||[],o.columns.push(f),t.columns.length>1){const d={...t,columns:t.columns.slice(1)};O(l,d,f,s+x+e.attribute+x+u,r,i)}}}return o}const qe=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,Re=/^-?\d+$/,Fe=/^-?\d+\.\d+$/,Te=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,J=n=>n==="true"||n==="false"?"boolean":Re.test(n)?"int":Fe.test(n)?"float":qe.test(n)&&!Number.isNaN(Date.parse(n))?"date":"string",X=n=>Te.test(n),_e=n=>n==null||n==="",Pe=n=>{const e=[...n];return e.length<=1?{type:e[0]??"any",conflict:!1}:e.every(t=>t==="int"||t==="float")?{type:"float",conflict:!1}:{type:"any",conflict:!0}},Z=(n,e={})=>{const r=e.deep??(e.sampleSize!==void 0&&e.sampleSize>1)?e.sampleSize??1/0:1,s=e.coerceStrings??!0,i=new Map,o=[],a=Math.min(n.length,r);for(let f=0;f<a;f++){const l=n[f];if(l)for(const[d,h]of Object.entries(l)){let y=i.get(d);if(y||(y={observed:new Set,empty:0,scanned:0},i.set(d,y),o.push(d)),y.scanned++,_e(h)){y.empty++;continue}let v;typeof h=="string"&&s?(v=J(h),v==="string"&&!y.hint&&X(h)&&(y.hint="column looks date-like (non-ISO) — review manually")):v=te(h),y.observed.add(v)}}const u=[],c=[];for(const f of o){const l=i.get(f),{type:d,conflict:h}=Pe(l.observed.size?l.observed:new Set(["string"]));u.push({key:f,type:d}),c.push({column:f,inferredType:d,observedTypes:[...l.observed].sort(),emptyRate:l.scanned===0?0:l.empty/l.scanned,conflict:h,hint:l.hint})}return{properties:u,diagnostics:c}},Ge=(n,e=!1)=>Z(n,typeof e=="boolean"?{deep:e}:e).properties,Y=n=>Number(n)===n&&n%1===0,ee=n=>Number(n)===n&&n%1!==0,te=n=>{switch(typeof n){case"string":return"string";case"number":return Y(n)?"int":ee(n)?"float":"any";case"boolean":return"boolean";case"object":return j(n)?"date":"json";default:return"any"}},Be=(n,e)=>{const t=B(n.text||""),r=e?.attributeKey||n.filterKey;let s;const i=e?.comparisonType||"containsIgnoreCase";return i==="containsIgnoreCase"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["lowercase"]}}]}:i==="containsIgnoreCaseAndWhitespace"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["removeWhitespace","lowercase"]}}]}:i==="contains"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:`/${t}/`,operator:"find"}]}:i==="equal"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:n.text,operator:"eq"}]}:i==="equalIgnoreCase"&&(s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:n.text,operator:"eq",options:{transform:["lowercase"]}}]}),s},ze=(n,e)=>{const t=e?.attributeKey||n.filterKey;return{groupKey:n.filterKey,queries:[{queryKey:n.value,attribute:t,value:n.value,operator:"eq"}]}},je=(n,e)=>{const t=e?.attributeKey||n.filterKey,r={groupKey:n.filterKey,queries:[]};return typeof n.eq<"u"&&(r.groupType="or",Array.isArray(n.eq)?n.eq.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq"})}):r.queries.push({attribute:t,value:n.eq,operator:"eq"})),typeof n.ne<"u"&&(r.groupType="and",Array.isArray(n.ne)?n.ne.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq",options:{invert:!0}})}):r.queries.push({attribute:t,value:n.ne,operator:"eq",options:{invert:!0}})),typeof n.gt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.gt,operator:"gt"})),typeof n.lt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.lt,operator:"lt"})),typeof n.gte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.gte,operator:"gte"})),typeof n.lte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.lte,operator:"lte"})),r},We=(n,e)=>{const t=e?.attributeKey||n.filterKey,r={groupKey:n.filterKey,queries:[]};return n.itemKeys.forEach(s=>{r.queries.push({queryKey:s,attribute:t,value:{key:s},operator:"eq"})}),r},Le=n=>!(typeof n.modelKey!="string"||!Array.isArray(n.queries));class Ve{constructor(e,t,r){this.scriptController=e,this.globalItemService=t,this.modelParser=r}registeredCustomOperator=new Map;queryBuilder=new C;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(r=>this.transformValue(r,t));if(typeof e!="string")return e;for(const r of t)r==="lowercase"?e=e.toLowerCase():r==="trim"?e=e.trim():r==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let r,s=e.value;const i=e.options?.arrayValueHandling||"some";if(Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(s=this.transformValue(s,e.options.transform)),e.attribute.includes(".")||e.attribute.includes("[")?r=p.get(t,e.attribute):r=t[e.attribute],Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(r=this.transformValue(r,e.options.transform)),(typeof r>"u"||r===null)&&!["typeof","isTruthy","eq"].includes(e.operator))return!1;switch(e.operator){case"eq":return e.options?.invert?!p.isEqual(r,s):p.isEqual(r,s);case"find":return e.options?.invert?!this.queryFind(r,s,i):this.queryFind(r,s,i);case"lt":return Array.isArray(r)?i==="some"?r.some(o=>o<s):r.every(o=>o<s):r<s;case"gt":return Array.isArray(r)?i==="some"?r.some(o=>o>s):r.every(o=>o>s):r>s;case"lte":return Array.isArray(r)?i==="some"?r.some(o=>o<=s):r.every(o=>o<=s):r<=s;case"gte":return Array.isArray(r)?i==="some"?r.some(o=>o>=s):r.every(o=>o>=s):r>=s;case"typeof":return e.options?.invert?typeof r!==s:Array.isArray(r)?i==="some"?r.some(o=>typeof o===s):r.every(o=>typeof o===s):typeof r===s;case"isTruthy":return s===!0?Array.isArray(r)?i==="some"?r.some(o=>typeof!!o):r.every(o=>typeof!!o):!!r:!r;case"size":return typeof r=="string"?r.length===s:p.size(r)===s;default:if(this.scriptController.hasScript(e.operator))return this.scriptController.executeScript(e.operator,"operator",{query:e,item:t});if(this.registeredCustomOperator.has(e.operator)){const o=this.registeredCustomOperator.get(e.operator);if(typeof o=="function")return o(e,t)}}return!1}evaluateEqOperator(e,t,r,s){const i=new Map,o=s.get(t.attribute);if(o){let a;if(typeof t.value=="string"?a=t.value:t.value?.key&&Object.keys(t.value).length===1&&(a=t.value.key),typeof a<"u"){const u=o.get(a);if(u)if(u.forEach(c=>{r.has(c)&&i.set(c,r.get(c))}),t.options?.invert){const c=p.differenceBy(Array.from(r.values()),Array.from(i.values()),"key"),f=new Map;return c.forEach(l=>{f.set(l.key,l)}),f}else return i}}for(let[a,u]of r){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(f=>f.isDeepQuery)){const f=this.queryBuilder.getProjectionForAttributeEntries(c.filter(l=>l.isDeepQuery));u=this.globalItemService.getProjectedData(f,this.modelParser.models.get(e.modelKey),u)}this.evaluateQuery(t,u)&&i.set(a,u)}return i}equalRegexFn(e,t){if(typeof t=="string"&&p.startsWith(t,"/")&&p.endsWith(t,"/"))try{return new RegExp(t.slice(1,-1)).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(r=>p.isEqualWith(r,t,this.equalRegexFn)):typeof t=="object"?p.isMatch(e,t):e===t}queryFind(e,t,r){return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?r==="some"?e.some(s=>p.isEqualWith(s,t,this.equalRegexFn)):e.every(s=>p.isEqualWith(s,t,this.equalRegexFn)):!!p.find(e,t):p.isEqualWith(e,t,this.equalRegexFn)}validateQuery(e){if(this.queryBuilder.isQuery(e)){if(!e.attribute||!e.operator)throw new Error("invalid query - missing attribute or operator");if(e.operator==="find"&&Array.isArray(e.value))throw new Error("invalid query - find operator cannot have array value");return!0}else{if(this.queryBuilder.isQueryGroup(e))return p.every(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,r,s){const i=new Map;if(t.attribute.includes("[*]")){const o=t.options?.invert===!0,a=new Set;for(let u of r.values()){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(d=>d.isDeepQuery)){const d=this.queryBuilder.getProjectionForAttributeEntries(c.filter(h=>h.isDeepQuery));u=this.globalItemService.getProjectedData(d,this.modelParser.models.get(e.modelKey),u)}const f=this.handleArrayStarQuery(t,u);let l=!1;for(const d of f.queries){const h={...d,options:{...d.options,invert:!1}};if(this.evaluateQuery(h,u)){l=!0;break}}l&&(a.add(u.key),o||i.set(u.key,u))}if(o)for(const[u,c]of r)a.has(u)||i.set(u,c)}else{if(t.operator==="eq")return this.evaluateEqOperator(e,t,r,s);for(let[o,a]of r){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(c=>c.isDeepQuery)){const c=this.queryBuilder.getProjectionForAttributeEntries(u.filter(f=>f.isDeepQuery));a=this.globalItemService.getProjectedData(c,this.modelParser.models.get(e.modelKey),a)}this.evaluateQuery(t,a)&&i.set(o,a)}}return i}handleArrayStarQuery(e,t){const r=e.attribute.indexOf("[*]"),s={groupKey:e.queryKey||e.attribute+"[*]",groupType:"or",queries:[]};if(r!==-1){const i=e.attribute.substring(0,r),o=i.includes(".")?p.get(t,i):t[i];if(Array.isArray(o))for(let a=0;a<o.length;a++){const u=e.attribute.replace("[*]",`[${a}]`);s.queries.push({attribute:u,operator:e.operator,value:e.value,options:e.options})}}return s}evaluateQueryGroup(e,t,r,s,i){let o=new Map,a=r;if(!t.queries||t.queries?.length===0)return a;for(const u of t.queries){let c=new Map;if(this.queryBuilder.isQuery(u)?c=this.getEvaluatedQueryDataset(e,u,a,i):c=this.evaluateQueryGroup(e,u,a,s,i),o.size===0&&(o=c),t.groupType==="or")c.forEach(f=>{o.set(f.key,f)});else{const f=p.differenceBy(Array.from(o.values()),Array.from(c.values()),"key");for(const l of f)o.delete(l.key)}t.groupType==="and"?a=o:a=r}return o}queryData(e,t,r,s){const i=new Map(e);return t.queries.length===0?e:(t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,i,r,s))}}const re="k:",se="h:";function S(n,e=0){if(n.key)return`${re}${n.key}`;const t=I({type:n.type,url:n.rawUrl??n.url,model:n.model??"",occurrence:e});return`${se}${t}`}function Ue(n){const e=new Map,t=new Set;return n.map(r=>{const s=`${r.key??""}|${r.type}|${r.rawUrl??r.url}|${r.model??""}`;let i=e.get(s)??0,o=S(r,i);for(;t.has(o);)i+=1,o=r.key?`${S(r)}#${i}`:S(r,i);return e.set(s,i+1),t.add(o),o})}class He{scripts=new Map;scriptFunctions=new Map;constructor(){}keys(){return Array.from(this.scripts.keys())}setScript(e,t){this.scripts.set(e,t)}removeScript(e){this.scripts.delete(e)}getScript(e){return this.scripts.get(e)}hasScript(e){return this.scripts.has(e)}getScriptAsFn(e,t){if(this.scriptFunctions.has(e))return this.scriptFunctions.get(e);const r=this.getScript(e);if(!r)throw new Error(`Script ${e} not found`);const s=this.getWrapperScript(r),i=new Function("script_type",...t,s);return this.scriptFunctions.set(e,i),i}getWrapperScript(e){return`
|
|
2
2
|
"use strict";
|
|
3
3
|
${e}
|
|
4
|
-
`}executeScript(e,t,r){if(!this.getScript(e))throw new Error(`Script ${e} not found`);r.context||(r.context=r.options||{});const
|
|
4
|
+
`}executeScript(e,t,r){if(!this.getScript(e))throw new Error(`Script ${e} not found`);r.context||(r.context=r.options||{});const i=Object.keys(r),o=Object.values(r);return this.getScriptAsFn(e,i)(t,...o)}}const Je=(n,e)=>n?(e||(e={}),n.replace(/\$\{(.*?)\}/g,(t,r)=>p.get(e,r.trim(),""))):"",Xe=n=>{const e=new Set;return n.replace(/\$\{(.*?)\}/g,(r,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(r=>({name:r}))}},Ze=["any","Array<date>","Array<float>","Array<int>","Array<string>","boolean","date","float","int","json","string"],Ye=["int","float","Array<int>","Array<float>"],et=["date","Array<date>"],tt=["eq","find","gt","gte","lt","lte","typeof","isTruthy","size"];exports.AUTHORED_RESOURCE_ID_PREFIX=re;exports.AnalyticsController=ie;exports.AttributeDependencyGraph=oe;exports.CacheController=ae;exports.ChangeDetector=ye;exports.DERIVED_RESOURCE_ID_PREFIX=se;exports.DatePropertyTypes=et;exports.DcuplQueryBuilder=C;exports.DcuplQueryOperatorsAsArray=tt;exports.DeepQueryService=L;exports.DependencyGraph=T;exports.IndicesController=U;exports.Logger=g;exports.NumberPropertyTypes=Ye;exports.PropertyTypesAsArray=Ze;exports.QueryManager=Ve;exports.ScriptController=He;exports.clone=k;exports.coerceStringType=J;exports.compareVersions=z;exports.computeSuggestions=ve;exports.deepQueryService=m;exports.escapeRegExp=B;exports.evaluateTemplate=Je;exports.generateBooleanQuery=ze;exports.generateKey=G;exports.generateNumberAndDateQuery=je;exports.generateReferenceQuery=We;exports.generateTextQuery=Be;exports.getAggregation=Q;exports.getDateConstraintUid=fe;exports.getDcuplPropertyTypeForNativeType=te;exports.getDeepPathValues=w;exports.getDistinct=V;exports.getFacets=ke;exports.getFilterEntryId=ue;exports.getNumberConstraintUid=ce;exports.getPropertiesForData=Ge;exports.groupBy=de;exports.hasMinimumVersion=ge;exports.inferModel=Z;exports.isDateInstance=j;exports.isFloat=ee;exports.isInt=Y;exports.isValidDate=W;exports.isValidQueryStatement=Le;exports.isValidVersion=M;exports.logger=P;exports.looksDateLike=X;exports.parseDate=De;exports.parseTemplate=Xe;exports.perf=A;exports.pivot=O;exports.removeTrailingSlash=he;exports.resolveResourceId=S;exports.resolveResourceIds=Ue;exports.trigger=me;exports.unescapeRegExp=pe;exports.uniqBy=le;
|
|
5
5
|
//# sourceMappingURL=index.cjs.map
|