@kitelev/exocortex-cli 16.96.1 → 16.96.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @kitelev/exocortex-cli v16.96.
|
|
2
|
+
// @kitelev/exocortex-cli v16.96.2
|
|
3
3
|
// CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
|
|
4
4
|
// License: MIT
|
|
5
5
|
|
|
@@ -45,7 +45,7 @@ Expecting `+jp.join(", ")+", got '"+(this.terminals_[gt]||gt)+"'":Tb="Parse erro
|
|
|
45
45
|
`)+`
|
|
46
46
|
`+s.trimStart()),s}findPrefixStarDeclarations(e){let t=[],r=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(r.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 o=i;for(;i<e.length&&e[i]!==">";)i++;if(e[i]===">"){let c=e.substring(o,i);i++;let l=this.findDeclarationEnd(e,i);t.push({uri:c,startPos:s,endPos:l}),i=l;continue}else throw new ll(`Unclosed IRI in PREFIX* declaration at position ${o}`)}else throw new ll(`Expected IRI after PREFIX* at position ${i}`)}else continue}i++}return t}findDeclarationEnd(e,t){let r=t;for(;r<e.length;){let i=e[r];if(i===`
|
|
47
47
|
`)return r+1;let s=e.substring(r).toUpperCase();if(s.startsWith("PREFIX")||s.startsWith("BASE")||s.startsWith("SELECT")||s.startsWith("CONSTRUCT")||s.startsWith("DESCRIBE")||s.startsWith("ASK"))return r;if(/\s/.test(i)){r++;continue}break}return r}extractPrefixFromUri(e){let t=e.replace(/^https?:\/\//,"");t=t.replace(/\/$/,"").replace(/#$/,"");let r=t.split(/[/.#]+/).filter(Boolean);if(r.length===0)return null;let i=r[r.length-1];return/^(ontology|vocab|schema|ns|core)$/i.test(i)&&r.length>1?r[r.length-2].toLowerCase():i.toLowerCase().replace(/[^a-z0-9]/g,"")}};Yo.PrefixStarTransformer=DS;var ll=class extends Error{static{a(this,"PrefixStarTransformerError")}constructor(e){super(`PREFIX* transformation error: ${e}`),this.name="PrefixStarTransformerError"}};Yo.PrefixStarTransformerError=ll});var FS=w(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.DescribeOptionsTransformer=fl.DescribeOptionsTransformerError=void 0;var Wh=class extends Error{static{a(this,"DescribeOptionsTransformerError")}constructor(e){super(e),this.name="DescribeOptionsTransformerError"}};fl.DescribeOptionsTransformerError=Wh;var ul=class n{static{a(this,"DescribeOptionsTransformer")}transform(e){if(!n.DESCRIBE_QUERY_PATTERN.test(e))return{query:e};let t=e,r={},i=!1,s=n.DEPTH_PATTERN.exec(e);if(s){let o=parseInt(s[1],10);if(o<0)throw new Wh(`DESCRIBE DEPTH must be a non-negative integer, got: ${o}`);r.depth=o,i=!0,n.DEPTH_PATTERN.lastIndex=0,t=t.replace(n.DEPTH_PATTERN,"")}return n.DEPTH_PATTERN.lastIndex=0,n.SYMMETRIC_PATTERN.test(e)&&(r.symmetric=!0,i=!0,n.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(n.SYMMETRIC_PATTERN,"")),n.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(/\s{2,}/g," ").trim(),{query:t,options:i?r:void 0}}hasDescribeOptions(e){let t=n.DEPTH_PATTERN.test(e);n.DEPTH_PATTERN.lastIndex=0;let r=n.SYMMETRIC_PATTERN.test(e);return n.SYMMETRIC_PATTERN.lastIndex=0,t||r}};fl.DescribeOptionsTransformer=ul;ul.DEPTH_PATTERN=/\bDEPTH\s+(\d+)/gi;ul.SYMMETRIC_PATTERN=/\bSYMMETRIC\b/gi;ul.DESCRIBE_QUERY_PATTERN=/\bDESCRIBE\b/i});var uR=w(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});dl.DirectionalLangTagTransformerError=dl.DirectionalLangTagTransformer=void 0;var zh=class n{static{a(this,"DirectionalLangTagTransformer")}constructor(){this.directionMappings=new Map}transform(e){return this.directionMappings.clear(),e.replace(n.DIRECTIONAL_TAG_REGEX,(t,r,i,s,o)=>{let c=s.toLowerCase();return this.directionMappings.set(c,o),`${r}${i}${r}@${s}`})}getDirection(e){return this.directionMappings.get(e.toLowerCase())}getAllMappings(){return new Map(this.directionMappings)}hasDirectionalTags(e){return n.DIRECTIONAL_TAG_REGEX.lastIndex=0,n.DIRECTIONAL_TAG_REGEX.test(e)}clearMappings(){this.directionMappings.clear()}};dl.DirectionalLangTagTransformer=zh;zh.DIRECTIONAL_TAG_REGEX=/(["'])((?:[^\\]|\\.)*?)\1@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)--(ltr|rtl)/g;var LS=class extends Error{static{a(this,"DirectionalLangTagTransformerError")}constructor(e){super(`Directional language tag transformation error: ${e}`),this.name="DirectionalLangTagTransformerError"}};dl.DirectionalLangTagTransformerError=LS});var fR=w(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});hl.TripleTermTransformerError=hl.TripleTermTransformer=void 0;var NS=class{static{a(this,"TripleTermTransformer")}transform(e){let t=e,r,i=0,s=100;do if(r=t,t=this.transformSinglePass(t),i++,i>s)throw new pl("Too many nested triple terms (max 100 iterations)");while(t!==r);return t}hasTripleTermSyntax(e){return this.findTripleTermPositions(e).length>0}transformSinglePass(e){let t=this.findTripleTermPositions(e);if(t.length===0)return e;let r=e;for(let i=t.length-1;i>=0;i--){let s=t[i],o=this.extractTripleTerm(r,s);if(o){let c=this.convertToStandardSyntax(o.content);r=r.substring(0,s)+c+r.substring(s+o.length)}}return r}findTripleTermPositions(e){let t=[],r=0;for(;r<e.length;){if(e[r]==="'"){r=this.skipStringLiteral(e,r,"'");continue}if(e[r]==='"'){r=this.skipStringLiteral(e,r,'"');continue}if(e.substring(r,r+2)==="<<"&&this.isParenthesizedTripleTerm(e,r)){t.push(r),r+=2;continue}r++}return t}skipStringLiteral(e,t,r){let i=r.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]!==r;)e[t]==="\\"&&t++,t++;return t+1}isParenthesizedTripleTerm(e,t){let r=t+2;for(;r<e.length&&/\s/.test(e[r]);)r++;return e[r]==="("}extractTripleTerm(e,t){let r=t+2;for(;r<e.length&&/\s/.test(e[r]);)r++;if(e[r]!=="(")return null;r++;let i=1;for(;r<e.length&&i>0;){if(e[r]==="'"||e[r]==='"'){r=this.skipStringLiteral(e,r,e[r]);continue}if(e.substring(r,r+2)==="<<"&&this.isParenthesizedTripleTerm(e,r)){for(r+=2;r<e.length&&/\s/.test(e[r]);)r++;e[r]==="("&&(i++,r++);continue}if(e.substring(r,r+2)==="<<"){r+=2;let s=1;for(;r<e.length&&s>0;){if(e[r]==="'"||e[r]==='"'){r=this.skipStringLiteral(e,r,e[r]);continue}if(e.substring(r,r+2)==="<<"){s++,r+=2;continue}if(e.substring(r,r+2)===">>"){s--,r+=2;continue}r++}continue}if(e[r]==="("){i++,r++;continue}if(e[r]===")"){let s=r+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e.substring(s,s+2)===">>"){if(i--,i===0){let o=e.substring(t,s+2);return{content:o,length:o.length}}r=s+2;continue}r++;continue}r++}if(i>0)throw new pl(`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 pl(`Invalid triple term syntax: ${e.substring(0,50)}...`);return`<< ${t[1]} >>`}};hl.TripleTermTransformer=NS;var pl=class extends Error{static{a(this,"TripleTermTransformerError")}constructor(e){super(`Triple term transformation error: ${e}`),this.name="TripleTermTransformerError"}};hl.TripleTermTransformerError=pl});var MS=w(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});Hh.VaultPrefixTransformer=void 0;var M6=/PREFIX\s+(\w+)\s*:/gi,j6=new Set(["mailto","http","https","urn","ftp","prefix","base","select","construct","describe","ask","where","filter","optional","union","graph","order","group","having","limit","offset","values","bind","minus","service","insert","delete","load","clear","drop","create","move","copy","add"]),kS=class{static{a(this,"VaultPrefixTransformer")}constructor(){this.vaultPrefixes=new Map}setVaultPrefixes(e){this.vaultPrefixes=new Map(e)}getVaultPrefixes(){return new Map(this.vaultPrefixes)}transform(e){if(this.vaultPrefixes.size===0)return e;let t=this.findDeclaredPrefixes(e),r=[];for(let[o,c]of this.vaultPrefixes)!t.has(o.toLowerCase())&&!j6.has(o.toLowerCase())&&r.push({prefix:o,baseIRI:c});if(r.length===0)return e;let i="",s=0;for(;s<e.length;){let o=e[s];if(o==='"'||o==="'"){let l=this.skipLiteral(e,s);i+=e.substring(s,l),s=l;continue}if(o==="<"){let l=e.indexOf(">",s);l!==-1?(i+=e.substring(s,l+1),s=l+1):(i+=o,s++);continue}if(o==="#"){let l=e.indexOf(`
|
|
48
|
-
`,s);l!==-1?(i+=e.substring(s,l),s=l):(i+=e.substring(s),s=e.length);continue}let c=this.tryReplacePrefixedName(e,s,r);if(c){i+=c.iri,s=c.endIndex;continue}i+=o,s++}return i}tryReplacePrefixedName(e,t,r){if(t>0&&/[a-zA-Z0-9_]/.test(e[t-1]))return null;for(let{prefix:i,baseIRI:s}of r){if(e.substring(t,t+i.length+1)!==i+":")continue;let o=t+i.length+1,c=o;for(;c<e.length&&/[a-zA-Z0-9_.%-]/.test(e[c]);)c++;if(c===o)continue;let l=e.substring(o,c);return{iri:`<${s}${l}.md>`,endIndex:c}}return null}findDeclaredPrefixes(e){let t=new Set,r=new RegExp(M6.source,"gi"),i;for(;(i=r.exec(e))!==null;)t.add(i[1].toLowerCase());return t}skipLiteral(e,t){let r=e[t];if(t+2<e.length&&e.substring(t,t+3)===r+r+r){let s=e.indexOf(r+r+r,t+3);return s!==-1?s+3:e.length}let i=t+1;for(;i<e.length&&e[i]!==r;)e[i]==="\\"&&i++,i++;return i<e.length?i+1:e.length}};Hh.VaultPrefixTransformer=kS});var ml=w(Ln=>{"use strict";var $6=Ln&&Ln.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:a(function(){return e[t]},"get")}),Object.defineProperty(n,r,i)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),U6=Ln&&Ln.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),B6=Ln&&Ln.__importStar||(function(){var n=a(function(e){return n=Object.getOwnPropertyNames||function(t){var r=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[r.length]=i);return r},n(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=n(e),i=0;i<r.length;i++)r[i]!=="default"&&$6(t,e,r[i]);return U6(t,e),t}})();Object.defineProperty(Ln,"__esModule",{value:!0});Ln.SPARQLParser=Ln.ExoQLParser=Ln.SPARQLParseError=void 0;var dR=B6(cR()),jS=PS(),$S=OS(),pR=lR(),US=FS(),V6=uR(),BS=fR(),G6=MS(),pr=class extends Error{static{a(this,"SPARQLParseError")}constructor(e,t,r,i){super(e,i?{cause:i}:void 0),this.name="SPARQLParseError",this.line=t,this.column=r}};Ln.SPARQLParseError=pr;var Kh=class{static{a(this,"ExoQLParser")}constructor(e){this.lastDirectionMappings=new Map,this.parser=new dR.Parser({sparqlStar:!0}),this.generator=new dR.Generator({sparqlStar:!0}),this.caseWhenTransformer=new jS.CaseWhenTransformer,this.lateralTransformer=new $S.LateralTransformer,this.prefixStarTransformer=new pR.PrefixStarTransformer(e?.vocabularyResolver),this.describeOptionsTransformer=new US.DescribeOptionsTransformer,this.directionalLangTagTransformer=new V6.DirectionalLangTagTransformer,this.tripleTermTransformer=new BS.TripleTermTransformer,this.vaultPrefixTransformer=new G6.VaultPrefixTransformer}setVaultPrefixes(e){this.vaultPrefixTransformer.setVaultPrefixes(e)}parse(e){try{let t=this.vaultPrefixTransformer.transform(e),r=this.describeOptionsTransformer.transform(t);this.lastDescribeOptions=r.options;let i=r.query;i=this.directionalLangTagTransformer.transform(i),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),i=this.lateralTransformer.transform(i),i=this.caseWhenTransformer.transform(i),i=this.tripleTermTransformer.transform(i);let s=this.parser.parse(i);return this.validateQuery(s),this.lastDescribeOptions&&this.isDescribeQuery(s)&&(s.describeOptions=this.lastDescribeOptions),s}catch(t){if(t instanceof US.DescribeOptionsTransformerError)throw new pr(t.message);if(t instanceof $S.LateralTransformerError)throw new pr(t.message);if(t instanceof jS.CaseWhenTransformerError)throw new pr(t.message);if(t instanceof BS.TripleTermTransformerError)throw new pr(t.message);if(t instanceof Error){let r=t.message.match(/line (\d+), column (\d+)/),i=r?parseInt(r[1],10):void 0,s=r?parseInt(r[2],10):void 0;throw new pr(`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.vaultPrefixTransformer.transform(e),r=this.describeOptionsTransformer.transform(t);this.lastDescribeOptions=r.options;let i=r.query;i=this.directionalLangTagTransformer.transform(i),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),i=await this.prefixStarTransformer.transform(i),i=this.lateralTransformer.transform(i),i=this.caseWhenTransformer.transform(i),i=this.tripleTermTransformer.transform(i);let s=this.parser.parse(i);return this.validateQuery(s),this.lastDescribeOptions&&this.isDescribeQuery(s)&&(s.describeOptions=this.lastDescribeOptions),s}catch(t){if(t instanceof US.DescribeOptionsTransformerError)throw new pr(t.message);if(t instanceof pR.PrefixStarTransformerError)throw new pr(t.message);if(t instanceof $S.LateralTransformerError)throw new pr(t.message);if(t instanceof jS.CaseWhenTransformerError)throw new pr(t.message);if(t instanceof BS.TripleTermTransformerError)throw new pr(t.message);if(t instanceof Error){let r=t.message.match(/line (\d+), column (\d+)/),i=r?parseInt(r[1],10):void 0,s=r?parseInt(r[2],10):void 0;throw new pr(`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 pr(`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 pr("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 pr("Invalid query: not an object");if(e.type!=="query"&&e.type!=="update")throw new pr(`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 pr(`Invalid query type: expected one of ${t.join(", ")}, got "${e.queryType}"`)}}};Ln.ExoQLParser=Kh;Ln.SPARQLParser=Kh});var ic=w(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});Qh.AlgebraTranslatorError=void 0;var VS=class extends Error{static{a(this,"AlgebraTranslatorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AlgebraTranslatorError"}};Qh.AlgebraTranslatorError=VS});var Xh=w(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.isVariableExpression=q6;bs.isVariableTerm=W6;bs.isNamedNode=z6;bs.isLiteral=H6;bs.isPropertyPath=K6;bs.isAggregateExpression=Q6;bs.isOperationExpression=X6;bs.isFunctionCallExpression=Y6;function q6(n){return typeof n=="object"&&n!==null&&"expression"in n&&"variable"in n}a(q6,"isVariableExpression");function W6(n){return typeof n=="object"&&n!==null&&"termType"in n&&n.termType==="Variable"}a(W6,"isVariableTerm");function z6(n){return typeof n=="object"&&n!==null&&"termType"in n&&n.termType==="NamedNode"}a(z6,"isNamedNode");function H6(n){return typeof n=="object"&&n!==null&&"termType"in n&&n.termType==="Literal"}a(H6,"isLiteral");function K6(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="path"}a(K6,"isPropertyPath");function Q6(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="aggregate"}a(Q6,"isAggregateExpression");function X6(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="operation"}a(X6,"isOperationExpression");function Y6(n){return typeof n=="object"&&n!==null&&"type"in n&&(n.type==="functionCall"||n.type==="functioncall")}a(Y6,"isFunctionCallExpression")});var hR=w(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});Yh.TripleTranslator=void 0;var pn=ic(),GS=class{static{a(this,"TripleTranslator")}constructor(){this.directionMappings=new Map}setDirectionMappings(e){this.directionMappings=e}translateBGP(e){if(!("triples"in e)||!Array.isArray(e.triples))throw new pn.AlgebraTranslatorError("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 pn.AlgebraTranslatorError("Triple must have subject, predicate, and object");return{subject:this.translateTripleElement(e.subject),predicate:this.translatePredicate(e.predicate),object:this.translateTripleElement(e.object)}}translateConstructTemplate(e){return!e||!Array.isArray(e)?[]:e.map(t=>this.translateTriple(t))}translatePredicate(e){return"type"in e&&e.type==="path"?this.translatePropertyPath(e):this.translateTripleElement(e)}translatePropertyPath(e){if(!("pathType"in e)||!e.pathType)throw new pn.AlgebraTranslatorError("Property path must have pathType");if(!("items"in e)||!Array.isArray(e.items))throw new pn.AlgebraTranslatorError("Property path must have items array");let t=e.items.map(r=>this.translatePathItem(r));switch(e.pathType){case"/":return{type:"path",pathType:"/",items:t};case"|":return{type:"path",pathType:"|",items:t};case"^":if(t.length!==1)throw new pn.AlgebraTranslatorError("Inverse path must have exactly one item");return{type:"path",pathType:"^",items:[t[0]]};case"+":if(t.length!==1)throw new pn.AlgebraTranslatorError("OneOrMore path must have exactly one item");return{type:"path",pathType:"+",items:[t[0]]};case"*":if(t.length!==1)throw new pn.AlgebraTranslatorError("ZeroOrMore path must have exactly one item");return{type:"path",pathType:"*",items:[t[0]]};case"?":if(t.length!==1)throw new pn.AlgebraTranslatorError("ZeroOrOne path must have exactly one item");return{type:"path",pathType:"?",items:[t[0]]};default:throw new pn.AlgebraTranslatorError(`Unsupported property path type: ${e.pathType}`)}}translatePathItem(e){if("type"in e&&e.type==="path")return this.translatePropertyPath(e);if("termType"in e&&e.termType==="NamedNode")return{type:"iri",value:e.value};let t="type"in e?e.type:"termType"in e?e.termType:"unknown";throw new pn.AlgebraTranslatorError(`Unsupported path item type: ${String(t)}`)}translateTripleElement(e){if(!e||!("termType"in e))throw new pn.AlgebraTranslatorError("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 r=this.directionMappings.get(e.language.toLowerCase());r&&(t.direction=r)}return t}case"BlankNode":return{type:"blank",value:e.value};case"Quad":return this.translateQuotedTriple(e);default:throw new pn.AlgebraTranslatorError(`Unsupported term type: ${e.termType}`)}}translateQuotedTriple(e){if(!e.subject||!e.predicate||!e.object)throw new pn.AlgebraTranslatorError("Quoted triple must have subject, predicate, and object");return{type:"quoted",subject:this.translateTripleElement(e.subject),predicate:this.translateQuotedTriplePredicate(e.predicate),object:this.translateTripleElement(e.object)}}translateQuotedTriplePredicate(e){if(!e||!("termType"in e))throw new pn.AlgebraTranslatorError("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 pn.AlgebraTranslatorError(`Quoted triple predicate must be IRI or Variable, got: ${e.termType}`)}}};Yh.TripleTranslator=GS});var mR=w(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0});Jh.ExpressionTranslator=void 0;var gl=ic(),qS=class{static{a(this,"ExpressionTranslator")}constructor(e){this.translateWhereFn=e.translateWhere,this.translateBGPFn=e.translateBGP,this.translatePatternFn=e.translatePattern}translateExpression(e){if(!e)throw new gl.AlgebraTranslatorError("Expression cannot be null or undefined");if("type"in e&&e.type==="operation")return this.translateOperationExpression(e);let t="type"in e?e.type:void 0;if(t==="functioncall"||t==="functionCall"){let r=e;return{type:"functionCall",function:r.function,args:r.args.map(i=>this.translateExpression(i))}}if("termType"in e)return this.translateTermExpression(e);throw new gl.AlgebraTranslatorError(`Unsupported expression structure: ${JSON.stringify(e)}`)}translateFilter(e){if(!e.expression)throw new gl.AlgebraTranslatorError("Filter pattern must have expression");let t={type:"bgp",triples:[]};return{type:"filter",expression:this.translateExpression(e.expression),input:t}}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)}}translateOperationExpression(e){let t=["=","!=","<",">","<=",">="],r=["&&","||","!"],i=["+","-","*","/"],s=e.args.filter(o=>!("patterns"in o)||"termType"in o);return t.includes(e.operator)?{type:"comparison",operator:e.operator,left:this.translateExpression(s[0]),right:this.translateExpression(s[1])}:r.includes(e.operator)?{type:"logical",operator:e.operator,operands:s.map(o=>this.translateExpression(o))}:i.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:this.translateExpression(s[0]),right:this.translateExpression(s[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:s.map(o=>this.translateExpression(o))}}translateExistsExpression(e){if(!e.args||e.args.length!==1)throw new gl.AlgebraTranslatorError("EXISTS/NOT EXISTS must have exactly one pattern argument");let t=e.args[0],r;return t.type==="group"&&"patterns"in t&&t.patterns?r=this.translateWhereFn(t.patterns):t.type==="bgp"?r=this.translateBGPFn(t):r=this.translatePatternFn(t),{type:"exists",negated:e.operator==="notexists",pattern:r}}translateInExpression(e){if(!e.args||e.args.length!==2)throw new gl.AlgebraTranslatorError("IN/NOT IN must have exactly 2 arguments (expression and list)");let t=e.args[0],r=e.args[1];if(!Array.isArray(r))throw new gl.AlgebraTranslatorError("IN/NOT IN second argument must be an array of values");return{type:"in",expression:this.translateExpression(t),list:r.map(i=>this.translateExpression(i)),negated:e.operator==="notin"}}};Jh.ExpressionTranslator=qS});var bR=w(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});Zh.PatternTranslator=void 0;var gR=OS(),$r=ic(),yR=Xh(),WS=class{static{a(this,"PatternTranslator")}constructor(e){this.directionMappings=new Map,this.translateExpressionFn=e.translateExpression,this.translateSelectFn=e.translateSelect,this.translateBGPFn=e.translateBGP}setDirectionMappings(e){this.directionMappings=e}translateWhere(e){if(e.length===0)throw new $r.AlgebraTranslatorError("Empty WHERE clause");let t=e.filter(o=>o.type==="filter"),r=e.filter(o=>o.type==="bind"),i=e.filter(o=>o.type!=="filter"&&o.type!=="bind"),s;if(i.length===0)s={type:"bgp",triples:[]};else if(i.length===1)if(i[0].type==="optional"){let o=i[0].expression;s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:o?this.translateExpressionFn(o):void 0}}else s=this.translatePattern(i[0]);else{if(i[0].type==="optional"){let o=i[0].expression;s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:o?this.translateExpressionFn(o):void 0}}else s=this.translatePattern(i[0]);for(let o=1;o<i.length;o++){let c=i[o];if(this.isLateralPattern(c)){let l=this.extractLateralSubquery(c),u=this.removeLateralMarker(l),f=this.translateSelectFn(u);s={type:"lateraljoin",left:s,right:f}}else if(c.type==="optional"){let l=c.expression;s={type:"leftjoin",left:s,right:this.translateWhere(c.patterns),expression:l?this.translateExpressionFn(l):void 0}}else{let l=this.translatePattern(c);s={type:"join",left:s,right:l}}}}for(let o of r)s=this.translateBind(o,s);for(let o of t)s={type:"filter",expression:this.translateExpressionFn(o.expression),input:s};return s}translatePattern(e){if(!e||!e.type)throw new $r.AlgebraTranslatorError("Invalid pattern: missing type");switch(e.type){case"bgp":return this.translateBGPFn(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 $r.AlgebraTranslatorError(`Unsupported pattern type: ${e.type}`)}}translateFilter(e){if(!e.expression)throw new $r.AlgebraTranslatorError("Filter pattern must have expression");let t={type:"bgp",triples:[]};return{type:"filter",expression:this.translateExpressionFn(e.expression),input:t}}translateOptional(e){if(!e.patterns||e.patterns.length===0)throw new $r.AlgebraTranslatorError("OPTIONAL pattern must have patterns");let t=e.expression;return{type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns),expression:t?this.translateExpressionFn(t):void 0}}translateUnion(e){if(!e.patterns||e.patterns.length<2)throw new $r.AlgebraTranslatorError("UNION pattern must have at least 2 patterns");let t=a(i=>i.type==="graph"?this.translateGraph(i):i.type==="service"?this.translateService(i):"patterns"in i&&i.patterns&&Array.isArray(i.patterns)?this.translateWhere(i.patterns):this.translateWhere([i]),"translateBranch"),r={type:"union",left:t(e.patterns[0]),right:t(e.patterns[1])};for(let i=2;i<e.patterns.length;i++)r={type:"union",left:r,right:t(e.patterns[i])};return r}translateMinus(e){if(!e.patterns||e.patterns.length===0)throw new $r.AlgebraTranslatorError("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 $r.AlgebraTranslatorError("VALUES pattern must have values array");let t=new Set;for(let i of e.values)for(let s of Object.keys(i)){let o=s.startsWith("?")?s.slice(1):s;t.add(o)}let r=e.values.map(i=>this.translateValuesBinding(i));return{type:"values",variables:Array.from(t),bindings:r}}translateValuesBinding(e){let t={};for(let[r,i]of Object.entries(e)){let s=r.startsWith("?")?r.slice(1):r,o=i;if(o)if(o.termType==="NamedNode")t[s]={type:"iri",value:o.value};else if(o.termType==="Literal"){let c=o,l={type:"literal",value:c.value,datatype:c.datatype?.value,language:c.language||void 0};if(c.language){let u=this.directionMappings.get(c.language.toLowerCase());u&&(l.direction=u)}t[s]=l}else throw new $r.AlgebraTranslatorError(`Unsupported VALUES term type: ${o.termType}`)}return t}translateBind(e,t){if(!e.variable||!e.expression)throw new $r.AlgebraTranslatorError("BIND pattern must have variable and expression");return{type:"extend",variable:e.variable.value,expression:this.translateExpressionFn(e.expression),input:t}}translateSubquery(e){if(e.queryType!=="SELECT")throw new $r.AlgebraTranslatorError(`Only SELECT subqueries are supported, got: ${String(e.queryType)}`);let t=this.removeLateralMarker(e);return{type:"subquery",query:this.translateSelectFn(t)}}translateService(e){if(!e.name||e.name.termType!=="NamedNode")throw new $r.AlgebraTranslatorError("SERVICE pattern must have a NamedNode endpoint");if(!e.patterns||!Array.isArray(e.patterns))throw new $r.AlgebraTranslatorError("SERVICE pattern must have patterns array");return{type:"service",endpoint:e.name.value,pattern:this.translateWhere(e.patterns),silent:e.silent||!1}}translateGraph(e){if(!e.name)throw new $r.AlgebraTranslatorError("GRAPH pattern must have a name (IRI or variable)");if(!e.patterns||!Array.isArray(e.patterns))throw new $r.AlgebraTranslatorError("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 $r.AlgebraTranslatorError(`GRAPH pattern name must be NamedNode or Variable, got: ${e.name.termType}`);return{type:"graph",name:t,pattern:this.translateWhere(e.patterns)}}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){let t=e.patterns[0];if(t.type==="query")return t}throw new $r.AlgebraTranslatorError("Invalid lateral pattern structure")}isLateralSubquery(e){return!("queryType"in e)||e.queryType!=="SELECT"||!("variables"in e)||!e.variables?!1:e.variables.some(i=>(0,yR.isVariableTerm)(i)&&i.value===gR.LateralTransformer.LATERAL_MARKER)}removeLateralMarker(e){if(!("variables"in e)||!e.variables)return e;let t=e,r=t.variables;return{...t,variables:r.filter(i=>!((0,yR.isVariableTerm)(i)&&i.value===gR.LateralTransformer.LATERAL_MARKER))}}};Zh.PatternTranslator=WS});var SR=w(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.AggregateTranslator=void 0;var _R=ic(),J6=Xh(),zS=class{static{a(this,"AggregateTranslator")}constructor(e){this.aggregateCounter=0,this.translateExpressionFn=e.translateExpression}resetCounter(){this.aggregateCounter=0}extractAggregatesWithMapping(e,t){if(!e)return[];let r=[];for(let i of e)(0,J6.isVariableExpression)(i)&&("type"in i.expression&&i.expression.type==="aggregate"?(r.push({variable:i.variable.value,expression:this.translateAggregateExpression(i.expression)}),t.set(i.expression,i.variable.value)):this.collectNestedAggregates(i.expression,r,t));return r}extractGroupVariables(e){return e?e.filter(t=>t.expression&&"termType"in t.expression&&t.expression.termType==="Variable").map(t=>t.expression.value):[]}extractHavingExpressions(e,t,r){if(!e||e.length===0)return[];for(let i of e)this.collectNestedAggregates(i,t,r);return e.map(i=>this.transformExpressionWithAggregateVars(i,r))}transformExpressionWithAggregateVars(e,t){let r=t.get(e);if(r!==void 0)return{type:"variable",name:r};if("type"in e&&e.type==="operation"&&"args"in e){let i=e,s=i.args.filter(u=>!Array.isArray(u)&&!("patterns"in u)).map(u=>this.transformExpressionWithAggregateVars(u,t)),o=["=","!=","<",">","<=",">="],c=["&&","||","!"],l=["+","-","*","/"];return o.includes(i.operator)?{type:"comparison",operator:i.operator,left:s[0],right:s[1]}:c.includes(i.operator)?{type:"logical",operator:i.operator,operands:s}:l.includes(i.operator)?{type:"arithmetic",operator:i.operator,left:s[0],right:s[1]}:{type:"function",function:i.operator,args:s}}return this.translateExpressionFn(e)}translateOrderComparator(e){return{expression:this.translateExpressionFn(e.expression),descending:e.descending||!1}}translateAggregateExpression(e){let t=e.aggregation,r=a(()=>{if(e.expression&&!("termType"in e.expression&&e.expression.termType==="Wildcard"))return this.translateExpressionFn(e.expression)},"translateInnerExpr");if(typeof t=="string"){let s=t.toLowerCase();return["count","sum","avg","min","max","group_concat","sample"].includes(s)?{type:"aggregate",aggregation:s,expression:r(),distinct:e.distinct||!1,separator:e.separator}:{type:"aggregate",aggregation:{type:"custom",iri:t},expression:r(),distinct:e.distinct||!1,separator:e.separator}}let i=t;if(i&&typeof i=="object"){let s,o=i;if(o.termType==="NamedNode"&&typeof o.value=="string")s=o.value;else if("value"in o)s=String(o.value);else throw new _R.AlgebraTranslatorError(`Invalid custom aggregate: expected IRI but got ${JSON.stringify(i)}`);return{type:"aggregate",aggregation:{type:"custom",iri:s},expression:r(),distinct:e.distinct||!1,separator:e.separator}}throw new _R.AlgebraTranslatorError(`Unknown aggregate format: ${JSON.stringify(t)}`)}collectNestedAggregates(e,t,r){if(e){if("type"in e&&e.type==="aggregate"){let i=`__agg${this.aggregateCounter++}`;t.push({variable:i,expression:this.translateAggregateExpression(e)}),r.set(e,i)}else if("type"in e&&e.type==="operation"&&"args"in e){let i=e;for(let s of i.args)!Array.isArray(s)&&"type"in s&&!("patterns"in s)?this.collectNestedAggregates(s,t,r):"termType"in s&&this.collectNestedAggregates(s,t,r)}}}};em.AggregateTranslator=zS});var yl=w(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.AlgebraTranslator=Jo.ExoQLAlgebraTranslator=Jo.AlgebraTranslatorError=void 0;var tm=ic(),rm=Xh(),Z6=hR(),e7=mR(),t7=bR(),r7=SR(),n7=ic();Object.defineProperty(Jo,"AlgebraTranslatorError",{enumerable:!0,get:a(function(){return n7.AlgebraTranslatorError},"get")});var nm=class{static{a(this,"ExoQLAlgebraTranslator")}constructor(){this.tripleTranslator=new Z6.TripleTranslator,this.expressionTranslator=new e7.ExpressionTranslator({translateWhere:a(e=>this.patternTranslator.translateWhere(e),"translateWhere"),translateBGP:a(e=>this.tripleTranslator.translateBGP(e),"translateBGP"),translatePattern:a(e=>this.patternTranslator.translatePattern(e),"translatePattern")}),this.patternTranslator=new t7.PatternTranslator({translateExpression:a(e=>this.expressionTranslator.translateExpression(e),"translateExpression"),translateSelect:a(e=>this.translateSelect(e),"translateSelect"),translateBGP:a(e=>this.tripleTranslator.translateBGP(e),"translateBGP")}),this.aggregateTranslator=new r7.AggregateTranslator({translateExpression:a(e=>this.expressionTranslator.translateExpression(e),"translateExpression")})}setDirectionMappings(e){this.tripleTranslator.setDirectionMappings(e),this.patternTranslator.setDirectionMappings(e)}translate(e){if(e.type!=="query")throw new tm.AlgebraTranslatorError("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 tm.AlgebraTranslatorError(`Query type ${String(e.queryType)} not yet supported`)}translateSelect(e){if(!e.where||e.where.length===0)throw new tm.AlgebraTranslatorError("SELECT query must have WHERE clause");let t=this.patternTranslator.translateWhere(e.where);this.aggregateTranslator.resetCounter();let r=new Map,i=Array.isArray(e.variables)?e.variables.filter(l=>!("termType"in l&&l.termType==="Wildcard")):[],s=this.aggregateTranslator.extractAggregatesWithMapping(i,r),o=this.aggregateTranslator.extractGroupVariables(e.group),c=this.aggregateTranslator.extractHavingExpressions(e.having,s,r);if((s.length>0||o.length>0||c.length>0)&&(t={type:"group",variables:o,aggregates:s,having:c.length>0?c:void 0,input:t}),i.length>0){for(let u of i)if((0,rm.isVariableExpression)(u)){if("type"in u.expression&&u.expression.type==="aggregate")continue;let f=this.aggregateTranslator.transformExpressionWithAggregateVars(u.expression,r);t={type:"extend",variable:u.variable.value,expression:f,input:t}}let l=i.filter(u=>(0,rm.isVariableTerm)(u)||(0,rm.isVariableExpression)(u)).map(u=>(0,rm.isVariableTerm)(u)?u.value:u.variable.value);l.length>0&&(t={type:"project",variables:l,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(l=>this.aggregateTranslator.translateOrderComparator(l)),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.tripleTranslator.translateConstructTemplate(e.template??[]);if(!e.where||e.where.length===0)throw new tm.AlgebraTranslatorError("CONSTRUCT query must have WHERE clause");let r=this.patternTranslator.translateWhere(e.where),i=e;return(i.limit!==void 0||i.offset!==void 0)&&(r={type:"slice",limit:i.limit,offset:i.offset,input:r}),{type:"construct",template:t,where:r}}translateAsk(e){return{type:"ask",where:e.where&&e.where.length>0?this.patternTranslator.translateWhere(e.where):{type:"bgp",triples:[]}}}translateDescribe(e){let t=[];if(e.variables&&Array.isArray(e.variables)){let s=e.variables;for(let o of s)o.termType==="Wildcard"||o.value==="*"||(o.termType==="Variable"?t.push({type:"variable",value:o.value}):o.termType==="NamedNode"&&t.push({type:"iri",value:o.value}))}let r;e.where&&e.where.length>0&&(r=this.patternTranslator.translateWhere(e.where));let i=e.describeOptions;return{type:"describe",resources:t,where:r,depth:i?.depth,symmetric:i?.symmetric}}};Jo.ExoQLAlgebraTranslator=nm;Jo.AlgebraTranslator=nm});var _s=w(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});im.SolutionMapping=void 0;var wR=qe(),vR=Oe(),ER=Bt(),HS=class n{static{a(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,r]of this.bindings.entries()){let i=e.get(t);if(i!==void 0&&!this.areEqual(r,i))return!1}return!0}merge(e){if(!this.isCompatibleWith(e))return null;let t=new n(this.bindings);for(let[r,i]of e.getBindings().entries())t.set(r,i);return t}clone(){return new n(this.bindings)}areEqual(e,t){return e instanceof wR.Literal&&t instanceof wR.Literal?e.equals(t):e instanceof vR.IRI&&t instanceof vR.IRI?e.value===t.value:e instanceof ER.BlankNode&&t instanceof ER.BlankNode?e.id===t.id:!1}toJSON(){let e={};for(let[t,r]of this.bindings.entries())e[t]=r.toString();return e}size(){return this.bindings.size}};im.SolutionMapping=HS});var AR=w(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});_l.PropertyPathExecutor=_l.PropertyPathExecutorError=void 0;var i7=_s(),sm=Oe(),TR=Bt(),s7=qe(),bl=class extends Error{static{a(this,"PropertyPathExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="PropertyPathExecutorError"}};_l.PropertyPathExecutorError=bl;var KS=class n{static{a(this,"PropertyPathExecutor")}constructor(e){this.tripleStore=e,this.MAX_DEPTH=100}async*execute(e,t,r){if(this.isLiteralElement(e)||this.isLiteralElement(r)){let o=this.isLiteralElement(e)?"subject":"object",c=this.isLiteralElement(e)?e:r,l="value"in c?String(c.value):"<unknown>",u=l.length>80?`${l.slice(0,77)}...`:l,f=this.describePath(t),d={position:o,value:u,path:f,hint:"Wikilink could not be resolved to IRI (likely label-form wikilink with no matching basename/alias). Check whether the target file exists in the queried vault, add an alias, or load the target vault via --also. See issue #3282."};if(console.error(`[PropertyPathExecutor] literal-safety guard fired: literal in ${o} position \u2014 yielding 0 solutions. value="${u}" path=${f}`,d),n.isStrictModeEnabled())throw new bl(`Literal subject in property path: "${u}" (path=${f}). Set EXOCORTEX_SPARQL_STRICT=0 or omit --strict to fall back to warn-and-empty behaviour.`);return}let i=await this.resolveElement(e),s=this.isVariable(r)?null:await this.resolveElement(r);for(let o of i){let c=await this.evaluatePath(o,t,s);for(let l of c){let u=new i7.SolutionMapping;this.isVariable(e)&&u.set(e.value,o),this.isVariable(r)&&u.set(r.value,l),yield u}}}async*executeWithBindings(e,t){if(!this.isPropertyPath(e.predicate))throw new bl("Predicate is not a property path");let r=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.object,t);for await(let s of this.execute(r,e.predicate,i)){let o=t.merge(s);o!==null&&(yield o)}}async evaluatePath(e,t,r){switch(t.pathType){case"/":return this.evaluateSequencePath(e,t.items,r);case"|":return this.evaluateAlternativePath(e,t.items,r);case"^":return this.evaluateInversePath(e,t.items[0],r);case"+":return this.evaluateOneOrMorePath(e,t.items[0],r);case"*":return this.evaluateZeroOrMorePath(e,t.items[0],r);case"?":return this.evaluateZeroOrOnePath(e,t.items[0],r)}}async evaluateSequencePath(e,t,r){let i=new Set([e]);for(let s=0;s<t.length;s++){let o=t[s],c=s===t.length-1,l=new Set;for(let u of i){let f=await this.evaluatePathItem(u,o,c?r:null);for(let d of f)l.add(d)}if(i=l,i.size===0)break}return i}async evaluateAlternativePath(e,t,r){let i=new Set;for(let s of t){let o=await this.evaluatePathItem(e,s,r);for(let c of o)i.add(c)}return i}async evaluateInversePath(e,t,r){if(t.type==="iri"){let i=new sm.IRI(t.value),s=await this.tripleStore.match(void 0,i,e),o=new Set;for(let c of s)(r===null||this.nodeInSet(c.subject,r))&&o.add(c.subject);return o}else return this.evaluatePath(e,this.invertPath(t),r)}async evaluateOneOrMorePath(e,t,r){let i=new Set,s=new Set,o=[{node:e,depth:0}];for(;o.length>0;){let c=o.shift();if(!c)break;let{node:l,depth:u}=c;if(u>=this.MAX_DEPTH)continue;let f=await this.evaluatePathItem(l,t,null);for(let d of f){let p=this.nodeToKey(d);(r===null||this.nodeInSet(d,r))&&s.add(d),i.has(p)||(i.add(p),o.push({node:d,depth:u+1}))}}return s}async evaluateZeroOrMorePath(e,t,r){let i=await this.evaluateOneOrMorePath(e,t,r);return(r===null||this.nodeInSet(e,r))&&i.add(e),i}async evaluateZeroOrOnePath(e,t,r){let i=new Set;(r===null||this.nodeInSet(e,r))&&i.add(e);let s=await this.evaluatePathItem(e,t,r);for(let o of s)i.add(o);return i}async evaluatePathItem(e,t,r){if(t.type==="iri"){let i=new sm.IRI(t.value),s=await this.tripleStore.match(e,i,void 0),o=new Set;for(let c of s)(r===null||this.nodeInSet(c.object,r))&&o.add(c.object);return o}else return this.evaluatePath(e,t,r)}invertPath(e){switch(e.pathType){case"^":return e.items[0];case"/":return{type:"path",pathType:"/",items:[...e.items].reverse().map(t=>t.type==="iri"?{type:"path",pathType:"^",items:[t]}:this.invertPath(t))};case"|":return{type:"path",pathType:"|",items:e.items.map(t=>t.type==="iri"?{type:"path",pathType:"^",items:[t]}:this.invertPath(t))};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 r=new Set,i=await this.tripleStore.match(void 0,void 0,void 0);for(let s of i)r.add(s.subject),r.add(s.object);return r}let t=new Set;switch(e.type){case"iri":t.add(new sm.IRI(e.value));break;case"blank":t.add(new TR.BlankNode(e.value));break;default:throw new bl(`Unsupported element type in subject/object position: ${e.type}`)}return t}instantiateElement(e,t){if(this.isVariable(e)){let r=t.get(e.value);if(r){if(r instanceof sm.IRI)return{type:"iri",value:r.value};if(r instanceof TR.BlankNode)return{type:"blank",value:r.id};if(r instanceof s7.Literal)return{type:"literal",value:r.value,datatype:r.datatype?.value,language:r.language,direction:r.direction}}}return e}isVariable(e){return e.type==="variable"}isLiteralElement(e){return e.type==="literal"}isPropertyPath(e){return e.type==="path"}nodeToKey(e){return e.toString()}nodeInSet(e,t){let r=this.nodeToKey(e);for(let i of t)if(this.nodeToKey(i)===r)return!0;return!1}describePath(e){try{let t=e.items,r=a(s=>{if(s&&typeof s=="object"&&"type"in s){let o=s;if(o.type==="iri")return`<${String(o.value)}>`;if(o.type==="path")return this.describePath(o)}return"?"},"renderItem");if(!Array.isArray(t)||t.length===0)return"(?)";if(t.length===1){let s=r(t[0]);return e.pathType==="^"?`(^${s})`:e.pathType==="+"||e.pathType==="*"||e.pathType==="?"?`(${s}${e.pathType})`:`(${s})`}return`(${t.map(r).join(` ${e.pathType} `)})`}catch{return"<unprintable-path>"}}static isStrictModeEnabled(){let t=(typeof process<"u"?process.env:void 0)?.EXOCORTEX_SPARQL_STRICT;if(!t)return!1;let r=t.trim().toLowerCase();return r==="1"||r==="true"||r==="yes"}};_l.PropertyPathExecutor=KS});var YS=w(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.BGPExecutor=Sl.BGPExecutorError=void 0;var om=_s(),Zo=Oe(),QS=qe(),am=Bt(),cm=_f(),IR=AR(),Ur=class extends Error{static{a(this,"BGPExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="BGPExecutorError"}};Sl.BGPExecutorError=Ur;var XS=class{static{a(this,"BGPExecutor")}constructor(e){this.tripleStore=e,this.propertyPathExecutor=new IR.PropertyPathExecutor(e)}async*execute(e){if(e.triples.length===0){yield new om.SolutionMapping;return}let t=this.matchTriplePattern(e.triples[0]);for(let r=1;r<e.triples.length;r++)t=this.joinWithPattern(t,e.triples[r]);for await(let r of t)yield r}async executeAll(e){let t=[];for await(let r of this.execute(e))t.push(r);return t}async*executeInGraph(e,t){if(e.triples.length===0){yield new om.SolutionMapping;return}let r=this.matchTriplePatternInGraph(e.triples[0],t);for(let i=1;i<e.triples.length;i++)r=this.joinWithPatternInGraph(r,e.triples[i],t);for await(let i of r)yield i}async*matchTriplePatternInGraph(e,t){if(this.isPropertyPath(e.predicate))throw new Ur("Property paths within named graphs are not yet supported");let r=e.predicate;if(this.isLiteral(e.subject)||this.isLiteral(r)){this.warnLiteralGuard("matchTriplePatternInGraph",this.isLiteral(e.subject)?"subject":"predicate",this.isLiteral(e.subject)?e.subject:r);return}let i=this.isVariable(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),s=this.isVariable(r)?void 0:this.toRDFTermAsPredicate(r),o=this.isVariable(e.object)?void 0:this.toRDFTerm(e.object);if(!this.tripleStore.matchInGraph)throw new Ur("Triple store does not support named graph operations");let c=await this.tripleStore.matchInGraph(i,s,o,t);for(let l of c){let u=new om.SolutionMapping;this.isVariable(e.subject)&&u.set(e.subject.value,l.subject),this.isVariable(r)&&u.set(r.value,l.predicate),this.isVariable(e.object)&&u.set(e.object.value,l.object),yield u}}async*joinWithPatternInGraph(e,t,r){let i=[];for await(let s of e)i.push(s);for(let s of i){let o=this.instantiatePattern(t,s);for await(let c of this.matchTriplePatternInGraph(o,r)){let l=s.merge(c);l!==null&&(yield l)}}}async*matchTriplePattern(e){if(this.isPropertyPath(e.predicate)){if(this.isLiteral(e.subject)||this.isLiteral(e.object)){this.warnLiteralGuard("matchTriplePattern.propertyPath",this.isLiteral(e.subject)?"subject":"object",this.isLiteral(e.subject)?e.subject:e.object);return}yield*this.propertyPathExecutor.execute(e.subject,e.predicate,e.object);return}let t=e.predicate;if(this.isLiteral(e.subject)||this.isLiteral(t)){this.warnLiteralGuard("matchTriplePattern",this.isLiteral(e.subject)?"subject":"predicate",this.isLiteral(e.subject)?e.subject:t);return}let r=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),o=await this.tripleStore.match(r,i,s);for(let c of o){let l=new om.SolutionMapping;if(this.isVariable(e.subject))l.set(e.subject.value,c.subject);else if(this.isQuotedTriple(e.subject)){let u=this.matchQuotedTriplePattern(e.subject,c.subject);if(u===null)continue;for(let[f,d]of u.entries())l.set(f,d)}if(this.isVariable(t)&&l.set(t.value,c.predicate),this.isVariable(e.object))l.set(e.object.value,c.object);else if(this.isQuotedTriple(e.object)){let u=this.matchQuotedTriplePattern(e.object,c.object);if(u===null)continue;for(let[f,d]of u.entries())l.set(f,d)}yield l}}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 cm.QuotedTriple))return null;let r=new Map;if(this.isVariable(e.subject))r.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,o]of i)r.set(s,o)}else if(!this.elementsMatch(e.subject,t.subject))return null;if(e.predicate.type==="variable")r.set(e.predicate.value,t.predicate);else if(e.predicate.value!==t.predicate.value)return null;if(this.isVariable(e.object))r.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,o]of i)r.set(s,o)}else if(!this.elementsMatch(e.object,t.object))return null;return r}elementsMatch(e,t){switch(e.type){case"iri":return t instanceof Zo.IRI&&e.value===t.value;case"literal":return!(!(t instanceof QS.Literal)||e.value!==t.value||e.datatype!==t.datatype?.value||e.language!==t.language||e.direction!==t.direction);case"blank":return t instanceof am.BlankNode&&e.value===t.id;case"quoted":return t instanceof cm.QuotedTriple?this.toRDFQuotedTriple(e).equals(t):!1;default:return!1}}isPropertyPath(e){return e.type==="path"}async*joinWithPattern(e,t){let r=[];for await(let i of e)r.push(i);for(let i of r){let s=this.instantiatePattern(t,i);for await(let o of this.matchTriplePattern(s)){let c=i.merge(o);c!==null&&(yield c)}}}instantiatePattern(e,t){let r=this.isPropertyPath(e.predicate)?e.predicate:this.instantiateElement(e.predicate,t);return{subject:this.instantiateElement(e.subject,t),predicate:r,object:this.instantiateElement(e.object,t)}}instantiateElement(e,t){if(this.isVariable(e)){let r=t.get(e.value);if(r)return this.toAlgebraElement(r)}return this.isQuotedTriple(e)?this.instantiateQuotedTriple(e,t):e}instantiateQuotedTriple(e,t){let r=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:r,predicate:i,object:s}}instantiatePredicateVariable(e,t){let r=t.get(e.value);return r&&r instanceof Zo.IRI?{type:"iri",value:r.value}:e}isVariable(e){return e.type==="variable"}isQuotedTriple(e){return e.type==="quoted"}isLiteral(e){return e.type==="literal"}warnLiteralGuard(e,t,r){let i="value"in r?String(r.value):"<unknown>",s=i.length>80?`${i.slice(0,77)}...`:i,o={executor:"BGPExecutor",context:e,position:t,value:s,hint:"Wikilink could not be resolved to IRI (likely label-form wikilink with no matching basename/alias). Check whether the target file exists in the queried vault, add an alias, or load the target vault via --also. See issue #3282."};if(console.error(`[BGPExecutor] literal-safety guard fired in ${e}: literal in ${t} position \u2014 yielding 0 solutions. value="${s}"`,o),IR.PropertyPathExecutor.isStrictModeEnabled())throw new Ur(`Literal in ${t} position (${e}): "${s}". Set EXOCORTEX_SPARQL_STRICT=0 or omit --strict to fall back to warn-and-empty behaviour.`)}toRDFTermAsSubject(e){switch(e.type){case"iri":return new Zo.IRI(e.value);case"blank":return new am.BlankNode(e.value);case"literal":throw new Ur("Literals cannot appear in subject position");case"variable":throw new Ur(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new Ur(`Unknown element type: ${String(e)}`)}}toRDFQuotedTriple(e){let t=this.toRDFTermAsSubject(e.subject),r=e.predicate.type==="iri"?new Zo.IRI(e.predicate.value):(()=>{throw new Ur("Quoted triple predicate must be IRI")})(),i=this.toRDFTerm(e.object);return new cm.QuotedTriple(t,r,i)}toRDFTermAsPredicate(e){switch(e.type){case"iri":return new Zo.IRI(e.value);case"literal":throw new Ur("Literals cannot appear in predicate position");case"blank":throw new Ur("Blank nodes cannot appear in predicate position");case"variable":throw new Ur(`Cannot convert variable to RDF term: ${e.value}`);default:throw new Ur(`Unknown element type: ${String(e)}`)}}toRDFTerm(e){switch(e.type){case"iri":return new Zo.IRI(e.value);case"literal":return new QS.Literal(e.value,e.datatype?new Zo.IRI(e.datatype):void 0,e.language,e.direction);case"blank":return new am.BlankNode(e.value);case"variable":throw new Ur(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new Ur(`Unknown element type: ${String(e)}`)}}toAlgebraElement(e){if(e instanceof Zo.IRI)return{type:"iri",value:e.value};if(e instanceof QS.Literal)return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language,direction:e.direction};if(e instanceof am.BlankNode)return{type:"blank",value:e.id};if(e instanceof cm.QuotedTriple)return this.toAlgebraQuotedTriple(e);throw new Ur(`Unknown RDF term type: ${String(e)}`)}toAlgebraQuotedTriple(e){return{type:"quoted",subject:this.toAlgebraElement(e.subject),predicate:{type:"iri",value:e.predicate.value},object:this.toAlgebraElement(e.object)}}};Sl.BGPExecutor=XS});var xR=w(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});lm.StringFunctions=void 0;var wl=Oe(),ea=qe(),JS=Bt(),Uf=class n{static{a(this,"StringFunctions")}static str(e){if(e===void 0)throw new Error("STR: argument is undefined");return e instanceof wl.IRI||e instanceof ea.Literal?e.value:e instanceof JS.BlankNode?e.id:String(e)}static lang(e){if(e===void 0)throw new Error("LANG: argument is undefined");return e instanceof ea.Literal&&e.language?e.language:""}static langdir(e){if(e===void 0)throw new Error("LANGDIR: argument is undefined");return!(e instanceof ea.Literal)||!e.language?"":e.direction?`${e.language}--${e.direction}`:e.language}static langMatches(e,t){let[r,i]=n.parseDirectionalLangTag(e),[s,o]=n.parseDirectionalLangTag(t),c=r.toLowerCase(),l=s.toLowerCase();return l==="*"?c!=="":c===""?l==="":o&&i!==o?!1:c===l?!0:c.startsWith(l+"-")}static parseDirectionalLangTag(e){let t=e.indexOf("--");if(t===-1)return[e,void 0];let r=e.substring(0,t),i=e.substring(t+2).toLowerCase();return[r,i]}static regex(e,t,r){try{let i=r?r.includes("u")?r:r+"u":"u";return new RegExp(t,i).test(e)}catch(i){throw new Error(`REGEX: invalid pattern '${t}': ${i.message}`)}}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,r){let i=t-1;if(i<0){if(r!==void 0){let s=r+i;return s<=0?"":e.substring(0,s)}return e}return r!==void 0?e.substring(i,i+r):e.substring(i)}static strBefore(e,t){if(t==="")return"";let r=e.indexOf(t);return r===-1?"":e.substring(0,r)}static strAfter(e,t){if(t==="")return e;let r=e.indexOf(t);return r===-1?"":e.substring(r+t.length)}static concat(...e){return e.join("")}static replace(e,t,r,i){try{let s=i||"g",o=s.includes("u")?s:s+"u",c=new RegExp(t,o);return e.replace(c,r)}catch(s){throw new Error(`REPLACE: invalid pattern '${t}': ${s.message}`)}}static encodeForUri(e){return encodeURIComponent(e)}static normalize(e,t){if(e===void 0)throw new Error("NORMALIZE: string argument is undefined");let r;if(e instanceof ea.Literal)r=e.value;else if(e instanceof wl.IRI)r=e.value;else if(e instanceof JS.BlankNode)r=e.id;else if(typeof e=="string")r=e;else throw new Error("NORMALIZE: first argument must be a string or literal");let i="NFC";if(t!==void 0)if(t instanceof ea.Literal)i=t.value.toUpperCase();else if(typeof t=="string")i=t.toUpperCase();else if(t instanceof wl.IRI)i=t.value.toUpperCase();else throw new Error("NORMALIZE: second argument must be a string literal");if(!n.VALID_NORMALIZATION_FORMS.includes(i))throw new Error(`NORMALIZE: invalid normalization form '${i}'. Valid forms are: NFC, NFD, NFKC, NFKD`);let s=r.normalize(i);return new ea.Literal(s,new wl.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 ea.Literal)t=e.value;else if(e instanceof wl.IRI)t=e.value;else if(e instanceof JS.BlankNode)t=e.id;else if(typeof e=="string")t=e;else throw new Error("FOLD: argument must be a string or literal");let r=n.unicodeCaseFold(t);return new ea.Literal(r,new wl.IRI("http://www.w3.org/2001/XMLSchema#string"))}static unicodeCaseFold(e){let t="";for(let r of e){let i=n.CASE_FOLDING_MAP.get(r);i!==void 0?t+=i:t+=r.toLowerCase()}return t}};lm.StringFunctions=Uf;Uf.VALID_NORMALIZATION_FORMS=["NFC","NFD","NFKC","NFKD"];Uf.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 RR=w(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});um.MathFunctions=void 0;var ZS=class{static{a(this,"MathFunctions")}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()}};um.MathFunctions=ZS});var Bf=w(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});fm.DateTimeParsing=void 0;var o7=Oe(),a7=qe(),ew=class n{static{a(this,"DateTimeParsing")}static parseDate(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`PARSEDATE: invalid date string '${e}'`);return t.getTime()}static parseDayTimeDuration(e){if(!e)throw new Error("parseDayTimeDuration: duration string is empty");let t=!1,r=e.trim();if(r.startsWith("-")&&(t=!0,r=r.substring(1)),!r.startsWith("P"))throw new Error(`parseDayTimeDuration: invalid format, must start with 'P': '${e}'`);r=r.substring(1);let i=0,s=r.indexOf("T"),o="",c="";if(s===-1?o=r:(o=r.substring(0,s),c=r.substring(s+1)),o){let l=o.match(/^(\d+(?:\.\d+)?)D$/);if(l){let u=parseFloat(l[1]);i+=u*24*60*60*1e3}else if(o!=="")throw new Error(`parseDayTimeDuration: invalid day component: '${o}' in '${e}'`)}if(c){let l=c,u=l.match(/^(\d+(?:\.\d+)?)H/);if(u){let p=parseFloat(u[1]);i+=p*60*60*1e3,l=l.substring(u[0].length)}let f=l.match(/^(\d+(?:\.\d+)?)M/);if(f){let p=parseFloat(f[1]);i+=p*60*1e3,l=l.substring(f[0].length)}let d=l.match(/^(\d+(?:\.\d+)?)S$/);if(d){let p=parseFloat(d[1]);i+=p*1e3,l=l.substring(d[0].length)}if(l!=="")throw new Error(`parseDayTimeDuration: invalid time component: '${l}' in '${e}'`)}return t?-i:i}static formatDayTimeDuration(e){let t=e<0,r=Math.abs(e),i=Math.floor(r/(1440*60*1e3));r=r%(1440*60*1e3);let s=Math.floor(r/(3600*1e3));r=r%(3600*1e3);let o=Math.floor(r/(60*1e3));r=r%(60*1e3);let c=r/1e3,l=t?"-P":"P";return i>0&&(l+=`${i}D`),(s>0||o>0||c>0||i===0)&&(l+="T",s>0&&(l+=`${s}H`),o>0&&(l+=`${o}M`),(c>0||s===0&&o===0)&&(Number.isInteger(c)?l+=`${c}S`:l+=`${parseFloat(c.toFixed(3))}S`)),l}static xsdDayTimeDuration(e){return n.parseDayTimeDuration(e),new a7.Literal(e,new o7.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static parseXSDDate(e){let t=/^(-?\d{4})-(\d{2})-(\d{2})(Z|[+-]\d{2}:\d{2})?$/,r=e.match(t);if(!r){let u=new Date(e);return isNaN(u.getTime())?null:new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()))}let i=parseInt(r[1],10),s=parseInt(r[2],10)-1,o=parseInt(r[3],10),c=r[4],l=new Date(Date.UTC(i,s,o));if(c&&c!=="Z"){let u=c.match(/([+-])(\d{2}):(\d{2})/);if(u){let f=u[1]==="+"?1:-1,d=parseInt(u[2],10),p=parseInt(u[3],10),h=f*(d*60+p)*60*1e3;l=new Date(l.getTime()-h)}}return l}static parseXSDTime(e){let t=/^(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$/,r=e.match(t);if(!r)return null;let i=parseInt(r[1],10),s=parseInt(r[2],10),o=parseInt(r[3],10),c=r[4],l=r[5];if(i<0||i>24||s<0||s>59||o<0||o>59||i===24&&(s!==0||o!==0))return null;let u=0;if(c){let d=c.padEnd(3,"0").slice(0,3);u=parseInt(d,10)}let f=i*60*60*1e3+s*60*1e3+o*1e3+u;if(i===24&&(f=1440*60*1e3),l&&l!=="Z"){let d=l.match(/([+-])(\d{2}):(\d{2})/);if(d){let p=d[1]==="+"?1:-1,h=parseInt(d[2],10),y=parseInt(d[3],10),g=p*(h*60+y)*60*1e3;f-=g}}return f}static formatDateDuration(e){if(e===0)return"P0D";let t=e<0,r=Math.abs(e);return t?`-P${r}D`:`P${r}D`}static parseYearMonthDuration(e){let t=/^(-)?P(?:(\d+)Y)?(?:(\d+)M)?$/,r=e.match(t);if(!r)throw new Error(`parseYearMonthDuration: invalid format: '${e}'`);let i=r[1]==="-",s=parseInt(r[2]||"0",10),o=parseInt(r[3]||"0",10);if(!r[2]&&!r[3])throw new Error(`parseYearMonthDuration: invalid format (no duration components): '${e}'`);let c=s*12+o;return i?-c:c}static formatYearMonthDuration(e){let t=e<0,r=Math.abs(e),i=Math.floor(r/12),s=r%12,o=t?"-P":"P";return i>0&&(o+=`${i}Y`),(s>0||i===0)&&(o+=`${s}M`),o}static parseYearMonthDurationComponents(e){let t=/^(-)?P(?:(\d+)Y)?(?:(\d+)M)?$/,r=e.match(t);if(!r)throw new Error(`parseYearMonthDurationComponents: invalid format: '${e}'`);let i=r[1]==="-",s=parseInt(r[2]||"0",10),o=parseInt(r[3]||"0",10);if(!r[2]&&!r[3])throw new Error(`parseYearMonthDurationComponents: invalid format (no duration components): '${e}'`);return{years:s,months:o,negative:i}}static parseDurationComponents(e){if(!e)throw new Error("parseDurationComponents: duration string is empty");let t=!1,r=e.trim();if(r.startsWith("-")&&(t=!0,r=r.substring(1)),!r.startsWith("P"))throw new Error(`parseDurationComponents: invalid format, must start with 'P': '${e}'`);r=r.substring(1);let i=0,s=0,o=0,c=0,l=r.indexOf("T"),u="",f="";if(l===-1?u=r:(u=r.substring(0,l),f=r.substring(l+1)),u){let d=u.match(/^(\d+(?:\.\d+)?)D$/);if(d)i=parseFloat(d[1]);else if(u!=="")throw new Error(`parseDurationComponents: invalid day component: '${u}' in '${e}'`)}if(f){let d=f,p=d.match(/^(\d+(?:\.\d+)?)H/);p&&(s=parseFloat(p[1]),d=d.substring(p[0].length));let h=d.match(/^(\d+(?:\.\d+)?)M/);h&&(o=parseFloat(h[1]),d=d.substring(h[0].length));let y=d.match(/^(\d+(?:\.\d+)?)S$/);if(y&&(c=parseFloat(y[1]),d=d.substring(y[0].length)),d!=="")throw new Error(`parseDurationComponents: invalid time component: '${d}' in '${e}'`)}return{negative:t,days:i,hours:s,minutes:o,seconds:c}}};fm.DateTimeParsing=ew});var CR=w(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});dm.DateTimeArithmetic=void 0;var hn=Oe(),$e=qe(),st=Bf(),tw=class{static{a(this,"DateTimeArithmetic")}static dateTimeDiff(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r),o=new Date(i);if(isNaN(s.getTime()))throw new Error(`dateTimeDiff: invalid first dateTime: '${r}'`);if(isNaN(o.getTime()))throw new Error(`dateTimeDiff: invalid second dateTime: '${i}'`);let c=s.getTime()-o.getTime(),l=st.DateTimeParsing.formatDayTimeDuration(c);return new $e.Literal(l,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static dateTimeAdd(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r);if(isNaN(s.getTime()))throw new Error(`dateTimeAdd: invalid dateTime: '${r}'`);let o=st.DateTimeParsing.parseDayTimeDuration(i),c=s.getTime()+o,l=new Date(c);return new $e.Literal(l.toISOString(),new hn.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtract(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtract: invalid dateTime: '${r}'`);let o=st.DateTimeParsing.parseDayTimeDuration(i),c=s.getTime()-o,l=new Date(c);return new $e.Literal(l.toISOString(),new hn.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateAdd(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseXSDDate(r);if(s===null)throw new Error(`dateAdd: invalid date: '${r}'`);let o=st.DateTimeParsing.parseDayTimeDuration(i),c=s.getTime()+o,l=new Date(c),u=l.getUTCFullYear(),f=String(l.getUTCMonth()+1).padStart(2,"0"),d=String(l.getUTCDate()).padStart(2,"0"),p=`${u}-${f}-${d}`;return new $e.Literal(p,new hn.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateSubtract(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseXSDDate(r);if(s===null)throw new Error(`dateSubtract: invalid date: '${r}'`);let o=st.DateTimeParsing.parseDayTimeDuration(i),c=s.getTime()-o,l=new Date(c),u=l.getUTCFullYear(),f=String(l.getUTCMonth()+1).padStart(2,"0"),d=String(l.getUTCDate()).padStart(2,"0"),p=`${u}-${f}-${d}`;return new $e.Literal(p,new hn.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateTimeAddYearMonth(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r);if(isNaN(s.getTime()))throw new Error(`dateTimeAddYearMonth: invalid dateTime: '${r}'`);let o=st.DateTimeParsing.parseYearMonthDuration(i),c=s.getUTCDate();return s.setUTCMonth(s.getUTCMonth()+o),s.getUTCDate()!==c&&s.setUTCDate(0),new $e.Literal(s.toISOString(),new hn.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtractYearMonth(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtractYearMonth: invalid dateTime: '${r}'`);let o=st.DateTimeParsing.parseYearMonthDuration(i),c=s.getUTCDate();return s.setUTCMonth(s.getUTCMonth()-o),s.getUTCDate()!==c&&s.setUTCDate(0),new $e.Literal(s.toISOString(),new hn.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateAddYearMonth(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseXSDDate(r);if(s===null)throw new Error(`dateAddYearMonth: invalid date: '${r}'`);let o=st.DateTimeParsing.parseYearMonthDuration(i),c=s.getUTCDate();s.setUTCMonth(s.getUTCMonth()+o),s.getUTCDate()!==c&&s.setUTCDate(0);let l=s.getUTCFullYear(),u=String(s.getUTCMonth()+1).padStart(2,"0"),f=String(s.getUTCDate()).padStart(2,"0"),d=`${l}-${u}-${f}`;return new $e.Literal(d,new hn.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateSubtractYearMonth(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseXSDDate(r);if(s===null)throw new Error(`dateSubtractYearMonth: invalid date: '${r}'`);let o=st.DateTimeParsing.parseYearMonthDuration(i),c=s.getUTCDate();s.setUTCMonth(s.getUTCMonth()-o),s.getUTCDate()!==c&&s.setUTCDate(0);let l=s.getUTCFullYear(),u=String(s.getUTCMonth()+1).padStart(2,"0"),f=String(s.getUTCDate()).padStart(2,"0"),d=`${l}-${u}-${f}`;return new $e.Literal(d,new hn.IRI("http://www.w3.org/2001/XMLSchema#date"))}static durationAdd(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseDayTimeDuration(r),o=st.DateTimeParsing.parseDayTimeDuration(i),c=st.DateTimeParsing.formatDayTimeDuration(s+o);return new $e.Literal(c,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationSubtract(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseDayTimeDuration(r),o=st.DateTimeParsing.parseDayTimeDuration(i),c=st.DateTimeParsing.formatDayTimeDuration(s-o);return new $e.Literal(c,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationMultiply(e,t){let r=e instanceof $e.Literal?e.value:e,i=st.DateTimeParsing.parseDayTimeDuration(r),s=st.DateTimeParsing.formatDayTimeDuration(i*t);return new $e.Literal(s,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationDivide(e,t){if(t===0)throw new Error("durationDivide: division by zero");let r=e instanceof $e.Literal?e.value:e,i=st.DateTimeParsing.parseDayTimeDuration(r),s=st.DateTimeParsing.formatDayTimeDuration(i/t);return new $e.Literal(s,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static yearMonthDurationAdd(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseYearMonthDuration(r),o=st.DateTimeParsing.parseYearMonthDuration(i),c=st.DateTimeParsing.formatYearMonthDuration(s+o);return new $e.Literal(c,new hn.IRI("http://www.w3.org/2001/XMLSchema#yearMonthDuration"))}static yearMonthDurationSubtract(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseYearMonthDuration(r),o=st.DateTimeParsing.parseYearMonthDuration(i),c=st.DateTimeParsing.formatYearMonthDuration(s-o);return new $e.Literal(c,new hn.IRI("http://www.w3.org/2001/XMLSchema#yearMonthDuration"))}static durationToDays(e){let t=e instanceof $e.Literal?e.value:e;return st.DateTimeParsing.parseDayTimeDuration(t)/(1440*60*1e3)}static durationToHours(e){let t=e instanceof $e.Literal?e.value:e;return st.DateTimeParsing.parseDayTimeDuration(t)/(3600*1e3)}static durationToMinutes(e){let t=e instanceof $e.Literal?e.value:e;return st.DateTimeParsing.parseDayTimeDuration(t)/(60*1e3)}static durationToSeconds(e){let t=e instanceof $e.Literal?e.value:e;return st.DateTimeParsing.parseDayTimeDuration(t)/1e3}};dm.DateTimeArithmetic=tw});var PR=w(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});pm.DateTimeAccessors=void 0;var Vf=Oe(),Vt=qe(),Rt=Bf(),rw=class{static{a(this,"DateTimeAccessors")}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 durationDays(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseDurationComponents(t),i=Math.floor(r.days);return r.negative?-i:i}static durationHours(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseDurationComponents(t),i=Math.floor(r.hours);return r.negative?-i:i}static durationMinutes(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseDurationComponents(t),i=Math.floor(r.minutes);return r.negative?-i:i}static durationSeconds(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseDurationComponents(t);return r.negative?-r.seconds:r.seconds}static durationYears(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseYearMonthDurationComponents(t);return r.negative?-r.years:r.years}static durationMonths(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseYearMonthDurationComponents(t);return r.negative?-r.months:r.months}static timezone(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TIMEZONE: invalid date string '${e}'`);let r;if(e.endsWith("Z"))r="PT0S";else{let i=e.match(/([+-]\d{2}):?(\d{2})$/);if(i){let s=parseInt(i[1],10),o=parseInt(i[2],10),c=s>=0?"":"-",l=Math.abs(s);o===0?r=`${c}PT${l}H`:r=`${c}PT${l}H${o}M`}else{let s=-t.getTimezoneOffset(),o=Math.floor(Math.abs(s)/60),c=Math.abs(s)%60,l=s>=0?"":"-";c===0?r=`${l}PT${o}H`:r=`${l}PT${o}H${c}M`}}return new Vt.Literal(r,new Vf.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 r=e.match(/([+-]\d{2}:\d{2})$/);if(r)return r[1];let i=e.match(/([+-])(\d{2})(\d{2})$/);return i?`${i[1]}${i[2]}:${i[3]}`:""}static adjust(e,t){let r=e instanceof Vt.Literal?e.value:e,i=new Date(r);if(isNaN(i.getTime()))throw new Error(`ADJUST: invalid dateTime: '${r}'`);if(t==null){let R=i.getUTCFullYear(),q=String(i.getUTCMonth()+1).padStart(2,"0"),Y=String(i.getUTCDate()).padStart(2,"0"),P=String(i.getUTCHours()).padStart(2,"0"),O=String(i.getUTCMinutes()).padStart(2,"0"),k=String(i.getUTCSeconds()).padStart(2,"0"),H=i.getUTCMilliseconds(),G=`${R}-${q}-${Y}T${P}:${O}:${k}`;return H>0&&(G+=`.${String(H).padStart(3,"0")}`),new Vt.Literal(G,new Vf.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}let s=t instanceof Vt.Literal?t.value:t,o=Rt.DateTimeParsing.parseDayTimeDuration(s),c=840*60*1e3;if(Math.abs(o)>c)throw new Error(`ADJUST: timezone offset out of range: '${s}'`);let l=i.getTime(),u=new Date(l+o),f=u.getUTCFullYear(),d=String(u.getUTCMonth()+1).padStart(2,"0"),p=String(u.getUTCDate()).padStart(2,"0"),h=String(u.getUTCHours()).padStart(2,"0"),y=String(u.getUTCMinutes()).padStart(2,"0"),g=String(u.getUTCSeconds()).padStart(2,"0"),v=u.getUTCMilliseconds(),b=o>=0?"+":"-",S=Math.floor(Math.abs(o)/(3600*1e3)),T=Math.floor(Math.abs(o)%(3600*1e3)/(60*1e3)),I=`${b}${String(S).padStart(2,"0")}:${String(T).padStart(2,"0")}`,A=`${f}-${d}-${p}T${h}:${y}:${g}`;return v>0&&(A+=`.${String(v).padStart(3,"0")}`),A+=I,new Vt.Literal(A,new Vf.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static now(){return new Date().toISOString()}static dateBefore(e,t){let r=Rt.DateTimeParsing.parseDate(e),i=Rt.DateTimeParsing.parseDate(t);return r<i}static dateAfter(e,t){let r=Rt.DateTimeParsing.parseDate(e),i=Rt.DateTimeParsing.parseDate(t);return r>i}static dateInRange(e,t,r){let i=Rt.DateTimeParsing.parseDate(e),s=Rt.DateTimeParsing.parseDate(t),o=Rt.DateTimeParsing.parseDate(r);return i>=s&&i<=o}static compareDurations(e,t,r){let i=e instanceof Vt.Literal?e.value:e,s=t instanceof Vt.Literal?t.value:t,o=Rt.DateTimeParsing.parseDayTimeDuration(i),c=Rt.DateTimeParsing.parseDayTimeDuration(s);switch(r){case"=":return o===c;case"!=":return o!==c;case"<":return o<c;case">":return o>c;case"<=":return o<=c;case">=":return o>=c;default:throw new Error(`compareDurations: unknown operator: ${r}`)}}static dateDiffMinutes(e,t){let r=Rt.DateTimeParsing.parseDate(e),i=Rt.DateTimeParsing.parseDate(t),s=Math.abs(i-r);return Math.round(s/(1e3*60))}static dateDiffHours(e,t){let r=Rt.DateTimeParsing.parseDate(e),i=Rt.DateTimeParsing.parseDate(t),s=Math.abs(i-r);return Math.round(s/(1e3*60*60)*100)/100}static timeDiff(e,t){let r=e instanceof Vt.Literal?e.value:e,i=t instanceof Vt.Literal?t.value:t,s=Rt.DateTimeParsing.parseXSDTime(r),o=Rt.DateTimeParsing.parseXSDTime(i);if(s===null)throw new Error(`timeDiff: invalid first time: '${r}'`);if(o===null)throw new Error(`timeDiff: invalid second time: '${i}'`);let c=s-o,l=Rt.DateTimeParsing.formatDayTimeDuration(c);return new Vt.Literal(l,new Vf.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static isDayTimeDuration(e){return e instanceof Vt.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static isDate(e){return e instanceof Vt.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#date":!1}static isYearMonthDuration(e){return e instanceof Vt.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#yearMonthDuration":!1}static isTime(e){return e instanceof Vt.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#time":!1}static dateDiff(e,t){let r=e instanceof Vt.Literal?e.value:e,i=t instanceof Vt.Literal?t.value:t,s=Rt.DateTimeParsing.parseXSDDate(r),o=Rt.DateTimeParsing.parseXSDDate(i);if(s===null)throw new Error(`dateDiff: invalid first date: '${r}'`);if(o===null)throw new Error(`dateDiff: invalid second date: '${i}'`);let c=s.getTime()-o.getTime(),l=Math.round(c/(1440*60*1e3)),u=Rt.DateTimeParsing.formatDateDuration(l);return new Vt.Literal(u,new Vf.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}};pm.DateTimeAccessors=rw});var mm=w(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});hm.DateTimeFunctions=void 0;var vl=Bf(),hr=CR(),St=PR(),nw=class{static{a(this,"DateTimeFunctions")}static parseDate(e){return vl.DateTimeParsing.parseDate(e)}static parseDayTimeDuration(e){return vl.DateTimeParsing.parseDayTimeDuration(e)}static formatDayTimeDuration(e){return vl.DateTimeParsing.formatDayTimeDuration(e)}static xsdDayTimeDuration(e){return vl.DateTimeParsing.xsdDayTimeDuration(e)}static parseYearMonthDuration(e){return vl.DateTimeParsing.parseYearMonthDuration(e)}static formatYearMonthDuration(e){return vl.DateTimeParsing.formatYearMonthDuration(e)}static year(e){return St.DateTimeAccessors.year(e)}static month(e){return St.DateTimeAccessors.month(e)}static day(e){return St.DateTimeAccessors.day(e)}static hours(e){return St.DateTimeAccessors.hours(e)}static minutes(e){return St.DateTimeAccessors.minutes(e)}static seconds(e){return St.DateTimeAccessors.seconds(e)}static durationDays(e){return St.DateTimeAccessors.durationDays(e)}static durationHours(e){return St.DateTimeAccessors.durationHours(e)}static durationMinutes(e){return St.DateTimeAccessors.durationMinutes(e)}static durationSeconds(e){return St.DateTimeAccessors.durationSeconds(e)}static durationYears(e){return St.DateTimeAccessors.durationYears(e)}static durationMonths(e){return St.DateTimeAccessors.durationMonths(e)}static timezone(e){return St.DateTimeAccessors.timezone(e)}static tz(e){return St.DateTimeAccessors.tz(e)}static adjust(e,t){return St.DateTimeAccessors.adjust(e,t)}static now(){return St.DateTimeAccessors.now()}static dateBefore(e,t){return St.DateTimeAccessors.dateBefore(e,t)}static dateAfter(e,t){return St.DateTimeAccessors.dateAfter(e,t)}static dateInRange(e,t,r){return St.DateTimeAccessors.dateInRange(e,t,r)}static compareDurations(e,t,r){return St.DateTimeAccessors.compareDurations(e,t,r)}static dateDiffMinutes(e,t){return St.DateTimeAccessors.dateDiffMinutes(e,t)}static dateDiffHours(e,t){return St.DateTimeAccessors.dateDiffHours(e,t)}static timeDiff(e,t){return St.DateTimeAccessors.timeDiff(e,t)}static dateDiff(e,t){return St.DateTimeAccessors.dateDiff(e,t)}static isDayTimeDuration(e){return St.DateTimeAccessors.isDayTimeDuration(e)}static isDate(e){return St.DateTimeAccessors.isDate(e)}static isYearMonthDuration(e){return St.DateTimeAccessors.isYearMonthDuration(e)}static isTime(e){return St.DateTimeAccessors.isTime(e)}static dateTimeDiff(e,t){return hr.DateTimeArithmetic.dateTimeDiff(e,t)}static dateTimeAdd(e,t){return hr.DateTimeArithmetic.dateTimeAdd(e,t)}static dateTimeSubtract(e,t){return hr.DateTimeArithmetic.dateTimeSubtract(e,t)}static dateAdd(e,t){return hr.DateTimeArithmetic.dateAdd(e,t)}static dateSubtract(e,t){return hr.DateTimeArithmetic.dateSubtract(e,t)}static dateTimeAddYearMonth(e,t){return hr.DateTimeArithmetic.dateTimeAddYearMonth(e,t)}static dateTimeSubtractYearMonth(e,t){return hr.DateTimeArithmetic.dateTimeSubtractYearMonth(e,t)}static dateAddYearMonth(e,t){return hr.DateTimeArithmetic.dateAddYearMonth(e,t)}static dateSubtractYearMonth(e,t){return hr.DateTimeArithmetic.dateSubtractYearMonth(e,t)}static durationAdd(e,t){return hr.DateTimeArithmetic.durationAdd(e,t)}static durationSubtract(e,t){return hr.DateTimeArithmetic.durationSubtract(e,t)}static durationMultiply(e,t){return hr.DateTimeArithmetic.durationMultiply(e,t)}static durationDivide(e,t){return hr.DateTimeArithmetic.durationDivide(e,t)}static yearMonthDurationAdd(e,t){return hr.DateTimeArithmetic.yearMonthDurationAdd(e,t)}static yearMonthDurationSubtract(e,t){return hr.DateTimeArithmetic.yearMonthDurationSubtract(e,t)}static durationToDays(e){return hr.DateTimeArithmetic.durationToDays(e)}static durationToHours(e){return hr.DateTimeArithmetic.durationToHours(e)}static durationToMinutes(e){return hr.DateTimeArithmetic.durationToMinutes(e)}static durationToSeconds(e){return hr.DateTimeArithmetic.durationToSeconds(e)}};hm.DateTimeFunctions=nw});var OR=w(ym=>{"use strict";Object.defineProperty(ym,"__esModule",{value:!0});ym.LogicalFunctions=void 0;var c7=Oe(),El=qe(),l7=Bt(),gm=mm(),iw=class n{static{a(this,"LogicalFunctions")}static compare(e,t,r){if(n.isDayTimeDurationValue(e)&&n.isDayTimeDurationValue(t))return gm.DateTimeFunctions.compareDurations(e instanceof El.Literal?e:String(e),t instanceof El.Literal?t:String(t),r);if(n.isDayTimeDurationValue(e)&&typeof t=="string"&&/^-?P/.test(t))return gm.DateTimeFunctions.compareDurations(e instanceof El.Literal?e:String(e),t,r);if(typeof e=="string"&&/^-?P/.test(e)&&n.isDayTimeDurationValue(t))return gm.DateTimeFunctions.compareDurations(e,t instanceof El.Literal?t:String(t),r);let i=n.toComparableValue(e),s=n.toComparableValue(t);switch(r){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: ${r}`)}}static isDayTimeDurationValue(e){return e instanceof El.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 El.Literal){let t=e.datatype?.value;if(t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double")){let r=parseFloat(e.value);if(!isNaN(r))return r}if(t==="http://www.w3.org/2001/XMLSchema#dayTimeDuration")try{return gm.DateTimeFunctions.parseDayTimeDuration(e.value)}catch{return e.value}return e.value}return e instanceof c7.IRI?e.value:e instanceof l7.BlankNode?e.id:String(e)}static logicalAnd(e){return e.every(t=>t===!0)}static logicalOr(e){return e.some(t=>t===!0)}static logicalNot(e){return!e}static coalesce(e){for(let t of e)if(t!=null)return t}static if(e,t,r){return e?t:r}};ym.LogicalFunctions=iw});var DR=w(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});bm.RDFTermFunctions=void 0;var Br=Oe(),At=qe(),Ci=Bt(),Tl=_f(),sw=Ii(),ow=class n{static{a(this,"RDFTermFunctions")}static datatype(e){if(e===void 0)throw new Error("DATATYPE: argument is undefined");if(e instanceof At.Literal)return e.datatype?e.datatype:e.language?new Br.IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"):new Br.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 Br.IRI}static isBlank(e){return e===void 0?!1:e instanceof Ci.BlankNode}static isLiteral(e){return e===void 0?!1:e instanceof At.Literal}static isTriple(e){return e===void 0?!1:e instanceof Tl.QuotedTriple}static hasLangdir(e){return e===void 0||!(e instanceof At.Literal)?!1:!!e.language&&!!e.direction}static isNumeric(e){if(e===void 0||!(e instanceof At.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 xsdDateTime(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`xsd:dateTime: invalid date string '${e}'`);return new At.Literal(t.toISOString(),new Br.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 At.Literal(String(t),new Br.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 At.Literal(String(t),new Br.IRI("http://www.w3.org/2001/XMLSchema#decimal"))}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 Br.IRI&&t instanceof Br.IRI)return e.value===t.value;if(e instanceof Ci.BlankNode&&t instanceof Ci.BlankNode)return e.id===t.id;if(e instanceof At.Literal&&t instanceof At.Literal){if(e.value!==t.value||e.language!==t.language)return!1;let r=e.datatype?.value,i=t.datatype?.value;return r===i}return!1}static iri(e){if(e===void 0)throw new Error("IRI: argument is undefined");if(e instanceof Br.IRI)return e;if(e instanceof At.Literal)return new Br.IRI(e.value);throw e instanceof Ci.BlankNode?new Error("IRI: cannot convert blank node to IRI"):new Error("IRI: unsupported term type")}static uri(e){return n.iri(e)}static bnode(e){if(e===void 0){let t=`b${(0,sw.v4)().replace(/-/g,"").substring(0,12)}`;return new Ci.BlankNode(t)}if(e instanceof At.Literal)return new Ci.BlankNode(e.value);if(e instanceof Ci.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 r;if(e instanceof At.Literal){if(e.language)throw new Error("STRDT: lexical form must not have a language tag");r=e.value}else if(typeof e=="string")r=e;else throw new Error("STRDT: lexical form must be a string literal");let i;if(t instanceof Br.IRI)i=t;else if(t instanceof At.Literal)i=new Br.IRI(t.value);else throw new Error("STRDT: datatype must be an IRI");return new At.Literal(r,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 r;if(e instanceof At.Literal){if(e.language)throw new Error("STRLANG: lexical form must not already have a language tag");r=e.value}else if(typeof e=="string")r=e;else throw new Error("STRLANG: lexical form must be a string literal");let i;if(t instanceof At.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 At.Literal(r,void 0,i)}static strlangdir(e,t,r){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(r===void 0)throw new Error("STRLANGDIR: direction is undefined");let i;if(e instanceof At.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 At.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 o;if(r instanceof At.Literal)o=r.value.toLowerCase();else throw new Error("STRLANGDIR: direction must be a string literal");if(o!=="ltr"&&o!=="rtl")throw new Error(`STRLANGDIR: invalid direction '${o}'. Must be 'ltr' or 'rtl'`);return new At.Literal(i,void 0,s,o)}static uuid(){let e=(0,sw.v4)();return new Br.IRI(`urn:uuid:${e}`)}static struuid(){let e=(0,sw.v4)();return new At.Literal(e)}static triple(e,t,r){if(e===void 0)throw new Error("TRIPLE: subject is undefined");if(t===void 0)throw new Error("TRIPLE: predicate is undefined");if(r===void 0)throw new Error("TRIPLE: object is undefined");if(e instanceof At.Literal)throw new Error("TRIPLE: subject must be IRI, BlankNode, or QuotedTriple, got Literal");if(!(t instanceof Br.IRI)){let c=t instanceof At.Literal?"Literal":t instanceof Ci.BlankNode?"BlankNode":t instanceof Tl.QuotedTriple?"QuotedTriple":typeof t;throw new Error(`TRIPLE: predicate must be IRI, got ${c}`)}let i=e,s=t,o=r;return new Tl.QuotedTriple(i,s,o)}static subject(e){if(e===void 0)throw new Error("SUBJECT: argument is undefined");if(!(e instanceof Tl.QuotedTriple)){let t=e instanceof Br.IRI?"IRI":e instanceof At.Literal?"Literal":e instanceof Ci.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 Tl.QuotedTriple)){let t=e instanceof Br.IRI?"IRI":e instanceof At.Literal?"Literal":e instanceof Ci.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 Tl.QuotedTriple)){let t=e instanceof Br.IRI?"IRI":e instanceof At.Literal?"Literal":e instanceof Ci.BlankNode?"BlankNode":typeof e;throw new Error(`OBJECT: argument must be QuotedTriple, got ${t}`)}return e.object}};bm.RDFTermFunctions=ow});var FR=w(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});_m.HashFunctions=void 0;var aw=class{static{a(this,"HashFunctions")}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")}};_m.HashFunctions=aw});var wm=w(Sm=>{"use strict";Object.defineProperty(Sm,"__esModule",{value:!0});Sm.BuiltInFunctions=void 0;var mr=xR(),ta=RR(),Pe=mm(),Al=OR(),Lt=DR(),Gf=FR(),cw=class{static{a(this,"BuiltInFunctions")}static str(...e){return mr.StringFunctions.str(...e)}static lang(...e){return mr.StringFunctions.lang(...e)}static langdir(...e){return mr.StringFunctions.langdir(...e)}static langMatches(...e){return mr.StringFunctions.langMatches(...e)}static regex(...e){return mr.StringFunctions.regex(...e)}static contains(...e){return mr.StringFunctions.contains(...e)}static strStarts(...e){return mr.StringFunctions.strStarts(...e)}static strEnds(...e){return mr.StringFunctions.strEnds(...e)}static strlen(...e){return mr.StringFunctions.strlen(...e)}static ucase(...e){return mr.StringFunctions.ucase(...e)}static lcase(...e){return mr.StringFunctions.lcase(...e)}static substr(...e){return mr.StringFunctions.substr(...e)}static strBefore(...e){return mr.StringFunctions.strBefore(...e)}static strAfter(...e){return mr.StringFunctions.strAfter(...e)}static concat(...e){return mr.StringFunctions.concat(...e)}static replace(...e){return mr.StringFunctions.replace(...e)}static encodeForUri(...e){return mr.StringFunctions.encodeForUri(...e)}static normalize(...e){return mr.StringFunctions.normalize(...e)}static fold(...e){return mr.StringFunctions.fold(...e)}static abs(...e){return ta.MathFunctions.abs(...e)}static round(...e){return ta.MathFunctions.round(...e)}static ceil(...e){return ta.MathFunctions.ceil(...e)}static floor(...e){return ta.MathFunctions.floor(...e)}static rand(){return ta.MathFunctions.rand()}static msToMinutes(...e){return ta.MathFunctions.msToMinutes(...e)}static msToHours(...e){return ta.MathFunctions.msToHours(...e)}static msToSeconds(...e){return ta.MathFunctions.msToSeconds(...e)}static parseDate(...e){return Pe.DateTimeFunctions.parseDate(...e)}static dateBefore(...e){return Pe.DateTimeFunctions.dateBefore(...e)}static dateAfter(...e){return Pe.DateTimeFunctions.dateAfter(...e)}static dateInRange(...e){return Pe.DateTimeFunctions.dateInRange(...e)}static dateDiffMinutes(...e){return Pe.DateTimeFunctions.dateDiffMinutes(...e)}static dateDiffHours(...e){return Pe.DateTimeFunctions.dateDiffHours(...e)}static year(...e){return Pe.DateTimeFunctions.year(...e)}static month(...e){return Pe.DateTimeFunctions.month(...e)}static day(...e){return Pe.DateTimeFunctions.day(...e)}static hours(...e){return Pe.DateTimeFunctions.hours(...e)}static minutes(...e){return Pe.DateTimeFunctions.minutes(...e)}static seconds(...e){return Pe.DateTimeFunctions.seconds(...e)}static timezone(...e){return Pe.DateTimeFunctions.timezone(...e)}static tz(...e){return Pe.DateTimeFunctions.tz(...e)}static now(){return Pe.DateTimeFunctions.now()}static parseDayTimeDuration(...e){return Pe.DateTimeFunctions.parseDayTimeDuration(...e)}static formatDayTimeDuration(...e){return Pe.DateTimeFunctions.formatDayTimeDuration(...e)}static xsdDayTimeDuration(...e){return Pe.DateTimeFunctions.xsdDayTimeDuration(...e)}static compareDurations(...e){return Pe.DateTimeFunctions.compareDurations(...e)}static isDayTimeDuration(...e){return Pe.DateTimeFunctions.isDayTimeDuration(...e)}static isDate(...e){return Pe.DateTimeFunctions.isDate(...e)}static dateDiff(...e){return Pe.DateTimeFunctions.dateDiff(...e)}static dateTimeDiff(...e){return Pe.DateTimeFunctions.dateTimeDiff(...e)}static dateTimeAdd(...e){return Pe.DateTimeFunctions.dateTimeAdd(...e)}static dateTimeSubtract(...e){return Pe.DateTimeFunctions.dateTimeSubtract(...e)}static dateAdd(...e){return Pe.DateTimeFunctions.dateAdd(...e)}static dateSubtract(...e){return Pe.DateTimeFunctions.dateSubtract(...e)}static parseYearMonthDuration(...e){return Pe.DateTimeFunctions.parseYearMonthDuration(...e)}static isYearMonthDuration(...e){return Pe.DateTimeFunctions.isYearMonthDuration(...e)}static dateTimeAddYearMonth(...e){return Pe.DateTimeFunctions.dateTimeAddYearMonth(...e)}static dateTimeSubtractYearMonth(...e){return Pe.DateTimeFunctions.dateTimeSubtractYearMonth(...e)}static dateAddYearMonth(...e){return Pe.DateTimeFunctions.dateAddYearMonth(...e)}static dateSubtractYearMonth(...e){return Pe.DateTimeFunctions.dateSubtractYearMonth(...e)}static durationAdd(...e){return Pe.DateTimeFunctions.durationAdd(...e)}static durationSubtract(...e){return Pe.DateTimeFunctions.durationSubtract(...e)}static durationMultiply(...e){return Pe.DateTimeFunctions.durationMultiply(...e)}static durationDivide(...e){return Pe.DateTimeFunctions.durationDivide(...e)}static formatYearMonthDuration(...e){return Pe.DateTimeFunctions.formatYearMonthDuration(...e)}static yearMonthDurationAdd(...e){return Pe.DateTimeFunctions.yearMonthDurationAdd(...e)}static yearMonthDurationSubtract(...e){return Pe.DateTimeFunctions.yearMonthDurationSubtract(...e)}static durationYears(...e){return Pe.DateTimeFunctions.durationYears(...e)}static durationMonths(...e){return Pe.DateTimeFunctions.durationMonths(...e)}static durationToDays(...e){return Pe.DateTimeFunctions.durationToDays(...e)}static durationToHours(...e){return Pe.DateTimeFunctions.durationToHours(...e)}static durationToMinutes(...e){return Pe.DateTimeFunctions.durationToMinutes(...e)}static durationToSeconds(...e){return Pe.DateTimeFunctions.durationToSeconds(...e)}static durationDays(...e){return Pe.DateTimeFunctions.durationDays(...e)}static durationHours(...e){return Pe.DateTimeFunctions.durationHours(...e)}static durationMinutes(...e){return Pe.DateTimeFunctions.durationMinutes(...e)}static durationSeconds(...e){return Pe.DateTimeFunctions.durationSeconds(...e)}static adjust(...e){return Pe.DateTimeFunctions.adjust(...e)}static isTime(...e){return Pe.DateTimeFunctions.isTime(...e)}static timeDiff(...e){return Pe.DateTimeFunctions.timeDiff(...e)}static compare(...e){return Al.LogicalFunctions.compare(...e)}static logicalAnd(...e){return Al.LogicalFunctions.logicalAnd(...e)}static logicalOr(...e){return Al.LogicalFunctions.logicalOr(...e)}static logicalNot(...e){return Al.LogicalFunctions.logicalNot(...e)}static coalesce(...e){return Al.LogicalFunctions.coalesce(...e)}static if(...e){return Al.LogicalFunctions.if(...e)}static datatype(...e){return Lt.RDFTermFunctions.datatype(...e)}static bound(...e){return Lt.RDFTermFunctions.bound(...e)}static isIRI(...e){return Lt.RDFTermFunctions.isIRI(...e)}static isBlank(...e){return Lt.RDFTermFunctions.isBlank(...e)}static isLiteral(...e){return Lt.RDFTermFunctions.isLiteral(...e)}static isTriple(...e){return Lt.RDFTermFunctions.isTriple(...e)}static isNumeric(...e){return Lt.RDFTermFunctions.isNumeric(...e)}static hasLangdir(...e){return Lt.RDFTermFunctions.hasLangdir(...e)}static sameTerm(...e){return Lt.RDFTermFunctions.sameTerm(...e)}static iri(...e){return Lt.RDFTermFunctions.iri(...e)}static uri(...e){return Lt.RDFTermFunctions.uri(...e)}static bnode(...e){return Lt.RDFTermFunctions.bnode(...e)}static strdt(...e){return Lt.RDFTermFunctions.strdt(...e)}static strlang(...e){return Lt.RDFTermFunctions.strlang(...e)}static strlangdir(...e){return Lt.RDFTermFunctions.strlangdir(...e)}static uuid(){return Lt.RDFTermFunctions.uuid()}static struuid(){return Lt.RDFTermFunctions.struuid()}static xsdDateTime(...e){return Lt.RDFTermFunctions.xsdDateTime(...e)}static xsdInteger(...e){return Lt.RDFTermFunctions.xsdInteger(...e)}static xsdDecimal(...e){return Lt.RDFTermFunctions.xsdDecimal(...e)}static triple(...e){return Lt.RDFTermFunctions.triple(...e)}static subject(...e){return Lt.RDFTermFunctions.subject(...e)}static predicate(...e){return Lt.RDFTermFunctions.predicate(...e)}static object(...e){return Lt.RDFTermFunctions.object(...e)}static md5(...e){return Gf.HashFunctions.md5(...e)}static sha1(...e){return Gf.HashFunctions.sha1(...e)}static sha256(...e){return Gf.HashFunctions.sha256(...e)}static sha384(...e){return Gf.HashFunctions.sha384(...e)}static sha512(...e){return Gf.HashFunctions.sha512(...e)}};Sm.BuiltInFunctions=cw});var qf=w(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.ExoQLBudgetExceededError=Ss.ExoQLCycleError=Ss.ExoQLEvalDisabledError=Ss.ExoQLForbiddenKeywordError=void 0;var lw=class extends Error{static{a(this,"ExoQLForbiddenKeywordError")}constructor(e,t){super(t??`ExoQLForbiddenKeywordError: keyword "${e}" is not permitted by the exoql__Query AST allowlist`),this.name="ExoQLForbiddenKeywordError",this.keyword=e}};Ss.ExoQLForbiddenKeywordError=lw;var uw=class extends Error{static{a(this,"ExoQLEvalDisabledError")}constructor(e){super(e??"ExoQLEvalDisabledError: exoql.eval.enabled is false (default). Flip the feature flag to opt in."),this.name="ExoQLEvalDisabledError"}};Ss.ExoQLEvalDisabledError=uw;var fw=class extends Error{static{a(this,"ExoQLCycleError")}constructor(e,t){super(t??`ExoQLCycleError: cycle detected in nested exo:eval invocations: ${e.join(" \u2192 ")}`),this.name="ExoQLCycleError",this.path=e}};Ss.ExoQLCycleError=fw;var dw=class extends Error{static{a(this,"ExoQLBudgetExceededError")}constructor(e,t,r,i){super(i??`ExoQLBudgetExceededError: ${e} budget exceeded (limit=${t}, observed=${r})`),this.name="ExoQLBudgetExceededError",this.budget=e,this.limit=t,this.observed=r}};Ss.ExoQLBudgetExceededError=dw});var VR=w(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.functionHandlers=void 0;var K=wm();Q.functionHandlers=new Map;Q.functionHandlers.set("str",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.str(t)});Q.functionHandlers.set("lang",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.lang(t)});Q.functionHandlers.set("langmatches",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.langMatches(t,r)});Q.functionHandlers.set("contains",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.contains(t,r)});Q.functionHandlers.set("strstarts",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.strStarts(t,r)});Q.functionHandlers.set("strends",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.strEnds(t,r)});Q.functionHandlers.set("strlen",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.strlen(t)});Q.functionHandlers.set("ucase",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.ucase(t)});Q.functionHandlers.set("lcase",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.lcase(t)});Q.functionHandlers.set("substr",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=Number(e.evaluateExpression(n[1],e.solution));if(n[2]){let i=Number(e.evaluateExpression(n[2],e.solution));return K.BuiltInFunctions.substr(t,r,i)}return K.BuiltInFunctions.substr(t,r)});Q.functionHandlers.set("strbefore",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.strBefore(t,r)});Q.functionHandlers.set("strafter",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.strAfter(t,r)});Q.functionHandlers.set("concat",(n,e)=>{let t=n.map(r=>e.getStringValue(e.evaluateExpression(r,e.solution)));return K.BuiltInFunctions.concat(...t)});Q.functionHandlers.set("replace",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=e.getStringValue(e.evaluateExpression(n[2],e.solution)),s=n[3]?e.getStringValue(e.evaluateExpression(n[3],e.solution)):void 0;return K.BuiltInFunctions.replace(t,r,i,s)});Q.functionHandlers.set("regex",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=n[2]?e.getStringValue(e.evaluateExpression(n[2],e.solution)):void 0;return K.BuiltInFunctions.regex(t,r,i)});Q.functionHandlers.set("encode_for_uri",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.encodeForUri(t)});Q.functionHandlers.set("datatype",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.datatype(t).value});Q.functionHandlers.set("bound",(n,e)=>{let t=n[0];if(t.type==="variable"&&t.name){let r=e.solution.get(t.name);return K.BuiltInFunctions.bound(r)}return!0});var LR=a((n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isIRI(t)},"isIriHandler");Q.functionHandlers.set("isiri",LR);Q.functionHandlers.set("isuri",LR);Q.functionHandlers.set("isblank",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isBlank(t)});Q.functionHandlers.set("isliteral",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isLiteral(t)});Q.functionHandlers.set("isnumeric",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isNumeric(t)});Q.functionHandlers.set("haslangdir",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.hasLangdir(t)});Q.functionHandlers.set("istriple",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isTriple(t)});Q.functionHandlers.set("sameterm",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution),r=e.getTermFromExpression(n[1],e.solution);return K.BuiltInFunctions.sameTerm(t,r)});Q.functionHandlers.set("abs",(n,e)=>{let t=Number(e.getStringValue(e.evaluateExpression(n[0],e.solution)));return K.BuiltInFunctions.abs(t)});Q.functionHandlers.set("round",(n,e)=>{let t=Number(e.getStringValue(e.evaluateExpression(n[0],e.solution)));return K.BuiltInFunctions.round(t)});Q.functionHandlers.set("ceil",(n,e)=>{let t=Number(e.getStringValue(e.evaluateExpression(n[0],e.solution)));return K.BuiltInFunctions.ceil(t)});Q.functionHandlers.set("floor",(n,e)=>{let t=Number(e.getStringValue(e.evaluateExpression(n[0],e.solution)));return K.BuiltInFunctions.floor(t)});Q.functionHandlers.set("rand",()=>K.BuiltInFunctions.rand());Q.functionHandlers.set("parsedate",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.parseDate(t)});Q.functionHandlers.set("datebefore",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.dateBefore(t,r)});Q.functionHandlers.set("dateafter",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.dateAfter(t,r)});Q.functionHandlers.set("dateinrange",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=e.getStringValue(e.evaluateExpression(n[2],e.solution));return K.BuiltInFunctions.dateInRange(t,r,i)});Q.functionHandlers.set("datediffminutes",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.dateDiffMinutes(t,r)});Q.functionHandlers.set("datediffhours",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.dateDiffHours(t,r)});var Il=a((n,e,t)=>(r,i)=>{let s=i.evaluateExpression(r[0],i.solution);return e&&i.isYearMonthDurationValue(s)?e(s):t&&i.isDayTimeDurationValue(s)?t(s):n(i.getStringValue(s))},"createDateTimeAccessor"),NR=Il(K.BuiltInFunctions.year.bind(K.BuiltInFunctions),K.BuiltInFunctions.durationYears.bind(K.BuiltInFunctions),null);Q.functionHandlers.set("year",NR);Q.functionHandlers.set("years",NR);var kR=Il(K.BuiltInFunctions.month.bind(K.BuiltInFunctions),K.BuiltInFunctions.durationMonths.bind(K.BuiltInFunctions),null);Q.functionHandlers.set("month",kR);Q.functionHandlers.set("months",kR);var MR=Il(K.BuiltInFunctions.day.bind(K.BuiltInFunctions),null,K.BuiltInFunctions.durationDays.bind(K.BuiltInFunctions));Q.functionHandlers.set("day",MR);Q.functionHandlers.set("days",MR);Q.functionHandlers.set("hours",Il(K.BuiltInFunctions.hours.bind(K.BuiltInFunctions),null,K.BuiltInFunctions.durationHours.bind(K.BuiltInFunctions)));Q.functionHandlers.set("minutes",Il(K.BuiltInFunctions.minutes.bind(K.BuiltInFunctions),null,K.BuiltInFunctions.durationMinutes.bind(K.BuiltInFunctions)));Q.functionHandlers.set("seconds",Il(K.BuiltInFunctions.seconds.bind(K.BuiltInFunctions),null,K.BuiltInFunctions.durationSeconds.bind(K.BuiltInFunctions)));Q.functionHandlers.set("timezone",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.timezone(t)});Q.functionHandlers.set("tz",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.tz(t)});Q.functionHandlers.set("adjust",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution),r=n.length>1?e.evaluateExpression(n[1],e.solution):void 0;return K.BuiltInFunctions.adjust(t,r)});Q.functionHandlers.set("now",()=>K.BuiltInFunctions.now());var jR=a((n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.xsdDateTime(e.getStringValue(t))},"dateTimeHandler");Q.functionHandlers.set("datetime",jR);Q.functionHandlers.set("xsd:datetime",jR);var $R=a((n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.xsdInteger(e.getStringValue(t))},"integerHandler");Q.functionHandlers.set("integer",$R);Q.functionHandlers.set("xsd:integer",$R);var UR=a((n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.xsdDecimal(e.getStringValue(t))},"decimalHandler");Q.functionHandlers.set("decimal",UR);Q.functionHandlers.set("xsd:decimal",UR);var BR=a((n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.xsdDayTimeDuration(e.getStringValue(t))},"dayTimeDurationHandler");Q.functionHandlers.set("daytimeduration",BR);Q.functionHandlers.set("xsd:daytimeduration",BR);Q.functionHandlers.set("durationtodays",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationToDays(t)});Q.functionHandlers.set("durationtohours",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationToHours(t)});Q.functionHandlers.set("durationtominutes",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationToMinutes(t)});Q.functionHandlers.set("durationtoseconds",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationToSeconds(t)});Q.functionHandlers.set("durationdays",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationDays(t)});Q.functionHandlers.set("durationhours",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationHours(t)});Q.functionHandlers.set("durationminutes",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationMinutes(t)});Q.functionHandlers.set("durationseconds",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationSeconds(t)});Q.functionHandlers.set("durationyears",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationYears(t)});Q.functionHandlers.set("durationmonths",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationMonths(t)});Q.functionHandlers.set("datetimediff",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution),r=e.evaluateExpression(n[1],e.solution);return K.BuiltInFunctions.dateTimeDiff(t,r)});Q.functionHandlers.set("datetimeadd",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution),r=e.evaluateExpression(n[1],e.solution);return K.BuiltInFunctions.dateTimeAdd(t,r)});Q.functionHandlers.set("datetimesubtract",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution),r=e.evaluateExpression(n[1],e.solution);return K.BuiltInFunctions.dateTimeSubtract(t,r)});Q.functionHandlers.set("mstominutes",(n,e)=>{let t=Number(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.msToMinutes(t)});Q.functionHandlers.set("mstohours",(n,e)=>{let t=Number(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.msToHours(t)});Q.functionHandlers.set("mstoseconds",(n,e)=>{let t=Number(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.msToSeconds(t)});Q.functionHandlers.set("md5",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.md5(t)});Q.functionHandlers.set("sha1",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.sha1(t)});Q.functionHandlers.set("sha256",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.sha256(t)});Q.functionHandlers.set("sha384",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.sha384(t)});Q.functionHandlers.set("sha512",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.sha512(t)});Q.functionHandlers.set("subject",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.subject(t)});Q.functionHandlers.set("predicate",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.predicate(t)});Q.functionHandlers.set("object",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.object(t)});Q.functionHandlers.set("triple",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution),r=e.getTermFromExpression(n[1],e.solution),i=e.getTermFromExpression(n[2],e.solution);return K.BuiltInFunctions.triple(t,r,i)});Q.functionHandlers.set("days_between",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=new Date(t),s=new Date(r);return Math.floor((s.getTime()-i.getTime())/(1440*60*1e3))});Q.functionHandlers.set("minutes_between",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=new Date(t),s=new Date(r);return Math.floor((s.getTime()-i.getTime())/(60*1e3))});Q.functionHandlers.set("hours_between",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=new Date(t);return(new Date(r).getTime()-i.getTime())/(3600*1e3)});Q.functionHandlers.set("age_days",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=new Date(t);return Math.floor((new Date().getTime()-r.getTime())/(1440*60*1e3))});Q.functionHandlers.set("week_number",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=new Date(t),i=new Date(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate()));i.setUTCDate(i.getUTCDate()+4-(i.getUTCDay()||7));let s=new Date(Date.UTC(i.getUTCFullYear(),0,1));return Math.ceil(((i.getTime()-s.getTime())/(1440*60*1e3)+1)/7)});Q.functionHandlers.set("format_date",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=new Date(t);return r.replace("YYYY",String(i.getFullYear())).replace("MM",String(i.getMonth()+1).padStart(2,"0")).replace("DD",String(i.getDate()).padStart(2,"0")).replace("HH",String(i.getHours()).padStart(2,"0")).replace("mm",String(i.getMinutes()).padStart(2,"0")).replace("ss",String(i.getSeconds()).padStart(2,"0"))});Q.functionHandlers.set("exo:eval",()=>{let{ExoQLEvalDisabledError:n}=qf();throw new n})});var vm=w(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});xl.FilterExecutor=xl.FilterExecutorError=void 0;var wt=wm(),u7=VR(),pw=Oe(),ws=qe(),wr=class extends Error{static{a(this,"FilterExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="FilterExecutorError"}};xl.FilterExecutorError=wr;var hw=class{static{a(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 r=this.expressionContainsExists(e.expression);for await(let i of t)try{let s;r?s=await this.evaluateExpressionAsync(e.expression,i):s=this.evaluateExpression(e.expression,i),s===!0&&(yield i)}catch{continue}}expressionContainsExists(e){if(!e||typeof e!="object")return!1;if(e.type==="exists")return!0;if(e.type==="logical")return e.operands.some(t=>this.expressionContainsExists(t));if(e.type==="comparison"){let t=e;return this.expressionContainsExists(t.left)||this.expressionContainsExists(t.right)}if(e.type==="arithmetic"){let t=e;return this.expressionContainsExists(t.left)||this.expressionContainsExists(t.right)}if(e.type==="in"){let t=e;return this.expressionContainsExists(t.expression)||t.list.some(r=>this.expressionContainsExists(r))}if(e.type==="function"||e.type==="functionCall"){let t=e;return Array.isArray(t.args)?t.args.some(r=>this.expressionContainsExists(r)):!1}return!1}async executeAll(e,t){let r=[];async function*i(){for(let s of t)yield s}a(i,"generator");for await(let s of this.execute(e,i()))r.push(s);return r}evaluateExpression(e,t){let r=e;if("termType"in e)switch(r.termType){case"Variable":return t.get(r.value);case"Literal":{let i=r.value,s=r.datatype,o=typeof s=="string"?s:s?.value;return o&&i.length>0&&this.shouldPreserveDatatype(o)?new ws.Literal(i,new pw.IRI(o)):i}case"NamedNode":return r.value;default:throw new wr(`Unsupported termType: ${String(r.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":{let i=e;return i.datatype&&i.value.length>0&&this.shouldPreserveDatatype(i.datatype)?new ws.Literal(i.value,new pw.IRI(i.datatype)):i.value}case"in":return this.evaluateIn(e,t);case"exists":throw new wr("EXISTS expressions require async evaluation. Use evaluateExpressionAsync instead.");default:throw new wr(`Unsupported expression type: ${e.type}`)}}async evaluateExpressionAsync(e,t){if(!this.expressionContainsExists(e))return this.evaluateExpression(e,t);if(e.type==="exists")return this.evaluateExists(e,t);if(e.type==="logical")return this.evaluateLogicalAsync(e,t);if(e.type==="comparison"){let r=e,i=await this.evaluateExpressionAsync(r.left,t),s=await this.evaluateExpressionAsync(r.right,t);return wt.BuiltInFunctions.compare(i,s,r.operator)}return e.type==="in"?this.evaluateInAsync(e,t):e.type==="function"||e.type==="functionCall"?this.evaluateFunctionAsync(e,t):this.evaluateExpression(e,t)}async evaluateExists(e,t){if(!this.existsEvaluator)throw new wr("EXISTS evaluator not set. Call setExistsEvaluator before evaluating EXISTS expressions.");let r=await this.existsEvaluator(e.pattern,t);return e.negated?!r:r}async evaluateLogicalAsync(e,t){if(e.operator==="!"){let i=await this.evaluateExpressionAsync(e.operands[0],t);return wt.BuiltInFunctions.logicalNot(i)}let r=[];for(let i of e.operands){let s=await this.evaluateExpressionAsync(i,t);r.push(s)}if(e.operator==="&&")return wt.BuiltInFunctions.logicalAnd(r);if(e.operator==="||")return wt.BuiltInFunctions.logicalOr(r);throw new wr(`Unknown logical operator: ${String(e.operator)}`)}async evaluateInAsync(e,t){let r=await this.evaluateExpressionAsync(e.expression,t),i=!1;for(let s of e.list){let o=await this.evaluateExpressionAsync(s,t);if(wt.BuiltInFunctions.compare(r,o,"=")){i=!0;break}}return e.negated?!i:i}async evaluateFunctionAsync(e,t){let r=e,i=this.extractFunctionName(r.function),s=r.args??[];if(i==="if"){if(s.length!==3)throw new wr("IF requires exactly 3 arguments");let l=await this.evaluateExpressionAsync(s[0],t);return this.toBoolean(l)?this.evaluateExpressionAsync(s[1],t):this.evaluateExpressionAsync(s[2],t)}if(i==="coalesce"){for(let l of s)try{let u=await this.evaluateExpressionAsync(l,t);if(u!=null)return u}catch{continue}return}let o=[];for(let l of s){let u=await this.evaluateExpressionAsync(l,t);o.push(this.wrapAsLiteralExpression(u))}let c={...r,args:o};return this.evaluateFunction(c,t)}wrapAsLiteralExpression(e){return e==null?{type:"literal",value:""}:typeof e=="object"&&"termType"in e?e:e instanceof pw.IRI||e instanceof ws.Literal?{type:"literal",value:e.value}:typeof e=="number"||typeof e=="boolean"||typeof e=="string"?{type:"literal",value:e}:{type:"literal",value:String(e)}}evaluateComparison(e,t){let r=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);return wt.BuiltInFunctions.compare(r,i,e.operator)}evaluateLogical(e,t){if(e.operator==="!"){let i=this.evaluateExpression(e.operands[0],t);return wt.BuiltInFunctions.logicalNot(i)}let r=e.operands.map(i=>this.evaluateExpression(i,t));if(e.operator==="&&")return wt.BuiltInFunctions.logicalAnd(r);if(e.operator==="||")return wt.BuiltInFunctions.logicalOr(r);throw new wr(`Unknown logical operator: ${String(e.operator)}`)}evaluateIn(e,t){let r=this.evaluateExpression(e.expression,t),i=e.list.some(s=>{let o=this.evaluateExpression(s,t);return wt.BuiltInFunctions.compare(r,o,"=")});return e.negated?!i:i}evaluateArithmetic(e,t){let r=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);if(e.operator==="-"&&this.isDateValue(r)&&this.isDateValue(i))return wt.BuiltInFunctions.dateDiff(r,i);if(e.operator==="-"&&this.isTimeValue(r)&&this.isTimeValue(i))return wt.BuiltInFunctions.timeDiff(r,i);if(e.operator==="-"&&this.isDateTimeValue(r)&&this.isDateTimeValue(i))return wt.BuiltInFunctions.dateTimeDiff(r,i);if(e.operator==="+"&&this.isDateValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.dateAdd(r,i);if(e.operator==="-"&&this.isDateValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.dateSubtract(r,i);if(e.operator==="+"&&this.isDateValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.dateAddYearMonth(r,i);if(e.operator==="-"&&this.isDateValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.dateSubtractYearMonth(r,i);if(e.operator==="+"&&this.isDateTimeValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.dateTimeAdd(r,i);if(e.operator==="-"&&this.isDateTimeValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.dateTimeSubtract(r,i);if(e.operator==="+"&&this.isDateTimeValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.dateTimeAddYearMonth(r,i);if(e.operator==="-"&&this.isDateTimeValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.dateTimeSubtractYearMonth(r,i);if(e.operator==="+"&&this.isDayTimeDurationValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.durationAdd(r,i);if(e.operator==="-"&&this.isDayTimeDurationValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.durationSubtract(r,i);if(e.operator==="*"&&this.isDayTimeDurationValue(r)&&!this.isDayTimeDurationValue(i)){let c=this.toNumericValue(i);return wt.BuiltInFunctions.durationMultiply(r,c)}if(e.operator==="*"&&!this.isDayTimeDurationValue(r)&&this.isDayTimeDurationValue(i)){let c=this.toNumericValue(r);return wt.BuiltInFunctions.durationMultiply(i,c)}if(e.operator==="/"&&this.isDayTimeDurationValue(r)&&!this.isDayTimeDurationValue(i)){let c=this.toNumericValue(i);if(c===0)throw new wr("Division by zero");return wt.BuiltInFunctions.durationDivide(r,c)}if(e.operator==="+"&&this.isYearMonthDurationValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.yearMonthDurationAdd(r,i);if(e.operator==="-"&&this.isYearMonthDurationValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.yearMonthDurationSubtract(r,i);let s=this.toNumericValue(r),o=this.toNumericValue(i);switch(e.operator){case"+":return s+o;case"-":return s-o;case"*":return s*o;case"/":if(o===0)throw new wr("Division by zero");return s/o;default:throw new wr(`Unknown arithmetic operator: ${String(e.operator)}`)}}shouldPreserveDatatype(e){return e==="http://www.w3.org/2001/XMLSchema#dateTime"||e==="http://www.w3.org/2001/XMLSchema#date"||e==="http://www.w3.org/2001/XMLSchema#time"||e==="http://www.w3.org/2001/XMLSchema#dayTimeDuration"||e==="http://www.w3.org/2001/XMLSchema#yearMonthDuration"||e==="http://www.w3.org/2001/XMLSchema#duration"}isDayTimeDurationValue(e){return e instanceof ws.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}isYearMonthDurationValue(e){return e instanceof ws.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#yearMonthDuration":!1}toNumericValue(e){if(typeof e=="number")return e;if(e instanceof ws.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 r=parseFloat(e.value);if(!isNaN(r))return r}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 wr(`Cannot convert to number: ${e}`)}isDateTimeValue(e){if(e instanceof ws.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 ws.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#date":!1}isTimeValue(e){return e instanceof ws.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#time":!1}evaluateFunction(e,t){let r=e,i=this.extractFunctionName(r.function),s=this.evaluateSpecialFunction(i,r.args,t);if(s!==void 0)return s.value;let o=u7.functionHandlers.get(i);if(!o)throw new wr(`Unknown function: ${i}`);let c={evaluateExpression:a((l,u)=>this.evaluateExpression(l,u),"evaluateExpression"),getTermFromExpression:a((l,u)=>this.getTermFromExpression(l,u),"getTermFromExpression"),getStringValue:a(l=>this.getStringValue(l),"getStringValue"),solution:t,isYearMonthDurationValue:a(l=>this.isYearMonthDurationValue(l),"isYearMonthDurationValue"),isDayTimeDurationValue:a(l=>this.isDayTimeDurationValue(l),"isDayTimeDurationValue")};return o(r.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 wr(`Unknown function format: ${String(e)}`)}evaluateSpecialFunction(e,t,r){switch(e){case"coalesce":for(let i of t)try{let s=this.evaluateExpression(i,r);if(s!=null)return{value:s}}catch{continue}return{value:void 0};case"if":{if(!t||t.length!==3)throw new wr("IF requires exactly 3 arguments");let i=this.evaluateExpression(t[0],r);return{value:this.toBoolean(i)?this.evaluateExpression(t[1],r):this.evaluateExpression(t[2],r)}}case"byuuid":return{value:this.evaluateByUUID({type:"function",function:"byuuid",args:t},r)};default:return}}getTermFromExpression(e,t){let r=e;if(r.type==="variable"&&r.name)return t.get(r.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 ws.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 r=parseFloat(e.value);return!isNaN(r)&&r!==0}return e.value.length>0}return!!e}evaluateByUUID(e,t){if(!e.args||e.args.length!==1)throw new wr("exo:byUUID requires exactly 1 argument (UUID string)");let r=this.evaluateExpression(e.args[0],t),i=this.getStringValue(r);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 o=this.tripleStore.findSubjectsByUUIDSync(s);if(o.length===0){this.uuidCache.set(s,null);return}let c=o[0];return this.uuidCache.set(s,c),c}this.uuidCache.set(s,null)}cacheUUIDResult(e,t){let r=e.toLowerCase();this.uuidCache.set(r,t)}getCachedUUID(e){let t=e.toLowerCase();if(this.uuidCache.has(t))return this.uuidCache.get(t)}};xl.FilterExecutor=hw});var gw=w(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});Em.OptionalExecutor=void 0;var mw=class{static{a(this,"OptionalExecutor")}async*execute(e,t){let r=[];for await(let s of e)r.push(s);let i=[];for await(let s of t)i.push(s);yield*this.hashJoin(r,i)}async executeAll(e,t){let r=[];for(let i of this.hashJoin(e,t))r.push(i);return r}*hashJoin(e,t){if(e.length===0)return;if(t.length===0){yield*e;return}let r=new Set;for(let l of e)for(let u of l.variables())r.add(u);let i=new Set;for(let l of t)for(let u of l.variables())i.add(u);let s=[];for(let l of r)i.has(l)&&s.push(l);if(s.sort(),s.length===0){yield*this.nestedLoopJoin(e,t);return}let o="\0",c=new Map;for(let l of t){let u=this.computeHashKey(l,s,o),f=c.get(u);f||(f=[],c.set(u,f)),f.push(l)}for(let l of e){let u=this.computeHashKey(l,s,o),f=c.get(u),d=!1;if(f)for(let p of f){let h=l.merge(p);h!==null&&(yield h,d=!0)}d||(yield l)}}computeHashKey(e,t,r){let i=[];for(let s of t){let o=e.get(s);i.push(o!==void 0?o.toString():"UNBOUND")}return i.join(r)}*nestedLoopJoin(e,t){for(let r of e){let i=!1;for(let s of t){let o=r.merge(s);o!==null&&(yield o,i=!0)}i||(yield r)}}};Em.OptionalExecutor=mw});var bw=w(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});Tm.UnionExecutor=void 0;var yw=class{static{a(this,"UnionExecutor")}async*execute(e,t){let r=new Set;for await(let i of e){let s=this.getSolutionKey(i);r.has(s)||(r.add(s),yield i)}for await(let i of t){let s=this.getSolutionKey(i);r.has(s)||(r.add(s),yield i)}}async executeAll(e,t){let r=[];async function*i(){for(let o of e)yield o}a(i,"generateLeft");async function*s(){for(let o of t)yield o}a(s,"generateRight");for await(let o of this.execute(i(),s()))r.push(o);return r}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}};Tm.UnionExecutor=yw});var GR=w(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});Am.MinusExecutor=void 0;var _w=class{static{a(this,"MinusExecutor")}async*execute(e,t){let r=[];for await(let s of e)r.push(s);let i=[];for await(let s of t)i.push(s);for(let s of r){let o=!1;for(let c of i)if(this.areCompatible(s,c)){o=!0;break}o||(yield s)}}async executeAll(e,t){let r=[];async function*i(){for(let o of e)yield o}a(i,"generateLeft");async function*s(){for(let o of t)yield o}a(s,"generateRight");for await(let o of this.execute(i(),s()))r.push(o);return r}areCompatible(e,t){let r=e.variables(),i=new Set(t.variables()),s=r.filter(o=>i.has(o));if(s.length===0)return!1;for(let o of s){let c=e.get(o),l=t.get(o);if(c===void 0||l===void 0||c.toString()!==l.toString())return!1}return!0}};Am.MinusExecutor=_w});var WR=w(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.ValuesExecutor=Rl.ValuesExecutorError=void 0;var f7=_s(),qR=Oe(),d7=qe(),Im=class extends Error{static{a(this,"ValuesExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ValuesExecutorError"}};Rl.ValuesExecutorError=Im;var Sw=class{static{a(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 r of this.execute(e))t.push(r);return t}createSolutionMapping(e){let t=new f7.SolutionMapping;for(let[r,i]of Object.entries(e)){let s=this.toRDFTerm(i);t.set(r,s)}return t}toRDFTerm(e){if(e.type==="iri")return new qR.IRI(e.value);if(e.type==="literal")return new d7.Literal(e.value,e.datatype?new qR.IRI(e.datatype):void 0,e.language,e.direction);throw new Im(`Unknown term type: ${e.type}`)}};Rl.ValuesExecutor=Sw});var ww=w(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.CustomAggregateRegistry=Pl.CustomAggregateError=void 0;var Cl=class extends Error{static{a(this,"CustomAggregateError")}constructor(e,t){super(e),this.iri=t,this.name="CustomAggregateError"}};Pl.CustomAggregateError=Cl;var xm=class n{static{a(this,"CustomAggregateRegistry")}constructor(){this.aggregates=new Map}static getInstance(){return n.instance||(n.instance=new n),n.instance}static resetInstance(){n.instance&&n.instance.clear(),n.instance=null}register(e,t){if(!e||typeof e!="string")throw new Cl("Aggregate IRI must be a non-empty string");if(!t||typeof t.init!="function"||typeof t.step!="function"||typeof t.finalize!="function")throw new Cl("Aggregate must implement init(), step(), and finalize() methods",e);if(this.aggregates.has(e))throw new Cl(`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}};Pl.CustomAggregateRegistry=xm;xm.instance=null});var vw=w(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.BUILT_IN_AGGREGATES=ot.modeAggregate=ot.stddevAggregate=ot.varianceAggregate=ot.medianAggregate=ot.EXO_AGGREGATE_NS=void 0;ot.getNumericValue=Rm;ot.createDecimalLiteral=Pi;ot.createDoubleLiteral=m7;ot.createPercentileAggregate=sc;var oc=qe(),Ol=Oe(),p7=new Ol.IRI("http://www.w3.org/2001/XMLSchema#decimal"),h7=new Ol.IRI("http://www.w3.org/2001/XMLSchema#double");ot.EXO_AGGREGATE_NS="https://exocortex.my/ontology/agg#";function Rm(n){return n==null?NaN:typeof n=="number"?n:typeof n=="string"?parseFloat(n):n instanceof oc.Literal?parseFloat(n.value):n instanceof Ol.IRI?NaN:typeof n=="boolean"?n?1:0:NaN}a(Rm,"getNumericValue");function Pi(n){return new oc.Literal(String(n),p7)}a(Pi,"createDecimalLiteral");function m7(n){return new oc.Literal(String(n),h7)}a(m7,"createDoubleLiteral");ot.medianAggregate={init(){return{values:[]}},step(n,e){let t=n,r=Rm(e);isNaN(r)||t.values.push(r)},finalize(n){let e=n,{values:t}=e;if(t.length===0)return Pi(0);let r=[...t].sort((o,c)=>o-c),i=Math.floor(r.length/2),s=r.length%2!==0?r[i]:(r[i-1]+r[i])/2;return Pi(s)}};ot.varianceAggregate={init(){return{values:[]}},step(n,e){let t=n,r=Rm(e);isNaN(r)||t.values.push(r)},finalize(n){let e=n,{values:t}=e;if(t.length===0)return Pi(0);let r=t.reduce((s,o)=>s+o,0)/t.length,i=t.reduce((s,o)=>s+Math.pow(o-r,2),0)/t.length;return Pi(i)}};ot.stddevAggregate={init(){return{values:[]}},step(n,e){ot.varianceAggregate.step(n,e)},finalize(n){let e=n,{values:t}=e;if(t.length===0)return Pi(0);let r=t.reduce((s,o)=>s+o,0)/t.length,i=t.reduce((s,o)=>s+Math.pow(o-r,2),0)/t.length;return Pi(Math.sqrt(i))}};ot.modeAggregate={init(){return{counts:new Map,values:new Map}},step(n,e){if(e==null)return;let t=n,r=String(e instanceof oc.Literal||e instanceof Ol.IRI?e.value:e),i=t.counts.get(r)||0;t.counts.set(r,i+1),t.values.set(r,e)},finalize(n){let e=n;if(e.counts.size===0)return new oc.Literal(" ",new Ol.IRI("http://www.w3.org/2001/XMLSchema#string"));let t="",r=0;for(let[o,c]of e.counts)c>r&&(r=c,t=o);let i=e.values.get(t);if(i instanceof oc.Literal)return i;let s=parseFloat(t);return isNaN(s)?new oc.Literal(t,new Ol.IRI("http://www.w3.org/2001/XMLSchema#string")):Pi(s)}};function sc(n){let e=Math.max(0,Math.min(100,n))/100;return{init(){return{values:[],percentile:e}},step(t,r){let i=t,s=Rm(r);isNaN(s)||i.values.push(s)},finalize(t){let r=t,{values:i}=r;if(i.length===0)return Pi(0);let s=[...i].sort((d,p)=>d-p),o=r.percentile*(s.length-1),c=Math.floor(o),l=Math.ceil(o);if(c===l)return Pi(s[c]);let u=o-c,f=s[c]*(1-u)+s[l]*u;return Pi(f)}}}a(sc,"createPercentileAggregate");ot.BUILT_IN_AGGREGATES={[`${ot.EXO_AGGREGATE_NS}median`]:ot.medianAggregate,[`${ot.EXO_AGGREGATE_NS}variance`]:ot.varianceAggregate,[`${ot.EXO_AGGREGATE_NS}stddev`]:ot.stddevAggregate,[`${ot.EXO_AGGREGATE_NS}mode`]:ot.modeAggregate,[`${ot.EXO_AGGREGATE_NS}percentile25`]:sc(25),[`${ot.EXO_AGGREGATE_NS}percentile50`]:sc(50),[`${ot.EXO_AGGREGATE_NS}percentile75`]:sc(75),[`${ot.EXO_AGGREGATE_NS}percentile90`]:sc(90),[`${ot.EXO_AGGREGATE_NS}percentile95`]:sc(95),[`${ot.EXO_AGGREGATE_NS}percentile99`]:sc(99)}});var KR=w(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});Dl.AggregateExecutor=Dl.AggregateExecutorError=void 0;var gr=qe(),Tw=Oe(),g7=vm(),y7=ww(),b7=vw(),zR=new Tw.IRI("http://www.w3.org/2001/XMLSchema#integer"),ac=new Tw.IRI("http://www.w3.org/2001/XMLSchema#decimal"),vs=new Tw.IRI("http://www.w3.org/2001/XMLSchema#string");function HR(n){return typeof n=="object"&&n.type==="custom"}a(HR,"isCustomAggregation");var Wf=class extends Error{static{a(this,"AggregateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AggregateExecutorError"}};Dl.AggregateExecutorError=Wf;var Ew=class{static{a(this,"AggregateExecutor")}constructor(){this.filterExecutor=new g7.FilterExecutor}execute(e,t){let r=this.groupSolutions(t,e.variables),i=[];for(let[s,o]of r.entries()){let c=new Map;for(let f of e.variables)if(o.length>0){let d=o[0].get(f);d&&c.set(f,d)}for(let f of e.aggregates){let d=this.computeAggregate(f.expression,o);c.set(f.variable,d)}let{SolutionMapping:l}=_s(),u=new l;for(let[f,d]of c.entries())u.set(f,d);i.push(u)}if(i.length===0&&e.aggregates.length>0){let s=this.createEmptyAggregateResult(e);s&&i.push(s)}return i}groupSolutions(e,t){let r=new Map;if(t.length===0)return r.set("",e),r;for(let i of e){let s=this.computeGroupKey(i,t),o=r.get(s);o?o.push(i):r.set(s,[i])}return r}computeGroupKey(e,t){return t.map(r=>{let i=e.get(r);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(HR(e.aggregation))return this.computeCustomAggregate(e,t);let r=this.extractValues(e,t),i=e.aggregation;switch(i){case"count":{let s=this.computeCount(r,e.distinct);return new gr.Literal(String(s),zR)}case"sum":{let s=this.computeSum(r);return new gr.Literal(String(s),ac)}case"avg":{let s=this.computeAvg(r);return new gr.Literal(String(s),ac)}case"min":{let s=this.computeMin(r);return s===void 0?new gr.Literal("",vs):typeof s=="number"?new gr.Literal(String(s),ac):new gr.Literal(String(s),vs)}case"max":{let s=this.computeMax(r);return s===void 0?new gr.Literal("",vs):typeof s=="number"?new gr.Literal(String(s),ac):new gr.Literal(String(s),vs)}case"group_concat":{let s=this.computeGroupConcat(r,e.separator||" ",e.distinct);return new gr.Literal(s||" ",vs)}case"sample":{let s=this.computeSample(r,e.distinct);return s===void 0?new gr.Literal(" ",vs):typeof s=="number"?new gr.Literal(String(s),ac):new gr.Literal(String(s),vs)}default:{let s=i;throw new Wf(`Unknown aggregation function: ${s}`)}}}computeCustomAggregate(e,t){let i=e.aggregation.iri,o=y7.CustomAggregateRegistry.getInstance().get(i);if(o||(o=b7.BUILT_IN_AGGREGATES[i]),!o)throw new Wf(`Unknown custom aggregate function: ${i}. Register it with CustomAggregateRegistry.getInstance().register() or use a built-in aggregate.`);let c=o.init();for(let l of t){let u=null;if(e.expression){let f=this.evaluateExpression(e.expression,l);f!==void 0&&(u=f)}else u=1;o.step(c,u)}return o.finalize(c)}extractValues(e,t){if(!e.expression)return t.map(()=>1);let r=[];for(let i of t){let s=this.evaluateExpression(e.expression,i);s!=null&&r.push(s)}return r}evaluateExpression(e,t){if(e.type==="variable"){let r=t.get(e.name);return r==null?void 0:typeof r=="number"||typeof r=="string"||typeof r=="boolean"?r:typeof r=="object"&&"value"in r?r.value:r}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(r=>String(r))).size:e.length}computeSum(e){return e.map(r=>parseFloat(String(r))).filter(r=>!isNaN(r)).reduce((r,i)=>r+i,0)}computeAvg(e){let t=e.map(r=>parseFloat(String(r))).filter(r=>!isNaN(r));return t.length===0?0:t.reduce((r,i)=>r+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 r=e.map(i=>String(i));return r.reduce((i,s)=>s<i?s:i,r[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 r=e.map(i=>String(i));return r.reduce((i,s)=>s>i?s:i,r[0])}computeGroupConcat(e,t,r){let i=e.map(s=>String(s));return r&&(i=[...new Set(i)]),i.join(t)}computeSample(e,t){if(e.length===0)return;if(t){let s=[...new Set(e.map(l=>String(l)))];if(s.length===0)return;let o=s[0],c=parseFloat(o);return isNaN(c)?o:c}let r=e[0];if(typeof r=="number")return r;let i=parseFloat(String(r));return isNaN(i)?String(r):i}createEmptyAggregateResult(e){let{SolutionMapping:t}=_s(),r=new t;for(let i of e.aggregates){let s=i.expression.aggregation;if(HR(s)){r.set(i.variable,new gr.Literal("0",ac));continue}switch(s){case"count":r.set(i.variable,new gr.Literal("0",zR));break;case"sum":case"avg":r.set(i.variable,new gr.Literal("0",ac));break;case"group_concat":r.set(i.variable,new gr.Literal(" ",vs));break;case"min":case"max":case"sample":r.set(i.variable,new gr.Literal("",vs));break;default:r.set(i.variable,new gr.Literal("",vs))}}return r}};Dl.AggregateExecutor=Ew});var Rw=w(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});Cm.ConstructExecutor=void 0;var _7=Wn(),cc=Oe(),Aw=qe(),Iw=Bt(),S7=_f(),xw=class{static{a(this,"ConstructExecutor")}async execute(e,t){let r=[],i=new Set;for(let s of t)for(let o of e)try{let c=this.instantiateTriple(o,s),l=`${c.subject.toString()}|${c.predicate.toString()}|${c.object.toString()}`;i.has(l)||(i.add(l),r.push(c))}catch{continue}return r}instantiateTriple(e,t){if(this.isPropertyPath(e.predicate))throw new Error("Property paths are not supported in CONSTRUCT templates");let r=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.predicate,t),s=this.instantiateElement(e.object,t);return new _7.Triple(r,i,s)}isPropertyPath(e){return e.type==="path"}instantiateElement(e,t){if(e.type==="variable"){let r=t.get(e.value);if(!r)throw new Error(`Unbound variable: ${e.value}`);return r}if(e.type==="iri")return new cc.IRI(e.value);if(e.type==="literal")return new Aw.Literal(e.value,e.datatype?new cc.IRI(e.datatype):void 0,e.language);if(e.type==="blank")return new Iw.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Unknown element type: ${e.type}`)}instantiateQuotedTriple(e,t){let r=this.instantiateQuotedSubject(e.subject,t),i=this.instantiateQuotedPredicate(e.predicate,t),s=this.instantiateQuotedObject(e.object,t);return new S7.QuotedTriple(r,i,s)}instantiateQuotedSubject(e,t){if(e.type==="variable"){let r=t.get(e.value);if(!r)throw new Error(`Unbound variable in quoted triple subject: ${e.value}`);if(r instanceof Aw.Literal)throw new Error("Literals cannot appear in quoted triple subject position");return r}if(e.type==="iri")return new cc.IRI(e.value);if(e.type==="blank")return new Iw.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 r=t.get(e.value);if(!r)throw new Error(`Unbound variable in quoted triple predicate: ${e.value}`);if(!(r instanceof cc.IRI))throw new Error("Quoted triple predicate must be an IRI");return r}return new cc.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 cc.IRI(e.value);if(e.type==="blank")return new Iw.BlankNode(e.value);if(e.type==="literal")return new Aw.Literal(e.value,e.datatype?new cc.IRI(e.datatype):void 0,e.language);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);let r=e;throw new Error(`Invalid element type for quoted triple object: ${r.type}`)}};Cm.ConstructExecutor=xw});var XR=w(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});Fl.ServiceExecutor=Fl.ServiceExecutorError=void 0;var w7=_s(),QR=Oe(),v7=qe(),E7=Bt(),lc=class extends Error{static{a(this,"ServiceExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ServiceExecutorError"}};Fl.ServiceExecutorError=lc;var Cw=class{static{a(this,"ServiceExecutor")}constructor(e={}){this.timeout=e.timeout??3e4,this.httpClient=e.httpClient??((t,r)=>fetch(t,r)),this.maxRetries=e.maxRetries??2,this.retryDelay=e.retryDelay??1e3}async*execute(e,t){try{let r=t(e.pattern),i=await this.executeRemoteQuery(e.endpoint,r);for(let s of i)yield s}catch(r){if(e.silent)return;throw r}}async executeRemoteQuery(e,t){let r;for(let i=0;i<=this.maxRetries;i++)try{let s=new AbortController,o=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 lc(`Remote SPARQL endpoint returned ${c.status}: ${c.statusText}`);let l=await c.json();return this.parseJsonResults(l)}finally{clearTimeout(o)}}catch(s){if(r=s instanceof Error?s:new Error(String(s)),this.isRetryableError(r)&&i<this.maxRetries){await this.delay(this.retryDelay);continue}throw new lc(`Failed to query remote SPARQL endpoint ${e}: ${r.message}`,r)}throw new lc(`Failed to query remote SPARQL endpoint ${e} after ${this.maxRetries+1} attempts`,r)}parseJsonResults(e){return!e.results||!Array.isArray(e.results.bindings)?[]:e.results.bindings.map(t=>this.parseBinding(t))}parseBinding(e){let t=new w7.SolutionMapping;for(let[r,i]of Object.entries(e)){let s=this.parseRDFTerm(i);t.set(r,s)}return t}parseRDFTerm(e){switch(e.type){case"uri":return new QR.IRI(e.value);case"literal":{let t=e.datatype?new QR.IRI(e.datatype):void 0;return new v7.Literal(e.value,t,e["xml:lang"])}case"bnode":return new E7.BlankNode(e.value);default:throw new lc(`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))}};Fl.ServiceExecutor=Cw});var JR=w(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});Ll.GraphExecutor=Ll.GraphExecutorError=void 0;var YR=Oe(),Pm=class extends Error{static{a(this,"GraphExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="GraphExecutorError"}};Ll.GraphExecutorError=Pm;var Pw=class{static{a(this,"GraphExecutor")}constructor(e){this.tripleStore=e}async*execute(e,t,r){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,r);else throw new Pm(`Invalid graph name type: ${i.type}`)}async*executeWithGraph(e,t,r){let i=new YR.IRI(t.value);this.tripleStore.hasGraph&&!await this.tripleStore.hasGraph(i)||(yield*r(e,i))}async*executeWithGraphVariable(e,t,r,i){if(i){let o=i.get(t.value);if(o&&o instanceof YR.IRI){yield*this.executeWithGraph(e.pattern,{type:"iri",value:o.value},r);return}}if(!this.tripleStore.getNamedGraphs)return;let s=await this.tripleStore.getNamedGraphs();for(let o of s)for await(let c of r(e.pattern,o)){let l=c.clone();l.set(t.value,o),yield l}}};Ll.GraphExecutor=Pw});var ZR=w(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.SPARQLGenerator=kl.SPARQLGeneratorError=void 0;var Nl=class extends Error{static{a(this,"SPARQLGeneratorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="SPARQLGeneratorError"}};kl.SPARQLGeneratorError=Nl;var Ow=class{static{a(this,"SPARQLGenerator")}collectVariables(e){let t=new Set;return this.collectVariablesFromOperation(e,t),t}generateSelect(e){let t=this.collectVariables(e),r=t.size>0?Array.from(t).map(s=>`?${s}`).join(" "):"*",i=this.generateWhereClause(e);return`SELECT ${r} WHERE {
|
|
48
|
+
`,s);l!==-1?(i+=e.substring(s,l),s=l):(i+=e.substring(s),s=e.length);continue}let c=this.tryReplacePrefixedName(e,s,r);if(c){i+=c.iri,s=c.endIndex;continue}i+=o,s++}return i}tryReplacePrefixedName(e,t,r){if(t>0&&/[a-zA-Z0-9_]/.test(e[t-1]))return null;for(let{prefix:i,baseIRI:s}of r){if(e.substring(t,t+i.length+1)!==i+":")continue;let o=t+i.length+1,c=o;for(;c<e.length&&/[a-zA-Z0-9_.%-]/.test(e[c]);)c++;if(c===o)continue;let l=e.substring(o,c);return{iri:`<${s}${l}.md>`,endIndex:c}}return null}findDeclaredPrefixes(e){let t=new Set,r=new RegExp(M6.source,"gi"),i;for(;(i=r.exec(e))!==null;)t.add(i[1].toLowerCase());return t}skipLiteral(e,t){let r=e[t];if(t+2<e.length&&e.substring(t,t+3)===r+r+r){let s=e.indexOf(r+r+r,t+3);return s!==-1?s+3:e.length}let i=t+1;for(;i<e.length&&e[i]!==r;)e[i]==="\\"&&i++,i++;return i<e.length?i+1:e.length}};Hh.VaultPrefixTransformer=kS});var ml=w(Ln=>{"use strict";var $6=Ln&&Ln.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:a(function(){return e[t]},"get")}),Object.defineProperty(n,r,i)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),U6=Ln&&Ln.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),B6=Ln&&Ln.__importStar||(function(){var n=a(function(e){return n=Object.getOwnPropertyNames||function(t){var r=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[r.length]=i);return r},n(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=n(e),i=0;i<r.length;i++)r[i]!=="default"&&$6(t,e,r[i]);return U6(t,e),t}})();Object.defineProperty(Ln,"__esModule",{value:!0});Ln.SPARQLParser=Ln.ExoQLParser=Ln.SPARQLParseError=void 0;var dR=B6(cR()),jS=PS(),$S=OS(),pR=lR(),US=FS(),V6=uR(),BS=fR(),G6=MS(),pr=class extends Error{static{a(this,"SPARQLParseError")}constructor(e,t,r,i){super(e,i?{cause:i}:void 0),this.name="SPARQLParseError",this.line=t,this.column=r}};Ln.SPARQLParseError=pr;var Kh=class{static{a(this,"ExoQLParser")}constructor(e){this.lastDirectionMappings=new Map,this.parser=new dR.Parser({sparqlStar:!0}),this.generator=new dR.Generator({sparqlStar:!0}),this.caseWhenTransformer=new jS.CaseWhenTransformer,this.lateralTransformer=new $S.LateralTransformer,this.prefixStarTransformer=new pR.PrefixStarTransformer(e?.vocabularyResolver),this.describeOptionsTransformer=new US.DescribeOptionsTransformer,this.directionalLangTagTransformer=new V6.DirectionalLangTagTransformer,this.tripleTermTransformer=new BS.TripleTermTransformer,this.vaultPrefixTransformer=new G6.VaultPrefixTransformer}setVaultPrefixes(e){this.vaultPrefixTransformer.setVaultPrefixes(e)}parse(e){try{let t=this.vaultPrefixTransformer.transform(e),r=this.describeOptionsTransformer.transform(t);this.lastDescribeOptions=r.options;let i=r.query;i=this.directionalLangTagTransformer.transform(i),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),i=this.lateralTransformer.transform(i),i=this.caseWhenTransformer.transform(i),i=this.tripleTermTransformer.transform(i);let s=this.parser.parse(i);return this.validateQuery(s),this.lastDescribeOptions&&this.isDescribeQuery(s)&&(s.describeOptions=this.lastDescribeOptions),s}catch(t){if(t instanceof US.DescribeOptionsTransformerError)throw new pr(t.message);if(t instanceof $S.LateralTransformerError)throw new pr(t.message);if(t instanceof jS.CaseWhenTransformerError)throw new pr(t.message);if(t instanceof BS.TripleTermTransformerError)throw new pr(t.message);if(t instanceof Error){let r=t.message.match(/line (\d+), column (\d+)/),i=r?parseInt(r[1],10):void 0,s=r?parseInt(r[2],10):void 0;throw new pr(`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.vaultPrefixTransformer.transform(e),r=this.describeOptionsTransformer.transform(t);this.lastDescribeOptions=r.options;let i=r.query;i=this.directionalLangTagTransformer.transform(i),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),i=await this.prefixStarTransformer.transform(i),i=this.lateralTransformer.transform(i),i=this.caseWhenTransformer.transform(i),i=this.tripleTermTransformer.transform(i);let s=this.parser.parse(i);return this.validateQuery(s),this.lastDescribeOptions&&this.isDescribeQuery(s)&&(s.describeOptions=this.lastDescribeOptions),s}catch(t){if(t instanceof US.DescribeOptionsTransformerError)throw new pr(t.message);if(t instanceof pR.PrefixStarTransformerError)throw new pr(t.message);if(t instanceof $S.LateralTransformerError)throw new pr(t.message);if(t instanceof jS.CaseWhenTransformerError)throw new pr(t.message);if(t instanceof BS.TripleTermTransformerError)throw new pr(t.message);if(t instanceof Error){let r=t.message.match(/line (\d+), column (\d+)/),i=r?parseInt(r[1],10):void 0,s=r?parseInt(r[2],10):void 0;throw new pr(`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 pr(`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 pr("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 pr("Invalid query: not an object");if(e.type!=="query"&&e.type!=="update")throw new pr(`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 pr(`Invalid query type: expected one of ${t.join(", ")}, got "${e.queryType}"`)}}};Ln.ExoQLParser=Kh;Ln.SPARQLParser=Kh});var ic=w(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});Qh.AlgebraTranslatorError=void 0;var VS=class extends Error{static{a(this,"AlgebraTranslatorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AlgebraTranslatorError"}};Qh.AlgebraTranslatorError=VS});var Xh=w(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.isVariableExpression=q6;bs.isVariableTerm=W6;bs.isNamedNode=z6;bs.isLiteral=H6;bs.isPropertyPath=K6;bs.isAggregateExpression=Q6;bs.isOperationExpression=X6;bs.isFunctionCallExpression=Y6;function q6(n){return typeof n=="object"&&n!==null&&"expression"in n&&"variable"in n}a(q6,"isVariableExpression");function W6(n){return typeof n=="object"&&n!==null&&"termType"in n&&n.termType==="Variable"}a(W6,"isVariableTerm");function z6(n){return typeof n=="object"&&n!==null&&"termType"in n&&n.termType==="NamedNode"}a(z6,"isNamedNode");function H6(n){return typeof n=="object"&&n!==null&&"termType"in n&&n.termType==="Literal"}a(H6,"isLiteral");function K6(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="path"}a(K6,"isPropertyPath");function Q6(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="aggregate"}a(Q6,"isAggregateExpression");function X6(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="operation"}a(X6,"isOperationExpression");function Y6(n){return typeof n=="object"&&n!==null&&"type"in n&&(n.type==="functionCall"||n.type==="functioncall")}a(Y6,"isFunctionCallExpression")});var hR=w(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});Yh.TripleTranslator=void 0;var pn=ic(),GS=class{static{a(this,"TripleTranslator")}constructor(){this.directionMappings=new Map}setDirectionMappings(e){this.directionMappings=e}translateBGP(e){if(!("triples"in e)||!Array.isArray(e.triples))throw new pn.AlgebraTranslatorError("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 pn.AlgebraTranslatorError("Triple must have subject, predicate, and object");return{subject:this.translateTripleElement(e.subject),predicate:this.translatePredicate(e.predicate),object:this.translateTripleElement(e.object)}}translateConstructTemplate(e){return!e||!Array.isArray(e)?[]:e.map(t=>this.translateTriple(t))}translatePredicate(e){return"type"in e&&e.type==="path"?this.translatePropertyPath(e):this.translateTripleElement(e)}translatePropertyPath(e){if(!("pathType"in e)||!e.pathType)throw new pn.AlgebraTranslatorError("Property path must have pathType");if(!("items"in e)||!Array.isArray(e.items))throw new pn.AlgebraTranslatorError("Property path must have items array");let t=e.items.map(r=>this.translatePathItem(r));switch(e.pathType){case"/":return{type:"path",pathType:"/",items:t};case"|":return{type:"path",pathType:"|",items:t};case"^":if(t.length!==1)throw new pn.AlgebraTranslatorError("Inverse path must have exactly one item");return{type:"path",pathType:"^",items:[t[0]]};case"+":if(t.length!==1)throw new pn.AlgebraTranslatorError("OneOrMore path must have exactly one item");return{type:"path",pathType:"+",items:[t[0]]};case"*":if(t.length!==1)throw new pn.AlgebraTranslatorError("ZeroOrMore path must have exactly one item");return{type:"path",pathType:"*",items:[t[0]]};case"?":if(t.length!==1)throw new pn.AlgebraTranslatorError("ZeroOrOne path must have exactly one item");return{type:"path",pathType:"?",items:[t[0]]};default:throw new pn.AlgebraTranslatorError(`Unsupported property path type: ${e.pathType}`)}}translatePathItem(e){if("type"in e&&e.type==="path")return this.translatePropertyPath(e);if("termType"in e&&e.termType==="NamedNode")return{type:"iri",value:e.value};let t="type"in e?e.type:"termType"in e?e.termType:"unknown";throw new pn.AlgebraTranslatorError(`Unsupported path item type: ${String(t)}`)}translateTripleElement(e){if(!e||!("termType"in e))throw new pn.AlgebraTranslatorError("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 r=this.directionMappings.get(e.language.toLowerCase());r&&(t.direction=r)}return t}case"BlankNode":return{type:"blank",value:e.value};case"Quad":return this.translateQuotedTriple(e);default:throw new pn.AlgebraTranslatorError(`Unsupported term type: ${e.termType}`)}}translateQuotedTriple(e){if(!e.subject||!e.predicate||!e.object)throw new pn.AlgebraTranslatorError("Quoted triple must have subject, predicate, and object");return{type:"quoted",subject:this.translateTripleElement(e.subject),predicate:this.translateQuotedTriplePredicate(e.predicate),object:this.translateTripleElement(e.object)}}translateQuotedTriplePredicate(e){if(!e||!("termType"in e))throw new pn.AlgebraTranslatorError("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 pn.AlgebraTranslatorError(`Quoted triple predicate must be IRI or Variable, got: ${e.termType}`)}}};Yh.TripleTranslator=GS});var mR=w(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0});Jh.ExpressionTranslator=void 0;var gl=ic(),qS=class{static{a(this,"ExpressionTranslator")}constructor(e){this.translateWhereFn=e.translateWhere,this.translateBGPFn=e.translateBGP,this.translatePatternFn=e.translatePattern}translateExpression(e){if(!e)throw new gl.AlgebraTranslatorError("Expression cannot be null or undefined");if("type"in e&&e.type==="operation")return this.translateOperationExpression(e);let t="type"in e?e.type:void 0;if(t==="functioncall"||t==="functionCall"){let r=e;return{type:"functionCall",function:r.function,args:r.args.map(i=>this.translateExpression(i))}}if("termType"in e)return this.translateTermExpression(e);throw new gl.AlgebraTranslatorError(`Unsupported expression structure: ${JSON.stringify(e)}`)}translateFilter(e){if(!e.expression)throw new gl.AlgebraTranslatorError("Filter pattern must have expression");let t={type:"bgp",triples:[]};return{type:"filter",expression:this.translateExpression(e.expression),input:t}}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)}}translateOperationExpression(e){let t=["=","!=","<",">","<=",">="],r=["&&","||","!"],i=["+","-","*","/"],s=e.args.filter(o=>!("patterns"in o)||"termType"in o);return t.includes(e.operator)?{type:"comparison",operator:e.operator,left:this.translateExpression(s[0]),right:this.translateExpression(s[1])}:r.includes(e.operator)?{type:"logical",operator:e.operator,operands:s.map(o=>this.translateExpression(o))}:i.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:this.translateExpression(s[0]),right:this.translateExpression(s[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:s.map(o=>this.translateExpression(o))}}translateExistsExpression(e){if(!e.args||e.args.length!==1)throw new gl.AlgebraTranslatorError("EXISTS/NOT EXISTS must have exactly one pattern argument");let t=e.args[0],r;return t.type==="group"&&"patterns"in t&&t.patterns?r=this.translateWhereFn(t.patterns):t.type==="bgp"?r=this.translateBGPFn(t):r=this.translatePatternFn(t),{type:"exists",negated:e.operator==="notexists",pattern:r}}translateInExpression(e){if(!e.args||e.args.length!==2)throw new gl.AlgebraTranslatorError("IN/NOT IN must have exactly 2 arguments (expression and list)");let t=e.args[0],r=e.args[1];if(!Array.isArray(r))throw new gl.AlgebraTranslatorError("IN/NOT IN second argument must be an array of values");return{type:"in",expression:this.translateExpression(t),list:r.map(i=>this.translateExpression(i)),negated:e.operator==="notin"}}};Jh.ExpressionTranslator=qS});var bR=w(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});Zh.PatternTranslator=void 0;var gR=OS(),$r=ic(),yR=Xh(),WS=class{static{a(this,"PatternTranslator")}constructor(e){this.directionMappings=new Map,this.translateExpressionFn=e.translateExpression,this.translateSelectFn=e.translateSelect,this.translateBGPFn=e.translateBGP}setDirectionMappings(e){this.directionMappings=e}translateWhere(e){if(e.length===0)throw new $r.AlgebraTranslatorError("Empty WHERE clause");let t=e.filter(o=>o.type==="filter"),r=e.filter(o=>o.type==="bind"),i=e.filter(o=>o.type!=="filter"&&o.type!=="bind"),s;if(i.length===0)s={type:"bgp",triples:[]};else if(i.length===1)if(i[0].type==="optional"){let o=i[0].expression;s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:o?this.translateExpressionFn(o):void 0}}else s=this.translatePattern(i[0]);else{if(i[0].type==="optional"){let o=i[0].expression;s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:o?this.translateExpressionFn(o):void 0}}else s=this.translatePattern(i[0]);for(let o=1;o<i.length;o++){let c=i[o];if(this.isLateralPattern(c)){let l=this.extractLateralSubquery(c),u=this.removeLateralMarker(l),f=this.translateSelectFn(u);s={type:"lateraljoin",left:s,right:f}}else if(c.type==="optional"){let l=c.expression;s={type:"leftjoin",left:s,right:this.translateWhere(c.patterns),expression:l?this.translateExpressionFn(l):void 0}}else{let l=this.translatePattern(c);s={type:"join",left:s,right:l}}}}for(let o of r)s=this.translateBind(o,s);for(let o of t)s={type:"filter",expression:this.translateExpressionFn(o.expression),input:s};return s}translatePattern(e){if(!e||!e.type)throw new $r.AlgebraTranslatorError("Invalid pattern: missing type");switch(e.type){case"bgp":return this.translateBGPFn(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 $r.AlgebraTranslatorError(`Unsupported pattern type: ${e.type}`)}}translateFilter(e){if(!e.expression)throw new $r.AlgebraTranslatorError("Filter pattern must have expression");let t={type:"bgp",triples:[]};return{type:"filter",expression:this.translateExpressionFn(e.expression),input:t}}translateOptional(e){if(!e.patterns||e.patterns.length===0)throw new $r.AlgebraTranslatorError("OPTIONAL pattern must have patterns");let t=e.expression;return{type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns),expression:t?this.translateExpressionFn(t):void 0}}translateUnion(e){if(!e.patterns||e.patterns.length<2)throw new $r.AlgebraTranslatorError("UNION pattern must have at least 2 patterns");let t=a(i=>i.type==="graph"?this.translateGraph(i):i.type==="service"?this.translateService(i):"patterns"in i&&i.patterns&&Array.isArray(i.patterns)?this.translateWhere(i.patterns):this.translateWhere([i]),"translateBranch"),r={type:"union",left:t(e.patterns[0]),right:t(e.patterns[1])};for(let i=2;i<e.patterns.length;i++)r={type:"union",left:r,right:t(e.patterns[i])};return r}translateMinus(e){if(!e.patterns||e.patterns.length===0)throw new $r.AlgebraTranslatorError("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 $r.AlgebraTranslatorError("VALUES pattern must have values array");let t=new Set;for(let i of e.values)for(let s of Object.keys(i)){let o=s.startsWith("?")?s.slice(1):s;t.add(o)}let r=e.values.map(i=>this.translateValuesBinding(i));return{type:"values",variables:Array.from(t),bindings:r}}translateValuesBinding(e){let t={};for(let[r,i]of Object.entries(e)){let s=r.startsWith("?")?r.slice(1):r,o=i;if(o)if(o.termType==="NamedNode")t[s]={type:"iri",value:o.value};else if(o.termType==="Literal"){let c=o,l={type:"literal",value:c.value,datatype:c.datatype?.value,language:c.language||void 0};if(c.language){let u=this.directionMappings.get(c.language.toLowerCase());u&&(l.direction=u)}t[s]=l}else throw new $r.AlgebraTranslatorError(`Unsupported VALUES term type: ${o.termType}`)}return t}translateBind(e,t){if(!e.variable||!e.expression)throw new $r.AlgebraTranslatorError("BIND pattern must have variable and expression");return{type:"extend",variable:e.variable.value,expression:this.translateExpressionFn(e.expression),input:t}}translateSubquery(e){if(e.queryType!=="SELECT")throw new $r.AlgebraTranslatorError(`Only SELECT subqueries are supported, got: ${String(e.queryType)}`);let t=this.removeLateralMarker(e);return{type:"subquery",query:this.translateSelectFn(t)}}translateService(e){if(!e.name||e.name.termType!=="NamedNode")throw new $r.AlgebraTranslatorError("SERVICE pattern must have a NamedNode endpoint");if(!e.patterns||!Array.isArray(e.patterns))throw new $r.AlgebraTranslatorError("SERVICE pattern must have patterns array");return{type:"service",endpoint:e.name.value,pattern:this.translateWhere(e.patterns),silent:e.silent||!1}}translateGraph(e){if(!e.name)throw new $r.AlgebraTranslatorError("GRAPH pattern must have a name (IRI or variable)");if(!e.patterns||!Array.isArray(e.patterns))throw new $r.AlgebraTranslatorError("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 $r.AlgebraTranslatorError(`GRAPH pattern name must be NamedNode or Variable, got: ${e.name.termType}`);return{type:"graph",name:t,pattern:this.translateWhere(e.patterns)}}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){let t=e.patterns[0];if(t.type==="query")return t}throw new $r.AlgebraTranslatorError("Invalid lateral pattern structure")}isLateralSubquery(e){return!("queryType"in e)||e.queryType!=="SELECT"||!("variables"in e)||!e.variables?!1:e.variables.some(i=>(0,yR.isVariableTerm)(i)&&i.value===gR.LateralTransformer.LATERAL_MARKER)}removeLateralMarker(e){if(!("variables"in e)||!e.variables)return e;let t=e,r=t.variables;return{...t,variables:r.filter(i=>!((0,yR.isVariableTerm)(i)&&i.value===gR.LateralTransformer.LATERAL_MARKER))}}};Zh.PatternTranslator=WS});var SR=w(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.AggregateTranslator=void 0;var _R=ic(),J6=Xh(),zS=class{static{a(this,"AggregateTranslator")}constructor(e){this.aggregateCounter=0,this.translateExpressionFn=e.translateExpression}resetCounter(){this.aggregateCounter=0}extractAggregatesWithMapping(e,t){if(!e)return[];let r=[];for(let i of e)(0,J6.isVariableExpression)(i)&&("type"in i.expression&&i.expression.type==="aggregate"?(r.push({variable:i.variable.value,expression:this.translateAggregateExpression(i.expression)}),t.set(i.expression,i.variable.value)):this.collectNestedAggregates(i.expression,r,t));return r}extractGroupVariables(e){return e?e.filter(t=>t.expression&&"termType"in t.expression&&t.expression.termType==="Variable").map(t=>t.expression.value):[]}extractHavingExpressions(e,t,r){if(!e||e.length===0)return[];for(let i of e)this.collectNestedAggregates(i,t,r);return e.map(i=>this.transformExpressionWithAggregateVars(i,r))}transformExpressionWithAggregateVars(e,t){let r=t.get(e);if(r!==void 0)return{type:"variable",name:r};if("type"in e&&e.type==="operation"&&"args"in e){let i=e,s=i.args.filter(u=>!Array.isArray(u)&&!("patterns"in u)).map(u=>this.transformExpressionWithAggregateVars(u,t)),o=["=","!=","<",">","<=",">="],c=["&&","||","!"],l=["+","-","*","/"];return o.includes(i.operator)?{type:"comparison",operator:i.operator,left:s[0],right:s[1]}:c.includes(i.operator)?{type:"logical",operator:i.operator,operands:s}:l.includes(i.operator)?{type:"arithmetic",operator:i.operator,left:s[0],right:s[1]}:{type:"function",function:i.operator,args:s}}return this.translateExpressionFn(e)}translateOrderComparator(e){return{expression:this.translateExpressionFn(e.expression),descending:e.descending||!1}}translateAggregateExpression(e){let t=e.aggregation,r=a(()=>{if(e.expression&&!("termType"in e.expression&&e.expression.termType==="Wildcard"))return this.translateExpressionFn(e.expression)},"translateInnerExpr");if(typeof t=="string"){let s=t.toLowerCase();return["count","sum","avg","min","max","group_concat","sample"].includes(s)?{type:"aggregate",aggregation:s,expression:r(),distinct:e.distinct||!1,separator:e.separator}:{type:"aggregate",aggregation:{type:"custom",iri:t},expression:r(),distinct:e.distinct||!1,separator:e.separator}}let i=t;if(i&&typeof i=="object"){let s,o=i;if(o.termType==="NamedNode"&&typeof o.value=="string")s=o.value;else if("value"in o)s=String(o.value);else throw new _R.AlgebraTranslatorError(`Invalid custom aggregate: expected IRI but got ${JSON.stringify(i)}`);return{type:"aggregate",aggregation:{type:"custom",iri:s},expression:r(),distinct:e.distinct||!1,separator:e.separator}}throw new _R.AlgebraTranslatorError(`Unknown aggregate format: ${JSON.stringify(t)}`)}collectNestedAggregates(e,t,r){if(e){if("type"in e&&e.type==="aggregate"){let i=`__agg${this.aggregateCounter++}`;t.push({variable:i,expression:this.translateAggregateExpression(e)}),r.set(e,i)}else if("type"in e&&e.type==="operation"&&"args"in e){let i=e;for(let s of i.args)!Array.isArray(s)&&"type"in s&&!("patterns"in s)?this.collectNestedAggregates(s,t,r):"termType"in s&&this.collectNestedAggregates(s,t,r)}}}};em.AggregateTranslator=zS});var yl=w(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.AlgebraTranslator=Jo.ExoQLAlgebraTranslator=Jo.AlgebraTranslatorError=void 0;var tm=ic(),rm=Xh(),Z6=hR(),e7=mR(),t7=bR(),r7=SR(),n7=ic();Object.defineProperty(Jo,"AlgebraTranslatorError",{enumerable:!0,get:a(function(){return n7.AlgebraTranslatorError},"get")});var nm=class{static{a(this,"ExoQLAlgebraTranslator")}constructor(){this.tripleTranslator=new Z6.TripleTranslator,this.expressionTranslator=new e7.ExpressionTranslator({translateWhere:a(e=>this.patternTranslator.translateWhere(e),"translateWhere"),translateBGP:a(e=>this.tripleTranslator.translateBGP(e),"translateBGP"),translatePattern:a(e=>this.patternTranslator.translatePattern(e),"translatePattern")}),this.patternTranslator=new t7.PatternTranslator({translateExpression:a(e=>this.expressionTranslator.translateExpression(e),"translateExpression"),translateSelect:a(e=>this.translateSelect(e),"translateSelect"),translateBGP:a(e=>this.tripleTranslator.translateBGP(e),"translateBGP")}),this.aggregateTranslator=new r7.AggregateTranslator({translateExpression:a(e=>this.expressionTranslator.translateExpression(e),"translateExpression")})}setDirectionMappings(e){this.tripleTranslator.setDirectionMappings(e),this.patternTranslator.setDirectionMappings(e)}translate(e){if(e.type!=="query")throw new tm.AlgebraTranslatorError("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 tm.AlgebraTranslatorError(`Query type ${String(e.queryType)} not yet supported`)}translateSelect(e){if(!e.where||e.where.length===0)throw new tm.AlgebraTranslatorError("SELECT query must have WHERE clause");let t=this.patternTranslator.translateWhere(e.where);this.aggregateTranslator.resetCounter();let r=new Map,i=Array.isArray(e.variables)?e.variables.filter(l=>!("termType"in l&&l.termType==="Wildcard")):[],s=this.aggregateTranslator.extractAggregatesWithMapping(i,r),o=this.aggregateTranslator.extractGroupVariables(e.group),c=this.aggregateTranslator.extractHavingExpressions(e.having,s,r);if((s.length>0||o.length>0||c.length>0)&&(t={type:"group",variables:o,aggregates:s,having:c.length>0?c:void 0,input:t}),i.length>0){for(let l of i)if((0,rm.isVariableExpression)(l)){if("type"in l.expression&&l.expression.type==="aggregate")continue;let u=this.aggregateTranslator.transformExpressionWithAggregateVars(l.expression,r);t={type:"extend",variable:l.variable.value,expression:u,input:t}}}if(e.order&&e.order.length>0&&(t={type:"orderby",comparators:e.order.map(l=>this.aggregateTranslator.translateOrderComparator(l)),input:t}),i.length>0){let l=i.filter(u=>(0,rm.isVariableTerm)(u)||(0,rm.isVariableExpression)(u)).map(u=>(0,rm.isVariableTerm)(u)?u.value:u.variable.value);l.length>0&&(t={type:"project",variables:l,input:t})}return e.distinct&&(t={type:"distinct",input:t}),e.reduced&&(t={type:"reduced",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.tripleTranslator.translateConstructTemplate(e.template??[]);if(!e.where||e.where.length===0)throw new tm.AlgebraTranslatorError("CONSTRUCT query must have WHERE clause");let r=this.patternTranslator.translateWhere(e.where),i=e;return(i.limit!==void 0||i.offset!==void 0)&&(r={type:"slice",limit:i.limit,offset:i.offset,input:r}),{type:"construct",template:t,where:r}}translateAsk(e){return{type:"ask",where:e.where&&e.where.length>0?this.patternTranslator.translateWhere(e.where):{type:"bgp",triples:[]}}}translateDescribe(e){let t=[];if(e.variables&&Array.isArray(e.variables)){let s=e.variables;for(let o of s)o.termType==="Wildcard"||o.value==="*"||(o.termType==="Variable"?t.push({type:"variable",value:o.value}):o.termType==="NamedNode"&&t.push({type:"iri",value:o.value}))}let r;e.where&&e.where.length>0&&(r=this.patternTranslator.translateWhere(e.where));let i=e.describeOptions;return{type:"describe",resources:t,where:r,depth:i?.depth,symmetric:i?.symmetric}}};Jo.ExoQLAlgebraTranslator=nm;Jo.AlgebraTranslator=nm});var _s=w(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});im.SolutionMapping=void 0;var wR=qe(),vR=Oe(),ER=Bt(),HS=class n{static{a(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,r]of this.bindings.entries()){let i=e.get(t);if(i!==void 0&&!this.areEqual(r,i))return!1}return!0}merge(e){if(!this.isCompatibleWith(e))return null;let t=new n(this.bindings);for(let[r,i]of e.getBindings().entries())t.set(r,i);return t}clone(){return new n(this.bindings)}areEqual(e,t){return e instanceof wR.Literal&&t instanceof wR.Literal?e.equals(t):e instanceof vR.IRI&&t instanceof vR.IRI?e.value===t.value:e instanceof ER.BlankNode&&t instanceof ER.BlankNode?e.id===t.id:!1}toJSON(){let e={};for(let[t,r]of this.bindings.entries())e[t]=r.toString();return e}size(){return this.bindings.size}};im.SolutionMapping=HS});var AR=w(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});_l.PropertyPathExecutor=_l.PropertyPathExecutorError=void 0;var i7=_s(),sm=Oe(),TR=Bt(),s7=qe(),bl=class extends Error{static{a(this,"PropertyPathExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="PropertyPathExecutorError"}};_l.PropertyPathExecutorError=bl;var KS=class n{static{a(this,"PropertyPathExecutor")}constructor(e){this.tripleStore=e,this.MAX_DEPTH=100}async*execute(e,t,r){if(this.isLiteralElement(e)||this.isLiteralElement(r)){let o=this.isLiteralElement(e)?"subject":"object",c=this.isLiteralElement(e)?e:r,l="value"in c?String(c.value):"<unknown>",u=l.length>80?`${l.slice(0,77)}...`:l,f=this.describePath(t),d={position:o,value:u,path:f,hint:"Wikilink could not be resolved to IRI (likely label-form wikilink with no matching basename/alias). Check whether the target file exists in the queried vault, add an alias, or load the target vault via --also. See issue #3282."};if(console.error(`[PropertyPathExecutor] literal-safety guard fired: literal in ${o} position \u2014 yielding 0 solutions. value="${u}" path=${f}`,d),n.isStrictModeEnabled())throw new bl(`Literal subject in property path: "${u}" (path=${f}). Set EXOCORTEX_SPARQL_STRICT=0 or omit --strict to fall back to warn-and-empty behaviour.`);return}let i=await this.resolveElement(e),s=this.isVariable(r)?null:await this.resolveElement(r);for(let o of i){let c=await this.evaluatePath(o,t,s);for(let l of c){let u=new i7.SolutionMapping;this.isVariable(e)&&u.set(e.value,o),this.isVariable(r)&&u.set(r.value,l),yield u}}}async*executeWithBindings(e,t){if(!this.isPropertyPath(e.predicate))throw new bl("Predicate is not a property path");let r=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.object,t);for await(let s of this.execute(r,e.predicate,i)){let o=t.merge(s);o!==null&&(yield o)}}async evaluatePath(e,t,r){switch(t.pathType){case"/":return this.evaluateSequencePath(e,t.items,r);case"|":return this.evaluateAlternativePath(e,t.items,r);case"^":return this.evaluateInversePath(e,t.items[0],r);case"+":return this.evaluateOneOrMorePath(e,t.items[0],r);case"*":return this.evaluateZeroOrMorePath(e,t.items[0],r);case"?":return this.evaluateZeroOrOnePath(e,t.items[0],r)}}async evaluateSequencePath(e,t,r){let i=new Set([e]);for(let s=0;s<t.length;s++){let o=t[s],c=s===t.length-1,l=new Set;for(let u of i){let f=await this.evaluatePathItem(u,o,c?r:null);for(let d of f)l.add(d)}if(i=l,i.size===0)break}return i}async evaluateAlternativePath(e,t,r){let i=new Set;for(let s of t){let o=await this.evaluatePathItem(e,s,r);for(let c of o)i.add(c)}return i}async evaluateInversePath(e,t,r){if(t.type==="iri"){let i=new sm.IRI(t.value),s=await this.tripleStore.match(void 0,i,e),o=new Set;for(let c of s)(r===null||this.nodeInSet(c.subject,r))&&o.add(c.subject);return o}else return this.evaluatePath(e,this.invertPath(t),r)}async evaluateOneOrMorePath(e,t,r){let i=new Set,s=new Set,o=[{node:e,depth:0}];for(;o.length>0;){let c=o.shift();if(!c)break;let{node:l,depth:u}=c;if(u>=this.MAX_DEPTH)continue;let f=await this.evaluatePathItem(l,t,null);for(let d of f){let p=this.nodeToKey(d);(r===null||this.nodeInSet(d,r))&&s.add(d),i.has(p)||(i.add(p),o.push({node:d,depth:u+1}))}}return s}async evaluateZeroOrMorePath(e,t,r){let i=await this.evaluateOneOrMorePath(e,t,r);return(r===null||this.nodeInSet(e,r))&&i.add(e),i}async evaluateZeroOrOnePath(e,t,r){let i=new Set;(r===null||this.nodeInSet(e,r))&&i.add(e);let s=await this.evaluatePathItem(e,t,r);for(let o of s)i.add(o);return i}async evaluatePathItem(e,t,r){if(t.type==="iri"){let i=new sm.IRI(t.value),s=await this.tripleStore.match(e,i,void 0),o=new Set;for(let c of s)(r===null||this.nodeInSet(c.object,r))&&o.add(c.object);return o}else return this.evaluatePath(e,t,r)}invertPath(e){switch(e.pathType){case"^":return e.items[0];case"/":return{type:"path",pathType:"/",items:[...e.items].reverse().map(t=>t.type==="iri"?{type:"path",pathType:"^",items:[t]}:this.invertPath(t))};case"|":return{type:"path",pathType:"|",items:e.items.map(t=>t.type==="iri"?{type:"path",pathType:"^",items:[t]}:this.invertPath(t))};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 r=new Set,i=await this.tripleStore.match(void 0,void 0,void 0);for(let s of i)r.add(s.subject),r.add(s.object);return r}let t=new Set;switch(e.type){case"iri":t.add(new sm.IRI(e.value));break;case"blank":t.add(new TR.BlankNode(e.value));break;default:throw new bl(`Unsupported element type in subject/object position: ${e.type}`)}return t}instantiateElement(e,t){if(this.isVariable(e)){let r=t.get(e.value);if(r){if(r instanceof sm.IRI)return{type:"iri",value:r.value};if(r instanceof TR.BlankNode)return{type:"blank",value:r.id};if(r instanceof s7.Literal)return{type:"literal",value:r.value,datatype:r.datatype?.value,language:r.language,direction:r.direction}}}return e}isVariable(e){return e.type==="variable"}isLiteralElement(e){return e.type==="literal"}isPropertyPath(e){return e.type==="path"}nodeToKey(e){return e.toString()}nodeInSet(e,t){let r=this.nodeToKey(e);for(let i of t)if(this.nodeToKey(i)===r)return!0;return!1}describePath(e){try{let t=e.items,r=a(s=>{if(s&&typeof s=="object"&&"type"in s){let o=s;if(o.type==="iri")return`<${String(o.value)}>`;if(o.type==="path")return this.describePath(o)}return"?"},"renderItem");if(!Array.isArray(t)||t.length===0)return"(?)";if(t.length===1){let s=r(t[0]);return e.pathType==="^"?`(^${s})`:e.pathType==="+"||e.pathType==="*"||e.pathType==="?"?`(${s}${e.pathType})`:`(${s})`}return`(${t.map(r).join(` ${e.pathType} `)})`}catch{return"<unprintable-path>"}}static isStrictModeEnabled(){let t=(typeof process<"u"?process.env:void 0)?.EXOCORTEX_SPARQL_STRICT;if(!t)return!1;let r=t.trim().toLowerCase();return r==="1"||r==="true"||r==="yes"}};_l.PropertyPathExecutor=KS});var YS=w(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.BGPExecutor=Sl.BGPExecutorError=void 0;var om=_s(),Zo=Oe(),QS=qe(),am=Bt(),cm=_f(),IR=AR(),Ur=class extends Error{static{a(this,"BGPExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="BGPExecutorError"}};Sl.BGPExecutorError=Ur;var XS=class{static{a(this,"BGPExecutor")}constructor(e){this.tripleStore=e,this.propertyPathExecutor=new IR.PropertyPathExecutor(e)}async*execute(e){if(e.triples.length===0){yield new om.SolutionMapping;return}let t=this.matchTriplePattern(e.triples[0]);for(let r=1;r<e.triples.length;r++)t=this.joinWithPattern(t,e.triples[r]);for await(let r of t)yield r}async executeAll(e){let t=[];for await(let r of this.execute(e))t.push(r);return t}async*executeInGraph(e,t){if(e.triples.length===0){yield new om.SolutionMapping;return}let r=this.matchTriplePatternInGraph(e.triples[0],t);for(let i=1;i<e.triples.length;i++)r=this.joinWithPatternInGraph(r,e.triples[i],t);for await(let i of r)yield i}async*matchTriplePatternInGraph(e,t){if(this.isPropertyPath(e.predicate))throw new Ur("Property paths within named graphs are not yet supported");let r=e.predicate;if(this.isLiteral(e.subject)||this.isLiteral(r)){this.warnLiteralGuard("matchTriplePatternInGraph",this.isLiteral(e.subject)?"subject":"predicate",this.isLiteral(e.subject)?e.subject:r);return}let i=this.isVariable(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),s=this.isVariable(r)?void 0:this.toRDFTermAsPredicate(r),o=this.isVariable(e.object)?void 0:this.toRDFTerm(e.object);if(!this.tripleStore.matchInGraph)throw new Ur("Triple store does not support named graph operations");let c=await this.tripleStore.matchInGraph(i,s,o,t);for(let l of c){let u=new om.SolutionMapping;this.isVariable(e.subject)&&u.set(e.subject.value,l.subject),this.isVariable(r)&&u.set(r.value,l.predicate),this.isVariable(e.object)&&u.set(e.object.value,l.object),yield u}}async*joinWithPatternInGraph(e,t,r){let i=[];for await(let s of e)i.push(s);for(let s of i){let o=this.instantiatePattern(t,s);for await(let c of this.matchTriplePatternInGraph(o,r)){let l=s.merge(c);l!==null&&(yield l)}}}async*matchTriplePattern(e){if(this.isPropertyPath(e.predicate)){if(this.isLiteral(e.subject)||this.isLiteral(e.object)){this.warnLiteralGuard("matchTriplePattern.propertyPath",this.isLiteral(e.subject)?"subject":"object",this.isLiteral(e.subject)?e.subject:e.object);return}yield*this.propertyPathExecutor.execute(e.subject,e.predicate,e.object);return}let t=e.predicate;if(this.isLiteral(e.subject)||this.isLiteral(t)){this.warnLiteralGuard("matchTriplePattern",this.isLiteral(e.subject)?"subject":"predicate",this.isLiteral(e.subject)?e.subject:t);return}let r=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),o=await this.tripleStore.match(r,i,s);for(let c of o){let l=new om.SolutionMapping;if(this.isVariable(e.subject))l.set(e.subject.value,c.subject);else if(this.isQuotedTriple(e.subject)){let u=this.matchQuotedTriplePattern(e.subject,c.subject);if(u===null)continue;for(let[f,d]of u.entries())l.set(f,d)}if(this.isVariable(t)&&l.set(t.value,c.predicate),this.isVariable(e.object))l.set(e.object.value,c.object);else if(this.isQuotedTriple(e.object)){let u=this.matchQuotedTriplePattern(e.object,c.object);if(u===null)continue;for(let[f,d]of u.entries())l.set(f,d)}yield l}}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 cm.QuotedTriple))return null;let r=new Map;if(this.isVariable(e.subject))r.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,o]of i)r.set(s,o)}else if(!this.elementsMatch(e.subject,t.subject))return null;if(e.predicate.type==="variable")r.set(e.predicate.value,t.predicate);else if(e.predicate.value!==t.predicate.value)return null;if(this.isVariable(e.object))r.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,o]of i)r.set(s,o)}else if(!this.elementsMatch(e.object,t.object))return null;return r}elementsMatch(e,t){switch(e.type){case"iri":return t instanceof Zo.IRI&&e.value===t.value;case"literal":return!(!(t instanceof QS.Literal)||e.value!==t.value||e.datatype!==t.datatype?.value||e.language!==t.language||e.direction!==t.direction);case"blank":return t instanceof am.BlankNode&&e.value===t.id;case"quoted":return t instanceof cm.QuotedTriple?this.toRDFQuotedTriple(e).equals(t):!1;default:return!1}}isPropertyPath(e){return e.type==="path"}async*joinWithPattern(e,t){let r=[];for await(let i of e)r.push(i);for(let i of r){let s=this.instantiatePattern(t,i);for await(let o of this.matchTriplePattern(s)){let c=i.merge(o);c!==null&&(yield c)}}}instantiatePattern(e,t){let r=this.isPropertyPath(e.predicate)?e.predicate:this.instantiateElement(e.predicate,t);return{subject:this.instantiateElement(e.subject,t),predicate:r,object:this.instantiateElement(e.object,t)}}instantiateElement(e,t){if(this.isVariable(e)){let r=t.get(e.value);if(r)return this.toAlgebraElement(r)}return this.isQuotedTriple(e)?this.instantiateQuotedTriple(e,t):e}instantiateQuotedTriple(e,t){let r=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:r,predicate:i,object:s}}instantiatePredicateVariable(e,t){let r=t.get(e.value);return r&&r instanceof Zo.IRI?{type:"iri",value:r.value}:e}isVariable(e){return e.type==="variable"}isQuotedTriple(e){return e.type==="quoted"}isLiteral(e){return e.type==="literal"}warnLiteralGuard(e,t,r){let i="value"in r?String(r.value):"<unknown>",s=i.length>80?`${i.slice(0,77)}...`:i,o={executor:"BGPExecutor",context:e,position:t,value:s,hint:"Wikilink could not be resolved to IRI (likely label-form wikilink with no matching basename/alias). Check whether the target file exists in the queried vault, add an alias, or load the target vault via --also. See issue #3282."};if(console.error(`[BGPExecutor] literal-safety guard fired in ${e}: literal in ${t} position \u2014 yielding 0 solutions. value="${s}"`,o),IR.PropertyPathExecutor.isStrictModeEnabled())throw new Ur(`Literal in ${t} position (${e}): "${s}". Set EXOCORTEX_SPARQL_STRICT=0 or omit --strict to fall back to warn-and-empty behaviour.`)}toRDFTermAsSubject(e){switch(e.type){case"iri":return new Zo.IRI(e.value);case"blank":return new am.BlankNode(e.value);case"literal":throw new Ur("Literals cannot appear in subject position");case"variable":throw new Ur(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new Ur(`Unknown element type: ${String(e)}`)}}toRDFQuotedTriple(e){let t=this.toRDFTermAsSubject(e.subject),r=e.predicate.type==="iri"?new Zo.IRI(e.predicate.value):(()=>{throw new Ur("Quoted triple predicate must be IRI")})(),i=this.toRDFTerm(e.object);return new cm.QuotedTriple(t,r,i)}toRDFTermAsPredicate(e){switch(e.type){case"iri":return new Zo.IRI(e.value);case"literal":throw new Ur("Literals cannot appear in predicate position");case"blank":throw new Ur("Blank nodes cannot appear in predicate position");case"variable":throw new Ur(`Cannot convert variable to RDF term: ${e.value}`);default:throw new Ur(`Unknown element type: ${String(e)}`)}}toRDFTerm(e){switch(e.type){case"iri":return new Zo.IRI(e.value);case"literal":return new QS.Literal(e.value,e.datatype?new Zo.IRI(e.datatype):void 0,e.language,e.direction);case"blank":return new am.BlankNode(e.value);case"variable":throw new Ur(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new Ur(`Unknown element type: ${String(e)}`)}}toAlgebraElement(e){if(e instanceof Zo.IRI)return{type:"iri",value:e.value};if(e instanceof QS.Literal)return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language,direction:e.direction};if(e instanceof am.BlankNode)return{type:"blank",value:e.id};if(e instanceof cm.QuotedTriple)return this.toAlgebraQuotedTriple(e);throw new Ur(`Unknown RDF term type: ${String(e)}`)}toAlgebraQuotedTriple(e){return{type:"quoted",subject:this.toAlgebraElement(e.subject),predicate:{type:"iri",value:e.predicate.value},object:this.toAlgebraElement(e.object)}}};Sl.BGPExecutor=XS});var xR=w(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});lm.StringFunctions=void 0;var wl=Oe(),ea=qe(),JS=Bt(),Uf=class n{static{a(this,"StringFunctions")}static str(e){if(e===void 0)throw new Error("STR: argument is undefined");return e instanceof wl.IRI||e instanceof ea.Literal?e.value:e instanceof JS.BlankNode?e.id:String(e)}static lang(e){if(e===void 0)throw new Error("LANG: argument is undefined");return e instanceof ea.Literal&&e.language?e.language:""}static langdir(e){if(e===void 0)throw new Error("LANGDIR: argument is undefined");return!(e instanceof ea.Literal)||!e.language?"":e.direction?`${e.language}--${e.direction}`:e.language}static langMatches(e,t){let[r,i]=n.parseDirectionalLangTag(e),[s,o]=n.parseDirectionalLangTag(t),c=r.toLowerCase(),l=s.toLowerCase();return l==="*"?c!=="":c===""?l==="":o&&i!==o?!1:c===l?!0:c.startsWith(l+"-")}static parseDirectionalLangTag(e){let t=e.indexOf("--");if(t===-1)return[e,void 0];let r=e.substring(0,t),i=e.substring(t+2).toLowerCase();return[r,i]}static regex(e,t,r){try{let i=r?r.includes("u")?r:r+"u":"u";return new RegExp(t,i).test(e)}catch(i){throw new Error(`REGEX: invalid pattern '${t}': ${i.message}`)}}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,r){let i=t-1;if(i<0){if(r!==void 0){let s=r+i;return s<=0?"":e.substring(0,s)}return e}return r!==void 0?e.substring(i,i+r):e.substring(i)}static strBefore(e,t){if(t==="")return"";let r=e.indexOf(t);return r===-1?"":e.substring(0,r)}static strAfter(e,t){if(t==="")return e;let r=e.indexOf(t);return r===-1?"":e.substring(r+t.length)}static concat(...e){return e.join("")}static replace(e,t,r,i){try{let s=i||"g",o=s.includes("u")?s:s+"u",c=new RegExp(t,o);return e.replace(c,r)}catch(s){throw new Error(`REPLACE: invalid pattern '${t}': ${s.message}`)}}static encodeForUri(e){return encodeURIComponent(e)}static normalize(e,t){if(e===void 0)throw new Error("NORMALIZE: string argument is undefined");let r;if(e instanceof ea.Literal)r=e.value;else if(e instanceof wl.IRI)r=e.value;else if(e instanceof JS.BlankNode)r=e.id;else if(typeof e=="string")r=e;else throw new Error("NORMALIZE: first argument must be a string or literal");let i="NFC";if(t!==void 0)if(t instanceof ea.Literal)i=t.value.toUpperCase();else if(typeof t=="string")i=t.toUpperCase();else if(t instanceof wl.IRI)i=t.value.toUpperCase();else throw new Error("NORMALIZE: second argument must be a string literal");if(!n.VALID_NORMALIZATION_FORMS.includes(i))throw new Error(`NORMALIZE: invalid normalization form '${i}'. Valid forms are: NFC, NFD, NFKC, NFKD`);let s=r.normalize(i);return new ea.Literal(s,new wl.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 ea.Literal)t=e.value;else if(e instanceof wl.IRI)t=e.value;else if(e instanceof JS.BlankNode)t=e.id;else if(typeof e=="string")t=e;else throw new Error("FOLD: argument must be a string or literal");let r=n.unicodeCaseFold(t);return new ea.Literal(r,new wl.IRI("http://www.w3.org/2001/XMLSchema#string"))}static unicodeCaseFold(e){let t="";for(let r of e){let i=n.CASE_FOLDING_MAP.get(r);i!==void 0?t+=i:t+=r.toLowerCase()}return t}};lm.StringFunctions=Uf;Uf.VALID_NORMALIZATION_FORMS=["NFC","NFD","NFKC","NFKD"];Uf.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 RR=w(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});um.MathFunctions=void 0;var ZS=class{static{a(this,"MathFunctions")}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()}};um.MathFunctions=ZS});var Bf=w(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});fm.DateTimeParsing=void 0;var o7=Oe(),a7=qe(),ew=class n{static{a(this,"DateTimeParsing")}static parseDate(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`PARSEDATE: invalid date string '${e}'`);return t.getTime()}static parseDayTimeDuration(e){if(!e)throw new Error("parseDayTimeDuration: duration string is empty");let t=!1,r=e.trim();if(r.startsWith("-")&&(t=!0,r=r.substring(1)),!r.startsWith("P"))throw new Error(`parseDayTimeDuration: invalid format, must start with 'P': '${e}'`);r=r.substring(1);let i=0,s=r.indexOf("T"),o="",c="";if(s===-1?o=r:(o=r.substring(0,s),c=r.substring(s+1)),o){let l=o.match(/^(\d+(?:\.\d+)?)D$/);if(l){let u=parseFloat(l[1]);i+=u*24*60*60*1e3}else if(o!=="")throw new Error(`parseDayTimeDuration: invalid day component: '${o}' in '${e}'`)}if(c){let l=c,u=l.match(/^(\d+(?:\.\d+)?)H/);if(u){let p=parseFloat(u[1]);i+=p*60*60*1e3,l=l.substring(u[0].length)}let f=l.match(/^(\d+(?:\.\d+)?)M/);if(f){let p=parseFloat(f[1]);i+=p*60*1e3,l=l.substring(f[0].length)}let d=l.match(/^(\d+(?:\.\d+)?)S$/);if(d){let p=parseFloat(d[1]);i+=p*1e3,l=l.substring(d[0].length)}if(l!=="")throw new Error(`parseDayTimeDuration: invalid time component: '${l}' in '${e}'`)}return t?-i:i}static formatDayTimeDuration(e){let t=e<0,r=Math.abs(e),i=Math.floor(r/(1440*60*1e3));r=r%(1440*60*1e3);let s=Math.floor(r/(3600*1e3));r=r%(3600*1e3);let o=Math.floor(r/(60*1e3));r=r%(60*1e3);let c=r/1e3,l=t?"-P":"P";return i>0&&(l+=`${i}D`),(s>0||o>0||c>0||i===0)&&(l+="T",s>0&&(l+=`${s}H`),o>0&&(l+=`${o}M`),(c>0||s===0&&o===0)&&(Number.isInteger(c)?l+=`${c}S`:l+=`${parseFloat(c.toFixed(3))}S`)),l}static xsdDayTimeDuration(e){return n.parseDayTimeDuration(e),new a7.Literal(e,new o7.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static parseXSDDate(e){let t=/^(-?\d{4})-(\d{2})-(\d{2})(Z|[+-]\d{2}:\d{2})?$/,r=e.match(t);if(!r){let u=new Date(e);return isNaN(u.getTime())?null:new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()))}let i=parseInt(r[1],10),s=parseInt(r[2],10)-1,o=parseInt(r[3],10),c=r[4],l=new Date(Date.UTC(i,s,o));if(c&&c!=="Z"){let u=c.match(/([+-])(\d{2}):(\d{2})/);if(u){let f=u[1]==="+"?1:-1,d=parseInt(u[2],10),p=parseInt(u[3],10),h=f*(d*60+p)*60*1e3;l=new Date(l.getTime()-h)}}return l}static parseXSDTime(e){let t=/^(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$/,r=e.match(t);if(!r)return null;let i=parseInt(r[1],10),s=parseInt(r[2],10),o=parseInt(r[3],10),c=r[4],l=r[5];if(i<0||i>24||s<0||s>59||o<0||o>59||i===24&&(s!==0||o!==0))return null;let u=0;if(c){let d=c.padEnd(3,"0").slice(0,3);u=parseInt(d,10)}let f=i*60*60*1e3+s*60*1e3+o*1e3+u;if(i===24&&(f=1440*60*1e3),l&&l!=="Z"){let d=l.match(/([+-])(\d{2}):(\d{2})/);if(d){let p=d[1]==="+"?1:-1,h=parseInt(d[2],10),y=parseInt(d[3],10),g=p*(h*60+y)*60*1e3;f-=g}}return f}static formatDateDuration(e){if(e===0)return"P0D";let t=e<0,r=Math.abs(e);return t?`-P${r}D`:`P${r}D`}static parseYearMonthDuration(e){let t=/^(-)?P(?:(\d+)Y)?(?:(\d+)M)?$/,r=e.match(t);if(!r)throw new Error(`parseYearMonthDuration: invalid format: '${e}'`);let i=r[1]==="-",s=parseInt(r[2]||"0",10),o=parseInt(r[3]||"0",10);if(!r[2]&&!r[3])throw new Error(`parseYearMonthDuration: invalid format (no duration components): '${e}'`);let c=s*12+o;return i?-c:c}static formatYearMonthDuration(e){let t=e<0,r=Math.abs(e),i=Math.floor(r/12),s=r%12,o=t?"-P":"P";return i>0&&(o+=`${i}Y`),(s>0||i===0)&&(o+=`${s}M`),o}static parseYearMonthDurationComponents(e){let t=/^(-)?P(?:(\d+)Y)?(?:(\d+)M)?$/,r=e.match(t);if(!r)throw new Error(`parseYearMonthDurationComponents: invalid format: '${e}'`);let i=r[1]==="-",s=parseInt(r[2]||"0",10),o=parseInt(r[3]||"0",10);if(!r[2]&&!r[3])throw new Error(`parseYearMonthDurationComponents: invalid format (no duration components): '${e}'`);return{years:s,months:o,negative:i}}static parseDurationComponents(e){if(!e)throw new Error("parseDurationComponents: duration string is empty");let t=!1,r=e.trim();if(r.startsWith("-")&&(t=!0,r=r.substring(1)),!r.startsWith("P"))throw new Error(`parseDurationComponents: invalid format, must start with 'P': '${e}'`);r=r.substring(1);let i=0,s=0,o=0,c=0,l=r.indexOf("T"),u="",f="";if(l===-1?u=r:(u=r.substring(0,l),f=r.substring(l+1)),u){let d=u.match(/^(\d+(?:\.\d+)?)D$/);if(d)i=parseFloat(d[1]);else if(u!=="")throw new Error(`parseDurationComponents: invalid day component: '${u}' in '${e}'`)}if(f){let d=f,p=d.match(/^(\d+(?:\.\d+)?)H/);p&&(s=parseFloat(p[1]),d=d.substring(p[0].length));let h=d.match(/^(\d+(?:\.\d+)?)M/);h&&(o=parseFloat(h[1]),d=d.substring(h[0].length));let y=d.match(/^(\d+(?:\.\d+)?)S$/);if(y&&(c=parseFloat(y[1]),d=d.substring(y[0].length)),d!=="")throw new Error(`parseDurationComponents: invalid time component: '${d}' in '${e}'`)}return{negative:t,days:i,hours:s,minutes:o,seconds:c}}};fm.DateTimeParsing=ew});var CR=w(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});dm.DateTimeArithmetic=void 0;var hn=Oe(),$e=qe(),st=Bf(),tw=class{static{a(this,"DateTimeArithmetic")}static dateTimeDiff(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r),o=new Date(i);if(isNaN(s.getTime()))throw new Error(`dateTimeDiff: invalid first dateTime: '${r}'`);if(isNaN(o.getTime()))throw new Error(`dateTimeDiff: invalid second dateTime: '${i}'`);let c=s.getTime()-o.getTime(),l=st.DateTimeParsing.formatDayTimeDuration(c);return new $e.Literal(l,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static dateTimeAdd(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r);if(isNaN(s.getTime()))throw new Error(`dateTimeAdd: invalid dateTime: '${r}'`);let o=st.DateTimeParsing.parseDayTimeDuration(i),c=s.getTime()+o,l=new Date(c);return new $e.Literal(l.toISOString(),new hn.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtract(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtract: invalid dateTime: '${r}'`);let o=st.DateTimeParsing.parseDayTimeDuration(i),c=s.getTime()-o,l=new Date(c);return new $e.Literal(l.toISOString(),new hn.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateAdd(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseXSDDate(r);if(s===null)throw new Error(`dateAdd: invalid date: '${r}'`);let o=st.DateTimeParsing.parseDayTimeDuration(i),c=s.getTime()+o,l=new Date(c),u=l.getUTCFullYear(),f=String(l.getUTCMonth()+1).padStart(2,"0"),d=String(l.getUTCDate()).padStart(2,"0"),p=`${u}-${f}-${d}`;return new $e.Literal(p,new hn.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateSubtract(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseXSDDate(r);if(s===null)throw new Error(`dateSubtract: invalid date: '${r}'`);let o=st.DateTimeParsing.parseDayTimeDuration(i),c=s.getTime()-o,l=new Date(c),u=l.getUTCFullYear(),f=String(l.getUTCMonth()+1).padStart(2,"0"),d=String(l.getUTCDate()).padStart(2,"0"),p=`${u}-${f}-${d}`;return new $e.Literal(p,new hn.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateTimeAddYearMonth(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r);if(isNaN(s.getTime()))throw new Error(`dateTimeAddYearMonth: invalid dateTime: '${r}'`);let o=st.DateTimeParsing.parseYearMonthDuration(i),c=s.getUTCDate();return s.setUTCMonth(s.getUTCMonth()+o),s.getUTCDate()!==c&&s.setUTCDate(0),new $e.Literal(s.toISOString(),new hn.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtractYearMonth(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=new Date(r);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtractYearMonth: invalid dateTime: '${r}'`);let o=st.DateTimeParsing.parseYearMonthDuration(i),c=s.getUTCDate();return s.setUTCMonth(s.getUTCMonth()-o),s.getUTCDate()!==c&&s.setUTCDate(0),new $e.Literal(s.toISOString(),new hn.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateAddYearMonth(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseXSDDate(r);if(s===null)throw new Error(`dateAddYearMonth: invalid date: '${r}'`);let o=st.DateTimeParsing.parseYearMonthDuration(i),c=s.getUTCDate();s.setUTCMonth(s.getUTCMonth()+o),s.getUTCDate()!==c&&s.setUTCDate(0);let l=s.getUTCFullYear(),u=String(s.getUTCMonth()+1).padStart(2,"0"),f=String(s.getUTCDate()).padStart(2,"0"),d=`${l}-${u}-${f}`;return new $e.Literal(d,new hn.IRI("http://www.w3.org/2001/XMLSchema#date"))}static dateSubtractYearMonth(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseXSDDate(r);if(s===null)throw new Error(`dateSubtractYearMonth: invalid date: '${r}'`);let o=st.DateTimeParsing.parseYearMonthDuration(i),c=s.getUTCDate();s.setUTCMonth(s.getUTCMonth()-o),s.getUTCDate()!==c&&s.setUTCDate(0);let l=s.getUTCFullYear(),u=String(s.getUTCMonth()+1).padStart(2,"0"),f=String(s.getUTCDate()).padStart(2,"0"),d=`${l}-${u}-${f}`;return new $e.Literal(d,new hn.IRI("http://www.w3.org/2001/XMLSchema#date"))}static durationAdd(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseDayTimeDuration(r),o=st.DateTimeParsing.parseDayTimeDuration(i),c=st.DateTimeParsing.formatDayTimeDuration(s+o);return new $e.Literal(c,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationSubtract(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseDayTimeDuration(r),o=st.DateTimeParsing.parseDayTimeDuration(i),c=st.DateTimeParsing.formatDayTimeDuration(s-o);return new $e.Literal(c,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationMultiply(e,t){let r=e instanceof $e.Literal?e.value:e,i=st.DateTimeParsing.parseDayTimeDuration(r),s=st.DateTimeParsing.formatDayTimeDuration(i*t);return new $e.Literal(s,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationDivide(e,t){if(t===0)throw new Error("durationDivide: division by zero");let r=e instanceof $e.Literal?e.value:e,i=st.DateTimeParsing.parseDayTimeDuration(r),s=st.DateTimeParsing.formatDayTimeDuration(i/t);return new $e.Literal(s,new hn.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static yearMonthDurationAdd(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseYearMonthDuration(r),o=st.DateTimeParsing.parseYearMonthDuration(i),c=st.DateTimeParsing.formatYearMonthDuration(s+o);return new $e.Literal(c,new hn.IRI("http://www.w3.org/2001/XMLSchema#yearMonthDuration"))}static yearMonthDurationSubtract(e,t){let r=e instanceof $e.Literal?e.value:e,i=t instanceof $e.Literal?t.value:t,s=st.DateTimeParsing.parseYearMonthDuration(r),o=st.DateTimeParsing.parseYearMonthDuration(i),c=st.DateTimeParsing.formatYearMonthDuration(s-o);return new $e.Literal(c,new hn.IRI("http://www.w3.org/2001/XMLSchema#yearMonthDuration"))}static durationToDays(e){let t=e instanceof $e.Literal?e.value:e;return st.DateTimeParsing.parseDayTimeDuration(t)/(1440*60*1e3)}static durationToHours(e){let t=e instanceof $e.Literal?e.value:e;return st.DateTimeParsing.parseDayTimeDuration(t)/(3600*1e3)}static durationToMinutes(e){let t=e instanceof $e.Literal?e.value:e;return st.DateTimeParsing.parseDayTimeDuration(t)/(60*1e3)}static durationToSeconds(e){let t=e instanceof $e.Literal?e.value:e;return st.DateTimeParsing.parseDayTimeDuration(t)/1e3}};dm.DateTimeArithmetic=tw});var PR=w(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});pm.DateTimeAccessors=void 0;var Vf=Oe(),Vt=qe(),Rt=Bf(),rw=class{static{a(this,"DateTimeAccessors")}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 durationDays(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseDurationComponents(t),i=Math.floor(r.days);return r.negative?-i:i}static durationHours(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseDurationComponents(t),i=Math.floor(r.hours);return r.negative?-i:i}static durationMinutes(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseDurationComponents(t),i=Math.floor(r.minutes);return r.negative?-i:i}static durationSeconds(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseDurationComponents(t);return r.negative?-r.seconds:r.seconds}static durationYears(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseYearMonthDurationComponents(t);return r.negative?-r.years:r.years}static durationMonths(e){let t=e instanceof Vt.Literal?e.value:e,r=Rt.DateTimeParsing.parseYearMonthDurationComponents(t);return r.negative?-r.months:r.months}static timezone(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TIMEZONE: invalid date string '${e}'`);let r;if(e.endsWith("Z"))r="PT0S";else{let i=e.match(/([+-]\d{2}):?(\d{2})$/);if(i){let s=parseInt(i[1],10),o=parseInt(i[2],10),c=s>=0?"":"-",l=Math.abs(s);o===0?r=`${c}PT${l}H`:r=`${c}PT${l}H${o}M`}else{let s=-t.getTimezoneOffset(),o=Math.floor(Math.abs(s)/60),c=Math.abs(s)%60,l=s>=0?"":"-";c===0?r=`${l}PT${o}H`:r=`${l}PT${o}H${c}M`}}return new Vt.Literal(r,new Vf.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 r=e.match(/([+-]\d{2}:\d{2})$/);if(r)return r[1];let i=e.match(/([+-])(\d{2})(\d{2})$/);return i?`${i[1]}${i[2]}:${i[3]}`:""}static adjust(e,t){let r=e instanceof Vt.Literal?e.value:e,i=new Date(r);if(isNaN(i.getTime()))throw new Error(`ADJUST: invalid dateTime: '${r}'`);if(t==null){let R=i.getUTCFullYear(),q=String(i.getUTCMonth()+1).padStart(2,"0"),Y=String(i.getUTCDate()).padStart(2,"0"),P=String(i.getUTCHours()).padStart(2,"0"),O=String(i.getUTCMinutes()).padStart(2,"0"),k=String(i.getUTCSeconds()).padStart(2,"0"),H=i.getUTCMilliseconds(),G=`${R}-${q}-${Y}T${P}:${O}:${k}`;return H>0&&(G+=`.${String(H).padStart(3,"0")}`),new Vt.Literal(G,new Vf.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}let s=t instanceof Vt.Literal?t.value:t,o=Rt.DateTimeParsing.parseDayTimeDuration(s),c=840*60*1e3;if(Math.abs(o)>c)throw new Error(`ADJUST: timezone offset out of range: '${s}'`);let l=i.getTime(),u=new Date(l+o),f=u.getUTCFullYear(),d=String(u.getUTCMonth()+1).padStart(2,"0"),p=String(u.getUTCDate()).padStart(2,"0"),h=String(u.getUTCHours()).padStart(2,"0"),y=String(u.getUTCMinutes()).padStart(2,"0"),g=String(u.getUTCSeconds()).padStart(2,"0"),v=u.getUTCMilliseconds(),b=o>=0?"+":"-",S=Math.floor(Math.abs(o)/(3600*1e3)),T=Math.floor(Math.abs(o)%(3600*1e3)/(60*1e3)),I=`${b}${String(S).padStart(2,"0")}:${String(T).padStart(2,"0")}`,A=`${f}-${d}-${p}T${h}:${y}:${g}`;return v>0&&(A+=`.${String(v).padStart(3,"0")}`),A+=I,new Vt.Literal(A,new Vf.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static now(){return new Date().toISOString()}static dateBefore(e,t){let r=Rt.DateTimeParsing.parseDate(e),i=Rt.DateTimeParsing.parseDate(t);return r<i}static dateAfter(e,t){let r=Rt.DateTimeParsing.parseDate(e),i=Rt.DateTimeParsing.parseDate(t);return r>i}static dateInRange(e,t,r){let i=Rt.DateTimeParsing.parseDate(e),s=Rt.DateTimeParsing.parseDate(t),o=Rt.DateTimeParsing.parseDate(r);return i>=s&&i<=o}static compareDurations(e,t,r){let i=e instanceof Vt.Literal?e.value:e,s=t instanceof Vt.Literal?t.value:t,o=Rt.DateTimeParsing.parseDayTimeDuration(i),c=Rt.DateTimeParsing.parseDayTimeDuration(s);switch(r){case"=":return o===c;case"!=":return o!==c;case"<":return o<c;case">":return o>c;case"<=":return o<=c;case">=":return o>=c;default:throw new Error(`compareDurations: unknown operator: ${r}`)}}static dateDiffMinutes(e,t){let r=Rt.DateTimeParsing.parseDate(e),i=Rt.DateTimeParsing.parseDate(t),s=Math.abs(i-r);return Math.round(s/(1e3*60))}static dateDiffHours(e,t){let r=Rt.DateTimeParsing.parseDate(e),i=Rt.DateTimeParsing.parseDate(t),s=Math.abs(i-r);return Math.round(s/(1e3*60*60)*100)/100}static timeDiff(e,t){let r=e instanceof Vt.Literal?e.value:e,i=t instanceof Vt.Literal?t.value:t,s=Rt.DateTimeParsing.parseXSDTime(r),o=Rt.DateTimeParsing.parseXSDTime(i);if(s===null)throw new Error(`timeDiff: invalid first time: '${r}'`);if(o===null)throw new Error(`timeDiff: invalid second time: '${i}'`);let c=s-o,l=Rt.DateTimeParsing.formatDayTimeDuration(c);return new Vt.Literal(l,new Vf.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static isDayTimeDuration(e){return e instanceof Vt.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static isDate(e){return e instanceof Vt.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#date":!1}static isYearMonthDuration(e){return e instanceof Vt.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#yearMonthDuration":!1}static isTime(e){return e instanceof Vt.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#time":!1}static dateDiff(e,t){let r=e instanceof Vt.Literal?e.value:e,i=t instanceof Vt.Literal?t.value:t,s=Rt.DateTimeParsing.parseXSDDate(r),o=Rt.DateTimeParsing.parseXSDDate(i);if(s===null)throw new Error(`dateDiff: invalid first date: '${r}'`);if(o===null)throw new Error(`dateDiff: invalid second date: '${i}'`);let c=s.getTime()-o.getTime(),l=Math.round(c/(1440*60*1e3)),u=Rt.DateTimeParsing.formatDateDuration(l);return new Vt.Literal(u,new Vf.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}};pm.DateTimeAccessors=rw});var mm=w(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});hm.DateTimeFunctions=void 0;var vl=Bf(),hr=CR(),St=PR(),nw=class{static{a(this,"DateTimeFunctions")}static parseDate(e){return vl.DateTimeParsing.parseDate(e)}static parseDayTimeDuration(e){return vl.DateTimeParsing.parseDayTimeDuration(e)}static formatDayTimeDuration(e){return vl.DateTimeParsing.formatDayTimeDuration(e)}static xsdDayTimeDuration(e){return vl.DateTimeParsing.xsdDayTimeDuration(e)}static parseYearMonthDuration(e){return vl.DateTimeParsing.parseYearMonthDuration(e)}static formatYearMonthDuration(e){return vl.DateTimeParsing.formatYearMonthDuration(e)}static year(e){return St.DateTimeAccessors.year(e)}static month(e){return St.DateTimeAccessors.month(e)}static day(e){return St.DateTimeAccessors.day(e)}static hours(e){return St.DateTimeAccessors.hours(e)}static minutes(e){return St.DateTimeAccessors.minutes(e)}static seconds(e){return St.DateTimeAccessors.seconds(e)}static durationDays(e){return St.DateTimeAccessors.durationDays(e)}static durationHours(e){return St.DateTimeAccessors.durationHours(e)}static durationMinutes(e){return St.DateTimeAccessors.durationMinutes(e)}static durationSeconds(e){return St.DateTimeAccessors.durationSeconds(e)}static durationYears(e){return St.DateTimeAccessors.durationYears(e)}static durationMonths(e){return St.DateTimeAccessors.durationMonths(e)}static timezone(e){return St.DateTimeAccessors.timezone(e)}static tz(e){return St.DateTimeAccessors.tz(e)}static adjust(e,t){return St.DateTimeAccessors.adjust(e,t)}static now(){return St.DateTimeAccessors.now()}static dateBefore(e,t){return St.DateTimeAccessors.dateBefore(e,t)}static dateAfter(e,t){return St.DateTimeAccessors.dateAfter(e,t)}static dateInRange(e,t,r){return St.DateTimeAccessors.dateInRange(e,t,r)}static compareDurations(e,t,r){return St.DateTimeAccessors.compareDurations(e,t,r)}static dateDiffMinutes(e,t){return St.DateTimeAccessors.dateDiffMinutes(e,t)}static dateDiffHours(e,t){return St.DateTimeAccessors.dateDiffHours(e,t)}static timeDiff(e,t){return St.DateTimeAccessors.timeDiff(e,t)}static dateDiff(e,t){return St.DateTimeAccessors.dateDiff(e,t)}static isDayTimeDuration(e){return St.DateTimeAccessors.isDayTimeDuration(e)}static isDate(e){return St.DateTimeAccessors.isDate(e)}static isYearMonthDuration(e){return St.DateTimeAccessors.isYearMonthDuration(e)}static isTime(e){return St.DateTimeAccessors.isTime(e)}static dateTimeDiff(e,t){return hr.DateTimeArithmetic.dateTimeDiff(e,t)}static dateTimeAdd(e,t){return hr.DateTimeArithmetic.dateTimeAdd(e,t)}static dateTimeSubtract(e,t){return hr.DateTimeArithmetic.dateTimeSubtract(e,t)}static dateAdd(e,t){return hr.DateTimeArithmetic.dateAdd(e,t)}static dateSubtract(e,t){return hr.DateTimeArithmetic.dateSubtract(e,t)}static dateTimeAddYearMonth(e,t){return hr.DateTimeArithmetic.dateTimeAddYearMonth(e,t)}static dateTimeSubtractYearMonth(e,t){return hr.DateTimeArithmetic.dateTimeSubtractYearMonth(e,t)}static dateAddYearMonth(e,t){return hr.DateTimeArithmetic.dateAddYearMonth(e,t)}static dateSubtractYearMonth(e,t){return hr.DateTimeArithmetic.dateSubtractYearMonth(e,t)}static durationAdd(e,t){return hr.DateTimeArithmetic.durationAdd(e,t)}static durationSubtract(e,t){return hr.DateTimeArithmetic.durationSubtract(e,t)}static durationMultiply(e,t){return hr.DateTimeArithmetic.durationMultiply(e,t)}static durationDivide(e,t){return hr.DateTimeArithmetic.durationDivide(e,t)}static yearMonthDurationAdd(e,t){return hr.DateTimeArithmetic.yearMonthDurationAdd(e,t)}static yearMonthDurationSubtract(e,t){return hr.DateTimeArithmetic.yearMonthDurationSubtract(e,t)}static durationToDays(e){return hr.DateTimeArithmetic.durationToDays(e)}static durationToHours(e){return hr.DateTimeArithmetic.durationToHours(e)}static durationToMinutes(e){return hr.DateTimeArithmetic.durationToMinutes(e)}static durationToSeconds(e){return hr.DateTimeArithmetic.durationToSeconds(e)}};hm.DateTimeFunctions=nw});var OR=w(ym=>{"use strict";Object.defineProperty(ym,"__esModule",{value:!0});ym.LogicalFunctions=void 0;var c7=Oe(),El=qe(),l7=Bt(),gm=mm(),iw=class n{static{a(this,"LogicalFunctions")}static compare(e,t,r){if(n.isDayTimeDurationValue(e)&&n.isDayTimeDurationValue(t))return gm.DateTimeFunctions.compareDurations(e instanceof El.Literal?e:String(e),t instanceof El.Literal?t:String(t),r);if(n.isDayTimeDurationValue(e)&&typeof t=="string"&&/^-?P/.test(t))return gm.DateTimeFunctions.compareDurations(e instanceof El.Literal?e:String(e),t,r);if(typeof e=="string"&&/^-?P/.test(e)&&n.isDayTimeDurationValue(t))return gm.DateTimeFunctions.compareDurations(e,t instanceof El.Literal?t:String(t),r);let i=n.toComparableValue(e),s=n.toComparableValue(t);switch(r){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: ${r}`)}}static isDayTimeDurationValue(e){return e instanceof El.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 El.Literal){let t=e.datatype?.value;if(t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double")){let r=parseFloat(e.value);if(!isNaN(r))return r}if(t==="http://www.w3.org/2001/XMLSchema#dayTimeDuration")try{return gm.DateTimeFunctions.parseDayTimeDuration(e.value)}catch{return e.value}return e.value}return e instanceof c7.IRI?e.value:e instanceof l7.BlankNode?e.id:String(e)}static logicalAnd(e){return e.every(t=>t===!0)}static logicalOr(e){return e.some(t=>t===!0)}static logicalNot(e){return!e}static coalesce(e){for(let t of e)if(t!=null)return t}static if(e,t,r){return e?t:r}};ym.LogicalFunctions=iw});var DR=w(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});bm.RDFTermFunctions=void 0;var Br=Oe(),At=qe(),Ci=Bt(),Tl=_f(),sw=Ii(),ow=class n{static{a(this,"RDFTermFunctions")}static datatype(e){if(e===void 0)throw new Error("DATATYPE: argument is undefined");if(e instanceof At.Literal)return e.datatype?e.datatype:e.language?new Br.IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"):new Br.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 Br.IRI}static isBlank(e){return e===void 0?!1:e instanceof Ci.BlankNode}static isLiteral(e){return e===void 0?!1:e instanceof At.Literal}static isTriple(e){return e===void 0?!1:e instanceof Tl.QuotedTriple}static hasLangdir(e){return e===void 0||!(e instanceof At.Literal)?!1:!!e.language&&!!e.direction}static isNumeric(e){if(e===void 0||!(e instanceof At.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 xsdDateTime(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`xsd:dateTime: invalid date string '${e}'`);return new At.Literal(t.toISOString(),new Br.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 At.Literal(String(t),new Br.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 At.Literal(String(t),new Br.IRI("http://www.w3.org/2001/XMLSchema#decimal"))}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 Br.IRI&&t instanceof Br.IRI)return e.value===t.value;if(e instanceof Ci.BlankNode&&t instanceof Ci.BlankNode)return e.id===t.id;if(e instanceof At.Literal&&t instanceof At.Literal){if(e.value!==t.value||e.language!==t.language)return!1;let r=e.datatype?.value,i=t.datatype?.value;return r===i}return!1}static iri(e){if(e===void 0)throw new Error("IRI: argument is undefined");if(e instanceof Br.IRI)return e;if(e instanceof At.Literal)return new Br.IRI(e.value);throw e instanceof Ci.BlankNode?new Error("IRI: cannot convert blank node to IRI"):new Error("IRI: unsupported term type")}static uri(e){return n.iri(e)}static bnode(e){if(e===void 0){let t=`b${(0,sw.v4)().replace(/-/g,"").substring(0,12)}`;return new Ci.BlankNode(t)}if(e instanceof At.Literal)return new Ci.BlankNode(e.value);if(e instanceof Ci.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 r;if(e instanceof At.Literal){if(e.language)throw new Error("STRDT: lexical form must not have a language tag");r=e.value}else if(typeof e=="string")r=e;else throw new Error("STRDT: lexical form must be a string literal");let i;if(t instanceof Br.IRI)i=t;else if(t instanceof At.Literal)i=new Br.IRI(t.value);else throw new Error("STRDT: datatype must be an IRI");return new At.Literal(r,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 r;if(e instanceof At.Literal){if(e.language)throw new Error("STRLANG: lexical form must not already have a language tag");r=e.value}else if(typeof e=="string")r=e;else throw new Error("STRLANG: lexical form must be a string literal");let i;if(t instanceof At.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 At.Literal(r,void 0,i)}static strlangdir(e,t,r){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(r===void 0)throw new Error("STRLANGDIR: direction is undefined");let i;if(e instanceof At.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 At.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 o;if(r instanceof At.Literal)o=r.value.toLowerCase();else throw new Error("STRLANGDIR: direction must be a string literal");if(o!=="ltr"&&o!=="rtl")throw new Error(`STRLANGDIR: invalid direction '${o}'. Must be 'ltr' or 'rtl'`);return new At.Literal(i,void 0,s,o)}static uuid(){let e=(0,sw.v4)();return new Br.IRI(`urn:uuid:${e}`)}static struuid(){let e=(0,sw.v4)();return new At.Literal(e)}static triple(e,t,r){if(e===void 0)throw new Error("TRIPLE: subject is undefined");if(t===void 0)throw new Error("TRIPLE: predicate is undefined");if(r===void 0)throw new Error("TRIPLE: object is undefined");if(e instanceof At.Literal)throw new Error("TRIPLE: subject must be IRI, BlankNode, or QuotedTriple, got Literal");if(!(t instanceof Br.IRI)){let c=t instanceof At.Literal?"Literal":t instanceof Ci.BlankNode?"BlankNode":t instanceof Tl.QuotedTriple?"QuotedTriple":typeof t;throw new Error(`TRIPLE: predicate must be IRI, got ${c}`)}let i=e,s=t,o=r;return new Tl.QuotedTriple(i,s,o)}static subject(e){if(e===void 0)throw new Error("SUBJECT: argument is undefined");if(!(e instanceof Tl.QuotedTriple)){let t=e instanceof Br.IRI?"IRI":e instanceof At.Literal?"Literal":e instanceof Ci.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 Tl.QuotedTriple)){let t=e instanceof Br.IRI?"IRI":e instanceof At.Literal?"Literal":e instanceof Ci.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 Tl.QuotedTriple)){let t=e instanceof Br.IRI?"IRI":e instanceof At.Literal?"Literal":e instanceof Ci.BlankNode?"BlankNode":typeof e;throw new Error(`OBJECT: argument must be QuotedTriple, got ${t}`)}return e.object}};bm.RDFTermFunctions=ow});var FR=w(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});_m.HashFunctions=void 0;var aw=class{static{a(this,"HashFunctions")}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")}};_m.HashFunctions=aw});var wm=w(Sm=>{"use strict";Object.defineProperty(Sm,"__esModule",{value:!0});Sm.BuiltInFunctions=void 0;var mr=xR(),ta=RR(),Pe=mm(),Al=OR(),Lt=DR(),Gf=FR(),cw=class{static{a(this,"BuiltInFunctions")}static str(...e){return mr.StringFunctions.str(...e)}static lang(...e){return mr.StringFunctions.lang(...e)}static langdir(...e){return mr.StringFunctions.langdir(...e)}static langMatches(...e){return mr.StringFunctions.langMatches(...e)}static regex(...e){return mr.StringFunctions.regex(...e)}static contains(...e){return mr.StringFunctions.contains(...e)}static strStarts(...e){return mr.StringFunctions.strStarts(...e)}static strEnds(...e){return mr.StringFunctions.strEnds(...e)}static strlen(...e){return mr.StringFunctions.strlen(...e)}static ucase(...e){return mr.StringFunctions.ucase(...e)}static lcase(...e){return mr.StringFunctions.lcase(...e)}static substr(...e){return mr.StringFunctions.substr(...e)}static strBefore(...e){return mr.StringFunctions.strBefore(...e)}static strAfter(...e){return mr.StringFunctions.strAfter(...e)}static concat(...e){return mr.StringFunctions.concat(...e)}static replace(...e){return mr.StringFunctions.replace(...e)}static encodeForUri(...e){return mr.StringFunctions.encodeForUri(...e)}static normalize(...e){return mr.StringFunctions.normalize(...e)}static fold(...e){return mr.StringFunctions.fold(...e)}static abs(...e){return ta.MathFunctions.abs(...e)}static round(...e){return ta.MathFunctions.round(...e)}static ceil(...e){return ta.MathFunctions.ceil(...e)}static floor(...e){return ta.MathFunctions.floor(...e)}static rand(){return ta.MathFunctions.rand()}static msToMinutes(...e){return ta.MathFunctions.msToMinutes(...e)}static msToHours(...e){return ta.MathFunctions.msToHours(...e)}static msToSeconds(...e){return ta.MathFunctions.msToSeconds(...e)}static parseDate(...e){return Pe.DateTimeFunctions.parseDate(...e)}static dateBefore(...e){return Pe.DateTimeFunctions.dateBefore(...e)}static dateAfter(...e){return Pe.DateTimeFunctions.dateAfter(...e)}static dateInRange(...e){return Pe.DateTimeFunctions.dateInRange(...e)}static dateDiffMinutes(...e){return Pe.DateTimeFunctions.dateDiffMinutes(...e)}static dateDiffHours(...e){return Pe.DateTimeFunctions.dateDiffHours(...e)}static year(...e){return Pe.DateTimeFunctions.year(...e)}static month(...e){return Pe.DateTimeFunctions.month(...e)}static day(...e){return Pe.DateTimeFunctions.day(...e)}static hours(...e){return Pe.DateTimeFunctions.hours(...e)}static minutes(...e){return Pe.DateTimeFunctions.minutes(...e)}static seconds(...e){return Pe.DateTimeFunctions.seconds(...e)}static timezone(...e){return Pe.DateTimeFunctions.timezone(...e)}static tz(...e){return Pe.DateTimeFunctions.tz(...e)}static now(){return Pe.DateTimeFunctions.now()}static parseDayTimeDuration(...e){return Pe.DateTimeFunctions.parseDayTimeDuration(...e)}static formatDayTimeDuration(...e){return Pe.DateTimeFunctions.formatDayTimeDuration(...e)}static xsdDayTimeDuration(...e){return Pe.DateTimeFunctions.xsdDayTimeDuration(...e)}static compareDurations(...e){return Pe.DateTimeFunctions.compareDurations(...e)}static isDayTimeDuration(...e){return Pe.DateTimeFunctions.isDayTimeDuration(...e)}static isDate(...e){return Pe.DateTimeFunctions.isDate(...e)}static dateDiff(...e){return Pe.DateTimeFunctions.dateDiff(...e)}static dateTimeDiff(...e){return Pe.DateTimeFunctions.dateTimeDiff(...e)}static dateTimeAdd(...e){return Pe.DateTimeFunctions.dateTimeAdd(...e)}static dateTimeSubtract(...e){return Pe.DateTimeFunctions.dateTimeSubtract(...e)}static dateAdd(...e){return Pe.DateTimeFunctions.dateAdd(...e)}static dateSubtract(...e){return Pe.DateTimeFunctions.dateSubtract(...e)}static parseYearMonthDuration(...e){return Pe.DateTimeFunctions.parseYearMonthDuration(...e)}static isYearMonthDuration(...e){return Pe.DateTimeFunctions.isYearMonthDuration(...e)}static dateTimeAddYearMonth(...e){return Pe.DateTimeFunctions.dateTimeAddYearMonth(...e)}static dateTimeSubtractYearMonth(...e){return Pe.DateTimeFunctions.dateTimeSubtractYearMonth(...e)}static dateAddYearMonth(...e){return Pe.DateTimeFunctions.dateAddYearMonth(...e)}static dateSubtractYearMonth(...e){return Pe.DateTimeFunctions.dateSubtractYearMonth(...e)}static durationAdd(...e){return Pe.DateTimeFunctions.durationAdd(...e)}static durationSubtract(...e){return Pe.DateTimeFunctions.durationSubtract(...e)}static durationMultiply(...e){return Pe.DateTimeFunctions.durationMultiply(...e)}static durationDivide(...e){return Pe.DateTimeFunctions.durationDivide(...e)}static formatYearMonthDuration(...e){return Pe.DateTimeFunctions.formatYearMonthDuration(...e)}static yearMonthDurationAdd(...e){return Pe.DateTimeFunctions.yearMonthDurationAdd(...e)}static yearMonthDurationSubtract(...e){return Pe.DateTimeFunctions.yearMonthDurationSubtract(...e)}static durationYears(...e){return Pe.DateTimeFunctions.durationYears(...e)}static durationMonths(...e){return Pe.DateTimeFunctions.durationMonths(...e)}static durationToDays(...e){return Pe.DateTimeFunctions.durationToDays(...e)}static durationToHours(...e){return Pe.DateTimeFunctions.durationToHours(...e)}static durationToMinutes(...e){return Pe.DateTimeFunctions.durationToMinutes(...e)}static durationToSeconds(...e){return Pe.DateTimeFunctions.durationToSeconds(...e)}static durationDays(...e){return Pe.DateTimeFunctions.durationDays(...e)}static durationHours(...e){return Pe.DateTimeFunctions.durationHours(...e)}static durationMinutes(...e){return Pe.DateTimeFunctions.durationMinutes(...e)}static durationSeconds(...e){return Pe.DateTimeFunctions.durationSeconds(...e)}static adjust(...e){return Pe.DateTimeFunctions.adjust(...e)}static isTime(...e){return Pe.DateTimeFunctions.isTime(...e)}static timeDiff(...e){return Pe.DateTimeFunctions.timeDiff(...e)}static compare(...e){return Al.LogicalFunctions.compare(...e)}static logicalAnd(...e){return Al.LogicalFunctions.logicalAnd(...e)}static logicalOr(...e){return Al.LogicalFunctions.logicalOr(...e)}static logicalNot(...e){return Al.LogicalFunctions.logicalNot(...e)}static coalesce(...e){return Al.LogicalFunctions.coalesce(...e)}static if(...e){return Al.LogicalFunctions.if(...e)}static datatype(...e){return Lt.RDFTermFunctions.datatype(...e)}static bound(...e){return Lt.RDFTermFunctions.bound(...e)}static isIRI(...e){return Lt.RDFTermFunctions.isIRI(...e)}static isBlank(...e){return Lt.RDFTermFunctions.isBlank(...e)}static isLiteral(...e){return Lt.RDFTermFunctions.isLiteral(...e)}static isTriple(...e){return Lt.RDFTermFunctions.isTriple(...e)}static isNumeric(...e){return Lt.RDFTermFunctions.isNumeric(...e)}static hasLangdir(...e){return Lt.RDFTermFunctions.hasLangdir(...e)}static sameTerm(...e){return Lt.RDFTermFunctions.sameTerm(...e)}static iri(...e){return Lt.RDFTermFunctions.iri(...e)}static uri(...e){return Lt.RDFTermFunctions.uri(...e)}static bnode(...e){return Lt.RDFTermFunctions.bnode(...e)}static strdt(...e){return Lt.RDFTermFunctions.strdt(...e)}static strlang(...e){return Lt.RDFTermFunctions.strlang(...e)}static strlangdir(...e){return Lt.RDFTermFunctions.strlangdir(...e)}static uuid(){return Lt.RDFTermFunctions.uuid()}static struuid(){return Lt.RDFTermFunctions.struuid()}static xsdDateTime(...e){return Lt.RDFTermFunctions.xsdDateTime(...e)}static xsdInteger(...e){return Lt.RDFTermFunctions.xsdInteger(...e)}static xsdDecimal(...e){return Lt.RDFTermFunctions.xsdDecimal(...e)}static triple(...e){return Lt.RDFTermFunctions.triple(...e)}static subject(...e){return Lt.RDFTermFunctions.subject(...e)}static predicate(...e){return Lt.RDFTermFunctions.predicate(...e)}static object(...e){return Lt.RDFTermFunctions.object(...e)}static md5(...e){return Gf.HashFunctions.md5(...e)}static sha1(...e){return Gf.HashFunctions.sha1(...e)}static sha256(...e){return Gf.HashFunctions.sha256(...e)}static sha384(...e){return Gf.HashFunctions.sha384(...e)}static sha512(...e){return Gf.HashFunctions.sha512(...e)}};Sm.BuiltInFunctions=cw});var qf=w(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.ExoQLBudgetExceededError=Ss.ExoQLCycleError=Ss.ExoQLEvalDisabledError=Ss.ExoQLForbiddenKeywordError=void 0;var lw=class extends Error{static{a(this,"ExoQLForbiddenKeywordError")}constructor(e,t){super(t??`ExoQLForbiddenKeywordError: keyword "${e}" is not permitted by the exoql__Query AST allowlist`),this.name="ExoQLForbiddenKeywordError",this.keyword=e}};Ss.ExoQLForbiddenKeywordError=lw;var uw=class extends Error{static{a(this,"ExoQLEvalDisabledError")}constructor(e){super(e??"ExoQLEvalDisabledError: exoql.eval.enabled is false (default). Flip the feature flag to opt in."),this.name="ExoQLEvalDisabledError"}};Ss.ExoQLEvalDisabledError=uw;var fw=class extends Error{static{a(this,"ExoQLCycleError")}constructor(e,t){super(t??`ExoQLCycleError: cycle detected in nested exo:eval invocations: ${e.join(" \u2192 ")}`),this.name="ExoQLCycleError",this.path=e}};Ss.ExoQLCycleError=fw;var dw=class extends Error{static{a(this,"ExoQLBudgetExceededError")}constructor(e,t,r,i){super(i??`ExoQLBudgetExceededError: ${e} budget exceeded (limit=${t}, observed=${r})`),this.name="ExoQLBudgetExceededError",this.budget=e,this.limit=t,this.observed=r}};Ss.ExoQLBudgetExceededError=dw});var VR=w(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.functionHandlers=void 0;var K=wm();Q.functionHandlers=new Map;Q.functionHandlers.set("str",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.str(t)});Q.functionHandlers.set("lang",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.lang(t)});Q.functionHandlers.set("langmatches",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.langMatches(t,r)});Q.functionHandlers.set("contains",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.contains(t,r)});Q.functionHandlers.set("strstarts",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.strStarts(t,r)});Q.functionHandlers.set("strends",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.strEnds(t,r)});Q.functionHandlers.set("strlen",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.strlen(t)});Q.functionHandlers.set("ucase",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.ucase(t)});Q.functionHandlers.set("lcase",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.lcase(t)});Q.functionHandlers.set("substr",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=Number(e.evaluateExpression(n[1],e.solution));if(n[2]){let i=Number(e.evaluateExpression(n[2],e.solution));return K.BuiltInFunctions.substr(t,r,i)}return K.BuiltInFunctions.substr(t,r)});Q.functionHandlers.set("strbefore",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.strBefore(t,r)});Q.functionHandlers.set("strafter",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.strAfter(t,r)});Q.functionHandlers.set("concat",(n,e)=>{let t=n.map(r=>e.getStringValue(e.evaluateExpression(r,e.solution)));return K.BuiltInFunctions.concat(...t)});Q.functionHandlers.set("replace",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=e.getStringValue(e.evaluateExpression(n[2],e.solution)),s=n[3]?e.getStringValue(e.evaluateExpression(n[3],e.solution)):void 0;return K.BuiltInFunctions.replace(t,r,i,s)});Q.functionHandlers.set("regex",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=n[2]?e.getStringValue(e.evaluateExpression(n[2],e.solution)):void 0;return K.BuiltInFunctions.regex(t,r,i)});Q.functionHandlers.set("encode_for_uri",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.encodeForUri(t)});Q.functionHandlers.set("datatype",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.datatype(t).value});Q.functionHandlers.set("bound",(n,e)=>{let t=n[0];if(t.type==="variable"&&t.name){let r=e.solution.get(t.name);return K.BuiltInFunctions.bound(r)}return!0});var LR=a((n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isIRI(t)},"isIriHandler");Q.functionHandlers.set("isiri",LR);Q.functionHandlers.set("isuri",LR);Q.functionHandlers.set("isblank",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isBlank(t)});Q.functionHandlers.set("isliteral",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isLiteral(t)});Q.functionHandlers.set("isnumeric",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isNumeric(t)});Q.functionHandlers.set("haslangdir",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.hasLangdir(t)});Q.functionHandlers.set("istriple",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.isTriple(t)});Q.functionHandlers.set("sameterm",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution),r=e.getTermFromExpression(n[1],e.solution);return K.BuiltInFunctions.sameTerm(t,r)});Q.functionHandlers.set("abs",(n,e)=>{let t=Number(e.getStringValue(e.evaluateExpression(n[0],e.solution)));return K.BuiltInFunctions.abs(t)});Q.functionHandlers.set("round",(n,e)=>{let t=Number(e.getStringValue(e.evaluateExpression(n[0],e.solution)));return K.BuiltInFunctions.round(t)});Q.functionHandlers.set("ceil",(n,e)=>{let t=Number(e.getStringValue(e.evaluateExpression(n[0],e.solution)));return K.BuiltInFunctions.ceil(t)});Q.functionHandlers.set("floor",(n,e)=>{let t=Number(e.getStringValue(e.evaluateExpression(n[0],e.solution)));return K.BuiltInFunctions.floor(t)});Q.functionHandlers.set("rand",()=>K.BuiltInFunctions.rand());Q.functionHandlers.set("parsedate",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.parseDate(t)});Q.functionHandlers.set("datebefore",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.dateBefore(t,r)});Q.functionHandlers.set("dateafter",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.dateAfter(t,r)});Q.functionHandlers.set("dateinrange",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=e.getStringValue(e.evaluateExpression(n[2],e.solution));return K.BuiltInFunctions.dateInRange(t,r,i)});Q.functionHandlers.set("datediffminutes",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.dateDiffMinutes(t,r)});Q.functionHandlers.set("datediffhours",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution));return K.BuiltInFunctions.dateDiffHours(t,r)});var Il=a((n,e,t)=>(r,i)=>{let s=i.evaluateExpression(r[0],i.solution);return e&&i.isYearMonthDurationValue(s)?e(s):t&&i.isDayTimeDurationValue(s)?t(s):n(i.getStringValue(s))},"createDateTimeAccessor"),NR=Il(K.BuiltInFunctions.year.bind(K.BuiltInFunctions),K.BuiltInFunctions.durationYears.bind(K.BuiltInFunctions),null);Q.functionHandlers.set("year",NR);Q.functionHandlers.set("years",NR);var kR=Il(K.BuiltInFunctions.month.bind(K.BuiltInFunctions),K.BuiltInFunctions.durationMonths.bind(K.BuiltInFunctions),null);Q.functionHandlers.set("month",kR);Q.functionHandlers.set("months",kR);var MR=Il(K.BuiltInFunctions.day.bind(K.BuiltInFunctions),null,K.BuiltInFunctions.durationDays.bind(K.BuiltInFunctions));Q.functionHandlers.set("day",MR);Q.functionHandlers.set("days",MR);Q.functionHandlers.set("hours",Il(K.BuiltInFunctions.hours.bind(K.BuiltInFunctions),null,K.BuiltInFunctions.durationHours.bind(K.BuiltInFunctions)));Q.functionHandlers.set("minutes",Il(K.BuiltInFunctions.minutes.bind(K.BuiltInFunctions),null,K.BuiltInFunctions.durationMinutes.bind(K.BuiltInFunctions)));Q.functionHandlers.set("seconds",Il(K.BuiltInFunctions.seconds.bind(K.BuiltInFunctions),null,K.BuiltInFunctions.durationSeconds.bind(K.BuiltInFunctions)));Q.functionHandlers.set("timezone",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.timezone(t)});Q.functionHandlers.set("tz",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.tz(t)});Q.functionHandlers.set("adjust",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution),r=n.length>1?e.evaluateExpression(n[1],e.solution):void 0;return K.BuiltInFunctions.adjust(t,r)});Q.functionHandlers.set("now",()=>K.BuiltInFunctions.now());var jR=a((n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.xsdDateTime(e.getStringValue(t))},"dateTimeHandler");Q.functionHandlers.set("datetime",jR);Q.functionHandlers.set("xsd:datetime",jR);var $R=a((n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.xsdInteger(e.getStringValue(t))},"integerHandler");Q.functionHandlers.set("integer",$R);Q.functionHandlers.set("xsd:integer",$R);var UR=a((n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.xsdDecimal(e.getStringValue(t))},"decimalHandler");Q.functionHandlers.set("decimal",UR);Q.functionHandlers.set("xsd:decimal",UR);var BR=a((n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.xsdDayTimeDuration(e.getStringValue(t))},"dayTimeDurationHandler");Q.functionHandlers.set("daytimeduration",BR);Q.functionHandlers.set("xsd:daytimeduration",BR);Q.functionHandlers.set("durationtodays",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationToDays(t)});Q.functionHandlers.set("durationtohours",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationToHours(t)});Q.functionHandlers.set("durationtominutes",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationToMinutes(t)});Q.functionHandlers.set("durationtoseconds",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationToSeconds(t)});Q.functionHandlers.set("durationdays",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationDays(t)});Q.functionHandlers.set("durationhours",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationHours(t)});Q.functionHandlers.set("durationminutes",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationMinutes(t)});Q.functionHandlers.set("durationseconds",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationSeconds(t)});Q.functionHandlers.set("durationyears",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationYears(t)});Q.functionHandlers.set("durationmonths",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution);return K.BuiltInFunctions.durationMonths(t)});Q.functionHandlers.set("datetimediff",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution),r=e.evaluateExpression(n[1],e.solution);return K.BuiltInFunctions.dateTimeDiff(t,r)});Q.functionHandlers.set("datetimeadd",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution),r=e.evaluateExpression(n[1],e.solution);return K.BuiltInFunctions.dateTimeAdd(t,r)});Q.functionHandlers.set("datetimesubtract",(n,e)=>{let t=e.evaluateExpression(n[0],e.solution),r=e.evaluateExpression(n[1],e.solution);return K.BuiltInFunctions.dateTimeSubtract(t,r)});Q.functionHandlers.set("mstominutes",(n,e)=>{let t=Number(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.msToMinutes(t)});Q.functionHandlers.set("mstohours",(n,e)=>{let t=Number(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.msToHours(t)});Q.functionHandlers.set("mstoseconds",(n,e)=>{let t=Number(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.msToSeconds(t)});Q.functionHandlers.set("md5",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.md5(t)});Q.functionHandlers.set("sha1",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.sha1(t)});Q.functionHandlers.set("sha256",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.sha256(t)});Q.functionHandlers.set("sha384",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.sha384(t)});Q.functionHandlers.set("sha512",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution));return K.BuiltInFunctions.sha512(t)});Q.functionHandlers.set("subject",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.subject(t)});Q.functionHandlers.set("predicate",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.predicate(t)});Q.functionHandlers.set("object",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution);return K.BuiltInFunctions.object(t)});Q.functionHandlers.set("triple",(n,e)=>{let t=e.getTermFromExpression(n[0],e.solution),r=e.getTermFromExpression(n[1],e.solution),i=e.getTermFromExpression(n[2],e.solution);return K.BuiltInFunctions.triple(t,r,i)});Q.functionHandlers.set("days_between",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=new Date(t),s=new Date(r);return Math.floor((s.getTime()-i.getTime())/(1440*60*1e3))});Q.functionHandlers.set("minutes_between",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=new Date(t),s=new Date(r);return Math.floor((s.getTime()-i.getTime())/(60*1e3))});Q.functionHandlers.set("hours_between",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=new Date(t);return(new Date(r).getTime()-i.getTime())/(3600*1e3)});Q.functionHandlers.set("age_days",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=new Date(t);return Math.floor((new Date().getTime()-r.getTime())/(1440*60*1e3))});Q.functionHandlers.set("week_number",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=new Date(t),i=new Date(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate()));i.setUTCDate(i.getUTCDate()+4-(i.getUTCDay()||7));let s=new Date(Date.UTC(i.getUTCFullYear(),0,1));return Math.ceil(((i.getTime()-s.getTime())/(1440*60*1e3)+1)/7)});Q.functionHandlers.set("format_date",(n,e)=>{let t=e.getStringValue(e.evaluateExpression(n[0],e.solution)),r=e.getStringValue(e.evaluateExpression(n[1],e.solution)),i=new Date(t);return r.replace("YYYY",String(i.getFullYear())).replace("MM",String(i.getMonth()+1).padStart(2,"0")).replace("DD",String(i.getDate()).padStart(2,"0")).replace("HH",String(i.getHours()).padStart(2,"0")).replace("mm",String(i.getMinutes()).padStart(2,"0")).replace("ss",String(i.getSeconds()).padStart(2,"0"))});Q.functionHandlers.set("exo:eval",()=>{let{ExoQLEvalDisabledError:n}=qf();throw new n})});var vm=w(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});xl.FilterExecutor=xl.FilterExecutorError=void 0;var wt=wm(),u7=VR(),pw=Oe(),ws=qe(),wr=class extends Error{static{a(this,"FilterExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="FilterExecutorError"}};xl.FilterExecutorError=wr;var hw=class{static{a(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 r=this.expressionContainsExists(e.expression);for await(let i of t)try{let s;r?s=await this.evaluateExpressionAsync(e.expression,i):s=this.evaluateExpression(e.expression,i),s===!0&&(yield i)}catch{continue}}expressionContainsExists(e){if(!e||typeof e!="object")return!1;if(e.type==="exists")return!0;if(e.type==="logical")return e.operands.some(t=>this.expressionContainsExists(t));if(e.type==="comparison"){let t=e;return this.expressionContainsExists(t.left)||this.expressionContainsExists(t.right)}if(e.type==="arithmetic"){let t=e;return this.expressionContainsExists(t.left)||this.expressionContainsExists(t.right)}if(e.type==="in"){let t=e;return this.expressionContainsExists(t.expression)||t.list.some(r=>this.expressionContainsExists(r))}if(e.type==="function"||e.type==="functionCall"){let t=e;return Array.isArray(t.args)?t.args.some(r=>this.expressionContainsExists(r)):!1}return!1}async executeAll(e,t){let r=[];async function*i(){for(let s of t)yield s}a(i,"generator");for await(let s of this.execute(e,i()))r.push(s);return r}evaluateExpression(e,t){let r=e;if("termType"in e)switch(r.termType){case"Variable":return t.get(r.value);case"Literal":{let i=r.value,s=r.datatype,o=typeof s=="string"?s:s?.value;return o&&i.length>0&&this.shouldPreserveDatatype(o)?new ws.Literal(i,new pw.IRI(o)):i}case"NamedNode":return r.value;default:throw new wr(`Unsupported termType: ${String(r.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":{let i=e;return i.datatype&&i.value.length>0&&this.shouldPreserveDatatype(i.datatype)?new ws.Literal(i.value,new pw.IRI(i.datatype)):i.value}case"in":return this.evaluateIn(e,t);case"exists":throw new wr("EXISTS expressions require async evaluation. Use evaluateExpressionAsync instead.");default:throw new wr(`Unsupported expression type: ${e.type}`)}}async evaluateExpressionAsync(e,t){if(!this.expressionContainsExists(e))return this.evaluateExpression(e,t);if(e.type==="exists")return this.evaluateExists(e,t);if(e.type==="logical")return this.evaluateLogicalAsync(e,t);if(e.type==="comparison"){let r=e,i=await this.evaluateExpressionAsync(r.left,t),s=await this.evaluateExpressionAsync(r.right,t);return wt.BuiltInFunctions.compare(i,s,r.operator)}return e.type==="in"?this.evaluateInAsync(e,t):e.type==="function"||e.type==="functionCall"?this.evaluateFunctionAsync(e,t):this.evaluateExpression(e,t)}async evaluateExists(e,t){if(!this.existsEvaluator)throw new wr("EXISTS evaluator not set. Call setExistsEvaluator before evaluating EXISTS expressions.");let r=await this.existsEvaluator(e.pattern,t);return e.negated?!r:r}async evaluateLogicalAsync(e,t){if(e.operator==="!"){let i=await this.evaluateExpressionAsync(e.operands[0],t);return wt.BuiltInFunctions.logicalNot(i)}let r=[];for(let i of e.operands){let s=await this.evaluateExpressionAsync(i,t);r.push(s)}if(e.operator==="&&")return wt.BuiltInFunctions.logicalAnd(r);if(e.operator==="||")return wt.BuiltInFunctions.logicalOr(r);throw new wr(`Unknown logical operator: ${String(e.operator)}`)}async evaluateInAsync(e,t){let r=await this.evaluateExpressionAsync(e.expression,t),i=!1;for(let s of e.list){let o=await this.evaluateExpressionAsync(s,t);if(wt.BuiltInFunctions.compare(r,o,"=")){i=!0;break}}return e.negated?!i:i}async evaluateFunctionAsync(e,t){let r=e,i=this.extractFunctionName(r.function),s=r.args??[];if(i==="if"){if(s.length!==3)throw new wr("IF requires exactly 3 arguments");let l=await this.evaluateExpressionAsync(s[0],t);return this.toBoolean(l)?this.evaluateExpressionAsync(s[1],t):this.evaluateExpressionAsync(s[2],t)}if(i==="coalesce"){for(let l of s)try{let u=await this.evaluateExpressionAsync(l,t);if(u!=null)return u}catch{continue}return}let o=[];for(let l of s){let u=await this.evaluateExpressionAsync(l,t);o.push(this.wrapAsLiteralExpression(u))}let c={...r,args:o};return this.evaluateFunction(c,t)}wrapAsLiteralExpression(e){return e==null?{type:"literal",value:""}:typeof e=="object"&&"termType"in e?e:e instanceof pw.IRI||e instanceof ws.Literal?{type:"literal",value:e.value}:typeof e=="number"||typeof e=="boolean"||typeof e=="string"?{type:"literal",value:e}:{type:"literal",value:String(e)}}evaluateComparison(e,t){let r=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);return wt.BuiltInFunctions.compare(r,i,e.operator)}evaluateLogical(e,t){if(e.operator==="!"){let i=this.evaluateExpression(e.operands[0],t);return wt.BuiltInFunctions.logicalNot(i)}let r=e.operands.map(i=>this.evaluateExpression(i,t));if(e.operator==="&&")return wt.BuiltInFunctions.logicalAnd(r);if(e.operator==="||")return wt.BuiltInFunctions.logicalOr(r);throw new wr(`Unknown logical operator: ${String(e.operator)}`)}evaluateIn(e,t){let r=this.evaluateExpression(e.expression,t),i=e.list.some(s=>{let o=this.evaluateExpression(s,t);return wt.BuiltInFunctions.compare(r,o,"=")});return e.negated?!i:i}evaluateArithmetic(e,t){let r=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);if(e.operator==="-"&&this.isDateValue(r)&&this.isDateValue(i))return wt.BuiltInFunctions.dateDiff(r,i);if(e.operator==="-"&&this.isTimeValue(r)&&this.isTimeValue(i))return wt.BuiltInFunctions.timeDiff(r,i);if(e.operator==="-"&&this.isDateTimeValue(r)&&this.isDateTimeValue(i))return wt.BuiltInFunctions.dateTimeDiff(r,i);if(e.operator==="+"&&this.isDateValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.dateAdd(r,i);if(e.operator==="-"&&this.isDateValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.dateSubtract(r,i);if(e.operator==="+"&&this.isDateValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.dateAddYearMonth(r,i);if(e.operator==="-"&&this.isDateValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.dateSubtractYearMonth(r,i);if(e.operator==="+"&&this.isDateTimeValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.dateTimeAdd(r,i);if(e.operator==="-"&&this.isDateTimeValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.dateTimeSubtract(r,i);if(e.operator==="+"&&this.isDateTimeValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.dateTimeAddYearMonth(r,i);if(e.operator==="-"&&this.isDateTimeValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.dateTimeSubtractYearMonth(r,i);if(e.operator==="+"&&this.isDayTimeDurationValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.durationAdd(r,i);if(e.operator==="-"&&this.isDayTimeDurationValue(r)&&this.isDayTimeDurationValue(i))return wt.BuiltInFunctions.durationSubtract(r,i);if(e.operator==="*"&&this.isDayTimeDurationValue(r)&&!this.isDayTimeDurationValue(i)){let c=this.toNumericValue(i);return wt.BuiltInFunctions.durationMultiply(r,c)}if(e.operator==="*"&&!this.isDayTimeDurationValue(r)&&this.isDayTimeDurationValue(i)){let c=this.toNumericValue(r);return wt.BuiltInFunctions.durationMultiply(i,c)}if(e.operator==="/"&&this.isDayTimeDurationValue(r)&&!this.isDayTimeDurationValue(i)){let c=this.toNumericValue(i);if(c===0)throw new wr("Division by zero");return wt.BuiltInFunctions.durationDivide(r,c)}if(e.operator==="+"&&this.isYearMonthDurationValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.yearMonthDurationAdd(r,i);if(e.operator==="-"&&this.isYearMonthDurationValue(r)&&this.isYearMonthDurationValue(i))return wt.BuiltInFunctions.yearMonthDurationSubtract(r,i);let s=this.toNumericValue(r),o=this.toNumericValue(i);switch(e.operator){case"+":return s+o;case"-":return s-o;case"*":return s*o;case"/":if(o===0)throw new wr("Division by zero");return s/o;default:throw new wr(`Unknown arithmetic operator: ${String(e.operator)}`)}}shouldPreserveDatatype(e){return e==="http://www.w3.org/2001/XMLSchema#dateTime"||e==="http://www.w3.org/2001/XMLSchema#date"||e==="http://www.w3.org/2001/XMLSchema#time"||e==="http://www.w3.org/2001/XMLSchema#dayTimeDuration"||e==="http://www.w3.org/2001/XMLSchema#yearMonthDuration"||e==="http://www.w3.org/2001/XMLSchema#duration"}isDayTimeDurationValue(e){return e instanceof ws.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}isYearMonthDurationValue(e){return e instanceof ws.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#yearMonthDuration":!1}toNumericValue(e){if(typeof e=="number")return e;if(e instanceof ws.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 r=parseFloat(e.value);if(!isNaN(r))return r}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 wr(`Cannot convert to number: ${e}`)}isDateTimeValue(e){if(e instanceof ws.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 ws.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#date":!1}isTimeValue(e){return e instanceof ws.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#time":!1}evaluateFunction(e,t){let r=e,i=this.extractFunctionName(r.function),s=this.evaluateSpecialFunction(i,r.args,t);if(s!==void 0)return s.value;let o=u7.functionHandlers.get(i);if(!o)throw new wr(`Unknown function: ${i}`);let c={evaluateExpression:a((l,u)=>this.evaluateExpression(l,u),"evaluateExpression"),getTermFromExpression:a((l,u)=>this.getTermFromExpression(l,u),"getTermFromExpression"),getStringValue:a(l=>this.getStringValue(l),"getStringValue"),solution:t,isYearMonthDurationValue:a(l=>this.isYearMonthDurationValue(l),"isYearMonthDurationValue"),isDayTimeDurationValue:a(l=>this.isDayTimeDurationValue(l),"isDayTimeDurationValue")};return o(r.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 wr(`Unknown function format: ${String(e)}`)}evaluateSpecialFunction(e,t,r){switch(e){case"coalesce":for(let i of t)try{let s=this.evaluateExpression(i,r);if(s!=null)return{value:s}}catch{continue}return{value:void 0};case"if":{if(!t||t.length!==3)throw new wr("IF requires exactly 3 arguments");let i=this.evaluateExpression(t[0],r);return{value:this.toBoolean(i)?this.evaluateExpression(t[1],r):this.evaluateExpression(t[2],r)}}case"byuuid":return{value:this.evaluateByUUID({type:"function",function:"byuuid",args:t},r)};default:return}}getTermFromExpression(e,t){let r=e;if(r.type==="variable"&&r.name)return t.get(r.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 ws.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 r=parseFloat(e.value);return!isNaN(r)&&r!==0}return e.value.length>0}return!!e}evaluateByUUID(e,t){if(!e.args||e.args.length!==1)throw new wr("exo:byUUID requires exactly 1 argument (UUID string)");let r=this.evaluateExpression(e.args[0],t),i=this.getStringValue(r);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 o=this.tripleStore.findSubjectsByUUIDSync(s);if(o.length===0){this.uuidCache.set(s,null);return}let c=o[0];return this.uuidCache.set(s,c),c}this.uuidCache.set(s,null)}cacheUUIDResult(e,t){let r=e.toLowerCase();this.uuidCache.set(r,t)}getCachedUUID(e){let t=e.toLowerCase();if(this.uuidCache.has(t))return this.uuidCache.get(t)}};xl.FilterExecutor=hw});var gw=w(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});Em.OptionalExecutor=void 0;var mw=class{static{a(this,"OptionalExecutor")}async*execute(e,t){let r=[];for await(let s of e)r.push(s);let i=[];for await(let s of t)i.push(s);yield*this.hashJoin(r,i)}async executeAll(e,t){let r=[];for(let i of this.hashJoin(e,t))r.push(i);return r}*hashJoin(e,t){if(e.length===0)return;if(t.length===0){yield*e;return}let r=new Set;for(let l of e)for(let u of l.variables())r.add(u);let i=new Set;for(let l of t)for(let u of l.variables())i.add(u);let s=[];for(let l of r)i.has(l)&&s.push(l);if(s.sort(),s.length===0){yield*this.nestedLoopJoin(e,t);return}let o="\0",c=new Map;for(let l of t){let u=this.computeHashKey(l,s,o),f=c.get(u);f||(f=[],c.set(u,f)),f.push(l)}for(let l of e){let u=this.computeHashKey(l,s,o),f=c.get(u),d=!1;if(f)for(let p of f){let h=l.merge(p);h!==null&&(yield h,d=!0)}d||(yield l)}}computeHashKey(e,t,r){let i=[];for(let s of t){let o=e.get(s);i.push(o!==void 0?o.toString():"UNBOUND")}return i.join(r)}*nestedLoopJoin(e,t){for(let r of e){let i=!1;for(let s of t){let o=r.merge(s);o!==null&&(yield o,i=!0)}i||(yield r)}}};Em.OptionalExecutor=mw});var bw=w(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});Tm.UnionExecutor=void 0;var yw=class{static{a(this,"UnionExecutor")}async*execute(e,t){let r=new Set;for await(let i of e){let s=this.getSolutionKey(i);r.has(s)||(r.add(s),yield i)}for await(let i of t){let s=this.getSolutionKey(i);r.has(s)||(r.add(s),yield i)}}async executeAll(e,t){let r=[];async function*i(){for(let o of e)yield o}a(i,"generateLeft");async function*s(){for(let o of t)yield o}a(s,"generateRight");for await(let o of this.execute(i(),s()))r.push(o);return r}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}};Tm.UnionExecutor=yw});var GR=w(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});Am.MinusExecutor=void 0;var _w=class{static{a(this,"MinusExecutor")}async*execute(e,t){let r=[];for await(let s of e)r.push(s);let i=[];for await(let s of t)i.push(s);for(let s of r){let o=!1;for(let c of i)if(this.areCompatible(s,c)){o=!0;break}o||(yield s)}}async executeAll(e,t){let r=[];async function*i(){for(let o of e)yield o}a(i,"generateLeft");async function*s(){for(let o of t)yield o}a(s,"generateRight");for await(let o of this.execute(i(),s()))r.push(o);return r}areCompatible(e,t){let r=e.variables(),i=new Set(t.variables()),s=r.filter(o=>i.has(o));if(s.length===0)return!1;for(let o of s){let c=e.get(o),l=t.get(o);if(c===void 0||l===void 0||c.toString()!==l.toString())return!1}return!0}};Am.MinusExecutor=_w});var WR=w(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.ValuesExecutor=Rl.ValuesExecutorError=void 0;var f7=_s(),qR=Oe(),d7=qe(),Im=class extends Error{static{a(this,"ValuesExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ValuesExecutorError"}};Rl.ValuesExecutorError=Im;var Sw=class{static{a(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 r of this.execute(e))t.push(r);return t}createSolutionMapping(e){let t=new f7.SolutionMapping;for(let[r,i]of Object.entries(e)){let s=this.toRDFTerm(i);t.set(r,s)}return t}toRDFTerm(e){if(e.type==="iri")return new qR.IRI(e.value);if(e.type==="literal")return new d7.Literal(e.value,e.datatype?new qR.IRI(e.datatype):void 0,e.language,e.direction);throw new Im(`Unknown term type: ${e.type}`)}};Rl.ValuesExecutor=Sw});var ww=w(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.CustomAggregateRegistry=Pl.CustomAggregateError=void 0;var Cl=class extends Error{static{a(this,"CustomAggregateError")}constructor(e,t){super(e),this.iri=t,this.name="CustomAggregateError"}};Pl.CustomAggregateError=Cl;var xm=class n{static{a(this,"CustomAggregateRegistry")}constructor(){this.aggregates=new Map}static getInstance(){return n.instance||(n.instance=new n),n.instance}static resetInstance(){n.instance&&n.instance.clear(),n.instance=null}register(e,t){if(!e||typeof e!="string")throw new Cl("Aggregate IRI must be a non-empty string");if(!t||typeof t.init!="function"||typeof t.step!="function"||typeof t.finalize!="function")throw new Cl("Aggregate must implement init(), step(), and finalize() methods",e);if(this.aggregates.has(e))throw new Cl(`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}};Pl.CustomAggregateRegistry=xm;xm.instance=null});var vw=w(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.BUILT_IN_AGGREGATES=ot.modeAggregate=ot.stddevAggregate=ot.varianceAggregate=ot.medianAggregate=ot.EXO_AGGREGATE_NS=void 0;ot.getNumericValue=Rm;ot.createDecimalLiteral=Pi;ot.createDoubleLiteral=m7;ot.createPercentileAggregate=sc;var oc=qe(),Ol=Oe(),p7=new Ol.IRI("http://www.w3.org/2001/XMLSchema#decimal"),h7=new Ol.IRI("http://www.w3.org/2001/XMLSchema#double");ot.EXO_AGGREGATE_NS="https://exocortex.my/ontology/agg#";function Rm(n){return n==null?NaN:typeof n=="number"?n:typeof n=="string"?parseFloat(n):n instanceof oc.Literal?parseFloat(n.value):n instanceof Ol.IRI?NaN:typeof n=="boolean"?n?1:0:NaN}a(Rm,"getNumericValue");function Pi(n){return new oc.Literal(String(n),p7)}a(Pi,"createDecimalLiteral");function m7(n){return new oc.Literal(String(n),h7)}a(m7,"createDoubleLiteral");ot.medianAggregate={init(){return{values:[]}},step(n,e){let t=n,r=Rm(e);isNaN(r)||t.values.push(r)},finalize(n){let e=n,{values:t}=e;if(t.length===0)return Pi(0);let r=[...t].sort((o,c)=>o-c),i=Math.floor(r.length/2),s=r.length%2!==0?r[i]:(r[i-1]+r[i])/2;return Pi(s)}};ot.varianceAggregate={init(){return{values:[]}},step(n,e){let t=n,r=Rm(e);isNaN(r)||t.values.push(r)},finalize(n){let e=n,{values:t}=e;if(t.length===0)return Pi(0);let r=t.reduce((s,o)=>s+o,0)/t.length,i=t.reduce((s,o)=>s+Math.pow(o-r,2),0)/t.length;return Pi(i)}};ot.stddevAggregate={init(){return{values:[]}},step(n,e){ot.varianceAggregate.step(n,e)},finalize(n){let e=n,{values:t}=e;if(t.length===0)return Pi(0);let r=t.reduce((s,o)=>s+o,0)/t.length,i=t.reduce((s,o)=>s+Math.pow(o-r,2),0)/t.length;return Pi(Math.sqrt(i))}};ot.modeAggregate={init(){return{counts:new Map,values:new Map}},step(n,e){if(e==null)return;let t=n,r=String(e instanceof oc.Literal||e instanceof Ol.IRI?e.value:e),i=t.counts.get(r)||0;t.counts.set(r,i+1),t.values.set(r,e)},finalize(n){let e=n;if(e.counts.size===0)return new oc.Literal(" ",new Ol.IRI("http://www.w3.org/2001/XMLSchema#string"));let t="",r=0;for(let[o,c]of e.counts)c>r&&(r=c,t=o);let i=e.values.get(t);if(i instanceof oc.Literal)return i;let s=parseFloat(t);return isNaN(s)?new oc.Literal(t,new Ol.IRI("http://www.w3.org/2001/XMLSchema#string")):Pi(s)}};function sc(n){let e=Math.max(0,Math.min(100,n))/100;return{init(){return{values:[],percentile:e}},step(t,r){let i=t,s=Rm(r);isNaN(s)||i.values.push(s)},finalize(t){let r=t,{values:i}=r;if(i.length===0)return Pi(0);let s=[...i].sort((d,p)=>d-p),o=r.percentile*(s.length-1),c=Math.floor(o),l=Math.ceil(o);if(c===l)return Pi(s[c]);let u=o-c,f=s[c]*(1-u)+s[l]*u;return Pi(f)}}}a(sc,"createPercentileAggregate");ot.BUILT_IN_AGGREGATES={[`${ot.EXO_AGGREGATE_NS}median`]:ot.medianAggregate,[`${ot.EXO_AGGREGATE_NS}variance`]:ot.varianceAggregate,[`${ot.EXO_AGGREGATE_NS}stddev`]:ot.stddevAggregate,[`${ot.EXO_AGGREGATE_NS}mode`]:ot.modeAggregate,[`${ot.EXO_AGGREGATE_NS}percentile25`]:sc(25),[`${ot.EXO_AGGREGATE_NS}percentile50`]:sc(50),[`${ot.EXO_AGGREGATE_NS}percentile75`]:sc(75),[`${ot.EXO_AGGREGATE_NS}percentile90`]:sc(90),[`${ot.EXO_AGGREGATE_NS}percentile95`]:sc(95),[`${ot.EXO_AGGREGATE_NS}percentile99`]:sc(99)}});var KR=w(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});Dl.AggregateExecutor=Dl.AggregateExecutorError=void 0;var gr=qe(),Tw=Oe(),g7=vm(),y7=ww(),b7=vw(),zR=new Tw.IRI("http://www.w3.org/2001/XMLSchema#integer"),ac=new Tw.IRI("http://www.w3.org/2001/XMLSchema#decimal"),vs=new Tw.IRI("http://www.w3.org/2001/XMLSchema#string");function HR(n){return typeof n=="object"&&n.type==="custom"}a(HR,"isCustomAggregation");var Wf=class extends Error{static{a(this,"AggregateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AggregateExecutorError"}};Dl.AggregateExecutorError=Wf;var Ew=class{static{a(this,"AggregateExecutor")}constructor(){this.filterExecutor=new g7.FilterExecutor}execute(e,t){let r=this.groupSolutions(t,e.variables),i=[];for(let[s,o]of r.entries()){let c=new Map;for(let f of e.variables)if(o.length>0){let d=o[0].get(f);d&&c.set(f,d)}for(let f of e.aggregates){let d=this.computeAggregate(f.expression,o);c.set(f.variable,d)}let{SolutionMapping:l}=_s(),u=new l;for(let[f,d]of c.entries())u.set(f,d);i.push(u)}if(i.length===0&&e.aggregates.length>0){let s=this.createEmptyAggregateResult(e);s&&i.push(s)}return i}groupSolutions(e,t){let r=new Map;if(t.length===0)return r.set("",e),r;for(let i of e){let s=this.computeGroupKey(i,t),o=r.get(s);o?o.push(i):r.set(s,[i])}return r}computeGroupKey(e,t){return t.map(r=>{let i=e.get(r);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(HR(e.aggregation))return this.computeCustomAggregate(e,t);let r=this.extractValues(e,t),i=e.aggregation;switch(i){case"count":{let s=this.computeCount(r,e.distinct);return new gr.Literal(String(s),zR)}case"sum":{let s=this.computeSum(r);return new gr.Literal(String(s),ac)}case"avg":{let s=this.computeAvg(r);return new gr.Literal(String(s),ac)}case"min":{let s=this.computeMin(r);return s===void 0?new gr.Literal("",vs):typeof s=="number"?new gr.Literal(String(s),ac):new gr.Literal(String(s),vs)}case"max":{let s=this.computeMax(r);return s===void 0?new gr.Literal("",vs):typeof s=="number"?new gr.Literal(String(s),ac):new gr.Literal(String(s),vs)}case"group_concat":{let s=this.computeGroupConcat(r,e.separator||" ",e.distinct);return new gr.Literal(s||" ",vs)}case"sample":{let s=this.computeSample(r,e.distinct);return s===void 0?new gr.Literal(" ",vs):typeof s=="number"?new gr.Literal(String(s),ac):new gr.Literal(String(s),vs)}default:{let s=i;throw new Wf(`Unknown aggregation function: ${s}`)}}}computeCustomAggregate(e,t){let i=e.aggregation.iri,o=y7.CustomAggregateRegistry.getInstance().get(i);if(o||(o=b7.BUILT_IN_AGGREGATES[i]),!o)throw new Wf(`Unknown custom aggregate function: ${i}. Register it with CustomAggregateRegistry.getInstance().register() or use a built-in aggregate.`);let c=o.init();for(let l of t){let u=null;if(e.expression){let f=this.evaluateExpression(e.expression,l);f!==void 0&&(u=f)}else u=1;o.step(c,u)}return o.finalize(c)}extractValues(e,t){if(!e.expression)return t.map(()=>1);let r=[];for(let i of t){let s=this.evaluateExpression(e.expression,i);s!=null&&r.push(s)}return r}evaluateExpression(e,t){if(e.type==="variable"){let r=t.get(e.name);return r==null?void 0:typeof r=="number"||typeof r=="string"||typeof r=="boolean"?r:typeof r=="object"&&"value"in r?r.value:r}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(r=>String(r))).size:e.length}computeSum(e){return e.map(r=>parseFloat(String(r))).filter(r=>!isNaN(r)).reduce((r,i)=>r+i,0)}computeAvg(e){let t=e.map(r=>parseFloat(String(r))).filter(r=>!isNaN(r));return t.length===0?0:t.reduce((r,i)=>r+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 r=e.map(i=>String(i));return r.reduce((i,s)=>s<i?s:i,r[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 r=e.map(i=>String(i));return r.reduce((i,s)=>s>i?s:i,r[0])}computeGroupConcat(e,t,r){let i=e.map(s=>String(s));return r&&(i=[...new Set(i)]),i.join(t)}computeSample(e,t){if(e.length===0)return;if(t){let s=[...new Set(e.map(l=>String(l)))];if(s.length===0)return;let o=s[0],c=parseFloat(o);return isNaN(c)?o:c}let r=e[0];if(typeof r=="number")return r;let i=parseFloat(String(r));return isNaN(i)?String(r):i}createEmptyAggregateResult(e){let{SolutionMapping:t}=_s(),r=new t;for(let i of e.aggregates){let s=i.expression.aggregation;if(HR(s)){r.set(i.variable,new gr.Literal("0",ac));continue}switch(s){case"count":r.set(i.variable,new gr.Literal("0",zR));break;case"sum":case"avg":r.set(i.variable,new gr.Literal("0",ac));break;case"group_concat":r.set(i.variable,new gr.Literal(" ",vs));break;case"min":case"max":case"sample":r.set(i.variable,new gr.Literal("",vs));break;default:r.set(i.variable,new gr.Literal("",vs))}}return r}};Dl.AggregateExecutor=Ew});var Rw=w(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});Cm.ConstructExecutor=void 0;var _7=Wn(),cc=Oe(),Aw=qe(),Iw=Bt(),S7=_f(),xw=class{static{a(this,"ConstructExecutor")}async execute(e,t){let r=[],i=new Set;for(let s of t)for(let o of e)try{let c=this.instantiateTriple(o,s),l=`${c.subject.toString()}|${c.predicate.toString()}|${c.object.toString()}`;i.has(l)||(i.add(l),r.push(c))}catch{continue}return r}instantiateTriple(e,t){if(this.isPropertyPath(e.predicate))throw new Error("Property paths are not supported in CONSTRUCT templates");let r=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.predicate,t),s=this.instantiateElement(e.object,t);return new _7.Triple(r,i,s)}isPropertyPath(e){return e.type==="path"}instantiateElement(e,t){if(e.type==="variable"){let r=t.get(e.value);if(!r)throw new Error(`Unbound variable: ${e.value}`);return r}if(e.type==="iri")return new cc.IRI(e.value);if(e.type==="literal")return new Aw.Literal(e.value,e.datatype?new cc.IRI(e.datatype):void 0,e.language);if(e.type==="blank")return new Iw.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Unknown element type: ${e.type}`)}instantiateQuotedTriple(e,t){let r=this.instantiateQuotedSubject(e.subject,t),i=this.instantiateQuotedPredicate(e.predicate,t),s=this.instantiateQuotedObject(e.object,t);return new S7.QuotedTriple(r,i,s)}instantiateQuotedSubject(e,t){if(e.type==="variable"){let r=t.get(e.value);if(!r)throw new Error(`Unbound variable in quoted triple subject: ${e.value}`);if(r instanceof Aw.Literal)throw new Error("Literals cannot appear in quoted triple subject position");return r}if(e.type==="iri")return new cc.IRI(e.value);if(e.type==="blank")return new Iw.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 r=t.get(e.value);if(!r)throw new Error(`Unbound variable in quoted triple predicate: ${e.value}`);if(!(r instanceof cc.IRI))throw new Error("Quoted triple predicate must be an IRI");return r}return new cc.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 cc.IRI(e.value);if(e.type==="blank")return new Iw.BlankNode(e.value);if(e.type==="literal")return new Aw.Literal(e.value,e.datatype?new cc.IRI(e.datatype):void 0,e.language);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);let r=e;throw new Error(`Invalid element type for quoted triple object: ${r.type}`)}};Cm.ConstructExecutor=xw});var XR=w(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});Fl.ServiceExecutor=Fl.ServiceExecutorError=void 0;var w7=_s(),QR=Oe(),v7=qe(),E7=Bt(),lc=class extends Error{static{a(this,"ServiceExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ServiceExecutorError"}};Fl.ServiceExecutorError=lc;var Cw=class{static{a(this,"ServiceExecutor")}constructor(e={}){this.timeout=e.timeout??3e4,this.httpClient=e.httpClient??((t,r)=>fetch(t,r)),this.maxRetries=e.maxRetries??2,this.retryDelay=e.retryDelay??1e3}async*execute(e,t){try{let r=t(e.pattern),i=await this.executeRemoteQuery(e.endpoint,r);for(let s of i)yield s}catch(r){if(e.silent)return;throw r}}async executeRemoteQuery(e,t){let r;for(let i=0;i<=this.maxRetries;i++)try{let s=new AbortController,o=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 lc(`Remote SPARQL endpoint returned ${c.status}: ${c.statusText}`);let l=await c.json();return this.parseJsonResults(l)}finally{clearTimeout(o)}}catch(s){if(r=s instanceof Error?s:new Error(String(s)),this.isRetryableError(r)&&i<this.maxRetries){await this.delay(this.retryDelay);continue}throw new lc(`Failed to query remote SPARQL endpoint ${e}: ${r.message}`,r)}throw new lc(`Failed to query remote SPARQL endpoint ${e} after ${this.maxRetries+1} attempts`,r)}parseJsonResults(e){return!e.results||!Array.isArray(e.results.bindings)?[]:e.results.bindings.map(t=>this.parseBinding(t))}parseBinding(e){let t=new w7.SolutionMapping;for(let[r,i]of Object.entries(e)){let s=this.parseRDFTerm(i);t.set(r,s)}return t}parseRDFTerm(e){switch(e.type){case"uri":return new QR.IRI(e.value);case"literal":{let t=e.datatype?new QR.IRI(e.datatype):void 0;return new v7.Literal(e.value,t,e["xml:lang"])}case"bnode":return new E7.BlankNode(e.value);default:throw new lc(`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))}};Fl.ServiceExecutor=Cw});var JR=w(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});Ll.GraphExecutor=Ll.GraphExecutorError=void 0;var YR=Oe(),Pm=class extends Error{static{a(this,"GraphExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="GraphExecutorError"}};Ll.GraphExecutorError=Pm;var Pw=class{static{a(this,"GraphExecutor")}constructor(e){this.tripleStore=e}async*execute(e,t,r){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,r);else throw new Pm(`Invalid graph name type: ${i.type}`)}async*executeWithGraph(e,t,r){let i=new YR.IRI(t.value);this.tripleStore.hasGraph&&!await this.tripleStore.hasGraph(i)||(yield*r(e,i))}async*executeWithGraphVariable(e,t,r,i){if(i){let o=i.get(t.value);if(o&&o instanceof YR.IRI){yield*this.executeWithGraph(e.pattern,{type:"iri",value:o.value},r);return}}if(!this.tripleStore.getNamedGraphs)return;let s=await this.tripleStore.getNamedGraphs();for(let o of s)for await(let c of r(e.pattern,o)){let l=c.clone();l.set(t.value,o),yield l}}};Ll.GraphExecutor=Pw});var ZR=w(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.SPARQLGenerator=kl.SPARQLGeneratorError=void 0;var Nl=class extends Error{static{a(this,"SPARQLGeneratorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="SPARQLGeneratorError"}};kl.SPARQLGeneratorError=Nl;var Ow=class{static{a(this,"SPARQLGenerator")}collectVariables(e){let t=new Set;return this.collectVariablesFromOperation(e,t),t}generateSelect(e){let t=this.collectVariables(e),r=t.size>0?Array.from(t).map(s=>`?${s}`).join(" "):"*",i=this.generateWhereClause(e);return`SELECT ${r} WHERE {
|
|
49
49
|
${i}
|
|
50
50
|
}`}generateWhereClause(e,t=2){let r=" ".repeat(t);switch(e.type){case"bgp":return this.generateBGP(e,t);case"filter":return`${this.generateWhereClause(e.input,t)}
|
|
51
51
|
${r}FILTER(${this.generateExpression(e.expression)})`;case"join":return`${this.generateWhereClause(e.left,t)}
|
|
@@ -775,7 +775,7 @@ Next steps:
|
|
|
775
775
|
`),process.stdout.write(` File: ${e.file}
|
|
776
776
|
`),process.stdout.write(` Commit: ${e.sha}
|
|
777
777
|
`),process.stdout.write(` URL: ${e.url}
|
|
778
|
-
`)),process.exit(0)}catch(e){let t=e instanceof Error?e:new Error(String(e)),r=new Ei;t.message=r.redact(t.message),t.stack&&(t.stack=r.redact(t.stack)),le.handle(t)}})}a(Jie,"restPushCommand");var $o=require("node:fs"),Fj=require("node:crypto"),Ti=J(require("node:path"));var Ai=J(rt());var Zie=a(async n=>{let e=await Fj.webcrypto.subtle.digest("SHA-1",n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength));return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")},"nodeSha1"),ese={parse:a(n=>Nt.load(n,{schema:Nt.CORE_SCHEMA}),"parse"),stringify:a(n=>Nt.dump(n,{schema:Nt.CORE_SCHEMA,lineWidth:-1}),"stringify")};function tse(n,e){if(n.tokenFromGh===!0)return Ei.resolveGhToken(e.ghTokenRunner);let t=e.env??process.env,r=n.token||t.GITHUB_TOKEN||t.GH_TOKEN||"";if(r.length===0)throw new Error("A GitHub token is required (private sync units read as 404 without one). Use --token-from-gh, --token <pat>, or set GITHUB_TOKEN / GH_TOKEN.");return r}a(tse,"resolveToken");function rse(n){let e=a(r=>Ti.join(n,r),"abs"),t=a(async(r,i)=>{let s;try{s=await $o.promises.readdir(r,{withFileTypes:!0})}catch{return}for(let o of s){let c=Ti.join(r,o.name);if(o.isDirectory()){if(o.name===".git")continue;await t(c,i)}else o.isFile()&&i.push(Ti.relative(n,c).split(Ti.sep).join("/"))}},"walk");return{async list(){let r=[];return(0,$o.existsSync)(n)&&await t(n,r),r},read:a(r=>$o.promises.readFile(e(r),"utf-8"),"read"),async readBinary(r){return new Uint8Array(await $o.promises.readFile(e(r)))},async write(){throw new Error("exosync-parity is read-only \u2014 write refused")},async delete(){throw new Error("exosync-parity is read-only \u2014 delete refused")}}}a(rse,"nodeLocalFilesPort");function vA(n){let e=new pt(n),t=new Ai.SpaceSpecAccumulator;for(let r of e.getAllFiles()){let i=e.getFrontmatter(r);if(!i)continue;let s=(0,Ai.classifySpaceDeclaration)(i,r.path);if(s.kind==="not-space"||(s.warning!==void 0&&t.warnings.push(s.warning),s.kind==="skip"))continue;let o=t.offer(s.candidate);o!==null&&(0,$o.existsSync)(Ti.join(n,o.localPath))&&t.commit(s.candidate)}return{specs:t.specs,warnings:t.warnings}}a(vA,"collectVaultSpecs");function nse(n,e){for(let t of n.repos){let r=t.headSha!==void 0?` @${t.headSha.slice(0,7)}`:"";e(`${t.repoKey}${r}: ${t.status} \u2014 ${t.inParity}/${t.filesChecked} in parity, M2 diffs ${t.m2SemanticDiffs}, accounted ${t.accountedCount}, M1 violations ${t.m1Violations.length}${t.attachmentHashSetIdentical!==void 0?`, attachment hash-set ${t.attachmentHashSetIdentical?"identical":"DIFFERS"}`:""}`),t.detail!==void 0&&e(` ${t.detail}`);for(let i of t.warnings)e(` warn: ${i}`);for(let i of t.discrepancies)e(` ${i.cls}: ${i.path}${i.detail!==void 0?` (${i.detail})`:""}`);for(let i of t.m1Violations)e(` M1 VIOLATION: ${i.path} \u2014 ${i.detail}`)}e((0,Ai.summarizeParityRound)(n))}a(nse,"printHumanReport");async function ise(n,e={}){let t=e.out??(y=>console.log(y)),r=Ti.resolve(n.vault);if(!(0,$o.existsSync)(r))throw new Error(`Vault path does not exist: ${r}`);let i=tse(n,e),s=new Ei({token:i,...n.apiBase!==void 0?{apiBase:n.apiBase}:{}}),o=e.transportFactory?.(i,n.apiBase)??s.transport(),{specs:c,warnings:l}=vA(r);for(let y of l)t(`warn: ${y}`);if(c.length===0)return t("Nothing to check \u2014 no materialized AssetSpaces with a GitHub source found in this vault."),2;let u=n.configDir??".obsidian",f=Ti.join(r,u,"plugins","exocortex",Ai.WATERMARK_STORE_FILENAME),d=new Ai.FileWatermarkStore({read:a(async()=>{try{return await $o.promises.readFile(f,"utf-8")}catch{return null}},"read"),writeAtomic:a(async()=>{throw new Error("exosync-parity: watermark access is read-only by contract")},"writeAtomic")}),p=new Ai.ParityValidator({transport:o,sha1:Zie,localFilesFor:a(y=>rse(Ti.join(r,y.localPath)),"localFilesFor"),watermarks:{get:a(y=>d.get(y),"get")},yaml:ese,redact:a(y=>s.redact(y),"redact"),...n.apiBase!==void 0?{baseURL:n.apiBase}:{}});t(`ExoSync parity check: ${c.length} repo(s), vault ${r}`);let h=await p.runRound(c,{trigger:"standalone"});return n.json===!0?t(JSON.stringify(h,null,2)):nse(h,t),h.vacuous?2:h.ok?0:1}a(ise,"runExosyncParity");function Lj(){return new Ae("exosync-parity").description("ExoSync M1/M2 parity report: compare materialized sync units against their remote heads (read-only; RFC 4e4dc453 Phase E)").requiredOption("--vault <path>","Vault root path").option("--config-dir <name>","Obsidian config dir name (watermark location)",".obsidian").option("--json","Print the full round record as JSON").option("--token <pat>","GitHub PAT (or env GITHUB_TOKEN / GH_TOKEN). Prefer --token-from-gh.").option("--token-from-gh","Resolve the PAT via `gh auth token`").option("--api-base <url>","GitHub API base (testing)").action(async n=>{try{process.exitCode=await ise(n)}catch(e){le.handle(e,{command:"exosync-parity"}),process.exitCode=1}})}a(Lj,"exosyncParityCommand");var Dr=require("node:fs"),kj=require("node:crypto"),xn=J(require("node:path"));var Fr=J(rt());var Nj=a(async n=>{let e=await kj.webcrypto.subtle.digest("SHA-1",n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength));return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")},"nodeSha1"),sse={parse:a(n=>Nt.load(n,{schema:Nt.CORE_SCHEMA}),"parse"),stringify:a(n=>Nt.dump(n,{schema:Nt.CORE_SCHEMA,lineWidth:-1}),"stringify")};function ose(n,e){if(n.tokenFromGh===!0)return Ei.resolveGhToken(e.ghTokenRunner);let t=e.env??process.env,r=n.token||t.GITHUB_TOKEN||t.GH_TOKEN||"";if(r.length===0)throw new Error("A GitHub token is required (private sync units read as 404 and push needs write scope). Use --token-from-gh, --token <pat>, or set GITHUB_TOKEN / GH_TOKEN.");return r}a(ose,"resolveToken");function ase(n){let e=/^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(n.trim());if(e===null)throw new Error(`Invalid quarantine repo URL (expected https://github.com/<owner>/<repo>): ${n}`);return{owner:e[1],repo:e[2]}}a(ase,"parseGitHubRepoUrl");function cse(n){let e=a(i=>xn.join(n,i),"abs"),t=a(async(i,s)=>{let o;try{o=await Dr.promises.readdir(i,{withFileTypes:!0})}catch{return}for(let c of o){let l=xn.join(i,c.name);if(c.isDirectory()){if(c.name===".git")continue;await t(l,s)}else c.isFile()&&s.push(xn.relative(n,l).split(xn.sep).join("/"))}},"walk"),r=a(async(i,s)=>{let o=xn.dirname(i);await Dr.promises.mkdir(o,{recursive:!0});let c=`${i}.local.tmp`;await s(c),await Dr.promises.rename(c,i)},"writeAtomic");return{async list(){let i=[];return(0,Dr.existsSync)(n)&&await t(n,i),i},read:a(i=>Dr.promises.readFile(e(i),"utf-8"),"read"),async write(i,s){await r(e(i),o=>Dr.promises.writeFile(o,s,"utf-8"))},async delete(i){await Dr.promises.rm(e(i),{force:!0})},async readBinary(i){return new Uint8Array(await Dr.promises.readFile(e(i)))},async writeBinary(i,s){let o=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);await r(e(i),c=>Dr.promises.writeFile(c,Buffer.from(o)))}}}a(cse,"nodeLocalFilesPort");function lse(n){return{async read(){try{return await Dr.promises.readFile(n,"utf-8")}catch{return null}},async writeAtomic(e){await Dr.promises.mkdir(xn.dirname(n),{recursive:!0});let t=`${n}.local.tmp`;await Dr.promises.writeFile(t,e,"utf-8"),await Dr.promises.rename(t,n)}}}a(lse,"nodeWatermarkFileIO");function use(n){return{async check(e){let t=xn.join(n,e.localPath);if(!(0,Dr.existsSync)(t))return{fullyMaterialized:!1,reason:`mount folder ${e.localPath} does not exist`};let r=0;try{r=(await Dr.promises.readdir(t)).length}catch{return{fullyMaterialized:!1,reason:`mount folder ${e.localPath} is not readable`}}return r===0&&e.spaceKind!=="file"?{fullyMaterialized:!1,reason:`mount folder ${e.localPath} is empty (mid-mount?)`}:{fullyMaterialized:!0}}}}a(use,"nodeMaterializationCheck");function fse(n,e){let t=n.pushedSha!==void 0?` \u2192@${n.pushedSha.slice(0,7)}`:"";e(`${n.repoKey}${t}: ${n.status} \u2014 pulled ${n.pulledCount}, pushed ${n.pushedCount}, merged ${n.mergedCount}, quarantined ${n.quarantinedCount}${(n.pushedDeletes?.length??0)>0?`, deleted ${n.pushedDeletes.length}`:""}`),n.detail!==void 0&&e(` ${n.detail}`);for(let r of n.warnings)e(` warn: ${r}`);(n.deferredPaths?.length??0)>0&&e(` deferred (\u2192 full sync): ${n.deferredPaths.join(", ")}`),(n.deferredDeletes?.length??0)>0&&e(` deferred deletes: ${n.deferredDeletes.join(", ")}`)}a(fse,"printRepoResult");function dse(n){return n==="conflict"||n==="full-conflict"||n==="retry-exhausted"||n==="busy"||n==="auth-required"||n==="error"}a(dse,"isFailureStatus");async function pse(n,e,t={}){let r=t.out??(b=>console.log(b)),i=xn.resolve(e.vault);if(!(0,Dr.existsSync)(i))throw new Error(`Vault path does not exist: ${i}`);let s=ose(e,t),o=new Ei({token:s,...e.apiBase!==void 0?{apiBase:e.apiBase}:{}}),c=t.transportFactory?.(s,e.apiBase)??o.transport(),{specs:l,warnings:u}=vA(i);for(let b of u)r(`warn: ${b}`);if(l.length===0)return r("Nothing to sync \u2014 no materialized AssetSpaces with a GitHub source found in this vault."),2;let f=e.configDir??".obsidian",d=xn.join(i,f,"plugins","exocortex",Fr.WATERMARK_STORE_FILENAME),p,h=e.quarantineRepo?.trim()??"";if(h.length>0){let{owner:b,repo:S}=ase(h);p=new Fr.SyncedQuarantineStore({transport:(0,Fr.withRateLimitBackoff)(c),sha1:Nj,owner:b,repo:S,branch:Fr.SYNC_BRANCH,redact:a(T=>o.redact(T),"redact")})}let y=new Fr.SyncEngine({transport:c,watermarkStore:new Fr.FileWatermarkStore(lse(d)),materializationCheck:use(i),localFilesFor:a(b=>cse(xn.join(i,b.localPath)),"localFilesFor"),sha1:Nj,redact:a(b=>o.redact(b),"redact"),commitMessage:a((b,S,T=0)=>`exosync: ${S} change(s)${T>0?`, ${T} deletion(s)`:""} (CLI)`,"commitMessage"),mergeLayer:new Fr.GatedStructuredMerger(new Fr.StructuredMerger(sse)),...p!==void 0?{quarantine:p}:{},...e.apiBase!==void 0?{baseURL:e.apiBase}:{}});r(`ExoSync ${n}: ${l.length} repo(s), vault ${i}${p!==void 0?" (quarantine configured)":""}`);let g=(0,Fr.orderChildrenFirst)(l),v=await y.syncAll(g,n);if(e.json===!0)r(JSON.stringify(v,null,2));else{for(let S of v)fse(S,r);let b=v.reduce((S,T)=>({pulled:S.pulled+T.pulledCount,pushed:S.pushed+T.pushedCount,merged:S.merged+T.mergedCount,quarantined:S.quarantined+T.quarantinedCount}),{pulled:0,pushed:0,merged:0,quarantined:0});r(`Summary: ${v.length} repo(s) \u2014 pulled ${b.pulled}, pushed ${b.pushed}, merged ${b.merged}, quarantined ${b.quarantined}`)}return v.some(b=>dse(b.status))?1:0}a(pse,"runExosyncSync");function EA(n){return n.requiredOption("--vault <path>","Vault root path").option("--config-dir <name>","Obsidian config dir name (watermark location)",".obsidian").option("--quarantine-repo <url>","Quarantine repo URL (https://github.com/<owner>/<repo>) \u2014 required for FileSpaces").option("--token <pat>","GitHub PAT (or env GITHUB_TOKEN / GH_TOKEN). Prefer --token-from-gh.").option("--token-from-gh","Resolve the PAT via `gh auth token`").option("--json","Print the full per-repo result array as JSON").option("--api-base <url>","GitHub API base (testing)")}a(EA,"withSyncOptions");function TA(n){return async e=>{try{process.exitCode=await pse(n,e)}catch(t){le.handle(t,{command:`exosync ${n}`}),process.exitCode=1}}}a(TA,"makeDirectionAction");function Mj(){let n=new Ae("exosync").description("ExoSync over the GitHub REST API: sync/pull/push the materialized AssetSpace set (CLI parity with the plugin; RFC 4e4dc453 Phase B). Read-only divergence check: `exosync-parity`.");return EA(n.command("sync").description("Full pull\u2192merge\u2192push cycle for every materialized repo")).action(TA("sync")),EA(n.command("pull").description("Apply remote changes only (nothing leaves the device; local changes re-derive)")).action(TA("pull")),EA(n.command("push").description("Send the local delta only (remote changes are pinned to re-derive on the next pull/sync)")).action(TA("push")),n}a(Mj,"exosyncCommand");function jj(n){let e=new Ae;return e.name("exocortex").description("CLI tool for Exocortex knowledge management system").version(n??"16.96.1"),e.addCommand(VM()),e.addCommand(JM()),e.addCommand(Lk()),e.addCommand(Mk()),e.addCommand(dM()),e.addCommand(Bk()),e.addCommand(Vk()),e.addCommand(Hk()),e.addCommand(mM()),e.addCommand(TM()),e.addCommand(IM()),e.addCommand(OM()),e.addCommand(BM()),e.addCommand(pj()),e.addCommand(_j()),e.addCommand(Sj()),e.addCommand(Ej()),e.addCommand(xj()),e.addCommand(Dj()),e.addCommand(Lj()),e.addCommand(Mj()),e}a(jj,"createProgram");jj().parse();0&&(module.exports={createProgram});
|
|
778
|
+
`)),process.exit(0)}catch(e){let t=e instanceof Error?e:new Error(String(e)),r=new Ei;t.message=r.redact(t.message),t.stack&&(t.stack=r.redact(t.stack)),le.handle(t)}})}a(Jie,"restPushCommand");var $o=require("node:fs"),Fj=require("node:crypto"),Ti=J(require("node:path"));var Ai=J(rt());var Zie=a(async n=>{let e=await Fj.webcrypto.subtle.digest("SHA-1",n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength));return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")},"nodeSha1"),ese={parse:a(n=>Nt.load(n,{schema:Nt.CORE_SCHEMA}),"parse"),stringify:a(n=>Nt.dump(n,{schema:Nt.CORE_SCHEMA,lineWidth:-1}),"stringify")};function tse(n,e){if(n.tokenFromGh===!0)return Ei.resolveGhToken(e.ghTokenRunner);let t=e.env??process.env,r=n.token||t.GITHUB_TOKEN||t.GH_TOKEN||"";if(r.length===0)throw new Error("A GitHub token is required (private sync units read as 404 without one). Use --token-from-gh, --token <pat>, or set GITHUB_TOKEN / GH_TOKEN.");return r}a(tse,"resolveToken");function rse(n){let e=a(r=>Ti.join(n,r),"abs"),t=a(async(r,i)=>{let s;try{s=await $o.promises.readdir(r,{withFileTypes:!0})}catch{return}for(let o of s){let c=Ti.join(r,o.name);if(o.isDirectory()){if(o.name===".git")continue;await t(c,i)}else o.isFile()&&i.push(Ti.relative(n,c).split(Ti.sep).join("/"))}},"walk");return{async list(){let r=[];return(0,$o.existsSync)(n)&&await t(n,r),r},read:a(r=>$o.promises.readFile(e(r),"utf-8"),"read"),async readBinary(r){return new Uint8Array(await $o.promises.readFile(e(r)))},async write(){throw new Error("exosync-parity is read-only \u2014 write refused")},async delete(){throw new Error("exosync-parity is read-only \u2014 delete refused")}}}a(rse,"nodeLocalFilesPort");function vA(n){let e=new pt(n),t=new Ai.SpaceSpecAccumulator;for(let r of e.getAllFiles()){let i=e.getFrontmatter(r);if(!i)continue;let s=(0,Ai.classifySpaceDeclaration)(i,r.path);if(s.kind==="not-space"||(s.warning!==void 0&&t.warnings.push(s.warning),s.kind==="skip"))continue;let o=t.offer(s.candidate);o!==null&&(0,$o.existsSync)(Ti.join(n,o.localPath))&&t.commit(s.candidate)}return{specs:t.specs,warnings:t.warnings}}a(vA,"collectVaultSpecs");function nse(n,e){for(let t of n.repos){let r=t.headSha!==void 0?` @${t.headSha.slice(0,7)}`:"";e(`${t.repoKey}${r}: ${t.status} \u2014 ${t.inParity}/${t.filesChecked} in parity, M2 diffs ${t.m2SemanticDiffs}, accounted ${t.accountedCount}, M1 violations ${t.m1Violations.length}${t.attachmentHashSetIdentical!==void 0?`, attachment hash-set ${t.attachmentHashSetIdentical?"identical":"DIFFERS"}`:""}`),t.detail!==void 0&&e(` ${t.detail}`);for(let i of t.warnings)e(` warn: ${i}`);for(let i of t.discrepancies)e(` ${i.cls}: ${i.path}${i.detail!==void 0?` (${i.detail})`:""}`);for(let i of t.m1Violations)e(` M1 VIOLATION: ${i.path} \u2014 ${i.detail}`)}e((0,Ai.summarizeParityRound)(n))}a(nse,"printHumanReport");async function ise(n,e={}){let t=e.out??(y=>console.log(y)),r=Ti.resolve(n.vault);if(!(0,$o.existsSync)(r))throw new Error(`Vault path does not exist: ${r}`);let i=tse(n,e),s=new Ei({token:i,...n.apiBase!==void 0?{apiBase:n.apiBase}:{}}),o=e.transportFactory?.(i,n.apiBase)??s.transport(),{specs:c,warnings:l}=vA(r);for(let y of l)t(`warn: ${y}`);if(c.length===0)return t("Nothing to check \u2014 no materialized AssetSpaces with a GitHub source found in this vault."),2;let u=n.configDir??".obsidian",f=Ti.join(r,u,"plugins","exocortex",Ai.WATERMARK_STORE_FILENAME),d=new Ai.FileWatermarkStore({read:a(async()=>{try{return await $o.promises.readFile(f,"utf-8")}catch{return null}},"read"),writeAtomic:a(async()=>{throw new Error("exosync-parity: watermark access is read-only by contract")},"writeAtomic")}),p=new Ai.ParityValidator({transport:o,sha1:Zie,localFilesFor:a(y=>rse(Ti.join(r,y.localPath)),"localFilesFor"),watermarks:{get:a(y=>d.get(y),"get")},yaml:ese,redact:a(y=>s.redact(y),"redact"),...n.apiBase!==void 0?{baseURL:n.apiBase}:{}});t(`ExoSync parity check: ${c.length} repo(s), vault ${r}`);let h=await p.runRound(c,{trigger:"standalone"});return n.json===!0?t(JSON.stringify(h,null,2)):nse(h,t),h.vacuous?2:h.ok?0:1}a(ise,"runExosyncParity");function Lj(){return new Ae("exosync-parity").description("ExoSync M1/M2 parity report: compare materialized sync units against their remote heads (read-only; RFC 4e4dc453 Phase E)").requiredOption("--vault <path>","Vault root path").option("--config-dir <name>","Obsidian config dir name (watermark location)",".obsidian").option("--json","Print the full round record as JSON").option("--token <pat>","GitHub PAT (or env GITHUB_TOKEN / GH_TOKEN). Prefer --token-from-gh.").option("--token-from-gh","Resolve the PAT via `gh auth token`").option("--api-base <url>","GitHub API base (testing)").action(async n=>{try{process.exitCode=await ise(n)}catch(e){le.handle(e,{command:"exosync-parity"}),process.exitCode=1}})}a(Lj,"exosyncParityCommand");var Dr=require("node:fs"),kj=require("node:crypto"),xn=J(require("node:path"));var Fr=J(rt());var Nj=a(async n=>{let e=await kj.webcrypto.subtle.digest("SHA-1",n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength));return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")},"nodeSha1"),sse={parse:a(n=>Nt.load(n,{schema:Nt.CORE_SCHEMA}),"parse"),stringify:a(n=>Nt.dump(n,{schema:Nt.CORE_SCHEMA,lineWidth:-1}),"stringify")};function ose(n,e){if(n.tokenFromGh===!0)return Ei.resolveGhToken(e.ghTokenRunner);let t=e.env??process.env,r=n.token||t.GITHUB_TOKEN||t.GH_TOKEN||"";if(r.length===0)throw new Error("A GitHub token is required (private sync units read as 404 and push needs write scope). Use --token-from-gh, --token <pat>, or set GITHUB_TOKEN / GH_TOKEN.");return r}a(ose,"resolveToken");function ase(n){let e=/^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(n.trim());if(e===null)throw new Error(`Invalid quarantine repo URL (expected https://github.com/<owner>/<repo>): ${n}`);return{owner:e[1],repo:e[2]}}a(ase,"parseGitHubRepoUrl");function cse(n){let e=a(i=>xn.join(n,i),"abs"),t=a(async(i,s)=>{let o;try{o=await Dr.promises.readdir(i,{withFileTypes:!0})}catch{return}for(let c of o){let l=xn.join(i,c.name);if(c.isDirectory()){if(c.name===".git")continue;await t(l,s)}else c.isFile()&&s.push(xn.relative(n,l).split(xn.sep).join("/"))}},"walk"),r=a(async(i,s)=>{let o=xn.dirname(i);await Dr.promises.mkdir(o,{recursive:!0});let c=`${i}.local.tmp`;await s(c),await Dr.promises.rename(c,i)},"writeAtomic");return{async list(){let i=[];return(0,Dr.existsSync)(n)&&await t(n,i),i},read:a(i=>Dr.promises.readFile(e(i),"utf-8"),"read"),async write(i,s){await r(e(i),o=>Dr.promises.writeFile(o,s,"utf-8"))},async delete(i){await Dr.promises.rm(e(i),{force:!0})},async readBinary(i){return new Uint8Array(await Dr.promises.readFile(e(i)))},async writeBinary(i,s){let o=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);await r(e(i),c=>Dr.promises.writeFile(c,Buffer.from(o)))}}}a(cse,"nodeLocalFilesPort");function lse(n){return{async read(){try{return await Dr.promises.readFile(n,"utf-8")}catch{return null}},async writeAtomic(e){await Dr.promises.mkdir(xn.dirname(n),{recursive:!0});let t=`${n}.local.tmp`;await Dr.promises.writeFile(t,e,"utf-8"),await Dr.promises.rename(t,n)}}}a(lse,"nodeWatermarkFileIO");function use(n){return{async check(e){let t=xn.join(n,e.localPath);if(!(0,Dr.existsSync)(t))return{fullyMaterialized:!1,reason:`mount folder ${e.localPath} does not exist`};let r=0;try{r=(await Dr.promises.readdir(t)).length}catch{return{fullyMaterialized:!1,reason:`mount folder ${e.localPath} is not readable`}}return r===0&&e.spaceKind!=="file"?{fullyMaterialized:!1,reason:`mount folder ${e.localPath} is empty (mid-mount?)`}:{fullyMaterialized:!0}}}}a(use,"nodeMaterializationCheck");function fse(n,e){let t=n.pushedSha!==void 0?` \u2192@${n.pushedSha.slice(0,7)}`:"";e(`${n.repoKey}${t}: ${n.status} \u2014 pulled ${n.pulledCount}, pushed ${n.pushedCount}, merged ${n.mergedCount}, quarantined ${n.quarantinedCount}${(n.pushedDeletes?.length??0)>0?`, deleted ${n.pushedDeletes.length}`:""}`),n.detail!==void 0&&e(` ${n.detail}`);for(let r of n.warnings)e(` warn: ${r}`);(n.deferredPaths?.length??0)>0&&e(` deferred (\u2192 full sync): ${n.deferredPaths.join(", ")}`),(n.deferredDeletes?.length??0)>0&&e(` deferred deletes: ${n.deferredDeletes.join(", ")}`)}a(fse,"printRepoResult");function dse(n){return n==="conflict"||n==="full-conflict"||n==="retry-exhausted"||n==="busy"||n==="auth-required"||n==="error"}a(dse,"isFailureStatus");async function pse(n,e,t={}){let r=t.out??(b=>console.log(b)),i=xn.resolve(e.vault);if(!(0,Dr.existsSync)(i))throw new Error(`Vault path does not exist: ${i}`);let s=ose(e,t),o=new Ei({token:s,...e.apiBase!==void 0?{apiBase:e.apiBase}:{}}),c=t.transportFactory?.(s,e.apiBase)??o.transport(),{specs:l,warnings:u}=vA(i);for(let b of u)r(`warn: ${b}`);if(l.length===0)return r("Nothing to sync \u2014 no materialized AssetSpaces with a GitHub source found in this vault."),2;let f=e.configDir??".obsidian",d=xn.join(i,f,"plugins","exocortex",Fr.WATERMARK_STORE_FILENAME),p,h=e.quarantineRepo?.trim()??"";if(h.length>0){let{owner:b,repo:S}=ase(h);p=new Fr.SyncedQuarantineStore({transport:(0,Fr.withRateLimitBackoff)(c),sha1:Nj,owner:b,repo:S,branch:Fr.SYNC_BRANCH,redact:a(T=>o.redact(T),"redact")})}let y=new Fr.SyncEngine({transport:c,watermarkStore:new Fr.FileWatermarkStore(lse(d)),materializationCheck:use(i),localFilesFor:a(b=>cse(xn.join(i,b.localPath)),"localFilesFor"),sha1:Nj,redact:a(b=>o.redact(b),"redact"),commitMessage:a((b,S,T=0)=>`exosync: ${S} change(s)${T>0?`, ${T} deletion(s)`:""} (CLI)`,"commitMessage"),mergeLayer:new Fr.GatedStructuredMerger(new Fr.StructuredMerger(sse)),...p!==void 0?{quarantine:p}:{},...e.apiBase!==void 0?{baseURL:e.apiBase}:{}});r(`ExoSync ${n}: ${l.length} repo(s), vault ${i}${p!==void 0?" (quarantine configured)":""}`);let g=(0,Fr.orderChildrenFirst)(l),v=await y.syncAll(g,n);if(e.json===!0)r(JSON.stringify(v,null,2));else{for(let S of v)fse(S,r);let b=v.reduce((S,T)=>({pulled:S.pulled+T.pulledCount,pushed:S.pushed+T.pushedCount,merged:S.merged+T.mergedCount,quarantined:S.quarantined+T.quarantinedCount}),{pulled:0,pushed:0,merged:0,quarantined:0});r(`Summary: ${v.length} repo(s) \u2014 pulled ${b.pulled}, pushed ${b.pushed}, merged ${b.merged}, quarantined ${b.quarantined}`)}return v.some(b=>dse(b.status))?1:0}a(pse,"runExosyncSync");function EA(n){return n.requiredOption("--vault <path>","Vault root path").option("--config-dir <name>","Obsidian config dir name (watermark location)",".obsidian").option("--quarantine-repo <url>","Quarantine repo URL (https://github.com/<owner>/<repo>) \u2014 required for FileSpaces").option("--token <pat>","GitHub PAT (or env GITHUB_TOKEN / GH_TOKEN). Prefer --token-from-gh.").option("--token-from-gh","Resolve the PAT via `gh auth token`").option("--json","Print the full per-repo result array as JSON").option("--api-base <url>","GitHub API base (testing)")}a(EA,"withSyncOptions");function TA(n){return async e=>{try{process.exitCode=await pse(n,e)}catch(t){le.handle(t,{command:`exosync ${n}`}),process.exitCode=1}}}a(TA,"makeDirectionAction");function Mj(){let n=new Ae("exosync").description("ExoSync over the GitHub REST API: sync/pull/push the materialized AssetSpace set (CLI parity with the plugin; RFC 4e4dc453 Phase B). Read-only divergence check: `exosync-parity`.");return EA(n.command("sync").description("Full pull\u2192merge\u2192push cycle for every materialized repo")).action(TA("sync")),EA(n.command("pull").description("Apply remote changes only (nothing leaves the device; local changes re-derive)")).action(TA("pull")),EA(n.command("push").description("Send the local delta only (remote changes are pinned to re-derive on the next pull/sync)")).action(TA("push")),n}a(Mj,"exosyncCommand");function jj(n){let e=new Ae;return e.name("exocortex").description("CLI tool for Exocortex knowledge management system").version(n??"16.96.2"),e.addCommand(VM()),e.addCommand(JM()),e.addCommand(Lk()),e.addCommand(Mk()),e.addCommand(dM()),e.addCommand(Bk()),e.addCommand(Vk()),e.addCommand(Hk()),e.addCommand(mM()),e.addCommand(TM()),e.addCommand(IM()),e.addCommand(OM()),e.addCommand(BM()),e.addCommand(pj()),e.addCommand(_j()),e.addCommand(Sj()),e.addCommand(Ej()),e.addCommand(xj()),e.addCommand(Dj()),e.addCommand(Lj()),e.addCommand(Mj()),e}a(jj,"createProgram");jj().parse();0&&(module.exports={createProgram});
|
|
779
779
|
/*! Bundled license information:
|
|
780
780
|
|
|
781
781
|
reflect-metadata/Reflect.js:
|