@kanonak-protocol/sdk 4.4.0 → 4.6.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 CHANGED
@@ -1,2 +1,2 @@
1
- import{a as fe,b as ge,c as me,d as C,e as E,f as d,g as Ye}from"./chunk-2D3MZRJB.js";import{a as Qe}from"./chunk-NG2YXSH7.js";import"./chunk-QHABFCRC.js";import{b as L,c as W,d as F}from"./chunk-YCV4H6H5.js";import{a as H}from"./chunk-4NO7MHS7.js";import{a as Pe,b as we,c as he}from"./chunk-WBRCKPEH.js";import{a as ke,b as be}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as Le,B as We,C as Fe,D as Ge,M as Xe,a as Ke,b as xe,c as Se,d as Re,f as De,g as Be,h as Ce,i as Ee,k as je,l as ve,m as _e,n as Ie,o as Ae,p as Te,q as Oe,r as Ve,s as $e,t as Ue,u as Me,v as ze,w as Ne,x as Je,y as He,z as qe}from"./chunk-P3MJIJSK.js";import"./chunk-SHDHMKMJ.js";import{a as Y,c as le,i as pe}from"./chunk-FSHQVKZ5.js";import{a as q}from"./chunk-ZYAABYDS.js";import{a as ye}from"./chunk-UK2OIPAB.js";import"./chunk-PBNVHBS3.js";import{b as ue,c as de}from"./chunk-VKTFLHCW.js";import{a as G,b as X,c as Q,d as ee,e as re,f as te,g as ne,h as oe,i as se,j as ie,k as ae,l as ce}from"./chunk-T3JR2SV6.js";import{a as Z}from"./chunk-FUUTGGJS.js";import{c as O,d as V,e as $,f as U,g as M,h as z,i as N,j as J}from"./chunk-2ACBWC7K.js";var j="kanonak-credentials",u="credentials",Ze=1,g=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,Ze);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
1
+ import{a as fe,b as ge,c as me,d as C,e as E,f as d,g as Ye}from"./chunk-KGWDV7FW.js";import{a as Qe}from"./chunk-NV63IOB7.js";import"./chunk-QHABFCRC.js";import{b as L,c as W,d as F}from"./chunk-F26XWM5K.js";import{a as H}from"./chunk-4NO7MHS7.js";import{a as Pe,b as we,c as he}from"./chunk-RYOZTXI7.js";import{a as ke,b as be}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as Le,B as We,C as Fe,D as Ge,M as Xe,a as Ke,b as xe,c as Se,d as Re,f as De,g as Be,h as Ce,i as Ee,k as je,l as ve,m as _e,n as Ie,o as Ae,p as Te,q as Oe,r as Ve,s as $e,t as Ue,u as Me,v as ze,w as Ne,x as Je,y as He,z as qe}from"./chunk-IZRPJCQW.js";import"./chunk-SHDHMKMJ.js";import{a as Y,c as le,i as pe}from"./chunk-DSHPAWJQ.js";import{a as q}from"./chunk-NJ3AZYQD.js";import{a as ye}from"./chunk-UK2OIPAB.js";import"./chunk-PBNVHBS3.js";import{b as ue,c as de}from"./chunk-VKTFLHCW.js";import{a as G,b as X,c as Q,d as ee,e as re,f as te,g as ne,h as oe,i as se,j as ie,k as ae,l as ce}from"./chunk-T3JR2SV6.js";import{a as Z}from"./chunk-FUUTGGJS.js";import{c as O,d as V,e as $,f as U,g as M,h as z,i as N,j as J}from"./chunk-2ACBWC7K.js";var j="kanonak-credentials",u="credentials",Ze=1,g=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,Ze);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
2
2
  Credential storage requires IndexedDB support in your browser.`))})}async function _(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey);return{signingKey:n.privateKey,publicKeyJwk:r}}async function k(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey),e=await crypto.subtle.exportKey("jwk",n.privateKey);return{keys:{signingKey:n.privateKey,publicKeyJwk:r},dpopKeyPair:{publicKey:r,privateKey:e}}}async function b(n){return{signingKey:await crypto.subtle.importKey("jwk",n.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:n.publicKey}}async function K(n,r,e,t,o){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:n.publicKeyJwk.kty,crv:n.publicKeyJwk.crv,x:n.publicKeyJwk.x,y:n.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:r.toUpperCase(),htu:e,iat:Math.floor(Date.now()/1e3)};return t&&(s.ath=await rr(t)),o&&(s.nonce=o),await er(a,s,n.signingKey)}function x(n){return!n||n.length===0?!1:n.some(r=>r.toUpperCase()==="ES256")}async function er(n,r,e){let t=v(JSON.stringify(n)),o=v(JSON.stringify(r)),a=new TextEncoder().encode(`${t}.${o}`),s=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,a),l=D(s);return`${t}.${o}.${l}`}async function rr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return D(e)}function v(n){let r=new TextEncoder().encode(n);return D(r.buffer)}function D(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var tr=300*1e3,S=class{credentialBackend;callbackUrl;constructor(r){this.credentialBackend=new g,this.callbackUrl=r??`${window.location.origin}/browser/callback.html`}async authorize(r){let e=d(r),t=await this.discover(e);if(!t)return{success:!1,error:`No OAuth discovery endpoint found for '${e}'.`};if(!t.authorizationEndpoint||!t.tokenEndpoint)return{success:!1,error:`OAuth metadata incomplete for '${e}'.`};let o=x(t.dpopSigningAlgValuesSupported),a=null,s=null;if(o){let f=await k();a=f.keys,s=f.dpopKeyPair}let l=await this.credentialBackend.get(e),i=l?.clientId??null,c=l?.clientSecret??null;if(!i&&t.registrationEndpoint){let f=await this.registerClient(t.registrationEndpoint);if(!f)return{success:!1,error:`Dynamic client registration failed for '${e}'.`};i=f.clientId,c=f.clientSecret??null}if(!i)return{success:!1,error:`No OAuth client credentials for '${e}'.`};let m=nr(),p=await or(m),R=sr(),A=ir(t.authorizationEndpoint,i,this.callbackUrl,R,p),y=await this.openAuthPopup(A,R);if(!y)return{success:!1,error:"Authorization timed out or was cancelled."};if(y.error)return{success:!1,error:`Authorization failed: ${y.error}`};if(!y.code)return{success:!1,error:"No authorization code received."};if(y.state!==R)return{success:!1,error:"State mismatch \u2014 possible CSRF attack."};let P=await this.exchangeCode(t.tokenEndpoint,i,c,y.code,this.callbackUrl,m,a);if(!P)return{success:!1,error:"Token exchange failed."};let T={clientId:i,clientSecret:c,accessToken:P.accessToken??null,refreshToken:P.refreshToken??null,expiresAt:P.expiresIn?new Date(Date.now()+P.expiresIn*1e3).toISOString():null,tokenEndpoint:t.tokenEndpoint,dpopKeyPair:s};return await this.credentialBackend.store(e,T),{success:!0,host:e}}async getCredentialWithKeys(r){let e=await this.credentialBackend.get(r);if(!e)return null;let t=null;return e.dpopKeyPair&&(t=await b(e.dpopKeyPair)),{credential:e,dpopKeys:t}}async logout(r){let e=d(r);return await this.credentialBackend.remove(e),{success:!0,host:e}}async listAuthenticated(){return this.credentialBackend.list()}async discover(r){for(let e of[`https://${r}/.well-known/oauth-authorization-server`,`https://${r}/.well-known/openid-configuration`])try{let t=await fetch(e);if(!t.ok)continue;let o=await t.json();return{issuer:w(o.issuer),authorizationEndpoint:w(o.authorization_endpoint),tokenEndpoint:w(o.token_endpoint),registrationEndpoint:w(o.registration_endpoint),revocationEndpoint:w(o.revocation_endpoint),dpopSigningAlgValuesSupported:I(o.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:I(o.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(r){try{let e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak Browser",redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})});if(!e.ok)return null;let t=await e.json(),o=t.client_id;return o?{clientId:o,clientSecret:t.client_secret}:null}catch{return null}}openAuthPopup(r,e){return new Promise(t=>{let o=window.open(r,"kanonak-auth","width=500,height=700,menubar=no,toolbar=no,location=yes,status=no");if(!o){t(null);return}let a=setTimeout(()=>{i(),t(null)},tr),s=c=>{c.origin===window.location.origin&&(!c.data||c.data.type!=="kanonak-auth-callback"||(i(),t({code:c.data.code??void 0,state:c.data.state??void 0,error:c.data.error??void 0})))},l=setInterval(()=>{o.closed&&(i(),t(null))},500),i=()=>{clearTimeout(a),clearInterval(l),window.removeEventListener("message",s);try{o.close()}catch{}};window.addEventListener("message",s)})}async exchangeCode(r,e,t,o,a,s,l){let i=new URLSearchParams({grant_type:"authorization_code",client_id:e,code:o,redirect_uri:a,code_verifier:s});t&&i.set("client_secret",t);let c={"Content-Type":"application/x-www-form-urlencoded"};l&&(c.DPoP=await K(l,"POST",r));try{let m=await fetch(r,{method:"POST",headers:c,body:i.toString()});if(!m.ok)return null;let p=await m.json();return{accessToken:p.access_token,refreshToken:p.refresh_token,expiresIn:typeof p.expires_in=="number"?p.expires_in:void 0}}catch{return null}}};function nr(){let n=new Uint8Array(32);return crypto.getRandomValues(n),B(n.buffer)}async function or(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return B(e)}function sr(){let n=new Uint8Array(16);return crypto.getRandomValues(n),B(n.buffer)}function ir(n,r,e,t,o){let a=new URLSearchParams({client_id:r,response_type:"code",redirect_uri:e,state:t,code_challenge:o,code_challenge_method:"S256"});return`${n}?${a}`}function B(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(n){return typeof n=="string"?n:null}function I(n){return Array.isArray(n)?n.filter(r=>typeof r=="string"):null}export{Ne as AmbiguousReferenceRule,se as BooleanStatement,g as BrowserCredentialBackend,S as BrowserOAuthFlow,Fe as ClassDefinitionRule,Ie as ClassHierarchyCycleRule,X as DefinedKanonak,Me as DefinitionPropertyReferenceRule,ge as EdgeType,Y as EmbeddedKanonak,je as EmbeddedKanonakTypeRule,ae as EmbeddedStatement,me as GraphBuilder,F as HttpKanonakDocumentRepository,ve as ImportExistenceRule,H as InMemoryKanonakDocumentRepository,Ue as InstancePropertyReferenceRule,G as Kanonak,we as KanonakDocumentPositions,pe as KanonakObjectParser,Xe as KanonakObjectValidator,q as KanonakParser,Z as KanonakUri,ke as KanonakUriBuilder,ce as ListStatement,Ge as MarkdownLinkRule,le as MarkdownStatement,$e as NamespaceImportCycleRule,De as NamespacePrefixRule,fe as NodeType,oe as NumberStatement,He as ObjectPropertyImportRule,qe as ObjectPropertyValueValidationRule,Se as OntologyValidationError,Ke as OntologyValidationResult,Le as PropertyDomainRule,Ae as PropertyHierarchyCycleRule,Pe as PropertyMetadata,Je as PropertyRangeReferenceRule,Te as PropertyRangeRequiredRule,Ce as PropertyTypeSpecificityRule,We as PropertyValueTypeRule,L as PublisherConfigResolver,W as PublisherIndex,ee as ReferenceKanonak,ie as ReferenceStatement,Be as ResourceNamingRule,ue as ResourceResolver,ye as ResourceTypeClassifier,te as ScalarStatement,re as Statement,ne as StringStatement,Oe as SubClassOfReferenceRule,Ve as SubPropertyOfReferenceRule,Q as SubjectKanonak,Ee as SubjectKanonakTypeRequiredRule,de as TypeResolver,_e as UnresolvedReferenceRule,Re as ValidationContext,xe as ValidationSeverity,ze as XsdImportRule,x as browserServerSupportsDPoP,Ye as buildOntologyModel,O as compareVersions,K as createBrowserDPoPProof,U as createVersion,Qe as findDerivation,be as findInstancesByType,$ as formatVersion,k as generateBrowserDPoPKeyPair,_ as generateBrowserDPoPKeys,E as hasValidToken,b as importDPoPKeys,z as isCompatibleVersion,C as isExpired,N as isMajorCompatible,d as normalizeHost,M as parseVersionString,he as parseWithPositions,J as pickHighestDocument,V as versionsEqual};
