@kitelev/exocortex-cli 15.14.1 → 15.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +5 -5
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // @kitelev/exocortex-cli v15.14.1
2
+ // @kitelev/exocortex-cli v15.15.1
3
3
  // CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
4
4
  // License: MIT
5
5
 
@@ -257,7 +257,7 @@ Expecting `+ml.join(", ")+", got '"+(this.terminals_[Ze]||Ze)+"'":lp="Parse erro
257
257
  `;)n++;continue}if(e[n]==="{"){i++,n++;continue}if(e[n]==="}"){if(i--,i===0){let s=e.substring(t,n+1);return{content:s,length:s.length}}n++;continue}n++}if(i>0)throw new ps(`Unclosed LATERAL block at position ${t}`);return null}transformLateral(e){let t=e.indexOf("{");if(t===-1)throw new ps("LATERAL expression missing opening brace");let n=e.substring(t+1,e.length-1).trim();if(!n.toUpperCase().trim().startsWith("SELECT"))throw new ps("LATERAL block must contain a SELECT subquery");let a=n.toUpperCase().indexOf("SELECT")+6;for(;a<n.length&&/\s/.test(n[a]);)a++;let c=n.substring(a).toUpperCase();return c.startsWith("DISTINCT")?a+=8:c.startsWith("REDUCED")&&(a+=7),`{ ${n.substring(0,a)+` ?${r.LATERAL_MARKER}`+n.substring(a)} }`}isWordBoundary(e,t,n){let i=t>0?e[t-1]:"",s=t===0||!/[a-zA-Z0-9_]/.test(i),a=t+n<e.length?e[t+n]:"",c=t+n>=e.length||!/[a-zA-Z0-9_]/.test(a);return s&&c}};to.LateralTransformer=zf;zf.LATERAL_MARKER="__LATERAL_JOIN__";var ps=class extends Error{static{o(this,"LateralTransformerError")}constructor(e){super(`LATERAL transformation error: ${e}`),this.name="LateralTransformerError"}};to.LateralTransformerError=ps});var Cb=_(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.PrefixStarTransformerError=ms.PrefixStarTransformer=ms.WellKnownPrefixResolver=void 0;var Yf=class{static{o(this,"WellKnownPrefixResolver")}constructor(){this.wellKnownPrefixes=new Map;let e=new Map;e.set("schema","http://schema.org/"),this.wellKnownPrefixes.set("http://schema.org/",e);let t=new Map;t.set("foaf","http://xmlns.com/foaf/0.1/"),this.wellKnownPrefixes.set("http://xmlns.com/foaf/0.1/",t);let n=new Map;n.set("dc","http://purl.org/dc/elements/1.1/"),n.set("dcterms","http://purl.org/dc/terms/"),this.wellKnownPrefixes.set("http://purl.org/dc/elements/1.1/",n),this.wellKnownPrefixes.set("http://purl.org/dc/terms/",n);let i=new Map;i.set("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#"),i.set("rdfs","http://www.w3.org/2000/01/rdf-schema#"),this.wellKnownPrefixes.set("http://www.w3.org/1999/02/22-rdf-syntax-ns#",i),this.wellKnownPrefixes.set("http://www.w3.org/2000/01/rdf-schema#",i);let s=new Map;s.set("owl","http://www.w3.org/2002/07/owl#"),this.wellKnownPrefixes.set("http://www.w3.org/2002/07/owl#",s);let a=new Map;a.set("xsd","http://www.w3.org/2001/XMLSchema#"),this.wellKnownPrefixes.set("http://www.w3.org/2001/XMLSchema#",a);let c=new Map;c.set("skos","http://www.w3.org/2004/02/skos/core#"),this.wellKnownPrefixes.set("http://www.w3.org/2004/02/skos/core#",c);let u=new Map;u.set("prov","http://www.w3.org/ns/prov#"),this.wellKnownPrefixes.set("http://www.w3.org/ns/prov#",u);let l=new Map;l.set("geo","http://www.w3.org/2003/01/geo/wgs84_pos#"),this.wellKnownPrefixes.set("http://www.w3.org/2003/01/geo/wgs84_pos#",l);let f=new Map;f.set("dcat","http://www.w3.org/ns/dcat#"),this.wellKnownPrefixes.set("http://www.w3.org/ns/dcat#",f)}async resolve(e){let t=e.endsWith("#")||e.endsWith("/")?e:e+(e.includes("#")?"":"/"),n=this.wellKnownPrefixes.get(t);if(n)return n;let i=t.slice(0,-1),s=this.wellKnownPrefixes.get(i);return s||new Map}addVocabulary(e,t){this.wellKnownPrefixes.set(e,t)}};ms.WellKnownPrefixResolver=Yf;var W0=class{static{o(this,"PrefixStarTransformer")}constructor(e){this.resolver=e??new Yf}async transform(e){let t=this.findPrefixStarDeclarations(e);if(t.length===0)return e;let n=[],i=[];for(let a of t)try{let c=await this.resolver.resolve(a.uri);for(let[u,l]of c)n.push(`PREFIX ${u}: <${l}>`);if(c.size===0){let u=this.extractPrefixFromUri(a.uri);u&&n.push(`PREFIX ${u}: <${a.uri}>`)}}catch(c){let u=c instanceof Error?c.message:String(c);i.push(`Failed to resolve vocabulary ${a.uri}: ${u}`)}if(n.length===0&&i.length>0)throw new ro(i.join("; "));let s=e;for(let a=t.length-1;a>=0;a--){let c=t[a];s=s.substring(0,c.startPos)+s.substring(c.endPos)}return n.length>0&&(s=n.join(`
258
258
  `)+`
259
259
  `+s.trimStart()),s}findPrefixStarDeclarations(e){let t=[],n=e.toUpperCase(),i=0;for(;i<e.length;){if(e[i]==="'"||e[i]==='"'){let s=e[i];for(i++;i<e.length&&e[i]!==s;)e[i]==="\\"&&i++,i++;i++;continue}if(n.substring(i,i+6)==="PREFIX"){let s=i;for(i+=6;i<e.length&&/\s/.test(e[i]);)i++;if(e[i]==="*"){for(i++;i<e.length&&/\s/.test(e[i]);)i++;if(e[i]==="<"){i++;let a=i;for(;i<e.length&&e[i]!==">";)i++;if(e[i]===">"){let c=e.substring(a,i);i++;let u=this.findDeclarationEnd(e,i);t.push({uri:c,startPos:s,endPos:u}),i=u;continue}else throw new ro(`Unclosed IRI in PREFIX* declaration at position ${a}`)}else throw new ro(`Expected IRI after PREFIX* at position ${i}`)}else continue}i++}return t}findDeclarationEnd(e,t){let n=t;for(;n<e.length;){let i=e[n];if(i===`
260
- `)return n+1;let s=e.substring(n).toUpperCase();if(s.startsWith("PREFIX")||s.startsWith("BASE")||s.startsWith("SELECT")||s.startsWith("CONSTRUCT")||s.startsWith("DESCRIBE")||s.startsWith("ASK"))return n;if(/\s/.test(i)){n++;continue}break}return n}extractPrefixFromUri(e){let t=e.replace(/^https?:\/\//,"");t=t.replace(/\/$/,"").replace(/#$/,"");let n=t.split(/[/.#]+/).filter(Boolean);if(n.length===0)return null;let i=n[n.length-1];return/^(ontology|vocab|schema|ns|core)$/i.test(i)&&n.length>1?n[n.length-2].toLowerCase():i.toLowerCase().replace(/[^a-z0-9]/g,"")}};ms.PrefixStarTransformer=W0;var ro=class extends Error{static{o(this,"PrefixStarTransformerError")}constructor(e){super(`PREFIX* transformation error: ${e}`),this.name="PrefixStarTransformerError"}};ms.PrefixStarTransformerError=ro});var H0=_(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.DescribeOptionsTransformer=io.DescribeOptionsTransformerError=void 0;var Qf=class extends Error{static{o(this,"DescribeOptionsTransformerError")}constructor(e){super(e),this.name="DescribeOptionsTransformerError"}};io.DescribeOptionsTransformerError=Qf;var no=class r{static{o(this,"DescribeOptionsTransformer")}transform(e){if(!r.DESCRIBE_QUERY_PATTERN.test(e))return{query:e};let t=e,n={},i=!1,s=r.DEPTH_PATTERN.exec(e);if(s){let a=parseInt(s[1],10);if(a<0)throw new Qf(`DESCRIBE DEPTH must be a non-negative integer, got: ${a}`);n.depth=a,i=!0,r.DEPTH_PATTERN.lastIndex=0,t=t.replace(r.DEPTH_PATTERN,"")}return r.DEPTH_PATTERN.lastIndex=0,r.SYMMETRIC_PATTERN.test(e)&&(n.symmetric=!0,i=!0,r.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(r.SYMMETRIC_PATTERN,"")),r.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(/\s{2,}/g," ").trim(),{query:t,options:i?n:void 0}}hasDescribeOptions(e){let t=r.DEPTH_PATTERN.test(e);r.DEPTH_PATTERN.lastIndex=0;let n=r.SYMMETRIC_PATTERN.test(e);return r.SYMMETRIC_PATTERN.lastIndex=0,t||n}};io.DescribeOptionsTransformer=no;no.DEPTH_PATTERN=/\bDEPTH\s+(\d+)/gi;no.SYMMETRIC_PATTERN=/\bSYMMETRIC\b/gi;no.DESCRIBE_QUERY_PATTERN=/\bDESCRIBE\b/i});var Ib=_(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.DirectionalLangTagTransformerError=so.DirectionalLangTagTransformer=void 0;var Kf=class r{static{o(this,"DirectionalLangTagTransformer")}constructor(){this.directionMappings=new Map}transform(e){return this.directionMappings.clear(),e.replace(r.DIRECTIONAL_TAG_REGEX,(t,n,i,s,a)=>{let c=s.toLowerCase();return this.directionMappings.set(c,a),`${n}${i}${n}@${s}`})}getDirection(e){return this.directionMappings.get(e.toLowerCase())}getAllMappings(){return new Map(this.directionMappings)}hasDirectionalTags(e){return r.DIRECTIONAL_TAG_REGEX.lastIndex=0,r.DIRECTIONAL_TAG_REGEX.test(e)}clearMappings(){this.directionMappings.clear()}};so.DirectionalLangTagTransformer=Kf;Kf.DIRECTIONAL_TAG_REGEX=/(["'])((?:[^\\]|\\.)*?)\1@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)--(ltr|rtl)/g;var z0=class extends Error{static{o(this,"DirectionalLangTagTransformerError")}constructor(e){super(`Directional language tag transformation error: ${e}`),this.name="DirectionalLangTagTransformerError"}};so.DirectionalLangTagTransformerError=z0});var Ob=_(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.TripleTermTransformerError=oo.TripleTermTransformer=void 0;var Y0=class{static{o(this,"TripleTermTransformer")}transform(e){let t=e,n,i=0,s=100;do if(n=t,t=this.transformSinglePass(t),i++,i>s)throw new ao("Too many nested triple terms (max 100 iterations)");while(t!==n);return t}hasTripleTermSyntax(e){return this.findTripleTermPositions(e).length>0}transformSinglePass(e){let t=this.findTripleTermPositions(e);if(t.length===0)return e;let n=e;for(let i=t.length-1;i>=0;i--){let s=t[i],a=this.extractTripleTerm(n,s);if(a){let c=this.convertToStandardSyntax(a.content);n=n.substring(0,s)+c+n.substring(s+a.length)}}return n}findTripleTermPositions(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="'"){n=this.skipStringLiteral(e,n,"'");continue}if(e[n]==='"'){n=this.skipStringLiteral(e,n,'"');continue}if(e.substring(n,n+2)==="<<"&&this.isParenthesizedTripleTerm(e,n)){t.push(n),n+=2;continue}n++}return t}skipStringLiteral(e,t,n){let i=n.repeat(3);if(e.substring(t,t+3)===i){for(t+=3;t<e.length;){if(e.substring(t,t+3)===i)return t+3;e[t]==="\\"&&t++,t++}return t}for(t++;t<e.length&&e[t]!==n;)e[t]==="\\"&&t++,t++;return t+1}isParenthesizedTripleTerm(e,t){let n=t+2;for(;n<e.length&&/\s/.test(e[n]);)n++;return e[n]==="("}extractTripleTerm(e,t){let n=t+2;for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="(")return null;n++;let i=1;for(;n<e.length&&i>0;){if(e[n]==="'"||e[n]==='"'){n=this.skipStringLiteral(e,n,e[n]);continue}if(e.substring(n,n+2)==="<<"&&this.isParenthesizedTripleTerm(e,n)){for(n+=2;n<e.length&&/\s/.test(e[n]);)n++;e[n]==="("&&(i++,n++);continue}if(e.substring(n,n+2)==="<<"){n+=2;let s=1;for(;n<e.length&&s>0;){if(e[n]==="'"||e[n]==='"'){n=this.skipStringLiteral(e,n,e[n]);continue}if(e.substring(n,n+2)==="<<"){s++,n+=2;continue}if(e.substring(n,n+2)===">>"){s--,n+=2;continue}n++}continue}if(e[n]==="("){i++,n++;continue}if(e[n]===")"){let s=n+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e.substring(s,s+2)===">>"){if(i--,i===0){let a=e.substring(t,s+2);return{content:a,length:a.length}}n=s+2;continue}n++;continue}n++}if(i>0)throw new ao(`Unclosed triple term at position ${t}: missing )>>`);return null}convertToStandardSyntax(e){let t=e.match(/^<<\s*\(\s*([\s\S]*?)\s*\)\s*>>$/);if(!t)throw new ao(`Invalid triple term syntax: ${e.substring(0,50)}...`);return`<< ${t[1]} >>`}};oo.TripleTermTransformer=Y0;var ao=class extends Error{static{o(this,"TripleTermTransformerError")}constructor(e){super(`Triple term transformation error: ${e}`),this.name="TripleTermTransformerError"}};oo.TripleTermTransformerError=ao});var Fb=_(mn=>{"use strict";var NN=mn&&mn.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),LN=mn&&mn.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),MN=mn&&mn.__importStar||(function(){var r=o(function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&NN(t,e,n[i]);return LN(t,e),t}})();Object.defineProperty(mn,"__esModule",{value:!0});mn.SPARQLParser=mn.SPARQLParseError=void 0;var Pb=MN(xb()),Q0=q0(),K0=G0(),Db=Cb(),X0=H0(),kN=Ib(),J0=Ob(),Nt=class extends Error{static{o(this,"SPARQLParseError")}constructor(e,t,n,i){super(e,i?{cause:i}:void 0),this.name="SPARQLParseError",this.line=t,this.column=n}};mn.SPARQLParseError=Nt;var Z0=class{static{o(this,"SPARQLParser")}constructor(e){this.lastDirectionMappings=new Map,this.parser=new Pb.Parser({sparqlStar:!0}),this.generator=new Pb.Generator({sparqlStar:!0}),this.caseWhenTransformer=new Q0.CaseWhenTransformer,this.lateralTransformer=new K0.LateralTransformer,this.prefixStarTransformer=new Db.PrefixStarTransformer(e?.vocabularyResolver),this.describeOptionsTransformer=new X0.DescribeOptionsTransformer,this.directionalLangTagTransformer=new kN.DirectionalLangTagTransformer,this.tripleTermTransformer=new J0.TripleTermTransformer}parse(e){try{let t=this.describeOptionsTransformer.transform(e);this.lastDescribeOptions=t.options;let n=t.query;n=this.directionalLangTagTransformer.transform(n),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),n=this.lateralTransformer.transform(n),n=this.caseWhenTransformer.transform(n),n=this.tripleTermTransformer.transform(n);let i=this.parser.parse(n);return this.validateQuery(i),this.lastDescribeOptions&&this.isDescribeQuery(i)&&(i.describeOptions=this.lastDescribeOptions),i}catch(t){if(t instanceof X0.DescribeOptionsTransformerError)throw new Nt(t.message);if(t instanceof K0.LateralTransformerError)throw new Nt(t.message);if(t instanceof Q0.CaseWhenTransformerError)throw new Nt(t.message);if(t instanceof J0.TripleTermTransformerError)throw new Nt(t.message);if(t instanceof Error){let n=t.message.match(/line (\d+), column (\d+)/),i=n?parseInt(n[1],10):void 0,s=n?parseInt(n[2],10):void 0;throw new Nt(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}parseWithOptions(e){return{query:this.parse(e),describeOptions:this.lastDescribeOptions}}getLastDescribeOptions(){return this.lastDescribeOptions}async parseAsync(e){try{let t=this.describeOptionsTransformer.transform(e);this.lastDescribeOptions=t.options;let n=t.query;n=this.directionalLangTagTransformer.transform(n),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),n=await this.prefixStarTransformer.transform(n),n=this.lateralTransformer.transform(n),n=this.caseWhenTransformer.transform(n),n=this.tripleTermTransformer.transform(n);let i=this.parser.parse(n);return this.validateQuery(i),this.lastDescribeOptions&&this.isDescribeQuery(i)&&(i.describeOptions=this.lastDescribeOptions),i}catch(t){if(t instanceof X0.DescribeOptionsTransformerError)throw new Nt(t.message);if(t instanceof Db.PrefixStarTransformerError)throw new Nt(t.message);if(t instanceof K0.LateralTransformerError)throw new Nt(t.message);if(t instanceof Q0.CaseWhenTransformerError)throw new Nt(t.message);if(t instanceof J0.TripleTermTransformerError)throw new Nt(t.message);if(t instanceof Error){let n=t.message.match(/line (\d+), column (\d+)/),i=n?parseInt(n[1],10):void 0,s=n?parseInt(n[2],10):void 0;throw new Nt(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}async parseAsyncWithOptions(e){return{query:await this.parseAsync(e),describeOptions:this.lastDescribeOptions}}hasPrefixStar(e){return/PREFIX\s*\*/i.test(e)}hasLateral(e){return this.lateralTransformer.hasLateral(e)}hasDescribeOptions(e){return this.describeOptionsTransformer.hasDescribeOptions(e)}hasDirectionalLangTags(e){return this.directionalLangTagTransformer.hasDirectionalTags(e)}hasTripleTermSyntax(e){return this.tripleTermTransformer.hasTripleTermSyntax(e)}getLastDirectionMappings(){return new Map(this.lastDirectionMappings)}getDirectionForLanguage(e){return this.lastDirectionMappings.get(e.toLowerCase())}toString(e){try{return this.generator.stringify(e)}catch(t){throw t instanceof Error?new Nt(`Failed to serialize SPARQL query: ${t.message}`,void 0,void 0,t):t}}getQueryType(e){if("queryType"in e&&e.type==="query")return e.queryType;throw new Nt("Query does not have a valid queryType property")}isSelectQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="SELECT"}isConstructQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="CONSTRUCT"}isAskQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="ASK"}isDescribeQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="DESCRIBE"}isUpdateQuery(e){return e.type==="update"}isInsertDataOperation(e){return"updateType"in e&&e.updateType==="insert"}isDeleteDataOperation(e){return"updateType"in e&&e.updateType==="delete"}validateQuery(e){if(!e||typeof e!="object")throw new Nt("Invalid query: not an object");if(e.type!=="query"&&e.type!=="update")throw new Nt(`Invalid type: expected "query" or "update", got "${e.type}"`);if(e.type==="query"){let t=["SELECT","CONSTRUCT","ASK","DESCRIBE"];if(!t.includes(e.queryType))throw new Nt(`Invalid query type: expected one of ${t.join(", ")}, got "${e.queryType}"`)}}};mn.SPARQLParser=Z0});var Nb=_(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.AlgebraTranslator=co.AlgebraTranslatorError=void 0;var Rb=G0(),me=class extends Error{static{o(this,"AlgebraTranslatorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AlgebraTranslatorError"}};co.AlgebraTranslatorError=me;var ey=class{static{o(this,"AlgebraTranslator")}constructor(){this.directionMappings=new Map,this.aggregateCounter=0}setDirectionMappings(e){this.directionMappings=e}translate(e){if(e.type!=="query")throw new me("Only query operations are supported (not updates)");if(e.queryType==="SELECT")return this.translateSelect(e);if(e.queryType==="CONSTRUCT")return this.translateConstruct(e);if(e.queryType==="ASK")return this.translateAsk(e);if(e.queryType==="DESCRIBE")return this.translateDescribe(e);throw new me(`Query type ${e.queryType} not yet supported`)}translateSelect(e){let t;if(!e.where||e.where.length===0)throw new me("SELECT query must have WHERE clause");t=this.translateWhere(e.where),this.aggregateCounter=0;let n=new Map,i=this.extractAggregatesWithMapping(e.variables,n),s=this.extractGroupVariables(e.group);if((i.length>0||s.length>0)&&(t={type:"group",variables:s,aggregates:i,input:t}),e.variables&&e.variables.length>0){for(let c of e.variables){let u=c;if(u.expression&&u.variable){if(u.expression.type==="aggregate")continue;let l=this.transformExpressionWithAggregateVars(u.expression,n);t={type:"extend",variable:u.variable.value,expression:l,input:t}}}let a=e.variables.filter(c=>c.termType==="Variable"||c.variable).map(c=>c.termType==="Variable"?c.value:c.variable.value);a.length>0&&(t={type:"project",variables:a,input:t})}return e.distinct&&(t={type:"distinct",input:t}),e.reduced&&(t={type:"reduced",input:t}),e.order&&e.order.length>0&&(t={type:"orderby",comparators:e.order.map(a=>this.translateOrderComparator(a)),input:t}),(e.limit!==void 0||e.offset!==void 0)&&(t={type:"slice",limit:e.limit,offset:e.offset,input:t}),t}translateConstruct(e){let t=this.translateConstructTemplate(e.template??[]);if(!e.where||e.where.length===0)throw new me("CONSTRUCT query must have WHERE clause");let n=this.translateWhere(e.where);return{type:"construct",template:t,where:n}}translateConstructTemplate(e){return!e||!Array.isArray(e)?[]:e.map(t=>this.translateTriple(t))}translateAsk(e){return{type:"ask",where:e.where&&e.where.length>0?this.translateWhere(e.where):{type:"bgp",triples:[]}}}extractAggregatesWithMapping(e,t){if(!e)return[];let n=[];for(let i of e)!i.expression||!i.variable||(i.expression.type==="aggregate"?(n.push({variable:i.variable.value,expression:this.translateAggregateExpression(i.expression)}),t.set(i.expression,i.variable.value)):this.collectNestedAggregates(i.expression,n,t));return n}collectNestedAggregates(e,t,n){if(e){if(e.type==="aggregate"){let i=`__agg${this.aggregateCounter++}`;t.push({variable:i,expression:this.translateAggregateExpression(e)}),n.set(e,i)}else if(e.type==="operation"&&e.args)for(let i of e.args)this.collectNestedAggregates(i,t,n)}}transformExpressionWithAggregateVars(e,t){if(t.has(e))return{type:"variable",name:t.get(e)};if(e.type==="operation"&&e.args){let n=e.args.map(c=>this.transformExpressionWithAggregateVars(c,t)),i=["=","!=","<",">","<=",">="],s=["&&","||","!"],a=["+","-","*","/"];return i.includes(e.operator)?{type:"comparison",operator:e.operator,left:n[0],right:n[1]}:s.includes(e.operator)?{type:"logical",operator:e.operator,operands:n}:a.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:n[0],right:n[1]}:{type:"function",function:e.operator,args:n}}return this.translateExpression(e)}extractGroupVariables(e){return e?e.filter(t=>t.expression&&t.expression.termType==="Variable").map(t=>t.expression.value):[]}translateAggregateExpression(e){let t=e.aggregation;if(typeof t=="string"){let n=t.toLowerCase();return["count","sum","avg","min","max","group_concat","sample"].includes(n)?{type:"aggregate",aggregation:n,expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}:{type:"aggregate",aggregation:{type:"custom",iri:t},expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}if(t&&typeof t=="object"){let n;if(t.termType==="NamedNode"&&t.value)n=t.value;else if("value"in t)n=String(t.value);else throw new me(`Invalid custom aggregate: expected IRI but got ${JSON.stringify(t)}`);return{type:"aggregate",aggregation:{type:"custom",iri:n},expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}throw new me(`Unknown aggregate format: ${JSON.stringify(t)}`)}isLateralPattern(e){if(e.type==="query"&&this.isLateralSubquery(e))return!0;if(e.type==="group"&&e.patterns?.length===1){let t=e.patterns[0];if(t.type==="query"&&this.isLateralSubquery(t))return!0}return!1}extractLateralSubquery(e){if(e.type==="query")return e;if(e.type==="group"&&e.patterns?.length===1)return e.patterns[0];throw new me("Invalid lateral pattern structure")}translateWhere(e){if(e.length===0)throw new me("Empty WHERE clause");let t=e.filter(a=>a.type==="filter"),n=e.filter(a=>a.type==="bind"),i=e.filter(a=>a.type!=="filter"&&a.type!=="bind"),s;if(i.length===0)s={type:"bgp",triples:[]};else if(i.length===1)i[0].type==="optional"?s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:i[0].expression?this.translateExpression(i[0].expression):void 0}:s=this.translatePattern(i[0]);else{i[0].type==="optional"?s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:i[0].expression?this.translateExpression(i[0].expression):void 0}:s=this.translatePattern(i[0]);for(let a=1;a<i.length;a++){let c=i[a];if(this.isLateralPattern(c)){let u=this.extractLateralSubquery(c),l=this.removeLateralMarker(u),f=this.translateSelect(l);s={type:"lateraljoin",left:s,right:f}}else if(c.type==="optional")s={type:"leftjoin",left:s,right:this.translateWhere(c.patterns),expression:c.expression?this.translateExpression(c.expression):void 0};else{let u=this.translatePattern(c);s={type:"join",left:s,right:u}}}}for(let a of n)s=this.translateBind(a,s);for(let a of t)s={type:"filter",expression:this.translateExpression(a.expression),input:s};return s}translatePattern(e){if(!e||!e.type)throw new me("Invalid pattern: missing type");switch(e.type){case"bgp":return this.translateBGP(e);case"filter":return this.translateFilter(e);case"optional":return this.translateOptional(e);case"union":return this.translateUnion(e);case"minus":return this.translateMinus(e);case"values":return this.translateValues(e);case"group":return this.translateWhere(e.patterns);case"query":return this.translateSubquery(e);case"service":return this.translateService(e);case"graph":return this.translateGraph(e);default:throw new me(`Unsupported pattern type: ${e.type}`)}}translateBGP(e){if(!e.triples||!Array.isArray(e.triples))throw new me("BGP pattern must have triples array");return{type:"bgp",triples:e.triples.map(t=>this.translateTriple(t))}}translateTriple(e){if(!e.subject||!e.predicate||!e.object)throw new me("Triple must have subject, predicate, and object");return{subject:this.translateTripleElement(e.subject),predicate:this.translatePredicate(e.predicate),object:this.translateTripleElement(e.object)}}translatePredicate(e){return e.type==="path"?this.translatePropertyPath(e):this.translateTripleElement(e)}translatePropertyPath(e){if(!e.pathType)throw new me("Property path must have pathType");if(!e.items||!Array.isArray(e.items))throw new me("Property path must have items array");let t=e.items.map(n=>this.translatePathItem(n));switch(e.pathType){case"/":return{type:"path",pathType:"/",items:t};case"|":return{type:"path",pathType:"|",items:t};case"^":if(t.length!==1)throw new me("Inverse path must have exactly one item");return{type:"path",pathType:"^",items:[t[0]]};case"+":if(t.length!==1)throw new me("OneOrMore path must have exactly one item");return{type:"path",pathType:"+",items:[t[0]]};case"*":if(t.length!==1)throw new me("ZeroOrMore path must have exactly one item");return{type:"path",pathType:"*",items:[t[0]]};case"?":if(t.length!==1)throw new me("ZeroOrOne path must have exactly one item");return{type:"path",pathType:"?",items:[t[0]]};default:throw new me(`Unsupported property path type: ${e.pathType}`)}}translatePathItem(e){if(e.type==="path")return this.translatePropertyPath(e);if(e.termType==="NamedNode")return{type:"iri",value:e.value};throw new me(`Unsupported path item type: ${e.type||e.termType}`)}translateTripleElement(e){if(!e||!e.termType)throw new me("Triple element must have termType");switch(e.termType){case"Variable":return{type:"variable",value:e.value};case"NamedNode":return{type:"iri",value:e.value};case"Literal":{let t={type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};if(e.language){let n=this.directionMappings.get(e.language.toLowerCase());n&&(t.direction=n)}return t}case"BlankNode":return{type:"blank",value:e.value};case"Quad":return this.translateQuotedTriple(e);default:throw new me(`Unsupported term type: ${e.termType}`)}}translateQuotedTriple(e){if(!e.subject||!e.predicate||!e.object)throw new me("Quoted triple must have subject, predicate, and object");let t=this.translateTripleElement(e.subject),n=this.translateQuotedTriplePredicate(e.predicate),i=this.translateTripleElement(e.object);return{type:"quoted",subject:t,predicate:n,object:i}}translateQuotedTriplePredicate(e){if(!e||!e.termType)throw new me("Quoted triple predicate must have termType");switch(e.termType){case"Variable":return{type:"variable",value:e.value};case"NamedNode":return{type:"iri",value:e.value};default:throw new me(`Quoted triple predicate must be IRI or Variable, got: ${e.termType}`)}}translateFilter(e){if(!e.expression)throw new me("Filter pattern must have expression");let t=e.patterns?this.translateWhere(e.patterns):{type:"bgp",triples:[]};return{type:"filter",expression:this.translateExpression(e.expression),input:t}}translateExpression(e){if(!e)throw new me("Expression cannot be null or undefined");if(e.type==="operation")return this.translateOperationExpression(e);if(e.type==="functioncall"||e.type==="functionCall")return{type:"functionCall",function:e.function,args:e.args.map(t=>this.translateExpression(t))};if(e.termType)return this.translateTermExpression(e);throw new me(`Unsupported expression structure: ${JSON.stringify(e)}`)}translateOperationExpression(e){let t=["=","!=","<",">","<=",">="],n=["&&","||","!"],i=["+","-","*","/"];return t.includes(e.operator)?{type:"comparison",operator:e.operator,left:this.translateExpression(e.args[0]),right:this.translateExpression(e.args[1])}:n.includes(e.operator)?{type:"logical",operator:e.operator,operands:e.args.map(s=>this.translateExpression(s))}:i.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:this.translateExpression(e.args[0]),right:this.translateExpression(e.args[1])}:e.operator==="exists"||e.operator==="notexists"?this.translateExistsExpression(e):e.operator==="in"||e.operator==="notin"?this.translateInExpression(e):{type:"function",function:e.operator,args:e.args.map(s=>this.translateExpression(s))}}translateExistsExpression(e){if(!e.args||e.args.length!==1)throw new me("EXISTS/NOT EXISTS must have exactly one pattern argument");let t=e.args[0],n;return t.type==="group"&&t.patterns?n=this.translateWhere(t.patterns):t.type==="bgp"?n=this.translateBGP(t):n=this.translatePattern(t),{type:"exists",negated:e.operator==="notexists",pattern:n}}translateInExpression(e){if(!e.args||e.args.length!==2)throw new me("IN/NOT IN must have exactly 2 arguments (expression and list)");let t=e.args[0],n=e.args[1];if(!Array.isArray(n))throw new me("IN/NOT IN second argument must be an array of values");return{type:"in",expression:this.translateExpression(t),list:n.map(i=>this.translateExpression(i)),negated:e.operator==="notin"}}translateTermExpression(e){if(e.termType==="Variable")return{type:"variable",name:e.value};if(e.termType==="Literal"){let t=e.value;return e.datatype&&(e.datatype.value.includes("#integer")||e.datatype.value.includes("#decimal")?t=parseFloat(e.value):e.datatype.value.includes("#boolean")&&(t=e.value==="true")),{type:"literal",value:t,datatype:e.datatype?.value}}return{type:"literal",value:String(e.value||e)}}translateOptional(e){if(!e.patterns||e.patterns.length===0)throw new me("OPTIONAL pattern must have patterns");return{type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns),expression:e.expression?this.translateExpression(e.expression):void 0}}translateUnion(e){if(!e.patterns||e.patterns.length<2)throw new me("UNION pattern must have at least 2 patterns");let t=o(i=>i.type==="graph"?this.translateGraph(i):i.type==="service"?this.translateService(i):i.patterns&&Array.isArray(i.patterns)?this.translateWhere(i.patterns):this.translateWhere([i]),"translateBranch"),n={type:"union",left:t(e.patterns[0]),right:t(e.patterns[1])};for(let i=2;i<e.patterns.length;i++)n={type:"union",left:n,right:t(e.patterns[i])};return n}translateMinus(e){if(!e.patterns||e.patterns.length===0)throw new me("MINUS pattern must have patterns");return{type:"minus",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns)}}translateValues(e){if(!e.values||!Array.isArray(e.values))throw new me("VALUES pattern must have values array");let t=new Set;for(let i of e.values)for(let s of Object.keys(i)){let a=s.startsWith("?")?s.slice(1):s;t.add(a)}let n=e.values.map(i=>this.translateValuesBinding(i));return{type:"values",variables:Array.from(t),bindings:n}}translateValuesBinding(e){let t={};for(let[n,i]of Object.entries(e)){let s=n.startsWith("?")?n.slice(1):n,a=i;if(a)if(a.termType==="NamedNode")t[s]={type:"iri",value:a.value};else if(a.termType==="Literal"){let c={type:"literal",value:a.value,datatype:a.datatype?.value,language:a.language||void 0};if(a.language){let u=this.directionMappings.get(a.language.toLowerCase());u&&(c.direction=u)}t[s]=c}else throw new me(`Unsupported VALUES term type: ${a.termType}`)}return t}translateBind(e,t){if(!e.variable||!e.expression)throw new me("BIND pattern must have variable and expression");return{type:"extend",variable:e.variable.value,expression:this.translateExpression(e.expression),input:t}}translateOrderComparator(e){return{expression:this.translateExpression(e.expression),descending:e.descending||!1}}isLateralSubquery(e){return e.queryType!=="SELECT"||!e.variables?!1:e.variables.some(t=>t.termType==="Variable"&&t.value===Rb.LateralTransformer.LATERAL_MARKER)}removeLateralMarker(e){return e.variables?{...e,variables:e.variables.filter(t=>!(t.termType==="Variable"&&t.value===Rb.LateralTransformer.LATERAL_MARKER))}:e}translateSubquery(e){if(e.queryType!=="SELECT")throw new me(`Only SELECT subqueries are supported, got: ${e.queryType}`);let t=this.removeLateralMarker(e);return{type:"subquery",query:this.translateSelect(t)}}translateService(e){if(!e.name||e.name.termType!=="NamedNode")throw new me("SERVICE pattern must have a NamedNode endpoint");if(!e.patterns||!Array.isArray(e.patterns))throw new me("SERVICE pattern must have patterns array");let t=this.translateWhere(e.patterns);return{type:"service",endpoint:e.name.value,pattern:t,silent:e.silent||!1}}translateGraph(e){if(!e.name)throw new me("GRAPH pattern must have a name (IRI or variable)");if(!e.patterns||!Array.isArray(e.patterns))throw new me("GRAPH pattern must have patterns array");let t;if(e.name.termType==="NamedNode")t={type:"iri",value:e.name.value};else if(e.name.termType==="Variable")t={type:"variable",value:e.name.value};else throw new me(`GRAPH pattern name must be NamedNode or Variable, got: ${e.name.termType}`);let n=this.translateWhere(e.patterns);return{type:"graph",name:t,pattern:n}}translateDescribe(e){let t=[];if(e.variables&&Array.isArray(e.variables))for(let s of e.variables){let a=s;a.termType==="Wildcard"||a.value==="*"||(a.termType==="Variable"?t.push({type:"variable",value:a.value}):a.termType==="NamedNode"&&t.push({type:"iri",value:a.value}))}let n;e.where&&e.where.length>0&&(n=this.translateWhere(e.where));let i=e.describeOptions;return{type:"describe",resources:t,where:n,depth:i?.depth,symmetric:i?.symmetric}}};co.AlgebraTranslator=ey});var ry=_(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});Xf.FilterContainsOptimizer=void 0;var jN=Ye(),$N=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,ty=class{static{o(this,"FilterContainsOptimizer")}constructor(){this.tripleStore=null,this.lastOptimizationHints=[]}setTripleStore(e){this.tripleStore=e}getLastOptimizationHints(){return this.lastOptimizationHints}clearHints(){this.lastOptimizationHints=[]}async optimize(e){return this.clearHints(),this.optimizeRecursive(e)}optimizeSync(e,t){return this.clearHints(),this.optimizeSyncRecursive(e,t)}async optimizeRecursive(e){return e.type==="filter"?this.optimizeFilter(e):e.type==="join"?{type:"join",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="leftjoin"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="union"?{type:"union",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="minus"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="project"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="orderby"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="slice"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="distinct"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="reduced"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="group"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="extend"?{...e,input:await this.optimizeRecursive(e.input)}:e}optimizeSyncRecursive(e,t){return e.type==="filter"?this.optimizeFilterSync(e,t):e.type==="join"?{type:"join",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="leftjoin"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="union"?{type:"union",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="minus"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="project"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="orderby"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="slice"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="distinct"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="reduced"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="group"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="extend"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e}async optimizeFilter(e){let t=this.detectContainsUUIDPattern(e.expression);if(!t)return{type:"filter",expression:e.expression,input:await this.optimizeRecursive(e.input)};let n=[];return this.tripleStore&&(n=await this.findSubjectsContainingUUID(t.uuid)),this.rewriteFilter(e,t,n)}optimizeFilterSync(e,t){let n=this.detectContainsUUIDPattern(e.expression);if(!n)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input,t)};let i=t?t.filter(s=>s.includes(n.uuid)):[];return this.rewriteFilter(e,n,i)}rewriteFilter(e,t,n){if(this.lastOptimizationHints.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${t.variable}), "${t.uuid}"))`,suggestedRewrite:n.length===1?`VALUES ?${t.variable} { <${n[0]}> }`:n.length>1?`VALUES ?${t.variable} { ${n.map(i=>`<${i}>`).join(" ")} }`:"No matching URIs found for UUID",estimatedSpeedup:n.length>0?"O(n) \u2192 O(1)":"N/A",matchedUri:n.length===1?n[0]:void 0}),n.length===0)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input)};if(n.length===1){let i=this.injectSubjectConstraint(e.input,t.variable,n[0]);if(i!==e.input)return i}return this.createValuesJoin(e,t,n)}detectContainsUUIDPattern(e){if(e.type==="function"||e.type==="functionCall"){let t=e;if((typeof t.function=="string"?t.function.toLowerCase():t.function?.value?.toLowerCase()??"")==="contains"&&t.args.length===2)return this.analyzeContainsArgs(t.args[0],t.args[1],e)}if(e.type==="logical"&&e.operator==="&&")for(let t of e.operands){let n=this.detectContainsUUIDPattern(t);if(n)return n}return null}analyzeContainsArgs(e,t,n){let i=null;if(e.type==="function"||e.type==="functionCall"){let s=e;if((typeof s.function=="string"?s.function.toLowerCase():s.function?.value?.toLowerCase()??"")==="str"&&s.args.length===1){let c=s.args[0];c.type==="variable"&&(i=c.name)}}if(!i&&e.type==="variable"&&(i=e.name),!i)return null;if(t.type==="literal"){let c=String(t.value).match($N);if(c)return{variable:i,uuid:c[0].toLowerCase(),originalExpression:n}}return null}async findSubjectsContainingUUID(e){if(!this.tripleStore)return[];if(this.tripleStore.findSubjectsByUUID)return(await this.tripleStore.findSubjectsByUUID(e)).map(s=>s.value);let t=await this.tripleStore.subjects(),n=[];for(let i of t)i instanceof jN.IRI&&i.value.toLowerCase().includes(e.toLowerCase())&&n.push(i.value);return n}injectSubjectConstraint(e,t,n){if(e.type==="bgp"){let i=e.triples.map(a=>a.subject.type==="variable"&&a.subject.value===t?{...a,subject:{type:"iri",value:n}}:a);if(i.some((a,c)=>a.subject!==e.triples[c].subject))return{type:"bgp",triples:i}}if(e.type==="join"){let i=this.injectSubjectConstraint(e.left,t,n),s=this.injectSubjectConstraint(e.right,t,n);if(i!==e.left||s!==e.right)return{type:"join",left:i,right:s}}if(e.type==="filter"){let i=this.injectSubjectConstraint(e.input,t,n);if(i!==e.input)return{...e,input:i}}return e}createValuesJoin(e,t,n){return{type:"join",left:{type:"values",variables:[t.variable],bindings:n.map(a=>({[t.variable]:{type:"iri",value:a}}))},right:this.optimizeSyncRecursive(e.input)}}analyzeQuery(e){let t=[];return this.analyzeRecursive(e,t),t}analyzeRecursive(e,t){if(e.type==="filter"){let n=this.detectContainsUUIDPattern(e.expression);n&&t.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${n.variable}), "${n.uuid}"))`,suggestedRewrite:`Use --optimize flag or rewrite as VALUES ?${n.variable} { <uri-containing-uuid> }`,estimatedSpeedup:"O(n) \u2192 O(1) with UUID index lookup"}),this.analyzeRecursive(e.input,t);return}e.type==="join"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="leftjoin"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="union"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="minus"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="project"?this.analyzeRecursive(e.input,t):e.type==="orderby"?this.analyzeRecursive(e.input,t):e.type==="slice"?this.analyzeRecursive(e.input,t):e.type==="distinct"?this.analyzeRecursive(e.input,t):e.type==="reduced"?this.analyzeRecursive(e.input,t):e.type==="group"?this.analyzeRecursive(e.input,t):e.type==="extend"&&this.analyzeRecursive(e.input,t)}};Xf.FilterContainsOptimizer=ty});var Lb=_(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});Jf.AlgebraOptimizer=void 0;var BN=ry(),ny=class{static{o(this,"AlgebraOptimizer")}constructor(){this.stats=new Map,this.tripleStore=null,this.filterContainsOptimizer=new BN.FilterContainsOptimizer}setTripleStore(e){this.tripleStore=e,this.filterContainsOptimizer.setTripleStore(e)}getOptimizationHints(){return this.filterContainsOptimizer.getLastOptimizationHints()}analyzeQuery(e){return this.filterContainsOptimizer.analyzeQuery(e)}optimize(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),t=this.filterPushDown(t),t=this.joinReordering(t),t}async optimizeAsync(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),this.tripleStore&&(t=await this.filterContainsOptimizer.optimize(t)),t=this.filterPushDown(t),t=this.joinReordering(t),t}optimizeWithSubjects(e,t){let n=e;return n=this.eliminateEmptyBGPInFilterJoin(n),n=this.filterContainsOptimizer.optimizeSync(n,t),n=this.filterPushDown(n),n=this.joinReordering(n),n}eliminateEmptyBGPInFilterJoin(e){if(e.type==="join"){if(e.left.type==="filter"){let t=e.left;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.right)}}if(e.right.type==="filter"){let t=e.right;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.left)}}return{type:"join",left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}}return e.type==="filter"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="leftjoin"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="union"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="minus"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="project"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="orderby"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="slice"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="distinct"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e}filterPushDown(e){return e.type==="filter"?this.pushDownFilter(e):e.type==="join"?{type:"join",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="leftjoin"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="union"?{type:"union",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="minus"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="project"?{...e,input:this.filterPushDown(e.input)}:e.type==="orderby"?{...e,input:this.filterPushDown(e.input)}:e.type==="slice"?{...e,input:this.filterPushDown(e.input)}:e.type==="distinct"?{...e,input:this.filterPushDown(e.input)}:e}pushDownFilter(e){let t=e.input;if(t.type==="join"){let n=this.getFilterVariables(e.expression),i=this.getOperationVariables(t.left),s=this.getOperationVariables(t.right),a=n.every(u=>i.has(u)),c=n.every(u=>s.has(u));return a&&!c?{type:"join",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:this.filterPushDown(t.right)}:c&&!a?{type:"join",left:this.filterPushDown(t.left),right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:{type:"join",left:this.filterPushDown(t.left),right:this.filterPushDown(t.right)}}}return t.type==="union"?{type:"union",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:this.filterPushDown(t)}}getFilterVariables(e){let t=[];if(e.type==="variable")t.push(e.name);else if(e.type==="comparison")t.push(...this.getFilterVariables(e.left)),t.push(...this.getFilterVariables(e.right));else if(e.type==="logical")for(let n of e.operands)t.push(...this.getFilterVariables(n));else if(e.type==="function")for(let n of e.args)t.push(...this.getFilterVariables(n));return Array.from(new Set(t))}getOperationVariables(e){let t=new Set;if(e.type==="bgp")for(let n of e.triples)n.subject.type==="variable"&&t.add(n.subject.value),n.predicate.type==="variable"&&t.add(n.predicate.value),n.object.type==="variable"&&t.add(n.object.value);else if(e.type==="join"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else{if(e.type==="filter")return this.getOperationVariables(e.input);if(e.type==="leftjoin"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else if(e.type==="union"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else{if(e.type==="minus")return this.getOperationVariables(e.left);if(e.type==="project")return new Set(e.variables)}}return t}joinReordering(e){return e.type==="join"?this.reorderJoin(e):e.type==="filter"?{...e,input:this.joinReordering(e.input)}:e.type==="leftjoin"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="union"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="minus"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="project"?{...e,input:this.joinReordering(e.input)}:e.type==="orderby"?{...e,input:this.joinReordering(e.input)}:e.type==="slice"?{...e,input:this.joinReordering(e.input)}:e.type==="distinct"?{...e,input:this.joinReordering(e.input)}:e}reorderJoin(e){let t=this.estimateCost(e.left);return this.estimateCost(e.right)<t?{type:"join",left:this.joinReordering(e.right),right:this.joinReordering(e.left)}:{type:"join",left:this.joinReordering(e.left),right:this.joinReordering(e.right)}}estimateCost(e){if(e.type==="bgp"){let t=e.triples.length*100;for(let n of e.triples)n.subject.type==="variable"&&(t+=10),n.predicate.type==="variable"&&(t+=20),n.object.type==="variable"&&(t+=10);return t}return e.type==="filter"?this.estimateCost(e.input)*.3:e.type==="join"?this.estimateCost(e.left)*this.estimateCost(e.right):e.type==="leftjoin"?this.estimateCost(e.left)+this.estimateCost(e.right)*.5:e.type==="union"?this.estimateCost(e.left)+this.estimateCost(e.right):e.type==="minus"?this.estimateCost(e.left)+this.estimateCost(e.right)*.3:100}setStatistics(e,t){this.stats.set(e,t)}getStatistics(e){return this.stats.get(e)}};Jf.AlgebraOptimizer=ny});var Mb=_(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});Zf.AlgebraSerializer=void 0;var iy=class{static{o(this,"AlgebraSerializer")}toString(e,t=0){let n=" ".repeat(t);switch(e.type){case"bgp":return`${n}BGP [
260
+ `)return n+1;let s=e.substring(n).toUpperCase();if(s.startsWith("PREFIX")||s.startsWith("BASE")||s.startsWith("SELECT")||s.startsWith("CONSTRUCT")||s.startsWith("DESCRIBE")||s.startsWith("ASK"))return n;if(/\s/.test(i)){n++;continue}break}return n}extractPrefixFromUri(e){let t=e.replace(/^https?:\/\//,"");t=t.replace(/\/$/,"").replace(/#$/,"");let n=t.split(/[/.#]+/).filter(Boolean);if(n.length===0)return null;let i=n[n.length-1];return/^(ontology|vocab|schema|ns|core)$/i.test(i)&&n.length>1?n[n.length-2].toLowerCase():i.toLowerCase().replace(/[^a-z0-9]/g,"")}};ms.PrefixStarTransformer=W0;var ro=class extends Error{static{o(this,"PrefixStarTransformerError")}constructor(e){super(`PREFIX* transformation error: ${e}`),this.name="PrefixStarTransformerError"}};ms.PrefixStarTransformerError=ro});var H0=_(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.DescribeOptionsTransformer=io.DescribeOptionsTransformerError=void 0;var Qf=class extends Error{static{o(this,"DescribeOptionsTransformerError")}constructor(e){super(e),this.name="DescribeOptionsTransformerError"}};io.DescribeOptionsTransformerError=Qf;var no=class r{static{o(this,"DescribeOptionsTransformer")}transform(e){if(!r.DESCRIBE_QUERY_PATTERN.test(e))return{query:e};let t=e,n={},i=!1,s=r.DEPTH_PATTERN.exec(e);if(s){let a=parseInt(s[1],10);if(a<0)throw new Qf(`DESCRIBE DEPTH must be a non-negative integer, got: ${a}`);n.depth=a,i=!0,r.DEPTH_PATTERN.lastIndex=0,t=t.replace(r.DEPTH_PATTERN,"")}return r.DEPTH_PATTERN.lastIndex=0,r.SYMMETRIC_PATTERN.test(e)&&(n.symmetric=!0,i=!0,r.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(r.SYMMETRIC_PATTERN,"")),r.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(/\s{2,}/g," ").trim(),{query:t,options:i?n:void 0}}hasDescribeOptions(e){let t=r.DEPTH_PATTERN.test(e);r.DEPTH_PATTERN.lastIndex=0;let n=r.SYMMETRIC_PATTERN.test(e);return r.SYMMETRIC_PATTERN.lastIndex=0,t||n}};io.DescribeOptionsTransformer=no;no.DEPTH_PATTERN=/\bDEPTH\s+(\d+)/gi;no.SYMMETRIC_PATTERN=/\bSYMMETRIC\b/gi;no.DESCRIBE_QUERY_PATTERN=/\bDESCRIBE\b/i});var Ib=_(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.DirectionalLangTagTransformerError=so.DirectionalLangTagTransformer=void 0;var Kf=class r{static{o(this,"DirectionalLangTagTransformer")}constructor(){this.directionMappings=new Map}transform(e){return this.directionMappings.clear(),e.replace(r.DIRECTIONAL_TAG_REGEX,(t,n,i,s,a)=>{let c=s.toLowerCase();return this.directionMappings.set(c,a),`${n}${i}${n}@${s}`})}getDirection(e){return this.directionMappings.get(e.toLowerCase())}getAllMappings(){return new Map(this.directionMappings)}hasDirectionalTags(e){return r.DIRECTIONAL_TAG_REGEX.lastIndex=0,r.DIRECTIONAL_TAG_REGEX.test(e)}clearMappings(){this.directionMappings.clear()}};so.DirectionalLangTagTransformer=Kf;Kf.DIRECTIONAL_TAG_REGEX=/(["'])((?:[^\\]|\\.)*?)\1@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)--(ltr|rtl)/g;var z0=class extends Error{static{o(this,"DirectionalLangTagTransformerError")}constructor(e){super(`Directional language tag transformation error: ${e}`),this.name="DirectionalLangTagTransformerError"}};so.DirectionalLangTagTransformerError=z0});var Ob=_(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.TripleTermTransformerError=oo.TripleTermTransformer=void 0;var Y0=class{static{o(this,"TripleTermTransformer")}transform(e){let t=e,n,i=0,s=100;do if(n=t,t=this.transformSinglePass(t),i++,i>s)throw new ao("Too many nested triple terms (max 100 iterations)");while(t!==n);return t}hasTripleTermSyntax(e){return this.findTripleTermPositions(e).length>0}transformSinglePass(e){let t=this.findTripleTermPositions(e);if(t.length===0)return e;let n=e;for(let i=t.length-1;i>=0;i--){let s=t[i],a=this.extractTripleTerm(n,s);if(a){let c=this.convertToStandardSyntax(a.content);n=n.substring(0,s)+c+n.substring(s+a.length)}}return n}findTripleTermPositions(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="'"){n=this.skipStringLiteral(e,n,"'");continue}if(e[n]==='"'){n=this.skipStringLiteral(e,n,'"');continue}if(e.substring(n,n+2)==="<<"&&this.isParenthesizedTripleTerm(e,n)){t.push(n),n+=2;continue}n++}return t}skipStringLiteral(e,t,n){let i=n.repeat(3);if(e.substring(t,t+3)===i){for(t+=3;t<e.length;){if(e.substring(t,t+3)===i)return t+3;e[t]==="\\"&&t++,t++}return t}for(t++;t<e.length&&e[t]!==n;)e[t]==="\\"&&t++,t++;return t+1}isParenthesizedTripleTerm(e,t){let n=t+2;for(;n<e.length&&/\s/.test(e[n]);)n++;return e[n]==="("}extractTripleTerm(e,t){let n=t+2;for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="(")return null;n++;let i=1;for(;n<e.length&&i>0;){if(e[n]==="'"||e[n]==='"'){n=this.skipStringLiteral(e,n,e[n]);continue}if(e.substring(n,n+2)==="<<"&&this.isParenthesizedTripleTerm(e,n)){for(n+=2;n<e.length&&/\s/.test(e[n]);)n++;e[n]==="("&&(i++,n++);continue}if(e.substring(n,n+2)==="<<"){n+=2;let s=1;for(;n<e.length&&s>0;){if(e[n]==="'"||e[n]==='"'){n=this.skipStringLiteral(e,n,e[n]);continue}if(e.substring(n,n+2)==="<<"){s++,n+=2;continue}if(e.substring(n,n+2)===">>"){s--,n+=2;continue}n++}continue}if(e[n]==="("){i++,n++;continue}if(e[n]===")"){let s=n+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e.substring(s,s+2)===">>"){if(i--,i===0){let a=e.substring(t,s+2);return{content:a,length:a.length}}n=s+2;continue}n++;continue}n++}if(i>0)throw new ao(`Unclosed triple term at position ${t}: missing )>>`);return null}convertToStandardSyntax(e){let t=e.match(/^<<\s*\(\s*([\s\S]*?)\s*\)\s*>>$/);if(!t)throw new ao(`Invalid triple term syntax: ${e.substring(0,50)}...`);return`<< ${t[1]} >>`}};oo.TripleTermTransformer=Y0;var ao=class extends Error{static{o(this,"TripleTermTransformerError")}constructor(e){super(`Triple term transformation error: ${e}`),this.name="TripleTermTransformerError"}};oo.TripleTermTransformerError=ao});var Fb=_(mn=>{"use strict";var NN=mn&&mn.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),LN=mn&&mn.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),MN=mn&&mn.__importStar||(function(){var r=o(function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&NN(t,e,n[i]);return LN(t,e),t}})();Object.defineProperty(mn,"__esModule",{value:!0});mn.SPARQLParser=mn.SPARQLParseError=void 0;var Pb=MN(xb()),Q0=q0(),K0=G0(),Db=Cb(),X0=H0(),kN=Ib(),J0=Ob(),Nt=class extends Error{static{o(this,"SPARQLParseError")}constructor(e,t,n,i){super(e,i?{cause:i}:void 0),this.name="SPARQLParseError",this.line=t,this.column=n}};mn.SPARQLParseError=Nt;var Z0=class{static{o(this,"SPARQLParser")}constructor(e){this.lastDirectionMappings=new Map,this.parser=new Pb.Parser({sparqlStar:!0}),this.generator=new Pb.Generator({sparqlStar:!0}),this.caseWhenTransformer=new Q0.CaseWhenTransformer,this.lateralTransformer=new K0.LateralTransformer,this.prefixStarTransformer=new Db.PrefixStarTransformer(e?.vocabularyResolver),this.describeOptionsTransformer=new X0.DescribeOptionsTransformer,this.directionalLangTagTransformer=new kN.DirectionalLangTagTransformer,this.tripleTermTransformer=new J0.TripleTermTransformer}parse(e){try{let t=this.describeOptionsTransformer.transform(e);this.lastDescribeOptions=t.options;let n=t.query;n=this.directionalLangTagTransformer.transform(n),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),n=this.lateralTransformer.transform(n),n=this.caseWhenTransformer.transform(n),n=this.tripleTermTransformer.transform(n);let i=this.parser.parse(n);return this.validateQuery(i),this.lastDescribeOptions&&this.isDescribeQuery(i)&&(i.describeOptions=this.lastDescribeOptions),i}catch(t){if(t instanceof X0.DescribeOptionsTransformerError)throw new Nt(t.message);if(t instanceof K0.LateralTransformerError)throw new Nt(t.message);if(t instanceof Q0.CaseWhenTransformerError)throw new Nt(t.message);if(t instanceof J0.TripleTermTransformerError)throw new Nt(t.message);if(t instanceof Error){let n=t.message.match(/line (\d+), column (\d+)/),i=n?parseInt(n[1],10):void 0,s=n?parseInt(n[2],10):void 0;throw new Nt(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}parseWithOptions(e){return{query:this.parse(e),describeOptions:this.lastDescribeOptions}}getLastDescribeOptions(){return this.lastDescribeOptions}async parseAsync(e){try{let t=this.describeOptionsTransformer.transform(e);this.lastDescribeOptions=t.options;let n=t.query;n=this.directionalLangTagTransformer.transform(n),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),n=await this.prefixStarTransformer.transform(n),n=this.lateralTransformer.transform(n),n=this.caseWhenTransformer.transform(n),n=this.tripleTermTransformer.transform(n);let i=this.parser.parse(n);return this.validateQuery(i),this.lastDescribeOptions&&this.isDescribeQuery(i)&&(i.describeOptions=this.lastDescribeOptions),i}catch(t){if(t instanceof X0.DescribeOptionsTransformerError)throw new Nt(t.message);if(t instanceof Db.PrefixStarTransformerError)throw new Nt(t.message);if(t instanceof K0.LateralTransformerError)throw new Nt(t.message);if(t instanceof Q0.CaseWhenTransformerError)throw new Nt(t.message);if(t instanceof J0.TripleTermTransformerError)throw new Nt(t.message);if(t instanceof Error){let n=t.message.match(/line (\d+), column (\d+)/),i=n?parseInt(n[1],10):void 0,s=n?parseInt(n[2],10):void 0;throw new Nt(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}async parseAsyncWithOptions(e){return{query:await this.parseAsync(e),describeOptions:this.lastDescribeOptions}}hasPrefixStar(e){return/PREFIX\s*\*/i.test(e)}hasLateral(e){return this.lateralTransformer.hasLateral(e)}hasDescribeOptions(e){return this.describeOptionsTransformer.hasDescribeOptions(e)}hasDirectionalLangTags(e){return this.directionalLangTagTransformer.hasDirectionalTags(e)}hasTripleTermSyntax(e){return this.tripleTermTransformer.hasTripleTermSyntax(e)}getLastDirectionMappings(){return new Map(this.lastDirectionMappings)}getDirectionForLanguage(e){return this.lastDirectionMappings.get(e.toLowerCase())}toString(e){try{return this.generator.stringify(e)}catch(t){throw t instanceof Error?new Nt(`Failed to serialize SPARQL query: ${t.message}`,void 0,void 0,t):t}}getQueryType(e){if("queryType"in e&&e.type==="query")return e.queryType;throw new Nt("Query does not have a valid queryType property")}isSelectQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="SELECT"}isConstructQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="CONSTRUCT"}isAskQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="ASK"}isDescribeQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="DESCRIBE"}isUpdateQuery(e){return e.type==="update"}isInsertDataOperation(e){return"updateType"in e&&e.updateType==="insert"}isDeleteDataOperation(e){return"updateType"in e&&e.updateType==="delete"}validateQuery(e){if(!e||typeof e!="object")throw new Nt("Invalid query: not an object");if(e.type!=="query"&&e.type!=="update")throw new Nt(`Invalid type: expected "query" or "update", got "${e.type}"`);if(e.type==="query"){let t=["SELECT","CONSTRUCT","ASK","DESCRIBE"];if(!t.includes(e.queryType))throw new Nt(`Invalid query type: expected one of ${t.join(", ")}, got "${e.queryType}"`)}}};mn.SPARQLParser=Z0});var Nb=_(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.AlgebraTranslator=co.AlgebraTranslatorError=void 0;var Rb=G0(),me=class extends Error{static{o(this,"AlgebraTranslatorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AlgebraTranslatorError"}};co.AlgebraTranslatorError=me;var ey=class{static{o(this,"AlgebraTranslator")}constructor(){this.directionMappings=new Map,this.aggregateCounter=0}setDirectionMappings(e){this.directionMappings=e}translate(e){if(e.type!=="query")throw new me("Only query operations are supported (not updates)");if(e.queryType==="SELECT")return this.translateSelect(e);if(e.queryType==="CONSTRUCT")return this.translateConstruct(e);if(e.queryType==="ASK")return this.translateAsk(e);if(e.queryType==="DESCRIBE")return this.translateDescribe(e);throw new me(`Query type ${e.queryType} not yet supported`)}translateSelect(e){let t;if(!e.where||e.where.length===0)throw new me("SELECT query must have WHERE clause");t=this.translateWhere(e.where),this.aggregateCounter=0;let n=new Map,i=this.extractAggregatesWithMapping(e.variables,n),s=this.extractGroupVariables(e.group),a=this.extractHavingExpressions(e.having,i,n);if((i.length>0||s.length>0||a.length>0)&&(t={type:"group",variables:s,aggregates:i,having:a.length>0?a:void 0,input:t}),e.variables&&e.variables.length>0){for(let u of e.variables){let l=u;if(l.expression&&l.variable){if(l.expression.type==="aggregate")continue;let f=this.transformExpressionWithAggregateVars(l.expression,n);t={type:"extend",variable:l.variable.value,expression:f,input:t}}}let c=e.variables.filter(u=>u.termType==="Variable"||u.variable).map(u=>u.termType==="Variable"?u.value:u.variable.value);c.length>0&&(t={type:"project",variables:c,input:t})}return e.distinct&&(t={type:"distinct",input:t}),e.reduced&&(t={type:"reduced",input:t}),e.order&&e.order.length>0&&(t={type:"orderby",comparators:e.order.map(c=>this.translateOrderComparator(c)),input:t}),(e.limit!==void 0||e.offset!==void 0)&&(t={type:"slice",limit:e.limit,offset:e.offset,input:t}),t}translateConstruct(e){let t=this.translateConstructTemplate(e.template??[]);if(!e.where||e.where.length===0)throw new me("CONSTRUCT query must have WHERE clause");let n=this.translateWhere(e.where);return{type:"construct",template:t,where:n}}translateConstructTemplate(e){return!e||!Array.isArray(e)?[]:e.map(t=>this.translateTriple(t))}translateAsk(e){return{type:"ask",where:e.where&&e.where.length>0?this.translateWhere(e.where):{type:"bgp",triples:[]}}}extractAggregatesWithMapping(e,t){if(!e)return[];let n=[];for(let i of e)!i.expression||!i.variable||(i.expression.type==="aggregate"?(n.push({variable:i.variable.value,expression:this.translateAggregateExpression(i.expression)}),t.set(i.expression,i.variable.value)):this.collectNestedAggregates(i.expression,n,t));return n}collectNestedAggregates(e,t,n){if(e){if(e.type==="aggregate"){let i=`__agg${this.aggregateCounter++}`;t.push({variable:i,expression:this.translateAggregateExpression(e)}),n.set(e,i)}else if(e.type==="operation"&&e.args)for(let i of e.args)this.collectNestedAggregates(i,t,n)}}transformExpressionWithAggregateVars(e,t){if(t.has(e))return{type:"variable",name:t.get(e)};if(e.type==="operation"&&e.args){let n=e.args.map(c=>this.transformExpressionWithAggregateVars(c,t)),i=["=","!=","<",">","<=",">="],s=["&&","||","!"],a=["+","-","*","/"];return i.includes(e.operator)?{type:"comparison",operator:e.operator,left:n[0],right:n[1]}:s.includes(e.operator)?{type:"logical",operator:e.operator,operands:n}:a.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:n[0],right:n[1]}:{type:"function",function:e.operator,args:n}}return this.translateExpression(e)}extractGroupVariables(e){return e?e.filter(t=>t.expression&&t.expression.termType==="Variable").map(t=>t.expression.value):[]}extractHavingExpressions(e,t,n){if(!e||e.length===0)return[];for(let i of e)this.collectNestedAggregates(i,t,n);return e.map(i=>this.transformExpressionWithAggregateVars(i,n))}translateAggregateExpression(e){let t=e.aggregation;if(typeof t=="string"){let n=t.toLowerCase();return["count","sum","avg","min","max","group_concat","sample"].includes(n)?{type:"aggregate",aggregation:n,expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}:{type:"aggregate",aggregation:{type:"custom",iri:t},expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}if(t&&typeof t=="object"){let n;if(t.termType==="NamedNode"&&t.value)n=t.value;else if("value"in t)n=String(t.value);else throw new me(`Invalid custom aggregate: expected IRI but got ${JSON.stringify(t)}`);return{type:"aggregate",aggregation:{type:"custom",iri:n},expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}throw new me(`Unknown aggregate format: ${JSON.stringify(t)}`)}isLateralPattern(e){if(e.type==="query"&&this.isLateralSubquery(e))return!0;if(e.type==="group"&&e.patterns?.length===1){let t=e.patterns[0];if(t.type==="query"&&this.isLateralSubquery(t))return!0}return!1}extractLateralSubquery(e){if(e.type==="query")return e;if(e.type==="group"&&e.patterns?.length===1)return e.patterns[0];throw new me("Invalid lateral pattern structure")}translateWhere(e){if(e.length===0)throw new me("Empty WHERE clause");let t=e.filter(a=>a.type==="filter"),n=e.filter(a=>a.type==="bind"),i=e.filter(a=>a.type!=="filter"&&a.type!=="bind"),s;if(i.length===0)s={type:"bgp",triples:[]};else if(i.length===1)i[0].type==="optional"?s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:i[0].expression?this.translateExpression(i[0].expression):void 0}:s=this.translatePattern(i[0]);else{i[0].type==="optional"?s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:i[0].expression?this.translateExpression(i[0].expression):void 0}:s=this.translatePattern(i[0]);for(let a=1;a<i.length;a++){let c=i[a];if(this.isLateralPattern(c)){let u=this.extractLateralSubquery(c),l=this.removeLateralMarker(u),f=this.translateSelect(l);s={type:"lateraljoin",left:s,right:f}}else if(c.type==="optional")s={type:"leftjoin",left:s,right:this.translateWhere(c.patterns),expression:c.expression?this.translateExpression(c.expression):void 0};else{let u=this.translatePattern(c);s={type:"join",left:s,right:u}}}}for(let a of n)s=this.translateBind(a,s);for(let a of t)s={type:"filter",expression:this.translateExpression(a.expression),input:s};return s}translatePattern(e){if(!e||!e.type)throw new me("Invalid pattern: missing type");switch(e.type){case"bgp":return this.translateBGP(e);case"filter":return this.translateFilter(e);case"optional":return this.translateOptional(e);case"union":return this.translateUnion(e);case"minus":return this.translateMinus(e);case"values":return this.translateValues(e);case"group":return this.translateWhere(e.patterns);case"query":return this.translateSubquery(e);case"service":return this.translateService(e);case"graph":return this.translateGraph(e);default:throw new me(`Unsupported pattern type: ${e.type}`)}}translateBGP(e){if(!e.triples||!Array.isArray(e.triples))throw new me("BGP pattern must have triples array");return{type:"bgp",triples:e.triples.map(t=>this.translateTriple(t))}}translateTriple(e){if(!e.subject||!e.predicate||!e.object)throw new me("Triple must have subject, predicate, and object");return{subject:this.translateTripleElement(e.subject),predicate:this.translatePredicate(e.predicate),object:this.translateTripleElement(e.object)}}translatePredicate(e){return e.type==="path"?this.translatePropertyPath(e):this.translateTripleElement(e)}translatePropertyPath(e){if(!e.pathType)throw new me("Property path must have pathType");if(!e.items||!Array.isArray(e.items))throw new me("Property path must have items array");let t=e.items.map(n=>this.translatePathItem(n));switch(e.pathType){case"/":return{type:"path",pathType:"/",items:t};case"|":return{type:"path",pathType:"|",items:t};case"^":if(t.length!==1)throw new me("Inverse path must have exactly one item");return{type:"path",pathType:"^",items:[t[0]]};case"+":if(t.length!==1)throw new me("OneOrMore path must have exactly one item");return{type:"path",pathType:"+",items:[t[0]]};case"*":if(t.length!==1)throw new me("ZeroOrMore path must have exactly one item");return{type:"path",pathType:"*",items:[t[0]]};case"?":if(t.length!==1)throw new me("ZeroOrOne path must have exactly one item");return{type:"path",pathType:"?",items:[t[0]]};default:throw new me(`Unsupported property path type: ${e.pathType}`)}}translatePathItem(e){if(e.type==="path")return this.translatePropertyPath(e);if(e.termType==="NamedNode")return{type:"iri",value:e.value};throw new me(`Unsupported path item type: ${e.type||e.termType}`)}translateTripleElement(e){if(!e||!e.termType)throw new me("Triple element must have termType");switch(e.termType){case"Variable":return{type:"variable",value:e.value};case"NamedNode":return{type:"iri",value:e.value};case"Literal":{let t={type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};if(e.language){let n=this.directionMappings.get(e.language.toLowerCase());n&&(t.direction=n)}return t}case"BlankNode":return{type:"blank",value:e.value};case"Quad":return this.translateQuotedTriple(e);default:throw new me(`Unsupported term type: ${e.termType}`)}}translateQuotedTriple(e){if(!e.subject||!e.predicate||!e.object)throw new me("Quoted triple must have subject, predicate, and object");let t=this.translateTripleElement(e.subject),n=this.translateQuotedTriplePredicate(e.predicate),i=this.translateTripleElement(e.object);return{type:"quoted",subject:t,predicate:n,object:i}}translateQuotedTriplePredicate(e){if(!e||!e.termType)throw new me("Quoted triple predicate must have termType");switch(e.termType){case"Variable":return{type:"variable",value:e.value};case"NamedNode":return{type:"iri",value:e.value};default:throw new me(`Quoted triple predicate must be IRI or Variable, got: ${e.termType}`)}}translateFilter(e){if(!e.expression)throw new me("Filter pattern must have expression");let t=e.patterns?this.translateWhere(e.patterns):{type:"bgp",triples:[]};return{type:"filter",expression:this.translateExpression(e.expression),input:t}}translateExpression(e){if(!e)throw new me("Expression cannot be null or undefined");if(e.type==="operation")return this.translateOperationExpression(e);if(e.type==="functioncall"||e.type==="functionCall")return{type:"functionCall",function:e.function,args:e.args.map(t=>this.translateExpression(t))};if(e.termType)return this.translateTermExpression(e);throw new me(`Unsupported expression structure: ${JSON.stringify(e)}`)}translateOperationExpression(e){let t=["=","!=","<",">","<=",">="],n=["&&","||","!"],i=["+","-","*","/"];return t.includes(e.operator)?{type:"comparison",operator:e.operator,left:this.translateExpression(e.args[0]),right:this.translateExpression(e.args[1])}:n.includes(e.operator)?{type:"logical",operator:e.operator,operands:e.args.map(s=>this.translateExpression(s))}:i.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:this.translateExpression(e.args[0]),right:this.translateExpression(e.args[1])}:e.operator==="exists"||e.operator==="notexists"?this.translateExistsExpression(e):e.operator==="in"||e.operator==="notin"?this.translateInExpression(e):{type:"function",function:e.operator,args:e.args.map(s=>this.translateExpression(s))}}translateExistsExpression(e){if(!e.args||e.args.length!==1)throw new me("EXISTS/NOT EXISTS must have exactly one pattern argument");let t=e.args[0],n;return t.type==="group"&&t.patterns?n=this.translateWhere(t.patterns):t.type==="bgp"?n=this.translateBGP(t):n=this.translatePattern(t),{type:"exists",negated:e.operator==="notexists",pattern:n}}translateInExpression(e){if(!e.args||e.args.length!==2)throw new me("IN/NOT IN must have exactly 2 arguments (expression and list)");let t=e.args[0],n=e.args[1];if(!Array.isArray(n))throw new me("IN/NOT IN second argument must be an array of values");return{type:"in",expression:this.translateExpression(t),list:n.map(i=>this.translateExpression(i)),negated:e.operator==="notin"}}translateTermExpression(e){if(e.termType==="Variable")return{type:"variable",name:e.value};if(e.termType==="Literal"){let t=e.value;return e.datatype&&(e.datatype.value.includes("#integer")||e.datatype.value.includes("#decimal")?t=parseFloat(e.value):e.datatype.value.includes("#boolean")&&(t=e.value==="true")),{type:"literal",value:t,datatype:e.datatype?.value}}return{type:"literal",value:String(e.value||e)}}translateOptional(e){if(!e.patterns||e.patterns.length===0)throw new me("OPTIONAL pattern must have patterns");return{type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns),expression:e.expression?this.translateExpression(e.expression):void 0}}translateUnion(e){if(!e.patterns||e.patterns.length<2)throw new me("UNION pattern must have at least 2 patterns");let t=o(i=>i.type==="graph"?this.translateGraph(i):i.type==="service"?this.translateService(i):i.patterns&&Array.isArray(i.patterns)?this.translateWhere(i.patterns):this.translateWhere([i]),"translateBranch"),n={type:"union",left:t(e.patterns[0]),right:t(e.patterns[1])};for(let i=2;i<e.patterns.length;i++)n={type:"union",left:n,right:t(e.patterns[i])};return n}translateMinus(e){if(!e.patterns||e.patterns.length===0)throw new me("MINUS pattern must have patterns");return{type:"minus",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns)}}translateValues(e){if(!e.values||!Array.isArray(e.values))throw new me("VALUES pattern must have values array");let t=new Set;for(let i of e.values)for(let s of Object.keys(i)){let a=s.startsWith("?")?s.slice(1):s;t.add(a)}let n=e.values.map(i=>this.translateValuesBinding(i));return{type:"values",variables:Array.from(t),bindings:n}}translateValuesBinding(e){let t={};for(let[n,i]of Object.entries(e)){let s=n.startsWith("?")?n.slice(1):n,a=i;if(a)if(a.termType==="NamedNode")t[s]={type:"iri",value:a.value};else if(a.termType==="Literal"){let c={type:"literal",value:a.value,datatype:a.datatype?.value,language:a.language||void 0};if(a.language){let u=this.directionMappings.get(a.language.toLowerCase());u&&(c.direction=u)}t[s]=c}else throw new me(`Unsupported VALUES term type: ${a.termType}`)}return t}translateBind(e,t){if(!e.variable||!e.expression)throw new me("BIND pattern must have variable and expression");return{type:"extend",variable:e.variable.value,expression:this.translateExpression(e.expression),input:t}}translateOrderComparator(e){return{expression:this.translateExpression(e.expression),descending:e.descending||!1}}isLateralSubquery(e){return e.queryType!=="SELECT"||!e.variables?!1:e.variables.some(t=>t.termType==="Variable"&&t.value===Rb.LateralTransformer.LATERAL_MARKER)}removeLateralMarker(e){return e.variables?{...e,variables:e.variables.filter(t=>!(t.termType==="Variable"&&t.value===Rb.LateralTransformer.LATERAL_MARKER))}:e}translateSubquery(e){if(e.queryType!=="SELECT")throw new me(`Only SELECT subqueries are supported, got: ${e.queryType}`);let t=this.removeLateralMarker(e);return{type:"subquery",query:this.translateSelect(t)}}translateService(e){if(!e.name||e.name.termType!=="NamedNode")throw new me("SERVICE pattern must have a NamedNode endpoint");if(!e.patterns||!Array.isArray(e.patterns))throw new me("SERVICE pattern must have patterns array");let t=this.translateWhere(e.patterns);return{type:"service",endpoint:e.name.value,pattern:t,silent:e.silent||!1}}translateGraph(e){if(!e.name)throw new me("GRAPH pattern must have a name (IRI or variable)");if(!e.patterns||!Array.isArray(e.patterns))throw new me("GRAPH pattern must have patterns array");let t;if(e.name.termType==="NamedNode")t={type:"iri",value:e.name.value};else if(e.name.termType==="Variable")t={type:"variable",value:e.name.value};else throw new me(`GRAPH pattern name must be NamedNode or Variable, got: ${e.name.termType}`);let n=this.translateWhere(e.patterns);return{type:"graph",name:t,pattern:n}}translateDescribe(e){let t=[];if(e.variables&&Array.isArray(e.variables))for(let s of e.variables){let a=s;a.termType==="Wildcard"||a.value==="*"||(a.termType==="Variable"?t.push({type:"variable",value:a.value}):a.termType==="NamedNode"&&t.push({type:"iri",value:a.value}))}let n;e.where&&e.where.length>0&&(n=this.translateWhere(e.where));let i=e.describeOptions;return{type:"describe",resources:t,where:n,depth:i?.depth,symmetric:i?.symmetric}}};co.AlgebraTranslator=ey});var ry=_(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});Xf.FilterContainsOptimizer=void 0;var jN=Ye(),$N=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,ty=class{static{o(this,"FilterContainsOptimizer")}constructor(){this.tripleStore=null,this.lastOptimizationHints=[]}setTripleStore(e){this.tripleStore=e}getLastOptimizationHints(){return this.lastOptimizationHints}clearHints(){this.lastOptimizationHints=[]}async optimize(e){return this.clearHints(),this.optimizeRecursive(e)}optimizeSync(e,t){return this.clearHints(),this.optimizeSyncRecursive(e,t)}async optimizeRecursive(e){return e.type==="filter"?this.optimizeFilter(e):e.type==="join"?{type:"join",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="leftjoin"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="union"?{type:"union",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="minus"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="project"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="orderby"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="slice"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="distinct"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="reduced"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="group"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="extend"?{...e,input:await this.optimizeRecursive(e.input)}:e}optimizeSyncRecursive(e,t){return e.type==="filter"?this.optimizeFilterSync(e,t):e.type==="join"?{type:"join",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="leftjoin"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="union"?{type:"union",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="minus"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="project"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="orderby"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="slice"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="distinct"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="reduced"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="group"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="extend"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e}async optimizeFilter(e){let t=this.detectContainsUUIDPattern(e.expression);if(!t)return{type:"filter",expression:e.expression,input:await this.optimizeRecursive(e.input)};let n=[];return this.tripleStore&&(n=await this.findSubjectsContainingUUID(t.uuid)),this.rewriteFilter(e,t,n)}optimizeFilterSync(e,t){let n=this.detectContainsUUIDPattern(e.expression);if(!n)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input,t)};let i=t?t.filter(s=>s.includes(n.uuid)):[];return this.rewriteFilter(e,n,i)}rewriteFilter(e,t,n){if(this.lastOptimizationHints.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${t.variable}), "${t.uuid}"))`,suggestedRewrite:n.length===1?`VALUES ?${t.variable} { <${n[0]}> }`:n.length>1?`VALUES ?${t.variable} { ${n.map(i=>`<${i}>`).join(" ")} }`:"No matching URIs found for UUID",estimatedSpeedup:n.length>0?"O(n) \u2192 O(1)":"N/A",matchedUri:n.length===1?n[0]:void 0}),n.length===0)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input)};if(n.length===1){let i=this.injectSubjectConstraint(e.input,t.variable,n[0]);if(i!==e.input)return i}return this.createValuesJoin(e,t,n)}detectContainsUUIDPattern(e){if(e.type==="function"||e.type==="functionCall"){let t=e;if((typeof t.function=="string"?t.function.toLowerCase():t.function?.value?.toLowerCase()??"")==="contains"&&t.args.length===2)return this.analyzeContainsArgs(t.args[0],t.args[1],e)}if(e.type==="logical"&&e.operator==="&&")for(let t of e.operands){let n=this.detectContainsUUIDPattern(t);if(n)return n}return null}analyzeContainsArgs(e,t,n){let i=null;if(e.type==="function"||e.type==="functionCall"){let s=e;if((typeof s.function=="string"?s.function.toLowerCase():s.function?.value?.toLowerCase()??"")==="str"&&s.args.length===1){let c=s.args[0];c.type==="variable"&&(i=c.name)}}if(!i&&e.type==="variable"&&(i=e.name),!i)return null;if(t.type==="literal"){let c=String(t.value).match($N);if(c)return{variable:i,uuid:c[0].toLowerCase(),originalExpression:n}}return null}async findSubjectsContainingUUID(e){if(!this.tripleStore)return[];if(this.tripleStore.findSubjectsByUUID)return(await this.tripleStore.findSubjectsByUUID(e)).map(s=>s.value);let t=await this.tripleStore.subjects(),n=[];for(let i of t)i instanceof jN.IRI&&i.value.toLowerCase().includes(e.toLowerCase())&&n.push(i.value);return n}injectSubjectConstraint(e,t,n){if(e.type==="bgp"){let i=e.triples.map(a=>a.subject.type==="variable"&&a.subject.value===t?{...a,subject:{type:"iri",value:n}}:a);if(i.some((a,c)=>a.subject!==e.triples[c].subject))return{type:"bgp",triples:i}}if(e.type==="join"){let i=this.injectSubjectConstraint(e.left,t,n),s=this.injectSubjectConstraint(e.right,t,n);if(i!==e.left||s!==e.right)return{type:"join",left:i,right:s}}if(e.type==="filter"){let i=this.injectSubjectConstraint(e.input,t,n);if(i!==e.input)return{...e,input:i}}return e}createValuesJoin(e,t,n){return{type:"join",left:{type:"values",variables:[t.variable],bindings:n.map(a=>({[t.variable]:{type:"iri",value:a}}))},right:this.optimizeSyncRecursive(e.input)}}analyzeQuery(e){let t=[];return this.analyzeRecursive(e,t),t}analyzeRecursive(e,t){if(e.type==="filter"){let n=this.detectContainsUUIDPattern(e.expression);n&&t.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${n.variable}), "${n.uuid}"))`,suggestedRewrite:`Use --optimize flag or rewrite as VALUES ?${n.variable} { <uri-containing-uuid> }`,estimatedSpeedup:"O(n) \u2192 O(1) with UUID index lookup"}),this.analyzeRecursive(e.input,t);return}e.type==="join"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="leftjoin"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="union"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="minus"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="project"?this.analyzeRecursive(e.input,t):e.type==="orderby"?this.analyzeRecursive(e.input,t):e.type==="slice"?this.analyzeRecursive(e.input,t):e.type==="distinct"?this.analyzeRecursive(e.input,t):e.type==="reduced"?this.analyzeRecursive(e.input,t):e.type==="group"?this.analyzeRecursive(e.input,t):e.type==="extend"&&this.analyzeRecursive(e.input,t)}};Xf.FilterContainsOptimizer=ty});var Lb=_(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});Jf.AlgebraOptimizer=void 0;var BN=ry(),ny=class{static{o(this,"AlgebraOptimizer")}constructor(){this.stats=new Map,this.tripleStore=null,this.filterContainsOptimizer=new BN.FilterContainsOptimizer}setTripleStore(e){this.tripleStore=e,this.filterContainsOptimizer.setTripleStore(e)}getOptimizationHints(){return this.filterContainsOptimizer.getLastOptimizationHints()}analyzeQuery(e){return this.filterContainsOptimizer.analyzeQuery(e)}optimize(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),t=this.filterPushDown(t),t=this.joinReordering(t),t}async optimizeAsync(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),this.tripleStore&&(t=await this.filterContainsOptimizer.optimize(t)),t=this.filterPushDown(t),t=this.joinReordering(t),t}optimizeWithSubjects(e,t){let n=e;return n=this.eliminateEmptyBGPInFilterJoin(n),n=this.filterContainsOptimizer.optimizeSync(n,t),n=this.filterPushDown(n),n=this.joinReordering(n),n}eliminateEmptyBGPInFilterJoin(e){if(e.type==="join"){if(e.left.type==="filter"){let t=e.left;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.right)}}if(e.right.type==="filter"){let t=e.right;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.left)}}return{type:"join",left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}}return e.type==="filter"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="leftjoin"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="union"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="minus"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="project"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="orderby"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="slice"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="distinct"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e}filterPushDown(e){return e.type==="filter"?this.pushDownFilter(e):e.type==="join"?{type:"join",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="leftjoin"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="union"?{type:"union",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="minus"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="project"?{...e,input:this.filterPushDown(e.input)}:e.type==="orderby"?{...e,input:this.filterPushDown(e.input)}:e.type==="slice"?{...e,input:this.filterPushDown(e.input)}:e.type==="distinct"?{...e,input:this.filterPushDown(e.input)}:e}pushDownFilter(e){let t=e.input;if(t.type==="join"){let n=this.getFilterVariables(e.expression),i=this.getOperationVariables(t.left),s=this.getOperationVariables(t.right),a=n.every(u=>i.has(u)),c=n.every(u=>s.has(u));return a&&!c?{type:"join",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:this.filterPushDown(t.right)}:c&&!a?{type:"join",left:this.filterPushDown(t.left),right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:{type:"join",left:this.filterPushDown(t.left),right:this.filterPushDown(t.right)}}}return t.type==="union"?{type:"union",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:this.filterPushDown(t)}}getFilterVariables(e){let t=[];if(e.type==="variable")t.push(e.name);else if(e.type==="comparison")t.push(...this.getFilterVariables(e.left)),t.push(...this.getFilterVariables(e.right));else if(e.type==="logical")for(let n of e.operands)t.push(...this.getFilterVariables(n));else if(e.type==="function")for(let n of e.args)t.push(...this.getFilterVariables(n));return Array.from(new Set(t))}getOperationVariables(e){let t=new Set;if(e.type==="bgp")for(let n of e.triples)n.subject.type==="variable"&&t.add(n.subject.value),n.predicate.type==="variable"&&t.add(n.predicate.value),n.object.type==="variable"&&t.add(n.object.value);else if(e.type==="join"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else{if(e.type==="filter")return this.getOperationVariables(e.input);if(e.type==="leftjoin"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else if(e.type==="union"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else{if(e.type==="minus")return this.getOperationVariables(e.left);if(e.type==="project")return new Set(e.variables)}}return t}joinReordering(e){return e.type==="join"?this.reorderJoin(e):e.type==="filter"?{...e,input:this.joinReordering(e.input)}:e.type==="leftjoin"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="union"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="minus"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="project"?{...e,input:this.joinReordering(e.input)}:e.type==="orderby"?{...e,input:this.joinReordering(e.input)}:e.type==="slice"?{...e,input:this.joinReordering(e.input)}:e.type==="distinct"?{...e,input:this.joinReordering(e.input)}:e}reorderJoin(e){let t=this.estimateCost(e.left);return this.estimateCost(e.right)<t?{type:"join",left:this.joinReordering(e.right),right:this.joinReordering(e.left)}:{type:"join",left:this.joinReordering(e.left),right:this.joinReordering(e.right)}}estimateCost(e){if(e.type==="bgp"){let t=e.triples.length*100;for(let n of e.triples)n.subject.type==="variable"&&(t+=10),n.predicate.type==="variable"&&(t+=20),n.object.type==="variable"&&(t+=10);return t}return e.type==="filter"?this.estimateCost(e.input)*.3:e.type==="join"?this.estimateCost(e.left)*this.estimateCost(e.right):e.type==="leftjoin"?this.estimateCost(e.left)+this.estimateCost(e.right)*.5:e.type==="union"?this.estimateCost(e.left)+this.estimateCost(e.right):e.type==="minus"?this.estimateCost(e.left)+this.estimateCost(e.right)*.3:100}setStatistics(e,t){this.stats.set(e,t)}getStatistics(e){return this.stats.get(e)}};Jf.AlgebraOptimizer=ny});var Mb=_(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});Zf.AlgebraSerializer=void 0;var iy=class{static{o(this,"AlgebraSerializer")}toString(e,t=0){let n=" ".repeat(t);switch(e.type){case"bgp":return`${n}BGP [
261
261
  ${e.triples.map(l=>`${n} ${this.tripleToString(l)}`).join(`
262
262
  `)}
263
263
  ${n}]`;case"filter":return`${n}Filter(
@@ -289,7 +289,7 @@ ${n})`;case"extend":return`${n}Extend (?${e.variable} = ${this.expressionToStrin
289
289
  ${this.toString(e.input,t+1)}
290
290
  ${n})`;case"subquery":return`${n}Subquery(
291
291
  ${this.toString(e.query,t+1)}
292
- ${n})`;default:return`${n}Unknown(${e.type})`}}tripleToString(e){return`${this.elementToString(e.subject)} ${this.predicateToString(e.predicate)} ${this.elementToString(e.object)}`}predicateToString(e){return this.isPropertyPath(e)?this.propertyPathToString(e):this.elementToString(e)}isPropertyPath(e){return e.type==="path"}propertyPathToString(e){let t=e.items.map(n=>n.type==="path"?`(${this.propertyPathToString(n)})`:`<${n.value}>`);switch(e.pathType){case"/":return t.join("/");case"|":return t.join("|");case"^":return`^${t[0]}`;case"+":return`${t[0]}+`;case"*":return`${t[0]}*`;case"?":return`${t[0]}?`}}elementToString(e){switch(e.type){case"variable":return`?${e.value}`;case"iri":return`<${e.value}>`;case"literal":let t=`"${e.value}"`;return e.language&&(t+=`@${e.language}`),e.datatype&&(t+=`^^<${e.datatype}>`),t;case"blank":return`_:${e.value}`;default:return String(e)}}expressionToString(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value}"`:String(e.value);case"comparison":return`(${this.expressionToString(e.left)} ${e.operator} ${this.expressionToString(e.right)})`;case"logical":return e.operator==="!"?`!(${this.expressionToString(e.operands[0])})`:`(${e.operands.map(t=>this.expressionToString(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.expressionToString(e.left)} ${e.operator} ${this.expressionToString(e.right)})`;case"function":return`${e.function}(${e.args.map(t=>this.expressionToString(t)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.toString(e.pattern,0)} }`;default:return"unknown"}}toJSON(e){return JSON.stringify(e,null,2)}};Zf.AlgebraSerializer=iy});var Hi=_(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});eh.SolutionMapping=void 0;var kb=ht(),jb=Ye(),$b=Rt(),sy=class r{static{o(this,"SolutionMapping")}constructor(e){this.bindings=e?new Map(e):new Map}get(e){return this.bindings.get(e)}set(e,t){this.bindings.set(e,t)}has(e){return this.bindings.has(e)}variables(){return Array.from(this.bindings.keys())}getBindings(){return new Map(this.bindings)}isCompatibleWith(e){for(let[t,n]of this.bindings.entries()){let i=e.get(t);if(i!==void 0&&!this.areEqual(n,i))return!1}return!0}merge(e){if(!this.isCompatibleWith(e))return null;let t=new r(this.bindings);for(let[n,i]of e.getBindings().entries())t.set(n,i);return t}clone(){return new r(this.bindings)}areEqual(e,t){return e instanceof kb.Literal&&t instanceof kb.Literal?e.equals(t):e instanceof jb.IRI&&t instanceof jb.IRI?e.value===t.value:e instanceof $b.BlankNode&&t instanceof $b.BlankNode?e.id===t.id:!1}toJSON(){let e={};for(let[t,n]of this.bindings.entries())e[t]=n.toString();return e}size(){return this.bindings.size}};eh.SolutionMapping=sy});var Vb=_(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.PropertyPathExecutor=uo.PropertyPathExecutorError=void 0;var VN=Hi(),th=Ye(),Bb=Rt(),Yc=class extends Error{static{o(this,"PropertyPathExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="PropertyPathExecutorError"}};uo.PropertyPathExecutorError=Yc;var ay=class{static{o(this,"PropertyPathExecutor")}constructor(e){this.tripleStore=e,this.MAX_DEPTH=100}async*execute(e,t,n){let i=await this.resolveElement(e),s=this.isVariable(n)?null:await this.resolveElement(n);for(let a of i){let c=await this.evaluatePath(a,t,s);for(let u of c){let l=new VN.SolutionMapping;this.isVariable(e)&&l.set(e.value,a),this.isVariable(n)&&l.set(n.value,u),yield l}}}async*executeWithBindings(e,t){if(!this.isPropertyPath(e.predicate))throw new Yc("Predicate is not a property path");let n=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.object,t);for await(let s of this.execute(n,e.predicate,i)){let a=t.merge(s);a!==null&&(yield a)}}async evaluatePath(e,t,n){switch(t.pathType){case"/":return this.evaluateSequencePath(e,t.items,n);case"|":return this.evaluateAlternativePath(e,t.items,n);case"^":return this.evaluateInversePath(e,t.items[0],n);case"+":return this.evaluateOneOrMorePath(e,t.items[0],n);case"*":return this.evaluateZeroOrMorePath(e,t.items[0],n);case"?":return this.evaluateZeroOrOnePath(e,t.items[0],n)}}async evaluateSequencePath(e,t,n){let i=new Set([e]);for(let s=0;s<t.length;s++){let a=t[s],c=s===t.length-1,u=new Set;for(let l of i){let f=await this.evaluatePathItem(l,a,c?n:null);for(let h of f)u.add(h)}if(i=u,i.size===0)break}return i}async evaluateAlternativePath(e,t,n){let i=new Set;for(let s of t){let a=await this.evaluatePathItem(e,s,n);for(let c of a)i.add(c)}return i}async evaluateInversePath(e,t,n){if(t.type==="iri"){let i=new th.IRI(t.value),s=await this.tripleStore.match(void 0,i,e),a=new Set;for(let c of s)(n===null||this.nodeInSet(c.subject,n))&&a.add(c.subject);return a}else return this.evaluatePath(e,this.invertPath(t),n)}async evaluateOneOrMorePath(e,t,n){let i=new Set,s=new Set,a=[{node:e,depth:0}];for(;a.length>0;){let{node:c,depth:u}=a.shift();if(u>=this.MAX_DEPTH)continue;let l=await this.evaluatePathItem(c,t,null);for(let f of l){let h=this.nodeToKey(f);(n===null||this.nodeInSet(f,n))&&s.add(f),i.has(h)||(i.add(h),a.push({node:f,depth:u+1}))}}return s}async evaluateZeroOrMorePath(e,t,n){let i=await this.evaluateOneOrMorePath(e,t,n);return(n===null||this.nodeInSet(e,n))&&i.add(e),i}async evaluateZeroOrOnePath(e,t,n){let i=new Set;(n===null||this.nodeInSet(e,n))&&i.add(e);let s=await this.evaluatePathItem(e,t,n);for(let a of s)i.add(a);return i}async evaluatePathItem(e,t,n){if(t.type==="iri"){let i=new th.IRI(t.value),s=await this.tripleStore.match(e,i,void 0),a=new Set;for(let c of s)(n===null||this.nodeInSet(c.object,n))&&a.add(c.object);return a}else return this.evaluatePath(e,t,n)}invertPath(e){switch(e.pathType){case"^":return e.items[0];case"/":return{type:"path",pathType:"/",items:[...e.items].reverse().map(n=>n.type==="iri"?{type:"path",pathType:"^",items:[n]}:this.invertPath(n))};case"|":return{type:"path",pathType:"|",items:e.items.map(n=>n.type==="iri"?{type:"path",pathType:"^",items:[n]}:this.invertPath(n))};case"+":case"*":case"?":let t=e.items[0].type==="iri"?{type:"path",pathType:"^",items:[e.items[0]]}:this.invertPath(e.items[0]);return{type:"path",pathType:e.pathType,items:[t]}}}async resolveElement(e){if(this.isVariable(e)){let n=new Set,i=await this.tripleStore.match(void 0,void 0,void 0);for(let s of i)n.add(s.subject),n.add(s.object);return n}let t=new Set;switch(e.type){case"iri":t.add(new th.IRI(e.value));break;case"blank":t.add(new Bb.BlankNode(e.value));break;default:throw new Yc(`Unsupported element type in subject/object position: ${e.type}`)}return t}instantiateElement(e,t){if(this.isVariable(e)){let n=t.get(e.value);if(n){if(n instanceof th.IRI)return{type:"iri",value:n.value};if(n instanceof Bb.BlankNode)return{type:"blank",value:n.id}}}return e}isVariable(e){return e.type==="variable"}isPropertyPath(e){return e.type==="path"}nodeToKey(e){return e.toString()}nodeInSet(e,t){let n=this.nodeToKey(e);for(let i of t)if(this.nodeToKey(i)===n)return!0;return!1}};uo.PropertyPathExecutor=ay});var uy=_(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.BGPExecutor=lo.BGPExecutorError=void 0;var rh=Hi(),gs=Ye(),oy=ht(),nh=Rt(),ih=wc(),UN=Vb(),fr=class extends Error{static{o(this,"BGPExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="BGPExecutorError"}};lo.BGPExecutorError=fr;var cy=class{static{o(this,"BGPExecutor")}constructor(e){this.tripleStore=e,this.propertyPathExecutor=new UN.PropertyPathExecutor(e)}async*execute(e){if(e.triples.length===0){yield new rh.SolutionMapping;return}let t=this.matchTriplePattern(e.triples[0]);for(let n=1;n<e.triples.length;n++)t=this.joinWithPattern(t,e.triples[n]);for await(let n of t)yield n}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*executeInGraph(e,t){if(e.triples.length===0){yield new rh.SolutionMapping;return}let n=this.matchTriplePatternInGraph(e.triples[0],t);for(let i=1;i<e.triples.length;i++)n=this.joinWithPatternInGraph(n,e.triples[i],t);for await(let i of n)yield i}async*matchTriplePatternInGraph(e,t){if(this.isPropertyPath(e.predicate))throw new fr("Property paths within named graphs are not yet supported");let n=e.predicate,i=this.isVariable(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),s=this.isVariable(n)?void 0:this.toRDFTermAsPredicate(n),a=this.isVariable(e.object)?void 0:this.toRDFTerm(e.object);if(!this.tripleStore.matchInGraph)throw new fr("Triple store does not support named graph operations");let c=await this.tripleStore.matchInGraph(i,s,a,t);for(let u of c){let l=new rh.SolutionMapping;this.isVariable(e.subject)&&l.set(e.subject.value,u.subject),this.isVariable(n)&&l.set(n.value,u.predicate),this.isVariable(e.object)&&l.set(e.object.value,u.object),yield l}}async*joinWithPatternInGraph(e,t,n){let i=[];for await(let s of e)i.push(s);for(let s of i){let a=this.instantiatePattern(t,s);for await(let c of this.matchTriplePatternInGraph(a,n)){let u=s.merge(c);u!==null&&(yield u)}}}async*matchTriplePattern(e){if(this.isPropertyPath(e.predicate)){yield*this.propertyPathExecutor.execute(e.subject,e.predicate,e.object);return}let t=e.predicate,n=this.isVariable(e.subject)||this.isQuotedTriple(e.subject)&&this.hasVariablesInQuotedTriple(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),i=this.isVariable(t)?void 0:this.toRDFTermAsPredicate(t),s=this.isVariable(e.object)||this.isQuotedTriple(e.object)&&this.hasVariablesInQuotedTriple(e.object)?void 0:this.toRDFTerm(e.object),a=await this.tripleStore.match(n,i,s);for(let c of a){let u=new rh.SolutionMapping;if(this.isVariable(e.subject))u.set(e.subject.value,c.subject);else if(this.isQuotedTriple(e.subject)){let l=this.matchQuotedTriplePattern(e.subject,c.subject);if(l===null)continue;for(let[f,h]of l.entries())u.set(f,h)}if(this.isVariable(t)&&u.set(t.value,c.predicate),this.isVariable(e.object))u.set(e.object.value,c.object);else if(this.isQuotedTriple(e.object)){let l=this.matchQuotedTriplePattern(e.object,c.object);if(l===null)continue;for(let[f,h]of l.entries())u.set(f,h)}yield u}}hasVariablesInQuotedTriple(e){return!!(this.isVariable(e.subject)||e.predicate.type==="variable"||this.isVariable(e.object)||this.isQuotedTriple(e.subject)&&this.hasVariablesInQuotedTriple(e.subject)||this.isQuotedTriple(e.object)&&this.hasVariablesInQuotedTriple(e.object))}matchQuotedTriplePattern(e,t){if(!(t instanceof ih.QuotedTriple))return null;let n=new Map;if(this.isVariable(e.subject))n.set(e.subject.value,t.subject);else if(this.isQuotedTriple(e.subject)){let i=this.matchQuotedTriplePattern(e.subject,t.subject);if(i===null)return null;for(let[s,a]of i)n.set(s,a)}else if(!this.elementsMatch(e.subject,t.subject))return null;if(e.predicate.type==="variable")n.set(e.predicate.value,t.predicate);else if(e.predicate.value!==t.predicate.value)return null;if(this.isVariable(e.object))n.set(e.object.value,t.object);else if(this.isQuotedTriple(e.object)){let i=this.matchQuotedTriplePattern(e.object,t.object);if(i===null)return null;for(let[s,a]of i)n.set(s,a)}else if(!this.elementsMatch(e.object,t.object))return null;return n}elementsMatch(e,t){switch(e.type){case"iri":return t instanceof gs.IRI&&e.value===t.value;case"literal":return!(!(t instanceof oy.Literal)||e.value!==t.value||e.datatype!==t.datatype?.value||e.language!==t.language||e.direction!==t.direction);case"blank":return t instanceof nh.BlankNode&&e.value===t.id;case"quoted":return t instanceof ih.QuotedTriple?this.toRDFQuotedTriple(e).equals(t):!1;default:return!1}}isPropertyPath(e){return e.type==="path"}async*joinWithPattern(e,t){let n=[];for await(let i of e)n.push(i);for(let i of n){let s=this.instantiatePattern(t,i);for await(let a of this.matchTriplePattern(s)){let c=i.merge(a);c!==null&&(yield c)}}}instantiatePattern(e,t){let n=this.isPropertyPath(e.predicate)?e.predicate:this.instantiateElement(e.predicate,t);return{subject:this.instantiateElement(e.subject,t),predicate:n,object:this.instantiateElement(e.object,t)}}instantiateElement(e,t){if(this.isVariable(e)){let n=t.get(e.value);if(n)return this.toAlgebraElement(n)}return this.isQuotedTriple(e)?this.instantiateQuotedTriple(e,t):e}instantiateQuotedTriple(e,t){let n=this.instantiateElement(e.subject,t),i=e.predicate.type==="variable"?this.instantiatePredicateVariable(e.predicate,t):e.predicate,s=this.instantiateElement(e.object,t);return{type:"quoted",subject:n,predicate:i,object:s}}instantiatePredicateVariable(e,t){let n=t.get(e.value);return n&&n instanceof gs.IRI?{type:"iri",value:n.value}:e}isVariable(e){return e.type==="variable"}isQuotedTriple(e){return e.type==="quoted"}toRDFTermAsSubject(e){switch(e.type){case"iri":return new gs.IRI(e.value);case"blank":return new nh.BlankNode(e.value);case"literal":throw new fr("Literals cannot appear in subject position");case"variable":throw new fr(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new fr(`Unknown element type: ${e.type}`)}}toRDFQuotedTriple(e){let t=this.toRDFTermAsSubject(e.subject),n=e.predicate.type==="iri"?new gs.IRI(e.predicate.value):(()=>{throw new fr("Quoted triple predicate must be IRI")})(),i=this.toRDFTerm(e.object);return new ih.QuotedTriple(t,n,i)}toRDFTermAsPredicate(e){switch(e.type){case"iri":return new gs.IRI(e.value);case"literal":throw new fr("Literals cannot appear in predicate position");case"blank":throw new fr("Blank nodes cannot appear in predicate position");case"variable":throw new fr(`Cannot convert variable to RDF term: ${e.value}`);default:throw new fr(`Unknown element type: ${e.type}`)}}toRDFTerm(e){switch(e.type){case"iri":return new gs.IRI(e.value);case"literal":return new oy.Literal(e.value,e.datatype?new gs.IRI(e.datatype):void 0,e.language,e.direction);case"blank":return new nh.BlankNode(e.value);case"variable":throw new fr(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new fr(`Unknown element type: ${e.type}`)}}toAlgebraElement(e){if(e instanceof gs.IRI)return{type:"iri",value:e.value};if(e instanceof oy.Literal)return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language,direction:e.direction};if(e instanceof nh.BlankNode)return{type:"blank",value:e.id};if(e instanceof ih.QuotedTriple)return this.toAlgebraQuotedTriple(e);throw new fr(`Unknown RDF term type: ${e.constructor?.name||"unknown"}`)}toAlgebraQuotedTriple(e){return{type:"quoted",subject:this.toAlgebraElement(e.subject),predicate:{type:"iri",value:e.predicate.value},object:this.toAlgebraElement(e.object)}}};lo.BGPExecutor=cy});var ah=_(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});sh.BuiltInFunctions=void 0;var ge=Ye(),D=ht(),Or=Rt(),fo=wc(),ly=Er(),Qc=class{static{o(this,"BuiltInFunctions")}static str(e){if(e===void 0)throw new Error("STR: argument is undefined");return e instanceof ge.IRI||e instanceof D.Literal?e.value:e instanceof Or.BlankNode?e.id:String(e)}static lang(e){if(e===void 0)throw new Error("LANG: argument is undefined");return e instanceof D.Literal&&e.language?e.language:""}static langdir(e){if(e===void 0)throw new Error("LANGDIR: argument is undefined");return!(e instanceof D.Literal)||!e.language?"":e.direction?`${e.language}--${e.direction}`:e.language}static langMatches(e,t){let[n,i]=this.parseDirectionalLangTag(e),[s,a]=this.parseDirectionalLangTag(t),c=n.toLowerCase(),u=s.toLowerCase();return u==="*"?c!=="":c===""?u==="":a&&i!==a?!1:c===u?!0:c.startsWith(u+"-")}static parseDirectionalLangTag(e){let t=e.indexOf("--");if(t===-1)return[e,void 0];let n=e.substring(0,t),i=e.substring(t+2).toLowerCase();return[n,i]}static datatype(e){if(e===void 0)throw new Error("DATATYPE: argument is undefined");if(e instanceof D.Literal)return e.datatype?e.datatype:e.language?new ge.IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"):new ge.IRI("http://www.w3.org/2001/XMLSchema#string");throw new Error("DATATYPE: argument must be a literal")}static bound(e){return e!==void 0}static isIRI(e){return e===void 0?!1:e instanceof ge.IRI}static isBlank(e){return e===void 0?!1:e instanceof Or.BlankNode}static isLiteral(e){return e===void 0?!1:e instanceof D.Literal}static isTriple(e){return e===void 0?!1:e instanceof fo.QuotedTriple}static hasLangdir(e){return e===void 0||!(e instanceof D.Literal)?!1:!!e.language&&!!e.direction}static isNumeric(e){if(e===void 0||!(e instanceof D.Literal))return!1;let t=e.datatype?.value;return t?["http://www.w3.org/2001/XMLSchema#integer","http://www.w3.org/2001/XMLSchema#decimal","http://www.w3.org/2001/XMLSchema#float","http://www.w3.org/2001/XMLSchema#double","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#long","http://www.w3.org/2001/XMLSchema#int","http://www.w3.org/2001/XMLSchema#short","http://www.w3.org/2001/XMLSchema#byte","http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#unsignedLong","http://www.w3.org/2001/XMLSchema#unsignedInt","http://www.w3.org/2001/XMLSchema#unsignedShort","http://www.w3.org/2001/XMLSchema#unsignedByte","http://www.w3.org/2001/XMLSchema#positiveInteger"].includes(t):!1}static regex(e,t,n){try{return new RegExp(t,n).test(e)}catch(i){throw new Error(`REGEX: invalid pattern '${t}': ${i.message}`)}}static compare(e,t,n){if(this.isDayTimeDurationValue(e)&&this.isDayTimeDurationValue(t))return this.compareDurations(e instanceof D.Literal?e:String(e),t instanceof D.Literal?t:String(t),n);let i=this.toComparableValue(e),s=this.toComparableValue(t);switch(n){case"=":return i===s;case"!=":return i!==s;case"<":return i<s;case">":return i>s;case"<=":return i<=s;case">=":return i>=s;default:throw new Error(`Unknown comparison operator: ${n}`)}}static isDayTimeDurationValue(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static toComparableValue(e){if(typeof e=="string"||typeof e=="number")return e;if(e instanceof D.Literal){let t=e.datatype?.value;if(t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double")){let n=parseFloat(e.value);if(!isNaN(n))return n}if(t==="http://www.w3.org/2001/XMLSchema#dayTimeDuration")try{return this.parseDayTimeDuration(e.value)}catch{return e.value}return e.value}return e instanceof ge.IRI?e.value:e instanceof Or.BlankNode?e.id:String(e)}static contains(e,t){return e.includes(t)}static strStarts(e,t){return e.startsWith(t)}static strEnds(e,t){return e.endsWith(t)}static strlen(e){return e.length}static ucase(e){return e.toUpperCase()}static lcase(e){return e.toLowerCase()}static substr(e,t,n){let i=t-1;if(i<0){if(n!==void 0){let s=n+i;return s<=0?"":e.substring(0,s)}return e}return n!==void 0?e.substring(i,i+n):e.substring(i)}static strBefore(e,t){if(t==="")return"";let n=e.indexOf(t);return n===-1?"":e.substring(0,n)}static strAfter(e,t){if(t==="")return e;let n=e.indexOf(t);return n===-1?"":e.substring(n+t.length)}static concat(...e){return e.join("")}static replace(e,t,n,i){try{let s=new RegExp(t,i||"g");return e.replace(s,n)}catch(s){throw new Error(`REPLACE: invalid pattern '${t}': ${s.message}`)}}static parseDate(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`PARSEDATE: invalid date string '${e}'`);return t.getTime()}static dateBefore(e,t){let n=this.parseDate(e),i=this.parseDate(t);return n<i}static dateAfter(e,t){let n=this.parseDate(e),i=this.parseDate(t);return n>i}static dateInRange(e,t,n){let i=this.parseDate(e),s=this.parseDate(t),a=this.parseDate(n);return i>=s&&i<=a}static dateDiffMinutes(e,t){let n=this.parseDate(e),i=this.parseDate(t),s=Math.abs(i-n);return Math.round(s/(1e3*60))}static dateDiffHours(e,t){let n=this.parseDate(e),i=this.parseDate(t),s=Math.abs(i-n);return Math.round(s/(1e3*60*60)*100)/100}static logicalAnd(e){return e.every(t=>t===!0)}static logicalOr(e){return e.some(t=>t===!0)}static logicalNot(e){return!e}static year(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`YEAR: invalid date string '${e}'`);return t.getFullYear()}static month(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`MONTH: invalid date string '${e}'`);return t.getMonth()+1}static day(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`DAY: invalid date string '${e}'`);return t.getDate()}static hours(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`HOURS: invalid date string '${e}'`);return t.getHours()}static minutes(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`MINUTES: invalid date string '${e}'`);return t.getMinutes()}static seconds(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`SECONDS: invalid date string '${e}'`);return t.getSeconds()+t.getMilliseconds()/1e3}static timezone(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TIMEZONE: invalid date string '${e}'`);let n;if(e.endsWith("Z"))n="PT0S";else{let i=e.match(/([+-]\d{2}):?(\d{2})$/);if(i){let s=parseInt(i[1],10),a=parseInt(i[2],10),c=s>=0?"":"-",u=Math.abs(s);a===0?n=`${c}PT${u}H`:n=`${c}PT${u}H${a}M`}else{let s=-t.getTimezoneOffset(),a=Math.floor(Math.abs(s)/60),c=Math.abs(s)%60,u=s>=0?"":"-";c===0?n=`${u}PT${a}H`:n=`${u}PT${a}H${c}M`}}return new D.Literal(n,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static tz(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TZ: invalid date string '${e}'`);if(e.endsWith("Z"))return"Z";let n=e.match(/([+-]\d{2}:\d{2})$/);if(n)return n[1];let i=e.match(/([+-])(\d{2})(\d{2})$/);return i?`${i[1]}${i[2]}:${i[3]}`:""}static now(){return new Date().toISOString()}static msToMinutes(e){return Math.round(e/(1e3*60))}static msToHours(e){return Math.round(e/(1e3*60*60)*100)/100}static msToSeconds(e){return Math.round(e/1e3)}static abs(e){return Math.abs(e)}static round(e){return Math.round(e)}static ceil(e){return Math.ceil(e)}static floor(e){return Math.floor(e)}static rand(){return Math.random()}static coalesce(e){for(let t of e)if(t!=null)return t}static if(e,t,n){return e?t:n}static xsdDateTime(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`xsd:dateTime: invalid date string '${e}'`);return new D.Literal(t.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static xsdInteger(e){let t=parseInt(e,10);if(isNaN(t))throw new Error(`xsd:integer: cannot convert '${e}' to integer`);return new D.Literal(String(t),new ge.IRI("http://www.w3.org/2001/XMLSchema#integer"))}static xsdDecimal(e){let t=parseFloat(e);if(isNaN(t))throw new Error(`xsd:decimal: cannot convert '${e}' to decimal`);return new D.Literal(String(t),new ge.IRI("http://www.w3.org/2001/XMLSchema#decimal"))}static encodeForUri(e){return encodeURIComponent(e)}static md5(e){return require("crypto").createHash("md5").update(e).digest("hex")}static sha1(e){return require("crypto").createHash("sha1").update(e).digest("hex")}static sha256(e){return require("crypto").createHash("sha256").update(e).digest("hex")}static sha384(e){return require("crypto").createHash("sha384").update(e).digest("hex")}static sha512(e){return require("crypto").createHash("sha512").update(e).digest("hex")}static sameTerm(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0||e.constructor!==t.constructor)return!1;if(e instanceof ge.IRI&&t instanceof ge.IRI)return e.value===t.value;if(e instanceof Or.BlankNode&&t instanceof Or.BlankNode)return e.id===t.id;if(e instanceof D.Literal&&t instanceof D.Literal){if(e.value!==t.value||e.language!==t.language)return!1;let n=e.datatype?.value,i=t.datatype?.value;return n===i}return!1}static iri(e){if(e===void 0)throw new Error("IRI: argument is undefined");if(e instanceof ge.IRI)return e;if(e instanceof D.Literal)return new ge.IRI(e.value);throw e instanceof Or.BlankNode?new Error("IRI: cannot convert blank node to IRI"):new Error("IRI: unsupported term type")}static uri(e){return this.iri(e)}static bnode(e){if(e===void 0){let t=`b${(0,ly.v4)().replace(/-/g,"").substring(0,12)}`;return new Or.BlankNode(t)}if(e instanceof D.Literal)return new Or.BlankNode(e.value);if(e instanceof Or.BlankNode)return e;throw new Error("BNODE: argument must be a string literal or omitted")}static strdt(e,t){if(e===void 0)throw new Error("STRDT: lexical form is undefined");if(t===void 0)throw new Error("STRDT: datatype IRI is undefined");let n;if(e instanceof D.Literal){if(e.language)throw new Error("STRDT: lexical form must not have a language tag");n=e.value}else if(typeof e=="string")n=e;else throw new Error("STRDT: lexical form must be a string literal");let i;if(t instanceof ge.IRI)i=t;else if(t instanceof D.Literal)i=new ge.IRI(t.value);else throw new Error("STRDT: datatype must be an IRI");return new D.Literal(n,i)}static strlang(e,t){if(e===void 0)throw new Error("STRLANG: lexical form is undefined");if(t===void 0)throw new Error("STRLANG: language tag is undefined");let n;if(e instanceof D.Literal){if(e.language)throw new Error("STRLANG: lexical form must not already have a language tag");n=e.value}else if(typeof e=="string")n=e;else throw new Error("STRLANG: lexical form must be a string literal");let i;if(t instanceof D.Literal)i=t.value;else if(typeof t=="string")i=t;else throw new Error("STRLANG: language tag must be a string literal");if(i==="")throw new Error("STRLANG: language tag cannot be empty");return new D.Literal(n,void 0,i)}static strlangdir(e,t,n){if(e===void 0)throw new Error("STRLANGDIR: lexical form is undefined");if(t===void 0)throw new Error("STRLANGDIR: language tag is undefined");if(n===void 0)throw new Error("STRLANGDIR: direction is undefined");let i;if(e instanceof D.Literal){if(e.language)throw new Error("STRLANGDIR: lexical form must not already have a language tag");i=e.value}else if(typeof e=="string")i=e;else throw new Error("STRLANGDIR: lexical form must be a string literal");let s;if(t instanceof D.Literal)s=t.value;else if(typeof t=="string")s=t;else throw new Error("STRLANGDIR: language tag must be a string literal");if(s==="")throw new Error("STRLANGDIR: language tag cannot be empty");let a;if(n instanceof D.Literal)a=n.value.toLowerCase();else throw new Error("STRLANGDIR: direction must be a string literal");if(a!=="ltr"&&a!=="rtl")throw new Error(`STRLANGDIR: invalid direction '${a}'. Must be 'ltr' or 'rtl'`);return new D.Literal(i,void 0,s,a)}static uuid(){let e=(0,ly.v4)();return new ge.IRI(`urn:uuid:${e}`)}static struuid(){let e=(0,ly.v4)();return new D.Literal(e)}static parseDayTimeDuration(e){if(!e)throw new Error("parseDayTimeDuration: duration string is empty");let t=!1,n=e.trim();if(n.startsWith("-")&&(t=!0,n=n.substring(1)),!n.startsWith("P"))throw new Error(`parseDayTimeDuration: invalid format, must start with 'P': '${e}'`);n=n.substring(1);let i=0,s=n.indexOf("T"),a="",c="";if(s===-1?a=n:(a=n.substring(0,s),c=n.substring(s+1)),a){let u=a.match(/^(\d+(?:\.\d+)?)D$/);if(u){let l=parseFloat(u[1]);i+=l*24*60*60*1e3}else if(a!=="")throw new Error(`parseDayTimeDuration: invalid day component: '${a}' in '${e}'`)}if(c){let u=c,l=u.match(/^(\d+(?:\.\d+)?)H/);if(l){let d=parseFloat(l[1]);i+=d*60*60*1e3,u=u.substring(l[0].length)}let f=u.match(/^(\d+(?:\.\d+)?)M/);if(f){let d=parseFloat(f[1]);i+=d*60*1e3,u=u.substring(f[0].length)}let h=u.match(/^(\d+(?:\.\d+)?)S$/);if(h){let d=parseFloat(h[1]);i+=d*1e3,u=u.substring(h[0].length)}if(u!=="")throw new Error(`parseDayTimeDuration: invalid time component: '${u}' in '${e}'`)}return t?-i:i}static formatDayTimeDuration(e){let t=e<0,n=Math.abs(e),i=Math.floor(n/(1440*60*1e3));n=n%(1440*60*1e3);let s=Math.floor(n/(3600*1e3));n=n%(3600*1e3);let a=Math.floor(n/(60*1e3));n=n%(60*1e3);let c=n/1e3,u=t?"-P":"P";return i>0&&(u+=`${i}D`),(s>0||a>0||c>0||i===0)&&(u+="T",s>0&&(u+=`${s}H`),a>0&&(u+=`${a}M`),(c>0||s===0&&a===0)&&(Number.isInteger(c)?u+=`${c}S`:u+=`${parseFloat(c.toFixed(3))}S`)),u}static xsdDayTimeDuration(e){return this.parseDayTimeDuration(e),new D.Literal(e,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static compareDurations(e,t,n){let i=e instanceof D.Literal?e.value:e,s=t instanceof D.Literal?t.value:t,a=this.parseDayTimeDuration(i),c=this.parseDayTimeDuration(s);switch(n){case"=":return a===c;case"!=":return a!==c;case"<":return a<c;case">":return a>c;case"<=":return a<=c;case">=":return a>=c;default:throw new Error(`compareDurations: unknown operator: ${n}`)}}static isDayTimeDuration(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static isDate(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#date":!1}static dateDiff(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n),a=this.parseXSDDate(i);if(s===null)throw new Error(`dateDiff: invalid first date: '${n}'`);if(a===null)throw new Error(`dateDiff: invalid second date: '${i}'`);let c=s.getTime()-a.getTime(),u=Math.round(c/(1440*60*1e3)),l=this.formatDateDuration(u);return new D.Literal(l,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static parseXSDDate(e){let t=/^(-?\d{4})-(\d{2})-(\d{2})(Z|[+-]\d{2}:\d{2})?$/,n=e.match(t);if(!n){let l=new Date(e);return isNaN(l.getTime())?null:new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),l.getUTCDate()))}let i=parseInt(n[1],10),s=parseInt(n[2],10)-1,a=parseInt(n[3],10),c=n[4],u=new Date(Date.UTC(i,s,a));if(c&&c!=="Z"){let l=c.match(/([+-])(\d{2}):(\d{2})/);if(l){let f=l[1]==="+"?1:-1,h=parseInt(l[2],10),d=parseInt(l[3],10),p=f*(h*60+d)*60*1e3;u=new Date(u.getTime()-p)}}return u}static formatDateDuration(e){if(e===0)return"P0D";let t=e<0,n=Math.abs(e);return t?`-P${n}D`:`P${n}D`}static dateTimeDiff(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n),a=new Date(i);if(isNaN(s.getTime()))throw new Error(`dateTimeDiff: invalid first dateTime: '${n}'`);if(isNaN(a.getTime()))throw new Error(`dateTimeDiff: invalid second dateTime: '${i}'`);let c=s.getTime()-a.getTime(),u=this.formatDayTimeDuration(c);return new D.Literal(u,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static dateTimeAdd(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeAdd: invalid dateTime: '${n}'`);let a=this.parseDayTimeDuration(i),c=s.getTime()+a,u=new Date(c);return new D.Literal(u.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtract(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtract: invalid dateTime: '${n}'`);let a=this.parseDayTimeDuration(i),c=s.getTime()-a,u=new Date(c);return new D.Literal(u.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateAdd(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n);if(s===null)throw new Error(`dateAdd: invalid date: '${n}'`);let a=this.parseDayTimeDuration(i),c=s.getTime()+a,u=new Date(c),l=u.getUTCFullYear(),f=String(u.getUTCMonth()+1).padStart(2,"0"),h=String(u.getUTCDate()).padStart(2,"0"),d=`${l}-${f}-${h}`;return new D.Literal(d,new ge.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateSubtract(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n);if(s===null)throw new Error(`dateSubtract: invalid date: '${n}'`);let a=this.parseDayTimeDuration(i),c=s.getTime()-a,u=new Date(c),l=u.getUTCFullYear(),f=String(u.getUTCMonth()+1).padStart(2,"0"),h=String(u.getUTCDate()).padStart(2,"0"),d=`${l}-${f}-${h}`;return new D.Literal(d,new ge.IRI("http://www.w3.org/2001/XMLSchema#date"))}static parseYearMonthDuration(e){let t=/^(-)?P(?:(\d+)Y)?(?:(\d+)M)?$/,n=e.match(t);if(!n)throw new Error(`parseYearMonthDuration: invalid format: '${e}'`);let i=n[1]==="-",s=parseInt(n[2]||"0",10),a=parseInt(n[3]||"0",10);if(!n[2]&&!n[3])throw new Error(`parseYearMonthDuration: invalid format (no duration components): '${e}'`);let c=s*12+a;return i?-c:c}static isYearMonthDuration(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#yearMonthDuration":!1}static dateTimeAddYearMonth(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeAddYearMonth: invalid dateTime: '${n}'`);let a=this.parseYearMonthDuration(i),c=s.getUTCDate();return s.setUTCMonth(s.getUTCMonth()+a),s.getUTCDate()!==c&&s.setUTCDate(0),new D.Literal(s.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtractYearMonth(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtractYearMonth: invalid dateTime: '${n}'`);let a=this.parseYearMonthDuration(i),c=s.getUTCDate();return s.setUTCMonth(s.getUTCMonth()-a),s.getUTCDate()!==c&&s.setUTCDate(0),new D.Literal(s.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateAddYearMonth(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n);if(s===null)throw new Error(`dateAddYearMonth: invalid date: '${n}'`);let a=this.parseYearMonthDuration(i),c=s.getUTCDate();s.setUTCMonth(s.getUTCMonth()+a),s.getUTCDate()!==c&&s.setUTCDate(0);let u=s.getUTCFullYear(),l=String(s.getUTCMonth()+1).padStart(2,"0"),f=String(s.getUTCDate()).padStart(2,"0"),h=`${u}-${l}-${f}`;return new D.Literal(h,new ge.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateSubtractYearMonth(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n);if(s===null)throw new Error(`dateSubtractYearMonth: invalid date: '${n}'`);let a=this.parseYearMonthDuration(i),c=s.getUTCDate();s.setUTCMonth(s.getUTCMonth()-a),s.getUTCDate()!==c&&s.setUTCDate(0);let u=s.getUTCFullYear(),l=String(s.getUTCMonth()+1).padStart(2,"0"),f=String(s.getUTCDate()).padStart(2,"0"),h=`${u}-${l}-${f}`;return new D.Literal(h,new ge.IRI("http://www.w3.org/2001/XMLSchema#date"))}static durationAdd(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseDayTimeDuration(n),a=this.parseDayTimeDuration(i),c=this.formatDayTimeDuration(s+a);return new D.Literal(c,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationSubtract(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseDayTimeDuration(n),a=this.parseDayTimeDuration(i),c=this.formatDayTimeDuration(s-a);return new D.Literal(c,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationMultiply(e,t){let n=e instanceof D.Literal?e.value:e,i=this.parseDayTimeDuration(n),s=this.formatDayTimeDuration(i*t);return new D.Literal(s,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationDivide(e,t){if(t===0)throw new Error("durationDivide: division by zero");let n=e instanceof D.Literal?e.value:e,i=this.parseDayTimeDuration(n),s=this.formatDayTimeDuration(i/t);return new D.Literal(s,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static formatYearMonthDuration(e){let t=e<0,n=Math.abs(e),i=Math.floor(n/12),s=n%12,a=t?"-P":"P";return i>0&&(a+=`${i}Y`),(s>0||i===0)&&(a+=`${s}M`),a}static yearMonthDurationAdd(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseYearMonthDuration(n),a=this.parseYearMonthDuration(i),c=this.formatYearMonthDuration(s+a);return new D.Literal(c,new ge.IRI("http://www.w3.org/2001/XMLSchema#yearMonthDuration"))}static yearMonthDurationSubtract(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseYearMonthDuration(n),a=this.parseYearMonthDuration(i),c=this.formatYearMonthDuration(s-a);return new D.Literal(c,new ge.IRI("http://www.w3.org/2001/XMLSchema#yearMonthDuration"))}static parseYearMonthDurationComponents(e){let t=/^(-)?P(?:(\d+)Y)?(?:(\d+)M)?$/,n=e.match(t);if(!n)throw new Error(`parseYearMonthDurationComponents: invalid format: '${e}'`);let i=n[1]==="-",s=parseInt(n[2]||"0",10),a=parseInt(n[3]||"0",10);if(!n[2]&&!n[3])throw new Error(`parseYearMonthDurationComponents: invalid format (no duration components): '${e}'`);return{years:s,months:a,negative:i}}static durationYears(e){let t=e instanceof D.Literal?e.value:e,n=this.parseYearMonthDurationComponents(t);return n.negative?-n.years:n.years}static durationMonths(e){let t=e instanceof D.Literal?e.value:e,n=this.parseYearMonthDurationComponents(t);return n.negative?-n.months:n.months}static durationToDays(e){let t=e instanceof D.Literal?e.value:e;return this.parseDayTimeDuration(t)/(1440*60*1e3)}static durationToHours(e){let t=e instanceof D.Literal?e.value:e;return this.parseDayTimeDuration(t)/(3600*1e3)}static durationToMinutes(e){let t=e instanceof D.Literal?e.value:e;return this.parseDayTimeDuration(t)/(60*1e3)}static durationToSeconds(e){let t=e instanceof D.Literal?e.value:e;return this.parseDayTimeDuration(t)/1e3}static parseDurationComponents(e){if(!e)throw new Error("parseDurationComponents: duration string is empty");let t=!1,n=e.trim();if(n.startsWith("-")&&(t=!0,n=n.substring(1)),!n.startsWith("P"))throw new Error(`parseDurationComponents: invalid format, must start with 'P': '${e}'`);n=n.substring(1);let i=0,s=0,a=0,c=0,u=n.indexOf("T"),l="",f="";if(u===-1?l=n:(l=n.substring(0,u),f=n.substring(u+1)),l){let h=l.match(/^(\d+(?:\.\d+)?)D$/);if(h)i=parseFloat(h[1]);else if(l!=="")throw new Error(`parseDurationComponents: invalid day component: '${l}' in '${e}'`)}if(f){let h=f,d=h.match(/^(\d+(?:\.\d+)?)H/);d&&(s=parseFloat(d[1]),h=h.substring(d[0].length));let p=h.match(/^(\d+(?:\.\d+)?)M/);p&&(a=parseFloat(p[1]),h=h.substring(p[0].length));let v=h.match(/^(\d+(?:\.\d+)?)S$/);if(v&&(c=parseFloat(v[1]),h=h.substring(v[0].length)),h!=="")throw new Error(`parseDurationComponents: invalid time component: '${h}' in '${e}'`)}return{negative:t,days:i,hours:s,minutes:a,seconds:c}}static durationDays(e){let t=e instanceof D.Literal?e.value:e,n=this.parseDurationComponents(t),i=Math.floor(n.days);return n.negative?-i:i}static durationHours(e){let t=e instanceof D.Literal?e.value:e,n=this.parseDurationComponents(t),i=Math.floor(n.hours);return n.negative?-i:i}static durationMinutes(e){let t=e instanceof D.Literal?e.value:e,n=this.parseDurationComponents(t),i=Math.floor(n.minutes);return n.negative?-i:i}static durationSeconds(e){let t=e instanceof D.Literal?e.value:e,n=this.parseDurationComponents(t);return n.negative?-n.seconds:n.seconds}static adjust(e,t){let n=e instanceof D.Literal?e.value:e,i=new Date(n);if(isNaN(i.getTime()))throw new Error(`ADJUST: invalid dateTime: '${n}'`);if(t==null){let Ce=i.getUTCFullYear(),Ve=String(i.getUTCMonth()+1).padStart(2,"0"),Ue=String(i.getUTCDate()).padStart(2,"0"),G=String(i.getUTCHours()).padStart(2,"0"),se=String(i.getUTCMinutes()).padStart(2,"0"),Te=String(i.getUTCSeconds()).padStart(2,"0"),lt=i.getUTCMilliseconds(),rt=`${Ce}-${Ve}-${Ue}T${G}:${se}:${Te}`;return lt>0&&(rt+=`.${String(lt).padStart(3,"0")}`),new D.Literal(rt,new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}let s=t instanceof D.Literal?t.value:t,a=this.parseDayTimeDuration(s),c=840*60*1e3;if(Math.abs(a)>c)throw new Error(`ADJUST: timezone offset out of range: '${s}'`);let u=i.getTime(),l=new Date(u+a),f=l.getUTCFullYear(),h=String(l.getUTCMonth()+1).padStart(2,"0"),d=String(l.getUTCDate()).padStart(2,"0"),p=String(l.getUTCHours()).padStart(2,"0"),v=String(l.getUTCMinutes()).padStart(2,"0"),b=String(l.getUTCSeconds()).padStart(2,"0"),E=l.getUTCMilliseconds(),C=a>=0?"+":"-",I=Math.floor(Math.abs(a)/(3600*1e3)),N=Math.floor(Math.abs(a)%(3600*1e3)/(60*1e3)),B=`${C}${String(I).padStart(2,"0")}:${String(N).padStart(2,"0")}`,W=`${f}-${h}-${d}T${p}:${v}:${b}`;return E>0&&(W+=`.${String(E).padStart(3,"0")}`),W+=B,new D.Literal(W,new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static normalize(e,t){if(e===void 0)throw new Error("NORMALIZE: string argument is undefined");let n;if(e instanceof D.Literal)n=e.value;else if(e instanceof ge.IRI)n=e.value;else if(e instanceof Or.BlankNode)n=e.id;else if(typeof e=="string")n=e;else throw new Error("NORMALIZE: first argument must be a string or literal");let i="NFC";if(t!==void 0)if(t instanceof D.Literal)i=t.value.toUpperCase();else if(typeof t=="string")i=t.toUpperCase();else if(t instanceof ge.IRI)i=t.value.toUpperCase();else throw new Error("NORMALIZE: second argument must be a string literal");if(!this.VALID_NORMALIZATION_FORMS.includes(i))throw new Error(`NORMALIZE: invalid normalization form '${i}'. Valid forms are: NFC, NFD, NFKC, NFKD`);let s=n.normalize(i);return new D.Literal(s,new ge.IRI("http://www.w3.org/2001/XMLSchema#string"))}static fold(e){if(e===void 0)throw new Error("FOLD: string argument is undefined");let t;if(e instanceof D.Literal)t=e.value;else if(e instanceof ge.IRI)t=e.value;else if(e instanceof Or.BlankNode)t=e.id;else if(typeof e=="string")t=e;else throw new Error("FOLD: argument must be a string or literal");let n=this.unicodeCaseFold(t);return new D.Literal(n,new ge.IRI("http://www.w3.org/2001/XMLSchema#string"))}static unicodeCaseFold(e){let t="";for(let n of e){let i=this.CASE_FOLDING_MAP.get(n);i!==void 0?t+=i:t+=n.toLowerCase()}return t}static isTime(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#time":!1}static timeDiff(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDTime(n),a=this.parseXSDTime(i);if(s===null)throw new Error(`timeDiff: invalid first time: '${n}'`);if(a===null)throw new Error(`timeDiff: invalid second time: '${i}'`);let c=s-a,u=this.formatDayTimeDuration(c);return new D.Literal(u,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static parseXSDTime(e){let t=/^(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$/,n=e.match(t);if(!n)return null;let i=parseInt(n[1],10),s=parseInt(n[2],10),a=parseInt(n[3],10),c=n[4],u=n[5];if(i<0||i>24||s<0||s>59||a<0||a>59||i===24&&(s!==0||a!==0))return null;let l=0;if(c){let h=c.padEnd(3,"0").slice(0,3);l=parseInt(h,10)}let f=i*60*60*1e3+s*60*1e3+a*1e3+l;if(i===24&&(f=1440*60*1e3),u&&u!=="Z"){let h=u.match(/([+-])(\d{2}):(\d{2})/);if(h){let d=h[1]==="+"?1:-1,p=parseInt(h[2],10),v=parseInt(h[3],10),b=d*(p*60+v)*60*1e3;f-=b}}return f}static triple(e,t,n){if(e===void 0)throw new Error("TRIPLE: subject is undefined");if(t===void 0)throw new Error("TRIPLE: predicate is undefined");if(n===void 0)throw new Error("TRIPLE: object is undefined");if(e instanceof D.Literal)throw new Error("TRIPLE: subject must be IRI, BlankNode, or QuotedTriple, got Literal");if(!(t instanceof ge.IRI)){let c=t instanceof D.Literal?"Literal":t instanceof Or.BlankNode?"BlankNode":t instanceof fo.QuotedTriple?"QuotedTriple":typeof t;throw new Error(`TRIPLE: predicate must be IRI, got ${c}`)}let i=e,s=t,a=n;return new fo.QuotedTriple(i,s,a)}static subject(e){if(e===void 0)throw new Error("SUBJECT: argument is undefined");if(!(e instanceof fo.QuotedTriple)){let t=e instanceof ge.IRI?"IRI":e instanceof D.Literal?"Literal":e instanceof Or.BlankNode?"BlankNode":typeof e;throw new Error(`SUBJECT: argument must be QuotedTriple, got ${t}`)}return e.subject}static predicate(e){if(e===void 0)throw new Error("PREDICATE: argument is undefined");if(!(e instanceof fo.QuotedTriple)){let t=e instanceof ge.IRI?"IRI":e instanceof D.Literal?"Literal":e instanceof Or.BlankNode?"BlankNode":typeof e;throw new Error(`PREDICATE: argument must be QuotedTriple, got ${t}`)}return e.predicate}static object(e){if(e===void 0)throw new Error("OBJECT: argument is undefined");if(!(e instanceof fo.QuotedTriple)){let t=e instanceof ge.IRI?"IRI":e instanceof D.Literal?"Literal":e instanceof Or.BlankNode?"BlankNode":typeof e;throw new Error(`OBJECT: argument must be QuotedTriple, got ${t}`)}return e.object}};sh.BuiltInFunctions=Qc;Qc.VALID_NORMALIZATION_FORMS=["NFC","NFD","NFKC","NFKD"];Qc.CASE_FOLDING_MAP=new Map([["\xDF","ss"],["\u1E9E","ss"],["\u03A3","\u03C3"],["\u03C2","\u03C3"],["\u0130","i\u0307"],["I","i"],["\u0587","\u0565\u0582"],["\uFB00","ff"],["\uFB01","fi"],["\uFB02","fl"],["\uFB03","ffi"],["\uFB04","ffl"],["\uFB05","st"],["\uFB06","st"],["\u0390","\u03B9\u0308\u0301"],["\u03B0","\u03C5\u0308\u0301"],["\u017F","s"],["\u1E9B","\u1E61"],["\u212A","k"],["\u212B","\xE5"]])});var Kb=_(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.functionHandlers=void 0;var M=ah();L.functionHandlers=new Map;L.functionHandlers.set("str",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.str(t)});L.functionHandlers.set("lang",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.lang(t)});L.functionHandlers.set("langmatches",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.langMatches(t,n)});L.functionHandlers.set("contains",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.contains(t,n)});L.functionHandlers.set("strstarts",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.strStarts(t,n)});L.functionHandlers.set("strends",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.strEnds(t,n)});L.functionHandlers.set("strlen",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.strlen(t)});L.functionHandlers.set("ucase",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.ucase(t)});L.functionHandlers.set("lcase",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.lcase(t)});L.functionHandlers.set("substr",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=Number(e.evaluateExpression(r[1],e.solution));if(r[2]){let i=Number(e.evaluateExpression(r[2],e.solution));return M.BuiltInFunctions.substr(t,n,i)}return M.BuiltInFunctions.substr(t,n)});L.functionHandlers.set("strbefore",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.strBefore(t,n)});L.functionHandlers.set("strafter",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.strAfter(t,n)});L.functionHandlers.set("concat",(r,e)=>{let t=r.map(n=>e.getStringValue(e.evaluateExpression(n,e.solution)));return M.BuiltInFunctions.concat(...t)});L.functionHandlers.set("replace",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution)),i=e.getStringValue(e.evaluateExpression(r[2],e.solution)),s=r[3]?e.getStringValue(e.evaluateExpression(r[3],e.solution)):void 0;return M.BuiltInFunctions.replace(t,n,i,s)});L.functionHandlers.set("regex",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution)),i=r[2]?e.getStringValue(e.evaluateExpression(r[2],e.solution)):void 0;return M.BuiltInFunctions.regex(t,n,i)});L.functionHandlers.set("encode_for_uri",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.encodeForUri(t)});L.functionHandlers.set("datatype",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.datatype(t).value});L.functionHandlers.set("bound",(r,e)=>{let t=r[0];if(t.type==="variable"&&t.name){let n=e.solution.get(t.name);return M.BuiltInFunctions.bound(n)}return!0});var Ub=o((r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isIRI(t)},"isIriHandler");L.functionHandlers.set("isiri",Ub);L.functionHandlers.set("isuri",Ub);L.functionHandlers.set("isblank",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isBlank(t)});L.functionHandlers.set("isliteral",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isLiteral(t)});L.functionHandlers.set("isnumeric",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isNumeric(t)});L.functionHandlers.set("haslangdir",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.hasLangdir(t)});L.functionHandlers.set("istriple",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isTriple(t)});L.functionHandlers.set("sameterm",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution),n=e.getTermFromExpression(r[1],e.solution);return M.BuiltInFunctions.sameTerm(t,n)});L.functionHandlers.set("abs",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.abs(t)});L.functionHandlers.set("round",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.round(t)});L.functionHandlers.set("ceil",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.ceil(t)});L.functionHandlers.set("floor",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.floor(t)});L.functionHandlers.set("rand",()=>M.BuiltInFunctions.rand());L.functionHandlers.set("parsedate",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.parseDate(t)});L.functionHandlers.set("datebefore",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.dateBefore(t,n)});L.functionHandlers.set("dateafter",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.dateAfter(t,n)});L.functionHandlers.set("dateinrange",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution)),i=e.getStringValue(e.evaluateExpression(r[2],e.solution));return M.BuiltInFunctions.dateInRange(t,n,i)});L.functionHandlers.set("datediffminutes",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.dateDiffMinutes(t,n)});L.functionHandlers.set("datediffhours",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.dateDiffHours(t,n)});var ho=o((r,e,t)=>(n,i)=>{let s=i.evaluateExpression(n[0],i.solution);return e&&i.isYearMonthDurationValue(s)?e(s):t&&i.isDayTimeDurationValue(s)?t(s):r(i.getStringValue(s))},"createDateTimeAccessor"),qb=ho(M.BuiltInFunctions.year,M.BuiltInFunctions.durationYears,null);L.functionHandlers.set("year",qb);L.functionHandlers.set("years",qb);var Gb=ho(M.BuiltInFunctions.month,M.BuiltInFunctions.durationMonths,null);L.functionHandlers.set("month",Gb);L.functionHandlers.set("months",Gb);var Wb=ho(M.BuiltInFunctions.day,null,M.BuiltInFunctions.durationDays);L.functionHandlers.set("day",Wb);L.functionHandlers.set("days",Wb);L.functionHandlers.set("hours",ho(M.BuiltInFunctions.hours,null,M.BuiltInFunctions.durationHours));L.functionHandlers.set("minutes",ho(M.BuiltInFunctions.minutes,null,M.BuiltInFunctions.durationMinutes));L.functionHandlers.set("seconds",ho(M.BuiltInFunctions.seconds,null,M.BuiltInFunctions.durationSeconds));L.functionHandlers.set("timezone",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.timezone(t)});L.functionHandlers.set("tz",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.tz(t)});L.functionHandlers.set("adjust",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution),n=r.length>1?e.evaluateExpression(r[1],e.solution):void 0;return M.BuiltInFunctions.adjust(t,n)});L.functionHandlers.set("now",()=>M.BuiltInFunctions.now());var Hb=o((r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.xsdDateTime(e.getStringValue(t))},"dateTimeHandler");L.functionHandlers.set("datetime",Hb);L.functionHandlers.set("xsd:datetime",Hb);var zb=o((r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.xsdInteger(e.getStringValue(t))},"integerHandler");L.functionHandlers.set("integer",zb);L.functionHandlers.set("xsd:integer",zb);var Yb=o((r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.xsdDecimal(e.getStringValue(t))},"decimalHandler");L.functionHandlers.set("decimal",Yb);L.functionHandlers.set("xsd:decimal",Yb);var Qb=o((r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.xsdDayTimeDuration(e.getStringValue(t))},"dayTimeDurationHandler");L.functionHandlers.set("daytimeduration",Qb);L.functionHandlers.set("xsd:daytimeduration",Qb);L.functionHandlers.set("durationtodays",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationToDays(t)});L.functionHandlers.set("durationtohours",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationToHours(t)});L.functionHandlers.set("durationtominutes",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationToMinutes(t)});L.functionHandlers.set("durationtoseconds",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationToSeconds(t)});L.functionHandlers.set("durationdays",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationDays(t)});L.functionHandlers.set("durationhours",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationHours(t)});L.functionHandlers.set("durationminutes",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationMinutes(t)});L.functionHandlers.set("durationseconds",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationSeconds(t)});L.functionHandlers.set("durationyears",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationYears(t)});L.functionHandlers.set("durationmonths",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationMonths(t)});L.functionHandlers.set("datetimediff",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution),n=e.evaluateExpression(r[1],e.solution);return M.BuiltInFunctions.dateTimeDiff(t,n)});L.functionHandlers.set("datetimeadd",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution),n=e.evaluateExpression(r[1],e.solution);return M.BuiltInFunctions.dateTimeAdd(t,n)});L.functionHandlers.set("datetimesubtract",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution),n=e.evaluateExpression(r[1],e.solution);return M.BuiltInFunctions.dateTimeSubtract(t,n)});L.functionHandlers.set("mstominutes",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.msToMinutes(t)});L.functionHandlers.set("mstohours",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.msToHours(t)});L.functionHandlers.set("mstoseconds",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.msToSeconds(t)});L.functionHandlers.set("md5",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.md5(t)});L.functionHandlers.set("sha1",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.sha1(t)});L.functionHandlers.set("sha256",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.sha256(t)});L.functionHandlers.set("sha384",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.sha384(t)});L.functionHandlers.set("sha512",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.sha512(t)});L.functionHandlers.set("subject",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.subject(t)});L.functionHandlers.set("predicate",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.predicate(t)});L.functionHandlers.set("object",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.object(t)});L.functionHandlers.set("triple",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution),n=e.getTermFromExpression(r[1],e.solution),i=e.getTermFromExpression(r[2],e.solution);return M.BuiltInFunctions.triple(t,n,i)})});var oh=_(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.FilterExecutor=po.FilterExecutorError=void 0;var ut=ah(),qN=Kb(),fa=ht(),er=class extends Error{static{o(this,"FilterExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="FilterExecutorError"}};po.FilterExecutorError=er;var fy=class{static{o(this,"FilterExecutor")}constructor(){this.existsEvaluator=null,this.tripleStore=null,this.uuidCache=new Map}setExistsEvaluator(e){this.existsEvaluator=e}setTripleStore(e){this.tripleStore=e,this.uuidCache.clear()}async*execute(e,t){let n=this.expressionContainsExists(e.expression);for await(let i of t)try{let s;n?s=await this.evaluateExpressionAsync(e.expression,i):s=this.evaluateExpression(e.expression,i),s===!0&&(yield i)}catch{continue}}expressionContainsExists(e){if(e.type==="exists")return!0;if(e.type==="logical")return e.operands.some(t=>this.expressionContainsExists(t));if(e.type==="comparison")return this.expressionContainsExists(e.left)||this.expressionContainsExists(e.right);if(e.type==="in"){let t=e;return this.expressionContainsExists(t.expression)||t.list.some(n=>this.expressionContainsExists(n))}return!1}async executeAll(e,t){let n=[];async function*i(){for(let s of t)yield s}o(i,"generator");for await(let s of this.execute(e,i()))n.push(s);return n}evaluateExpression(e,t){let n=e;if(n.termType)switch(n.termType){case"Variable":return t.get(n.value);case"Literal":return n.value;case"NamedNode":return n.value;default:throw new er(`Unsupported termType: ${n.termType}`)}switch(e.type){case"comparison":return this.evaluateComparison(e,t);case"logical":return this.evaluateLogical(e,t);case"arithmetic":return this.evaluateArithmetic(e,t);case"function":case"functionCall":return this.evaluateFunction(e,t);case"variable":return t.get(e.name);case"literal":return e.value;case"in":return this.evaluateIn(e,t);case"exists":throw new er("EXISTS expressions require async evaluation. Use evaluateExpressionAsync instead.");default:throw new er(`Unsupported expression type: ${e.type}, expr.termType=${n.termType}`)}}async evaluateExpressionAsync(e,t){return e.type==="exists"?this.evaluateExists(e,t):e.type==="logical"?this.evaluateLogicalAsync(e,t):this.evaluateExpression(e,t)}async evaluateExists(e,t){if(!this.existsEvaluator)throw new er("EXISTS evaluator not set. Call setExistsEvaluator before evaluating EXISTS expressions.");let n=await this.existsEvaluator(e.pattern,t);return e.negated?!n:n}async evaluateLogicalAsync(e,t){if(e.operator==="!"){let i=await this.evaluateExpressionAsync(e.operands[0],t);return ut.BuiltInFunctions.logicalNot(i)}let n=[];for(let i of e.operands){let s=await this.evaluateExpressionAsync(i,t);n.push(s)}if(e.operator==="&&")return ut.BuiltInFunctions.logicalAnd(n);if(e.operator==="||")return ut.BuiltInFunctions.logicalOr(n);throw new er(`Unknown logical operator: ${e.operator}`)}evaluateComparison(e,t){let n=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);return ut.BuiltInFunctions.compare(n,i,e.operator)}evaluateLogical(e,t){if(e.operator==="!"){let i=this.evaluateExpression(e.operands[0],t);return ut.BuiltInFunctions.logicalNot(i)}let n=e.operands.map(i=>this.evaluateExpression(i,t));if(e.operator==="&&")return ut.BuiltInFunctions.logicalAnd(n);if(e.operator==="||")return ut.BuiltInFunctions.logicalOr(n);throw new er(`Unknown logical operator: ${e.operator}`)}evaluateIn(e,t){let n=this.evaluateExpression(e.expression,t),i=e.list.some(s=>{let a=this.evaluateExpression(s,t);return ut.BuiltInFunctions.compare(n,a,"=")});return e.negated?!i:i}evaluateArithmetic(e,t){let n=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);if(e.operator==="-"&&this.isDateValue(n)&&this.isDateValue(i))return ut.BuiltInFunctions.dateDiff(n,i);if(e.operator==="-"&&this.isTimeValue(n)&&this.isTimeValue(i))return ut.BuiltInFunctions.timeDiff(n,i);if(e.operator==="-"&&this.isDateTimeValue(n)&&this.isDateTimeValue(i))return ut.BuiltInFunctions.dateTimeDiff(n,i);if(e.operator==="+"&&this.isDateValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.dateAdd(n,i);if(e.operator==="-"&&this.isDateValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.dateSubtract(n,i);if(e.operator==="+"&&this.isDateValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.dateAddYearMonth(n,i);if(e.operator==="-"&&this.isDateValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.dateSubtractYearMonth(n,i);if(e.operator==="+"&&this.isDateTimeValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.dateTimeAdd(n,i);if(e.operator==="-"&&this.isDateTimeValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.dateTimeSubtract(n,i);if(e.operator==="+"&&this.isDateTimeValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.dateTimeAddYearMonth(n,i);if(e.operator==="-"&&this.isDateTimeValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.dateTimeSubtractYearMonth(n,i);if(e.operator==="+"&&this.isDayTimeDurationValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.durationAdd(n,i);if(e.operator==="-"&&this.isDayTimeDurationValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.durationSubtract(n,i);if(e.operator==="*"&&this.isDayTimeDurationValue(n)&&!this.isDayTimeDurationValue(i)){let c=this.toNumericValue(i);return ut.BuiltInFunctions.durationMultiply(n,c)}if(e.operator==="*"&&!this.isDayTimeDurationValue(n)&&this.isDayTimeDurationValue(i)){let c=this.toNumericValue(n);return ut.BuiltInFunctions.durationMultiply(i,c)}if(e.operator==="/"&&this.isDayTimeDurationValue(n)&&!this.isDayTimeDurationValue(i)){let c=this.toNumericValue(i);if(c===0)throw new er("Division by zero");return ut.BuiltInFunctions.durationDivide(n,c)}if(e.operator==="+"&&this.isYearMonthDurationValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.yearMonthDurationAdd(n,i);if(e.operator==="-"&&this.isYearMonthDurationValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.yearMonthDurationSubtract(n,i);let s=this.toNumericValue(n),a=this.toNumericValue(i);switch(e.operator){case"+":return s+a;case"-":return s-a;case"*":return s*a;case"/":if(a===0)throw new er("Division by zero");return s/a;default:throw new er(`Unknown arithmetic operator: ${e.operator}`)}}isDayTimeDurationValue(e){return e instanceof fa.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}isYearMonthDurationValue(e){return e instanceof fa.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#yearMonthDuration":!1}toNumericValue(e){if(typeof e=="number")return e;if(e instanceof fa.Literal){let t=e.datatype?.value||"";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let i=parseFloat(e.value);if(!isNaN(i))return i}let n=parseFloat(e.value);if(!isNaN(n))return n}if(typeof e=="string"){let t=parseFloat(e);if(!isNaN(t))return t}if(e&&typeof e=="object"&&"value"in e){let t=parseFloat(String(e.value));if(!isNaN(t))return t}throw new er(`Cannot convert to number: ${e}`)}isDateTimeValue(e){if(e instanceof fa.Literal){let t=e.datatype?.value||"";return t.includes("#dateTime")||t.includes("#date")?!0:/^\d{4}-\d{2}-\d{2}(T|\s)/.test(e.value)}return typeof e=="string"?/^\d{4}-\d{2}-\d{2}(T|\s)/.test(e):!1}isDateValue(e){return e instanceof fa.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#date":!1}isTimeValue(e){return e instanceof fa.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#time":!1}evaluateFunction(e,t){let n=e,i=this.extractFunctionName(n.function),s=this.evaluateSpecialFunction(i,n.args,t);if(s!==void 0)return s.value;let a=qN.functionHandlers.get(i);if(!a)throw new er(`Unknown function: ${i}`);let c={evaluateExpression:o((u,l)=>this.evaluateExpression(u,l),"evaluateExpression"),getTermFromExpression:o((u,l)=>this.getTermFromExpression(u,l),"getTermFromExpression"),getStringValue:o(u=>this.getStringValue(u),"getStringValue"),solution:t,isYearMonthDurationValue:o(u=>this.isYearMonthDurationValue(u),"isYearMonthDurationValue"),isDayTimeDurationValue:o(u=>this.isDayTimeDurationValue(u),"isDayTimeDurationValue")};return a(n.args,c)}extractFunctionName(e){if(typeof e=="string")return e.toLowerCase();if(e&&typeof e=="object"&&"value"in e){let t=e.value;return((t.includes("#")?t.split("#").pop():t.split("/").pop())||t).toLowerCase()}throw new er(`Unknown function format: ${e}`)}evaluateSpecialFunction(e,t,n){switch(e){case"coalesce":for(let c of t)try{let u=this.evaluateExpression(c,n);if(u!=null)return{value:u}}catch{continue}return{value:void 0};case"if":if(!t||t.length!==3)throw new er("IF requires exactly 3 arguments");let i=this.evaluateExpression(t[0],n);return{value:this.toBoolean(i)?this.evaluateExpression(t[1],n):this.evaluateExpression(t[2],n)};case"byuuid":return{value:this.evaluateByUUID({args:t},n)};default:return}}getTermFromExpression(e,t){let n=e;if(n.type==="variable"&&n.name)return t.get(n.name)}getStringValue(e){return e==null?"":typeof e=="object"&&"value"in e?String(e.value):String(e)}toBoolean(e){if(typeof e=="boolean")return e;if(typeof e=="number")return!isNaN(e)&&e!==0;if(typeof e=="string")return e.length>0;if(e instanceof fa.Literal){let t=e.datatype?.value||"";if(t.includes("#boolean"))return e.value==="true"||e.value==="1";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let n=parseFloat(e.value);return!isNaN(n)&&n!==0}return e.value.length>0}return!!e}evaluateByUUID(e,t){if(!e.args||e.args.length!==1)throw new er("exo:byUUID requires exactly 1 argument (UUID string)");let n=this.evaluateExpression(e.args[0],t),i=this.getStringValue(n);if(!i)return;let s=i.toLowerCase();if(this.uuidCache.has(s))return this.uuidCache.get(s)??void 0;if(!this.tripleStore){this.uuidCache.set(s,null);return}if(this.tripleStore.findSubjectsByUUIDSync){let a=this.tripleStore.findSubjectsByUUIDSync(s);if(a.length===0){this.uuidCache.set(s,null);return}let c=a[0];return this.uuidCache.set(s,c),c}this.uuidCache.set(s,null)}cacheUUIDResult(e,t){let n=e.toLowerCase();this.uuidCache.set(n,t)}getCachedUUID(e){let t=e.toLowerCase();if(this.uuidCache.has(t))return this.uuidCache.get(t)}};po.FilterExecutor=fy});var dy=_(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});ch.OptionalExecutor=void 0;var hy=class{static{o(this,"OptionalExecutor")}async*execute(e,t){let n=[];for await(let s of e)n.push(s);let i=[];for await(let s of t)i.push(s);for(let s of n){let a=!1;for(let c of i){let u=s.merge(c);u!==null&&(yield u,a=!0)}a||(yield s)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}};ch.OptionalExecutor=hy});var my=_(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});uh.UnionExecutor=void 0;var py=class{static{o(this,"UnionExecutor")}async*execute(e,t){let n=new Set;for await(let i of e){let s=this.getSolutionKey(i);n.has(s)||(n.add(s),yield i)}for await(let i of t){let s=this.getSolutionKey(i);n.has(s)||(n.add(s),yield i)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}};uh.UnionExecutor=py});var vy=_(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});lh.ConstructExecutor=void 0;var GN=$i(),ha=Ye(),gy=ht(),yy=Rt(),WN=wc(),_y=class{static{o(this,"ConstructExecutor")}async execute(e,t){let n=[],i=new Set;for(let s of t)for(let a of e)try{let c=this.instantiateTriple(a,s),u=`${c.subject.toString()}|${c.predicate.toString()}|${c.object.toString()}`;i.has(u)||(i.add(u),n.push(c))}catch{continue}return n}instantiateTriple(e,t){if(this.isPropertyPath(e.predicate))throw new Error("Property paths are not supported in CONSTRUCT templates");let n=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.predicate,t),s=this.instantiateElement(e.object,t);return new GN.Triple(n,i,s)}isPropertyPath(e){return e.type==="path"}instantiateElement(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable: ${e.value}`);return n}if(e.type==="iri")return new ha.IRI(e.value);if(e.type==="literal")return new gy.Literal(e.value,e.datatype?new ha.IRI(e.datatype):void 0,e.language);if(e.type==="blank")return new yy.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Unknown element type: ${e.type}`)}instantiateQuotedTriple(e,t){let n=this.instantiateQuotedSubject(e.subject,t),i=this.instantiateQuotedPredicate(e.predicate,t),s=this.instantiateQuotedObject(e.object,t);return new WN.QuotedTriple(n,i,s)}instantiateQuotedSubject(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable in quoted triple subject: ${e.value}`);if(n instanceof gy.Literal)throw new Error("Literals cannot appear in quoted triple subject position");return n}if(e.type==="iri")return new ha.IRI(e.value);if(e.type==="blank")return new yy.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Invalid element type for quoted triple subject: ${e.type}`)}instantiateQuotedPredicate(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable in quoted triple predicate: ${e.value}`);if(!(n instanceof ha.IRI))throw new Error("Quoted triple predicate must be an IRI");return n}return new ha.IRI(e.value)}instantiateQuotedObject(e,t){if(e.type==="variable"){let i=t.get(e.value);if(!i)throw new Error(`Unbound variable in quoted triple object: ${e.value}`);return i}if(e.type==="iri")return new ha.IRI(e.value);if(e.type==="blank")return new yy.BlankNode(e.value);if(e.type==="literal")return new gy.Literal(e.value,e.datatype?new ha.IRI(e.datatype):void 0,e.language);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);let n=e;throw new Error(`Invalid element type for quoted triple object: ${n.type}`)}};lh.ConstructExecutor=_y});var Jb=_(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});fh.DescribeExecutor=void 0;var Xb=Ye(),Sy=class{static{o(this,"DescribeExecutor")}constructor(e){this.tripleStore=e}async execute(e,t){let n=[],i=new Set,s=new Set,a=t?.depth;for(let c of e)await this.describeResourceWithDepth(c,a,1,t?.symmetric??!0,n,i,s);return n}async describeResourceWithDepth(e,t,n,i,s,a,c){let u=e.toString();if(c.has(u)||(c.add(u),t!==void 0&&n>t))return;let l=[],f=await this.tripleStore.match(e,void 0,void 0);if(l.push(...f),i){let d=await this.tripleStore.match(void 0,void 0,e);l.push(...d)}let h=[];for(let d of l){let p=`${d.subject.toString()}|${d.predicate.toString()}|${d.object.toString()}`;a.has(p)||(a.add(p),s.push(d),(t===void 0||n<t)&&(this.isIRI(d.subject)&&d.subject.toString()!==u&&h.push(d.subject),this.isIRI(d.object)&&d.object.toString()!==u&&h.push(d.object)))}for(let d of h)await this.describeResourceWithDepth(d,t,n+1,i,s,a,c)}isIRI(e){return e?e instanceof Xb.IRI||e.termType==="NamedNode"||typeof e.value=="string"&&e.value.startsWith("http"):!1}async describeByIRI(e,t){let n=new Xb.IRI(e);return this.execute([n],t)}};fh.DescribeExecutor=Sy});var Zb=_(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});hh.MinusExecutor=void 0;var by=class{static{o(this,"MinusExecutor")}async*execute(e,t){let n=[];for await(let s of e)n.push(s);let i=[];for await(let s of t)i.push(s);for(let s of n){let a=!1;for(let c of i)if(this.areCompatible(s,c)){a=!0;break}a||(yield s)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}areCompatible(e,t){let n=e.variables(),i=new Set(t.variables()),s=n.filter(a=>i.has(a));if(s.length===0)return!1;for(let a of s){let c=e.get(a),u=t.get(a);if(c===void 0||u===void 0||c.toString()!==u.toString())return!1}return!0}};hh.MinusExecutor=by});var tw=_(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.ValuesExecutor=mo.ValuesExecutorError=void 0;var HN=Hi(),ew=Ye(),zN=ht(),dh=class extends Error{static{o(this,"ValuesExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ValuesExecutorError"}};mo.ValuesExecutorError=dh;var wy=class{static{o(this,"ValuesExecutor")}async*execute(e){if(e.bindings.length!==0)for(let t of e.bindings)yield this.createSolutionMapping(t)}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}createSolutionMapping(e){let t=new HN.SolutionMapping;for(let[n,i]of Object.entries(e)){let s=this.toRDFTerm(i);t.set(n,s)}return t}toRDFTerm(e){if(e.type==="iri")return new ew.IRI(e.value);if(e.type==="literal")return new zN.Literal(e.value,e.datatype?new ew.IRI(e.datatype):void 0,e.language,e.direction);throw new dh(`Unknown term type: ${e.type}`)}};mo.ValuesExecutor=wy});var Ey=_(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.CustomAggregateRegistry=yo.CustomAggregateError=void 0;var go=class extends Error{static{o(this,"CustomAggregateError")}constructor(e,t){super(e),this.iri=t,this.name="CustomAggregateError"}};yo.CustomAggregateError=go;var ph=class r{static{o(this,"CustomAggregateRegistry")}constructor(){this.aggregates=new Map}static getInstance(){return r.instance||(r.instance=new r),r.instance}static resetInstance(){r.instance&&r.instance.clear(),r.instance=null}register(e,t){if(!e||typeof e!="string")throw new go("Aggregate IRI must be a non-empty string");if(!t||typeof t.init!="function"||typeof t.step!="function"||typeof t.finalize!="function")throw new go("Aggregate must implement init(), step(), and finalize() methods",e);if(this.aggregates.has(e))throw new go(`Aggregate with IRI "${e}" is already registered`,e);this.aggregates.set(e,t)}unregister(e){return this.aggregates.delete(e)}get(e){return this.aggregates.get(e)}has(e){return this.aggregates.has(e)}getRegisteredIris(){return Array.from(this.aggregates.keys())}clear(){this.aggregates.clear()}get size(){return this.aggregates.size}};yo.CustomAggregateRegistry=ph;ph.instance=null});var Ty=_(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.BUILT_IN_AGGREGATES=Be.modeAggregate=Be.stddevAggregate=Be.varianceAggregate=Be.medianAggregate=Be.EXO_AGGREGATE_NS=void 0;Be.getNumericValue=mh;Be.createDecimalLiteral=zn;Be.createDoubleLiteral=KN;Be.createPercentileAggregate=da;var pa=ht(),_o=Ye(),YN=new _o.IRI("http://www.w3.org/2001/XMLSchema#decimal"),QN=new _o.IRI("http://www.w3.org/2001/XMLSchema#double");Be.EXO_AGGREGATE_NS="https://exocortex.my/ontology/agg#";function mh(r){return r==null?NaN:typeof r=="number"?r:typeof r=="string"?parseFloat(r):r instanceof pa.Literal?parseFloat(r.value):r instanceof _o.IRI?NaN:typeof r=="boolean"?r?1:0:NaN}o(mh,"getNumericValue");function zn(r){return new pa.Literal(String(r),YN)}o(zn,"createDecimalLiteral");function KN(r){return new pa.Literal(String(r),QN)}o(KN,"createDoubleLiteral");Be.medianAggregate={init(){return{values:[]}},step(r,e){let t=r,n=mh(e);isNaN(n)||t.values.push(n)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return zn(0);let n=[...t].sort((a,c)=>a-c),i=Math.floor(n.length/2),s=n.length%2!==0?n[i]:(n[i-1]+n[i])/2;return zn(s)}};Be.varianceAggregate={init(){return{values:[]}},step(r,e){let t=r,n=mh(e);isNaN(n)||t.values.push(n)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return zn(0);let n=t.reduce((s,a)=>s+a,0)/t.length,i=t.reduce((s,a)=>s+Math.pow(a-n,2),0)/t.length;return zn(i)}};Be.stddevAggregate={init(){return{values:[]}},step(r,e){Be.varianceAggregate.step(r,e)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return zn(0);let n=t.reduce((s,a)=>s+a,0)/t.length,i=t.reduce((s,a)=>s+Math.pow(a-n,2),0)/t.length;return zn(Math.sqrt(i))}};Be.modeAggregate={init(){return{counts:new Map,values:new Map}},step(r,e){if(e==null)return;let t=r,n=String(e instanceof pa.Literal||e instanceof _o.IRI?e.value:e),i=t.counts.get(n)||0;t.counts.set(n,i+1),t.values.set(n,e)},finalize(r){let e=r;if(e.counts.size===0)return new pa.Literal(" ",new _o.IRI("http://www.w3.org/2001/XMLSchema#string"));let t="",n=0;for(let[a,c]of e.counts)c>n&&(n=c,t=a);let i=e.values.get(t);if(i instanceof pa.Literal)return i;let s=parseFloat(t);return isNaN(s)?new pa.Literal(t,new _o.IRI("http://www.w3.org/2001/XMLSchema#string")):zn(s)}};function da(r){let e=Math.max(0,Math.min(100,r))/100;return{init(){return{values:[],percentile:e}},step(t,n){let i=t,s=mh(n);isNaN(s)||i.values.push(s)},finalize(t){let n=t,{values:i}=n;if(i.length===0)return zn(0);let s=[...i].sort((h,d)=>h-d),a=n.percentile*(s.length-1),c=Math.floor(a),u=Math.ceil(a);if(c===u)return zn(s[c]);let l=a-c,f=s[c]*(1-l)+s[u]*l;return zn(f)}}}o(da,"createPercentileAggregate");Be.BUILT_IN_AGGREGATES={[`${Be.EXO_AGGREGATE_NS}median`]:Be.medianAggregate,[`${Be.EXO_AGGREGATE_NS}variance`]:Be.varianceAggregate,[`${Be.EXO_AGGREGATE_NS}stddev`]:Be.stddevAggregate,[`${Be.EXO_AGGREGATE_NS}mode`]:Be.modeAggregate,[`${Be.EXO_AGGREGATE_NS}percentile25`]:da(25),[`${Be.EXO_AGGREGATE_NS}percentile50`]:da(50),[`${Be.EXO_AGGREGATE_NS}percentile75`]:da(75),[`${Be.EXO_AGGREGATE_NS}percentile90`]:da(90),[`${Be.EXO_AGGREGATE_NS}percentile95`]:da(95),[`${Be.EXO_AGGREGATE_NS}percentile99`]:da(99)}});var iw=_(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.AggregateExecutor=vo.AggregateExecutorError=void 0;var Lt=ht(),xy=Ye(),XN=oh(),JN=Ey(),ZN=Ty(),rw=new xy.IRI("http://www.w3.org/2001/XMLSchema#integer"),ma=new xy.IRI("http://www.w3.org/2001/XMLSchema#decimal"),yi=new xy.IRI("http://www.w3.org/2001/XMLSchema#string");function nw(r){return typeof r=="object"&&r.type==="custom"}o(nw,"isCustomAggregation");var Kc=class extends Error{static{o(this,"AggregateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AggregateExecutorError"}};vo.AggregateExecutorError=Kc;var Ay=class{static{o(this,"AggregateExecutor")}constructor(){this.filterExecutor=new XN.FilterExecutor}execute(e,t){let n=this.groupSolutions(t,e.variables),i=[];for(let[s,a]of n.entries()){let c=new Map;for(let f of e.variables)if(a.length>0){let h=a[0].get(f);h&&c.set(f,h)}for(let f of e.aggregates){let h=this.computeAggregate(f.expression,a);c.set(f.variable,h)}let{SolutionMapping:u}=Hi(),l=new u;for(let[f,h]of c.entries())l.set(f,h);i.push(l)}if(i.length===0&&e.aggregates.length>0){let s=this.createEmptyAggregateResult(e);s&&i.push(s)}return i}groupSolutions(e,t){let n=new Map;if(t.length===0)return n.set("",e),n;for(let i of e){let s=this.computeGroupKey(i,t),a=n.get(s);a?a.push(i):n.set(s,[i])}return n}computeGroupKey(e,t){return t.map(n=>{let i=e.get(n);return i?this.termToString(i):""}).join("|")}termToString(e){if(e&&typeof e=="object"){if("value"in e)return String(e.value);if("id"in e)return String(e.id)}return String(e)}computeAggregate(e,t){if(nw(e.aggregation))return this.computeCustomAggregate(e,t);let n=this.extractValues(e,t),i=e.aggregation;switch(i){case"count":{let s=this.computeCount(n,e.distinct);return new Lt.Literal(String(s),rw)}case"sum":{let s=this.computeSum(n);return new Lt.Literal(String(s),ma)}case"avg":{let s=this.computeAvg(n);return new Lt.Literal(String(s),ma)}case"min":{let s=this.computeMin(n);return s===void 0?new Lt.Literal("",yi):typeof s=="number"?new Lt.Literal(String(s),ma):new Lt.Literal(String(s),yi)}case"max":{let s=this.computeMax(n);return s===void 0?new Lt.Literal("",yi):typeof s=="number"?new Lt.Literal(String(s),ma):new Lt.Literal(String(s),yi)}case"group_concat":{let s=this.computeGroupConcat(n,e.separator||" ",e.distinct);return new Lt.Literal(s||" ",yi)}case"sample":{let s=this.computeSample(n,e.distinct);return s===void 0?new Lt.Literal(" ",yi):typeof s=="number"?new Lt.Literal(String(s),ma):new Lt.Literal(String(s),yi)}default:{let s=i;throw new Kc(`Unknown aggregation function: ${s}`)}}}computeCustomAggregate(e,t){let i=e.aggregation.iri,a=JN.CustomAggregateRegistry.getInstance().get(i);if(a||(a=ZN.BUILT_IN_AGGREGATES[i]),!a)throw new Kc(`Unknown custom aggregate function: ${i}. Register it with CustomAggregateRegistry.getInstance().register() or use a built-in aggregate.`);let c=a.init();for(let u of t){let l=null;if(e.expression){let f=this.evaluateExpression(e.expression,u);f!==void 0&&(l=f)}else l=1;a.step(c,l)}return a.finalize(c)}extractValues(e,t){if(!e.expression)return t.map(()=>1);let n=[];for(let i of t){let s=this.evaluateExpression(e.expression,i);s!=null&&n.push(s)}return n}evaluateExpression(e,t){if(e.type==="variable"){let n=t.get(e.name);return n==null?void 0:typeof n=="number"||typeof n=="string"||typeof n=="boolean"?n:typeof n=="object"&&"value"in n?n.value:n}if(e.type==="literal")return e.value;try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}computeCount(e,t){return t?new Set(e.map(n=>String(n))).size:e.length}computeSum(e){return e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n)).reduce((n,i)=>n+i,0)}computeAvg(e){let t=e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n));return t.length===0?0:t.reduce((n,i)=>n+i,0)/t.length}computeMin(e){if(e.length===0)return;let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));if(t.length>0)return Math.min(...t);let n=e.map(i=>String(i));return n.reduce((i,s)=>s<i?s:i,n[0])}computeMax(e){if(e.length===0)return;let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));if(t.length>0)return Math.max(...t);let n=e.map(i=>String(i));return n.reduce((i,s)=>s>i?s:i,n[0])}computeGroupConcat(e,t,n){let i=e.map(s=>String(s));return n&&(i=[...new Set(i)]),i.join(t)}computeSample(e,t){if(e.length===0)return;if(t){let s=[...new Set(e.map(u=>String(u)))];if(s.length===0)return;let a=s[0],c=parseFloat(a);return isNaN(c)?a:c}let n=e[0];if(typeof n=="number")return n;let i=parseFloat(String(n));return isNaN(i)?String(n):i}createEmptyAggregateResult(e){let{SolutionMapping:t}=Hi(),n=new t;for(let i of e.aggregates){let s=i.expression.aggregation;if(nw(s)){n.set(i.variable,new Lt.Literal("0",ma));continue}switch(s){case"count":n.set(i.variable,new Lt.Literal("0",rw));break;case"sum":case"avg":n.set(i.variable,new Lt.Literal("0",ma));break;case"group_concat":n.set(i.variable,new Lt.Literal(" ",yi));break;case"min":case"max":case"sample":n.set(i.variable,new Lt.Literal("",yi));break;default:n.set(i.variable,new Lt.Literal("",yi))}}return n}};vo.AggregateExecutor=Ay});var aw=_(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.ServiceExecutor=So.ServiceExecutorError=void 0;var e5=Hi(),sw=Ye(),t5=ht(),r5=Rt(),ga=class extends Error{static{o(this,"ServiceExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ServiceExecutorError"}};So.ServiceExecutorError=ga;var Cy=class{static{o(this,"ServiceExecutor")}constructor(e={}){this.timeout=e.timeout??3e4,this.httpClient=e.httpClient??((t,n)=>fetch(t,n)),this.maxRetries=e.maxRetries??2,this.retryDelay=e.retryDelay??1e3}async*execute(e,t){try{let n=t(e.pattern),i=await this.executeRemoteQuery(e.endpoint,n);for(let s of i)yield s}catch(n){if(e.silent)return;throw n}}async executeRemoteQuery(e,t){let n;for(let i=0;i<=this.maxRetries;i++)try{let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout);try{let c=await this.httpClient(e,{method:"POST",headers:{"Content-Type":"application/sparql-query",Accept:"application/sparql-results+json"},body:t,signal:s.signal});if(!c.ok)throw new ga(`Remote SPARQL endpoint returned ${c.status}: ${c.statusText}`);let u=await c.json();return this.parseJsonResults(u)}finally{clearTimeout(a)}}catch(s){if(n=s instanceof Error?s:new Error(String(s)),this.isRetryableError(n)&&i<this.maxRetries){await this.delay(this.retryDelay);continue}throw new ga(`Failed to query remote SPARQL endpoint ${e}: ${n.message}`,n)}throw new ga(`Failed to query remote SPARQL endpoint ${e} after ${this.maxRetries+1} attempts`,n)}parseJsonResults(e){return!e.results||!Array.isArray(e.results.bindings)?[]:e.results.bindings.map(t=>this.parseBinding(t))}parseBinding(e){let t=new e5.SolutionMapping;for(let[n,i]of Object.entries(e)){let s=this.parseRDFTerm(i);t.set(n,s)}return t}parseRDFTerm(e){switch(e.type){case"uri":return new sw.IRI(e.value);case"literal":{let t=e.datatype?new sw.IRI(e.datatype):void 0;return new t5.Literal(e.value,t,e["xml:lang"])}case"bnode":return new r5.BlankNode(e.value);default:throw new ga(`Unknown RDF term type: ${e.type}`)}}isRetryableError(e){let t=e.message.toLowerCase();return!!(e.name==="AbortError"||t.includes("network")||t.includes("econnreset")||t.includes("econnrefused")||t.includes("etimedout")||t.includes("returned 5"))}delay(e){return new Promise(t=>setTimeout(t,e))}};So.ServiceExecutor=Cy});var cw=_(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.GraphExecutor=bo.GraphExecutorError=void 0;var ow=Ye(),gh=class extends Error{static{o(this,"GraphExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="GraphExecutorError"}};bo.GraphExecutorError=gh;var Iy=class{static{o(this,"GraphExecutor")}constructor(e){this.tripleStore=e}async*execute(e,t,n){let i=e.name;if(i.type==="iri")yield*this.executeWithGraph(e.pattern,i,t);else if(i.type==="variable")yield*this.executeWithGraphVariable(e,i,t,n);else throw new gh(`Invalid graph name type: ${i.type}`)}async*executeWithGraph(e,t,n){let i=new ow.IRI(t.value);this.tripleStore.hasGraph&&!await this.tripleStore.hasGraph(i)||(yield*n(e,i))}async*executeWithGraphVariable(e,t,n,i){if(i){let a=i.get(t.value);if(a&&a instanceof ow.IRI){yield*this.executeWithGraph(e.pattern,{type:"iri",value:a.value},n);return}}if(!this.tripleStore.getNamedGraphs)return;let s=await this.tripleStore.getNamedGraphs();for(let a of s)for await(let c of n(e.pattern,a)){let u=c.clone();u.set(t.value,a),yield u}}};bo.GraphExecutor=Iy});var uw=_(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.SPARQLGenerator=Eo.SPARQLGeneratorError=void 0;var wo=class extends Error{static{o(this,"SPARQLGeneratorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="SPARQLGeneratorError"}};Eo.SPARQLGeneratorError=wo;var Oy=class{static{o(this,"SPARQLGenerator")}collectVariables(e){let t=new Set;return this.collectVariablesFromOperation(e,t),t}generateSelect(e){let t=this.collectVariables(e),n=t.size>0?Array.from(t).map(s=>`?${s}`).join(" "):"*",i=this.generateWhereClause(e);return`SELECT ${n} WHERE {
292
+ ${n})`;default:return`${n}Unknown(${e.type})`}}tripleToString(e){return`${this.elementToString(e.subject)} ${this.predicateToString(e.predicate)} ${this.elementToString(e.object)}`}predicateToString(e){return this.isPropertyPath(e)?this.propertyPathToString(e):this.elementToString(e)}isPropertyPath(e){return e.type==="path"}propertyPathToString(e){let t=e.items.map(n=>n.type==="path"?`(${this.propertyPathToString(n)})`:`<${n.value}>`);switch(e.pathType){case"/":return t.join("/");case"|":return t.join("|");case"^":return`^${t[0]}`;case"+":return`${t[0]}+`;case"*":return`${t[0]}*`;case"?":return`${t[0]}?`}}elementToString(e){switch(e.type){case"variable":return`?${e.value}`;case"iri":return`<${e.value}>`;case"literal":let t=`"${e.value}"`;return e.language&&(t+=`@${e.language}`),e.datatype&&(t+=`^^<${e.datatype}>`),t;case"blank":return`_:${e.value}`;default:return String(e)}}expressionToString(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value}"`:String(e.value);case"comparison":return`(${this.expressionToString(e.left)} ${e.operator} ${this.expressionToString(e.right)})`;case"logical":return e.operator==="!"?`!(${this.expressionToString(e.operands[0])})`:`(${e.operands.map(t=>this.expressionToString(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.expressionToString(e.left)} ${e.operator} ${this.expressionToString(e.right)})`;case"function":return`${e.function}(${e.args.map(t=>this.expressionToString(t)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.toString(e.pattern,0)} }`;default:return"unknown"}}toJSON(e){return JSON.stringify(e,null,2)}};Zf.AlgebraSerializer=iy});var Hi=_(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});eh.SolutionMapping=void 0;var kb=ht(),jb=Ye(),$b=Rt(),sy=class r{static{o(this,"SolutionMapping")}constructor(e){this.bindings=e?new Map(e):new Map}get(e){return this.bindings.get(e)}set(e,t){this.bindings.set(e,t)}has(e){return this.bindings.has(e)}variables(){return Array.from(this.bindings.keys())}getBindings(){return new Map(this.bindings)}isCompatibleWith(e){for(let[t,n]of this.bindings.entries()){let i=e.get(t);if(i!==void 0&&!this.areEqual(n,i))return!1}return!0}merge(e){if(!this.isCompatibleWith(e))return null;let t=new r(this.bindings);for(let[n,i]of e.getBindings().entries())t.set(n,i);return t}clone(){return new r(this.bindings)}areEqual(e,t){return e instanceof kb.Literal&&t instanceof kb.Literal?e.equals(t):e instanceof jb.IRI&&t instanceof jb.IRI?e.value===t.value:e instanceof $b.BlankNode&&t instanceof $b.BlankNode?e.id===t.id:!1}toJSON(){let e={};for(let[t,n]of this.bindings.entries())e[t]=n.toString();return e}size(){return this.bindings.size}};eh.SolutionMapping=sy});var Vb=_(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.PropertyPathExecutor=uo.PropertyPathExecutorError=void 0;var VN=Hi(),th=Ye(),Bb=Rt(),Yc=class extends Error{static{o(this,"PropertyPathExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="PropertyPathExecutorError"}};uo.PropertyPathExecutorError=Yc;var ay=class{static{o(this,"PropertyPathExecutor")}constructor(e){this.tripleStore=e,this.MAX_DEPTH=100}async*execute(e,t,n){let i=await this.resolveElement(e),s=this.isVariable(n)?null:await this.resolveElement(n);for(let a of i){let c=await this.evaluatePath(a,t,s);for(let u of c){let l=new VN.SolutionMapping;this.isVariable(e)&&l.set(e.value,a),this.isVariable(n)&&l.set(n.value,u),yield l}}}async*executeWithBindings(e,t){if(!this.isPropertyPath(e.predicate))throw new Yc("Predicate is not a property path");let n=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.object,t);for await(let s of this.execute(n,e.predicate,i)){let a=t.merge(s);a!==null&&(yield a)}}async evaluatePath(e,t,n){switch(t.pathType){case"/":return this.evaluateSequencePath(e,t.items,n);case"|":return this.evaluateAlternativePath(e,t.items,n);case"^":return this.evaluateInversePath(e,t.items[0],n);case"+":return this.evaluateOneOrMorePath(e,t.items[0],n);case"*":return this.evaluateZeroOrMorePath(e,t.items[0],n);case"?":return this.evaluateZeroOrOnePath(e,t.items[0],n)}}async evaluateSequencePath(e,t,n){let i=new Set([e]);for(let s=0;s<t.length;s++){let a=t[s],c=s===t.length-1,u=new Set;for(let l of i){let f=await this.evaluatePathItem(l,a,c?n:null);for(let h of f)u.add(h)}if(i=u,i.size===0)break}return i}async evaluateAlternativePath(e,t,n){let i=new Set;for(let s of t){let a=await this.evaluatePathItem(e,s,n);for(let c of a)i.add(c)}return i}async evaluateInversePath(e,t,n){if(t.type==="iri"){let i=new th.IRI(t.value),s=await this.tripleStore.match(void 0,i,e),a=new Set;for(let c of s)(n===null||this.nodeInSet(c.subject,n))&&a.add(c.subject);return a}else return this.evaluatePath(e,this.invertPath(t),n)}async evaluateOneOrMorePath(e,t,n){let i=new Set,s=new Set,a=[{node:e,depth:0}];for(;a.length>0;){let{node:c,depth:u}=a.shift();if(u>=this.MAX_DEPTH)continue;let l=await this.evaluatePathItem(c,t,null);for(let f of l){let h=this.nodeToKey(f);(n===null||this.nodeInSet(f,n))&&s.add(f),i.has(h)||(i.add(h),a.push({node:f,depth:u+1}))}}return s}async evaluateZeroOrMorePath(e,t,n){let i=await this.evaluateOneOrMorePath(e,t,n);return(n===null||this.nodeInSet(e,n))&&i.add(e),i}async evaluateZeroOrOnePath(e,t,n){let i=new Set;(n===null||this.nodeInSet(e,n))&&i.add(e);let s=await this.evaluatePathItem(e,t,n);for(let a of s)i.add(a);return i}async evaluatePathItem(e,t,n){if(t.type==="iri"){let i=new th.IRI(t.value),s=await this.tripleStore.match(e,i,void 0),a=new Set;for(let c of s)(n===null||this.nodeInSet(c.object,n))&&a.add(c.object);return a}else return this.evaluatePath(e,t,n)}invertPath(e){switch(e.pathType){case"^":return e.items[0];case"/":return{type:"path",pathType:"/",items:[...e.items].reverse().map(n=>n.type==="iri"?{type:"path",pathType:"^",items:[n]}:this.invertPath(n))};case"|":return{type:"path",pathType:"|",items:e.items.map(n=>n.type==="iri"?{type:"path",pathType:"^",items:[n]}:this.invertPath(n))};case"+":case"*":case"?":let t=e.items[0].type==="iri"?{type:"path",pathType:"^",items:[e.items[0]]}:this.invertPath(e.items[0]);return{type:"path",pathType:e.pathType,items:[t]}}}async resolveElement(e){if(this.isVariable(e)){let n=new Set,i=await this.tripleStore.match(void 0,void 0,void 0);for(let s of i)n.add(s.subject),n.add(s.object);return n}let t=new Set;switch(e.type){case"iri":t.add(new th.IRI(e.value));break;case"blank":t.add(new Bb.BlankNode(e.value));break;default:throw new Yc(`Unsupported element type in subject/object position: ${e.type}`)}return t}instantiateElement(e,t){if(this.isVariable(e)){let n=t.get(e.value);if(n){if(n instanceof th.IRI)return{type:"iri",value:n.value};if(n instanceof Bb.BlankNode)return{type:"blank",value:n.id}}}return e}isVariable(e){return e.type==="variable"}isPropertyPath(e){return e.type==="path"}nodeToKey(e){return e.toString()}nodeInSet(e,t){let n=this.nodeToKey(e);for(let i of t)if(this.nodeToKey(i)===n)return!0;return!1}};uo.PropertyPathExecutor=ay});var uy=_(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.BGPExecutor=lo.BGPExecutorError=void 0;var rh=Hi(),gs=Ye(),oy=ht(),nh=Rt(),ih=wc(),UN=Vb(),fr=class extends Error{static{o(this,"BGPExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="BGPExecutorError"}};lo.BGPExecutorError=fr;var cy=class{static{o(this,"BGPExecutor")}constructor(e){this.tripleStore=e,this.propertyPathExecutor=new UN.PropertyPathExecutor(e)}async*execute(e){if(e.triples.length===0){yield new rh.SolutionMapping;return}let t=this.matchTriplePattern(e.triples[0]);for(let n=1;n<e.triples.length;n++)t=this.joinWithPattern(t,e.triples[n]);for await(let n of t)yield n}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*executeInGraph(e,t){if(e.triples.length===0){yield new rh.SolutionMapping;return}let n=this.matchTriplePatternInGraph(e.triples[0],t);for(let i=1;i<e.triples.length;i++)n=this.joinWithPatternInGraph(n,e.triples[i],t);for await(let i of n)yield i}async*matchTriplePatternInGraph(e,t){if(this.isPropertyPath(e.predicate))throw new fr("Property paths within named graphs are not yet supported");let n=e.predicate,i=this.isVariable(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),s=this.isVariable(n)?void 0:this.toRDFTermAsPredicate(n),a=this.isVariable(e.object)?void 0:this.toRDFTerm(e.object);if(!this.tripleStore.matchInGraph)throw new fr("Triple store does not support named graph operations");let c=await this.tripleStore.matchInGraph(i,s,a,t);for(let u of c){let l=new rh.SolutionMapping;this.isVariable(e.subject)&&l.set(e.subject.value,u.subject),this.isVariable(n)&&l.set(n.value,u.predicate),this.isVariable(e.object)&&l.set(e.object.value,u.object),yield l}}async*joinWithPatternInGraph(e,t,n){let i=[];for await(let s of e)i.push(s);for(let s of i){let a=this.instantiatePattern(t,s);for await(let c of this.matchTriplePatternInGraph(a,n)){let u=s.merge(c);u!==null&&(yield u)}}}async*matchTriplePattern(e){if(this.isPropertyPath(e.predicate)){yield*this.propertyPathExecutor.execute(e.subject,e.predicate,e.object);return}let t=e.predicate,n=this.isVariable(e.subject)||this.isQuotedTriple(e.subject)&&this.hasVariablesInQuotedTriple(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),i=this.isVariable(t)?void 0:this.toRDFTermAsPredicate(t),s=this.isVariable(e.object)||this.isQuotedTriple(e.object)&&this.hasVariablesInQuotedTriple(e.object)?void 0:this.toRDFTerm(e.object),a=await this.tripleStore.match(n,i,s);for(let c of a){let u=new rh.SolutionMapping;if(this.isVariable(e.subject))u.set(e.subject.value,c.subject);else if(this.isQuotedTriple(e.subject)){let l=this.matchQuotedTriplePattern(e.subject,c.subject);if(l===null)continue;for(let[f,h]of l.entries())u.set(f,h)}if(this.isVariable(t)&&u.set(t.value,c.predicate),this.isVariable(e.object))u.set(e.object.value,c.object);else if(this.isQuotedTriple(e.object)){let l=this.matchQuotedTriplePattern(e.object,c.object);if(l===null)continue;for(let[f,h]of l.entries())u.set(f,h)}yield u}}hasVariablesInQuotedTriple(e){return!!(this.isVariable(e.subject)||e.predicate.type==="variable"||this.isVariable(e.object)||this.isQuotedTriple(e.subject)&&this.hasVariablesInQuotedTriple(e.subject)||this.isQuotedTriple(e.object)&&this.hasVariablesInQuotedTriple(e.object))}matchQuotedTriplePattern(e,t){if(!(t instanceof ih.QuotedTriple))return null;let n=new Map;if(this.isVariable(e.subject))n.set(e.subject.value,t.subject);else if(this.isQuotedTriple(e.subject)){let i=this.matchQuotedTriplePattern(e.subject,t.subject);if(i===null)return null;for(let[s,a]of i)n.set(s,a)}else if(!this.elementsMatch(e.subject,t.subject))return null;if(e.predicate.type==="variable")n.set(e.predicate.value,t.predicate);else if(e.predicate.value!==t.predicate.value)return null;if(this.isVariable(e.object))n.set(e.object.value,t.object);else if(this.isQuotedTriple(e.object)){let i=this.matchQuotedTriplePattern(e.object,t.object);if(i===null)return null;for(let[s,a]of i)n.set(s,a)}else if(!this.elementsMatch(e.object,t.object))return null;return n}elementsMatch(e,t){switch(e.type){case"iri":return t instanceof gs.IRI&&e.value===t.value;case"literal":return!(!(t instanceof oy.Literal)||e.value!==t.value||e.datatype!==t.datatype?.value||e.language!==t.language||e.direction!==t.direction);case"blank":return t instanceof nh.BlankNode&&e.value===t.id;case"quoted":return t instanceof ih.QuotedTriple?this.toRDFQuotedTriple(e).equals(t):!1;default:return!1}}isPropertyPath(e){return e.type==="path"}async*joinWithPattern(e,t){let n=[];for await(let i of e)n.push(i);for(let i of n){let s=this.instantiatePattern(t,i);for await(let a of this.matchTriplePattern(s)){let c=i.merge(a);c!==null&&(yield c)}}}instantiatePattern(e,t){let n=this.isPropertyPath(e.predicate)?e.predicate:this.instantiateElement(e.predicate,t);return{subject:this.instantiateElement(e.subject,t),predicate:n,object:this.instantiateElement(e.object,t)}}instantiateElement(e,t){if(this.isVariable(e)){let n=t.get(e.value);if(n)return this.toAlgebraElement(n)}return this.isQuotedTriple(e)?this.instantiateQuotedTriple(e,t):e}instantiateQuotedTriple(e,t){let n=this.instantiateElement(e.subject,t),i=e.predicate.type==="variable"?this.instantiatePredicateVariable(e.predicate,t):e.predicate,s=this.instantiateElement(e.object,t);return{type:"quoted",subject:n,predicate:i,object:s}}instantiatePredicateVariable(e,t){let n=t.get(e.value);return n&&n instanceof gs.IRI?{type:"iri",value:n.value}:e}isVariable(e){return e.type==="variable"}isQuotedTriple(e){return e.type==="quoted"}toRDFTermAsSubject(e){switch(e.type){case"iri":return new gs.IRI(e.value);case"blank":return new nh.BlankNode(e.value);case"literal":throw new fr("Literals cannot appear in subject position");case"variable":throw new fr(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new fr(`Unknown element type: ${e.type}`)}}toRDFQuotedTriple(e){let t=this.toRDFTermAsSubject(e.subject),n=e.predicate.type==="iri"?new gs.IRI(e.predicate.value):(()=>{throw new fr("Quoted triple predicate must be IRI")})(),i=this.toRDFTerm(e.object);return new ih.QuotedTriple(t,n,i)}toRDFTermAsPredicate(e){switch(e.type){case"iri":return new gs.IRI(e.value);case"literal":throw new fr("Literals cannot appear in predicate position");case"blank":throw new fr("Blank nodes cannot appear in predicate position");case"variable":throw new fr(`Cannot convert variable to RDF term: ${e.value}`);default:throw new fr(`Unknown element type: ${e.type}`)}}toRDFTerm(e){switch(e.type){case"iri":return new gs.IRI(e.value);case"literal":return new oy.Literal(e.value,e.datatype?new gs.IRI(e.datatype):void 0,e.language,e.direction);case"blank":return new nh.BlankNode(e.value);case"variable":throw new fr(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new fr(`Unknown element type: ${e.type}`)}}toAlgebraElement(e){if(e instanceof gs.IRI)return{type:"iri",value:e.value};if(e instanceof oy.Literal)return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language,direction:e.direction};if(e instanceof nh.BlankNode)return{type:"blank",value:e.id};if(e instanceof ih.QuotedTriple)return this.toAlgebraQuotedTriple(e);throw new fr(`Unknown RDF term type: ${e.constructor?.name||"unknown"}`)}toAlgebraQuotedTriple(e){return{type:"quoted",subject:this.toAlgebraElement(e.subject),predicate:{type:"iri",value:e.predicate.value},object:this.toAlgebraElement(e.object)}}};lo.BGPExecutor=cy});var ah=_(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});sh.BuiltInFunctions=void 0;var ge=Ye(),D=ht(),Or=Rt(),fo=wc(),ly=Er(),Qc=class{static{o(this,"BuiltInFunctions")}static str(e){if(e===void 0)throw new Error("STR: argument is undefined");return e instanceof ge.IRI||e instanceof D.Literal?e.value:e instanceof Or.BlankNode?e.id:String(e)}static lang(e){if(e===void 0)throw new Error("LANG: argument is undefined");return e instanceof D.Literal&&e.language?e.language:""}static langdir(e){if(e===void 0)throw new Error("LANGDIR: argument is undefined");return!(e instanceof D.Literal)||!e.language?"":e.direction?`${e.language}--${e.direction}`:e.language}static langMatches(e,t){let[n,i]=this.parseDirectionalLangTag(e),[s,a]=this.parseDirectionalLangTag(t),c=n.toLowerCase(),u=s.toLowerCase();return u==="*"?c!=="":c===""?u==="":a&&i!==a?!1:c===u?!0:c.startsWith(u+"-")}static parseDirectionalLangTag(e){let t=e.indexOf("--");if(t===-1)return[e,void 0];let n=e.substring(0,t),i=e.substring(t+2).toLowerCase();return[n,i]}static datatype(e){if(e===void 0)throw new Error("DATATYPE: argument is undefined");if(e instanceof D.Literal)return e.datatype?e.datatype:e.language?new ge.IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"):new ge.IRI("http://www.w3.org/2001/XMLSchema#string");throw new Error("DATATYPE: argument must be a literal")}static bound(e){return e!==void 0}static isIRI(e){return e===void 0?!1:e instanceof ge.IRI}static isBlank(e){return e===void 0?!1:e instanceof Or.BlankNode}static isLiteral(e){return e===void 0?!1:e instanceof D.Literal}static isTriple(e){return e===void 0?!1:e instanceof fo.QuotedTriple}static hasLangdir(e){return e===void 0||!(e instanceof D.Literal)?!1:!!e.language&&!!e.direction}static isNumeric(e){if(e===void 0||!(e instanceof D.Literal))return!1;let t=e.datatype?.value;return t?["http://www.w3.org/2001/XMLSchema#integer","http://www.w3.org/2001/XMLSchema#decimal","http://www.w3.org/2001/XMLSchema#float","http://www.w3.org/2001/XMLSchema#double","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#long","http://www.w3.org/2001/XMLSchema#int","http://www.w3.org/2001/XMLSchema#short","http://www.w3.org/2001/XMLSchema#byte","http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#unsignedLong","http://www.w3.org/2001/XMLSchema#unsignedInt","http://www.w3.org/2001/XMLSchema#unsignedShort","http://www.w3.org/2001/XMLSchema#unsignedByte","http://www.w3.org/2001/XMLSchema#positiveInteger"].includes(t):!1}static regex(e,t,n){try{let i=n?n.includes("u")?n:n+"u":"u";return new RegExp(t,i).test(e)}catch(i){throw new Error(`REGEX: invalid pattern '${t}': ${i.message}`)}}static compare(e,t,n){if(this.isDayTimeDurationValue(e)&&this.isDayTimeDurationValue(t))return this.compareDurations(e instanceof D.Literal?e:String(e),t instanceof D.Literal?t:String(t),n);let i=this.toComparableValue(e),s=this.toComparableValue(t);switch(n){case"=":return i===s;case"!=":return i!==s;case"<":return i<s;case">":return i>s;case"<=":return i<=s;case">=":return i>=s;default:throw new Error(`Unknown comparison operator: ${n}`)}}static isDayTimeDurationValue(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static toComparableValue(e){if(typeof e=="string"||typeof e=="number")return e;if(e instanceof D.Literal){let t=e.datatype?.value;if(t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double")){let n=parseFloat(e.value);if(!isNaN(n))return n}if(t==="http://www.w3.org/2001/XMLSchema#dayTimeDuration")try{return this.parseDayTimeDuration(e.value)}catch{return e.value}return e.value}return e instanceof ge.IRI?e.value:e instanceof Or.BlankNode?e.id:String(e)}static contains(e,t){return e.includes(t)}static strStarts(e,t){return e.startsWith(t)}static strEnds(e,t){return e.endsWith(t)}static strlen(e){return e.length}static ucase(e){return e.toUpperCase()}static lcase(e){return e.toLowerCase()}static substr(e,t,n){let i=t-1;if(i<0){if(n!==void 0){let s=n+i;return s<=0?"":e.substring(0,s)}return e}return n!==void 0?e.substring(i,i+n):e.substring(i)}static strBefore(e,t){if(t==="")return"";let n=e.indexOf(t);return n===-1?"":e.substring(0,n)}static strAfter(e,t){if(t==="")return e;let n=e.indexOf(t);return n===-1?"":e.substring(n+t.length)}static concat(...e){return e.join("")}static replace(e,t,n,i){try{let s=i||"g",a=s.includes("u")?s:s+"u",c=new RegExp(t,a);return e.replace(c,n)}catch(s){throw new Error(`REPLACE: invalid pattern '${t}': ${s.message}`)}}static parseDate(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`PARSEDATE: invalid date string '${e}'`);return t.getTime()}static dateBefore(e,t){let n=this.parseDate(e),i=this.parseDate(t);return n<i}static dateAfter(e,t){let n=this.parseDate(e),i=this.parseDate(t);return n>i}static dateInRange(e,t,n){let i=this.parseDate(e),s=this.parseDate(t),a=this.parseDate(n);return i>=s&&i<=a}static dateDiffMinutes(e,t){let n=this.parseDate(e),i=this.parseDate(t),s=Math.abs(i-n);return Math.round(s/(1e3*60))}static dateDiffHours(e,t){let n=this.parseDate(e),i=this.parseDate(t),s=Math.abs(i-n);return Math.round(s/(1e3*60*60)*100)/100}static logicalAnd(e){return e.every(t=>t===!0)}static logicalOr(e){return e.some(t=>t===!0)}static logicalNot(e){return!e}static year(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`YEAR: invalid date string '${e}'`);return t.getFullYear()}static month(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`MONTH: invalid date string '${e}'`);return t.getMonth()+1}static day(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`DAY: invalid date string '${e}'`);return t.getDate()}static hours(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`HOURS: invalid date string '${e}'`);return t.getHours()}static minutes(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`MINUTES: invalid date string '${e}'`);return t.getMinutes()}static seconds(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`SECONDS: invalid date string '${e}'`);return t.getSeconds()+t.getMilliseconds()/1e3}static timezone(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TIMEZONE: invalid date string '${e}'`);let n;if(e.endsWith("Z"))n="PT0S";else{let i=e.match(/([+-]\d{2}):?(\d{2})$/);if(i){let s=parseInt(i[1],10),a=parseInt(i[2],10),c=s>=0?"":"-",u=Math.abs(s);a===0?n=`${c}PT${u}H`:n=`${c}PT${u}H${a}M`}else{let s=-t.getTimezoneOffset(),a=Math.floor(Math.abs(s)/60),c=Math.abs(s)%60,u=s>=0?"":"-";c===0?n=`${u}PT${a}H`:n=`${u}PT${a}H${c}M`}}return new D.Literal(n,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static tz(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TZ: invalid date string '${e}'`);if(e.endsWith("Z"))return"Z";let n=e.match(/([+-]\d{2}:\d{2})$/);if(n)return n[1];let i=e.match(/([+-])(\d{2})(\d{2})$/);return i?`${i[1]}${i[2]}:${i[3]}`:""}static now(){return new Date().toISOString()}static msToMinutes(e){return Math.round(e/(1e3*60))}static msToHours(e){return Math.round(e/(1e3*60*60)*100)/100}static msToSeconds(e){return Math.round(e/1e3)}static abs(e){return Math.abs(e)}static round(e){return Math.round(e)}static ceil(e){return Math.ceil(e)}static floor(e){return Math.floor(e)}static rand(){return Math.random()}static coalesce(e){for(let t of e)if(t!=null)return t}static if(e,t,n){return e?t:n}static xsdDateTime(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`xsd:dateTime: invalid date string '${e}'`);return new D.Literal(t.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static xsdInteger(e){let t=parseInt(e,10);if(isNaN(t))throw new Error(`xsd:integer: cannot convert '${e}' to integer`);return new D.Literal(String(t),new ge.IRI("http://www.w3.org/2001/XMLSchema#integer"))}static xsdDecimal(e){let t=parseFloat(e);if(isNaN(t))throw new Error(`xsd:decimal: cannot convert '${e}' to decimal`);return new D.Literal(String(t),new ge.IRI("http://www.w3.org/2001/XMLSchema#decimal"))}static encodeForUri(e){return encodeURIComponent(e)}static md5(e){return require("crypto").createHash("md5").update(e).digest("hex")}static sha1(e){return require("crypto").createHash("sha1").update(e).digest("hex")}static sha256(e){return require("crypto").createHash("sha256").update(e).digest("hex")}static sha384(e){return require("crypto").createHash("sha384").update(e).digest("hex")}static sha512(e){return require("crypto").createHash("sha512").update(e).digest("hex")}static sameTerm(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0||e.constructor!==t.constructor)return!1;if(e instanceof ge.IRI&&t instanceof ge.IRI)return e.value===t.value;if(e instanceof Or.BlankNode&&t instanceof Or.BlankNode)return e.id===t.id;if(e instanceof D.Literal&&t instanceof D.Literal){if(e.value!==t.value||e.language!==t.language)return!1;let n=e.datatype?.value,i=t.datatype?.value;return n===i}return!1}static iri(e){if(e===void 0)throw new Error("IRI: argument is undefined");if(e instanceof ge.IRI)return e;if(e instanceof D.Literal)return new ge.IRI(e.value);throw e instanceof Or.BlankNode?new Error("IRI: cannot convert blank node to IRI"):new Error("IRI: unsupported term type")}static uri(e){return this.iri(e)}static bnode(e){if(e===void 0){let t=`b${(0,ly.v4)().replace(/-/g,"").substring(0,12)}`;return new Or.BlankNode(t)}if(e instanceof D.Literal)return new Or.BlankNode(e.value);if(e instanceof Or.BlankNode)return e;throw new Error("BNODE: argument must be a string literal or omitted")}static strdt(e,t){if(e===void 0)throw new Error("STRDT: lexical form is undefined");if(t===void 0)throw new Error("STRDT: datatype IRI is undefined");let n;if(e instanceof D.Literal){if(e.language)throw new Error("STRDT: lexical form must not have a language tag");n=e.value}else if(typeof e=="string")n=e;else throw new Error("STRDT: lexical form must be a string literal");let i;if(t instanceof ge.IRI)i=t;else if(t instanceof D.Literal)i=new ge.IRI(t.value);else throw new Error("STRDT: datatype must be an IRI");return new D.Literal(n,i)}static strlang(e,t){if(e===void 0)throw new Error("STRLANG: lexical form is undefined");if(t===void 0)throw new Error("STRLANG: language tag is undefined");let n;if(e instanceof D.Literal){if(e.language)throw new Error("STRLANG: lexical form must not already have a language tag");n=e.value}else if(typeof e=="string")n=e;else throw new Error("STRLANG: lexical form must be a string literal");let i;if(t instanceof D.Literal)i=t.value;else if(typeof t=="string")i=t;else throw new Error("STRLANG: language tag must be a string literal");if(i==="")throw new Error("STRLANG: language tag cannot be empty");return new D.Literal(n,void 0,i)}static strlangdir(e,t,n){if(e===void 0)throw new Error("STRLANGDIR: lexical form is undefined");if(t===void 0)throw new Error("STRLANGDIR: language tag is undefined");if(n===void 0)throw new Error("STRLANGDIR: direction is undefined");let i;if(e instanceof D.Literal){if(e.language)throw new Error("STRLANGDIR: lexical form must not already have a language tag");i=e.value}else if(typeof e=="string")i=e;else throw new Error("STRLANGDIR: lexical form must be a string literal");let s;if(t instanceof D.Literal)s=t.value;else if(typeof t=="string")s=t;else throw new Error("STRLANGDIR: language tag must be a string literal");if(s==="")throw new Error("STRLANGDIR: language tag cannot be empty");let a;if(n instanceof D.Literal)a=n.value.toLowerCase();else throw new Error("STRLANGDIR: direction must be a string literal");if(a!=="ltr"&&a!=="rtl")throw new Error(`STRLANGDIR: invalid direction '${a}'. Must be 'ltr' or 'rtl'`);return new D.Literal(i,void 0,s,a)}static uuid(){let e=(0,ly.v4)();return new ge.IRI(`urn:uuid:${e}`)}static struuid(){let e=(0,ly.v4)();return new D.Literal(e)}static parseDayTimeDuration(e){if(!e)throw new Error("parseDayTimeDuration: duration string is empty");let t=!1,n=e.trim();if(n.startsWith("-")&&(t=!0,n=n.substring(1)),!n.startsWith("P"))throw new Error(`parseDayTimeDuration: invalid format, must start with 'P': '${e}'`);n=n.substring(1);let i=0,s=n.indexOf("T"),a="",c="";if(s===-1?a=n:(a=n.substring(0,s),c=n.substring(s+1)),a){let u=a.match(/^(\d+(?:\.\d+)?)D$/);if(u){let l=parseFloat(u[1]);i+=l*24*60*60*1e3}else if(a!=="")throw new Error(`parseDayTimeDuration: invalid day component: '${a}' in '${e}'`)}if(c){let u=c,l=u.match(/^(\d+(?:\.\d+)?)H/);if(l){let d=parseFloat(l[1]);i+=d*60*60*1e3,u=u.substring(l[0].length)}let f=u.match(/^(\d+(?:\.\d+)?)M/);if(f){let d=parseFloat(f[1]);i+=d*60*1e3,u=u.substring(f[0].length)}let h=u.match(/^(\d+(?:\.\d+)?)S$/);if(h){let d=parseFloat(h[1]);i+=d*1e3,u=u.substring(h[0].length)}if(u!=="")throw new Error(`parseDayTimeDuration: invalid time component: '${u}' in '${e}'`)}return t?-i:i}static formatDayTimeDuration(e){let t=e<0,n=Math.abs(e),i=Math.floor(n/(1440*60*1e3));n=n%(1440*60*1e3);let s=Math.floor(n/(3600*1e3));n=n%(3600*1e3);let a=Math.floor(n/(60*1e3));n=n%(60*1e3);let c=n/1e3,u=t?"-P":"P";return i>0&&(u+=`${i}D`),(s>0||a>0||c>0||i===0)&&(u+="T",s>0&&(u+=`${s}H`),a>0&&(u+=`${a}M`),(c>0||s===0&&a===0)&&(Number.isInteger(c)?u+=`${c}S`:u+=`${parseFloat(c.toFixed(3))}S`)),u}static xsdDayTimeDuration(e){return this.parseDayTimeDuration(e),new D.Literal(e,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static compareDurations(e,t,n){let i=e instanceof D.Literal?e.value:e,s=t instanceof D.Literal?t.value:t,a=this.parseDayTimeDuration(i),c=this.parseDayTimeDuration(s);switch(n){case"=":return a===c;case"!=":return a!==c;case"<":return a<c;case">":return a>c;case"<=":return a<=c;case">=":return a>=c;default:throw new Error(`compareDurations: unknown operator: ${n}`)}}static isDayTimeDuration(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static isDate(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#date":!1}static dateDiff(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n),a=this.parseXSDDate(i);if(s===null)throw new Error(`dateDiff: invalid first date: '${n}'`);if(a===null)throw new Error(`dateDiff: invalid second date: '${i}'`);let c=s.getTime()-a.getTime(),u=Math.round(c/(1440*60*1e3)),l=this.formatDateDuration(u);return new D.Literal(l,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static parseXSDDate(e){let t=/^(-?\d{4})-(\d{2})-(\d{2})(Z|[+-]\d{2}:\d{2})?$/,n=e.match(t);if(!n){let l=new Date(e);return isNaN(l.getTime())?null:new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),l.getUTCDate()))}let i=parseInt(n[1],10),s=parseInt(n[2],10)-1,a=parseInt(n[3],10),c=n[4],u=new Date(Date.UTC(i,s,a));if(c&&c!=="Z"){let l=c.match(/([+-])(\d{2}):(\d{2})/);if(l){let f=l[1]==="+"?1:-1,h=parseInt(l[2],10),d=parseInt(l[3],10),p=f*(h*60+d)*60*1e3;u=new Date(u.getTime()-p)}}return u}static formatDateDuration(e){if(e===0)return"P0D";let t=e<0,n=Math.abs(e);return t?`-P${n}D`:`P${n}D`}static dateTimeDiff(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n),a=new Date(i);if(isNaN(s.getTime()))throw new Error(`dateTimeDiff: invalid first dateTime: '${n}'`);if(isNaN(a.getTime()))throw new Error(`dateTimeDiff: invalid second dateTime: '${i}'`);let c=s.getTime()-a.getTime(),u=this.formatDayTimeDuration(c);return new D.Literal(u,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static dateTimeAdd(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeAdd: invalid dateTime: '${n}'`);let a=this.parseDayTimeDuration(i),c=s.getTime()+a,u=new Date(c);return new D.Literal(u.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtract(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtract: invalid dateTime: '${n}'`);let a=this.parseDayTimeDuration(i),c=s.getTime()-a,u=new Date(c);return new D.Literal(u.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateAdd(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n);if(s===null)throw new Error(`dateAdd: invalid date: '${n}'`);let a=this.parseDayTimeDuration(i),c=s.getTime()+a,u=new Date(c),l=u.getUTCFullYear(),f=String(u.getUTCMonth()+1).padStart(2,"0"),h=String(u.getUTCDate()).padStart(2,"0"),d=`${l}-${f}-${h}`;return new D.Literal(d,new ge.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateSubtract(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n);if(s===null)throw new Error(`dateSubtract: invalid date: '${n}'`);let a=this.parseDayTimeDuration(i),c=s.getTime()-a,u=new Date(c),l=u.getUTCFullYear(),f=String(u.getUTCMonth()+1).padStart(2,"0"),h=String(u.getUTCDate()).padStart(2,"0"),d=`${l}-${f}-${h}`;return new D.Literal(d,new ge.IRI("http://www.w3.org/2001/XMLSchema#date"))}static parseYearMonthDuration(e){let t=/^(-)?P(?:(\d+)Y)?(?:(\d+)M)?$/,n=e.match(t);if(!n)throw new Error(`parseYearMonthDuration: invalid format: '${e}'`);let i=n[1]==="-",s=parseInt(n[2]||"0",10),a=parseInt(n[3]||"0",10);if(!n[2]&&!n[3])throw new Error(`parseYearMonthDuration: invalid format (no duration components): '${e}'`);let c=s*12+a;return i?-c:c}static isYearMonthDuration(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#yearMonthDuration":!1}static dateTimeAddYearMonth(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeAddYearMonth: invalid dateTime: '${n}'`);let a=this.parseYearMonthDuration(i),c=s.getUTCDate();return s.setUTCMonth(s.getUTCMonth()+a),s.getUTCDate()!==c&&s.setUTCDate(0),new D.Literal(s.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtractYearMonth(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtractYearMonth: invalid dateTime: '${n}'`);let a=this.parseYearMonthDuration(i),c=s.getUTCDate();return s.setUTCMonth(s.getUTCMonth()-a),s.getUTCDate()!==c&&s.setUTCDate(0),new D.Literal(s.toISOString(),new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateAddYearMonth(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n);if(s===null)throw new Error(`dateAddYearMonth: invalid date: '${n}'`);let a=this.parseYearMonthDuration(i),c=s.getUTCDate();s.setUTCMonth(s.getUTCMonth()+a),s.getUTCDate()!==c&&s.setUTCDate(0);let u=s.getUTCFullYear(),l=String(s.getUTCMonth()+1).padStart(2,"0"),f=String(s.getUTCDate()).padStart(2,"0"),h=`${u}-${l}-${f}`;return new D.Literal(h,new ge.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateSubtractYearMonth(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDDate(n);if(s===null)throw new Error(`dateSubtractYearMonth: invalid date: '${n}'`);let a=this.parseYearMonthDuration(i),c=s.getUTCDate();s.setUTCMonth(s.getUTCMonth()-a),s.getUTCDate()!==c&&s.setUTCDate(0);let u=s.getUTCFullYear(),l=String(s.getUTCMonth()+1).padStart(2,"0"),f=String(s.getUTCDate()).padStart(2,"0"),h=`${u}-${l}-${f}`;return new D.Literal(h,new ge.IRI("http://www.w3.org/2001/XMLSchema#date"))}static durationAdd(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseDayTimeDuration(n),a=this.parseDayTimeDuration(i),c=this.formatDayTimeDuration(s+a);return new D.Literal(c,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationSubtract(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseDayTimeDuration(n),a=this.parseDayTimeDuration(i),c=this.formatDayTimeDuration(s-a);return new D.Literal(c,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationMultiply(e,t){let n=e instanceof D.Literal?e.value:e,i=this.parseDayTimeDuration(n),s=this.formatDayTimeDuration(i*t);return new D.Literal(s,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationDivide(e,t){if(t===0)throw new Error("durationDivide: division by zero");let n=e instanceof D.Literal?e.value:e,i=this.parseDayTimeDuration(n),s=this.formatDayTimeDuration(i/t);return new D.Literal(s,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static formatYearMonthDuration(e){let t=e<0,n=Math.abs(e),i=Math.floor(n/12),s=n%12,a=t?"-P":"P";return i>0&&(a+=`${i}Y`),(s>0||i===0)&&(a+=`${s}M`),a}static yearMonthDurationAdd(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseYearMonthDuration(n),a=this.parseYearMonthDuration(i),c=this.formatYearMonthDuration(s+a);return new D.Literal(c,new ge.IRI("http://www.w3.org/2001/XMLSchema#yearMonthDuration"))}static yearMonthDurationSubtract(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseYearMonthDuration(n),a=this.parseYearMonthDuration(i),c=this.formatYearMonthDuration(s-a);return new D.Literal(c,new ge.IRI("http://www.w3.org/2001/XMLSchema#yearMonthDuration"))}static parseYearMonthDurationComponents(e){let t=/^(-)?P(?:(\d+)Y)?(?:(\d+)M)?$/,n=e.match(t);if(!n)throw new Error(`parseYearMonthDurationComponents: invalid format: '${e}'`);let i=n[1]==="-",s=parseInt(n[2]||"0",10),a=parseInt(n[3]||"0",10);if(!n[2]&&!n[3])throw new Error(`parseYearMonthDurationComponents: invalid format (no duration components): '${e}'`);return{years:s,months:a,negative:i}}static durationYears(e){let t=e instanceof D.Literal?e.value:e,n=this.parseYearMonthDurationComponents(t);return n.negative?-n.years:n.years}static durationMonths(e){let t=e instanceof D.Literal?e.value:e,n=this.parseYearMonthDurationComponents(t);return n.negative?-n.months:n.months}static durationToDays(e){let t=e instanceof D.Literal?e.value:e;return this.parseDayTimeDuration(t)/(1440*60*1e3)}static durationToHours(e){let t=e instanceof D.Literal?e.value:e;return this.parseDayTimeDuration(t)/(3600*1e3)}static durationToMinutes(e){let t=e instanceof D.Literal?e.value:e;return this.parseDayTimeDuration(t)/(60*1e3)}static durationToSeconds(e){let t=e instanceof D.Literal?e.value:e;return this.parseDayTimeDuration(t)/1e3}static parseDurationComponents(e){if(!e)throw new Error("parseDurationComponents: duration string is empty");let t=!1,n=e.trim();if(n.startsWith("-")&&(t=!0,n=n.substring(1)),!n.startsWith("P"))throw new Error(`parseDurationComponents: invalid format, must start with 'P': '${e}'`);n=n.substring(1);let i=0,s=0,a=0,c=0,u=n.indexOf("T"),l="",f="";if(u===-1?l=n:(l=n.substring(0,u),f=n.substring(u+1)),l){let h=l.match(/^(\d+(?:\.\d+)?)D$/);if(h)i=parseFloat(h[1]);else if(l!=="")throw new Error(`parseDurationComponents: invalid day component: '${l}' in '${e}'`)}if(f){let h=f,d=h.match(/^(\d+(?:\.\d+)?)H/);d&&(s=parseFloat(d[1]),h=h.substring(d[0].length));let p=h.match(/^(\d+(?:\.\d+)?)M/);p&&(a=parseFloat(p[1]),h=h.substring(p[0].length));let v=h.match(/^(\d+(?:\.\d+)?)S$/);if(v&&(c=parseFloat(v[1]),h=h.substring(v[0].length)),h!=="")throw new Error(`parseDurationComponents: invalid time component: '${h}' in '${e}'`)}return{negative:t,days:i,hours:s,minutes:a,seconds:c}}static durationDays(e){let t=e instanceof D.Literal?e.value:e,n=this.parseDurationComponents(t),i=Math.floor(n.days);return n.negative?-i:i}static durationHours(e){let t=e instanceof D.Literal?e.value:e,n=this.parseDurationComponents(t),i=Math.floor(n.hours);return n.negative?-i:i}static durationMinutes(e){let t=e instanceof D.Literal?e.value:e,n=this.parseDurationComponents(t),i=Math.floor(n.minutes);return n.negative?-i:i}static durationSeconds(e){let t=e instanceof D.Literal?e.value:e,n=this.parseDurationComponents(t);return n.negative?-n.seconds:n.seconds}static adjust(e,t){let n=e instanceof D.Literal?e.value:e,i=new Date(n);if(isNaN(i.getTime()))throw new Error(`ADJUST: invalid dateTime: '${n}'`);if(t==null){let Ce=i.getUTCFullYear(),Ve=String(i.getUTCMonth()+1).padStart(2,"0"),Ue=String(i.getUTCDate()).padStart(2,"0"),G=String(i.getUTCHours()).padStart(2,"0"),se=String(i.getUTCMinutes()).padStart(2,"0"),Te=String(i.getUTCSeconds()).padStart(2,"0"),lt=i.getUTCMilliseconds(),rt=`${Ce}-${Ve}-${Ue}T${G}:${se}:${Te}`;return lt>0&&(rt+=`.${String(lt).padStart(3,"0")}`),new D.Literal(rt,new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}let s=t instanceof D.Literal?t.value:t,a=this.parseDayTimeDuration(s),c=840*60*1e3;if(Math.abs(a)>c)throw new Error(`ADJUST: timezone offset out of range: '${s}'`);let u=i.getTime(),l=new Date(u+a),f=l.getUTCFullYear(),h=String(l.getUTCMonth()+1).padStart(2,"0"),d=String(l.getUTCDate()).padStart(2,"0"),p=String(l.getUTCHours()).padStart(2,"0"),v=String(l.getUTCMinutes()).padStart(2,"0"),b=String(l.getUTCSeconds()).padStart(2,"0"),E=l.getUTCMilliseconds(),C=a>=0?"+":"-",I=Math.floor(Math.abs(a)/(3600*1e3)),N=Math.floor(Math.abs(a)%(3600*1e3)/(60*1e3)),B=`${C}${String(I).padStart(2,"0")}:${String(N).padStart(2,"0")}`,W=`${f}-${h}-${d}T${p}:${v}:${b}`;return E>0&&(W+=`.${String(E).padStart(3,"0")}`),W+=B,new D.Literal(W,new ge.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static normalize(e,t){if(e===void 0)throw new Error("NORMALIZE: string argument is undefined");let n;if(e instanceof D.Literal)n=e.value;else if(e instanceof ge.IRI)n=e.value;else if(e instanceof Or.BlankNode)n=e.id;else if(typeof e=="string")n=e;else throw new Error("NORMALIZE: first argument must be a string or literal");let i="NFC";if(t!==void 0)if(t instanceof D.Literal)i=t.value.toUpperCase();else if(typeof t=="string")i=t.toUpperCase();else if(t instanceof ge.IRI)i=t.value.toUpperCase();else throw new Error("NORMALIZE: second argument must be a string literal");if(!this.VALID_NORMALIZATION_FORMS.includes(i))throw new Error(`NORMALIZE: invalid normalization form '${i}'. Valid forms are: NFC, NFD, NFKC, NFKD`);let s=n.normalize(i);return new D.Literal(s,new ge.IRI("http://www.w3.org/2001/XMLSchema#string"))}static fold(e){if(e===void 0)throw new Error("FOLD: string argument is undefined");let t;if(e instanceof D.Literal)t=e.value;else if(e instanceof ge.IRI)t=e.value;else if(e instanceof Or.BlankNode)t=e.id;else if(typeof e=="string")t=e;else throw new Error("FOLD: argument must be a string or literal");let n=this.unicodeCaseFold(t);return new D.Literal(n,new ge.IRI("http://www.w3.org/2001/XMLSchema#string"))}static unicodeCaseFold(e){let t="";for(let n of e){let i=this.CASE_FOLDING_MAP.get(n);i!==void 0?t+=i:t+=n.toLowerCase()}return t}static isTime(e){return e instanceof D.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#time":!1}static timeDiff(e,t){let n=e instanceof D.Literal?e.value:e,i=t instanceof D.Literal?t.value:t,s=this.parseXSDTime(n),a=this.parseXSDTime(i);if(s===null)throw new Error(`timeDiff: invalid first time: '${n}'`);if(a===null)throw new Error(`timeDiff: invalid second time: '${i}'`);let c=s-a,u=this.formatDayTimeDuration(c);return new D.Literal(u,new ge.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static parseXSDTime(e){let t=/^(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$/,n=e.match(t);if(!n)return null;let i=parseInt(n[1],10),s=parseInt(n[2],10),a=parseInt(n[3],10),c=n[4],u=n[5];if(i<0||i>24||s<0||s>59||a<0||a>59||i===24&&(s!==0||a!==0))return null;let l=0;if(c){let h=c.padEnd(3,"0").slice(0,3);l=parseInt(h,10)}let f=i*60*60*1e3+s*60*1e3+a*1e3+l;if(i===24&&(f=1440*60*1e3),u&&u!=="Z"){let h=u.match(/([+-])(\d{2}):(\d{2})/);if(h){let d=h[1]==="+"?1:-1,p=parseInt(h[2],10),v=parseInt(h[3],10),b=d*(p*60+v)*60*1e3;f-=b}}return f}static triple(e,t,n){if(e===void 0)throw new Error("TRIPLE: subject is undefined");if(t===void 0)throw new Error("TRIPLE: predicate is undefined");if(n===void 0)throw new Error("TRIPLE: object is undefined");if(e instanceof D.Literal)throw new Error("TRIPLE: subject must be IRI, BlankNode, or QuotedTriple, got Literal");if(!(t instanceof ge.IRI)){let c=t instanceof D.Literal?"Literal":t instanceof Or.BlankNode?"BlankNode":t instanceof fo.QuotedTriple?"QuotedTriple":typeof t;throw new Error(`TRIPLE: predicate must be IRI, got ${c}`)}let i=e,s=t,a=n;return new fo.QuotedTriple(i,s,a)}static subject(e){if(e===void 0)throw new Error("SUBJECT: argument is undefined");if(!(e instanceof fo.QuotedTriple)){let t=e instanceof ge.IRI?"IRI":e instanceof D.Literal?"Literal":e instanceof Or.BlankNode?"BlankNode":typeof e;throw new Error(`SUBJECT: argument must be QuotedTriple, got ${t}`)}return e.subject}static predicate(e){if(e===void 0)throw new Error("PREDICATE: argument is undefined");if(!(e instanceof fo.QuotedTriple)){let t=e instanceof ge.IRI?"IRI":e instanceof D.Literal?"Literal":e instanceof Or.BlankNode?"BlankNode":typeof e;throw new Error(`PREDICATE: argument must be QuotedTriple, got ${t}`)}return e.predicate}static object(e){if(e===void 0)throw new Error("OBJECT: argument is undefined");if(!(e instanceof fo.QuotedTriple)){let t=e instanceof ge.IRI?"IRI":e instanceof D.Literal?"Literal":e instanceof Or.BlankNode?"BlankNode":typeof e;throw new Error(`OBJECT: argument must be QuotedTriple, got ${t}`)}return e.object}};sh.BuiltInFunctions=Qc;Qc.VALID_NORMALIZATION_FORMS=["NFC","NFD","NFKC","NFKD"];Qc.CASE_FOLDING_MAP=new Map([["\xDF","ss"],["\u1E9E","ss"],["\u03A3","\u03C3"],["\u03C2","\u03C3"],["\u0130","i\u0307"],["I","i"],["\u0587","\u0565\u0582"],["\uFB00","ff"],["\uFB01","fi"],["\uFB02","fl"],["\uFB03","ffi"],["\uFB04","ffl"],["\uFB05","st"],["\uFB06","st"],["\u0390","\u03B9\u0308\u0301"],["\u03B0","\u03C5\u0308\u0301"],["\u017F","s"],["\u1E9B","\u1E61"],["\u212A","k"],["\u212B","\xE5"]])});var Kb=_(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.functionHandlers=void 0;var M=ah();L.functionHandlers=new Map;L.functionHandlers.set("str",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.str(t)});L.functionHandlers.set("lang",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.lang(t)});L.functionHandlers.set("langmatches",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.langMatches(t,n)});L.functionHandlers.set("contains",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.contains(t,n)});L.functionHandlers.set("strstarts",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.strStarts(t,n)});L.functionHandlers.set("strends",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.strEnds(t,n)});L.functionHandlers.set("strlen",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.strlen(t)});L.functionHandlers.set("ucase",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.ucase(t)});L.functionHandlers.set("lcase",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.lcase(t)});L.functionHandlers.set("substr",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=Number(e.evaluateExpression(r[1],e.solution));if(r[2]){let i=Number(e.evaluateExpression(r[2],e.solution));return M.BuiltInFunctions.substr(t,n,i)}return M.BuiltInFunctions.substr(t,n)});L.functionHandlers.set("strbefore",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.strBefore(t,n)});L.functionHandlers.set("strafter",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.strAfter(t,n)});L.functionHandlers.set("concat",(r,e)=>{let t=r.map(n=>e.getStringValue(e.evaluateExpression(n,e.solution)));return M.BuiltInFunctions.concat(...t)});L.functionHandlers.set("replace",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution)),i=e.getStringValue(e.evaluateExpression(r[2],e.solution)),s=r[3]?e.getStringValue(e.evaluateExpression(r[3],e.solution)):void 0;return M.BuiltInFunctions.replace(t,n,i,s)});L.functionHandlers.set("regex",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution)),i=r[2]?e.getStringValue(e.evaluateExpression(r[2],e.solution)):void 0;return M.BuiltInFunctions.regex(t,n,i)});L.functionHandlers.set("encode_for_uri",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.encodeForUri(t)});L.functionHandlers.set("datatype",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.datatype(t).value});L.functionHandlers.set("bound",(r,e)=>{let t=r[0];if(t.type==="variable"&&t.name){let n=e.solution.get(t.name);return M.BuiltInFunctions.bound(n)}return!0});var Ub=o((r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isIRI(t)},"isIriHandler");L.functionHandlers.set("isiri",Ub);L.functionHandlers.set("isuri",Ub);L.functionHandlers.set("isblank",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isBlank(t)});L.functionHandlers.set("isliteral",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isLiteral(t)});L.functionHandlers.set("isnumeric",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isNumeric(t)});L.functionHandlers.set("haslangdir",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.hasLangdir(t)});L.functionHandlers.set("istriple",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.isTriple(t)});L.functionHandlers.set("sameterm",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution),n=e.getTermFromExpression(r[1],e.solution);return M.BuiltInFunctions.sameTerm(t,n)});L.functionHandlers.set("abs",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.abs(t)});L.functionHandlers.set("round",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.round(t)});L.functionHandlers.set("ceil",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.ceil(t)});L.functionHandlers.set("floor",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.floor(t)});L.functionHandlers.set("rand",()=>M.BuiltInFunctions.rand());L.functionHandlers.set("parsedate",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.parseDate(t)});L.functionHandlers.set("datebefore",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.dateBefore(t,n)});L.functionHandlers.set("dateafter",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.dateAfter(t,n)});L.functionHandlers.set("dateinrange",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution)),i=e.getStringValue(e.evaluateExpression(r[2],e.solution));return M.BuiltInFunctions.dateInRange(t,n,i)});L.functionHandlers.set("datediffminutes",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.dateDiffMinutes(t,n)});L.functionHandlers.set("datediffhours",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution)),n=e.getStringValue(e.evaluateExpression(r[1],e.solution));return M.BuiltInFunctions.dateDiffHours(t,n)});var ho=o((r,e,t)=>(n,i)=>{let s=i.evaluateExpression(n[0],i.solution);return e&&i.isYearMonthDurationValue(s)?e(s):t&&i.isDayTimeDurationValue(s)?t(s):r(i.getStringValue(s))},"createDateTimeAccessor"),qb=ho(M.BuiltInFunctions.year,M.BuiltInFunctions.durationYears,null);L.functionHandlers.set("year",qb);L.functionHandlers.set("years",qb);var Gb=ho(M.BuiltInFunctions.month,M.BuiltInFunctions.durationMonths,null);L.functionHandlers.set("month",Gb);L.functionHandlers.set("months",Gb);var Wb=ho(M.BuiltInFunctions.day,null,M.BuiltInFunctions.durationDays);L.functionHandlers.set("day",Wb);L.functionHandlers.set("days",Wb);L.functionHandlers.set("hours",ho(M.BuiltInFunctions.hours,null,M.BuiltInFunctions.durationHours));L.functionHandlers.set("minutes",ho(M.BuiltInFunctions.minutes,null,M.BuiltInFunctions.durationMinutes));L.functionHandlers.set("seconds",ho(M.BuiltInFunctions.seconds,null,M.BuiltInFunctions.durationSeconds));L.functionHandlers.set("timezone",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.timezone(t)});L.functionHandlers.set("tz",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.tz(t)});L.functionHandlers.set("adjust",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution),n=r.length>1?e.evaluateExpression(r[1],e.solution):void 0;return M.BuiltInFunctions.adjust(t,n)});L.functionHandlers.set("now",()=>M.BuiltInFunctions.now());var Hb=o((r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.xsdDateTime(e.getStringValue(t))},"dateTimeHandler");L.functionHandlers.set("datetime",Hb);L.functionHandlers.set("xsd:datetime",Hb);var zb=o((r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.xsdInteger(e.getStringValue(t))},"integerHandler");L.functionHandlers.set("integer",zb);L.functionHandlers.set("xsd:integer",zb);var Yb=o((r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.xsdDecimal(e.getStringValue(t))},"decimalHandler");L.functionHandlers.set("decimal",Yb);L.functionHandlers.set("xsd:decimal",Yb);var Qb=o((r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.xsdDayTimeDuration(e.getStringValue(t))},"dayTimeDurationHandler");L.functionHandlers.set("daytimeduration",Qb);L.functionHandlers.set("xsd:daytimeduration",Qb);L.functionHandlers.set("durationtodays",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationToDays(t)});L.functionHandlers.set("durationtohours",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationToHours(t)});L.functionHandlers.set("durationtominutes",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationToMinutes(t)});L.functionHandlers.set("durationtoseconds",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationToSeconds(t)});L.functionHandlers.set("durationdays",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationDays(t)});L.functionHandlers.set("durationhours",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationHours(t)});L.functionHandlers.set("durationminutes",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationMinutes(t)});L.functionHandlers.set("durationseconds",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationSeconds(t)});L.functionHandlers.set("durationyears",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationYears(t)});L.functionHandlers.set("durationmonths",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution);return M.BuiltInFunctions.durationMonths(t)});L.functionHandlers.set("datetimediff",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution),n=e.evaluateExpression(r[1],e.solution);return M.BuiltInFunctions.dateTimeDiff(t,n)});L.functionHandlers.set("datetimeadd",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution),n=e.evaluateExpression(r[1],e.solution);return M.BuiltInFunctions.dateTimeAdd(t,n)});L.functionHandlers.set("datetimesubtract",(r,e)=>{let t=e.evaluateExpression(r[0],e.solution),n=e.evaluateExpression(r[1],e.solution);return M.BuiltInFunctions.dateTimeSubtract(t,n)});L.functionHandlers.set("mstominutes",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.msToMinutes(t)});L.functionHandlers.set("mstohours",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.msToHours(t)});L.functionHandlers.set("mstoseconds",(r,e)=>{let t=Number(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.msToSeconds(t)});L.functionHandlers.set("md5",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.md5(t)});L.functionHandlers.set("sha1",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.sha1(t)});L.functionHandlers.set("sha256",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.sha256(t)});L.functionHandlers.set("sha384",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.sha384(t)});L.functionHandlers.set("sha512",(r,e)=>{let t=e.getStringValue(e.evaluateExpression(r[0],e.solution));return M.BuiltInFunctions.sha512(t)});L.functionHandlers.set("subject",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.subject(t)});L.functionHandlers.set("predicate",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.predicate(t)});L.functionHandlers.set("object",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution);return M.BuiltInFunctions.object(t)});L.functionHandlers.set("triple",(r,e)=>{let t=e.getTermFromExpression(r[0],e.solution),n=e.getTermFromExpression(r[1],e.solution),i=e.getTermFromExpression(r[2],e.solution);return M.BuiltInFunctions.triple(t,n,i)})});var oh=_(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.FilterExecutor=po.FilterExecutorError=void 0;var ut=ah(),qN=Kb(),fa=ht(),er=class extends Error{static{o(this,"FilterExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="FilterExecutorError"}};po.FilterExecutorError=er;var fy=class{static{o(this,"FilterExecutor")}constructor(){this.existsEvaluator=null,this.tripleStore=null,this.uuidCache=new Map}setExistsEvaluator(e){this.existsEvaluator=e}setTripleStore(e){this.tripleStore=e,this.uuidCache.clear()}async*execute(e,t){let n=this.expressionContainsExists(e.expression);for await(let i of t)try{let s;n?s=await this.evaluateExpressionAsync(e.expression,i):s=this.evaluateExpression(e.expression,i),s===!0&&(yield i)}catch{continue}}expressionContainsExists(e){if(e.type==="exists")return!0;if(e.type==="logical")return e.operands.some(t=>this.expressionContainsExists(t));if(e.type==="comparison")return this.expressionContainsExists(e.left)||this.expressionContainsExists(e.right);if(e.type==="in"){let t=e;return this.expressionContainsExists(t.expression)||t.list.some(n=>this.expressionContainsExists(n))}return!1}async executeAll(e,t){let n=[];async function*i(){for(let s of t)yield s}o(i,"generator");for await(let s of this.execute(e,i()))n.push(s);return n}evaluateExpression(e,t){let n=e;if(n.termType)switch(n.termType){case"Variable":return t.get(n.value);case"Literal":return n.value;case"NamedNode":return n.value;default:throw new er(`Unsupported termType: ${n.termType}`)}switch(e.type){case"comparison":return this.evaluateComparison(e,t);case"logical":return this.evaluateLogical(e,t);case"arithmetic":return this.evaluateArithmetic(e,t);case"function":case"functionCall":return this.evaluateFunction(e,t);case"variable":return t.get(e.name);case"literal":return e.value;case"in":return this.evaluateIn(e,t);case"exists":throw new er("EXISTS expressions require async evaluation. Use evaluateExpressionAsync instead.");default:throw new er(`Unsupported expression type: ${e.type}, expr.termType=${n.termType}`)}}async evaluateExpressionAsync(e,t){return e.type==="exists"?this.evaluateExists(e,t):e.type==="logical"?this.evaluateLogicalAsync(e,t):this.evaluateExpression(e,t)}async evaluateExists(e,t){if(!this.existsEvaluator)throw new er("EXISTS evaluator not set. Call setExistsEvaluator before evaluating EXISTS expressions.");let n=await this.existsEvaluator(e.pattern,t);return e.negated?!n:n}async evaluateLogicalAsync(e,t){if(e.operator==="!"){let i=await this.evaluateExpressionAsync(e.operands[0],t);return ut.BuiltInFunctions.logicalNot(i)}let n=[];for(let i of e.operands){let s=await this.evaluateExpressionAsync(i,t);n.push(s)}if(e.operator==="&&")return ut.BuiltInFunctions.logicalAnd(n);if(e.operator==="||")return ut.BuiltInFunctions.logicalOr(n);throw new er(`Unknown logical operator: ${e.operator}`)}evaluateComparison(e,t){let n=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);return ut.BuiltInFunctions.compare(n,i,e.operator)}evaluateLogical(e,t){if(e.operator==="!"){let i=this.evaluateExpression(e.operands[0],t);return ut.BuiltInFunctions.logicalNot(i)}let n=e.operands.map(i=>this.evaluateExpression(i,t));if(e.operator==="&&")return ut.BuiltInFunctions.logicalAnd(n);if(e.operator==="||")return ut.BuiltInFunctions.logicalOr(n);throw new er(`Unknown logical operator: ${e.operator}`)}evaluateIn(e,t){let n=this.evaluateExpression(e.expression,t),i=e.list.some(s=>{let a=this.evaluateExpression(s,t);return ut.BuiltInFunctions.compare(n,a,"=")});return e.negated?!i:i}evaluateArithmetic(e,t){let n=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);if(e.operator==="-"&&this.isDateValue(n)&&this.isDateValue(i))return ut.BuiltInFunctions.dateDiff(n,i);if(e.operator==="-"&&this.isTimeValue(n)&&this.isTimeValue(i))return ut.BuiltInFunctions.timeDiff(n,i);if(e.operator==="-"&&this.isDateTimeValue(n)&&this.isDateTimeValue(i))return ut.BuiltInFunctions.dateTimeDiff(n,i);if(e.operator==="+"&&this.isDateValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.dateAdd(n,i);if(e.operator==="-"&&this.isDateValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.dateSubtract(n,i);if(e.operator==="+"&&this.isDateValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.dateAddYearMonth(n,i);if(e.operator==="-"&&this.isDateValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.dateSubtractYearMonth(n,i);if(e.operator==="+"&&this.isDateTimeValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.dateTimeAdd(n,i);if(e.operator==="-"&&this.isDateTimeValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.dateTimeSubtract(n,i);if(e.operator==="+"&&this.isDateTimeValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.dateTimeAddYearMonth(n,i);if(e.operator==="-"&&this.isDateTimeValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.dateTimeSubtractYearMonth(n,i);if(e.operator==="+"&&this.isDayTimeDurationValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.durationAdd(n,i);if(e.operator==="-"&&this.isDayTimeDurationValue(n)&&this.isDayTimeDurationValue(i))return ut.BuiltInFunctions.durationSubtract(n,i);if(e.operator==="*"&&this.isDayTimeDurationValue(n)&&!this.isDayTimeDurationValue(i)){let c=this.toNumericValue(i);return ut.BuiltInFunctions.durationMultiply(n,c)}if(e.operator==="*"&&!this.isDayTimeDurationValue(n)&&this.isDayTimeDurationValue(i)){let c=this.toNumericValue(n);return ut.BuiltInFunctions.durationMultiply(i,c)}if(e.operator==="/"&&this.isDayTimeDurationValue(n)&&!this.isDayTimeDurationValue(i)){let c=this.toNumericValue(i);if(c===0)throw new er("Division by zero");return ut.BuiltInFunctions.durationDivide(n,c)}if(e.operator==="+"&&this.isYearMonthDurationValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.yearMonthDurationAdd(n,i);if(e.operator==="-"&&this.isYearMonthDurationValue(n)&&this.isYearMonthDurationValue(i))return ut.BuiltInFunctions.yearMonthDurationSubtract(n,i);let s=this.toNumericValue(n),a=this.toNumericValue(i);switch(e.operator){case"+":return s+a;case"-":return s-a;case"*":return s*a;case"/":if(a===0)throw new er("Division by zero");return s/a;default:throw new er(`Unknown arithmetic operator: ${e.operator}`)}}isDayTimeDurationValue(e){return e instanceof fa.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}isYearMonthDurationValue(e){return e instanceof fa.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#yearMonthDuration":!1}toNumericValue(e){if(typeof e=="number")return e;if(e instanceof fa.Literal){let t=e.datatype?.value||"";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let i=parseFloat(e.value);if(!isNaN(i))return i}let n=parseFloat(e.value);if(!isNaN(n))return n}if(typeof e=="string"){let t=parseFloat(e);if(!isNaN(t))return t}if(e&&typeof e=="object"&&"value"in e){let t=parseFloat(String(e.value));if(!isNaN(t))return t}throw new er(`Cannot convert to number: ${e}`)}isDateTimeValue(e){if(e instanceof fa.Literal){let t=e.datatype?.value||"";return t.includes("#dateTime")||t.includes("#date")?!0:/^\d{4}-\d{2}-\d{2}(T|\s)/.test(e.value)}return typeof e=="string"?/^\d{4}-\d{2}-\d{2}(T|\s)/.test(e):!1}isDateValue(e){return e instanceof fa.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#date":!1}isTimeValue(e){return e instanceof fa.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#time":!1}evaluateFunction(e,t){let n=e,i=this.extractFunctionName(n.function),s=this.evaluateSpecialFunction(i,n.args,t);if(s!==void 0)return s.value;let a=qN.functionHandlers.get(i);if(!a)throw new er(`Unknown function: ${i}`);let c={evaluateExpression:o((u,l)=>this.evaluateExpression(u,l),"evaluateExpression"),getTermFromExpression:o((u,l)=>this.getTermFromExpression(u,l),"getTermFromExpression"),getStringValue:o(u=>this.getStringValue(u),"getStringValue"),solution:t,isYearMonthDurationValue:o(u=>this.isYearMonthDurationValue(u),"isYearMonthDurationValue"),isDayTimeDurationValue:o(u=>this.isDayTimeDurationValue(u),"isDayTimeDurationValue")};return a(n.args,c)}extractFunctionName(e){if(typeof e=="string")return e.toLowerCase();if(e&&typeof e=="object"&&"value"in e){let t=e.value;return((t.includes("#")?t.split("#").pop():t.split("/").pop())||t).toLowerCase()}throw new er(`Unknown function format: ${e}`)}evaluateSpecialFunction(e,t,n){switch(e){case"coalesce":for(let c of t)try{let u=this.evaluateExpression(c,n);if(u!=null)return{value:u}}catch{continue}return{value:void 0};case"if":if(!t||t.length!==3)throw new er("IF requires exactly 3 arguments");let i=this.evaluateExpression(t[0],n);return{value:this.toBoolean(i)?this.evaluateExpression(t[1],n):this.evaluateExpression(t[2],n)};case"byuuid":return{value:this.evaluateByUUID({args:t},n)};default:return}}getTermFromExpression(e,t){let n=e;if(n.type==="variable"&&n.name)return t.get(n.name)}getStringValue(e){return e==null?"":typeof e=="object"&&"value"in e?String(e.value):String(e)}toBoolean(e){if(typeof e=="boolean")return e;if(typeof e=="number")return!isNaN(e)&&e!==0;if(typeof e=="string")return e.length>0;if(e instanceof fa.Literal){let t=e.datatype?.value||"";if(t.includes("#boolean"))return e.value==="true"||e.value==="1";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let n=parseFloat(e.value);return!isNaN(n)&&n!==0}return e.value.length>0}return!!e}evaluateByUUID(e,t){if(!e.args||e.args.length!==1)throw new er("exo:byUUID requires exactly 1 argument (UUID string)");let n=this.evaluateExpression(e.args[0],t),i=this.getStringValue(n);if(!i)return;let s=i.toLowerCase();if(this.uuidCache.has(s))return this.uuidCache.get(s)??void 0;if(!this.tripleStore){this.uuidCache.set(s,null);return}if(this.tripleStore.findSubjectsByUUIDSync){let a=this.tripleStore.findSubjectsByUUIDSync(s);if(a.length===0){this.uuidCache.set(s,null);return}let c=a[0];return this.uuidCache.set(s,c),c}this.uuidCache.set(s,null)}cacheUUIDResult(e,t){let n=e.toLowerCase();this.uuidCache.set(n,t)}getCachedUUID(e){let t=e.toLowerCase();if(this.uuidCache.has(t))return this.uuidCache.get(t)}};po.FilterExecutor=fy});var dy=_(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});ch.OptionalExecutor=void 0;var hy=class{static{o(this,"OptionalExecutor")}async*execute(e,t){let n=[];for await(let s of e)n.push(s);let i=[];for await(let s of t)i.push(s);for(let s of n){let a=!1;for(let c of i){let u=s.merge(c);u!==null&&(yield u,a=!0)}a||(yield s)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}};ch.OptionalExecutor=hy});var my=_(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});uh.UnionExecutor=void 0;var py=class{static{o(this,"UnionExecutor")}async*execute(e,t){let n=new Set;for await(let i of e){let s=this.getSolutionKey(i);n.has(s)||(n.add(s),yield i)}for await(let i of t){let s=this.getSolutionKey(i);n.has(s)||(n.add(s),yield i)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}};uh.UnionExecutor=py});var vy=_(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});lh.ConstructExecutor=void 0;var GN=$i(),ha=Ye(),gy=ht(),yy=Rt(),WN=wc(),_y=class{static{o(this,"ConstructExecutor")}async execute(e,t){let n=[],i=new Set;for(let s of t)for(let a of e)try{let c=this.instantiateTriple(a,s),u=`${c.subject.toString()}|${c.predicate.toString()}|${c.object.toString()}`;i.has(u)||(i.add(u),n.push(c))}catch{continue}return n}instantiateTriple(e,t){if(this.isPropertyPath(e.predicate))throw new Error("Property paths are not supported in CONSTRUCT templates");let n=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.predicate,t),s=this.instantiateElement(e.object,t);return new GN.Triple(n,i,s)}isPropertyPath(e){return e.type==="path"}instantiateElement(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable: ${e.value}`);return n}if(e.type==="iri")return new ha.IRI(e.value);if(e.type==="literal")return new gy.Literal(e.value,e.datatype?new ha.IRI(e.datatype):void 0,e.language);if(e.type==="blank")return new yy.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Unknown element type: ${e.type}`)}instantiateQuotedTriple(e,t){let n=this.instantiateQuotedSubject(e.subject,t),i=this.instantiateQuotedPredicate(e.predicate,t),s=this.instantiateQuotedObject(e.object,t);return new WN.QuotedTriple(n,i,s)}instantiateQuotedSubject(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable in quoted triple subject: ${e.value}`);if(n instanceof gy.Literal)throw new Error("Literals cannot appear in quoted triple subject position");return n}if(e.type==="iri")return new ha.IRI(e.value);if(e.type==="blank")return new yy.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Invalid element type for quoted triple subject: ${e.type}`)}instantiateQuotedPredicate(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable in quoted triple predicate: ${e.value}`);if(!(n instanceof ha.IRI))throw new Error("Quoted triple predicate must be an IRI");return n}return new ha.IRI(e.value)}instantiateQuotedObject(e,t){if(e.type==="variable"){let i=t.get(e.value);if(!i)throw new Error(`Unbound variable in quoted triple object: ${e.value}`);return i}if(e.type==="iri")return new ha.IRI(e.value);if(e.type==="blank")return new yy.BlankNode(e.value);if(e.type==="literal")return new gy.Literal(e.value,e.datatype?new ha.IRI(e.datatype):void 0,e.language);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);let n=e;throw new Error(`Invalid element type for quoted triple object: ${n.type}`)}};lh.ConstructExecutor=_y});var Jb=_(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});fh.DescribeExecutor=void 0;var Xb=Ye(),Sy=class{static{o(this,"DescribeExecutor")}constructor(e){this.tripleStore=e}async execute(e,t){let n=[],i=new Set,s=new Set,a=t?.depth;for(let c of e)await this.describeResourceWithDepth(c,a,1,t?.symmetric??!0,n,i,s);return n}async describeResourceWithDepth(e,t,n,i,s,a,c){let u=e.toString();if(c.has(u)||(c.add(u),t!==void 0&&n>t))return;let l=[],f=await this.tripleStore.match(e,void 0,void 0);if(l.push(...f),i){let d=await this.tripleStore.match(void 0,void 0,e);l.push(...d)}let h=[];for(let d of l){let p=`${d.subject.toString()}|${d.predicate.toString()}|${d.object.toString()}`;a.has(p)||(a.add(p),s.push(d),(t===void 0||n<t)&&(this.isIRI(d.subject)&&d.subject.toString()!==u&&h.push(d.subject),this.isIRI(d.object)&&d.object.toString()!==u&&h.push(d.object)))}for(let d of h)await this.describeResourceWithDepth(d,t,n+1,i,s,a,c)}isIRI(e){return e?e instanceof Xb.IRI||e.termType==="NamedNode"||typeof e.value=="string"&&e.value.startsWith("http"):!1}async describeByIRI(e,t){let n=new Xb.IRI(e);return this.execute([n],t)}};fh.DescribeExecutor=Sy});var Zb=_(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});hh.MinusExecutor=void 0;var by=class{static{o(this,"MinusExecutor")}async*execute(e,t){let n=[];for await(let s of e)n.push(s);let i=[];for await(let s of t)i.push(s);for(let s of n){let a=!1;for(let c of i)if(this.areCompatible(s,c)){a=!0;break}a||(yield s)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}areCompatible(e,t){let n=e.variables(),i=new Set(t.variables()),s=n.filter(a=>i.has(a));if(s.length===0)return!1;for(let a of s){let c=e.get(a),u=t.get(a);if(c===void 0||u===void 0||c.toString()!==u.toString())return!1}return!0}};hh.MinusExecutor=by});var tw=_(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.ValuesExecutor=mo.ValuesExecutorError=void 0;var HN=Hi(),ew=Ye(),zN=ht(),dh=class extends Error{static{o(this,"ValuesExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ValuesExecutorError"}};mo.ValuesExecutorError=dh;var wy=class{static{o(this,"ValuesExecutor")}async*execute(e){if(e.bindings.length!==0)for(let t of e.bindings)yield this.createSolutionMapping(t)}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}createSolutionMapping(e){let t=new HN.SolutionMapping;for(let[n,i]of Object.entries(e)){let s=this.toRDFTerm(i);t.set(n,s)}return t}toRDFTerm(e){if(e.type==="iri")return new ew.IRI(e.value);if(e.type==="literal")return new zN.Literal(e.value,e.datatype?new ew.IRI(e.datatype):void 0,e.language,e.direction);throw new dh(`Unknown term type: ${e.type}`)}};mo.ValuesExecutor=wy});var Ey=_(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.CustomAggregateRegistry=yo.CustomAggregateError=void 0;var go=class extends Error{static{o(this,"CustomAggregateError")}constructor(e,t){super(e),this.iri=t,this.name="CustomAggregateError"}};yo.CustomAggregateError=go;var ph=class r{static{o(this,"CustomAggregateRegistry")}constructor(){this.aggregates=new Map}static getInstance(){return r.instance||(r.instance=new r),r.instance}static resetInstance(){r.instance&&r.instance.clear(),r.instance=null}register(e,t){if(!e||typeof e!="string")throw new go("Aggregate IRI must be a non-empty string");if(!t||typeof t.init!="function"||typeof t.step!="function"||typeof t.finalize!="function")throw new go("Aggregate must implement init(), step(), and finalize() methods",e);if(this.aggregates.has(e))throw new go(`Aggregate with IRI "${e}" is already registered`,e);this.aggregates.set(e,t)}unregister(e){return this.aggregates.delete(e)}get(e){return this.aggregates.get(e)}has(e){return this.aggregates.has(e)}getRegisteredIris(){return Array.from(this.aggregates.keys())}clear(){this.aggregates.clear()}get size(){return this.aggregates.size}};yo.CustomAggregateRegistry=ph;ph.instance=null});var Ty=_(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.BUILT_IN_AGGREGATES=Be.modeAggregate=Be.stddevAggregate=Be.varianceAggregate=Be.medianAggregate=Be.EXO_AGGREGATE_NS=void 0;Be.getNumericValue=mh;Be.createDecimalLiteral=zn;Be.createDoubleLiteral=KN;Be.createPercentileAggregate=da;var pa=ht(),_o=Ye(),YN=new _o.IRI("http://www.w3.org/2001/XMLSchema#decimal"),QN=new _o.IRI("http://www.w3.org/2001/XMLSchema#double");Be.EXO_AGGREGATE_NS="https://exocortex.my/ontology/agg#";function mh(r){return r==null?NaN:typeof r=="number"?r:typeof r=="string"?parseFloat(r):r instanceof pa.Literal?parseFloat(r.value):r instanceof _o.IRI?NaN:typeof r=="boolean"?r?1:0:NaN}o(mh,"getNumericValue");function zn(r){return new pa.Literal(String(r),YN)}o(zn,"createDecimalLiteral");function KN(r){return new pa.Literal(String(r),QN)}o(KN,"createDoubleLiteral");Be.medianAggregate={init(){return{values:[]}},step(r,e){let t=r,n=mh(e);isNaN(n)||t.values.push(n)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return zn(0);let n=[...t].sort((a,c)=>a-c),i=Math.floor(n.length/2),s=n.length%2!==0?n[i]:(n[i-1]+n[i])/2;return zn(s)}};Be.varianceAggregate={init(){return{values:[]}},step(r,e){let t=r,n=mh(e);isNaN(n)||t.values.push(n)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return zn(0);let n=t.reduce((s,a)=>s+a,0)/t.length,i=t.reduce((s,a)=>s+Math.pow(a-n,2),0)/t.length;return zn(i)}};Be.stddevAggregate={init(){return{values:[]}},step(r,e){Be.varianceAggregate.step(r,e)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return zn(0);let n=t.reduce((s,a)=>s+a,0)/t.length,i=t.reduce((s,a)=>s+Math.pow(a-n,2),0)/t.length;return zn(Math.sqrt(i))}};Be.modeAggregate={init(){return{counts:new Map,values:new Map}},step(r,e){if(e==null)return;let t=r,n=String(e instanceof pa.Literal||e instanceof _o.IRI?e.value:e),i=t.counts.get(n)||0;t.counts.set(n,i+1),t.values.set(n,e)},finalize(r){let e=r;if(e.counts.size===0)return new pa.Literal(" ",new _o.IRI("http://www.w3.org/2001/XMLSchema#string"));let t="",n=0;for(let[a,c]of e.counts)c>n&&(n=c,t=a);let i=e.values.get(t);if(i instanceof pa.Literal)return i;let s=parseFloat(t);return isNaN(s)?new pa.Literal(t,new _o.IRI("http://www.w3.org/2001/XMLSchema#string")):zn(s)}};function da(r){let e=Math.max(0,Math.min(100,r))/100;return{init(){return{values:[],percentile:e}},step(t,n){let i=t,s=mh(n);isNaN(s)||i.values.push(s)},finalize(t){let n=t,{values:i}=n;if(i.length===0)return zn(0);let s=[...i].sort((h,d)=>h-d),a=n.percentile*(s.length-1),c=Math.floor(a),u=Math.ceil(a);if(c===u)return zn(s[c]);let l=a-c,f=s[c]*(1-l)+s[u]*l;return zn(f)}}}o(da,"createPercentileAggregate");Be.BUILT_IN_AGGREGATES={[`${Be.EXO_AGGREGATE_NS}median`]:Be.medianAggregate,[`${Be.EXO_AGGREGATE_NS}variance`]:Be.varianceAggregate,[`${Be.EXO_AGGREGATE_NS}stddev`]:Be.stddevAggregate,[`${Be.EXO_AGGREGATE_NS}mode`]:Be.modeAggregate,[`${Be.EXO_AGGREGATE_NS}percentile25`]:da(25),[`${Be.EXO_AGGREGATE_NS}percentile50`]:da(50),[`${Be.EXO_AGGREGATE_NS}percentile75`]:da(75),[`${Be.EXO_AGGREGATE_NS}percentile90`]:da(90),[`${Be.EXO_AGGREGATE_NS}percentile95`]:da(95),[`${Be.EXO_AGGREGATE_NS}percentile99`]:da(99)}});var iw=_(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.AggregateExecutor=vo.AggregateExecutorError=void 0;var Lt=ht(),xy=Ye(),XN=oh(),JN=Ey(),ZN=Ty(),rw=new xy.IRI("http://www.w3.org/2001/XMLSchema#integer"),ma=new xy.IRI("http://www.w3.org/2001/XMLSchema#decimal"),yi=new xy.IRI("http://www.w3.org/2001/XMLSchema#string");function nw(r){return typeof r=="object"&&r.type==="custom"}o(nw,"isCustomAggregation");var Kc=class extends Error{static{o(this,"AggregateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AggregateExecutorError"}};vo.AggregateExecutorError=Kc;var Ay=class{static{o(this,"AggregateExecutor")}constructor(){this.filterExecutor=new XN.FilterExecutor}execute(e,t){let n=this.groupSolutions(t,e.variables),i=[];for(let[s,a]of n.entries()){let c=new Map;for(let f of e.variables)if(a.length>0){let h=a[0].get(f);h&&c.set(f,h)}for(let f of e.aggregates){let h=this.computeAggregate(f.expression,a);c.set(f.variable,h)}let{SolutionMapping:u}=Hi(),l=new u;for(let[f,h]of c.entries())l.set(f,h);i.push(l)}if(i.length===0&&e.aggregates.length>0){let s=this.createEmptyAggregateResult(e);s&&i.push(s)}return i}groupSolutions(e,t){let n=new Map;if(t.length===0)return n.set("",e),n;for(let i of e){let s=this.computeGroupKey(i,t),a=n.get(s);a?a.push(i):n.set(s,[i])}return n}computeGroupKey(e,t){return t.map(n=>{let i=e.get(n);return i?this.termToString(i):""}).join("|")}termToString(e){if(e&&typeof e=="object"){if("value"in e)return String(e.value);if("id"in e)return String(e.id)}return String(e)}computeAggregate(e,t){if(nw(e.aggregation))return this.computeCustomAggregate(e,t);let n=this.extractValues(e,t),i=e.aggregation;switch(i){case"count":{let s=this.computeCount(n,e.distinct);return new Lt.Literal(String(s),rw)}case"sum":{let s=this.computeSum(n);return new Lt.Literal(String(s),ma)}case"avg":{let s=this.computeAvg(n);return new Lt.Literal(String(s),ma)}case"min":{let s=this.computeMin(n);return s===void 0?new Lt.Literal("",yi):typeof s=="number"?new Lt.Literal(String(s),ma):new Lt.Literal(String(s),yi)}case"max":{let s=this.computeMax(n);return s===void 0?new Lt.Literal("",yi):typeof s=="number"?new Lt.Literal(String(s),ma):new Lt.Literal(String(s),yi)}case"group_concat":{let s=this.computeGroupConcat(n,e.separator||" ",e.distinct);return new Lt.Literal(s||" ",yi)}case"sample":{let s=this.computeSample(n,e.distinct);return s===void 0?new Lt.Literal(" ",yi):typeof s=="number"?new Lt.Literal(String(s),ma):new Lt.Literal(String(s),yi)}default:{let s=i;throw new Kc(`Unknown aggregation function: ${s}`)}}}computeCustomAggregate(e,t){let i=e.aggregation.iri,a=JN.CustomAggregateRegistry.getInstance().get(i);if(a||(a=ZN.BUILT_IN_AGGREGATES[i]),!a)throw new Kc(`Unknown custom aggregate function: ${i}. Register it with CustomAggregateRegistry.getInstance().register() or use a built-in aggregate.`);let c=a.init();for(let u of t){let l=null;if(e.expression){let f=this.evaluateExpression(e.expression,u);f!==void 0&&(l=f)}else l=1;a.step(c,l)}return a.finalize(c)}extractValues(e,t){if(!e.expression)return t.map(()=>1);let n=[];for(let i of t){let s=this.evaluateExpression(e.expression,i);s!=null&&n.push(s)}return n}evaluateExpression(e,t){if(e.type==="variable"){let n=t.get(e.name);return n==null?void 0:typeof n=="number"||typeof n=="string"||typeof n=="boolean"?n:typeof n=="object"&&"value"in n?n.value:n}if(e.type==="literal")return e.value;try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}computeCount(e,t){return t?new Set(e.map(n=>String(n))).size:e.length}computeSum(e){return e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n)).reduce((n,i)=>n+i,0)}computeAvg(e){let t=e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n));return t.length===0?0:t.reduce((n,i)=>n+i,0)/t.length}computeMin(e){if(e.length===0)return;let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));if(t.length>0)return Math.min(...t);let n=e.map(i=>String(i));return n.reduce((i,s)=>s<i?s:i,n[0])}computeMax(e){if(e.length===0)return;let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));if(t.length>0)return Math.max(...t);let n=e.map(i=>String(i));return n.reduce((i,s)=>s>i?s:i,n[0])}computeGroupConcat(e,t,n){let i=e.map(s=>String(s));return n&&(i=[...new Set(i)]),i.join(t)}computeSample(e,t){if(e.length===0)return;if(t){let s=[...new Set(e.map(u=>String(u)))];if(s.length===0)return;let a=s[0],c=parseFloat(a);return isNaN(c)?a:c}let n=e[0];if(typeof n=="number")return n;let i=parseFloat(String(n));return isNaN(i)?String(n):i}createEmptyAggregateResult(e){let{SolutionMapping:t}=Hi(),n=new t;for(let i of e.aggregates){let s=i.expression.aggregation;if(nw(s)){n.set(i.variable,new Lt.Literal("0",ma));continue}switch(s){case"count":n.set(i.variable,new Lt.Literal("0",rw));break;case"sum":case"avg":n.set(i.variable,new Lt.Literal("0",ma));break;case"group_concat":n.set(i.variable,new Lt.Literal(" ",yi));break;case"min":case"max":case"sample":n.set(i.variable,new Lt.Literal("",yi));break;default:n.set(i.variable,new Lt.Literal("",yi))}}return n}};vo.AggregateExecutor=Ay});var aw=_(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.ServiceExecutor=So.ServiceExecutorError=void 0;var e5=Hi(),sw=Ye(),t5=ht(),r5=Rt(),ga=class extends Error{static{o(this,"ServiceExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ServiceExecutorError"}};So.ServiceExecutorError=ga;var Cy=class{static{o(this,"ServiceExecutor")}constructor(e={}){this.timeout=e.timeout??3e4,this.httpClient=e.httpClient??((t,n)=>fetch(t,n)),this.maxRetries=e.maxRetries??2,this.retryDelay=e.retryDelay??1e3}async*execute(e,t){try{let n=t(e.pattern),i=await this.executeRemoteQuery(e.endpoint,n);for(let s of i)yield s}catch(n){if(e.silent)return;throw n}}async executeRemoteQuery(e,t){let n;for(let i=0;i<=this.maxRetries;i++)try{let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout);try{let c=await this.httpClient(e,{method:"POST",headers:{"Content-Type":"application/sparql-query",Accept:"application/sparql-results+json"},body:t,signal:s.signal});if(!c.ok)throw new ga(`Remote SPARQL endpoint returned ${c.status}: ${c.statusText}`);let u=await c.json();return this.parseJsonResults(u)}finally{clearTimeout(a)}}catch(s){if(n=s instanceof Error?s:new Error(String(s)),this.isRetryableError(n)&&i<this.maxRetries){await this.delay(this.retryDelay);continue}throw new ga(`Failed to query remote SPARQL endpoint ${e}: ${n.message}`,n)}throw new ga(`Failed to query remote SPARQL endpoint ${e} after ${this.maxRetries+1} attempts`,n)}parseJsonResults(e){return!e.results||!Array.isArray(e.results.bindings)?[]:e.results.bindings.map(t=>this.parseBinding(t))}parseBinding(e){let t=new e5.SolutionMapping;for(let[n,i]of Object.entries(e)){let s=this.parseRDFTerm(i);t.set(n,s)}return t}parseRDFTerm(e){switch(e.type){case"uri":return new sw.IRI(e.value);case"literal":{let t=e.datatype?new sw.IRI(e.datatype):void 0;return new t5.Literal(e.value,t,e["xml:lang"])}case"bnode":return new r5.BlankNode(e.value);default:throw new ga(`Unknown RDF term type: ${e.type}`)}}isRetryableError(e){let t=e.message.toLowerCase();return!!(e.name==="AbortError"||t.includes("network")||t.includes("econnreset")||t.includes("econnrefused")||t.includes("etimedout")||t.includes("returned 5"))}delay(e){return new Promise(t=>setTimeout(t,e))}};So.ServiceExecutor=Cy});var cw=_(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.GraphExecutor=bo.GraphExecutorError=void 0;var ow=Ye(),gh=class extends Error{static{o(this,"GraphExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="GraphExecutorError"}};bo.GraphExecutorError=gh;var Iy=class{static{o(this,"GraphExecutor")}constructor(e){this.tripleStore=e}async*execute(e,t,n){let i=e.name;if(i.type==="iri")yield*this.executeWithGraph(e.pattern,i,t);else if(i.type==="variable")yield*this.executeWithGraphVariable(e,i,t,n);else throw new gh(`Invalid graph name type: ${i.type}`)}async*executeWithGraph(e,t,n){let i=new ow.IRI(t.value);this.tripleStore.hasGraph&&!await this.tripleStore.hasGraph(i)||(yield*n(e,i))}async*executeWithGraphVariable(e,t,n,i){if(i){let a=i.get(t.value);if(a&&a instanceof ow.IRI){yield*this.executeWithGraph(e.pattern,{type:"iri",value:a.value},n);return}}if(!this.tripleStore.getNamedGraphs)return;let s=await this.tripleStore.getNamedGraphs();for(let a of s)for await(let c of n(e.pattern,a)){let u=c.clone();u.set(t.value,a),yield u}}};bo.GraphExecutor=Iy});var uw=_(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.SPARQLGenerator=Eo.SPARQLGeneratorError=void 0;var wo=class extends Error{static{o(this,"SPARQLGeneratorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="SPARQLGeneratorError"}};Eo.SPARQLGeneratorError=wo;var Oy=class{static{o(this,"SPARQLGenerator")}collectVariables(e){let t=new Set;return this.collectVariablesFromOperation(e,t),t}generateSelect(e){let t=this.collectVariables(e),n=t.size>0?Array.from(t).map(s=>`?${s}`).join(" "):"*",i=this.generateWhereClause(e);return`SELECT ${n} WHERE {
293
293
  ${i}
294
294
  }`}generateWhereClause(e,t=2){let n=" ".repeat(t);switch(e.type){case"bgp":return this.generateBGP(e,t);case"filter":return`${this.generateWhereClause(e.input,t)}
295
295
  ${n}FILTER(${this.generateExpression(e.expression)})`;case"join":return`${this.generateWhereClause(e.left,t)}
@@ -311,7 +311,7 @@ ${n}}`}default:throw new wo(`Unsupported operation type for SPARQL generation: $
311
311
  `)}generateTriple(e){let t=this.generateElement(e.subject),n=this.generatePredicate(e.predicate),i=this.generateElement(e.object);return`${t} ${n} ${i}`}generatePredicate(e){return"pathType"in e?this.generatePropertyPath(e):this.generateElement(e)}generatePropertyPath(e){let t=e.items.map(n=>"pathType"in n?`(${this.generatePropertyPath(n)})`:`<${n.value}>`);switch(e.pathType){case"/":return t.join("/");case"|":return t.join("|");case"^":return`^${t[0]}`;case"+":return`${t[0]}+`;case"*":return`${t[0]}*`;case"?":return`${t[0]}?`}}generateElement(e){switch(e.type){case"variable":return`?${e.value}`;case"iri":return`<${e.value}>`;case"literal":{let n=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`;return e.language?n+=`@${e.language}`:e.datatype&&(n+=`^^<${e.datatype}>`),n}case"blank":return`_:${e.value}`;default:throw new wo(`Unknown element type: ${e.type}`)}}generateValues(e,t){let n=" ".repeat(t);if(e.variables.length===0||e.bindings.length===0)return"";if(e.variables.length===1){let a=e.variables[0],c=e.bindings.map(u=>{let l=u[a];return l?this.generateValuesTerm(l):"UNDEF"}).join(" ");return`${n}VALUES ?${a} { ${c} }`}let i=e.variables.map(a=>`?${a}`).join(" "),s=e.bindings.map(a=>`(${e.variables.map(u=>{let l=a[u];return l?this.generateValuesTerm(l):"UNDEF"}).join(" ")})`);return`${n}VALUES (${i}) {
312
312
  ${s.map(a=>`${n} ${a}`).join(`
313
313
  `)}
314
- ${n}}`}generateValuesTerm(e){if(e.type==="iri")return`<${e.value}>`;let n=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return e.language?n+=`@${e.language}`:e.datatype&&(n+=`^^<${e.datatype}>`),n}generateExpression(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e.value=="boolean"?e.value?"true":"false":String(e.value);case"comparison":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"logical":return e.operator==="!"?`!(${this.generateExpression(e.operands[0])})`:`(${e.operands.map(t=>this.generateExpression(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"function":return`${e.function.toUpperCase()}(${e.args.map(t=>this.generateExpression(t)).join(", ")})`;case"functionCall":return`${(typeof e.function=="string"?e.function:e.function.value).toUpperCase()}(${e.args.map(n=>this.generateExpression(n)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.generateWhereClause(e.pattern,0)} }`;case"in":{let t=this.generateExpression(e.expression),n=e.list.map(i=>this.generateExpression(i)).join(", ");return e.negated?`${t} NOT IN (${n})`:`${t} IN (${n})`}default:throw new wo(`Unknown expression type: ${e.type}`)}}collectVariablesFromOperation(e,t){switch(e.type){case"bgp":for(let n of e.triples)this.collectVariablesFromTriple(n,t);break;case"filter":this.collectVariablesFromOperation(e.input,t),this.collectVariablesFromExpression(e.expression,t);break;case"join":case"leftjoin":case"union":case"minus":this.collectVariablesFromOperation(e.left,t),this.collectVariablesFromOperation(e.right,t);break;case"values":for(let n of e.variables)t.add(n);break;case"project":for(let n of e.variables)t.add(n);this.collectVariablesFromOperation(e.input,t);break;case"extend":t.add(e.variable),this.collectVariablesFromOperation(e.input,t);break;case"orderby":case"slice":case"distinct":case"reduced":this.collectVariablesFromOperation(e.input,t);break;case"group":for(let n of e.variables)t.add(n);for(let n of e.aggregates)t.add(n.variable);this.collectVariablesFromOperation(e.input,t);break;case"subquery":this.collectVariablesFromOperation(e.query,t);break}}collectVariablesFromTriple(e,t){e.subject.type==="variable"&&t.add(e.subject.value),"type"in e.predicate&&e.predicate.type==="variable"&&t.add(e.predicate.value),e.object.type==="variable"&&t.add(e.object.value)}collectVariablesFromExpression(e,t){switch(e.type){case"variable":t.add(e.name);break;case"comparison":case"arithmetic":this.collectVariablesFromExpression(e.left,t),this.collectVariablesFromExpression(e.right,t);break;case"logical":for(let n of e.operands)this.collectVariablesFromExpression(n,t);break;case"function":case"functionCall":for(let n of e.args)this.collectVariablesFromExpression(n,t);break;case"exists":this.collectVariablesFromOperation(e.pattern,t);break;case"in":this.collectVariablesFromExpression(e.expression,t);for(let n of e.list)this.collectVariablesFromExpression(n,t);break}}};Eo.SPARQLGenerator=Oy});var lw=_(gn=>{"use strict";var n5=gn&&gn.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),i5=gn&&gn.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),s5=gn&&gn.__importStar||(function(){var r=o(function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&n5(t,e,n[i]);return i5(t,e),t}})();Object.defineProperty(gn,"__esModule",{value:!0});gn.QueryExecutor=gn.QueryExecutorError=void 0;var a5=uy(),o5=oh(),c5=dy(),u5=my(),l5=Zb(),f5=tw(),h5=iw(),d5=vy(),p5=aw(),m5=cw(),g5=uw(),y5=Ye(),To=class extends Error{static{o(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};gn.QueryExecutorError=To;var Py=class{static{o(this,"QueryExecutor")}constructor(e,t={}){this.tripleStore=e,this.bgpExecutor=new a5.BGPExecutor(e),this.filterExecutor=new o5.FilterExecutor,this.optionalExecutor=new c5.OptionalExecutor,this.unionExecutor=new u5.UnionExecutor,this.minusExecutor=new l5.MinusExecutor,this.valuesExecutor=new f5.ValuesExecutor,this.aggregateExecutor=new h5.AggregateExecutor,this.constructExecutor=new d5.ConstructExecutor,this.serviceExecutor=new p5.ServiceExecutor(t.serviceConfig),this.graphExecutor=new m5.GraphExecutor(e),this.sparqlGenerator=new g5.SPARQLGenerator,this.filterExecutor.setExistsEvaluator(async(n,i)=>this.evaluateExistsPattern(n,i)),this.filterExecutor.setTripleStore(e)}async evaluateExistsPattern(e,t){for await(let n of this.execute(e))if(t.merge(n)!==null)return!0;return!1}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*execute(e){switch(e.type){case"bgp":yield*this.executeBGP(e);break;case"filter":yield*this.executeFilter(e);break;case"join":yield*this.executeJoin(e);break;case"leftjoin":yield*this.executeLeftJoin(e);break;case"union":yield*this.executeUnion(e);break;case"minus":yield*this.executeMinus(e);break;case"values":yield*this.executeValues(e);break;case"project":yield*this.executeProject(e);break;case"orderby":yield*this.executeOrderBy(e);break;case"slice":yield*this.executeSlice(e);break;case"distinct":yield*this.executeDistinct(e);break;case"reduced":yield*this.executeReduced(e);break;case"group":yield*this.executeGroup(e);break;case"extend":yield*this.executeExtend(e);break;case"subquery":yield*this.executeSubquery(e);break;case"lateraljoin":yield*this.executeLateralJoin(e);break;case"service":yield*this.executeService(e);break;case"graph":yield*this.executeGraph(e);break;default:throw new To(`Unknown operation type: ${e.type}`)}}async*executeBGP(e){yield*this.bgpExecutor.execute(e)}async*executeFilter(e){let t=this.execute(e.input);yield*this.filterExecutor.execute(e,t)}async*executeJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t)for await(let i of this.execute(e.right)){let s=n.merge(i);s!==null&&(yield s)}}async*executeLeftJoin(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.optionalExecutor.execute(i(),s())}async*executeUnion(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.unionExecutor.execute(i(),s())}async*executeMinus(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.minusExecutor.execute(i(),s())}async*executeValues(e){yield*this.valuesExecutor.execute(e)}async*executeProject(e){for await(let t of this.execute(e.input))yield t}async*executeOrderBy(e){let t=[];for await(let n of this.execute(e.input))t.push(n);t.sort((n,i)=>{for(let s of e.comparators){let a=this.getExpressionValue(s.expression,n),c=this.getExpressionValue(s.expression,i),u=0;if(a===void 0&&c===void 0?u=0:a===void 0?u=1:c===void 0?u=-1:typeof a=="number"&&typeof c=="number"?u=a-c:u=String(a).localeCompare(String(c)),s.descending&&(u=-u),u!==0)return u}return 0});for(let n of t)yield n}async*executeSlice(e){let t=0,n=e.offset??0,i=e.limit;for await(let s of this.execute(e.input)){if(t>=n){if(i!==void 0&&t-n>=i)break;yield s}t++}}async*executeDistinct(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeReduced(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeGroup(e){let t=[];for await(let i of this.execute(e.input))t.push(i);let n=this.aggregateExecutor.execute(e,t);for(let i of n)yield i}async*executeExtend(e){for await(let t of this.execute(e.input)){let n=t.clone(),i=this.evaluateExtendExpression(e.expression,t);i!==void 0&&n.set(e.variable,i),yield n}}async*executeSubquery(e){yield*this.execute(e.query)}async*executeLateralJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t){let i=this.substituteVariables(e.right,n);for await(let s of this.execute(i)){let a=n.merge(s);a!==null&&(yield a)}}}substituteVariables(e,t){let n=JSON.parse(JSON.stringify(e));return this.substituteInOperation(n,t)}substituteInOperation(e,t){return!e||typeof e!="object"?e:e.type==="bgp"&&e.triples?(e.triples=e.triples.map(n=>this.substituteInTriple(n,t)),e):(e.input&&(e.input=this.substituteInOperation(e.input,t)),e.left&&(e.left=this.substituteInOperation(e.left,t)),e.right&&(e.right=this.substituteInOperation(e.right,t)),e.pattern&&(e.pattern=this.substituteInOperation(e.pattern,t)),e.query&&(e.query=this.substituteInOperation(e.query,t)),e.where&&(e.where=this.substituteInOperation(e.where,t)),e)}substituteInTriple(e,t){return{subject:this.substituteInTripleElement(e.subject,t),predicate:e.predicate,object:this.substituteInTripleElement(e.object,t)}}substituteInTripleElement(e,t){if(e&&e.type==="variable"){let n=t.get(e.value);if(n){if(n instanceof y5.IRI||n.termType==="NamedNode")return{type:"iri",value:n.value};if(n.termType==="Literal"||typeof n.value=="string"){let i=n;return{type:"literal",value:i.value,datatype:i.datatype?.value||i._datatype?.value,language:i.language||i._language}}}}return e}async*executeService(e){yield*this.serviceExecutor.execute(e,t=>this.sparqlGenerator.generateSelect(t))}async*executeGraph(e){let t=async function*(n,i){let s=this.currentGraphContext;this.currentGraphContext=i;try{n.type==="bgp"&&i&&this.tripleStore.matchInGraph?yield*this.executeBGPInGraph(n,i):yield*this.execute(n)}finally{this.currentGraphContext=s}}.bind(this);yield*this.graphExecutor.execute(e,t)}async*executeBGPInGraph(e,t){if(e.triples.length===0){let{SolutionMapping:n}=await Promise.resolve().then(()=>s5(Hi()));yield new n;return}yield*this.bgpExecutor.executeInGraph(e,t)}evaluateExtendExpression(e,t){if(e.type!=="aggregate")try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}getExpressionValue(e,t){if(e.type==="variable"){let n=t.get(e.name);return n?n.value??n.id??String(n):void 0}return e.value}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}isConstructQuery(e){return e.type==="construct"}async executeConstruct(e){if(e.type!=="construct")throw new To("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}isAskQuery(e){return e.type==="ask"}async executeAsk(e){if(e.type!=="ask")throw new To("executeAsk requires an ASK operation");for await(let t of this.execute(e.where))return!0;return!1}};gn.QueryExecutor=Py});var hw=_(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.UpdateExecutor=xo.UpdateExecutorError=void 0;var _5=$i(),Ao=Ye(),Dy=ht(),fw=Rt(),hr=class extends Error{static{o(this,"UpdateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="UpdateExecutorError"}};xo.UpdateExecutorError=hr;var Fy=class{static{o(this,"UpdateExecutor")}constructor(e){this.tripleStore=e}async execute(e){if(e.type!=="update")throw new hr("Expected UPDATE request");let t=[];for(let n of e.updates){let i=await this.executeOperation(n);t.push(i)}return t}async executeOperation(e){if("updateType"in e)switch(e.updateType){case"insert":return this.executeInsertData(e);case"delete":return this.executeDeleteData(e);case"insertdelete":throw new hr("INSERT/DELETE with WHERE clause not yet implemented");case"deletewhere":throw new hr("DELETE WHERE not yet implemented");default:throw new hr(`Unknown update type: ${e.updateType}`)}if("type"in e)switch(e.type){case"clear":case"drop":case"load":case"create":case"copy":case"move":case"add":throw new hr(`${e.type.toUpperCase()} operation not yet implemented`);default:throw new hr(`Unknown operation type: ${e.type}`)}throw new hr("Unknown update operation structure")}async executeInsertData(e){if(e.updateType!=="insert")throw new hr("Expected INSERT DATA operation");let t=e,n=0;for(let i of t.insert)if(i.type==="bgp"){let s=this.resolveGraphName(t.graph);n+=await this.insertTriples(i.triples,s)}else if(i.type==="graph"){let s=i,a=this.parseGraphName(s.name);n+=await this.insertTriples(s.triples,a)}return{type:"insert",inserted:n,success:!0}}async executeDeleteData(e){if(e.updateType!=="delete")throw new hr("Expected DELETE DATA operation");let t=e,n=0;for(let i of t.delete)if(i.type==="bgp"){let s=this.resolveGraphName(t.graph);n+=await this.deleteTriples(i.triples,s)}else if(i.type==="graph"){let s=i,a=this.parseGraphName(s.name);n+=await this.deleteTriples(s.triples,a)}return{type:"delete",deleted:n,success:!0}}async insertTriples(e,t){let n=0;for(let i of e){let s=this.convertTriple(i);t&&this.tripleStore.addToGraph?await this.tripleStore.addToGraph(s,t):await this.tripleStore.add(s),n++}return n}async deleteTriples(e,t){let n=0;for(let i of e){let s=this.convertTriple(i),a;t&&this.tripleStore.removeFromGraph?a=await this.tripleStore.removeFromGraph(s,t):a=await this.tripleStore.remove(s),a&&n++}return n}convertTriple(e){return new _5.Triple(this.convertSubject(e.subject),this.convertPredicate(e.predicate),this.convertObject(e.object))}convertSubject(e){if(e.termType==="NamedNode")return new Ao.IRI(e.value);if(e.termType==="BlankNode")return new fw.BlankNode(e.value);throw new hr(`Invalid subject term type: ${e.termType}. Variables are not allowed in INSERT DATA.`)}convertPredicate(e){if("termType"in e&&e.termType==="NamedNode")return new Ao.IRI(e.value);throw new hr("Invalid predicate term type. Only IRIs are allowed in INSERT DATA.")}convertObject(e){if(e.termType==="NamedNode")return new Ao.IRI(e.value);if(e.termType==="BlankNode")return new fw.BlankNode(e.value);if(e.termType==="Literal"){let t=e;return t.language?new Dy.Literal(t.value,void 0,t.language):t.datatype?new Dy.Literal(t.value,new Ao.IRI(t.datatype.value)):new Dy.Literal(t.value)}throw new hr(`Invalid object term type: ${e.termType}. Variables are not allowed in INSERT DATA.`)}resolveGraphName(e){if(e&&!e.default&&e.name)return new Ao.IRI(e.name.value)}parseGraphName(e){if(e.termType==="Variable")throw new hr("Variables are not allowed as graph names in INSERT DATA / DELETE DATA.");return new Ao.IRI(e.value)}};xo.UpdateExecutor=Fy});var pw=_(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});yh.AggregateFunctions=void 0;var Ry=ht(),dw=Ye(),Ny=class{static{o(this,"AggregateFunctions")}static count(e,t){if(!t)return e.length;let n=0;for(let i of e)i.has(t)&&n++;return n}static countDistinct(e,t){let n=new Set;for(let i of e){let s=i.get(t);s&&n.add(s.toString())}return n.size}static sum(e,t){let n=0;for(let i of e){let s=i.get(t);if(s instanceof Ry.Literal){let a=this.toNumber(s);isNaN(a)||(n+=a)}}return n}static avg(e,t){let n=this.sum(e,t),i=this.count(e,t);return i>0?n/i:0}static min(e,t){let n=null;for(let i of e){let s=i.get(t);if(!s)continue;let a=this.toComparable(s);(n===null||a<n)&&(n=a)}return n}static max(e,t){let n=null;for(let i of e){let s=i.get(t);if(!s)continue;let a=this.toComparable(s);(n===null||a>n)&&(n=a)}return n}static groupConcat(e,t,n=" "){let i=[];for(let s of e){let a=s.get(t);a&&(a instanceof Ry.Literal||a instanceof dw.IRI?i.push(a.value):i.push(a.toString()))}return i.join(n)}static sample(e,t){for(let n of e){let i=n.get(t);if(i)return this.toComparable(i)}return null}static sampleDistinct(e,t){return this.sample(e,t)}static toNumber(e){let t=e.datatype?.value;return t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double"),parseFloat(e.value)}static toComparable(e){if(e instanceof Ry.Literal){let t=this.toNumber(e);return isNaN(t)?e.value:t}return e instanceof dw.IRI?e.value:String(e)}};yh.AggregateFunctions=Ny});var mw=_(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});_h.QueryPlanCache=void 0;var v5=Nf(),Ly=class{static{o(this,"QueryPlanCache")}constructor(e=100){this.hits=0,this.misses=0,this.cache=new v5.LRUCache(e)}get(e){let t=this.normalizeQuery(e),n=this.cache.get(t);return n!==void 0?this.hits++:this.misses++,n}set(e,t){let n=this.normalizeQuery(e);this.cache.set(n,t)}has(e){let t=this.normalizeQuery(e);return this.cache.get(t)!==void 0}clear(){this.cache.clear()}getStats(){let e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,size:this.cache.size()}}resetStats(){this.hits=0,this.misses=0}normalizeQuery(e){return e.replace(/\s+/g," ").trim()}};_h.QueryPlanCache=Ly});var gw=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.SPARQLResultCache=void 0;Xc.createSPARQLResultCache=w5;var S5=Nf(),b5={maxSize:500,ttlMs:300*1e3,enableFileInvalidation:!0,maxResultSizeBytes:10*1024*1024},vh=class{static{o(this,"SPARQLResultCache")}constructor(e={}){this.fileToQueries=new Map,this.stats={hits:0,misses:0,evictions:0,ttlInvalidations:0,fileInvalidations:0,totalTimeSavedMs:0},this.avgQueryTimeMs=100,this.options={...b5,...e},this.cache=new S5.LRUCache(this.options.maxSize)}normalizeQuery(e){return e.replace(/\s+/g," ").trim()}hashResult(e){return this.isTripleArray(e)?`T:${e.length}`:`S:${e.length}`}isTripleArray(e){return e.length>0&&"subject"in e[0]}estimateResultSize(e){return this.isTripleArray(e)?e.length*300:e.length*200}get(e){let t=this.normalizeQuery(e),n=this.cache.get(t);if(n===void 0){this.stats.misses++;return}if(Date.now()-n.timestamp>this.options.ttlMs){this.cache.set(t,void 0),this.stats.ttlInvalidations++,this.stats.misses++;return}return this.stats.hits++,this.stats.totalTimeSavedMs+=this.avgQueryTimeMs,n.result}set(e,t,n,i){if(this.estimateResultSize(t)>this.options.maxResultSizeBytes)return;i!==void 0&&(this.avgQueryTimeMs=(this.avgQueryTimeMs+i)/2);let a=this.normalizeQuery(e),c=n??new Set,u={result:t,timestamp:Date.now(),affectedFiles:c,resultHash:this.hashResult(t)};if(this.cache.size()>=this.options.maxSize&&this.stats.evictions++,this.cache.set(a,u),this.options.enableFileInvalidation)for(let f of c){let h=this.fileToQueries.get(f);h||(h=new Set,this.fileToQueries.set(f,h)),h.add(a)}}has(e){let t=this.normalizeQuery(e),n=this.cache.get(t);return n===void 0?!1:Date.now()-n.timestamp<=this.options.ttlMs}invalidateByFile(e){if(!this.options.enableFileInvalidation)return 0;let t=this.fileToQueries.get(e);if(!t)return 0;let n=0;for(let i of t)this.cache.set(i,void 0),n++,this.stats.fileInvalidations++;return this.fileToQueries.delete(e),n}clear(){this.cache.clear(),this.fileToQueries.clear()}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{hits:this.stats.hits,misses:this.stats.misses,hitRate:t,size:this.cache.size(),maxSize:this.options.maxSize,evictions:this.stats.evictions,ttlInvalidations:this.stats.ttlInvalidations,fileInvalidations:this.stats.fileInvalidations,avgTimeSavedMs:this.stats.hits>0?this.stats.totalTimeSavedMs/this.stats.hits:0}}resetStats(){this.stats={hits:0,misses:0,evictions:0,ttlInvalidations:0,fileInvalidations:0,totalTimeSavedMs:0}}size(){return this.cache.size()}pruneExpired(){return 0}};Xc.SPARQLResultCache=vh;function w5(r){return new vh(r)}o(w5,"createSPARQLResultCache")});var yw=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.IncrementalIndexer=void 0;Jc.createIncrementalIndexer=T5;var E5={throttleMs:500,maxBatchSize:100,useContentHashing:!1},Sh=class{static{o(this,"IncrementalIndexer")}constructor(e={}){this.fileMetadata=new Map,this.pendingChanges=[],this.throttleTimer=null,this.invalidateCallbacks=[],this.lastIndexTime=0,this.stats={totalChanges:0,invalidations:0,noOpChanges:0,indexDurations:[]},this.options={...E5,...e}}recordChange(e){this.pendingChanges.push(e),this.stats.totalChanges++,this.throttleTimer===null&&(this.throttleTimer=setTimeout(()=>{this.processPendingChanges(),this.throttleTimer=null},this.options.throttleMs))}processPendingChanges(){if(this.pendingChanges.length===0)return;let e=performance.now(),t=new Map;for(let a of this.pendingChanges)t.set(a.path,a);let n=Array.from(t.values()),i=[];for(let a of n)switch(a.type){case"deleted":this.fileMetadata.delete(a.path),i.push(a);break;case"renamed":a.oldPath&&this.fileMetadata.delete(a.oldPath),i.push(a);break;case"created":case"modified":i.push(a);break}if(i.length>0){this.stats.invalidations+=i.length;for(let a of this.invalidateCallbacks)try{a(i)}catch(c){console.error("IncrementalIndexer: Error in invalidation callback:",c)}}let s=performance.now()-e;this.stats.indexDurations.push(s),this.stats.indexDurations.length>100&&this.stats.indexDurations.shift(),this.lastIndexTime=Date.now(),this.pendingChanges=[]}flush(){this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.processPendingChanges()}updateMetadata(e,t,n,i){this.fileMetadata.set(e,{mtime:t,size:n,contentHash:i})}hasChanged(e,t,n){let i=this.fileMetadata.get(e);return i===void 0||i.mtime!==t||n!==void 0&&i.size!==n}getChangedFiles(e){let t=[];for(let[n,i]of this.fileMetadata.entries())i.mtime>e&&t.push(n);return t}onInvalidate(e){return this.invalidateCallbacks.push(e),()=>{let t=this.invalidateCallbacks.indexOf(e);t!==-1&&this.invalidateCallbacks.splice(t,1)}}getStats(){let e=this.stats.indexDurations,t=e.length>0?e.reduce((i,s)=>i+s,0)/e.length:0,n=e.length>0?e[e.length-1]:0;return{trackedFiles:this.fileMetadata.size,totalChanges:this.stats.totalChanges,invalidations:this.stats.invalidations,noOpChanges:this.stats.noOpChanges,lastIndexDurationMs:n,avgIndexDurationMs:t,lastIndexTime:this.lastIndexTime}}resetStats(){this.stats={totalChanges:0,invalidations:0,noOpChanges:0,indexDurations:[]}}clear(){this.fileMetadata.clear(),this.pendingChanges=[],this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null)}size(){return this.fileMetadata.size}isTracked(e){return this.fileMetadata.has(e)}getMetadata(e){return this.fileMetadata.get(e)}dispose(){this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.invalidateCallbacks=[],this.pendingChanges=[],this.fileMetadata.clear()}};Jc.IncrementalIndexer=Sh;function T5(r){return new Sh(r)}o(T5,"createIncrementalIndexer")});var _w=_(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});Th.ResultSerializer=void 0;var bh=ht(),wh=Ye(),Eh=Rt(),My=class{static{o(this,"ResultSerializer")}serialize(e,t,n={}){switch(t){case"json":return this.serializeJSON(e,n);case"xml":return this.serializeXML(e,n);case"csv":return this.serializeCSV(e,n);case"turtle":return this.serializeTurtle(e,n);default:throw new Error(`Unsupported result format: ${t}`)}}serializeJSON(e,t={}){let n=this.toJSONResultSet(e,t),i=t.pretty?t.indent??2:void 0;return JSON.stringify(n,null,i)}toJSONResultSet(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=e.map(a=>{let c={};for(let u of i){let l=a.get(u);l!==void 0&&(c[u]=this.termToJSONBinding(l))}return c});return{head:{vars:i},results:{bindings:s}}}termToJSONBinding(e){return e instanceof wh.IRI?{type:"uri",value:e.value}:e instanceof Eh.BlankNode?{type:"bnode",value:e.id}:e instanceof bh.Literal?this.literalToJSONBinding(e):{type:"literal",value:String(e)}}literalToJSONBinding(e){let t={type:"literal",value:e.value};return e.datatype?t.datatype=e.datatype.value:e.language&&(t["xml:lang"]=e.language,e.hasDirection()&&e.direction&&(t.direction=e.direction)),t}serializeXML(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=['<?xml version="1.0"?>','<sparql xmlns="http://www.w3.org/2005/sparql-results#">'," <head>"];for(let a of i)s.push(` <variable name="${this.escapeXML(a)}"/>`);s.push(" </head>"),s.push(" <results>");for(let a of e){s.push(" <result>");for(let c of i){let u=a.get(c);u!==void 0&&(s.push(` <binding name="${this.escapeXML(c)}">`),s.push(" "+this.termToXML(u)),s.push(" </binding>"))}s.push(" </result>")}return s.push(" </results>"),s.push("</sparql>"),s.join(`
314
+ ${n}}`}generateValuesTerm(e){if(e.type==="iri")return`<${e.value}>`;let n=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return e.language?n+=`@${e.language}`:e.datatype&&(n+=`^^<${e.datatype}>`),n}generateExpression(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e.value=="boolean"?e.value?"true":"false":String(e.value);case"comparison":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"logical":return e.operator==="!"?`!(${this.generateExpression(e.operands[0])})`:`(${e.operands.map(t=>this.generateExpression(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"function":return`${e.function.toUpperCase()}(${e.args.map(t=>this.generateExpression(t)).join(", ")})`;case"functionCall":return`${(typeof e.function=="string"?e.function:e.function.value).toUpperCase()}(${e.args.map(n=>this.generateExpression(n)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.generateWhereClause(e.pattern,0)} }`;case"in":{let t=this.generateExpression(e.expression),n=e.list.map(i=>this.generateExpression(i)).join(", ");return e.negated?`${t} NOT IN (${n})`:`${t} IN (${n})`}default:throw new wo(`Unknown expression type: ${e.type}`)}}collectVariablesFromOperation(e,t){switch(e.type){case"bgp":for(let n of e.triples)this.collectVariablesFromTriple(n,t);break;case"filter":this.collectVariablesFromOperation(e.input,t),this.collectVariablesFromExpression(e.expression,t);break;case"join":case"leftjoin":case"union":case"minus":this.collectVariablesFromOperation(e.left,t),this.collectVariablesFromOperation(e.right,t);break;case"values":for(let n of e.variables)t.add(n);break;case"project":for(let n of e.variables)t.add(n);this.collectVariablesFromOperation(e.input,t);break;case"extend":t.add(e.variable),this.collectVariablesFromOperation(e.input,t);break;case"orderby":case"slice":case"distinct":case"reduced":this.collectVariablesFromOperation(e.input,t);break;case"group":for(let n of e.variables)t.add(n);for(let n of e.aggregates)t.add(n.variable);this.collectVariablesFromOperation(e.input,t);break;case"subquery":this.collectVariablesFromOperation(e.query,t);break}}collectVariablesFromTriple(e,t){e.subject.type==="variable"&&t.add(e.subject.value),"type"in e.predicate&&e.predicate.type==="variable"&&t.add(e.predicate.value),e.object.type==="variable"&&t.add(e.object.value)}collectVariablesFromExpression(e,t){switch(e.type){case"variable":t.add(e.name);break;case"comparison":case"arithmetic":this.collectVariablesFromExpression(e.left,t),this.collectVariablesFromExpression(e.right,t);break;case"logical":for(let n of e.operands)this.collectVariablesFromExpression(n,t);break;case"function":case"functionCall":for(let n of e.args)this.collectVariablesFromExpression(n,t);break;case"exists":this.collectVariablesFromOperation(e.pattern,t);break;case"in":this.collectVariablesFromExpression(e.expression,t);for(let n of e.list)this.collectVariablesFromExpression(n,t);break}}};Eo.SPARQLGenerator=Oy});var lw=_(gn=>{"use strict";var n5=gn&&gn.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),i5=gn&&gn.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),s5=gn&&gn.__importStar||(function(){var r=o(function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&n5(t,e,n[i]);return i5(t,e),t}})();Object.defineProperty(gn,"__esModule",{value:!0});gn.QueryExecutor=gn.QueryExecutorError=void 0;var a5=uy(),o5=oh(),c5=dy(),u5=my(),l5=Zb(),f5=tw(),h5=iw(),d5=vy(),p5=aw(),m5=cw(),g5=uw(),y5=Ye(),To=class extends Error{static{o(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};gn.QueryExecutorError=To;var Py=class{static{o(this,"QueryExecutor")}constructor(e,t={}){this.tripleStore=e,this.bgpExecutor=new a5.BGPExecutor(e),this.filterExecutor=new o5.FilterExecutor,this.optionalExecutor=new c5.OptionalExecutor,this.unionExecutor=new u5.UnionExecutor,this.minusExecutor=new l5.MinusExecutor,this.valuesExecutor=new f5.ValuesExecutor,this.aggregateExecutor=new h5.AggregateExecutor,this.constructExecutor=new d5.ConstructExecutor,this.serviceExecutor=new p5.ServiceExecutor(t.serviceConfig),this.graphExecutor=new m5.GraphExecutor(e),this.sparqlGenerator=new g5.SPARQLGenerator,this.filterExecutor.setExistsEvaluator(async(n,i)=>this.evaluateExistsPattern(n,i)),this.filterExecutor.setTripleStore(e)}async evaluateExistsPattern(e,t){for await(let n of this.execute(e))if(t.merge(n)!==null)return!0;return!1}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*execute(e){switch(e.type){case"bgp":yield*this.executeBGP(e);break;case"filter":yield*this.executeFilter(e);break;case"join":yield*this.executeJoin(e);break;case"leftjoin":yield*this.executeLeftJoin(e);break;case"union":yield*this.executeUnion(e);break;case"minus":yield*this.executeMinus(e);break;case"values":yield*this.executeValues(e);break;case"project":yield*this.executeProject(e);break;case"orderby":yield*this.executeOrderBy(e);break;case"slice":yield*this.executeSlice(e);break;case"distinct":yield*this.executeDistinct(e);break;case"reduced":yield*this.executeReduced(e);break;case"group":yield*this.executeGroup(e);break;case"extend":yield*this.executeExtend(e);break;case"subquery":yield*this.executeSubquery(e);break;case"lateraljoin":yield*this.executeLateralJoin(e);break;case"service":yield*this.executeService(e);break;case"graph":yield*this.executeGraph(e);break;default:throw new To(`Unknown operation type: ${e.type}`)}}async*executeBGP(e){yield*this.bgpExecutor.execute(e)}async*executeFilter(e){let t=this.execute(e.input);yield*this.filterExecutor.execute(e,t)}async*executeJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t)for await(let i of this.execute(e.right)){let s=n.merge(i);s!==null&&(yield s)}}async*executeLeftJoin(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.optionalExecutor.execute(i(),s())}async*executeUnion(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.unionExecutor.execute(i(),s())}async*executeMinus(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.minusExecutor.execute(i(),s())}async*executeValues(e){yield*this.valuesExecutor.execute(e)}async*executeProject(e){for await(let t of this.execute(e.input))yield t}async*executeOrderBy(e){let t=[];for await(let n of this.execute(e.input))t.push(n);t.sort((n,i)=>{for(let s of e.comparators){let a=this.getExpressionValue(s.expression,n),c=this.getExpressionValue(s.expression,i),u=0;if(a===void 0&&c===void 0?u=0:a===void 0?u=1:c===void 0?u=-1:typeof a=="number"&&typeof c=="number"?u=a-c:u=String(a).localeCompare(String(c)),s.descending&&(u=-u),u!==0)return u}return 0});for(let n of t)yield n}async*executeSlice(e){let t=0,n=e.offset??0,i=e.limit;for await(let s of this.execute(e.input)){if(t>=n){if(i!==void 0&&t-n>=i)break;yield s}t++}}async*executeDistinct(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeReduced(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeGroup(e){let t=[];for await(let i of this.execute(e.input))t.push(i);let n=this.aggregateExecutor.execute(e,t);if(e.having&&e.having.length>0)for(let i of n)e.having.every(a=>this.filterExecutor.evaluateExpression(a,i)===!0)&&(yield i);else for(let i of n)yield i}async*executeExtend(e){for await(let t of this.execute(e.input)){let n=t.clone(),i=this.evaluateExtendExpression(e.expression,t);i!==void 0&&n.set(e.variable,i),yield n}}async*executeSubquery(e){yield*this.execute(e.query)}async*executeLateralJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t){let i=this.substituteVariables(e.right,n);for await(let s of this.execute(i)){let a=n.merge(s);a!==null&&(yield a)}}}substituteVariables(e,t){let n=JSON.parse(JSON.stringify(e));return this.substituteInOperation(n,t)}substituteInOperation(e,t){return!e||typeof e!="object"?e:e.type==="bgp"&&e.triples?(e.triples=e.triples.map(n=>this.substituteInTriple(n,t)),e):(e.input&&(e.input=this.substituteInOperation(e.input,t)),e.left&&(e.left=this.substituteInOperation(e.left,t)),e.right&&(e.right=this.substituteInOperation(e.right,t)),e.pattern&&(e.pattern=this.substituteInOperation(e.pattern,t)),e.query&&(e.query=this.substituteInOperation(e.query,t)),e.where&&(e.where=this.substituteInOperation(e.where,t)),e)}substituteInTriple(e,t){return{subject:this.substituteInTripleElement(e.subject,t),predicate:e.predicate,object:this.substituteInTripleElement(e.object,t)}}substituteInTripleElement(e,t){if(e&&e.type==="variable"){let n=t.get(e.value);if(n){if(n instanceof y5.IRI||n.termType==="NamedNode")return{type:"iri",value:n.value};if(n.termType==="Literal"||typeof n.value=="string"){let i=n;return{type:"literal",value:i.value,datatype:i.datatype?.value||i._datatype?.value,language:i.language||i._language}}}}return e}async*executeService(e){yield*this.serviceExecutor.execute(e,t=>this.sparqlGenerator.generateSelect(t))}async*executeGraph(e){let t=async function*(n,i){let s=this.currentGraphContext;this.currentGraphContext=i;try{n.type==="bgp"&&i&&this.tripleStore.matchInGraph?yield*this.executeBGPInGraph(n,i):yield*this.execute(n)}finally{this.currentGraphContext=s}}.bind(this);yield*this.graphExecutor.execute(e,t)}async*executeBGPInGraph(e,t){if(e.triples.length===0){let{SolutionMapping:n}=await Promise.resolve().then(()=>s5(Hi()));yield new n;return}yield*this.bgpExecutor.executeInGraph(e,t)}evaluateExtendExpression(e,t){if(e.type!=="aggregate")try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}getExpressionValue(e,t){if(e.type==="variable"){let n=t.get(e.name);return n?n.value??n.id??String(n):void 0}return e.value}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}isConstructQuery(e){return e.type==="construct"}async executeConstruct(e){if(e.type!=="construct")throw new To("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}isAskQuery(e){return e.type==="ask"}async executeAsk(e){if(e.type!=="ask")throw new To("executeAsk requires an ASK operation");for await(let t of this.execute(e.where))return!0;return!1}};gn.QueryExecutor=Py});var hw=_(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.UpdateExecutor=xo.UpdateExecutorError=void 0;var _5=$i(),Ao=Ye(),Dy=ht(),fw=Rt(),hr=class extends Error{static{o(this,"UpdateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="UpdateExecutorError"}};xo.UpdateExecutorError=hr;var Fy=class{static{o(this,"UpdateExecutor")}constructor(e){this.tripleStore=e}async execute(e){if(e.type!=="update")throw new hr("Expected UPDATE request");let t=[];for(let n of e.updates){let i=await this.executeOperation(n);t.push(i)}return t}async executeOperation(e){if("updateType"in e)switch(e.updateType){case"insert":return this.executeInsertData(e);case"delete":return this.executeDeleteData(e);case"insertdelete":throw new hr("INSERT/DELETE with WHERE clause not yet implemented");case"deletewhere":throw new hr("DELETE WHERE not yet implemented");default:throw new hr(`Unknown update type: ${e.updateType}`)}if("type"in e)switch(e.type){case"clear":case"drop":case"load":case"create":case"copy":case"move":case"add":throw new hr(`${e.type.toUpperCase()} operation not yet implemented`);default:throw new hr(`Unknown operation type: ${e.type}`)}throw new hr("Unknown update operation structure")}async executeInsertData(e){if(e.updateType!=="insert")throw new hr("Expected INSERT DATA operation");let t=e,n=0;for(let i of t.insert)if(i.type==="bgp"){let s=this.resolveGraphName(t.graph);n+=await this.insertTriples(i.triples,s)}else if(i.type==="graph"){let s=i,a=this.parseGraphName(s.name);n+=await this.insertTriples(s.triples,a)}return{type:"insert",inserted:n,success:!0}}async executeDeleteData(e){if(e.updateType!=="delete")throw new hr("Expected DELETE DATA operation");let t=e,n=0;for(let i of t.delete)if(i.type==="bgp"){let s=this.resolveGraphName(t.graph);n+=await this.deleteTriples(i.triples,s)}else if(i.type==="graph"){let s=i,a=this.parseGraphName(s.name);n+=await this.deleteTriples(s.triples,a)}return{type:"delete",deleted:n,success:!0}}async insertTriples(e,t){let n=0;for(let i of e){let s=this.convertTriple(i);t&&this.tripleStore.addToGraph?await this.tripleStore.addToGraph(s,t):await this.tripleStore.add(s),n++}return n}async deleteTriples(e,t){let n=0;for(let i of e){let s=this.convertTriple(i),a;t&&this.tripleStore.removeFromGraph?a=await this.tripleStore.removeFromGraph(s,t):a=await this.tripleStore.remove(s),a&&n++}return n}convertTriple(e){return new _5.Triple(this.convertSubject(e.subject),this.convertPredicate(e.predicate),this.convertObject(e.object))}convertSubject(e){if(e.termType==="NamedNode")return new Ao.IRI(e.value);if(e.termType==="BlankNode")return new fw.BlankNode(e.value);throw new hr(`Invalid subject term type: ${e.termType}. Variables are not allowed in INSERT DATA.`)}convertPredicate(e){if("termType"in e&&e.termType==="NamedNode")return new Ao.IRI(e.value);throw new hr("Invalid predicate term type. Only IRIs are allowed in INSERT DATA.")}convertObject(e){if(e.termType==="NamedNode")return new Ao.IRI(e.value);if(e.termType==="BlankNode")return new fw.BlankNode(e.value);if(e.termType==="Literal"){let t=e;return t.language?new Dy.Literal(t.value,void 0,t.language):t.datatype?new Dy.Literal(t.value,new Ao.IRI(t.datatype.value)):new Dy.Literal(t.value)}throw new hr(`Invalid object term type: ${e.termType}. Variables are not allowed in INSERT DATA.`)}resolveGraphName(e){if(e&&!e.default&&e.name)return new Ao.IRI(e.name.value)}parseGraphName(e){if(e.termType==="Variable")throw new hr("Variables are not allowed as graph names in INSERT DATA / DELETE DATA.");return new Ao.IRI(e.value)}};xo.UpdateExecutor=Fy});var pw=_(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});yh.AggregateFunctions=void 0;var Ry=ht(),dw=Ye(),Ny=class{static{o(this,"AggregateFunctions")}static count(e,t){if(!t)return e.length;let n=0;for(let i of e)i.has(t)&&n++;return n}static countDistinct(e,t){let n=new Set;for(let i of e){let s=i.get(t);s&&n.add(s.toString())}return n.size}static sum(e,t){let n=0;for(let i of e){let s=i.get(t);if(s instanceof Ry.Literal){let a=this.toNumber(s);isNaN(a)||(n+=a)}}return n}static avg(e,t){let n=this.sum(e,t),i=this.count(e,t);return i>0?n/i:0}static min(e,t){let n=null;for(let i of e){let s=i.get(t);if(!s)continue;let a=this.toComparable(s);(n===null||a<n)&&(n=a)}return n}static max(e,t){let n=null;for(let i of e){let s=i.get(t);if(!s)continue;let a=this.toComparable(s);(n===null||a>n)&&(n=a)}return n}static groupConcat(e,t,n=" "){let i=[];for(let s of e){let a=s.get(t);a&&(a instanceof Ry.Literal||a instanceof dw.IRI?i.push(a.value):i.push(a.toString()))}return i.join(n)}static sample(e,t){for(let n of e){let i=n.get(t);if(i)return this.toComparable(i)}return null}static sampleDistinct(e,t){return this.sample(e,t)}static toNumber(e){let t=e.datatype?.value;return t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double"),parseFloat(e.value)}static toComparable(e){if(e instanceof Ry.Literal){let t=this.toNumber(e);return isNaN(t)?e.value:t}return e instanceof dw.IRI?e.value:String(e)}};yh.AggregateFunctions=Ny});var mw=_(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});_h.QueryPlanCache=void 0;var v5=Nf(),Ly=class{static{o(this,"QueryPlanCache")}constructor(e=100){this.hits=0,this.misses=0,this.cache=new v5.LRUCache(e)}get(e){let t=this.normalizeQuery(e),n=this.cache.get(t);return n!==void 0?this.hits++:this.misses++,n}set(e,t){let n=this.normalizeQuery(e);this.cache.set(n,t)}has(e){let t=this.normalizeQuery(e);return this.cache.get(t)!==void 0}clear(){this.cache.clear()}getStats(){let e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,size:this.cache.size()}}resetStats(){this.hits=0,this.misses=0}normalizeQuery(e){return e.replace(/\s+/g," ").trim()}};_h.QueryPlanCache=Ly});var gw=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.SPARQLResultCache=void 0;Xc.createSPARQLResultCache=w5;var S5=Nf(),b5={maxSize:500,ttlMs:300*1e3,enableFileInvalidation:!0,maxResultSizeBytes:10*1024*1024},vh=class{static{o(this,"SPARQLResultCache")}constructor(e={}){this.fileToQueries=new Map,this.stats={hits:0,misses:0,evictions:0,ttlInvalidations:0,fileInvalidations:0,totalTimeSavedMs:0},this.avgQueryTimeMs=100,this.options={...b5,...e},this.cache=new S5.LRUCache(this.options.maxSize)}normalizeQuery(e){return e.replace(/\s+/g," ").trim()}hashResult(e){return this.isTripleArray(e)?`T:${e.length}`:`S:${e.length}`}isTripleArray(e){return e.length>0&&"subject"in e[0]}estimateResultSize(e){return this.isTripleArray(e)?e.length*300:e.length*200}get(e){let t=this.normalizeQuery(e),n=this.cache.get(t);if(n===void 0){this.stats.misses++;return}if(Date.now()-n.timestamp>this.options.ttlMs){this.cache.set(t,void 0),this.stats.ttlInvalidations++,this.stats.misses++;return}return this.stats.hits++,this.stats.totalTimeSavedMs+=this.avgQueryTimeMs,n.result}set(e,t,n,i){if(this.estimateResultSize(t)>this.options.maxResultSizeBytes)return;i!==void 0&&(this.avgQueryTimeMs=(this.avgQueryTimeMs+i)/2);let a=this.normalizeQuery(e),c=n??new Set,u={result:t,timestamp:Date.now(),affectedFiles:c,resultHash:this.hashResult(t)};if(this.cache.size()>=this.options.maxSize&&this.stats.evictions++,this.cache.set(a,u),this.options.enableFileInvalidation)for(let f of c){let h=this.fileToQueries.get(f);h||(h=new Set,this.fileToQueries.set(f,h)),h.add(a)}}has(e){let t=this.normalizeQuery(e),n=this.cache.get(t);return n===void 0?!1:Date.now()-n.timestamp<=this.options.ttlMs}invalidateByFile(e){if(!this.options.enableFileInvalidation)return 0;let t=this.fileToQueries.get(e);if(!t)return 0;let n=0;for(let i of t)this.cache.set(i,void 0),n++,this.stats.fileInvalidations++;return this.fileToQueries.delete(e),n}clear(){this.cache.clear(),this.fileToQueries.clear()}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{hits:this.stats.hits,misses:this.stats.misses,hitRate:t,size:this.cache.size(),maxSize:this.options.maxSize,evictions:this.stats.evictions,ttlInvalidations:this.stats.ttlInvalidations,fileInvalidations:this.stats.fileInvalidations,avgTimeSavedMs:this.stats.hits>0?this.stats.totalTimeSavedMs/this.stats.hits:0}}resetStats(){this.stats={hits:0,misses:0,evictions:0,ttlInvalidations:0,fileInvalidations:0,totalTimeSavedMs:0}}size(){return this.cache.size()}pruneExpired(){return 0}};Xc.SPARQLResultCache=vh;function w5(r){return new vh(r)}o(w5,"createSPARQLResultCache")});var yw=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.IncrementalIndexer=void 0;Jc.createIncrementalIndexer=T5;var E5={throttleMs:500,maxBatchSize:100,useContentHashing:!1},Sh=class{static{o(this,"IncrementalIndexer")}constructor(e={}){this.fileMetadata=new Map,this.pendingChanges=[],this.throttleTimer=null,this.invalidateCallbacks=[],this.lastIndexTime=0,this.stats={totalChanges:0,invalidations:0,noOpChanges:0,indexDurations:[]},this.options={...E5,...e}}recordChange(e){this.pendingChanges.push(e),this.stats.totalChanges++,this.throttleTimer===null&&(this.throttleTimer=setTimeout(()=>{this.processPendingChanges(),this.throttleTimer=null},this.options.throttleMs))}processPendingChanges(){if(this.pendingChanges.length===0)return;let e=performance.now(),t=new Map;for(let a of this.pendingChanges)t.set(a.path,a);let n=Array.from(t.values()),i=[];for(let a of n)switch(a.type){case"deleted":this.fileMetadata.delete(a.path),i.push(a);break;case"renamed":a.oldPath&&this.fileMetadata.delete(a.oldPath),i.push(a);break;case"created":case"modified":i.push(a);break}if(i.length>0){this.stats.invalidations+=i.length;for(let a of this.invalidateCallbacks)try{a(i)}catch(c){console.error("IncrementalIndexer: Error in invalidation callback:",c)}}let s=performance.now()-e;this.stats.indexDurations.push(s),this.stats.indexDurations.length>100&&this.stats.indexDurations.shift(),this.lastIndexTime=Date.now(),this.pendingChanges=[]}flush(){this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.processPendingChanges()}updateMetadata(e,t,n,i){this.fileMetadata.set(e,{mtime:t,size:n,contentHash:i})}hasChanged(e,t,n){let i=this.fileMetadata.get(e);return i===void 0||i.mtime!==t||n!==void 0&&i.size!==n}getChangedFiles(e){let t=[];for(let[n,i]of this.fileMetadata.entries())i.mtime>e&&t.push(n);return t}onInvalidate(e){return this.invalidateCallbacks.push(e),()=>{let t=this.invalidateCallbacks.indexOf(e);t!==-1&&this.invalidateCallbacks.splice(t,1)}}getStats(){let e=this.stats.indexDurations,t=e.length>0?e.reduce((i,s)=>i+s,0)/e.length:0,n=e.length>0?e[e.length-1]:0;return{trackedFiles:this.fileMetadata.size,totalChanges:this.stats.totalChanges,invalidations:this.stats.invalidations,noOpChanges:this.stats.noOpChanges,lastIndexDurationMs:n,avgIndexDurationMs:t,lastIndexTime:this.lastIndexTime}}resetStats(){this.stats={totalChanges:0,invalidations:0,noOpChanges:0,indexDurations:[]}}clear(){this.fileMetadata.clear(),this.pendingChanges=[],this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null)}size(){return this.fileMetadata.size}isTracked(e){return this.fileMetadata.has(e)}getMetadata(e){return this.fileMetadata.get(e)}dispose(){this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.invalidateCallbacks=[],this.pendingChanges=[],this.fileMetadata.clear()}};Jc.IncrementalIndexer=Sh;function T5(r){return new Sh(r)}o(T5,"createIncrementalIndexer")});var _w=_(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});Th.ResultSerializer=void 0;var bh=ht(),wh=Ye(),Eh=Rt(),My=class{static{o(this,"ResultSerializer")}serialize(e,t,n={}){switch(t){case"json":return this.serializeJSON(e,n);case"xml":return this.serializeXML(e,n);case"csv":return this.serializeCSV(e,n);case"turtle":return this.serializeTurtle(e,n);default:throw new Error(`Unsupported result format: ${t}`)}}serializeJSON(e,t={}){let n=this.toJSONResultSet(e,t),i=t.pretty?t.indent??2:void 0;return JSON.stringify(n,null,i)}toJSONResultSet(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=e.map(a=>{let c={};for(let u of i){let l=a.get(u);l!==void 0&&(c[u]=this.termToJSONBinding(l))}return c});return{head:{vars:i},results:{bindings:s}}}termToJSONBinding(e){return e instanceof wh.IRI?{type:"uri",value:e.value}:e instanceof Eh.BlankNode?{type:"bnode",value:e.id}:e instanceof bh.Literal?this.literalToJSONBinding(e):{type:"literal",value:String(e)}}literalToJSONBinding(e){let t={type:"literal",value:e.value};return e.datatype?t.datatype=e.datatype.value:e.language&&(t["xml:lang"]=e.language,e.hasDirection()&&e.direction&&(t.direction=e.direction)),t}serializeXML(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=['<?xml version="1.0"?>','<sparql xmlns="http://www.w3.org/2005/sparql-results#">'," <head>"];for(let a of i)s.push(` <variable name="${this.escapeXML(a)}"/>`);s.push(" </head>"),s.push(" <results>");for(let a of e){s.push(" <result>");for(let c of i){let u=a.get(c);u!==void 0&&(s.push(` <binding name="${this.escapeXML(c)}">`),s.push(" "+this.termToXML(u)),s.push(" </binding>"))}s.push(" </result>")}return s.push(" </results>"),s.push("</sparql>"),s.join(`
315
315
  `)}termToXML(e){return e instanceof wh.IRI?`<uri>${this.escapeXML(e.value)}</uri>`:e instanceof Eh.BlankNode?`<bnode>${this.escapeXML(e.id)}</bnode>`:e instanceof bh.Literal?this.literalToXML(e):`<literal>${this.escapeXML(String(e))}</literal>`}literalToXML(e){let t=this.escapeXML(e.value);if(e.datatype)return`<literal datatype="${this.escapeXML(e.datatype.value)}">${t}</literal>`;if(e.language){let n=`xml:lang="${this.escapeXML(e.language)}"`;return e.hasDirection()&&e.direction&&(n+=` direction="${e.direction}"`),`<literal ${n}>${t}</literal>`}return`<literal>${t}</literal>`}serializeCSV(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=[];s.push(i.map(a=>this.escapeCSV(a)).join(","));for(let a of e){let c=i.map(u=>{let l=a.get(u);return l===void 0?"":this.escapeCSV(this.termToCSV(l))});s.push(c.join(","))}return s.join(`
316
316
  `)}termToCSV(e){return e instanceof wh.IRI?e.value:e instanceof Eh.BlankNode?`_:${e.id}`:e instanceof bh.Literal?this.literalToCSV(e):String(e)}literalToCSV(e){if(e.datatype)return`${e.value}^^<${e.datatype.value}>`;if(e.language){let t=e.language;return e.hasDirection()&&e.direction&&(t+=`--${e.direction}`),`${e.value}@${t}`}return e.value}serializeTurtle(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=[];s.push(`# SPARQL Results - ${e.length} solution(s)`),s.push(`# Variables: ${i.join(", ")}`),s.push("");for(let a=0;a<e.length;a++){let c=e[a];s.push(`# Solution ${a+1}`);for(let u of i){let l=c.get(u);l!==void 0&&s.push(`?${u} = ${this.termToTurtle(l)}`)}s.push("")}return s.join(`
317
317
  `).trimEnd()}termToTurtle(e){return e instanceof wh.IRI?`<${e.value}>`:e instanceof Eh.BlankNode?`_:${e.id}`:e instanceof bh.Literal?e.toString():`"${String(e)}"`}escapeXML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}escapeCSV(e){return e.includes(",")||e.includes('"')||e.includes(`
@@ -461,7 +461,7 @@ globstar while`,e,d,t,p,v),this.matchOne(e.slice(d),t.slice(p),n))return this.de
461
461
  ${t}
462
462
  Continue? (y/n): `,s=>{n.close(),i(s.toLowerCase()==="y"||s.toLowerCase()==="yes")})})}};var qd=class{static{o(this,"CLIContainer")}static setup(){ac.container.register(Hu.DI_TOKENS.ILogger,{useFactory:o(()=>new jd("exocortex-cli"),"useFactory")}),ac.container.register(Hu.DI_TOKENS.IEventBus,{useClass:$d}),ac.container.register(Hu.DI_TOKENS.IConfiguration,{useClass:Bd}),ac.container.register(Hu.DI_TOKENS.INotificationService,{useClass:Ud})}static reset(){ac.container.clearInstances()}};function zu(r){qd.setup(),Pa.container.register(Ds.DI_TOKENS.IVaultAdapter,{useFactory:o(()=>new Ti(r),"useFactory")})}o(zu,"setupContainer");function w$(r){if(r.length===0)return"No practices found.";let e=[];for(let t of r){let n="\u2B1C";t.doneToday?n="\u2705":t.inProgressToday&&(n="\u{1F504}");let i=t.estimatedDuration?` (${t.estimatedDuration}m)`:"";e.push(`${n} ${t.label}${i}`)}return e.join(`
463
463
  `)}o(w$,"formatPractices");function E$(r){let e=[`\u{1F4C5} Daily Review: ${r.date}`,"","\u{1F4CA} Tasks:",` Planned: ${r.plannedCount}`,` Completed: ${r.completedCount}`,` In Progress: ${r.inProgressCount}`,` Progress: ${r.completionPercentage}%`,"",`\u23F1\uFE0F Total time: ${Math.round(r.totalTimeMinutes)} minutes`];if(r.practicesDue.length>0){e.push(""),e.push(`\u{1F4CB} Practices due (${r.practicesDue.length}):`);for(let t of r.practicesDue){let n=t.estimatedDuration?` (${t.estimatedDuration}m)`:"";e.push(` \u2B1C ${t.label}${n}`)}}return e.join(`
464
- `)}o(E$,"formatSummary");function Yx(){let r=new It("daily").description("Daily review operations for mobile-friendly workflow");return r.command("practices").description("List today's practices (recurring tasks)").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async e=>{let t=e.format||"text";Y.setFormat(t);try{let n=(0,oc.resolve)(e.vault);if(!(0,cc.existsSync)(n))throw new jt(n);zu(n);let s=await Pa.container.resolve(Ds.DailyReviewService).getPractices();if(t==="json"){let a=$e.success({practices:s,count:s.length});console.log(JSON.stringify(a,null,2))}else console.log(w$(s))}catch(n){Y.handle(n)}}),r.command("summary").description("Show today's daily review summary").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").option("--date <value>","Date in YYYY-MM-DD format (default: today)").action(async e=>{let t=e.format||"text";Y.setFormat(t);try{let n=(0,oc.resolve)(e.vault);if(!(0,cc.existsSync)(n))throw new jt(n);zu(n);let i=Pa.container.resolve(Ds.DailyReviewService),s;if(e.date&&(s=new Date(e.date),isNaN(s.getTime())))throw new st(`Invalid date format: ${e.date}`,"exocortex daily summary --date YYYY-MM-DD",{date:e.date});let a=await i.getDailyReviewSummary(s);if(t==="json"){let c=$e.success(a);console.log(JSON.stringify(c,null,2))}else console.log(E$(a))}catch(n){Y.handle(n)}}),r.command("log").description("Quick capture an activity").argument("<label>","Activity label/description").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").option("--start","Start the task immediately (default: true)").option("--no-start","Don't start the task immediately").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);zu(i);let s=Pa.container.resolve(Ds.DailyReviewService),a=t.start!==!1,c=await s.quickCapture(e,a);if(n==="json"){let u=$e.success(c);console.log(JSON.stringify(u,null,2))}else{let u=c.started?"\u{1F504}":"\u2B1C";console.log(`${u} Created: ${c.label}`),console.log(` Path: ${c.path}`)}}catch(i){Y.handle(i)}}),r.command("start").description("Start a practice (create task instance from prototype)").argument("<prototype-uid>","Practice/prototype UID to start").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);zu(i);let a=await Pa.container.resolve(Ds.DailyReviewService).createFromPractice({prototypeUid:e,startImmediately:!0});if(n==="json"){let c=$e.success(a);console.log(JSON.stringify(c,null,2))}else console.log(`\u{1F504} Started: ${a.label}`),console.log(` Path: ${a.path}`)}catch(i){Y.handle(i)}}),r.command("done").description("Mark a practice as done").argument("<prototype-uid>","Practice/prototype UID to mark as done").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);if(zu(i),await Pa.container.resolve(Ds.DailyReviewService).markPracticeDone(e),n==="json"){let a=$e.success({prototypeUid:e,status:"done"});console.log(JSON.stringify(a,null,2))}else console.log(`\u2705 Marked as done: ${e}`)}catch(i){Y.handle(i)}}),r}o(Yx,"dailyReviewCommand");var Oi=new It;Oi.name("exocortex").description("CLI tool for Exocortex knowledge management system").version("15.14.1");var Qx=Oi.command("sparql").description("SPARQL query execution and cache management");Qx.addCommand(wA());Qx.addCommand(AA());Oi.addCommand(Fx());Oi.addCommand(Lx());Oi.addCommand(Mx());Oi.addCommand(jx());Oi.addCommand($x());Oi.addCommand(Gx());Oi.addCommand(Yx());Oi.parse();
464
+ `)}o(E$,"formatSummary");function Yx(){let r=new It("daily").description("Daily review operations for mobile-friendly workflow");return r.command("practices").description("List today's practices (recurring tasks)").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async e=>{let t=e.format||"text";Y.setFormat(t);try{let n=(0,oc.resolve)(e.vault);if(!(0,cc.existsSync)(n))throw new jt(n);zu(n);let s=await Pa.container.resolve(Ds.DailyReviewService).getPractices();if(t==="json"){let a=$e.success({practices:s,count:s.length});console.log(JSON.stringify(a,null,2))}else console.log(w$(s))}catch(n){Y.handle(n)}}),r.command("summary").description("Show today's daily review summary").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").option("--date <value>","Date in YYYY-MM-DD format (default: today)").action(async e=>{let t=e.format||"text";Y.setFormat(t);try{let n=(0,oc.resolve)(e.vault);if(!(0,cc.existsSync)(n))throw new jt(n);zu(n);let i=Pa.container.resolve(Ds.DailyReviewService),s;if(e.date&&(s=new Date(e.date),isNaN(s.getTime())))throw new st(`Invalid date format: ${e.date}`,"exocortex daily summary --date YYYY-MM-DD",{date:e.date});let a=await i.getDailyReviewSummary(s);if(t==="json"){let c=$e.success(a);console.log(JSON.stringify(c,null,2))}else console.log(E$(a))}catch(n){Y.handle(n)}}),r.command("log").description("Quick capture an activity").argument("<label>","Activity label/description").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").option("--start","Start the task immediately (default: true)").option("--no-start","Don't start the task immediately").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);zu(i);let s=Pa.container.resolve(Ds.DailyReviewService),a=t.start!==!1,c=await s.quickCapture(e,a);if(n==="json"){let u=$e.success(c);console.log(JSON.stringify(u,null,2))}else{let u=c.started?"\u{1F504}":"\u2B1C";console.log(`${u} Created: ${c.label}`),console.log(` Path: ${c.path}`)}}catch(i){Y.handle(i)}}),r.command("start").description("Start a practice (create task instance from prototype)").argument("<prototype-uid>","Practice/prototype UID to start").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);zu(i);let a=await Pa.container.resolve(Ds.DailyReviewService).createFromPractice({prototypeUid:e,startImmediately:!0});if(n==="json"){let c=$e.success(a);console.log(JSON.stringify(c,null,2))}else console.log(`\u{1F504} Started: ${a.label}`),console.log(` Path: ${a.path}`)}catch(i){Y.handle(i)}}),r.command("done").description("Mark a practice as done").argument("<prototype-uid>","Practice/prototype UID to mark as done").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);if(zu(i),await Pa.container.resolve(Ds.DailyReviewService).markPracticeDone(e),n==="json"){let a=$e.success({prototypeUid:e,status:"done"});console.log(JSON.stringify(a,null,2))}else console.log(`\u2705 Marked as done: ${e}`)}catch(i){Y.handle(i)}}),r}o(Yx,"dailyReviewCommand");var Oi=new It;Oi.name("exocortex").description("CLI tool for Exocortex knowledge management system").version("15.15.1");var Qx=Oi.command("sparql").description("SPARQL query execution and cache management");Qx.addCommand(wA());Qx.addCommand(AA());Oi.addCommand(Fx());Oi.addCommand(Lx());Oi.addCommand(Mx());Oi.addCommand(jx());Oi.addCommand($x());Oi.addCommand(Gx());Oi.addCommand(Yx());Oi.parse();
465
465
  /*! Bundled license information:
466
466
 
467
467
  reflect-metadata/Reflect.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kitelev/exocortex-cli",
3
- "version": "15.14.1",
3
+ "version": "15.15.1",
4
4
  "description": "CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more",
5
5
  "main": "dist/index.js",
6
6
  "bin": {