@kitelev/exocortex-cli 15.90.8 → 15.90.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @kitelev/exocortex-cli v15.90.
|
|
2
|
+
// @kitelev/exocortex-cli v15.90.9
|
|
3
3
|
// CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
|
|
4
4
|
// License: MIT
|
|
5
5
|
|
|
@@ -65,7 +65,7 @@ ${r}}`}default:throw new Dc(`Unsupported operation type for SPARQL generation: $
|
|
|
65
65
|
`)}generateTriple(e){let t=this.generateElement(e.subject),r=this.generatePredicate(e.predicate),i=this.generateElement(e.object);return`${t} ${r} ${i}`}generatePredicate(e){return"pathType"in e?this.generatePropertyPath(e):this.generateElement(e)}generatePropertyPath(e){let t=e.items.map(r=>"pathType"in r?`(${this.generatePropertyPath(r)})`:`<${r.value}>`);switch(e.pathType){case"/":return t.join("/");case"|":return t.join("|");case"^":return`^${t[0]}`;case"+":return`${t[0]}+`;case"*":return`${t[0]}*`;case"?":return`${t[0]}?`}}generateElement(e){switch(e.type){case"variable":return`?${e.value}`;case"iri":return`<${e.value}>`;case"literal":{let r=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`;return e.language?r+=`@${e.language}`:e.datatype&&(r+=`^^<${e.datatype}>`),r}case"blank":return`_:${e.value}`;default:throw new Dc(`Unknown element type: ${e.type}`)}}generateValues(e,t){let r=" ".repeat(t);if(e.variables.length===0||e.bindings.length===0)return"";if(e.variables.length===1){let a=e.variables[0],c=e.bindings.map(l=>{let u=l[a];return u?this.generateValuesTerm(u):"UNDEF"}).join(" ");return`${r}VALUES ?${a} { ${c} }`}let i=e.variables.map(a=>`?${a}`).join(" "),s=e.bindings.map(a=>`(${e.variables.map(l=>{let u=a[l];return u?this.generateValuesTerm(u):"UNDEF"}).join(" ")})`);return`${r}VALUES (${i}) {
|
|
66
66
|
${s.map(a=>`${r} ${a}`).join(`
|
|
67
67
|
`)}
|
|
68
|
-
${r}}`}generateValuesTerm(e){if(e.type==="iri")return`<${e.value}>`;let r=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return e.language?r+=`@${e.language}`:e.datatype&&(r+=`^^<${e.datatype}>`),r}generateExpression(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e.value=="boolean"?e.value?"true":"false":String(e.value);case"comparison":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"logical":return e.operator==="!"?`!(${this.generateExpression(e.operands[0])})`:`(${e.operands.map(t=>this.generateExpression(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"function":return`${e.function.toUpperCase()}(${e.args.map(t=>this.generateExpression(t)).join(", ")})`;case"functionCall":return`${(typeof e.function=="string"?e.function:e.function.value).toUpperCase()}(${e.args.map(r=>this.generateExpression(r)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.generateWhereClause(e.pattern,0)} }`;case"in":{let t=this.generateExpression(e.expression),r=e.list.map(i=>this.generateExpression(i)).join(", ");return e.negated?`${t} NOT IN (${r})`:`${t} IN (${r})`}default:throw new Dc(`Unknown expression type: ${e.type}`)}}collectVariablesFromOperation(e,t){switch(e.type){case"bgp":for(let r of e.triples)this.collectVariablesFromTriple(r,t);break;case"filter":this.collectVariablesFromOperation(e.input,t),this.collectVariablesFromExpression(e.expression,t);break;case"join":case"leftjoin":case"union":case"minus":this.collectVariablesFromOperation(e.left,t),this.collectVariablesFromOperation(e.right,t);break;case"values":for(let r of e.variables)t.add(r);break;case"project":for(let r of e.variables)t.add(r);this.collectVariablesFromOperation(e.input,t);break;case"extend":t.add(e.variable),this.collectVariablesFromOperation(e.input,t);break;case"orderby":case"slice":case"distinct":case"reduced":this.collectVariablesFromOperation(e.input,t);break;case"group":for(let r of e.variables)t.add(r);for(let r of e.aggregates)t.add(r.variable);this.collectVariablesFromOperation(e.input,t);break;case"subquery":this.collectVariablesFromOperation(e.query,t);break}}collectVariablesFromTriple(e,t){e.subject.type==="variable"&&t.add(e.subject.value),"type"in e.predicate&&e.predicate.type==="variable"&&t.add(e.predicate.value),e.object.type==="variable"&&t.add(e.object.value)}collectVariablesFromExpression(e,t){switch(e.type){case"variable":t.add(e.name);break;case"comparison":case"arithmetic":this.collectVariablesFromExpression(e.left,t),this.collectVariablesFromExpression(e.right,t);break;case"logical":for(let r of e.operands)this.collectVariablesFromExpression(r,t);break;case"function":case"functionCall":for(let r of e.args)this.collectVariablesFromExpression(r,t);break;case"exists":this.collectVariablesFromOperation(e.pattern,t);break;case"in":this.collectVariablesFromExpression(e.expression,t);for(let r of e.list)this.collectVariablesFromExpression(r,t);break}}};Fc.SPARQLGenerator=q1});var wu=v(yn=>{"use strict";var rM=yn&&yn.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(n,r,i)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),nM=yn&&yn.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),KT=yn&&yn.__importStar||(function(){var n=o(function(e){return n=Object.getOwnPropertyNames||function(t){var r=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[r.length]=i);return r},n(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=n(e),i=0;i<r.length;i++)r[i]!=="default"&&rM(t,e,r[i]);return nM(t,e),t}})();Object.defineProperty(yn,"__esModule",{value:!0});yn.QueryExecutor=yn.ExoQLQueryExecutor=yn.QueryExecutorError=void 0;var iM=h1(),sM=Gh(),aM=I1(),oM=P1(),cM=VT(),lM=BT(),uM=GT(),fM=V1(),dM=HT(),hM=YT(),pM=XT(),mM=xe(),Nc=class extends Error{static{o(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};yn.QueryExecutorError=Nc;var ep=class{static{o(this,"ExoQLQueryExecutor")}constructor(e,t={}){this.tripleStore=e,this.bgpExecutor=new iM.BGPExecutor(e),this.filterExecutor=new sM.FilterExecutor,this.optionalExecutor=new aM.OptionalExecutor,this.unionExecutor=new oM.UnionExecutor,this.minusExecutor=new cM.MinusExecutor,this.valuesExecutor=new lM.ValuesExecutor,this.aggregateExecutor=new uM.AggregateExecutor,this.constructExecutor=new fM.ConstructExecutor,this.serviceExecutor=new dM.ServiceExecutor(t.serviceConfig),this.graphExecutor=new hM.GraphExecutor(e),this.sparqlGenerator=new pM.SPARQLGenerator,this.filterExecutor.setExistsEvaluator(async(r,i)=>this.evaluateExistsPattern(r,i)),this.filterExecutor.setTripleStore(e)}async evaluateExistsPattern(e,t){for await(let r of this.execute(e))if(t.merge(r)!==null)return!0;return!1}async executeAll(e){let t=[];for await(let r of this.execute(e))t.push(r);return t}async*execute(e){switch(e.type){case"bgp":yield*this.executeBGP(e);break;case"filter":yield*this.executeFilter(e);break;case"join":yield*this.executeJoin(e);break;case"leftjoin":yield*this.executeLeftJoin(e);break;case"union":yield*this.executeUnion(e);break;case"minus":yield*this.executeMinus(e);break;case"values":yield*this.executeValues(e);break;case"project":yield*this.executeProject(e);break;case"orderby":yield*this.executeOrderBy(e);break;case"slice":yield*this.executeSlice(e);break;case"distinct":yield*this.executeDistinct(e);break;case"reduced":yield*this.executeReduced(e);break;case"group":yield*this.executeGroup(e);break;case"extend":yield*this.executeExtend(e);break;case"subquery":yield*this.executeSubquery(e);break;case"lateraljoin":yield*this.executeLateralJoin(e);break;case"service":yield*this.executeService(e);break;case"graph":yield*this.executeGraph(e);break;default:throw new Nc(`Unknown operation type: ${e.type}`)}}async*executeBGP(e){yield*this.bgpExecutor.execute(e)}async*executeFilter(e){let t=this.execute(e.input);yield*this.filterExecutor.execute(e,t)}async*executeJoin(e){let t=[];for await(let a of this.execute(e.left))t.push(a);if(t.length===0)return;let r=new Set;for(let a of t)for(let c of a.variables())r.add(c);let i=this.collectOperationVariables(e.right);if([...r].some(a=>i.has(a)))for(let a of t){let c=this.substituteVariables(e.right,a);for await(let l of this.execute(c)){let u=a.merge(l);u!==null&&(yield u)}}else{let a=[];for await(let c of this.execute(e.right))a.push(c);for(let c of t)for(let l of a){let u=c.merge(l);u!==null&&(yield u)}}}async*executeLeftJoin(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let r=[];for await(let a of this.execute(e.right))r.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of r)yield a}o(s,"rightGen"),yield*this.optionalExecutor.execute(i(),s())}async*executeUnion(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let r=[];for await(let a of this.execute(e.right))r.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of r)yield a}o(s,"rightGen"),yield*this.unionExecutor.execute(i(),s())}async*executeMinus(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let r=[];for await(let a of this.execute(e.right))r.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of r)yield a}o(s,"rightGen"),yield*this.minusExecutor.execute(i(),s())}async*executeValues(e){yield*this.valuesExecutor.execute(e)}async*executeProject(e){let{SolutionMapping:t}=await Promise.resolve().then(()=>KT(Gi())),r=new Set(e.variables);for await(let i of this.execute(e.input)){let s=new t;for(let a of i.variables())if(r.has(a)){let c=i.get(a);c!==void 0&&s.set(a,c)}yield s}}async*executeOrderBy(e){let t=[];for await(let r of this.execute(e.input))t.push(r);t.sort((r,i)=>{for(let s of e.comparators){let a=this.getExpressionValue(s.expression,r),c=this.getExpressionValue(s.expression,i),l=0;if(a===void 0&&c===void 0?l=0:a===void 0?l=1:c===void 0?l=-1:typeof a=="number"&&typeof c=="number"?l=a-c:l=String(a).localeCompare(String(c)),s.descending&&(l=-l),l!==0)return l}return 0});for(let r of t)yield r}async*executeSlice(e){let t=0,r=e.offset??0,i=e.limit;for await(let s of this.execute(e.input)){if(t>=r){if(i!==void 0&&t-r>=i)break;yield s}t++}}async*executeDistinct(e){let t=new Set;for await(let r of this.execute(e.input)){let i=this.getSolutionKey(r);t.has(i)||(t.add(i),yield r)}}async*executeReduced(e){let t=new Set;for await(let r of this.execute(e.input)){let i=this.getSolutionKey(r);t.has(i)||(t.add(i),yield r)}}async*executeGroup(e){let t=[];for await(let i of this.execute(e.input))t.push(i);let r=this.aggregateExecutor.execute(e,t);if(e.having&&e.having.length>0)for(let i of r)e.having.every(a=>this.filterExecutor.evaluateExpression(a,i)===!0)&&(yield i);else for(let i of r)yield i}async*executeExtend(e){for await(let t of this.execute(e.input)){let r=t.clone(),i=this.evaluateExtendExpression(e.expression,t);i!==void 0&&r.set(e.variable,i),yield r}}async*executeSubquery(e){yield*this.execute(e.query)}async*executeLateralJoin(e){let t=[];for await(let r of this.execute(e.left))t.push(r);for(let r of t){let i=this.substituteVariables(e.right,r);for await(let s of this.execute(i)){let a=r.merge(s);a!==null&&(yield a)}}}substituteVariables(e,t){let r=JSON.parse(JSON.stringify(e));return this.substituteInOperation(r,t)}substituteInOperation(e,t){if(!e||typeof e!="object")return e;let r=e;return e.type==="bgp"&&e.triples?(e.triples=e.triples.map(i=>this.substituteInTriple(i,t)),e):(r.input&&(r.input=this.substituteInOperation(r.input,t)),r.left&&(r.left=this.substituteInOperation(r.left,t)),r.right&&(r.right=this.substituteInOperation(r.right,t)),r.pattern&&(r.pattern=this.substituteInOperation(r.pattern,t)),r.query&&(r.query=this.substituteInOperation(r.query,t)),r.where&&(r.where=this.substituteInOperation(r.where,t)),r.expression&&this.substituteInExpression(r.expression,t),e)}substituteInExpression(e,t){if(!(!e||typeof e!="object")){if(e.type==="exists"&&e.pattern&&(e.pattern=this.substituteInOperation(e.pattern,t)),e.left&&this.substituteInExpression(e.left,t),e.right&&this.substituteInExpression(e.right,t),e.operands)for(let r of e.operands)this.substituteInExpression(r,t);if(e.args)for(let r of e.args)this.substituteInExpression(r,t);if(e.expression&&this.substituteInExpression(e.expression,t),e.list)for(let r of e.list)this.substituteInExpression(r,t)}}substituteInTriple(e,t){return{subject:this.substituteInTripleElement(e.subject,t),predicate:e.predicate,object:this.substituteInTripleElement(e.object,t)}}substituteInTripleElement(e,t){if(e&&e.type==="variable"){let r=t.get(e.value);if(r!=null){let i=r;if(r instanceof mM.IRI||i.termType==="NamedNode")return{type:"iri",value:r.value};if(i.termType==="Literal"||typeof i.value=="string")return{type:"literal",value:i.value,datatype:i.datatype?.value??i._datatype?.value,language:i.language??i._language}}}return e}async*executeService(e){yield*this.serviceExecutor.execute(e,t=>this.sparqlGenerator.generateSelect(t))}async*executeGraph(e){let t=async function*(r,i){let s=this.currentGraphContext;this.currentGraphContext=i;try{r.type==="bgp"&&i&&this.tripleStore.matchInGraph?yield*this.executeBGPInGraph(r,i):yield*this.execute(r)}finally{this.currentGraphContext=s}}.bind(this);yield*this.graphExecutor.execute(e,t)}async*executeBGPInGraph(e,t){if(e.triples.length===0){let{SolutionMapping:r}=await Promise.resolve().then(()=>KT(Gi()));yield new r;return}yield*this.bgpExecutor.executeInGraph(e,t)}evaluateExtendExpression(e,t){if(e.type!=="aggregate")try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}getExpressionValue(e,t){if(e.type==="variable"){let r=t.get(e.name);return r?r.value??r.id??String(r):void 0}if(e.type==="literal")return e.value}collectOperationVariables(e){let t=new Set;return this.collectVarsFromOperation(e,t),t}collectVarsFromOperation(e,t){if(!e||typeof e!="object")return;let r=e;if(r.type==="bgp"&&r.triples)for(let i of r.triples)this.collectVarsFromElement(i.subject,t),i.predicate?.type!=="path"&&this.collectVarsFromElement(i.predicate,t),this.collectVarsFromElement(i.object,t);if(r.type==="values"&&r.variables)for(let i of r.variables)t.add(i);r.expression&&this.collectVarsFromExpressionTree(r.expression,t),r.type==="extend"&&r.variable&&t.add(r.variable),r.input&&this.collectVarsFromOperation(r.input,t),r.left&&this.collectVarsFromOperation(r.left,t),r.right&&this.collectVarsFromOperation(r.right,t),r.pattern&&this.collectVarsFromOperation(r.pattern,t),r.query&&this.collectVarsFromOperation(r.query,t),r.where&&this.collectVarsFromOperation(r.where,t)}collectVarsFromElement(e,t){if(!e||typeof e!="object")return;let r=e;r.type==="variable"&&t.add(r.value),r.type==="quoted"&&(this.collectVarsFromElement(r.subject,t),this.collectVarsFromElement(r.predicate,t),this.collectVarsFromElement(r.object,t))}collectVarsFromExpressionTree(e,t){if(!e||typeof e!="object")return;let r=e;if(r.type==="variable"&&r.name&&t.add(r.name),r.type==="exists"&&r.pattern&&this.collectVarsFromOperation(r.pattern,t),r.left&&this.collectVarsFromExpressionTree(r.left,t),r.right&&this.collectVarsFromExpressionTree(r.right,t),r.operands)for(let i of r.operands)this.collectVarsFromExpressionTree(i,t);if(r.args)for(let i of r.args)this.collectVarsFromExpressionTree(i,t);if(r.expression&&this.collectVarsFromExpressionTree(r.expression,t),r.list)for(let i of r.list)this.collectVarsFromExpressionTree(i,t)}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}isConstructQuery(e){return e.type==="construct"}async executeConstruct(e){if(e.type!=="construct")throw new Nc("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}isAskQuery(e){return e.type==="ask"}async executeAsk(e){if(e.type!=="ask")throw new Nc("executeAsk requires an ASK operation");for await(let t of this.execute(e.where))return!0;return!1}};yn.ExoQLQueryExecutor=ep;yn.QueryExecutor=ep});var JT=v(Rs=>{"use strict";var gM=Rs&&Rs.__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},yM=Rs&&Rs.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(Rs,"__esModule",{value:!0});Rs.CommandResolver=void 0;var _M=ve(),Is=xe(),ei=Ge(),Se=wr(),W1=ec(),vM=mu(),bM=gu(),SM=wu(),G1=10,z1=class{static{o(this,"CommandResolver")}constructor(e){this.tripleStore=e,this.cache=new Map}async resolveForAsset(e,t,r){let i=`${e}:${t}:${r??""}`,s=this.cache.get(i);if(s)return s;let a=await this.findBindings(t,r,e),c=[];for(let l of a){let u=await this.loadCommand(l.commandRef);if(!u)continue;let f=l.precondition?{...u,precondition:l.precondition}:u;c.push({command:f,binding:l})}return c.sort((l,u)=>{let f=this.getBindingPriority(l.binding),d=this.getBindingPriority(u.binding);return f!==d?f-d:(l.binding.order??100)-(u.binding.order??100)}),this.cache.set(i,c),c}async loadCommand(e){let t=await this.findSubjectByUID(e);if(!t||(await this.tripleStore.match(t,Se.Namespace.RDF.term("type"),Se.Namespace.EXOCMD.term("Command"))).length===0)return null;let i=await this.getLiteralValue(t,Se.Namespace.EXO.term("Asset_label"))??"Unknown Command",s=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_labelTemplate")),a=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_icon")),c=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_confirmMessage")),l=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_successMessage")),u=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_category")),f=await this.loadLinkedPrecondition(t),d=await this.loadLinkedGrounding(t,0);return d?{id:e,name:i,labelTemplate:s??void 0,icon:a??void 0,precondition:f??void 0,grounding:d,confirmMessage:c??void 0,successMessage:l??void 0,category:u??void 0}:null}async findBindings(e,t,r){let i=await this.tripleStore.match(void 0,Se.Namespace.RDF.term("type"),Se.Namespace.EXOCMD.term("CommandBinding")),s=[];for(let a of i){let c=a.subject,l=await this.loadBindingDefinition(c);l&&this.bindingMatches(l,e,t,r)&&s.push(l)}return s}invalidateCache(){this.cache.clear()}async resolveLabel(e,t){if(!e.labelTemplate)return e.name;let r=e.labelTemplate,i=this.extractPlaceholders(e.labelTemplate);for(let{full:s,body:a}of i){let c=await this.evaluateSelectSnippet(a,t);r=r.replace(s,c)}return r}extractPlaceholders(e){let t=[],r=0;for(;r<e.length;)if(e[r]==="{"){let i=1,s=r+1;for(;s<e.length&&i>0;)e[s]==="{"?i++:e[s]==="}"&&i--,s++;if(i===0){let a=e.slice(r,s),c=e.slice(r+1,s-1);t.push({full:a,body:c})}r=s}else r++;return t}async evaluateSelectSnippet(e,t){try{let r=e.replace(/\$target/g,`<${t}>`),s=new vM.ExoQLParser().parse(r),c=new bM.ExoQLAlgebraTranslator().translate(s),u=await new SM.ExoQLQueryExecutor(this.tripleStore).executeAll(c);if(u.length===0)return"";let f=u[0],d=f.variables();if(d.length===0)return"";let h=f.get(d[0]);return h?h instanceof ei.Literal||h instanceof Is.IRI?h.value:String(h):""}catch{return""}}async loadBindingDefinition(e){let t=await this.getLiteralValue(e,Se.Namespace.EXO.term("Asset_uid"));if(!t)return null;let r=await this.getLiteralValue(e,Se.Namespace.EXO.term("Asset_label"))??"",i=await this.getLinkedUID(e,Se.Namespace.EXOCMD.term("CommandBinding_command"));if(!i)return null;let s=await this.getLinkedValue(e,Se.Namespace.EXOCMD.term("CommandBinding_targetClass")),a=await this.getLinkedValue(e,Se.Namespace.EXOCMD.term("CommandBinding_targetPrototype")),c=await this.getLinkedValue(e,Se.Namespace.EXOCMD.term("CommandBinding_targetAsset"));if(!s&&!a&&!c)return null;let l=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("CommandBinding_position")),u=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("CommandBinding_order")),f=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("CommandBinding_group")),d=await this.loadLinkedPreconditionFromProperty(e,Se.Namespace.EXOCMD.term("CommandBinding_precondition"));return{id:t,label:r,commandRef:i,targetClass:s??void 0,targetPrototype:a??void 0,targetAsset:c??void 0,position:l??void 0,order:u?parseInt(u,10):void 0,group:f??void 0,precondition:d??void 0}}bindingMatches(e,t,r,i){return!!(e.targetAsset&&i&&this.matchesReference(e.targetAsset,i)||e.targetPrototype&&r&&this.matchesReference(e.targetPrototype,r)||e.targetClass&&t&&this.matchesReference(e.targetClass,t))}matchesReference(e,t){let r=this.normalizeWikilink(e),i=this.normalizeWikilink(t);if(r===i)return!0;let s=this.extractAlias(t);if(s&&r===s)return!0;let a=this.extractAlias(e);return!!(a&&a===i)}extractAlias(e){let t=e.replace(/["'[\]]/g,"").trim(),r=t.indexOf("|");return r>=0?t.substring(r+1).trim():null}getBindingPriority(e){return e.targetAsset?0:e.targetPrototype?1:2}async loadLinkedPrecondition(e){return this.loadLinkedPreconditionFromProperty(e,Se.Namespace.EXOCMD.term("Command_precondition"))}async loadLinkedPreconditionFromProperty(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object,s=null;if(i instanceof Is.IRI)s=i;else if(i instanceof ei.Literal){let f=this.normalizeWikilink(i.value);s=await this.findSubjectByUID(f)}if(!s)return null;let a=await this.getLiteralValue(s,Se.Namespace.EXO.term("Asset_uid")),c=await this.getLiteralValue(s,Se.Namespace.EXO.term("Asset_label"))??"",l=await this.getLiteralValue(s,Se.Namespace.EXOCMD.term("Precondition_sparqlAsk")),u=await this.getLiteralValue(s,Se.Namespace.EXOCMD.term("Precondition_hostFunction"));return!a||!l&&!u?null:{id:a,label:c,...l&&{sparqlAsk:l},...u&&{hostFunction:u}}}async loadLinkedGrounding(e,t){if(t>=G1)return null;let r=await this.tripleStore.match(e,Se.Namespace.EXOCMD.term("Command_grounding"),void 0);if(r.length===0)return null;let i=r[0].object,s=null;if(i instanceof Is.IRI)s=i;else if(i instanceof ei.Literal){let a=this.normalizeWikilink(i.value);s=await this.findSubjectByUID(a)}return s?this.loadGroundingDefinition(s,t):null}async loadGroundingDefinition(e,t){if(t>=G1)return null;let r=await this.getLiteralValue(e,Se.Namespace.EXO.term("Asset_uid"));if(!r)return null;let i=await this.getLiteralValue(e,Se.Namespace.EXO.term("Asset_label"))??"",s=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_type"));if(!s)return null;let a=this.resolveGroundingType(s);if(!a)return null;let c=await this.getObsidianName(e,Se.Namespace.EXOCMD.term("Grounding_targetProperty"));!c&&a===W1.GroundingType.SERVICE_CALL&&(c=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_serviceId")));let l=await this.getObsidianWikilinkValue(e,Se.Namespace.EXOCMD.term("Grounding_targetValue")),u=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_sparqlUpdate")),f=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_targetClass")),d=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_targetPrototype")),h=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_targetFolder")),p=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_inputSchema")),_;a===W1.GroundingType.COMPOSITE&&(_=await this.loadCompositeSteps(e,t+1));let b;if(p)try{let w=JSON.parse(p);w?.properties&&(b=Object.entries(w.properties).map(([x,R])=>({name:x,type:R.type==="string"?"text":R.type,label:R.title??x,required:Array.isArray(w.required)&&w.required.includes(x)})))}catch{}let E={id:r,label:i,type:a,targetProperty:c??void 0,targetValue:l??void 0,sparqlUpdate:u??void 0,steps:_,targetClass:f??void 0,targetPrototype:d??void 0,targetFolder:h??void 0};return b&&(E.inputSchema=b),E}async loadCompositeSteps(e,t){if(t>=G1)return[];let r=await this.tripleStore.match(e,Se.Namespace.EXOCMD.term("Grounding_steps"),void 0),i=[];for(let s of r){let a=null;if(s.object instanceof Is.IRI)a=s.object;else if(s.object instanceof ei.Literal){let l=this.normalizeWikilink(s.object.value);a=await this.findSubjectByUID(l)}if(!a)continue;let c=await this.loadGroundingDefinition(a,t);c&&i.push(c)}return i}resolveGroundingType(e){let t=e.toLowerCase().trim();return Object.values(W1.GroundingType).includes(t)?t:null}async findSubjectByUID(e){if(this.tripleStore.findSubjectsByUUID){let r=await this.tripleStore.findSubjectsByUUID(e);if(r.length>0)return r[0]}let t=await this.tripleStore.match(void 0,Se.Namespace.EXO.term("Asset_uid"),void 0);for(let r of t)if(r.object instanceof ei.Literal&&r.object.value===e)return r.subject;return null}async getLiteralValue(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;return i instanceof ei.Literal||i instanceof Is.IRI?i.value:null}async getLinkedUID(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;if(i instanceof Is.IRI){let s=await this.tripleStore.match(i,Se.Namespace.EXO.term("Asset_uid"),void 0);return s.length>0&&s[0].object instanceof ei.Literal?s[0].object.value:i.value.split("/").pop()?.replace(".md","")??null}return i instanceof ei.Literal?this.normalizeWikilink(i.value):null}async getLinkedValue(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;return i instanceof ei.Literal?this.normalizeWikilink(i.value):i instanceof Is.IRI?this.iriToObsidianName(i.value)??i.value:null}async getObsidianName(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;return i instanceof ei.Literal?i.value:i instanceof Is.IRI?this.iriToObsidianName(i.value)??i.value:null}async getObsidianWikilinkValue(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;if(i instanceof ei.Literal)return this.resolveWikilinkAlias(i.value);if(i instanceof Is.IRI){let s=this.iriToObsidianName(i.value);return s?`"[[${s}]]"`:i.value}return null}async resolveWikilinkAlias(e){let t=e.match(/\[\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\]\]/);if(!t)return e;let r=t[1],i=await this.findSubjectByUID(r);if(!i)return e;let s=await this.getLiteralValue(i,Se.Namespace.EXO.term("Asset_label"));return s?e.replace(`[[${r}]]`,`[[${r}|${s}]]`):e}iriToObsidianName(e){let t=e.lastIndexOf("#");if(t>=0){let i=e.substring(0,t+1),s=e.substring(t+1);if(i===Se.Namespace.EMS.iri.value)return`ems__${s}`;if(i===Se.Namespace.EXO.iri.value)return`exo__${s}`;if(i===Se.Namespace.EXOCMD.iri.value)return`exocmd__${s}`;if(i===Se.Namespace.IMS.iri.value)return`ims__${s}`;if(i===Se.Namespace.ZTLK.iri.value)return`ztlk__${s}`;if(i===Se.Namespace.PTMS.iri.value)return`ptms__${s}`;if(i===Se.Namespace.LIT.iri.value)return`lit__${s}`;if(i===Se.Namespace.INBOX.iri.value)return`inbox__${s}`}let r=e.match(/\/([^/]+)\.md$/);return r?r[1]:null}normalizeWikilink(e){let t=e.replace(/["'[\]]/g,"").trim(),r=t.indexOf("|");return r>=0?t.substring(0,r):t}};Rs.CommandResolver=z1;Rs.CommandResolver=z1=gM([(0,_M.injectable)(),yM("design:paramtypes",[Object])],z1)});var e3=v(Ps=>{"use strict";var wM=Ps&&Ps.__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},EM=Ps&&Ps.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Eu;Object.defineProperty(Ps,"__esModule",{value:!0});Ps.PreconditionEvaluator=void 0;var TM=ve(),xM=mu(),AM=gu(),ZT=wu(),Tu=Eu=class{static{o(this,"PreconditionEvaluator")}constructor(e){this.hostFunctions=new Map,this.askCache=new Map,this.tripleStore=e}async evaluate(e,t,r){return e?e.sparqlAsk?this.evaluateSparqlAsk(e.sparqlAsk,t):e.hostFunction?this.evaluateHostFunction(e.hostFunction,t,r):!0:!0}registerHostFunction(e,t){this.hostFunctions.set(e,t)}hasHostFunction(e){return this.hostFunctions.has(e)}invalidateCache(){this.askCache.clear()}compileAsk(e){let t=this.substituteVariables(e,Eu.SENTINEL_IRI),i=new xM.ExoQLParser().parse(t),a=new AM.ExoQLAlgebraTranslator().translate(i);return new ZT.ExoQLQueryExecutor(this.tripleStore).isAskQuery(a)?a:null}evaluateHostFunction(e,t,r){let i=this.hostFunctions.get(e);if(!i)return!0;let s=r?{...r,targetIRI:t}:{targetIRI:t};return i(s)}async evaluateSparqlAsk(e,t){try{let r=this.askCache.get(e);if(r===void 0){let a=this.compileAsk(e);if(!a)return!1;r=a,this.askCache.set(e,r)}let i=JSON.parse(JSON.stringify(r).replaceAll(Eu.SENTINEL_IRI,t));return await new ZT.ExoQLQueryExecutor(this.tripleStore).executeAsk(i)}catch{return!1}}substituteVariables(e,t){let r=new Date().toISOString(),i=r.slice(0,10),s=new Date,a=new Date(s.getTime()+Eu.ALMATY_OFFSET_MS),c=a.getUTCFullYear(),l=a.getUTCMonth(),u=a.getUTCDate(),f=a.getUTCDay(),h=new Date(Date.UTC(c,l,u-1)).toISOString().slice(0,10),p=(f+6)%7,_=new Date(Date.UTC(c,l,u-p)),b=_.toISOString().slice(0,10),w=new Date(_.getTime()-10080*60*1e3).toISOString().slice(0,10),x=`${c}-${String(l+1).padStart(2,"0")}-01`,R=l===0?11:l-1,z=`${l===0?c-1:c}-${String(R+1).padStart(2,"0")}-01`,we=`${c}-01-01`;return e.replace(/\$target/g,`<${t}>`).replace(/\$now/g,`"${r}"^^xsd:dateTime`).replace(/\$yesterday/g,`"${h}"^^xsd:date`).replace(/\$thisWeekStart/g,`"${b}"^^xsd:date`).replace(/\$lastWeekStart/g,`"${w}"^^xsd:date`).replace(/\$thisMonthStart/g,`"${x}"^^xsd:date`).replace(/\$lastMonthStart/g,`"${z}"^^xsd:date`).replace(/\$thisYearStart/g,`"${we}"^^xsd:date`).replace(/\$today/g,`"${i}"^^xsd:date`)}};Ps.PreconditionEvaluator=Tu;Tu.SENTINEL_IRI="urn:exocortex:cache-sentinel:target";Tu.ALMATY_OFFSET_MS=300*60*1e3;Ps.PreconditionEvaluator=Tu=Eu=wM([(0,TM.injectable)(),EM("design:paramtypes",[Object])],Tu)});var Hi=v(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});tp.FrontmatterService=void 0;var xu=class n{static{o(this,"FrontmatterService")}parse(e){let t=e.match(n.FRONTMATTER_REGEX);return t?{exists:!0,content:t[1],originalContent:e}:{exists:!1,content:"",originalContent:e}}updateProperty(e,t,r){t=n.normalizeIRI(t),typeof r=="string"&&(r=n.normalizeIRIValue(r));let i=this.parse(e),s=this.serializeValue(t,r);if(!i.exists)return`---
|
|
68
|
+
${r}}`}generateValuesTerm(e){if(e.type==="iri")return`<${e.value}>`;let r=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return e.language?r+=`@${e.language}`:e.datatype&&(r+=`^^<${e.datatype}>`),r}generateExpression(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e.value=="boolean"?e.value?"true":"false":String(e.value);case"comparison":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"logical":return e.operator==="!"?`!(${this.generateExpression(e.operands[0])})`:`(${e.operands.map(t=>this.generateExpression(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"function":return`${e.function.toUpperCase()}(${e.args.map(t=>this.generateExpression(t)).join(", ")})`;case"functionCall":return`${(typeof e.function=="string"?e.function:e.function.value).toUpperCase()}(${e.args.map(r=>this.generateExpression(r)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.generateWhereClause(e.pattern,0)} }`;case"in":{let t=this.generateExpression(e.expression),r=e.list.map(i=>this.generateExpression(i)).join(", ");return e.negated?`${t} NOT IN (${r})`:`${t} IN (${r})`}default:throw new Dc(`Unknown expression type: ${e.type}`)}}collectVariablesFromOperation(e,t){switch(e.type){case"bgp":for(let r of e.triples)this.collectVariablesFromTriple(r,t);break;case"filter":this.collectVariablesFromOperation(e.input,t),this.collectVariablesFromExpression(e.expression,t);break;case"join":case"leftjoin":case"union":case"minus":this.collectVariablesFromOperation(e.left,t),this.collectVariablesFromOperation(e.right,t);break;case"values":for(let r of e.variables)t.add(r);break;case"project":for(let r of e.variables)t.add(r);this.collectVariablesFromOperation(e.input,t);break;case"extend":t.add(e.variable),this.collectVariablesFromOperation(e.input,t);break;case"orderby":case"slice":case"distinct":case"reduced":this.collectVariablesFromOperation(e.input,t);break;case"group":for(let r of e.variables)t.add(r);for(let r of e.aggregates)t.add(r.variable);this.collectVariablesFromOperation(e.input,t);break;case"subquery":this.collectVariablesFromOperation(e.query,t);break}}collectVariablesFromTriple(e,t){e.subject.type==="variable"&&t.add(e.subject.value),"type"in e.predicate&&e.predicate.type==="variable"&&t.add(e.predicate.value),e.object.type==="variable"&&t.add(e.object.value)}collectVariablesFromExpression(e,t){switch(e.type){case"variable":t.add(e.name);break;case"comparison":case"arithmetic":this.collectVariablesFromExpression(e.left,t),this.collectVariablesFromExpression(e.right,t);break;case"logical":for(let r of e.operands)this.collectVariablesFromExpression(r,t);break;case"function":case"functionCall":for(let r of e.args)this.collectVariablesFromExpression(r,t);break;case"exists":this.collectVariablesFromOperation(e.pattern,t);break;case"in":this.collectVariablesFromExpression(e.expression,t);for(let r of e.list)this.collectVariablesFromExpression(r,t);break}}};Fc.SPARQLGenerator=q1});var wu=v(yn=>{"use strict";var rM=yn&&yn.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(n,r,i)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),nM=yn&&yn.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),KT=yn&&yn.__importStar||(function(){var n=o(function(e){return n=Object.getOwnPropertyNames||function(t){var r=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[r.length]=i);return r},n(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=n(e),i=0;i<r.length;i++)r[i]!=="default"&&rM(t,e,r[i]);return nM(t,e),t}})();Object.defineProperty(yn,"__esModule",{value:!0});yn.QueryExecutor=yn.ExoQLQueryExecutor=yn.QueryExecutorError=void 0;var iM=h1(),sM=Gh(),aM=I1(),oM=P1(),cM=VT(),lM=BT(),uM=GT(),fM=V1(),dM=HT(),hM=YT(),pM=XT(),mM=xe(),Nc=class extends Error{static{o(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};yn.QueryExecutorError=Nc;var ep=class{static{o(this,"ExoQLQueryExecutor")}constructor(e,t={}){this.tripleStore=e,this.bgpExecutor=new iM.BGPExecutor(e),this.filterExecutor=new sM.FilterExecutor,this.optionalExecutor=new aM.OptionalExecutor,this.unionExecutor=new oM.UnionExecutor,this.minusExecutor=new cM.MinusExecutor,this.valuesExecutor=new lM.ValuesExecutor,this.aggregateExecutor=new uM.AggregateExecutor,this.constructExecutor=new fM.ConstructExecutor,this.serviceExecutor=new dM.ServiceExecutor(t.serviceConfig),this.graphExecutor=new hM.GraphExecutor(e),this.sparqlGenerator=new pM.SPARQLGenerator,this.filterExecutor.setExistsEvaluator(async(r,i)=>this.evaluateExistsPattern(r,i)),this.filterExecutor.setTripleStore(e)}async evaluateExistsPattern(e,t){for await(let r of this.execute(e))if(t.merge(r)!==null)return!0;return!1}async executeAll(e){let t=[];for await(let r of this.execute(e))t.push(r);return t}async*execute(e){switch(e.type){case"bgp":yield*this.executeBGP(e);break;case"filter":yield*this.executeFilter(e);break;case"join":yield*this.executeJoin(e);break;case"leftjoin":yield*this.executeLeftJoin(e);break;case"union":yield*this.executeUnion(e);break;case"minus":yield*this.executeMinus(e);break;case"values":yield*this.executeValues(e);break;case"project":yield*this.executeProject(e);break;case"orderby":yield*this.executeOrderBy(e);break;case"slice":yield*this.executeSlice(e);break;case"distinct":yield*this.executeDistinct(e);break;case"reduced":yield*this.executeReduced(e);break;case"group":yield*this.executeGroup(e);break;case"extend":yield*this.executeExtend(e);break;case"subquery":yield*this.executeSubquery(e);break;case"lateraljoin":yield*this.executeLateralJoin(e);break;case"service":yield*this.executeService(e);break;case"graph":yield*this.executeGraph(e);break;default:throw new Nc(`Unknown operation type: ${e.type}`)}}async*executeBGP(e){yield*this.bgpExecutor.execute(e)}async*executeFilter(e){let t=this.execute(e.input);yield*this.filterExecutor.execute(e,t)}async*executeJoin(e){let t=[];for await(let a of this.execute(e.left))t.push(a);if(t.length===0)return;let r=new Set;for(let a of t)for(let c of a.variables())r.add(c);let i=this.collectOperationVariables(e.right);if([...r].some(a=>i.has(a)))for(let a of t){let c=this.substituteVariables(e.right,a);for await(let l of this.execute(c)){let u=a.merge(l);u!==null&&(yield u)}}else{let a=[];for await(let c of this.execute(e.right))a.push(c);for(let c of t)for(let l of a){let u=c.merge(l);u!==null&&(yield u)}}}async*executeLeftJoin(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let r=[];for await(let a of this.execute(e.right))r.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of r)yield a}o(s,"rightGen"),yield*this.optionalExecutor.execute(i(),s())}async*executeUnion(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let r=[];for await(let a of this.execute(e.right))r.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of r)yield a}o(s,"rightGen"),yield*this.unionExecutor.execute(i(),s())}async*executeMinus(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let r=[];for await(let a of this.execute(e.right))r.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of r)yield a}o(s,"rightGen"),yield*this.minusExecutor.execute(i(),s())}async*executeValues(e){yield*this.valuesExecutor.execute(e)}async*executeProject(e){let{SolutionMapping:t}=await Promise.resolve().then(()=>KT(Gi())),r=new Set(e.variables);for await(let i of this.execute(e.input)){let s=new t;for(let a of i.variables())if(r.has(a)){let c=i.get(a);c!==void 0&&s.set(a,c)}yield s}}async*executeOrderBy(e){let t=[];for await(let r of this.execute(e.input))t.push(r);t.sort((r,i)=>{for(let s of e.comparators){let a=this.getExpressionValue(s.expression,r),c=this.getExpressionValue(s.expression,i),l=0;if(a===void 0&&c===void 0?l=0:a===void 0?l=1:c===void 0?l=-1:typeof a=="number"&&typeof c=="number"?l=a-c:l=String(a).localeCompare(String(c)),s.descending&&(l=-l),l!==0)return l}return 0});for(let r of t)yield r}async*executeSlice(e){let t=0,r=e.offset??0,i=e.limit;for await(let s of this.execute(e.input)){if(t>=r){if(i!==void 0&&t-r>=i)break;yield s}t++}}async*executeDistinct(e){let t=new Set;for await(let r of this.execute(e.input)){let i=this.getSolutionKey(r);t.has(i)||(t.add(i),yield r)}}async*executeReduced(e){let t=new Set;for await(let r of this.execute(e.input)){let i=this.getSolutionKey(r);t.has(i)||(t.add(i),yield r)}}async*executeGroup(e){let t=[];for await(let i of this.execute(e.input))t.push(i);let r=this.aggregateExecutor.execute(e,t);if(e.having&&e.having.length>0)for(let i of r)e.having.every(a=>this.filterExecutor.evaluateExpression(a,i)===!0)&&(yield i);else for(let i of r)yield i}async*executeExtend(e){for await(let t of this.execute(e.input)){let r=t.clone(),i=this.evaluateExtendExpression(e.expression,t);i!==void 0&&r.set(e.variable,i),yield r}}async*executeSubquery(e){yield*this.execute(e.query)}async*executeLateralJoin(e){let t=[];for await(let r of this.execute(e.left))t.push(r);for(let r of t){let i=this.substituteVariables(e.right,r);for await(let s of this.execute(i)){let a=r.merge(s);a!==null&&(yield a)}}}substituteVariables(e,t){let r=JSON.parse(JSON.stringify(e));return this.substituteInOperation(r,t)}substituteInOperation(e,t){if(!e||typeof e!="object")return e;let r=e;return e.type==="bgp"&&e.triples?(e.triples=e.triples.map(i=>this.substituteInTriple(i,t)),e):(r.input&&(r.input=this.substituteInOperation(r.input,t)),r.left&&(r.left=this.substituteInOperation(r.left,t)),r.right&&(r.right=this.substituteInOperation(r.right,t)),r.pattern&&(r.pattern=this.substituteInOperation(r.pattern,t)),r.query&&(r.query=this.substituteInOperation(r.query,t)),r.where&&(r.where=this.substituteInOperation(r.where,t)),r.expression&&this.substituteInExpression(r.expression,t),e)}substituteInExpression(e,t){if(!(!e||typeof e!="object")){if(e.type==="exists"&&e.pattern&&(e.pattern=this.substituteInOperation(e.pattern,t)),e.left&&this.substituteInExpression(e.left,t),e.right&&this.substituteInExpression(e.right,t),e.operands)for(let r of e.operands)this.substituteInExpression(r,t);if(e.args)for(let r of e.args)this.substituteInExpression(r,t);if(e.expression&&this.substituteInExpression(e.expression,t),e.list)for(let r of e.list)this.substituteInExpression(r,t)}}substituteInTriple(e,t){return{subject:this.substituteInTripleElement(e.subject,t),predicate:e.predicate,object:this.substituteInTripleElement(e.object,t)}}substituteInTripleElement(e,t){if(e&&e.type==="variable"){let r=t.get(e.value);if(r!=null){let i=r;if(r instanceof mM.IRI||i.termType==="NamedNode")return{type:"iri",value:r.value};if(i.termType==="Literal"||typeof i.value=="string")return{type:"literal",value:i.value,datatype:i.datatype?.value??i._datatype?.value,language:i.language??i._language}}}return e}async*executeService(e){yield*this.serviceExecutor.execute(e,t=>this.sparqlGenerator.generateSelect(t))}async*executeGraph(e){let t=async function*(r,i){let s=this.currentGraphContext;this.currentGraphContext=i;try{r.type==="bgp"&&i&&this.tripleStore.matchInGraph?yield*this.executeBGPInGraph(r,i):yield*this.execute(r)}finally{this.currentGraphContext=s}}.bind(this);yield*this.graphExecutor.execute(e,t)}async*executeBGPInGraph(e,t){if(e.triples.length===0){let{SolutionMapping:r}=await Promise.resolve().then(()=>KT(Gi()));yield new r;return}yield*this.bgpExecutor.executeInGraph(e,t)}evaluateExtendExpression(e,t){if(e.type!=="aggregate")try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}getExpressionValue(e,t){if(e.type==="variable"){let r=t.get(e.name);return r?r.value??r.id??String(r):void 0}if(e.type==="literal")return e.value}collectOperationVariables(e){let t=new Set;return this.collectVarsFromOperation(e,t),t}collectVarsFromOperation(e,t){if(!e||typeof e!="object")return;let r=e;if(r.type==="bgp"&&r.triples)for(let i of r.triples)this.collectVarsFromElement(i.subject,t),i.predicate?.type!=="path"&&this.collectVarsFromElement(i.predicate,t),this.collectVarsFromElement(i.object,t);if(r.type==="values"&&r.variables)for(let i of r.variables)t.add(i);r.expression&&this.collectVarsFromExpressionTree(r.expression,t),r.type==="extend"&&r.variable&&t.add(r.variable),r.input&&this.collectVarsFromOperation(r.input,t),r.left&&this.collectVarsFromOperation(r.left,t),r.right&&this.collectVarsFromOperation(r.right,t),r.pattern&&this.collectVarsFromOperation(r.pattern,t),r.query&&this.collectVarsFromOperation(r.query,t),r.where&&this.collectVarsFromOperation(r.where,t)}collectVarsFromElement(e,t){if(!e||typeof e!="object")return;let r=e;r.type==="variable"&&t.add(r.value),r.type==="quoted"&&(this.collectVarsFromElement(r.subject,t),this.collectVarsFromElement(r.predicate,t),this.collectVarsFromElement(r.object,t))}collectVarsFromExpressionTree(e,t){if(!e||typeof e!="object")return;let r=e;if(r.type==="variable"&&r.name&&t.add(r.name),r.type==="exists"&&r.pattern&&this.collectVarsFromOperation(r.pattern,t),r.left&&this.collectVarsFromExpressionTree(r.left,t),r.right&&this.collectVarsFromExpressionTree(r.right,t),r.operands)for(let i of r.operands)this.collectVarsFromExpressionTree(i,t);if(r.args)for(let i of r.args)this.collectVarsFromExpressionTree(i,t);if(r.expression&&this.collectVarsFromExpressionTree(r.expression,t),r.list)for(let i of r.list)this.collectVarsFromExpressionTree(i,t)}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}isConstructQuery(e){return e.type==="construct"}async executeConstruct(e){if(e.type!=="construct")throw new Nc("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}isAskQuery(e){return e.type==="ask"}async executeAsk(e){if(e.type!=="ask")throw new Nc("executeAsk requires an ASK operation");for await(let t of this.execute(e.where))return!0;return!1}};yn.ExoQLQueryExecutor=ep;yn.QueryExecutor=ep});var JT=v(Rs=>{"use strict";var gM=Rs&&Rs.__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},yM=Rs&&Rs.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(Rs,"__esModule",{value:!0});Rs.CommandResolver=void 0;var _M=ve(),Is=xe(),ei=Ge(),Se=wr(),W1=ec(),vM=mu(),bM=gu(),SM=wu(),G1=10,z1=class{static{o(this,"CommandResolver")}constructor(e){this.tripleStore=e,this.cache=new Map}async resolveForAsset(e,t,r){let i=`${e}:${t}:${r??""}`,s=this.cache.get(i);if(s)return s;let a=await this.findBindings(t,r,e),c=[];for(let l of a){let u=await this.loadCommand(l.commandRef);if(!u)continue;let f=l.precondition?{...u,precondition:l.precondition}:u;c.push({command:f,binding:l})}return c.sort((l,u)=>{let f=this.getBindingPriority(l.binding),d=this.getBindingPriority(u.binding);return f!==d?f-d:(l.binding.order??100)-(u.binding.order??100)}),this.cache.set(i,c),c}async loadCommand(e){let t=await this.findSubjectByUID(e);if(!t||(await this.tripleStore.match(t,Se.Namespace.RDF.term("type"),Se.Namespace.EXOCMD.term("Command"))).length===0)return null;let i=await this.getLiteralValue(t,Se.Namespace.EXO.term("Asset_label"))??"Unknown Command",s=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_labelTemplate")),a=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_icon")),c=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_confirmMessage")),l=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_successMessage")),u=await this.getLiteralValue(t,Se.Namespace.EXOCMD.term("Command_category")),f=await this.loadLinkedPrecondition(t),d=await this.loadLinkedGrounding(t,0);return d?{id:e,name:i,labelTemplate:s??void 0,icon:a??void 0,precondition:f??void 0,grounding:d,confirmMessage:c??void 0,successMessage:l??void 0,category:u??void 0}:null}async findBindings(e,t,r){let i=await this.tripleStore.match(void 0,Se.Namespace.RDF.term("type"),Se.Namespace.EXOCMD.term("CommandBinding")),s=[];for(let a of i){let c=a.subject,l=await this.loadBindingDefinition(c);l&&this.bindingMatches(l,e,t,r)&&s.push(l)}return s}invalidateCache(){this.cache.clear()}async resolveLabel(e,t){if(!e.labelTemplate)return e.name;let r=e.labelTemplate,i=this.extractPlaceholders(e.labelTemplate);for(let{full:s,body:a}of i){let c=await this.evaluateSelectSnippet(a,t);r=r.replace(s,c)}return r}extractPlaceholders(e){let t=[],r=0;for(;r<e.length;)if(e[r]==="{"){let i=1,s=r+1;for(;s<e.length&&i>0;)e[s]==="{"?i++:e[s]==="}"&&i--,s++;if(i===0){let a=e.slice(r,s),c=e.slice(r+1,s-1);t.push({full:a,body:c})}r=s}else r++;return t}async evaluateSelectSnippet(e,t){try{let r=e.replace(/\$target/g,`<${t}>`),s=new vM.ExoQLParser().parse(r),c=new bM.ExoQLAlgebraTranslator().translate(s),u=await new SM.ExoQLQueryExecutor(this.tripleStore).executeAll(c);if(u.length===0)return"";let f=u[0],d=f.variables();if(d.length===0)return"";let h=f.get(d[0]);return h?h instanceof ei.Literal||h instanceof Is.IRI?h.value:String(h):""}catch{return""}}async loadBindingDefinition(e){let t=await this.getLiteralValue(e,Se.Namespace.EXO.term("Asset_uid"));if(!t)return null;let r=await this.getLiteralValue(e,Se.Namespace.EXO.term("Asset_label"))??"",i=await this.getLinkedUID(e,Se.Namespace.EXOCMD.term("CommandBinding_command"));if(!i)return null;let s=await this.getLinkedValue(e,Se.Namespace.EXOCMD.term("CommandBinding_targetClass")),a=await this.getLinkedValue(e,Se.Namespace.EXOCMD.term("CommandBinding_targetPrototype")),c=await this.getLinkedValue(e,Se.Namespace.EXOCMD.term("CommandBinding_targetAsset"));if(!s&&!a&&!c)return null;let l=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("CommandBinding_position")),u=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("CommandBinding_order")),f=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("CommandBinding_group")),d=await this.loadLinkedPreconditionFromProperty(e,Se.Namespace.EXOCMD.term("CommandBinding_precondition"));return{id:t,label:r,commandRef:i,targetClass:s??void 0,targetPrototype:a??void 0,targetAsset:c??void 0,position:l??void 0,order:u?parseInt(u,10):void 0,group:f??void 0,precondition:d??void 0}}bindingMatches(e,t,r,i){return!!(e.targetAsset&&i&&this.matchesReference(e.targetAsset,i)||e.targetPrototype&&r&&this.matchesReference(e.targetPrototype,r)||e.targetClass&&t&&this.matchesReference(e.targetClass,t))}matchesReference(e,t){let r=this.normalizeWikilink(e),i=this.normalizeWikilink(t);if(r===i)return!0;let s=this.extractAlias(t);if(s&&r===s)return!0;let a=this.extractAlias(e);return!!(a&&a===i)}extractAlias(e){let t=e.replace(/["'[\]]/g,"").trim(),r=t.indexOf("|");return r>=0?t.substring(r+1).trim():null}getBindingPriority(e){return e.targetAsset?0:e.targetPrototype?1:2}async loadLinkedPrecondition(e){return this.loadLinkedPreconditionFromProperty(e,Se.Namespace.EXOCMD.term("Command_precondition"))}async loadLinkedPreconditionFromProperty(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object,s=null;if(i instanceof Is.IRI)s=i;else if(i instanceof ei.Literal){let f=this.normalizeWikilink(i.value);s=await this.findSubjectByUID(f)}if(!s)return null;let a=await this.getLiteralValue(s,Se.Namespace.EXO.term("Asset_uid")),c=await this.getLiteralValue(s,Se.Namespace.EXO.term("Asset_label"))??"",l=await this.getLiteralValue(s,Se.Namespace.EXOCMD.term("Precondition_sparqlAsk")),u=await this.getLiteralValue(s,Se.Namespace.EXOCMD.term("Precondition_hostFunction"));return!a||!l&&!u?null:{id:a,label:c,...l&&{sparqlAsk:l},...u&&{hostFunction:u}}}async loadLinkedGrounding(e,t){if(t>=G1)return null;let r=await this.tripleStore.match(e,Se.Namespace.EXOCMD.term("Command_grounding"),void 0);if(r.length===0)return null;let i=r[0].object,s=null;if(i instanceof Is.IRI)s=i;else if(i instanceof ei.Literal){let a=this.normalizeWikilink(i.value);s=await this.findSubjectByUID(a)}return s?this.loadGroundingDefinition(s,t):null}async loadGroundingDefinition(e,t){if(t>=G1)return null;let r=await this.getLiteralValue(e,Se.Namespace.EXO.term("Asset_uid"));if(!r)return null;let i=await this.getLiteralValue(e,Se.Namespace.EXO.term("Asset_label"))??"",s=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_type"));if(!s)return null;let a=this.resolveGroundingType(s);if(!a)return null;let c=await this.getObsidianName(e,Se.Namespace.EXOCMD.term("Grounding_targetProperty"));if(a===W1.GroundingType.SERVICE_CALL){let w=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_serviceId"));w&&(c=w)}let l=await this.getObsidianWikilinkValue(e,Se.Namespace.EXOCMD.term("Grounding_targetValue")),u=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_sparqlUpdate")),f=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_targetClass")),d=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_targetPrototype")),h=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_targetFolder")),p=await this.getLiteralValue(e,Se.Namespace.EXOCMD.term("Grounding_inputSchema")),_;a===W1.GroundingType.COMPOSITE&&(_=await this.loadCompositeSteps(e,t+1));let b;if(p)try{let w=JSON.parse(p);w?.properties&&(b=Object.entries(w.properties).map(([x,R])=>({name:x,type:R.type==="string"?"text":R.type,label:R.title??x,required:Array.isArray(w.required)&&w.required.includes(x)})))}catch{}let E={id:r,label:i,type:a,targetProperty:c??void 0,targetValue:l??void 0,sparqlUpdate:u??void 0,steps:_,targetClass:f??void 0,targetPrototype:d??void 0,targetFolder:h??void 0};return b&&(E.inputSchema=b),E}async loadCompositeSteps(e,t){if(t>=G1)return[];let r=await this.tripleStore.match(e,Se.Namespace.EXOCMD.term("Grounding_steps"),void 0),i=[];for(let s of r){let a=null;if(s.object instanceof Is.IRI)a=s.object;else if(s.object instanceof ei.Literal){let l=this.normalizeWikilink(s.object.value);a=await this.findSubjectByUID(l)}if(!a)continue;let c=await this.loadGroundingDefinition(a,t);c&&i.push(c)}return i}resolveGroundingType(e){let t=e.toLowerCase().trim();return Object.values(W1.GroundingType).includes(t)?t:null}async findSubjectByUID(e){if(this.tripleStore.findSubjectsByUUID){let r=await this.tripleStore.findSubjectsByUUID(e);if(r.length>0)return r[0]}let t=await this.tripleStore.match(void 0,Se.Namespace.EXO.term("Asset_uid"),void 0);for(let r of t)if(r.object instanceof ei.Literal&&r.object.value===e)return r.subject;return null}async getLiteralValue(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;return i instanceof ei.Literal||i instanceof Is.IRI?i.value:null}async getLinkedUID(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;if(i instanceof Is.IRI){let s=await this.tripleStore.match(i,Se.Namespace.EXO.term("Asset_uid"),void 0);return s.length>0&&s[0].object instanceof ei.Literal?s[0].object.value:i.value.split("/").pop()?.replace(".md","")??null}return i instanceof ei.Literal?this.normalizeWikilink(i.value):null}async getLinkedValue(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;return i instanceof ei.Literal?this.normalizeWikilink(i.value):i instanceof Is.IRI?this.iriToObsidianName(i.value)??i.value:null}async getObsidianName(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;return i instanceof ei.Literal?i.value:i instanceof Is.IRI?this.iriToObsidianName(i.value)??i.value:null}async getObsidianWikilinkValue(e,t){let r=await this.tripleStore.match(e,t,void 0);if(r.length===0)return null;let i=r[0].object;if(i instanceof ei.Literal)return this.resolveWikilinkAlias(i.value);if(i instanceof Is.IRI){let s=this.iriToObsidianName(i.value);return s?`"[[${s}]]"`:i.value}return null}async resolveWikilinkAlias(e){let t=e.match(/\[\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\]\]/);if(!t)return e;let r=t[1],i=await this.findSubjectByUID(r);if(!i)return e;let s=await this.getLiteralValue(i,Se.Namespace.EXO.term("Asset_label"));return s?e.replace(`[[${r}]]`,`[[${r}|${s}]]`):e}iriToObsidianName(e){let t=e.lastIndexOf("#");if(t>=0){let i=e.substring(0,t+1),s=e.substring(t+1);if(i===Se.Namespace.EMS.iri.value)return`ems__${s}`;if(i===Se.Namespace.EXO.iri.value)return`exo__${s}`;if(i===Se.Namespace.EXOCMD.iri.value)return`exocmd__${s}`;if(i===Se.Namespace.IMS.iri.value)return`ims__${s}`;if(i===Se.Namespace.ZTLK.iri.value)return`ztlk__${s}`;if(i===Se.Namespace.PTMS.iri.value)return`ptms__${s}`;if(i===Se.Namespace.LIT.iri.value)return`lit__${s}`;if(i===Se.Namespace.INBOX.iri.value)return`inbox__${s}`}let r=e.match(/\/([^/]+)\.md$/);return r?r[1]:null}normalizeWikilink(e){let t=e.replace(/["'[\]]/g,"").trim(),r=t.indexOf("|");return r>=0?t.substring(0,r):t}};Rs.CommandResolver=z1;Rs.CommandResolver=z1=gM([(0,_M.injectable)(),yM("design:paramtypes",[Object])],z1)});var e3=v(Ps=>{"use strict";var wM=Ps&&Ps.__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},EM=Ps&&Ps.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)},Eu;Object.defineProperty(Ps,"__esModule",{value:!0});Ps.PreconditionEvaluator=void 0;var TM=ve(),xM=mu(),AM=gu(),ZT=wu(),Tu=Eu=class{static{o(this,"PreconditionEvaluator")}constructor(e){this.hostFunctions=new Map,this.askCache=new Map,this.tripleStore=e}async evaluate(e,t,r){return e?e.sparqlAsk?this.evaluateSparqlAsk(e.sparqlAsk,t):e.hostFunction?this.evaluateHostFunction(e.hostFunction,t,r):!0:!0}registerHostFunction(e,t){this.hostFunctions.set(e,t)}hasHostFunction(e){return this.hostFunctions.has(e)}invalidateCache(){this.askCache.clear()}compileAsk(e){let t=this.substituteVariables(e,Eu.SENTINEL_IRI),i=new xM.ExoQLParser().parse(t),a=new AM.ExoQLAlgebraTranslator().translate(i);return new ZT.ExoQLQueryExecutor(this.tripleStore).isAskQuery(a)?a:null}evaluateHostFunction(e,t,r){let i=this.hostFunctions.get(e);if(!i)return!0;let s=r?{...r,targetIRI:t}:{targetIRI:t};return i(s)}async evaluateSparqlAsk(e,t){try{let r=this.askCache.get(e);if(r===void 0){let a=this.compileAsk(e);if(!a)return!1;r=a,this.askCache.set(e,r)}let i=JSON.parse(JSON.stringify(r).replaceAll(Eu.SENTINEL_IRI,t));return await new ZT.ExoQLQueryExecutor(this.tripleStore).executeAsk(i)}catch{return!1}}substituteVariables(e,t){let r=new Date().toISOString(),i=r.slice(0,10),s=new Date,a=new Date(s.getTime()+Eu.ALMATY_OFFSET_MS),c=a.getUTCFullYear(),l=a.getUTCMonth(),u=a.getUTCDate(),f=a.getUTCDay(),h=new Date(Date.UTC(c,l,u-1)).toISOString().slice(0,10),p=(f+6)%7,_=new Date(Date.UTC(c,l,u-p)),b=_.toISOString().slice(0,10),w=new Date(_.getTime()-10080*60*1e3).toISOString().slice(0,10),x=`${c}-${String(l+1).padStart(2,"0")}-01`,R=l===0?11:l-1,z=`${l===0?c-1:c}-${String(R+1).padStart(2,"0")}-01`,we=`${c}-01-01`;return e.replace(/\$target/g,`<${t}>`).replace(/\$now/g,`"${r}"^^xsd:dateTime`).replace(/\$yesterday/g,`"${h}"^^xsd:date`).replace(/\$thisWeekStart/g,`"${b}"^^xsd:date`).replace(/\$lastWeekStart/g,`"${w}"^^xsd:date`).replace(/\$thisMonthStart/g,`"${x}"^^xsd:date`).replace(/\$lastMonthStart/g,`"${z}"^^xsd:date`).replace(/\$thisYearStart/g,`"${we}"^^xsd:date`).replace(/\$today/g,`"${i}"^^xsd:date`)}};Ps.PreconditionEvaluator=Tu;Tu.SENTINEL_IRI="urn:exocortex:cache-sentinel:target";Tu.ALMATY_OFFSET_MS=300*60*1e3;Ps.PreconditionEvaluator=Tu=Eu=wM([(0,TM.injectable)(),EM("design:paramtypes",[Object])],Tu)});var Hi=v(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});tp.FrontmatterService=void 0;var xu=class n{static{o(this,"FrontmatterService")}parse(e){let t=e.match(n.FRONTMATTER_REGEX);return t?{exists:!0,content:t[1],originalContent:e}:{exists:!1,content:"",originalContent:e}}updateProperty(e,t,r){t=n.normalizeIRI(t),typeof r=="string"&&(r=n.normalizeIRIValue(r));let i=this.parse(e),s=this.serializeValue(t,r);if(!i.exists)return`---
|
|
69
69
|
${s}
|
|
70
70
|
---
|
|
71
71
|
${e}`;let a=i.content;if(this.hasProperty(a,t)){let c=new RegExp(`${this.escapeRegex(t)}:.*(?:
|
|
@@ -86,7 +86,7 @@ ${Object.entries(t).map(([a,c])=>this.serializeValue(a,c)).join(`
|
|
|
86
86
|
${r}`}return`${e}: ${String(t)}`}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}};tp.FrontmatterService=xu;xu.FRONTMATTER_REGEX=/^---\n([\s\S]*?)\n---/;xu.IRI_PREFIX_MAP={"https://exocortex.my/ontology/ems#":"ems__","https://exocortex.my/ontology/exo#":"exo__","https://exocortex.my/ontology/exocmd#":"exocmd__","https://exocortex.my/ontology/ims#":"ims__","https://exocortex.my/ontology/ztlk#":"ztlk__","https://exocortex.my/ontology/ptms#":"ptms__","https://exocortex.my/ontology/lit#":"lit__","https://exocortex.my/ontology/inbox#":"inbox__"}});var pa=v(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});rp.LoggingService=void 0;var Au=class{static{o(this,"LoggingService")}static setVerbose(e){this.isVerbose=e}static setDevelopmentMode(e){this.isDevelopment=e}static checkIsDevelopment(){return this.isDevelopment!==void 0?this.isDevelopment:typeof process<"u"?(this.isDevelopment=!1,this.isDevelopment):(this.isDevelopment=!1,this.isDevelopment)}static debug(e,t){this.isVerbose&&console.debug(`[Exocortex] ${e}`,t??"")}static info(e,t){console.log(`[Exocortex] ${e}`,t??"")}static warn(e,t){console.warn(`[Exocortex] ${e}`,t??"")}static error(e,t,r){let i=this.checkIsDevelopment(),s=r?` [${r}]`:"";if(i){let a=t?.stack?`
|
|
87
87
|
Stack trace:
|
|
88
88
|
${t.stack}`:"";console.error(`[Exocortex ERROR]${s} ${e}${a}`,t??"")}else{let a=t?.message?`
|
|
89
|
-
Details: ${t.message}`:"";console.error(`[Exocortex ERROR]${s} ${e}${a}`)}}};rp.LoggingService=Au;Au.isVerbose=!1;Au.isDevelopment=void 0});var r3=v(ti=>{"use strict";var CM=ti&&ti.__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},IM=ti&&ti.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(ti,"__esModule",{value:!0});ti.GroundingExecutor=ti.ServiceRegistry=void 0;var RM=ve(),PM=hn(),fo=ec(),OM=Hi(),DM=pa(),np=class{static{o(this,"ServiceRegistry")}constructor(){this.services=new Map}register(e,t){this.services.set(e,t)}get(e){return this.services.get(e)}has(e){return this.services.has(e)}getRegisteredIds(){return Array.from(this.services.keys())}};ti.ServiceRegistry=np;var t3=20,H1=class{static{o(this,"GroundingExecutor")}constructor(e,t,r){this.frontmatterService=new OM.FrontmatterService,this.fileReader=e,this.fileWriter=t,this.serviceRegistry=r}async execute(e,t,r,i){try{switch(e.type){case fo.GroundingType.PROPERTY_SET:return await this.executePropertySet(e,t,r);case fo.GroundingType.PROPERTY_DELETE:return await this.executePropertyDelete(e,r);case fo.GroundingType.COMPOSITE:return await this.executeComposite(e,t,r,i,0);case fo.GroundingType.SERVICE_CALL:return await this.executeServiceCall(e,t,i);case fo.GroundingType.CREATE_INSTANCE:return await this.executeCreateInstance(e,t,i);case fo.GroundingType.SPARQL_UPDATE:return{success:!1,error:"sparql_update grounding not yet implemented. Use property_set/property_delete instead."};default:return{success:!1,error:`Unknown grounding type: ${e.type}`}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}async executePropertySet(e,t,r){if(!e.targetProperty)return{success:!1,error:"property_set requires targetProperty"};if(e.targetValue===void 0)return{success:!1,error:"property_set requires targetValue"};let i=this.substituteVariables(e.targetValue,t),s=await this.fileReader.readFile(r),a=this.frontmatterService.updateProperty(s,e.targetProperty,i);return await this.fileWriter.updateFile(r,a),{success:!0}}async executePropertyDelete(e,t){if(!e.targetProperty)return{success:!1,error:"property_delete requires targetProperty"};let r=await this.fileReader.readFile(t),i=this.frontmatterService.removeProperty(r,e.targetProperty);return await this.fileWriter.updateFile(t,i),{success:!0}}async executeComposite(e,t,r,i,s){if(s>=t3)return{success:!1,error:`Composite grounding exceeded maximum depth of ${t3}`};let a=e.steps??[];if(a.length===0)return{success:!0};let c;try{c=await this.fileReader.readFile(r)}catch{}let l=[];try{for(let u=0;u<a.length;u++){let f=a[u],d=await this.executeStep(f,t,r,i,s+1);if(!d.success)return await this.rollback(c,r,l),{success:!1,error:`Composite step ${u} failed: ${d.error}`};l.push(u)}return{success:!0}}catch(u){return await this.rollback(c,r,l),{success:!1,error:`Composite execution failed: ${u instanceof Error?u.message:String(u)}`}}}async executeServiceCall(e,t,r){let i=e.targetProperty;if(!i)return{success:!1,error:"service_call requires targetProperty as serviceId"};let s=this.serviceRegistry.get(i);return s?(await s.execute(t,r),{success:!0}):{success:!1,error:`Service not found: "${i}". Registered services: ${this.serviceRegistry.getRegisteredIds().join(", ")||"none"}`}}async executeCreateInstance(e,t,r){if(!e.targetFolder)return{success:!1,error:"create_instance requires targetFolder"};let i=(0,PM.v4)(),s=r?.label??"Untitled",a={exo__Asset_uid:i,exo__Asset_createdAt:new Date().toISOString(),exo__Asset_label:s};if(s!=="Untitled"&&(a.aliases=[s]),e.targetClass&&(a.exo__Instance_class=[`"[[${e.targetClass}]]"`]),e.targetPrototype&&(a.exo__Asset_prototype=`"[[${e.targetPrototype}]]"`),t&&(a.exo__Asset_source=`"[[${t}]]"`),r)for(let[u,f]of Object.entries(r))u!=="label"&&f!=null&&(a[u]=f);let c=this.frontmatterService.createFrontmatter("",a),l=`${e.targetFolder}/${i}.md`;return await this.fileWriter.createFile(l,c),{success:!0}}async executeStep(e,t,r,i,s){return e.type===fo.GroundingType.COMPOSITE?this.executeComposite(e,t,r,i,s):this.execute(e,t,r,i)}async rollback(e,t,r){if(e!==void 0)try{await this.fileWriter.updateFile(t,e)}catch(i){DM.LoggingService.error(`[GroundingExecutor] Rollback failed for ${t}`,i instanceof Error?i:new Error(String(i)))}}substituteVariables(e,t){let r=new Date().toISOString(),i=r.slice(0,10);return e.replace(/\$target/g,t).replace(/\$now/g,r).replace(/\$today/g,i)}};ti.GroundingExecutor=H1;ti.GroundingExecutor=H1=CM([(0,RM.injectable)(),IM("design:paramtypes",[Object,Object,np])],H1)});var rn=v(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});ip.DateFormatter=void 0;var Q1=class n{static{o(this,"DateFormatter")}static toISOTimestamp(e){return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toLocalTimestamp(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0");return`${t}-${r}-${i}T${s}:${a}:${c}`}static toDateWikilink(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`"[[${t}-${r}-${i}]]"`}static getTodayWikilink(){return n.toDateWikilink(new Date)}static toDateString(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}static parseWikilink(e){let r=e.replace(/^["']|["']$/g,"").match(/\[\[(\d{4}-\d{2}-\d{2})\]\]/);return r?r[1]:null}static addDays(e,t){let r=new Date(e);return r.setDate(r.getDate()+t),r}static isSameDay(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}static getTodayStartTimestamp(){let e=new Date;return e.setHours(0,0,0,0),n.toLocalTimestamp(e)}static toTimestampAtStartOfDay(e){let t=e.split("-").map(Number);if(t.length!==3||t.some(isNaN))throw new Error(`Invalid date format: ${e}. Expected YYYY-MM-DD`);let[r,i,s]=t,a=new Date(r,i-1,s,0,0,0,0);if(isNaN(a.getTime()))throw new Error(`Invalid date values: ${e}`);return n.toLocalTimestamp(a)}static normalizeTimestamp(e){if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(e))return e;let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp format: ${e}`);return n.toISOTimestamp(t)}static isISOTimestamp(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(e)}};ip.DateFormatter=Q1});var Cu=v(Os=>{"use strict";var FM=Os&&Os.__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},NM=Os&&Os.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(Os,"__esModule",{value:!0});Os.WorkflowEngine=void 0;var LM=ve(),Y1=class{static{o(this,"WorkflowEngine")}constructor(e){this.definition=e}getAvailableTransitions(e){return this.definition.transitions.filter(t=>t.from===e&&!t.isRollback)}getRollbackTransitions(e){return this.definition.transitions.filter(t=>t.from===e&&t.isRollback)}getAllTransitions(e){return this.definition.transitions.filter(t=>t.from===e)}canTransition(e,t){return this.definition.transitions.some(r=>r.from===e&&r.to===t)}getPreviousStatus(e){return this.definition.transitions.find(r=>r.from===e&&r.isRollback)?.to??null}getNextStates(e){return this.getAvailableTransitions(e).map(t=>t.to)}isTerminalState(e){return this.definition.terminalStates.includes(e)}isInitialState(e){return this.definition.initialState===e}getTimestampsForStatus(e){return this.definition.states.find(r=>r.status===e)?.timestampOnEnter??[]}getTransition(e,t){return this.definition.transitions.find(r=>r.from===e&&r.to===t)}getOrderedStates(){return this.definition.states.map(e=>e.status)}getDefinition(){return this.definition}validate(){let e=[],t=new Set(this.definition.states.map(i=>i.status));this.definition.states.length===0&&e.push("Workflow must have at least one state"),t.has(this.definition.initialState)||e.push(`Initial state "${this.definition.initialState}" is not in the states list`);for(let i of this.definition.terminalStates)t.has(i)||e.push(`Terminal state "${i}" is not in the states list`);for(let i of this.definition.transitions)t.has(i.from)||e.push(`Transition "${i.label}" references unknown source state "${i.from}"`),t.has(i.to)||e.push(`Transition "${i.label}" references unknown target state "${i.to}"`);for(let i of this.definition.states){if(this.definition.terminalStates.includes(i.status))continue;this.definition.transitions.filter(a=>a.from===i.status&&!a.isRollback).length===0&&e.push(`State "${i.status}" has no outgoing forward transitions (dead end)`)}let r=new Set;for(let i of this.definition.transitions){let s=`${i.from}\u2192${i.to}`;r.has(s)&&e.push(`Duplicate transition: ${s}`),r.add(s)}return{valid:e.length===0,errors:e}}};Os.WorkflowEngine=Y1;Os.WorkflowEngine=Y1=FM([(0,LM.injectable)(),NM("design:paramtypes",[Object])],Y1)});var n3=v(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.EFFORT_WORKFLOW_PROPERTY=Qi.WorkflowTransitionProperty=Qi.WorkflowStateProperty=Qi.WorkflowProperty=void 0;Qi.WorkflowProperty={TARGET_CLASS:"ems__Workflow_targetClass",INITIAL_STATE:"ems__Workflow_initialState",TERMINAL_STATES:"ems__Workflow_terminalStates",IS_DEFAULT:"ems__Workflow_isDefault"};Qi.WorkflowStateProperty={WORKFLOW:"ems__WorkflowState_workflow",STATUS:"ems__WorkflowState_status",ORDER:"ems__WorkflowState_order",OPTIONAL:"ems__WorkflowState_optional",TIMESTAMP_ON_ENTER:"ems__WorkflowState_timestampOnEnter",BADGE_COLOR:"ems__WorkflowState_badgeColor"};Qi.WorkflowTransitionProperty={WORKFLOW:"ems__WorkflowTransition_workflow",FROM:"ems__WorkflowTransition_from",TO:"ems__WorkflowTransition_to",LABEL:"ems__WorkflowTransition_label",ICON:"ems__WorkflowTransition_icon",IS_ROLLBACK:"ems__WorkflowTransition_isRollback"};Qi.EFFORT_WORKFLOW_PROPERTY="ems__Effort_workflow"});var Yi=v(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});sp.MetadataHelpers=void 0;var X1=class{static{o(this,"MetadataHelpers")}static findAllReferencingProperties(e,t){let r=[];for(let[i,s]of Object.entries(e))this.containsReference(s,t)&&r.push(i);return r}static findReferencingProperty(e,t){for(let[r,i]of Object.entries(e))if(this.containsReference(i,t))return r}static containsReference(e,t){if(!e)return!1;let r=t.replace(/\.md$/,"");if(typeof e=="string"){let i=/\[\[([^\[\]]+)\]\]/g,s;for(;(s=i.exec(e))!==null;){let c=s[1].split("|")[0].trim();if(c===r||c.endsWith(`/${r}`))return!0}return!1}return Array.isArray(e)?e.some(i=>this.containsReference(i,t)):!1}static isAssetArchived(e){let t=e?.exo__Asset_isArchived;if(t!=null){if(t===!0||t===1)return!0;if(typeof t=="string"){let i=t.toLowerCase().trim();if(i==="true"||i==="yes"||i==="1")return!0}if(typeof t=="boolean")return t}let r=e?.archived;if(r==null)return!1;if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let i=r.toLowerCase().trim();return i==="true"||i==="yes"||i==="1"}return!1}static getPropertyValue(e,t){return t==="Name"||t==="title"?e.title:t==="created"?e.created:t==="modified"?e.modified:t==="path"?e.path:e.metadata?.[t]}static ensureQuoted(e){return!e||e==='""'?'""':e.startsWith('"')&&e.endsWith('"')?e:`"${e}"`}static buildFileContent(e,t){let r=Object.entries(e).map(([s,a])=>{if(Array.isArray(a)){let c=a.map(l=>` - ${l}`).join(`
|
|
89
|
+
Details: ${t.message}`:"";console.error(`[Exocortex ERROR]${s} ${e}${a}`)}}};rp.LoggingService=Au;Au.isVerbose=!1;Au.isDevelopment=void 0});var r3=v(ti=>{"use strict";var CM=ti&&ti.__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},IM=ti&&ti.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(ti,"__esModule",{value:!0});ti.GroundingExecutor=ti.ServiceRegistry=void 0;var RM=ve(),PM=hn(),fo=ec(),OM=Hi(),DM=pa(),np=class{static{o(this,"ServiceRegistry")}constructor(){this.services=new Map}register(e,t){this.services.set(e,t)}get(e){return this.services.get(e)}has(e){return this.services.has(e)}getRegisteredIds(){return Array.from(this.services.keys())}};ti.ServiceRegistry=np;var t3=20,H1=class{static{o(this,"GroundingExecutor")}constructor(e,t,r){this.frontmatterService=new OM.FrontmatterService,this.fileReader=e,this.fileWriter=t,this.serviceRegistry=r}async execute(e,t,r,i){try{switch(e.type){case fo.GroundingType.PROPERTY_SET:return await this.executePropertySet(e,t,r);case fo.GroundingType.PROPERTY_DELETE:return await this.executePropertyDelete(e,r);case fo.GroundingType.COMPOSITE:return await this.executeComposite(e,t,r,i,0);case fo.GroundingType.SERVICE_CALL:return await this.executeServiceCall(e,t,i);case fo.GroundingType.CREATE_INSTANCE:return await this.executeCreateInstance(e,t,i);case fo.GroundingType.SPARQL_UPDATE:return{success:!1,error:"sparql_update grounding not yet implemented. Use property_set/property_delete instead."};default:return{success:!1,error:`Unknown grounding type: ${e.type}`}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}async executePropertySet(e,t,r){if(!e.targetProperty)return{success:!1,error:"property_set requires targetProperty"};if(e.targetValue===void 0)return{success:!1,error:"property_set requires targetValue"};let i=this.substituteVariables(e.targetValue,t),s=await this.fileReader.readFile(r),a=this.frontmatterService.updateProperty(s,e.targetProperty,i);return await this.fileWriter.updateFile(r,a),{success:!0}}async executePropertyDelete(e,t){if(!e.targetProperty)return{success:!1,error:"property_delete requires targetProperty"};let r=await this.fileReader.readFile(t),i=this.frontmatterService.removeProperty(r,e.targetProperty);return await this.fileWriter.updateFile(t,i),{success:!0}}async executeComposite(e,t,r,i,s){if(s>=t3)return{success:!1,error:`Composite grounding exceeded maximum depth of ${t3}`};let a=e.steps??[];if(a.length===0)return{success:!0};let c;try{c=await this.fileReader.readFile(r)}catch{}let l=[];try{for(let u=0;u<a.length;u++){let f=a[u],d=await this.executeStep(f,t,r,i,s+1);if(!d.success)return await this.rollback(c,r,l),{success:!1,error:`Composite step ${u} failed: ${d.error}`};l.push(u)}return{success:!0}}catch(u){return await this.rollback(c,r,l),{success:!1,error:`Composite execution failed: ${u instanceof Error?u.message:String(u)}`}}}async executeServiceCall(e,t,r){let i=e.targetProperty;if(!i)return{success:!1,error:"service_call requires targetProperty as serviceId"};let s=this.serviceRegistry.get(i);if(!s)return{success:!1,error:`Service not found: "${i}". Registered services: ${this.serviceRegistry.getRegisteredIds().join(", ")||"none"}`};let a=r;if(e.targetValue)try{let c=JSON.parse(e.targetValue);typeof c=="object"&&c!==null&&(a={...c,...r??{}})}catch{}return await s.execute(t,a),{success:!0}}async executeCreateInstance(e,t,r){if(!e.targetFolder)return{success:!1,error:"create_instance requires targetFolder"};let i=(0,PM.v4)(),s=r?.label??"Untitled",a={exo__Asset_uid:i,exo__Asset_createdAt:new Date().toISOString(),exo__Asset_label:s};if(s!=="Untitled"&&(a.aliases=[s]),e.targetClass&&(a.exo__Instance_class=[`"[[${e.targetClass}]]"`]),e.targetPrototype&&(a.exo__Asset_prototype=`"[[${e.targetPrototype}]]"`),t&&(a.exo__Asset_source=`"[[${t}]]"`),r)for(let[u,f]of Object.entries(r))u!=="label"&&f!=null&&(a[u]=f);let c=this.frontmatterService.createFrontmatter("",a),l=`${e.targetFolder}/${i}.md`;return await this.fileWriter.createFile(l,c),{success:!0}}async executeStep(e,t,r,i,s){return e.type===fo.GroundingType.COMPOSITE?this.executeComposite(e,t,r,i,s):this.execute(e,t,r,i)}async rollback(e,t,r){if(e!==void 0)try{await this.fileWriter.updateFile(t,e)}catch(i){DM.LoggingService.error(`[GroundingExecutor] Rollback failed for ${t}`,i instanceof Error?i:new Error(String(i)))}}substituteVariables(e,t){let r=new Date().toISOString(),i=r.slice(0,10);return e.replace(/\$target/g,t).replace(/\$now/g,r).replace(/\$today/g,i)}};ti.GroundingExecutor=H1;ti.GroundingExecutor=H1=CM([(0,RM.injectable)(),IM("design:paramtypes",[Object,Object,np])],H1)});var rn=v(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});ip.DateFormatter=void 0;var Q1=class n{static{o(this,"DateFormatter")}static toISOTimestamp(e){return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toLocalTimestamp(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0");return`${t}-${r}-${i}T${s}:${a}:${c}`}static toDateWikilink(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`"[[${t}-${r}-${i}]]"`}static getTodayWikilink(){return n.toDateWikilink(new Date)}static toDateString(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}static parseWikilink(e){let r=e.replace(/^["']|["']$/g,"").match(/\[\[(\d{4}-\d{2}-\d{2})\]\]/);return r?r[1]:null}static addDays(e,t){let r=new Date(e);return r.setDate(r.getDate()+t),r}static isSameDay(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}static getTodayStartTimestamp(){let e=new Date;return e.setHours(0,0,0,0),n.toLocalTimestamp(e)}static toTimestampAtStartOfDay(e){let t=e.split("-").map(Number);if(t.length!==3||t.some(isNaN))throw new Error(`Invalid date format: ${e}. Expected YYYY-MM-DD`);let[r,i,s]=t,a=new Date(r,i-1,s,0,0,0,0);if(isNaN(a.getTime()))throw new Error(`Invalid date values: ${e}`);return n.toLocalTimestamp(a)}static normalizeTimestamp(e){if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(e))return e;let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp format: ${e}`);return n.toISOTimestamp(t)}static isISOTimestamp(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(e)}};ip.DateFormatter=Q1});var Cu=v(Os=>{"use strict";var FM=Os&&Os.__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},NM=Os&&Os.__metadata||function(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)};Object.defineProperty(Os,"__esModule",{value:!0});Os.WorkflowEngine=void 0;var LM=ve(),Y1=class{static{o(this,"WorkflowEngine")}constructor(e){this.definition=e}getAvailableTransitions(e){return this.definition.transitions.filter(t=>t.from===e&&!t.isRollback)}getRollbackTransitions(e){return this.definition.transitions.filter(t=>t.from===e&&t.isRollback)}getAllTransitions(e){return this.definition.transitions.filter(t=>t.from===e)}canTransition(e,t){return this.definition.transitions.some(r=>r.from===e&&r.to===t)}getPreviousStatus(e){return this.definition.transitions.find(r=>r.from===e&&r.isRollback)?.to??null}getNextStates(e){return this.getAvailableTransitions(e).map(t=>t.to)}isTerminalState(e){return this.definition.terminalStates.includes(e)}isInitialState(e){return this.definition.initialState===e}getTimestampsForStatus(e){return this.definition.states.find(r=>r.status===e)?.timestampOnEnter??[]}getTransition(e,t){return this.definition.transitions.find(r=>r.from===e&&r.to===t)}getOrderedStates(){return this.definition.states.map(e=>e.status)}getDefinition(){return this.definition}validate(){let e=[],t=new Set(this.definition.states.map(i=>i.status));this.definition.states.length===0&&e.push("Workflow must have at least one state"),t.has(this.definition.initialState)||e.push(`Initial state "${this.definition.initialState}" is not in the states list`);for(let i of this.definition.terminalStates)t.has(i)||e.push(`Terminal state "${i}" is not in the states list`);for(let i of this.definition.transitions)t.has(i.from)||e.push(`Transition "${i.label}" references unknown source state "${i.from}"`),t.has(i.to)||e.push(`Transition "${i.label}" references unknown target state "${i.to}"`);for(let i of this.definition.states){if(this.definition.terminalStates.includes(i.status))continue;this.definition.transitions.filter(a=>a.from===i.status&&!a.isRollback).length===0&&e.push(`State "${i.status}" has no outgoing forward transitions (dead end)`)}let r=new Set;for(let i of this.definition.transitions){let s=`${i.from}\u2192${i.to}`;r.has(s)&&e.push(`Duplicate transition: ${s}`),r.add(s)}return{valid:e.length===0,errors:e}}};Os.WorkflowEngine=Y1;Os.WorkflowEngine=Y1=FM([(0,LM.injectable)(),NM("design:paramtypes",[Object])],Y1)});var n3=v(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.EFFORT_WORKFLOW_PROPERTY=Qi.WorkflowTransitionProperty=Qi.WorkflowStateProperty=Qi.WorkflowProperty=void 0;Qi.WorkflowProperty={TARGET_CLASS:"ems__Workflow_targetClass",INITIAL_STATE:"ems__Workflow_initialState",TERMINAL_STATES:"ems__Workflow_terminalStates",IS_DEFAULT:"ems__Workflow_isDefault"};Qi.WorkflowStateProperty={WORKFLOW:"ems__WorkflowState_workflow",STATUS:"ems__WorkflowState_status",ORDER:"ems__WorkflowState_order",OPTIONAL:"ems__WorkflowState_optional",TIMESTAMP_ON_ENTER:"ems__WorkflowState_timestampOnEnter",BADGE_COLOR:"ems__WorkflowState_badgeColor"};Qi.WorkflowTransitionProperty={WORKFLOW:"ems__WorkflowTransition_workflow",FROM:"ems__WorkflowTransition_from",TO:"ems__WorkflowTransition_to",LABEL:"ems__WorkflowTransition_label",ICON:"ems__WorkflowTransition_icon",IS_ROLLBACK:"ems__WorkflowTransition_isRollback"};Qi.EFFORT_WORKFLOW_PROPERTY="ems__Effort_workflow"});var Yi=v(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});sp.MetadataHelpers=void 0;var X1=class{static{o(this,"MetadataHelpers")}static findAllReferencingProperties(e,t){let r=[];for(let[i,s]of Object.entries(e))this.containsReference(s,t)&&r.push(i);return r}static findReferencingProperty(e,t){for(let[r,i]of Object.entries(e))if(this.containsReference(i,t))return r}static containsReference(e,t){if(!e)return!1;let r=t.replace(/\.md$/,"");if(typeof e=="string"){let i=/\[\[([^\[\]]+)\]\]/g,s;for(;(s=i.exec(e))!==null;){let c=s[1].split("|")[0].trim();if(c===r||c.endsWith(`/${r}`))return!0}return!1}return Array.isArray(e)?e.some(i=>this.containsReference(i,t)):!1}static isAssetArchived(e){let t=e?.exo__Asset_isArchived;if(t!=null){if(t===!0||t===1)return!0;if(typeof t=="string"){let i=t.toLowerCase().trim();if(i==="true"||i==="yes"||i==="1")return!0}if(typeof t=="boolean")return t}let r=e?.archived;if(r==null)return!1;if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let i=r.toLowerCase().trim();return i==="true"||i==="yes"||i==="1"}return!1}static getPropertyValue(e,t){return t==="Name"||t==="title"?e.title:t==="created"?e.created:t==="modified"?e.modified:t==="path"?e.path:e.metadata?.[t]}static ensureQuoted(e){return!e||e==='""'?'""':e.startsWith('"')&&e.endsWith('"')?e:`"${e}"`}static buildFileContent(e,t){let r=Object.entries(e).map(([s,a])=>{if(Array.isArray(a)){let c=a.map(l=>` - ${l}`).join(`
|
|
90
90
|
`);return`${s}:
|
|
91
91
|
${c}`}return`${s}: ${a}`}).join(`
|
|
92
92
|
`),i=t?`
|
|
@@ -744,7 +744,7 @@ ${Pr.dump(i,{lineWidth:-1})}---
|
|
|
744
744
|
\u{1F50D} Dry-run: command "${l.name}" on "${t.target}"
|
|
745
745
|
`),console.log(" Precondition: passed \u2705"),console.log(" Grounding (would execute):"),bS(l.grounding," ");return}let h=new Mt.ServiceRegistry;zO(h);let p=new Ft(i),b=await new Mt.GroundingExecutor(p,p,h).execute(l.grounding,u,t.target);if(r==="json"){let E=Z.success({command:l.name,target:t.target,preconditionPassed:!0,executed:!0,success:b.success,...b.error&&{error:b.error},...l.successMessage&&b.success&&{message:l.successMessage}});console.log(JSON.stringify(E,null,2))}else if(b.success){let E=l.successMessage??`Command "${l.name}" executed successfully.`;console.log(`\u2705 ${E}`)}else console.log(`\u274C Command "${l.name}" failed: ${b.error}`),process.exitCode=5}catch(i){k.handle(i)}}),n.command("validate").description("Validate all dynamic command definitions in vault").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--output <type>","Response format: text|json","text").action(async e=>{let t=e.output||"text";k.setFormat(t);try{let r=(0,fs.resolve)(e.vault);if(!(0,us.existsSync)(r))throw new Ce(r);let i=eH(r);if(t==="json"){let s=Z.success({totalCommands:_S(r).length,totalIssues:i.reduce((a,c)=>a+c.issues.length,0),commandsWithIssues:i.length,issues:i});console.log(JSON.stringify(s,null,2))}else{let s=_S(r);if(i.length===0)console.log(`\u2705 All ${s.length} dynamic command(s) are valid.`);else{let a=i.reduce((c,l)=>c+l.issues.length,0);console.log(`\u274C Found ${a} issue(s) in ${i.length} command(s) out of ${s.length} total:
|
|
746
746
|
`);for(let c of i){console.log(` \u{1F4C4} ${c.label} (${c.uid}):`);for(let l of c.issues)console.log(` \u2022 ${l}`);console.log()}process.exitCode=5}}}catch(r){k.handle(r)}}),n}o(HO,"dynamicCommandCommand");function _S(n){let e=[],t=[];SS(n,t);for(let{filePath:r,fm:i}of t){if(!Ml(i,"exocmd__Command"))continue;let s=i.exo__Asset_uid??"",a=i.exo__Asset_label??QO(r),c=i.exocmd__Command_category,l=i.exocmd__Command_icon,u=!!i.exocmd__Command_precondition,f=i.exocmd__Command_grounding,d;if(f){let h=Eg(String(f)),p=t.find(_=>_.fm.exo__Asset_uid===h&&Ml(_.fm,"exocmd__Grounding"));p&&(d=p.fm.exocmd__Grounding_type)}e.push({filePath:r,uid:s,label:a,category:c,icon:l,hasPrecondition:u,groundingType:d})}return e}o(_S,"scanCommands");async function Zz(n,e){let{tripleStore:t}=await vS(n),r=new Mt.CommandResolver(t),i=await r.findBindings(),s=new Set;for(let c of i)s.add(c.commandRef);let a=[];for(let c of s){let l=await r.loadCommand(c);l&&a.push({filePath:"",uid:l.id,label:l.name,category:l.category,icon:l.icon,hasPrecondition:!!l.precondition,groundingType:l.grounding.type})}return a}o(Zz,"listCommandsForTarget");function eH(n){let e=[],t=[];SS(n,t);let r=new Map;for(let i of t){let s=i.fm.exo__Asset_uid;s&&r.set(s,i)}for(let{filePath:i,fm:s}of t){if(!Ml(s,"exocmd__Command"))continue;let a=s.exo__Asset_uid??"",c=s.exo__Asset_label??QO(i),l=[];a||l.push("Missing exo__Asset_uid"),s.exo__Asset_label||l.push("Missing exo__Asset_label");let u=s.exocmd__Command_grounding;if(!u)l.push("Missing exocmd__Command_grounding (required)");else{let h=Eg(String(u)),p=r.get(h);if(!p)l.push(`Grounding reference "${h}" not found in vault`);else if(!Ml(p.fm,"exocmd__Grounding"))l.push(`Grounding reference "${h}" is not an exocmd__Grounding asset`);else{let _=p.fm,b=_.exocmd__Grounding_type;b?(Object.values(Mt.GroundingType).includes(b)||l.push(`Grounding "${h}" has invalid type "${b}"`),(b===Mt.GroundingType.PROPERTY_SET||b===Mt.GroundingType.PROPERTY_DELETE)&&!_.exocmd__Grounding_targetProperty&&l.push(`Grounding "${h}" (${b}) missing targetProperty`),b===Mt.GroundingType.PROPERTY_SET&&!_.exocmd__Grounding_targetValue&&l.push(`Grounding "${h}" (property_set) missing targetValue`),b===Mt.GroundingType.SERVICE_CALL&&((_.exocmd__Grounding_serviceId??_.exocmd__Grounding_targetProperty)||l.push(`Grounding "${h}" (service_call) missing serviceId and targetProperty`))):l.push(`Grounding "${h}" missing exocmd__Grounding_type`)}}let f=s.exocmd__Command_precondition;if(f){let h=Eg(String(f)),p=r.get(h);if(!p)l.push(`Precondition reference "${h}" not found in vault`);else if(!Ml(p.fm,"exocmd__Precondition"))l.push(`Precondition reference "${h}" is not an exocmd__Precondition asset`);else{let _=p.fm.exocmd__Precondition_sparqlAsk,b=p.fm.exocmd__Precondition_hostFunction;!_&&!b&&l.push(`Precondition "${h}" missing both sparqlAsk and hostFunction`)}}t.some(h=>Ml(h.fm,"exocmd__CommandBinding")?Eg(String(h.fm.exocmd__CommandBinding_command??""))===a:!1)||l.push("No CommandBinding references this command (command will be unused)"),l.length>0&&e.push({uid:a,label:c,filePath:i,issues:l})}return e}o(eH,"validateCommands");async function vS(n){let e=new hr(n),r=await new Mt.NoteToRDFConverter(e).convertVault(),i=new Mt.InMemoryTripleStore;return await i.addAll(r),{tripleStore:i}}o(vS,"buildTripleStore");function bS(n,e){if(console.log(`${e}ID: ${n.id}`),console.log(`${e}Label: ${n.label}`),console.log(`${e}Type: ${n.type}`),n.targetProperty&&console.log(`${e}Target property: ${n.targetProperty}`),n.targetValue!==void 0&&console.log(`${e}Target value: ${n.targetValue}`),n.sparqlUpdate&&console.log(`${e}SPARQL UPDATE: ${n.sparqlUpdate}`),n.steps&&n.steps.length>0){console.log(`${e}Steps (${n.steps.length}):`);for(let t=0;t<n.steps.length;t++)console.log(`${e} Step ${t+1}:`),bS(n.steps[t],e+" ")}}o(bS,"printGrounding");function SS(n,e){let t;try{t=(0,us.readdirSync)(n,{withFileTypes:!0})}catch{return}for(let r of t){let i=(0,fs.join)(n,r.name);if(r.isDirectory()){if(r.name.startsWith(".")||r.name==="node_modules")continue;SS(i,e)}else if(r.name.endsWith(".md"))try{let s=(0,us.readFileSync)(i,"utf-8"),a=Jz.parse(s);a.exists&&e.push({filePath:i,fm:tH(a.content)})}catch{}}}o(SS,"collectParsedFiles");function tH(n){let e={},t=n.split(`
|
|
747
|
-
`),r="",i=null;for(let s of t){if(s.match(/^\s+-\s+/)&&r){let c=s.replace(/^\s+-\s+/,"").trim();i||(i=[]),i.push(c),e[r]=i;continue}let a=s.match(/^([a-zA-Z0-9_]+):\s*(.*)/);if(a){r=a[1],i=null;let c=a[2].trim();if((c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),c==="true"?c=!0:c==="false"&&(c=!1),c===""){e[r]=[],i=e[r];continue}e[r]=c}}return e}o(tH,"parseYamlFrontmatter");function Ml(n,e){let t=n.exo__Instance_class;if(!t)return!1;let r=Array.isArray(t)?t:[t];for(let i of r){if(typeof i!="string")continue;let s=i.match(/\[\[([^|\]]+)/);if((s?s[1]:i)===e)return!0}return!1}o(Ml,"hasClass");function Eg(n){if(typeof n!="string")return"";let e=n.replace(/["'[\]]/g,"").trim(),t=e.indexOf("|");return t>=0?e.substring(0,t).trim():e}o(Eg,"normalizeWikilink");function QO(n){return(0,fs.basename)(n,".md")}o(QO,"extractLabelFromFilename");function YO(n){n.addCommand(WR()),n.addCommand(QR()),n.addCommand(YR())}o(YO,"addQuerySubcommands");function XO(n){let e=new Le;e.name("exocortex").description("CLI tool for Exocortex knowledge management system").version(n??"15.90.
|
|
747
|
+
`),r="",i=null;for(let s of t){if(s.match(/^\s+-\s+/)&&r){let c=s.replace(/^\s+-\s+/,"").trim();i||(i=[]),i.push(c),e[r]=i;continue}let a=s.match(/^([a-zA-Z0-9_]+):\s*(.*)/);if(a){r=a[1],i=null;let c=a[2].trim();if((c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),c==="true"?c=!0:c==="false"&&(c=!1),c===""){e[r]=[],i=e[r];continue}e[r]=c}}return e}o(tH,"parseYamlFrontmatter");function Ml(n,e){let t=n.exo__Instance_class;if(!t)return!1;let r=Array.isArray(t)?t:[t];for(let i of r){if(typeof i!="string")continue;let s=i.match(/\[\[([^|\]]+)/);if((s?s[1]:i)===e)return!0}return!1}o(Ml,"hasClass");function Eg(n){if(typeof n!="string")return"";let e=n.replace(/["'[\]]/g,"").trim(),t=e.indexOf("|");return t>=0?e.substring(0,t).trim():e}o(Eg,"normalizeWikilink");function QO(n){return(0,fs.basename)(n,".md")}o(QO,"extractLabelFromFilename");function YO(n){n.addCommand(WR()),n.addCommand(QR()),n.addCommand(YR())}o(YO,"addQuerySubcommands");function XO(n){let e=new Le;e.name("exocortex").description("CLI tool for Exocortex knowledge management system").version(n??"15.90.9");let t=e.command("exoql").description("ExoQL query execution and cache management");YO(t);let r=e.command("sparql").description("(deprecated) Use 'exoql' instead");return YO(r),r.hook("preAction",()=>{console.error('\u26A0\uFE0F "sparql" is deprecated. Use "exoql" instead.')}),e.addCommand(nO()),e.addCommand(aO()),e.addCommand(oO()),e.addCommand(lO()),e.addCommand(uO()),e.addCommand(mO()),e.addCommand(vO()),e.addCommand(CO()),e.addCommand(PO()),e.addCommand(LO()),e.addCommand(jO()),e.addCommand($O()),e.addCommand(UO()),e.addCommand(HO()),e}o(XO,"createProgram");XO().parse();0&&(module.exports={createProgram});
|
|
748
748
|
/*! Bundled license information:
|
|
749
749
|
|
|
750
750
|
reflect-metadata/Reflect.js:
|