@kanonak-protocol/sdk 3.8.0 → 3.10.0
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/browser.js +18 -18
- package/dist/index.js +25 -25
- package/dist/parsing/index.js +1 -1
- package/dist/reasoning/index.js +1 -1
- package/dist/resolution/index.js +1 -1
- package/dist/validation/index.js +10 -10
- package/dist/validation/rules/repository/EmbeddedKanonakTypeRule.d.ts +36 -9
- package/package.json +2 -2
package/dist/parsing/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ee=Object.defineProperty;var te=(p,e)=>()=>(p&&(e=p(p=0)),e);var ne=(p,e)=>{for(var t in e)ee(p,t,{get:e[t],enumerable:!0})};var J={};ne(J,{KanonakUri:()=>R});function re(p,e,t){return{major:p,minor:e,patch:t,toString:()=>`${p}.${e}.${t}`,equals:n=>!n||typeof n!="object"?!1:n.major===p&&n.minor===e&&n.patch===t,getHashCode:()=>p<<20|e<<10|t,compareTo:n=>p!==n.major?p-n.major:e!==n.minor?e-n.minor:t-n.patch}}var R,q=te(()=>{"use strict";R=class p{constructor(e,t,n,r){this.publisher=e;this.package_=t;this.name=n;this.version=r}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("/");if(t.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[n,r,o]=t;if(!n||!r||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let s=r.indexOf("@");if(s===-1)return new p(n,r,o,void 0);let i=r.substring(0,s),a=r.substring(s+1);if(!i||!a)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let c=a.split(".").map(Number),u=re(c[0]||0,c[1]||0,c[2]||0);return new p(n,i,o,u)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});import*as F from"js-yaml";var w=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let n=t.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return t.document}parseWithErrors(e){let t=[],n;try{e=e.replace(/^\uFEFF/,"");let r=F.load(e);if(!r||typeof r!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let o=this.extractMetadata(r),s=this.extractBody(r,o);return n={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:t,isValid:!0}}catch(r){let o=r,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let n=e.metadata.namespace_,r={type:"Package",publisher:n.publisher};n.version&&(r.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(r.imports=this.serializeImports(e.metadata.imports)),t[n.package_]=r}return Object.assign(t,e.body),F.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let n=[];for(let r of Object.values(t))n.push(...r);return n},enumerable:!0,configurable:!0}),e}createVersion(e,t,n){return{major:e,minor:t,patch:n,toString:()=>`${e}.${t}.${n}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:n-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[n,r]of Object.entries(e))if(r&&typeof r=="object"&&r.type==="Package"){t.type_="Package";let o=n,s=r.publisher,i=r.version?this.parseVersion(r.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:a=>!a||typeof a!="object"?!1:a.publisher===s&&a.package_===o&&(!i||!a.version||i.equals(a.version)),getHashCode:()=>{let a=0;for(let c=0;c<s.length;c++)a=(a<<5)-a+s.charCodeAt(c);for(let c=0;c<o.length;c++)a=(a<<5)-a+o.charCodeAt(c);return a|0}}),r.imports&&Array.isArray(r.imports)&&(t.imports=this.parseImportsV3(r.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let n=e.kanonak;return(n.publisher||n.package||n.version)&&(t.namespace_=this.parseNamespace(n)),n.imports&&typeof n.imports=="object"&&(t.imports=this.parseImportsLegacy(n.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let n={},r;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){r=o;break}for(let[o,s]of Object.entries(e))o!==r&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(n[o]=s);return n}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===o[1]&&i.package_===o[2]&&(!s||!i.version||s.equals(i.version)),getHashCode:()=>{let i=0;for(let a=0;a<o[1].length;a++)i=(i<<5)-i+o[1].charCodeAt(a);for(let a=0;a<o[2].length;a++)i=(i<<5)-i+o[2].charCodeAt(a);return i|0}}}}let t=e.publisher||"",n=e.package||"",r=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:n,version:r,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===n&&(!r||!o.version||r.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<n.length;s++)o=(o<<5)-o+n.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let r=n.publisher;if(!r)throw new Error("PublisherImport requires 'publisher' property");t[r]||(t[r]=[]);for(let o of n.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,r);t[r].push(s)}}else{let r=this.parseImportFromEmbeddedObject(n,n.publisher),o=r.publisher||"";t[o]||(t[o]=[]),t[o].push(r)}return t}parseImportsLegacy(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.map(o=>this.parseImport(o,n)));return t}parseImportFromEmbeddedObject(e,t){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let r=e.match;if(!r)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),i=this.parseVersionOperator(r),a=this.calculateMaxVersion(r,s),c=e.alias;return{package_:`${n} ${r} ${s.toString()}`,publisher:t,packageName:n,versionOperator:i,version:s,alias:c,minVersion:s,maxVersion:a,toEmbeddedObject:()=>{let u={package:n,match:r,version:s.toString()};return c&&(u.alias=c),u},toString:()=>c?`${n} ${r} ${s.toString()} as ${c}`:`${n} ${r} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let a=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(a){let u=a[1].trim(),m=a[2],l=this.parseVersion(a[3].trim()),f=a[4].trim(),g=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:u,versionOperator:g,version:l,alias:f,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let d={package:u,match:m,version:l.toString()};return f&&(d.alias=f),d},toString:()=>`${u} ${m} ${l.toString()} as ${f}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let u=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),f=this.parseVersionOperator(m),g=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:u,versionOperator:f,version:l,alias:void 0,minVersion:l,maxVersion:g,toEmbeddedObject:()=>({package:u,match:m,version:l.toString()}),toString:()=>`${u} ${m} ${l.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),r=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][n],i=this.calculateMaxVersion(e.operator||"~",r);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:n,version:r,alias:e.alias,minVersion:r,maxVersion:i,toEmbeddedObject:()=>{let a={package:o,match:s,version:r.toString()};return e.alias&&(a.alias=e.alias),a},toString:()=>`${o} ${s} ${r.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[n,r]of Object.entries(e)){let o={publisher:n,packages:r.map(s=>{let i=["=","~","^","*"][s.versionOperator],a={package:s.packageName,match:i,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(a.alias=s.alias),a})};t.push(o)}return t}};var K=class{};var A=class extends K{statement=[]};var $=class extends A{namespace;name;icon};var E=class extends A{name};q();var y=class p extends K{subject;static parse(e){let t=new p;return t.subject=R.parse(e),t}};var _=class extends K{value};var S=class{predicate;object};var I=class extends S{};var j=class p extends I{static parse(e,t){let n=new p;return n.predicate=y.parse(e),n.object=t,n}};var N=class p extends I{static parse(e,t){let n=new p;return n.predicate=y.parse(e),n.object=t,n}};var L=class extends I{};var C=class p extends S{static parse(e,t){let n=new p;return n.predicate=y.parse(e),n.object=y.parse(t),n}};var V=class extends S{};var D=class extends S{};q();function H(p){if(Array.isArray(p))return p.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=p?.toString();return e?[e]:[]}var W=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let n=t.metadata?.namespace_?.toString()??"unknown",r=this.cache.get(n);if(r){let s=r.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(n,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let n=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let r=e.split("."),o=r[0],s=r[1],i=await this.findDocumentForAlias(t,o);return i?await this.resolveAllEntitiesAsync(s,i):[]}return n.filter(r=>r.entityName===e)}async buildAllEntitiesIndexAsync(e,t,n){let r=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),r;t.add(o);let s=n.length===0?o:`${n} \u2192 ${o}`;for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};r.push({entityName:i,uri:new R(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:a,definedInNamespace:o,isImported:n.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${r.length} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((a,c)=>a+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[a,c]of Object.entries(e.metadata.imports))for(let u of c)try{this.logger?.debug?.(`Resolving import: ${a}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(a,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,s);r.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${u.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${a}/${u.packageName} for namespace ${o}. Error: ${l.message}`,l),new Error(`Failed to process import ${a}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return r}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,n){let r=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),r;t.add(o);let s=n.length===0?o:`${n} \u2192 ${o}`,i=0;for(let[a,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!r.has(a)){let u=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};r.set(a,{entityName:a,uri:new R(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,u),entity:c,definedInNamespace:o,isImported:n.length>0,importPath:s}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((c,u)=>c+u.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[c,u]of Object.entries(e.metadata.imports))for(let m of u)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(c,m);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let f=await this.buildEntityIndexAsyncInternal(l,t,s),g=0;for(let[h,d]of f.entries())if(r.has(h)||(r.set(h,d),g++),m.alias&&!h.includes(".")){let P=`${m.alias}.${h}`;r.has(P)||(r.set(P,d),g++)}this.logger?.debug?.(`Merged ${g} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let f=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${o}. Error: ${f.message}`,f),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${o}. See inner exception for details.`,{cause:l})}}return r}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[n,r]of Object.entries(e.metadata.imports))for(let o of r){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(n,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(n,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,n){if(e===t)return!0;let r=new Set;return await this.isSubclassOfRecursiveAsync(e,t,n,r)}async isSubclassOfRecursiveAsync(e,t,n,r){if(r.has(e))return!1;r.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubclassOfRecursiveAsync(a,t,n,r))return!0}return!1}async isSubpropertyOfAsync(e,t,n){if(e===t)return!0;let r=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,n,r)}async isSubpropertyOfRecursiveAsync(e,t,n,r){if(r.has(e))return!1;r.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubpropertyOfRecursiveAsync(a,t,n,r))return!0}return!1}};var U=class p{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&p.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return p.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,t);if(n){let r=n.entity.type;if(r){let o=String(r);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var Y=class{constructor(e){}async parseKanonaks(e){let t=[],n=await e.getAllDocumentsAsync(),r=new W(e),o=new U(r);for(let a of n){let c=a.metadata.namespace_?.toString()??"";for(let[u,m]of Object.entries(a.body)){let l=new $,f=this.resolveCanonicalEntity(u,a,c);l.namespace=f.namespace,l.name=f.name,l.statement=[];let g=await this.parseStatements(m,a,r,o,e);l.statement.push(...g),t.push(l)}}let s=new Map,i=[];for(let a of t)if(a instanceof $){let c=`${a.namespace}/${a.name}`,u=s.get(c);u?u.statement.push(...a.statement):(s.set(c,a),i.push(a))}else i.push(a);return i}resolveCanonicalEntity(e,t,n){if(!e.includes(".")||!t.metadata?.imports)return{namespace:n,name:e};let r=e.indexOf("."),o=e.substring(0,r),s=e.substring(r+1);for(let[i,a]of Object.entries(t.metadata.imports))for(let c of a)if((c.alias??c.packageName)===o){let m=c.version;return{namespace:`${i}/${c.packageName}@${m.major}.${m.minor}.${m.patch}`,name:s}}return{namespace:n,name:e}}async parseStatements(e,t,n,r,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[i,a]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,n,o,r);if(!c)continue;let u=await this.parsePropertyValue(i,a,c,t,n,r);u&&s.push(u)}catch(c){console.error(`Error parsing property ${i}:`,c)}return s}async getPropertyMetadata(e,t,n,r,o){let s=await n.resolveEntityAsync(e,t);if(!s)return;let i=s.entity,a=i.type?.toString()??"",c=a.includes(".")?a.substring(a.lastIndexOf(".")+1):a;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=o.getPropertyTypeClassification(a),l=i.range?.toString(),f;if(m==="ObjectProperty")f="ObjectProperty";else if(m==="DatatypeProperty")f="DatatypeProperty";else{let h=l&&l.includes(".")?l.substring(l.lastIndexOf(".")+1):l??"";(l?o.isKnownXsdDatatypeName(l):!1)||h==="Literal"?f="DatatypeProperty":f="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:f,range:l,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,n,r,o,s){let i=n.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,n,r,o,s);if(n.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,n);if(n.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,n,r,o,s)}}parseDatatypeValue(e,t,n){if(t instanceof Date)return j.parse(e,t.toISOString());if(typeof t=="string")return j.parse(e,t);if(typeof t=="number")return N.parse(e,t);if(typeof t=="boolean"){let r=new L;return r.predicate=y.parse(e),r.object=t,r}}async parseObjectValue(e,t,n,r,o,s){if(typeof t=="string"){let i=await this.resolveReference(t,r,o);if(!i)return;let a=new C;return a.predicate=y.parse(e),a.object=i,a}if(typeof t=="object"&&!Array.isArray(t)){let i=new E;if(i.statement=await this.parseStatements(t,r,o,s,{}),i.statement.length>0){let u=new V;return u.predicate=y.parse(e),u.object=i,u}let a=[];for(let[u,m]of Object.entries(t))if(typeof m=="object"&&m!==null&&!Array.isArray(m)){let l=new E;l.name=u,l.statement=await this.parseStatements(m,r,o,s,{}),a.push(l)}else if(typeof m=="string"){let l=await this.resolveReference(m,r,o);l&&a.push(l)}if(a.length>0){let u=new D;return u.predicate=y.parse(e),u.object=a,u}let c=new V;return c.predicate=y.parse(e),c.object=i,c}}async parseListValue(e,t,n,r,o,s){let i=[],a=n.propertyType==="DatatypeProperty";for(let u of t){if(a&&(typeof u=="string"||typeof u=="number"||typeof u=="boolean")){let m=new _;m.value=u,i.push(m);continue}if(a&&u instanceof Date){let m=new _;m.value=u.toISOString(),i.push(m);continue}if(typeof u=="string"){let m=await this.resolveReference(u,r,o);m&&i.push(m)}else if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let m=new E;m.statement=await this.parseStatements(u,r,o,s,{}),i.push(m)}}let c=new D;return c.predicate=y.parse(e),c.object=i,c}async resolveReference(e,t,n){let r=await n.resolveEntityAsync(e,t);if(r){let s=new y;return s.subject=r.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(q(),J)),i=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),u=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[l,f]of Object.entries(t.metadata.imports))for(let g of f)if((g.alias??g.packageName)===u){let d=new y;return d.subject=new s(l,g.packageName,m,g.version),d}}}let a=new y;return a.subject=new s(o.publisher,o.package_,e,i),a}return null}async saveKanonaks(e,t){let n=new Map;for(let r of e)r instanceof $&&r.namespace&&(n.has(r.namespace)||n.set(r.namespace,[]),n.get(r.namespace).push(r));for(let[r,o]of n){let s=await this.convertKanonaksToDocument(r,o),i=`${r.split("@")[0]}.yml`;await t.saveDocumentAsync(s,i)}}async serializeToYaml(e,t){let n=e.filter(s=>s instanceof $&&s.namespace===t);if(n.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let r=await this.convertKanonaksToDocument(t,n);return new w().save(r)}async convertKanonaksToDocument(e,t){let r={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let i of Object.values(this.imports))s.push(...i);return s}},body:{}},o=new Map;for(let s of t){let i={};for(let a of s.statement){let[c,u]=this.convertStatementToProperty(a);c&&u!==null&&u!==void 0&&(i[c]=u),this.collectImportsFromStatement(a,e,o)}r.body[s.name]=i}return r}convertStatementToProperty(e){if(e instanceof j)return[e.predicate.subject.name,e.object];if(e instanceof N)return[e.predicate.subject.name,e.object];if(e instanceof L)return[e.predicate.subject.name,e.object];if(e instanceof C)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof D){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof V){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let n of e)n instanceof y?t.push(n.subject.name):n instanceof E&&t.push(this.convertEmbeddedKanonakToValue(n));return t}convertEmbeddedKanonakToValue(e){let t={};for(let n of e.statement){let[r,o]=this.convertStatementToProperty(n);r&&o!==null&&o!==void 0&&(t[r]=o)}return t}collectImportsFromStatement(e,t,n){}};var B=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as oe,LineCounter as se,isMap as x,isPair as k,isScalar as b,isSeq as X}from"yaml";var T=class p{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new p,n=new se,r=oe(e,{lineCounter:n});if(r.errors.length>0||!x(r.contents))return t;G(r.contents,[],n,t);for(let o of r.contents.items){if(!k(o)||!b(o.key))continue;let s=String(o.key.value),i=o.key.range;if(!i)continue;t.entities.set(s,v(i,n));let a=o.value,c=a&&typeof a=="object"&&"range"in a?a.range:void 0;if(c?t.entityBlocks.set(s,v([i[0],i[1],c[2]],n)):t.entityBlocks.set(s,v(i,n)),x(o.value)){let u=new Map,m=new Map,l=new Map;for(let g of o.value.items){if(!k(g)||!b(g.key))continue;let h=String(g.key.value),d=g.key.range;d&&u.set(h,v(d,n));let P=g.value;if(P&&typeof P=="object"&&"range"in P&&Array.isArray(P.range)){let O=P.range;m.set(h,v(O,n))}if(X(P)){let O=[];for(let M of P.items)M&&typeof M=="object"&&"range"in M&&Array.isArray(M.range)&&O.push(v(M.range,n));O.length>0&&l.set(h,O)}}u.size>0&&t.properties.set(s,u),m.size>0&&t.propertyValues.set(s,m),l.size>0&&t.valueListItems.set(s,l);let f=ae(o.value,n);f.length>0&&t.importPackages.set(s,f)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[n,r]of this.entityBlocks)if(z(r,e,t))return n}findPropertyAtPosition(e,t){let n=this.findEntityAtPosition(e,t);if(!n)return;let r=this.properties.get(n),o=this.propertyValues.get(n);if(!r&&!o)return{entityName:n};let s,i;if(o)for(let[a,c]of o)z(c,e,t)&&(!i||Q(c,i))&&(s=a,i=c);if(r)for(let[a,c]of r)z(c,e,t)&&(!i||Q(c,i))&&(s=a,i=c);return s?{entityName:n,propertyName:s}:{entityName:n}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,n]of this.importPackages)for(let r of n)e.push({entityName:t,entry:r});return e}findPropertySourceName(e,t){let n=this.properties.get(e);if(n){if(n.has(t))return t;for(let r of n.keys()){let o=r.lastIndexOf(".");if((o===-1?r:r.substring(o+1))===t)return r}}}getListItemPosition(e,t,n){let r=this.valueListItems.get(e)?.get(t);if(!(!r||n<0||n>=r.length))return r[n]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,n){if(e){if(t!==void 0){if(n!==void 0){let s=this.getListItemPosition(e,t,n);if(s)return s}let r=this.getPropertyValuePosition(e,t);if(r)return r;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function ae(p,e){let t=[];if(!x(p))return t;let n=p.items.find(r=>k(r)&&b(r.key)&&String(r.key.value)==="imports");if(!n||!k(n)||!X(n.value))return t;for(let r of n.value.items){if(!x(r))continue;let o=r.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="publisher");if(!o||!k(o)||!b(o.value))continue;let s=String(o.value.value),i=r.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="packages");if(!(!i||!k(i)||!X(i.value)))for(let a of i.value.items){if(!x(a))continue;let c=a.items.find(d=>k(d)&&b(d.key)&&String(d.key.value)==="package");if(!c||!k(c)||!b(c.value)||!c.value.range)continue;let u=String(c.value.value),m=a.items.find(d=>k(d)&&b(d.key)&&String(d.key.value)==="version"),l=m&&k(m)&&b(m.value)?String(m.value.value):"",f=a.items.find(d=>k(d)&&b(d.key)&&String(d.key.value)==="alias"),g=f&&k(f)&&b(f.value)?String(f.value.value):void 0,h=g!==void 0?{publisher:s,package_:u,version:l,alias:g,position:v(c.value.range,e)}:{publisher:s,package_:u,version:l,position:v(c.value.range,e)};t.push(h)}}return t}function z(p,e,t){return!(e<p.line||e>p.endLine||e===p.line&&t<p.column||e===p.endLine&&t>p.endColumn)}function Q(p,e){let t=p.endLine-p.line,n=e.endLine-e.line;if(t!==n)return t<n;let r=p.endLine===p.line?p.endColumn-p.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return r<o}function G(p,e,t,n){if(x(p)){for(let r of p.items){if(!k(r)||!b(r.key))continue;let o=String(r.key.value),s=[...e,o],i=JSON.stringify(s);r.key.range&&n.setNestedKeyPosition(i,v(r.key.range,t));let a=r.value,c=Z(a);c&&n.setNestedValuePosition(i,v(c,t)),G(a,s,t,n)}return}if(X(p)){for(let r=0;r<p.items.length;r++){let o=p.items[r],s=[...e,r],i=JSON.stringify(s),a=Z(o);a&&n.setNestedValuePosition(i,v(a,t)),G(o,s,t,n)}return}}function Z(p){if(!p||typeof p!="object"||!("range"in p))return;let e=p.range;return Array.isArray(e)&&e.length>=3?e:void 0}function v(p,e){let t=e.linePos(p[0]),n=e.linePos(p[2]);return{line:t.line-1,column:t.col-1,endLine:n.line-1,endColumn:n.col-1}}function ie(p,e){let n=(e??new w).parse(p),r=T.fromContent(p);return{document:n,positions:r}}export{T as KanonakDocumentPositions,Y as KanonakObjectParser,w as KanonakParser,B as PropertyMetadata,ie as parseWithPositions};
|
|
1
|
+
var ee=Object.defineProperty;var te=(p,e)=>()=>(p&&(e=p(p=0)),e);var ne=(p,e)=>{for(var t in e)ee(p,t,{get:e[t],enumerable:!0})};var J={};ne(J,{KanonakUri:()=>R});function re(p,e,t){return{major:p,minor:e,patch:t,toString:()=>`${p}.${e}.${t}`,equals:n=>!n||typeof n!="object"?!1:n.major===p&&n.minor===e&&n.patch===t,getHashCode:()=>p<<20|e<<10|t,compareTo:n=>p!==n.major?p-n.major:e!==n.minor?e-n.minor:t-n.patch}}var R,q=te(()=>{"use strict";R=class p{constructor(e,t,n,r){this.publisher=e;this.package_=t;this.name=n;this.version=r}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("/");if(t.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[n,r,o]=t;if(!n||!r||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let s=r.indexOf("@");if(s===-1)return new p(n,r,o,void 0);let i=r.substring(0,s),a=r.substring(s+1);if(!i||!a)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let c=a.split(".").map(Number),u=re(c[0]||0,c[1]||0,c[2]||0);return new p(n,i,o,u)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});import*as F from"js-yaml";var w=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let n=t.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return t.document}parseWithErrors(e){let t=[],n;try{e=e.replace(/^\uFEFF/,"");let r=F.load(e);if(!r||typeof r!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let o=this.extractMetadata(r),s=this.extractBody(r,o);return n={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:t,isValid:!0}}catch(r){let o=r,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let n=e.metadata.namespace_,r={type:"Package",publisher:n.publisher};n.version&&(r.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(r.imports=this.serializeImports(e.metadata.imports)),t[n.package_]=r}return Object.assign(t,e.body),F.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let n=[];for(let r of Object.values(t))n.push(...r);return n},enumerable:!0,configurable:!0}),e}createVersion(e,t,n){return{major:e,minor:t,patch:n,toString:()=>`${e}.${t}.${n}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:n-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[n,r]of Object.entries(e))if(r&&typeof r=="object"&&r.type==="Package"){t.type_="Package";let o=n,s=r.publisher,i=r.version?this.parseVersion(r.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:a=>!a||typeof a!="object"?!1:a.publisher===s&&a.package_===o&&(!i||!a.version||i.equals(a.version)),getHashCode:()=>{let a=0;for(let c=0;c<s.length;c++)a=(a<<5)-a+s.charCodeAt(c);for(let c=0;c<o.length;c++)a=(a<<5)-a+o.charCodeAt(c);return a|0}}),r.imports&&Array.isArray(r.imports)&&(t.imports=this.parseImportsV3(r.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let n=e.kanonak;return(n.publisher||n.package||n.version)&&(t.namespace_=this.parseNamespace(n)),n.imports&&typeof n.imports=="object"&&(t.imports=this.parseImportsLegacy(n.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let n={},r;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){r=o;break}for(let[o,s]of Object.entries(e))o!==r&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(n[o]=s);return n}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===o[1]&&i.package_===o[2]&&(!s||!i.version||s.equals(i.version)),getHashCode:()=>{let i=0;for(let a=0;a<o[1].length;a++)i=(i<<5)-i+o[1].charCodeAt(a);for(let a=0;a<o[2].length;a++)i=(i<<5)-i+o[2].charCodeAt(a);return i|0}}}}let t=e.publisher||"",n=e.package||"",r=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:n,version:r,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===n&&(!r||!o.version||r.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<n.length;s++)o=(o<<5)-o+n.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let r=n.publisher;if(!r)throw new Error("PublisherImport requires 'publisher' property");t[r]||(t[r]=[]);for(let o of n.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,r);t[r].push(s)}}else{let r=this.parseImportFromEmbeddedObject(n,n.publisher),o=r.publisher||"";t[o]||(t[o]=[]),t[o].push(r)}return t}parseImportsLegacy(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.map(o=>this.parseImport(o,n)));return t}parseImportFromEmbeddedObject(e,t){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let r=e.match;if(!r)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),i=this.parseVersionOperator(r),a=this.calculateMaxVersion(r,s),c=e.alias;return{package_:`${n} ${r} ${s.toString()}`,publisher:t,packageName:n,versionOperator:i,version:s,alias:c,minVersion:s,maxVersion:a,toEmbeddedObject:()=>{let u={package:n,match:r,version:s.toString()};return c&&(u.alias=c),u},toString:()=>c?`${n} ${r} ${s.toString()} as ${c}`:`${n} ${r} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let a=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(a){let u=a[1].trim(),m=a[2],l=this.parseVersion(a[3].trim()),f=a[4].trim(),g=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:u,versionOperator:g,version:l,alias:f,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let d={package:u,match:m,version:l.toString()};return f&&(d.alias=f),d},toString:()=>`${u} ${m} ${l.toString()} as ${f}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let u=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),f=this.parseVersionOperator(m),g=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:u,versionOperator:f,version:l,alias:void 0,minVersion:l,maxVersion:g,toEmbeddedObject:()=>({package:u,match:m,version:l.toString()}),toString:()=>`${u} ${m} ${l.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),r=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][n],i=this.calculateMaxVersion(e.operator||"~",r);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:n,version:r,alias:e.alias,minVersion:r,maxVersion:i,toEmbeddedObject:()=>{let a={package:o,match:s,version:r.toString()};return e.alias&&(a.alias=e.alias),a},toString:()=>`${o} ${s} ${r.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[n,r]of Object.entries(e)){let o={publisher:n,packages:r.map(s=>{let i=["=","~","^","*"][s.versionOperator],a={package:s.packageName,match:i,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(a.alias=s.alias),a})};t.push(o)}return t}};var K=class{};var A=class extends K{statement=[]};var $=class extends A{namespace;name;icon};var E=class extends A{name};q();var y=class p extends K{subject;static parse(e){let t=new p;return t.subject=R.parse(e),t}};var _=class extends K{value};var S=class{predicate;object};var I=class extends S{};var j=class p extends I{static parse(e,t){let n=new p;return n.predicate=y.parse(e),n.object=t,n}};var N=class p extends I{static parse(e,t){let n=new p;return n.predicate=y.parse(e),n.object=t,n}};var L=class extends I{};var C=class p extends S{static parse(e,t){let n=new p;return n.predicate=y.parse(e),n.object=y.parse(t),n}};var V=class extends S{};var D=class extends S{};q();function H(p){if(Array.isArray(p))return p.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=p?.toString();return e?[e]:[]}var W=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let n=t.metadata?.namespace_?.toString()??"unknown",r=this.cache.get(n);if(r){let s=r.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(n,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let n=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let r=e.split("."),o=r[0],s=r[1],i=await this.findDocumentForAlias(t,o);return i?await this.resolveAllEntitiesAsync(s,i):[]}return n.filter(r=>r.entityName===e)}async buildAllEntitiesIndexAsync(e,t,n){let r=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),r;t.add(o);let s=n.length===0?o:`${n} \u2192 ${o}`;for(let[i,a]of Object.entries(e.body))if(!i.includes(".")&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};r.push({entityName:i,uri:new R(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:a,definedInNamespace:o,isImported:n.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${r.length} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((a,c)=>a+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[a,c]of Object.entries(e.metadata.imports))for(let u of c)try{this.logger?.debug?.(`Resolving import: ${a}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(a,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,s);r.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${u.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${a}/${u.packageName} for namespace ${o}. Error: ${l.message}`,l),new Error(`Failed to process import ${a}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return r}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,n){let r=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),r;t.add(o);let s=n.length===0?o:`${n} \u2192 ${o}`,i=0;for(let[a,c]of Object.entries(e.body))if(!a.includes(".")&&c&&typeof c=="object"&&!Array.isArray(c)&&!r.has(a)){let u=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};r.set(a,{entityName:a,uri:new R(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,u),entity:c,definedInNamespace:o,isImported:n.length>0,importPath:s}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((c,u)=>c+u.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[c,u]of Object.entries(e.metadata.imports))for(let m of u)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(c,m);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let f=await this.buildEntityIndexAsyncInternal(l,t,s),g=0;for(let[h,d]of f.entries())if(r.has(h)||(r.set(h,d),g++),m.alias&&!h.includes(".")){let P=`${m.alias}.${h}`;r.has(P)||(r.set(P,d),g++)}this.logger?.debug?.(`Merged ${g} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let f=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${o}. Error: ${f.message}`,f),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${o}. See inner exception for details.`,{cause:l})}}return r}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[n,r]of Object.entries(e.metadata.imports))for(let o of r){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(n,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(n,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,n){if(e===t)return!0;let r=new Set;return await this.isSubclassOfRecursiveAsync(e,t,n,r)}async isSubclassOfRecursiveAsync(e,t,n,r){if(r.has(e))return!1;r.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubclassOfRecursiveAsync(a,t,n,r))return!0}return!1}async isSubpropertyOfAsync(e,t,n){if(e===t)return!0;let r=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,n,r)}async isSubpropertyOfRecursiveAsync(e,t,n,r){if(r.has(e))return!1;r.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubpropertyOfRecursiveAsync(a,t,n,r))return!0}return!1}};var U=class p{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&p.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return p.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,t);if(n){let r=n.entity.type;if(r){let o=String(r);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var Y=class{constructor(e){}async parseKanonaks(e){let t=[],n=await e.getAllDocumentsAsync(),r=new W(e),o=new U(r);for(let a of n){let c=a.metadata.namespace_?.toString()??"";for(let[u,m]of Object.entries(a.body)){let l=new $,f=this.resolveCanonicalEntity(u,a,c);l.namespace=f.namespace,l.name=f.name,l.statement=[];let g=await this.parseStatements(m,a,r,o,e);l.statement.push(...g),t.push(l)}}let s=new Map,i=[];for(let a of t)if(a instanceof $){let c=`${a.namespace}/${a.name}`,u=s.get(c);u?u.statement.push(...a.statement):(s.set(c,a),i.push(a))}else i.push(a);return i}resolveCanonicalEntity(e,t,n){if(!e.includes(".")||!t.metadata?.imports)return{namespace:n,name:e};let r=e.indexOf("."),o=e.substring(0,r),s=e.substring(r+1);for(let[i,a]of Object.entries(t.metadata.imports))for(let c of a)if((c.alias??c.packageName)===o){let m=c.version;return{namespace:`${i}/${c.packageName}@${m.major}.${m.minor}.${m.patch}`,name:s}}return{namespace:n,name:e}}async parseStatements(e,t,n,r,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[i,a]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,n,o,r);if(!c)continue;let u=await this.parsePropertyValue(i,a,c,t,n,r);u&&s.push(u)}catch(c){console.error(`Error parsing property ${i}:`,c)}return s}async getPropertyMetadata(e,t,n,r,o){let s=await n.resolveEntityAsync(e,t);if(!s)return;let i=s.entity,a=i.type?.toString()??"",c=a.includes(".")?a.substring(a.lastIndexOf(".")+1):a;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=o.getPropertyTypeClassification(a),l=i.range?.toString(),f;if(m==="ObjectProperty")f="ObjectProperty";else if(m==="DatatypeProperty")f="DatatypeProperty";else{let h=l&&l.includes(".")?l.substring(l.lastIndexOf(".")+1):l??"";(l?o.isKnownXsdDatatypeName(l):!1)||h==="Literal"?f="DatatypeProperty":f="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:f,range:l,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,n,r,o,s){let i=n.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,n,r,o,s);if(n.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,n);if(n.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,n,r,o,s)}}parseDatatypeValue(e,t,n){if(t instanceof Date)return j.parse(e,t.toISOString());if(typeof t=="string")return j.parse(e,t);if(typeof t=="number")return N.parse(e,t);if(typeof t=="boolean"){let r=new L;return r.predicate=y.parse(e),r.object=t,r}}async parseObjectValue(e,t,n,r,o,s){if(typeof t=="string"){let i=await this.resolveReference(t,r,o);if(!i)return;let a=new C;return a.predicate=y.parse(e),a.object=i,a}if(typeof t=="object"&&!Array.isArray(t)){let i=new E;if(i.statement=await this.parseStatements(t,r,o,s,{}),i.statement.length>0){let u=new V;return u.predicate=y.parse(e),u.object=i,u}let a=[];for(let[u,m]of Object.entries(t))if(typeof m=="object"&&m!==null&&!Array.isArray(m)){let l=new E;l.name=u,l.statement=await this.parseStatements(m,r,o,s,{}),a.push(l)}else if(typeof m=="string"){let l=await this.resolveReference(m,r,o);l&&a.push(l)}if(a.length>0){let u=new D;return u.predicate=y.parse(e),u.object=a,u}let c=new V;return c.predicate=y.parse(e),c.object=i,c}}async parseListValue(e,t,n,r,o,s){let i=[],a=n.propertyType==="DatatypeProperty";for(let u of t){if(a&&(typeof u=="string"||typeof u=="number"||typeof u=="boolean")){let m=new _;m.value=u,i.push(m);continue}if(a&&u instanceof Date){let m=new _;m.value=u.toISOString(),i.push(m);continue}if(typeof u=="string"){let m=await this.resolveReference(u,r,o);m&&i.push(m)}else if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let m=new E;m.statement=await this.parseStatements(u,r,o,s,{}),i.push(m)}}let c=new D;return c.predicate=y.parse(e),c.object=i,c}async resolveReference(e,t,n){let r=await n.resolveEntityAsync(e,t);if(r){let s=new y;return s.subject=r.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(q(),J)),i=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),u=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[l,f]of Object.entries(t.metadata.imports))for(let g of f)if((g.alias??g.packageName)===u){let d=new y;return d.subject=new s(l,g.packageName,m,g.version),d}}}let a=new y;return a.subject=new s(o.publisher,o.package_,e,i),a}return null}async saveKanonaks(e,t){let n=new Map;for(let r of e)r instanceof $&&r.namespace&&(n.has(r.namespace)||n.set(r.namespace,[]),n.get(r.namespace).push(r));for(let[r,o]of n){let s=await this.convertKanonaksToDocument(r,o),i=`${r.split("@")[0]}.yml`;await t.saveDocumentAsync(s,i)}}async serializeToYaml(e,t){let n=e.filter(s=>s instanceof $&&s.namespace===t);if(n.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let r=await this.convertKanonaksToDocument(t,n);return new w().save(r)}async convertKanonaksToDocument(e,t){let r={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let i of Object.values(this.imports))s.push(...i);return s}},body:{}},o=new Map;for(let s of t){let i={};for(let a of s.statement){let[c,u]=this.convertStatementToProperty(a);c&&u!==null&&u!==void 0&&(i[c]=u),this.collectImportsFromStatement(a,e,o)}r.body[s.name]=i}return r}convertStatementToProperty(e){if(e instanceof j)return[e.predicate.subject.name,e.object];if(e instanceof N)return[e.predicate.subject.name,e.object];if(e instanceof L)return[e.predicate.subject.name,e.object];if(e instanceof C)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof D){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof V){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let n of e)n instanceof y?t.push(n.subject.name):n instanceof E&&t.push(this.convertEmbeddedKanonakToValue(n));return t}convertEmbeddedKanonakToValue(e){let t={};for(let n of e.statement){let[r,o]=this.convertStatementToProperty(n);r&&o!==null&&o!==void 0&&(t[r]=o)}return t}collectImportsFromStatement(e,t,n){}};var B=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as oe,LineCounter as se,isMap as x,isPair as k,isScalar as b,isSeq as X}from"yaml";var T=class p{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new p,n=new se,r=oe(e,{lineCounter:n});if(r.errors.length>0||!x(r.contents))return t;G(r.contents,[],n,t);for(let o of r.contents.items){if(!k(o)||!b(o.key))continue;let s=String(o.key.value),i=o.key.range;if(!i)continue;t.entities.set(s,v(i,n));let a=o.value,c=a&&typeof a=="object"&&"range"in a?a.range:void 0;if(c?t.entityBlocks.set(s,v([i[0],i[1],c[2]],n)):t.entityBlocks.set(s,v(i,n)),x(o.value)){let u=new Map,m=new Map,l=new Map;for(let g of o.value.items){if(!k(g)||!b(g.key))continue;let h=String(g.key.value),d=g.key.range;d&&u.set(h,v(d,n));let P=g.value;if(P&&typeof P=="object"&&"range"in P&&Array.isArray(P.range)){let O=P.range;m.set(h,v(O,n))}if(X(P)){let O=[];for(let M of P.items)M&&typeof M=="object"&&"range"in M&&Array.isArray(M.range)&&O.push(v(M.range,n));O.length>0&&l.set(h,O)}}u.size>0&&t.properties.set(s,u),m.size>0&&t.propertyValues.set(s,m),l.size>0&&t.valueListItems.set(s,l);let f=ae(o.value,n);f.length>0&&t.importPackages.set(s,f)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[n,r]of this.entityBlocks)if(z(r,e,t))return n}findPropertyAtPosition(e,t){let n=this.findEntityAtPosition(e,t);if(!n)return;let r=this.properties.get(n),o=this.propertyValues.get(n);if(!r&&!o)return{entityName:n};let s,i;if(o)for(let[a,c]of o)z(c,e,t)&&(!i||Q(c,i))&&(s=a,i=c);if(r)for(let[a,c]of r)z(c,e,t)&&(!i||Q(c,i))&&(s=a,i=c);return s?{entityName:n,propertyName:s}:{entityName:n}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,n]of this.importPackages)for(let r of n)e.push({entityName:t,entry:r});return e}findPropertySourceName(e,t){let n=this.properties.get(e);if(n){if(n.has(t))return t;for(let r of n.keys()){let o=r.lastIndexOf(".");if((o===-1?r:r.substring(o+1))===t)return r}}}getListItemPosition(e,t,n){let r=this.valueListItems.get(e)?.get(t);if(!(!r||n<0||n>=r.length))return r[n]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,n){if(e){if(t!==void 0){if(n!==void 0){let s=this.getListItemPosition(e,t,n);if(s)return s}let r=this.getPropertyValuePosition(e,t);if(r)return r;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function ae(p,e){let t=[];if(!x(p))return t;let n=p.items.find(r=>k(r)&&b(r.key)&&String(r.key.value)==="imports");if(!n||!k(n)||!X(n.value))return t;for(let r of n.value.items){if(!x(r))continue;let o=r.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="publisher");if(!o||!k(o)||!b(o.value))continue;let s=String(o.value.value),i=r.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="packages");if(!(!i||!k(i)||!X(i.value)))for(let a of i.value.items){if(!x(a))continue;let c=a.items.find(d=>k(d)&&b(d.key)&&String(d.key.value)==="package");if(!c||!k(c)||!b(c.value)||!c.value.range)continue;let u=String(c.value.value),m=a.items.find(d=>k(d)&&b(d.key)&&String(d.key.value)==="version"),l=m&&k(m)&&b(m.value)?String(m.value.value):"",f=a.items.find(d=>k(d)&&b(d.key)&&String(d.key.value)==="alias"),g=f&&k(f)&&b(f.value)?String(f.value.value):void 0,h=g!==void 0?{publisher:s,package_:u,version:l,alias:g,position:v(c.value.range,e)}:{publisher:s,package_:u,version:l,position:v(c.value.range,e)};t.push(h)}}return t}function z(p,e,t){return!(e<p.line||e>p.endLine||e===p.line&&t<p.column||e===p.endLine&&t>p.endColumn)}function Q(p,e){let t=p.endLine-p.line,n=e.endLine-e.line;if(t!==n)return t<n;let r=p.endLine===p.line?p.endColumn-p.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return r<o}function G(p,e,t,n){if(x(p)){for(let r of p.items){if(!k(r)||!b(r.key))continue;let o=String(r.key.value),s=[...e,o],i=JSON.stringify(s);r.key.range&&n.setNestedKeyPosition(i,v(r.key.range,t));let a=r.value,c=Z(a);c&&n.setNestedValuePosition(i,v(c,t)),G(a,s,t,n)}return}if(X(p)){for(let r=0;r<p.items.length;r++){let o=p.items[r],s=[...e,r],i=JSON.stringify(s),a=Z(o);a&&n.setNestedValuePosition(i,v(a,t)),G(o,s,t,n)}return}}function Z(p){if(!p||typeof p!="object"||!("range"in p))return;let e=p.range;return Array.isArray(e)&&e.length>=3?e:void 0}function v(p,e){let t=e.linePos(p[0]),n=e.linePos(p[2]);return{line:t.line-1,column:t.col-1,endLine:n.line-1,endColumn:n.col-1}}function ie(p,e){let n=(e??new w).parse(p),r=T.fromContent(p);return{document:n,positions:r}}export{T as KanonakDocumentPositions,Y as KanonakObjectParser,w as KanonakParser,B as PropertyMetadata,ie as parseWithPositions};
|
package/dist/reasoning/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var te=Object.defineProperty;var re=(s,e)=>()=>(s&&(e=s(s=0)),e);var ne=(s,e)=>{for(var t in e)te(s,t,{get:e[t],enumerable:!0})};var ee={};ne(ee,{KanonakUri:()=>P});function oe(s,e,t){return{major:s,minor:e,patch:t,toString:()=>`${s}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===s&&r.minor===e&&r.patch===t,getHashCode:()=>s<<20|e<<10|t,compareTo:r=>s!==r.major?s-r.major:e!==r.minor?e-r.minor:t-r.patch}}var P,C=re(()=>{"use strict";P=class s{constructor(e,t,r,o){this.publisher=e;this.package_=t;this.name=r;this.version=o}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("/");if(t.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[r,o,n]=t;if(!r||!o||!n)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let a=o.indexOf("@");if(a===-1)return new s(r,o,n,void 0);let c=o.substring(0,a),i=o.substring(a+1);if(!c||!i)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let p=i.split(".").map(Number),l=oe(p[0]||0,p[1]||0,p[2]||0);return new s(r,c,n,l)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});var S=class{};var V=class extends S{statement=[]};var v=class extends V{namespace;name;icon};var R=class extends V{name};C();var d=class s extends S{subject;static parse(e){let t=new s;return t.subject=P.parse(e),t}};var w=class extends S{value};var k=class{predicate;object};var I=class extends k{};var $=class s extends I{static parse(e,t){let r=new s;return r.predicate=d.parse(e),r.object=t,r}};var x=class s extends I{static parse(e,t){let r=new s;return r.predicate=d.parse(e),r.object=t,r}};var A=class extends I{};var E=class s extends k{static parse(e,t){let r=new s;return r.predicate=d.parse(e),r.object=d.parse(t),r}};var j=class extends k{};var O=class extends k{};C();function B(s){if(Array.isArray(s))return s.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=s?.toString();return e?[e]:[]}var M=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",o=this.cache.get(r);if(o){let a=o.get(e);if(a)return a}let n=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,n),n.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let o=e.split("."),n=o[0],a=o[1],c=await this.findDocumentForAlias(t,n);return c?await this.resolveAllEntitiesAsync(a,c):[]}return r.filter(o=>o.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let o=[],n=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${n}`),t.has(n))return this.logger?.debug?.(`Skipping ${n} - already visited (circular import prevention)`),o;t.add(n);let a=r.length===0?n:`${r} \u2192 ${n}`;for(let[c,i]of Object.entries(e.body))if(i&&typeof i=="object"&&!Array.isArray(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.push({entityName:c,uri:new P(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,p),entity:i,definedInNamespace:n,isImported:r.length>0,importPath:a})}if(this.logger?.debug?.(`Collected ${o.length} entities from ${n}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((i,p)=>i+p.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${n}`);for(let[i,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${i}/${l.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,l);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let f=await this.buildAllEntitiesIndexAsync(u,t,a);o.push(...f),this.logger?.debug?.(`Added ${f.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${l.packageName}`)}catch(u){let f=u;throw this.logger?.error?.(`Failed to process import ${i}/${l.packageName} for namespace ${n}. Error: ${f.message}`,f),new Error(`Failed to process import ${i}/${l.packageName} for namespace ${n}. See inner exception for details.`,{cause:u})}}return o}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let o=new Map,n=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${n}`),t.has(n))return this.logger?.debug?.(`Skipping ${n} - already visited (circular import prevention)`),o;t.add(n);let a=r.length===0?n:`${r} \u2192 ${n}`,c=0;for(let[i,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)&&!o.has(i)){let l=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.set(i,{entityName:i,uri:new P(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,l),entity:p,definedInNamespace:n,isImported:r.length>0,importPath:a}),c++}if(this.logger?.debug?.(`Indexed ${c} entities from ${n}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((p,l)=>p+l.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${n}`);for(let[p,l]of Object.entries(e.metadata.imports))for(let u of l)try{this.logger?.debug?.(`Resolving import: ${p}/${u.packageName}`);let f=await this.repository.getHighestCompatibleVersionAsync(p,u);if(f){this.logger?.debug?.(`Successfully loaded import: ${f.metadata?.namespace_?.toString()}`);let m=await this.buildEntityIndexAsyncInternal(f,t,a),b=0;for(let[h,K]of m.entries())if(o.has(h)||(o.set(h,K),b++),u.alias&&!h.includes(".")){let z=`${u.alias}.${h}`;o.has(z)||(o.set(z,K),b++)}this.logger?.debug?.(`Merged ${b} entities from import ${f.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${p}/${u.packageName}`)}catch(f){let m=f;throw this.logger?.error?.(`Failed to process import ${p}/${u.packageName} for namespace ${n}. Error: ${m.message}`,m),new Error(`Failed to process import ${p}/${u.packageName} for namespace ${n}. See inner exception for details.`,{cause:f})}}return o}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,o]of Object.entries(e.metadata.imports))for(let n of o){if(n.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,n);if(!n.alias&&n.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,n)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let o=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,o)}async isSubclassOfRecursiveAsync(e,t,r,o){if(o.has(e))return!1;o.add(e);let n=await this.resolveEntityAsync(e,r);if(!n?.entity)return!1;let a=n.entity.subClassOf;if(a){let c=B(a);for(let i of c)if(i===t||await this.isSubclassOfRecursiveAsync(i,t,r,o))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let o=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,o)}async isSubpropertyOfRecursiveAsync(e,t,r,o){if(o.has(e))return!1;o.add(e);let n=await this.resolveEntityAsync(e,r);if(!n?.entity)return!1;let a=n.entity.subPropertyOf;if(a){let c=B(a);for(let i of c)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,o))return!0}return!1}};var N=class s{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&s.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return s.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let o=r.entity.type;if(o){let n=String(o);return n==="Class"||n==="rdfs.Class"||n.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};import*as F from"js-yaml";var q=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let o=F.load(e);if(!o||typeof o!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let n=this.extractMetadata(o),a=this.extractBody(o,n);return r={metadata:n,body:a,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(o){let n=o,a={message:n.message||"Unknown parse error",line:n.mark?.line??0,column:n.mark?.column??0,errorType:n.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${n.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${n.mark?.line??0}: ${n.message||"Unknown parse error"}`};return t.push(a),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,o={type:"Package",publisher:r.publisher};r.version&&(o.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(o.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=o}return Object.assign(t,e.body),F.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let o of Object.values(t))r.push(...o);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===e&&n.minor===t&&n.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:n=>e!==n.major?e-n.major:t!==n.minor?t-n.minor:r-n.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){t.type_="Package";let n=r,a=o.publisher,c=o.version?this.parseVersion(o.version):void 0;return a&&n&&(t.namespace_={publisher:a,package_:n,version:c,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:i=>!i||typeof i!="object"?!1:i.publisher===a&&i.package_===n&&(!c||!i.version||c.equals(i.version)),getHashCode:()=>{let i=0;for(let p=0;p<a.length;p++)i=(i<<5)-i+a.charCodeAt(p);for(let p=0;p<n.length;p++)i=(i<<5)-i+n.charCodeAt(p);return i|0}}),o.imports&&Array.isArray(o.imports)&&(t.imports=this.parseImportsV3(o.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},o;for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){o=n;break}for(let[n,a]of Object.entries(e))n!==o&&n!=="kanonak"&&n!=="namespace"&&n!=="imports"&&(r[n]=a);return r}parseNamespace(e){if(typeof e=="string"){let n=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(n){let a=n[3]?this.parseVersion(n[3]):this.createVersion(1,0,0);return{publisher:n[1],package_:n[2],version:a,toString:()=>e,equals:c=>!c||typeof c!="object"?!1:c.publisher===n[1]&&c.package_===n[2]&&(!a||!c.version||a.equals(c.version)),getHashCode:()=>{let c=0;for(let i=0;i<n[1].length;i++)c=(c<<5)-c+n[1].charCodeAt(i);for(let i=0;i<n[2].length;i++)c=(c<<5)-c+n[2].charCodeAt(i);return c|0}}}}let t=e.publisher||"",r=e.package||"",o=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:o,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:n=>!n||typeof n!="object"?!1:n.publisher===t&&n.package_===r&&(!o||!n.version||o.equals(n.version)),getHashCode:()=>{let n=0;for(let a=0;a<t.length;a++)n=(n<<5)-n+t.charCodeAt(a);for(let a=0;a<r.length;a++)n=(n<<5)-n+r.charCodeAt(a);return n|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let o=r.publisher;if(!o)throw new Error("PublisherImport requires 'publisher' property");t[o]||(t[o]=[]);for(let n of r.packages){if(!n||typeof n!="object")continue;let a=this.parseImportFromEmbeddedObject(n,o);t[o].push(a)}}else{let o=this.parseImportFromEmbeddedObject(r,r.publisher),n=o.publisher||"";t[n]||(t[n]=[]),t[n].push(o)}return t}parseImportsLegacy(e){let t={};for(let[r,o]of Object.entries(e))Array.isArray(o)&&(t[r]=o.map(n=>this.parseImport(n,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let o=e.match;if(!o)throw new Error("Import requires 'match' property");let n=e.version;if(!n)throw new Error("Import requires 'version' property");let a=this.parseVersion(n),c=this.parseVersionOperator(o),i=this.calculateMaxVersion(o,a),p=e.alias;return{package_:`${r} ${o} ${a.toString()}`,publisher:t,packageName:r,versionOperator:c,version:a,alias:p,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let l={package:r,match:o,version:a.toString()};return p&&(l.alias=p),l},toString:()=>p?`${r} ${o} ${a.toString()} as ${p}`:`${r} ${o} ${a.toString()}`}}parseImport(e,t){if(typeof e=="string"){let i=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(i){let l=i[1].trim(),u=i[2],f=this.parseVersion(i[3].trim()),m=i[4].trim(),b=this.parseVersionOperator(u),h=this.calculateMaxVersion(u,f);return{package_:e,publisher:t,packageName:l,versionOperator:b,version:f,alias:m,minVersion:f,maxVersion:h,toEmbeddedObject:()=>{let K={package:l,match:u,version:f.toString()};return m&&(K.alias=m),K},toString:()=>`${l} ${u} ${f.toString()} as ${m}`}}let p=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(p){let l=p[1].trim(),u=p[2],f=this.parseVersion(p[3].trim()),m=this.parseVersionOperator(u),b=this.calculateMaxVersion(u,f);return{package_:e,publisher:t,packageName:l,versionOperator:m,version:f,alias:void 0,minVersion:f,maxVersion:b,toEmbeddedObject:()=>({package:l,match:u,version:f.toString()}),toString:()=>`${l} ${u} ${f.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),o=this.parseVersion(e.version||"1.0.0"),n=e.packageName||e.package||"",a=["=","~","^","*"][r],c=this.calculateMaxVersion(e.operator||"~",o);return{package_:e.package||"",publisher:t,packageName:n,versionOperator:r,version:o,alias:e.alias,minVersion:o,maxVersion:c,toEmbeddedObject:()=>{let i={package:n,match:a,version:o.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${n} ${a} ${o.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,o]of Object.entries(e)){let n={publisher:r,packages:o.map(a=>{let c=["=","~","^","*"][a.versionOperator],i={package:a.packageName,match:c,version:`${a.version.major}.${a.version.minor}.${a.version.patch}`};return a.alias&&(i.alias=a.alias),i})};t.push(n)}return t}};var W=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),o=new M(e),n=new N(o);for(let i of r){let p=i.metadata.namespace_?.toString()??"";for(let[l,u]of Object.entries(i.body)){let f=new v,m=this.resolveCanonicalEntity(l,i,p);f.namespace=m.namespace,f.name=m.name,f.statement=[];let b=await this.parseStatements(u,i,o,n,e);f.statement.push(...b),t.push(f)}}let a=new Map,c=[];for(let i of t)if(i instanceof v){let p=`${i.namespace}/${i.name}`,l=a.get(p);l?l.statement.push(...i.statement):(a.set(p,i),c.push(i))}else c.push(i);return c}resolveCanonicalEntity(e,t,r){if(!e.includes(".")||!t.metadata?.imports)return{namespace:r,name:e};let o=e.indexOf("."),n=e.substring(0,o),a=e.substring(o+1);for(let[c,i]of Object.entries(t.metadata.imports))for(let p of i)if((p.alias??p.packageName)===n){let u=p.version;return{namespace:`${c}/${p.packageName}@${u.major}.${u.minor}.${u.patch}`,name:a}}return{namespace:r,name:e}}async parseStatements(e,t,r,o,n){let a=[];if(typeof e!="object"||e===null||Array.isArray(e))return a;for(let[c,i]of Object.entries(e))try{let p=await this.getPropertyMetadata(c,t,r,n,o);if(!p)continue;let l=await this.parsePropertyValue(c,i,p,t,r,o);l&&a.push(l)}catch(p){console.error(`Error parsing property ${c}:`,p)}return a}async getPropertyMetadata(e,t,r,o,n){let a=await r.resolveEntityAsync(e,t);if(!a)return;let c=a.entity,i=c.type?.toString()??"",p=i.includes(".")?i.substring(i.lastIndexOf(".")+1):i;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(p))return;let u=n.getPropertyTypeClassification(i),f=c.range?.toString(),m;if(u==="ObjectProperty")m="ObjectProperty";else if(u==="DatatypeProperty")m="DatatypeProperty";else{let h=f&&f.includes(".")?f.substring(f.lastIndexOf(".")+1):f??"";(f?n.isKnownXsdDatatypeName(f):!1)||h==="Literal"?m="DatatypeProperty":m="ObjectProperty"}return{propertyUri:a.uri.toString(),propertyType:m,range:f,isImported:a.isImported,definedInNamespace:a.definedInNamespace}}async parsePropertyValue(e,t,r,o,n,a){let c=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(c,t,r,o,n,a);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(c,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(c,t,r,o,n,a)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return $.parse(e,t.toISOString());if(typeof t=="string")return $.parse(e,t);if(typeof t=="number")return x.parse(e,t);if(typeof t=="boolean"){let o=new A;return o.predicate=d.parse(e),o.object=t,o}}async parseObjectValue(e,t,r,o,n,a){if(typeof t=="string"){let c=await this.resolveReference(t,o,n);if(!c)return;let i=new E;return i.predicate=d.parse(e),i.object=c,i}if(typeof t=="object"&&!Array.isArray(t)){let c=new R;if(c.statement=await this.parseStatements(t,o,n,a,{}),c.statement.length>0){let l=new j;return l.predicate=d.parse(e),l.object=c,l}let i=[];for(let[l,u]of Object.entries(t))if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let f=new R;f.name=l,f.statement=await this.parseStatements(u,o,n,a,{}),i.push(f)}else if(typeof u=="string"){let f=await this.resolveReference(u,o,n);f&&i.push(f)}if(i.length>0){let l=new O;return l.predicate=d.parse(e),l.object=i,l}let p=new j;return p.predicate=d.parse(e),p.object=c,p}}async parseListValue(e,t,r,o,n,a){let c=[],i=r.propertyType==="DatatypeProperty";for(let l of t){if(i&&(typeof l=="string"||typeof l=="number"||typeof l=="boolean")){let u=new w;u.value=l,c.push(u);continue}if(i&&l instanceof Date){let u=new w;u.value=l.toISOString(),c.push(u);continue}if(typeof l=="string"){let u=await this.resolveReference(l,o,n);u&&c.push(u)}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let u=new R;u.statement=await this.parseStatements(l,o,n,a,{}),c.push(u)}}let p=new O;return p.predicate=d.parse(e),p.object=c,p}async resolveReference(e,t,r){let o=await r.resolveEntityAsync(e,t);if(o){let a=new d;return a.subject=o.uri,a}let n=t.metadata?.namespace_;if(n){let{KanonakUri:a}=await Promise.resolve().then(()=>(C(),ee)),c=n.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let p=e.indexOf("."),l=e.substring(0,p),u=e.substring(p+1);if(t.metadata?.imports){for(let[f,m]of Object.entries(t.metadata.imports))for(let b of m)if((b.alias??b.packageName)===l){let K=new d;return K.subject=new a(f,b.packageName,u,b.version),K}}}let i=new d;return i.subject=new a(n.publisher,n.package_,e,c),i}return null}async saveKanonaks(e,t){let r=new Map;for(let o of e)o instanceof v&&o.namespace&&(r.has(o.namespace)||r.set(o.namespace,[]),r.get(o.namespace).push(o));for(let[o,n]of r){let a=await this.convertKanonaksToDocument(o,n),c=`${o.split("@")[0]}.yml`;await t.saveDocumentAsync(a,c)}}async serializeToYaml(e,t){let r=e.filter(a=>a instanceof v&&a.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let o=await this.convertKanonaksToDocument(t,r);return new q().save(o)}async convertKanonaksToDocument(e,t){let o={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let a=[];for(let c of Object.values(this.imports))a.push(...c);return a}},body:{}},n=new Map;for(let a of t){let c={};for(let i of a.statement){let[p,l]=this.convertStatementToProperty(i);p&&l!==null&&l!==void 0&&(c[p]=l),this.collectImportsFromStatement(i,e,n)}o.body[a.name]=c}return o}convertStatementToProperty(e){if(e instanceof $)return[e.predicate.subject.name,e.object];if(e instanceof x)return[e.predicate.subject.name,e.object];if(e instanceof A)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof O){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof j){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof d?t.push(r.subject.name):r instanceof R&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[o,n]=this.convertStatementToProperty(r);o&&n!==null&&n!==void 0&&(t[o]=n)}return t}collectImportsFromStatement(e,t,r){}};function U(s){return`${s.publisher}/${s.package_}/${s.name}`}function g(s,e,t){return`${s}/${e}/${t}`}function H(s){return`${s.s}|${s.p}|${G(s.o)}`}function G(s){switch(s.kind){case"uri":return`u:${s.key}`;case"literal":return`l:${s.datatype}:${s.lexical}`;case"blank":return`b:${s.id}`}}function y(s,e,t){return{s,p:e,o:{kind:"uri",key:t}}}var D=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=H(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),J(this.byPIdx,e.p,e),J(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&J(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(H(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let t=this.byPIdx.get(e);return t?t.slice():[]}bySubjectPredicate(e,t){let r=this.bySPIdx.get(`${e}|${t}`);return r?r.slice():[]}byPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);return r?r.slice():[]}subjectsWithPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);if(!r)return[];let o=new Set;for(let n of r)o.add(n.s);return Array.from(o)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let o=new Set;for(let n of r)n.o.kind==="uri"&&o.add(n.o.key);return Array.from(o)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${G(r)}`)}};function J(s,e,t){let r=s.get(e);r?r.push(t):s.set(e,[t])}var _=class{type=g("kanonak.org","core-rdf","type");subClassOf=g("kanonak.org","core-rdf","subClassOf");subPropertyOf=g("kanonak.org","core-rdf","subPropertyOf");domain=g("kanonak.org","core-rdf","domain");range=g("kanonak.org","core-rdf","range");equivalentClass=g("kanonak.org","core-owl","equivalentClass");equivalentProperty=g("kanonak.org","core-owl","equivalentProperty");inverseOf=g("kanonak.org","core-owl","inverseOf");sameAs=g("kanonak.org","core-owl","sameAs");transitiveProperty=g("kanonak.org","core-owl","TransitiveProperty");symmetricProperty=g("kanonak.org","core-owl","SymmetricProperty")};var ae={name:"rdfs2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(o))s.add(y(a.s,e.type,n))&&(t=!0)}return t}},se={name:"rdfs3",apply(s,e){let t=!1;for(let r of s.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(o))a.o.kind==="uri"&&s.add(y(a.o.key,e.type,n))&&(t=!0)}return t}},ie={name:"rdfs5",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.bySubjectPredicate(n,e.subPropertyOf))a.o.kind==="uri"&&s.add(y(o,e.subPropertyOf,a.o.key))&&(t=!0)}return t}},ce={name:"rdfs7",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicate(o)){let c={s:a.s,p:n,o:a.o};s.add(c)&&(t=!0)}}return t}},pe={name:"rdfs9",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicateObject(e.type,o))s.add(y(a.s,e.type,n))&&(t=!0)}return t}},le={name:"rdfs11",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.bySubjectPredicate(n,e.subClassOf))a.o.kind==="uri"&&s.add(y(o,e.subClassOf,a.o.key))&&(t=!0)}return t}},X=[ae,se,ie,ce,pe,le];var ue={name:"prp-trp",apply(s,e){let t=!1,r=s.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let o of r){let n=s.byPredicate(o);for(let a of n){if(a.o.kind!=="uri")continue;let c=a.o.key;for(let i of s.bySubjectPredicate(c,o))i.o.kind==="uri"&&a.s!==i.o.key&&s.add(y(a.s,o,i.o.key))&&(t=!0)}}return t}},fe={name:"prp-symp",apply(s,e){let t=!1,r=s.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let o of r)for(let n of s.byPredicate(o))n.o.kind==="uri"&&s.add(y(n.o.key,o,n.s))&&(t=!0);return t}},me={name:"prp-inv1",apply(s,e){let t=!1;for(let r of s.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(o))a.o.kind==="uri"&&s.add(y(a.o.key,n,a.s))&&(t=!0)}return t}},de={name:"prp-inv2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(n))a.o.kind==="uri"&&s.add(y(a.o.key,o,a.s))&&(t=!0)}return t}},ye={name:"prp-eqp1",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicate(o))s.add({s:a.s,p:n,o:a.o})&&(t=!0)}return t}},ge={name:"prp-eqp2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicate(n))s.add({s:a.s,p:o,o:a.o})&&(t=!0)}return t}},be={name:"cax-eqc1",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicateObject(e.type,o))s.add(y(a.s,e.type,n))&&(t=!0)}return t}},ke={name:"cax-eqc2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicateObject(e.type,n))s.add(y(a.s,e.type,o))&&(t=!0)}return t}},he={name:"eq-rep-s",apply(s,e){let t=!1;for(let r of s.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n){for(let a of s.snapshot())a.s===o&&s.add({s:n,p:a.p,o:a.o})&&(t=!0);for(let a of s.snapshot())a.s===n&&s.add({s:o,p:a.p,o:a.o})&&(t=!0)}}return t}},Ke={name:"eq-rep-o",apply(s,e){let t=!1;for(let r of s.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.snapshot())a.o.kind==="uri"&&(a.o.key===o?s.add(y(a.s,a.p,n))&&(t=!0):a.o.key===n&&s.add(y(a.s,a.p,o))&&(t=!0))}return t}},Y=[ue,fe,me,de,ye,ge,be,ke,he,Ke];var L=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=T(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=T(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(o=>o!==t)}getSuperclasses(e){let t=T(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(T(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(T(e),this.vocabulary.type,T(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function T(s){return typeof s=="string"?s:g(s.publisher,s.package_,s.name)}var Q=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new _,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new D,o=await new W().parseKanonaks(e),n=new Z;for(let i of o)if(i instanceof v){let p=ve(i);if(!p)continue;for(let l of i.statement)this.emitStatement(p,l,t,n)}let a=[...X];this.profile==="owl-rl-classification"&&a.push(...Y);let c=0;for(;c<this.maxIterations;){let i=!1;for(let p of a)p.apply(t,this.vocabulary)&&(i=!0);if(!i)break;c++}return new L(t,this.vocabulary)}emitStatement(e,t,r,o){let n=Re(t);if(n){if(t instanceof $){r.add({s:e,p:n,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof x){r.add({s:e,p:n,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof A){r.add({s:e,p:n,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof E){let a=U(t.object.subject);r.add(y(e,n,a));return}if(t instanceof j){let a=o.next();r.add({s:e,p:n,o:{kind:"blank",id:a}}),this.emitEmbedded(a,t.object,r,o);return}if(t instanceof O){for(let a of t.object??[])this.emitListItem(e,n,a,r,o);return}}}emitListItem(e,t,r,o,n){if(r instanceof d)o.add(y(e,t,U(r.subject)));else if(r instanceof R){let a=n.next();o.add({s:e,p:t,o:{kind:"blank",id:a}}),this.emitEmbedded(a,r,o,n)}else if(r instanceof w){let a=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";o.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:a}})}}emitEmbedded(e,t,r,o){let n=`_:${e}`;for(let a of t.statement)this.emitStatement(n,a,r,o)}},Z=class{counter=0;next(){return`b${this.counter++}`}};function ve(s){let e=s.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),o=r.indexOf("/");if(o===-1)return null;let n=r.substring(0,o),a=r.substring(o+1);return!n||!a||!s.name?null:g(n,a,s.name)}function Re(s){let e=s.predicate;return e?.subject?U(e.subject):null}export{_ as KanonakVocabulary,Y as OWL_RL_CLASSIFICATION_RULES,X as RDFS_RULES,Q as Reasoner,L as ReasoningResult,D as TripleStore,g as makeUriKey,H as tripleKey,U as uriKey,y as uriTriple};
|
|
1
|
+
var te=Object.defineProperty;var re=(s,e)=>()=>(s&&(e=s(s=0)),e);var ne=(s,e)=>{for(var t in e)te(s,t,{get:e[t],enumerable:!0})};var ee={};ne(ee,{KanonakUri:()=>P});function oe(s,e,t){return{major:s,minor:e,patch:t,toString:()=>`${s}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===s&&r.minor===e&&r.patch===t,getHashCode:()=>s<<20|e<<10|t,compareTo:r=>s!==r.major?s-r.major:e!==r.minor?e-r.minor:t-r.patch}}var P,C=re(()=>{"use strict";P=class s{constructor(e,t,r,o){this.publisher=e;this.package_=t;this.name=r;this.version=o}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("/");if(t.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[r,o,n]=t;if(!r||!o||!n)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let a=o.indexOf("@");if(a===-1)return new s(r,o,n,void 0);let c=o.substring(0,a),i=o.substring(a+1);if(!c||!i)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let p=i.split(".").map(Number),l=oe(p[0]||0,p[1]||0,p[2]||0);return new s(r,c,n,l)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});var S=class{};var V=class extends S{statement=[]};var v=class extends V{namespace;name;icon};var R=class extends V{name};C();var d=class s extends S{subject;static parse(e){let t=new s;return t.subject=P.parse(e),t}};var w=class extends S{value};var k=class{predicate;object};var I=class extends k{};var $=class s extends I{static parse(e,t){let r=new s;return r.predicate=d.parse(e),r.object=t,r}};var x=class s extends I{static parse(e,t){let r=new s;return r.predicate=d.parse(e),r.object=t,r}};var A=class extends I{};var E=class s extends k{static parse(e,t){let r=new s;return r.predicate=d.parse(e),r.object=d.parse(t),r}};var j=class extends k{};var O=class extends k{};C();function B(s){if(Array.isArray(s))return s.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=s?.toString();return e?[e]:[]}var M=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",o=this.cache.get(r);if(o){let a=o.get(e);if(a)return a}let n=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,n),n.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let o=e.split("."),n=o[0],a=o[1],c=await this.findDocumentForAlias(t,n);return c?await this.resolveAllEntitiesAsync(a,c):[]}return r.filter(o=>o.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let o=[],n=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${n}`),t.has(n))return this.logger?.debug?.(`Skipping ${n} - already visited (circular import prevention)`),o;t.add(n);let a=r.length===0?n:`${r} \u2192 ${n}`;for(let[c,i]of Object.entries(e.body))if(!c.includes(".")&&i&&typeof i=="object"&&!Array.isArray(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.push({entityName:c,uri:new P(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,p),entity:i,definedInNamespace:n,isImported:r.length>0,importPath:a})}if(this.logger?.debug?.(`Collected ${o.length} entities from ${n}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((i,p)=>i+p.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${n}`);for(let[i,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${i}/${l.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,l);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let f=await this.buildAllEntitiesIndexAsync(u,t,a);o.push(...f),this.logger?.debug?.(`Added ${f.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${l.packageName}`)}catch(u){let f=u;throw this.logger?.error?.(`Failed to process import ${i}/${l.packageName} for namespace ${n}. Error: ${f.message}`,f),new Error(`Failed to process import ${i}/${l.packageName} for namespace ${n}. See inner exception for details.`,{cause:u})}}return o}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let o=new Map,n=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${n}`),t.has(n))return this.logger?.debug?.(`Skipping ${n} - already visited (circular import prevention)`),o;t.add(n);let a=r.length===0?n:`${r} \u2192 ${n}`,c=0;for(let[i,p]of Object.entries(e.body))if(!i.includes(".")&&p&&typeof p=="object"&&!Array.isArray(p)&&!o.has(i)){let l=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.set(i,{entityName:i,uri:new P(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,l),entity:p,definedInNamespace:n,isImported:r.length>0,importPath:a}),c++}if(this.logger?.debug?.(`Indexed ${c} entities from ${n}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((p,l)=>p+l.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${n}`);for(let[p,l]of Object.entries(e.metadata.imports))for(let u of l)try{this.logger?.debug?.(`Resolving import: ${p}/${u.packageName}`);let f=await this.repository.getHighestCompatibleVersionAsync(p,u);if(f){this.logger?.debug?.(`Successfully loaded import: ${f.metadata?.namespace_?.toString()}`);let m=await this.buildEntityIndexAsyncInternal(f,t,a),b=0;for(let[h,K]of m.entries())if(o.has(h)||(o.set(h,K),b++),u.alias&&!h.includes(".")){let z=`${u.alias}.${h}`;o.has(z)||(o.set(z,K),b++)}this.logger?.debug?.(`Merged ${b} entities from import ${f.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${p}/${u.packageName}`)}catch(f){let m=f;throw this.logger?.error?.(`Failed to process import ${p}/${u.packageName} for namespace ${n}. Error: ${m.message}`,m),new Error(`Failed to process import ${p}/${u.packageName} for namespace ${n}. See inner exception for details.`,{cause:f})}}return o}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,o]of Object.entries(e.metadata.imports))for(let n of o){if(n.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,n);if(!n.alias&&n.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,n)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let o=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,o)}async isSubclassOfRecursiveAsync(e,t,r,o){if(o.has(e))return!1;o.add(e);let n=await this.resolveEntityAsync(e,r);if(!n?.entity)return!1;let a=n.entity.subClassOf;if(a){let c=B(a);for(let i of c)if(i===t||await this.isSubclassOfRecursiveAsync(i,t,r,o))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let o=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,o)}async isSubpropertyOfRecursiveAsync(e,t,r,o){if(o.has(e))return!1;o.add(e);let n=await this.resolveEntityAsync(e,r);if(!n?.entity)return!1;let a=n.entity.subPropertyOf;if(a){let c=B(a);for(let i of c)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,o))return!0}return!1}};var N=class s{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&s.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return s.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let o=r.entity.type;if(o){let n=String(o);return n==="Class"||n==="rdfs.Class"||n.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};import*as F from"js-yaml";var q=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let o=F.load(e);if(!o||typeof o!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let n=this.extractMetadata(o),a=this.extractBody(o,n);return r={metadata:n,body:a,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(o){let n=o,a={message:n.message||"Unknown parse error",line:n.mark?.line??0,column:n.mark?.column??0,errorType:n.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${n.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${n.mark?.line??0}: ${n.message||"Unknown parse error"}`};return t.push(a),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,o={type:"Package",publisher:r.publisher};r.version&&(o.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(o.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=o}return Object.assign(t,e.body),F.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let o of Object.values(t))r.push(...o);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===e&&n.minor===t&&n.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:n=>e!==n.major?e-n.major:t!==n.minor?t-n.minor:r-n.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){t.type_="Package";let n=r,a=o.publisher,c=o.version?this.parseVersion(o.version):void 0;return a&&n&&(t.namespace_={publisher:a,package_:n,version:c,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:i=>!i||typeof i!="object"?!1:i.publisher===a&&i.package_===n&&(!c||!i.version||c.equals(i.version)),getHashCode:()=>{let i=0;for(let p=0;p<a.length;p++)i=(i<<5)-i+a.charCodeAt(p);for(let p=0;p<n.length;p++)i=(i<<5)-i+n.charCodeAt(p);return i|0}}),o.imports&&Array.isArray(o.imports)&&(t.imports=this.parseImportsV3(o.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},o;for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){o=n;break}for(let[n,a]of Object.entries(e))n!==o&&n!=="kanonak"&&n!=="namespace"&&n!=="imports"&&(r[n]=a);return r}parseNamespace(e){if(typeof e=="string"){let n=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(n){let a=n[3]?this.parseVersion(n[3]):this.createVersion(1,0,0);return{publisher:n[1],package_:n[2],version:a,toString:()=>e,equals:c=>!c||typeof c!="object"?!1:c.publisher===n[1]&&c.package_===n[2]&&(!a||!c.version||a.equals(c.version)),getHashCode:()=>{let c=0;for(let i=0;i<n[1].length;i++)c=(c<<5)-c+n[1].charCodeAt(i);for(let i=0;i<n[2].length;i++)c=(c<<5)-c+n[2].charCodeAt(i);return c|0}}}}let t=e.publisher||"",r=e.package||"",o=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:o,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:n=>!n||typeof n!="object"?!1:n.publisher===t&&n.package_===r&&(!o||!n.version||o.equals(n.version)),getHashCode:()=>{let n=0;for(let a=0;a<t.length;a++)n=(n<<5)-n+t.charCodeAt(a);for(let a=0;a<r.length;a++)n=(n<<5)-n+r.charCodeAt(a);return n|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let o=r.publisher;if(!o)throw new Error("PublisherImport requires 'publisher' property");t[o]||(t[o]=[]);for(let n of r.packages){if(!n||typeof n!="object")continue;let a=this.parseImportFromEmbeddedObject(n,o);t[o].push(a)}}else{let o=this.parseImportFromEmbeddedObject(r,r.publisher),n=o.publisher||"";t[n]||(t[n]=[]),t[n].push(o)}return t}parseImportsLegacy(e){let t={};for(let[r,o]of Object.entries(e))Array.isArray(o)&&(t[r]=o.map(n=>this.parseImport(n,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let o=e.match;if(!o)throw new Error("Import requires 'match' property");let n=e.version;if(!n)throw new Error("Import requires 'version' property");let a=this.parseVersion(n),c=this.parseVersionOperator(o),i=this.calculateMaxVersion(o,a),p=e.alias;return{package_:`${r} ${o} ${a.toString()}`,publisher:t,packageName:r,versionOperator:c,version:a,alias:p,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let l={package:r,match:o,version:a.toString()};return p&&(l.alias=p),l},toString:()=>p?`${r} ${o} ${a.toString()} as ${p}`:`${r} ${o} ${a.toString()}`}}parseImport(e,t){if(typeof e=="string"){let i=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(i){let l=i[1].trim(),u=i[2],f=this.parseVersion(i[3].trim()),m=i[4].trim(),b=this.parseVersionOperator(u),h=this.calculateMaxVersion(u,f);return{package_:e,publisher:t,packageName:l,versionOperator:b,version:f,alias:m,minVersion:f,maxVersion:h,toEmbeddedObject:()=>{let K={package:l,match:u,version:f.toString()};return m&&(K.alias=m),K},toString:()=>`${l} ${u} ${f.toString()} as ${m}`}}let p=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(p){let l=p[1].trim(),u=p[2],f=this.parseVersion(p[3].trim()),m=this.parseVersionOperator(u),b=this.calculateMaxVersion(u,f);return{package_:e,publisher:t,packageName:l,versionOperator:m,version:f,alias:void 0,minVersion:f,maxVersion:b,toEmbeddedObject:()=>({package:l,match:u,version:f.toString()}),toString:()=>`${l} ${u} ${f.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),o=this.parseVersion(e.version||"1.0.0"),n=e.packageName||e.package||"",a=["=","~","^","*"][r],c=this.calculateMaxVersion(e.operator||"~",o);return{package_:e.package||"",publisher:t,packageName:n,versionOperator:r,version:o,alias:e.alias,minVersion:o,maxVersion:c,toEmbeddedObject:()=>{let i={package:n,match:a,version:o.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${n} ${a} ${o.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,o]of Object.entries(e)){let n={publisher:r,packages:o.map(a=>{let c=["=","~","^","*"][a.versionOperator],i={package:a.packageName,match:c,version:`${a.version.major}.${a.version.minor}.${a.version.patch}`};return a.alias&&(i.alias=a.alias),i})};t.push(n)}return t}};var W=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),o=new M(e),n=new N(o);for(let i of r){let p=i.metadata.namespace_?.toString()??"";for(let[l,u]of Object.entries(i.body)){let f=new v,m=this.resolveCanonicalEntity(l,i,p);f.namespace=m.namespace,f.name=m.name,f.statement=[];let b=await this.parseStatements(u,i,o,n,e);f.statement.push(...b),t.push(f)}}let a=new Map,c=[];for(let i of t)if(i instanceof v){let p=`${i.namespace}/${i.name}`,l=a.get(p);l?l.statement.push(...i.statement):(a.set(p,i),c.push(i))}else c.push(i);return c}resolveCanonicalEntity(e,t,r){if(!e.includes(".")||!t.metadata?.imports)return{namespace:r,name:e};let o=e.indexOf("."),n=e.substring(0,o),a=e.substring(o+1);for(let[c,i]of Object.entries(t.metadata.imports))for(let p of i)if((p.alias??p.packageName)===n){let u=p.version;return{namespace:`${c}/${p.packageName}@${u.major}.${u.minor}.${u.patch}`,name:a}}return{namespace:r,name:e}}async parseStatements(e,t,r,o,n){let a=[];if(typeof e!="object"||e===null||Array.isArray(e))return a;for(let[c,i]of Object.entries(e))try{let p=await this.getPropertyMetadata(c,t,r,n,o);if(!p)continue;let l=await this.parsePropertyValue(c,i,p,t,r,o);l&&a.push(l)}catch(p){console.error(`Error parsing property ${c}:`,p)}return a}async getPropertyMetadata(e,t,r,o,n){let a=await r.resolveEntityAsync(e,t);if(!a)return;let c=a.entity,i=c.type?.toString()??"",p=i.includes(".")?i.substring(i.lastIndexOf(".")+1):i;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(p))return;let u=n.getPropertyTypeClassification(i),f=c.range?.toString(),m;if(u==="ObjectProperty")m="ObjectProperty";else if(u==="DatatypeProperty")m="DatatypeProperty";else{let h=f&&f.includes(".")?f.substring(f.lastIndexOf(".")+1):f??"";(f?n.isKnownXsdDatatypeName(f):!1)||h==="Literal"?m="DatatypeProperty":m="ObjectProperty"}return{propertyUri:a.uri.toString(),propertyType:m,range:f,isImported:a.isImported,definedInNamespace:a.definedInNamespace}}async parsePropertyValue(e,t,r,o,n,a){let c=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(c,t,r,o,n,a);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(c,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(c,t,r,o,n,a)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return $.parse(e,t.toISOString());if(typeof t=="string")return $.parse(e,t);if(typeof t=="number")return x.parse(e,t);if(typeof t=="boolean"){let o=new A;return o.predicate=d.parse(e),o.object=t,o}}async parseObjectValue(e,t,r,o,n,a){if(typeof t=="string"){let c=await this.resolveReference(t,o,n);if(!c)return;let i=new E;return i.predicate=d.parse(e),i.object=c,i}if(typeof t=="object"&&!Array.isArray(t)){let c=new R;if(c.statement=await this.parseStatements(t,o,n,a,{}),c.statement.length>0){let l=new j;return l.predicate=d.parse(e),l.object=c,l}let i=[];for(let[l,u]of Object.entries(t))if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let f=new R;f.name=l,f.statement=await this.parseStatements(u,o,n,a,{}),i.push(f)}else if(typeof u=="string"){let f=await this.resolveReference(u,o,n);f&&i.push(f)}if(i.length>0){let l=new O;return l.predicate=d.parse(e),l.object=i,l}let p=new j;return p.predicate=d.parse(e),p.object=c,p}}async parseListValue(e,t,r,o,n,a){let c=[],i=r.propertyType==="DatatypeProperty";for(let l of t){if(i&&(typeof l=="string"||typeof l=="number"||typeof l=="boolean")){let u=new w;u.value=l,c.push(u);continue}if(i&&l instanceof Date){let u=new w;u.value=l.toISOString(),c.push(u);continue}if(typeof l=="string"){let u=await this.resolveReference(l,o,n);u&&c.push(u)}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let u=new R;u.statement=await this.parseStatements(l,o,n,a,{}),c.push(u)}}let p=new O;return p.predicate=d.parse(e),p.object=c,p}async resolveReference(e,t,r){let o=await r.resolveEntityAsync(e,t);if(o){let a=new d;return a.subject=o.uri,a}let n=t.metadata?.namespace_;if(n){let{KanonakUri:a}=await Promise.resolve().then(()=>(C(),ee)),c=n.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let p=e.indexOf("."),l=e.substring(0,p),u=e.substring(p+1);if(t.metadata?.imports){for(let[f,m]of Object.entries(t.metadata.imports))for(let b of m)if((b.alias??b.packageName)===l){let K=new d;return K.subject=new a(f,b.packageName,u,b.version),K}}}let i=new d;return i.subject=new a(n.publisher,n.package_,e,c),i}return null}async saveKanonaks(e,t){let r=new Map;for(let o of e)o instanceof v&&o.namespace&&(r.has(o.namespace)||r.set(o.namespace,[]),r.get(o.namespace).push(o));for(let[o,n]of r){let a=await this.convertKanonaksToDocument(o,n),c=`${o.split("@")[0]}.yml`;await t.saveDocumentAsync(a,c)}}async serializeToYaml(e,t){let r=e.filter(a=>a instanceof v&&a.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let o=await this.convertKanonaksToDocument(t,r);return new q().save(o)}async convertKanonaksToDocument(e,t){let o={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let a=[];for(let c of Object.values(this.imports))a.push(...c);return a}},body:{}},n=new Map;for(let a of t){let c={};for(let i of a.statement){let[p,l]=this.convertStatementToProperty(i);p&&l!==null&&l!==void 0&&(c[p]=l),this.collectImportsFromStatement(i,e,n)}o.body[a.name]=c}return o}convertStatementToProperty(e){if(e instanceof $)return[e.predicate.subject.name,e.object];if(e instanceof x)return[e.predicate.subject.name,e.object];if(e instanceof A)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof O){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof j){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof d?t.push(r.subject.name):r instanceof R&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[o,n]=this.convertStatementToProperty(r);o&&n!==null&&n!==void 0&&(t[o]=n)}return t}collectImportsFromStatement(e,t,r){}};function U(s){return`${s.publisher}/${s.package_}/${s.name}`}function g(s,e,t){return`${s}/${e}/${t}`}function H(s){return`${s.s}|${s.p}|${G(s.o)}`}function G(s){switch(s.kind){case"uri":return`u:${s.key}`;case"literal":return`l:${s.datatype}:${s.lexical}`;case"blank":return`b:${s.id}`}}function y(s,e,t){return{s,p:e,o:{kind:"uri",key:t}}}var D=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=H(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),J(this.byPIdx,e.p,e),J(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&J(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(H(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let t=this.byPIdx.get(e);return t?t.slice():[]}bySubjectPredicate(e,t){let r=this.bySPIdx.get(`${e}|${t}`);return r?r.slice():[]}byPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);return r?r.slice():[]}subjectsWithPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);if(!r)return[];let o=new Set;for(let n of r)o.add(n.s);return Array.from(o)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let o=new Set;for(let n of r)n.o.kind==="uri"&&o.add(n.o.key);return Array.from(o)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${G(r)}`)}};function J(s,e,t){let r=s.get(e);r?r.push(t):s.set(e,[t])}var _=class{type=g("kanonak.org","core-rdf","type");subClassOf=g("kanonak.org","core-rdf","subClassOf");subPropertyOf=g("kanonak.org","core-rdf","subPropertyOf");domain=g("kanonak.org","core-rdf","domain");range=g("kanonak.org","core-rdf","range");equivalentClass=g("kanonak.org","core-owl","equivalentClass");equivalentProperty=g("kanonak.org","core-owl","equivalentProperty");inverseOf=g("kanonak.org","core-owl","inverseOf");sameAs=g("kanonak.org","core-owl","sameAs");transitiveProperty=g("kanonak.org","core-owl","TransitiveProperty");symmetricProperty=g("kanonak.org","core-owl","SymmetricProperty")};var ae={name:"rdfs2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(o))s.add(y(a.s,e.type,n))&&(t=!0)}return t}},se={name:"rdfs3",apply(s,e){let t=!1;for(let r of s.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(o))a.o.kind==="uri"&&s.add(y(a.o.key,e.type,n))&&(t=!0)}return t}},ie={name:"rdfs5",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.bySubjectPredicate(n,e.subPropertyOf))a.o.kind==="uri"&&s.add(y(o,e.subPropertyOf,a.o.key))&&(t=!0)}return t}},ce={name:"rdfs7",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicate(o)){let c={s:a.s,p:n,o:a.o};s.add(c)&&(t=!0)}}return t}},pe={name:"rdfs9",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicateObject(e.type,o))s.add(y(a.s,e.type,n))&&(t=!0)}return t}},le={name:"rdfs11",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.bySubjectPredicate(n,e.subClassOf))a.o.kind==="uri"&&s.add(y(o,e.subClassOf,a.o.key))&&(t=!0)}return t}},X=[ae,se,ie,ce,pe,le];var ue={name:"prp-trp",apply(s,e){let t=!1,r=s.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let o of r){let n=s.byPredicate(o);for(let a of n){if(a.o.kind!=="uri")continue;let c=a.o.key;for(let i of s.bySubjectPredicate(c,o))i.o.kind==="uri"&&a.s!==i.o.key&&s.add(y(a.s,o,i.o.key))&&(t=!0)}}return t}},fe={name:"prp-symp",apply(s,e){let t=!1,r=s.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let o of r)for(let n of s.byPredicate(o))n.o.kind==="uri"&&s.add(y(n.o.key,o,n.s))&&(t=!0);return t}},me={name:"prp-inv1",apply(s,e){let t=!1;for(let r of s.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(o))a.o.kind==="uri"&&s.add(y(a.o.key,n,a.s))&&(t=!0)}return t}},de={name:"prp-inv2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(n))a.o.kind==="uri"&&s.add(y(a.o.key,o,a.s))&&(t=!0)}return t}},ye={name:"prp-eqp1",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicate(o))s.add({s:a.s,p:n,o:a.o})&&(t=!0)}return t}},ge={name:"prp-eqp2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicate(n))s.add({s:a.s,p:o,o:a.o})&&(t=!0)}return t}},be={name:"cax-eqc1",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicateObject(e.type,o))s.add(y(a.s,e.type,n))&&(t=!0)}return t}},ke={name:"cax-eqc2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicateObject(e.type,n))s.add(y(a.s,e.type,o))&&(t=!0)}return t}},he={name:"eq-rep-s",apply(s,e){let t=!1;for(let r of s.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n){for(let a of s.snapshot())a.s===o&&s.add({s:n,p:a.p,o:a.o})&&(t=!0);for(let a of s.snapshot())a.s===n&&s.add({s:o,p:a.p,o:a.o})&&(t=!0)}}return t}},Ke={name:"eq-rep-o",apply(s,e){let t=!1;for(let r of s.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.snapshot())a.o.kind==="uri"&&(a.o.key===o?s.add(y(a.s,a.p,n))&&(t=!0):a.o.key===n&&s.add(y(a.s,a.p,o))&&(t=!0))}return t}},Y=[ue,fe,me,de,ye,ge,be,ke,he,Ke];var L=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=T(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=T(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(o=>o!==t)}getSuperclasses(e){let t=T(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(T(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(T(e),this.vocabulary.type,T(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function T(s){return typeof s=="string"?s:g(s.publisher,s.package_,s.name)}var Q=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new _,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new D,o=await new W().parseKanonaks(e),n=new Z;for(let i of o)if(i instanceof v){let p=ve(i);if(!p)continue;for(let l of i.statement)this.emitStatement(p,l,t,n)}let a=[...X];this.profile==="owl-rl-classification"&&a.push(...Y);let c=0;for(;c<this.maxIterations;){let i=!1;for(let p of a)p.apply(t,this.vocabulary)&&(i=!0);if(!i)break;c++}return new L(t,this.vocabulary)}emitStatement(e,t,r,o){let n=Re(t);if(n){if(t instanceof $){r.add({s:e,p:n,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof x){r.add({s:e,p:n,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof A){r.add({s:e,p:n,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof E){let a=U(t.object.subject);r.add(y(e,n,a));return}if(t instanceof j){let a=o.next();r.add({s:e,p:n,o:{kind:"blank",id:a}}),this.emitEmbedded(a,t.object,r,o);return}if(t instanceof O){for(let a of t.object??[])this.emitListItem(e,n,a,r,o);return}}}emitListItem(e,t,r,o,n){if(r instanceof d)o.add(y(e,t,U(r.subject)));else if(r instanceof R){let a=n.next();o.add({s:e,p:t,o:{kind:"blank",id:a}}),this.emitEmbedded(a,r,o,n)}else if(r instanceof w){let a=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";o.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:a}})}}emitEmbedded(e,t,r,o){let n=`_:${e}`;for(let a of t.statement)this.emitStatement(n,a,r,o)}},Z=class{counter=0;next(){return`b${this.counter++}`}};function ve(s){let e=s.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),o=r.indexOf("/");if(o===-1)return null;let n=r.substring(0,o),a=r.substring(o+1);return!n||!a||!s.name?null:g(n,a,s.name)}function Re(s){let e=s.predicate;return e?.subject?U(e.subject):null}export{_ as KanonakVocabulary,Y as OWL_RL_CLASSIFICATION_RULES,X as RDFS_RULES,Q as Reasoner,L as ReasoningResult,D as TripleStore,g as makeUriKey,H as tripleKey,U as uriKey,y as uriTriple};
|
package/dist/resolution/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=class t{constructor(e,r,n,s){this.publisher=e;this.package_=r;this.name=n;this.version=s}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let r=e.split("/");if(r.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[n,s,o]=r;if(!n||!s||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let a=s.indexOf("@");if(a===-1)return new t(n,s,o,void 0);let c=s.substring(0,a),i=s.substring(a+1);if(!c||!i)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let u=i.split(".").map(Number),p=D(u[0]||0,u[1]||0,u[2]||0);return new t(n,c,o,p)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}};function D(t,e,r){return{major:t,minor:e,patch:r,toString:()=>`${t}.${e}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===t&&n.minor===e&&n.patch===r,getHashCode:()=>t<<20|e<<10|r,compareTo:n=>t!==n.major?t-n.major:e!==n.minor?e-n.minor:r-n.patch}}function b(t){if(Array.isArray(t))return t.map(r=>r?.toString()??"").filter(r=>r.length>0);let e=t?.toString();return e?[e]:[]}var k=class{cache=new Map;repository;logger;constructor(e,r){this.repository=e,this.logger=r}async resolveEntityAsync(e,r){let n=r.metadata?.namespace_?.toString()??"unknown",s=this.cache.get(n);if(s){let a=s.get(e);if(a)return a}let o=await this.buildEntityIndexAsyncInternal(r,new Set,"");return this.cache.set(n,o),o.get(e)??null}async resolveAllEntitiesAsync(e,r){let n=await this.buildAllEntitiesIndexAsync(r,new Set,"");if(e.includes(".")){let s=e.split("."),o=s[0],a=s[1],c=await this.findDocumentForAlias(r,o);return c?await this.resolveAllEntitiesAsync(a,c):[]}return n.filter(s=>s.entityName===e)}async buildAllEntitiesIndexAsync(e,r,n){let s=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),r.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),s;r.add(o);let a=n.length===0?o:`${n} \u2192 ${o}`;for(let[c,i]of Object.entries(e.body))if(i&&typeof i=="object"&&!Array.isArray(i)){let u=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};s.push({entityName:c,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,u),entity:i,definedInNamespace:o,isImported:n.length>0,importPath:a})}if(this.logger?.debug?.(`Collected ${s.length} entities from ${o}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((i,u)=>i+u.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${o}`);for(let[i,u]of Object.entries(e.metadata.imports))for(let p of u)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(i,p);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(l,r,a);s.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${p.packageName}`)}catch(l){let m=l;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${i}/${p.packageName} for namespace ${o}. See inner exception for details.`,{cause:l})}}return s}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,r,n){let s=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),r.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),s;r.add(o);let a=n.length===0?o:`${n} \u2192 ${o}`,c=0;for(let[i,u]of Object.entries(e.body))if(u&&typeof u=="object"&&!Array.isArray(u)&&!s.has(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};s.set(i,{entityName:i,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),entity:u,definedInNamespace:o,isImported:n.length>0,importPath:a}),c++}if(this.logger?.debug?.(`Indexed ${c} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((u,p)=>u+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[u,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${u}/${l.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(u,l);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(m,r,a),h=0;for(let[y,$]of d.entries())if(s.has(y)||(s.set(y,$),h++),l.alias&&!y.includes(".")){let x=`${l.alias}.${y}`;s.has(x)||(s.set(x,$),h++)}this.logger?.debug?.(`Merged ${h} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${u}/${l.packageName}`)}catch(m){let d=m;throw this.logger?.error?.(`Failed to process import ${u}/${l.packageName} for namespace ${o}. Error: ${d.message}`,d),new Error(`Failed to process import ${u}/${l.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return s}async findDocumentForAlias(e,r){if(!e.metadata?.imports)return null;for(let[n,s]of Object.entries(e.metadata.imports))for(let o of s){if(o.alias===r)return await this.repository.getHighestCompatibleVersionAsync(n,o);if(!o.alias&&o.packageName===r)return await this.repository.getHighestCompatibleVersionAsync(n,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,r,n){if(e===r)return!0;let s=new Set;return await this.isSubclassOfRecursiveAsync(e,r,n,s)}async isSubclassOfRecursiveAsync(e,r,n,s){if(s.has(e))return!1;s.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let a=o.entity.subClassOf;if(a){let c=b(a);for(let i of c)if(i===r||await this.isSubclassOfRecursiveAsync(i,r,n,s))return!0}return!1}async isSubpropertyOfAsync(e,r,n){if(e===r)return!0;let s=new Set;return await this.isSubpropertyOfRecursiveAsync(e,r,n,s)}async isSubpropertyOfRecursiveAsync(e,r,n,s){if(s.has(e))return!1;s.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let a=o.entity.subPropertyOf;if(a){let c=b(a);for(let i of c)if(i===r||await this.isSubpropertyOfRecursiveAsync(i,r,n,s))return!0}return!1}};var v=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,r){return(await this.resourceResolver.resolveEntityAsync(e,r))?.uri??null}buildFromName(e,r,n){if(e.includes(".")){let o=e.split("."),a=o[0],c=o[1],i=this.findPackageNameForAlias(n,a);if(i){for(let u of r.values())if(u.entityName===c&&u.uri.package_===i)return u.uri}return null}let s=r.get(e);return s?s.uri:null}create(e,r,n,s){return new g(e,r,n,s)}findPackageNameForAlias(e,r){if(!e.metadata.imports)return null;for(let[n,s]of Object.entries(e.metadata.imports))for(let o of s)if(o.alias===r||!o.alias&&o.packageName===r)return o.packageName;return null}};function V(t){if(!t||t.trim().length===0)throw new Error("Kanonak address string cannot be null or empty");let e=t.trim(),r=e.split("/");if(r.length===1){let n=r[0];if(!n)throw new Error(`Invalid Kanonak address: "${t}". Expected publisher, publisher/package[@version], or publisher/package[@version]/name.`);if(n.includes("@"))throw new Error(`Invalid Kanonak address: "${t}". A bare publisher cannot carry an @version qualifier \u2014 versions belong to packages.`);return{kind:"publisher",publisher:n}}if(r.length===2){let[n,s]=r;if(!n||!s)throw new Error(`Invalid Kanonak address: "${t}". Expected publisher/package[@version].`);let o=s.indexOf("@");if(o===-1)return{kind:"package",publisher:n,package_:s};let a=s.substring(0,o),c=s.substring(o+1);if(!a||!c)throw new Error(`Invalid Kanonak address: "${t}". Expected publisher/package[@version].`);let i=S(c);return{kind:"package",publisher:n,package_:a,version:i}}return{kind:"resource",uri:g.parse(e)}}function P(t){switch(t.kind){case"publisher":return t.publisher;case"package":return t.version?`${t.publisher}/${t.package_}@${t.version.major}.${t.version.minor}.${t.version.patch}`:`${t.publisher}/${t.package_}`;case"resource":return t.uri.toString()}}function S(t){let e=t.split(".").map(Number);return I(e[0]||0,e[1]||0,e[2]||0)}function I(t,e,r){return{major:t,minor:e,patch:r,toString:()=>`${t}.${e}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===t&&n.minor===e&&n.patch===r,getHashCode:()=>t<<20|e<<10|r,compareTo:n=>t!==n.major?t-n.major:e!==n.minor?e-n.minor:r-n.patch}}var R=class t{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&t.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let r=e.includes(".")?e.split(".")[1]:e;return t.KNOWN_XSD_DATATYPES.has(r.toLowerCase())}async isClassTypeAsync(e,r){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,r);if(n){let s=n.entity.type;if(s){let o=String(s);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,r){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(r)||e==="Property"&&this.isLiteralType(r))}isEffectiveObjectProperty(e,r){return!!(e==="ObjectProperty"||e==="Property"&&r&&!this.isXsdDatatype(r)&&!this.isLiteralType(r))}};async function E(t,e){let r=[],n=await t.getAllDocumentsAsync();for(let s of n){let o=s.metadata.namespace_;if(!o)continue;let a=o.publisher,c=o.package_,i=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[u,p]of Object.entries(s.body)){if(!p||typeof p!="object")continue;let l=p.type;!l||typeof l!="string"||l!=="Package"&&_(l,e)&&r.push({entityName:u,entity:p,documentNamespace:`${a}/${c}@${i}`,publisher:a,package_:c,version:i})}}return r}function _(t,e){let r=w(t),n=w(e);return r===n}function w(t){let e=t.lastIndexOf(".");if(e!==-1)return t.substring(e+1);let r=t.lastIndexOf("/");return r!==-1?t.substring(r+1):t}function f(t,e){return t.major!==e.major?t.major-e.major:t.minor!==e.minor?t.minor-e.minor:t.patch-e.patch}function j(t,e){return t.major===e.major&&t.minor===e.minor&&t.patch===e.patch}function A(t){return`${t.major}.${t.minor}.${t.patch}`}function K(t,e,r){let n=`${t}.${e}.${r}`;return{major:t,minor:e,patch:r,toString:()=>n,equals:s=>s?.major===t&&s?.minor===e&&s?.patch===r,getHashCode:()=>t<<20|e<<10|r,compareTo:s=>t!==s.major?t-s.major:e!==s.minor?e-s.minor:r-s.patch}}function O(t){let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(t);return e?K(Number(e[1]),Number(e[2]),Number(e[3])):null}function C(t,e){return f(t,e)>=0&&t.major===e.major&&t.minor===e.minor}function N(t,e){return e.major===0?f(t,e)>=0&&t.major===0&&t.minor===e.minor:f(t,e)>=0&&t.major===e.major}function M(t,e={}){let{requestedVersion:r}=e;if(t.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!r};if(r){let s=t.find(o=>{let a=o.metadata.namespace_?.version;return!!a&&A(a)===r});return s?{chosen:s,alternatives:t.filter(o=>o!==s),multipleVersionsPresent:t.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:t,multipleVersionsPresent:t.length>1,exactRequestedVersionMissing:!0}}if(t.length===1)return{chosen:t[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let n=[...t].sort((s,o)=>{let a=s.metadata.namespace_?.version,c=o.metadata.namespace_?.version;return!a&&!c?0:a?c?f(c,a):-1:1});return{chosen:n[0],alternatives:n.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}export{g as KanonakUri,v as KanonakUriBuilder,k as ResourceResolver,R as TypeResolver,f as compareVersions,K as createVersion,E as findInstancesByType,P as formatKanonakAddress,A as formatVersion,C as isCompatibleVersion,N as isMajorCompatible,V as parseKanonakAddress,O as parseVersionString,M as pickHighestDocument,j as versionsEqual};
|
|
1
|
+
var g=class t{constructor(e,r,n,s){this.publisher=e;this.package_=r;this.name=n;this.version=s}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let r=e.split("/");if(r.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[n,s,o]=r;if(!n||!s||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let a=s.indexOf("@");if(a===-1)return new t(n,s,o,void 0);let c=s.substring(0,a),i=s.substring(a+1);if(!c||!i)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let u=i.split(".").map(Number),p=D(u[0]||0,u[1]||0,u[2]||0);return new t(n,c,o,p)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}};function D(t,e,r){return{major:t,minor:e,patch:r,toString:()=>`${t}.${e}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===t&&n.minor===e&&n.patch===r,getHashCode:()=>t<<20|e<<10|r,compareTo:n=>t!==n.major?t-n.major:e!==n.minor?e-n.minor:r-n.patch}}function b(t){if(Array.isArray(t))return t.map(r=>r?.toString()??"").filter(r=>r.length>0);let e=t?.toString();return e?[e]:[]}var k=class{cache=new Map;repository;logger;constructor(e,r){this.repository=e,this.logger=r}async resolveEntityAsync(e,r){let n=r.metadata?.namespace_?.toString()??"unknown",s=this.cache.get(n);if(s){let a=s.get(e);if(a)return a}let o=await this.buildEntityIndexAsyncInternal(r,new Set,"");return this.cache.set(n,o),o.get(e)??null}async resolveAllEntitiesAsync(e,r){let n=await this.buildAllEntitiesIndexAsync(r,new Set,"");if(e.includes(".")){let s=e.split("."),o=s[0],a=s[1],c=await this.findDocumentForAlias(r,o);return c?await this.resolveAllEntitiesAsync(a,c):[]}return n.filter(s=>s.entityName===e)}async buildAllEntitiesIndexAsync(e,r,n){let s=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),r.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),s;r.add(o);let a=n.length===0?o:`${n} \u2192 ${o}`;for(let[c,i]of Object.entries(e.body))if(!c.includes(".")&&i&&typeof i=="object"&&!Array.isArray(i)){let u=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};s.push({entityName:c,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,u),entity:i,definedInNamespace:o,isImported:n.length>0,importPath:a})}if(this.logger?.debug?.(`Collected ${s.length} entities from ${o}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((i,u)=>i+u.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${o}`);for(let[i,u]of Object.entries(e.metadata.imports))for(let p of u)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(i,p);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(l,r,a);s.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${p.packageName}`)}catch(l){let m=l;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${i}/${p.packageName} for namespace ${o}. See inner exception for details.`,{cause:l})}}return s}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,r,n){let s=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),r.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),s;r.add(o);let a=n.length===0?o:`${n} \u2192 ${o}`,c=0;for(let[i,u]of Object.entries(e.body))if(!i.includes(".")&&u&&typeof u=="object"&&!Array.isArray(u)&&!s.has(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};s.set(i,{entityName:i,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),entity:u,definedInNamespace:o,isImported:n.length>0,importPath:a}),c++}if(this.logger?.debug?.(`Indexed ${c} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((u,p)=>u+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[u,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${u}/${l.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(u,l);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(m,r,a),h=0;for(let[y,$]of d.entries())if(s.has(y)||(s.set(y,$),h++),l.alias&&!y.includes(".")){let x=`${l.alias}.${y}`;s.has(x)||(s.set(x,$),h++)}this.logger?.debug?.(`Merged ${h} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${u}/${l.packageName}`)}catch(m){let d=m;throw this.logger?.error?.(`Failed to process import ${u}/${l.packageName} for namespace ${o}. Error: ${d.message}`,d),new Error(`Failed to process import ${u}/${l.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return s}async findDocumentForAlias(e,r){if(!e.metadata?.imports)return null;for(let[n,s]of Object.entries(e.metadata.imports))for(let o of s){if(o.alias===r)return await this.repository.getHighestCompatibleVersionAsync(n,o);if(!o.alias&&o.packageName===r)return await this.repository.getHighestCompatibleVersionAsync(n,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,r,n){if(e===r)return!0;let s=new Set;return await this.isSubclassOfRecursiveAsync(e,r,n,s)}async isSubclassOfRecursiveAsync(e,r,n,s){if(s.has(e))return!1;s.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let a=o.entity.subClassOf;if(a){let c=b(a);for(let i of c)if(i===r||await this.isSubclassOfRecursiveAsync(i,r,n,s))return!0}return!1}async isSubpropertyOfAsync(e,r,n){if(e===r)return!0;let s=new Set;return await this.isSubpropertyOfRecursiveAsync(e,r,n,s)}async isSubpropertyOfRecursiveAsync(e,r,n,s){if(s.has(e))return!1;s.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let a=o.entity.subPropertyOf;if(a){let c=b(a);for(let i of c)if(i===r||await this.isSubpropertyOfRecursiveAsync(i,r,n,s))return!0}return!1}};var v=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,r){return(await this.resourceResolver.resolveEntityAsync(e,r))?.uri??null}buildFromName(e,r,n){if(e.includes(".")){let o=e.split("."),a=o[0],c=o[1],i=this.findPackageNameForAlias(n,a);if(i){for(let u of r.values())if(u.entityName===c&&u.uri.package_===i)return u.uri}return null}let s=r.get(e);return s?s.uri:null}create(e,r,n,s){return new g(e,r,n,s)}findPackageNameForAlias(e,r){if(!e.metadata.imports)return null;for(let[n,s]of Object.entries(e.metadata.imports))for(let o of s)if(o.alias===r||!o.alias&&o.packageName===r)return o.packageName;return null}};function V(t){if(!t||t.trim().length===0)throw new Error("Kanonak address string cannot be null or empty");let e=t.trim(),r=e.split("/");if(r.length===1){let n=r[0];if(!n)throw new Error(`Invalid Kanonak address: "${t}". Expected publisher, publisher/package[@version], or publisher/package[@version]/name.`);if(n.includes("@"))throw new Error(`Invalid Kanonak address: "${t}". A bare publisher cannot carry an @version qualifier \u2014 versions belong to packages.`);return{kind:"publisher",publisher:n}}if(r.length===2){let[n,s]=r;if(!n||!s)throw new Error(`Invalid Kanonak address: "${t}". Expected publisher/package[@version].`);let o=s.indexOf("@");if(o===-1)return{kind:"package",publisher:n,package_:s};let a=s.substring(0,o),c=s.substring(o+1);if(!a||!c)throw new Error(`Invalid Kanonak address: "${t}". Expected publisher/package[@version].`);let i=S(c);return{kind:"package",publisher:n,package_:a,version:i}}return{kind:"resource",uri:g.parse(e)}}function P(t){switch(t.kind){case"publisher":return t.publisher;case"package":return t.version?`${t.publisher}/${t.package_}@${t.version.major}.${t.version.minor}.${t.version.patch}`:`${t.publisher}/${t.package_}`;case"resource":return t.uri.toString()}}function S(t){let e=t.split(".").map(Number);return I(e[0]||0,e[1]||0,e[2]||0)}function I(t,e,r){return{major:t,minor:e,patch:r,toString:()=>`${t}.${e}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===t&&n.minor===e&&n.patch===r,getHashCode:()=>t<<20|e<<10|r,compareTo:n=>t!==n.major?t-n.major:e!==n.minor?e-n.minor:r-n.patch}}var R=class t{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&t.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let r=e.includes(".")?e.split(".")[1]:e;return t.KNOWN_XSD_DATATYPES.has(r.toLowerCase())}async isClassTypeAsync(e,r){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,r);if(n){let s=n.entity.type;if(s){let o=String(s);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,r){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(r)||e==="Property"&&this.isLiteralType(r))}isEffectiveObjectProperty(e,r){return!!(e==="ObjectProperty"||e==="Property"&&r&&!this.isXsdDatatype(r)&&!this.isLiteralType(r))}};async function E(t,e){let r=[],n=await t.getAllDocumentsAsync();for(let s of n){let o=s.metadata.namespace_;if(!o)continue;let a=o.publisher,c=o.package_,i=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[u,p]of Object.entries(s.body)){if(!p||typeof p!="object")continue;let l=p.type;!l||typeof l!="string"||l!=="Package"&&_(l,e)&&r.push({entityName:u,entity:p,documentNamespace:`${a}/${c}@${i}`,publisher:a,package_:c,version:i})}}return r}function _(t,e){let r=w(t),n=w(e);return r===n}function w(t){let e=t.lastIndexOf(".");if(e!==-1)return t.substring(e+1);let r=t.lastIndexOf("/");return r!==-1?t.substring(r+1):t}function f(t,e){return t.major!==e.major?t.major-e.major:t.minor!==e.minor?t.minor-e.minor:t.patch-e.patch}function j(t,e){return t.major===e.major&&t.minor===e.minor&&t.patch===e.patch}function A(t){return`${t.major}.${t.minor}.${t.patch}`}function K(t,e,r){let n=`${t}.${e}.${r}`;return{major:t,minor:e,patch:r,toString:()=>n,equals:s=>s?.major===t&&s?.minor===e&&s?.patch===r,getHashCode:()=>t<<20|e<<10|r,compareTo:s=>t!==s.major?t-s.major:e!==s.minor?e-s.minor:r-s.patch}}function O(t){let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(t);return e?K(Number(e[1]),Number(e[2]),Number(e[3])):null}function C(t,e){return f(t,e)>=0&&t.major===e.major&&t.minor===e.minor}function N(t,e){return e.major===0?f(t,e)>=0&&t.major===0&&t.minor===e.minor:f(t,e)>=0&&t.major===e.major}function M(t,e={}){let{requestedVersion:r}=e;if(t.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!r};if(r){let s=t.find(o=>{let a=o.metadata.namespace_?.version;return!!a&&A(a)===r});return s?{chosen:s,alternatives:t.filter(o=>o!==s),multipleVersionsPresent:t.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:t,multipleVersionsPresent:t.length>1,exactRequestedVersionMissing:!0}}if(t.length===1)return{chosen:t[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let n=[...t].sort((s,o)=>{let a=s.metadata.namespace_?.version,c=o.metadata.namespace_?.version;return!a&&!c?0:a?c?f(c,a):-1:1});return{chosen:n[0],alternatives:n.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}export{g as KanonakUri,v as KanonakUriBuilder,k as ResourceResolver,R as TypeResolver,f as compareVersions,K as createVersion,E as findInstancesByType,P as formatKanonakAddress,A as formatVersion,C as isCompatibleVersion,N as isMajorCompatible,V as parseKanonakAddress,O as parseVersionString,M as pickHighestDocument,j as versionsEqual};
|