@kitelev/exocortex-cli 16.20.1 → 16.20.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.
Files changed (2) hide show
  1. package/dist/index.js +3 -3
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // @kitelev/exocortex-cli v16.20.1
2
+ // @kitelev/exocortex-cli v16.20.2
3
3
  // CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
4
4
  // License: MIT
5
5
 
@@ -368,7 +368,7 @@ LIMIT ${this.config.defaultLimit}`,s="\u041D\u0435 \u0443\u0434\u0430\u043B\u043
368
368
  `,i=this.composePrefixes(t),s=this.serializePrefixes(i,r),a=this.nTriplesSerializer.serialize(e,{newline:r}).trimEnd();return s?a?`${s}${r}${r}${a}${r}`:`${s}${r}`:a?`${a}${r}`:""}serializePrefixes(e,t){let r=Object.entries(e);return r.length===0?"":r.map(([i,s])=>`@prefix ${i}: <${s}> .`).join(t)}composePrefixes(e){return e.includeDefaultPrefixes??!0?{...g8,...e.prefixes??{}}:{...e.prefixes??{}}}serializeTriplesOnly(e,t){return this.nTriplesSerializer.serializeChunk(e,t).trimEnd()}};Mp.TurtleSerializer=rS});var ox=b($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});$p.JSONLDSerializer=void 0;var sx=Ee(),ax=$t(),y8=Me(),Zc=ir(),_8={rdf:Zc.Namespace.RDF.iri.value,rdfs:Zc.Namespace.RDFS.iri.value,owl:Zc.Namespace.OWL.iri.value,xsd:Zc.Namespace.XSD.iri.value,exo:Zc.Namespace.EXO.iri.value,ems:Zc.Namespace.EMS.iri.value},nS=class{static{o(this,"JSONLDSerializer")}toDocument(e,t={}){let r={..._8,...t.context??{}},i=new Map;for(let s of e){let a=this.subjectToId(s.subject),c=this.compactIri(s.predicate.value,r),l=this.objectToJSONLD(s.object,r),u=i.get(a)??{"@id":a},f=u[c];f===void 0?u[c]=l:Array.isArray(f)?f.push(l):u[c]=[f,l],i.set(a,u)}return{"@context":r,"@graph":Array.from(i.values())}}serialize(e,t={}){let r=this.toDocument(e,t),i=t.pretty?t.indent??2:void 0;return JSON.stringify(r,null,i)}subjectToId(e){return e instanceof sx.IRI?e.value:e instanceof ax.BlankNode?`_:${e.id}`:String(e)}compactIri(e,t){for(let[r,i]of Object.entries(t))if(e.startsWith(i)){let s=e.slice(i.length);if(s.length>0)return`${r}:${s}`}return e}objectToJSONLD(e,t){if(e instanceof sx.IRI)return{"@id":e.value};if(e instanceof ax.BlankNode)return{"@id":`_:${e.id}`};if(e instanceof y8.Literal){let r={"@value":e.value};return e.datatype?r["@type"]=this.compactIri(e.datatype.value,t):e.language&&(r["@language"]=e.language,e.hasDirection()&&e.direction&&(r["@direction"]=e.direction)),r}return e}};$p.JSONLDSerializer=nS});var aS=b(Vp=>{"use strict";Object.defineProperty(Vp,"__esModule",{value:!0});Vp.NTriplesParser=void 0;var b8=Yn(),cx=Ee(),iS=Me(),S8=$t(),el=ir(),w8={rdf:el.Namespace.RDF.iri.value,rdfs:el.Namespace.RDFS.iri.value,owl:el.Namespace.OWL.iri.value,xsd:el.Namespace.XSD.iri.value,exo:el.Namespace.EXO.iri.value,ems:el.Namespace.EMS.iri.value},sS=class{static{o(this,"NTriplesParser")}parse(e,t={}){let r={prefixes:{...w8,...t.prefixes??{}},strict:t.strict??!1},i=[];return e.split(/\r?\n/).forEach((a,c)=>{let l=a.trim();!l||l.startsWith("#")||i.push(this.parseLine(l,c+1,r))}),i}parseLine(e,t,r){if(!e.endsWith("."))throw new Error(`Invalid RDF statement at line ${t}: missing '.' terminator`);let s=e.slice(0,-1).trim(),a=this.parseSubject(s,t,r);s=a.rest.trim();let c=this.parsePredicate(s,t,r);s=c.rest.trim();let l=this.parseObject(s,t,r);if(s=l.rest.trim(),s.length>0)throw new Error(`Unexpected tokens after object at line ${t}`);return new b8.Triple(a.node,c.node,l.node)}parseSubject(e,t,r){return e.startsWith("<")?this.consumeIRI(e,t,r):e.startsWith("_:")?this.consumeBlankNode(e,t):this.consumePrefixedName(e,t,r)}parsePredicate(e,t,r){return e.startsWith("<")?this.consumeIRI(e,t,r):this.consumePrefixedName(e,t,r)}parseObject(e,t,r){return e.startsWith("<")?this.consumeIRI(e,t,r):e.startsWith("_:")?this.consumeBlankNode(e,t):e.startsWith('"')?this.consumeLiteral(e,t,r):this.consumePrefixedName(e,t,r)}consumePrefixedName(e,t,r){let i=e.match(/^([a-zA-Z_][\w-]*):([^\s]+)(?:\s+(.*))?$/);if(!i)throw new Error(`Invalid token at line ${t}: ${e}`);let[,s,a,c]=i,l=r.prefixes[s];if(!l)throw new Error(`Unknown prefix "${s}" at line ${t}`);return{node:new cx.IRI(`${l}${a}`),rest:(c??"").trimStart()}}consumeIRI(e,t,r){let i=this.findClosingBracket(e,"<",">");if(i===-1)throw new Error(`Invalid IRI at line ${t}`);let s=e.slice(1,i),a=new cx.IRI(s),c=e.slice(i+1).trimStart();return{node:a,rest:c}}consumeBlankNode(e,t){let r=e.match(/^_:(\w+)(?:\s+(.*))?$/);if(!r)throw new Error(`Invalid blank node identifier at line ${t}`);let[,i,s]=r;return{node:new S8.BlankNode(i),rest:(s??"").trimStart()}}consumeLiteral(e,t,r){let{value:i,rest:s}=this.consumeQuotedString(e,t),a=s.trimStart();if(a.startsWith("^^")){a=a.slice(2).trimStart();let c=a.startsWith("<")?this.consumeIRI(a,t,r):this.consumePrefixedName(a,t,r);return{node:new iS.Literal(i,c.node),rest:c.rest}}if(a.startsWith("@")){let c=a.match(/^@([a-zA-Z-]+)(?:\s+(.*))?$/);if(!c)throw new Error(`Invalid language tag at line ${t}`);let[,l,u]=c;return{node:new iS.Literal(i,void 0,l),rest:(u??"").trimStart()}}return{node:new iS.Literal(i),rest:a}}consumeQuotedString(e,t){if(!e.startsWith('"'))throw new Error(`Expected quoted string at line ${t}`);let r="";for(let i=1;i<e.length;i++){let s=e[i];if(s==="\\"){if(i+1>=e.length)throw new Error(`Invalid escape sequence at line ${t}`);let a=e[i+1];switch(a){case"t":r+=" ",i+=1;break;case"b":r+="\b",i+=1;break;case"n":r+=`
369
369
  `,i+=1;break;case"r":r+="\r",i+=1;break;case"f":r+="\f",i+=1;break;case'"':r+='"',i+=1;break;case"\\":r+="\\",i+=1;break;case"u":{let c=e.slice(i+2,i+6);if(c.length!==4||!/^[0-9a-fA-F]{4}$/.test(c))throw new Error(`Invalid \\u escape at line ${t}`);r+=String.fromCharCode(parseInt(c,16)),i+=5;break}case"U":{let c=e.slice(i+2,i+10);if(c.length!==8||!/^[0-9a-fA-F]{8}$/.test(c))throw new Error(`Invalid \\U escape at line ${t}`);r+=String.fromCodePoint(parseInt(c,16)),i+=9;break}default:throw new Error(`Unknown escape sequence \\${a} at line ${t}`)}continue}if(s==='"'){let a=e.slice(i+1);return{value:r,rest:a}}r+=s}throw new Error(`Unterminated string literal at line ${t}`)}findClosingBracket(e,t,r){let i=0;for(let s=0;s<e.length;s++){let a=e[s];if(a===t){i++;continue}if(a===r&&(i--,i===0))return s}return-1}};Vp.NTriplesParser=sS});var lx=b(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});Bp.TurtleParser=void 0;var tl=ir(),v8=aS(),E8={rdf:tl.Namespace.RDF.iri.value,rdfs:tl.Namespace.RDFS.iri.value,owl:tl.Namespace.OWL.iri.value,xsd:tl.Namespace.XSD.iri.value,exo:tl.Namespace.EXO.iri.value,ems:tl.Namespace.EMS.iri.value},T8=/^@prefix\s+([a-zA-Z_][\w-]*):\s*<([^>]+)>\s*\.$/,oS=class{static{o(this,"TurtleParser")}constructor(){this.nTriplesParser=new v8.NTriplesParser}parse(e,t={}){let r={...E8,...t.prefixes??{}},i=this.collectStatements(e),s=[];return i.forEach(({statement:a,lineNumber:c})=>{if(this.isPrefixStatement(a)){let u=a.match(T8);if(!u)throw new Error(`Invalid prefix declaration at line ${c}`);let[,f,d]=u;r[f]=d;return}if(a.includes(";")||a.includes(","))throw new Error(`Complex Turtle statements with ';' or ',' are not supported (line ${c})`);let l=this.normalizeShortcuts(a);s.push(this.nTriplesParser.parseLine(l,c,{prefixes:r,strict:!1}))}),s}collectStatements(e){let t=e.split(/\r?\n/),r=[],i="",s=0;if(t.forEach((a,c)=>{let l=a.trim();!l||l.startsWith("#")||(i||(s=c+1),i=i?`${i} ${l}`:l,l.endsWith(".")&&(r.push({statement:i,lineNumber:s}),i=""))}),i)throw new Error(`Unterminated Turtle statement near line ${s}`);return r}isPrefixStatement(e){return e.startsWith("@prefix")}normalizeShortcuts(e){return e.includes(" a ")?e.replace(/\sa\s/g," rdf:type "):e}};Bp.TurtleParser=oS});var ux=b(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.RDFSerializer=void 0;var rl=Yn(),Lo=Ee(),ko=Me(),cS=$t(),ds=ir(),A8=ix(),x8=tS(),I8=ox(),C8=lx(),R8=aS(),O8=1024,P8=`
370
370
  `,F8={rdf:ds.Namespace.RDF.iri.value,rdfs:ds.Namespace.RDFS.iri.value,owl:ds.Namespace.OWL.iri.value,xsd:ds.Namespace.XSD.iri.value,exo:ds.Namespace.EXO.iri.value,ems:ds.Namespace.EMS.iri.value},lS=class{static{o(this,"RDFSerializer")}constructor(e){this.store=e,this.turtleSerializer=new A8.TurtleSerializer,this.nTriplesSerializer=new x8.NTriplesSerializer,this.jsonldSerializer=new I8.JSONLDSerializer,this.turtleParser=new C8.TurtleParser,this.nTriplesParser=new R8.NTriplesParser}async serialize(e,t={}){let r=await this.store.match();return this.serializeTriples(r,e,t)}serializeTriples(e,t,r={}){switch(t){case"turtle":return this.turtleSerializer.serialize(e,{prefixes:r.prefixes,includeDefaultPrefixes:r.includeDefaultPrefixes,newline:r.newline});case"n-triples":return this.nTriplesSerializer.serialize(e,{newline:r.newline});case"json-ld":return this.jsonldSerializer.serialize(e,{context:r.prefixes,pretty:r.pretty,indent:r.indent});default:throw new Error(`Unsupported serialization format: ${t}`)}}stream(e,t={}){let r=t.newline??P8,i=t.batchSize??O8,s=t.includeDefaultPrefixes,a=t.prefixes,c=this,l=!1,u=[],f=[],d=0,h=o(async()=>{if(!l){if(f=await c.store.match(),e==="json-ld"){let y=c.jsonldSerializer.toDocument(f,{context:a,pretty:!1});u.push(...c.buildJsonLdChunks(y))}else if(e==="turtle"){let y=c.turtleSerializer.serializePrefixes(c.composePrefixes(a,s),r);y&&u.push(`${y}${r}${r}`)}l=!0}},"ensureInitialized");return{async next(){if(await h(),u.length>0)return{value:u.shift(),done:!1};if(e==="json-ld")return{value:void 0,done:!0};if(d>=f.length)return{value:void 0,done:!0};let y=f.slice(d,d+i);d+=y.length;let S="";if(e==="turtle"){let v=c.turtleSerializer.serializeTriplesOnly(y,r);v&&(S=`${v}${r}`)}else e==="n-triples"&&(S=c.nTriplesSerializer.serializeChunk(y,r));return S?{value:S,done:!1}:this.next()},async return(){return u=[],f=[],d=0,{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}async load(e,t,r={}){let i=this.parse(e,t,r);return r.mode!=="append"&&await this.store.clear(),await this.store.addAll(i),i.length}parse(e,t,r={}){switch(t){case"turtle":return this.turtleParser.parse(e,this.buildTurtleParseOptions(r));case"n-triples":return this.nTriplesParser.parse(e,this.buildNTriplesParseOptions(r));case"json-ld":return this.parseJsonLd(e,r);default:throw new Error(`Unsupported serialization format: ${t}`)}}buildTurtleParseOptions(e){return{prefixes:this.composePrefixes(e.prefixes,!0),strict:e.strict}}buildNTriplesParseOptions(e){return{prefixes:this.composePrefixes(e.prefixes,!0),strict:e.strict}}composePrefixes(e,t){return t??!0?{...F8,...e??{}}:{...e??{}}}parseJsonLd(e,t){let r;try{r=JSON.parse(e)}catch(u){throw new Error(`Invalid JSON-LD document: ${u.message}`)}let i=this.composePrefixes(t.prefixes,!0),s=this.extractContext(r),a={...i,...s},c=this.extractGraph(r),l=[];return c.forEach((u,f)=>{if(!u||typeof u!="object"||Array.isArray(u))throw new Error(`Invalid JSON-LD node at index ${f}`);let d=this.parseSubjectFromNode(u,a,f),h=Object.entries(u);for(let[p,y]of h){if(p==="@id"||p==="@context")continue;if(p==="@type"){this.collectTypeTriples(d,y,l,a);continue}let S=this.expandTerm(p,a),v=new Lo.IRI(S);this.collectTriplesForValue(d,v,y,l,a)}}),l}extractContext(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e["@context"];if(!t||typeof t!="object"||Array.isArray(t))return{};let r={};return Object.entries(t).forEach(([i,s])=>{typeof s=="string"&&(r[i]=s)}),r}extractGraph(e){if(Array.isArray(e))return e;if(!e||typeof e!="object")return[];let t=e["@graph"];return Array.isArray(t)?t:[e]}parseSubjectFromNode(e,t,r){let i=e["@id"];if(typeof i=="string"){if(i.startsWith("_:"))return new cS.BlankNode(i.slice(2));if(this.isAbsoluteIri(i))return new Lo.IRI(i);let s=this.expandTerm(i,t);return new Lo.IRI(s)}return new cS.BlankNode(`jsonld_${r}`)}collectTypeTriples(e,t,r,i){let s=ds.Namespace.RDF.term("type");(Array.isArray(t)?t:[t]).forEach(c=>{if(typeof c!="string")throw new Error("Invalid @type value in JSON-LD node");let l=this.expandTerm(c,i);r.push(new rl.Triple(e,s,new Lo.IRI(l)))})}collectTriplesForValue(e,t,r,i,s){if(r!=null){if(Array.isArray(r)){r.forEach(a=>this.collectTriplesForValue(e,t,a,i,s));return}if(typeof r=="object"){let a=r;if(typeof a["@id"]=="string"){let c=this.parseIdNode(a["@id"],s);i.push(new rl.Triple(e,t,c));return}if(a["@value"]!==void 0){let c=this.parseLiteralObject(a,s);i.push(new rl.Triple(e,t,c));return}}if(typeof r=="string"){i.push(new rl.Triple(e,t,new ko.Literal(r)));return}if(typeof r=="number"){let a=Number.isInteger(r)?ds.Namespace.XSD.term("integer"):ds.Namespace.XSD.term("decimal");i.push(new rl.Triple(e,t,new ko.Literal(r.toString(),a)));return}if(typeof r=="boolean"){let a=ds.Namespace.XSD.term("boolean");i.push(new rl.Triple(e,t,new ko.Literal(r.toString(),a)));return}throw new Error("Unsupported JSON-LD value encountered")}}parseIdNode(e,t){if(e.startsWith("_:"))return new cS.BlankNode(e.slice(2));if(this.isAbsoluteIri(e))return new Lo.IRI(e);let r=this.expandTerm(e,t);return new Lo.IRI(r)}parseLiteralObject(e,t){let r=e["@value"];if(typeof r!="string")throw new Error("JSON-LD literal values must be strings");if(typeof e["@language"]=="string"){let i=e["@direction"];return i==="ltr"||i==="rtl"?new ko.Literal(r,void 0,e["@language"],i):new ko.Literal(r,void 0,e["@language"])}if(typeof e["@type"]=="string"){let i=this.expandTerm(e["@type"],t);return new ko.Literal(r,new Lo.IRI(i))}return new ko.Literal(r)}expandTerm(e,t){if(this.isAbsoluteIri(e))return e;let r=e.indexOf(":");if(r>0){let s=e.slice(0,r),a=e.slice(r+1),c=t[s];if(!c)throw new Error(`Unknown prefix "${s}" in JSON-LD document`);return`${c}${a}`}let i=t["@vocab"];if(i)return`${i}${e}`;throw new Error(`Unable to expand JSON-LD term "${e}"`)}isAbsoluteIri(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)}buildJsonLdChunks(e){let t=[],r=JSON.stringify(e["@context"]);return t.push(`{"@context":${r},"@graph":[`),e["@graph"].forEach((i,s)=>{let a=JSON.stringify(i);s>0?t.push(`,${a}`):t.push(a)}),t.push(`]}
371
- `),t}};Up.RDFSerializer=lS});var uS=b(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.OBSIDIAN_VAULT_SCHEME=void 0;nl.vaultPathToIRI=D8;nl.OBSIDIAN_VAULT_SCHEME="obsidian://vault/";function D8(n){let e=n.startsWith("./")?n.slice(2):n;return`${nl.OBSIDIAN_VAULT_SCHEME}${encodeURI(e)}`}o(D8,"vaultPathToIRI")});var dS=b(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});qp.RDFVocabularyMapper=void 0;var Xt=Yn(),fx=Ee(),J=ir(),fS=class{static{o(this,"RDFVocabularyMapper")}constructor(){this.propertyMappings=new Map([["exo__Instance_class",J.Namespace.RDF.term("type")],["exo__Asset_isDefinedBy",J.Namespace.RDFS.term("isDefinedBy")],["exo__Class_superClass",J.Namespace.RDFS.term("subClassOf")],["exo__Property_range",J.Namespace.RDFS.term("range")],["exo__Property_domain",J.Namespace.RDFS.term("domain")],["exo__Property_superProperty",J.Namespace.RDFS.term("subPropertyOf")]])}generateClassHierarchyTriples(){let e=[];return e.push(new Xt.Triple(J.Namespace.EXO.term("Asset"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.RDFS.term("Resource"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Class"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.RDFS.term("Class"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Property"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.RDF.term("Property"))),e.push(new Xt.Triple(J.Namespace.EMS.term("Task"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("Project"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("Area"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("Workflow"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("WorkflowState"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("WorkflowTransition"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EXOCMD.term("Command"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EXOCMD.term("Precondition"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EXOCMD.term("Grounding"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EXOCMD.term("CommandBinding"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e}generatePropertyHierarchyTriples(){let e=[];return e.push(new Xt.Triple(J.Namespace.EXO.term("Instance_class"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDF.term("type"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Asset_isDefinedBy"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("isDefinedBy"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Class_superClass"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("subClassOf"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Property_range"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("range"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Property_domain"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("domain"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Property_superProperty"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("subPropertyOf"))),e}generateMappedTriple(e,t,r){let i=this.propertyMappings.get(t);if(!i)return null;let s;if(r instanceof fx.IRI)s=r;else{let a=r.match(/^(ems|exo|exocmd)__(.+)$/);if(a){let[,c,l]=a;s=(c==="ems"?J.Namespace.EMS:c==="exocmd"?J.Namespace.EXOCMD:J.Namespace.EXO).term(l)}else s=new fx.IRI(r)}return new Xt.Triple(e,i,s)}hasMappingFor(e){return this.propertyMappings.has(e)}};qp.RDFVocabularyMapper=fS});var dx=b(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});Gp.RDFSInferenceEngine=void 0;var N8=Yn(),Wp=Ee(),hS=class{static{o(this,"RDFSInferenceEngine")}async materialize(e){let t=await e.predicates(),r=t.find(d=>d.value.includes("Class_superClass")),i=t.find(d=>d.value.includes("Instance_class"));if(!r||!i)return 0;let s=await this.buildDirectParentMap(e,r);if(s.size===0)return 0;let a=this.computeAllAncestors(s),c=await e.count(),l=await e.match(void 0,i),u=[];for(let d of l)if(d.object instanceof Wp.IRI){let h=a.get(d.object.value);if(h)for(let p of h)u.push(new N8.Triple(d.subject,i,new Wp.IRI(p)))}return u.length>0&&await e.addAll(u),await e.count()-c}async buildDirectParentMap(e,t){let r=await e.match(void 0,t),i=new Map;for(let s of r)if(s.subject instanceof Wp.IRI&&s.object instanceof Wp.IRI){let a=s.subject.value,c=s.object.value;i.has(a)||i.set(a,new Set),i.get(a).add(c)}return i}computeAllAncestors(e){let t=new Map;for(let r of e.keys())t.has(r)||t.set(r,this.computeAncestorsBFS(r,e));return t}computeAncestorsBFS(e,t){let r=new Set,i=new Set,s=[],a=t.get(e);if(a)for(let c of a)s.push(c);for(;s.length>0;){let c=s.shift();if(i.has(c))continue;i.add(c),r.add(c);let l=t.get(c);if(l)for(let u of l)i.has(u)||s.push(u)}return r}};Gp.RDFSInferenceEngine=hS});var gS=b(jo=>{"use strict";var L8=jo&&jo.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s};Object.defineProperty(jo,"__esModule",{value:!0});jo.NonInheritablePropertyRegistry=void 0;var k8=Ce(),hx=Ee(),px=Me(),pS=ir(),mS=class{static{o(this,"NonInheritablePropertyRegistry")}constructor(){this.nonInheritableIRIs=new Set,this.initialized=!1}async initialize(e){this.nonInheritableIRIs.clear();try{let t=await e.predicates(),r=t.find(c=>c.value.includes("Instance_class"));if(!r){this.initialized=!0;return}let i=await this.findNonInheritableClassIRI(e,t);if(!i){this.initialized=!0;return}let s=await e.match(void 0,r,i);if(s.length===0){this.initialized=!0;return}let a=t.find(c=>c.value.includes("Asset_label"));if(!a){this.initialized=!0;return}for(let c of s){let l=await e.match(c.subject,a,void 0);for(let u of l)if(u.object instanceof px.Literal){let f=u.object.value,d=this.propertyKeyToIRI(f);d&&this.nonInheritableIRIs.add(d)}}}catch{}this.initialized=!0}isNonInheritable(e){return this.nonInheritableIRIs.has(e)}get size(){return this.nonInheritableIRIs.size}get isInitialized(){return this.initialized}async findNonInheritableClassIRI(e,t){let r=t.find(a=>a.value.includes("Asset_label"));if(!r)return null;let i=await e.match(void 0,r,new px.Literal("exo__NonInheritableProperty"));if(i.length>0&&i[0].subject instanceof hx.IRI)return i[0].subject;let s=t.find(a=>a.value.includes("Instance_class"));if(s){let a=await e.match(void 0,s,void 0);for(let c of a)if(c.object instanceof hx.IRI&&c.object.value.includes("NonInheritableProperty"))return c.object}return null}propertyKeyToIRI(e){return e.startsWith("exo__")?pS.Namespace.EXO.term(e.substring(5)).value:e.startsWith("ems__")?pS.Namespace.EMS.term(e.substring(5)).value:e.startsWith("exocmd__")?pS.Namespace.EXOCMD.term(e.substring(8)).value:null}};jo.NonInheritablePropertyRegistry=mS;jo.NonInheritablePropertyRegistry=mS=L8([(0,k8.injectable)()],mS)});var bS=b(Mo=>{"use strict";var j8=Mo&&Mo.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s};Object.defineProperty(Mo,"__esModule",{value:!0});Mo.PropertyCardinalityRegistry=void 0;var M8=Ce(),mx=Ee(),gx=Me(),yS=ir(),_S=class{static{o(this,"PropertyCardinalityRegistry")}constructor(){this.multiValuedIRIs=new Set,this.initialized=!1}async initialize(e){this.multiValuedIRIs.clear();try{let t=await e.predicates(),r=t.find(c=>c.value.includes("Property_cardinality"));if(!r){this.initialized=!0;return}let i=await this.findMultipleCardinalityIRI(e,t);if(!i){this.initialized=!0;return}let s=await e.match(void 0,r,i);if(s.length===0){this.initialized=!0;return}let a=t.find(c=>c.value.includes("Asset_label"));if(!a){this.initialized=!0;return}for(let c of s){let l=await e.match(c.subject,a,void 0);for(let u of l)if(u.object instanceof gx.Literal){let f=u.object.value,d=this.propertyKeyToIRI(f);d&&this.multiValuedIRIs.add(d)}}}catch{}this.initialized=!0}isMultiValued(e){return this.multiValuedIRIs.has(e)}get size(){return this.multiValuedIRIs.size}get isInitialized(){return this.initialized}async findMultipleCardinalityIRI(e,t){let r=t.find(a=>a.value.includes("Asset_label"));if(!r)return null;let i=await e.match(void 0,r,new gx.Literal("exo__PropertyCardinalityMultiple"));if(i.length>0&&i[0].subject instanceof mx.IRI)return i[0].subject;let s=t.find(a=>a.value.includes("Instance_class"));if(s){let a=await e.match(void 0,s,void 0);for(let c of a)if(c.object instanceof mx.IRI&&c.object.value.includes("PropertyCardinalityMultiple"))return c.object}return null}propertyKeyToIRI(e){return e.startsWith("exo__")?yS.Namespace.EXO.term(e.substring(5)).value:e.startsWith("ems__")?yS.Namespace.EMS.term(e.substring(5)).value:e.startsWith("exocmd__")?yS.Namespace.EXOCMD.term(e.substring(8)).value:null}};Mo.PropertyCardinalityRegistry=_S;Mo.PropertyCardinalityRegistry=_S=j8([(0,M8.injectable)()],_S)});var vS=b(br=>{"use strict";var $8=br&&br.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},V8=br&&br.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(br,"__esModule",{value:!0});br.PrototypeChainMaterializer=br.MAX_PROTOTYPE_DEPTH=br.INFERRED_GRAPH=void 0;br.inferredGraphForDepth=SS;var B8=Ce(),yx=Yn(),La=Ee(),U8=gS(),q8=bS();br.INFERRED_GRAPH=new La.IRI("https://exocortex.my/ontology/exo#inferred");var W8="https://exocortex.my/ontology/exo#inferred/";function SS(n){return new La.IRI(`${W8}${n}`)}o(SS,"inferredGraphForDepth");br.MAX_PROTOTYPE_DEPTH=10;var wS=class{static{o(this,"PrototypeChainMaterializer")}constructor(e,t){this.registry=e,this.cardinalityRegistry=t??null}async materialize(e){let r=(await e.predicates()).find(c=>c.value.includes("Asset_prototype"));if(!r)return 0;let i=await e.match(void 0,r,void 0);if(i.length===0)return 0;let s=new Map;for(let c of i)if(c.subject instanceof La.IRI&&c.object instanceof La.IRI){let l=c.subject.value,u=c.object.value;l!==u&&s.set(l,c.object)}if(s.size===0)return 0;let a=0;for(let[c]of s){let l=new La.IRI(c),u=this.resolveChain(c,s);if(u.length===0)continue;let f=await e.match(l,void 0,void 0),d=new Set,h=new Map;for(let p of f)if(d.add(p.predicate.value),this.isMultiValued(p.predicate.value)){let y=p.object instanceof La.IRI?p.object.value:String(p.object),S=h.get(p.predicate.value);S||(S=new Set,h.set(p.predicate.value,S)),S.add(y)}for(let p=0;p<u.length;p++){let y=u[p],S=p+1,v=new La.IRI(y),w=await e.match(v,void 0,void 0),T=new Set;if(e.matchInGraph){let C=await e.matchInGraph(v,void 0,void 0,br.INFERRED_GRAPH);for(let V of C)T.add(V.predicate.value)}for(let C of w){let V=C.predicate.value;if(this.registry.isNonInheritable(V)||T.has(V))continue;if(d.has(V)&&this.isMultiValued(V)){let ee=C.object instanceof La.IRI?C.object.value:String(C.object);if(h.get(V)?.has(ee))continue;let W=h.get(V);W||(W=new Set,h.set(V,W)),W.add(ee);let F=new yx.Triple(l,C.predicate,C.object);await e.add(F),e.addToGraph&&(await e.addToGraph(F,br.INFERRED_GRAPH),await e.addToGraph(F,SS(S))),a++;continue}if(d.has(V))continue;let L=new yx.Triple(l,C.predicate,C.object);await e.add(L),e.addToGraph&&(await e.addToGraph(L,br.INFERRED_GRAPH),await e.addToGraph(L,SS(S))),d.add(V),a++}}}return a}isMultiValued(e){return this.cardinalityRegistry?this.cardinalityRegistry.isMultiValued(e):!1}resolveChain(e,t){let r=[],i=new Set;i.add(e);let s=[],a=t.get(e);for(a&&s.push(a.value);s.length>0&&r.length<br.MAX_PROTOTYPE_DEPTH;){let c=s.shift();if(c===void 0)break;if(i.has(c))continue;i.add(c),r.push(c);let l=t.get(c);l&&!i.has(l.value)&&s.push(l.value)}return r}};br.PrototypeChainMaterializer=wS;br.PrototypeChainMaterializer=wS=$8([(0,B8.injectable)(),V8("design:paramtypes",[U8.NonInheritablePropertyRegistry,q8.PropertyCardinalityRegistry])],wS)});var TS=b(lr=>{"use strict";var G8=lr&&lr.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},z8=lr&&lr.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(lr,"__esModule",{value:!0});lr.SourceAnnotator=lr.DEPTH_VARIABLE=lr.SOURCE_VARIABLE=void 0;var H8=Ce(),il=Me(),Q8=Ee(),zp=vS();lr.SOURCE_VARIABLE="_source";lr.DEPTH_VARIABLE="_depth";var ES=class{static{o(this,"SourceAnnotator")}constructor(e){this.tripleStore=e}async annotate(e,t,r,i){if(!this.tripleStore.matchInGraph)return e.map(a=>{let c=a.clone();return c.set(lr.SOURCE_VARIABLE,new il.Literal("own")),c});let s=[];for(let a of e){let c=a.get(t),l=a.get(r),u=a.get(i),f=a.clone();if(!c||!l||!u)f.set(lr.SOURCE_VARIABLE,new il.Literal("own"));else{let d=await this.determineSource(c,l,u);f.set(lr.SOURCE_VARIABLE,new il.Literal(d))}s.push(f)}return s}async annotateSingle(e,t,r,i){return(await this.annotate([e],t,r,i))[0]}async determineSource(e,t,r){return this.tripleStore.matchInGraph&&(await this.tripleStore.matchInGraph(e,t,r,zp.INFERRED_GRAPH)).length>0?"inherited":"own"}async getInheritanceDepth(e,t,r){if(!this.tripleStore.matchInGraph)return 0;for(let i=1;i<=zp.MAX_PROTOTYPE_DEPTH;i++){let s=(0,zp.inferredGraphForDepth)(i);if((await this.tripleStore.matchInGraph(e,t,r,s)).length>0)return i}return 0}async annotateBySubject(e,t){if(!this.tripleStore.matchInGraph)return e.map(s=>{let a=s.clone();return a.set(lr.SOURCE_VARIABLE,new il.Literal("own")),a});let r=[],i=new Map;for(let s of e){let a=s.get(t),c=s.clone();if(!a||!(a instanceof Q8.IRI))c.set(lr.SOURCE_VARIABLE,new il.Literal("own"));else{let l=a.value;if(!i.has(l)){let f=await this.tripleStore.matchInGraph(a,void 0,void 0,zp.INFERRED_GRAPH);i.set(l,f.length>0?"inherited":"own")}let u=i.get(l)??"own";c.set(lr.SOURCE_VARIABLE,new il.Literal(u))}r.push(c)}return r}};lr.SourceAnnotator=ES;lr.SourceAnnotator=ES=G8([(0,H8.injectable)(),z8("design:paramtypes",[Object])],ES)});var xS=b(ki=>{"use strict";var K8=ki&&ki.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},Y8=ki&&ki.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},_x=ki&&ki.__param||function(n,e){return function(t,r){e(t,r,n)}};Object.defineProperty(ki,"__esModule",{value:!0});ki.NoteToRDFConverter=void 0;var AS=Ce(),ur=Yn(),ka=Ee(),hn=Me(),bx=$t(),Wt=ir(),Sx=Ct(),X8=dS(),J8=pc(),wx=uS(),On=S0(),Z8=new Set(["archived","draft","pinned"]),sl=class{static{o(this,"NoteToRDFConverter")}constructor(e,t=J8.NullLogger){this.vault=e,this.logger=t,this.BODY_WIKILINK_PATTERN=/(?<!!)\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g,this.pendingExtraTriples=[],this.vocabularyMapper=new X8.RDFVocabularyMapper}async convertNote(e){let t=this.vault.getFrontmatter(e);if(!t)return[];let r=this.notePathToIRI(e.path),i=Wt.Namespace.EXO.term("Asset_filename"),s=new ur.Triple(r,i,new hn.Literal(e.basename));if(On.Exo003Parser.isExo003Format(t)){let a=await this.convertExo003Note(e,t);return[s,...a]}return this.convertLegacyNote(e,t,s)}async convertLegacyNote(e,t,r){this.pendingExtraTriples=[];let i=[r],s=this.notePathToIRI(e.path);for(let[f,d]of Object.entries(t)){let h=Z8.has(f)?`exo__Asset_${f}`:f;if(!this.isExocortexProperty(h))continue;let p=this.propertyKeyToIRI(h),y=Array.isArray(d)?d:[d];for(let S of y)if(!(f==="exo__Asset_label"&&typeof S=="string"&&S.trim()===""))if(f==="exo__Instance_class"){let v=this.valueToClassURI(S);i.push(new ur.Triple(s,p,v))}else{let v=await this.valueToRDFObject(S,e,p);for(let w of v)if(i.push(new ur.Triple(s,p,w)),this.vocabularyMapper.hasMappingFor(f)&&w instanceof ka.IRI){let T=this.vocabularyMapper.generateMappedTriple(s,f,w);T&&i.push(T)}}if(f==="exo__Instance_class")for(let S of y){let v=this.valueToClassURI(S);if(v instanceof ka.IRI){let w=Wt.Namespace.RDF.term("type");i.push(new ur.Triple(s,w,v))}}if(f==="exo__Asset_label"){let S=Wt.Namespace.RDFS.term("label");for(let v of y)typeof v=="string"&&v.length>0&&i.push(new ur.Triple(s,S,new hn.Literal(v)))}}let a="exo__Instance_class"in t||"exo__Asset_uid"in t,c=t.exo__Asset_label,l="exo__Asset_label"in t&&c!==null&&c!==void 0&&!(typeof c=="string"&&c.trim()==="")&&!(Array.isArray(c)&&c.length===0);if(a&&!l){let f=Wt.Namespace.RDFS.term("label"),d=Wt.Namespace.EXO.term("Asset_label"),h=new hn.Literal(e.basename);i.push(new ur.Triple(s,f,h)),i.push(new ur.Triple(s,d,h))}i.push(...this.pendingExtraTriples),this.pendingExtraTriples=[];let u=await this.convertBodyWikilinks(e,s);return i.push(...u),i}async convertExo003Note(e,t){let r=On.Exo003Parser.parse(t);if(!r.success||!r.metadata)return[];let i=r.metadata,s=[];switch(i.metadata){case On.Exo003MetadataType.Namespace:break;case On.Exo003MetadataType.Anchor:s.push(...this.convertExo003Anchor(e,i));break;case On.Exo003MetadataType.BlankNode:s.push(...this.convertExo003BlankNode(e,i));break;case On.Exo003MetadataType.Statement:s.push(...this.convertExo003Statement(e,i));break;case On.Exo003MetadataType.Body:s.push(...await this.convertExo003Body(e,i));break}return s}convertExo003Anchor(e,t){let r=this.notePathToIRI(e.path),i=new ka.IRI(t.uri);return[new ur.Triple(r,Wt.Namespace.OWL.term("sameAs"),i),new ur.Triple(i,Wt.Namespace.OWL.term("sameAs"),r)]}convertExo003BlankNode(e,t){let r=this.notePathToIRI(e.path),i=t.uri.replace(/[^a-zA-Z0-9_-]/g,"_");return[new ur.Triple(r,Wt.Namespace.OWL.term("sameAs"),new bx.BlankNode(i))]}convertExo003Statement(e,t){let r=[];try{let i=this.createExo003ReferenceResolver(e),s=On.Exo003Parser.toTriple(t,i);r.push(s);let a=this.notePathToIRI(e.path);r.push(new ur.Triple(a,Wt.Namespace.RDF.term("value"),s.subject))}catch{}return r}async convertExo003Body(e,t){let r=[];try{let i=await this.vault.read(e),s=this.extractBodyContent(i),a=this.createExo003ReferenceResolver(e),c=a(t.subject),l=a(t.predicate);if(c.type==="literal")throw new Error("Body subject cannot be a literal");if(l.type!=="iri")throw new Error("Body predicate must be an IRI");let u=c.type==="iri"?new ka.IRI(c.value):new bx.BlankNode(c.value),f=new ka.IRI(l.value),d=On.Exo003Parser.toLiteral(t,s.trim());r.push(new ur.Triple(u,f,d));let h=this.notePathToIRI(e.path);r.push(new ur.Triple(h,Wt.Namespace.RDF.term("value"),u))}catch{}return r}createExo003ReferenceResolver(e){return t=>{let r=this.extractWikilink(t),i=r||t,s=this.vault.getFirstLinkpathDest(i,e.path);if(s){let a=this.vault.getFrontmatter(s);if(a&&On.Exo003Parser.isExo003Format(a)){let c=On.Exo003Parser.parse(a);if(c.success&&c.metadata){let l=c.metadata;if(l.metadata===On.Exo003MetadataType.Anchor||l.metadata===On.Exo003MetadataType.Namespace)return{type:"iri",value:l.uri};if(l.metadata===On.Exo003MetadataType.BlankNode)return{type:"blank",value:l.uri.replace(/[^a-zA-Z0-9_-]/g,"_")}}}return{type:"iri",value:this.notePathToIRI(s.path).value}}return!r&&t.includes("://")?{type:"iri",value:t}:{type:"literal",value:t}}}async convertVault(){return(await this.convertVaultWithValidation({strict:!1})).triples}async convertVaultWithValidation(e={}){let t=this.vault.getAllFiles(),r=[],i=[],s=e.strict??!1;for(let a of t)try{let c=this.vault.getFrontmatter(a),l=c?this.validateExocortexAsset(c,a.basename):null;if(l){if(s)throw new Error(`Invariant violation in "${a.path}": ${l.message}`);i.push({path:a.path,reason:`Invariant violation: ${l.message}`}),this.logger.warn(`Skipping file with invariant violation: ${a.path}`,{code:l.code,property:l.property,reason:l.message});continue}let u=await this.convertNote(a);r.push(...u)}catch(c){let l=c instanceof Error?c.message:String(c);if(s)throw new Error(`Invalid IRI for file "${a.path}": ${l}`);i.push({path:a.path,reason:`Invalid IRI: ${l}`}),this.logger.warn(`Skipping file with invalid IRI: ${a.path}`,{reason:l})}return{triples:r,skippedFiles:i,summary:{total:t.length,indexed:t.length-i.length,skipped:i.length}}}static inferLabelFromBasename(e){return Wt.Namespace.fromPropertyKey(e)!==null?e:null}validateExocortexAsset(e,t){let r=o(d=>d==null?!0:typeof d=="string"?d.trim()==="":Array.isArray(d)?d.length===0||d.every(r):!1,"isEmpty");if(!("exo__Instance_class"in e||"exo__Asset_uid"in e))return null;let s=["exo__Asset_uid","exo__Instance_class"];for(let d of s){if(!(d in e))return{code:"MISSING_PROPERTY",property:d,message:`Required property "${d}" is missing`};if(r(e[d]))return{code:"EMPTY_PROPERTY",property:d,message:`Required property "${d}" is empty`}}let a=["ems__Effort_status","ems__Effort_parent","ems__Effort_lockedBy","ems__Effort_lockExpires","exo__Asset_updatedAt","ems__Effort_startTimestamp"];for(let d of a)if(d in e&&r(e[d]))return{code:"EMPTY_OPTIONAL_PROPERTY",property:d,message:`Optional property "${d}" is present but empty`};let c=e.exo__Instance_class,l=Array.isArray(c)?c:[c],u=null,f=!1;for(let d of l){if(typeof d!="string")continue;let h=this.removeQuotes(d),y=(this.extractWikilink(h)??h).trim();/^[a-z][a-zA-Z0-9]*__/.test(y)&&/[\s()]/.test(y)?u||(u={candidate:d}):f=!0}return u&&!f?{code:"INVALID_INSTANCE_CLASS_IRI",property:"exo__Instance_class",message:`Invalid Instance_class IRI: "${u.candidate}"`}:null}async validateVault(){let e=this.vault.getAllFiles(),t=[];for(let r of e){let i=(0,wx.vaultPathToIRI)(r.path);ka.IRI.isValidIRI(i)||t.push({path:r.path,reason:`Path "${r.path}" cannot be converted to a valid IRI`})}return t}notePathToIRI(e){return new ka.IRI((0,wx.vaultPathToIRI)(e))}isExocortexProperty(e){return Wt.Namespace.fromPropertyKey(e)!==null}propertyKeyToIRI(e){let t=Wt.Namespace.fromPropertyKey(e);if(!t)throw new Error(`Invalid property key: ${e}`);return t.namespace.term(t.localName)}emitTypeTripleForEnumInstance(e,t){let r=this.vault.getFrontmatter(t);if(!r)return;let i=r.exo__Instance_class,s=Array.isArray(i)?i[0]:i;if(typeof s!="string")return;let a=this.valueToClassURI(s);a instanceof ka.IRI&&(this.pendingExtraTriples.push(new ur.Triple(e,Wt.Namespace.RDF.term("type"),a)),this.pendingExtraTriples.push(new ur.Triple(e,Wt.Namespace.EXO.term("Instance_class"),a)))}async valueToRDFObject(e,t,r){if(typeof e=="string"){let i=this.removeQuotes(e),s=this.extractWikilink(i);if(s){let a=this.vault.getFirstLinkpathDest(s,t.path);if(a){let l=this.notePathToIRI(a.path),u=s.includes("|")?s.split("|")[0]:s;if(this.isUUID(u)){let d=new hn.Literal(u);if(r?.value.endsWith("#Grounding_targetValueRef")||r?.value.endsWith("#Grounding_targetValueSubstitution")||r?.value.endsWith("#Grounding_targetClass"))return[l];let p=this.expandClassValue(a.basename);if(p)return this.emitTypeTripleForEnumInstance(p,a),[p];let y=this.vault.getFrontmatter(a);if(y){let v=y.exo__Asset_label;if(typeof v=="string"){let w=this.expandClassValue(v);if(w)return this.emitTypeTripleForEnumInstance(w,a),[w]}}return r?.value.endsWith("#Asset_prototype")||r?.value.endsWith("/Asset_prototype")?[l,d]:[l]}let f=this.expandClassValue(a.basename);return f?(this.emitTypeTripleForEnumInstance(f,a),[f]):[l]}if(this.isClassReference(s)){let l=this.expandClassValue(s);if(l)return[l]}let c=s.includes("|")?s.split("|")[0]:s;return this.isUUID(c)?[this.notePathToIRI(`${c}.md`)]:[new hn.Literal(i)]}if(this.isClassReference(i)){let a=this.expandClassValue(i);if(a)return[a]}return this.isISO8601DateTime(i)?[new hn.Literal(i,Wt.Namespace.XSD.term("dateTime"))]:[new hn.Literal(i)]}return typeof e=="boolean"?[new hn.Literal(e.toString())]:typeof e=="number"?[new hn.Literal(e.toString(),Wt.Namespace.XSD.term("decimal"))]:e instanceof Date?[new hn.Literal(e.toISOString(),Wt.Namespace.XSD.term("dateTime"))]:[new hn.Literal(String(e))]}isISO8601DateTime(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})?$/.test(e)}removeQuotes(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.substring(1,t.length-1):e}extractWikilink(e){let t=e.match(/^\[\[([^\]]+)\]\]$/);if(!t)return null;let r=t[1];return r.includes("|")?r.split("|")[0]:r}extractWikilinkAlias(e){let t=e.match(/^\[\[([^\]]+)\]\]$/);if(!t)return null;let r=t[1],i=r.indexOf("|");return i>=0?r.substring(i+1).trim():null}valueToClassURI(e){if(typeof e!="string")return new hn.Literal(String(e));let t=this.removeQuotes(e),i=this.extractWikilink(t)||t,s=this.expandClassValue(i);if(s)return s;let a=this.extractWikilinkAlias(t);if(a){let c=this.expandClassValue(a);if(c)return c}if(this.isUUID(i)){let c=this.vault.getFirstLinkpathDest(i,"");if(c){let l=this.expandClassValue(c.basename);if(l)return l;let u=this.vault.getFrontmatter(c);if(u){let f=u.exo__Asset_label;if(typeof f=="string"){let d=this.expandClassValue(f);if(d)return d}}}}return new hn.Literal(t)}isClassReference(e){return/\s/.test(e)?!1:Wt.Namespace.fromPropertyKey(e)!==null}isUUID(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}expandClassValue(e){let t=this.removeQuotes(e),r=Wt.Namespace.fromPropertyKey(t);return!r||/[\s()]/.test(r.localName)?null:r.namespace.term(r.localName)}extractBodyContent(e){let t=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;return e.replace(t,"")}extractBodyWikilinks(e){let t=new Set,r,i=new RegExp(this.BODY_WIKILINK_PATTERN.source,"g");for(;(r=i.exec(e))!==null;)r[1]&&t.add(r[1]);return Array.from(t)}async convertBodyWikilinks(e,t){let r=[];try{let i=await this.vault.read(e),s=this.extractBodyContent(i),a=this.extractBodyWikilinks(s),c=Wt.Namespace.EXO.term("Asset_bodyLink");for(let l of a){let u=this.vault.getFirstLinkpathDest(l,e.path);if(u){let f=this.notePathToIRI(u.path);r.push(new ur.Triple(t,c,f))}else if(this.isClassReference(l)){let f=this.expandClassValue(l);f?r.push(new ur.Triple(t,c,f)):r.push(new ur.Triple(t,c,new hn.Literal(l)))}else r.push(new ur.Triple(t,c,new hn.Literal(l)))}}catch{}return r}};ki.NoteToRDFConverter=sl;sl.SkippedFileInfo=class{constructor(n,e){this.path=n,this.reason=e}};sl.VaultValidationResult=class{constructor(n,e,t){this.triples=n,this.skippedFiles=e,this.summary=t}};sl.VaultValidationOptions=class{constructor(n=!1){this.strict=n}};ki.NoteToRDFConverter=sl=K8([(0,AS.injectable)(),_x(0,(0,AS.inject)(Sx.DI_TOKENS.IVaultAdapter)),_x(1,(0,AS.inject)(Sx.DI_TOKENS.ILogger)),Y8("design:paramtypes",[Object,Object])],sl)});var CS=b(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});Hp.FilterContainsOptimizer=void 0;var e$=Ee(),t$=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,IS=class{static{o(this,"FilterContainsOptimizer")}constructor(){this.tripleStore=null,this.lastOptimizationHints=[]}setTripleStore(e){this.tripleStore=e}getLastOptimizationHints(){return this.lastOptimizationHints}clearHints(){this.lastOptimizationHints=[]}async optimize(e){return this.clearHints(),this.optimizeRecursive(e)}optimizeSync(e,t){return this.clearHints(),this.optimizeSyncRecursive(e,t)}async optimizeRecursive(e){return e.type==="filter"?this.optimizeFilter(e):e.type==="join"?{type:"join",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="leftjoin"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="union"?{type:"union",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="minus"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="project"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="orderby"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="slice"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="distinct"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="reduced"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="group"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="extend"?{...e,input:await this.optimizeRecursive(e.input)}:e}optimizeSyncRecursive(e,t){return e.type==="filter"?this.optimizeFilterSync(e,t):e.type==="join"?{type:"join",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="leftjoin"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="union"?{type:"union",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="minus"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="project"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="orderby"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="slice"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="distinct"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="reduced"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="group"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="extend"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e}async optimizeFilter(e){let t=this.detectContainsUUIDPattern(e.expression);if(!t)return{type:"filter",expression:e.expression,input:await this.optimizeRecursive(e.input)};let r=[];return this.tripleStore&&(r=await this.findSubjectsContainingUUID(t.uuid)),this.rewriteFilter(e,t,r)}optimizeFilterSync(e,t){let r=this.detectContainsUUIDPattern(e.expression);if(!r)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input,t)};let i=t?t.filter(s=>s.includes(r.uuid)):[];return this.rewriteFilter(e,r,i)}rewriteFilter(e,t,r){if(this.lastOptimizationHints.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${t.variable}), "${t.uuid}"))`,suggestedRewrite:r.length===1?`VALUES ?${t.variable} { <${r[0]}> }`:r.length>1?`VALUES ?${t.variable} { ${r.map(i=>`<${i}>`).join(" ")} }`:"No matching URIs found for UUID",estimatedSpeedup:r.length>0?"O(n) \u2192 O(1)":"N/A",matchedUri:r.length===1?r[0]:void 0}),r.length===0)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input)};if(r.length===1){let i=this.injectSubjectConstraint(e.input,t.variable,r[0]);if(i!==e.input)return i}return this.createValuesJoin(e,t,r)}detectContainsUUIDPattern(e){if(e.type==="function"||e.type==="functionCall"){let t=e;if((typeof t.function=="string"?t.function.toLowerCase():t.function?.value?.toLowerCase()??"")==="contains"&&t.args.length===2)return this.analyzeContainsArgs(t.args[0],t.args[1],e)}if(e.type==="logical"&&e.operator==="&&")for(let t of e.operands){let r=this.detectContainsUUIDPattern(t);if(r)return r}return null}analyzeContainsArgs(e,t,r){let i=null;if(e.type==="function"||e.type==="functionCall"){let s=e;if((typeof s.function=="string"?s.function.toLowerCase():s.function?.value?.toLowerCase()??"")==="str"&&s.args.length===1){let c=s.args[0];c.type==="variable"&&(i=c.name)}}if(!i&&e.type==="variable"&&(i=e.name),!i)return null;if(t.type==="literal"){let c=String(t.value).match(t$);if(c)return{variable:i,uuid:c[0].toLowerCase(),originalExpression:r}}return null}async findSubjectsContainingUUID(e){if(!this.tripleStore)return[];if(this.tripleStore.findSubjectsByUUID)return(await this.tripleStore.findSubjectsByUUID(e)).map(s=>s.value);let t=await this.tripleStore.subjects(),r=[];for(let i of t)i instanceof e$.IRI&&i.value.toLowerCase().includes(e.toLowerCase())&&r.push(i.value);return r}injectSubjectConstraint(e,t,r){if(e.type==="bgp"){let i=e.triples.map(a=>a.subject.type==="variable"&&a.subject.value===t?{...a,subject:{type:"iri",value:r}}:a);if(i.some((a,c)=>a.subject!==e.triples[c].subject))return{type:"bgp",triples:i}}if(e.type==="join"){let i=this.injectSubjectConstraint(e.left,t,r),s=this.injectSubjectConstraint(e.right,t,r);if(i!==e.left||s!==e.right)return{type:"join",left:i,right:s}}if(e.type==="filter"){let i=this.injectSubjectConstraint(e.input,t,r);if(i!==e.input)return{...e,input:i}}return e}createValuesJoin(e,t,r){return{type:"join",left:{type:"values",variables:[t.variable],bindings:r.map(a=>({[t.variable]:{type:"iri",value:a}}))},right:this.optimizeSyncRecursive(e.input)}}analyzeQuery(e){let t=[];return this.analyzeRecursive(e,t),t}analyzeRecursive(e,t){if(e.type==="filter"){let r=this.detectContainsUUIDPattern(e.expression);r&&t.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${r.variable}), "${r.uuid}"))`,suggestedRewrite:`Use --optimize flag or rewrite as VALUES ?${r.variable} { <uri-containing-uuid> }`,estimatedSpeedup:"O(n) \u2192 O(1) with UUID index lookup"}),this.analyzeRecursive(e.input,t);return}e.type==="join"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="leftjoin"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="union"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="minus"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="project"?this.analyzeRecursive(e.input,t):e.type==="orderby"?this.analyzeRecursive(e.input,t):e.type==="slice"?this.analyzeRecursive(e.input,t):e.type==="distinct"?this.analyzeRecursive(e.input,t):e.type==="reduced"?this.analyzeRecursive(e.input,t):e.type==="group"?this.analyzeRecursive(e.input,t):e.type==="extend"&&this.analyzeRecursive(e.input,t)}};Hp.FilterContainsOptimizer=IS});var vx=b(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});Qp.AlgebraOptimizer=void 0;var r$=CS(),RS=class{static{o(this,"AlgebraOptimizer")}constructor(){this.stats=new Map,this.tripleStore=null,this.filterContainsOptimizer=new r$.FilterContainsOptimizer}setTripleStore(e){this.tripleStore=e,this.filterContainsOptimizer.setTripleStore(e)}getOptimizationHints(){return this.filterContainsOptimizer.getLastOptimizationHints()}analyzeQuery(e){return this.filterContainsOptimizer.analyzeQuery(e)}optimize(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),t=this.filterPushDown(t),t=this.joinReordering(t),t}async optimizeAsync(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),this.tripleStore&&(t=await this.filterContainsOptimizer.optimize(t)),t=this.filterPushDown(t),t=this.joinReordering(t),t}optimizeWithSubjects(e,t){let r=e;return r=this.eliminateEmptyBGPInFilterJoin(r),r=this.filterContainsOptimizer.optimizeSync(r,t),r=this.filterPushDown(r),r=this.joinReordering(r),r}eliminateEmptyBGPInFilterJoin(e){if(e.type==="join"){if(e.left.type==="filter"){let t=e.left;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.right)}}if(e.right.type==="filter"){let t=e.right;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.left)}}return{type:"join",left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}}return e.type==="filter"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="leftjoin"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="union"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="minus"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="project"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="orderby"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="slice"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="distinct"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e}filterPushDown(e){return e.type==="filter"?this.pushDownFilter(e):e.type==="join"?{type:"join",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="leftjoin"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="union"?{type:"union",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="minus"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="project"?{...e,input:this.filterPushDown(e.input)}:e.type==="orderby"?{...e,input:this.filterPushDown(e.input)}:e.type==="slice"?{...e,input:this.filterPushDown(e.input)}:e.type==="distinct"?{...e,input:this.filterPushDown(e.input)}:e}pushDownFilter(e){let t=e.input;if(t.type==="join"){let r=this.getFilterVariables(e.expression),i=this.getOperationVariables(t.left),s=this.getOperationVariables(t.right),a=r.every(l=>i.has(l)),c=r.every(l=>s.has(l));return a&&!c?{type:"join",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:this.filterPushDown(t.right)}:c&&!a?{type:"join",left:this.filterPushDown(t.left),right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:{type:"join",left:this.filterPushDown(t.left),right:this.filterPushDown(t.right)}}}return t.type==="union"?{type:"union",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:this.filterPushDown(t)}}getFilterVariables(e){let t=[];if(e.type==="variable")t.push(e.name);else if(e.type==="comparison")t.push(...this.getFilterVariables(e.left)),t.push(...this.getFilterVariables(e.right));else if(e.type==="logical")for(let r of e.operands)t.push(...this.getFilterVariables(r));else if(e.type==="function")for(let r of e.args)t.push(...this.getFilterVariables(r));return Array.from(new Set(t))}getOperationVariables(e){let t=new Set;if(e.type==="bgp")for(let r of e.triples)r.subject.type==="variable"&&t.add(r.subject.value),r.predicate.type==="variable"&&t.add(r.predicate.value),r.object.type==="variable"&&t.add(r.object.value);else if(e.type==="join"){let r=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...r,...i])}else{if(e.type==="filter")return this.getOperationVariables(e.input);if(e.type==="leftjoin"){let r=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...r,...i])}else if(e.type==="union"){let r=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...r,...i])}else{if(e.type==="minus")return this.getOperationVariables(e.left);if(e.type==="project")return new Set(e.variables)}}return t}joinReordering(e){return e.type==="join"?this.reorderJoin(e):e.type==="filter"?{...e,input:this.joinReordering(e.input)}:e.type==="leftjoin"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="union"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="minus"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="project"?{...e,input:this.joinReordering(e.input)}:e.type==="orderby"?{...e,input:this.joinReordering(e.input)}:e.type==="slice"?{...e,input:this.joinReordering(e.input)}:e.type==="distinct"?{...e,input:this.joinReordering(e.input)}:e}reorderJoin(e){let t=this.isConstrained(e.left),r=this.isConstrained(e.right);if(r&&!t)return{type:"join",left:this.joinReordering(e.right),right:this.joinReordering(e.left)};if(t&&!r)return{type:"join",left:this.joinReordering(e.left),right:this.joinReordering(e.right)};let i=this.estimateCost(e.left);return this.estimateCost(e.right)<i?{type:"join",left:this.joinReordering(e.right),right:this.joinReordering(e.left)}:{type:"join",left:this.joinReordering(e.left),right:this.joinReordering(e.right)}}isConstrained(e){return e.type==="values"?!0:e.type==="bgp"?e.triples.some(t=>t.object.type!=="variable"||t.subject.type!=="variable"):e.type==="filter"?this.isConstrained(e.input):e.type==="join"?this.isConstrained(e.left)||this.isConstrained(e.right):e.type==="union"?this.isConstrained(e.left)&&this.isConstrained(e.right):!1}estimateCost(e){if(e.type==="bgp"){let t=0;for(let r of e.triples){let i=10;r.subject.type==="variable"&&(i*=10),r.predicate.type==="variable"&&(i*=20),r.object.type==="variable"&&(i*=5),t+=i}return t}if(e.type==="filter")return this.estimateCost(e.input)*.3;if(e.type==="join"){let t=this.estimateCost(e.left),r=this.estimateCost(e.right);return e.left.type==="values"||e.right.type==="values"?Math.min(t,r)*2:t*r}if(e.type==="leftjoin")return this.estimateCost(e.left)+this.estimateCost(e.right)*.5;if(e.type==="union")return this.estimateCost(e.left)+this.estimateCost(e.right);if(e.type==="values"){let t=e.bindings;return Array.isArray(t)?t.length*5:10}return e.type==="minus"?this.estimateCost(e.left)+this.estimateCost(e.right)*.3:100}setStatistics(e,t){this.stats.set(e,t)}getStatistics(e){return this.stats.get(e)}};Qp.AlgebraOptimizer=RS});var Ex=b(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});Kp.AlgebraSerializer=void 0;var OS=class{static{o(this,"AlgebraSerializer")}toString(e,t=0){let r=" ".repeat(t);switch(e.type){case"bgp":return`${r}BGP [
371
+ `),t}};Up.RDFSerializer=lS});var uS=b(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.OBSIDIAN_VAULT_SCHEME=void 0;nl.vaultPathToIRI=D8;nl.OBSIDIAN_VAULT_SCHEME="obsidian://vault/";function D8(n){let e=n.startsWith("./")?n.slice(2):n;return`${nl.OBSIDIAN_VAULT_SCHEME}${encodeURI(e)}`}o(D8,"vaultPathToIRI")});var dS=b(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});qp.RDFVocabularyMapper=void 0;var Xt=Yn(),fx=Ee(),J=ir(),fS=class{static{o(this,"RDFVocabularyMapper")}constructor(){this.propertyMappings=new Map([["exo__Instance_class",J.Namespace.RDF.term("type")],["exo__Asset_isDefinedBy",J.Namespace.RDFS.term("isDefinedBy")],["exo__Class_superClass",J.Namespace.RDFS.term("subClassOf")],["exo__Property_range",J.Namespace.RDFS.term("range")],["exo__Property_domain",J.Namespace.RDFS.term("domain")],["exo__Property_superProperty",J.Namespace.RDFS.term("subPropertyOf")]])}generateClassHierarchyTriples(){let e=[];return e.push(new Xt.Triple(J.Namespace.EXO.term("Asset"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.RDFS.term("Resource"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Class"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.RDFS.term("Class"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Property"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.RDF.term("Property"))),e.push(new Xt.Triple(J.Namespace.EMS.term("Task"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("Project"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("Area"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("Workflow"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("WorkflowState"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EMS.term("WorkflowTransition"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EXOCMD.term("Command"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EXOCMD.term("Precondition"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EXOCMD.term("Grounding"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e.push(new Xt.Triple(J.Namespace.EXOCMD.term("CommandBinding"),J.Namespace.RDFS.term("subClassOf"),J.Namespace.EXO.term("Asset"))),e}generatePropertyHierarchyTriples(){let e=[];return e.push(new Xt.Triple(J.Namespace.EXO.term("Instance_class"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDF.term("type"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Asset_isDefinedBy"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("isDefinedBy"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Class_superClass"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("subClassOf"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Property_range"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("range"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Property_domain"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("domain"))),e.push(new Xt.Triple(J.Namespace.EXO.term("Property_superProperty"),J.Namespace.RDFS.term("subPropertyOf"),J.Namespace.RDFS.term("subPropertyOf"))),e}generateMappedTriple(e,t,r){let i=this.propertyMappings.get(t);if(!i)return null;let s;if(r instanceof fx.IRI)s=r;else{let a=r.match(/^(ems|exo|exocmd)__(.+)$/);if(a){let[,c,l]=a;s=(c==="ems"?J.Namespace.EMS:c==="exocmd"?J.Namespace.EXOCMD:J.Namespace.EXO).term(l)}else s=new fx.IRI(r)}return new Xt.Triple(e,i,s)}hasMappingFor(e){return this.propertyMappings.has(e)}};qp.RDFVocabularyMapper=fS});var dx=b(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});Gp.RDFSInferenceEngine=void 0;var N8=Yn(),Wp=Ee(),hS=class{static{o(this,"RDFSInferenceEngine")}async materialize(e){let t=await e.predicates(),r=t.find(d=>d.value.includes("Class_superClass")),i=t.find(d=>d.value.includes("Instance_class"));if(!r||!i)return 0;let s=await this.buildDirectParentMap(e,r);if(s.size===0)return 0;let a=this.computeAllAncestors(s),c=await e.count(),l=await e.match(void 0,i),u=[];for(let d of l)if(d.object instanceof Wp.IRI){let h=a.get(d.object.value);if(h)for(let p of h)u.push(new N8.Triple(d.subject,i,new Wp.IRI(p)))}return u.length>0&&await e.addAll(u),await e.count()-c}async buildDirectParentMap(e,t){let r=await e.match(void 0,t),i=new Map;for(let s of r)if(s.subject instanceof Wp.IRI&&s.object instanceof Wp.IRI){let a=s.subject.value,c=s.object.value;i.has(a)||i.set(a,new Set),i.get(a).add(c)}return i}computeAllAncestors(e){let t=new Map;for(let r of e.keys())t.has(r)||t.set(r,this.computeAncestorsBFS(r,e));return t}computeAncestorsBFS(e,t){let r=new Set,i=new Set,s=[],a=t.get(e);if(a)for(let c of a)s.push(c);for(;s.length>0;){let c=s.shift();if(i.has(c))continue;i.add(c),r.add(c);let l=t.get(c);if(l)for(let u of l)i.has(u)||s.push(u)}return r}};Gp.RDFSInferenceEngine=hS});var gS=b(jo=>{"use strict";var L8=jo&&jo.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s};Object.defineProperty(jo,"__esModule",{value:!0});jo.NonInheritablePropertyRegistry=void 0;var k8=Ce(),hx=Ee(),px=Me(),pS=ir(),mS=class{static{o(this,"NonInheritablePropertyRegistry")}constructor(){this.nonInheritableIRIs=new Set,this.initialized=!1}async initialize(e){this.nonInheritableIRIs.clear();try{let t=await e.predicates(),r=t.find(c=>c.value.includes("Instance_class"));if(!r){this.initialized=!0;return}let i=await this.findNonInheritableClassIRI(e,t);if(!i){this.initialized=!0;return}let s=await e.match(void 0,r,i);if(s.length===0){this.initialized=!0;return}let a=t.find(c=>c.value.includes("Asset_label"));if(!a){this.initialized=!0;return}for(let c of s){let l=await e.match(c.subject,a,void 0);for(let u of l)if(u.object instanceof px.Literal){let f=u.object.value,d=this.propertyKeyToIRI(f);d&&this.nonInheritableIRIs.add(d)}}}catch{}this.initialized=!0}isNonInheritable(e){return this.nonInheritableIRIs.has(e)}get size(){return this.nonInheritableIRIs.size}get isInitialized(){return this.initialized}async findNonInheritableClassIRI(e,t){let r=t.find(a=>a.value.includes("Asset_label"));if(!r)return null;let i=await e.match(void 0,r,new px.Literal("exo__NonInheritableProperty"));if(i.length>0&&i[0].subject instanceof hx.IRI)return i[0].subject;let s=t.find(a=>a.value.includes("Instance_class"));if(s){let a=await e.match(void 0,s,void 0);for(let c of a)if(c.object instanceof hx.IRI&&c.object.value.includes("NonInheritableProperty"))return c.object}return null}propertyKeyToIRI(e){return e.startsWith("exo__")?pS.Namespace.EXO.term(e.substring(5)).value:e.startsWith("ems__")?pS.Namespace.EMS.term(e.substring(5)).value:e.startsWith("exocmd__")?pS.Namespace.EXOCMD.term(e.substring(8)).value:null}};jo.NonInheritablePropertyRegistry=mS;jo.NonInheritablePropertyRegistry=mS=L8([(0,k8.injectable)()],mS)});var bS=b(Mo=>{"use strict";var j8=Mo&&Mo.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s};Object.defineProperty(Mo,"__esModule",{value:!0});Mo.PropertyCardinalityRegistry=void 0;var M8=Ce(),mx=Ee(),gx=Me(),yS=ir(),_S=class{static{o(this,"PropertyCardinalityRegistry")}constructor(){this.multiValuedIRIs=new Set,this.initialized=!1}async initialize(e){this.multiValuedIRIs.clear();try{let t=await e.predicates(),r=t.find(c=>c.value.includes("Property_cardinality"));if(!r){this.initialized=!0;return}let i=await this.findMultipleCardinalityIRI(e,t);if(!i){this.initialized=!0;return}let s=await e.match(void 0,r,i);if(s.length===0){this.initialized=!0;return}let a=t.find(c=>c.value.includes("Asset_label"));if(!a){this.initialized=!0;return}for(let c of s){let l=await e.match(c.subject,a,void 0);for(let u of l)if(u.object instanceof gx.Literal){let f=u.object.value,d=this.propertyKeyToIRI(f);d&&this.multiValuedIRIs.add(d)}}}catch{}this.initialized=!0}isMultiValued(e){return this.multiValuedIRIs.has(e)}get size(){return this.multiValuedIRIs.size}get isInitialized(){return this.initialized}async findMultipleCardinalityIRI(e,t){let r=t.find(a=>a.value.includes("Asset_label"));if(!r)return null;let i=await e.match(void 0,r,new gx.Literal("exo__PropertyCardinalityMultiple"));if(i.length>0&&i[0].subject instanceof mx.IRI)return i[0].subject;let s=t.find(a=>a.value.includes("Instance_class"));if(s){let a=await e.match(void 0,s,void 0);for(let c of a)if(c.object instanceof mx.IRI&&c.object.value.includes("PropertyCardinalityMultiple"))return c.object}return null}propertyKeyToIRI(e){return e.startsWith("exo__")?yS.Namespace.EXO.term(e.substring(5)).value:e.startsWith("ems__")?yS.Namespace.EMS.term(e.substring(5)).value:e.startsWith("exocmd__")?yS.Namespace.EXOCMD.term(e.substring(8)).value:null}};Mo.PropertyCardinalityRegistry=_S;Mo.PropertyCardinalityRegistry=_S=j8([(0,M8.injectable)()],_S)});var vS=b(br=>{"use strict";var $8=br&&br.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},V8=br&&br.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(br,"__esModule",{value:!0});br.PrototypeChainMaterializer=br.MAX_PROTOTYPE_DEPTH=br.INFERRED_GRAPH=void 0;br.inferredGraphForDepth=SS;var B8=Ce(),yx=Yn(),La=Ee(),U8=gS(),q8=bS();br.INFERRED_GRAPH=new La.IRI("https://exocortex.my/ontology/exo#inferred");var W8="https://exocortex.my/ontology/exo#inferred/";function SS(n){return new La.IRI(`${W8}${n}`)}o(SS,"inferredGraphForDepth");br.MAX_PROTOTYPE_DEPTH=10;var wS=class{static{o(this,"PrototypeChainMaterializer")}constructor(e,t){this.registry=e,this.cardinalityRegistry=t??null}async materialize(e){let r=(await e.predicates()).find(c=>c.value.includes("Asset_prototype"));if(!r)return 0;let i=await e.match(void 0,r,void 0);if(i.length===0)return 0;let s=new Map;for(let c of i)if(c.subject instanceof La.IRI&&c.object instanceof La.IRI){let l=c.subject.value,u=c.object.value;l!==u&&s.set(l,c.object)}if(s.size===0)return 0;let a=0;for(let[c]of s){let l=new La.IRI(c),u=this.resolveChain(c,s);if(u.length===0)continue;let f=await e.match(l,void 0,void 0),d=new Set,h=new Map;for(let p of f)if(d.add(p.predicate.value),this.isMultiValued(p.predicate.value)){let y=p.object instanceof La.IRI?p.object.value:String(p.object),S=h.get(p.predicate.value);S||(S=new Set,h.set(p.predicate.value,S)),S.add(y)}for(let p=0;p<u.length;p++){let y=u[p],S=p+1,v=new La.IRI(y),w=await e.match(v,void 0,void 0),T=new Set;if(e.matchInGraph){let C=await e.matchInGraph(v,void 0,void 0,br.INFERRED_GRAPH);for(let V of C)T.add(V.predicate.value)}for(let C of w){let V=C.predicate.value;if(this.registry.isNonInheritable(V)||T.has(V))continue;if(d.has(V)&&this.isMultiValued(V)){let ee=C.object instanceof La.IRI?C.object.value:String(C.object);if(h.get(V)?.has(ee))continue;let W=h.get(V);W||(W=new Set,h.set(V,W)),W.add(ee);let F=new yx.Triple(l,C.predicate,C.object);await e.add(F),e.addToGraph&&(await e.addToGraph(F,br.INFERRED_GRAPH),await e.addToGraph(F,SS(S))),a++;continue}if(d.has(V))continue;let L=new yx.Triple(l,C.predicate,C.object);await e.add(L),e.addToGraph&&(await e.addToGraph(L,br.INFERRED_GRAPH),await e.addToGraph(L,SS(S))),d.add(V),a++}}}return a}isMultiValued(e){return this.cardinalityRegistry?this.cardinalityRegistry.isMultiValued(e):!1}resolveChain(e,t){let r=[],i=new Set;i.add(e);let s=[],a=t.get(e);for(a&&s.push(a.value);s.length>0&&r.length<br.MAX_PROTOTYPE_DEPTH;){let c=s.shift();if(c===void 0)break;if(i.has(c))continue;i.add(c),r.push(c);let l=t.get(c);l&&!i.has(l.value)&&s.push(l.value)}return r}};br.PrototypeChainMaterializer=wS;br.PrototypeChainMaterializer=wS=$8([(0,B8.injectable)(),V8("design:paramtypes",[U8.NonInheritablePropertyRegistry,q8.PropertyCardinalityRegistry])],wS)});var TS=b(lr=>{"use strict";var G8=lr&&lr.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},z8=lr&&lr.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(lr,"__esModule",{value:!0});lr.SourceAnnotator=lr.DEPTH_VARIABLE=lr.SOURCE_VARIABLE=void 0;var H8=Ce(),il=Me(),Q8=Ee(),zp=vS();lr.SOURCE_VARIABLE="_source";lr.DEPTH_VARIABLE="_depth";var ES=class{static{o(this,"SourceAnnotator")}constructor(e){this.tripleStore=e}async annotate(e,t,r,i){if(!this.tripleStore.matchInGraph)return e.map(a=>{let c=a.clone();return c.set(lr.SOURCE_VARIABLE,new il.Literal("own")),c});let s=[];for(let a of e){let c=a.get(t),l=a.get(r),u=a.get(i),f=a.clone();if(!c||!l||!u)f.set(lr.SOURCE_VARIABLE,new il.Literal("own"));else{let d=await this.determineSource(c,l,u);f.set(lr.SOURCE_VARIABLE,new il.Literal(d))}s.push(f)}return s}async annotateSingle(e,t,r,i){return(await this.annotate([e],t,r,i))[0]}async determineSource(e,t,r){return this.tripleStore.matchInGraph&&(await this.tripleStore.matchInGraph(e,t,r,zp.INFERRED_GRAPH)).length>0?"inherited":"own"}async getInheritanceDepth(e,t,r){if(!this.tripleStore.matchInGraph)return 0;for(let i=1;i<=zp.MAX_PROTOTYPE_DEPTH;i++){let s=(0,zp.inferredGraphForDepth)(i);if((await this.tripleStore.matchInGraph(e,t,r,s)).length>0)return i}return 0}async annotateBySubject(e,t){if(!this.tripleStore.matchInGraph)return e.map(s=>{let a=s.clone();return a.set(lr.SOURCE_VARIABLE,new il.Literal("own")),a});let r=[],i=new Map;for(let s of e){let a=s.get(t),c=s.clone();if(!a||!(a instanceof Q8.IRI))c.set(lr.SOURCE_VARIABLE,new il.Literal("own"));else{let l=a.value;if(!i.has(l)){let f=await this.tripleStore.matchInGraph(a,void 0,void 0,zp.INFERRED_GRAPH);i.set(l,f.length>0?"inherited":"own")}let u=i.get(l)??"own";c.set(lr.SOURCE_VARIABLE,new il.Literal(u))}r.push(c)}return r}};lr.SourceAnnotator=ES;lr.SourceAnnotator=ES=G8([(0,H8.injectable)(),z8("design:paramtypes",[Object])],ES)});var xS=b(ki=>{"use strict";var K8=ki&&ki.__decorate||function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},Y8=ki&&ki.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},_x=ki&&ki.__param||function(n,e){return function(t,r){e(t,r,n)}};Object.defineProperty(ki,"__esModule",{value:!0});ki.NoteToRDFConverter=void 0;var AS=Ce(),ur=Yn(),ka=Ee(),hn=Me(),bx=$t(),Wt=ir(),Sx=Ct(),X8=dS(),J8=pc(),wx=uS(),On=S0(),Z8=new Set(["archived","draft","pinned"]),sl=class{static{o(this,"NoteToRDFConverter")}constructor(e,t=J8.NullLogger){this.vault=e,this.logger=t,this.BODY_WIKILINK_PATTERN=/(?<!!)\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g,this.pendingExtraTriples=[],this.vocabularyMapper=new X8.RDFVocabularyMapper}async convertNote(e){let t=this.vault.getFrontmatter(e);if(!t)return[];let r=this.notePathToIRI(e.path),i=Wt.Namespace.EXO.term("Asset_filename"),s=new ur.Triple(r,i,new hn.Literal(e.basename));if(On.Exo003Parser.isExo003Format(t)){let a=await this.convertExo003Note(e,t);return[s,...a]}return this.convertLegacyNote(e,t,s)}async convertLegacyNote(e,t,r){this.pendingExtraTriples=[];let i=[r],s=this.notePathToIRI(e.path);for(let[f,d]of Object.entries(t)){let h=Z8.has(f)?`exo__Asset_${f}`:f;if(!this.isExocortexProperty(h))continue;let p=this.propertyKeyToIRI(h),y=Array.isArray(d)?d:[d];for(let S of y)if(!(f==="exo__Asset_label"&&typeof S=="string"&&S.trim()===""))if(f==="exo__Instance_class"){let v=this.valueToClassURI(S);i.push(new ur.Triple(s,p,v))}else{let v=await this.valueToRDFObject(S,e,p);for(let w of v)if(i.push(new ur.Triple(s,p,w)),this.vocabularyMapper.hasMappingFor(f)&&w instanceof ka.IRI){let T=this.vocabularyMapper.generateMappedTriple(s,f,w);T&&i.push(T)}}if(f==="exo__Instance_class")for(let S of y){let v=this.valueToClassURI(S);if(v instanceof ka.IRI){let w=Wt.Namespace.RDF.term("type");i.push(new ur.Triple(s,w,v))}}if(f==="exo__Asset_label"){let S=Wt.Namespace.RDFS.term("label");for(let v of y)typeof v=="string"&&v.length>0&&i.push(new ur.Triple(s,S,new hn.Literal(v)))}}let a="exo__Instance_class"in t||"exo__Asset_uid"in t,c=t.exo__Asset_label,l="exo__Asset_label"in t&&c!==null&&c!==void 0&&!(typeof c=="string"&&c.trim()==="")&&!(Array.isArray(c)&&c.length===0);if(a&&!l){let f=Wt.Namespace.RDFS.term("label"),d=Wt.Namespace.EXO.term("Asset_label"),h=new hn.Literal(e.basename);i.push(new ur.Triple(s,f,h)),i.push(new ur.Triple(s,d,h))}i.push(...this.pendingExtraTriples),this.pendingExtraTriples=[];let u=await this.convertBodyWikilinks(e,s);return i.push(...u),i}async convertExo003Note(e,t){let r=On.Exo003Parser.parse(t);if(!r.success||!r.metadata)return[];let i=r.metadata,s=[];switch(i.metadata){case On.Exo003MetadataType.Namespace:break;case On.Exo003MetadataType.Anchor:s.push(...this.convertExo003Anchor(e,i));break;case On.Exo003MetadataType.BlankNode:s.push(...this.convertExo003BlankNode(e,i));break;case On.Exo003MetadataType.Statement:s.push(...this.convertExo003Statement(e,i));break;case On.Exo003MetadataType.Body:s.push(...await this.convertExo003Body(e,i));break}return s}convertExo003Anchor(e,t){let r=this.notePathToIRI(e.path),i=new ka.IRI(t.uri);return[new ur.Triple(r,Wt.Namespace.OWL.term("sameAs"),i),new ur.Triple(i,Wt.Namespace.OWL.term("sameAs"),r)]}convertExo003BlankNode(e,t){let r=this.notePathToIRI(e.path),i=t.uri.replace(/[^a-zA-Z0-9_-]/g,"_");return[new ur.Triple(r,Wt.Namespace.OWL.term("sameAs"),new bx.BlankNode(i))]}convertExo003Statement(e,t){let r=[];try{let i=this.createExo003ReferenceResolver(e),s=On.Exo003Parser.toTriple(t,i);r.push(s);let a=this.notePathToIRI(e.path);r.push(new ur.Triple(a,Wt.Namespace.RDF.term("value"),s.subject))}catch{}return r}async convertExo003Body(e,t){let r=[];try{let i=await this.vault.read(e),s=this.extractBodyContent(i),a=this.createExo003ReferenceResolver(e),c=a(t.subject),l=a(t.predicate);if(c.type==="literal")throw new Error("Body subject cannot be a literal");if(l.type!=="iri")throw new Error("Body predicate must be an IRI");let u=c.type==="iri"?new ka.IRI(c.value):new bx.BlankNode(c.value),f=new ka.IRI(l.value),d=On.Exo003Parser.toLiteral(t,s.trim());r.push(new ur.Triple(u,f,d));let h=this.notePathToIRI(e.path);r.push(new ur.Triple(h,Wt.Namespace.RDF.term("value"),u))}catch{}return r}createExo003ReferenceResolver(e){return t=>{let r=this.extractWikilink(t),i=r||t,s=this.vault.getFirstLinkpathDest(i,e.path);if(s){let a=this.vault.getFrontmatter(s);if(a&&On.Exo003Parser.isExo003Format(a)){let c=On.Exo003Parser.parse(a);if(c.success&&c.metadata){let l=c.metadata;if(l.metadata===On.Exo003MetadataType.Anchor||l.metadata===On.Exo003MetadataType.Namespace)return{type:"iri",value:l.uri};if(l.metadata===On.Exo003MetadataType.BlankNode)return{type:"blank",value:l.uri.replace(/[^a-zA-Z0-9_-]/g,"_")}}}return{type:"iri",value:this.notePathToIRI(s.path).value}}return!r&&t.includes("://")?{type:"iri",value:t}:{type:"literal",value:t}}}async convertVault(){return(await this.convertVaultWithValidation({strict:!1})).triples}async convertVaultWithValidation(e={}){let t=this.vault.getAllFiles(),r=[],i=[],s=e.strict??!1;for(let a of t)try{let c=this.vault.getFrontmatter(a),l=c?this.validateExocortexAsset(c,a.basename):null;if(l){if(s)throw new Error(`Invariant violation in "${a.path}": ${l.message}`);i.push({path:a.path,reason:`Invariant violation: ${l.message}`}),this.logger.warn(`Skipping file with invariant violation: ${a.path}`,{code:l.code,property:l.property,reason:l.message});continue}let u=await this.convertNote(a);r.push(...u)}catch(c){let l=c instanceof Error?c.message:String(c);if(s)throw new Error(`Invalid IRI for file "${a.path}": ${l}`);i.push({path:a.path,reason:`Invalid IRI: ${l}`}),this.logger.warn(`Skipping file with invalid IRI: ${a.path}`,{reason:l})}return{triples:r,skippedFiles:i,summary:{total:t.length,indexed:t.length-i.length,skipped:i.length}}}static inferLabelFromBasename(e){return Wt.Namespace.fromPropertyKey(e)!==null?e:null}validateExocortexAsset(e,t){let r=o(d=>d==null?!0:typeof d=="string"?d.trim()==="":Array.isArray(d)?d.length===0||d.every(r):!1,"isEmpty");if(!("exo__Instance_class"in e||"exo__Asset_uid"in e))return null;let s=["exo__Asset_uid","exo__Instance_class"];for(let d of s){if(!(d in e))return{code:"MISSING_PROPERTY",property:d,message:`Required property "${d}" is missing`};if(r(e[d]))return{code:"EMPTY_PROPERTY",property:d,message:`Required property "${d}" is empty`}}let a=["ems__Effort_status","ems__Effort_parent","ems__Effort_lockedBy","ems__Effort_lockExpires","exo__Asset_updatedAt","ems__Effort_startTimestamp"];for(let d of a)if(d in e&&r(e[d]))return{code:"EMPTY_OPTIONAL_PROPERTY",property:d,message:`Optional property "${d}" is present but empty`};let c=e.exo__Instance_class,l=Array.isArray(c)?c:[c],u=null,f=!1;for(let d of l){if(typeof d!="string")continue;let h=this.removeQuotes(d),y=(this.extractWikilink(h)??h).trim();/^[a-z][a-zA-Z0-9]*__/.test(y)&&/[\s()]/.test(y)?u||(u={candidate:d}):f=!0}return u&&!f?{code:"INVALID_INSTANCE_CLASS_IRI",property:"exo__Instance_class",message:`Invalid Instance_class IRI: "${u.candidate}"`}:null}async validateVault(){let e=this.vault.getAllFiles(),t=[];for(let r of e){let i=(0,wx.vaultPathToIRI)(r.path);ka.IRI.isValidIRI(i)||t.push({path:r.path,reason:`Path "${r.path}" cannot be converted to a valid IRI`})}return t}notePathToIRI(e){return new ka.IRI((0,wx.vaultPathToIRI)(e))}isExocortexProperty(e){return Wt.Namespace.fromPropertyKey(e)!==null}propertyKeyToIRI(e){let t=Wt.Namespace.fromPropertyKey(e);if(!t)throw new Error(`Invalid property key: ${e}`);return t.namespace.term(t.localName)}emitTypeTripleForEnumInstance(e,t){let r=this.vault.getFrontmatter(t);if(!r)return;let i=r.exo__Instance_class,s=Array.isArray(i)?i[0]:i;if(typeof s!="string")return;let a=this.valueToClassURI(s);a instanceof ka.IRI&&(this.pendingExtraTriples.push(new ur.Triple(e,Wt.Namespace.RDF.term("type"),a)),this.pendingExtraTriples.push(new ur.Triple(e,Wt.Namespace.EXO.term("Instance_class"),a)))}async valueToRDFObject(e,t,r){if(typeof e=="string"){let i=this.removeQuotes(e),s=this.extractWikilink(i);if(s){let a=this.vault.getFirstLinkpathDest(s,t.path);if(a){let l=this.notePathToIRI(a.path),u=s.includes("|")?s.split("|")[0]:s;if(this.isUUID(u)){let d=new hn.Literal(u);if(r?.value.endsWith("#Grounding_targetValueRef")||r?.value.endsWith("#Grounding_targetValueSubstitution")||r?.value.endsWith("#Grounding_targetClass"))return[l];let p=this.expandClassValue(a.basename);if(p)return this.emitTypeTripleForEnumInstance(p,a),[p];let y=this.vault.getFrontmatter(a);if(y){let v=y.exo__Asset_label;if(typeof v=="string"){let w=this.expandClassValue(v);if(w)return this.emitTypeTripleForEnumInstance(w,a),[w]}}return r?.value.endsWith("#Asset_prototype")||r?.value.endsWith("/Asset_prototype")?[l,d]:[l]}let f=this.expandClassValue(a.basename);return f?(this.emitTypeTripleForEnumInstance(f,a),[f]):[l]}if(this.isClassReference(s)){let l=this.expandClassValue(s);if(l)return[l]}let c=s.includes("|")?s.split("|")[0]:s;return this.isUUID(c)?[this.notePathToIRI(`${c}.md`)]:[new hn.Literal(i)]}if(this.isClassReference(i)){let a=this.expandClassValue(i);if(a)return[a]}return this.isISO8601DateTime(i)?[new hn.Literal(i,Wt.Namespace.XSD.term("dateTime"))]:[new hn.Literal(i)]}return typeof e=="boolean"?[new hn.Literal(e.toString())]:typeof e=="number"?[new hn.Literal(e.toString(),Wt.Namespace.XSD.term("decimal"))]:e instanceof Date?[new hn.Literal(e.toISOString(),Wt.Namespace.XSD.term("dateTime"))]:[new hn.Literal(String(e))]}isISO8601DateTime(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})?$/.test(e)}removeQuotes(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.substring(1,t.length-1):e}extractWikilink(e){let t=e.match(/^\[\[([^\]]+)\]\]$/);if(!t)return null;let r=t[1];return r.includes("|")?r.split("|")[0]:r}extractWikilinkAlias(e){let t=e.match(/^\[\[([^\]]+)\]\]$/);if(!t)return null;let r=t[1],i=r.indexOf("|");return i>=0?r.substring(i+1).trim():null}valueToClassURI(e){if(typeof e!="string")return new hn.Literal(String(e));let t=this.removeQuotes(e),i=this.extractWikilink(t)||t,s=this.expandClassValue(i);if(s)return s;let a=this.extractWikilinkAlias(t);if(a){let c=this.expandClassValue(a);if(c)return c}if(this.isUUID(i)){let c=this.vault.getFirstLinkpathDest(i,"");if(c){let l=this.expandClassValue(c.basename);if(l)return l;let u=this.vault.getFrontmatter(c);if(u){let f=u.exo__Asset_label;if(typeof f=="string"){let d=this.expandClassValue(f);if(d)return d}}return this.notePathToIRI(c.path)}}return new hn.Literal(t)}isClassReference(e){return/\s/.test(e)?!1:Wt.Namespace.fromPropertyKey(e)!==null}isUUID(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}expandClassValue(e){let t=this.removeQuotes(e),r=Wt.Namespace.fromPropertyKey(t);return!r||/[\s()]/.test(r.localName)?null:r.namespace.term(r.localName)}extractBodyContent(e){let t=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;return e.replace(t,"")}extractBodyWikilinks(e){let t=new Set,r,i=new RegExp(this.BODY_WIKILINK_PATTERN.source,"g");for(;(r=i.exec(e))!==null;)r[1]&&t.add(r[1]);return Array.from(t)}async convertBodyWikilinks(e,t){let r=[];try{let i=await this.vault.read(e),s=this.extractBodyContent(i),a=this.extractBodyWikilinks(s),c=Wt.Namespace.EXO.term("Asset_bodyLink");for(let l of a){let u=this.vault.getFirstLinkpathDest(l,e.path);if(u){let f=this.notePathToIRI(u.path);r.push(new ur.Triple(t,c,f))}else if(this.isClassReference(l)){let f=this.expandClassValue(l);f?r.push(new ur.Triple(t,c,f)):r.push(new ur.Triple(t,c,new hn.Literal(l)))}else r.push(new ur.Triple(t,c,new hn.Literal(l)))}}catch{}return r}};ki.NoteToRDFConverter=sl;sl.SkippedFileInfo=class{constructor(n,e){this.path=n,this.reason=e}};sl.VaultValidationResult=class{constructor(n,e,t){this.triples=n,this.skippedFiles=e,this.summary=t}};sl.VaultValidationOptions=class{constructor(n=!1){this.strict=n}};ki.NoteToRDFConverter=sl=K8([(0,AS.injectable)(),_x(0,(0,AS.inject)(Sx.DI_TOKENS.IVaultAdapter)),_x(1,(0,AS.inject)(Sx.DI_TOKENS.ILogger)),Y8("design:paramtypes",[Object,Object])],sl)});var CS=b(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});Hp.FilterContainsOptimizer=void 0;var e$=Ee(),t$=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,IS=class{static{o(this,"FilterContainsOptimizer")}constructor(){this.tripleStore=null,this.lastOptimizationHints=[]}setTripleStore(e){this.tripleStore=e}getLastOptimizationHints(){return this.lastOptimizationHints}clearHints(){this.lastOptimizationHints=[]}async optimize(e){return this.clearHints(),this.optimizeRecursive(e)}optimizeSync(e,t){return this.clearHints(),this.optimizeSyncRecursive(e,t)}async optimizeRecursive(e){return e.type==="filter"?this.optimizeFilter(e):e.type==="join"?{type:"join",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="leftjoin"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="union"?{type:"union",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="minus"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="project"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="orderby"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="slice"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="distinct"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="reduced"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="group"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="extend"?{...e,input:await this.optimizeRecursive(e.input)}:e}optimizeSyncRecursive(e,t){return e.type==="filter"?this.optimizeFilterSync(e,t):e.type==="join"?{type:"join",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="leftjoin"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="union"?{type:"union",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="minus"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="project"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="orderby"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="slice"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="distinct"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="reduced"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="group"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="extend"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e}async optimizeFilter(e){let t=this.detectContainsUUIDPattern(e.expression);if(!t)return{type:"filter",expression:e.expression,input:await this.optimizeRecursive(e.input)};let r=[];return this.tripleStore&&(r=await this.findSubjectsContainingUUID(t.uuid)),this.rewriteFilter(e,t,r)}optimizeFilterSync(e,t){let r=this.detectContainsUUIDPattern(e.expression);if(!r)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input,t)};let i=t?t.filter(s=>s.includes(r.uuid)):[];return this.rewriteFilter(e,r,i)}rewriteFilter(e,t,r){if(this.lastOptimizationHints.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${t.variable}), "${t.uuid}"))`,suggestedRewrite:r.length===1?`VALUES ?${t.variable} { <${r[0]}> }`:r.length>1?`VALUES ?${t.variable} { ${r.map(i=>`<${i}>`).join(" ")} }`:"No matching URIs found for UUID",estimatedSpeedup:r.length>0?"O(n) \u2192 O(1)":"N/A",matchedUri:r.length===1?r[0]:void 0}),r.length===0)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input)};if(r.length===1){let i=this.injectSubjectConstraint(e.input,t.variable,r[0]);if(i!==e.input)return i}return this.createValuesJoin(e,t,r)}detectContainsUUIDPattern(e){if(e.type==="function"||e.type==="functionCall"){let t=e;if((typeof t.function=="string"?t.function.toLowerCase():t.function?.value?.toLowerCase()??"")==="contains"&&t.args.length===2)return this.analyzeContainsArgs(t.args[0],t.args[1],e)}if(e.type==="logical"&&e.operator==="&&")for(let t of e.operands){let r=this.detectContainsUUIDPattern(t);if(r)return r}return null}analyzeContainsArgs(e,t,r){let i=null;if(e.type==="function"||e.type==="functionCall"){let s=e;if((typeof s.function=="string"?s.function.toLowerCase():s.function?.value?.toLowerCase()??"")==="str"&&s.args.length===1){let c=s.args[0];c.type==="variable"&&(i=c.name)}}if(!i&&e.type==="variable"&&(i=e.name),!i)return null;if(t.type==="literal"){let c=String(t.value).match(t$);if(c)return{variable:i,uuid:c[0].toLowerCase(),originalExpression:r}}return null}async findSubjectsContainingUUID(e){if(!this.tripleStore)return[];if(this.tripleStore.findSubjectsByUUID)return(await this.tripleStore.findSubjectsByUUID(e)).map(s=>s.value);let t=await this.tripleStore.subjects(),r=[];for(let i of t)i instanceof e$.IRI&&i.value.toLowerCase().includes(e.toLowerCase())&&r.push(i.value);return r}injectSubjectConstraint(e,t,r){if(e.type==="bgp"){let i=e.triples.map(a=>a.subject.type==="variable"&&a.subject.value===t?{...a,subject:{type:"iri",value:r}}:a);if(i.some((a,c)=>a.subject!==e.triples[c].subject))return{type:"bgp",triples:i}}if(e.type==="join"){let i=this.injectSubjectConstraint(e.left,t,r),s=this.injectSubjectConstraint(e.right,t,r);if(i!==e.left||s!==e.right)return{type:"join",left:i,right:s}}if(e.type==="filter"){let i=this.injectSubjectConstraint(e.input,t,r);if(i!==e.input)return{...e,input:i}}return e}createValuesJoin(e,t,r){return{type:"join",left:{type:"values",variables:[t.variable],bindings:r.map(a=>({[t.variable]:{type:"iri",value:a}}))},right:this.optimizeSyncRecursive(e.input)}}analyzeQuery(e){let t=[];return this.analyzeRecursive(e,t),t}analyzeRecursive(e,t){if(e.type==="filter"){let r=this.detectContainsUUIDPattern(e.expression);r&&t.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${r.variable}), "${r.uuid}"))`,suggestedRewrite:`Use --optimize flag or rewrite as VALUES ?${r.variable} { <uri-containing-uuid> }`,estimatedSpeedup:"O(n) \u2192 O(1) with UUID index lookup"}),this.analyzeRecursive(e.input,t);return}e.type==="join"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="leftjoin"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="union"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="minus"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="project"?this.analyzeRecursive(e.input,t):e.type==="orderby"?this.analyzeRecursive(e.input,t):e.type==="slice"?this.analyzeRecursive(e.input,t):e.type==="distinct"?this.analyzeRecursive(e.input,t):e.type==="reduced"?this.analyzeRecursive(e.input,t):e.type==="group"?this.analyzeRecursive(e.input,t):e.type==="extend"&&this.analyzeRecursive(e.input,t)}};Hp.FilterContainsOptimizer=IS});var vx=b(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});Qp.AlgebraOptimizer=void 0;var r$=CS(),RS=class{static{o(this,"AlgebraOptimizer")}constructor(){this.stats=new Map,this.tripleStore=null,this.filterContainsOptimizer=new r$.FilterContainsOptimizer}setTripleStore(e){this.tripleStore=e,this.filterContainsOptimizer.setTripleStore(e)}getOptimizationHints(){return this.filterContainsOptimizer.getLastOptimizationHints()}analyzeQuery(e){return this.filterContainsOptimizer.analyzeQuery(e)}optimize(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),t=this.filterPushDown(t),t=this.joinReordering(t),t}async optimizeAsync(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),this.tripleStore&&(t=await this.filterContainsOptimizer.optimize(t)),t=this.filterPushDown(t),t=this.joinReordering(t),t}optimizeWithSubjects(e,t){let r=e;return r=this.eliminateEmptyBGPInFilterJoin(r),r=this.filterContainsOptimizer.optimizeSync(r,t),r=this.filterPushDown(r),r=this.joinReordering(r),r}eliminateEmptyBGPInFilterJoin(e){if(e.type==="join"){if(e.left.type==="filter"){let t=e.left;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.right)}}if(e.right.type==="filter"){let t=e.right;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.left)}}return{type:"join",left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}}return e.type==="filter"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="leftjoin"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="union"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="minus"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="project"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="orderby"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="slice"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="distinct"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e}filterPushDown(e){return e.type==="filter"?this.pushDownFilter(e):e.type==="join"?{type:"join",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="leftjoin"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="union"?{type:"union",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="minus"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="project"?{...e,input:this.filterPushDown(e.input)}:e.type==="orderby"?{...e,input:this.filterPushDown(e.input)}:e.type==="slice"?{...e,input:this.filterPushDown(e.input)}:e.type==="distinct"?{...e,input:this.filterPushDown(e.input)}:e}pushDownFilter(e){let t=e.input;if(t.type==="join"){let r=this.getFilterVariables(e.expression),i=this.getOperationVariables(t.left),s=this.getOperationVariables(t.right),a=r.every(l=>i.has(l)),c=r.every(l=>s.has(l));return a&&!c?{type:"join",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:this.filterPushDown(t.right)}:c&&!a?{type:"join",left:this.filterPushDown(t.left),right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:{type:"join",left:this.filterPushDown(t.left),right:this.filterPushDown(t.right)}}}return t.type==="union"?{type:"union",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:this.filterPushDown(t)}}getFilterVariables(e){let t=[];if(e.type==="variable")t.push(e.name);else if(e.type==="comparison")t.push(...this.getFilterVariables(e.left)),t.push(...this.getFilterVariables(e.right));else if(e.type==="logical")for(let r of e.operands)t.push(...this.getFilterVariables(r));else if(e.type==="function")for(let r of e.args)t.push(...this.getFilterVariables(r));return Array.from(new Set(t))}getOperationVariables(e){let t=new Set;if(e.type==="bgp")for(let r of e.triples)r.subject.type==="variable"&&t.add(r.subject.value),r.predicate.type==="variable"&&t.add(r.predicate.value),r.object.type==="variable"&&t.add(r.object.value);else if(e.type==="join"){let r=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...r,...i])}else{if(e.type==="filter")return this.getOperationVariables(e.input);if(e.type==="leftjoin"){let r=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...r,...i])}else if(e.type==="union"){let r=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...r,...i])}else{if(e.type==="minus")return this.getOperationVariables(e.left);if(e.type==="project")return new Set(e.variables)}}return t}joinReordering(e){return e.type==="join"?this.reorderJoin(e):e.type==="filter"?{...e,input:this.joinReordering(e.input)}:e.type==="leftjoin"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="union"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="minus"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="project"?{...e,input:this.joinReordering(e.input)}:e.type==="orderby"?{...e,input:this.joinReordering(e.input)}:e.type==="slice"?{...e,input:this.joinReordering(e.input)}:e.type==="distinct"?{...e,input:this.joinReordering(e.input)}:e}reorderJoin(e){let t=this.isConstrained(e.left),r=this.isConstrained(e.right);if(r&&!t)return{type:"join",left:this.joinReordering(e.right),right:this.joinReordering(e.left)};if(t&&!r)return{type:"join",left:this.joinReordering(e.left),right:this.joinReordering(e.right)};let i=this.estimateCost(e.left);return this.estimateCost(e.right)<i?{type:"join",left:this.joinReordering(e.right),right:this.joinReordering(e.left)}:{type:"join",left:this.joinReordering(e.left),right:this.joinReordering(e.right)}}isConstrained(e){return e.type==="values"?!0:e.type==="bgp"?e.triples.some(t=>t.object.type!=="variable"||t.subject.type!=="variable"):e.type==="filter"?this.isConstrained(e.input):e.type==="join"?this.isConstrained(e.left)||this.isConstrained(e.right):e.type==="union"?this.isConstrained(e.left)&&this.isConstrained(e.right):!1}estimateCost(e){if(e.type==="bgp"){let t=0;for(let r of e.triples){let i=10;r.subject.type==="variable"&&(i*=10),r.predicate.type==="variable"&&(i*=20),r.object.type==="variable"&&(i*=5),t+=i}return t}if(e.type==="filter")return this.estimateCost(e.input)*.3;if(e.type==="join"){let t=this.estimateCost(e.left),r=this.estimateCost(e.right);return e.left.type==="values"||e.right.type==="values"?Math.min(t,r)*2:t*r}if(e.type==="leftjoin")return this.estimateCost(e.left)+this.estimateCost(e.right)*.5;if(e.type==="union")return this.estimateCost(e.left)+this.estimateCost(e.right);if(e.type==="values"){let t=e.bindings;return Array.isArray(t)?t.length*5:10}return e.type==="minus"?this.estimateCost(e.left)+this.estimateCost(e.right)*.3:100}setStatistics(e,t){this.stats.set(e,t)}getStatistics(e){return this.stats.get(e)}};Qp.AlgebraOptimizer=RS});var Ex=b(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});Kp.AlgebraSerializer=void 0;var OS=class{static{o(this,"AlgebraSerializer")}toString(e,t=0){let r=" ".repeat(t);switch(e.type){case"bgp":return`${r}BGP [
372
372
  ${e.triples.map(u=>`${r} ${this.tripleToString(u)}`).join(`
373
373
  `)}
374
374
  ${r}]`;case"filter":return`${r}Filter(
@@ -761,7 +761,7 @@ ${r}`}o(nX,"serializeFile");function CD(n,e,t={}){let r=Ug.default.dirname(n),i=
761
761
  `).map(s=>s.trim()).filter(Boolean)){let s=iX.exec(i);if(s){r.push({sessionName:i,uuid:s[1],type:"full"});continue}let a=sX.exec(i);a&&r.push({sessionName:i,uuid:a[1],type:"short"})}return r}o(oX,"listClaudeChildSessions");function cX(n,e,t){let r=null,i=e.toLowerCase();function s(a){if(r)return;let c;try{c=(0,Wg.readdirSync)(a,{withFileTypes:!0})}catch{return}for(let l of c){if(r)return;if(l.name.startsWith(".")||l.name==="node_modules")continue;let u=(0,RD.join)(a,l.name);if(l.isDirectory())s(u);else if(l.name.endsWith(".md")){let f=l.name.slice(0,-3).toLowerCase();(t==="full"&&f===i||t==="short"&&f.startsWith(i))&&(r=u)}}}return o(s,"walk"),s(n),r}o(cX,"findVaultFile");function lX(n,e){try{let i=(e??(s=>(0,Wg.readFileSync)(s,"utf8")))(n).match(/ems__Effort_status\s*:.*\[\[([^\]]+)\]\]/);return i?i[1].includes(aX):!1}catch{return!1}}o(lX,"isTaskDoing");async function PD(n,e=qg.exec,t){let r=await oX(e),i=[];for(let s of r){let a=cX(n,s.uuid,s.type);if(!a){i.push({sessionName:s.sessionName,taskUuid:s.uuid,taskFilePath:null,reason:"vault task not found"});continue}lX(a,t)||i.push({sessionName:s.sessionName,taskUuid:s.uuid,taskFilePath:a,reason:"vault task status != Doing"})}return i}o(PD,"detectOrphans");async function FD(n,e,t=qg.exec,r=CD){let i=OD(t);if(e)return{ok:!0};let s=new Date().toISOString();if(n.taskFilePath)try{r(n.taskFilePath,{ems__Effort_status:"[[ems__EffortStatusFailed]]",aiTask__Task_lastError:`orphan recovery: ${n.reason}`,exo__Asset_updatedAt:s})}catch(a){return{ok:!1,error:`vault update failed: ${a.message}`}}try{await i(`tmux kill-session -t ${JSON.stringify(n.sessionName)}`)}catch{}return{ok:!0}}o(FD,"recoverOrphan");function uX(){return process.env.EXOCORTEX_VAULT??(0,Gg.join)((0,ND.homedir)(),"vault-2025")}o(uX,"defaultVault");function LD(){return new Ie("recover").description("Detect and recover orphaned claude-child tmux sessions. A session is orphaned when the corresponding vault task is not in Doing status. Default mode: dry-run (no changes). Use --apply to perform recovery.").option("--vault <path>","Path to Obsidian vault",uX()).option("--dry-run","List orphans without applying changes (default)",!1).option("--apply","Apply orphan recovery: set Failed + kill tmux session",!1).action(async n=>{let e=(0,Gg.resolve)(n.vault);if(!(0,DD.existsSync)(e)){console.error(`[recover] vault not found: ${e}`),process.exitCode=1;return}let t=!n.apply;console.log(`[recover] vault=${e} mode=${t?"dry-run":"apply"}`);let r=await PD(e);if(r.length===0){console.log("[recover] No orphaned claude-child sessions found.");return}console.log(`[recover] Found ${r.length} orphan(s):`);for(let a of r){let c=a.taskFilePath??"(not found in vault)";console.log(` session=${a.sessionName} uuid=${a.taskUuid} reason=${a.reason}`),console.log(` file=${c}`)}if(t){console.log("[recover] Dry-run mode: no changes applied. Use --apply to recover.");return}let i=0,s=0;for(let a of r){let c=await FD(a,!1);c.ok?(i++,console.log(`[recover] RECOVERED: ${a.sessionName}`)):(s++,console.error(`[recover] ERROR recovering ${a.sessionName}: ${c.error}`))}console.log(`[recover] Done: recovered=${i} errors=${s}`),s>0&&(process.exitCode=1)})}o(LD,"recoverCommand");var _2=require("fs"),zg=require("path"),Gn=ce(fr());function fX(n,e){return e.concat([n])}o(fX,"collectAlso");var dX="https://exocortex.my/ontology/find#Alias_sparql",hX="https://exocortex.my/ontology/exo#Asset_label";function Yl(n){if(n&&typeof n=="object"&&"value"in n){let e=n.value;return typeof e=="string"?e:String(e)}return String(n)}o(Yl,"nodeValue");async function pX(n,e){let t=await n.match(void 0,void 0,void 0),r=[];for(let s of t)Yl(s.predicate)!==hX||Yl(s.object)!==e||r.push(Yl(s.subject));if(r.length===0)return null;let i=[];for(let s of r)for(let a of t)Yl(a.predicate)===dX&&Yl(a.subject)===s&&i.push(Yl(a.object));if(i.length===0)return null;if(i.length>1)throw new Bt(`Ambiguous find__Alias "${e}" \u2014 ${i.length} instances define a sparql fragment`,`Ensure exactly one find__Alias asset has exo:Asset_label "${e}"`);return i[0]}o(pX,"resolveAliasFragment");var mX=/^([a-z][a-zA-Z0-9]*)__([A-Za-z0-9_]+)$/,gX="https://exocortex.my/ontology/";function yX(n,e){let t=mX.exec(e);if(t){let i=`<${gX}${t[1]}#${t[2]}>`;return n.replace(/\?value\b/g,i)}let r=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return n.replace(/\?value\b/g,`"${r}"`)}o(yX,"bindValueLiteral");function kD(){return new Ie("find").description("Find vault assets via SPARQL \u2014 outputs file paths one per line (RFC 8e83442b T1.1)").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--also <path>","Additional vault to include (repeatable)",fX,[]).option("--sparql <query>","SPARQL SELECT query (must bind ?path)").option("--class <value>","Filter by class label via find__Alias 'class' (e.g. ems__Task)").action(async n=>{pe.setFormat("text");try{if(n.sparql&&n.class)throw new Bt("--sparql and --class are mutually exclusive","Pass either a raw --sparql query or a find__Alias-backed flag like --class");if(!n.sparql&&!n.class)throw new Bt("one of --sparql <query> or --class <value> is required",'exocortex find --class ems__Task OR exocortex find --sparql "SELECT ?path WHERE { ... }"');let e=(0,zg.resolve)(n.vault);if(!(0,_2.existsSync)(e))throw new Fe(e);let t=new kt(e),i=await new Gn.NoteToRDFConverter(t).convertVault(),s=n.also||[];for(let w of s){let T=(0,zg.resolve)(w);if(!(0,_2.existsSync)(T))throw new Fe(T);let C=new kt(T),L=await new Gn.NoteToRDFConverter(C).convertVault();i=i.concat(L)}let a=new Gn.InMemoryTripleStore;await a.addAll(i);let c;if(n.class){let w=await pX(a,"class");if(w===null)throw new Bt('No find__Alias with exo:Asset_label "class" was found in the vault',"Seed a find__Alias asset (label=class) or fall back to exocortex find --sparql");c=`SELECT ?path WHERE { ${yX(w,n.class)} }`}else c=n.sparql;let l=ql(c);l=Xa(l);let u=new Gn.ExoQLParser,f=Ja(Ya(e));for(let w of s){let T=Ja(Ya((0,zg.resolve)(w)));for(let[C,V]of T)f.has(C)||f.set(C,V)}f.size>0&&u.setVaultPrefixes(f);let d=u.parse(l),p=new Gn.ExoQLAlgebraTranslator().translate(d);p.type!=="construct"&&(p=new Gn.AlgebraOptimizer().optimize(p));let S=await new Gn.ExoQLQueryExecutor(a).executeAll(p),v="obsidian://vault/";for(let w of S){let C=w.toJSON().path;if(typeof C!="string"||!C.startsWith(v))continue;let V=C.slice(v.length),L;try{L=decodeURIComponent(V)}catch{L=V}process.stdout.write(L+`
762
762
  `)}}catch(e){pe.handle(e),process.exit(5)}})}o(kD,"findCommand");var w2=require("fs"),v2=require("path"),De=ce(fr());var UD=ce(fr()),Ft=ce($D());var VD="obsidian://vault/";function OX(n){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return{async resolveTargetPath(t){if(!t)throw new Error("Cannot resolve empty targetIRI to a vault path");let r=t;if(r.startsWith(VD))r=decodeURI(r.slice(VD.length));else if(e.test(r)){let i=await n.findFileByUID(r);if(!i)throw new Error(`No vault file found for UID: ${r}`);r=i}if(r.endsWith(".md")||(r=`${r}.md`),!await n.fileExists(r))throw new Error(`Cannot resolve target file for IRI "${t}" (tried "${r}")`);return r}}}o(OX,"createCliPathResolver");var PX=["openFile","sparqlSelect","getActiveFileIRI","getActiveFilePath","trashFile","duplicateFile"],S2=class extends Error{constructor(t){super(`Service "${t}" is not implemented in the CLI (no-op stub). dyncommand exec on this service_call grounding cannot change vault state. See CLI parity issues #2865-#2868 for port status.`);this.serviceId=t;this.name="CliServiceNotImplementedError"}static{o(this,"CliServiceNotImplementedError")}};function BD(n){return{async execute(){throw new S2(n)}}}o(BD,"notImplementedService");function FX(n){return e=>{let t=n.getFirstLinkpathDest(e,"");if(!t||!("basename"in t))return null;let i=n.getFrontmatter(t)?.exo__Asset_label;return typeof i=="string"&&i.length>0?i:null}}o(FX,"createCliClassResolver");function qD(n,e){for(let t of PX)n.register(t,BD(t));for(let t of["updateProperty","removeProperty","setStatus","createAsset"])n.register(t,BD(t));if(e){if(e.fsAdapter){let t=new UD.FrontmatterService,r=OX(e.fsAdapter);n.register("updateProperty",(0,Ft.createUpdatePropertyService)(e.fsAdapter,t,r)),n.register("removeProperty",(0,Ft.createRemovePropertyService)(e.fsAdapter,t,r)),n.register("setStatus",(0,Ft.createSetStatusService)(e.fsAdapter,t,r)),n.register("createAsset",(0,Ft.createCreateAssetService)(e.vaultAdapter,e.fsAdapter,FX(e.vaultAdapter)))}n.register("createRelatedTask",(0,Ft.createCreateRelatedTaskService)(e.vaultAdapter,e.genericAssetCreationService)),n.register("createRelatedProject",(0,Ft.createCreateRelatedProjectService)(e.vaultAdapter,e.genericAssetCreationService)),n.register("archiveAsset",(0,Ft.createArchiveAssetService)(e.vaultAdapter,e.archiveAssetService)),n.register("planForEvening",(0,Ft.createPlanForEveningService)(e.vaultAdapter,e.taskStatusService)),n.register("cleanProperties",(0,Ft.createCleanPropertiesService)(e.vaultAdapter,e.propertyCleanupService)),n.register("renameToUid",(0,Ft.createRenameToUidService)(e.vaultAdapter,e.renameToUidService)),n.register("repairFolder",(0,Ft.createRepairFolderService)(e.vaultAdapter,e.folderRepairService)),n.register("fixMissingLabel",(0,Ft.createFixMissingLabelService)(e.vaultAdapter,e.fixMissingLabelService))}}o(qD,"populateCliServiceRegistry");var DX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function NX(){if(process.stdin.isTTY)return[];let n=[];for await(let t of process.stdin)n.push(t);return Buffer.concat(n).toString("utf-8").split(`
763
763
  `).map(t=>t.trim()).filter(t=>t.length>0)}o(NX,"readStdinLines");function Qg(n){if(n&&typeof n=="object"&&"value"in n){let e=n.value;return typeof e=="string"?e:String(e)}return String(n)}o(Qg,"nodeValue");async function LX(n,e){let t=new De.IRI("https://exocortex.my/ontology/exocmd#Command_cliName"),r=await n.match(void 0,t,void 0),i=[];for(let s of r)if(Qg(s.object)===e){let l=Qg(s.subject).match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.md$/i);l&&i.push(l[1])}if(i.length===0)return null;if(i.length>1)throw new Bt(`Ambiguous cliName "${e}" \u2014 resolves to ${i.length} commands: ${i.join(", ")}`,"Use the UUID directly: exocortex apply <uuid> <path>");return i[0]}o(LX,"resolveSlugToUuid");async function kX(n,e){let t=new De.IRI("https://exocortex.my/ontology/exocmd#Command_destructive"),r=await n.match(void 0,t,void 0);for(let i of r)if(Qg(i.subject).includes(e)){let a=Qg(i.object);if(a==="true"||a==="True")return!0}return!1}o(kX,"isDestructive");async function jX(n,e,t,r,i,s,a){let c=(0,v2.resolve)(n,r);if(!(0,w2.existsSync)(c))return console.error(`\u274C Target file not found: ${r}`),!1;let u=await new De.CommandResolver(e).loadCommand(t);if(!u)return console.error(`\u274C Command with UID "${t}" not found.`),!1;if(await kX(e,t)&&!i.dryRun&&!i.yes)return console.error(`\u274C Command "${u.name}" is marked destructive. Add --dry-run to preview, or --yes to apply.`),!1;let d=(0,De.vaultPathToIRI)(r);if(!await new De.PreconditionEvaluator(e,void 0,{clock:s}).evaluate(u.precondition,d))return console.error(`\u274C Precondition not satisfied for "${u.name}" on "${r}".`),!1;if(i.dryRun)return console.log(`\u{1F50D} Dry-run: would apply "${u.name}" to "${r}" (precondition passed).`),!0;let y=new De.ServiceRegistry,S=new kt(n),v=new De.GenericAssetCreationService(S).withDeterminism({clock:s,uidGenerator:a}),w=new De.ArchiveAssetService(S),T=new De.PropertyCleanupService(S),C=new De.FixMissingLabelService(S),V=new De.RenameToUidService(S),L=new De.FolderRepairService(S),ee=new De.TaskStatusService(S,new De.EffortStatusWorkflow,new De.StatusTimestampService(S)),B=new pr(n);qD(y,{vaultAdapter:S,fsAdapter:B,genericAssetCreationService:v,archiveAssetService:w,taskStatusService:ee,propertyCleanupService:T,fixMissingLabelService:C,renameToUidService:V,folderRepairService:L});let W=new De.GroundingExecutor(B,B,y,void 0,{clock:s,uidGenerator:a}),F;if(i.input)try{let G=JSON.parse(i.input);if(typeof G!="object"||G===null||Array.isArray(G))throw new Error("must be a JSON object");F=G}catch(G){let Re=G instanceof Error?G.message:String(G);return console.error(`\u274C --input: invalid JSON object (${Re})`),!1}let D=await W.execute(u.grounding,d,r,F);if(D.success){let G=u.successMessage??`Applied "${u.name}" to "${r}".`;return console.log(`\u2705 ${G}`),!0}else return console.error(`\u274C "${u.name}" failed on "${r}": ${D.error}`),!1}o(jX,"executeOnTarget");function WD(){return new Ie("apply").description("Apply an exocmd__Command to one or more vault assets (RFC 8e83442b T1.2). Pass a path arg or pipe paths via stdin.").argument("<cmd>","Command UUID or cliName slug").argument("[path]","Vault-relative path to target asset (omit to read paths from stdin)").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--dry-run","Preview without writing").option("--yes","Skip destructive-command confirmation").option("--input <json>","JSON userInput for service_call groundings").option("--seed <uuid>","Deterministic UID seed for test/replay (uses seededUidGenerator)").option("--frozen-clock <iso>","Freeze clock to ISO timestamp for test/replay (uses frozenClock)").action(async(n,e,t)=>{pe.setFormat("text");try{let r=(0,v2.resolve)(t.vault);if(!(0,w2.existsSync)(r))throw new Fe(r);let i=t.frozenClock?(0,De.frozenClock)(t.frozenClock):(0,De.liveClock)(),s=t.seed?(0,De.seededUidGenerator)(t.seed):(0,De.liveUidGenerator)(),a=new kt(r),l=await new De.NoteToRDFConverter(a).convertVault(),u=new De.InMemoryTripleStore;await u.addAll(l);let f;if(DX.test(n))f=n;else{let y=await LX(u,n);y||(console.error(`\u274C No command found with UUID or cliName "${n}".`),process.exit(3)),f=y}let d;if(e)d=[e];else if(d=await NX(),d.length===0)throw new Bt("No target path provided and stdin is empty.","exocortex apply <uuid> <path> OR exocortex find ... | exocortex apply <uuid>");let h=0,p=0;for(let y of d)await jX(r,u,f,y,t,i,s)?h++:p++;d.length>1&&console.log(`
764
- \u{1F4CA} Applied to ${h}/${d.length} target(s) (${p} failed).`),p>0&&process.exit(5)}catch(r){pe.handle(r),process.exit(5)}})}o(WD,"applyCommand");function GD(n){let e=new Ie;return e.name("exocortex").description("CLI tool for Exocortex knowledge management system").version(n??"16.20.1"),e.addCommand(kD()),e.addCommand(WD()),e.addCommand(pF()),e.addCommand(_F()),e.addCommand(qF()),e.addCommand(wF()),e.addCommand(vF()),e.addCommand(IF()),e.addCommand(zF()),e.addCommand(eD()),e.addCommand(nD()),e.addCommand(iD()),e.addCommand(aD()),e.addCommand(yD()),e.addCommand(_D()),e.addCommand(AD()),e.addCommand(LD()),e}o(GD,"createProgram");GD().parse();0&&(module.exports={createProgram});
764
+ \u{1F4CA} Applied to ${h}/${d.length} target(s) (${p} failed).`),p>0&&process.exit(5)}catch(r){pe.handle(r),process.exit(5)}})}o(WD,"applyCommand");function GD(n){let e=new Ie;return e.name("exocortex").description("CLI tool for Exocortex knowledge management system").version(n??"16.20.2"),e.addCommand(kD()),e.addCommand(WD()),e.addCommand(pF()),e.addCommand(_F()),e.addCommand(qF()),e.addCommand(wF()),e.addCommand(vF()),e.addCommand(IF()),e.addCommand(zF()),e.addCommand(eD()),e.addCommand(nD()),e.addCommand(iD()),e.addCommand(aD()),e.addCommand(yD()),e.addCommand(_D()),e.addCommand(AD()),e.addCommand(LD()),e}o(GD,"createProgram");GD().parse();0&&(module.exports={createProgram});
765
765
  /*! Bundled license information:
766
766
 
767
767
  reflect-metadata/Reflect.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kitelev/exocortex-cli",
3
- "version": "16.20.1",
3
+ "version": "16.20.2",
4
4
  "description": "CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more",
5
5
  "main": "dist/index.js",
6
6
  "bin": {