@@ -1 +1 @@
1
- import{a as U}from"./chunk-ZYAABYDS.js";import{b as F,c as V,i as E}from"./chunk-VKTFLHCW.js";import{a as B,b as _,c as x,d as k,g as $,h as T,i as C,j as K,k as w,l as j}from"./chunk-T3JR2SV6.js";import{j as L}from"./chunk-2ACBWC7K.js";var S=class extends _{name};var I=class extends B{value;carrier;lexical};var R=class extends ${links=[]};var W=n=>({publisher:"kanonak.org",package_:"core-xsd",name:n}),J=n=>({publisher:"kanonak.org",package_:"core-rdf",name:n}),Y=(p=>(p.Integer="integer",p.Decimal="decimal",p.Double="double",p.Float="float",p.Boolean="boolean",p.String="string",p.AnyUri="anyURI",p.LangString="langString",p.DateTime="dateTime",p.Date="date",p.Time="time",p.HexBinary="hexBinary",p.Base64Binary="base64Binary",p))(Y||{});function v(n){return`${n.publisher}/${n.package_}/${n.name}`}var Q=[["integer","integer"],["long","integer"],["int","integer"],["short","integer"],["byte","integer"],["unsignedLong","integer"],["unsignedInt","integer"],["unsignedShort","integer"],["unsignedByte","integer"],["nonNegativeInteger","integer"],["positiveInteger","integer"],["nonPositiveInteger","integer"],["negativeInteger","integer"],["decimal","decimal"],["double","double"],["float","float"],["boolean","boolean"],["string","string"],["normalizedString","string"],["token","string"],["anyURI","anyURI"],["dateTime","dateTime"],["date","date"],["time","time"],["hexBinary","hexBinary"],["base64Binary","base64Binary"]],ee=new Map(Q.map(([n,e])=>[v(W(n)),e])),ne=v(J("langString"));function M(n){let e=v(n);return e===ne?"langString":ee.get(e)}function te(n){let e=n.trim();if(!/^[+-]?\d+$/.test(e))throw new Error(`canonicalInteger: '${n}' is not a valid xsd:integer lexical`);return BigInt(e.replace(/^\+/,"")).toString()}function re(n){let e=n.trim(),t=/^([+-]?)(\d*)(?:\.(\d*))?$/.exec(e);if(!t||t[2]===""&&(t[3]??"")==="")throw new Error(`canonicalDecimal: '${n}' is not a valid xsd:decimal lexical`);let a=t[1]==="-"?"-":"",r=(t[2]??"").replace(/^0+/,"")||"0",i=(t[3]??"").replace(/0+$/,""),o=i.length>0?`${r}.${i}`:r;return o==="0"?"0":`${a}${o}`}function Z(n,e,t){let a=n.trim();if(a==="NaN")return"NaN";if(a==="INF")return"INF";if(a==="-INF")return"-INF";if(!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(a))throw new Error(`canonical${t}: '${n}' is not a valid xsd:${t.toLowerCase()} lexical`);let r=e(Number(a));if(!Number.isFinite(r))throw new Error(`canonical${t}: '${n}' is out of the finite range`);return Object.is(r,-0)?"0":String(r)}function ae(n){return Z(n,e=>e,"Double")}function oe(n){return Z(n,e=>Math.fround(e),"Float")}function ie(n){let e=n.trim();if(e==="true"||e==="1")return"true";if(e==="false"||e==="0")return"false";throw new Error(`canonicalBoolean: '${n}' is not a valid xsd:boolean lexical`)}function z(n){return n.normalize("NFC")}function se(n){return n.normalize("NFC")}function ce(n){let e=n.trim();if(!/^([0-9A-Fa-f]{2})*$/.test(e))throw new Error(`canonicalHexBinary: '${n}' is not a valid xsd:hexBinary lexical`);return e.toUpperCase()}function fe(n){let e=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)throw new Error(`canonicalBase64: '${n}' is not a valid xsd:base64Binary lexical`);return Buffer.from(e,"base64").toString("base64")}var D=n=>n<10?`0${n}`:`${n}`;function P(n){let e=n.startsWith("-"),t=(e?n.slice(1):n).replace(/^0+/,"")||"0",a=t.length<4?t.padStart(4,"0"):t;return`${e?"-":""}${a}`}function H(n){if(!n)return"";let e=n.replace(/^\./,"").replace(/0+$/,"");return e.length>0?`.${e}`:""}function X(n){return n?n==="Z"||n==="+00:00"||n==="-00:00"?"Z":n:""}function pe(n){return n==="Z"?0:(n[0]==="-"?-1:1)*(Number(n.slice(1,3))*60+Number(n.slice(4,6)))}var ue=/^(-?\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,le=/^(-?\d{4,})-(\d{2})-(\d{2})(Z|[+-]\d{2}:\d{2})?$/,me=/^(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/;function de(n){let e=ue.exec(n.trim());if(!e)throw new Error(`canonicalDateTime: '${n}' is not a valid xsd:dateTime lexical`);let[,t,a,r,i,o,c,f,u]=e,d=H(f);if(!u)return`${P(t)}-${a}-${r}T${i}:${o}:${c}${d}`;let m=new Date(0);m.setUTCFullYear(Number(t),Number(a)-1,Number(r)),m.setUTCHours(Number(i),Number(o),Number(c),0);let s=new Date(m.getTime()-pe(u)*6e4);return`${P(String(s.getUTCFullYear()))}-${D(s.getUTCMonth()+1)}-${D(s.getUTCDate())}T${D(s.getUTCHours())}:${D(s.getUTCMinutes())}:${D(s.getUTCSeconds())}${d}Z`}function ge(n){let e=le.exec(n.trim());if(!e)throw new Error(`canonicalDate: '${n}' is not a valid xsd:date lexical`);let[,t,a,r,i]=e;return`${P(t)}-${a}-${r}${X(i)}`}function ye(n){let e=me.exec(n.trim());if(!e)throw new Error(`canonicalTime: '${n}' is not a valid xsd:time lexical`);let[,t,a,r,i,o]=e,c=H(i),f=t;return t==="24"&&a==="00"&&r==="00"&&c===""&&(f="00"),`${f}:${a}:${r}${c}${X(o)}`}function Re(n,e){switch(n){case"integer":return te(e);case"decimal":return re(e);case"double":return ae(e);case"float":return oe(e);case"boolean":return ie(e);case"string":return z(e);case"anyURI":return se(e);case"langString":return z(e);case"dateTime":return de(e);case"date":return ge(e);case"time":return ye(e);case"hexBinary":return ce(e);case"base64Binary":return fe(e)}}var ke=/\[\[([^\[\]\n]+)\]\]/g,be=/\[\[/g,G=/```[\s\S]*?```|`[^`\n]*`/g;function he(n){let e=[];for(let t of n.matchAll(G))e.push([t.index,t.index+t[0].length]);return e}function Te(n){if(!n||!n.includes("[["))return[];let e=he(n),t=i=>e.some(([o,c])=>i>=o&&i<c),a=new Set(A(n).map(i=>i.startOffset)),r=[];for(let i of n.matchAll(be)){let o=i.index;if(t(o)||a.has(o))continue;let c=n.slice(o,o+48).replace(/\s+/g," ").trim();r.push({startOffset:o,snippet:c})}return r}function A(n){if(!n||!n.includes("[["))return[];let e=[];for(let r of n.matchAll(G))e.push([r.index,r.index+r[0].length]);let t=r=>e.some(([i,o])=>r>=i&&r<o),a=[];for(let r of n.matchAll(ke)){let i=r.index;if(t(i))continue;let o=r[1],c=o.indexOf("|"),f=(c===-1?o:o.slice(0,c)).trim();if(f.length===0)continue;let u=c===-1?"":o.slice(c+1).trim(),d={reference:f,startOffset:i,endOffset:i+r[0].length};u.length>0&&(d.displayText=u),a.push(d)}return a}var q=class{constructor(e){}async parseKanonaks(e){let t=[],a=await e.getAllDocumentsAsync(),r=new F(e),i=new V(r);for(let s of a){let p=s.metadata.namespace_?.toString()??"";for(let[l,y]of Object.entries(s.body)){let g=new x,b=this.resolveCanonicalEntity(l,s,p);g.namespace=b.namespace,g.name=b.name,g.statement=[];let h=await this.parseStatements(y,s,r,i,e);g.statement.push(...h),t.push(g)}}let o=new Map,c=new Map,f=[];for(let s of t)if(s instanceof x){let p=`${s.namespace}/${s.name}`,l=o.get(p);if(l){let y=c.get(p);for(let g of s.statement){let b=O(g);y.has(b)||(y.add(b),l.statement.push(g))}}else{let y=new Set,g=[];for(let b of s.statement){let h=O(b);y.has(h)||(y.add(h),g.push(b))}s.statement=g,c.set(p,y),o.set(p,s),f.push(s)}}else f.push(s);let u=new Set;for(let s of f)if(s instanceof x){let p=s.namespace||"",l=p.indexOf("/"),y=l>=0?p.slice(0,l):"",g=l>=0?p.slice(l+1):"",b=g.indexOf("@"),h=b>=0?g.slice(0,b):g;u.add(`${y}/${h}/${s.name}`)}let d=s=>u.has(`${s.publisher}/${s.package_}/${s.name}`),m=new Map;for(let s of["core-rdf","core-owl","core-kanonak"]){let p=await e.getDocumentsByNamespaceAsync("kanonak.org",s);m.set(s,L(p).chosen?.metadata.namespace_?.version??void 0)}for(let s of f)s instanceof x&&this.canonicalizeStatementBuiltins(s.statement,d,m);return f}canonicalizeStatementBuiltins(e,t,a){for(let r of e){let i=r.predicate?.subject;if(E(i,t,a),r instanceof K)r.object instanceof k&&E(r.object.subject,t,a);else if(r instanceof w)r.object&&this.canonicalizeStatementBuiltins(r.object.statement,t,a);else if(r instanceof j)for(let o of r.object??[])o instanceof k?E(o.subject,t,a):o instanceof S&&this.canonicalizeStatementBuiltins(o.statement,t,a)}}resolveCanonicalEntity(e,t,a){if(!e.includes(".")||!t.metadata?.imports)return{namespace:a,name:e};let r=e.indexOf("."),i=e.substring(0,r),o=e.substring(r+1);for(let[c,f]of Object.entries(t.metadata.imports))for(let u of f)if((u.alias??u.packageName)===i){let m=u.version;return{namespace:`${c}/${u.packageName}@${m.major}.${m.minor}.${m.patch}`,name:o}}return{namespace:a,name:e}}async parseStatements(e,t,a,r,i){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[c,f]of Object.entries(e))try{let u=await this.getPropertyMetadata(c,t,a,i,r);if(!u)continue;let d=await this.parsePropertyValue(c,f,u,t,a,r,i);d&&o.push(d)}catch(u){throw new Error(`Failed to parse property '${c}': ${u.message}`,{cause:u})}return o}async getPropertyMetadata(e,t,a,r,i){let o=await a.resolveEntityAsync(e,t);if(!o)return;let c=o.entity,f=c.type?.toString()??"",u=f.includes(".")?f.substring(f.lastIndexOf(".")+1):f;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(u))return;let m=i.getPropertyTypeClassification(f),s=c.range?.toString(),p;if(m==="ObjectProperty")p="ObjectProperty";else if(m==="DatatypeProperty")p="DatatypeProperty";else{let g=s&&s.includes(".")?s.substring(s.lastIndexOf(".")+1):s??"";(s?i.isKnownXsdDatatypeName(s):!1)||g==="Literal"?p="DatatypeProperty":p="ObjectProperty"}let l;if(s){let g=t;if(o.isImported&&o.definedInNamespace){if(typeof r.getDocumentAsync!="function")throw new Error(`Cannot resolve the range of imported property '${e}': the parse repository cannot fetch defining document '${o.definedInNamespace}'. Thread the real repository through to embedded-object parsing \u2014 no stub, no fallback.`);let h=await r.getDocumentAsync(o.definedInNamespace);if(!h)throw new Error(`Cannot resolve the range of imported property '${e}': defining document '${o.definedInNamespace}' was not found in the repository.`);g=h}l=(await a.resolveEntityAsync(s,g))?.uri}return{propertyUri:o.uri.toString(),propertyType:p,range:s,rangeUri:l,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,a,r,i,o,c){let f=a.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(f,t,a,r,i,o,c);if(a.propertyType==="DatatypeProperty")return this.parseDatatypeValue(f,t,a,r,i,o);if(a.propertyType==="ObjectProperty")return this.parseObjectValue(f,t,a,r,i,o,c)}}async parseDatatypeValue(e,t,a,r,i,o){let c;if(typeof t=="string"){if(o.isSubstitutableDatatype(a.rangeUri))return await this.parseSubstitutableValue(e,t,r,i);c=t}else if(typeof t=="number"||typeof t=="boolean")c=String(t);else return;return this.typedScalarStatement(e,c,a)}typedScalarStatement(e,t,a){let r=k.parse(e),i=a.rangeUri?M(a.rangeUri):void 0;if(i==="boolean"){let c=new C;return c.predicate=r,c.object=t==="true"||t==="1",c.carrier=i,c.lexical=t,c}if(i==="integer"||i==="decimal"||i==="double"||i==="float"){let c=new T;return c.predicate=r,c.object=Number(t),c.carrier=i,c.lexical=t,c}let o=$.parse(e,t);return i&&(o.carrier=i,o.lexical=t),o}typedListLiteral(e,t){let a=new I,r=t.rangeUri?M(t.rangeUri):void 0;return r==="boolean"?a.value=e==="true"||e==="1":r==="integer"||r==="decimal"||r==="double"||r==="float"?a.value=Number(e):a.value=e,r&&(a.carrier=r,a.lexical=e),a}async parseSubstitutableValue(e,t,a,r){let i=new R;i.predicate=k.parse(e),i.object=t;for(let o of A(t)){let c=await r.resolveEntityAsync(o.reference,a),f;c&&(f=new k,f.subject=c.uri);let u={reference:o.reference,startOffset:o.startOffset,endOffset:o.endOffset};o.displayText!==void 0&&(u.displayText=o.displayText),f!==void 0&&(u.target=f),i.links.push(u)}return i}async parseObjectValue(e,t,a,r,i,o,c){if(typeof t=="string"){let f=await this.resolveReference(t,r,i);if(!f)return;let u=new K;return u.predicate=k.parse(e),u.object=f,u}if(typeof t=="object"&&!Array.isArray(t)){let f=new S;if(f.statement=await this.parseStatements(t,r,i,o,c),f.statement.length>0){let m=new w;return m.predicate=k.parse(e),m.object=f,m}let u=[];for(let[m,s]of Object.entries(t))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let p=new S;p.name=m,p.statement=await this.parseStatements(s,r,i,o,c),u.push(p)}else if(typeof s=="string"){let p=await this.resolveReference(s,r,i);p&&u.push(p)}if(u.length>0){let m=new j;return m.predicate=k.parse(e),m.object=u,m}let d=new w;return d.predicate=k.parse(e),d.object=f,d}}async parseListValue(e,t,a,r,i,o,c){let f=[],u=a.propertyType==="DatatypeProperty",d=a.rangeUri?.publisher==="kanonak.org"&&a.rangeUri?.package_==="core-rdf"&&a.rangeUri?.name==="List"||!a.rangeUri&&(a.range?.includes(".")?a.range.substring(a.range.lastIndexOf(".")+1):a.range)==="List";for(let s of t){let p=typeof s=="string"||typeof s=="number"||typeof s=="boolean";if(u&&p){let l=typeof s=="string"?s:String(s);f.push(this.typedListLiteral(l,a));continue}if(d&&p){if(typeof s=="string"){let l=await i.resolveEntityAsync(s,r);if(l){let y=new k;y.subject=l.uri,f.push(y)}else{let y=new I;y.value=s,f.push(y)}}else{let l=new I;l.value=s,f.push(l)}continue}if(typeof s=="string"){let l=await this.resolveReference(s,r,i);l&&f.push(l)}else if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let l=new S;l.statement=await this.parseStatements(s,r,i,o,c),f.push(l)}}let m=new j;return m.predicate=k.parse(e),m.object=f,m}async resolveReference(e,t,a){let r=await a.resolveEntityAsync(e,t);if(r){let o=new k;return o.subject=r.uri,o}let i=t.metadata?.namespace_;if(i){let{KanonakUri:o}=await import("./KanonakUri-4VJGV3FN.js"),c=i.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let u=e.indexOf("."),d=e.substring(0,u),m=e.substring(u+1);if(t.metadata?.imports){for(let[s,p]of Object.entries(t.metadata.imports))for(let l of p)if((l.alias??l.packageName)===d){let g=new k;return g.subject=new o(s,l.packageName,m,l.version),g}}}let f=new k;return f.subject=new o(i.publisher,i.package_,e,c),f}return null}async saveKanonaks(e,t){let a=new Map;for(let r of e)r instanceof x&&r.namespace&&(a.has(r.namespace)||a.set(r.namespace,[]),a.get(r.namespace).push(r));for(let[r,i]of a){let o=await this.convertKanonaksToDocument(r,i),c=`${r.split("@")[0]}.yml`;await t.saveDocumentAsync(o,c)}}async serializeToYaml(e,t){let a=e.filter(o=>o instanceof x&&o.namespace===t);if(a.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let r=await this.convertKanonaksToDocument(t,a);return new U().save(r)}async convertKanonaksToDocument(e,t){let r={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let c of Object.values(this.imports))o.push(...c);return o}},body:{}},i=new Map;for(let o of t){let c={};for(let f of o.statement){let[u,d]=this.convertStatementToProperty(f);u&&d!==null&&d!==void 0&&(c[u]=d),this.collectImportsFromStatement(f,e,i)}r.body[o.name]=c}return r}convertStatementToProperty(e){if(e instanceof $)return[e.predicate.subject.name,e.object];if(e instanceof T)return[e.predicate.subject.name,e.object];if(e instanceof C)return[e.predicate.subject.name,e.object];if(e instanceof K)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof j){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof w){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let a of e)a instanceof k?t.push(a.subject.name):a instanceof S&&t.push(this.convertEmbeddedKanonakToValue(a));return t}convertEmbeddedKanonakToValue(e){let t={};for(let a of e.statement){let[r,i]=this.convertStatementToProperty(a);r&&i!==null&&i!==void 0&&(t[r]=i)}return t}collectImportsFromStatement(e,t,a){}};function O(n){let e=n.predicate?.subject;return(e?`${e.publisher}/${e.package_}/${e.name}`:"?")+"="+Se(n)}function Se(n){return n instanceof R?"m:"+String(n.object):n instanceof $?"s:"+String(n.object):n instanceof T?"n:"+String(n.object):n instanceof C?"b:"+String(n.object):n instanceof K?"r:"+N(n.object):n instanceof w?"e:"+N(n.object):n instanceof j?"l:["+(n.object??[]).map(N).join("|")+"]":"x"}function N(n){if(!n)return"";if(n instanceof k){let e=n.subject;return"R("+(e?`${e.publisher}/${e.package_}/${e.name}`:"")+")"}return n instanceof S?"E("+(n.statement??[]).map(O).join(";")+")":n instanceof I?"L("+String(n.value)+")":"N"}export{S as a,I as b,R as c,Y as d,M as e,Re as f,Te as g,A as h,q as i};
1
+ import{a as U}from"./chunk-NJ3AZYQD.js";import{b as F,c as V,i as P}from"./chunk-VKTFLHCW.js";import{a as B,b as _,c as x,d as k,g as $,h as T,i as E,j as K,k as w,l as j}from"./chunk-T3JR2SV6.js";import{j as L}from"./chunk-2ACBWC7K.js";var S=class extends _{name};var I=class extends B{value;carrier;lexical};var R=class extends ${links=[]};var W=n=>({publisher:"kanonak.org",package_:"core-xsd",name:n}),J=n=>({publisher:"kanonak.org",package_:"core-rdf",name:n}),Y=(p=>(p.Integer="integer",p.Decimal="decimal",p.Double="double",p.Float="float",p.Boolean="boolean",p.String="string",p.AnyUri="anyURI",p.LangString="langString",p.DateTime="dateTime",p.Date="date",p.Time="time",p.HexBinary="hexBinary",p.Base64Binary="base64Binary",p))(Y||{});function v(n){return`${n.publisher}/${n.package_}/${n.name}`}var Q=[["integer","integer"],["long","integer"],["int","integer"],["short","integer"],["byte","integer"],["unsignedLong","integer"],["unsignedInt","integer"],["unsignedShort","integer"],["unsignedByte","integer"],["nonNegativeInteger","integer"],["positiveInteger","integer"],["nonPositiveInteger","integer"],["negativeInteger","integer"],["decimal","decimal"],["double","double"],["float","float"],["boolean","boolean"],["string","string"],["normalizedString","string"],["token","string"],["anyURI","anyURI"],["dateTime","dateTime"],["date","date"],["time","time"],["hexBinary","hexBinary"],["base64Binary","base64Binary"]],ee=new Map(Q.map(([n,e])=>[v(W(n)),e])),ne=v(J("langString"));function M(n){let e=v(n);return e===ne?"langString":ee.get(e)}function te(n){let e=n.trim();if(!/^[+-]?\d+$/.test(e))throw new Error(`canonicalInteger: '${n}' is not a valid xsd:integer lexical`);return BigInt(e.replace(/^\+/,"")).toString()}function re(n){let e=n.trim(),t=/^([+-]?)(\d*)(?:\.(\d*))?$/.exec(e);if(!t||t[2]===""&&(t[3]??"")==="")throw new Error(`canonicalDecimal: '${n}' is not a valid xsd:decimal lexical`);let a=t[1]==="-"?"-":"",r=(t[2]??"").replace(/^0+/,"")||"0",i=(t[3]??"").replace(/0+$/,""),o=i.length>0?`${r}.${i}`:r;return o==="0"?"0":`${a}${o}`}function Z(n,e,t){let a=n.trim();if(a==="NaN")return"NaN";if(a==="INF")return"INF";if(a==="-INF")return"-INF";if(!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(a))throw new Error(`canonical${t}: '${n}' is not a valid xsd:${t.toLowerCase()} lexical`);let r=e(Number(a));if(!Number.isFinite(r))throw new Error(`canonical${t}: '${n}' is out of the finite range`);return Object.is(r,-0)?"0":String(r)}function ae(n){return Z(n,e=>e,"Double")}function oe(n){return Z(n,e=>Math.fround(e),"Float")}function ie(n){let e=n.trim();if(e==="true"||e==="1")return"true";if(e==="false"||e==="0")return"false";throw new Error(`canonicalBoolean: '${n}' is not a valid xsd:boolean lexical`)}function z(n){return n.normalize("NFC")}function se(n){return n.normalize("NFC")}function ce(n){let e=n.trim();if(!/^([0-9A-Fa-f]{2})*$/.test(e))throw new Error(`canonicalHexBinary: '${n}' is not a valid xsd:hexBinary lexical`);return e.toUpperCase()}function fe(n){let e=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)throw new Error(`canonicalBase64: '${n}' is not a valid xsd:base64Binary lexical`);return Buffer.from(e,"base64").toString("base64")}var D=n=>n<10?`0${n}`:`${n}`;function C(n){let e=n.startsWith("-"),t=(e?n.slice(1):n).replace(/^0+/,"")||"0",a=t.length<4?t.padStart(4,"0"):t;return`${e?"-":""}${a}`}function H(n){if(!n)return"";let e=n.replace(/^\./,"").replace(/0+$/,"");return e.length>0?`.${e}`:""}function X(n){return n?n==="Z"||n==="+00:00"||n==="-00:00"?"Z":n:""}function pe(n){return n==="Z"?0:(n[0]==="-"?-1:1)*(Number(n.slice(1,3))*60+Number(n.slice(4,6)))}var ue=/^(-?\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,le=/^(-?\d{4,})-(\d{2})-(\d{2})(Z|[+-]\d{2}:\d{2})?$/,me=/^(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/;function de(n){let e=ue.exec(n.trim());if(!e)throw new Error(`canonicalDateTime: '${n}' is not a valid xsd:dateTime lexical`);let[,t,a,r,i,o,c,f,u]=e,d=H(f);if(!u)return`${C(t)}-${a}-${r}T${i}:${o}:${c}${d}`;let l=new Date(0);l.setUTCFullYear(Number(t),Number(a)-1,Number(r)),l.setUTCHours(Number(i),Number(o),Number(c),0);let s=new Date(l.getTime()-pe(u)*6e4);return`${C(String(s.getUTCFullYear()))}-${D(s.getUTCMonth()+1)}-${D(s.getUTCDate())}T${D(s.getUTCHours())}:${D(s.getUTCMinutes())}:${D(s.getUTCSeconds())}${d}Z`}function ge(n){let e=le.exec(n.trim());if(!e)throw new Error(`canonicalDate: '${n}' is not a valid xsd:date lexical`);let[,t,a,r,i]=e;return`${C(t)}-${a}-${r}${X(i)}`}function ye(n){let e=me.exec(n.trim());if(!e)throw new Error(`canonicalTime: '${n}' is not a valid xsd:time lexical`);let[,t,a,r,i,o]=e,c=H(i),f=t;return t==="24"&&a==="00"&&r==="00"&&c===""&&(f="00"),`${f}:${a}:${r}${c}${X(o)}`}function Re(n,e){switch(n){case"integer":return te(e);case"decimal":return re(e);case"double":return ae(e);case"float":return oe(e);case"boolean":return ie(e);case"string":return z(e);case"anyURI":return se(e);case"langString":return z(e);case"dateTime":return de(e);case"date":return ge(e);case"time":return ye(e);case"hexBinary":return ce(e);case"base64Binary":return fe(e)}}var ke=/\[\[([^\[\]\n]+)\]\]/g,be=/\[\[/g,G=/```[\s\S]*?```|`[^`\n]*`/g;function he(n){let e=[];for(let t of n.matchAll(G))e.push([t.index,t.index+t[0].length]);return e}function Te(n){if(!n||!n.includes("[["))return[];let e=he(n),t=i=>e.some(([o,c])=>i>=o&&i<c),a=new Set(A(n).map(i=>i.startOffset)),r=[];for(let i of n.matchAll(be)){let o=i.index;if(t(o)||a.has(o))continue;let c=n.slice(o,o+48).replace(/\s+/g," ").trim();r.push({startOffset:o,snippet:c})}return r}function A(n){if(!n||!n.includes("[["))return[];let e=[];for(let r of n.matchAll(G))e.push([r.index,r.index+r[0].length]);let t=r=>e.some(([i,o])=>r>=i&&r<o),a=[];for(let r of n.matchAll(ke)){let i=r.index;if(t(i))continue;let o=r[1],c=o.indexOf("|"),f=(c===-1?o:o.slice(0,c)).trim();if(f.length===0)continue;let u=c===-1?"":o.slice(c+1).trim(),d={reference:f,startOffset:i,endOffset:i+r[0].length};u.length>0&&(d.displayText=u),a.push(d)}return a}var q=class{constructor(e){}async parseKanonaks(e){let t=[],a=await e.getAllDocumentsAsync(),r=new F(e),i=new V(r);for(let s of a){let p=s.metadata.namespace_?.toString()??"";for(let[m,g]of Object.entries(s.body)){let y=new x,b=this.resolveCanonicalEntity(m,s,p);y.namespace=b.namespace,y.name=b.name,y.statement=[];let h=await this.parseStatements(g,s,r,i,e);y.statement.push(...h),t.push(y)}}let o=new Map,c=new Map,f=[];for(let s of t)if(s instanceof x){let p=`${s.namespace}/${s.name}`,m=o.get(p);if(m){let g=c.get(p);for(let y of s.statement){let b=O(y);g.has(b)||(g.add(b),m.statement.push(y))}}else{let g=new Set,y=[];for(let b of s.statement){let h=O(b);g.has(h)||(g.add(h),y.push(b))}s.statement=y,c.set(p,g),o.set(p,s),f.push(s)}}else f.push(s);let u=new Set;for(let s of f)if(s instanceof x){let p=s.namespace||"",m=p.indexOf("/"),g=m>=0?p.slice(0,m):"",y=m>=0?p.slice(m+1):"",b=y.indexOf("@"),h=b>=0?y.slice(0,b):y;u.add(`${g}/${h}/${s.name}`)}let d=s=>u.has(`${s.publisher}/${s.package_}/${s.name}`),l=new Map;for(let s of["core-rdf","core-owl","core-kanonak"]){let p=await e.getDocumentsByNamespaceAsync("kanonak.org",s);l.set(s,L(p).chosen?.metadata.namespace_?.version??void 0)}for(let s of f)s instanceof x&&this.canonicalizeStatementBuiltins(s.statement,d,l);return f}canonicalizeStatementBuiltins(e,t,a){for(let r of e){let i=r.predicate?.subject;if(P(i,t,a),r instanceof K)r.object instanceof k&&P(r.object.subject,t,a);else if(r instanceof w)r.object&&this.canonicalizeStatementBuiltins(r.object.statement,t,a);else if(r instanceof j)for(let o of r.object??[])o instanceof k?P(o.subject,t,a):o instanceof S&&this.canonicalizeStatementBuiltins(o.statement,t,a)}}resolveCanonicalEntity(e,t,a){if(!e.includes(".")||!t.metadata?.imports)return{namespace:a,name:e};let r=e.indexOf("."),i=e.substring(0,r),o=e.substring(r+1);for(let[c,f]of Object.entries(t.metadata.imports))for(let u of f)if((u.alias??u.packageName)===i){let l=u.version;return{namespace:`${c}/${u.packageName}@${l.major}.${l.minor}.${l.patch}`,name:o}}return{namespace:a,name:e}}async parseStatements(e,t,a,r,i){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[c,f]of Object.entries(e))try{let u=await this.getPropertyMetadata(c,t,a,i,r);if(!u)continue;let d=await this.parsePropertyValue(c,f,u,t,a,r,i);d&&o.push(d)}catch(u){throw new Error(`Failed to parse property '${c}': ${u.message}`,{cause:u})}return o}async getPropertyMetadata(e,t,a,r,i){let o=await a.resolveEntityAsync(e,t);if(!o)return;let c=o.entity,f=c.type?.toString()??"",u=f.includes(".")?f.substring(f.lastIndexOf(".")+1):f;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(u))return;let l=i.getPropertyTypeClassification(f),s=c.range?.toString(),p;if(l==="ObjectProperty")p="ObjectProperty";else if(l==="DatatypeProperty")p="DatatypeProperty";else{let y=s&&s.includes(".")?s.substring(s.lastIndexOf(".")+1):s??"";(s?i.isKnownXsdDatatypeName(s):!1)||y==="Literal"?p="DatatypeProperty":p="ObjectProperty"}let m;if(s){let y=t;if(o.isImported&&o.definedInNamespace){if(typeof r.getDocumentAsync!="function")throw new Error(`Cannot resolve the range of imported property '${e}': the parse repository cannot fetch defining document '${o.definedInNamespace}'. Thread the real repository through to embedded-object parsing \u2014 no stub, no fallback.`);let h=await r.getDocumentAsync(o.definedInNamespace);if(!h)throw new Error(`Cannot resolve the range of imported property '${e}': defining document '${o.definedInNamespace}' was not found in the repository.`);y=h}m=(await a.resolveEntityAsync(s,y))?.uri}return{propertyUri:o.uri.toString(),propertyType:p,range:s,rangeUri:m,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,a,r,i,o,c){let f=a.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(f,t,a,r,i,o,c);if(a.propertyType==="DatatypeProperty")return this.parseDatatypeValue(f,t,a,r,i,o);if(a.propertyType==="ObjectProperty")return this.parseObjectValue(f,t,a,r,i,o,c)}}async parseDatatypeValue(e,t,a,r,i,o){let c;if(typeof t=="string"){if(o.isSubstitutableDatatype(a.rangeUri))return await this.parseSubstitutableValue(e,t,r,i);c=t}else if(typeof t=="number"||typeof t=="boolean")c=String(t);else return;return this.typedScalarStatement(e,c,a)}typedScalarStatement(e,t,a){let r=k.parse(e),i=a.rangeUri?M(a.rangeUri):void 0;if(i==="boolean"){let c=new E;return c.predicate=r,c.object=t==="true"||t==="1",c.carrier=i,c.lexical=t,c}if(i==="integer"||i==="decimal"||i==="double"||i==="float"){let c=new T;return c.predicate=r,c.object=Number(t),c.carrier=i,c.lexical=t,c}let o=$.parse(e,t);return i&&(o.carrier=i,o.lexical=t),o}typedListLiteral(e,t){let a=new I,r=t.rangeUri?M(t.rangeUri):void 0;return r==="boolean"?a.value=e==="true"||e==="1":r==="integer"||r==="decimal"||r==="double"||r==="float"?a.value=Number(e):a.value=e,r&&(a.carrier=r,a.lexical=e),a}async parseSubstitutableValue(e,t,a,r){let i=new R;i.predicate=k.parse(e),i.object=t;for(let o of A(t)){let c=await r.resolveEntityAsync(o.reference,a),f;c&&(f=new k,f.subject=c.uri);let u={reference:o.reference,startOffset:o.startOffset,endOffset:o.endOffset};o.displayText!==void 0&&(u.displayText=o.displayText),f!==void 0&&(u.target=f),i.links.push(u)}return i}async parseObjectValue(e,t,a,r,i,o,c){if(typeof t=="string"){let f=await this.resolveReference(t,r,i);if(!f)return;let u=new K;return u.predicate=k.parse(e),u.object=f,u}if(typeof t=="object"&&!Array.isArray(t)){let f=new S;if(f.statement=await this.parseStatements(t,r,i,o,c),f.statement.length>0){let l=new w;return l.predicate=k.parse(e),l.object=f,l}let u=[];for(let[l,s]of Object.entries(t))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let p=new S;p.name=l,p.statement=await this.parseStatements(s,r,i,o,c),u.push(p)}else if(typeof s=="string"){let p=await this.resolveReference(s,r,i);p&&u.push(p)}if(u.length>0){let l=new j;return l.predicate=k.parse(e),l.object=u,l}let d=new w;return d.predicate=k.parse(e),d.object=f,d}}async parseListValue(e,t,a,r,i,o,c){let f=[],u=a.propertyType==="DatatypeProperty",d=a.rangeUri?.publisher==="kanonak.org"&&a.rangeUri?.package_==="core-rdf"&&a.rangeUri?.name==="List"||!a.rangeUri&&(a.range?.includes(".")?a.range.substring(a.range.lastIndexOf(".")+1):a.range)==="List";for(let s of t){let p=typeof s=="string"||typeof s=="number"||typeof s=="boolean";if(u&&p){let m=typeof s=="string"?s:String(s);f.push(this.typedListLiteral(m,a));continue}if(d&&p){if(typeof s=="string"){let m=await i.resolveEntityAsync(s,r);if(m){let g=new k;g.subject=m.uri,f.push(g)}else{let g=new I;g.value=s,f.push(g)}}else{let m=new I;m.value=s,f.push(m)}continue}if(typeof s=="string"){let m=await this.resolveReference(s,r,i);m&&f.push(m)}else if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let m=new S;m.statement=await this.parseStatements(s,r,i,o,c),f.push(m)}}let l=new j;return l.predicate=k.parse(e),l.object=f,l}async resolveReference(e,t,a){let r=await a.resolveEntityAsync(e,t);if(r){let o=new k;return o.subject=r.uri,o}let i=t.metadata?.namespace_;if(i){let{KanonakUri:o}=await import("./KanonakUri-4VJGV3FN.js");if(e.includes(".")){let f=e.indexOf("."),u=e.substring(0,f),d=e.substring(f+1);if(t.metadata?.imports){for(let[l,s]of Object.entries(t.metadata.imports))for(let p of s)if((p.alias??p.packageName)===u){let g=new k;return g.subject=new o(l,p.packageName,d,p.version),g}}}let c=new k;return c.subject=new o(i.publisher,i.package_,e,i.version??void 0),c}return null}async saveKanonaks(e,t){let a=new Map;for(let r of e)r instanceof x&&r.namespace&&(a.has(r.namespace)||a.set(r.namespace,[]),a.get(r.namespace).push(r));for(let[r,i]of a){let o=await this.convertKanonaksToDocument(r,i),c=`${r.split("@")[0]}.yml`;await t.saveDocumentAsync(o,c)}}async serializeToYaml(e,t){let a=e.filter(o=>o instanceof x&&o.namespace===t);if(a.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let r=await this.convertKanonaksToDocument(t,a);return new U().save(r)}async convertKanonaksToDocument(e,t){let r={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let c of Object.values(this.imports))o.push(...c);return o}},body:{}},i=new Map;for(let o of t){let c={};for(let f of o.statement){let[u,d]=this.convertStatementToProperty(f);u&&d!==null&&d!==void 0&&(c[u]=d),this.collectImportsFromStatement(f,e,i)}r.body[o.name]=c}return r}convertStatementToProperty(e){if(e instanceof $)return[e.predicate.subject.name,e.object];if(e instanceof T)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object];if(e instanceof K)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof j){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof w){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let a of e)a instanceof k?t.push(a.subject.name):a instanceof S&&t.push(this.convertEmbeddedKanonakToValue(a));return t}convertEmbeddedKanonakToValue(e){let t={};for(let a of e.statement){let[r,i]=this.convertStatementToProperty(a);r&&i!==null&&i!==void 0&&(t[r]=i)}return t}collectImportsFromStatement(e,t,a){}};function O(n){let e=n.predicate?.subject;return(e?`${e.publisher}/${e.package_}/${e.name}`:"?")+"="+Se(n)}function Se(n){return n instanceof R?"m:"+String(n.object):n instanceof $?"s:"+String(n.object):n instanceof T?"n:"+String(n.object):n instanceof E?"b:"+String(n.object):n instanceof K?"r:"+N(n.object):n instanceof w?"e:"+N(n.object):n instanceof j?"l:["+(n.object??[]).map(N).join("|")+"]":"x"}function N(n){if(!n)return"";if(n instanceof k){let e=n.subject;return"R("+(e?`${e.publisher}/${e.package_}/${e.name}`:"")+")"}return n instanceof S?"E("+(n.statement??[]).map(O).join(";")+")":n instanceof I?"L("+String(n.value)+")":"N"}export{S as a,I as b,R as c,Y as d,M as e,Re as f,Te as g,A as h,q as i};
@@ -1,2 +1,2 @@
1
- import{a as u}from"./chunk-SC5M74NM.js";import{a as y}from"./chunk-ZYAABYDS.js";import{e as v}from"./chunk-2ACBWC7K.js";var x="https://{publisher}/index.txt",P="https://{publisher}/{package}/{version}.kan.yml",k={version:1};function A(c){return{version:1,index:x.replaceAll("{publisher}",c),package:P.replaceAll("{publisher}",c),auth:"none"}}var f=class{cache=new Map;getConfig(t){let n=this.cache.get(t);return n||(n=this.fetchConfig(t),this.cache.set(t,n),n.catch(()=>{this.cache.get(t)===n&&this.cache.delete(t)})),n}async fetchConfig(t){let n=`https://${t}/.well-known/kanonak.json`,r;try{r=await fetch(n)}catch{return k}if(r.status===404)return k;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${n} (${r.status} ${r.statusText})`);let e=await r.json();if(typeof e.version!="number")throw new Error(`Invalid publisher config at ${n}: missing or invalid "version" field`);let s={version:e.version};return typeof e.index=="string"&&(s.index=e.index),typeof e.package=="string"&&(s.package=e.package),(e.auth==="none"||e.auth==="oauth"||e.auth==="bearer")&&(s.auth=e.auth),Array.isArray(e.render)&&e.render.every(i=>typeof i=="string")&&(s.render=e.render),typeof e.resolveByRedirect=="boolean"&&(s.resolveByRedirect=e.resolveByRedirect),s}resolveIndexUrl(t,n){let r=n.index??x;return w(r,{publisher:t})}resolvePackageUrl(t,n,r,e){let s=e.package??P;return w(s,{publisher:t,package:n,version:r})}};function w(c,t){let n=c;for(let[e,s]of Object.entries(t))n=n.replaceAll(`{${e}}`,s);let r=n.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${c}`);return n}import{VersionOperator as m}from"@kanonak-protocol/types/document/models/enums";var l=class c{indexCache=new Map;configResolver;fetchFn;constructor(t){this.configResolver=t?.configResolver??new f,this.fetchFn=t?.fetchFn}async resolveVersion(t,n){let r=await this.getPackageVersions(t,n.packageName);if(r.length===0)return null;let e=r.filter(s=>this.isVersionCompatible(s,n.version,n.versionOperator));return e.length===0?null:(e.sort((s,i)=>this.compareVersionStrings(i,s)),e[0])}async getHighestVersion(t,n){let r=await this.getPackageVersions(t,n);return r.length===0?null:[...r].sort((s,i)=>this.compareVersionStrings(i,s))[0]}async listLatestPackages(t){let n=await this.getIndex(t),r=[];for(let[e,s]of n){if(s.length===0)continue;let i=[...s].sort((o,a)=>this.compareVersionStrings(a,o));r.push({packageName:e,version:i[0]})}return r.sort((e,s)=>e.packageName.localeCompare(s.packageName)),r}async getPackageUrl(t,n,r){let e=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,n,r,e)}getConfig(t){return this.configResolver.getConfig(t)}async getPackageVersions(t,n){return(await this.getIndex(t)).get(n)??[]}getIndex(t){let n=this.indexCache.get(t);return n||(n=this.fetchIndex(t),this.indexCache.set(t,n),n.catch(()=>{this.indexCache.get(t)===n&&this.indexCache.delete(t)})),n}async fetchIndex(t){let n=await this.configResolver.getConfig(t),r=this.configResolver.resolveIndexUrl(t,n),e=this.fetchFn?await this.fetchFn(r,t):await fetch(r);if(!e.ok)throw new Error(`Failed to fetch publisher index: ${r} (${e.status} ${e.statusText})`);let s=await e.text();return c.parseIndex(s)}static parseIndex(t){let n=new Map;for(let r of t.split(`
1
+ import{a as u}from"./chunk-SC5M74NM.js";import{a as y}from"./chunk-NJ3AZYQD.js";import{e as v}from"./chunk-2ACBWC7K.js";var x="https://{publisher}/index.txt",P="https://{publisher}/{package}/{version}.kan.yml",k={version:1};function A(c){return{version:1,index:x.replaceAll("{publisher}",c),package:P.replaceAll("{publisher}",c),auth:"none"}}var f=class{cache=new Map;getConfig(t){let n=this.cache.get(t);return n||(n=this.fetchConfig(t),this.cache.set(t,n),n.catch(()=>{this.cache.get(t)===n&&this.cache.delete(t)})),n}async fetchConfig(t){let n=`https://${t}/.well-known/kanonak.json`,r;try{r=await fetch(n)}catch{return k}if(r.status===404)return k;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${n} (${r.status} ${r.statusText})`);let e=await r.json();if(typeof e.version!="number")throw new Error(`Invalid publisher config at ${n}: missing or invalid "version" field`);let s={version:e.version};return typeof e.index=="string"&&(s.index=e.index),typeof e.package=="string"&&(s.package=e.package),(e.auth==="none"||e.auth==="oauth"||e.auth==="bearer")&&(s.auth=e.auth),Array.isArray(e.render)&&e.render.every(i=>typeof i=="string")&&(s.render=e.render),typeof e.resolveByRedirect=="boolean"&&(s.resolveByRedirect=e.resolveByRedirect),s}resolveIndexUrl(t,n){let r=n.index??x;return w(r,{publisher:t})}resolvePackageUrl(t,n,r,e){let s=e.package??P;return w(s,{publisher:t,package:n,version:r})}};function w(c,t){let n=c;for(let[e,s]of Object.entries(t))n=n.replaceAll(`{${e}}`,s);let r=n.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${c}`);return n}import{VersionOperator as m}from"@kanonak-protocol/types/document/models/enums";var l=class c{indexCache=new Map;configResolver;fetchFn;constructor(t){this.configResolver=t?.configResolver??new f,this.fetchFn=t?.fetchFn}async resolveVersion(t,n){let r=await this.getPackageVersions(t,n.packageName);if(r.length===0)return null;let e=r.filter(s=>this.isVersionCompatible(s,n.version,n.versionOperator));return e.length===0?null:(e.sort((s,i)=>this.compareVersionStrings(i,s)),e[0])}async getHighestVersion(t,n){let r=await this.getPackageVersions(t,n);return r.length===0?null:[...r].sort((s,i)=>this.compareVersionStrings(i,s))[0]}async listLatestPackages(t){let n=await this.getIndex(t),r=[];for(let[e,s]of n){if(s.length===0)continue;let i=[...s].sort((o,a)=>this.compareVersionStrings(a,o));r.push({packageName:e,version:i[0]})}return r.sort((e,s)=>e.packageName.localeCompare(s.packageName)),r}async getPackageUrl(t,n,r){let e=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,n,r,e)}getConfig(t){return this.configResolver.getConfig(t)}async getPackageVersions(t,n){return(await this.getIndex(t)).get(n)??[]}getIndex(t){let n=this.indexCache.get(t);return n||(n=this.fetchIndex(t),this.indexCache.set(t,n),n.catch(()=>{this.indexCache.get(t)===n&&this.indexCache.delete(t)})),n}async fetchIndex(t){let n=await this.configResolver.getConfig(t),r=this.configResolver.resolveIndexUrl(t,n),e=this.fetchFn?await this.fetchFn(r,t):await fetch(r);if(!e.ok)throw new Error(`Failed to fetch publisher index: ${r} (${e.status} ${e.statusText})`);let s=await e.text();return c.parseIndex(s)}static parseIndex(t){let n=new Map;for(let r of t.split(`
2
2
  `)){let e=r.trim();if(!e||e.startsWith("#"))continue;let s=e.indexOf("/");if(s===-1)continue;let i=e.substring(0,s),o=e.substring(s+1);if(!i||!o)continue;let a=n.get(i);a?a.push(o):n.set(i,[o])}return n}isVersionCompatible(t,n,r){let e=c.parseVersion(t);if(!e)return!1;switch(r){case m.Any:return!0;case m.Exact:return e.major===n.major&&e.minor===n.minor&&e.patch===n.patch;case m.Compatible:return e.major===n.major&&e.minor===n.minor&&e.patch>=n.patch;case m.Major:return e.major!==n.major?!1:e.minor>n.minor?!0:e.minor===n.minor?e.patch>=n.patch:!1;default:return!1}}static parseVersion(t){let n=t.split(".");if(n.length<2)return null;let r=parseInt(n[0],10),e=parseInt(n[1],10),s=n.length>=3?parseInt(n[2],10):0;return isNaN(r)||isNaN(e)||isNaN(s)?null:{major:r,minor:e,patch:s}}compareVersionStrings(t,n){let r=c.parseVersion(t),e=c.parseVersion(n);return!r&&!e?0:r?e?r.major!==e.major?r.major-e.major:r.minor!==e.minor?r.minor-e.minor:r.patch-e.patch:1:-1}};import{VersionOperator as C}from"@kanonak-protocol/types/document/models/enums";var F=class{parser=new y;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new l({fetchFn:t.fetchFn}):new l}async getHighestCompatibleVersionAsync(t,n){if((await this.publisherIndex.getConfig(t)).resolveByRedirect)return this.resolveByRedirect(t,n);let e=await this.publisherIndex.resolveVersion(t,n);if(!e)return null;let s=`${t}/${n.packageName}@${e}`,i=this.documents.get(s);if(i)return i;if(this.getFromCache){let p=this.getFromCache(t,n.packageName,e);if(p){let d=this.parser.parse(p);return u(d,t,n.packageName,e),this.documents.set(s,d),this.contentCache.set(s,p),d}}let o=await this.publisherIndex.getPackageUrl(t,n.packageName,e),a=this.fetchFn?await this.fetchFn(o,t):await fetch(o);if(!a.ok)throw new Error(`Failed to fetch Kanonak package: ${o} (${a.status} ${a.statusText})`);let g=await a.text(),h=this.parser.parse(g);return u(h,t,n.packageName,e),this.onFetch&&this.onFetch(t,n.packageName,e,g),this.documents.set(s,h),this.contentCache.set(s,g),h}async resolveByRedirect(t,n){let r=n.packageName,s=n.versionOperator===C.Exact?await this.publisherIndex.getPackageUrl(t,r,v(n.version)):`https://${t}/${r}.kan.yml`,i=await this.fetchFollowing(s,t);if(!i)return null;let o=this.parser.parse(i.content),a=o.metadata.namespace_;if(!a||!a.version)throw new Error(`Producer origin returned a package with no namespace/version for ${t}/${r}`);let g=v(a.version);u(o,t,r,g);let h=`${t}/${r}@${g}`;return this.onFetch&&this.onFetch(t,r,g,i.content),this.documents.set(h,o),this.contentCache.set(h,i.content),o}async fetchFollowing(t,n,r=4){let e=t;for(let s=0;s<r;s++){let i=this.fetchFn?await this.fetchFn(e,n):await fetch(e,{redirect:"manual"});if(i.status===301||i.status===302){let o=i.headers.get("location");if(!o)throw new Error(`Redirect with no Location header from ${e}`);e=new URL(o,e).toString();continue}if(i.status===404)return null;if(!i.ok)throw new Error(`Failed to fetch Kanonak package: ${e} (${i.status} ${i.statusText})`);return{url:e,content:await i.text()}}throw new Error(`Too many redirects resolving ${t}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,n){return Array.from(this.documents.values()).filter(r=>{let e=r.metadata.namespace_;return e&&e.publisher===t&&e.package_===n})}async saveDocumentAsync(t,n){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,n){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let n=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!n)return null;let[,r,e,s]=n;return this.publisherIndex.getPackageUrl(r,e,s)}};export{A as a,f as b,l as c,F as d};
@@ -1,4 +1,4 @@
1
- import{d as _}from"./chunk-SHDHMKMJ.js";import{a as D,b as Ne,c as Ye,g as Ze,i as A}from"./chunk-FSHQVKZ5.js";import{a as Fe}from"./chunk-ZYAABYDS.js";import{a as B,d as W,e as Je,f as Qe,g as T,h as et}from"./chunk-UK2OIPAB.js";import{a as C,d as E,f as x,h as Te,i as w,j as L,k as V,l as O,m as S,n as M}from"./chunk-PBNVHBS3.js";import{a as N,b as U,c as Ge}from"./chunk-VKTFLHCW.js";import{c as I,d as H,k as qe,l as ze}from"./chunk-T3JR2SV6.js";import{a as Xe}from"./chunk-FUUTGGJS.js";import{e as P}from"./chunk-2ACBWC7K.js";var q=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var b=(n=>(n.Warning="Warning",n.Error="Error",n))(b||{});var g=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var Ue=class y{resolvedDocuments=[];currentEntityPath;withPath(e){let n=new y;return n.resolvedDocuments=this.resolvedDocuments,n.currentEntityPath=e,n}};var Se=class{constructor(e){this.underlying=e;this.repository=new Me(e)}underlying;repository;kanonaksPromise=null;importClosureCache=new Map;classDeclarationsCache=new Map;propertyNamesCache=new Map;allDocumentsPromise=null;getKanonaks(){return this.kanonaksPromise||(this.kanonaksPromise=new A().parseKanonaks(this.underlying)),this.kanonaksPromise}async getImportClosure(e){let n=this.importClosureCache.get(e);return n||(n=this.computeImportClosure(e),this.importClosureCache.set(e,n),n)}async getClassDeclarations(e){let n=this.classDeclarationsCache.get(e);return n||(n=this.computeClassDeclarations(e),this.classDeclarationsCache.set(e,n),n)}async getPropertyNames(e){let n=this.propertyNamesCache.get(e);return n||(n=this.computePropertyNames(e),this.propertyNamesCache.set(e,n),n)}getAllDocuments(){return this.allDocumentsPromise||(this.allDocumentsPromise=this.underlying.getAllDocumentsAsync()),this.allDocumentsPromise}async computeImportClosure(e){let n=new Set([e]),t=[e],o=await this.buildDocsByIdIndex();for(;t.length>0;){let a=t.shift(),r=o.get(a);if(r?.metadata.imports)for(let[i,s]of Object.entries(r.metadata.imports))for(let c of s){let p=await this.repository.getHighestCompatibleVersionAsync(i,c);if(!p)continue;let l=Le(p);!l||n.has(l)||(n.add(l),t.push(l))}}return n}async buildDocsByIdIndex(){let e=await this.getAllDocuments(),n=new Map;for(let t of e){let o=Le(t);o&&n.set(o,t)}return n}async computeClassDeclarations(e){let n=await this.findDocById(e),t=new Map;if(!n)return t;for(let[o,a]of Object.entries(n.body)){if(!tt(a))continue;let r=a,i=nt(r,"type");if(i==="Class"||i?.endsWith(".Class")){let s=dt(r);t.set(o,s)}}return t}async computePropertyNames(e){let n=await this.findDocById(e),t=new Set;if(!n)return t;for(let[o,a]of Object.entries(n.body)){if(!tt(a))continue;let i=nt(a,"type");(i==="ObjectProperty"||i?.endsWith(".ObjectProperty")||i==="DatatypeProperty"||i?.endsWith(".DatatypeProperty")||i==="AnnotationProperty"||i?.endsWith(".AnnotationProperty")||i==="Property"||i?.endsWith(".Property"))&&t.add(o)}return t}async findDocById(e){let n=await this.getAllDocuments();for(let t of n)if(Le(t)===e)return t}};function Le(y){let e=y.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${P(e.version)}`}function tt(y){return typeof y=="object"&&y!==null&&!Array.isArray(y)}function nt(y,e){if(e in y)return ot(y[e]);for(let n of Object.keys(y))if(n.endsWith(`.${e}`))return ot(y[n])}function ot(y){return Array.isArray(y)?y.length>0?String(y[0]):void 0:y==null?void 0:String(y)}function dt(y){let e=y.subClassOf;if(e===void 0){for(let n of Object.keys(y))if(n.endsWith(".subClassOf")){e=y[n];break}}return N(e)}var Me=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,n){let t=`${e}/${n}`,o=this.byNamespaceCache.get(t);return o||(o=this.inner.getDocumentsByNamespaceAsync(e,n),this.byNamespaceCache.set(t,o),o)}getHighestCompatibleVersionAsync(e,n){let t=n.version,o=t?`${t.major}.${t.minor}.${t.patch}`:"",a=`${e}/${n.packageName}@${n.versionOperator}:${o}`,r=this.highestVersionCache.get(a);return r||(r=this.inner.getHighestCompatibleVersionAsync(e,n),this.highestVersionCache.set(a,r),r)}saveDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}deleteDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}clearNamespaceAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var z=class y{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let n=[];for(let[t,o]of Object.entries(e.body))o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(t,o,n);return n}validateEntity(e,n,t){for(let[o,a]of Object.entries(n)){let r=a?.toString()??"";if(r&&y.NAMESPACE_PREFIX_PATTERN.test(r)){let i=this.getSuggestionForPrefixedValue(r),s=e.split(".")[0],c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=s,c.propertyName=e,c.actualValue=o,c.expectedValue=i,c.message=`Invalid namespace prefix '${r}'. Use '${i}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",t.push(c)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validateEntity(`${e}.${o}`,a,t)}}getSuggestionForPrefixedValue(e){let n=e.toLowerCase();if(n==="rdfs:class"||n==="owl:class")return"Class";if(n==="rdfs:property"||n==="rdf:property")return"DatatypeProperty or ObjectProperty";if(n.startsWith("xsd:"))return e.substring(4);let t=e.indexOf(":");return t>=0?e.substring(t+1):e}};var Y=class y{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let n=[],t=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[o,a]of Object.entries(e.body)){let r=y.VALID_AUGMENTATION_PATTERN.test(o);if(!r&&!t&&y.RESERVED_WORDS.has(o.toLowerCase())){let i=new g;i.ruleType=this.ruleName,i.severity="Error",i.entityName=o,i.message=`Entity name '${o}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",n.push(i);continue}if(!r&&!y.VALID_NAME_PATTERN.test(o)){let i;/^\d/.test(o)?i="Entity names must start with a letter, not a number.":o.includes(" ")?i="Entity names cannot contain spaces. Use camelCase or underscores instead.":i="Entity names must start with a letter and contain only letters, numbers, and underscores.";let s=new g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=o,s.message=`Invalid entity name '${o}'. ${i}`,s.suggestion=i,n.push(s)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validatePropertyNames(o,a,n)}return n}validatePropertyNames(e,n,t){for(let o of Object.keys(n))if(!y.VALID_PROPERTIES.has(o)&&!y.VALID_PROPERTY_NAME_PATTERN.test(o)){let a=new g;a.ruleType=this.ruleName,a.severity="Warning",a.entityName=e,a.propertyName=o,a.message=`Property name '${o}' in entity '${e}' doesn't follow naming conventions.`,a.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",t.push(a)}}};var G=class y{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let n=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return n;let t=this.isPropertyDefinedAsClass(e);for(let[o,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let r=a,i=r.type;if(i){let s=[];if(Array.isArray(i))for(let c of i){let p=c?.toString();p&&p==="Property"&&!t&&s.push(p)}else{let c=i?.toString();c&&c==="Property"&&!t&&s.push(c)}for(let c of s){let p=this.getPropertyValue(r,"range"),l=this.determinePropertyType(p),m=new g;m.ruleType=this.ruleName,m.severity="Error",m.entityName=o,m.propertyName="type",m.actualValue=c,m.expectedValue=l,m.message=`Invalid property type '${c}'. Use '${l}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",n.push(m)}}}return n}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":y.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,n){let t=e[n];return t?t.toString():null}isPropertyDefinedAsClass(e){let n=e.body.Property;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=n.type;if(o){let a=o.toString();return a==="Class"||a.endsWith(".Class")}}return!1}};var Z=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let n=[];for(let[t,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o)||t.includes("."))continue;let a=o,r="type"in a,i=a.type?.toString().trim();if(!r||!i){let s=new g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=t,s.propertyName="type",s.message=`Subject Kanonak '${t}' must have a 'type' property.`,s.suggestion=`Add a type statement like:
1
+ import{d as _}from"./chunk-SHDHMKMJ.js";import{a as D,b as Ne,c as Ye,g as Ze,i as A}from"./chunk-DSHPAWJQ.js";import{a as Fe}from"./chunk-NJ3AZYQD.js";import{a as B,d as W,e as Je,f as Qe,g as T,h as et}from"./chunk-UK2OIPAB.js";import{a as C,d as E,f as x,h as Te,i as w,j as L,k as V,l as O,m as S,n as M}from"./chunk-PBNVHBS3.js";import{a as N,b as U,c as Ge}from"./chunk-VKTFLHCW.js";import{c as I,d as H,k as qe,l as ze}from"./chunk-T3JR2SV6.js";import{a as Xe}from"./chunk-FUUTGGJS.js";import{e as P}from"./chunk-2ACBWC7K.js";var q=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var b=(n=>(n.Warning="Warning",n.Error="Error",n))(b||{});var g=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var Ue=class y{resolvedDocuments=[];currentEntityPath;withPath(e){let n=new y;return n.resolvedDocuments=this.resolvedDocuments,n.currentEntityPath=e,n}};var Se=class{constructor(e){this.underlying=e;this.repository=new Me(e)}underlying;repository;kanonaksPromise=null;importClosureCache=new Map;classDeclarationsCache=new Map;propertyNamesCache=new Map;allDocumentsPromise=null;getKanonaks(){return this.kanonaksPromise||(this.kanonaksPromise=new A().parseKanonaks(this.underlying)),this.kanonaksPromise}async getImportClosure(e){let n=this.importClosureCache.get(e);return n||(n=this.computeImportClosure(e),this.importClosureCache.set(e,n),n)}async getClassDeclarations(e){let n=this.classDeclarationsCache.get(e);return n||(n=this.computeClassDeclarations(e),this.classDeclarationsCache.set(e,n),n)}async getPropertyNames(e){let n=this.propertyNamesCache.get(e);return n||(n=this.computePropertyNames(e),this.propertyNamesCache.set(e,n),n)}getAllDocuments(){return this.allDocumentsPromise||(this.allDocumentsPromise=this.underlying.getAllDocumentsAsync()),this.allDocumentsPromise}async computeImportClosure(e){let n=new Set([e]),t=[e],o=await this.buildDocsByIdIndex();for(;t.length>0;){let a=t.shift(),r=o.get(a);if(r?.metadata.imports)for(let[i,s]of Object.entries(r.metadata.imports))for(let c of s){let p=await this.repository.getHighestCompatibleVersionAsync(i,c);if(!p)continue;let l=Le(p);!l||n.has(l)||(n.add(l),t.push(l))}}return n}async buildDocsByIdIndex(){let e=await this.getAllDocuments(),n=new Map;for(let t of e){let o=Le(t);o&&n.set(o,t)}return n}async computeClassDeclarations(e){let n=await this.findDocById(e),t=new Map;if(!n)return t;for(let[o,a]of Object.entries(n.body)){if(!tt(a))continue;let r=a,i=nt(r,"type");if(i==="Class"||i?.endsWith(".Class")){let s=dt(r);t.set(o,s)}}return t}async computePropertyNames(e){let n=await this.findDocById(e),t=new Set;if(!n)return t;for(let[o,a]of Object.entries(n.body)){if(!tt(a))continue;let i=nt(a,"type");(i==="ObjectProperty"||i?.endsWith(".ObjectProperty")||i==="DatatypeProperty"||i?.endsWith(".DatatypeProperty")||i==="AnnotationProperty"||i?.endsWith(".AnnotationProperty")||i==="Property"||i?.endsWith(".Property"))&&t.add(o)}return t}async findDocById(e){let n=await this.getAllDocuments();for(let t of n)if(Le(t)===e)return t}};function Le(y){let e=y.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${P(e.version)}`}function tt(y){return typeof y=="object"&&y!==null&&!Array.isArray(y)}function nt(y,e){if(e in y)return ot(y[e]);for(let n of Object.keys(y))if(n.endsWith(`.${e}`))return ot(y[n])}function ot(y){return Array.isArray(y)?y.length>0?String(y[0]):void 0:y==null?void 0:String(y)}function dt(y){let e=y.subClassOf;if(e===void 0){for(let n of Object.keys(y))if(n.endsWith(".subClassOf")){e=y[n];break}}return N(e)}var Me=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,n){let t=`${e}/${n}`,o=this.byNamespaceCache.get(t);return o||(o=this.inner.getDocumentsByNamespaceAsync(e,n),this.byNamespaceCache.set(t,o),o)}getHighestCompatibleVersionAsync(e,n){let t=n.version,o=t?`${t.major}.${t.minor}.${t.patch}`:"",a=`${e}/${n.packageName}@${n.versionOperator}:${o}`,r=this.highestVersionCache.get(a);return r||(r=this.inner.getHighestCompatibleVersionAsync(e,n),this.highestVersionCache.set(a,r),r)}saveDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}deleteDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}clearNamespaceAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var z=class y{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let n=[];for(let[t,o]of Object.entries(e.body))o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(t,o,n);return n}validateEntity(e,n,t){for(let[o,a]of Object.entries(n)){let r=a?.toString()??"";if(r&&y.NAMESPACE_PREFIX_PATTERN.test(r)){let i=this.getSuggestionForPrefixedValue(r),s=e.split(".")[0],c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=s,c.propertyName=e,c.actualValue=o,c.expectedValue=i,c.message=`Invalid namespace prefix '${r}'. Use '${i}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",t.push(c)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validateEntity(`${e}.${o}`,a,t)}}getSuggestionForPrefixedValue(e){let n=e.toLowerCase();if(n==="rdfs:class"||n==="owl:class")return"Class";if(n==="rdfs:property"||n==="rdf:property")return"DatatypeProperty or ObjectProperty";if(n.startsWith("xsd:"))return e.substring(4);let t=e.indexOf(":");return t>=0?e.substring(t+1):e}};var Y=class y{static RESERVED_WORDS=new Set(["imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let n=[],t=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[o,a]of Object.entries(e.body)){let r=y.VALID_AUGMENTATION_PATTERN.test(o);if(!r&&!t&&y.RESERVED_WORDS.has(o.toLowerCase())){let i=new g;i.ruleType=this.ruleName,i.severity="Error",i.entityName=o,i.message=`Entity name '${o}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",n.push(i);continue}if(!r&&!y.VALID_NAME_PATTERN.test(o)){let i;/^\d/.test(o)?i="Entity names must start with a letter, not a number.":o.includes(" ")?i="Entity names cannot contain spaces. Use camelCase or underscores instead.":i="Entity names must start with a letter and contain only letters, numbers, and underscores.";let s=new g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=o,s.message=`Invalid entity name '${o}'. ${i}`,s.suggestion=i,n.push(s)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validatePropertyNames(o,a,n)}return n}validatePropertyNames(e,n,t){for(let o of Object.keys(n))if(!y.VALID_PROPERTIES.has(o)&&!y.VALID_PROPERTY_NAME_PATTERN.test(o)){let a=new g;a.ruleType=this.ruleName,a.severity="Warning",a.entityName=e,a.propertyName=o,a.message=`Property name '${o}' in entity '${e}' doesn't follow naming conventions.`,a.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",t.push(a)}}};var G=class y{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let n=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return n;let t=this.isPropertyDefinedAsClass(e);for(let[o,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let r=a,i=r.type;if(i){let s=[];if(Array.isArray(i))for(let c of i){let p=c?.toString();p&&p==="Property"&&!t&&s.push(p)}else{let c=i?.toString();c&&c==="Property"&&!t&&s.push(c)}for(let c of s){let p=this.getPropertyValue(r,"range"),l=this.determinePropertyType(p),m=new g;m.ruleType=this.ruleName,m.severity="Error",m.entityName=o,m.propertyName="type",m.actualValue=c,m.expectedValue=l,m.message=`Invalid property type '${c}'. Use '${l}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",n.push(m)}}}return n}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":y.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,n){let t=e[n];return t?t.toString():null}isPropertyDefinedAsClass(e){let n=e.body.Property;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=n.type;if(o){let a=o.toString();return a==="Class"||a.endsWith(".Class")}}return!1}};var Z=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let n=[];for(let[t,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o)||t.includes("."))continue;let a=o,r="type"in a,i=a.type?.toString().trim();if(!r||!i){let s=new g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=t,s.propertyName="type",s.message=`Subject Kanonak '${t}' must have a 'type' property.`,s.suggestion=`Add a type statement like:
2
2
  type: Scene
3
3
 
4
4
  Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,s.expectedValue="A valid class name (Scene, Character, Story, etc.)",n.push(s)}}return n}};var gt=new Set(["EphemeralPackage"]),J=class{get ruleName(){return"PackageHeader"}validate(e){let n=e.metadata;if(!n.type_)return[];let t=[],o=this.packageKey(e,n.type_);return n.namespace_?(!gt.has(n.type_)&&!n.namespace_.version&&t.push(this.error(o,"version",`Package resource '${o}' requires a 'version' property \u2014 packages are addressed by name@version.`,`Add a version, e.g.:
@@ -1,2 +1,2 @@
1
- import{J as W,K as X}from"./chunk-P3MJIJSK.js";import{b as B,c as V,i as w}from"./chunk-FSHQVKZ5.js";import{a as b,d as K,e as q,f as z}from"./chunk-UK2OIPAB.js";import{a as D,f as E,h as F,j as N,k as Y,m as v}from"./chunk-PBNVHBS3.js";import{c as G,d as x}from"./chunk-T3JR2SV6.js";import{a as L}from"./chunk-FUUTGGJS.js";import{d as U}from"./chunk-2ACBWC7K.js";var Q=(t=>(t.Class="Class",t.DatatypeProperty="DatatypeProperty",t.ObjectProperty="ObjectProperty",t.AnnotationProperty="AnnotationProperty",t.Instance="Instance",t.Datatype="Datatype",t.Unknown="Unknown",t))(Q||{}),Z=(p=>(p.InstanceOf="instanceOf",p.SubClassOf="subClassOf",p.Domain="domain",p.Range="range",p.ObjectRelationship="objectRelationship",p.SubPropertyOf="subPropertyOf",p.PropertyValue="propertyValue",p.EmbeddedLink="embeddedLink",p))(Z||{}),I=class{static async buildFromRepository(e){let a=await new w().parseKanonaks(e),o=await e.getAllDocumentsAsync(),s=[],i=[],t=new Set,p=new Set,g=new Map;for(let u of a){let l=u;l.name&&(b.isClassType(l)&&t.add(l.name),(b.isObjectPropertyType(l)||b.isGenericPropertyType(l))&&p.add(l.name))}for(let u of o)for(let[l,f]of Object.entries(u.body))p.has(l)&&f?.range&&typeof f.range=="string"&&g.set(l,f.range);let y=new Map;for(let u of a){let l=u;l.name&&y.set(l.name,l)}for(let u of o){let l=u.metadata.namespace_,f=l?`${l.publisher}/${l.package_}`:"",c=l?.version?`${l.version.major}.${l.version.minor}.${l.version.patch}`:"",d=H(u);for(let[k,m]of Object.entries(u.body)){if(!m||typeof m!="object")continue;let P=y.get(k),h="Unknown";if(P){let T=P;b.isClassType(T)?h="Class":b.isObjectPropertyType(T)?h="ObjectProperty":b.isDatatypePropertyType(T)?h="DatatypeProperty":b.isAnnotationPropertyType(T)?h="AnnotationProperty":b.isDatatypeType(T)?h="Datatype":b.isGenericPropertyType(T)?h="ObjectProperty":b.isInstanceOfKnownClass(T,t)&&(h="Instance")}let j=f&&c?`${f}/${k}@${c}`:k,A={};for(let[T,$]of Object.entries(m))T!=="type"&&(typeof $!="object"||$===null)&&(A[T]=$);s.push({id:j,label:m.label??k,type:h,namespace:f,properties:A}),J(j,m,h,t,p,i,f,c,d),_(j,m,p,g,s,i,f,c,d),ue(j,P,i)}}return{nodes:s,edges:i}}static buildFromDocument(e){let r=[],a=[],o=e.metadata.namespace_,s=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",i=o?`${o.publisher}/${o.package_}`:"",t=new Set,p=new Set,g=new Map,y=H(e);for(let[f,c]of Object.entries(e.body)){let d=c?.type;d&&(pe(d,y)&&t.add(f),ce(d,y)&&(p.add(f),c.range&&typeof c.range=="string"&&g.set(f,c.range)))}for(let[f,c]of Object.entries(e.body)){if(!c||typeof c!="object")continue;let d=c.type,k=le(d,f,t,y),m=i&&s?`${i}/${f}@${s}`:f,P={};for(let[h,j]of Object.entries(c))h!=="type"&&(typeof j!="object"||j===null)&&(P[h]=j);r.push({id:m,label:c.label??f,type:k,namespace:i,properties:P}),J(m,c,k,t,p,a,i,s,y),_(m,c,p,g,r,a,i,s,y)}let u=new Set(r.map(f=>f.id)),l=a.filter(f=>u.has(f.source)&&u.has(f.target));return{nodes:r,edges:l}}};function H(n,e){let r=new Map;if(n.metadata?.imports)for(let[a,o]of Object.entries(n.metadata.imports))for(let s of o){let i=s.alias??s.packageName,t=s.version,p=`${t.major}.${t.minor}.${t.patch}`;r.set(i,{publisher:a,package_:s.packageName,version:p})}return r}var ee={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},ie=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function M(n,e){if(n.includes(".")){let r=n.indexOf("."),a=n.substring(0,r),o=n.substring(r+1),s=e.get(a);if(s)return`${s.publisher}/${s.package_}/${o}`}return null}function pe(n,e){let r=M(n,e);return r?ee[r]==="Class":!1}function ce(n,e){let r=M(n,e);return r?ie.has(r):!1}function le(n,e,r,a){if(!n||n==="Package")return"Unknown";let o=M(n,a);if(o){let i=ee[o];if(i)return i;let t=o.split("/").pop()?.split("@")[0]??"";return r.has(t)?"Instance":"Unknown"}let s=n.split(".").pop()??n;return r.has(s)?"Instance":"Unknown"}var ne=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function J(n,e,r,a,o,s,i,t,p){let g=e.type,y=e.subClassOf;if(y){let c=Array.isArray(y)?y:[y];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let c=Array.isArray(u)?u:[u];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subPropertyOf",label:"subPropertyOf"})}if(r==="Instance"&&g){let c=g.split(".").pop()??g;s.push({source:n,target:O(c,i,t,p),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[c,d]of Object.entries(e)){if(ne.has(c)||!o.has(c))continue;let k=Array.isArray(d)?d:[d];for(let m of k)typeof m=="string"&&fe(m)&&s.push({source:n,target:O(m,i,t,p),type:"propertyValue",label:c,propertyId:O(c,i,t,p)})}let l=r==="ObjectProperty"||r==="DatatypeProperty",f=e.domain&&e.range;if((l||f)&&e.domain&&e.range){let c=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;c&&d&&s.push({source:O(c,i,t,p),target:O(d,i,t,p),type:"objectRelationship",label:e.label??n.split("/").pop()??"",propertyId:n})}}function _(n,e,r,a,o,s,i,t,p){for(let[g,y]of Object.entries(e)){if(ne.has(g)||typeof y!="object"||y===null||Array.isArray(y))continue;let u=y,l=`${n}/${g}`,f=a.get(g),c=f?f.split(".").pop()??f:"Unknown",d={};for(let[m,P]of Object.entries(u))(typeof P!="object"||P===null)&&(d[m]=P);o.push({id:l,label:`${c} (embedded)`,type:"Instance",namespace:i,properties:d});let k=i&&t?`${i}/${g}@${t}`:g;s.push({source:n,target:l,type:"propertyValue",label:g,propertyId:r.has(g)?k:void 0}),f&&s.push({source:l,target:O(c,i,t,p),type:"instanceOf",label:"type (inferred)"}),_(l,u,r,a,o,s,i,t,p)}}function ue(n,e,r){let a=e?.statement;if(Array.isArray(a))for(let o of a){if(!(o instanceof V))continue;let s=o.predicate?.subject?.name??"";for(let i of o.links){let t=i.target?.subject;if(!t)continue;let p=t.version,g=p&&typeof p.major=="number"?`@${p.major}.${p.minor}.${p.patch}`:"";r.push({source:n,target:`${t.publisher}/${t.package_}/${t.name}${g}`,type:"embeddedLink",label:s})}}}function fe(n){return!(!n||n.includes(" ")||n.includes(`
1
+ import{J as W,K as X}from"./chunk-IZRPJCQW.js";import{b as B,c as V,i as w}from"./chunk-DSHPAWJQ.js";import{a as b,d as K,e as q,f as z}from"./chunk-UK2OIPAB.js";import{a as D,f as E,h as F,j as N,k as Y,m as v}from"./chunk-PBNVHBS3.js";import{c as G,d as x}from"./chunk-T3JR2SV6.js";import{a as L}from"./chunk-FUUTGGJS.js";import{d as U}from"./chunk-2ACBWC7K.js";var Q=(t=>(t.Class="Class",t.DatatypeProperty="DatatypeProperty",t.ObjectProperty="ObjectProperty",t.AnnotationProperty="AnnotationProperty",t.Instance="Instance",t.Datatype="Datatype",t.Unknown="Unknown",t))(Q||{}),Z=(p=>(p.InstanceOf="instanceOf",p.SubClassOf="subClassOf",p.Domain="domain",p.Range="range",p.ObjectRelationship="objectRelationship",p.SubPropertyOf="subPropertyOf",p.PropertyValue="propertyValue",p.EmbeddedLink="embeddedLink",p))(Z||{}),I=class{static async buildFromRepository(e){let a=await new w().parseKanonaks(e),o=await e.getAllDocumentsAsync(),s=[],i=[],t=new Set,p=new Set,g=new Map;for(let u of a){let l=u;l.name&&(b.isClassType(l)&&t.add(l.name),(b.isObjectPropertyType(l)||b.isGenericPropertyType(l))&&p.add(l.name))}for(let u of o)for(let[l,f]of Object.entries(u.body))p.has(l)&&f?.range&&typeof f.range=="string"&&g.set(l,f.range);let y=new Map;for(let u of a){let l=u;l.name&&y.set(l.name,l)}for(let u of o){let l=u.metadata.namespace_,f=l?`${l.publisher}/${l.package_}`:"",c=l?.version?`${l.version.major}.${l.version.minor}.${l.version.patch}`:"",d=H(u);for(let[k,m]of Object.entries(u.body)){if(!m||typeof m!="object")continue;let P=y.get(k),h="Unknown";if(P){let T=P;b.isClassType(T)?h="Class":b.isObjectPropertyType(T)?h="ObjectProperty":b.isDatatypePropertyType(T)?h="DatatypeProperty":b.isAnnotationPropertyType(T)?h="AnnotationProperty":b.isDatatypeType(T)?h="Datatype":b.isGenericPropertyType(T)?h="ObjectProperty":b.isInstanceOfKnownClass(T,t)&&(h="Instance")}let j=f&&c?`${f}/${k}@${c}`:k,A={};for(let[T,$]of Object.entries(m))T!=="type"&&(typeof $!="object"||$===null)&&(A[T]=$);s.push({id:j,label:m.label??k,type:h,namespace:f,properties:A}),J(j,m,h,t,p,i,f,c,d),_(j,m,p,g,s,i,f,c,d),ue(j,P,i)}}return{nodes:s,edges:i}}static buildFromDocument(e){let r=[],a=[],o=e.metadata.namespace_,s=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",i=o?`${o.publisher}/${o.package_}`:"",t=new Set,p=new Set,g=new Map,y=H(e);for(let[f,c]of Object.entries(e.body)){let d=c?.type;d&&(pe(d,y)&&t.add(f),ce(d,y)&&(p.add(f),c.range&&typeof c.range=="string"&&g.set(f,c.range)))}for(let[f,c]of Object.entries(e.body)){if(!c||typeof c!="object")continue;let d=c.type,k=le(d,f,t,y),m=i&&s?`${i}/${f}@${s}`:f,P={};for(let[h,j]of Object.entries(c))h!=="type"&&(typeof j!="object"||j===null)&&(P[h]=j);r.push({id:m,label:c.label??f,type:k,namespace:i,properties:P}),J(m,c,k,t,p,a,i,s,y),_(m,c,p,g,r,a,i,s,y)}let u=new Set(r.map(f=>f.id)),l=a.filter(f=>u.has(f.source)&&u.has(f.target));return{nodes:r,edges:l}}};function H(n,e){let r=new Map;if(n.metadata?.imports)for(let[a,o]of Object.entries(n.metadata.imports))for(let s of o){let i=s.alias??s.packageName,t=s.version,p=`${t.major}.${t.minor}.${t.patch}`;r.set(i,{publisher:a,package_:s.packageName,version:p})}return r}var ee={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},ie=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function M(n,e){if(n.includes(".")){let r=n.indexOf("."),a=n.substring(0,r),o=n.substring(r+1),s=e.get(a);if(s)return`${s.publisher}/${s.package_}/${o}`}return null}function pe(n,e){let r=M(n,e);return r?ee[r]==="Class":!1}function ce(n,e){let r=M(n,e);return r?ie.has(r):!1}function le(n,e,r,a){if(!n||n==="Package")return"Unknown";let o=M(n,a);if(o){let i=ee[o];if(i)return i;let t=o.split("/").pop()?.split("@")[0]??"";return r.has(t)?"Instance":"Unknown"}let s=n.split(".").pop()??n;return r.has(s)?"Instance":"Unknown"}var ne=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function J(n,e,r,a,o,s,i,t,p){let g=e.type,y=e.subClassOf;if(y){let c=Array.isArray(y)?y:[y];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let c=Array.isArray(u)?u:[u];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subPropertyOf",label:"subPropertyOf"})}if(r==="Instance"&&g){let c=g.split(".").pop()??g;s.push({source:n,target:O(c,i,t,p),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[c,d]of Object.entries(e)){if(ne.has(c)||!o.has(c))continue;let k=Array.isArray(d)?d:[d];for(let m of k)typeof m=="string"&&fe(m)&&s.push({source:n,target:O(m,i,t,p),type:"propertyValue",label:c,propertyId:O(c,i,t,p)})}let l=r==="ObjectProperty"||r==="DatatypeProperty",f=e.domain&&e.range;if((l||f)&&e.domain&&e.range){let c=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;c&&d&&s.push({source:O(c,i,t,p),target:O(d,i,t,p),type:"objectRelationship",label:e.label??n.split("/").pop()??"",propertyId:n})}}function _(n,e,r,a,o,s,i,t,p){for(let[g,y]of Object.entries(e)){if(ne.has(g)||typeof y!="object"||y===null||Array.isArray(y))continue;let u=y,l=`${n}/${g}`,f=a.get(g),c=f?f.split(".").pop()??f:"Unknown",d={};for(let[m,P]of Object.entries(u))(typeof P!="object"||P===null)&&(d[m]=P);o.push({id:l,label:`${c} (embedded)`,type:"Instance",namespace:i,properties:d});let k=i&&t?`${i}/${g}@${t}`:g;s.push({source:n,target:l,type:"propertyValue",label:g,propertyId:r.has(g)?k:void 0}),f&&s.push({source:l,target:O(c,i,t,p),type:"instanceOf",label:"type (inferred)"}),_(l,u,r,a,o,s,i,t,p)}}function ue(n,e,r){let a=e?.statement;if(Array.isArray(a))for(let o of a){if(!(o instanceof V))continue;let s=o.predicate?.subject?.name??"";for(let i of o.links){let t=i.target?.subject;if(!t)continue;let p=t.version,g=p&&typeof p.major=="number"?`@${p.major}.${p.minor}.${p.patch}`:"";r.push({source:n,target:`${t.publisher}/${t.package_}/${t.name}${g}`,type:"embeddedLink",label:s})}}}function fe(n){return!(!n||n.includes(" ")||n.includes(`
2
2
  `)||n.startsWith("http://")||n.startsWith("https://")||/^\d{4}-\d{2}/.test(n)||/^\d+(\.\d+)?$/.test(n))}function O(n,e,r,a){if(n.includes("@")&&n.includes("/"))return n;if(n.includes(".")){let o=n.indexOf("."),s=n.substring(0,o),i=n.substring(o+1);if(a){let t=a.get(s);if(t)return`${t.publisher}/${t.package_}/${i}@${t.version}`}return e&&r?`${e}/${i}@${r}`:i}return e&&r?`${e}/${n}@${r}`:n}function de(n){if(!n.expiresAt)return!1;let e=new Date(n.expiresAt),r=300*1e3;return e.getTime()<=Date.now()+r}function Re(n){return!!n.accessToken&&!de(n)}function Se(n){let e=n.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}var C="kanonak.org",S="core-rdf",re="core-xsd",te={publisher:C,package_:S,name:"subClassOf"},oe={publisher:C,package_:S,name:"label"},ye={publisher:C,package_:S,name:"comment"},se={publisher:C,package_:"core-owl",name:"oneOf"},ae=n=>n;function ge(n){let e=Y(n,te);if(e)return[e];let r=[];for(let a of v(n,te))a instanceof x&&r.push(a.subject);return r}function me(n,e,r){if(e.publisher===C&&e.package_===S&&e.name==="Literal")return{kind:"datatype",uri:e};let o=E(n,e);if(o){let s=ae(o);if(b.isDatatypeType(s))return{kind:"datatype",uri:e};if(b.isClassType(s))return{kind:"class",uri:K(o)??e,localName:o.name}}return e.publisher===C&&e.package_===re?{kind:"datatype",uri:e}:r==="datatype"?{kind:"datatype",uri:e}:{kind:"class",uri:e,localName:e.name}}function be(n,e,r){if(!e.range)throw new Error(`Property ${e.uri.publisher}/${e.uri.package_}/${e.uri.name} has no rdfs.range; every property must declare a range. Validate the ontology before introspecting it.`);let a=me(n,e.range,e.kind),o=e.kind==="object"?"object":e.kind==="datatype"?"datatype":a.kind==="class"?"object":"datatype";return{uri:e.uri,localName:e.uri.name,kind:o,range:a,...e.label!==void 0?{label:e.label}:{},...e.comment!==void 0?{comment:e.comment}:{},...r??{}}}var R=n=>new L(C,re,n);function ke(n){return typeof n=="boolean"?R("boolean"):typeof n=="number"?Number.isInteger(n)?R("integer"):R("decimal"):R("string")}function he(n,e){let r=[];for(let a of v(e,se))if(a instanceof x){let o=E(n,a.subject),s=(o?K(o):void 0)??a.subject,i=o?N(o,oe):void 0;r.push({kind:"individual",uri:s,localName:s.name,...i!==void 0?{label:i}:{}})}else a instanceof B&&r.push({kind:"literal",value:a.value,datatype:ke(a.value)});return r}function Pe(n,e,r,a){let o=q(n,e),s=D(e);return z(n,e).filter(t=>r?!0:t.domains.some(p=>D(p)===s)).map(t=>be(n,t,X(a,o,t.uri)))}async function Te(n,e,r){let a=n.metadata?.namespace_;if(!a)throw new Error("buildOntologyModel: document has no namespace (publisher/package/version).");let o=r?.includeInherited??!1,s=await new w().parseKanonaks(e),i=W(s),t=[],p=[],g=new Set;for(let y of s){if(!(y instanceof G)||!b.isClassType(ae(y)))continue;let u=K(y);if(!u||u.publisher!==a.publisher||u.package_!==a.package_||u.version&&a.version&&!U(u.version,a.version))continue;let l=D(u);if(g.has(l))continue;g.add(l);let f=ge(y).map(k=>({uri:k,localName:k.name})),c=N(y,oe),d=N(y,ye);t.push({uri:u,localName:u.name,superClasses:f,properties:Pe(s,u,o,i),...c!==void 0?{label:c}:{},...d!==void 0?{comment:d}:{}}),F(y,se)&&p.push({uri:u,localName:u.name,members:he(s,y),...c!==void 0?{label:c}:{},...d!==void 0?{comment:d}:{}})}return{classes:t,enums:p}}export{Q as a,Z as b,I as c,de as d,Re as e,Se as f,Te as g};
@@ -0,0 +1 @@
1
+ import{d as v}from"./chunk-F26XWM5K.js";import{a as w}from"./chunk-4NO7MHS7.js";import{a as f}from"./chunk-NJ3AZYQD.js";import{c as A,d as R,g as b,h as F,i as S}from"./chunk-2ACBWC7K.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as x}from"url";import{VersionOperator as P}from"@kanonak-protocol/types/document/models/enums";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=c.resolve(e),this.recursive=t,this.parser=n??new f,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=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.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(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case P.Exact:return R(r,t.version);case P.Compatible:return F(r,t.version);case P.Major:return S(r,t.version);case P.Any:return A(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return A(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],h=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,h)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.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 r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,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 o=x(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return x(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 i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as g from"fs";var _=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(_||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}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 o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}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),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,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 $}from"os";import{join as B}from"path";function d(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||B($(),".kanonak","packages")}var C=class u{static createComposite(e,t,n){let o=e??d(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{VersionOperator as H}from"@kanonak-protocol/types/document/models/enums";var K=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return this.lock.packages[`${e}/${t}`]?.version}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=b(n);if(o){let s={...t,versionOperator:H.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as V,readdirSync as j}from"fs";import{join as N}from"path";var E=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function I(u,e=[]){for(let t of j(u,{withFileTypes:!0}))t.isDirectory()?E.has(t.name)||I(N(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(N(u,t.name));return e}async function z(u,e=new f,t={}){let n=new w(e);for(let m of I(u))try{let l=e.parse(V(m,"utf-8")),p=l.metadata?.namespace_,h=p?.version;p&&h&&await n.saveDocumentAsync(l,`${p.publisher}/${p.package_}@${h.major}.${h.minor}.${h.patch}`)}catch{}let o=new y(d(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,p)=>s.get(`${m}|${l}|${p}`)??null,onFetch:(m,l,p,h)=>{s.set(`${m}|${l}|${p}`,h)}},r=new v({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,_ as b,k as c,d,C as e,D as f,K as g,I as h,z as i};
@@ -0,0 +1 @@
1
+ import{a as u,b as l}from"./chunk-2ACBWC7K.js";import*as c from"js-yaml";var g=new Set(["Package","EphemeralPackage"]);function d(m){return typeof m=="string"&&g.has(m)}var h=class{parse(e){let r=this.parseWithErrors(e);if(!r.isValid){let n=r.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return r.document}parseWithErrors(e){let r=[],n;try{e=e.replace(/^\uFEFF/,"");let a=c.load(e,{schema:c.FAILSAFE_SCHEMA});if(!a||typeof a!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:r,isValid:!0};let t=this.extractMetadata(a),s=this.extractBody(a,t);return n={metadata:t,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:r,isValid:!0}}catch(a){let t=a,s={message:t.message||"Unknown parse error",line:t.mark?.line??0,column:t.mark?.column??0,errorType:t.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${t.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${t.mark?.line??0}: ${t.message||"Unknown parse error"}`};return r.push(s),{document:void 0,errors:r,isValid:!1}}}save(e){let r={};if(e.metadata.namespace_){let n=e.metadata.namespace_,a={type:"Package",publisher:n.publisher};n.version&&(a.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(a.imports=this.serializeImports(e.metadata.imports)),r[n.package_]=a}return Object.assign(r,e.body),c.dump(r,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let r=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!r)return[];let n=[];for(let a of Object.values(r))n.push(...a);return n},enumerable:!0,configurable:!0}),e}createVersion(e,r,n){return{major:e,minor:r,patch:n,toString:()=>`${e}.${r}.${n}`,equals:t=>!t||typeof t!="object"?!1:t.major===e&&t.minor===r&&t.patch===n,getHashCode:()=>e<<20|r<<10|n,compareTo:t=>e!==t.major?e-t.major:r!==t.minor?r-t.minor:n-t.patch}}extractMetadata(e){let r=this.createEmptyMetadata();for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&d(a.type)){r.type_=a.type;let t=n,s=a.publisher,i=a.version?this.parseVersion(a.version):void 0;return s&&t&&(r.namespace_={publisher:s,package_:t,version:i,toString:function(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}`:`${this.publisher}/${this.package_}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===s&&o.package_===t&&(!i||!o.version||i.equals(o.version)),getHashCode:()=>{let o=0;for(let p=0;p<s.length;p++)o=(o<<5)-o+s.charCodeAt(p);for(let p=0;p<t.length;p++)o=(o<<5)-o+t.charCodeAt(p);return o|0}}),a.imports&&Array.isArray(a.imports)&&(r.imports=this.parseImportsV3(a.imports)),this.addAllImportsGetter(r)}return r}extractBody(e,r){let n={};for(let[a,t]of Object.entries(e))if(t&&typeof t=="object"&&d(t.type)){let s={};for(let[i,o]of Object.entries(t))i==="publisher"||i==="version"||i==="imports"||(s[i]=o);n[a]=s}else n[a]=t;return n}parseVersion(e){if(typeof e=="string"){let r=e.split(".").map(Number);return this.createVersion(r[0]||0,r[1]||0,r[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let r={};for(let n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let a=n.publisher;if(!a)throw new Error("PublisherImport requires 'publisher' property");r[a]||(r[a]=[]);for(let t of n.packages){if(!t||typeof t!="object")continue;let s=this.parseImportFromEmbeddedObject(t,a);r[a].push(s)}}else{let a=this.parseImportFromEmbeddedObject(n,n.publisher),t=a.publisher||"";r[t]||(r[t]=[]),r[t].push(a)}return r}parseImportFromEmbeddedObject(e,r){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let a=e.match;if(!a)throw new Error("Import requires 'match' property");let t=e.version;if(!t)throw new Error("Import requires 'version' property");return this.makeImport(n,a,t,r,e.alias)}makeImport(e,r,n,a,t){let s=this.parseVersion(n),i=this.parseVersionOperator(r),o=this.calculateMaxVersion(r,s);return{package_:`${e} ${r} ${s.toString()}`,publisher:a,packageName:e,versionOperator:i,version:s,alias:t,minVersion:s,maxVersion:o,toEmbeddedObject:()=>{let p={package:e,match:r,version:s.toString()};return t&&(p.alias=t),p},toString:()=>t?`${e} ${r} ${s.toString()} as ${t}`:`${e} ${r} ${s.toString()}`}}buildImport(e,r,n,a){return this.makeImport(e,r,n,a)}parseVersionOperator(e){return u(e)}calculateMaxVersion(e,r){switch(e){case"~":return this.createVersion(r.major,r.minor+1,0);case"^":return r.major===0?this.createVersion(0,r.minor+1,0):this.createVersion(r.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let r=[];for(let[n,a]of Object.entries(e)){let t={publisher:n,packages:a.map(s=>{let i=l(s.versionOperator),o={package:s.packageName,match:i,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(o.alias=s.alias),o})};r.push(t)}return r}};export{h as a};
@@ -1 +1 @@
1
- import{a as D}from"./chunk-FSHQVKZ5.js";import{c as j,d as m,g as R,j as p,k as K,l as k}from"./chunk-T3JR2SV6.js";import{c as b,g as u}from"./chunk-2ACBWC7K.js";function F(a,e,n,t){let i=g(a);if(i.length>0){let s=v(i,e,n);return s?{transformation:s.transformation,source:"instance"}:void 0}let r=new Set,o=O(a);for(;o.length>0;){let s=o.shift(),f=_(s.subject);if(r.has(f))continue;r.add(f);let l=S(t,s.subject);if(l.length===0)continue;let U=l.flatMap(g),h=v(U,e,n);if(h)return{transformation:h.transformation,source:{publisher:s.subject.publisher,package_:s.subject.package_,name:s.subject.name}};for(let T of l)for(let P of $(T))o.push(P)}let c={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"};if(!r.has(_(c))){let s=S(t,c).flatMap(g),f=v(s,e,n);if(f)return{transformation:f.transformation,source:c}}}function g(a){let e=[];for(let n of a.statement)if(n instanceof k&&d(n,"kanonak.org","derivation","derivations"))for(let t of n.object??[]){if(!(t instanceof D))continue;let i=x(t);i&&e.push(i)}return e}function v(a,e,n){let t=a.filter(o=>E(o.format,e)&&E(o.variant,n));if(t.length<=1)return t[0];let i=t[0].transformation,r=t[0];for(let o of t){let c=o.transformation;if(c.publisher!==i.publisher||c.package_!==i.package_||c.name!==i.name)continue;let s=u(r.transformation.version),f=u(c.version);s&&f&&b(f,s)>0&&(r=o)}return r}function x(a){let e,n,t;for(let i of a.statement)i instanceof p?d(i,"kanonak.org","derivation","format")?e=y(i):d(i,"kanonak.org","derivation","variant")&&(n=y(i)):i instanceof K&&d(i,"kanonak.org","derivation","transformation")&&(t=C(i.object));if(!(!e||!t))return n||(n={publisher:"kanonak.org",package_:"derivation",name:"default"}),{format:e,variant:n,transformation:t}}function C(a){let e,n,t,i;for(let r of a.statement){if(!(r instanceof R))continue;let o=r.predicate?.subject?.name;o==="publisher"?e=r.object:o==="package"?n=r.object:o==="version"?t=r.object:o==="name"&&(i=r.object)}if(!(!e||!n||!t||!i))return{publisher:e,package_:n,version:t,name:i}}function O(a){let e=[];for(let n of a.statement)n instanceof p&&n.predicate?.subject?.name==="type"&&n.object instanceof m&&e.push(n.object);return e}function $(a){let e=[];for(let n of a.statement)if(n instanceof p){if(n.predicate?.subject?.name!=="subClassOf")continue;n.object instanceof m&&e.push(n.object)}else if(n instanceof k){if(n.predicate?.subject?.name!=="subClassOf")continue;for(let t of n.object??[])t instanceof m&&e.push(t)}return e}function S(a,e){let n=[];for(let t of a){if(!(t instanceof j)||t.name!==e.name)continue;(t.namespace||"").startsWith(`${e.publisher}/${e.package_}@`)&&n.push(t)}return n.sort((t,i)=>{let r=u((t.namespace||"").split("@")[1]??""),o=u((i.namespace||"").split("@")[1]??"");return!r||!o?0:b(o,r)}),n}function d(a,e,n,t){let i=a.predicate?.subject;return i?i.publisher===e&&i.package_===n&&i.name===t:!1}function y(a){let e=a.object.subject;return{publisher:e.publisher,package_:e.package_,name:e.name}}function E(a,e){return a.publisher===e.publisher&&a.package_===e.package_&&a.name===e.name}function _(a){return`${a.publisher}/${a.package_}/${a.name}`}export{F as a};
1
+ import{a as D}from"./chunk-DSHPAWJQ.js";import{c as j,d as m,g as R,j as p,k as K,l as k}from"./chunk-T3JR2SV6.js";import{c as b,g as u}from"./chunk-2ACBWC7K.js";function F(a,e,n,t){let i=g(a);if(i.length>0){let s=v(i,e,n);return s?{transformation:s.transformation,source:"instance"}:void 0}let r=new Set,o=O(a);for(;o.length>0;){let s=o.shift(),f=_(s.subject);if(r.has(f))continue;r.add(f);let l=S(t,s.subject);if(l.length===0)continue;let U=l.flatMap(g),h=v(U,e,n);if(h)return{transformation:h.transformation,source:{publisher:s.subject.publisher,package_:s.subject.package_,name:s.subject.name}};for(let T of l)for(let P of $(T))o.push(P)}let c={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"};if(!r.has(_(c))){let s=S(t,c).flatMap(g),f=v(s,e,n);if(f)return{transformation:f.transformation,source:c}}}function g(a){let e=[];for(let n of a.statement)if(n instanceof k&&d(n,"kanonak.org","derivation","derivations"))for(let t of n.object??[]){if(!(t instanceof D))continue;let i=x(t);i&&e.push(i)}return e}function v(a,e,n){let t=a.filter(o=>E(o.format,e)&&E(o.variant,n));if(t.length<=1)return t[0];let i=t[0].transformation,r=t[0];for(let o of t){let c=o.transformation;if(c.publisher!==i.publisher||c.package_!==i.package_||c.name!==i.name)continue;let s=u(r.transformation.version),f=u(c.version);s&&f&&b(f,s)>0&&(r=o)}return r}function x(a){let e,n,t;for(let i of a.statement)i instanceof p?d(i,"kanonak.org","derivation","format")?e=y(i):d(i,"kanonak.org","derivation","variant")&&(n=y(i)):i instanceof K&&d(i,"kanonak.org","derivation","transformation")&&(t=C(i.object));if(!(!e||!t))return n||(n={publisher:"kanonak.org",package_:"derivation",name:"default"}),{format:e,variant:n,transformation:t}}function C(a){let e,n,t,i;for(let r of a.statement){if(!(r instanceof R))continue;let o=r.predicate?.subject?.name;o==="publisher"?e=r.object:o==="package"?n=r.object:o==="version"?t=r.object:o==="name"&&(i=r.object)}if(!(!e||!n||!t||!i))return{publisher:e,package_:n,version:t,name:i}}function O(a){let e=[];for(let n of a.statement)n instanceof p&&n.predicate?.subject?.name==="type"&&n.object instanceof m&&e.push(n.object);return e}function $(a){let e=[];for(let n of a.statement)if(n instanceof p){if(n.predicate?.subject?.name!=="subClassOf")continue;n.object instanceof m&&e.push(n.object)}else if(n instanceof k){if(n.predicate?.subject?.name!=="subClassOf")continue;for(let t of n.object??[])t instanceof m&&e.push(t)}return e}function S(a,e){let n=[];for(let t of a){if(!(t instanceof j)||t.name!==e.name)continue;(t.namespace||"").startsWith(`${e.publisher}/${e.package_}@`)&&n.push(t)}return n.sort((t,i)=>{let r=u((t.namespace||"").split("@")[1]??""),o=u((i.namespace||"").split("@")[1]??"");return!r||!o?0:b(o,r)}),n}function d(a,e,n,t){let i=a.predicate?.subject;return i?i.publisher===e&&i.package_===n&&i.name===t:!1}function y(a){let e=a.object.subject;return{publisher:e.publisher,package_:e.package_,name:e.name}}function E(a,e){return a.publisher===e.publisher&&a.package_===e.package_&&a.name===e.name}function _(a){return`${a.publisher}/${a.package_}/${a.name}`}export{F as a};
@@ -1 +1 @@
1
- import{a as j,b as x,i as _}from"./chunk-FSHQVKZ5.js";import{d as l,e as u,f as b,g as $,h as s,j as h}from"./chunk-VKTFLHCW.js";import{c as S,d as O,g as I,h as T,i as g,j as v,k as L,l as q}from"./chunk-T3JR2SV6.js";var d=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=b(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),P(this.byPIdx,e.p,e),P(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&P(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(b(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 n=new Set;for(let a of r)n.add(a.s);return Array.from(n)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let a of r)a.o.kind==="uri"&&n.add(a.o.key);return Array.from(n)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${$(r)}`)}};function P(o,e,t){let r=o.get(e);r?r.push(t):o.set(e,[t])}var w={name:"rdfs2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},C={name:"rdfs3",apply(o,e){let t=!1;for(let r of o.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))i.o.kind==="uri"&&o.add(s(i.o.key,e.type,a))&&(t=!0)}return t}},A={name:"rdfs5",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.bySubjectPredicate(a,e.subPropertyOf))i.o.kind==="uri"&&o.add(s(n,e.subPropertyOf,i.o.key))&&(t=!0)}return t}},V={name:"rdfs7",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(n)){let f={s:i.s,p:a,o:i.o};o.add(f)&&(t=!0)}}return t}},W={name:"rdfs9",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},F={name:"rdfs11",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.bySubjectPredicate(a,e.subClassOf))i.o.kind==="uri"&&o.add(s(n,e.subClassOf,i.o.key))&&(t=!0)}return t}},k=[w,C,A,V,W,F];var N={name:"prp-trp",apply(o,e){let t=!1,r=o.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let n of r){let a=o.byPredicate(n);for(let i of a){if(i.o.kind!=="uri")continue;let f=i.o.key;for(let c of o.bySubjectPredicate(f,n))c.o.kind==="uri"&&i.s!==c.o.key&&o.add(s(i.s,n,c.o.key))&&(t=!0)}}return t}},D={name:"prp-symp",apply(o,e){let t=!1,r=o.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let n of r)for(let a of o.byPredicate(n))a.o.kind==="uri"&&o.add(s(a.o.key,n,a.s))&&(t=!0);return t}},z={name:"prp-inv1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))i.o.kind==="uri"&&o.add(s(i.o.key,a,i.s))&&(t=!0)}return t}},B={name:"prp-inv2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(a))i.o.kind==="uri"&&o.add(s(i.o.key,n,i.s))&&(t=!0)}return t}},M={name:"prp-eqp1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(n))o.add({s:i.s,p:a,o:i.o})&&(t=!0)}return t}},G={name:"prp-eqp2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(a))o.add({s:i.s,p:n,o:i.o})&&(t=!0)}return t}},H={name:"cax-eqc1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},J={name:"cax-eqc2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,a))o.add(s(i.s,e.type,n))&&(t=!0)}return t}},Q={name:"eq-rep-s",apply(o,e){let t=!1;for(let r of o.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a){for(let i of o.snapshot())i.s===n&&o.add({s:a,p:i.p,o:i.o})&&(t=!0);for(let i of o.snapshot())i.s===a&&o.add({s:n,p:i.p,o:i.o})&&(t=!0)}}return t}},X={name:"eq-rep-o",apply(o,e){let t=!1;for(let r of o.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.snapshot())i.o.kind==="uri"&&(i.o.key===n?o.add(s(i.s,i.p,a))&&(t=!0):i.o.key===a&&o.add(s(i.s,i.p,n))&&(t=!0))}return t}},K=[N,D,z,B,M,G,H,J,Q,X];var y=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=p(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=p(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(n=>n!==t)}getSuperclasses(e){let t=p(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(p(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(p(e),this.vocabulary.type,p(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function p(o){return typeof o=="string"?o:u(o.publisher,o.package_,o.name)}var R=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new h,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new d,n=await new _().parseKanonaks(e),a=new U;for(let c of n)if(c instanceof S){let m=Y(c);if(!m)continue;for(let E of c.statement)this.emitStatement(m,E,t,a)}let i=[...k];this.profile==="owl-rl-classification"&&i.push(...K);let f=0;for(;f<this.maxIterations;){let c=!1;for(let m of i)m.apply(t,this.vocabulary)&&(c=!0);if(!c)break;f++}return new y(t,this.vocabulary)}emitStatement(e,t,r,n){let a=Z(t);if(a){if(t instanceof I){r.add({s:e,p:a,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof T){r.add({s:e,p:a,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof g){r.add({s:e,p:a,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof v){let i=l(t.object.subject);r.add(s(e,a,i));return}if(t instanceof L){let i=n.next();r.add({s:e,p:a,o:{kind:"blank",id:i}}),this.emitEmbedded(i,t.object,r,n);return}if(t instanceof q){for(let i of t.object??[])this.emitListItem(e,a,i,r,n);return}}}emitListItem(e,t,r,n,a){if(r instanceof O)n.add(s(e,t,l(r.subject)));else if(r instanceof j){let i=a.next();n.add({s:e,p:t,o:{kind:"blank",id:i}}),this.emitEmbedded(i,r,n,a)}else if(r instanceof x){let i=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";n.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:i}})}}emitEmbedded(e,t,r,n){let a=`_:${e}`;for(let i of t.statement)this.emitStatement(a,i,r,n)}},U=class{counter=0;next(){return`b${this.counter++}`}};function Y(o){let e=o.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),n=r.indexOf("/");if(n===-1)return null;let a=r.substring(0,n),i=r.substring(n+1);return!a||!i||!o.name?null:u(a,i,o.name)}function Z(o){let e=o.predicate;return e?.subject?l(e.subject):null}export{d as a,k as b,K as c,y as d,R as e};
1
+ import{a as j,b as x,i as _}from"./chunk-DSHPAWJQ.js";import{d as l,e as u,f as b,g as $,h as s,j as h}from"./chunk-VKTFLHCW.js";import{c as S,d as O,g as I,h as T,i as g,j as v,k as L,l as q}from"./chunk-T3JR2SV6.js";var d=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=b(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),P(this.byPIdx,e.p,e),P(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&P(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(b(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 n=new Set;for(let a of r)n.add(a.s);return Array.from(n)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let a of r)a.o.kind==="uri"&&n.add(a.o.key);return Array.from(n)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${$(r)}`)}};function P(o,e,t){let r=o.get(e);r?r.push(t):o.set(e,[t])}var w={name:"rdfs2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},C={name:"rdfs3",apply(o,e){let t=!1;for(let r of o.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))i.o.kind==="uri"&&o.add(s(i.o.key,e.type,a))&&(t=!0)}return t}},A={name:"rdfs5",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.bySubjectPredicate(a,e.subPropertyOf))i.o.kind==="uri"&&o.add(s(n,e.subPropertyOf,i.o.key))&&(t=!0)}return t}},V={name:"rdfs7",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(n)){let f={s:i.s,p:a,o:i.o};o.add(f)&&(t=!0)}}return t}},W={name:"rdfs9",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},F={name:"rdfs11",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.bySubjectPredicate(a,e.subClassOf))i.o.kind==="uri"&&o.add(s(n,e.subClassOf,i.o.key))&&(t=!0)}return t}},k=[w,C,A,V,W,F];var N={name:"prp-trp",apply(o,e){let t=!1,r=o.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let n of r){let a=o.byPredicate(n);for(let i of a){if(i.o.kind!=="uri")continue;let f=i.o.key;for(let c of o.bySubjectPredicate(f,n))c.o.kind==="uri"&&i.s!==c.o.key&&o.add(s(i.s,n,c.o.key))&&(t=!0)}}return t}},D={name:"prp-symp",apply(o,e){let t=!1,r=o.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let n of r)for(let a of o.byPredicate(n))a.o.kind==="uri"&&o.add(s(a.o.key,n,a.s))&&(t=!0);return t}},z={name:"prp-inv1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))i.o.kind==="uri"&&o.add(s(i.o.key,a,i.s))&&(t=!0)}return t}},B={name:"prp-inv2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(a))i.o.kind==="uri"&&o.add(s(i.o.key,n,i.s))&&(t=!0)}return t}},M={name:"prp-eqp1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(n))o.add({s:i.s,p:a,o:i.o})&&(t=!0)}return t}},G={name:"prp-eqp2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(a))o.add({s:i.s,p:n,o:i.o})&&(t=!0)}return t}},H={name:"cax-eqc1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},J={name:"cax-eqc2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,a))o.add(s(i.s,e.type,n))&&(t=!0)}return t}},Q={name:"eq-rep-s",apply(o,e){let t=!1;for(let r of o.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a){for(let i of o.snapshot())i.s===n&&o.add({s:a,p:i.p,o:i.o})&&(t=!0);for(let i of o.snapshot())i.s===a&&o.add({s:n,p:i.p,o:i.o})&&(t=!0)}}return t}},X={name:"eq-rep-o",apply(o,e){let t=!1;for(let r of o.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.snapshot())i.o.kind==="uri"&&(i.o.key===n?o.add(s(i.s,i.p,a))&&(t=!0):i.o.key===a&&o.add(s(i.s,i.p,n))&&(t=!0))}return t}},K=[N,D,z,B,M,G,H,J,Q,X];var y=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=p(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=p(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(n=>n!==t)}getSuperclasses(e){let t=p(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(p(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(p(e),this.vocabulary.type,p(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function p(o){return typeof o=="string"?o:u(o.publisher,o.package_,o.name)}var R=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new h,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new d,n=await new _().parseKanonaks(e),a=new U;for(let c of n)if(c instanceof S){let m=Y(c);if(!m)continue;for(let E of c.statement)this.emitStatement(m,E,t,a)}let i=[...k];this.profile==="owl-rl-classification"&&i.push(...K);let f=0;for(;f<this.maxIterations;){let c=!1;for(let m of i)m.apply(t,this.vocabulary)&&(c=!0);if(!c)break;f++}return new y(t,this.vocabulary)}emitStatement(e,t,r,n){let a=Z(t);if(a){if(t instanceof I){r.add({s:e,p:a,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof T){r.add({s:e,p:a,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof g){r.add({s:e,p:a,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof v){let i=l(t.object.subject);r.add(s(e,a,i));return}if(t instanceof L){let i=n.next();r.add({s:e,p:a,o:{kind:"blank",id:i}}),this.emitEmbedded(i,t.object,r,n);return}if(t instanceof q){for(let i of t.object??[])this.emitListItem(e,a,i,r,n);return}}}emitListItem(e,t,r,n,a){if(r instanceof O)n.add(s(e,t,l(r.subject)));else if(r instanceof j){let i=a.next();n.add({s:e,p:t,o:{kind:"blank",id:i}}),this.emitEmbedded(i,r,n,a)}else if(r instanceof x){let i=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";n.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:i}})}}emitEmbedded(e,t,r,n){let a=`_:${e}`;for(let i of t.statement)this.emitStatement(a,i,r,n)}},U=class{counter=0;next(){return`b${this.counter++}`}};function Y(o){let e=o.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),n=r.indexOf("/");if(n===-1)return null;let a=r.substring(0,n),i=r.substring(n+1);return!a||!i||!o.name?null:u(a,i,o.name)}function Z(o){let e=o.predicate;return e?.subject?l(e.subject):null}export{d as a,k as b,K as c,y as d,R as e};
@@ -1,2 +1,2 @@
1
- import{h as V}from"./chunk-FSHQVKZ5.js";import{a as E}from"./chunk-ZYAABYDS.js";var L=class{propertyUri;propertyType;range;rangeUri;isImported;definedInNamespace};import{parseDocument as O,LineCounter as R,isMap as h,isPair as f,isScalar as g,isSeq as I}from"yaml";var K=class i{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 i,n=new R,r=O(e,{lineCounter:n});if(r.errors.length>0||!h(r.contents))return t;N(r.contents,[],n,t);for(let o of r.contents.items){if(!f(o)||!g(o.key))continue;let a=String(o.key.value),u=o.key.range;if(!u)continue;t.entities.set(a,d(u,n));let s=o.value,c=s&&typeof s=="object"&&"range"in s?s.range:void 0;if(c?t.entityBlocks.set(a,d([u[0],u[1],c[2]],n)):t.entityBlocks.set(a,d(u,n)),h(o.value)){let k=new Map,m=new Map,l=new Map;for(let P of o.value.items){if(!f(P)||!g(P.key))continue;let b=String(P.key.value),p=P.key.range;p&&k.set(b,d(p,n));let S=P.value;if(S&&typeof S=="object"&&"range"in S&&Array.isArray(S.range)){let v=S.range;m.set(b,d(v,n))}if(I(S)){let v=[];for(let M of S.items)M&&typeof M=="object"&&"range"in M&&Array.isArray(M.range)&&v.push(d(M.range,n));v.length>0&&l.set(b,v)}}k.size>0&&t.properties.set(a,k),m.size>0&&t.propertyValues.set(a,m),l.size>0&&t.valueListItems.set(a,l);let y=j(o.value,n);y.length>0&&t.importPackages.set(a,y)}}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(w(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 a,u;if(o)for(let[s,c]of o)w(c,e,t)&&(!u||C(c,u))&&(a=s,u=c);if(r)for(let[s,c]of r)w(c,e,t)&&(!u||C(c,u))&&(a=s,u=c);return a?{entityName:n,propertyName:a}:{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 a=this.getListItemPosition(e,t,n);if(a)return a}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 j(i,e){let t=[];if(!h(i))return t;let n=i.items.find(r=>f(r)&&g(r.key)&&String(r.key.value)==="imports");if(!n||!f(n)||!I(n.value))return t;for(let r of n.value.items){if(!h(r))continue;let o=r.items.find(s=>f(s)&&g(s.key)&&String(s.key.value)==="publisher");if(!o||!f(o)||!g(o.value))continue;let a=String(o.value.value),u=r.items.find(s=>f(s)&&g(s.key)&&String(s.key.value)==="packages");if(!(!u||!f(u)||!I(u.value)))for(let s of u.value.items){if(!h(s))continue;let c=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="package");if(!c||!f(c)||!g(c.value)||!c.value.range)continue;let k=String(c.value.value),m=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="version"),l=m&&f(m)&&g(m.value)?String(m.value.value):"",y=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="alias"),P=y&&f(y)&&g(y.value)?String(y.value.value):void 0,b=P!==void 0?{publisher:a,package_:k,version:l,alias:P,position:d(c.value.range,e)}:{publisher:a,package_:k,version:l,position:d(c.value.range,e)};t.push(b)}}return t}function w(i,e,t){return!(e<i.line||e>i.endLine||e===i.line&&t<i.column||e===i.endLine&&t>i.endColumn)}function C(i,e){let t=i.endLine-i.line,n=e.endLine-e.line;if(t!==n)return t<n;let r=i.endLine===i.line?i.endColumn-i.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return r<o}function N(i,e,t,n){if(h(i)){for(let r of i.items){if(!f(r)||!g(r.key))continue;let o=String(r.key.value),a=[...e,o],u=JSON.stringify(a);r.key.range&&n.setNestedKeyPosition(u,d(r.key.range,t));let s=r.value,c=D(s);c&&n.setNestedValuePosition(u,d(c,t)),N(s,a,t,n)}return}if(I(i)){for(let r=0;r<i.items.length;r++){let o=i.items[r],a=[...e,r],u=JSON.stringify(a),s=D(o);s&&n.setNestedValuePosition(u,d(s,t)),N(o,a,t,n)}return}}function D(i){if(!i||typeof i!="object"||!("range"in i))return;let e=i.range;return Array.isArray(e)&&e.length>=3?e:void 0}function d(i,e){let t=e.linePos(i[0]),n=e.linePos(i[2]);return{line:t.line-1,column:t.col-1,endLine:n.line-1,endColumn:n.col-1}}function x(i,e){let n=(e??new E).parse(i),r=K.fromContent(i);return{document:n,positions:r}}function W(i,e,t,n,r){if(e<n.line||e>n.endLine||e===n.line&&t<n.column||e===n.endLine&&t>=n.endColumn)return;let o=A(r,n.line,n.column),a=A(r,n.endLine,n.endColumn);if(o<0||a<0)return;let u=r.substring(o,a),s=V(u);if(s.length!==i.links.length)return;let c=e-n.line,k=e===n.line?t-n.column:t,m=A(u,c,k);if(!(m<0))for(let l=0;l<s.length;l++){let y=s[l];if(m>=y.startOffset&&m<y.endOffset)return i.links[l]}}function A(i,e,t){let n=0,r=0;for(let o=0;o<i.length;o++){if(n===e)return Math.min(r+t,i.length);i[o]===`
1
+ import{h as V}from"./chunk-DSHPAWJQ.js";import{a as E}from"./chunk-NJ3AZYQD.js";var L=class{propertyUri;propertyType;range;rangeUri;isImported;definedInNamespace};import{parseDocument as O,LineCounter as R,isMap as h,isPair as f,isScalar as g,isSeq as I}from"yaml";var K=class i{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 i,n=new R,r=O(e,{lineCounter:n});if(r.errors.length>0||!h(r.contents))return t;N(r.contents,[],n,t);for(let o of r.contents.items){if(!f(o)||!g(o.key))continue;let a=String(o.key.value),u=o.key.range;if(!u)continue;t.entities.set(a,d(u,n));let s=o.value,c=s&&typeof s=="object"&&"range"in s?s.range:void 0;if(c?t.entityBlocks.set(a,d([u[0],u[1],c[2]],n)):t.entityBlocks.set(a,d(u,n)),h(o.value)){let k=new Map,m=new Map,l=new Map;for(let P of o.value.items){if(!f(P)||!g(P.key))continue;let b=String(P.key.value),p=P.key.range;p&&k.set(b,d(p,n));let S=P.value;if(S&&typeof S=="object"&&"range"in S&&Array.isArray(S.range)){let v=S.range;m.set(b,d(v,n))}if(I(S)){let v=[];for(let M of S.items)M&&typeof M=="object"&&"range"in M&&Array.isArray(M.range)&&v.push(d(M.range,n));v.length>0&&l.set(b,v)}}k.size>0&&t.properties.set(a,k),m.size>0&&t.propertyValues.set(a,m),l.size>0&&t.valueListItems.set(a,l);let y=j(o.value,n);y.length>0&&t.importPackages.set(a,y)}}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(w(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 a,u;if(o)for(let[s,c]of o)w(c,e,t)&&(!u||C(c,u))&&(a=s,u=c);if(r)for(let[s,c]of r)w(c,e,t)&&(!u||C(c,u))&&(a=s,u=c);return a?{entityName:n,propertyName:a}:{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 a=this.getListItemPosition(e,t,n);if(a)return a}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 j(i,e){let t=[];if(!h(i))return t;let n=i.items.find(r=>f(r)&&g(r.key)&&String(r.key.value)==="imports");if(!n||!f(n)||!I(n.value))return t;for(let r of n.value.items){if(!h(r))continue;let o=r.items.find(s=>f(s)&&g(s.key)&&String(s.key.value)==="publisher");if(!o||!f(o)||!g(o.value))continue;let a=String(o.value.value),u=r.items.find(s=>f(s)&&g(s.key)&&String(s.key.value)==="packages");if(!(!u||!f(u)||!I(u.value)))for(let s of u.value.items){if(!h(s))continue;let c=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="package");if(!c||!f(c)||!g(c.value)||!c.value.range)continue;let k=String(c.value.value),m=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="version"),l=m&&f(m)&&g(m.value)?String(m.value.value):"",y=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="alias"),P=y&&f(y)&&g(y.value)?String(y.value.value):void 0,b=P!==void 0?{publisher:a,package_:k,version:l,alias:P,position:d(c.value.range,e)}:{publisher:a,package_:k,version:l,position:d(c.value.range,e)};t.push(b)}}return t}function w(i,e,t){return!(e<i.line||e>i.endLine||e===i.line&&t<i.column||e===i.endLine&&t>i.endColumn)}function C(i,e){let t=i.endLine-i.line,n=e.endLine-e.line;if(t!==n)return t<n;let r=i.endLine===i.line?i.endColumn-i.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return r<o}function N(i,e,t,n){if(h(i)){for(let r of i.items){if(!f(r)||!g(r.key))continue;let o=String(r.key.value),a=[...e,o],u=JSON.stringify(a);r.key.range&&n.setNestedKeyPosition(u,d(r.key.range,t));let s=r.value,c=D(s);c&&n.setNestedValuePosition(u,d(c,t)),N(s,a,t,n)}return}if(I(i)){for(let r=0;r<i.items.length;r++){let o=i.items[r],a=[...e,r],u=JSON.stringify(a),s=D(o);s&&n.setNestedValuePosition(u,d(s,t)),N(o,a,t,n)}return}}function D(i){if(!i||typeof i!="object"||!("range"in i))return;let e=i.range;return Array.isArray(e)&&e.length>=3?e:void 0}function d(i,e){let t=e.linePos(i[0]),n=e.linePos(i[2]);return{line:t.line-1,column:t.col-1,endLine:n.line-1,endColumn:n.col-1}}function x(i,e){let n=(e??new E).parse(i),r=K.fromContent(i);return{document:n,positions:r}}function W(i,e,t,n,r){if(e<n.line||e>n.endLine||e===n.line&&t<n.column||e===n.endLine&&t>=n.endColumn)return;let o=A(r,n.line,n.column),a=A(r,n.endLine,n.endColumn);if(o<0||a<0)return;let u=r.substring(o,a),s=V(u);if(s.length!==i.links.length)return;let c=e-n.line,k=e===n.line?t-n.column:t,m=A(u,c,k);if(!(m<0))for(let l=0;l<s.length;l++){let y=s[l];if(m>=y.startOffset&&m<y.endOffset)return i.links[l]}}function A(i,e,t){let n=0,r=0;for(let o=0;o<i.length;o++){if(n===e)return Math.min(r+t,i.length);i[o]===`
2
2
  `&&(n++,r=o+1)}return n===e?Math.min(r+t,i.length):-1}export{L as a,K as b,x as c,W as d};
@@ -1,4 +1,4 @@
1
- import{a as Fn}from"./chunk-4NO7MHS7.js";import{a as Mn}from"./chunk-PEJALHXK.js";import{d as u}from"./chunk-SHDHMKMJ.js";import{a as x,c as xe,i as An}from"./chunk-FSHQVKZ5.js";import{a as Vn}from"./chunk-ZYAABYDS.js";import{a as pn,b as ue,c as xn,d as w,f as Pe,g as ke,j as gn,k as qe,m as Pn,n as Nn}from"./chunk-PBNVHBS3.js";import{b as Oe,c as G,d as E,g as X,h as me,i as re,j as T,k as H,l as V}from"./chunk-T3JR2SV6.js";import{a as Tn}from"./chunk-FUUTGGJS.js";import{c as en,g as $e}from"./chunk-2ACBWC7K.js";var Ve="kanonak.org",zn="look",We="core-rdf",Kt={publisher:Ve,package_:zn,name:"displayLabel"},Rt={publisher:Ve,package_:zn,name:"displaySummary"},Lt={publisher:Ve,package_:We,name:"type"},Ot={publisher:Ve,package_:We,name:"subClassOf"},Ut={publisher:Ve,package_:We,name:"label"},It={publisher:Ve,package_:We,name:"comment"},Dn=new Tn(Ve,We,"Resource");function D(r,e){let n=Bn(r,e,Kt)??Ut,t=Bn(r,e,Rt)??It,a=gn(e,n)??e.name,s=gn(e,t);return{label:a,summary:s}}function Bn(r,e,n){let t=qe(e,n);if(t)return t;let a=new Set,s=Hn(e,Lt);for(;s.length>0;){let o=s.shift(),i=pn(o);if(a.has(i))continue;a.add(i);let c=Pe(r,o);if(!c)continue;let l=qe(c,n);if(l)return l;s.push(...Hn(c,Ot))}if(!a.has(pn(Dn))){let o=Pe(r,Dn);if(o){let i=qe(o,n);if(i)return i}}}function Hn(r,e){let n=qe(r,e);if(n)return[n];let t=[];for(let a of Pn(r,e))a instanceof E&&t.push(a.subject);return t}function Ye(r,e={}){let n=r.replace(/\r\n/g,`
1
+ import{a as Fn}from"./chunk-4NO7MHS7.js";import{a as Mn}from"./chunk-PEJALHXK.js";import{d as u}from"./chunk-SHDHMKMJ.js";import{a as x,c as xe,i as An}from"./chunk-DSHPAWJQ.js";import{a as Vn}from"./chunk-NJ3AZYQD.js";import{a as pn,b as ue,c as xn,d as w,f as Pe,g as ke,j as gn,k as qe,m as Pn,n as Nn}from"./chunk-PBNVHBS3.js";import{b as Oe,c as G,d as E,g as X,h as me,i as re,j as T,k as H,l as V}from"./chunk-T3JR2SV6.js";import{a as Tn}from"./chunk-FUUTGGJS.js";import{c as en,g as $e}from"./chunk-2ACBWC7K.js";var Ve="kanonak.org",zn="look",We="core-rdf",Kt={publisher:Ve,package_:zn,name:"displayLabel"},Rt={publisher:Ve,package_:zn,name:"displaySummary"},Lt={publisher:Ve,package_:We,name:"type"},Ot={publisher:Ve,package_:We,name:"subClassOf"},Ut={publisher:Ve,package_:We,name:"label"},It={publisher:Ve,package_:We,name:"comment"},Dn=new Tn(Ve,We,"Resource");function D(r,e){let n=Bn(r,e,Kt)??Ut,t=Bn(r,e,Rt)??It,a=gn(e,n)??e.name,s=gn(e,t);return{label:a,summary:s}}function Bn(r,e,n){let t=qe(e,n);if(t)return t;let a=new Set,s=Hn(e,Lt);for(;s.length>0;){let o=s.shift(),i=pn(o);if(a.has(i))continue;a.add(i);let c=Pe(r,o);if(!c)continue;let l=qe(c,n);if(l)return l;s.push(...Hn(c,Ot))}if(!a.has(pn(Dn))){let o=Pe(r,Dn);if(o){let i=qe(o,n);if(i)return i}}}function Hn(r,e){let n=qe(r,e);if(n)return[n];let t=[];for(let a of Pn(r,e))a instanceof E&&t.push(a.subject);return t}function Ye(r,e={}){let n=r.replace(/\r\n/g,`
2
2
  `).split(`
3
3
  `),t=[],a=0;for(;a<n.length;){let s=n[a];if(s.trim()===""){a++;continue}let o=/^(\s*)```(\S*)\s*$/.exec(s);if(o){let l=o[2],d=[];for(a++;a<n.length&&!/^(\s*)```\s*$/.test(n[a]);)d.push(n[a]),a++;a++;let f=d.join(`
4
4
  `),g=l&&e.highlight?e.highlight(l,f):De(f),m=l?` class="language-${qn(l)}"`:"";t.push(`<pre class="kan-code"><code${m}>${g}</code></pre>`);continue}let i=/^(#{1,6})\s+(.*)$/.exec(s);if(i){let l=i[1].length,d=Ne(i[2].trim());t.push(`<h${l}>${d}</h${l}>`),a++;continue}if(s.includes("|")&&a+1<n.length&&Gn(n[a+1])){let l=mn(s),d=Ct(n[a+1]);a+=2;let f=[];for(;a<n.length&&n[a].trim()!==""&&n[a].includes("|");)f.push(mn(n[a])),a++;t.push(Ft(l,d,f));continue}if(/^\s*[-*]\s+/.test(s)){let l=[];for(;a<n.length&&/^\s*[-*]\s+/.test(n[a]);){let d=[n[a].replace(/^\s*[-*]\s+/,"")];for(a++;a<n.length&&n[a].trim()!==""&&!/^\s*[-*]\s+/.test(n[a])&&!/^\s*\d+\.\s+/.test(n[a]);)d.push(n[a]),a++;a<n.length&&n[a].trim()===""&&a++,l.push(`<li>${Ne(d.join(" ").trim())}</li>`)}t.push(`<ul>
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { InMemoryKanonakDocumentRepository, FileSystemKanonakDocumentRepository, CompositeKanonakDocumentRepository, RepositoryFactory, DocumentLocation, HttpKanonakDocumentRepository, LocalFirstRepository, buildLocalFirstRepository, collectKanonakFiles, PublisherIndex, PublisherConfigResolver, getGlobalCachePath } from './repositories/index.js';
1
+ export { InMemoryKanonakDocumentRepository, FileSystemKanonakDocumentRepository, CompositeKanonakDocumentRepository, RepositoryFactory, DocumentLocation, HttpKanonakDocumentRepository, LocalFirstRepository, LockAwareRepository, buildLocalFirstRepository, collectKanonakFiles, PublisherIndex, PublisherConfigResolver, getGlobalCachePath } from './repositories/index.js';
2
2
  export type { PublisherConfig, HttpCacheHooks } from './repositories/index.js';
3
3
  export { GraphBuilder, NodeType, EdgeType } from './graph/index.js';
4
4
  export type { GraphNode, GraphEdge, GraphData } from './graph/index.js';
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import{a as bn,b as Pn,c as wn,d as Sn,e as be}from"./chunk-B73JY5G4.js";import{a as fr,c as Ce,e as He,h as ze,i as We,j as yr}from"./chunk-SW4AJ6GD.js";import{a as gn,b as hn,c as kn,d as W,e as G,f as l,g as gr}from"./chunk-2D3MZRJB.js";import{a as mr}from"./chunk-NG2YXSH7.js";import"./chunk-QHABFCRC.js";import{a as zt,b as Wt,c as Gt,d as Jt,e as qt,f as en,g as tn,h as nn}from"./chunk-YWUKDEZA.js";import{b as Yt,c as Zt,d as Qt}from"./chunk-YCV4H6H5.js";import{a as Ht}from"./chunk-4NO7MHS7.js";import{a as Rn,b as En,c as xn,d as In}from"./chunk-WBRCKPEH.js";import{a as vn,b as On}from"./chunk-PEUTCG3B.js";import{a as $n}from"./chunk-PEJALHXK.js";import{a as Xt}from"./chunk-SC5M74NM.js";import{A as cr,B as lr,C as ur,D as pr,M as dr,a as Dn,b as Nn,c as Tn,d as _n,e as Ln,f as Un,g as Fn,h as Mn,i as Hn,j as zn,k as Wn,l as Gn,m as Jn,n as qn,o as Yn,p as Zn,q as Xn,r as Qn,s as er,t as tr,u as nr,v as rr,w as or,x as ar,y as ir,z as sr}from"./chunk-P3MJIJSK.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as C,c as an,d as Fe,e as v,f as ke,g as mn,h as fn,i as $}from"./chunk-FSHQVKZ5.js";import{a as S}from"./chunk-ZYAABYDS.js";import{a as yn,b as Pe,c as Kn,d as h,e as jn,f as Vn,g as An,h as Bn}from"./chunk-UK2OIPAB.js";import{f as z,k as j,l as we,m as Se,n as Me}from"./chunk-PBNVHBS3.js";import{b as sn,c as cn,d as K,e as ln,f as un,h as pn,j as dn}from"./chunk-VKTFLHCW.js";import{a as rn,b as fe,c as f,d as p,e as on,f as ye,g as R,h as ge,i as he,j as E,k as x,l as I}from"./chunk-T3JR2SV6.js";import{a as H}from"./chunk-FUUTGGJS.js";import{a as Nt,b as me,c as M,d as Tt,e as k,f as _t,g as Lt,h as Ut,i as Ft,j as Mt}from"./chunk-2ACBWC7K.js";import{a as Cn}from"./chunk-ODIECDN7.js";import{VersionOperator as Di}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Br,readFileSync as Or}from"fs";import{homedir as Dr}from"os";import{join as Nr}from"path";import{execFile as hr}from"child_process";import{promisify as kr}from"util";var J=kr(hr),q="kanonak",Y="/usr/bin/security",V=class{async get(e){let t=l(e);try{let{stdout:r}=await J(Y,["find-generic-password","-s",q,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
1
+ import{a as Pn,b as wn,c as Sn,d as Cn,e as be}from"./chunk-RWEGPZ23.js";import{a as yr,c as Ce,e as He,h as ze,i as We,j as gr}from"./chunk-XRXCYM3U.js";import{a as hn,b as kn,c as bn,d as W,e as G,f as l,g as hr}from"./chunk-KGWDV7FW.js";import{a as fr}from"./chunk-NV63IOB7.js";import"./chunk-QHABFCRC.js";import{a as zt,b as Wt,c as Gt,d as Jt,e as qt,f as en,g as tn,h as nn,i as rn}from"./chunk-MPBNEKCQ.js";import{b as Yt,c as Zt,d as Qt}from"./chunk-F26XWM5K.js";import{a as Ht}from"./chunk-4NO7MHS7.js";import{a as En,b as xn,c as In,d as vn}from"./chunk-RYOZTXI7.js";import{a as Kn,b as Dn}from"./chunk-PEUTCG3B.js";import{a as jn}from"./chunk-PEJALHXK.js";import{a as Xt}from"./chunk-SC5M74NM.js";import{A as lr,B as ur,C as pr,D as dr,M as mr,a as Nn,b as Tn,c as Ln,d as _n,e as Un,f as Fn,g as Mn,h as Hn,i as zn,j as Wn,k as Gn,l as Jn,m as qn,n as Yn,o as Zn,p as Xn,q as Qn,r as er,s as tr,t as nr,u as rr,v as or,w as ar,x as ir,y as sr,z as cr}from"./chunk-IZRPJCQW.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as C,c as sn,d as Fe,e as v,f as ke,g as fn,h as yn,i as $}from"./chunk-DSHPAWJQ.js";import{a as S}from"./chunk-NJ3AZYQD.js";import{a as gn,b as Pe,c as $n,d as h,e as An,f as Vn,g as Bn,h as On}from"./chunk-UK2OIPAB.js";import{f as z,k as j,l as we,m as Se,n as Me}from"./chunk-PBNVHBS3.js";import{b as cn,c as ln,d as K,e as un,f as pn,h as dn,j as mn}from"./chunk-VKTFLHCW.js";import{a as on,b as fe,c as f,d as p,e as an,f as ye,g as R,h as ge,i as he,j as E,k as x,l as I}from"./chunk-T3JR2SV6.js";import{a as H}from"./chunk-FUUTGGJS.js";import{a as Nt,b as me,c as M,d as Tt,e as k,f as Lt,g as _t,h as Ut,i as Ft,j as Mt}from"./chunk-2ACBWC7K.js";import{a as Rn}from"./chunk-ODIECDN7.js";import{VersionOperator as Ni}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Or,readFileSync as Dr}from"fs";import{homedir as Nr}from"os";import{join as Tr}from"path";import{execFile as kr}from"child_process";import{promisify as br}from"util";var J=br(kr),q="kanonak",Y="/usr/bin/security",A=class{async get(e){let t=l(e);try{let{stdout:r}=await J(Y,["find-generic-password","-s",q,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
2
2
  Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if(Ge(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${Z(r)}
3
3
  The Keychain may be locked or inaccessible.
4
4
  Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let r=l(e),o=JSON.stringify(t);try{await J(Y,["add-generic-password","-s",q,"-a",r,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${r}': ${Z(a)}
5
5
  Ensure the Keychain is unlocked and the CLI has write permission.
6
6
  On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await J(Y,["delete-generic-password","-s",q,"-a",t],{timeout:1e4})}catch(r){if(Ge(r,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${Z(r)}
7
7
  The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await J(Y,["dump-keychain"],{timeout:1e4}),t=[],r=!1;for(let o of e.split(`
8
- `))if(o.includes(`"svce"<blob>="${q}"`)&&(r=!0),r&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&t.push(a[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${Z(e)}`),[]}}};function Ge(n,e){return typeof n=="object"&&n!==null&&"code"in n&&n.code===e}function Z(n){return n instanceof Error?n.message:String(n)}import{execFile as br}from"child_process";import{promisify as Pr}from"util";var wr=Pr(br),X="kanonak:",A=class{async get(e){let t=X+l(e),r=`
8
+ `))if(o.includes(`"svce"<blob>="${q}"`)&&(r=!0),r&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&t.push(a[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${Z(e)}`),[]}}};function Ge(n,e){return typeof n=="object"&&n!==null&&"code"in n&&n.code===e}function Z(n){return n instanceof Error?n.message:String(n)}import{execFile as Pr}from"child_process";import{promisify as wr}from"util";var Sr=wr(Pr),X="kanonak:",V=class{async get(e){let t=X+l(e),r=`
9
9
  ${ee}
10
10
  $target = [Console]::In.ReadLine()
11
11
  $ptr = [IntPtr]::Zero
@@ -41,7 +41,7 @@ ${ee}
41
41
  $target = [Console]::In.ReadLine()
42
42
  [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await Q(r,t)}catch{}}async list(){let e=`
43
43
  ${ee}
44
- ${Sr}
44
+ ${Cr}
45
45
  $prefix = [Console]::In.ReadLine()
46
46
  $count = 0
47
47
  $pCreds = [IntPtr]::Zero
@@ -56,7 +56,7 @@ if ([CredMan]::CredEnumerate($null, 0, [ref]$count, [ref]$pCreds)) {
56
56
  }
57
57
  [CredMan]::CredFree($pCreds)
58
58
  }`;try{let{stdout:t}=await Q(e,X);return t.trim().split(`
59
- `).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function Q(n,e){for(let t of["pwsh","powershell"])try{return await wr(t,["-NoProfile","-NonInteractive","-Command",n],{timeout:15e3,...e!==void 0&&{input:e}})}catch(r){if(t==="powershell")throw r}throw new Error("Neither pwsh nor powershell found")}var ee=`
59
+ `).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function Q(n,e){for(let t of["pwsh","powershell"])try{return await Sr(t,["-NoProfile","-NonInteractive","-Command",n],{timeout:15e3,...e!==void 0&&{input:e}})}catch(r){if(t==="powershell")throw r}throw new Error("Neither pwsh nor powershell found")}var ee=`
60
60
  Add-Type -TypeDefinition @"
61
61
  using System;
62
62
  using System.Runtime.InteropServices;
@@ -87,13 +87,13 @@ public class CredMan {
87
87
  [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
88
88
  public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
89
89
  }
90
- "@`,Sr="";import{execFile as Cr,spawn as Rr}from"child_process";import{promisify as Er}from"util";var ne=Er(Cr),te="kanonak",B=class{async get(e){let t=l(e);try{let{stdout:r}=await ne("secret-tool",["lookup","service",te,"publisher",t],{timeout:1e4}),o=r.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let r=l(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=Rr("secret-tool",["store","--label",`Kanonak: ${r}`,"service",te,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",c=>{c===0?a():i(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",i)})}async remove(e){let t=l(e);try{await ne("secret-tool",["clear","service",te,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await ne("secret-tool",["search","service",te],{timeout:1e4}),t=[];for(let r of e.split(`
91
- `)){let o=r.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function Re(){try{return await ne("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Je,mkdirSync as qe,readFileSync as Ye,writeFileSync as Ze}from"fs";import{createCipheriv as xr,createDecipheriv as Ir,randomBytes as Xe}from"crypto";import{homedir as vr}from"os";import{join as Ie,dirname as Qe}from"path";var tt=Ie(vr(),".config","kanonak"),O=Ie(tt,"keyring.key"),re=Ie(tt,"credentials.enc"),et="aes-256-gcm",Ee=32,b=12,xe=16,D=class{async get(e){let t=this.loadStore(),r=l(e);return t[r]??null}async store(e,t){let r=this.loadStore(),o=l(e);r[o]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=l(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Je(re))return{};try{let e=this.getOrCreateKey(),t=Ye(re);if(t.length<b+xe)return{};let r=t.subarray(0,b),o=t.subarray(b,b+xe),a=t.subarray(b+xe),i=Ir(et,e,r);i.setAuthTag(o);let s=Buffer.concat([i.update(a),i.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),r=Xe(b),o=xr(et,t,r),a=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([o.update(a),o.final()]),s=o.getAuthTag(),c=Buffer.concat([r,s,i]);qe(Qe(re),{recursive:!0}),Ze(re,c,{mode:384})}getOrCreateKey(){if(Je(O)){let t=Ye(O);if(t.length!==Ee)throw new Error(`Credential keyring key is corrupted (expected ${Ee} bytes, got ${t.length}). Delete ${O} and re-authenticate.`);return t}let e=Xe(Ee);return qe(Qe(O),{recursive:!0}),Ze(O,e,{mode:384}),e}};import{execFile as Kr}from"child_process";import{promisify as $r}from"util";var jr=$r(Kr),nt=3e4,N=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(r){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${oe(r)}
90
+ "@`,Cr="";import{execFile as Rr,spawn as Er}from"child_process";import{promisify as xr}from"util";var ne=xr(Rr),te="kanonak",B=class{async get(e){let t=l(e);try{let{stdout:r}=await ne("secret-tool",["lookup","service",te,"publisher",t],{timeout:1e4}),o=r.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let r=l(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=Er("secret-tool",["store","--label",`Kanonak: ${r}`,"service",te,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",c=>{c===0?a():i(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",i)})}async remove(e){let t=l(e);try{await ne("secret-tool",["clear","service",te,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await ne("secret-tool",["search","service",te],{timeout:1e4}),t=[];for(let r of e.split(`
91
+ `)){let o=r.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function Re(){try{return await ne("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Je,mkdirSync as qe,readFileSync as Ye,writeFileSync as Ze}from"fs";import{createCipheriv as Ir,createDecipheriv as vr,randomBytes as Xe}from"crypto";import{homedir as Kr}from"os";import{join as Ie,dirname as Qe}from"path";var tt=Ie(Kr(),".config","kanonak"),O=Ie(tt,"keyring.key"),re=Ie(tt,"credentials.enc"),et="aes-256-gcm",Ee=32,b=12,xe=16,D=class{async get(e){let t=this.loadStore(),r=l(e);return t[r]??null}async store(e,t){let r=this.loadStore(),o=l(e);r[o]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=l(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Je(re))return{};try{let e=this.getOrCreateKey(),t=Ye(re);if(t.length<b+xe)return{};let r=t.subarray(0,b),o=t.subarray(b,b+xe),a=t.subarray(b+xe),i=vr(et,e,r);i.setAuthTag(o);let s=Buffer.concat([i.update(a),i.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),r=Xe(b),o=Ir(et,t,r),a=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([o.update(a),o.final()]),s=o.getAuthTag(),c=Buffer.concat([r,s,i]);qe(Qe(re),{recursive:!0}),Ze(re,c,{mode:384})}getOrCreateKey(){if(Je(O)){let t=Ye(O);if(t.length!==Ee)throw new Error(`Credential keyring key is corrupted (expected ${Ee} bytes, got ${t.length}). Delete ${O} and re-authenticate.`);return t}let e=Xe(Ee);return qe(Qe(O),{recursive:!0}),Ze(O,e,{mode:384}),e}};import{execFile as $r}from"child_process";import{promisify as jr}from"util";var Ar=jr($r),nt=3e4,N=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(r){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${oe(r)}
92
92
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
93
93
  Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let r=l(e);try{await this.runHelper("store",{publisher:r,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${r}': ${oe(o)}
94
- Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${oe(r)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${oe(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await jr(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:nt});return r}catch(r){throw Vr(r)?new Error(`Credential helper not found at '${this.helperPath}'.
95
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Ar(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${nt/1e3}s on '${e}'.
96
- The helper may be waiting for authentication to an external vault.`):r}}};function oe(n){return n instanceof Error?n.message:String(n)}function Vr(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"}function Ar(n){return n instanceof Error&&"killed"in n&&n.killed}var ve=Nr(Dr(),".kanonak","config.json"),ae=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=Tr(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!G(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=_r();return e.credentialHelper?new N(e.credentialHelper):process.platform==="darwin"?new V:process.platform==="win32"?new A:await Re()?new B:new D}};function Tr(n){let t="KANONAK_TOKEN_"+l(n).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function _r(){if(!Br(ve))return{};try{return JSON.parse(Or(ve,"utf-8"))}catch(n){let e=n instanceof Error?n.message:String(n);return console.warn(` Warning: Failed to parse ${ve}: ${e}
97
- Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Lr,createPrivateKey as Ur,generateKeyPairSync as Fr,randomUUID as Mr,sign as Hr}from"crypto";function ot(){let{publicKey:n,privateKey:e}=Fr("ec",{namedCurve:"P-256"});return{publicKey:n.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function T(n,e,t,r,o,a){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Mr(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Lr("sha256").update(o).digest("base64url")),a&&(s.nonce=a),zr(i,s,n)}function at(n){return!n||n.length===0?!1:n.some(e=>e.toUpperCase()==="ES256")}function zr(n,e,t){let r=rt(JSON.stringify(n)),o=rt(JSON.stringify(e)),a=`${r}.${o}`,i=Ur({key:t,format:"jwk"}),c=Hr("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${c}`}function rt(n){return Buffer.from(n,"utf-8").toString("base64url")}function it(n){let e=new Map;return async(t,r,o="GET")=>{if(!n)return fetch(t,{method:o});let a=await n.getCredential(r);if(!a?.accessToken)return fetch(t,{method:o});W(a)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let i={};if(a.dpopKeyPair){let c=e.get(r);try{let u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.Authorization=`DPoP ${a.accessToken}`,i.DPoP=u}catch(u){let d=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${r}': ${d}
98
- The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${a.accessToken}`}}else i.Authorization=`Bearer ${a.accessToken}`;let s=await fetch(t,{method:o,headers:i});if(s.status===401&&a.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(r,c);try{let u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=u,s=await fetch(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as Wr,writeFileSync as Gr,existsSync as Jr}from"fs";import{createHash as qr}from"crypto";import st from"js-yaml";var ct="kanonak.lock",Yr=`# This file is generated by Kanonak CLI. Do not edit manually.
99
- `;function lt(n=ct){if(!Jr(n))return null;let e=Wr(n,"utf-8"),t=st.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function ut(n,e=ct){n.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(n.packages).sort())t[o]=n.packages[o];n.packages=t;let r=st.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Gr(e,Yr+r,"utf-8")}function pt(n){return`sha256:${qr("sha256").update(n).digest("hex")}`}import*as Ae from"js-yaml";import{createHash as Xr}from"crypto";function Ke(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}function $e(n){return n.subjects.map(e=>{let t=new f,r=e.uri.lastIndexOf("/");return t.namespace=e.uri.slice(0,r),t.name=e.uri.slice(r+1),t.statement=(e.statements??[]).map(o=>mt(o.predicate,o.value)),t})}function dt(n,e,t){let r=new R;return r.predicate=p.parse(n),r.object=t,e&&(r.carrier=e,r.lexical=t),r}function mt(n,e){if("lit"in e)return dt(n,v(H.parse(e.datatype)),e.lit);if("raw"in e)return dt(n,void 0,e.raw);if("ref"in e){let t=new E;return t.predicate=p.parse(n),t.object=p.parse(e.ref),t}if("embed"in e){let t=new x;return t.predicate=p.parse(n),t.object=ft(e.embed),t}if("list"in e){let t=new I;return t.predicate=p.parse(n),t.object=e.list.map(Zr),t}throw new Error(`canonical input: unknown value shape ${JSON.stringify(e)}`)}function ft(n){let e=new y;return n.name&&(e.name=n.name),e.statement=(n.statements??[]).map(t=>mt(t.predicate,t.value)),e}function Zr(n){if("ref"in n)return p.parse(n.ref);if("embed"in n)return ft(n.embed);let e=new C;if("lit"in n){e.value=n.lit;let t=v(H.parse(n.datatype));t&&(e.carrier=t,e.lexical=n.lit)}else if("raw"in n)e.value=n.raw;else throw new Error(`canonical input: unknown list item shape ${JSON.stringify(n)}`);return e}var gt="1",yt=new TextEncoder;function ht(n,e){let t=yt.encode(n),r=yt.encode(e),o=Math.min(t.length,r.length);for(let a=0;a<o;a++)if(t[a]!==r[a])return t[a]-r[a];return t.length-r.length}function je(n){let e=Ke(n)?$e(n):n,t=[];for(let o of e)o instanceof f&&t.push(Qr(o));return t.sort((o,a)=>ht(o.uri,a.uri)),JSON.stringify({subjects:t})}function ie(n){let e=Ke(n)?$e(n):n,t=je(e);return`sha256:${Xr("sha256").update(t,"utf8").digest("hex")}`}function Qr(n){let e=ao(n),t=Ve(n.statement);return{uri:e,statements:t}}function Ve(n){let e=[];for(let t of n){let r=eo(t);r&&e.push(r)}return e.sort((t,r)=>ht(t.predicate,r.predicate)),e}function eo(n){let e=oo(n);if(!e)return;let t=to(n);if(t)return ro(e,t)}function to(n){if(n instanceof ye&&n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.object))};if(n instanceof R)return{type:"string",value:n.object};if(n instanceof ge)return{type:"number",value:wt(n.object)};if(n instanceof he)return{type:"boolean",value:n.object};if(n instanceof E)return{type:"ref",value:bt(n.object)};if(n instanceof x){let e=n.object;return kt(e)}if(n instanceof I)return{type:"list",items:n.object.map(no)}}function kt(n){let e=Ve(n.statement);return n.name&&n.name.length>0?{type:"embedded",name:n.name,statements:e}:{type:"embedded",statements:e}}function no(n){if(n instanceof p)return{type:"ref",value:bt(n)};if(n instanceof y)return kt(n);if(n instanceof C){if(n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.value))};let e=n.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:wt(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(n instanceof fe)return{type:"embedded",statements:Ve(n.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${n.constructor?.name??typeof n}); add canonicalization support before hashing data that contains it`)}function ro(n,e){switch(e.type){case"string":return{predicate:n,type:"string",value:e.value};case"number":return{predicate:n,type:"number",value:e.value};case"boolean":return{predicate:n,type:"boolean",value:e.value};case"typed":return{predicate:n,type:"typed",carrier:e.carrier,value:e.value};case"ref":return{predicate:n,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:n,type:"embedded",name:e.name,statements:e.statements}:{predicate:n,type:"embedded",statements:e.statements};case"list":return{predicate:n,type:"list",items:e.items}}}function oo(n){let e=n.predicate;if(e)return Pt(e.subject)}function ao(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function bt(n){return Pt(n.subject)}function Pt(n){let e=n.version;return e&&typeof e.major=="number"?`${n.publisher}/${n.package_}@${e.major}.${e.minor}.${e.patch}/${n.name}`:`${n.publisher}/${n.package_}/${n.name}`}function wt(n){if(Number.isNaN(n))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(n))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(n,-0)?"0":String(n)}import{VersionOperator as St}from"@kanonak-protocol/types/document/models/enums";var io="0.0.0",P=class{constructor(e,t=new S,r){this.repository=e;this.parser=t;this.objectParser=r??new $(this.parser)}repository;parser;objectParser;imports(){return new _}serializeValue(e,t){return Et(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Be(r),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=r),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:Rt(s),contentHash:r,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=o),Object.assign(r,e.header??{}),r.imports=t;let a={[e.name]:r,...e.body},i=this.dump(a),s={yaml:i,byteCount:Rt(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ae.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[Ct]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(Ae.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Me(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==Ct);for(let u of c)u.namespace="ephemeral";return ie(c)}},Ct="__pkgbuilder_probe__";function Rt(n){return new TextEncoder().encode(n).length}function Be(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var _=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=St.Major){let i=`${e}/${t}@${r}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:a}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,o){return`${this.ensure(e,t,io,o??t,St.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let o=e.get(r.publisher)??[];o.push(r),e.set(r.publisher,o)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:me(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=L(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function Et(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof p)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>Et(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(so(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function L(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function so(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var se=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,o){let a=`${t}/${r}@${k(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,r,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let o={operator:t.versionOperator,version:t.version},a=await r.resolveVersion(e,t.packageName,o);return a?this.produceCached(r,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=Pe(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let o=r.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Oe={async authorize(){return{allowed:!0}}},De={async record(){}},U=class extends Error{constructor(t,r){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},ce=class{inner;ctx;policy;meter;constructor(e,t,r=Oe,o=De){this.inner=e,this.ctx=t,this.policy=r,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let o={publisher:e,package_:t,version:r};await this.assertAllowed(o);let a=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new U(e,t.reason)}};var m="kanonak.org",g="view",xt="core-kanonak",co={publisher:m,package_:g,name:"rootView"},lo={publisher:m,package_:g,name:"bind"},uo={publisher:m,package_:g,name:"produces"},po={publisher:m,package_:g,name:"projections"},mo={publisher:m,package_:g,name:"where"},fo={publisher:m,package_:g,name:"value"},yo={publisher:m,package_:g,name:"as"},le=class{constructor(e,t=new S){this.repository=e;this.parser=t;this.objectParser=new $(this.parser),this.builder=new P(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(r,e),a=j(o,lo);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=j(o,uo);if(!i)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=go(o),c=It(r,m,xt),u=It(r,m,g),d=this.builder.imports(),ue=d.ensure(m,xt,c,"ck"),Kt=d.ensure(m,g,u,"v"),$t=d.ref(i),jt=new We(this.repository,this.parser,this.objectParser),Ne=new He(jt,r),Vt=this.readProjections(r,o),At=bo(o,mo),Bt=this.findInstances(r,a,await this.reason(t)),Te={},Ot=new Set;for(let F of Bt){if(!await this.passesWhere(Ne,r,At,F))continue;let de={type:$t};for(let Le of Vt){let Dt=await this.evaluateValue(Ne,r,Le.value,F),Ue=this.builder.serializeValue(vt(Dt),d);Ue!==void 0&&(de[d.ref(Le.as)]=Ue)}let _e=h(F);_e&&(de[`${Kt}.derivedFrom`]=d.ref(_e)),Te[this.rowName(F,Ot)]=de}let pe={};t.resolvedAt&&(pe[`${ue}.resolvedAt`]=t.resolvedAt),t.invocationId&&(pe[`${ue}.id`]=t.invocationId);let w=await this.builder.buildContentAddressed({publisher:s,book:d,body:Te,contentHashProperty:`${ue}.contentHash`,header:pe});return{yaml:w.yaml,contentHash:w.contentHash,packageName:w.packageName,publisher:w.publisher,rowCount:w.resourceCount}}resolveView(e,t){let r=z(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=j(r,co);if(o){let a=z(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return r}readProjections(e,t){let r=[];for(let o of Se(t,po)){let a=o instanceof y?o:o instanceof p?z(e,o.subject):void 0;if(!a)continue;let i=we(a,fo),s=j(a,yo);i&&s&&r.push({value:i,as:s})}return r}async reason(e){return new be({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let o=ko(e),a=[],i=new Set;for(let s of r.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let c=o.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=K(h(s)),d=K(h(c));return u<d?-1:u>d?1:0}),a}async passesWhere(e,t,r,o){for(let a of r){let i=await this.evaluateValue(e,t,a,o);if(!Po(i))return!1}return!0}async evaluateValue(e,t,r,o){let a=ze(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let r=L(e.name)||"row",o=r,a=2;for(;t.has(o);)o=`${r}-${a++}`;return t.add(o),o}};function vt(n){return Ce(n)?n.value:Array.isArray(n)?n.map(vt):n}function go(n){let e=h(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function It(n,e,t){let r=ho(n,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function ho(n,e,t){let r;for(let o of n){if(!(o instanceof f))continue;let a=h(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!r||M(a.version,r)>0)&&(r=a.version)}return r?k(r):void 0}function ko(n){let e=new Map,t=new Map;for(let r of n){if(!(r instanceof f))continue;let o=h(r);if(!o||!o.version)continue;let a=K(o),i=t.get(a);(!i||M(o.version,i)>0)&&(t.set(a,o.version),e.set(a,r))}return e}function bo(n,e){let t=we(n,e);return t?[t]:Se(n,e).filter(r=>r instanceof y)}function Po(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Ce(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{or as AmbiguousReferenceRule,he as BooleanStatement,gt as CANONICAL_FORM_VERSION,Fe as Carrier,ur as ClassDefinitionRule,qn as ClassHierarchyCycleRule,Gt as CompositeKanonakDocumentRepository,ae as CredentialStore,fe as DefinedKanonak,nr as DefinitionPropertyReferenceRule,Wt as DocumentLocation,hn as EdgeType,y as EmbeddedKanonak,Wn as EmbeddedKanonakTypeRule,x as EmbeddedStatement,U as EntitlementDeniedError,ce as EntitlementProducer,zt as FileSystemKanonakDocumentRepository,Cn as GitIgnoreFilter,kn as GraphBuilder,Qt as HttpKanonakDocumentRepository,_ as ImportBook,Gn as ImportExistenceRule,Ht as InMemoryKanonakDocumentRepository,tr as InstancePropertyReferenceRule,rn as Kanonak,En as KanonakDocumentPositions,$ as KanonakObjectParser,dr as KanonakObjectValidator,S as KanonakParser,H as KanonakUri,vn as KanonakUriBuilder,$n as KanonakUrlResolver,dn as KanonakVocabulary,I as ListStatement,C as LiteralKanonak,en as LocalFirstRepository,yr as LookRenderer,pr as MarkdownLinkRule,an as MarkdownStatement,er as NamespaceImportCycleRule,Un as NamespacePrefixRule,gn as NodeType,ge as NumberStatement,wn as OWL_RL_CLASSIFICATION_RULES,ir as ObjectPropertyImportRule,sr as ObjectPropertyValueValidationRule,Tn as OntologyValidationError,Dn as OntologyValidationResult,P as PackageBuilder,zn as PackageHeaderRule,se as ProducerRepository,cr as PropertyDomainRule,Yn as PropertyHierarchyCycleRule,Rn as PropertyMetadata,ar as PropertyRangeReferenceRule,Zn as PropertyRangeRequiredRule,Mn as PropertyTypeSpecificityRule,lr as PropertyValueTypeRule,Yt as PublisherConfigResolver,Zt as PublisherIndex,Pn as RDFS_RULES,be as Reasoner,Sn as ReasoningResult,p as ReferenceKanonak,E as ReferenceStatement,qt as RepositoryFactory,Fn as ResourceNamingRule,sn as ResourceResolver,yn as ResourceTypeClassifier,ye as ScalarStatement,on as Statement,R as StringStatement,Xn as SubClassOfReferenceRule,Qn as SubPropertyOfReferenceRule,f as SubjectKanonak,Hn as SubjectKanonakTypeRequiredRule,bn as TripleStore,cn as TypeResolver,Jn as UnresolvedReferenceRule,Ln as ValidationCache,_n as ValidationContext,Nn as ValidationSeverity,Di as VersionOperator,le as ViewMaterializer,rr as XsdImportRule,Oe as allowAllPolicy,Xt as assertPackageIdentity,nn as buildLocalFirstRepository,gr as buildOntologyModel,je as canonicalForm,ie as canonicalHash,v as carrierOf,tn as collectKanonakFiles,M as compareVersions,pt as computeIntegrity,Be as contentAddressedName,Bn as contextTypesOf,it as createAuthenticatedFetch,T as createDPoPProof,_t as createVersion,fn as extractMarkdownLinks,mr as findDerivation,On as findInstancesByType,mn as findMalformedReferences,In as findMarkdownLinkAt,Kn as formatKanonakAddress,k as formatVersion,ot as generateDPoPKeyPair,Jt as getGlobalCachePath,G as hasValidToken,Ut as isCompatibleVersion,W as isExpired,Ft as isMajorCompatible,lt as loadLockFile,ln as makeUriKey,De as noopMeter,l as normalizeHost,Pe as parseKanonakAddress,Lt as parseVersionString,xn as parseWithPositions,Mt as pickHighestDocument,Vn as propertiesInScope,fr as resolveDisplayValue,An as resolvePropertyStep,L as sanitizeName,ut as saveLockFile,at as serverSupportsDPoP,h as subjectUri,jn as superClassChain,un as tripleKey,K as uriKey,pn as uriTriple,Nt as versionOperatorFromChar,me as versionOperatorToChar,Tt as versionsEqual};
94
+ Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${oe(r)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${oe(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await Ar(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:nt});return r}catch(r){throw Vr(r)?new Error(`Credential helper not found at '${this.helperPath}'.
95
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Br(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${nt/1e3}s on '${e}'.
96
+ The helper may be waiting for authentication to an external vault.`):r}}};function oe(n){return n instanceof Error?n.message:String(n)}function Vr(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"}function Br(n){return n instanceof Error&&"killed"in n&&n.killed}var ve=Tr(Nr(),".kanonak","config.json"),ae=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=Lr(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!G(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=_r();return e.credentialHelper?new N(e.credentialHelper):process.platform==="darwin"?new A:process.platform==="win32"?new V:await Re()?new B:new D}};function Lr(n){let t="KANONAK_TOKEN_"+l(n).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function _r(){if(!Or(ve))return{};try{return JSON.parse(Dr(ve,"utf-8"))}catch(n){let e=n instanceof Error?n.message:String(n);return console.warn(` Warning: Failed to parse ${ve}: ${e}
97
+ Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Ur,createPrivateKey as Fr,generateKeyPairSync as Mr,randomUUID as Hr,sign as zr}from"crypto";function ot(){let{publicKey:n,privateKey:e}=Mr("ec",{namedCurve:"P-256"});return{publicKey:n.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function T(n,e,t,r,o,a){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Hr(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Ur("sha256").update(o).digest("base64url")),a&&(s.nonce=a),Wr(i,s,n)}function at(n){return!n||n.length===0?!1:n.some(e=>e.toUpperCase()==="ES256")}function Wr(n,e,t){let r=rt(JSON.stringify(n)),o=rt(JSON.stringify(e)),a=`${r}.${o}`,i=Fr({key:t,format:"jwk"}),c=zr("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${c}`}function rt(n){return Buffer.from(n,"utf-8").toString("base64url")}function it(n){let e=new Map;return async(t,r,o="GET")=>{if(!n)return fetch(t,{method:o});let a=await n.getCredential(r);if(!a?.accessToken)return fetch(t,{method:o});W(a)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let i={};if(a.dpopKeyPair){let c=e.get(r);try{let u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.Authorization=`DPoP ${a.accessToken}`,i.DPoP=u}catch(u){let d=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${r}': ${d}
98
+ The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${a.accessToken}`}}else i.Authorization=`Bearer ${a.accessToken}`;let s=await fetch(t,{method:o,headers:i});if(s.status===401&&a.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(r,c);try{let u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=u,s=await fetch(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as Gr,writeFileSync as Jr,existsSync as qr}from"fs";import{createHash as Yr}from"crypto";import st from"js-yaml";var ct="kanonak.lock",Zr=`# This file is generated by Kanonak CLI. Do not edit manually.
99
+ `;function lt(n=ct){if(!qr(n))return null;let e=Gr(n,"utf-8"),t=st.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function ut(n,e=ct){n.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(n.packages).sort())t[o]=n.packages[o];n.packages=t;let r=st.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Jr(e,Zr+r,"utf-8")}function pt(n){return`sha256:${Yr("sha256").update(n).digest("hex")}`}import*as Ve from"js-yaml";import{createHash as Qr}from"crypto";function Ke(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}function $e(n){return n.subjects.map(e=>{let t=new f,r=e.uri.lastIndexOf("/");return t.namespace=e.uri.slice(0,r),t.name=e.uri.slice(r+1),t.statement=(e.statements??[]).map(o=>mt(o.predicate,o.value)),t})}function dt(n,e,t){let r=new R;return r.predicate=p.parse(n),r.object=t,e&&(r.carrier=e,r.lexical=t),r}function mt(n,e){if("lit"in e)return dt(n,v(H.parse(e.datatype)),e.lit);if("raw"in e)return dt(n,void 0,e.raw);if("ref"in e){let t=new E;return t.predicate=p.parse(n),t.object=p.parse(e.ref),t}if("embed"in e){let t=new x;return t.predicate=p.parse(n),t.object=ft(e.embed),t}if("list"in e){let t=new I;return t.predicate=p.parse(n),t.object=e.list.map(Xr),t}throw new Error(`canonical input: unknown value shape ${JSON.stringify(e)}`)}function ft(n){let e=new y;return n.name&&(e.name=n.name),e.statement=(n.statements??[]).map(t=>mt(t.predicate,t.value)),e}function Xr(n){if("ref"in n)return p.parse(n.ref);if("embed"in n)return ft(n.embed);let e=new C;if("lit"in n){e.value=n.lit;let t=v(H.parse(n.datatype));t&&(e.carrier=t,e.lexical=n.lit)}else if("raw"in n)e.value=n.raw;else throw new Error(`canonical input: unknown list item shape ${JSON.stringify(n)}`);return e}var gt="1",yt=new TextEncoder;function ht(n,e){let t=yt.encode(n),r=yt.encode(e),o=Math.min(t.length,r.length);for(let a=0;a<o;a++)if(t[a]!==r[a])return t[a]-r[a];return t.length-r.length}function je(n){let e=Ke(n)?$e(n):n,t=[];for(let o of e)o instanceof f&&t.push(eo(o));return t.sort((o,a)=>ht(o.uri,a.uri)),JSON.stringify({subjects:t})}function ie(n){let e=Ke(n)?$e(n):n,t=je(e);return`sha256:${Qr("sha256").update(t,"utf8").digest("hex")}`}function eo(n){let e=io(n),t=Ae(n.statement);return{uri:e,statements:t}}function Ae(n){let e=[];for(let t of n){let r=to(t);r&&e.push(r)}return e.sort((t,r)=>ht(t.predicate,r.predicate)),e}function to(n){let e=ao(n);if(!e)return;let t=no(n);if(t)return oo(e,t)}function no(n){if(n instanceof ye&&n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.object))};if(n instanceof R)return{type:"string",value:n.object};if(n instanceof ge)return{type:"number",value:wt(n.object)};if(n instanceof he)return{type:"boolean",value:n.object};if(n instanceof E)return{type:"ref",value:bt(n.object)};if(n instanceof x){let e=n.object;return kt(e)}if(n instanceof I)return{type:"list",items:n.object.map(ro)}}function kt(n){let e=Ae(n.statement);return n.name&&n.name.length>0?{type:"embedded",name:n.name,statements:e}:{type:"embedded",statements:e}}function ro(n){if(n instanceof p)return{type:"ref",value:bt(n)};if(n instanceof y)return kt(n);if(n instanceof C){if(n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.value))};let e=n.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:wt(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(n instanceof fe)return{type:"embedded",statements:Ae(n.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${n.constructor?.name??typeof n}); add canonicalization support before hashing data that contains it`)}function oo(n,e){switch(e.type){case"string":return{predicate:n,type:"string",value:e.value};case"number":return{predicate:n,type:"number",value:e.value};case"boolean":return{predicate:n,type:"boolean",value:e.value};case"typed":return{predicate:n,type:"typed",carrier:e.carrier,value:e.value};case"ref":return{predicate:n,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:n,type:"embedded",name:e.name,statements:e.statements}:{predicate:n,type:"embedded",statements:e.statements};case"list":return{predicate:n,type:"list",items:e.items}}}function ao(n){let e=n.predicate;if(e)return Pt(e.subject)}function io(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function bt(n){return Pt(n.subject)}function Pt(n){let e=n.version;return e&&typeof e.major=="number"?`${n.publisher}/${n.package_}@${e.major}.${e.minor}.${e.patch}/${n.name}`:`${n.publisher}/${n.package_}/${n.name}`}function wt(n){if(Number.isNaN(n))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(n))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(n,-0)?"0":String(n)}import{VersionOperator as St}from"@kanonak-protocol/types/document/models/enums";var so="0.0.0",P=class{constructor(e,t=new S,r){this.repository=e;this.parser=t;this.objectParser=r??new $(this.parser)}repository;parser;objectParser;imports(){return new L}serializeValue(e,t){return Et(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Be(r),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=r),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:Rt(s),contentHash:r,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=o),Object.assign(r,e.header??{}),r.imports=t;let a={[e.name]:r,...e.body},i=this.dump(a),s={yaml:i,byteCount:Rt(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ve.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[Ct]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(Ve.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Me(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==Ct);for(let u of c)u.namespace="ephemeral";return ie(c)}},Ct="__pkgbuilder_probe__";function Rt(n){return new TextEncoder().encode(n).length}function Be(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var L=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=St.Major){let i=`${e}/${t}@${r}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:a}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,o){return`${this.ensure(e,t,so,o??t,St.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let o=e.get(r.publisher)??[];o.push(r),e.set(r.publisher,o)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:me(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=_(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function Et(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof p)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>Et(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(co(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function _(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function co(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var se=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,o){let a=`${t}/${r}@${k(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,r,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let o={operator:t.versionOperator,version:t.version},a=await r.resolveVersion(e,t.packageName,o);return a?this.produceCached(r,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=Pe(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let o=r.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Oe={async authorize(){return{allowed:!0}}},De={async record(){}},U=class extends Error{constructor(t,r){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},ce=class{inner;ctx;policy;meter;constructor(e,t,r=Oe,o=De){this.inner=e,this.ctx=t,this.policy=r,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let o={publisher:e,package_:t,version:r};await this.assertAllowed(o);let a=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new U(e,t.reason)}};var m="kanonak.org",g="view",xt="core-kanonak",lo={publisher:m,package_:g,name:"rootView"},uo={publisher:m,package_:g,name:"bind"},po={publisher:m,package_:g,name:"produces"},mo={publisher:m,package_:g,name:"projections"},fo={publisher:m,package_:g,name:"where"},yo={publisher:m,package_:g,name:"value"},go={publisher:m,package_:g,name:"as"},le=class{constructor(e,t=new S){this.repository=e;this.parser=t;this.objectParser=new $(this.parser),this.builder=new P(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(r,e),a=j(o,uo);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=j(o,po);if(!i)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=ho(o),c=It(r,m,xt),u=It(r,m,g),d=this.builder.imports(),ue=d.ensure(m,xt,c,"ck"),Kt=d.ensure(m,g,u,"v"),$t=d.ref(i),jt=new We(this.repository,this.parser,this.objectParser),Ne=new He(jt,r),At=this.readProjections(r,o),Vt=Po(o,fo),Bt=this.findInstances(r,a,await this.reason(t)),Te={},Ot=new Set;for(let F of Bt){if(!await this.passesWhere(Ne,r,Vt,F))continue;let de={type:$t};for(let _e of At){let Dt=await this.evaluateValue(Ne,r,_e.value,F),Ue=this.builder.serializeValue(vt(Dt),d);Ue!==void 0&&(de[d.ref(_e.as)]=Ue)}let Le=h(F);Le&&(de[`${Kt}.derivedFrom`]=d.ref(Le)),Te[this.rowName(F,Ot)]=de}let pe={};t.resolvedAt&&(pe[`${ue}.resolvedAt`]=t.resolvedAt),t.invocationId&&(pe[`${ue}.id`]=t.invocationId);let w=await this.builder.buildContentAddressed({publisher:s,book:d,body:Te,contentHashProperty:`${ue}.contentHash`,header:pe});return{yaml:w.yaml,contentHash:w.contentHash,packageName:w.packageName,publisher:w.publisher,rowCount:w.resourceCount}}resolveView(e,t){let r=z(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=j(r,lo);if(o){let a=z(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return r}readProjections(e,t){let r=[];for(let o of Se(t,mo)){let a=o instanceof y?o:o instanceof p?z(e,o.subject):void 0;if(!a)continue;let i=we(a,yo),s=j(a,go);i&&s&&r.push({value:i,as:s})}return r}async reason(e){return new be({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let o=bo(e),a=[],i=new Set;for(let s of r.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let c=o.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=K(h(s)),d=K(h(c));return u<d?-1:u>d?1:0}),a}async passesWhere(e,t,r,o){for(let a of r){let i=await this.evaluateValue(e,t,a,o);if(!wo(i))return!1}return!0}async evaluateValue(e,t,r,o){let a=ze(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let r=_(e.name)||"row",o=r,a=2;for(;t.has(o);)o=`${r}-${a++}`;return t.add(o),o}};function vt(n){return Ce(n)?n.value:Array.isArray(n)?n.map(vt):n}function ho(n){let e=h(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function It(n,e,t){let r=ko(n,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function ko(n,e,t){let r;for(let o of n){if(!(o instanceof f))continue;let a=h(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!r||M(a.version,r)>0)&&(r=a.version)}return r?k(r):void 0}function bo(n){let e=new Map,t=new Map;for(let r of n){if(!(r instanceof f))continue;let o=h(r);if(!o||!o.version)continue;let a=K(o),i=t.get(a);(!i||M(o.version,i)>0)&&(t.set(a,o.version),e.set(a,r))}return e}function Po(n,e){let t=we(n,e);return t?[t]:Se(n,e).filter(r=>r instanceof y)}function wo(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Ce(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{ar as AmbiguousReferenceRule,he as BooleanStatement,gt as CANONICAL_FORM_VERSION,Fe as Carrier,pr as ClassDefinitionRule,Yn as ClassHierarchyCycleRule,Gt as CompositeKanonakDocumentRepository,ae as CredentialStore,fe as DefinedKanonak,rr as DefinitionPropertyReferenceRule,Wt as DocumentLocation,kn as EdgeType,y as EmbeddedKanonak,Gn as EmbeddedKanonakTypeRule,x as EmbeddedStatement,U as EntitlementDeniedError,ce as EntitlementProducer,zt as FileSystemKanonakDocumentRepository,Rn as GitIgnoreFilter,bn as GraphBuilder,Qt as HttpKanonakDocumentRepository,L as ImportBook,Jn as ImportExistenceRule,Ht as InMemoryKanonakDocumentRepository,nr as InstancePropertyReferenceRule,on as Kanonak,xn as KanonakDocumentPositions,$ as KanonakObjectParser,mr as KanonakObjectValidator,S as KanonakParser,H as KanonakUri,Kn as KanonakUriBuilder,jn as KanonakUrlResolver,mn as KanonakVocabulary,I as ListStatement,C as LiteralKanonak,en as LocalFirstRepository,tn as LockAwareRepository,gr as LookRenderer,dr as MarkdownLinkRule,sn as MarkdownStatement,tr as NamespaceImportCycleRule,Fn as NamespacePrefixRule,hn as NodeType,ge as NumberStatement,Sn as OWL_RL_CLASSIFICATION_RULES,sr as ObjectPropertyImportRule,cr as ObjectPropertyValueValidationRule,Ln as OntologyValidationError,Nn as OntologyValidationResult,P as PackageBuilder,Wn as PackageHeaderRule,se as ProducerRepository,lr as PropertyDomainRule,Zn as PropertyHierarchyCycleRule,En as PropertyMetadata,ir as PropertyRangeReferenceRule,Xn as PropertyRangeRequiredRule,Hn as PropertyTypeSpecificityRule,ur as PropertyValueTypeRule,Yt as PublisherConfigResolver,Zt as PublisherIndex,wn as RDFS_RULES,be as Reasoner,Cn as ReasoningResult,p as ReferenceKanonak,E as ReferenceStatement,qt as RepositoryFactory,Mn as ResourceNamingRule,cn as ResourceResolver,gn as ResourceTypeClassifier,ye as ScalarStatement,an as Statement,R as StringStatement,Qn as SubClassOfReferenceRule,er as SubPropertyOfReferenceRule,f as SubjectKanonak,zn as SubjectKanonakTypeRequiredRule,Pn as TripleStore,ln as TypeResolver,qn as UnresolvedReferenceRule,Un as ValidationCache,_n as ValidationContext,Tn as ValidationSeverity,Ni as VersionOperator,le as ViewMaterializer,or as XsdImportRule,Oe as allowAllPolicy,Xt as assertPackageIdentity,rn as buildLocalFirstRepository,hr as buildOntologyModel,je as canonicalForm,ie as canonicalHash,v as carrierOf,nn as collectKanonakFiles,M as compareVersions,pt as computeIntegrity,Be as contentAddressedName,On as contextTypesOf,it as createAuthenticatedFetch,T as createDPoPProof,Lt as createVersion,yn as extractMarkdownLinks,fr as findDerivation,Dn as findInstancesByType,fn as findMalformedReferences,vn as findMarkdownLinkAt,$n as formatKanonakAddress,k as formatVersion,ot as generateDPoPKeyPair,Jt as getGlobalCachePath,G as hasValidToken,Ut as isCompatibleVersion,W as isExpired,Ft as isMajorCompatible,lt as loadLockFile,un as makeUriKey,De as noopMeter,l as normalizeHost,Pe as parseKanonakAddress,_t as parseVersionString,In as parseWithPositions,Mt as pickHighestDocument,Vn as propertiesInScope,yr as resolveDisplayValue,Bn as resolvePropertyStep,_ as sanitizeName,ut as saveLockFile,at as serverSupportsDPoP,h as subjectUri,An as superClassChain,pn as tripleKey,K as uriKey,dn as uriTriple,Nt as versionOperatorFromChar,me as versionOperatorToChar,Tt as versionsEqual};
@@ -9,11 +9,24 @@ export declare class KanonakParser implements IKanonakParser {
9
9
  private createVersion;
10
10
  private extractMetadata;
11
11
  private extractBody;
12
- private parseNamespace;
13
12
  private parseVersion;
14
13
  private parseImportsV3;
15
- private parseImportsLegacy;
14
+ /**
15
+ * Parse one authored import object (`{ package, match, version, alias? }`)
16
+ * into an {@link Import}. Validates the required fields — a missing
17
+ * `package`/`match`/`version` is an error (never a fabricated default), then
18
+ * delegates to the single {@link makeImport} builder.
19
+ */
16
20
  private parseImportFromEmbeddedObject;
21
+ /**
22
+ * THE single {@link Import} constructor — every import, whether parsed from a
23
+ * document or built by parts ({@link buildImport}), is produced here, so the
24
+ * operator/version/min-max/identity fields are computed one way. `operator`
25
+ * is the character form (`= ~ ^ *`); `version` is a `major.minor.patch`
26
+ * string. No fabricated defaults: callers supply the operator and version
27
+ * (the parser rejects an authored import that omits them).
28
+ */
29
+ private makeImport;
17
30
  /**
18
31
  * Build a single {@link Import} from its parts — the canonical way to
19
32
  * construct one OUTSIDE parsing a document (e.g. to request a seed package
@@ -23,7 +36,6 @@ export declare class KanonakParser implements IKanonakParser {
23
36
  * the character form (`= ~ ^ *`); `version` is a `major.minor.patch` string.
24
37
  */
25
38
  buildImport(packageName: string, operator: string, version: string, publisher?: string): Import;
26
- private parseImport;
27
39
  private parseVersionOperator;
28
40
  private calculateMaxVersion;
29
41
  private serializeImports;
@@ -1 +1 @@
1
- import{a as c,b as d,c as e,d as f}from"../chunk-WBRCKPEH.js";import{i as b}from"../chunk-FSHQVKZ5.js";import{a}from"../chunk-ZYAABYDS.js";import"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{d as KanonakDocumentPositions,b as KanonakObjectParser,a as KanonakParser,c as PropertyMetadata,f as findMarkdownLinkAt,e as parseWithPositions};
1
+ import{a as c,b as d,c as e,d as f}from"../chunk-RYOZTXI7.js";import{i as b}from"../chunk-DSHPAWJQ.js";import{a}from"../chunk-NJ3AZYQD.js";import"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{d as KanonakDocumentPositions,b as KanonakObjectParser,a as KanonakParser,c as PropertyMetadata,f as findMarkdownLinkAt,e as parseWithPositions};
@@ -1 +1 @@
1
- import{a as g,b as h,c as i,d as j,e as k}from"../chunk-B73JY5G4.js";import"../chunk-FSHQVKZ5.js";import"../chunk-ZYAABYDS.js";import{d as a,e as b,f as c,h as d,i as e,j as f}from"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{f as KanonakVocabulary,i as OWL_RL_CLASSIFICATION_RULES,h as RDFS_RULES,k as Reasoner,j as ReasoningResult,g as TripleStore,e as canonicalizeBuiltinUri,b as makeUriKey,c as tripleKey,a as uriKey,d as uriTriple};
1
+ import{a as g,b as h,c as i,d as j,e as k}from"../chunk-RWEGPZ23.js";import"../chunk-DSHPAWJQ.js";import"../chunk-NJ3AZYQD.js";import{d as a,e as b,f as c,h as d,i as e,j as f}from"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{f as KanonakVocabulary,i as OWL_RL_CLASSIFICATION_RULES,h as RDFS_RULES,k as Reasoner,j as ReasoningResult,g as TripleStore,e as canonicalizeBuiltinUri,b as makeUriKey,c as tripleKey,a as uriKey,d as uriTriple};
@@ -0,0 +1,41 @@
1
+ import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
2
+ import type { KanonakDocument, Import, DocumentReference } from '@kanonak-protocol/types/document/models/types';
3
+ import type { LockFile } from '../lock/LockFile.js';
4
+ /**
5
+ * A repository decorator that resolves versions through a `kanonak.lock`, so a
6
+ * package's identity is computed over its LOCKED closure rather than a freshly
7
+ * floated one (typescript#59). Without this, `^`/`~`/`*` imports — and the
8
+ * implicit `core-kanonak` every package carries via `type: Package` — resolve to
9
+ * the highest version that happens to be installed, so identical bytes hash
10
+ * differently across environments.
11
+ *
12
+ * It pins the two resolution seams the canonical form flows through:
13
+ * - `getHighestCompatibleVersionAsync` — explicit imports (via ResourceResolver).
14
+ * - `getDocumentsByNamespaceAsync` — the implicit-foundation version lookup
15
+ * (core-rdf/owl/kanonak) used to stamp re-homed builtins.
16
+ * A locked package resolves to EXACTLY its locked version; an unlocked one
17
+ * floats through the base repository. Everything else passes straight through.
18
+ * (The `--frozen` guarantee — error on an unpinned import — is enforced as a
19
+ * pre-flight check by the caller, because `ResourceResolver` swallows
20
+ * resolution-time throws; this decorator only pins.)
21
+ *
22
+ * Stage 1 (#59): the hash/identity path. Producers that bake locked pins into
23
+ * EphemeralPackages are stage 2.
24
+ */
25
+ export declare class LockAwareRepository implements IKanonakDocumentRepository {
26
+ private readonly base;
27
+ private readonly lock;
28
+ constructor(base: IKanonakDocumentRepository, lock: LockFile);
29
+ /** The locked version string for `publisher/packageName`, if the lock pins it. */
30
+ private pinnedVersion;
31
+ getHighestCompatibleVersionAsync(publisher: string, import_: Import): Promise<KanonakDocument | null>;
32
+ getDocumentsByNamespaceAsync(publisher: string, package_: string): Promise<KanonakDocument[]>;
33
+ getAllDocumentsAsync(): Promise<KanonakDocument[]>;
34
+ getDocumentAsync(identifier: string): Promise<KanonakDocument | null>;
35
+ saveDocumentAsync(document: KanonakDocument, identifier: string): Promise<void>;
36
+ deleteDocumentAsync(identifier: string): Promise<void>;
37
+ clearNamespaceAsync(publisher: string, package_: string): Promise<void>;
38
+ getAllDocumentReferencesAsync(): Promise<DocumentReference[]>;
39
+ getDocumentContentAsync(identifier: string): Promise<string | null>;
40
+ getDocumentUriAsync(identifier: string): Promise<string | null>;
41
+ }
@@ -1 +1 @@
1
- import{b as e,c as r,d as n}from"../chunk-YCV4H6H5.js";import{a as o}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-ZYAABYDS.js";import"../chunk-2ACBWC7K.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
1
+ import{b as e,c as r,d as n}from"../chunk-F26XWM5K.js";import{a as o}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-NJ3AZYQD.js";import"../chunk-2ACBWC7K.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
@@ -4,6 +4,7 @@ export { CompositeKanonakDocumentRepository, DocumentLocation } from './Composit
4
4
  export { RepositoryFactory } from './RepositoryFactory.js';
5
5
  export { HttpKanonakDocumentRepository } from './HttpKanonakDocumentRepository.js';
6
6
  export { LocalFirstRepository } from './LocalFirstRepository.js';
7
+ export { LockAwareRepository } from './LockAwareRepository.js';
7
8
  export { buildLocalFirstRepository, collectKanonakFiles, type HttpCacheHooks, } from './buildLocalFirstRepository.js';
8
9
  export { PublisherIndex } from './PublisherIndex.js';
9
10
  export { PublisherConfigResolver, defaultPublisherConfig } from './PublisherConfig.js';
@@ -1 +1 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m}from"../chunk-YWUKDEZA.js";import{a as g,b as h,c as i,d as j}from"../chunk-YCV4H6H5.js";import{a}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-ZYAABYDS.js";import"../chunk-2ACBWC7K.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,m as buildLocalFirstRepository,l as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m,i as n}from"../chunk-MPBNEKCQ.js";import{a as g,b as h,c as i,d as j}from"../chunk-F26XWM5K.js";import{a}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-NJ3AZYQD.js";import"../chunk-2ACBWC7K.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,l as LockAwareRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,n as buildLocalFirstRepository,m as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
@@ -1,4 +1,4 @@
1
- import{a as g}from"../chunk-SW4AJ6GD.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import"../chunk-FSHQVKZ5.js";import"../chunk-ZYAABYDS.js";import{d as m,h as S}from"../chunk-UK2OIPAB.js";import{a as p,f as E}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as v}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
1
+ import{a as g}from"../chunk-XRXCYM3U.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import"../chunk-DSHPAWJQ.js";import"../chunk-NJ3AZYQD.js";import{d as m,h as S}from"../chunk-UK2OIPAB.js";import{a as p,f as E}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as v}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
2
2
  Install it with:
3
3
  npm install @huggingface/transformers
4
4
  (underlying import error: ${e.message})`)}return F({transformers:r})})()),y}function H(r,e){let t=0;for(let n=0;n<r.length;n++)t+=r[n]*e[n];return t}function R(r,e){return e?r.version?e.version?x(r.version,e.version)>0:!0:!1:!0}function K(r,e){let t=g(r,e),n=[t.label],s=S(e);if(s.length>0){let i=E(r,s[0]),a=i?g(r,i).label:s[0].name;a&&n.push(`\u2014 a ${a}.`)}return t.summary&&n.push(t.summary),n.join(" ")}function q(r){let e=new Map;for(let t of r){if(!(t instanceof v))continue;let n=m(t);if(!n)continue;let s=p(n),i=e.get(s);(!i||R(n,m(i)))&&e.set(s,t)}return[...e.values()].sort((t,n)=>{let s=m(t)?p(m(t)):t.name,i=m(n)?p(m(n)):n.name;return s.localeCompare(i)})}var k=class{entries=[];embedder;constructor(e={}){this.embedder=e.embedder}resolveEmbedder(){return this.embedder?Promise.resolve(this.embedder):U()}get size(){return this.entries.length}async build(e,t={}){let n=q(e);if(t.include&&(n=n.filter(t.include)),n.length===0)return this.entries=[],{size:0,cached:!1};let s=n.map(o=>K(e,o)),i=t.cacheDir,a;if(i){let o=C("sha256").update(h+"|"+w+`
@@ -1,3 +1,3 @@
1
- import{j as E}from"../chunk-SW4AJ6GD.js";import"../chunk-QHABFCRC.js";import{a as Z,d as A,f as te,g as N}from"../chunk-YWUKDEZA.js";import{a as ee,b as re,c as V,d as I}from"../chunk-YCV4H6H5.js";import{a as X}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as oe}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{i as L}from"../chunk-FSHQVKZ5.js";import{a as D}from"../chunk-ZYAABYDS.js";import{b as O}from"../chunk-UK2OIPAB.js";import"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as ne}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{c as F,e as z,f as K,g as Q}from"../chunk-2ACBWC7K.js";import{readFileSync as ue,existsSync as de,readdirSync as me,writeFileSync as ge,mkdirSync as fe}from"fs";import{join as q}from"path";function se(n){let e=n.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function M(n,e){let t=new Set,r=[...n];for(;r.length>0;){let o=r.shift(),i=se(o);if(!i||t.has(i))continue;t.add(i);let d=o.metadata?.imports;if(d)for(let[c,f]of Object.entries(d))for(let g of f)try{let l=await e.getHighestCompatibleVersionAsync(c,g);l&&r.push(l)}catch{}}return t}var j=class{constructor(e,t){this.inner=e;this.scope=t}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(t=>{let r=se(t);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.inner.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.inner.getHighestCompatibleVersionAsync(e,t)}saveDocumentAsync(e,t){return this.inner.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.inner.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var ae=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function C(n){let e=n?.render;if(e&&e.length>0){let t=[];for(let r of e)try{let o=O(r);o.kind==="package"?t.push({publisher:o.publisher,package_:o.package_}):o.kind==="resource"&&t.push({publisher:o.uri.publisher,package_:o.uri.package_})}catch{}if(t.length>0)return t}return ae}function H(n){return`${n.publisher}/${n.package_}`}function B(n){let{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,producers:c}=n,f=new Map,g=new Map,l=new Map,a=new Set;for(let m of r){if(!(m instanceof ne))continue;let y=m.namespace||"";if(!i.has(y))continue;f.set(`${y}/${m.name}`,m);let v=y.split("/")[1]??"",[x,p]=v.split("@");if(!x||!p)continue;let b=Q(p);b&&(a.has(v)||(a.add(v),g.has(x)||g.set(x,[]),g.get(x).push({verStr:p,version:b})),m.name===x&&l.set(v,m))}for(let m of g.values())m.sort((y,v)=>F(v.version,y.version));return{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,bySubject:f,pkgVersions:g,pkgSelfByVer:l,...c?{producers:c}:{}}}async function T(n,e={}){let t=new D,r=new X(t),o=[],i=[];for(let p of N(n)){let b;try{b=ue(p,"utf-8")}catch{continue}let w;try{w=t.parse(b).metadata?.namespace_}catch{continue}if(!w?.version)continue;let $=w.version;i.push({publisher:w.publisher,package_:w.package_,verStr:`${$.major}.${$.minor}.${$.patch}`,version:$,source:b})}i.sort((p,b)=>F(b.version,p.version));for(let p of i)await r.saveDocumentAsync(t.parse(p.source),`${p.publisher}/${p.package_}@${p.verStr}`),o.push({publisher:p.publisher,package_:p.package_,verStr:p.verStr,source:p.source});let d=[...new Set(o.map(p=>p.publisher))].sort(),c=e.publisher;if(c){if(!d.includes(c))throw new Error(`Publisher "${c}" not found in workspace. Available: ${d.join(", ")||"(none)"}`)}else if(d.length===1)c=d[0];else throw d.length===0?new Error(`No Kanonak packages found under ${n}`):new Error(`Workspace has multiple publishers (${d.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,g=new Map;for(let p of o)p.publisher===c&&(f.add(`${p.publisher}/${p.package_}@${p.verStr}`),g.set(`${p.package_}@${p.verStr}`,p.source));let l=new Z(A(),!0,t),a=e.repository??new te(r,l,new I(e.httpCache?{getFromCache:e.httpCache.getFromCache,onFetch:e.httpCache.onFetch}:void 0)),m=C(void 0);if(!e.repository){let p=A(),b=s=>{let h=q(p,s);return de(h)?new Set(me(h).filter(k=>k.endsWith(".kan.yml")).map(k=>k.split("@")[0])):new Set},w=(s,h)=>o.some(k=>k.publisher===s&&k.package_===h),$=new V,u=new Map;for(let s of m)if(u.has(s.publisher)||u.set(s.publisher,b(s.publisher)),!(u.get(s.publisher).has(s.package_)||w(s.publisher,s.package_)))try{let h=await $.getHighestVersion(s.publisher,s.package_);if(!h)continue;let k=await $.getPackageUrl(s.publisher,s.package_,h),_=await fetch(k);if(!_.ok)continue;let le=await _.text(),J=q(p,s.publisher);fe(J,{recursive:!0}),ge(q(J,`${s.package_}@${h}.kan.yml`),le,"utf-8")}catch{}}let y=a;if(!e.repository){let p=(await r.getAllDocumentsAsync()).filter(w=>w.metadata.namespace_?.publisher===c),b=await M(p,a);for(let w of m)b.add(H(w));y=new j(a,b)}let v=await new L(t).parseKanonaks(y),x=new E(v);return B({publisher:c,availablePublishers:d,catalog:v,lookRenderer:x,localNamespaces:f,rawByNsKey:g})}import{existsSync as he,readFileSync as ke,writeFileSync as ye,mkdirSync as ve}from"fs";import{join as ie}from"path";async function U(n,e={}){let t=new D,r=O(n),o=r.kind==="resource"?r.uri.publisher:r.publisher,i=e.cacheRoot??A(),d=(u,s,h)=>ie(i,u,`${s}@${h}.kan.yml`),c=new I({getFromCache:(u,s,h)=>{let k=d(u,s,h);return he(k)?ke(k,"utf-8"):null},onFetch:(u,s,h,k)=>{let _=ie(i,u);ve(_,{recursive:!0}),ye(d(u,s,h),k,"utf-8")},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),f=new V(e.fetchFn?{fetchFn:e.fetchFn}:void 0),g;if(r.kind==="resource"){let u=r.uri.version;g=[u?{package_:r.uri.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let u=r.version;g=[u?{package_:r.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.package_}]}else g=(await f.listLatestPackages(o)).map(s=>({package_:s.packageName}));let l=async(u,s,h)=>{try{let k=h?t.buildImport(s,"=",h,u):t.buildImport(s,"*","0.0.0",u);return await c.getHighestCompatibleVersionAsync(u,k)}catch{return null}},a=[];for(let u of g){let s=await l(o,u.package_,u.version);s&&a.push(s)}if(a.length===0)throw new Error(`Could not fetch any package for address "${n}" from publisher "${o}".`);let m=await new re().getConfig(o).catch(()=>{}),y=[];for(let u of C(m)){let s=await l(u.publisher,u.package_,void 0);s&&y.push(s)}let v=await M([...a,...y],c),x=new j(c,v),p=await new L(t).parseKanonaks(x),b=new E(p),w=new Set,$=new Map;for(let u of await c.getAllDocumentsAsync()){let s=u.metadata.namespace_;if(!s||s.publisher!==o)continue;let h=`${s.version.major}.${s.version.minor}.${s.version.patch}`,k=`${s.publisher}/${s.package_}@${h}`;w.add(k);let _=await c.getDocumentContentAsync(k);_!==null&&$.set(`${s.package_}@${h}`,_)}return B({publisher:o,availablePublishers:[o],catalog:p,lookRenderer:b,localNamespaces:w,rawByNsKey:$})}import{VersionOperator as W}from"@kanonak-protocol/types/document/models/enums";var S={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},R=(n,e,t,r)=>({status:n,headers:{"Content-Type":e,...r||{}},body:t}),P=n=>R(404,S[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${n}</p>`),be=n=>({status:301,headers:{Location:n},body:""}),we=n=>({status:302,headers:{Location:n},body:""});function Se(n){switch(n.kind){case"exact":return{operator:W.Exact,version:K(n.major,n.minor,n.patch)};case"minor-pin":return{operator:W.Compatible,version:K(n.major,n.minor,0)};case"major-pin":return{operator:W.Major,version:K(n.major,0,0)};default:return{operator:W.Any,version:K(0,0,0)}}}async function Re(n,e,t,r){if(!r)return null;let o=n.producers?.find(f=>f.canProduce(n.publisher,e));if(!o)return null;let i=await o.resolveVersion(n.publisher,e,Se(t));if(!i)return null;let d=z(i);if(t.kind!=="exact")return we(`/${e}/${d}.kan.yml`);let{source:c}=await o.produce(n.publisher,e,i);return R(200,S[".kan.yml"],c)}function ce(n,e,t){let r=n.pkgVersions.get(e);if(!r||r.length===0)return null;switch(t.kind){case"any":return r[0].verStr;case"major-pin":return r.find(o=>o.version.major===t.major)?.verStr??null;case"minor-pin":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor)?.verStr??null;case"exact":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor&&o.version.patch===t.patch)?.verStr??null;default:return null}}async function G(n,e,t=""){let{lookRenderer:r,publisher:o}=n;if(e==="/.well-known/kanonak.json"){let a=ee(o);return n.producers&&n.producers.length>0&&(a.resolveByRedirect=!0),R(200,S[".json"],JSON.stringify(a,null,2))}if(e==="/index.txt"){let a=[...n.localNamespaces].map(m=>m.split("/")[1].replace("@","/")).sort();return R(200,S[".txt"],a.join(`
1
+ import{j as E}from"../chunk-XRXCYM3U.js";import"../chunk-QHABFCRC.js";import{a as Z,d as A,f as te,h as N}from"../chunk-MPBNEKCQ.js";import{a as ee,b as re,c as V,d as I}from"../chunk-F26XWM5K.js";import{a as X}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as oe}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{i as L}from"../chunk-DSHPAWJQ.js";import{a as D}from"../chunk-NJ3AZYQD.js";import{b as O}from"../chunk-UK2OIPAB.js";import"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as ne}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{c as F,e as z,f as K,g as Q}from"../chunk-2ACBWC7K.js";import{readFileSync as ue,existsSync as de,readdirSync as me,writeFileSync as ge,mkdirSync as fe}from"fs";import{join as q}from"path";function se(n){let e=n.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function M(n,e){let t=new Set,r=[...n];for(;r.length>0;){let o=r.shift(),i=se(o);if(!i||t.has(i))continue;t.add(i);let d=o.metadata?.imports;if(d)for(let[c,f]of Object.entries(d))for(let g of f)try{let l=await e.getHighestCompatibleVersionAsync(c,g);l&&r.push(l)}catch{}}return t}var j=class{constructor(e,t){this.inner=e;this.scope=t}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(t=>{let r=se(t);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.inner.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.inner.getHighestCompatibleVersionAsync(e,t)}saveDocumentAsync(e,t){return this.inner.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.inner.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var ae=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function C(n){let e=n?.render;if(e&&e.length>0){let t=[];for(let r of e)try{let o=O(r);o.kind==="package"?t.push({publisher:o.publisher,package_:o.package_}):o.kind==="resource"&&t.push({publisher:o.uri.publisher,package_:o.uri.package_})}catch{}if(t.length>0)return t}return ae}function H(n){return`${n.publisher}/${n.package_}`}function B(n){let{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,producers:c}=n,f=new Map,g=new Map,l=new Map,a=new Set;for(let m of r){if(!(m instanceof ne))continue;let y=m.namespace||"";if(!i.has(y))continue;f.set(`${y}/${m.name}`,m);let v=y.split("/")[1]??"",[x,p]=v.split("@");if(!x||!p)continue;let b=Q(p);b&&(a.has(v)||(a.add(v),g.has(x)||g.set(x,[]),g.get(x).push({verStr:p,version:b})),m.name===x&&l.set(v,m))}for(let m of g.values())m.sort((y,v)=>F(v.version,y.version));return{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,bySubject:f,pkgVersions:g,pkgSelfByVer:l,...c?{producers:c}:{}}}async function T(n,e={}){let t=new D,r=new X(t),o=[],i=[];for(let p of N(n)){let b;try{b=ue(p,"utf-8")}catch{continue}let w;try{w=t.parse(b).metadata?.namespace_}catch{continue}if(!w?.version)continue;let $=w.version;i.push({publisher:w.publisher,package_:w.package_,verStr:`${$.major}.${$.minor}.${$.patch}`,version:$,source:b})}i.sort((p,b)=>F(b.version,p.version));for(let p of i)await r.saveDocumentAsync(t.parse(p.source),`${p.publisher}/${p.package_}@${p.verStr}`),o.push({publisher:p.publisher,package_:p.package_,verStr:p.verStr,source:p.source});let d=[...new Set(o.map(p=>p.publisher))].sort(),c=e.publisher;if(c){if(!d.includes(c))throw new Error(`Publisher "${c}" not found in workspace. Available: ${d.join(", ")||"(none)"}`)}else if(d.length===1)c=d[0];else throw d.length===0?new Error(`No Kanonak packages found under ${n}`):new Error(`Workspace has multiple publishers (${d.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,g=new Map;for(let p of o)p.publisher===c&&(f.add(`${p.publisher}/${p.package_}@${p.verStr}`),g.set(`${p.package_}@${p.verStr}`,p.source));let l=new Z(A(),!0,t),a=e.repository??new te(r,l,new I(e.httpCache?{getFromCache:e.httpCache.getFromCache,onFetch:e.httpCache.onFetch}:void 0)),m=C(void 0);if(!e.repository){let p=A(),b=s=>{let h=q(p,s);return de(h)?new Set(me(h).filter(k=>k.endsWith(".kan.yml")).map(k=>k.split("@")[0])):new Set},w=(s,h)=>o.some(k=>k.publisher===s&&k.package_===h),$=new V,u=new Map;for(let s of m)if(u.has(s.publisher)||u.set(s.publisher,b(s.publisher)),!(u.get(s.publisher).has(s.package_)||w(s.publisher,s.package_)))try{let h=await $.getHighestVersion(s.publisher,s.package_);if(!h)continue;let k=await $.getPackageUrl(s.publisher,s.package_,h),_=await fetch(k);if(!_.ok)continue;let le=await _.text(),J=q(p,s.publisher);fe(J,{recursive:!0}),ge(q(J,`${s.package_}@${h}.kan.yml`),le,"utf-8")}catch{}}let y=a;if(!e.repository){let p=(await r.getAllDocumentsAsync()).filter(w=>w.metadata.namespace_?.publisher===c),b=await M(p,a);for(let w of m)b.add(H(w));y=new j(a,b)}let v=await new L(t).parseKanonaks(y),x=new E(v);return B({publisher:c,availablePublishers:d,catalog:v,lookRenderer:x,localNamespaces:f,rawByNsKey:g})}import{existsSync as he,readFileSync as ke,writeFileSync as ye,mkdirSync as ve}from"fs";import{join as ie}from"path";async function U(n,e={}){let t=new D,r=O(n),o=r.kind==="resource"?r.uri.publisher:r.publisher,i=e.cacheRoot??A(),d=(u,s,h)=>ie(i,u,`${s}@${h}.kan.yml`),c=new I({getFromCache:(u,s,h)=>{let k=d(u,s,h);return he(k)?ke(k,"utf-8"):null},onFetch:(u,s,h,k)=>{let _=ie(i,u);ve(_,{recursive:!0}),ye(d(u,s,h),k,"utf-8")},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),f=new V(e.fetchFn?{fetchFn:e.fetchFn}:void 0),g;if(r.kind==="resource"){let u=r.uri.version;g=[u?{package_:r.uri.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let u=r.version;g=[u?{package_:r.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.package_}]}else g=(await f.listLatestPackages(o)).map(s=>({package_:s.packageName}));let l=async(u,s,h)=>{try{let k=h?t.buildImport(s,"=",h,u):t.buildImport(s,"*","0.0.0",u);return await c.getHighestCompatibleVersionAsync(u,k)}catch{return null}},a=[];for(let u of g){let s=await l(o,u.package_,u.version);s&&a.push(s)}if(a.length===0)throw new Error(`Could not fetch any package for address "${n}" from publisher "${o}".`);let m=await new re().getConfig(o).catch(()=>{}),y=[];for(let u of C(m)){let s=await l(u.publisher,u.package_,void 0);s&&y.push(s)}let v=await M([...a,...y],c),x=new j(c,v),p=await new L(t).parseKanonaks(x),b=new E(p),w=new Set,$=new Map;for(let u of await c.getAllDocumentsAsync()){let s=u.metadata.namespace_;if(!s||s.publisher!==o)continue;let h=`${s.version.major}.${s.version.minor}.${s.version.patch}`,k=`${s.publisher}/${s.package_}@${h}`;w.add(k);let _=await c.getDocumentContentAsync(k);_!==null&&$.set(`${s.package_}@${h}`,_)}return B({publisher:o,availablePublishers:[o],catalog:p,lookRenderer:b,localNamespaces:w,rawByNsKey:$})}import{VersionOperator as W}from"@kanonak-protocol/types/document/models/enums";var S={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},R=(n,e,t,r)=>({status:n,headers:{"Content-Type":e,...r||{}},body:t}),P=n=>R(404,S[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${n}</p>`),be=n=>({status:301,headers:{Location:n},body:""}),we=n=>({status:302,headers:{Location:n},body:""});function Se(n){switch(n.kind){case"exact":return{operator:W.Exact,version:K(n.major,n.minor,n.patch)};case"minor-pin":return{operator:W.Compatible,version:K(n.major,n.minor,0)};case"major-pin":return{operator:W.Major,version:K(n.major,0,0)};default:return{operator:W.Any,version:K(0,0,0)}}}async function Re(n,e,t,r){if(!r)return null;let o=n.producers?.find(f=>f.canProduce(n.publisher,e));if(!o)return null;let i=await o.resolveVersion(n.publisher,e,Se(t));if(!i)return null;let d=z(i);if(t.kind!=="exact")return we(`/${e}/${d}.kan.yml`);let{source:c}=await o.produce(n.publisher,e,i);return R(200,S[".kan.yml"],c)}function ce(n,e,t){let r=n.pkgVersions.get(e);if(!r||r.length===0)return null;switch(t.kind){case"any":return r[0].verStr;case"major-pin":return r.find(o=>o.version.major===t.major)?.verStr??null;case"minor-pin":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor)?.verStr??null;case"exact":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor&&o.version.patch===t.patch)?.verStr??null;default:return null}}async function G(n,e,t=""){let{lookRenderer:r,publisher:o}=n;if(e==="/.well-known/kanonak.json"){let a=ee(o);return n.producers&&n.producers.length>0&&(a.resolveByRedirect=!0),R(200,S[".json"],JSON.stringify(a,null,2))}if(e==="/index.txt"){let a=[...n.localNamespaces].map(m=>m.split("/")[1].replace("@","/")).sort();return R(200,S[".txt"],a.join(`
2
2
  `)+`
3
3
  `)}if(e==="/"||e==="/index.html"||e==="/index.css"){let a=r.publisherSubject(o);return e==="/index.css"?R(200,S[".css"],r.renderStylesheet(a)):R(200,S[".html"],await r.renderDocument(a,{rootIndex:!0}))}let i=".html",d=!1,c=e;for(let a of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(a)){i=a,d=!0,c=e.slice(0,-a.length);break}let f=!d&&/application\/yaml|text\/yaml/i.test(t),g=c.endsWith("/");g&&c!=="/"&&(c=c.slice(0,-1));let l=oe.parse(c,o);if(!l)return P(e);if(l.kind==="package"){let a=ce(n,l.package_,l.versionSpec);if(!a)return await Re(n,l.package_,l.versionSpec,i===".kan.yml"||f)??P(e);if(i===".kan.yml"||f){let v=n.rawByNsKey.get(`${l.package_}@${a}`);return v!==void 0?R(200,S[".kan.yml"],v):P(e)}let m=n.pkgSelfByVer.get(`${l.package_}@${a}`);if(!m)return P(e);if(i===".css")return R(200,S[".css"],r.renderStylesheet(m));if(!g)return be(c+"/");let y=l.versionSpec.kind==="any";if(y&&!r.hasDeclaredView(m)){let v=(n.pkgVersions.get(l.package_)||[]).map(x=>x.verStr);return R(200,S[".html"],r.renderPackageVersionList(l.package_,v,m))}return R(200,S[".html"],await r.renderDocument(m,y?{bareOverview:!0}:void 0))}if(l.kind==="resource"){let a=ce(n,l.package_,l.versionSpec);if(!a)return P(e);let m=n.bySubject.get(`${o}/${l.package_}@${a}/${l.name}`);if(!m)return P(e);switch(i){case".css":return R(200,S[".css"],r.renderStylesheet(m));case".svg":return R(200,S[".svg"],await r.renderSvg(m));case".md":{let y=r.renderRawMarkdown(m);return y===void 0?P(e):R(200,S[".md"],y)}default:return R(200,S[".html"],await r.renderDocument(m))}}return P(e)}import{readFileSync as xe}from"fs";var Y=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,t=new Set;if(this.options.root!==void 0){let r=new D;for(let o of N(this.options.root))try{let i=r.parse(xe(o,"utf-8")).metadata?.namespace_;if(!i?.version)continue;let d=i.version;e.add(`${i.publisher}/${i.package_}@${d.major}.${d.minor}.${d.patch}`),t.add(`${i.publisher}/${i.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:t},this.workspaceIndex}async modelFor(e,t,r){let o=this.getWorkspaceIndex(),i=this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},d=t?r?o.exact.has(`${e}/${t}@${r}`):o.pkgs.has(`${e}/${t}`):[...o.pkgs].some(a=>a.startsWith(`${e}/`)),c,f;if(d&&this.options.root!==void 0){let a=this.options.root;c=`ws:${e}`,f=()=>T(a,{publisher:e})}else{let a=t?r?`${e}/${t}@${r}`:`${e}/${t}`:e;c=`rm:${a}`,f=()=>U(a,i)}let g=this.models.get(c);if(g)return g;let l=await f();return l.lookRenderer.setLinkMode("open-world"),this.models.set(c,l),l}async handle(e,t=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:pe()};let o=r[0];if(!o.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let i=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),d=!i&&r.length>=2?r[1]:void 0,c=!i&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,f=await this.modelFor(o,d,c),g=e.endsWith("/")&&r.length>1?"/":"",l="/"+r.slice(1).join("/")+g,a=await G(f,l,t);return a.headers.Location?{...a,headers:{...a.headers,Location:`/${o}${a.headers.Location}`}}:a}};function pe(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{j as ClosureScopedRepository,Y as RequestRouter,ae as UNIVERSAL_RENDER_BASE,M as deriveImportClosure,pe as landingPage,U as loadResourceModel,T as loadServerModel,H as renderRefKey,C as resolveRenderContract,G as route};
@@ -1,4 +1,4 @@
1
- import{b as Y,c as An,d as Sn,e as ce,f as Te,g as O,h as wn,i as X,j as q}from"../chunk-SW4AJ6GD.js";import{a as se}from"../chunk-NG2YXSH7.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-WBRCKPEH.js";import"../chunk-PEJALHXK.js";import{a as kn,b as bn,c as hn,d as Dn}from"../chunk-SHDHMKMJ.js";import{i as ie}from"../chunk-FSHQVKZ5.js";import{a as ae}from"../chunk-ZYAABYDS.js";import{b as L,c as A,f as S}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{b as N,c as D,d as K,g as M,h as P,i as F,j as W,l as H}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{g as oe}from"../chunk-2ACBWC7K.js";var $e="kanonak.org",Ue="document-ast",i=e=>({publisher:$e,package_:Ue,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ue(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var j=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=xe(n.metadata,t),o=Le(n.children),s=["---",...r,"---","",o].join(`
1
+ import{b as Y,c as An,d as Sn,e as ce,f as Te,g as O,h as wn,i as X,j as q}from"../chunk-XRXCYM3U.js";import{a as se}from"../chunk-NV63IOB7.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-RYOZTXI7.js";import"../chunk-PEJALHXK.js";import{a as kn,b as bn,c as hn,d as Dn}from"../chunk-SHDHMKMJ.js";import{i as ie}from"../chunk-DSHPAWJQ.js";import{a as ae}from"../chunk-NJ3AZYQD.js";import{b as L,c as A,f as S}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{b as N,c as D,d as K,g as M,h as P,i as F,j as W,l as H}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{g as oe}from"../chunk-2ACBWC7K.js";var $e="kanonak.org",Ue="document-ast",i=e=>({publisher:$e,package_:Ue,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ue(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var j=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=xe(n.metadata,t),o=Le(n.children),s=["---",...r,"---","",o].join(`
2
2
  `);return t?.trailingNewline&&(s.endsWith(`
3
3
  `)||(s+=`
4
4
  `)),s}};function xe(e,n){if(!e)return[];let t=new Map;for(let c of e.entries)t.set(I(c.key),c);let r=new Map;if(n?.metadataRenames)for(let[c,u]of n.metadataRenames)r.set(I(c),u);let a=(n?.metadataKeys??e.entries.map(c=>c.key)).map(I),s=[];for(let c of a){let u=t.get(c);if(!u)continue;let f=r.get(c),l=I(f??c),d=me(u.value,u.escapeHint);d!==void 0&&s.push(`${l}: ${d}`)}return s}function I(e){let n=e.lastIndexOf(".");return n===-1?e:e.substring(n+1)||e}function me(e,n){switch(e.kind){case"StringScalar":return Ve(e.stringValue,n);case"IntegerScalar":return String(e.integerValue);case"StructuredList":{let t=[];for(let r of e.items){let o=me(r,n);o!==void 0&&t.push(o)}return t.join(", ")}case"StructuredMap":return;default:return}}function Ve(e,n){return!n||ue(n,m.ESC_RAW)?e:ue(n,m.ESC_YAML_SAFE)?ve(e):e}function ve(e){return e.includes(`
@@ -1 +1 @@
1
- import{A,B,C,D,E,F,G,H,I,L as J,M as K,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-P3MJIJSK.js";import"../chunk-SHDHMKMJ.js";import"../chunk-FSHQVKZ5.js";import"../chunk-ZYAABYDS.js";import"../chunk-UK2OIPAB.js";import"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{w as AmbiguousReferenceRule,C as ClassDefinitionRule,n as ClassHierarchyCycleRule,u as DefinitionPropertyReferenceRule,J as DiamondNameClashRule,E as DisplayLensScopeRule,k as EmbeddedKanonakTypeRule,l as ImportExistenceRule,t as InstancePropertyReferenceRule,K as KanonakObjectValidator,F as LookSemanticSvgPathRule,D as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,y as ObjectPropertyImportRule,z as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,I as OwlOneOfRule,j as PackageHeaderRule,A as PropertyDomainRule,o as PropertyHierarchyCycleRule,x as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,B as PropertyValueTypeRule,g as ResourceNamingRule,H as ShaclShapeRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,G as TxExpressionPathRule,m as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,v as XsdImportRule};
1
+ import{A,B,C,D,E,F,G,H,I,L as J,M as K,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-IZRPJCQW.js";import"../chunk-SHDHMKMJ.js";import"../chunk-DSHPAWJQ.js";import"../chunk-NJ3AZYQD.js";import"../chunk-UK2OIPAB.js";import"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{w as AmbiguousReferenceRule,C as ClassDefinitionRule,n as ClassHierarchyCycleRule,u as DefinitionPropertyReferenceRule,J as DiamondNameClashRule,E as DisplayLensScopeRule,k as EmbeddedKanonakTypeRule,l as ImportExistenceRule,t as InstancePropertyReferenceRule,K as KanonakObjectValidator,F as LookSemanticSvgPathRule,D as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,y as ObjectPropertyImportRule,z as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,I as OwlOneOfRule,j as PackageHeaderRule,A as PropertyDomainRule,o as PropertyHierarchyCycleRule,x as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,B as PropertyValueTypeRule,g as ResourceNamingRule,H as ShaclShapeRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,G as TxExpressionPathRule,m as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,v as XsdImportRule};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "4.4.0",
3
+ "version": "4.6.0",
4
4
  "description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -125,7 +125,7 @@
125
125
  "yaml-parser"
126
126
  ],
127
127
  "dependencies": {
128
- "@kanonak-protocol/types": "^4.4.0",
128
+ "@kanonak-protocol/types": "^4.6.0",
129
129
  "ignore": "^7.0.5",
130
130
  "js-yaml": "^4.1.0",
131
131
  "yaml": "^2.7.0"
@@ -1 +0,0 @@
1
- import{d as v}from"./chunk-YCV4H6H5.js";import{a as A}from"./chunk-4NO7MHS7.js";import{a as f}from"./chunk-ZYAABYDS.js";import{c as w,d as I,h as R,i as F}from"./chunk-2ACBWC7K.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as b}from"url";import{VersionOperator as P}from"@kanonak-protocol/types/document/models/enums";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=c.resolve(e),this.recursive=t,this.parser=n??new f,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=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.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(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case P.Exact:return I(r,t.version);case P.Compatible:return R(r,t.version);case P.Major:return F(r,t.version);case P.Any:return w(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return w(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],p=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,p)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.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 r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,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 o=b(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return b(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 i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as d from"fs";var S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;d.existsSync(e)||d.mkdirSync(e,{recursive:!0}),d.existsSync(t)||d.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}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 o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}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),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,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 _}from"os";import{join as N}from"path";function g(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||N(_(),".kanonak","packages")}var C=class u{static createComposite(e,t,n){let o=e??g(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=g(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{readFileSync as B,readdirSync as H}from"fs";import{join as x}from"path";var $=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function K(u,e=[]){for(let t of H(u,{withFileTypes:!0}))t.isDirectory()?$.has(t.name)||K(x(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(x(u,t.name));return e}async function j(u,e=new f,t={}){let n=new A(e);for(let m of K(u))try{let l=e.parse(B(m,"utf-8")),h=l.metadata?.namespace_,p=h?.version;h&&p&&await n.saveDocumentAsync(l,`${h.publisher}/${h.package_}@${p.major}.${p.minor}.${p.patch}`)}catch{}let o=new y(g(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,h)=>s.get(`${m}|${l}|${h}`)??null,onFetch:(m,l,h,p)=>{s.set(`${m}|${l}|${h}`,p)}},r=new v({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,S as b,k as c,g as d,C as e,D as f,K as g,j as h};
@@ -1 +0,0 @@
1
- import{a as k,b as f}from"./chunk-2ACBWC7K.js";import*as h from"js-yaml";var b=new Set(["Package","EphemeralPackage"]);function v(d){return typeof d=="string"&&b.has(d)}var $=class{parse(r){let t=this.parseWithErrors(r);if(!t.isValid){let a=t.errors[0];throw new Error(`YAML parse error at line ${a.line}, column ${a.column}: ${a.message}`)}return t.document}parseWithErrors(r){let t=[],a;try{r=r.replace(/^\uFEFF/,"");let s=h.load(r,{schema:h.FAILSAFE_SCHEMA});if(!s||typeof s!="object")return a={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:a,errors:t,isValid:!0};let e=this.extractMetadata(s),n=this.extractBody(s,e);return a={metadata:e,body:n,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:a,errors:t,isValid:!0}}catch(s){let e=s,n={message:e.message||"Unknown parse error",line:e.mark?.line??0,column:e.mark?.column??0,errorType:e.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${e.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${e.mark?.line??0}: ${e.message||"Unknown parse error"}`};return t.push(n),{document:void 0,errors:t,isValid:!1}}}save(r){let t={};if(r.metadata.namespace_){let a=r.metadata.namespace_,s={type:"Package",publisher:a.publisher};a.version&&(s.version=`${a.version.major}.${a.version.minor}.${a.version.patch}`),r.metadata.imports&&(s.imports=this.serializeImports(r.metadata.imports)),t[a.package_]=s}return Object.assign(t,r.body),h.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(r){let t=r.imports;return Object.defineProperty(r,"allImports",{get:function(){if(!t)return[];let a=[];for(let s of Object.values(t))a.push(...s);return a},enumerable:!0,configurable:!0}),r}createVersion(r,t,a){return{major:r,minor:t,patch:a,toString:()=>`${r}.${t}.${a}`,equals:e=>!e||typeof e!="object"?!1:e.major===r&&e.minor===t&&e.patch===a,getHashCode:()=>r<<20|t<<10|a,compareTo:e=>r!==e.major?r-e.major:t!==e.minor?t-e.minor:a-e.patch}}extractMetadata(r){let t=this.createEmptyMetadata();for(let[a,s]of Object.entries(r))if(s&&typeof s=="object"&&v(s.type)){t.type_=s.type;let e=a,n=s.publisher,i=s.version?this.parseVersion(s.version):void 0;return n&&e&&(t.namespace_={publisher:n,package_:e,version:i,toString:function(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}`:`${this.publisher}/${this.package_}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===n&&o.package_===e&&(!i||!o.version||i.equals(o.version)),getHashCode:()=>{let o=0;for(let c=0;c<n.length;c++)o=(o<<5)-o+n.charCodeAt(c);for(let c=0;c<e.length;c++)o=(o<<5)-o+e.charCodeAt(c);return o|0}}),s.imports&&Array.isArray(s.imports)&&(t.imports=this.parseImportsV3(s.imports)),this.addAllImportsGetter(t)}if(r.kanonak&&typeof r.kanonak=="object"){let a=r.kanonak;return(a.publisher||a.package||a.version)&&(t.namespace_=this.parseNamespace(a)),a.imports&&typeof a.imports=="object"&&(t.imports=this.parseImportsLegacy(a.imports)),this.addAllImportsGetter(t)}return t}extractBody(r,t){let a={};for(let[s,e]of Object.entries(r))if(!(s==="kanonak"||s==="namespace"||s==="imports"))if(e&&typeof e=="object"&&v(e.type)){let n={};for(let[i,o]of Object.entries(e))i==="publisher"||i==="version"||i==="imports"||(n[i]=o);a[s]=n}else a[s]=e;return a}parseNamespace(r){if(typeof r=="string"){let e=r.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(e){let n=e[3]?this.parseVersion(e[3]):this.createVersion(1,0,0);return{publisher:e[1],package_:e[2],version:n,toString:()=>r,equals:i=>!i||typeof i!="object"?!1:i.publisher===e[1]&&i.package_===e[2]&&(!n||!i.version||n.equals(i.version)),getHashCode:()=>{let i=0;for(let o=0;o<e[1].length;o++)i=(i<<5)-i+e[1].charCodeAt(o);for(let o=0;o<e[2].length;o++)i=(i<<5)-i+e[2].charCodeAt(o);return i|0}}}}let t=r.publisher||"",a=r.package||"",s=r.version?this.parseVersion(r.version):this.createVersion(1,0,0);return{publisher:t,package_:a,version:s,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:e=>!e||typeof e!="object"?!1:e.publisher===t&&e.package_===a&&(!s||!e.version||s.equals(e.version)),getHashCode:()=>{let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n);for(let n=0;n<a.length;n++)e=(e<<5)-e+a.charCodeAt(n);return e|0}}}parseVersion(r){if(typeof r=="string"){let t=r.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(r.major||0,r.minor||0,r.patch||0)}parseImportsV3(r){let t={};for(let a of r)if(!(!a||typeof a!="object"))if(a.packages&&Array.isArray(a.packages)){let s=a.publisher;if(!s)throw new Error("PublisherImport requires 'publisher' property");t[s]||(t[s]=[]);for(let e of a.packages){if(!e||typeof e!="object")continue;let n=this.parseImportFromEmbeddedObject(e,s);t[s].push(n)}}else{let s=this.parseImportFromEmbeddedObject(a,a.publisher),e=s.publisher||"";t[e]||(t[e]=[]),t[e].push(s)}return t}parseImportsLegacy(r){let t={};for(let[a,s]of Object.entries(r))Array.isArray(s)&&(t[a]=s.map(e=>this.parseImport(e,a)));return t}parseImportFromEmbeddedObject(r,t){let a=r.package;if(!a)throw new Error("Import requires 'package' property");let s=r.match;if(!s)throw new Error("Import requires 'match' property");let e=r.version;if(!e)throw new Error("Import requires 'version' property");let n=this.parseVersion(e),i=this.parseVersionOperator(s),o=this.calculateMaxVersion(s,n),c=r.alias;return{package_:`${a} ${s} ${n.toString()}`,publisher:t,packageName:a,versionOperator:i,version:n,alias:c,minVersion:n,maxVersion:o,toEmbeddedObject:()=>{let m={package:a,match:s,version:n.toString()};return c&&(m.alias=c),m},toString:()=>c?`${a} ${s} ${n.toString()} as ${c}`:`${a} ${s} ${n.toString()}`}}buildImport(r,t,a,s){return this.parseImport({packageName:r,operator:t,version:a},s)}parseImport(r,t){if(typeof r=="string"){let o=r.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(o){let m=o[1].trim(),u=o[2],p=this.parseVersion(o[3].trim()),l=o[4].trim(),g=this.parseVersionOperator(u),V=this.calculateMaxVersion(u,p);return{package_:r,publisher:t,packageName:m,versionOperator:g,version:p,alias:l,minVersion:p,maxVersion:V,toEmbeddedObject:()=>{let y={package:m,match:u,version:p.toString()};return l&&(y.alias=l),y},toString:()=>`${m} ${u} ${p.toString()} as ${l}`}}let c=r.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let m=c[1].trim(),u=c[2],p=this.parseVersion(c[3].trim()),l=this.parseVersionOperator(u),g=this.calculateMaxVersion(u,p);return{package_:r,publisher:t,packageName:m,versionOperator:l,version:p,alias:void 0,minVersion:p,maxVersion:g,toEmbeddedObject:()=>({package:m,match:u,version:p.toString()}),toString:()=>`${m} ${u} ${p.toString()}`}}}let a=this.parseVersionOperator(r.operator||"~"),s=this.parseVersion(r.version||"1.0.0"),e=r.packageName||r.package||"",n=f(a),i=this.calculateMaxVersion(r.operator||"~",s);return{package_:r.package||"",publisher:t,packageName:e,versionOperator:a,version:s,alias:r.alias,minVersion:s,maxVersion:i,toEmbeddedObject:()=>{let o={package:e,match:n,version:s.toString()};return r.alias&&(o.alias=r.alias),o},toString:()=>`${e} ${n} ${s.toString()}`}}parseVersionOperator(r){return k(r)}calculateMaxVersion(r,t){switch(r){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(r){let t=[];for(let[a,s]of Object.entries(r)){let e={publisher:a,packages:s.map(n=>{let i=f(n.versionOperator),o={package:n.packageName,match:i,version:`${n.version.major}.${n.version.minor}.${n.version.patch}`};return n.alias&&(o.alias=n.alias),o})};t.push(e)}return t}};export{$ as a};