@kanonak-protocol/sdk 5.3.0 → 5.4.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.d.ts CHANGED
@@ -27,6 +27,8 @@ export { PublisherConfigResolver } from './repositories/PublisherConfig.js';
27
27
  export type { PublisherConfig } from './repositories/PublisherConfig.js';
28
28
  export { findDerivation } from './derivation/index.js';
29
29
  export type { DerivationEntityUri, TransformationReferenceTuple, DerivationLookupResult, } from './derivation/index.js';
30
+ export { canonicalForm, canonicalHash, CANONICAL_FORM_VERSION, Carrier, carrierOf, } from './canonical/index.js';
31
+ export type { CanonicalInput, CanonicalInputSubject, CanonicalInputStatement, CanonicalInputValue, } from './canonical/index.js';
30
32
  export { buildOntologyModel } from './introspection/index.js';
31
33
  export type { OntologyModel, ClassDef, PropertyDef, ClassRef, TypeRef, BuildOntologyModelOptions, } from './introspection/index.js';
32
34
  export { isExpired, hasValidToken, normalizeHost } from './auth/CredentialBackend.js';
package/dist/browser.js CHANGED
@@ -1 +1 @@
1
- import{a as U,b as B,c as A,d as ke,e as xe,f as Pe,g as Ke}from"./chunk-S5URV3V7.js";import{a as ge}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as m,b as u,c as d,d as c,f as y,g as R,h as f}from"./chunk-JYBKSBB5.js";import{a as p}from"./chunk-4NO7MHS7.js";import{a as G,b as H,c as L}from"./chunk-S6VSAKXB.js";import{a as w,b as q}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as ye,B as Re,K as fe,a as W,b as _,c as z,d as F,f as J,g as Q,h as X,i as Y,k as Z,l as $,m as ee,n as oe,o as te,p as re,q as ne,r as ae,s as ie,t as se,u as pe,v as le,w as me,x as ue,y as de,z as ce}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as g,c as E,l as N}from"./chunk-MX3DEXMV.js";import{a as l}from"./chunk-NJ3AZYQD.js";import{a as M}from"./chunk-ZP6P7HNU.js";import"./chunk-6U26UASC.js";import{a as v,b as T}from"./chunk-GZPLWII7.js";import{a as k,b as x,c as P,d as S,e as b,f as D,g as h,h as C,i as V,j,k as I,l as O}from"./chunk-7BHDZHJY.js";import{a as K}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{pe as AmbiguousReferenceRule,V as BooleanStatement,ye as ClassDefinitionRule,oe as ClassHierarchyCycleRule,x as DefinedKanonak,B as EdgeType,g as EmbeddedKanonak,Z as EmbeddedKanonakTypeRule,I as EmbeddedStatement,A as GraphBuilder,f as HttpKanonakDocumentRepository,$ as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,m as KANONAK_USER_AGENT,k as Kanonak,H as KanonakDocumentPositions,N as KanonakObjectParser,fe as KanonakObjectValidator,l as KanonakParser,K as KanonakUri,w as KanonakUriBuilder,O as ListStatement,Re as MarkdownLinkRule,E as MarkdownStatement,ie as NamespaceImportCycleRule,J as NamespacePrefixRule,U as NodeType,C as NumberStatement,me as ObjectPropertyValueValidationRule,z as OntologyValidationError,W as OntologyValidationResult,ue as PropertyDomainRule,te as PropertyHierarchyCycleRule,de as PropertyKindRangeConsistencyRule,G as PropertyMetadata,le as PropertyRangeReferenceRule,re as PropertyRangeRequiredRule,X as PropertyTypeSpecificityRule,y as PublisherConfigResolver,R as PublisherIndex,S as ReferenceKanonak,j as ReferenceStatement,ce as ReservedNameShadowRule,Q as ResourceNamingRule,v as ResourceResolver,M as ResourceTypeClassifier,D as ScalarStatement,b as Statement,h as StringStatement,ne as SubClassOfReferenceRule,ae as SubPropertyOfReferenceRule,P as SubjectKanonak,Y as SubjectKanonakTypeRequiredRule,T as TypeResolver,se as UnresolvedPredicateRule,ee as UnresolvedReferenceRule,F as ValidationContext,_ as ValidationSeverity,Ke as buildOntologyModel,e as compareVersions,r as createVersion,ge as findDerivation,q as findInstancesByType,t as formatVersion,d as getKanonakUserAgent,xe as hasValidToken,a as isCompatibleVersion,ke as isExpired,i as isMajorCompatible,c as kanonakFetch,Pe as normalizeHost,n as parseVersionString,L as parseWithPositions,s as pickHighestDocument,u as setKanonakUserAgent,o as versionsEqual};
1
+ import{a as B,b as H,c as L,d as Pe,e as ge,f as Ke,g as Ce,h as be,i as Ie,j as Ve}from"./chunk-VOJ6BGAR.js";import{a as Se}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as m,b as u,c,d,f as y,g as R,h as f}from"./chunk-JYBKSBB5.js";import{a as p}from"./chunk-4NO7MHS7.js";import{a as G,b as w,c as _}from"./chunk-S6VSAKXB.js";import{a as q,b as F}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as fe,B as ke,K as xe,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 ye,z as Re}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as g,c as E,h as T,i as M,l as A}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 N,b as v}from"./chunk-GZPLWII7.js";import{a as k,b as x,c as P,d as S,e as C,f as b,g as I,h as V,i as h,j,k as D,l as O}from"./chunk-7BHDZHJY.js";import{a as K}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,h as BooleanStatement,Ie as CANONICAL_FORM_VERSION,T as Carrier,fe as ClassDefinitionRule,re as ClassHierarchyCycleRule,x 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,k as Kanonak,w as KanonakDocumentPositions,A as KanonakObjectParser,xe as KanonakObjectValidator,l as KanonakParser,K as KanonakUri,q as KanonakUriBuilder,O as ListStatement,ke as MarkdownLinkRule,E as MarkdownStatement,pe as NamespaceImportCycleRule,X as NamespacePrefixRule,B as NodeType,V as NumberStatement,ce as ObjectPropertyValueValidationRule,J as OntologyValidationError,W as OntologyValidationResult,de as PropertyDomainRule,ne as PropertyHierarchyCycleRule,ye as PropertyKindRangeConsistencyRule,G as PropertyMetadata,ue as PropertyRangeReferenceRule,ae as PropertyRangeRequiredRule,Z as PropertyTypeSpecificityRule,y as PublisherConfigResolver,R as PublisherIndex,S as ReferenceKanonak,j as ReferenceStatement,Re as ReservedNameShadowRule,Y as ResourceNamingRule,N as ResourceResolver,U as ResourceTypeClassifier,b as ScalarStatement,C as Statement,I as StringStatement,ie as SubClassOfReferenceRule,se as SubPropertyOfReferenceRule,P as SubjectKanonak,$ as SubjectKanonakTypeRequiredRule,v as TypeResolver,le as UnresolvedPredicateRule,te as UnresolvedReferenceRule,Q as ValidationContext,z as ValidationSeverity,Ve as buildOntologyModel,Ce as canonicalForm,be as canonicalHash,M as carrierOf,e as compareVersions,r as createVersion,Se as findDerivation,F as findInstancesByType,t as formatVersion,c as getKanonakUserAgent,ge as hasValidToken,a as isCompatibleVersion,Pe as isExpired,i as isMajorCompatible,d as kanonakFetch,Ke as normalizeHost,n as parseVersionString,_ as parseWithPositions,s as pickHighestDocument,u as setKanonakUserAgent,o as versionsEqual};
@@ -0,0 +1,2 @@
1
+ import{H as sn,I as cn}from"./chunk-7K5TAJ44.js";import{a as z,b as K,c as en,h as U,l as N}from"./chunk-MX3DEXMV.js";import{a as k,d as $,e as on,f as an}from"./chunk-ZP6P7HNU.js";import{b as H,c as O,d as T,f as q,g as W,h as X,i as J,j as Q,k as Z,l as nn,m as w,r as v,t as tn,v as x,w as rn,y as _}from"./chunk-7BHDZHJY.js";import{a as Y}from"./chunk-FUUTGGJS.js";import{d as B}from"./chunk-2ACBWC7K.js";var ln=(r=>(r.Class="Class",r.DatatypeProperty="DatatypeProperty",r.ObjectProperty="ObjectProperty",r.AnnotationProperty="AnnotationProperty",r.Instance="Instance",r.Datatype="Datatype",r.Unknown="Unknown",r))(ln||{}),fn=(c=>(c.InstanceOf="instanceOf",c.SubClassOf="subClassOf",c.Domain="domain",c.Range="range",c.ObjectRelationship="objectRelationship",c.SubPropertyOf="subPropertyOf",c.PropertyValue="propertyValue",c.EmbeddedLink="embeddedLink",c))(fn||{}),M=class{static async buildFromRepository(e){let a=await new N().parseKanonaks(e),o=await e.getAllDocumentsAsync(),i=[],s=[],r=new Set,c=new Set,g=new Map;for(let l of a){let u=l;u.name&&(k.isClassType(u)&&r.add(u.name),(k.isObjectPropertyType(u)||k.isGenericPropertyType(u))&&c.add(u.name))}for(let l of o)for(let[u,f]of Object.entries(l.body))c.has(u)&&f?.range&&typeof f.range=="string"&&g.set(u,f.range);let y=new Map;for(let l of a){let u=l;u.name&&y.set(u.name,u)}for(let l of o){let u=l.metadata.namespace_,f=u?`${u.publisher}/${u.package_}`:"",p=u?.version?`${u.version.major}.${u.version.minor}.${u.version.patch}`:"",d=pn(l);for(let[b,m]of Object.entries(l.body)){if(!m||typeof m!="object")continue;let C=y.get(b),h="Unknown";if(C){let j=C;k.isClassType(j)?h="Class":k.isObjectPropertyType(j)?h="ObjectProperty":k.isDatatypePropertyType(j)?h="DatatypeProperty":k.isAnnotationPropertyType(j)?h="AnnotationProperty":k.isDatatypeType(j)?h="Datatype":k.isGenericPropertyType(j)?h="ObjectProperty":k.isInstanceOfKnownClass(j,r)&&(h="Instance")}let S=f&&p?`${f}/${b}@${p}`:b,F={};for(let[j,E]of Object.entries(m))j!=="type"&&(typeof E!="object"||E===null)&&(F[j]=E);i.push({id:S,label:m.label??b,type:h,namespace:f,properties:F}),un(S,m,h,r,c,s,f,p,d),A(S,m,c,g,i,s,f,p,d),xn(S,C,s)}}return{nodes:i,edges:s}}static buildFromDocument(e){let t=[],a=[],o=e.metadata.namespace_,i=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",s=o?`${o.publisher}/${o.package_}`:"",r=new Set,c=new Set,g=new Map,y=pn(e);for(let[f,p]of Object.entries(e.body)){let d=p?.type;d&&(On(d,y)&&r.add(f),Kn(d,y)&&(c.add(f),p.range&&typeof p.range=="string"&&g.set(f,p.range)))}for(let[f,p]of Object.entries(e.body)){if(!p||typeof p!="object")continue;let d=p.type,b=wn(d,f,r,y),m=s&&i?`${s}/${f}@${i}`:f,C={};for(let[h,S]of Object.entries(p))h!=="type"&&(typeof S!="object"||S===null)&&(C[h]=S);t.push({id:m,label:p.label??f,type:b,namespace:s,properties:C}),un(m,p,b,r,c,a,s,i,y),A(m,p,c,g,t,a,s,i,y)}let l=new Set(t.map(f=>f.id)),u=a.filter(f=>l.has(f.source)&&l.has(f.target));return{nodes:t,edges:u}}};function pn(n,e){let t=new Map;if(n.metadata?.imports)for(let[a,o]of Object.entries(n.metadata.imports))for(let i of o){let s=i.alias??i.packageName,r=i.version,c=`${r.major}.${r.minor}.${r.patch}`;t.set(s,{publisher:a,package_:i.packageName,version:c})}return t}var dn={"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"},Tn=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function L(n,e){if(n.includes(".")){let t=n.indexOf("."),a=n.substring(0,t),o=n.substring(t+1),i=e.get(a);if(i)return`${i.publisher}/${i.package_}/${o}`}return null}function On(n,e){let t=L(n,e);return t?dn[t]==="Class":!1}function Kn(n,e){let t=L(n,e);return t?Tn.has(t):!1}function wn(n,e,t,a){if(!n||n==="Package")return"Unknown";let o=L(n,a);if(o){let s=dn[o];if(s)return s;let r=o.split("/").pop()?.split("@")[0]??"";return t.has(r)?"Instance":"Unknown"}let i=n.split(".").pop()??n;return t.has(i)?"Instance":"Unknown"}var yn=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function un(n,e,t,a,o,i,s,r,c){let g=e.type,y=e.subClassOf;if(y){let p=Array.isArray(y)?y:[y];for(let d of p)typeof d=="string"&&i.push({source:n,target:P(d,s,r,c),type:"subClassOf",label:"subClassOf"})}let l=e.subPropertyOf;if(l){let p=Array.isArray(l)?l:[l];for(let d of p)typeof d=="string"&&i.push({source:n,target:P(d,s,r,c),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&g){let p=g.split(".").pop()??g;i.push({source:n,target:P(p,s,r,c),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[p,d]of Object.entries(e)){if(yn.has(p)||!o.has(p))continue;let b=Array.isArray(d)?d:[d];for(let m of b)typeof m=="string"&&Nn(m)&&i.push({source:n,target:P(m,s,r,c),type:"propertyValue",label:p,propertyId:P(p,s,r,c)})}let u=t==="ObjectProperty"||t==="DatatypeProperty",f=e.domain&&e.range;if((u||f)&&e.domain&&e.range){let p=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;p&&d&&i.push({source:P(p,s,r,c),target:P(d,s,r,c),type:"objectRelationship",label:e.label??n.split("/").pop()??"",propertyId:n})}}function A(n,e,t,a,o,i,s,r,c){for(let[g,y]of Object.entries(e)){if(yn.has(g)||typeof y!="object"||y===null||Array.isArray(y))continue;let l=y,u=`${n}/${g}`,f=a.get(g),p=f?f.split(".").pop()??f:"Unknown",d={};for(let[m,C]of Object.entries(l))(typeof C!="object"||C===null)&&(d[m]=C);o.push({id:u,label:`${p} (embedded)`,type:"Instance",namespace:s,properties:d});let b=s&&r?`${s}/${g}@${r}`:g;i.push({source:n,target:u,type:"propertyValue",label:g,propertyId:t.has(g)?b:void 0}),f&&i.push({source:u,target:P(p,s,r,c),type:"instanceOf",label:"type (inferred)"}),A(u,l,t,a,o,i,s,r,c)}}function xn(n,e,t){let a=e?.statement;if(Array.isArray(a))for(let o of a){if(!(o instanceof en))continue;let i=o.predicate?.subject?.name??"";for(let s of o.links){let r=s.target?.subject;if(!r)continue;let c=r.version,g=c&&typeof c.major=="number"?`@${c.major}.${c.minor}.${c.patch}`:"";t.push({source:n,target:`${r.publisher}/${r.package_}/${r.name}${g}`,type:"embeddedLink",label:i})}}}function Nn(n){return!(!n||n.includes(" ")||n.includes(`
2
+ `)||n.startsWith("http://")||n.startsWith("https://")||/^\d{4}-\d{2}/.test(n)||/^\d+(\.\d+)?$/.test(n))}function P(n,e,t,a){if(n.includes("@")&&n.includes("/"))return n;if(n.includes(".")){let o=n.indexOf("."),i=n.substring(0,o),s=n.substring(o+1);if(a){let r=a.get(i);if(r)return`${r.publisher}/${r.package_}/${s}@${r.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${n}@${t}`:n}function $n(n){if(!n.expiresAt)return!1;let e=new Date(n.expiresAt),t=300*1e3;return e.getTime()<=Date.now()+t}function te(n){return!!n.accessToken&&!$n(n)}function re(n){let e=n.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}import{canonicalForm as Dn,canonicalHash as Rn}from"@kanonak-protocol/canonical";function G(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}import{CANONICAL_FORM_VERSION as Ln}from"@kanonak-protocol/canonical";function En(n){return Dn(G(n)?n:gn(n))}function vn(n){return Rn(G(n)?n:gn(n))}function gn(n){let e=[];for(let t of n)t instanceof O&&e.push({uri:An(t),statements:V(t.statement)});return{subjects:e}}function V(n){let e=[];for(let t of n){let a=Mn(t);if(!a)continue;let o=_n(t);o&&e.push({predicate:a,value:o})}return e}function _n(n){if(n instanceof q&&n.carrier)return{lit:n.lexical??String(n.object),datatype:kn(n.carrier)};if(n instanceof W)return{raw:n.object};if(n instanceof X)return{raw:n.lexical??String(n.object)};if(n instanceof J)return{raw:n.lexical??String(n.object)};if(n instanceof Q)return{ref:bn(n.object)};if(n instanceof Z)return mn(n.object);if(n instanceof nn)return{list:n.object.map(Un)}}function mn(n){let e=V(n.statement);return n.name&&n.name.length>0?{embed:{name:n.name,statements:e}}:{embed:{statements:e}}}function Un(n){if(n instanceof T)return{ref:bn(n)};if(n instanceof z)return mn(n);if(n instanceof K){if(n.carrier)return{lit:n.lexical??String(n.value),datatype:kn(n.carrier)};let e=n.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(n instanceof H)return{embed:{statements:V(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 kn(n){return n===U.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${n}`}function Mn(n){let e=n.predicate;if(e)return hn(e.subject)}function An(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function bn(n){return hn(n.subject)}function hn(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}`}var I="kanonak.org",R="core-rdf",jn="core-xsd",Cn={publisher:I,package_:R,name:"subClassOf"},Sn={publisher:I,package_:R,name:"label"},Gn={publisher:I,package_:R,name:"comment"},Pn={publisher:I,package_:"core-owl",name:"oneOf"},In=n=>n;function Vn(n){let e=rn(n,Cn);if(e)return[e];let t=[];for(let a of _(n,Cn))a instanceof T&&t.push(a.subject);return t}function Fn(n,e,t){if(e.publisher===I&&e.package_===R&&e.name==="Literal")return{kind:"datatype",uri:e};let o=v(n,e);if(o){let i=In(o);if(k.isDatatypeType(i))return{kind:"datatype",uri:e};if(k.isClassType(i))return{kind:"class",uri:$(o)??e,localName:o.name}}return e.publisher===I&&e.package_===jn?{kind:"datatype",uri:e}:t==="datatype"?{kind:"datatype",uri:e}:{kind:"class",uri:e,localName:e.name}}function Bn(n,e,t){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=Fn(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}:{},...t??{}}}var D=n=>new Y(I,jn,n);function Hn(n){return typeof n=="boolean"?D("boolean"):typeof n=="number"?Number.isInteger(n)?D("integer"):D("decimal"):D("string")}function zn(n,e){let t=[];for(let a of _(e,Pn))if(a instanceof T){let o=v(n,a.subject),i=(o?$(o):void 0)??a.subject,s=o?x(o,Sn):void 0;t.push({kind:"individual",uri:i,localName:i.name,...s!==void 0?{label:s}:{}})}else a instanceof K&&t.push({kind:"literal",value:a.value,datatype:Hn(a.value)});return t}function Yn(n,e,t,a){let o=on(n,e),i=w(e);return an(n,e).filter(r=>t?!0:r.domains.some(c=>w(c)===i)).map(r=>Bn(n,r,cn(a,o,r.uri)))}async function qn(n,e,t){let a=n.metadata?.namespace_;if(!a)throw new Error("buildOntologyModel: document has no namespace (publisher/package/version).");let o=t?.includeInherited??!1,i=await new N().parseKanonaks(e),s=sn(i),r=[],c=[],g=new Set;for(let y of i){if(!(y instanceof O)||!k.isClassType(In(y)))continue;let l=$(y);if(!l||l.publisher!==a.publisher||l.package_!==a.package_||l.version&&a.version&&!B(l.version,a.version))continue;let u=w(l);if(g.has(u))continue;g.add(u);let f=Vn(y).map(b=>({uri:b,localName:b.name})),p=x(y,Sn),d=x(y,Gn);r.push({uri:l,localName:l.name,superClasses:f,properties:Yn(i,l,o,s),...p!==void 0?{label:p}:{},...d!==void 0?{comment:d}:{}}),tn(y,Pn)&&c.push({uri:l,localName:l.name,members:zn(i,y),...p!==void 0?{label:p}:{},...d!==void 0?{comment:d}:{}})}return{classes:r,enums:c}}export{ln as a,fn as b,M as c,$n as d,te as e,re as f,En as g,vn as h,Ln as i,qn as j};
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import{a as _r,b as Nr,c as Or,d as jr,e as Ie}from"./chunk-TVSHIXLA.js";import{a as An,c as Ke,e as Ye,h as Ze,i as Qe,j as In}from"./chunk-IHB7UVEH.js";import{a as Kr,b as $r,c as Tr,d as Q,e as ee,f as l,g as Dn}from"./chunk-S5URV3V7.js";import{a as xn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as rr,b as nr,c as or,d as ir,e as sr,f as fr,g as yr,h as hr,i as gr}from"./chunk-GMEPM2QQ.js";import{a as ar,b as cr,c as lr,d as D,f as dr,g as pr,h as mr}from"./chunk-JYBKSBB5.js";import{a as tr}from"./chunk-4NO7MHS7.js";import{a as Mr,b as Vr,c as Lr,d as Fr}from"./chunk-S6VSAKXB.js";import{a as Ur,b as Xr}from"./chunk-PEUTCG3B.js";import{a as zr}from"./chunk-PEJALHXK.js";import{a as ur}from"./chunk-SC5M74NM.js";import{A as Rn,B as En,K as Cn,a as Yr,b as Zr,c as Qr,d as en,e as tn,f as rn,g as nn,h as on,i as sn,j as an,k as cn,l as ln,m as dn,n as pn,o as un,p as mn,q as fn,r as yn,s as hn,t as gn,u as kn,v as Sn,w as wn,x as vn,y as bn,z as Pn}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as b,b as Se,c as vr,h as Z,i as qe,j as Ar,k as Ir,l as F}from"./chunk-MX3DEXMV.js";import{a as M}from"./chunk-NJ3AZYQD.js";import{a as Dr,b as De,c as Hr,d as P,e as Wr,f as Gr,g as Jr,h as qr}from"./chunk-ZP6P7HNU.js";import{a as Xe}from"./chunk-6U26UASC.js";import{a as br,b as Pr,c as L,d as Rr,e as Er,g as Cr,k as xr}from"./chunk-GZPLWII7.js";import{a as kr,b as ke,c as v,d as x,e as wr,f as we,g as ve,h as be,i as Pe,j as Re,k as Ee,l as Ce,r as Y,w as V,x as xe,y as Ae}from"./chunk-7BHDZHJY.js";import{a as Sr}from"./chunk-FUUTGGJS.js";import{a as Jt,b as ge,c as X,d as qt,e as C,f as Xt,g as Yt,h as Zt,i as Qt,j as er}from"./chunk-2ACBWC7K.js";import{a as Br}from"./chunk-ODIECDN7.js";import{VersionOperator as Ma}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Zn,readFileSync as Qn}from"fs";import{homedir as eo}from"os";import{join as to}from"path";import{execFile as Kn}from"child_process";import{promisify as $n}from"util";var te=$n(Kn),Tn="kanonak",re="/usr/bin/security",m=class{constructor(e=Tn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await te(re,["find-generic-password","-s",this.service,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
2
- Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(n){if(et(n,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${ne(n)}
1
+ import{a as Rr,b as xr,c as Cr,d as Ar,e as ke}from"./chunk-TVSHIXLA.js";import{a as Sn,c as ve,e as je,h as Me,i as Ve,j as vn}from"./chunk-IHB7UVEH.js";import{a as Pr,b as br,c as Er,d as Z,e as Q,f as l,g as wn,h as we,i as Pn,j as bn}from"./chunk-VOJ6BGAR.js";import{a as kn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as Ot,b as Bt,c as jt,d as Mt,e as Vt,f as Jt,g as qt,h as Xt,i as Yt}from"./chunk-GMEPM2QQ.js";import{a as Lt,b as Ft,c as Ut,d as C,f as Ht,g as zt,h as Gt}from"./chunk-JYBKSBB5.js";import{a as Nt}from"./chunk-4NO7MHS7.js";import{a as Tr,b as _r,c as $r,d as Ir}from"./chunk-S6VSAKXB.js";import{a as Kr,b as Lr}from"./chunk-PEUTCG3B.js";import{a as Or}from"./chunk-PEJALHXK.js";import{a as Wt}from"./chunk-SC5M74NM.js";import{A as fn,B as hn,K as gn,a as Fr,b as Ur,c as Hr,d as zr,e as Wr,f as Gr,g as Jr,h as qr,i as Xr,j as Yr,k as Zr,l as Qr,m as en,n as tn,o as rn,p as nn,q as on,r as sn,s as an,t as cn,u as ln,v as dn,w as pn,x as un,y as mn,z as yn}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as D,b as tr,c as dr,h as mr,i as yr,j as Sr,k as vr,l as F}from"./chunk-MX3DEXMV.js";import{a as j}from"./chunk-NJ3AZYQD.js";import{a as wr,b as Se,c as Nr,d as w,e as Br,f as jr,g as Mr,h as Vr}from"./chunk-ZP6P7HNU.js";import{a as Be}from"./chunk-6U26UASC.js";import{a as pr,b as ur,c as L,d as fr,e as hr,g as gr,k as kr}from"./chunk-GZPLWII7.js";import{a as Zt,b as Qt,c as A,d as M,e as rr,f as nr,g as or,h as sr,i as ir,j as ar,k as cr,l as lr,r as Y,w as V,x as he,y as ge}from"./chunk-7BHDZHJY.js";import{a as er}from"./chunk-FUUTGGJS.js";import{a as At,b as fe,c as X,d as Dt,e as E,f as Tt,g as _t,h as $t,i as It,j as Kt}from"./chunk-2ACBWC7K.js";import{a as Dr}from"./chunk-ODIECDN7.js";import{VersionOperator as fa}from"@kanonak-protocol/types/document/models/enums";import{existsSync as zn,readFileSync as Wn}from"fs";import{homedir as Gn}from"os";import{join as Jn}from"path";import{execFile as En}from"child_process";import{promisify as Rn}from"util";var ee=Rn(En),xn="kanonak",te="/usr/bin/security",m=class{constructor(e=xn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:r}=await ee(te,["find-generic-password","-s",this.service,"-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
+ Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if(Le(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${re(r)}
3
3
  The Keychain may be locked or inaccessible.
4
- Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let n=l(e),o=JSON.stringify(t);try{await te(re,["add-generic-password","-s",this.service,"-a",n,"-U","-w",o],{timeout:1e4})}catch(i){throw new Error(`macOS Keychain write failed for '${n}': ${ne(i)}
4
+ Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let r=l(e),n=JSON.stringify(t);try{await ee(te,["add-generic-password","-s",this.service,"-a",r,"-U","-w",n],{timeout:1e4})}catch(s){throw new Error(`macOS Keychain write failed for '${r}': ${re(s)}
5
5
  Ensure the Keychain is unlocked and the CLI has write permission.
6
- On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await te(re,["delete-generic-password","-s",this.service,"-a",t],{timeout:1e4})}catch(n){if(et(n,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${ne(n)}
7
- The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await te(re,["dump-keychain"],{timeout:1e4}),t=[],n=!1;for(let o of e.split(`
8
- `))if(o.includes(`"svce"<blob>="${this.service}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let i=o.match(/"acct"<blob>="([^"]+)"/);i&&t.push(i[1]),n=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${ne(e)}`),[]}}};function et(r,e){return typeof r=="object"&&r!==null&&"code"in r&&r.code===e}function ne(r){return r instanceof Error?r.message:String(r)}import{execFile as _n}from"child_process";import{promisify as Nn}from"util";var On=Nn(_n),jn="kanonak:",tt=2560,f=class{constructor(e=jn){this.targetPrefix=e}targetPrefix;async get(e){let t=this.targetPrefix+l(e),n=`
9
- ${ie}
6
+ On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await ee(te,["delete-generic-password","-s",this.service,"-a",t],{timeout:1e4})}catch(r){if(Le(r,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${re(r)}
7
+ The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await ee(te,["dump-keychain"],{timeout:1e4}),t=[],r=!1;for(let n of e.split(`
8
+ `))if(n.includes(`"svce"<blob>="${this.service}"`)&&(r=!0),r&&n.includes('"acct"<blob>=')){let s=n.match(/"acct"<blob>="([^"]+)"/);s&&t.push(s[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${re(e)}`),[]}}};function Le(o,e){return typeof o=="object"&&o!==null&&"code"in o&&o.code===e}function re(o){return o instanceof Error?o.message:String(o)}import{execFile as Cn}from"child_process";import{promisify as An}from"util";var Dn=An(Cn),Tn="kanonak:",Fe=2560,y=class{constructor(e=Tn){this.targetPrefix=e}targetPrefix;async get(e){let t=this.targetPrefix+l(e),r=`
9
+ ${oe}
10
10
  $target = $env:KANONAK_CRED_TARGET
11
11
  $ptr = [IntPtr]::Zero
12
12
  $result = [CredMan]::CredRead($target, 1, 0, [ref]$ptr)
@@ -18,8 +18,8 @@ try {
18
18
  [System.Text.Encoding]::Unicode.GetString($bytes)
19
19
  } finally {
20
20
  [CredMan]::CredFree($ptr)
21
- }`;try{let{stdout:o}=await oe(n,{KANONAK_CRED_TARGET:t}),i=o.trim();return i?JSON.parse(i):null}catch{return null}}async store(e,t){let n=this.targetPrefix+l(e),o=JSON.stringify(t),i=Buffer.byteLength(o,"utf16le");if(i>tt)throw new Error(`Credential '${n}' is ${i} bytes (UTF-16), over the Windows Credential Manager limit of ${tt} (CRED_MAX_CREDENTIAL_BLOB_SIZE). Keep only the secret here and store large/public material (certificates, chains) on disk.`);let s=`
22
- ${ie}
21
+ }`;try{let{stdout:n}=await ne(r,{KANONAK_CRED_TARGET:t}),s=n.trim();return s?JSON.parse(s):null}catch{return null}}async store(e,t){let r=this.targetPrefix+l(e),n=JSON.stringify(t),s=Buffer.byteLength(n,"utf16le");if(s>Fe)throw new Error(`Credential '${r}' is ${s} bytes (UTF-16), over the Windows Credential Manager limit of ${Fe} (CRED_MAX_CREDENTIAL_BLOB_SIZE). Keep only the secret here and store large/public material (certificates, chains) on disk.`);let i=`
22
+ ${oe}
23
23
  $target = $env:KANONAK_CRED_TARGET
24
24
  $json = $env:KANONAK_CRED_JSON
25
25
  $bytes = [System.Text.Encoding]::Unicode.GetBytes($json)
@@ -35,12 +35,12 @@ try {
35
35
  if (-not $result) { throw "CredWrite failed (Win32 error $([System.Runtime.InteropServices.Marshal]::GetLastWin32Error()))" }
36
36
  } finally {
37
37
  [System.Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
38
- }`;try{await oe(s,{KANONAK_CRED_TARGET:n,KANONAK_CRED_JSON:o})}catch(a){let c=a,d=c.stderr&&c.stderr.trim()||c.message||String(a);throw new Error(`Windows Credential Manager write failed: ${d}`)}}async remove(e){let t=this.targetPrefix+l(e),n=`
39
- ${ie}
38
+ }`;try{await ne(i,{KANONAK_CRED_TARGET:r,KANONAK_CRED_JSON:n})}catch(a){let c=a,d=c.stderr&&c.stderr.trim()||c.message||String(a);throw new Error(`Windows Credential Manager write failed: ${d}`)}}async remove(e){let t=this.targetPrefix+l(e),r=`
39
+ ${oe}
40
40
  $target = $env:KANONAK_CRED_TARGET
41
- [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await oe(n,{KANONAK_CRED_TARGET:t})}catch{}}async list(){let e=`
42
- ${ie}
43
- ${Bn}
41
+ [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await ne(r,{KANONAK_CRED_TARGET:t})}catch{}}async list(){let e=`
42
+ ${oe}
43
+ ${_n}
44
44
  $prefix = $env:KANONAK_CRED_PREFIX
45
45
  $count = 0
46
46
  $pCreds = [IntPtr]::Zero
@@ -57,8 +57,8 @@ if ([CredMan]::CredEnumerate(($prefix + "*"), 0, [ref]$count, [ref]$pCreds)) {
57
57
  }
58
58
  }
59
59
  [CredMan]::CredFree($pCreds)
60
- }`;try{let{stdout:t}=await oe(e,{KANONAK_CRED_PREFIX:this.targetPrefix});return t.trim().split(`
61
- `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function oe(r,e){let t=Buffer.from(r,"utf16le").toString("base64");for(let n of["pwsh","powershell"])try{return await On(n,["-NoProfile","-NonInteractive","-EncodedCommand",t],{timeout:15e3,...e&&{env:{...process.env,...e}}})}catch(o){if(n==="powershell")throw o}throw new Error("Neither pwsh nor powershell found")}var ie=`
60
+ }`;try{let{stdout:t}=await ne(e,{KANONAK_CRED_PREFIX:this.targetPrefix});return t.trim().split(`
61
+ `).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function ne(o,e){let t=Buffer.from(o,"utf16le").toString("base64");for(let r of["pwsh","powershell"])try{return await Dn(r,["-NoProfile","-NonInteractive","-EncodedCommand",t],{timeout:15e3,...e&&{env:{...process.env,...e}}})}catch(n){if(r==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var oe=`
62
62
  Add-Type -TypeDefinition @"
63
63
  using System;
64
64
  using System.Runtime.InteropServices;
@@ -89,15 +89,15 @@ public class CredMan {
89
89
  [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
90
90
  public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
91
91
  }
92
- "@`,Bn="";import{execFile as Mn,spawn as Vn}from"child_process";import{promisify as Ln}from"util";var se=Ln(Mn),Fn="kanonak",y=class{constructor(e=Fn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await se("secret-tool",["lookup","service",this.service,"publisher",t],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let n=l(e),o=JSON.stringify(t);await new Promise((i,s)=>{let a=Vn("secret-tool",["store","--label",`Kanonak: ${n}`,"service",this.service,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});a.stdin.write(o),a.stdin.end(),a.on("close",c=>{c===0?i():s(new Error(`secret-tool store exited with code ${c}`))}),a.on("error",s)})}async remove(e){let t=l(e);try{await se("secret-tool",["clear","service",this.service,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await se("secret-tool",["search","service",this.service],{timeout:1e4}),t=[];for(let n of e.split(`
93
- `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function A(){try{return await se("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as rt,mkdirSync as nt,readFileSync as ot,writeFileSync as it}from"fs";import{createCipheriv as Un,createDecipheriv as Hn,randomBytes as st}from"crypto";import{homedir as zn}from"os";import{join as _e,dirname as at}from"path";var lt=_e(zn(),".config","kanonak"),U=_e(lt,"keyring.key"),Wn=_e(lt,"credentials.enc"),ct="aes-256-gcm",$e=32,K=12,Te=16,h=class{constructor(e=Wn){this.secretsFile=e}secretsFile;async get(e){let t=this.loadStore(),n=l(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=l(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=l(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!rt(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=ot(this.secretsFile);if(t.length<K+Te)return{};let n=t.subarray(0,K),o=t.subarray(K,K+Te),i=t.subarray(K+Te),s=Hn(ct,e,n);s.setAuthTag(o);let a=Buffer.concat([s.update(i),s.final()]);return JSON.parse(a.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),n=st(K),o=Un(ct,t,n),i=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([o.update(i),o.final()]),a=o.getAuthTag(),c=Buffer.concat([n,a,s]);nt(at(this.secretsFile),{recursive:!0}),it(this.secretsFile,c,{mode:384})}getOrCreateKey(){if(rt(U)){let t=ot(U);if(t.length!==$e)throw new Error(`Credential keyring key is corrupted (expected ${$e} bytes, got ${t.length}). Delete ${U} and re-authenticate.`);return t}let e=st($e);return nt(at(U),{recursive:!0}),it(U,e,{mode:384}),e}};import{execFile as Gn}from"child_process";import{promisify as Jn}from"util";var qn=Jn(Gn),dt=3e4,H=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(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${ae(n)}
92
+ "@`,_n="";import{execFile as $n,spawn as In}from"child_process";import{promisify as Kn}from"util";var se=Kn($n),Nn="kanonak",f=class{constructor(e=Nn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:r}=await se("secret-tool",["lookup","service",this.service,"publisher",t],{timeout:1e4}),n=r.trim();return n?JSON.parse(n):null}catch{return null}}async store(e,t){let r=l(e),n=JSON.stringify(t);await new Promise((s,i)=>{let a=In("secret-tool",["store","--label",`Kanonak: ${r}`,"service",this.service,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});a.stdin.write(n),a.stdin.end(),a.on("close",c=>{c===0?s():i(new Error(`secret-tool store exited with code ${c}`))}),a.on("error",i)})}async remove(e){let t=l(e);try{await se("secret-tool",["clear","service",this.service,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await se("secret-tool",["search","service",this.service],{timeout:1e4}),t=[];for(let r of e.split(`
93
+ `)){let n=r.match(/attribute\.publisher\s*=\s*(.+)/);n&&t.push(n[1].trim())}return t}catch{return[]}}};async function R(){try{return await se("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Ue,mkdirSync as He,readFileSync as ze,writeFileSync as We}from"fs";import{createCipheriv as On,createDecipheriv as Bn,randomBytes as Ge}from"crypto";import{homedir as jn}from"os";import{join as Ee,dirname as Je}from"path";var Xe=Ee(jn(),".config","kanonak"),U=Ee(Xe,"keyring.key"),Mn=Ee(Xe,"credentials.enc"),qe="aes-256-gcm",Pe=32,T=12,be=16,h=class{constructor(e=Mn){this.secretsFile=e}secretsFile;async get(e){let t=this.loadStore(),r=l(e);return t[r]??null}async store(e,t){let r=this.loadStore(),n=l(e);r[n]=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(!Ue(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=ze(this.secretsFile);if(t.length<T+be)return{};let r=t.subarray(0,T),n=t.subarray(T,T+be),s=t.subarray(T+be),i=Bn(qe,e,r);i.setAuthTag(n);let a=Buffer.concat([i.update(s),i.final()]);return JSON.parse(a.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),r=Ge(T),n=On(qe,t,r),s=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([n.update(s),n.final()]),a=n.getAuthTag(),c=Buffer.concat([r,a,i]);He(Je(this.secretsFile),{recursive:!0}),We(this.secretsFile,c,{mode:384})}getOrCreateKey(){if(Ue(U)){let t=ze(U);if(t.length!==Pe)throw new Error(`Credential keyring key is corrupted (expected ${Pe} bytes, got ${t.length}). Delete ${U} and re-authenticate.`);return t}let e=Ge(Pe);return He(Je(U),{recursive:!0}),We(U,e,{mode:384}),e}};import{execFile as Vn}from"child_process";import{promisify as Ln}from"util";var Fn=Ln(Vn),Ye=3e4,H=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let n=(await this.runHelper("get",{publisher:t})).trim();return n?JSON.parse(n):null}catch(r){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${ie(r)}
94
94
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
95
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let n=l(e);try{await this.runHelper("store",{publisher:n,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${n}': ${ae(o)}
96
- Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${ae(n)}`)}}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: ${ae(e)}`),[]}}async runHelper(e,t){try{let{stdout:n}=await qn(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:dt});return n}catch(n){throw Xn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
97
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Yn(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${dt/1e3}s on '${e}'.
98
- The helper may be waiting for authentication to an external vault.`):n}}};function ae(r){return r instanceof Error?r.message:String(r)}function Xn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function Yn(r){return r instanceof Error&&"killed"in r&&r.killed}var Ne=to(eo(),".kanonak","config.json"),ce=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=ro(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!ee(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=no();return e.credentialHelper?new H(e.credentialHelper):process.platform==="darwin"?new m:process.platform==="win32"?new f:await A()?new y:new h}};function ro(r){let t="KANONAK_TOKEN_"+l(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function no(){if(!Zn(Ne))return{};try{return JSON.parse(Qn(Ne,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${Ne}: ${e}
99
- Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as ft}from"os";import{join as I}from"path";import{mkdir as oo,writeFile as pt,readFile as ut,rm as mt}from"fs/promises";var Oe="kanonak-device",io=I(ft(),".config","kanonak","device-credentials.enc"),so=I(ft(),".kanonak","devices"),R=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;certDir(e){let t=l(e).replace(/[^a-zA-Z0-9._-]/g,"_");return I(this.deps.certBaseDir??so,t)}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 get(e){let t=await(await this.getBackend()).get(e);if(!t)return null;if(typeof t.certificatePem=="string"&&typeof t.chainPem=="string")return t;let n=this.certDir(e),o,i;try{o=await ut(I(n,"cert.pem"),"utf-8"),i=await ut(I(n,"chain.pem"),"utf-8")}catch{return null}return{...t,certificatePem:o,chainPem:i}}async store(e,t){let{certificatePem:n,chainPem:o,...i}=t,s=this.certDir(e);await oo(s,{recursive:!0}),await pt(I(s,"cert.pem"),n,"utf-8"),await pt(I(s,"chain.pem"),o,"utf-8");try{await(await this.getBackend()).store(e,i)}catch(a){throw await mt(s,{recursive:!0,force:!0}).catch(()=>{}),a}}async remove(e){await(await this.getBackend()).remove(e),await mt(this.certDir(e),{recursive:!0,force:!0})}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(Oe):process.platform==="win32"?new f(`${Oe}:`):await A()?new y(Oe):new h(io)}};import{homedir as ao}from"os";import{join as co}from"path";var je="kanonak-session",lo=co(ao(),".config","kanonak","session-credentials.enc"),$=class{constructor(e={}){this.deps=e}deps;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 get(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(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(je):process.platform==="win32"?new f(`${je}:`):await A()?new y(je):new h(lo)}};function le(r,e=5*6e4,t=Date.now()){let n=Date.parse(r.expiresAt);return Number.isNaN(n)?!0:t>=n-e}var yt="key_thumbprint",E=class{cache=new Map;prCache=new Map;async discoverProtectedResource(e){let t=l(e);if(this.prCache.has(t))return this.prCache.get(t);let n=`https://${t}/.well-known/oauth-protected-resource`,o=await po(n),i=o&&Array.isArray(o.authorization_servers)?o.authorization_servers.filter(a=>typeof a=="string"):[],s=i.length>0?i:null;return this.prCache.set(t,s),s}async discover(e){let t=l(e);if(this.cache.has(t))return this.cache.get(t);let n=`https://${t}/.well-known/oauth-authorization-server`,o=await this.tryEndpoint(n);if(!o){let i=`https://${t}/.well-known/openid-configuration`;o=await this.tryEndpoint(i)}return this.cache.set(t,o),o}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let t;try{t=await fetch(e)}catch(o){let i=o instanceof Error?o.message:String(o);return i.includes("ENOTFOUND")||i.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${i})`),console.error(" If the server is behind a VPN, ensure you are connected.")):i.includes("CERT")||i.includes("SSL")||i.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${i})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${e} \u2014 network error: ${i}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let n;try{n=await t.json()}catch{return console.error(` OAuth discovery: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:g(n.issuer),authorizationEndpoint:g(n.authorization_endpoint),tokenEndpoint:g(n.token_endpoint),registrationEndpoint:g(n.registration_endpoint),revocationEndpoint:g(n.revocation_endpoint),scopesSupported:k(n.scopes_supported),responseTypesSupported:k(n.response_types_supported),grantTypesSupported:k(n.grant_types_supported),codeChallengeMethodsSupported:k(n.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:k(n.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:k(n.dpop_signing_alg_values_supported),enrollmentEndpoint:g(n.enrollment_endpoint),enrollmentIssuanceProtocols:k(n.enrollment_issuance_protocols),enrollmentKeyTypes:k(n.enrollment_key_types),enrollmentScopesSupported:k(n.enrollment_scopes_supported),enrollmentConsentBindingParam:g(n.enrollment_consent_binding_param),sessionEndpoint:g(n.session_endpoint),sessionEndpointAuthMethod:g(n.session_endpoint_auth_method)}}};async function po(r){try{let e=await fetch(r);return e.ok?await e.json():null}catch{return null}}function g(r){return typeof r=="string"?r:null}function k(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"):null}import*as ht from"https";import{createPrivateKey as uo}from"crypto";var mo="client_credentials",S=class extends Error{},T=class{constructor(e=ho){this.transport=e}transport;async exchange(e,t,n={}){let o=yo(t.keyMaterial),i=new URLSearchParams({grant_type:mo});n.scope&&i.set("scope",n.scope);let s=i.toString(),a;try{a=await this.transport({url:e,certPem:fo(t),keyPem:o,body:s,contentType:"application/x-www-form-urlencoded"})}catch(j){throw new S(`mTLS session exchange to ${e} failed: ${j.message}`)}if(a.status<200||a.status>=300)throw new S(`Session endpoint ${e} returned HTTP ${a.status}: ${a.body.slice(0,300)}`);let c;try{c=JSON.parse(a.body)}catch{throw new S(`Session endpoint returned a non-JSON response: ${a.body.slice(0,200)}`)}if(typeof c.access_token!="string"||!c.access_token)throw new S("Session response had no access_token.");let d=typeof c.expires_in=="number"?c.expires_in:0,p=n.nowMs??Date.now();return{token:c.access_token,tokenType:typeof c.token_type=="string"&&c.token_type?c.token_type:"Bearer",expiresAt:new Date(p+d*1e3).toISOString(),scope:typeof c.scope=="string"?c.scope:""}}};function fo(r){let e=r.chainPem.trim();return e?`${r.certificatePem.replace(/\s+$/,"")}
95
+ 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(n){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${r}': ${ie(n)}
96
+ 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}': ${ie(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: ${ie(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await Fn(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:Ye});return r}catch(r){throw Un(r)?new Error(`Credential helper not found at '${this.helperPath}'.
97
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Hn(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${Ye/1e3}s on '${e}'.
98
+ The helper may be waiting for authentication to an external vault.`):r}}};function ie(o){return o instanceof Error?o.message:String(o)}function Un(o){return o instanceof Error&&"code"in o&&o.code==="ENOENT"}function Hn(o){return o instanceof Error&&"killed"in o&&o.killed}var Re=Jn(Gn(),".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=qn(e);if(t)return t;let n=await(await this.getBackend()).get(e);return!n||!Q(n)?null:n.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=Xn();return e.credentialHelper?new H(e.credentialHelper):process.platform==="darwin"?new m:process.platform==="win32"?new y:await R()?new f:new h}};function qn(o){let t="KANONAK_TOKEN_"+l(o).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Xn(){if(!zn(Re))return{};try{return JSON.parse(Wn(Re,"utf-8"))}catch(o){let e=o instanceof Error?o.message:String(o);return console.warn(` Warning: Failed to parse ${Re}: ${e}
99
+ Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as tt}from"os";import{join as x}from"path";import{mkdir as Yn,writeFile as Ze,readFile as Qe,rm as et}from"fs/promises";var xe="kanonak-device",Zn=x(tt(),".config","kanonak","device-credentials.enc"),Qn=x(tt(),".kanonak","devices"),P=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;certDir(e){let t=l(e).replace(/[^a-zA-Z0-9._-]/g,"_");return x(this.deps.certBaseDir??Qn,t)}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 get(e){let t=await(await this.getBackend()).get(e);if(!t)return null;if(typeof t.certificatePem=="string"&&typeof t.chainPem=="string")return t;let r=this.certDir(e),n,s;try{n=await Qe(x(r,"cert.pem"),"utf-8"),s=await Qe(x(r,"chain.pem"),"utf-8")}catch{return null}return{...t,certificatePem:n,chainPem:s}}async store(e,t){let{certificatePem:r,chainPem:n,...s}=t,i=this.certDir(e);await Yn(i,{recursive:!0}),await Ze(x(i,"cert.pem"),r,"utf-8"),await Ze(x(i,"chain.pem"),n,"utf-8");try{await(await this.getBackend()).store(e,s)}catch(a){throw await et(i,{recursive:!0,force:!0}).catch(()=>{}),a}}async remove(e){await(await this.getBackend()).remove(e),await et(this.certDir(e),{recursive:!0,force:!0})}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(xe):process.platform==="win32"?new y(`${xe}:`):await R()?new f(xe):new h(Zn)}};import{homedir as eo}from"os";import{join as to}from"path";var Ce="kanonak-session",ro=to(eo(),".config","kanonak","session-credentials.enc"),_=class{constructor(e={}){this.deps=e}deps;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 get(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(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(Ce):process.platform==="win32"?new y(`${Ce}:`):await R()?new f(Ce):new h(ro)}};function ce(o,e=5*6e4,t=Date.now()){let r=Date.parse(o.expiresAt);return Number.isNaN(r)?!0:t>=r-e}var rt="key_thumbprint",b=class{cache=new Map;prCache=new Map;async discoverProtectedResource(e){let t=l(e);if(this.prCache.has(t))return this.prCache.get(t);let r=`https://${t}/.well-known/oauth-protected-resource`,n=await no(r),s=n&&Array.isArray(n.authorization_servers)?n.authorization_servers.filter(a=>typeof a=="string"):[],i=s.length>0?s:null;return this.prCache.set(t,i),i}async discover(e){let t=l(e);if(this.cache.has(t))return this.cache.get(t);let r=`https://${t}/.well-known/oauth-authorization-server`,n=await this.tryEndpoint(r);if(!n){let s=`https://${t}/.well-known/openid-configuration`;n=await this.tryEndpoint(s)}return this.cache.set(t,n),n}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let t;try{t=await fetch(e)}catch(n){let s=n instanceof Error?n.message:String(n);return s.includes("ENOTFOUND")||s.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \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: ${e} \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: ${e} \u2014 network error: ${s}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${e} \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: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:g(r.issuer),authorizationEndpoint:g(r.authorization_endpoint),tokenEndpoint:g(r.token_endpoint),registrationEndpoint:g(r.registration_endpoint),revocationEndpoint:g(r.revocation_endpoint),scopesSupported:k(r.scopes_supported),responseTypesSupported:k(r.response_types_supported),grantTypesSupported:k(r.grant_types_supported),codeChallengeMethodsSupported:k(r.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:k(r.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:k(r.dpop_signing_alg_values_supported),enrollmentEndpoint:g(r.enrollment_endpoint),enrollmentIssuanceProtocols:k(r.enrollment_issuance_protocols),enrollmentKeyTypes:k(r.enrollment_key_types),enrollmentScopesSupported:k(r.enrollment_scopes_supported),enrollmentConsentBindingParam:g(r.enrollment_consent_binding_param),sessionEndpoint:g(r.session_endpoint),sessionEndpointAuthMethod:g(r.session_endpoint_auth_method)}}};async function no(o){try{let e=await fetch(o);return e.ok?await e.json():null}catch{return null}}function g(o){return typeof o=="string"?o:null}function k(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"):null}import*as nt from"https";import{createPrivateKey as oo}from"crypto";var so="client_credentials",S=class extends Error{},$=class{constructor(e=co){this.transport=e}transport;async exchange(e,t,r={}){let n=ao(t.keyMaterial),s=new URLSearchParams({grant_type:so});r.scope&&s.set("scope",r.scope);let i=s.toString(),a;try{a=await this.transport({url:e,certPem:io(t),keyPem:n,body:i,contentType:"application/x-www-form-urlencoded"})}catch(O){throw new S(`mTLS session exchange to ${e} failed: ${O.message}`)}if(a.status<200||a.status>=300)throw new S(`Session endpoint ${e} returned HTTP ${a.status}: ${a.body.slice(0,300)}`);let c;try{c=JSON.parse(a.body)}catch{throw new S(`Session endpoint returned a non-JSON response: ${a.body.slice(0,200)}`)}if(typeof c.access_token!="string"||!c.access_token)throw new S("Session response had no access_token.");let d=typeof c.expires_in=="number"?c.expires_in:0,p=r.nowMs??Date.now();return{token:c.access_token,tokenType:typeof c.token_type=="string"&&c.token_type?c.token_type:"Bearer",expiresAt:new Date(p+d*1e3).toISOString(),scope:typeof c.scope=="string"?c.scope:""}}};function io(o){let e=o.chainPem.trim();return e?`${o.certificatePem.replace(/\s+$/,"")}
100
100
  ${e}
101
- `:r.certificatePem}function yo(r){try{return uo({key:r,format:"jwk"}).export({type:"pkcs8",format:"pem"})}catch(e){throw new S(`The device key is not an exportable software private key, so it cannot present mTLS in software (a future hardware key provider would do the handshake itself): ${e.message}`)}}var ho=r=>new Promise((e,t)=>{let n=new URL(r.url),o=ht.request({method:"POST",hostname:n.hostname,port:n.port||443,path:n.pathname+n.search,cert:r.certPem,key:r.keyPem,headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(r.body),Accept:"application/json"},timeout:3e4},i=>{let s=[];i.on("data",a=>s.push(a)),i.on("end",()=>e({status:i.statusCode??0,body:Buffer.concat(s).toString("utf-8")}))});o.on("error",t),o.on("timeout",()=>o.destroy(new Error("mTLS request timed out"))),o.write(r.body),o.end()});var _=class extends Error{},N=class{discovery;deviceStore;sessionStore;exchange;constructor(e={}){this.discovery=e.discovery??new E,this.deviceStore=e.deviceStore??new R,this.sessionStore=e.sessionStore??new $,this.exchange=e.exchange??new T}async acquire(e,t={}){let n=l(e),o=await this.sessionEndpoint(e);if(!o)throw new _(`'${n}' does not advertise a session endpoint \u2014 it issues no scoped sessions (public registries need no credential).`);let i=await this.deviceStore.get(e);if(!i)throw new _(`No device certificate enrolled for '${n}'. Run 'kanonak device enroll ${e}' first.`);let s=await this.exchange.exchange(o,i,t),a={token:s.token,tokenType:s.tokenType,expiresAt:s.expiresAt,scope:s.scope};return await this.sessionStore.store(n,a),a}async getValidSession(e){let t=l(e),n=await this.sessionStore.get(t);return n&&!le(n)?n:!await this.sessionEndpoint(e)||!await this.deviceStore.get(e)?null:this.acquire(e)}async clear(e){await this.sessionStore.remove(l(e))}async sessionEndpoint(e){return(await this.discovery.discover(e))?.sessionEndpoint??null}};var de=class{discovery;sessions;devices;constructor(e={}){this.discovery=e.discovery??new E,this.sessions=e.sessionManager??new N({discovery:this.discovery}),this.devices=e.deviceStore??new R}async resolve(e){let t=await this.discovery.discoverProtectedResource(e);if(!t||t.length===0)return null;let n=t.map(go).filter(s=>s!==void 0);for(let s of n){let a=await this.sessionFor(s);if(a)return a}let i=(await this.devices.list()).map(l).filter(s=>!n.includes(s));if(i.length===0)return null;for(let s of n){let a=(await this.discovery.discover(s))?.sessionEndpoint;if(a)for(let c of i){if((await this.discovery.discover(c))?.sessionEndpoint!==a)continue;let p=await this.sessionFor(c);if(p)return p}}return null}async sessionFor(e){let t=await this.sessions.getValidSession(e);return t?{authority:e,token:t.token,expiresAt:t.expiresAt,scope:t.scope}:null}};function go(r){try{return new URL(r).host}catch{return}}import{createHash as ko,createPrivateKey as So,generateKeyPairSync as wo,randomUUID as vo,sign as bo}from"crypto";function kt(){let{publicKey:r,privateKey:e}=wo("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function z(r,e,t,n,o,i){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},a={jti:vo(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(a.ath=ko("sha256").update(o).digest("base64url")),i&&(a.nonce=i),Po(s,a,r)}function St(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function Po(r,e,t){let n=gt(JSON.stringify(r)),o=gt(JSON.stringify(e)),i=`${n}.${o}`,s=So({key:t,format:"jwk"}),c=bo("SHA256",Buffer.from(i),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${i}.${c}`}function gt(r){return Buffer.from(r,"utf-8").toString("base64url")}function wt(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return D(t,{method:o});let i=await r.getCredential(n);if(!i?.accessToken)return D(t,{method:o});Q(i)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let s={};if(i.dpopKeyPair){let c=e.get(n);try{let d=z(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);s.Authorization=`DPoP ${i.accessToken}`,s.DPoP=d}catch(d){let p=d instanceof Error?d.message:String(d);console.error(` Error: Failed to create DPoP proof for '${n}': ${p}
102
- The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),s.Authorization=`Bearer ${i.accessToken}`}}else s.Authorization=`Bearer ${i.accessToken}`;let a=await D(t,{method:o,headers:s});if(a.status===401&&i.dpopKeyPair){let c=a.headers.get("DPoP-Nonce");if(c){e.set(n,c);try{let d=z(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);s.DPoP=d,a=await D(t,{method:o,headers:s})}catch{}}}return a}}import{readFileSync as Ro,writeFileSync as Eo,existsSync as Co}from"fs";import{createHash as xo}from"crypto";import vt from"js-yaml";var bt="kanonak.lock",Ao=`# This file is generated by Kanonak CLI. Do not edit manually.
103
- `;function Pt(r=bt){if(!Co(r))return null;let e=Ro(r,"utf-8"),t=vt.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function Rt(r,e=bt){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=vt.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Eo(e,Ao+n,"utf-8")}function Et(r){return`sha256:${xo("sha256").update(r).digest("hex")}`}import*as Ve from"js-yaml";import{canonicalForm as Io,canonicalHash as Do}from"@kanonak-protocol/canonical";function Be(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as $t}from"@kanonak-protocol/canonical";function Ct(r){return Io(Be(r)?r:xt(r))}function pe(r){return Do(Be(r)?r:xt(r))}function xt(r){let e=[];for(let t of r)t instanceof v&&e.push({uri:_o(t),statements:Me(t.statement)});return{subjects:e}}function Me(r){let e=[];for(let t of r){let n=To(t);if(!n)continue;let o=Ko(t);o&&e.push({predicate:n,value:o})}return e}function Ko(r){if(r instanceof we&&r.carrier)return{lit:r.lexical??String(r.object),datatype:It(r.carrier)};if(r instanceof ve)return{raw:r.object};if(r instanceof be)return{raw:r.lexical??String(r.object)};if(r instanceof Pe)return{raw:r.lexical??String(r.object)};if(r instanceof Re)return{ref:Dt(r.object)};if(r instanceof Ee)return At(r.object);if(r instanceof Ce)return{list:r.object.map($o)}}function At(r){let e=Me(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function $o(r){if(r instanceof x)return{ref:Dt(r)};if(r instanceof b)return At(r);if(r instanceof Se){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:It(r.carrier)};let e=r.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(r instanceof ke)return{embed:{statements:Me(r.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function It(r){return r===Z.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function To(r){let e=r.predicate;if(e)return Kt(e.subject)}function _o(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function Dt(r){return Kt(r.subject)}function Kt(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}import{VersionOperator as Tt}from"@kanonak-protocol/types/document/models/enums";var No="0.0.0",O=class{constructor(e,t=new M,n){this.repository=e;this.parser=t;this.objectParser=n??new F(this.parser)}repository;parser;objectParser;imports(){return new W}serializeValue(e,t){return Ot(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=Le(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let s={[o]:i,...e.body},a=this.dump(s);return{yaml:a,byteCount:Nt(a),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{}),n.imports=t;let i={[e.name]:n,...e.body},s=this.dump(i),a={yaml:s,byteCount:Nt(s),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(a.contentHash=o),a}dump(e){return Ve.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[_t]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ve.dump(o,{lineWidth:-1})),s=i.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Xe(i,this.repository))).filter(d=>d instanceof v&&d.namespace===s&&d.name!==_t);for(let d of c)d.namespace="ephemeral";return pe(c)}},_t="__pkgbuilder_probe__";function Nt(r){return new TextEncoder().encode(r).length}function Le(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var W=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=Tt.Major){let s=`${e}/${t}@${n}`,a=this.byKey.get(s);if(a)return a.alias;let c=this.uniqueAlias(o);return this.byKey.set(s,{publisher:e,package_:t,version:n,alias:c,match:i}),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_,C(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,No,o??t,Tt.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,i)=>o.package_<i.package_?-1:1).map(o=>({package:o.package_,match:ge(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=G(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function Ot(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof x)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>Ot(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof b)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(Oo(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function G(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Oo(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ue=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let i=`${t}/${n}@${C(o)}`,s=this.produced.get(i);if(s)return s;let{document:a}=await e.produce(t,n,o);return this.produced.set(i,a),a}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=De(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.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 Fe={async authorize(){return{allowed:!0}}},Ue={async record(){}},J=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},me=class{inner;ctx;policy;meter;constructor(e,t,n=Fe,o=Ue){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let i=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,i),i}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new J(e,t.reason)}};var u="kanonak.org",w="view",jt="core-kanonak",jo={publisher:u,package_:w,name:"rootView"},Bo={publisher:u,package_:w,name:"bind"},Mo={publisher:u,package_:w,name:"produces"},Vo={publisher:u,package_:w,name:"projections"},Lo={publisher:u,package_:w,name:"where"},Fo={publisher:u,package_:w,name:"value"},Uo={publisher:u,package_:w,name:"as"},fe=class{constructor(e,t=new M){this.repository=e;this.parser=t;this.objectParser=new F(this.parser),this.builder=new O(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),i=V(o,Bo);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let s=V(o,Mo);if(!s)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 a=Ho(o),c=Bt(n,u,jt),d=Bt(n,u,w),p=this.builder.imports(),j=p.ensure(u,jt,c,"ck"),Vt=p.ensure(u,w,d,"v"),Lt=p.ref(s),Ft=new Qe(this.repository,this.parser,this.objectParser),He=new Ye(Ft,n),Ut=this.readProjections(n,o),Ht=Go(o,Lo),zt=this.findInstances(n,i,await this.reason(t)),ze={},Wt=new Set;for(let q of zt){if(!await this.passesWhere(He,n,Ht,q))continue;let he={type:Lt};for(let Ge of Ut){let Gt=await this.evaluateValue(He,n,Ge.value,q),Je=this.builder.serializeValue(Mt(Gt),p);Je!==void 0&&(he[p.ref(Ge.as)]=Je)}let We=P(q);We&&(he[`${Vt}.derivedFrom`]=p.ref(We)),ze[this.rowName(q,Wt)]=he}let ye={};t.resolvedAt&&(ye[`${j}.resolvedAt`]=t.resolvedAt),t.invocationId&&(ye[`${j}.id`]=t.invocationId);let B=await this.builder.buildContentAddressed({publisher:a,book:p,body:ze,contentHashProperty:`${j}.contentHash`,header:ye});return{yaml:B.yaml,contentHash:B.contentHash,packageName:B.packageName,publisher:B.publisher,rowCount:B.resourceCount}}resolveView(e,t){let n=Y(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=V(n,jo);if(o){let i=Y(e,o);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return i}return n}readProjections(e,t){let n=[];for(let o of Ae(t,Vo)){let i=o instanceof b?o:o instanceof x?Y(e,o.subject):void 0;if(!i)continue;let s=xe(i,Fo),a=V(i,Uo);s&&a&&n.push({value:s,as:a})}return n}async reason(e){return new Ie({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=Wo(e),i=[],s=new Set;for(let a of n.getInstancesOfClass(t)){if(s.has(a))continue;s.add(a);let c=o.get(a);c&&i.push(c)}return i.sort((a,c)=>{let d=L(P(a)),p=L(P(c));return d<p?-1:d>p?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let s=await this.evaluateValue(e,t,i,o);if(!Jo(s))return!1}return!0}async evaluateValue(e,t,n,o){let i=Ze(n,"view-projection",{catalog:t,depth:0}),s=new Map([["input",o]]);return e.evaluate(i,s)}rowName(e,t){let n=G(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Mt(r){return Ke(r)?r.value:Array.isArray(r)?r.map(Mt):r}function Ho(r){let e=P(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function Bt(r,e,t){let n=zo(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function zo(r,e,t){let n;for(let o of r){if(!(o instanceof v))continue;let i=P(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||X(i.version,n)>0)&&(n=i.version)}return n?C(n):void 0}function Wo(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof v))continue;let o=P(n);if(!o||!o.version)continue;let i=L(o),s=t.get(i);(!s||X(o.version,s)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function Go(r,e){let t=xe(r,e);return t?[t]:Ae(r,e).filter(n=>n instanceof b)}function Jo(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:Ke(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{kn as AmbiguousReferenceRule,Pe as BooleanStatement,$t as CANONICAL_FORM_VERSION,Z as Carrier,Rn as ClassDefinitionRule,pn as ClassHierarchyCycleRule,or as CompositeKanonakDocumentRepository,de as CredentialResolver,ce as CredentialStore,yt as DEFAULT_CONSENT_BINDING_PARAM,ke as DefinedKanonak,R as DeviceCertificateStore,nr as DocumentLocation,$r as EdgeType,b as EmbeddedKanonak,cn as EmbeddedKanonakTypeRule,Ee as EmbeddedStatement,J as EntitlementDeniedError,me as EntitlementProducer,rr as FileSystemKanonakDocumentRepository,Br as GitIgnoreFilter,Tr as GraphBuilder,mr as HttpKanonakDocumentRepository,W as ImportBook,ln as ImportExistenceRule,tr as InMemoryKanonakDocumentRepository,ar as KANONAK_USER_AGENT,kr as Kanonak,Vr as KanonakDocumentPositions,F as KanonakObjectParser,Cn as KanonakObjectValidator,M as KanonakParser,Sr as KanonakUri,Ur as KanonakUriBuilder,zr as KanonakUrlResolver,xr as KanonakVocabulary,Ce as ListStatement,Se as LiteralKanonak,fr as LocalFirstRepository,yr as LockAwareRepository,In as LookRenderer,En as MarkdownLinkRule,vr as MarkdownStatement,hn as NamespaceImportCycleRule,rn as NamespacePrefixRule,Kr as NodeType,be as NumberStatement,E as OAuthDiscovery,Or as OWL_RL_CLASSIFICATION_RULES,wn as ObjectPropertyValueValidationRule,Qr as OntologyValidationError,Yr as OntologyValidationResult,O as PackageBuilder,an as PackageHeaderRule,ue as ProducerRepository,vn as PropertyDomainRule,un as PropertyHierarchyCycleRule,bn as PropertyKindRangeConsistencyRule,Mr as PropertyMetadata,Sn as PropertyRangeReferenceRule,mn as PropertyRangeRequiredRule,on as PropertyTypeSpecificityRule,dr as PublisherConfigResolver,pr as PublisherIndex,Nr as RDFS_RULES,Ie as Reasoner,jr as ReasoningResult,x as ReferenceKanonak,Re as ReferenceStatement,sr as RepositoryFactory,Pn as ReservedNameShadowRule,nn as ResourceNamingRule,br as ResourceResolver,Dr as ResourceTypeClassifier,we as ScalarStatement,_ as SessionError,T as SessionExchange,S as SessionExchangeError,N as SessionManager,$ as SessionStore,wr as Statement,ve as StringStatement,fn as SubClassOfReferenceRule,yn as SubPropertyOfReferenceRule,v as SubjectKanonak,sn as SubjectKanonakTypeRequiredRule,_r as TripleStore,Pr as TypeResolver,gn as UnresolvedPredicateRule,dn as UnresolvedReferenceRule,tn as ValidationCache,en as ValidationContext,Zr as ValidationSeverity,Ma as VersionOperator,fe as ViewMaterializer,Fe as allowAllPolicy,ur as assertPackageIdentity,gr as buildLocalFirstRepository,Dn as buildOntologyModel,Ct as canonicalForm,pe as canonicalHash,qe as carrierOf,hr as collectKanonakFiles,X as compareVersions,Et as computeIntegrity,Le as contentAddressedName,qr as contextTypesOf,wt as createAuthenticatedFetch,z as createDPoPProof,Xt as createVersion,Ir as extractMarkdownLinks,xn as findDerivation,Xr as findInstancesByType,Ar as findMalformedReferences,Fr as findMarkdownLinkAt,Hr as formatKanonakAddress,C as formatVersion,kt as generateDPoPKeyPair,ir as getGlobalCachePath,lr as getKanonakUserAgent,ee as hasValidToken,Zt as isCompatibleVersion,Q as isExpired,Qt as isMajorCompatible,D as kanonakFetch,Pt as loadLockFile,Rr as makeUriKey,Ue as noopMeter,l as normalizeHost,De as parseKanonakAddress,Yt as parseVersionString,Lr as parseWithPositions,er as pickHighestDocument,Gr as propertiesInScope,An as resolveDisplayValue,Jr as resolvePropertyStep,G as sanitizeName,Rt as saveLockFile,St as serverSupportsDPoP,le as sessionNeedsRefresh,cr as setKanonakUserAgent,P as subjectUri,Wr as superClassChain,Er as tripleKey,L as uriKey,Cr as uriTriple,Jt as versionOperatorFromChar,ge as versionOperatorToChar,qt as versionsEqual};
101
+ `:o.certificatePem}function ao(o){try{return oo({key:o,format:"jwk"}).export({type:"pkcs8",format:"pem"})}catch(e){throw new S(`The device key is not an exportable software private key, so it cannot present mTLS in software (a future hardware key provider would do the handshake itself): ${e.message}`)}}var co=o=>new Promise((e,t)=>{let r=new URL(o.url),n=nt.request({method:"POST",hostname:r.hostname,port:r.port||443,path:r.pathname+r.search,cert:o.certPem,key:o.keyPem,headers:{"Content-Type":o.contentType,"Content-Length":Buffer.byteLength(o.body),Accept:"application/json"},timeout:3e4},s=>{let i=[];s.on("data",a=>i.push(a)),s.on("end",()=>e({status:s.statusCode??0,body:Buffer.concat(i).toString("utf-8")}))});n.on("error",t),n.on("timeout",()=>n.destroy(new Error("mTLS request timed out"))),n.write(o.body),n.end()});var I=class extends Error{},K=class{discovery;deviceStore;sessionStore;exchange;constructor(e={}){this.discovery=e.discovery??new b,this.deviceStore=e.deviceStore??new P,this.sessionStore=e.sessionStore??new _,this.exchange=e.exchange??new $}async acquire(e,t={}){let r=l(e),n=await this.sessionEndpoint(e);if(!n)throw new I(`'${r}' does not advertise a session endpoint \u2014 it issues no scoped sessions (public registries need no credential).`);let s=await this.deviceStore.get(e);if(!s)throw new I(`No device certificate enrolled for '${r}'. Run 'kanonak device enroll ${e}' first.`);let i=await this.exchange.exchange(n,s,t),a={token:i.token,tokenType:i.tokenType,expiresAt:i.expiresAt,scope:i.scope};return await this.sessionStore.store(r,a),a}async getValidSession(e){let t=l(e),r=await this.sessionStore.get(t);return r&&!ce(r)?r:!await this.sessionEndpoint(e)||!await this.deviceStore.get(e)?null:this.acquire(e)}async clear(e){await this.sessionStore.remove(l(e))}async sessionEndpoint(e){return(await this.discovery.discover(e))?.sessionEndpoint??null}};var le=class{discovery;sessions;devices;constructor(e={}){this.discovery=e.discovery??new b,this.sessions=e.sessionManager??new K({discovery:this.discovery}),this.devices=e.deviceStore??new P}async resolve(e){let t=await this.discovery.discoverProtectedResource(e);if(!t||t.length===0)return null;let r=t.map(lo).filter(i=>i!==void 0);for(let i of r){let a=await this.sessionFor(i);if(a)return a}let s=(await this.devices.list()).map(l).filter(i=>!r.includes(i));if(s.length===0)return null;for(let i of r){let a=(await this.discovery.discover(i))?.sessionEndpoint;if(a)for(let c of s){if((await this.discovery.discover(c))?.sessionEndpoint!==a)continue;let p=await this.sessionFor(c);if(p)return p}}return null}async sessionFor(e){let t=await this.sessions.getValidSession(e);return t?{authority:e,token:t.token,expiresAt:t.expiresAt,scope:t.scope}:null}};function lo(o){try{return new URL(o).host}catch{return}}import{createHash as po,createPrivateKey as uo,generateKeyPairSync as mo,randomUUID as yo,sign as fo}from"crypto";function st(){let{publicKey:o,privateKey:e}=mo("ec",{namedCurve:"P-256"});return{publicKey:o.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function z(o,e,t,r,n,s){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},a={jti:yo(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return n&&(a.ath=po("sha256").update(n).digest("base64url")),s&&(a.nonce=s),ho(i,a,o)}function it(o){return!o||o.length===0?!1:o.some(e=>e.toUpperCase()==="ES256")}function ho(o,e,t){let r=ot(JSON.stringify(o)),n=ot(JSON.stringify(e)),s=`${r}.${n}`,i=uo({key:t,format:"jwk"}),c=fo("SHA256",Buffer.from(s),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${c}`}function ot(o){return Buffer.from(o,"utf-8").toString("base64url")}function at(o){let e=new Map;return async(t,r,n="GET")=>{if(!o)return C(t,{method:n});let s=await o.getCredential(r);if(!s?.accessToken)return C(t,{method:n});Z(s)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let i={};if(s.dpopKeyPair){let c=e.get(r);try{let d=z(s.dpopKeyPair.privateKey,s.dpopKeyPair.publicKey,n,t,s.accessToken,c);i.Authorization=`DPoP ${s.accessToken}`,i.DPoP=d}catch(d){let p=d instanceof Error?d.message:String(d);console.error(` Error: Failed to create DPoP proof for '${r}': ${p}
102
+ The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${s.accessToken}`}}else i.Authorization=`Bearer ${s.accessToken}`;let a=await C(t,{method:n,headers:i});if(a.status===401&&s.dpopKeyPair){let c=a.headers.get("DPoP-Nonce");if(c){e.set(r,c);try{let d=z(s.dpopKeyPair.privateKey,s.dpopKeyPair.publicKey,n,t,s.accessToken,c);i.DPoP=d,a=await C(t,{method:n,headers:i})}catch{}}}return a}}import{readFileSync as go,writeFileSync as ko,existsSync as So}from"fs";import{createHash as vo}from"crypto";import ct from"js-yaml";var lt="kanonak.lock",wo=`# This file is generated by Kanonak CLI. Do not edit manually.
103
+ `;function dt(o=lt){if(!So(o))return null;let e=go(o,"utf-8"),t=ct.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function pt(o,e=lt){o.lastUpdated=new Date().toISOString();let t={};for(let n of Object.keys(o.packages).sort())t[n]=o.packages[n];o.packages=t;let r=ct.dump(o,{lineWidth:-1,sortKeys:!1,quotingType:'"'});ko(e,wo+r,"utf-8")}function ut(o){return`sha256:${vo("sha256").update(o).digest("hex")}`}import*as Ae from"js-yaml";import{VersionOperator as mt}from"@kanonak-protocol/types/document/models/enums";var Po="0.0.0",N=class{constructor(e,t=new j,r){this.repository=e;this.parser=t;this.objectParser=r??new F(this.parser)}repository;parser;objectParser;imports(){return new W}serializeValue(e,t){return ht(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),n=De(r),s={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(s[e.contentHashProperty]=r),Object.assign(s,e.header??{}),s.imports=t;let i={[n]:s,...e.body},a=this.dump(i);return{yaml:a,byteCount:ft(a),contentHash:r,packageName:n,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},n;e.contentHashProperty&&(n=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=n),Object.assign(r,e.header??{}),r.imports=t;let s={[e.name]:r,...e.body},i=this.dump(s),a={yaml:i,byteCount:ft(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return n!==void 0&&(a.contentHash=n),a}dump(e){return Ae.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let n={[yt]:{type:"EphemeralPackage",publisher:e,imports:t},...r},s=this.parser.parse(Ae.dump(n,{lineWidth:-1})),i=s.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Be(s,this.repository))).filter(d=>d instanceof A&&d.namespace===i&&d.name!==yt);for(let d of c)d.namespace="ephemeral";return we(c)}},yt="__pkgbuilder_probe__";function ft(o){return new TextEncoder().encode(o).length}function De(o){let e="sha256:",t=o.startsWith(e)?e.length:0;return`q-${o.slice(t,t+16)}`}var W=class{byKey=new Map;aliases=new Set;ensure(e,t,r,n,s=mt.Major){let i=`${e}/${t}@${r}`,a=this.byKey.get(i);if(a)return a.alias;let c=this.uniqueAlias(n);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:s}),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_,E(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,n){return`${this.ensure(e,t,Po,n??t,mt.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let n=e.get(r.publisher)??[];n.push(r),e.set(r.publisher,n)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((n,s)=>n.package_<s.package_?-1:1).map(n=>({package:n.package_,match:fe(n.match),version:n.version,alias:n.alias}))}))}uniqueAlias(e){let t=G(e)||"pkg",r=t,n=2;for(;this.aliases.has(r);)r=`${t}${n++}`;return this.aliases.add(r),r}};function ht(o,e){if(o!=null){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(o instanceof M)return e.ref(o.subject);if(Array.isArray(o)){let t=o.map(r=>ht(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(o instanceof D)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(bo(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 G(o){return o.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function bo(o){return typeof o=="object"&&o!==null&&typeof o.publisher=="string"&&typeof o.package_=="string"&&typeof o.name=="string"}var de=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,n){let s=`${t}/${r}@${E(n)}`,i=this.produced.get(s);if(i)return i;let{document:a}=await e.produce(t,r,n);return this.produced.set(s,a),a}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let n={operator:t.versionOperator,version:t.version},s=await r.resolveVersion(e,t.packageName,n);return s?this.produceCached(r,e,t.packageName,s):null}async getDocumentAsync(e){let t;try{t=Se(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 n=r.metadata.namespace_;return n!=null&&n.publisher===e&&n.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 Te={async authorize(){return{allowed:!0}}},_e={async record(){}},J=class extends Error{constructor(t,r){let n=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${n}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},pe=class{inner;ctx;policy;meter;constructor(e,t,r=Te,n=_e){this.inner=e,this.ctx=t,this.policy=r,this.meter=n}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 n={publisher:e,package_:t,version:r};await this.assertAllowed(n);let s=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,n,s),s}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new J(e,t.reason)}};var u="kanonak.org",v="view",gt="core-kanonak",Eo={publisher:u,package_:v,name:"rootView"},Ro={publisher:u,package_:v,name:"bind"},xo={publisher:u,package_:v,name:"produces"},Co={publisher:u,package_:v,name:"projections"},Ao={publisher:u,package_:v,name:"where"},Do={publisher:u,package_:v,name:"value"},To={publisher:u,package_:v,name:"as"},ue=class{constructor(e,t=new j){this.repository=e;this.parser=t;this.objectParser=new F(this.parser),this.builder=new N(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),n=this.resolveView(r,e),s=V(n,Ro);if(!s)throw new Error(`View ${n.namespace}/${n.name} declares no view.bind; cannot materialize.`);let i=V(n,xo);if(!i)throw new Error(`View ${n.namespace}/${n.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 a=_o(n),c=kt(r,u,gt),d=kt(r,u,v),p=this.builder.imports(),O=p.ensure(u,gt,c,"ck"),vt=p.ensure(u,v,d,"v"),wt=p.ref(i),Pt=new Ve(this.repository,this.parser,this.objectParser),$e=new je(Pt,r),bt=this.readProjections(r,n),Et=Ko(n,Ao),Rt=this.findInstances(r,s,await this.reason(t)),Ie={},xt=new Set;for(let q of Rt){if(!await this.passesWhere($e,r,Et,q))continue;let ye={type:wt};for(let Ne of bt){let Ct=await this.evaluateValue($e,r,Ne.value,q),Oe=this.builder.serializeValue(St(Ct),p);Oe!==void 0&&(ye[p.ref(Ne.as)]=Oe)}let Ke=w(q);Ke&&(ye[`${vt}.derivedFrom`]=p.ref(Ke)),Ie[this.rowName(q,xt)]=ye}let me={};t.resolvedAt&&(me[`${O}.resolvedAt`]=t.resolvedAt),t.invocationId&&(me[`${O}.id`]=t.invocationId);let B=await this.builder.buildContentAddressed({publisher:a,book:p,body:Ie,contentHashProperty:`${O}.contentHash`,header:me});return{yaml:B.yaml,contentHash:B.contentHash,packageName:B.packageName,publisher:B.publisher,rowCount:B.resourceCount}}resolveView(e,t){let r=Y(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let n=V(r,Eo);if(n){let s=Y(e,n);if(!s)throw new Error(`ViewPackage ${t.name} names rootView ${n.name}, which is not in the catalog.`);return s}return r}readProjections(e,t){let r=[];for(let n of ge(t,Co)){let s=n instanceof D?n:n instanceof M?Y(e,n.subject):void 0;if(!s)continue;let i=he(s,Do),a=V(s,To);i&&a&&r.push({value:i,as:a})}return r}async reason(e){return new ke({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let n=Io(e),s=[],i=new Set;for(let a of r.getInstancesOfClass(t)){if(i.has(a))continue;i.add(a);let c=n.get(a);c&&s.push(c)}return s.sort((a,c)=>{let d=L(w(a)),p=L(w(c));return d<p?-1:d>p?1:0}),s}async passesWhere(e,t,r,n){for(let s of r){let i=await this.evaluateValue(e,t,s,n);if(!No(i))return!1}return!0}async evaluateValue(e,t,r,n){let s=Me(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",n]]);return e.evaluate(s,i)}rowName(e,t){let r=G(e.name)||"row",n=r,s=2;for(;t.has(n);)n=`${r}-${s++}`;return t.add(n),n}};function St(o){return ve(o)?o.value:Array.isArray(o)?o.map(St):o}function _o(o){let e=w(o);if(!e)throw new Error(`Could not derive a publisher from view ${o.namespace}/${o.name}.`);return e.publisher}function kt(o,e,t){let r=$o(o,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 $o(o,e,t){let r;for(let n of o){if(!(n instanceof A))continue;let s=w(n);!s||s.publisher!==e||s.package_!==t||!s.version||(!r||X(s.version,r)>0)&&(r=s.version)}return r?E(r):void 0}function Io(o){let e=new Map,t=new Map;for(let r of o){if(!(r instanceof A))continue;let n=w(r);if(!n||!n.version)continue;let s=L(n),i=t.get(s);(!i||X(n.version,i)>0)&&(t.set(s,n.version),e.set(s,r))}return e}function Ko(o,e){let t=he(o,e);return t?[t]:ge(o,e).filter(r=>r instanceof D)}function No(o){return o===!0?!0:o===!1||o===void 0||o===null?!1:typeof o=="string"?o.length>0:typeof o=="number"?o!==0:ve(o)?o.value.length>0:Array.isArray(o)?o.length>0:!!o}export{ln as AmbiguousReferenceRule,ir as BooleanStatement,Pn as CANONICAL_FORM_VERSION,mr as Carrier,fn as ClassDefinitionRule,tn as ClassHierarchyCycleRule,jt as CompositeKanonakDocumentRepository,le as CredentialResolver,ae as CredentialStore,rt as DEFAULT_CONSENT_BINDING_PARAM,Qt as DefinedKanonak,P as DeviceCertificateStore,Bt as DocumentLocation,br as EdgeType,D as EmbeddedKanonak,Zr as EmbeddedKanonakTypeRule,cr as EmbeddedStatement,J as EntitlementDeniedError,pe as EntitlementProducer,Ot as FileSystemKanonakDocumentRepository,Dr as GitIgnoreFilter,Er as GraphBuilder,Gt as HttpKanonakDocumentRepository,W as ImportBook,Qr as ImportExistenceRule,Nt as InMemoryKanonakDocumentRepository,Lt as KANONAK_USER_AGENT,Zt as Kanonak,_r as KanonakDocumentPositions,F as KanonakObjectParser,gn as KanonakObjectValidator,j as KanonakParser,er as KanonakUri,Kr as KanonakUriBuilder,Or as KanonakUrlResolver,kr as KanonakVocabulary,lr as ListStatement,tr as LiteralKanonak,Jt as LocalFirstRepository,qt as LockAwareRepository,vn as LookRenderer,hn as MarkdownLinkRule,dr as MarkdownStatement,an as NamespaceImportCycleRule,Gr as NamespacePrefixRule,Pr as NodeType,sr as NumberStatement,b as OAuthDiscovery,Cr as OWL_RL_CLASSIFICATION_RULES,pn as ObjectPropertyValueValidationRule,Hr as OntologyValidationError,Fr as OntologyValidationResult,N as PackageBuilder,Yr as PackageHeaderRule,de as ProducerRepository,un as PropertyDomainRule,rn as PropertyHierarchyCycleRule,mn as PropertyKindRangeConsistencyRule,Tr as PropertyMetadata,dn as PropertyRangeReferenceRule,nn as PropertyRangeRequiredRule,qr as PropertyTypeSpecificityRule,Ht as PublisherConfigResolver,zt as PublisherIndex,xr as RDFS_RULES,ke as Reasoner,Ar as ReasoningResult,M as ReferenceKanonak,ar as ReferenceStatement,Vt as RepositoryFactory,yn as ReservedNameShadowRule,Jr as ResourceNamingRule,pr as ResourceResolver,wr as ResourceTypeClassifier,nr as ScalarStatement,I as SessionError,$ as SessionExchange,S as SessionExchangeError,K as SessionManager,_ as SessionStore,rr as Statement,or as StringStatement,on as SubClassOfReferenceRule,sn as SubPropertyOfReferenceRule,A as SubjectKanonak,Xr as SubjectKanonakTypeRequiredRule,Rr as TripleStore,ur as TypeResolver,cn as UnresolvedPredicateRule,en as UnresolvedReferenceRule,Wr as ValidationCache,zr as ValidationContext,Ur as ValidationSeverity,fa as VersionOperator,ue as ViewMaterializer,Te as allowAllPolicy,Wt as assertPackageIdentity,Yt as buildLocalFirstRepository,bn as buildOntologyModel,wn as canonicalForm,we as canonicalHash,yr as carrierOf,Xt as collectKanonakFiles,X as compareVersions,ut as computeIntegrity,De as contentAddressedName,Vr as contextTypesOf,at as createAuthenticatedFetch,z as createDPoPProof,Tt as createVersion,vr as extractMarkdownLinks,kn as findDerivation,Lr as findInstancesByType,Sr as findMalformedReferences,Ir as findMarkdownLinkAt,Nr as formatKanonakAddress,E as formatVersion,st as generateDPoPKeyPair,Mt as getGlobalCachePath,Ut as getKanonakUserAgent,Q as hasValidToken,$t as isCompatibleVersion,Z as isExpired,It as isMajorCompatible,C as kanonakFetch,dt as loadLockFile,fr as makeUriKey,_e as noopMeter,l as normalizeHost,Se as parseKanonakAddress,_t as parseVersionString,$r as parseWithPositions,Kt as pickHighestDocument,jr as propertiesInScope,Sn as resolveDisplayValue,Mr as resolvePropertyStep,G as sanitizeName,pt as saveLockFile,it as serverSupportsDPoP,ce as sessionNeedsRefresh,Ft as setKanonakUserAgent,w as subjectUri,Br as superClassChain,hr as tripleKey,L as uriKey,gr as uriTriple,At as versionOperatorFromChar,fe as versionOperatorToChar,Dt as versionsEqual};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "5.3.0",
3
+ "version": "5.4.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.1",
129
- "@kanonak-protocol/types": "^5.3.0",
129
+ "@kanonak-protocol/types": "^5.4.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{H as W,I as X}from"./chunk-7K5TAJ44.js";import{b as B,c as V,l as N}from"./chunk-MX3DEXMV.js";import{a as b,d as K,e as q,f as z}from"./chunk-ZP6P7HNU.js";import{c as G,d as x,m as w,r as E,t as F,v as D,w as Y,y as v}from"./chunk-7BHDZHJY.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 N().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
- `)||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 Se(n){return!!n.accessToken&&!de(n)}function Re(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",R="core-rdf",re="core-xsd",te={publisher:C,package_:R,name:"subClassOf"},oe={publisher:C,package_:R,name:"label"},ye={publisher:C,package_:R,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_===R&&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 S=n=>new L(C,re,n);function ke(n){return typeof n=="boolean"?S("boolean"):typeof n=="number"?Number.isInteger(n)?S("integer"):S("decimal"):S("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?D(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=w(e);return z(n,e).filter(t=>r?!0:t.domains.some(p=>w(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 N().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=w(u);if(g.has(l))continue;g.add(l);let f=ge(y).map(k=>({uri:k,localName:k.name})),c=D(y,oe),d=D(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,Se as e,Re as f,Te as g};