@kanonak-protocol/sdk 5.12.0 → 5.13.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 +1 @@
1
- import{a as F,b as H,c as L,d as Pe,f as ge,g as Ce,h as he,i as Ke,j as be,k as Ie,l as Oe,m as je}from"./chunk-Y37TQT74.js";import{a as Se}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as m,b as u,c,e as d,h as R,j as y,k as f}from"./chunk-UXYCUGSF.js";import{a as p}from"./chunk-4NO7MHS7.js";import{a as B,b as G,c as q}from"./chunk-S6VSAKXB.js";import{a as w,b as _}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as fe,B as xe,K as ke,a as W,b as z,c as J,d as Q,f as X,g as Y,h as Z,i as $,k as ee,l as oe,m as te,n as re,o as ne,p as ae,q as ie,r as se,s as pe,t as le,u as me,v as ue,w as ce,x as de,y as Re,z as ye}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as g,c as v,h as T,i as A,l as M}from"./chunk-MX3DEXMV.js";import{a as l}from"./chunk-NJ3AZYQD.js";import{a as U}from"./chunk-ZP6P7HNU.js";import"./chunk-6U26UASC.js";import{a as E,b as N}from"./chunk-GZPLWII7.js";import{a as x,b as k,c as P,d as h,e as K,f as S,g as b,h as I,i as O,j,k as D,l as V}from"./chunk-7BHDZHJY.js";import{a as C}from"./chunk-FUUTGGJS.js";import{c as e,d as o,e as t,f as r,g as n,h as a,i,j as s}from"./chunk-2ACBWC7K.js";export{me as AmbiguousReferenceRule,O as BooleanStatement,Oe as CANONICAL_FORM_VERSION,T as Carrier,fe as ClassDefinitionRule,re as ClassHierarchyCycleRule,k as DefinedKanonak,H as EdgeType,g as EmbeddedKanonak,ee as EmbeddedKanonakTypeRule,D as EmbeddedStatement,L as GraphBuilder,f as HttpKanonakDocumentRepository,oe as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,m as KANONAK_USER_AGENT,x as Kanonak,G as KanonakDocumentPositions,M as KanonakObjectParser,ke as KanonakObjectValidator,l as KanonakParser,C as KanonakUri,w as KanonakUriBuilder,V as ListStatement,xe as MarkdownLinkRule,v as MarkdownStatement,pe as NamespaceImportCycleRule,X as NamespacePrefixRule,F as NodeType,I as NumberStatement,ge as OAuthDiscovery,ce as ObjectPropertyValueValidationRule,J as OntologyValidationError,W as OntologyValidationResult,de as PropertyDomainRule,ne as PropertyHierarchyCycleRule,Re as PropertyKindRangeConsistencyRule,B as PropertyMetadata,ue as PropertyRangeReferenceRule,ae as PropertyRangeRequiredRule,Z as PropertyTypeSpecificityRule,R as PublisherConfigResolver,y as PublisherIndex,h as ReferenceKanonak,j as ReferenceStatement,ye as ReservedNameShadowRule,Y as ResourceNamingRule,E as ResourceResolver,U as ResourceTypeClassifier,S as ScalarStatement,K as Statement,b as StringStatement,ie as SubClassOfReferenceRule,se as SubPropertyOfReferenceRule,P as SubjectKanonak,$ as SubjectKanonakTypeRequiredRule,Ke as TokenCredentialProvider,N as TypeResolver,le as UnresolvedPredicateRule,te as UnresolvedReferenceRule,Q as ValidationContext,z as ValidationSeverity,je as buildOntologyModel,be as canonicalForm,Ie as canonicalHash,A as carrierOf,e as compareVersions,he as createCredentialedFetch,r as createVersion,Se as findDerivation,_ as findInstancesByType,t as formatVersion,c as getKanonakUserAgent,a as isCompatibleVersion,i as isMajorCompatible,d as kanonakFetch,Pe as normalizeHost,Ce as parseAuthChallenge,n as parseVersionString,q as parseWithPositions,s as pickHighestDocument,u as setKanonakUserAgent,o as versionsEqual};
1
+ import{a as F,b as H,c as L,d as Pe,f as ge,g as Ce,h as he,i as Ke,j as be,k as Ie,l as Oe,m as je}from"./chunk-4SQZBFJJ.js";import{a as Se}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as m,b as u,c,e as d,h as R,j as y,k as f}from"./chunk-UXYCUGSF.js";import{a as p}from"./chunk-4NO7MHS7.js";import{a as B,b as G,c as q}from"./chunk-S6VSAKXB.js";import{a as w,b as _}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as fe,B as xe,K as ke,a as W,b as z,c as J,d as Q,f as X,g as Y,h as Z,i as $,k as ee,l as oe,m as te,n as re,o as ne,p as ae,q as ie,r as se,s as pe,t as le,u as me,v as ue,w as ce,x as de,y as Re,z as ye}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as g,c as v,h as T,i as A,l as M}from"./chunk-MX3DEXMV.js";import{a as l}from"./chunk-NJ3AZYQD.js";import{a as U}from"./chunk-ZP6P7HNU.js";import"./chunk-6U26UASC.js";import{a as E,b as N}from"./chunk-GZPLWII7.js";import{a as x,b as k,c as P,d as h,e as K,f as S,g as b,h as I,i as O,j,k as D,l as V}from"./chunk-7BHDZHJY.js";import{a as C}from"./chunk-FUUTGGJS.js";import{c as e,d as o,e as t,f as r,g as n,h as a,i,j as s}from"./chunk-2ACBWC7K.js";export{me as AmbiguousReferenceRule,O as BooleanStatement,Oe as CANONICAL_FORM_VERSION,T as Carrier,fe as ClassDefinitionRule,re as ClassHierarchyCycleRule,k as DefinedKanonak,H as EdgeType,g as EmbeddedKanonak,ee as EmbeddedKanonakTypeRule,D as EmbeddedStatement,L as GraphBuilder,f as HttpKanonakDocumentRepository,oe as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,m as KANONAK_USER_AGENT,x as Kanonak,G as KanonakDocumentPositions,M as KanonakObjectParser,ke as KanonakObjectValidator,l as KanonakParser,C as KanonakUri,w as KanonakUriBuilder,V as ListStatement,xe as MarkdownLinkRule,v as MarkdownStatement,pe as NamespaceImportCycleRule,X as NamespacePrefixRule,F as NodeType,I as NumberStatement,ge as OAuthDiscovery,ce as ObjectPropertyValueValidationRule,J as OntologyValidationError,W as OntologyValidationResult,de as PropertyDomainRule,ne as PropertyHierarchyCycleRule,Re as PropertyKindRangeConsistencyRule,B as PropertyMetadata,ue as PropertyRangeReferenceRule,ae as PropertyRangeRequiredRule,Z as PropertyTypeSpecificityRule,R as PublisherConfigResolver,y as PublisherIndex,h as ReferenceKanonak,j as ReferenceStatement,ye as ReservedNameShadowRule,Y as ResourceNamingRule,E as ResourceResolver,U as ResourceTypeClassifier,S as ScalarStatement,K as Statement,b as StringStatement,ie as SubClassOfReferenceRule,se as SubPropertyOfReferenceRule,P as SubjectKanonak,$ as SubjectKanonakTypeRequiredRule,Ke as TokenCredentialProvider,N as TypeResolver,le as UnresolvedPredicateRule,te as UnresolvedReferenceRule,Q as ValidationContext,z as ValidationSeverity,je as buildOntologyModel,be as canonicalForm,Ie as canonicalHash,A as carrierOf,e as compareVersions,he as createCredentialedFetch,r as createVersion,Se as findDerivation,_ as findInstancesByType,t as formatVersion,c as getKanonakUserAgent,a as isCompatibleVersion,i as isMajorCompatible,d as kanonakFetch,Pe as normalizeHost,Ce as parseAuthChallenge,n as parseVersionString,q as parseWithPositions,s as pickHighestDocument,u as setKanonakUserAgent,o as versionsEqual};
@@ -0,0 +1,2 @@
1
+ import{e as F}from"./chunk-UXYCUGSF.js";import{H as ye,I as me}from"./chunk-7K5TAJ44.js";import{a as ne,b as I,c as pe,h as B,l as x}from"./chunk-MX3DEXMV.js";import{a as b,d as K,e as fe,f as ge}from"./chunk-ZP6P7HNU.js";import{i as de}from"./chunk-GZPLWII7.js";import{b as ee,c as A,d as E,f as re,g as oe,h as se,i as ae,j as ie,k as ce,l as L,m as N,r as G,t as le,v as $,w as ue,y as V}from"./chunk-7BHDZHJY.js";import{a as te}from"./chunk-FUUTGGJS.js";import{d as Z}from"./chunk-2ACBWC7K.js";var be=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(be||{}),Ce=(i=>(i.InstanceOf="instanceOf",i.SubClassOf="subClassOf",i.Domain="domain",i.Range="range",i.ObjectRelationship="objectRelationship",i.SubPropertyOf="subPropertyOf",i.PropertyValue="propertyValue",i.EmbeddedLink="embeddedLink",i))(Ce||{}),z=class{static async buildFromRepository(n,t){let s=await new x().parseKanonaks(n),o=await n.getAllDocumentsAsync(),c=[],a=[],i=new Set,d=new Set,f=new Map;for(let y of s){let l=y;l.name&&(b.isClassType(l)&&i.add(l.name),(b.isObjectPropertyType(l)||b.isGenericPropertyType(l))&&d.add(l.name))}for(let y of o)for(let[l,u]of Object.entries(y.body))d.has(l)&&u?.range&&typeof u.range=="string"&&f.set(l,u.range);let p=new Map;for(let y of s){let l=y;l.name&&p.set(l.name,l)}for(let y of o){let l=y.metadata.namespace_,u=l?`${l.publisher}/${l.package_}`:"",m=l?.version?`${l.version.major}.${l.version.minor}.${l.version.patch}`:"",C=he(y);for(let[h,g]of Object.entries(y.body)){if(!g||typeof g!="object")continue;let O=p.get(h),k="Unknown";if(O){let v=O;b.isClassType(v)?k="Class":b.isObjectPropertyType(v)?k="ObjectProperty":b.isDatatypePropertyType(v)?k="DatatypeProperty":b.isAnnotationPropertyType(v)?k="AnnotationProperty":b.isDatatypeType(v)?k="Datatype":b.isGenericPropertyType(v)?k="ObjectProperty":b.isInstanceOfKnownClass(v,i)&&(k="Instance")}let S=u&&m?`${u}/${h}@${m}`:h,Q={};for(let[v,U]of Object.entries(g))v!=="type"&&(typeof U!="object"||U===null)&&(Q[v]=U);c.push({id:S,label:g.label??h,type:k,namespace:u,properties:Q}),ke(S,g,k,i,d,a,u,m,C,t),H(S,g,d,f,c,a,u,m,C),Ue(S,O,a)}}return{nodes:c,edges:a}}static buildFromDocument(n,t){let r=[],s=[],o=n.metadata.namespace_,c=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",a=o?`${o.publisher}/${o.package_}`:"",i=new Set,d=new Set,f=new Map,p=he(n);for(let[u,m]of Object.entries(n.body)){let C=m?.type;C&&(Ke(C,p)&&i.add(u),De(C,p)&&(d.add(u),m.range&&typeof m.range=="string"&&f.set(u,m.range)))}for(let[u,m]of Object.entries(n.body)){if(!m||typeof m!="object")continue;let C=m.type,h=Me(C,u,i,p),g=a&&c?`${a}/${u}@${c}`:u,O={};for(let[k,S]of Object.entries(m))k!=="type"&&(typeof S!="object"||S===null)&&(O[k]=S);r.push({id:g,label:m.label??u,type:h,namespace:a,properties:O}),ke(g,m,h,i,d,s,a,c,p,t),H(g,m,d,f,r,s,a,c,p)}let y=new Set(r.map(u=>u.id)),l=s.filter(u=>y.has(u.source)&&y.has(u.target));return{nodes:r,edges:l}}};function he(e,n){let t=new Map;if(e.metadata?.imports)for(let[r,s]of Object.entries(e.metadata.imports))for(let o of s){let c=o.alias??o.packageName,a=o.version,i=`${a.major}.${a.minor}.${a.patch}`;t.set(c,{publisher:r,package_:o.packageName,version:i})}return t}var Se={"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"},xe=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function q(e,n){if(e.includes(".")){let t=e.indexOf("."),r=e.substring(0,t),s=e.substring(t+1),o=n.get(r);if(o)return`${o.publisher}/${o.package_}/${s}`}return null}function Ke(e,n){let t=q(e,n);return t?Se[t]==="Class":!1}function De(e,n){let t=q(e,n);return t?xe.has(t):!1}function Me(e,n,t,r){if(!e||e==="Package")return"Unknown";let s=q(e,r);if(s){let c=Se[s];if(c)return c;let a=s.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=e.split(".").pop()??e;return t.has(o)?"Instance":"Unknown"}var Oe=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function ke(e,n,t,r,s,o,c,a,i,d){let f=n.type,p=n.subClassOf;if(p){let h=Array.isArray(p)?p:[p];for(let g of h)typeof g=="string"&&o.push({source:e,target:w(g,c,a,i),type:"subClassOf",label:"subClassOf"})}let y=n.subPropertyOf;if(y){let h=Array.isArray(y)?y:[y];for(let g of h)typeof g=="string"&&o.push({source:e,target:w(g,c,a,i),type:"subPropertyOf",label:"subPropertyOf"})}let l=n.domain,u=n.range;if(d?.includePropertyEdges){let h=[[l,"domain","domain"],[u,"range","range"]];for(let[g,O,k]of h)if(g!=null)for(let S of Array.isArray(g)?g:[g])typeof S=="string"&&o.push({source:e,target:w(S,c,a,i),type:O,label:k})}if(t==="Instance"&&f){let h=f.split(".").pop()??f;o.push({source:e,target:w(h,c,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[h,g]of Object.entries(n)){if(Oe.has(h)||!s.has(h))continue;let O=Array.isArray(g)?g:[g];for(let k of O)typeof k=="string"&&Fe(k)&&o.push({source:e,target:w(k,c,a,i),type:"propertyValue",label:h,propertyId:w(h,c,a,i)})}if((t==="ObjectProperty"||t==="DatatypeProperty"||l&&u)&&l&&u){let h=typeof l=="string"?l:null,g=typeof u=="string"?u:null;h&&g&&o.push({source:w(h,c,a,i),target:w(g,c,a,i),type:"objectRelationship",label:n.label??e.split("/").pop()??"",propertyId:e})}}function H(e,n,t,r,s,o,c,a,i){for(let[d,f]of Object.entries(n)){if(Oe.has(d)||typeof f!="object"||f===null||Array.isArray(f))continue;let p=f,y=`${e}/${d}`,l=r.get(d),u=l?l.split(".").pop()??l:"Unknown",m={};for(let[h,g]of Object.entries(p))(typeof g!="object"||g===null)&&(m[h]=g);s.push({id:y,label:`${u} (embedded)`,type:"Instance",namespace:c,properties:m});let C=c&&a?`${c}/${d}@${a}`:d;o.push({source:e,target:y,type:"propertyValue",label:d,propertyId:t.has(d)?C:void 0}),l&&o.push({source:y,target:w(u,c,a,i),type:"instanceOf",label:"type (inferred)"}),H(y,p,t,r,s,o,c,a,i)}}function Ue(e,n,t){let r=n?.statement;if(Array.isArray(r))for(let s of r){if(!(s instanceof pe))continue;let o=s.predicate?.subject?.name??"";for(let c of s.links){let a=c.target?.subject;if(!a)continue;let i=a.version,d=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"";t.push({source:e,target:`${a.publisher}/${a.package_}/${a.name}${d}`,type:"embeddedLink",label:o})}}}function Fe(e){return!(!e||e.includes(" ")||e.includes(`
2
+ `)||e.startsWith("http://")||e.startsWith("https://")||/^\d{4}-\d{2}/.test(e)||/^\d+(\.\d+)?$/.test(e))}function w(e,n,t,r){if(e.includes("@")&&e.includes("/"))return e;if(e.includes(".")){let s=e.indexOf("."),o=e.substring(0,s),c=e.substring(s+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${c}@${a.version}`}return n&&t?`${n}/${c}@${t}`:c}return n&&t?`${n}/${e}@${t}`:e}function R(e){let n=e.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!n)throw new Error("Publisher host cannot be empty");return n}var Le="key_thumbprint",_=class{cache=new Map;prCache=new Map;async discoverProtectedResource(n){let t=R(n);if(this.prCache.has(t))return this.prCache.get(t);let r=`https://${t}/.well-known/oauth-protected-resource`,s=await Ge(r),o=s&&Array.isArray(s.authorization_servers)?s.authorization_servers.filter(a=>typeof a=="string"):[],c=o.length>0?o:null;return this.prCache.set(t,c),c}async discover(n){let t=R(n);if(this.cache.has(t))return this.cache.get(t);let r=`https://${t}/.well-known/oauth-authorization-server`,s=await this.tryEndpoint(r);if(!s){let o=`https://${t}/.well-known/openid-configuration`;s=await this.tryEndpoint(o)}return this.cache.set(t,s),s}async supportsOAuth(n){return await this.discover(n)!==null}static supportsPkceS256(n){return n.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(n){return!!n.registrationEndpoint}static supportsAuthorizationCode(n){return n.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(n){return!!n.enrollmentEndpoint}static supportsSession(n){return!!n.sessionEndpoint}async tryEndpoint(n){let t;try{t=await fetch(n)}catch(s){let o=s instanceof Error?s.message:String(s);return o.includes("ENOTFOUND")||o.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${n} \u2014 host unreachable (${o})`),console.error(" If the server is behind a VPN, ensure you are connected.")):o.includes("CERT")||o.includes("SSL")||o.includes("TLS")?(console.error(` OAuth discovery: ${n} \u2014 TLS error (${o})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${n} \u2014 network error: ${o}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${n} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${n} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let r;try{r=await t.json()}catch{return console.error(` OAuth discovery: ${n} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:P(r.issuer),authorizationEndpoint:P(r.authorization_endpoint),tokenEndpoint:P(r.token_endpoint),registrationEndpoint:P(r.registration_endpoint),revocationEndpoint:P(r.revocation_endpoint),scopesSupported:T(r.scopes_supported),responseTypesSupported:T(r.response_types_supported),grantTypesSupported:T(r.grant_types_supported),codeChallengeMethodsSupported:T(r.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:T(r.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:T(r.dpop_signing_alg_values_supported),enrollmentEndpoint:P(r.enrollment_endpoint),enrollmentIssuanceProtocols:T(r.enrollment_issuance_protocols),enrollmentKeyTypes:T(r.enrollment_key_types),enrollmentScopesSupported:T(r.enrollment_scopes_supported),enrollmentConsentBindingParam:P(r.enrollment_consent_binding_param),sessionEndpoint:P(r.session_endpoint),sessionEndpointAuthMethod:P(r.session_endpoint_auth_method)}}};async function Ge(e){try{let n=await fetch(e);return n.ok?await n.json():null}catch{return null}}function P(e){return typeof e=="string"?e:null}function T(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):null}function ve(e){let n=e.headers.get("WWW-Authenticate")??void 0,t=e.headers.get("DPoP-Nonce")??void 0;if(!n&&!t)return;let r={wwwAuthenticate:n??""};if(t&&(r.nonce=t),n){let s=n.match(/acr_values\s*=\s*"([^"]*)"/i);s&&(r.acrValues=s[1])}return r}function Ve(e){try{return new URL(e).host}catch{return null}}function Be(e,n={}){let t=n.discovery??new _,r=new Map,s=new Map,o=async i=>{let d=r.get(i);if(d!==void 0)return d;let f=null,p=await t.discoverProtectedResource(i).catch(()=>null);return p&&p.length>0&&(f=Ve(p[0])),r.set(i,f),f},c=async(i,d)=>{if(!e)return null;if(!(d.forceRefresh||d.challenge)&&s.has(i))return s.get(i);let p=await e.resolve(i,d).catch(()=>null);return s.set(i,p),p},a=async(i,d,f,p)=>{let y=await o(d);if(!y)return{res:await F(i,{method:f,redirect:"manual"}),authed:!1};let l=await c(y,{method:f,url:i,...p}),u=l?.headers??{};return{res:await F(i,{method:f,redirect:"manual",headers:u}),authed:!!l}};return async(i,d,f="GET")=>{let p=await a(i,d,f,{});if((p.res.status===401||p.res.status===403)&&p.authed){let y=ve(p.res),l={forceRefresh:y===void 0};return y&&(l.challenge=y),(await a(i,d,f,l)).res}return p.res}}var we="KANONAK_TOKEN";function ze(){return typeof process<"u"&&process.env?process.env:{}}function He(e){return`${we}_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}var W=class{tokens;env;constructor(n={}){this.tokens=n.tokens??{},this.env=n.env??ze()}async resolve(n,t){let r=R(n),s=this.tokens[r]??this.env[He(r)]??this.env[we];return s?{headers:{Authorization:`Bearer ${s}`}}:null}};import{canonicalForm as qe,canonicalHash as We}from"@kanonak-protocol/canonical";function X(e){return typeof e=="object"&&e!==null&&Array.isArray(e.subjects)}import{CANONICAL_FORM_VERSION as on}from"@kanonak-protocol/canonical";function Xe(e){return qe(X(e)?e:Te(e))}function Ye(e){return We(X(e)?e:Te(e))}function Te(e){let n=[];for(let t of e)t instanceof A&&n.push({uri:rn(t),statements:Y(t.statement)});return{subjects:n}}function Y(e){let n=[];for(let t of e){let r=tn(t);if(!r)continue;if(t instanceof L&&Je(t.predicate.subject)){n.push(...Ze(t,r));continue}let s=en(t);s&&n.push({predicate:r,value:s})}return n}function Je(e){let n=de("type");return n!==void 0&&e.name==="type"&&e.publisher===n.publisher&&e.package_===n.package_}var Pe=new TextEncoder;function Qe(e,n){let t=Pe.encode(e),r=Pe.encode(n),s=Math.min(t.length,r.length);for(let o=0;o<s;o++)if(t[o]!==r[o])return t[o]-r[o];return t.length-r.length}function Ze(e,n){let t=[];for(let r of e.object){if(!(r instanceof E))throw new Error(`canonicalForm: a multi-valued type statement must contain only entity references, got ${r.constructor?.name??typeof r}`);t.push(J(r))}t.sort(Qe);for(let r=1;r<t.length;r++)if(t[r-1]===t[r])throw new Error(`canonicalForm: duplicate type ${t[r]} in a multi-valued type statement`);return t.map(r=>({predicate:n,value:{ref:r}}))}function en(e){if(e instanceof re&&e.carrier)return{lit:e.lexical??String(e.object),datatype:Ee(e.carrier)};if(e instanceof oe)return{raw:e.object};if(e instanceof se)return{raw:e.lexical??String(e.object)};if(e instanceof ae)return{raw:e.lexical??String(e.object)};if(e instanceof ie)return{ref:J(e.object)};if(e instanceof ce)return je(e.object);if(e instanceof L)return{list:e.object.map(nn)}}function je(e){let n=Y(e.statement);return e.name&&e.name.length>0?{embed:{name:e.name,statements:n}}:{embed:{statements:n}}}function nn(e){if(e instanceof E)return{ref:J(e)};if(e instanceof ne)return je(e);if(e instanceof I){if(e.carrier)return{lit:e.lexical??String(e.value),datatype:Ee(e.carrier)};let n=e.value;if(typeof n=="string")return{raw:n};if(typeof n=="number")return{raw:String(n)};if(typeof n=="boolean")return{raw:String(n)}}if(e instanceof ee)return{embed:{statements:Y(e.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${e.constructor?.name??typeof e}); add canonicalization support before hashing data that contains it`)}function Ee(e){return e===B.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${e}`}function tn(e){let n=e.predicate;if(n)return Re(n.subject)}function rn(e){let n=e.namespace??"",t=e.name??"";return`${n}/${t}`}function J(e){return Re(e.subject)}function Re(e){let n=e.version;return n&&typeof n.major=="number"?`${e.publisher}/${e.package_}@${n.major}.${n.minor}.${n.patch}/${e.name}`:`${e.publisher}/${e.package_}/${e.name}`}var j="kanonak.org",M="core-rdf",Ae="core-xsd",_e={publisher:j,package_:M,name:"subClassOf"},Ie={publisher:j,package_:M,name:"label"},sn={publisher:j,package_:M,name:"comment"},Ne={publisher:j,package_:"core-owl",name:"oneOf"},$e=e=>e;function an(e){let n=ue(e,_e);if(n)return[n];let t=[];for(let r of V(e,_e))r instanceof E&&t.push(r.subject);return t}function cn(e,n,t){if(n.publisher===j&&n.package_===M&&n.name==="Literal")return{kind:"datatype",uri:n};let s=G(e,n);if(s){let o=$e(s);if(b.isDatatypeType(o))return{kind:"datatype",uri:n};if(b.isClassType(o))return{kind:"class",uri:K(s)??n,localName:s.name}}return n.publisher===j&&n.package_===Ae?{kind:"datatype",uri:n}:t==="datatype"?{kind:"datatype",uri:n}:{kind:"class",uri:n,localName:n.name}}function pn(e,n,t){if(!n.range)throw new Error(`Property ${n.uri.publisher}/${n.uri.package_}/${n.uri.name} has no rdfs.range; every property must declare a range. Validate the ontology before introspecting it.`);let r=cn(e,n.range,n.kind),s=n.kind==="object"?"object":n.kind==="datatype"?"datatype":r.kind==="class"?"object":"datatype";return{uri:n.uri,localName:n.uri.name,kind:s,range:r,...n.label!==void 0?{label:n.label}:{},...n.comment!==void 0?{comment:n.comment}:{},...t??{}}}var D=e=>new te(j,Ae,e);function ln(e){return typeof e=="boolean"?D("boolean"):typeof e=="number"?Number.isInteger(e)?D("integer"):D("decimal"):D("string")}function un(e,n){let t=[];for(let r of V(n,Ne))if(r instanceof E){let s=G(e,r.subject),o=(s?K(s):void 0)??r.subject,c=s?$(s,Ie):void 0;t.push({kind:"individual",uri:o,localName:o.name,...c!==void 0?{label:c}:{}})}else r instanceof I&&t.push({kind:"literal",value:r.value,datatype:ln(r.value)});return t}function dn(e,n,t,r){let s=fe(e,n),o=N(n);return ge(e,n).filter(a=>t?!0:a.domains.some(i=>N(i)===o)).map(a=>pn(e,a,me(r,s,a.uri)))}async function fn(e,n,t){let r=e.metadata?.namespace_;if(!r)throw new Error("buildOntologyModel: document has no namespace (publisher/package/version).");let s=t?.includeInherited??!1,o=await new x().parseKanonaks(n),c=ye(o),a=[],i=[],d=new Set;for(let f of o){if(!(f instanceof A)||!b.isClassType($e(f)))continue;let p=K(f);if(!p||p.publisher!==r.publisher||p.package_!==r.package_||p.version&&r.version&&!Z(p.version,r.version))continue;let y=N(p);if(d.has(y))continue;d.add(y);let l=an(f).map(C=>({uri:C,localName:C.name})),u=$(f,Ie),m=$(f,sn);a.push({uri:p,localName:p.name,superClasses:l,properties:dn(o,p,s,c),...u!==void 0?{label:u}:{},...m!==void 0?{comment:m}:{}}),le(f,Ne)&&i.push({uri:p,localName:p.name,members:un(o,f),...u!==void 0?{label:u}:{},...m!==void 0?{comment:m}:{}})}return{classes:a,enums:i}}export{be as a,Ce as b,z as c,R as d,Le as e,_ as f,ve as g,Be as h,W as i,Xe as j,Ye as k,on as l,fn as m};
@@ -70,6 +70,33 @@ export interface GraphData {
70
70
  nodes: GraphNode[];
71
71
  edges: GraphEdge[];
72
72
  }
73
+ /**
74
+ * Options for both build entry points.
75
+ */
76
+ export interface GraphBuildOptions {
77
+ /**
78
+ * Also emit property-centric `EdgeType.Domain` and `EdgeType.Range` edges. Default `false`.
79
+ *
80
+ * The default graph is CLASS-centric: a property carrying both `domain` and `range`
81
+ * collapses into one `ObjectRelationship` edge (domain → range, labelled with the property),
82
+ * so a reader sees how entities relate without property nodes sitting between them. That is
83
+ * deliberate and unchanged.
84
+ *
85
+ * Set this when you want the PROPERTY-centric view instead — properties as first-class nodes
86
+ * with typed edges to their domain and range. It is the view for authoring and reviewing an
87
+ * ontology rather than reading one, and it surfaces two things the collapsed edge cannot:
88
+ *
89
+ * - a property declaring only ONE of `domain` / `range`, which produces no
90
+ * `ObjectRelationship` edge at all and is otherwise invisible;
91
+ * - the property node itself, which is never an edge ENDPOINT in the default graph (it is
92
+ * referenced only through `GraphEdge.propertyId`), so in a node-link rendering every
93
+ * property appears unattached.
94
+ *
95
+ * Additive: `ObjectRelationship` edges are still emitted, so enabling this yields both views.
96
+ * A consumer wanting only the property-centric one can filter by `EdgeType`.
97
+ */
98
+ includePropertyEdges?: boolean;
99
+ }
73
100
  /**
74
101
  * Builds a visualization-ready graph from Kanonak documents.
75
102
  *
@@ -92,10 +119,10 @@ export declare class GraphBuilder {
92
119
  * Build a graph from all documents in a repository.
93
120
  * This is the main entry point — handles imports, resolution, and classification.
94
121
  */
95
- static buildFromRepository(repository: IKanonakDocumentRepository): Promise<GraphData>;
122
+ static buildFromRepository(repository: IKanonakDocumentRepository, options?: GraphBuildOptions): Promise<GraphData>;
96
123
  /**
97
124
  * Build a graph from a single parsed document.
98
125
  * Simpler alternative when you don't need import resolution.
99
126
  */
100
- static buildFromDocument(document: KanonakDocument): GraphData;
127
+ static buildFromDocument(document: KanonakDocument, options?: GraphBuildOptions): GraphData;
101
128
  }
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as br,b as Rr,c as wr,d as Er,e as N}from"./chunk-TVSHIXLA.js";import{a as Y,b as ee,c as re}from"./chunk-L2KE7B3K.js";import{a as bn,c as B,e as ne,h as te,i as oe,j as Rn}from"./chunk-IHB7UVEH.js";import{a as gr,b as hr,c as Pr,d as mn,e as yn,f as fn,g as kn,h as gn,i as hn,j as wn,k as F,l as En,m as xn}from"./chunk-Y37TQT74.js";import{a as Pn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as Ve,b as je,c as Ae,d as Ce,e as Se,f as Te,g as ze,h as He,i as We}from"./chunk-CC44JAOT.js";import{a as De,b as Ue,c as Oe,d as _e,e as Me,f as $e,h as Ne,j as Le,k as Fe}from"./chunk-UXYCUGSF.js";import{a as ve}from"./chunk-4NO7MHS7.js";import{a as Kr,b as Ir,c as vr,d as Vr}from"./chunk-S6VSAKXB.js";import{a as jr,b as _r}from"./chunk-PEUTCG3B.js";import{a as Cr}from"./chunk-PEJALHXK.js";import{a as Be}from"./chunk-SC5M74NM.js";import{A as un,B as ln,K as dn,a as Mr,b as $r,c as Nr,d as Lr,e as Br,f as Fr,g as Tr,h as zr,i as Hr,j as Wr,k as qr,l as Gr,m as Jr,n as Zr,o as Qr,p as Xr,q as Yr,r as en,s as rn,t as nn,u as tn,v as on,w as an,x as sn,y as cn,z as pn}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as k,b as Ze,c as ar,h as cr,i as pr,j as yr,k as fr,l as E}from"./chunk-MX3DEXMV.js";import{a as P}from"./chunk-NJ3AZYQD.js";import{a as kr,b as L,c as Ar,d as m,e as Sr,f as Dr,g as Ur,h as Or}from"./chunk-ZP6P7HNU.js";import{a as X}from"./chunk-6U26UASC.js";import{a as ir,b as sr,c as w,d as ur,e as lr,g as dr,k as mr}from"./chunk-GZPLWII7.js";import{a as qe,b as Ge,c as f,d as b,e as Qe,f as Xe,g as Ye,h as er,i as rr,j as nr,k as tr,l as or,r as j,w as R,x as M,y as $}from"./chunk-7BHDZHJY.js";import{a as Je}from"./chunk-FUUTGGJS.js";import{a as be,b as _,c as V,d as Re,e as y,f as we,g as Ee,h as xe,i as Ke,j as Ie}from"./chunk-2ACBWC7K.js";import{a as xr}from"./chunk-ODIECDN7.js";import{VersionOperator as _t}from"@kanonak-protocol/types/document/models/enums";import*as T from"js-yaml";import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";var Kn="0.0.0",g=class{constructor(e,r=new P,n){this.repository=e;this.parser=r;this.objectParser=n??new E(this.parser)}repository;parser;objectParser;imports(){return new x}serializeValue(e,r){return ce(e,r)}async buildContentAddressed(e){let r=e.book.toImports(),n=await this.hashBody(e.publisher,r,e.body),t=z(n),a={type:"EphemeralPackage",publisher:e.publisher,imports:r};e.contentHashProperty&&(a[e.contentHashProperty]=n),Object.assign(a,e.header??{}),a.imports=r;let i={[t]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:se(s),contentHash:n,packageName:t,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let r=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:r},t;e.contentHashProperty&&(t=await this.hashBody(e.publisher,r,e.body),n[e.contentHashProperty]=t),Object.assign(n,e.header??{}),n.imports=r;let a={[e.name]:n,...e.body},i=this.dump(a),s={yaml:i,byteCount:se(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return t!==void 0&&(s.contentHash=t),s}dump(e){return T.dump(e,{lineWidth:-1})}async hashBody(e,r,n){let t={[ie]:{type:"EphemeralPackage",publisher:e,imports:r},...n},a=this.parser.parse(T.dump(t,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new X(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==ie);for(let u of c)u.namespace="ephemeral";return F(c)}},ie="__pkgbuilder_probe__";function se(o){return new TextEncoder().encode(o).length}function z(o){let e="sha256:",r=o.startsWith(e)?e.length:0;return`q-${o.slice(r,r+16)}`}var x=class{byKey=new Map;aliases=new Set;ensure(e,r,n,t,a=ae.Major){let i=`${e}/${r}@${n}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(t);return this.byKey.set(i,{publisher:e,package_:r,version:n,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_,y(e.version),e.package_)}.${e.name}`}refLatest(e,r,n,t){return`${this.ensure(e,r,Kn,t??r,ae.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let t=e.get(n.publisher)??[];t.push(n),e.set(n.publisher,t)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((t,a)=>t.package_<a.package_?-1:1).map(t=>({package:t.package_,match:_(t.match),version:t.version,alias:t.alias}))}))}uniqueAlias(e){let r=K(e)||"pkg",n=r,t=2;for(;this.aliases.has(n);)n=`${r}${t++}`;return this.aliases.add(n),n}};function ce(o,e){if(o!=null){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(o instanceof b)return e.ref(o.subject);if(Array.isArray(o)){let r=o.map(n=>ce(n,e)).filter(n=>n!==void 0);return r.length>0?r:void 0}if(o instanceof k)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(In(o))throw new Error(`Value produced a bare URI without a version (${o.publisher}/${o.package_}/${o.name}); cannot serialize it as a reference.`)}}function K(o){return o.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function In(o){return typeof o=="object"&&o!==null&&typeof o.publisher=="string"&&typeof o.package_=="string"&&typeof o.name=="string"}var A=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,r){return this.producers.find(n=>n.canProduce(e,r))}async produceCached(e,r,n,t){let a=`${r}/${n}@${y(t)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(r,n,t);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,r){let n=this.producerFor(e,r.packageName);if(!n)return null;let t={operator:r.versionOperator,version:r.version},a=await n.resolveVersion(e,r.packageName,t);return a?this.produceCached(n,e,r.packageName,a):null}async getDocumentAsync(e){let r;try{r=L(e)}catch{return null}if(r.kind!=="package"||!r.version)return null;let n=this.producerFor(r.publisher,r.package_);return n?this.produceCached(n,r.publisher,r.package_,r.version):null}async getDocumentsByNamespaceAsync(e,r){return Array.from(this.produced.values()).filter(n=>{let t=n.metadata.namespace_;return t!=null&&t.publisher===e&&t.package_===r})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,r){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,r){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 H={async authorize(){return{allowed:!0}}},W={async record(){}},I=class extends Error{constructor(r,n){let t=`${r.publisher}/${r.package_}${r.version?`@${r.version.major}.${r.version.minor}.${r.version.patch}`:""}`;super(`Not entitled to produce ${t}${n?`: ${n}`:""}`);this.address=r;this.reason=n;this.name="EntitlementDeniedError"}address;reason},C=class{inner;ctx;policy;meter;constructor(e,r,n=H,t=W){this.inner=e,this.ctx=r,this.policy=n,this.meter=t}canProduce(e,r){return this.inner.canProduce(e,r)}async resolveVersion(e,r,n){return await this.assertAllowed({publisher:e,package_:r,version:n.version}),this.inner.resolveVersion(e,r,n)}async produce(e,r,n){let t={publisher:e,package_:r,version:n};await this.assertAllowed(t);let a=await this.inner.produce(e,r,n);return await this.meter.record(this.ctx,t,a),a}async assertAllowed(e){let r=await this.policy.authorize(this.ctx,e);if(!r.allowed)throw new I(e,r.reason)}};var p="kanonak.org",d="view",pe="core-kanonak",vn={publisher:p,package_:d,name:"rootView"},Vn={publisher:p,package_:d,name:"bind"},jn={publisher:p,package_:d,name:"produces"},An={publisher:p,package_:d,name:"projections"},Cn={publisher:p,package_:d,name:"where"},Sn={publisher:p,package_:d,name:"value"},Dn={publisher:p,package_:d,name:"as"},S=class{constructor(e,r=new P){this.repository=e;this.parser=r;this.objectParser=new E(this.parser),this.builder=new g(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,r={}){let n=await this.objectParser.parseKanonaks(this.repository),t=this.resolveView(n,e),a=R(t,Vn);if(!a)throw new Error(`View ${t.namespace}/${t.name} declares no view.bind; cannot materialize.`);let i=R(t,jn);if(!i)throw new Error(`View ${t.namespace}/${t.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=Un(t),c=ue(n,p,pe),u=ue(n,p,d),l=this.builder.imports(),D=l.ensure(p,pe,c,"ck"),de=l.ensure(p,d,u,"v"),me=l.ref(i),ye=new oe(this.repository,this.parser,this.objectParser),q=new ne(ye,n),fe=this.readProjections(n,t),ke=Mn(t,Cn),ge=this.findInstances(n,a,await this.reason(r)),G={},he=new Set;for(let v of ge){if(!await this.passesWhere(q,n,ke,v))continue;let O={type:me};for(let Z of fe){let Pe=await this.evaluateValue(q,n,Z.value,v),Q=this.builder.serializeValue(le(Pe),l);Q!==void 0&&(O[l.ref(Z.as)]=Q)}let J=m(v);J&&(O[`${de}.derivedFrom`]=l.ref(J)),G[this.rowName(v,he)]=O}let U={};r.resolvedAt&&(U[`${D}.resolvedAt`]=r.resolvedAt),r.invocationId&&(U[`${D}.id`]=r.invocationId);let h=await this.builder.buildContentAddressed({publisher:s,book:l,body:G,contentHashProperty:`${D}.contentHash`,header:U});return{yaml:h.yaml,contentHash:h.contentHash,packageName:h.packageName,publisher:h.publisher,rowCount:h.resourceCount}}resolveView(e,r){let n=j(e,r);if(!n)throw new Error(`View ${r.publisher}/${r.package_}/${r.name} not found in the catalog.`);let t=R(n,vn);if(t){let a=j(e,t);if(!a)throw new Error(`ViewPackage ${r.name} names rootView ${t.name}, which is not in the catalog.`);return a}return n}readProjections(e,r){let n=[];for(let t of $(r,An)){let a=t instanceof k?t:t instanceof b?j(e,t.subject):void 0;if(!a)continue;let i=M(a,Sn),s=R(a,Dn);i&&s&&n.push({value:i,as:s})}return n}async reason(e){return new N({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,r,n){let t=_n(e),a=[],i=new Set;for(let s of n.getInstancesOfClass(r)){if(i.has(s))continue;i.add(s);let c=t.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=w(m(s)),l=w(m(c));return u<l?-1:u>l?1:0}),a}async passesWhere(e,r,n,t){for(let a of n){let i=await this.evaluateValue(e,r,a,t);if(!$n(i))return!1}return!0}async evaluateValue(e,r,n,t){let a=te(n,"view-projection",{catalog:r,depth:0}),i=new Map([["input",t]]);return e.evaluate(a,i)}rowName(e,r){let n=K(e.name)||"row",t=n,a=2;for(;r.has(t);)t=`${n}-${a++}`;return r.add(t),t}};function le(o){return B(o)?o.value:Array.isArray(o)?o.map(le):o}function Un(o){let e=m(o);if(!e)throw new Error(`Could not derive a publisher from view ${o.namespace}/${o.name}.`);return e.publisher}function ue(o,e,r){let n=On(o,e,r);if(!n)throw new Error(`Package ${e}/${r} is not in the catalog; it must be importable to materialize a view.`);return n}function On(o,e,r){let n;for(let t of o){if(!(t instanceof f))continue;let a=m(t);!a||a.publisher!==e||a.package_!==r||!a.version||(!n||V(a.version,n)>0)&&(n=a.version)}return n?y(n):void 0}function _n(o){let e=new Map,r=new Map;for(let n of o){if(!(n instanceof f))continue;let t=m(n);if(!t||!t.version)continue;let a=w(t),i=r.get(a);(!i||V(t.version,i)>0)&&(r.set(a,t.version),e.set(a,n))}return e}function Mn(o,e){let r=M(o,e);return r?[r]:$(o,e).filter(n=>n instanceof k)}function $n(o){return o===!0?!0:o===!1||o===void 0||o===null?!1:typeof o=="string"?o.length>0:typeof o=="number"?o!==0:B(o)?o.value.length>0:Array.isArray(o)?o.length>0:!!o}export{tn as AmbiguousReferenceRule,rr as BooleanStatement,En as CANONICAL_FORM_VERSION,cr as Carrier,un as ClassDefinitionRule,Zr as ClassHierarchyCycleRule,Ae as CompositeKanonakDocumentRepository,yn as DEFAULT_CONSENT_BINDING_PARAM,Ge as DefinedKanonak,je as DocumentLocation,hr as EdgeType,k as EmbeddedKanonak,qr as EmbeddedKanonakTypeRule,tr as EmbeddedStatement,I as EntitlementDeniedError,C as EntitlementProducer,Ve as FileSystemKanonakDocumentRepository,xr as GitIgnoreFilter,Pr as GraphBuilder,Fe as HttpKanonakDocumentRepository,x as ImportBook,Gr as ImportExistenceRule,ve as InMemoryKanonakDocumentRepository,De as KANONAK_USER_AGENT,qe as Kanonak,Ir as KanonakDocumentPositions,E as KanonakObjectParser,dn as KanonakObjectValidator,P as KanonakParser,Je as KanonakUri,jr as KanonakUriBuilder,Cr as KanonakUrlResolver,mr as KanonakVocabulary,or as ListStatement,Ze as LiteralKanonak,Te as LocalFirstRepository,ze as LockAwareRepository,Rn as LookRenderer,ln as MarkdownLinkRule,ar as MarkdownStatement,rn as NamespaceImportCycleRule,Fr as NamespacePrefixRule,gr as NodeType,er as NumberStatement,fn as OAuthDiscovery,wr as OWL_RL_CLASSIFICATION_RULES,an as ObjectPropertyValueValidationRule,Nr as OntologyValidationError,Mr as OntologyValidationResult,g as PackageBuilder,Wr as PackageHeaderRule,A as ProducerRepository,sn as PropertyDomainRule,Qr as PropertyHierarchyCycleRule,cn as PropertyKindRangeConsistencyRule,Kr as PropertyMetadata,on as PropertyRangeReferenceRule,Xr as PropertyRangeRequiredRule,zr as PropertyTypeSpecificityRule,Ne as PublisherConfigResolver,Le as PublisherIndex,Rr as RDFS_RULES,N as Reasoner,Er as ReasoningResult,b as ReferenceKanonak,nr as ReferenceStatement,Se as RepositoryFactory,pn as ReservedNameShadowRule,Tr as ResourceNamingRule,ir as ResourceResolver,kr as ResourceTypeClassifier,Xe as ScalarStatement,Qe as Statement,Ye as StringStatement,Yr as SubClassOfReferenceRule,en as SubPropertyOfReferenceRule,f as SubjectKanonak,Hr as SubjectKanonakTypeRequiredRule,hn as TokenCredentialProvider,br as TripleStore,sr as TypeResolver,nn as UnresolvedPredicateRule,Jr as UnresolvedReferenceRule,Br as ValidationCache,Lr as ValidationContext,$r as ValidationSeverity,_t as VersionOperator,S as ViewMaterializer,H as allowAllPolicy,_e as assertHttpsUrl,Be as assertPackageIdentity,We as buildLocalFirstRepository,xn as buildOntologyModel,wn as canonicalForm,F as canonicalHash,pr as carrierOf,He as collectKanonakFiles,V as compareVersions,re as computeIntegrity,z as contentAddressedName,Or as contextTypesOf,gn as createCredentialedFetch,we as createVersion,fr as extractMarkdownLinks,Pn as findDerivation,_r as findInstancesByType,yr as findMalformedReferences,Vr as findMarkdownLinkAt,Ar as formatKanonakAddress,y as formatVersion,Ce as getGlobalCachePath,Oe as getKanonakUserAgent,xe as isCompatibleVersion,Ke as isMajorCompatible,Me as kanonakFetch,Y as loadLockFile,ur as makeUriKey,W as noopMeter,mn as normalizeHost,kn as parseAuthChallenge,L as parseKanonakAddress,Ee as parseVersionString,vr as parseWithPositions,Ie as pickHighestDocument,Dr as propertiesInScope,bn as resolveDisplayValue,Ur as resolvePropertyStep,K as sanitizeName,ee as saveLockFile,$e as setKanonakFetchRetries,Ue as setKanonakUserAgent,m as subjectUri,Sr as superClassChain,lr as tripleKey,w as uriKey,dr as uriTriple,be as versionOperatorFromChar,_ as versionOperatorToChar,Re as versionsEqual};
1
+ import{a as br,b as Rr,c as wr,d as Er,e as N}from"./chunk-TVSHIXLA.js";import{a as Y,b as ee,c as re}from"./chunk-L2KE7B3K.js";import{a as bn,c as B,e as ne,h as te,i as oe,j as Rn}from"./chunk-IHB7UVEH.js";import{a as gr,b as hr,c as Pr,d as mn,e as yn,f as fn,g as kn,h as gn,i as hn,j as wn,k as F,l as En,m as xn}from"./chunk-4SQZBFJJ.js";import{a as Pn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as Ve,b as je,c as Ae,d as Ce,e as Se,f as Te,g as ze,h as He,i as We}from"./chunk-CC44JAOT.js";import{a as De,b as Ue,c as Oe,d as _e,e as Me,f as $e,h as Ne,j as Le,k as Fe}from"./chunk-UXYCUGSF.js";import{a as ve}from"./chunk-4NO7MHS7.js";import{a as Kr,b as Ir,c as vr,d as Vr}from"./chunk-S6VSAKXB.js";import{a as jr,b as _r}from"./chunk-PEUTCG3B.js";import{a as Cr}from"./chunk-PEJALHXK.js";import{a as Be}from"./chunk-SC5M74NM.js";import{A as un,B as ln,K as dn,a as Mr,b as $r,c as Nr,d as Lr,e as Br,f as Fr,g as Tr,h as zr,i as Hr,j as Wr,k as qr,l as Gr,m as Jr,n as Zr,o as Qr,p as Xr,q as Yr,r as en,s as rn,t as nn,u as tn,v as on,w as an,x as sn,y as cn,z as pn}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as k,b as Ze,c as ar,h as cr,i as pr,j as yr,k as fr,l as E}from"./chunk-MX3DEXMV.js";import{a as P}from"./chunk-NJ3AZYQD.js";import{a as kr,b as L,c as Ar,d as m,e as Sr,f as Dr,g as Ur,h as Or}from"./chunk-ZP6P7HNU.js";import{a as X}from"./chunk-6U26UASC.js";import{a as ir,b as sr,c as w,d as ur,e as lr,g as dr,k as mr}from"./chunk-GZPLWII7.js";import{a as qe,b as Ge,c as f,d as b,e as Qe,f as Xe,g as Ye,h as er,i as rr,j as nr,k as tr,l as or,r as j,w as R,x as M,y as $}from"./chunk-7BHDZHJY.js";import{a as Je}from"./chunk-FUUTGGJS.js";import{a as be,b as _,c as V,d as Re,e as y,f as we,g as Ee,h as xe,i as Ke,j as Ie}from"./chunk-2ACBWC7K.js";import{a as xr}from"./chunk-ODIECDN7.js";import{VersionOperator as _t}from"@kanonak-protocol/types/document/models/enums";import*as T from"js-yaml";import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";var Kn="0.0.0",g=class{constructor(e,r=new P,n){this.repository=e;this.parser=r;this.objectParser=n??new E(this.parser)}repository;parser;objectParser;imports(){return new x}serializeValue(e,r){return ce(e,r)}async buildContentAddressed(e){let r=e.book.toImports(),n=await this.hashBody(e.publisher,r,e.body),t=z(n),a={type:"EphemeralPackage",publisher:e.publisher,imports:r};e.contentHashProperty&&(a[e.contentHashProperty]=n),Object.assign(a,e.header??{}),a.imports=r;let i={[t]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:se(s),contentHash:n,packageName:t,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let r=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:r},t;e.contentHashProperty&&(t=await this.hashBody(e.publisher,r,e.body),n[e.contentHashProperty]=t),Object.assign(n,e.header??{}),n.imports=r;let a={[e.name]:n,...e.body},i=this.dump(a),s={yaml:i,byteCount:se(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return t!==void 0&&(s.contentHash=t),s}dump(e){return T.dump(e,{lineWidth:-1})}async hashBody(e,r,n){let t={[ie]:{type:"EphemeralPackage",publisher:e,imports:r},...n},a=this.parser.parse(T.dump(t,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new X(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==ie);for(let u of c)u.namespace="ephemeral";return F(c)}},ie="__pkgbuilder_probe__";function se(o){return new TextEncoder().encode(o).length}function z(o){let e="sha256:",r=o.startsWith(e)?e.length:0;return`q-${o.slice(r,r+16)}`}var x=class{byKey=new Map;aliases=new Set;ensure(e,r,n,t,a=ae.Major){let i=`${e}/${r}@${n}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(t);return this.byKey.set(i,{publisher:e,package_:r,version:n,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_,y(e.version),e.package_)}.${e.name}`}refLatest(e,r,n,t){return`${this.ensure(e,r,Kn,t??r,ae.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let t=e.get(n.publisher)??[];t.push(n),e.set(n.publisher,t)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((t,a)=>t.package_<a.package_?-1:1).map(t=>({package:t.package_,match:_(t.match),version:t.version,alias:t.alias}))}))}uniqueAlias(e){let r=K(e)||"pkg",n=r,t=2;for(;this.aliases.has(n);)n=`${r}${t++}`;return this.aliases.add(n),n}};function ce(o,e){if(o!=null){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(o instanceof b)return e.ref(o.subject);if(Array.isArray(o)){let r=o.map(n=>ce(n,e)).filter(n=>n!==void 0);return r.length>0?r:void 0}if(o instanceof k)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(In(o))throw new Error(`Value produced a bare URI without a version (${o.publisher}/${o.package_}/${o.name}); cannot serialize it as a reference.`)}}function K(o){return o.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function In(o){return typeof o=="object"&&o!==null&&typeof o.publisher=="string"&&typeof o.package_=="string"&&typeof o.name=="string"}var A=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,r){return this.producers.find(n=>n.canProduce(e,r))}async produceCached(e,r,n,t){let a=`${r}/${n}@${y(t)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(r,n,t);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,r){let n=this.producerFor(e,r.packageName);if(!n)return null;let t={operator:r.versionOperator,version:r.version},a=await n.resolveVersion(e,r.packageName,t);return a?this.produceCached(n,e,r.packageName,a):null}async getDocumentAsync(e){let r;try{r=L(e)}catch{return null}if(r.kind!=="package"||!r.version)return null;let n=this.producerFor(r.publisher,r.package_);return n?this.produceCached(n,r.publisher,r.package_,r.version):null}async getDocumentsByNamespaceAsync(e,r){return Array.from(this.produced.values()).filter(n=>{let t=n.metadata.namespace_;return t!=null&&t.publisher===e&&t.package_===r})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,r){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,r){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 H={async authorize(){return{allowed:!0}}},W={async record(){}},I=class extends Error{constructor(r,n){let t=`${r.publisher}/${r.package_}${r.version?`@${r.version.major}.${r.version.minor}.${r.version.patch}`:""}`;super(`Not entitled to produce ${t}${n?`: ${n}`:""}`);this.address=r;this.reason=n;this.name="EntitlementDeniedError"}address;reason},C=class{inner;ctx;policy;meter;constructor(e,r,n=H,t=W){this.inner=e,this.ctx=r,this.policy=n,this.meter=t}canProduce(e,r){return this.inner.canProduce(e,r)}async resolveVersion(e,r,n){return await this.assertAllowed({publisher:e,package_:r,version:n.version}),this.inner.resolveVersion(e,r,n)}async produce(e,r,n){let t={publisher:e,package_:r,version:n};await this.assertAllowed(t);let a=await this.inner.produce(e,r,n);return await this.meter.record(this.ctx,t,a),a}async assertAllowed(e){let r=await this.policy.authorize(this.ctx,e);if(!r.allowed)throw new I(e,r.reason)}};var p="kanonak.org",d="view",pe="core-kanonak",vn={publisher:p,package_:d,name:"rootView"},Vn={publisher:p,package_:d,name:"bind"},jn={publisher:p,package_:d,name:"produces"},An={publisher:p,package_:d,name:"projections"},Cn={publisher:p,package_:d,name:"where"},Sn={publisher:p,package_:d,name:"value"},Dn={publisher:p,package_:d,name:"as"},S=class{constructor(e,r=new P){this.repository=e;this.parser=r;this.objectParser=new E(this.parser),this.builder=new g(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,r={}){let n=await this.objectParser.parseKanonaks(this.repository),t=this.resolveView(n,e),a=R(t,Vn);if(!a)throw new Error(`View ${t.namespace}/${t.name} declares no view.bind; cannot materialize.`);let i=R(t,jn);if(!i)throw new Error(`View ${t.namespace}/${t.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=Un(t),c=ue(n,p,pe),u=ue(n,p,d),l=this.builder.imports(),D=l.ensure(p,pe,c,"ck"),de=l.ensure(p,d,u,"v"),me=l.ref(i),ye=new oe(this.repository,this.parser,this.objectParser),q=new ne(ye,n),fe=this.readProjections(n,t),ke=Mn(t,Cn),ge=this.findInstances(n,a,await this.reason(r)),G={},he=new Set;for(let v of ge){if(!await this.passesWhere(q,n,ke,v))continue;let O={type:me};for(let Z of fe){let Pe=await this.evaluateValue(q,n,Z.value,v),Q=this.builder.serializeValue(le(Pe),l);Q!==void 0&&(O[l.ref(Z.as)]=Q)}let J=m(v);J&&(O[`${de}.derivedFrom`]=l.ref(J)),G[this.rowName(v,he)]=O}let U={};r.resolvedAt&&(U[`${D}.resolvedAt`]=r.resolvedAt),r.invocationId&&(U[`${D}.id`]=r.invocationId);let h=await this.builder.buildContentAddressed({publisher:s,book:l,body:G,contentHashProperty:`${D}.contentHash`,header:U});return{yaml:h.yaml,contentHash:h.contentHash,packageName:h.packageName,publisher:h.publisher,rowCount:h.resourceCount}}resolveView(e,r){let n=j(e,r);if(!n)throw new Error(`View ${r.publisher}/${r.package_}/${r.name} not found in the catalog.`);let t=R(n,vn);if(t){let a=j(e,t);if(!a)throw new Error(`ViewPackage ${r.name} names rootView ${t.name}, which is not in the catalog.`);return a}return n}readProjections(e,r){let n=[];for(let t of $(r,An)){let a=t instanceof k?t:t instanceof b?j(e,t.subject):void 0;if(!a)continue;let i=M(a,Sn),s=R(a,Dn);i&&s&&n.push({value:i,as:s})}return n}async reason(e){return new N({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,r,n){let t=_n(e),a=[],i=new Set;for(let s of n.getInstancesOfClass(r)){if(i.has(s))continue;i.add(s);let c=t.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=w(m(s)),l=w(m(c));return u<l?-1:u>l?1:0}),a}async passesWhere(e,r,n,t){for(let a of n){let i=await this.evaluateValue(e,r,a,t);if(!$n(i))return!1}return!0}async evaluateValue(e,r,n,t){let a=te(n,"view-projection",{catalog:r,depth:0}),i=new Map([["input",t]]);return e.evaluate(a,i)}rowName(e,r){let n=K(e.name)||"row",t=n,a=2;for(;r.has(t);)t=`${n}-${a++}`;return r.add(t),t}};function le(o){return B(o)?o.value:Array.isArray(o)?o.map(le):o}function Un(o){let e=m(o);if(!e)throw new Error(`Could not derive a publisher from view ${o.namespace}/${o.name}.`);return e.publisher}function ue(o,e,r){let n=On(o,e,r);if(!n)throw new Error(`Package ${e}/${r} is not in the catalog; it must be importable to materialize a view.`);return n}function On(o,e,r){let n;for(let t of o){if(!(t instanceof f))continue;let a=m(t);!a||a.publisher!==e||a.package_!==r||!a.version||(!n||V(a.version,n)>0)&&(n=a.version)}return n?y(n):void 0}function _n(o){let e=new Map,r=new Map;for(let n of o){if(!(n instanceof f))continue;let t=m(n);if(!t||!t.version)continue;let a=w(t),i=r.get(a);(!i||V(t.version,i)>0)&&(r.set(a,t.version),e.set(a,n))}return e}function Mn(o,e){let r=M(o,e);return r?[r]:$(o,e).filter(n=>n instanceof k)}function $n(o){return o===!0?!0:o===!1||o===void 0||o===null?!1:typeof o=="string"?o.length>0:typeof o=="number"?o!==0:B(o)?o.value.length>0:Array.isArray(o)?o.length>0:!!o}export{tn as AmbiguousReferenceRule,rr as BooleanStatement,En as CANONICAL_FORM_VERSION,cr as Carrier,un as ClassDefinitionRule,Zr as ClassHierarchyCycleRule,Ae as CompositeKanonakDocumentRepository,yn as DEFAULT_CONSENT_BINDING_PARAM,Ge as DefinedKanonak,je as DocumentLocation,hr as EdgeType,k as EmbeddedKanonak,qr as EmbeddedKanonakTypeRule,tr as EmbeddedStatement,I as EntitlementDeniedError,C as EntitlementProducer,Ve as FileSystemKanonakDocumentRepository,xr as GitIgnoreFilter,Pr as GraphBuilder,Fe as HttpKanonakDocumentRepository,x as ImportBook,Gr as ImportExistenceRule,ve as InMemoryKanonakDocumentRepository,De as KANONAK_USER_AGENT,qe as Kanonak,Ir as KanonakDocumentPositions,E as KanonakObjectParser,dn as KanonakObjectValidator,P as KanonakParser,Je as KanonakUri,jr as KanonakUriBuilder,Cr as KanonakUrlResolver,mr as KanonakVocabulary,or as ListStatement,Ze as LiteralKanonak,Te as LocalFirstRepository,ze as LockAwareRepository,Rn as LookRenderer,ln as MarkdownLinkRule,ar as MarkdownStatement,rn as NamespaceImportCycleRule,Fr as NamespacePrefixRule,gr as NodeType,er as NumberStatement,fn as OAuthDiscovery,wr as OWL_RL_CLASSIFICATION_RULES,an as ObjectPropertyValueValidationRule,Nr as OntologyValidationError,Mr as OntologyValidationResult,g as PackageBuilder,Wr as PackageHeaderRule,A as ProducerRepository,sn as PropertyDomainRule,Qr as PropertyHierarchyCycleRule,cn as PropertyKindRangeConsistencyRule,Kr as PropertyMetadata,on as PropertyRangeReferenceRule,Xr as PropertyRangeRequiredRule,zr as PropertyTypeSpecificityRule,Ne as PublisherConfigResolver,Le as PublisherIndex,Rr as RDFS_RULES,N as Reasoner,Er as ReasoningResult,b as ReferenceKanonak,nr as ReferenceStatement,Se as RepositoryFactory,pn as ReservedNameShadowRule,Tr as ResourceNamingRule,ir as ResourceResolver,kr as ResourceTypeClassifier,Xe as ScalarStatement,Qe as Statement,Ye as StringStatement,Yr as SubClassOfReferenceRule,en as SubPropertyOfReferenceRule,f as SubjectKanonak,Hr as SubjectKanonakTypeRequiredRule,hn as TokenCredentialProvider,br as TripleStore,sr as TypeResolver,nn as UnresolvedPredicateRule,Jr as UnresolvedReferenceRule,Br as ValidationCache,Lr as ValidationContext,$r as ValidationSeverity,_t as VersionOperator,S as ViewMaterializer,H as allowAllPolicy,_e as assertHttpsUrl,Be as assertPackageIdentity,We as buildLocalFirstRepository,xn as buildOntologyModel,wn as canonicalForm,F as canonicalHash,pr as carrierOf,He as collectKanonakFiles,V as compareVersions,re as computeIntegrity,z as contentAddressedName,Or as contextTypesOf,gn as createCredentialedFetch,we as createVersion,fr as extractMarkdownLinks,Pn as findDerivation,_r as findInstancesByType,yr as findMalformedReferences,Vr as findMarkdownLinkAt,Ar as formatKanonakAddress,y as formatVersion,Ce as getGlobalCachePath,Oe as getKanonakUserAgent,xe as isCompatibleVersion,Ke as isMajorCompatible,Me as kanonakFetch,Y as loadLockFile,ur as makeUriKey,W as noopMeter,mn as normalizeHost,kn as parseAuthChallenge,L as parseKanonakAddress,Ee as parseVersionString,vr as parseWithPositions,Ie as pickHighestDocument,Dr as propertiesInScope,bn as resolveDisplayValue,Ur as resolvePropertyStep,K as sanitizeName,ee as saveLockFile,$e as setKanonakFetchRetries,Ue as setKanonakUserAgent,m as subjectUri,Sr as superClassChain,lr as tripleKey,w as uriKey,dr as uriTriple,be as versionOperatorFromChar,_ as versionOperatorToChar,Re as versionsEqual};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "5.12.0",
3
+ "version": "5.13.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",
@@ -126,7 +126,7 @@
126
126
  ],
127
127
  "dependencies": {
128
128
  "@kanonak-protocol/canonical": "^0.1.3",
129
- "@kanonak-protocol/types": "^5.12.0",
129
+ "@kanonak-protocol/types": "^5.13.0",
130
130
  "ignore": "^7.0.5",
131
131
  "js-yaml": "^4.1.0",
132
132
  "yaml": "^2.7.0"
@@ -1,2 +0,0 @@
1
- import{e as U}from"./chunk-UXYCUGSF.js";import{H as ge,I as ye}from"./chunk-7K5TAJ44.js";import{a as ee,b as A,c as ce,h as V,l as $}from"./chunk-MX3DEXMV.js";import{a as h,d as K,e as de,f as fe}from"./chunk-ZP6P7HNU.js";import{i as ue}from"./chunk-GZPLWII7.js";import{b as Z,c as E,d as T,f as te,g as re,h as oe,i as se,j as ae,k as ie,l as F,m as I,r as L,t as pe,v as N,w as le,y as G}from"./chunk-7BHDZHJY.js";import{a as ne}from"./chunk-FUUTGGJS.js";import{d as Q}from"./chunk-2ACBWC7K.js";var ke=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(ke||{}),be=(i=>(i.InstanceOf="instanceOf",i.SubClassOf="subClassOf",i.Domain="domain",i.Range="range",i.ObjectRelationship="objectRelationship",i.SubPropertyOf="subPropertyOf",i.PropertyValue="propertyValue",i.EmbeddedLink="embeddedLink",i))(be||{}),z=class{static async buildFromRepository(n){let r=await new $().parseKanonaks(n),o=await n.getAllDocumentsAsync(),s=[],p=[],a=new Set,i=new Set,g=new Map;for(let c of r){let u=c;u.name&&(h.isClassType(u)&&a.add(u.name),(h.isObjectPropertyType(u)||h.isGenericPropertyType(u))&&i.add(u.name))}for(let c of o)for(let[u,f]of Object.entries(c.body))i.has(u)&&f?.range&&typeof f.range=="string"&&g.set(u,f.range);let d=new Map;for(let c of r){let u=c;u.name&&d.set(u.name,u)}for(let c of o){let u=c.metadata.namespace_,f=u?`${u.publisher}/${u.package_}`:"",l=u?.version?`${u.version.major}.${u.version.minor}.${u.version.patch}`:"",y=me(c);for(let[k,m]of Object.entries(c.body)){if(!m||typeof m!="object")continue;let C=d.get(k),b="Unknown";if(C){let S=C;h.isClassType(S)?b="Class":h.isObjectPropertyType(S)?b="ObjectProperty":h.isDatatypePropertyType(S)?b="DatatypeProperty":h.isAnnotationPropertyType(S)?b="AnnotationProperty":h.isDatatypeType(S)?b="Datatype":h.isGenericPropertyType(S)?b="ObjectProperty":h.isInstanceOfKnownClass(S,a)&&(b="Instance")}let O=f&&l?`${f}/${k}@${l}`:k,J={};for(let[S,M]of Object.entries(m))S!=="type"&&(typeof M!="object"||M===null)&&(J[S]=M);s.push({id:O,label:m.label??k,type:b,namespace:f,properties:J}),he(O,m,b,a,i,p,f,l,y),B(O,m,i,g,s,p,f,l,y),Me(O,C,p)}}return{nodes:s,edges:p}}static buildFromDocument(n){let t=[],r=[],o=n.metadata.namespace_,s=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",p=o?`${o.publisher}/${o.package_}`:"",a=new Set,i=new Set,g=new Map,d=me(n);for(let[f,l]of Object.entries(n.body)){let y=l?.type;y&&(Ke(y,d)&&a.add(f),xe(y,d)&&(i.add(f),l.range&&typeof l.range=="string"&&g.set(f,l.range)))}for(let[f,l]of Object.entries(n.body)){if(!l||typeof l!="object")continue;let y=l.type,k=De(y,f,a,d),m=p&&s?`${p}/${f}@${s}`:f,C={};for(let[b,O]of Object.entries(l))b!=="type"&&(typeof O!="object"||O===null)&&(C[b]=O);t.push({id:m,label:l.label??f,type:k,namespace:p,properties:C}),he(m,l,k,a,i,r,p,s,d),B(m,l,i,g,t,r,p,s,d)}let c=new Set(t.map(f=>f.id)),u=r.filter(f=>c.has(f.source)&&c.has(f.target));return{nodes:t,edges:u}}};function me(e,n){let t=new Map;if(e.metadata?.imports)for(let[r,o]of Object.entries(e.metadata.imports))for(let s of o){let p=s.alias??s.packageName,a=s.version,i=`${a.major}.${a.minor}.${a.patch}`;t.set(p,{publisher:r,package_:s.packageName,version:i})}return t}var Ce={"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"},$e=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function H(e,n){if(e.includes(".")){let t=e.indexOf("."),r=e.substring(0,t),o=e.substring(t+1),s=n.get(r);if(s)return`${s.publisher}/${s.package_}/${o}`}return null}function Ke(e,n){let t=H(e,n);return t?Ce[t]==="Class":!1}function xe(e,n){let t=H(e,n);return t?$e.has(t):!1}function De(e,n,t,r){if(!e||e==="Package")return"Unknown";let o=H(e,r);if(o){let p=Ce[o];if(p)return p;let a=o.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let s=e.split(".").pop()??e;return t.has(s)?"Instance":"Unknown"}var Se=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function he(e,n,t,r,o,s,p,a,i){let g=n.type,d=n.subClassOf;if(d){let l=Array.isArray(d)?d:[d];for(let y of l)typeof y=="string"&&s.push({source:e,target:P(y,p,a,i),type:"subClassOf",label:"subClassOf"})}let c=n.subPropertyOf;if(c){let l=Array.isArray(c)?c:[c];for(let y of l)typeof y=="string"&&s.push({source:e,target:P(y,p,a,i),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&g){let l=g.split(".").pop()??g;s.push({source:e,target:P(l,p,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[l,y]of Object.entries(n)){if(Se.has(l)||!o.has(l))continue;let k=Array.isArray(y)?y:[y];for(let m of k)typeof m=="string"&&Ue(m)&&s.push({source:e,target:P(m,p,a,i),type:"propertyValue",label:l,propertyId:P(l,p,a,i)})}let u=t==="ObjectProperty"||t==="DatatypeProperty",f=n.domain&&n.range;if((u||f)&&n.domain&&n.range){let l=typeof n.domain=="string"?n.domain:null,y=typeof n.range=="string"?n.range:null;l&&y&&s.push({source:P(l,p,a,i),target:P(y,p,a,i),type:"objectRelationship",label:n.label??e.split("/").pop()??"",propertyId:e})}}function B(e,n,t,r,o,s,p,a,i){for(let[g,d]of Object.entries(n)){if(Se.has(g)||typeof d!="object"||d===null||Array.isArray(d))continue;let c=d,u=`${e}/${g}`,f=r.get(g),l=f?f.split(".").pop()??f:"Unknown",y={};for(let[m,C]of Object.entries(c))(typeof C!="object"||C===null)&&(y[m]=C);o.push({id:u,label:`${l} (embedded)`,type:"Instance",namespace:p,properties:y});let k=p&&a?`${p}/${g}@${a}`:g;s.push({source:e,target:u,type:"propertyValue",label:g,propertyId:t.has(g)?k:void 0}),f&&s.push({source:u,target:P(l,p,a,i),type:"instanceOf",label:"type (inferred)"}),B(u,c,t,r,o,s,p,a,i)}}function Me(e,n,t){let r=n?.statement;if(Array.isArray(r))for(let o of r){if(!(o instanceof ce))continue;let s=o.predicate?.subject?.name??"";for(let p of o.links){let a=p.target?.subject;if(!a)continue;let i=a.version,g=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"";t.push({source:e,target:`${a.publisher}/${a.package_}/${a.name}${g}`,type:"embeddedLink",label:s})}}}function Ue(e){return!(!e||e.includes(" ")||e.includes(`
2
- `)||e.startsWith("http://")||e.startsWith("https://")||/^\d{4}-\d{2}/.test(e)||/^\d+(\.\d+)?$/.test(e))}function P(e,n,t,r){if(e.includes("@")&&e.includes("/"))return e;if(e.includes(".")){let o=e.indexOf("."),s=e.substring(0,o),p=e.substring(o+1);if(r){let a=r.get(s);if(a)return`${a.publisher}/${a.package_}/${p}@${a.version}`}return n&&t?`${n}/${p}@${t}`:p}return n&&t?`${n}/${e}@${t}`:e}function _(e){let n=e.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!n)throw new Error("Publisher host cannot be empty");return n}var Fe="key_thumbprint",R=class{cache=new Map;prCache=new Map;async discoverProtectedResource(n){let t=_(n);if(this.prCache.has(t))return this.prCache.get(t);let r=`https://${t}/.well-known/oauth-protected-resource`,o=await Le(r),s=o&&Array.isArray(o.authorization_servers)?o.authorization_servers.filter(a=>typeof a=="string"):[],p=s.length>0?s:null;return this.prCache.set(t,p),p}async discover(n){let t=_(n);if(this.cache.has(t))return this.cache.get(t);let r=`https://${t}/.well-known/oauth-authorization-server`,o=await this.tryEndpoint(r);if(!o){let s=`https://${t}/.well-known/openid-configuration`;o=await this.tryEndpoint(s)}return this.cache.set(t,o),o}async supportsOAuth(n){return await this.discover(n)!==null}static supportsPkceS256(n){return n.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(n){return!!n.registrationEndpoint}static supportsAuthorizationCode(n){return n.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(n){return!!n.enrollmentEndpoint}static supportsSession(n){return!!n.sessionEndpoint}async tryEndpoint(n){let t;try{t=await fetch(n)}catch(o){let s=o instanceof Error?o.message:String(o);return s.includes("ENOTFOUND")||s.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${n} \u2014 host unreachable (${s})`),console.error(" If the server is behind a VPN, ensure you are connected.")):s.includes("CERT")||s.includes("SSL")||s.includes("TLS")?(console.error(` OAuth discovery: ${n} \u2014 TLS error (${s})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${n} \u2014 network error: ${s}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${n} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${n} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let r;try{r=await t.json()}catch{return console.error(` OAuth discovery: ${n} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:v(r.issuer),authorizationEndpoint:v(r.authorization_endpoint),tokenEndpoint:v(r.token_endpoint),registrationEndpoint:v(r.registration_endpoint),revocationEndpoint:v(r.revocation_endpoint),scopesSupported:w(r.scopes_supported),responseTypesSupported:w(r.response_types_supported),grantTypesSupported:w(r.grant_types_supported),codeChallengeMethodsSupported:w(r.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:w(r.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:w(r.dpop_signing_alg_values_supported),enrollmentEndpoint:v(r.enrollment_endpoint),enrollmentIssuanceProtocols:w(r.enrollment_issuance_protocols),enrollmentKeyTypes:w(r.enrollment_key_types),enrollmentScopesSupported:w(r.enrollment_scopes_supported),enrollmentConsentBindingParam:v(r.enrollment_consent_binding_param),sessionEndpoint:v(r.session_endpoint),sessionEndpointAuthMethod:v(r.session_endpoint_auth_method)}}};async function Le(e){try{let n=await fetch(e);return n.ok?await n.json():null}catch{return null}}function v(e){return typeof e=="string"?e:null}function w(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):null}function ve(e){let n=e.headers.get("WWW-Authenticate")??void 0,t=e.headers.get("DPoP-Nonce")??void 0;if(!n&&!t)return;let r={wwwAuthenticate:n??""};if(t&&(r.nonce=t),n){let o=n.match(/acr_values\s*=\s*"([^"]*)"/i);o&&(r.acrValues=o[1])}return r}function Ge(e){try{return new URL(e).host}catch{return null}}function Ve(e,n={}){let t=n.discovery??new R,r=new Map,o=new Map,s=async i=>{let g=r.get(i);if(g!==void 0)return g;let d=null,c=await t.discoverProtectedResource(i).catch(()=>null);return c&&c.length>0&&(d=Ge(c[0])),r.set(i,d),d},p=async(i,g)=>{if(!e)return null;if(!(g.forceRefresh||g.challenge)&&o.has(i))return o.get(i);let c=await e.resolve(i,g).catch(()=>null);return o.set(i,c),c},a=async(i,g,d,c)=>{let u=await s(g);if(!u)return{res:await U(i,{method:d,redirect:"manual"}),authed:!1};let f=await p(u,{method:d,url:i,...c}),l=f?.headers??{};return{res:await U(i,{method:d,redirect:"manual",headers:l}),authed:!!f}};return async(i,g,d="GET")=>{let c=await a(i,g,d,{});if((c.res.status===401||c.res.status===403)&&c.authed){let u=ve(c.res),f={forceRefresh:u===void 0};return u&&(f.challenge=u),(await a(i,g,d,f)).res}return c.res}}var we="KANONAK_TOKEN";function ze(){return typeof process<"u"&&process.env?process.env:{}}function Be(e){return`${we}_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}var q=class{tokens;env;constructor(n={}){this.tokens=n.tokens??{},this.env=n.env??ze()}async resolve(n,t){let r=_(n),o=this.tokens[r]??this.env[Be(r)]??this.env[we];return o?{headers:{Authorization:`Bearer ${o}`}}:null}};import{canonicalForm as He,canonicalHash as qe}from"@kanonak-protocol/canonical";function W(e){return typeof e=="object"&&e!==null&&Array.isArray(e.subjects)}import{CANONICAL_FORM_VERSION as rn}from"@kanonak-protocol/canonical";function We(e){return He(W(e)?e:Pe(e))}function Xe(e){return qe(W(e)?e:Pe(e))}function Pe(e){let n=[];for(let t of e)t instanceof E&&n.push({uri:tn(t),statements:X(t.statement)});return{subjects:n}}function X(e){let n=[];for(let t of e){let r=nn(t);if(!r)continue;if(t instanceof F&&Ye(t.predicate.subject)){n.push(...Qe(t,r));continue}let o=Ze(t);o&&n.push({predicate:r,value:o})}return n}function Ye(e){let n=ue("type");return n!==void 0&&e.name==="type"&&e.publisher===n.publisher&&e.package_===n.package_}var Oe=new TextEncoder;function Je(e,n){let t=Oe.encode(e),r=Oe.encode(n),o=Math.min(t.length,r.length);for(let s=0;s<o;s++)if(t[s]!==r[s])return t[s]-r[s];return t.length-r.length}function Qe(e,n){let t=[];for(let r of e.object){if(!(r instanceof T))throw new Error(`canonicalForm: a multi-valued type statement must contain only entity references, got ${r.constructor?.name??typeof r}`);t.push(Y(r))}t.sort(Je);for(let r=1;r<t.length;r++)if(t[r-1]===t[r])throw new Error(`canonicalForm: duplicate type ${t[r]} in a multi-valued type statement`);return t.map(r=>({predicate:n,value:{ref:r}}))}function Ze(e){if(e instanceof te&&e.carrier)return{lit:e.lexical??String(e.object),datatype:Te(e.carrier)};if(e instanceof re)return{raw:e.object};if(e instanceof oe)return{raw:e.lexical??String(e.object)};if(e instanceof se)return{raw:e.lexical??String(e.object)};if(e instanceof ae)return{ref:Y(e.object)};if(e instanceof ie)return je(e.object);if(e instanceof F)return{list:e.object.map(en)}}function je(e){let n=X(e.statement);return e.name&&e.name.length>0?{embed:{name:e.name,statements:n}}:{embed:{statements:n}}}function en(e){if(e instanceof T)return{ref:Y(e)};if(e instanceof ee)return je(e);if(e instanceof A){if(e.carrier)return{lit:e.lexical??String(e.value),datatype:Te(e.carrier)};let n=e.value;if(typeof n=="string")return{raw:n};if(typeof n=="number")return{raw:String(n)};if(typeof n=="boolean")return{raw:String(n)}}if(e instanceof Z)return{embed:{statements:X(e.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${e.constructor?.name??typeof e}); add canonicalization support before hashing data that contains it`)}function Te(e){return e===V.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${e}`}function nn(e){let n=e.predicate;if(n)return _e(n.subject)}function tn(e){let n=e.namespace??"",t=e.name??"";return`${n}/${t}`}function Y(e){return _e(e.subject)}function _e(e){let n=e.version;return n&&typeof n.major=="number"?`${e.publisher}/${e.package_}@${n.major}.${n.minor}.${n.patch}/${e.name}`:`${e.publisher}/${e.package_}/${e.name}`}var j="kanonak.org",D="core-rdf",Ee="core-xsd",Re={publisher:j,package_:D,name:"subClassOf"},Ae={publisher:j,package_:D,name:"label"},on={publisher:j,package_:D,name:"comment"},Ie={publisher:j,package_:"core-owl",name:"oneOf"},Ne=e=>e;function sn(e){let n=le(e,Re);if(n)return[n];let t=[];for(let r of G(e,Re))r instanceof T&&t.push(r.subject);return t}function an(e,n,t){if(n.publisher===j&&n.package_===D&&n.name==="Literal")return{kind:"datatype",uri:n};let o=L(e,n);if(o){let s=Ne(o);if(h.isDatatypeType(s))return{kind:"datatype",uri:n};if(h.isClassType(s))return{kind:"class",uri:K(o)??n,localName:o.name}}return n.publisher===j&&n.package_===Ee?{kind:"datatype",uri:n}:t==="datatype"?{kind:"datatype",uri:n}:{kind:"class",uri:n,localName:n.name}}function cn(e,n,t){if(!n.range)throw new Error(`Property ${n.uri.publisher}/${n.uri.package_}/${n.uri.name} has no rdfs.range; every property must declare a range. Validate the ontology before introspecting it.`);let r=an(e,n.range,n.kind),o=n.kind==="object"?"object":n.kind==="datatype"?"datatype":r.kind==="class"?"object":"datatype";return{uri:n.uri,localName:n.uri.name,kind:o,range:r,...n.label!==void 0?{label:n.label}:{},...n.comment!==void 0?{comment:n.comment}:{},...t??{}}}var x=e=>new ne(j,Ee,e);function pn(e){return typeof e=="boolean"?x("boolean"):typeof e=="number"?Number.isInteger(e)?x("integer"):x("decimal"):x("string")}function ln(e,n){let t=[];for(let r of G(n,Ie))if(r instanceof T){let o=L(e,r.subject),s=(o?K(o):void 0)??r.subject,p=o?N(o,Ae):void 0;t.push({kind:"individual",uri:s,localName:s.name,...p!==void 0?{label:p}:{}})}else r instanceof A&&t.push({kind:"literal",value:r.value,datatype:pn(r.value)});return t}function un(e,n,t,r){let o=de(e,n),s=I(n);return fe(e,n).filter(a=>t?!0:a.domains.some(i=>I(i)===s)).map(a=>cn(e,a,ye(r,o,a.uri)))}async function dn(e,n,t){let r=e.metadata?.namespace_;if(!r)throw new Error("buildOntologyModel: document has no namespace (publisher/package/version).");let o=t?.includeInherited??!1,s=await new $().parseKanonaks(n),p=ge(s),a=[],i=[],g=new Set;for(let d of s){if(!(d instanceof E)||!h.isClassType(Ne(d)))continue;let c=K(d);if(!c||c.publisher!==r.publisher||c.package_!==r.package_||c.version&&r.version&&!Q(c.version,r.version))continue;let u=I(c);if(g.has(u))continue;g.add(u);let f=sn(d).map(k=>({uri:k,localName:k.name})),l=N(d,Ae),y=N(d,on);a.push({uri:c,localName:c.name,superClasses:f,properties:un(s,c,o,p),...l!==void 0?{label:l}:{},...y!==void 0?{comment:y}:{}}),pe(d,Ie)&&i.push({uri:c,localName:c.name,members:ln(s,d),...l!==void 0?{label:l}:{},...y!==void 0?{comment:y}:{}})}return{classes:a,enums:i}}export{ke as a,be as b,z as c,_ as d,Fe as e,R as f,ve as g,Ve as h,q as i,We as j,Xe as k,rn as l,dn as m};