@kanonak-protocol/sdk 2.1.0 → 2.2.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.
@@ -1,2 +1,2 @@
1
- var b=class{documents=new Map;documentContents=new Map;parser;constructor(e){this.parser=e}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){let n=[];for(let r of this.documents.values())r.metadata?.namespace_?.publisher===e&&r.metadata?.namespace_?.package_===t&&n.push(r);return n}async getHighestCompatibleVersionAsync(e,t){let n=[];for(let s of this.documents.values())s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t.packageName&&s.metadata?.namespace_?.version!==void 0&&n.push(s);if(n.length===0)return null;let r=n.filter(s=>{let a=s.metadata.namespace_.version;if(!a)return!1;switch(t.versionOperator){case 0:return this.versionsEqual(a,t.version);case 1:return this.isCompatibleVersion(a,t.version);case 2:return this.isMajorCompatible(a,t.version);case 3:return this.compareVersions(a,t.minVersion)>=0;default:return!1}});return r.length===0?null:(r.sort((s,a)=>{let o=s.metadata.namespace_.version,i=a.metadata.namespace_.version;return!o&&!i?0:o?i?this.compareVersions(i,o):-1:1}),r[0])}async saveDocumentAsync(e,t){this.documents.set(t,e);let n=this.parser.save(e);this.documentContents.set(t,n)}async deleteDocumentAsync(e){this.documents.delete(e),this.documentContents.delete(e)}async clearNamespaceAsync(e,t){let n=[];for(let[r,s]of this.documents.entries())s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t&&n.push(r);for(let r of n)this.documents.delete(r),this.documentContents.delete(r)}async getAllDocumentReferencesAsync(){let e=[];for(let t of this.documents.values())t.metadata?.namespace_&&e.push({identifier:t.metadata.namespace_.toString(),uri:`kanonak://${t.metadata.namespace_}`,hasParseError:!1});return e}async getDocumentContentAsync(e){let t=this.documentContents.get(e);if(t!==void 0)return t;let n=this.documents.get(e);return n!==void 0?this.parser.save(n):null}async getDocumentUriAsync(e){let t=this.documents.get(e);return t?t.metadata?.namespace_?`kanonak://${t.metadata.namespace_}`:`kanonak://${e}`:null}versionsEqual(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}compareVersions(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}isCompatibleVersion(e,t){return this.compareVersions(e,t)>=0&&e.major===t.major&&e.minor===t.minor}isMajorCompatible(e,t){return t.major===0?this.compareVersions(e,t)>=0&&e.major===0&&e.minor===t.minor:this.compareVersions(e,t)>=0&&e.major===t.major}};import*as p from"fs/promises";import*as m from"path";import*as D from"js-yaml";var g=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=D.load(e);if(!r||typeof r!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let s=this.extractMetadata(r),a=this.extractBody(r,s);return n={metadata:s,body:a,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 s=r,a={message:s.message||"Unknown parse error",line:s.mark?.line??0,column:s.mark?.column??0,errorType:s.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${s.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${s.mark?.line??0}: ${s.message||"Unknown parse error"}`};return t.push(a),{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),D.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:s=>!s||typeof s!="object"?!1:s.major===e&&s.minor===t&&s.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:s=>e!==s.major?e-s.major:t!==s.minor?t-s.minor:n-s.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 s=n,a=r.publisher,o=r.version?this.parseVersion(r.version):void 0;return a&&s&&(t.namespace_={publisher:a,package_:s,version:o,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_===s&&(!o||!i.version||o.equals(i.version)),getHashCode:()=>{let i=0;for(let c=0;c<a.length;c++)i=(i<<5)-i+a.charCodeAt(c);for(let c=0;c<s.length;c++)i=(i<<5)-i+s.charCodeAt(c);return i|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[s,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){r=s;break}for(let[s,a]of Object.entries(e))s!==r&&s!=="kanonak"&&s!=="namespace"&&s!=="imports"&&(n[s]=a);return n}parseNamespace(e){if(typeof e=="string"){let s=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(s){let a=s[3]?this.parseVersion(s[3]):this.createVersion(1,0,0);return{publisher:s[1],package_:s[2],version:a,toString:()=>e,equals:o=>!o||typeof o!="object"?!1:o.publisher===s[1]&&o.package_===s[2]&&(!a||!o.version||a.equals(o.version)),getHashCode:()=>{let o=0;for(let i=0;i<s[1].length;i++)o=(o<<5)-o+s[1].charCodeAt(i);for(let i=0;i<s[2].length;i++)o=(o<<5)-o+s[2].charCodeAt(i);return o|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:s=>!s||typeof s!="object"?!1:s.publisher===t&&s.package_===n&&(!r||!s.version||r.equals(s.version)),getHashCode:()=>{let s=0;for(let a=0;a<t.length;a++)s=(s<<5)-s+t.charCodeAt(a);for(let a=0;a<n.length;a++)s=(s<<5)-s+n.charCodeAt(a);return s|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 s of n.packages){if(!s||typeof s!="object")continue;let a=this.parseImportFromEmbeddedObject(s,r);t[r].push(a)}}else{let r=this.parseImportFromEmbeddedObject(n,n.publisher),s=r.publisher||"";t[s]||(t[s]=[]),t[s].push(r)}return t}parseImportsLegacy(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.map(s=>this.parseImport(s,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 s=e.version;if(!s)throw new Error("Import requires 'version' property");let a=this.parseVersion(s),o=this.parseVersionOperator(r),i=this.calculateMaxVersion(r,a),c=e.alias;return{package_:`${n} ${r} ${a.toString()}`,publisher:t,packageName:n,versionOperator:o,version:a,alias:c,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let l={package:n,match:r,version:a.toString()};return c&&(l.alias=c),l},toString:()=>c?`${n} ${r} ${a.toString()} as ${c}`:`${n} ${r} ${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(),h=i[2],f=this.parseVersion(i[3].trim()),d=i[4].trim(),I=this.parseVersionOperator(h),j=this.calculateMaxVersion(h,f);return{package_:e,publisher:t,packageName:l,versionOperator:I,version:f,alias:d,minVersion:f,maxVersion:j,toEmbeddedObject:()=>{let R={package:l,match:h,version:f.toString()};return d&&(R.alias=d),R},toString:()=>`${l} ${h} ${f.toString()} as ${d}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let l=c[1].trim(),h=c[2],f=this.parseVersion(c[3].trim()),d=this.parseVersionOperator(h),I=this.calculateMaxVersion(h,f);return{package_:e,publisher:t,packageName:l,versionOperator:d,version:f,alias:void 0,minVersion:f,maxVersion:I,toEmbeddedObject:()=>({package:l,match:h,version:f.toString()}),toString:()=>`${l} ${h} ${f.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),r=this.parseVersion(e.version||"1.0.0"),s=e.packageName||e.package||"",a=["=","~","^","*"][n],o=this.calculateMaxVersion(e.operator||"~",r);return{package_:e.package||"",publisher:t,packageName:s,versionOperator:n,version:r,alias:e.alias,minVersion:r,maxVersion:o,toEmbeddedObject:()=>{let i={package:s,match:a,version:r.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${s} ${a} ${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 s={publisher:n,packages:r.map(a=>{let o=["=","~","^","*"][a.versionOperator],i={package:a.packageName,match:o,version:`${a.version.major}.${a.version.minor}.${a.version.patch}`};return a.alias&&(i.alias=a.alias),i})};t.push(s)}return t}};var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=m.resolve(e),this.recursive=t,this.parser=n??new g,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=m.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let r of[".kan.yml",".yml",".yaml"])if(!e.endsWith(r)){let s=e+r;if(t=this.documentCache.get(s),t)return t;let a=m.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(r=>r.metadata.namespace_?.publisher===e&&r.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),r=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(r.length===0)return null;let s=r.filter(a=>{let o=a.metadata.namespace_.version;switch(t.versionOperator){case 0:return this.versionsEqual(o,t.version);case 1:return this.isCompatibleVersion(o,t.version);case 2:return this.isMajorCompatible(o,t.version);case 3:return this.compareVersions(o,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,o)=>{let i=a.metadata.namespace_.version,c=o.metadata.namespace_.version;return this.compareVersions(c,i)}),s[0])}async saveDocumentAsync(e,t){let n,r=e.metadata.namespace_?.toString();if(r&&r.includes("@")&&r.includes("/")){let i=r.split("/"),c=i[0],h=i[1].replace("@","@")+".kan.yml";n=m.join(this.rootPath,c,h)}else n=m.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=m.dirname(n);await p.mkdir(s,{recursive:!0});let a=this.parser.save(e);await p.writeFile(n,a,"utf8"),r&&this.documentCache.set(r,e),this.documentCache.set(n,e);let o=m.relative(this.rootPath,n);this.documentCache.set(o,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await p.unlink(n)}catch{}let r=t.metadata.namespace_?.toString();r&&this.documentCache.delete(r),this.documentCache.delete(e),this.documentCache.delete(n);let s=m.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let o=a.metadata.namespace_?.toString()||"";o.includes(e)&&o.includes(t)&&n.push([s,a])}let r=m.join(this.rootPath,e);try{let s=await p.readdir(r);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await p.unlink(m.join(r,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let r=`file://${n}`,s;for(let[i,c]of this.documentCache.entries())if(this.filePathsByIdentifier.get(i)===n&&c.metadata.namespace_){s=c.metadata.namespace_.toString();break}let a=s??m.relative(this.rootPath,n),o=this.parsingErrors.has(n);t.push({identifier:a,uri:r,hasParseError:o})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await p.access(e),t=e}catch{let n=m.join(this.rootPath,e);try{await p.access(n),t=n}catch{return null}}try{return await p.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await p.access(e),t=e}catch{let n=m.join(this.rootPath,e);try{await p.access(n),t=n}catch{return null}}return`file://${t}`}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await p.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async r=>{try{let s=await p.readFile(r,"utf8"),a=this.parser.parse(s);return{filePath:r,document:a,error:null}}catch(s){return{filePath:r,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:r,document:s,error:a}of n){let o=m.relative(this.rootPath,r);if(s&&s.metadata.namespace_){let i=s.metadata.namespace_.toString();this.documentCache.set(i,s),this.documentCache.set(r,s),this.documentCache.set(o,s),this.filePathsByIdentifier.set(i,r),this.filePathsByIdentifier.set(r,r),this.filePathsByIdentifier.set(o,r)}else this.filePathsByIdentifier.set(r,r),this.filePathsByIdentifier.set(o,r);a&&this.parsingErrors.set(r,a)}}versionsEqual(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}compareVersions(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}isCompatibleVersion(e,t){return this.compareVersions(e,t)>=0&&e.major===t.major&&e.minor===t.minor}isMajorCompatible(e,t){return t.major===0?this.compareVersions(e,t)>=0&&e.major===0&&e.minor===t.minor:this.compareVersions(e,t)>=0&&e.major===t.major}async findYamlFiles(e,t){let n=[];try{let r=await p.readdir(e,{withFileTypes:!0});for(let s of r){let a=m.join(e,s.name);if(s.isDirectory()&&t){let o=await this.findYamlFiles(a,t);n.push(...o)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as k from"fs";var V=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(V||{}),P=class{cache;workspace;constructor(e,t,n){let r=n??new g;k.existsSync(e)||k.mkdirSync(e,{recursive:!0}),k.existsSync(t)||k.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,r),this.workspace=new y(t,!0,r)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let r of t)if(r.metadata.namespace_){let s=r.metadata.namespace_.toString();n.set(s,r)}for(let r of e)if(r.metadata.namespace_){let s=r.metadata.namespace_.toString();n.set(s,r)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),r=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of r)if(a.metadata.namespace_?.version){let o=a.metadata.namespace_.version.toString();s.set(o,a)}for(let a of n)if(a.metadata.namespace_?.version){let o=a.metadata.namespace_.version.toString();s.set(o,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as E}from"os";import{join as _}from"path";function A(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||_(E(),".kanonak","packages")}var K=class u{static createComposite(e,t,n){let r=e??A(),s=t??".";return new P(r,s,n)}static createFromEnvironment(e){let t=A(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};import{VersionOperator as C}from"@kanonak-protocol/types/document/models/enums";var S="https://{publisher}/index.txt",N="https://{publisher}/{package}/{version}.kan.yml",$={version:1},w=class{cache=new Map;async getConfig(e){let t=this.cache.get(e);if(t)return t;let n=await this.fetchConfig(e);return this.cache.set(e,n),n}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,n;try{n=await fetch(t)}catch{return $}if(n.status===404)return $;if(!n.ok)throw new Error(`Failed to fetch publisher config: ${t} (${n.status} ${n.statusText})`);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let s={version:r.version};return typeof r.index=="string"&&(s.index=r.index),typeof r.package=="string"&&(s.package=r.package),(r.auth==="none"||r.auth==="oauth"||r.auth==="bearer")&&(s.auth=r.auth),s}resolveIndexUrl(e,t){let n=t.index??S;return F(n,{publisher:e})}resolvePackageUrl(e,t,n,r){let s=r.package??N;return F(s,{publisher:e,package:t,version:n})}};function F(u,e){let t=u;for(let[r,s]of Object.entries(e))t=t.replaceAll(`{${r}}`,s);let n=t.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${u}`);return t}var v=class u{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new w,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let n=await this.getPackageVersions(e,t.packageName);if(n.length===0)return null;let r=n.filter(s=>this.isVersionCompatible(s,t.version,t.versionOperator));return r.length===0?null:(r.sort((s,a)=>this.compareVersionStrings(a,s)),r[0])}async getHighestVersion(e,t){let n=await this.getPackageVersions(e,t);return n.length===0?null:[...n].sort((s,a)=>this.compareVersionStrings(a,s))[0]}async listLatestPackages(e){let t=this.indexCache.get(e);t||(t=await this.fetchIndex(e),this.indexCache.set(e,t));let n=[];for(let[r,s]of t){if(s.length===0)continue;let a=[...s].sort((o,i)=>this.compareVersionStrings(i,o));n.push({packageName:r,version:a[0]})}return n.sort((r,s)=>r.packageName.localeCompare(s.packageName)),n}async getPackageUrl(e,t,n){let r=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,n,r)}async getPackageVersions(e,t){let n=this.indexCache.get(e);return n||(n=await this.fetchIndex(e),this.indexCache.set(e,n)),n.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),n=this.configResolver.resolveIndexUrl(e,t),r=this.fetchFn?await this.fetchFn(n,e):await fetch(n);if(!r.ok)throw new Error(`Failed to fetch publisher index: ${n} (${r.status} ${r.statusText})`);let s=await r.text();return u.parseIndex(s)}static parseIndex(e){let t=new Map;for(let n of e.split(`
2
- `)){let r=n.trim();if(!r||r.startsWith("#"))continue;let s=r.indexOf("/");if(s===-1)continue;let a=r.substring(0,s),o=r.substring(s+1);if(!a||!o)continue;let i=t.get(a);i?i.push(o):t.set(a,[o])}return t}isVersionCompatible(e,t,n){let r=u.parseVersion(e);if(!r)return!1;switch(n){case C.Any:return!0;case C.Exact:return r.major===t.major&&r.minor===t.minor&&r.patch===t.patch;case C.Compatible:return r.major===t.major&&r.minor===t.minor&&r.patch>=t.patch;case C.Major:return r.major!==t.major?!1:r.minor>t.minor?!0:r.minor===t.minor?r.patch>=t.patch:!1;default:return!1}}static parseVersion(e){let t=e.split(".");if(t.length<2)return null;let n=parseInt(t[0],10),r=parseInt(t[1],10),s=t.length>=3?parseInt(t[2],10):0;return isNaN(n)||isNaN(r)||isNaN(s)?null:{major:n,minor:r,patch:s}}compareVersionStrings(e,t){let n=u.parseVersion(e),r=u.parseVersion(t);return!n&&!r?0:n?r?n.major!==r.major?n.major-r.major:n.minor!==r.minor?n.minor-r.minor:n.patch-r.patch:1:-1}};var x=class{parser=new g;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new v({fetchFn:e.fetchFn}):new v}async getHighestCompatibleVersionAsync(e,t){let n=await this.publisherIndex.resolveVersion(e,t);if(!n)return null;let r=`${e}/${t.packageName}@${n}`,s=this.documents.get(r);if(s)return s;if(this.getFromCache){let l=this.getFromCache(e,t.packageName,n);if(l){let h=this.parser.parse(l);return this.documents.set(r,h),this.contentCache.set(r,l),h}}let a=await this.publisherIndex.getPackageUrl(e,t.packageName,n),o=this.fetchFn?await this.fetchFn(a,e):await fetch(a);if(!o.ok)throw new Error(`Failed to fetch Kanonak package: ${a} (${o.status} ${o.statusText})`);let i=await o.text();this.onFetch&&this.onFetch(e,t.packageName,n,i);let c=this.parser.parse(i);return this.documents.set(r,c),this.contentCache.set(r,i),c}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===e&&r.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,n,r,s]=t;return this.publisherIndex.getPackageUrl(n,r,s)}};export{P as CompositeKanonakDocumentRepository,V as DocumentLocation,y as FileSystemKanonakDocumentRepository,x as HttpKanonakDocumentRepository,b as InMemoryKanonakDocumentRepository,w as PublisherConfigResolver,v as PublisherIndex,K as RepositoryFactory,A as getGlobalCachePath};
1
+ function g(c,e){return c.major!==e.major?c.major-e.major:c.minor!==e.minor?c.minor-e.minor:c.patch-e.patch}function A(c,e){return c.major===e.major&&c.minor===e.minor&&c.patch===e.patch}function C(c,e){return g(c,e)>=0&&c.major===e.major&&c.minor===e.minor}function I(c,e){return e.major===0?g(c,e)>=0&&c.major===0&&c.minor===e.minor:g(c,e)>=0&&c.major===e.major}var R=class{documents=new Map;documentContents=new Map;parser;constructor(e){this.parser=e}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){let n=[];for(let r of this.documents.values())r.metadata?.namespace_?.publisher===e&&r.metadata?.namespace_?.package_===t&&n.push(r);return n}async getHighestCompatibleVersionAsync(e,t){let n=[];for(let s of this.documents.values())s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t.packageName&&s.metadata?.namespace_?.version!==void 0&&n.push(s);if(n.length===0)return null;let r=n.filter(s=>{let a=s.metadata.namespace_.version;if(!a)return!1;switch(t.versionOperator){case 0:return A(a,t.version);case 1:return C(a,t.version);case 2:return I(a,t.version);case 3:return g(a,t.minVersion)>=0;default:return!1}});return r.length===0?null:(r.sort((s,a)=>{let o=s.metadata.namespace_.version,i=a.metadata.namespace_.version;return!o&&!i?0:o?i?g(i,o):-1:1}),r[0])}async saveDocumentAsync(e,t){this.documents.set(t,e);let n=this.parser.save(e);this.documentContents.set(t,n)}async deleteDocumentAsync(e){this.documents.delete(e),this.documentContents.delete(e)}async clearNamespaceAsync(e,t){let n=[];for(let[r,s]of this.documents.entries())s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t&&n.push(r);for(let r of n)this.documents.delete(r),this.documentContents.delete(r)}async getAllDocumentReferencesAsync(){let e=[];for(let t of this.documents.values())t.metadata?.namespace_&&e.push({identifier:t.metadata.namespace_.toString(),uri:`kanonak://${t.metadata.namespace_}`,hasParseError:!1});return e}async getDocumentContentAsync(e){let t=this.documentContents.get(e);if(t!==void 0)return t;let n=this.documents.get(e);return n!==void 0?this.parser.save(n):null}async getDocumentUriAsync(e){let t=this.documents.get(e);return t?t.metadata?.namespace_?`kanonak://${t.metadata.namespace_}`:`kanonak://${e}`:null}};import*as p from"fs/promises";import*as u from"path";import{pathToFileURL as S}from"url";import*as b from"js-yaml";var d=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=b.load(e);if(!r||typeof r!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let s=this.extractMetadata(r),a=this.extractBody(r,s);return n={metadata:s,body:a,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 s=r,a={message:s.message||"Unknown parse error",line:s.mark?.line??0,column:s.mark?.column??0,errorType:s.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${s.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${s.mark?.line??0}: ${s.message||"Unknown parse error"}`};return t.push(a),{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),b.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:s=>!s||typeof s!="object"?!1:s.major===e&&s.minor===t&&s.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:s=>e!==s.major?e-s.major:t!==s.minor?t-s.minor:n-s.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 s=n,a=r.publisher,o=r.version?this.parseVersion(r.version):void 0;return a&&s&&(t.namespace_={publisher:a,package_:s,version:o,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_===s&&(!o||!i.version||o.equals(i.version)),getHashCode:()=>{let i=0;for(let m=0;m<a.length;m++)i=(i<<5)-i+a.charCodeAt(m);for(let m=0;m<s.length;m++)i=(i<<5)-i+s.charCodeAt(m);return i|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[s,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){r=s;break}for(let[s,a]of Object.entries(e))s!==r&&s!=="kanonak"&&s!=="namespace"&&s!=="imports"&&(n[s]=a);return n}parseNamespace(e){if(typeof e=="string"){let s=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(s){let a=s[3]?this.parseVersion(s[3]):this.createVersion(1,0,0);return{publisher:s[1],package_:s[2],version:a,toString:()=>e,equals:o=>!o||typeof o!="object"?!1:o.publisher===s[1]&&o.package_===s[2]&&(!a||!o.version||a.equals(o.version)),getHashCode:()=>{let o=0;for(let i=0;i<s[1].length;i++)o=(o<<5)-o+s[1].charCodeAt(i);for(let i=0;i<s[2].length;i++)o=(o<<5)-o+s[2].charCodeAt(i);return o|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:s=>!s||typeof s!="object"?!1:s.publisher===t&&s.package_===n&&(!r||!s.version||r.equals(s.version)),getHashCode:()=>{let s=0;for(let a=0;a<t.length;a++)s=(s<<5)-s+t.charCodeAt(a);for(let a=0;a<n.length;a++)s=(s<<5)-s+n.charCodeAt(a);return s|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 s of n.packages){if(!s||typeof s!="object")continue;let a=this.parseImportFromEmbeddedObject(s,r);t[r].push(a)}}else{let r=this.parseImportFromEmbeddedObject(n,n.publisher),s=r.publisher||"";t[s]||(t[s]=[]),t[s].push(r)}return t}parseImportsLegacy(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.map(s=>this.parseImport(s,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 s=e.version;if(!s)throw new Error("Import requires 'version' property");let a=this.parseVersion(s),o=this.parseVersionOperator(r),i=this.calculateMaxVersion(r,a),m=e.alias;return{package_:`${n} ${r} ${a.toString()}`,publisher:t,packageName:n,versionOperator:o,version:a,alias:m,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let l={package:n,match:r,version:a.toString()};return m&&(l.alias=m),l},toString:()=>m?`${n} ${r} ${a.toString()} as ${m}`:`${n} ${r} ${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(),h=i[2],f=this.parseVersion(i[3].trim()),y=i[4].trim(),K=this.parseVersionOperator(h),M=this.calculateMaxVersion(h,f);return{package_:e,publisher:t,packageName:l,versionOperator:K,version:f,alias:y,minVersion:f,maxVersion:M,toEmbeddedObject:()=>{let E={package:l,match:h,version:f.toString()};return y&&(E.alias=y),E},toString:()=>`${l} ${h} ${f.toString()} as ${y}`}}let m=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(m){let l=m[1].trim(),h=m[2],f=this.parseVersion(m[3].trim()),y=this.parseVersionOperator(h),K=this.calculateMaxVersion(h,f);return{package_:e,publisher:t,packageName:l,versionOperator:y,version:f,alias:void 0,minVersion:f,maxVersion:K,toEmbeddedObject:()=>({package:l,match:h,version:f.toString()}),toString:()=>`${l} ${h} ${f.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),r=this.parseVersion(e.version||"1.0.0"),s=e.packageName||e.package||"",a=["=","~","^","*"][n],o=this.calculateMaxVersion(e.operator||"~",r);return{package_:e.package||"",publisher:t,packageName:s,versionOperator:n,version:r,alias:e.alias,minVersion:r,maxVersion:o,toEmbeddedObject:()=>{let i={package:s,match:a,version:r.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${s} ${a} ${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 s={publisher:n,packages:r.map(a=>{let o=["=","~","^","*"][a.versionOperator],i={package:a.packageName,match:o,version:`${a.version.major}.${a.version.minor}.${a.version.patch}`};return a.alias&&(i.alias=a.alias),i})};t.push(s)}return t}};var k=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=u.resolve(e),this.recursive=t,this.parser=n??new d,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=u.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let r of[".kan.yml",".yml",".yaml"])if(!e.endsWith(r)){let s=e+r;if(t=this.documentCache.get(s),t)return t;let a=u.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(r=>r.metadata.namespace_?.publisher===e&&r.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),r=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(r.length===0)return null;let s=r.filter(a=>{let o=a.metadata.namespace_.version;switch(t.versionOperator){case 0:return A(o,t.version);case 1:return C(o,t.version);case 2:return I(o,t.version);case 3:return g(o,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,o)=>{let i=a.metadata.namespace_.version,m=o.metadata.namespace_.version;return g(m,i)}),s[0])}async saveDocumentAsync(e,t){let n,r=e.metadata.namespace_?.toString();if(r&&r.includes("@")&&r.includes("/")){let i=r.split("/"),m=i[0],h=i[1].replace("@","@")+".kan.yml";n=u.join(this.rootPath,m,h)}else n=u.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=u.dirname(n);await p.mkdir(s,{recursive:!0});let a=this.parser.save(e);await p.writeFile(n,a,"utf8"),r&&this.documentCache.set(r,e),this.documentCache.set(n,e);let o=u.relative(this.rootPath,n);this.documentCache.set(o,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await p.unlink(n)}catch{}let r=t.metadata.namespace_?.toString();r&&this.documentCache.delete(r),this.documentCache.delete(e),this.documentCache.delete(n);let s=u.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let o=a.metadata.namespace_?.toString()||"";o.includes(e)&&o.includes(t)&&n.push([s,a])}let r=u.join(this.rootPath,e);try{let s=await p.readdir(r);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await p.unlink(u.join(r,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let r=S(n).toString(),s;for(let[i,m]of this.documentCache.entries())if(this.filePathsByIdentifier.get(i)===n&&m.metadata.namespace_){s=m.metadata.namespace_.toString();break}let a=s??u.relative(this.rootPath,n),o=this.parsingErrors.has(n);t.push({identifier:a,uri:r,hasParseError:o})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await p.access(e),t=e}catch{let n=u.join(this.rootPath,e);try{await p.access(n),t=n}catch{return null}}try{return await p.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await p.access(e),t=e}catch{let n=u.join(this.rootPath,e);try{await p.access(n),t=n}catch{return null}}return S(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await p.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async r=>{try{let s=await p.readFile(r,"utf8"),a=this.parser.parse(s);return{filePath:r,document:a,error:null}}catch(s){return{filePath:r,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:r,document:s,error:a}of n){let o=u.relative(this.rootPath,r);if(s&&s.metadata.namespace_){let i=s.metadata.namespace_.toString();this.documentCache.set(i,s),this.documentCache.set(r,s),this.documentCache.set(o,s),this.filePathsByIdentifier.set(i,r),this.filePathsByIdentifier.set(r,r),this.filePathsByIdentifier.set(o,r)}else this.filePathsByIdentifier.set(r,r),this.filePathsByIdentifier.set(o,r);a&&this.parsingErrors.set(r,a)}}async findYamlFiles(e,t){let n=[];try{let r=await p.readdir(e,{withFileTypes:!0});for(let s of r){let a=u.join(e,s.name);if(s.isDirectory()&&t){let o=await this.findYamlFiles(a,t);n.push(...o)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as v from"fs";var _=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(_||{}),D=class{cache;workspace;constructor(e,t,n){let r=n??new d;v.existsSync(e)||v.mkdirSync(e,{recursive:!0}),v.existsSync(t)||v.mkdirSync(t,{recursive:!0}),this.cache=new k(e,!0,r),this.workspace=new k(t,!0,r)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let r of t)if(r.metadata.namespace_){let s=r.metadata.namespace_.toString();n.set(s,r)}for(let r of e)if(r.metadata.namespace_){let s=r.metadata.namespace_.toString();n.set(s,r)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),r=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of r)if(a.metadata.namespace_?.version){let o=a.metadata.namespace_.version.toString();s.set(o,a)}for(let a of n)if(a.metadata.namespace_?.version){let o=a.metadata.namespace_.version.toString();s.set(o,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as O}from"os";import{join as B}from"path";function x(){let c=process.env.KANONAK_PACKAGE_CACHE;return c||B(O(),".kanonak","packages")}var $=class c{static createComposite(e,t,n){let r=e??x(),s=t??".";return new D(r,s,n)}static createFromEnvironment(e){let t=x(),n=process.env.KANONAK_WORKSPACE_PATH??".";return c.createComposite(t,n,e)}};import{VersionOperator as V}from"@kanonak-protocol/types/document/models/enums";var U="https://{publisher}/index.txt",T="https://{publisher}/{package}/{version}.kan.yml",N={version:1},w=class{cache=new Map;async getConfig(e){let t=this.cache.get(e);if(t)return t;let n=await this.fetchConfig(e);return this.cache.set(e,n),n}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,n;try{n=await fetch(t)}catch{return N}if(n.status===404)return N;if(!n.ok)throw new Error(`Failed to fetch publisher config: ${t} (${n.status} ${n.statusText})`);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let s={version:r.version};return typeof r.index=="string"&&(s.index=r.index),typeof r.package=="string"&&(s.package=r.package),(r.auth==="none"||r.auth==="oauth"||r.auth==="bearer")&&(s.auth=r.auth),s}resolveIndexUrl(e,t){let n=t.index??U;return j(n,{publisher:e})}resolvePackageUrl(e,t,n,r){let s=r.package??T;return j(s,{publisher:e,package:t,version:n})}};function j(c,e){let t=c;for(let[r,s]of Object.entries(e))t=t.replaceAll(`{${r}}`,s);let n=t.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${c}`);return t}var P=class c{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new w,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let n=await this.getPackageVersions(e,t.packageName);if(n.length===0)return null;let r=n.filter(s=>this.isVersionCompatible(s,t.version,t.versionOperator));return r.length===0?null:(r.sort((s,a)=>this.compareVersionStrings(a,s)),r[0])}async getHighestVersion(e,t){let n=await this.getPackageVersions(e,t);return n.length===0?null:[...n].sort((s,a)=>this.compareVersionStrings(a,s))[0]}async listLatestPackages(e){let t=this.indexCache.get(e);t||(t=await this.fetchIndex(e),this.indexCache.set(e,t));let n=[];for(let[r,s]of t){if(s.length===0)continue;let a=[...s].sort((o,i)=>this.compareVersionStrings(i,o));n.push({packageName:r,version:a[0]})}return n.sort((r,s)=>r.packageName.localeCompare(s.packageName)),n}async getPackageUrl(e,t,n){let r=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,n,r)}async getPackageVersions(e,t){let n=this.indexCache.get(e);return n||(n=await this.fetchIndex(e),this.indexCache.set(e,n)),n.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),n=this.configResolver.resolveIndexUrl(e,t),r=this.fetchFn?await this.fetchFn(n,e):await fetch(n);if(!r.ok)throw new Error(`Failed to fetch publisher index: ${n} (${r.status} ${r.statusText})`);let s=await r.text();return c.parseIndex(s)}static parseIndex(e){let t=new Map;for(let n of e.split(`
2
+ `)){let r=n.trim();if(!r||r.startsWith("#"))continue;let s=r.indexOf("/");if(s===-1)continue;let a=r.substring(0,s),o=r.substring(s+1);if(!a||!o)continue;let i=t.get(a);i?i.push(o):t.set(a,[o])}return t}isVersionCompatible(e,t,n){let r=c.parseVersion(e);if(!r)return!1;switch(n){case V.Any:return!0;case V.Exact:return r.major===t.major&&r.minor===t.minor&&r.patch===t.patch;case V.Compatible:return r.major===t.major&&r.minor===t.minor&&r.patch>=t.patch;case V.Major:return r.major!==t.major?!1:r.minor>t.minor?!0:r.minor===t.minor?r.patch>=t.patch:!1;default:return!1}}static parseVersion(e){let t=e.split(".");if(t.length<2)return null;let n=parseInt(t[0],10),r=parseInt(t[1],10),s=t.length>=3?parseInt(t[2],10):0;return isNaN(n)||isNaN(r)||isNaN(s)?null:{major:n,minor:r,patch:s}}compareVersionStrings(e,t){let n=c.parseVersion(e),r=c.parseVersion(t);return!n&&!r?0:n?r?n.major!==r.major?n.major-r.major:n.minor!==r.minor?n.minor-r.minor:n.patch-r.patch:1:-1}};var F=class{parser=new d;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new P({fetchFn:e.fetchFn}):new P}async getHighestCompatibleVersionAsync(e,t){let n=await this.publisherIndex.resolveVersion(e,t);if(!n)return null;let r=`${e}/${t.packageName}@${n}`,s=this.documents.get(r);if(s)return s;if(this.getFromCache){let l=this.getFromCache(e,t.packageName,n);if(l){let h=this.parser.parse(l);return this.documents.set(r,h),this.contentCache.set(r,l),h}}let a=await this.publisherIndex.getPackageUrl(e,t.packageName,n),o=this.fetchFn?await this.fetchFn(a,e):await fetch(a);if(!o.ok)throw new Error(`Failed to fetch Kanonak package: ${a} (${o.status} ${o.statusText})`);let i=await o.text();this.onFetch&&this.onFetch(e,t.packageName,n,i);let m=this.parser.parse(i);return this.documents.set(r,m),this.contentCache.set(r,i),m}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===e&&r.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,n,r,s]=t;return this.publisherIndex.getPackageUrl(n,r,s)}};export{D as CompositeKanonakDocumentRepository,_ as DocumentLocation,k as FileSystemKanonakDocumentRepository,F as HttpKanonakDocumentRepository,R as InMemoryKanonakDocumentRepository,w as PublisherConfigResolver,P as PublisherIndex,$ as RepositoryFactory,x as getGlobalCachePath};
@@ -0,0 +1,40 @@
1
+ import type { Version, KanonakDocument } from '@kanonak-protocol/types/document/models/types';
2
+ export declare function compareVersions(a: Version, b: Version): number;
3
+ export declare function versionsEqual(a: Version, b: Version): boolean;
4
+ export declare function formatVersion(v: Version): string;
5
+ /**
6
+ * Construct a `Version` value with all the C#-shaped methods
7
+ * (`toString`, `equals`, `getHashCode`, `compareTo`) the type requires.
8
+ * Use this in preference to `{ major, minor, patch }` object literals
9
+ * — those don't satisfy the `Version` interface.
10
+ */
11
+ export declare function createVersion(major: number, minor: number, patch: number): Version;
12
+ export declare function parseVersionString(s: string): Version | null;
13
+ export declare function isCompatibleVersion(docVersion: Version, requiredVersion: Version): boolean;
14
+ export declare function isMajorCompatible(docVersion: Version, requiredVersion: Version): boolean;
15
+ export interface DocumentVersionPick {
16
+ /** Chosen document, or null when none matched. */
17
+ chosen: KanonakDocument | null;
18
+ /** Other versions of the same package present alongside the chosen one. */
19
+ alternatives: KanonakDocument[];
20
+ /** True when the input contained more than one version. */
21
+ multipleVersionsPresent: boolean;
22
+ /** True when a `requestedVersion` was given but no doc had that exact version. */
23
+ exactRequestedVersionMissing: boolean;
24
+ }
25
+ /**
26
+ * Pick a document from a same-package candidate list.
27
+ *
28
+ * - If `requestedVersion` is provided, picks the exact match. When no
29
+ * doc matches, returns `chosen: null` with `exactRequestedVersionMissing: true`
30
+ * so the caller can produce a precise error.
31
+ * - Otherwise picks the highest semver. When more than one version is
32
+ * present, `multipleVersionsPresent` is `true` so callers can decide
33
+ * whether to warn.
34
+ *
35
+ * No console output — the SDK stays pure. Callers that want to warn
36
+ * inspect the returned flags and emit their own diagnostic.
37
+ */
38
+ export declare function pickHighestDocument(docs: KanonakDocument[], options?: {
39
+ requestedVersion?: string;
40
+ }): DocumentVersionPick;
@@ -6,3 +6,5 @@ export type { ResourceResolutionResult } from './ResourceResolutionResult.js';
6
6
  export { TypeResolver } from './TypeResolver.js';
7
7
  export { findInstancesByType } from './InstanceSearch.js';
8
8
  export type { InstanceSearchResult } from './InstanceSearch.js';
9
+ export { compareVersions, versionsEqual, formatVersion, parseVersionString, createVersion, isCompatibleVersion, isMajorCompatible, pickHighestDocument, } from './VersionUtils.js';
10
+ export type { DocumentVersionPick } from './VersionUtils.js';
@@ -1 +1 @@
1
- var m=class l{constructor(e,t,o,n){this.publisher=e;this.package_=t;this.name=o;this.version=n}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!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let o=t[0],n=t[1],r=o.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${o}. Expected format: publisher/package/name`);let i=n.split(".").map(Number),c={major:i[0]||0,minor:i[1]||0,patch:i[2]||0,toString:()=>`${i[0]||0}.${i[1]||0}.${i[2]||0}`,equals:s=>!s||typeof s!="object"?!1:s.major===(i[0]||0)&&s.minor===(i[1]||0)&&s.patch===(i[2]||0),getHashCode:()=>(i[0]||0)<<20|(i[1]||0)<<10|(i[2]||0),compareTo:s=>(i[0]||0)!==s.major?(i[0]||0)-s.major:(i[1]||0)!==s.minor?(i[1]||0)-s.minor:(i[2]||0)-s.patch};return new l(r[0],r[1],r[2],c)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}};function h(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var b=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let o=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(o);if(n){let i=n.get(e);if(i)return i}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(o,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let o=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),r=n[0],i=n[1],c=await this.findDocumentForAlias(t,r);return c?await this.resolveAllEntitiesAsync(i,c):[]}return o.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,o){let n=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),n;t.add(r);let i=o.length===0?r:`${o} \u2192 ${r}`;for(let[c,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)){let a=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:c,uri:new m(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,a),entity:s,definedInNamespace:r,isImported:o.length>0,importPath:i})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${r}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((s,a)=>s+a.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${r}`);for(let[s,a]of Object.entries(e.metadata.imports))for(let p of a)try{this.logger?.debug?.(`Resolving import: ${s}/${p.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(s,p);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let g=await this.buildAllEntitiesIndexAsync(u,t,i);n.push(...g),this.logger?.debug?.(`Added ${g.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${p.packageName}`)}catch(u){let g=u;throw this.logger?.error?.(`Failed to process import ${s}/${p.packageName} for namespace ${r}. Error: ${g.message}`,g),new Error(`Failed to process import ${s}/${p.packageName} for namespace ${r}. See inner exception for details.`,{cause:u})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,o){let n=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),n;t.add(r);let i=o.length===0?r:`${o} \u2192 ${r}`,c=0;for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)&&!n.has(s)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(s,{entityName:s,uri:new m(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,s,p),entity:a,definedInNamespace:r,isImported:o.length>0,importPath:i}),c++}if(this.logger?.debug?.(`Indexed ${c} entities from ${r}`),e.metadata?.imports){let s=Object.values(e.metadata.imports).reduce((a,p)=>a+p.length,0);this.logger?.debug?.(`Processing ${s} import(s) for ${r}`);for(let[a,p]of Object.entries(e.metadata.imports))for(let u of p)try{this.logger?.debug?.(`Resolving import: ${a}/${u.packageName}`);let g=await this.repository.getHighestCompatibleVersionAsync(a,u);if(g){this.logger?.debug?.(`Successfully loaded import: ${g.metadata?.namespace_?.toString()}`);let f=await this.buildEntityIndexAsyncInternal(g,t,i),y=0;for(let[d,v]of f.entries())if(n.has(d)||(n.set(d,v),y++),u.alias&&!d.includes(".")){let $=`${u.alias}.${d}`;n.has($)||(n.set($,v),y++)}this.logger?.debug?.(`Merged ${y} entities from import ${g.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${u.packageName}`)}catch(g){let f=g;throw this.logger?.error?.(`Failed to process import ${a}/${u.packageName} for namespace ${r}. Error: ${f.message}`,f),new Error(`Failed to process import ${a}/${u.packageName} for namespace ${r}. See inner exception for details.`,{cause:g})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(o,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(o,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,o){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,o,n)}async isSubclassOfRecursiveAsync(e,t,o,n){if(n.has(e))return!1;n.add(e);let r=await this.resolveEntityAsync(e,o);if(!r?.entity)return!1;let i=r.entity.subClassOf;if(i){let c=h(i);for(let s of c)if(s===t||await this.isSubclassOfRecursiveAsync(s,t,o,n))return!0}return!1}async isSubpropertyOfAsync(e,t,o){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,o,n)}async isSubpropertyOfRecursiveAsync(e,t,o,n){if(n.has(e))return!1;n.add(e);let r=await this.resolveEntityAsync(e,o);if(!r?.entity)return!1;let i=r.entity.subPropertyOf;if(i){let c=h(i);for(let s of c)if(s===t||await this.isSubpropertyOfRecursiveAsync(s,t,o,n))return!0}return!1}};var R=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,t){return(await this.resourceResolver.resolveEntityAsync(e,t))?.uri??null}buildFromName(e,t,o){if(e.includes(".")){let r=e.split("."),i=r[0],c=r[1],s=this.findPackageNameForAlias(o,i);if(s){for(let a of t.values())if(a.entityName===c&&a.uri.package_===s)return a.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,o,n){return new m(e,t,o,n)}findPackageNameForAlias(e,t){if(!e.metadata.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n)if(r.alias===t||!r.alias&&r.packageName===t)return r.packageName;return null}};var k=class l{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"&&l.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 l.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let o=await this.resourceResolver.resolveEntityAsync(e,t);if(o){let n=o.entity.type;if(n){let r=String(n);return r==="Class"||r==="rdfs.Class"||r.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))}};async function w(l,e){let t=[],o=await l.getAllDocumentsAsync();for(let n of o){let r=n.metadata.namespace_;if(!r)continue;let i=r.publisher,c=r.package_,s=r.version?`${r.version.major}.${r.version.minor}.${r.version.patch}`:"0.0.0";for(let[a,p]of Object.entries(n.body)){if(!p||typeof p!="object")continue;let u=p.type;!u||typeof u!="string"||u!=="Package"&&S(u,e)&&t.push({entityName:a,entity:p,documentNamespace:`${i}/${c}@${s}`,publisher:i,package_:c,version:s})}}return t}function S(l,e){let t=A(l),o=A(e);return t===o}function A(l){let e=l.lastIndexOf(".");if(e!==-1)return l.substring(e+1);let t=l.lastIndexOf("/");return t!==-1?l.substring(t+1):l}export{m as KanonakUri,R as KanonakUriBuilder,b as ResourceResolver,k as TypeResolver,w as findInstancesByType};
1
+ var g=class s{constructor(e,t,o,n){this.publisher=e;this.package_=t;this.name=o;this.version=n}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!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let o=t[0],n=t[1],r=o.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${o}. Expected format: publisher/package/name`);let i=n.split(".").map(Number),c={major:i[0]||0,minor:i[1]||0,patch:i[2]||0,toString:()=>`${i[0]||0}.${i[1]||0}.${i[2]||0}`,equals:a=>!a||typeof a!="object"?!1:a.major===(i[0]||0)&&a.minor===(i[1]||0)&&a.patch===(i[2]||0),getHashCode:()=>(i[0]||0)<<20|(i[1]||0)<<10|(i[2]||0),compareTo:a=>(i[0]||0)!==a.major?(i[0]||0)-a.major:(i[1]||0)!==a.minor?(i[1]||0)-a.minor:(i[2]||0)-a.patch};return new s(r[0],r[1],r[2],c)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}};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 R=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let o=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(o);if(n){let i=n.get(e);if(i)return i}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(o,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let o=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),r=n[0],i=n[1],c=await this.findDocumentForAlias(t,r);return c?await this.resolveAllEntitiesAsync(i,c):[]}return o.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,o){let n=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),n;t.add(r);let i=o.length===0?r:`${o} \u2192 ${r}`;for(let[c,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let u=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:c,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,u),entity:a,definedInNamespace:r,isImported:o.length>0,importPath:i})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${r}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((a,u)=>a+u.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${r}`);for(let[a,u]of Object.entries(e.metadata.imports))for(let p of u)try{this.logger?.debug?.(`Resolving import: ${a}/${p.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(a,p);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(l,t,i);n.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${p.packageName}`)}catch(l){let m=l;throw this.logger?.error?.(`Failed to process import ${a}/${p.packageName} for namespace ${r}. Error: ${m.message}`,m),new Error(`Failed to process import ${a}/${p.packageName} for namespace ${r}. See inner exception for details.`,{cause:l})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,o){let n=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),n;t.add(r);let i=o.length===0?r:`${o} \u2192 ${r}`,c=0;for(let[a,u]of Object.entries(e.body))if(u&&typeof u=="object"&&!Array.isArray(u)&&!n.has(a)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(a,{entityName:a,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,p),entity:u,definedInNamespace:r,isImported:o.length>0,importPath:i}),c++}if(this.logger?.debug?.(`Indexed ${c} entities from ${r}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((u,p)=>u+p.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${r}`);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,t,i),h=0;for(let[y,$]of d.entries())if(n.has(y)||(n.set(y,$),h++),l.alias&&!y.includes(".")){let x=`${l.alias}.${y}`;n.has(x)||(n.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 ${r}. Error: ${d.message}`,d),new Error(`Failed to process import ${u}/${l.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(o,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(o,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,o){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,o,n)}async isSubclassOfRecursiveAsync(e,t,o,n){if(n.has(e))return!1;n.add(e);let r=await this.resolveEntityAsync(e,o);if(!r?.entity)return!1;let i=r.entity.subClassOf;if(i){let c=b(i);for(let a of c)if(a===t||await this.isSubclassOfRecursiveAsync(a,t,o,n))return!0}return!1}async isSubpropertyOfAsync(e,t,o){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,o,n)}async isSubpropertyOfRecursiveAsync(e,t,o,n){if(n.has(e))return!1;n.add(e);let r=await this.resolveEntityAsync(e,o);if(!r?.entity)return!1;let i=r.entity.subPropertyOf;if(i){let c=b(i);for(let a of c)if(a===t||await this.isSubpropertyOfRecursiveAsync(a,t,o,n))return!0}return!1}};var k=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,t){return(await this.resourceResolver.resolveEntityAsync(e,t))?.uri??null}buildFromName(e,t,o){if(e.includes(".")){let r=e.split("."),i=r[0],c=r[1],a=this.findPackageNameForAlias(o,i);if(a){for(let u of t.values())if(u.entityName===c&&u.uri.package_===a)return u.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,o,n){return new g(e,t,o,n)}findPackageNameForAlias(e,t){if(!e.metadata.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n)if(r.alias===t||!r.alias&&r.packageName===t)return r.packageName;return null}};var v=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 o=await this.resourceResolver.resolveEntityAsync(e,t);if(o){let n=o.entity.type;if(n){let r=String(n);return r==="Class"||r==="rdfs.Class"||r.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))}};async function P(s,e){let t=[],o=await s.getAllDocumentsAsync();for(let n of o){let r=n.metadata.namespace_;if(!r)continue;let i=r.publisher,c=r.package_,a=r.version?`${r.version.major}.${r.version.minor}.${r.version.patch}`:"0.0.0";for(let[u,p]of Object.entries(n.body)){if(!p||typeof p!="object")continue;let l=p.type;!l||typeof l!="string"||l!=="Package"&&S(l,e)&&t.push({entityName:u,entity:p,documentNamespace:`${i}/${c}@${a}`,publisher:i,package_:c,version:a})}}return t}function S(s,e){let t=A(s),o=A(e);return t===o}function A(s){let e=s.lastIndexOf(".");if(e!==-1)return s.substring(e+1);let t=s.lastIndexOf("/");return t!==-1?s.substring(t+1):s}function f(s,e){return s.major!==e.major?s.major-e.major:s.minor!==e.minor?s.minor-e.minor:s.patch-e.patch}function K(s,e){return s.major===e.major&&s.minor===e.minor&&s.patch===e.patch}function D(s){return`${s.major}.${s.minor}.${s.patch}`}function w(s,e,t){let o=`${s}.${e}.${t}`;return{major:s,minor:e,patch:t,toString:()=>o,equals:n=>n?.major===s&&n?.minor===e&&n?.patch===t,getHashCode:()=>s<<20|e<<10|t,compareTo:n=>s!==n.major?s-n.major:e!==n.minor?e-n.minor:t-n.patch}}function I(s){let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(s);return e?w(Number(e[1]),Number(e[2]),Number(e[3])):null}function V(s,e){return f(s,e)>=0&&s.major===e.major&&s.minor===e.minor}function j(s,e){return e.major===0?f(s,e)>=0&&s.major===0&&s.minor===e.minor:f(s,e)>=0&&s.major===e.major}function E(s,e={}){let{requestedVersion:t}=e;if(s.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!t};if(t){let n=s.find(r=>{let i=r.metadata.namespace_?.version;return!!i&&D(i)===t});return n?{chosen:n,alternatives:s.filter(r=>r!==n),multipleVersionsPresent:s.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:s,multipleVersionsPresent:s.length>1,exactRequestedVersionMissing:!0}}if(s.length===1)return{chosen:s[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let o=[...s].sort((n,r)=>{let i=n.metadata.namespace_?.version,c=r.metadata.namespace_?.version;return!i&&!c?0:i?c?f(c,i):-1:1});return{chosen:o[0],alternatives:o.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}export{g as KanonakUri,k as KanonakUriBuilder,R as ResourceResolver,v as TypeResolver,f as compareVersions,w as createVersion,P as findInstancesByType,D as formatVersion,V as isCompatibleVersion,j as isMajorCompatible,I as parseVersionString,E as pickHighestDocument,K as versionsEqual};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Kanonak Protocol SDK - Document repository and parsing implementations for TypeScript",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -90,8 +90,7 @@
90
90
  },
91
91
  "repository": {
92
92
  "type": "git",
93
- "url": "git+https://github.com/kanonak-protocol/typescript.git",
94
- "directory": "sdk"
93
+ "url": "https://github.com/kanonak-protocol"
95
94
  },
96
95
  "publishConfig": {
97
96
  "registry": "https://npm.pkg.github.com"
@@ -106,9 +105,10 @@
106
105
  "yaml-parser"
107
106
  ],
108
107
  "dependencies": {
109
- "@kanonak-protocol/types": "^2.1.0",
108
+ "@kanonak-protocol/types": "^2.2.0",
110
109
  "ignore": "^7.0.5",
111
- "js-yaml": "^4.1.0"
110
+ "js-yaml": "^4.1.0",
111
+ "yaml": "^2.7.0"
112
112
  },
113
113
  "devDependencies": {
114
114
  "@types/jest": "^29.5.0",