@kanonak-protocol/sdk 5.24.0 → 5.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/{chunk-DUM5Q4MH.js → chunk-D66LUZDB.js} +1 -1
- package/dist/{chunk-RZ4WYL2X.js → chunk-I3UXFEJA.js} +1 -1
- package/dist/{chunk-WKLSD5DQ.js → chunk-JFBPQN6T.js} +1 -1
- package/dist/chunk-P5VQEDBS.js +2 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/repositories/HttpKanonakDocumentRepository.d.ts +41 -2
- package/dist/repositories/browser.js +1 -1
- package/dist/repositories/buildLocalFirstRepository.d.ts +3 -2
- package/dist/repositories/index.d.ts +1 -1
- package/dist/repositories/index.js +1 -1
- package/dist/server/index.js +13 -13
- package/package.json +2 -2
- package/dist/chunk-M7OWTFTC.js +0 -2
package/dist/browser.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as _,b as q,c as w,d as he,e as Ke,f as Se,g as Ie,i as be,j as je,k as Oe,l as De,m as ve}from"./chunk-
|
|
1
|
+
import{a as _,b as q,c as w,d as he,e as Ke,f as Se,g as Ie,i as be,j as je,k as Oe,l as De,m as ve}from"./chunk-I3UXFEJA.js";import{a as Ve}from"./chunk-5GFOZL7D.js";import{a as m,b as c,c as u,e as d,h as R,i as y,j as f,k,l as x,m as P,n as g}from"./chunk-P5VQEDBS.js";import{a as B,b as z,c as W}from"./chunk-6YX2TDI5.js";import{a as X}from"./chunk-PEB52US5.js";import"./chunk-SC5M74NM.js";import{A as Pe,B as ge,L as Ce,a as Y,b as J,c as Q,d as Z,f as $,g as ee,h as oe,i as te,k as re,l as ne,m as ae,n as ie,o as se,p as pe,q as le,r as me,s as ce,t as ue,u as de,v as Re,w as ye,x as fe,y as ke,z as xe}from"./chunk-3XOXKMYB.js";import"./chunk-BRCVOR7A.js";import"./chunk-AND44TIS.js";import{a as p}from"./chunk-6VIUXP4N.js";import{a as S,c as A,i as U,j as G,m as H}from"./chunk-YU2VGLOT.js";import{a as l}from"./chunk-KOWDHKBN.js";import"./chunk-PEJALHXK.js";import{a as F,b as L,o as M}from"./chunk-O6YV2SDB.js";import{a as C,b as h,c as K,d as b,e as j,f as O,g as D,h as V,i as v,j as E,k as N,l as T}from"./chunk-H6UAD2LP.js";import{a as I}from"./chunk-FUUTGGJS.js";import{c as e,d as o,e as t,f as r,g as n,h as a,i,k as s}from"./chunk-QILEJIFU.js";export{de as AmbiguousReferenceRule,v as BooleanStatement,Se as CANONICAL_FORM_VERSION,U as Carrier,Pe as ClassDefinitionRule,ie as ClassHierarchyCycleRule,h as DefinedKanonak,q as EdgeType,S as EmbeddedKanonak,re as EmbeddedKanonakTypeRule,N as EmbeddedStatement,w as GraphBuilder,g as HttpKanonakDocumentRepository,y as INTEGRITY_PREFIX,ne as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,m as KANONAK_USER_AGENT,C as Kanonak,z as KanonakDocumentPositions,H as KanonakObjectParser,Ce as KanonakObjectValidator,l as KanonakParser,I as KanonakUri,X as KanonakUriBuilder,T as ListStatement,ge as MarkdownLinkRule,A as MarkdownStatement,ce as NamespaceImportCycleRule,$ as NamespacePrefixRule,_ as NodeType,V as NumberStatement,be as OAuthDiscovery,ye as ObjectPropertyValueValidationRule,Q as OntologyValidationError,Y as OntologyValidationResult,fe as PropertyDomainRule,se as PropertyHierarchyCycleRule,ke as PropertyKindRangeConsistencyRule,B as PropertyMetadata,Re as PropertyRangeReferenceRule,pe as PropertyRangeRequiredRule,oe as PropertyTypeSpecificityRule,R as PublisherConfigResolver,P as PublisherIndex,b as ReferenceKanonak,E as ReferenceStatement,xe as ReservedNameShadowRule,ee as ResourceNamingRule,F as ResourceResolver,M as ResourceTypeClassifier,O as ScalarStatement,j as Statement,D as StringStatement,le as SubClassOfReferenceRule,me as SubPropertyOfReferenceRule,K as SubjectKanonak,te as SubjectKanonakTypeRequiredRule,De as TokenCredentialProvider,L as TypeResolver,ue as UnresolvedPredicateRule,ae as UnresolvedReferenceRule,Z as ValidationContext,J as ValidationSeverity,ve as buildOntologyModel,he as canonicalForm,Ke as canonicalHash,G as carrierOf,e as compareVersions,x as computeIntegrityAsync,Oe as createCredentialedFetch,r as createVersion,Ve as findDerivation,t as formatVersion,u as getKanonakUserAgent,a as isCompatibleVersion,i as isMajorCompatible,d as kanonakFetch,Ie as normalizeHost,je as parseAuthChallenge,f as parseLockFile,n as parseVersionString,W as parseWithPositions,s as pickHighestDocument,k as serializeLockFile,c as setKanonakUserAgent,o as versionsEqual};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i,j as o,k as r}from"./chunk-
|
|
1
|
+
import{i,j as o,k as r}from"./chunk-P5VQEDBS.js";import{readFileSync as c,writeFileSync as l,existsSync as s}from"fs";import{createHash as a}from"crypto";var n="kanonak.lock";function f(e=n){return s(e)?o(c(e,"utf-8")):null}function k(e,t=n){e.lastUpdated=new Date().toISOString(),l(t,r(e),"utf-8")}function L(e){let t=a("sha256").update(e).digest("hex");return`${i}${t}`}export{f as a,k as b,L as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{e as F}from"./chunk-
|
|
1
|
+
import{e as F}from"./chunk-P5VQEDBS.js";import{I as me,J as he}from"./chunk-3XOXKMYB.js";import{a as te,b as $,c as le,i as z,m as D}from"./chunk-YU2VGLOT.js";import{k as ue,o as O,p as x,q as ge,r as B,v as ye}from"./chunk-O6YV2SDB.js";import{b as ne,c as T,d as _,f as oe,g as se,h as ae,i as ie,j as ce,k as pe,l as L,m as K,r as G,t as de,v as I,w as fe,y as V}from"./chunk-H6UAD2LP.js";import{a as re}from"./chunk-FUUTGGJS.js";import{d as ee}from"./chunk-QILEJIFU.js";var Ce=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(Ce||{}),Se=(i=>(i.InstanceOf="instanceOf",i.SubClassOf="subClassOf",i.Domain="domain",i.Range="range",i.ObjectRelationship="objectRelationship",i.SubPropertyOf="subPropertyOf",i.PropertyValue="propertyValue",i.EmbeddedLink="embeddedLink",i))(Se||{}),H=class{static async buildFromRepository(n,t){let o=await new D().parseKanonaks(n),s=await n.getAllDocumentsAsync(),c=[],a=[],i=new Set,d=new Set,f=new Map;for(let g of o){let u=g;if(u.name&&(O.isClassType(u)&&i.add(u.name),g instanceof T)){let l=B(o,g);(l==="ObjectProperty"||l==="Property")&&d.add(u.name)}}for(let g of s)for(let[u,l]of Object.entries(g.body))d.has(u)&&l?.range&&typeof l.range=="string"&&f.set(u,l.range);let p=new Map;for(let g of o){let u=g;u.name&&p.set(u.name,u)}for(let g of s){let u=g.metadata.namespace_,l=u?`${u.publisher}/${u.package_}`:"",m=u?.version?`${u.version.major}.${u.version.minor}.${u.version.patch}`:"",b=ke(g);for(let[h,y]of Object.entries(g.body)){if(!y||typeof y!="object")continue;let C=p.get(h),k="Unknown";if(C){let R=C,j=C instanceof T?B(o,C):void 0;O.isClassType(R)?k="Class":j==="ObjectProperty"?k="ObjectProperty":j==="DatatypeProperty"?k="DatatypeProperty":j==="AnnotationProperty"?k="AnnotationProperty":O.isDatatypeType(R)?k="Datatype":j==="Property"?k="ObjectProperty":O.isInstanceOfKnownClass(R,i)&&(k="Instance")}let S=l&&m?`${l}/${h}@${m}`:h,Z={};for(let[R,j]of Object.entries(y))R!=="type"&&(typeof j!="object"||j===null)&&(Z[R]=j);c.push({id:S,label:y.label??h,type:k,namespace:l,properties:Z}),be(S,y,k,i,d,a,l,m,b,t),q(S,y,d,f,c,a,l,m,b),Le(S,C,a)}}return{nodes:c,edges:a}}static buildFromDocument(n,t){let r=[],o=[],s=n.metadata.namespace_,c=s?.version?`${s.version.major}.${s.version.minor}.${s.version.patch}`:"",a=s?`${s.publisher}/${s.package_}`:"",i=new Set,d=new Set,f=new Map,p=ke(n);for(let[l,m]of Object.entries(n.body)){let b=m?.type;b&&(Me(b,p)&&i.add(l),Ue(b,p)&&(d.add(l),m.range&&typeof m.range=="string"&&f.set(l,m.range)))}for(let[l,m]of Object.entries(n.body)){if(!m||typeof m!="object")continue;let b=m.type,h=Fe(b,l,i,p),y=a&&c?`${a}/${l}@${c}`:l,C={};for(let[k,S]of Object.entries(m))k!=="type"&&(typeof S!="object"||S===null)&&(C[k]=S);r.push({id:y,label:m.label??l,type:h,namespace:a,properties:C}),be(y,m,h,i,d,o,a,c,p,t),q(y,m,d,f,r,o,a,c,p)}let g=new Set(r.map(l=>l.id)),u=o.filter(l=>g.has(l.source)&&g.has(l.target));return{nodes:r,edges:u}}};function ke(e,n){let t=new Map;if(e.metadata?.imports)for(let[r,o]of Object.entries(e.metadata.imports))for(let s of o){let c=s.alias??s.packageName,a=s.version,i=`${a.major}.${a.minor}.${a.patch}`;t.set(c,{publisher:r,package_:s.packageName,version:i})}return t}var Oe={"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"},De=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function W(e,n){if(e.includes(".")){let t=e.indexOf("."),r=e.substring(0,t),o=e.substring(t+1),s=n.get(r);if(s)return`${s.publisher}/${s.package_}/${o}`}return null}function Me(e,n){let t=W(e,n);return t?Oe[t]==="Class":!1}function Ue(e,n){let t=W(e,n);return t?De.has(t):!1}function Fe(e,n,t,r){if(!e||e==="Package")return"Unknown";let o=W(e,r);if(o){let c=Oe[o];if(c)return c;let a=o.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let s=e.split(".").pop()??e;return t.has(s)?"Instance":"Unknown"}var ve=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function be(e,n,t,r,o,s,c,a,i,d){let f=n.type,p=n.subClassOf;if(p){let h=Array.isArray(p)?p:[p];for(let y of h)typeof y=="string"&&s.push({source:e,target:v(y,c,a,i),type:"subClassOf",label:"subClassOf"})}let g=n.subPropertyOf;if(g){let h=Array.isArray(g)?g:[g];for(let y of h)typeof y=="string"&&s.push({source:e,target:v(y,c,a,i),type:"subPropertyOf",label:"subPropertyOf"})}let u=n.domain,l=n.range;if(d?.includePropertyEdges){let h=[[u,"domain","domain"],[l,"range","range"]];for(let[y,C,k]of h)if(y!=null)for(let S of Array.isArray(y)?y:[y])typeof S=="string"&&s.push({source:e,target:v(S,c,a,i),type:C,label:k})}if(t==="Instance"&&f){let h=f.split(".").pop()??f;s.push({source:e,target:v(h,c,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[h,y]of Object.entries(n)){if(ve.has(h)||!o.has(h))continue;let C=Array.isArray(y)?y:[y];for(let k of C)typeof k=="string"&&Ge(k)&&s.push({source:e,target:v(k,c,a,i),type:"propertyValue",label:h,propertyId:v(h,c,a,i)})}if((t==="ObjectProperty"||t==="DatatypeProperty"||u&&l)&&u&&l){let h=typeof u=="string"?u:null,y=typeof l=="string"?l:null;h&&y&&s.push({source:v(h,c,a,i),target:v(y,c,a,i),type:"objectRelationship",label:n.label??e.split("/").pop()??"",propertyId:e})}}function q(e,n,t,r,o,s,c,a,i){for(let[d,f]of Object.entries(n)){if(ve.has(d)||typeof f!="object"||f===null||Array.isArray(f))continue;let p=f,g=`${e}/${d}`,u=r.get(d),l=u?u.split(".").pop()??u:"Unknown",m={};for(let[h,y]of Object.entries(p))(typeof y!="object"||y===null)&&(m[h]=y);o.push({id:g,label:`${l} (embedded)`,type:"Instance",namespace:c,properties:m});let b=c&&a?`${c}/${d}@${a}`:d;s.push({source:e,target:g,type:"propertyValue",label:d,propertyId:t.has(d)?b:void 0}),u&&s.push({source:g,target:v(l,c,a,i),type:"instanceOf",label:"type (inferred)"}),q(g,p,t,r,o,s,c,a,i)}}function Le(e,n,t){let r=n?.statement;if(Array.isArray(r))for(let o of r){if(!(o instanceof le))continue;let s=o.predicate?.subject?.name??"";for(let c of o.links){let a=c.target?.subject;if(!a)continue;let i=a.version,d=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"";t.push({source:e,target:`${a.publisher}/${a.package_}/${a.name}${d}`,type:"embeddedLink",label:s})}}}function Ge(e){return!(!e||e.includes(" ")||e.includes(`
|
|
2
2
|
`)||e.startsWith("http://")||e.startsWith("https://")||/^\d{4}-\d{2}/.test(e)||/^\d+(\.\d+)?$/.test(e))}function v(e,n,t,r){if(e.includes("@")&&e.includes("/"))return e;if(e.includes(".")){let o=e.indexOf("."),s=e.substring(0,o),c=e.substring(o+1);if(r){let a=r.get(s);if(a)return`${a.publisher}/${a.package_}/${c}@${a.version}`}return n&&t?`${n}/${c}@${t}`:c}return n&&t?`${n}/${e}@${t}`:e}import{canonicalForm as Ve,canonicalHash as Be}from"@kanonak-protocol/canonical";function X(e){return typeof e=="object"&&e!==null&&Array.isArray(e.subjects)}import{CANONICAL_FORM_VERSION as en}from"@kanonak-protocol/canonical";function ze(e){return Ve(X(e)?e:Pe(e))}function He(e){return Be(X(e)?e:Pe(e))}function Pe(e){let n=[];for(let t of e)t instanceof T&&n.push({uri:Ze(t),statements:Y(t.statement)});return{subjects:n}}function Y(e){let n=[];for(let t of e){let r=Qe(t);if(!r)continue;if(t instanceof L&&qe(t.predicate.subject)){n.push(...Xe(t,r));continue}let o=Ye(t);o&&n.push({predicate:r,value:o})}return n}function qe(e){let n=ue("type");return n!==void 0&&e.name==="type"&&e.publisher===n.publisher&&e.package_===n.package_}var we=new TextEncoder;function We(e,n){let t=we.encode(e),r=we.encode(n),o=Math.min(t.length,r.length);for(let s=0;s<o;s++)if(t[s]!==r[s])return t[s]-r[s];return t.length-r.length}function Xe(e,n){let t=[];for(let r of e.object){if(!(r instanceof _))throw new Error(`canonicalForm: a multi-valued type statement must contain only entity references, got ${r.constructor?.name??typeof r}`);t.push(J(r))}t.sort(We);for(let r=1;r<t.length;r++)if(t[r-1]===t[r])throw new Error(`canonicalForm: duplicate type ${t[r]} in a multi-valued type statement`);return t.map(r=>({predicate:n,value:{ref:r}}))}function Ye(e){if(e instanceof oe&&e.carrier)return{lit:e.lexical??String(e.object),datatype:Te(e.carrier)};if(e instanceof se)return{raw:e.object};if(e instanceof ae)return{raw:e.lexical??String(e.object)};if(e instanceof ie)return{raw:e.lexical??String(e.object)};if(e instanceof ce)return{ref:J(e.object)};if(e instanceof pe)return je(e.object);if(e instanceof L)return{list:e.object.map(Je)}}function je(e){let n=Y(e.statement);return e.name&&e.name.length>0?{embed:{name:e.name,statements:n}}:{embed:{statements:n}}}function Je(e){if(e instanceof _)return{ref:J(e)};if(e instanceof te)return je(e);if(e instanceof $){if(e.carrier)return{lit:e.lexical??String(e.value),datatype:Te(e.carrier)};let n=e.value;if(typeof n=="string")return{raw:n};if(typeof n=="number")return{raw:String(n)};if(typeof n=="boolean")return{raw:String(n)}}if(e instanceof ne)return{embed:{statements:Y(e.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${e.constructor?.name??typeof e}); add canonicalization support before hashing data that contains it`)}function Te(e){return e===z.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${e}`}function Qe(e){let n=e.predicate;if(n)return Ee(n.subject)}function Ze(e){let n=e.namespace??"",t=e.name??"";return`${n}/${t}`}function J(e){return Ee(e.subject)}function Ee(e){let n=e.version;return n&&typeof n.major=="number"?`${e.publisher}/${e.package_}@${n.major}.${n.minor}.${n.patch}/${e.name}`:`${e.publisher}/${e.package_}/${e.name}`}function A(e){let n=e.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!n)throw new Error("Publisher host cannot be empty");return n}var nn="key_thumbprint",N=class{cache=new Map;prCache=new Map;async discoverProtectedResource(n){let t=A(n);if(this.prCache.has(t))return this.prCache.get(t);let r=`https://${t}/.well-known/oauth-protected-resource`,o=await tn(r),s=o&&Array.isArray(o.authorization_servers)?o.authorization_servers.filter(a=>typeof a=="string"):[],c=s.length>0?s:null;return this.prCache.set(t,c),c}async discover(n){let t=A(n);if(this.cache.has(t))return this.cache.get(t);let r=`https://${t}/.well-known/oauth-authorization-server`,o=await this.tryEndpoint(r);if(!o){let s=`https://${t}/.well-known/openid-configuration`;o=await this.tryEndpoint(s)}return this.cache.set(t,o),o}async supportsOAuth(n){return await this.discover(n)!==null}static supportsPkceS256(n){return n.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(n){return!!n.registrationEndpoint}static supportsAuthorizationCode(n){return n.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(n){return!!n.enrollmentEndpoint}static supportsSession(n){return!!n.sessionEndpoint}async tryEndpoint(n){let t;try{t=await fetch(n)}catch(o){let s=o instanceof Error?o.message:String(o);return s.includes("ENOTFOUND")||s.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${n} \u2014 host unreachable (${s})`),console.error(" If the server is behind a VPN, ensure you are connected.")):s.includes("CERT")||s.includes("SSL")||s.includes("TLS")?(console.error(` OAuth discovery: ${n} \u2014 TLS error (${s})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${n} \u2014 network error: ${s}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${n} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${n} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let r;try{r=await t.json()}catch{return console.error(` OAuth discovery: ${n} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:w(r.issuer),authorizationEndpoint:w(r.authorization_endpoint),tokenEndpoint:w(r.token_endpoint),registrationEndpoint:w(r.registration_endpoint),revocationEndpoint:w(r.revocation_endpoint),scopesSupported:P(r.scopes_supported),responseTypesSupported:P(r.response_types_supported),grantTypesSupported:P(r.grant_types_supported),codeChallengeMethodsSupported:P(r.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:P(r.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:P(r.dpop_signing_alg_values_supported),enrollmentEndpoint:w(r.enrollment_endpoint),enrollmentIssuanceProtocols:P(r.enrollment_issuance_protocols),enrollmentKeyTypes:P(r.enrollment_key_types),enrollmentScopesSupported:P(r.enrollment_scopes_supported),enrollmentConsentBindingParam:w(r.enrollment_consent_binding_param),sessionEndpoint:w(r.session_endpoint),sessionEndpointAuthMethod:w(r.session_endpoint_auth_method)}}};async function tn(e){try{let n=await fetch(e);return n.ok?await n.json():null}catch{return null}}function w(e){return typeof e=="string"?e:null}function P(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):null}function Re(e){let n=e.headers.get("WWW-Authenticate")??void 0,t=e.headers.get("DPoP-Nonce")??void 0;if(!n&&!t)return;let r={wwwAuthenticate:n??""};if(t&&(r.nonce=t),n){let o=n.match(/acr_values\s*=\s*"([^"]*)"/i);o&&(r.acrValues=o[1])}return r}function rn(e){try{return new URL(e).host}catch{return null}}function on(e,n={}){let t=n.discovery??new N,r=new Map,o=new Map,s=async i=>{let d=r.get(i);if(d!==void 0)return d;let f=null,p=await t.discoverProtectedResource(i).catch(()=>null);return p&&p.length>0&&(f=rn(p[0])),r.set(i,f),f},c=async(i,d)=>{if(!e)return null;if(!(d.forceRefresh||d.challenge)&&o.has(i))return o.get(i);let p=await e.resolve(i,d).catch(()=>null);return o.set(i,p),p},a=async(i,d,f,p)=>{let g=await s(d);if(!g)return{res:await F(i,{method:f,redirect:"manual"}),authed:!1};let u=await c(g,{method:f,url:i,...p}),l=u?.headers??{};return{res:await F(i,{method:f,redirect:"manual",headers:l}),authed:!!u}};return async(i,d,f="GET")=>{let p=await a(i,d,f,{});if((p.res.status===401||p.res.status===403)&&p.authed){let g=Re(p.res),u={forceRefresh:g===void 0};return g&&(u.challenge=g),(await a(i,d,f,u)).res}return p.res}}var _e="KANONAK_TOKEN";function sn(){return typeof process<"u"&&process.env?process.env:{}}function an(e){return`${_e}_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}var Q=class{tokens;env;constructor(n={}){this.tokens=n.tokens??{},this.env=n.env??sn()}async resolve(n,t){let r=A(n),o=this.tokens[r]??this.env[an(r)]??this.env[_e];return o?{headers:{Authorization:`Bearer ${o}`}}:null}};var E="kanonak.org",U="core-rdf",Ie="core-xsd",Ae={publisher:E,package_:U,name:"subClassOf"},Ne={publisher:E,package_:U,name:"label"},$e={publisher:E,package_:U,name:"comment"},Ke={publisher:E,package_:"core-owl",name:"oneOf"},xe=e=>e;function cn(e){let n=fe(e,Ae);if(n)return[n];let t=[];for(let r of V(e,Ae))r instanceof _&&t.push(r.subject);return t}function pn(e,n,t){if(n.publisher===E&&n.package_===U&&n.name==="Literal")return{kind:"datatype",uri:n};let o=G(e,n);if(o){let s=xe(o);if(O.isDatatypeType(s))return{kind:"datatype",uri:n};if(O.isClassType(s))return{kind:"class",uri:x(o)??n,localName:o.name}}return n.publisher===E&&n.package_===Ie?{kind:"datatype",uri:n}:t==="datatype"?{kind:"datatype",uri:n}:{kind:"class",uri:n,localName:n.name}}function ln(e,n,t){if(!n.range)throw new Error(`Property ${n.uri.publisher}/${n.uri.package_}/${n.uri.name} has no rdfs.range; every property must declare a range. Validate the ontology before introspecting it.`);let r=pn(e,n.range,n.kind),o=n.kind==="object"?"object":n.kind==="datatype"?"datatype":r.kind==="class"?"object":"datatype";return{uri:n.uri,localName:n.uri.name,kind:o,range:r,...n.label!==void 0?{label:n.label}:{},...n.comment!==void 0?{comment:n.comment}:{},...t??{}}}var M=e=>new re(E,Ie,e);function un(e){return typeof e=="boolean"?M("boolean"):typeof e=="number"?Number.isInteger(e)?M("integer"):M("decimal"):M("string")}function dn(e,n){let t=[];for(let r of V(n,Ke))if(r instanceof _){let o=G(e,r.subject),s=(o?x(o):void 0)??r.subject,c=o?I(o,Ne):void 0,a=o?I(o,$e):void 0;t.push({kind:"individual",uri:s,localName:s.name,...c!==void 0?{label:c}:{},...a!==void 0?{comment:a}:{}})}else r instanceof $&&t.push({kind:"literal",value:r.value,datatype:un(r.value)});return t}function fn(e,n,t,r){let o=ge(e,n),s=K(n);return ye(e,n).filter(a=>t?!0:a.domains.some(i=>K(i)===s)).map(a=>ln(e,a,he(r,o,a.uri)))}async function gn(e,n,t){let r=e.metadata?.namespace_;if(!r)throw new Error("buildOntologyModel: document has no namespace (publisher/package/version).");let o=t?.includeInherited??!1,s=await new D().parseKanonaks(n),c=me(s),a=[],i=[],d=new Set;for(let f of s){if(!(f instanceof T)||!O.isClassType(xe(f)))continue;let p=x(f);if(!p||p.publisher!==r.publisher||p.package_!==r.package_||p.version&&r.version&&!ee(p.version,r.version))continue;let g=K(p);if(d.has(g))continue;d.add(g);let u=cn(f).map(b=>({uri:b,localName:b.name})),l=I(f,Ne),m=I(f,$e);a.push({uri:p,localName:p.name,superClasses:u,properties:fn(s,p,o,c),...l!==void 0?{label:l}:{},...m!==void 0?{comment:m}:{}}),de(f,Ke)&&i.push({uri:p,localName:p.name,members:dn(s,f),...l!==void 0?{label:l}:{},...m!==void 0?{comment:m}:{}})}return{classes:a,enums:i}}export{Ce as a,Se as b,H as c,ze as d,He as e,en as f,A as g,nn as h,N as i,Re as j,on as k,Q as l,gn as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as A}from"./chunk-M7OWTFTC.js";import{a as P}from"./chunk-6VIUXP4N.js";import{a as f}from"./chunk-KOWDHKBN.js";import{c as K,g as I,j as R}from"./chunk-QILEJIFU.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as b}from"url";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;return R(r,t)});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return K(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],h=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,h)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=b(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return b(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as g from"fs";var F=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(F||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as x}from"os";import{join as _}from"path";function d(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||_(x(),".kanonak","packages")}var w=class u{static createComposite(e,t,n){let o=e??d(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{VersionOperator as N}from"@kanonak-protocol/types/document/models/enums";var v=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return this.lock.packages[`${e}/${t}`]?.version}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=I(n);if(o){let s={...t,versionOperator:N.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as $,readdirSync as B}from"fs";import{join as S}from"path";var H=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function C(u,e=[]){for(let t of B(u,{withFileTypes:!0}))t.isDirectory()?H.has(t.name)||C(S(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(S(u,t.name));return e}async function V(u,e=new f,t={}){let n=new P(e);for(let m of C(u))try{let l=e.parse($(m,"utf-8")),p=l.metadata?.namespace_,h=p?.version;p&&h&&await n.saveDocumentAsync(l,`${p.publisher}/${p.package_}@${h.major}.${h.minor}.${h.patch}`)}catch{}let o=new y(d(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,p)=>s.get(`${m}|${l}|${p}`)??null,onFetch:(m,l,p,h)=>{s.set(`${m}|${l}|${p}`,h)}},r=new A({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,F as b,k as c,d,w as e,D as f,v as g,C as h,V as i};
|
|
1
|
+
import{n as A}from"./chunk-P5VQEDBS.js";import{a as P}from"./chunk-6VIUXP4N.js";import{a as f}from"./chunk-KOWDHKBN.js";import{c as K,g as I,j as R}from"./chunk-QILEJIFU.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as b}from"url";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;return R(r,t)});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,p=r.metadata.namespace_.version;return K(p,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),p=m[0],h=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,p,h)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=b(n).toString(),s;for(let[m,p]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&p.metadata.namespace_){s=p.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return b(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as g from"fs";var F=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(F||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as x}from"os";import{join as _}from"path";function d(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||_(x(),".kanonak","packages")}var w=class u{static createComposite(e,t,n){let o=e??d(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{VersionOperator as H}from"@kanonak-protocol/types/document/models/enums";var v=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return this.lock.packages[`${e}/${t}`]?.version}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=I(n);if(o){let s={...t,versionOperator:H.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as N,readdirSync as $}from"fs";import{join as S}from"path";var B=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function C(u,e=[]){for(let t of $(u,{withFileTypes:!0}))t.isDirectory()?B.has(t.name)||C(S(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(S(u,t.name));return e}async function V(u,e=new f,t={}){let n=new P(e);for(let m of C(u))try{let p=e.parse(N(m,"utf-8")),l=p.metadata?.namespace_,h=l?.version;l&&h&&await n.saveDocumentAsync(p,`${l.publisher}/${l.package_}@${h.major}.${h.minor}.${h.patch}`)}catch{}let o=new y(d(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,p,l)=>s.get(`${m}|${p}|${l}`)??null,onFetch:(m,p,l,h)=>{s.set(`${m}|${p}|${l}`,h)}},r=new A({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,F as b,k as c,d,w as e,D as f,v as g,C as h,V as i};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as m}from"./chunk-SC5M74NM.js";import{a as P}from"./chunk-KOWDHKBN.js";import{e as p,g as w,j as v}from"./chunk-QILEJIFU.js";var _="@kanonak-protocol/sdk (+https://kanonak.org)",y=_;function j(o){y=o}function B(){return y}function g(o){let t;try{t=typeof o=="string"?new URL(o):o}catch{throw new Error(`Kanonak requires an absolute https:// URL \u2014 got an unparseable or relative URL: ${String(o)}`)}if(t.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${t.href} (only https:// is supported).`)}var D=new Set([429,502,503,504]),U=4,K=500,R=2e4;function u(o,t){g(o);let e=new Headers(t?.headers);return e.has("User-Agent")||e.set("User-Agent",y),b(o,{...t,headers:e})}var d=U;function W(o){d=Math.max(0,o)}async function b(o,t){let e;for(let n=0;n<=d;n++){let r;try{r=await fetch(o,t)}catch(s){if(e=s,n>=d)throw s;await A(C(n,null));continue}if(!D.has(r.status)||n>=d)return r;await A(C(n,r.headers.get("retry-after")))}throw e??new Error("kanonakFetch: exhausted retries")}function C(o,t){let e=I(t);if(e!=null)return Math.min(e,R);let n=Math.min(R,K*2**o);return Math.floor(n/2+Math.random()*(n/2))}function I(o){if(!o)return null;let t=Number(o);if(Number.isFinite(t))return Math.max(0,t*1e3);let e=Date.parse(o);return Number.isNaN(e)?null:Math.max(0,e-Date.now())}function A(o){return new Promise(t=>setTimeout(t,o))}var T="https://{publisher}/{package}/{version}.kan.yml",x={version:1};function G(){return{version:1}}var k=class{constructor(t){this.fetchFn=t}fetchFn;cache=new Map;getConfig(t){let e=this.cache.get(t);return e||(e=this.fetchConfig(t),this.cache.set(t,e),e.catch(()=>{this.cache.get(t)===e&&this.cache.delete(t)})),e}async fetchConfig(t){let e=`https://${t}/.well-known/kanonak.json`,n;try{n=await(this.fetchFn?this.fetchFn(e,t):u(e))}catch{return x}if(n.status===404)return x;if(!n.ok)throw new Error(`Failed to fetch publisher config: ${e} (${n.status} ${n.statusText})`);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let s={version:r.version};return typeof r.package_url_template=="string"&&(M(e,"package_url_template",r.package_url_template),s.package_url_template=r.package_url_template),Array.isArray(r.featured_packages)&&r.featured_packages.every(a=>typeof a=="string")&&(s.featured_packages=r.featured_packages),s}resolvePackageUrl(t,e,n,r){let s=r.package_url_template??T,a=H(s,{publisher:t,package:e,version:n});return g(a),a}};function M(o,t,e){if(!e.startsWith("https://"))throw new Error(`Invalid publisher config at ${o}: ${t} must be an absolute https:// URL template (got "${e}").`)}function H(o,t){let e=o;for(let[r,s]of Object.entries(t))e=e.replaceAll(`{${r}}`,s);let n=e.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${o}`);return e}import E from"js-yaml";var S=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
2
|
+
`,O="sha256:";function $(o){let t=E.load(o);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??"",packages:t.packages??{}}}function Y(o){let t={};for(let n of Object.keys(o.packages).sort())t[n]=o.packages[n];let e=E.dump({...o,packages:t},{lineWidth:-1,sortKeys:!1,quotingType:'"'});return S+e}async function J(o){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)),e=Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("");return`${O}${e}`}var f=class{configResolver;fetchFn;lockCache=new Map;constructor(t){this.configResolver=t?.configResolver??new k(t?.fetchFn),this.fetchFn=t?.fetchFn}getConfig(t){return this.configResolver.getConfig(t)}async getPackageUrl(t,e,n){let r=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,e,n,r)}getLock(t){let e=this.lockCache.get(t);return e||(e=this.fetchLock(t),this.lockCache.set(t,e),e.catch(()=>{this.lockCache.get(t)===e&&this.lockCache.delete(t)})),e}async fetchLock(t){let e=`https://${t}/kanonak.lock`,n;try{n=this.fetchFn?await this.fetchFn(e,t):await u(e)}catch{return null}if(n.status===404)return null;if(!n.ok)throw new Error(`Failed to fetch publisher lock: ${e} (${n.status} ${n.statusText})`);return $(await n.text())}};import{VersionOperator as F}from"@kanonak-protocol/types/document/models/enums";function N(o,t){let e=w(o);return e?v(e,t):!1}var L=class{parser=new P;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new f({fetchFn:t.fetchFn}):new f}async getHighestCompatibleVersionAsync(t,e){if(e.versionOperator===F.Exact){let s=await this.fromMemoOrCache(t,e.packageName,p(e.version));if(s)return s}let r=(await this.publisherIndex.getLock(t))?.packages[`${t}/${e.packageName}`];return r&&N(r.version,e)?this.fetchPinned(t,e.packageName,r):r&&e.versionOperator!==F.Exact?null:this.resolveByDirectFetch(t,e)}async fetchPinned(t,e,n){let r=n.version,s=`${t}/${e}@${r}`,a=await this.fromMemoOrCache(t,e,r);if(a)return a;let i=n.resolved,c=this.fetchFn?await this.fetchFn(i,t):await u(i);if(!c.ok)throw new Error(`Failed to fetch Kanonak package: ${i} (${c.status} ${c.statusText})`);let l=await c.text(),h=this.parser.parse(l);return m(h,t,e,r),this.onFetch&&await this.onFetch(t,e,r,l),this.documents.set(s,h),this.contentCache.set(s,l),h}async fromMemoOrCache(t,e,n){let r=`${t}/${e}@${n}`,s=this.documents.get(r);if(s)return s;if(!this.getFromCache)return null;let a=await this.getFromCache(t,e,n);if(a==null)return null;let i;try{i=this.parser.parse(a),m(i,t,e,n)}catch(c){throw new Error(`Cached content for ${r} is not a usable copy of that package \u2014 refusing to fall through to a fetch that would hide it. ${c.message}`,{cause:c})}return this.documents.set(r,i),this.contentCache.set(r,a),i}async resolveByDirectFetch(t,e){let n=e.packageName,s=e.versionOperator===F.Exact?await this.publisherIndex.getPackageUrl(t,n,p(e.version)):`https://${t}/${n}.kan.yml`,a=await this.fetchFollowing(s,t);if(!a)return null;let i=this.parser.parse(a.content),c=i.metadata.namespace_;if(!c||!c.version)throw new Error(`Producer origin returned a package with no namespace/version for ${t}/${n}`);let l=p(c.version);m(i,t,n,l);let h=`${t}/${n}@${l}`;return this.onFetch&&await this.onFetch(t,n,l,a.content),this.documents.set(h,i),this.contentCache.set(h,a.content),i}async fetchFollowing(t,e,n=4){let r=t;for(let s=0;s<n;s++){g(r);let a=this.fetchFn?await this.fetchFn(r,e):await u(r,{redirect:"manual"});if(a.status===301||a.status===302){let i=a.headers.get("location");if(!i)throw new Error(`Redirect with no Location header from ${r}`);r=new URL(i,r).toString();continue}if(a.status===404)return null;if(!a.ok)throw new Error(`Failed to fetch Kanonak package: ${r} (${a.status} ${a.statusText})`);return{url:r,content:await a.text()}}throw new Error(`Too many redirects resolving ${t}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===t&&r.package_===e})}async saveDocumentAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let e=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,n,r,s]=e;return this.publisherIndex.getPackageUrl(n,r,s)}};export{_ as a,j as b,B as c,g as d,u as e,W as f,G as g,k as h,O as i,$ as j,Y as k,J as l,f as m,L as n};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { InMemoryKanonakDocumentRepository, FileSystemKanonakDocumentRepository, CompositeKanonakDocumentRepository, RepositoryFactory, DocumentLocation, HttpKanonakDocumentRepository, LocalFirstRepository, LockAwareRepository, buildLocalFirstRepository, collectKanonakFiles, PublisherIndex, PublisherConfigResolver, getGlobalCachePath } from './repositories/index.js';
|
|
2
|
-
export type { PublisherConfig, HttpCacheHooks } from './repositories/index.js';
|
|
2
|
+
export type { PublisherConfig, HttpCacheHooks, HttpCacheRead, HttpCacheWrite } from './repositories/index.js';
|
|
3
3
|
export { GraphBuilder, NodeType, EdgeType } from './graph/index.js';
|
|
4
4
|
export type { GraphNode, GraphEdge, GraphData } from './graph/index.js';
|
|
5
5
|
export { Reasoner, ReasoningResult, TripleStore, KanonakVocabulary, uriKey, makeUriKey, tripleKey, uriTriple, RDFS_RULES, OWL_RL_CLASSIFICATION_RULES, } from './reasoning/index.js';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Jt,b as Zt,c as Qt,d as eo,e as T}from"./chunk-USQLCG3Q.js";import{a as qe,b as Xe,c as Ye}from"./chunk-DUM5Q4MH.js";import{a as qt,b as Xt,c as Yt,d as qo,e as Ee,f as Xo,g as Yo,h as Jo,i as Zo,j as Qo,k as er,l as nr,m as or}from"./chunk-RZ4WYL2X.js";import{a as tr}from"./chunk-5GFOZL7D.js";import{a as dt,b as mt,c as ft,d as yt,e as kt,f as It,g as Kt,h as vt,i as wt}from"./chunk-WKLSD5DQ.js";import{a as ht,b as gt,c as St,d as bt,e as Et,f as Pt,h as Rt,i as Me,j as De,k as $e,l as Te,m as xt,n as Ct}from"./chunk-M7OWTFTC.js";import{a as to,b as oo,c as ro,d as ao}from"./chunk-6YX2TDI5.js";import{a as io}from"./chunk-PEB52US5.js";import{a as _t}from"./chunk-SC5M74NM.js";import{A as Vo,B as jo,C as Uo,D as Ho,E as Mo,F as Fo,G as Bo,H as Go,K as Wo,L as zo,a as co,b as uo,c as po,d as lo,e as mo,f as fo,g as yo,h as ko,i as ho,j as go,k as So,l as bo,m as Eo,n as Po,o as Ro,p as xo,q as _o,r as Co,s as Io,t as Ko,u as vo,v as wo,w as No,x as Oo,y as Ao,z as Lo}from"./chunk-3XOXKMYB.js";import"./chunk-BRCVOR7A.js";import{a as Do,c as be,e as Ge,h as We,i as ze,j as $o,k as To}from"./chunk-AND44TIS.js";import{a as le}from"./chunk-6VIUXP4N.js";import{a as x,b as D,c as ke,i as V,j as Se,k as Wt,l as zt,m as O}from"./chunk-YU2VGLOT.js";import{a as L}from"./chunk-KOWDHKBN.js";import{a as so}from"./chunk-PEJALHXK.js";import{a as jt,b as Ut,c as he,d as Ht,e as $,f as Mt,g as Dt,i as $t,m as Tt,o as Ft,p as g,q as Z,v as Bt,w as Gt,x as Q}from"./chunk-O6YV2SDB.js";import{a as Nt,b as Ot,c as S,d as k,e as Lt,f as Vt,g as de,h as me,i as fe,j as q,k as ye,l as X,m as p,p as Fe,r as _,t as Be,u as w,v as Y,w as h,x as ge,y as N,z as J}from"./chunk-H6UAD2LP.js";import{a as At}from"./chunk-FUUTGGJS.js";import{a as rt,b as pe,c as z,d as at,e as I,f as it,g as st,h as ct,i as ut,j as pt,k as lt}from"./chunk-QILEJIFU.js";import{a as no}from"./chunk-ODIECDN7.js";async function Je(n){let e=await new O().parseKanonaks(n),o=await new T().reason(n);return{kind:"merged",catalog:e,reasoning:o}}function Ze(n,e){return{kind:"merged",catalog:n,reasoning:e}}async function Qe(n,e){let o=e??new le(new L);return{kind:"standalone",catalog:await new O().parseKanonaks(new J(n,o))}}var Pe="kanonak.org",Re="core-shacl",c=n=>({publisher:Pe,package_:Re,name:n}),en=c("NodeShape"),Fr=c("PropertyShape"),nn=c("targetClass"),tn=c("property"),on=c("path"),rn=c("minCount"),an=c("maxCount"),sn=c("datatype"),cn=c("class"),xe=c("in"),un=c("pattern"),pn=c("flags"),ln=c("minLength"),dn=c("maxLength"),mn=c("minInclusive"),fn=c("maxInclusive"),yn=c("message"),kn=c("targetNode"),hn=c("targetSubjectsOf"),gn=c("targetObjectsOf"),Sn=c("closed"),bn=c("ignoredProperties"),En=c("nodeKind"),Pn=c("IRI"),Rn=c("BlankNode"),xn=c("Literal"),_e=c("severity"),_n=c("Violation"),Cn=c("Warning"),In=c("Info"),Br=c("ValidationReport"),Gr=c("conforms"),Wr=c("result"),zr=c("ValidationResult"),qr=c("focusNode"),Xr=c("resultPath"),Yr=c("resultMessage"),Jr=c("resultSeverity"),Zr=c("sourceShape"),Qr=c("value"),ea=c("sourceConstraintComponent"),Kn=c("MinCountConstraintComponent"),vn=c("MaxCountConstraintComponent"),wn=c("DatatypeConstraintComponent"),Nn=c("ClassConstraintComponent"),On=c("InConstraintComponent"),An=c("PatternConstraintComponent"),Ln=c("MinLengthConstraintComponent"),Vn=c("MaxLengthConstraintComponent"),jn=c("MinInclusiveConstraintComponent"),Un=c("MaxInclusiveConstraintComponent"),Hn=c("NodeKindConstraintComponent"),Ce=c("ClosedConstraintComponent");function H(n){return typeof n=="number"?n:void 0}function rr(n){if(!n)return;let e=p(n);if(e===p(Pn))return"IRI";if(e===p(Rn))return"BlankNode";if(e===p(xn))return"Literal"}function Mn(n){if(!n)return;let e=p(n);if(e===p(_n))return"Violation";if(e===p(Cn))return"Warning";if(e===p(In))return"Info"}function Ie(n,e){let o=h(n,e);if(o)return[o];let t=[];for(let r of N(n,e))r instanceof k&&t.push(r.subject);return t}function ar(n,e){let o=h(n,on);if(!o)return;let t={path:o},r=H(w(n,rn)),a=H(w(n,an));r!==void 0&&(t.minCount=r),a!==void 0&&(t.maxCount=a);let s=H(w(n,ln)),i=H(w(n,dn));s!==void 0&&(t.minLength=s),i!==void 0&&(t.maxLength=i);let u=H(w(n,mn)),d=H(w(n,fn));u!==void 0&&(t.minInclusive=u),d!==void 0&&(t.maxInclusive=d);let m=Y(n,un);if(m!==void 0){let P=Y(n,pn);t.pattern=P!==void 0?{regex:m,flags:P}:{regex:m}}if(Be(n,xe)){let P=[],j=[];for(let U of N(n,xe))U instanceof D?P.push(U.value):U instanceof k&&j.push(U.subject);P.length>0&&(t.inValues=P),j.length>0&&(t.inRefs=j)}let b=h(n,sn);b&&(t.datatype=b);let E=h(n,cn);E&&(t.classRef=E);let l=rr(h(n,En));l&&(t.nodeKind=l);let f=Y(n,yn);f!==void 0&&(t.message=f);let y=Mn(h(n,_e))??e;return y&&(t.severity=y),t}function ee(n){let e=[];for(let o of n){if(!(o instanceof S)||!Fe(o,en))continue;let t=Mn(h(o,_e)),r={name:o.name,uri:g(o),targetClass:h(o,nn),targetNodes:Ie(o,kn),targetSubjectsOf:Ie(o,hn),targetObjectsOf:Ie(o,gn),closed:w(o,Sn)===!0,ignoredProperties:[],severity:t,properties:[]};for(let a of N(o,bn))a instanceof k&&r.ignoredProperties.push(a.subject);for(let a of N(o,tn)){let s;if(a instanceof x?s=a:a instanceof k&&(s=_(n,a.subject)),!s)continue;let i=ar(s,t);i&&r.properties.push(i)}e.push(r)}return e}var C="kanonak.org/transformations",ne="values";var te="allowed",K=n=>({type:`${C}/VarRef`,varName:n}),Ke=n=>({type:`${C}/IntegerLiteral`,integerLiteral:n}),ir=n=>({type:`${C}/DecimalLiteral`,decimalLiteral:n}),Dn=n=>Number.isInteger(n)?Ke(n):ir(n),$n=n=>({type:`${C}/Count`,source:n}),Tn=(n,e)=>({type:`${C}/GreaterThanOrEqual`,compareLeft:n,compareRight:e}),Fn=(n,e)=>({type:`${C}/LessThanOrEqual`,compareLeft:n,compareRight:e});function ve(n,e){if(!e||e.length===0)return n;let o=new Set(["i","m","s"]),t=[...new Set(e.split(""))];if(t.filter(a=>!o.has(a)).length>0)throw new Error(`sh:flags '${e}' is outside the pinned regex subset (supported: i, m, s)`);return`(?${t.sort().join("")})${n}`}function oe(n){let e=[];return n.minCount!==void 0&&e.push({component:"minCount",per:"node",expr:Tn($n(K(ne)),Ke(n.minCount))}),n.maxCount!==void 0&&e.push({component:"maxCount",per:"node",expr:Fn($n(K(ne)),Ke(n.maxCount))}),(n.inValues!==void 0||n.inRefs!==void 0)&&e.push({component:"in",per:"value",expr:{type:`${C}/Contains`,haystack:K(te),needle:K("v")}}),n.pattern!==void 0&&e.push({component:"pattern",per:"value",expr:{type:`${C}/Matches`,matchSource:K("v"),pattern:ve(n.pattern.regex,n.pattern.flags)}}),n.minLength!==void 0&&e.push({component:"minLength",per:"value",expr:{type:`${C}/Matches`,matchSource:K("v"),pattern:`(?s)^.{${n.minLength},}$`}}),n.maxLength!==void 0&&e.push({component:"maxLength",per:"value",expr:{type:`${C}/Matches`,matchSource:K("v"),pattern:`(?s)^.{0,${n.maxLength}}$`}}),n.minInclusive!==void 0&&e.push({component:"minInclusive",per:"value",expr:Tn(K("v"),Dn(n.minInclusive))}),n.maxInclusive!==void 0&&e.push({component:"maxInclusive",per:"value",expr:Fn(K("v"),Dn(n.maxInclusive))}),e}import{evaluate as cr,ExpressionError as ur}from"@kanonak-protocol/expression";function Wn(n,e){let o=pr(e)?e:ee(e),t=[];for(let r of o)for(let a of lr(n,r))fr(n,r,a,t);return{conforms:!t.some(r=>r.severity==="Violation"),results:t}}function pr(n){return n.length>0&&!(n[0]instanceof Object&&"statement"in n[0])&&typeof n[0].name=="string"&&"properties"in n[0]}function re(n){let e=n.predicate;return e instanceof k?e:void 0}function lr(n,e){let o=new Map,t=n.catalog.filter(a=>a instanceof S),r=a=>{let s=g(a);o.set(s?p(s):`${a.namespace}/${a.name}`,a)};if(e.targetClass){let a=p(e.targetClass);if(n.reasoning){let s=new Set(n.reasoning.getInstancesOfClass(e.targetClass));for(let i of t){let u=g(i);u&&s.has(p(u))&&r(i)}}else for(let s of t)Q(s).some(u=>p(u)===a||Z(n.catalog,u).some(d=>p(d)===a))&&r(s)}for(let a of e.targetNodes){let s=_(n.catalog,a);s instanceof S&&r(s)}for(let a of e.targetSubjectsOf){let s=p(a);for(let i of t)i.statement.some(u=>{let d=re(u);return d&&p(d.subject)===s})&&r(i)}for(let a of e.targetObjectsOf){let s=p(a);for(let i of t)for(let u of i.statement){let d=re(u);if(!(!d||p(d.subject)!==s))for(let m of dr(u)){let b=_(n.catalog,m);b instanceof S&&r(b)}}}return[...o.values()]}function dr(n){return n instanceof q?[n.object.subject]:n instanceof X?(n.object??[]).filter(e=>e instanceof k).map(e=>e.subject):[]}function mr(n,e,o){let t=[];for(let r of n.statement){let a=re(r);if(!(!a||p(a.subject)!==e)){if(r instanceof de||r instanceof ke)t.push({kernel:r.object,kind:"string",literal:r.object});else if(r instanceof me)t.push({kernel:r.object,kind:"number",literal:r.object});else if(r instanceof fe)t.push({kernel:r.object?1:0,kind:"boolean",literal:r.object});else if(r instanceof q)t.push({kernel:{ref:p(r.object.subject)},kind:"reference",ref:r.object.subject});else if(r instanceof ye)t.push(Bn(r.object,o,t.length));else if(r instanceof X){for(let s of r.object??[])if(s instanceof k)t.push({kernel:{ref:p(s.subject)},kind:"reference",ref:s.subject});else if(s instanceof x)t.push(Bn(s,o,t.length));else if(s instanceof D){let i=s.value;typeof i=="boolean"?t.push({kernel:i?1:0,kind:"boolean",literal:i}):t.push({kernel:i,kind:typeof i=="number"?"number":"string",literal:i})}}}}return t}function Bn(n,e,o){let t=n.name&&n.name.length>0?n.name:String(o);return{kernel:{ref:`${e}#${t}`},kind:"embedded"}}function fr(n,e,o,t){let r=g(o),a=r?p(r):`${o.namespace}/${o.name}`;for(let s of e.properties)kr(n,e,o,a,r,s,t);e.closed&&Er(e,o,a,r,t)}function we(n,e,o,t,r,a={},s){return{focusNode:e,focusUri:o,constraintComponent:t,severity:s??zn(n),message:r,sourceShape:n.name,sourceShapeUri:n.uri,...a}}function zn(n){return n.severity??"Violation"}var yr={minCount:Kn,maxCount:vn,in:On,pattern:An,minLength:Ln,maxLength:Vn,minInclusive:jn,maxInclusive:Un};function kr(n,e,o,t,r,a,s){let i=p(a.path),u=mr(o,i,t),d=a.severity??zn(e),m=a.path.name,b=[...(a.inValues??[]).map(l=>typeof l=="boolean"?l?1:0:l),...(a.inRefs??[]).map(l=>({ref:p(l)}))],E=(l,f,y)=>{s.push(we(e,t,r,l,a.message??f,{resultPath:a.path,value:y?.literal,valueRef:y?.ref},d))};for(let l of oe(a)){let f=yr[l.component];if(l.per==="node"){Gn(l,{[ne]:u.map(P=>P.kernel),[te]:b})||E(f,l.component==="minCount"?`'${m}' has ${u.length} value(s); minCount is ${a.minCount}.`:`'${m}' has ${u.length} value(s); maxCount is ${a.maxCount}.`);continue}for(let y of u){if((l.component==="pattern"||l.component==="minLength"||l.component==="maxLength")&&y.kind!=="string"){E(f,`'${m}' value is not a string; ${l.component} applies to string values.`,y);continue}Gn(l,{v:y.kernel,[te]:b})||E(f,hr(l,m,a,y),y)}}if(a.nodeKind)for(let l of u)gr(a.nodeKind,l)||E(Hn,`'${m}' value is ${l.kind}; nodeKind requires ${a.nodeKind}.`,l);if(a.datatype)for(let l of u){let f=Sr(a.datatype,l);f&&E(wn,`'${m}' ${f}`,l)}if(a.classRef)for(let l of u){let f=br(n,a.classRef,l);f&&E(Nn,`'${m}' ${f}`,l)}}function hr(n,e,o,t){let r=t.ref?p(t.ref):JSON.stringify(t.literal);switch(n.component){case"in":return`'${e}' value ${r} is not in the permitted set.`;case"pattern":return`'${e}' value ${r} does not match pattern ${o.pattern?.regex}.`;case"minLength":return`'${e}' value ${r} is shorter than minLength ${o.minLength}.`;case"maxLength":return`'${e}' value ${r} is longer than maxLength ${o.maxLength}.`;case"minInclusive":return`'${e}' value ${r} is below minInclusive ${o.minInclusive} (or not numeric).`;case"maxInclusive":return`'${e}' value ${r} is above maxInclusive ${o.maxInclusive} (or not numeric).`;default:return`'${e}' value ${r} violates ${n.component}.`}}function Gn(n,e){let o=t=>{let r=t.varName;if(t.type==="kanonak.org/transformations/VarRef"&&typeof r=="string"&&r in e)return e[r];throw new ur(`Conformance lowering produced an unexpected leaf '${t.type}'`)};return cr(n.expr,void 0,o)===1}function gr(n,e){switch(n){case"IRI":return e.kind==="reference";case"BlankNode":return e.kind==="embedded";case"Literal":return e.kind==="string"||e.kind==="number"||e.kind==="boolean"}}function Sr(n,e){if(e.kind==="reference"||e.kind==="embedded")return`value is a ${e.kind}; sh:datatype requires a literal of ${n.name}.`;let o=Se(n);if(o!==void 0)switch(o){case V.Boolean:return e.kind==="boolean"?void 0:`value is not a boolean (${n.name}).`;case V.Integer:return e.kind!=="number"?`value is not a number (${n.name}).`:Number.isInteger(e.literal)?void 0:`value is not an integer (${n.name}).`;case V.Decimal:case V.Double:case V.Float:return e.kind==="number"?void 0:`value is not a number (${n.name}).`;default:return e.kind==="string"?void 0:`value is not a string-carried literal (${n.name}).`}}function br(n,e,o){if(o.kind!=="reference"||!o.ref)return`value is not a reference; sh:class requires an instance of ${e.name}.`;let t=p(e);if(n.reasoning)return n.reasoning.isInstanceOf(o.ref,e)?void 0:`value ${p(o.ref)} is not an instance of ${e.name}.`;let r=_(n.catalog,o.ref);return r instanceof S?Q(r).some(s=>p(s)===t||Z(n.catalog,s).some(i=>p(i)===t))?void 0:`value ${p(o.ref)} is not an instance of ${e.name}.`:`value ${p(o.ref)} does not resolve in this scope (sh:class ${e.name}).`}function Er(n,e,o,t,r){let a=new Set([...n.properties.map(i=>p(i.path)),...n.ignoredProperties.map(i=>p(i))]),s=new Set;for(let i of e.statement){let u=re(i);if(!u)continue;let d=p(u.subject);a.has(d)||s.has(d)||(s.add(d),r.push(we(n,o,t,Ce,`'${e.name}' carries undeclared property '${u.subject.name}' (closed shape).`,{resultPath:u.subject})))}for(let i of e.unresolvedPredicates)s.has(i.key)||(s.add(i.key),r.push(we(n,o,t,Ce,`'${e.name}' carries unresolvable property '${i.key}' (closed shape).`,{value:i.key})))}import*as Ne from"js-yaml";import{VersionOperator as qn}from"@kanonak-protocol/types/document/models/enums";var Pr="0.0.0",A=class{constructor(e,o=new L,t){this.repository=e;this.parser=o;this.objectParser=t??new O(this.parser)}repository;parser;objectParser;imports(){return new F}serializeValue(e,o){return Jn(e,o)}async buildContentAddressed(e){let o=e.book.toImports(),t=await this.hashBody(e.publisher,o,e.body),r=Oe(t),a={type:"EphemeralPackage",publisher:e.publisher,imports:o};e.contentHashProperty&&(a[e.contentHashProperty]=t),Object.assign(a,e.header??{}),a.imports=o;let s={[r]:a,...e.body},i=this.dump(s);return{yaml:i,byteCount:Yn(i),contentHash:t,packageName:r,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let o=e.book.toImports(),t={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:o},r;e.contentHashProperty&&(r=await this.hashBody(e.publisher,o,e.body),t[e.contentHashProperty]=r),Object.assign(t,e.header??{}),t.imports=o;let a={[e.name]:t,...e.body},s=this.dump(a),i={yaml:s,byteCount:Yn(s),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return r!==void 0&&(i.contentHash=r),i}dump(e){return Ne.dump(e,{lineWidth:-1})}async hashBody(e,o,t){let r={[Xn]:{type:"EphemeralPackage",publisher:e,imports:o},...t},a=this.parser.parse(Ne.dump(r,{lineWidth:-1})),s=a.metadata.namespace_?.toString(),u=(await this.objectParser.parseKanonaks(new J(a,this.repository))).filter(d=>d instanceof S&&d.namespace===s&&d.name!==Xn);for(let d of u)d.namespace="ephemeral";return Ee(u)}},Xn="__pkgbuilder_probe__";function Yn(n){return new TextEncoder().encode(n).length}function Oe(n){let e="sha256:",o=n.startsWith(e)?e.length:0;return`q-${n.slice(o,o+16)}`}var F=class{byKey=new Map;aliases=new Set;ensure(e,o,t,r,a=qn.Major){let s=`${e}/${o}@${t}`,i=this.byKey.get(s);if(i)return i.alias;let u=this.uniqueAlias(r);return this.byKey.set(s,{publisher:e,package_:o,version:t,alias:u,match:a}),u}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_,I(e.version),e.package_)}.${e.name}`}refLatest(e,o,t,r){return`${this.ensure(e,o,Pr,r??o,qn.Any)}.${t}`}toImports(){let e=new Map;for(let t of this.byKey.values()){let r=e.get(t.publisher)??[];r.push(t),e.set(t.publisher,r)}return[...e.keys()].sort().map(t=>({publisher:t,packages:e.get(t).sort((r,a)=>r.package_<a.package_?-1:1).map(r=>({package:r.package_,match:pe(r.match),version:r.version,alias:r.alias}))}))}uniqueAlias(e){let o=B(e)||"pkg",t=o,r=2;for(;this.aliases.has(t);)t=`${o}${r++}`;return this.aliases.add(t),t}};function Jn(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof k)return e.ref(n.subject);if(Array.isArray(n)){let o=n.map(t=>Jn(t,e)).filter(t=>t!==void 0);return o.length>0?o:void 0}if(n instanceof x)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(Rr(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function B(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Rr(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var xr="1.1.0";async function Zn(n){let e=new A(n.repository),o=e.imports(),t=o.ensure(Pe,Re,xr,"sh"),r=(i,u)=>i&&i.version&&typeof i.version.major=="number"?`${o.ensure(i.publisher,i.package_,I(i.version),i.package_)}.${i.name}`:u,a={},s=[];return n.result.results.forEach((i,u)=>{let d=`result-${u+1}`;s.push(d);let m={type:`${t}.ValidationResult`,[`${t}.focusNode`]:r(i.focusUri,i.focusNode),[`${t}.resultMessage`]:i.message,[`${t}.resultSeverity`]:`${t}.${i.severity}`,[`${t}.sourceConstraintComponent`]:`${t}.${i.constraintComponent.name}`};i.resultPath&&(m[`${t}.resultPath`]=r(i.resultPath,p(i.resultPath))),i.sourceShapeUri&&(m[`${t}.sourceShape`]=r(i.sourceShapeUri,i.sourceShape)),i.valueRef?m[`${t}.value`]=r(i.valueRef,p(i.valueRef)):i.value!==void 0&&(m[`${t}.value`]=i.value),a[d]=m}),a.report={type:`${t}.ValidationReport`,[`${t}.conforms`]:n.result.conforms,...s.length>0?{[`${t}.result`]:s}:{}},e.buildContentAddressed({publisher:n.publisher,book:o,body:a,...n.header!==void 0?{header:n.header}:{},contentHashProperty:"contentHash"})}import{VersionOperator as Hi}from"@kanonak-protocol/types/document/models/enums";var ae=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,o){return this.producers.find(t=>t.canProduce(e,o))}async produceCached(e,o,t,r){let a=`${o}/${t}@${I(r)}`,s=this.produced.get(a);if(s)return s;let{document:i}=await e.produce(o,t,r);return this.produced.set(a,i),i}async getHighestCompatibleVersionAsync(e,o){let t=this.producerFor(e,o.packageName);if(!t)return null;let r={operator:o.versionOperator,version:o.version},a=await t.resolveVersion(e,o.packageName,r);return a?this.produceCached(t,e,o.packageName,a):null}async getDocumentAsync(e){let o;try{o=he(e)}catch{return null}if(o.kind!=="package"||!o.version)return null;let t=this.producerFor(o.publisher,o.package_);return t?this.produceCached(t,o.publisher,o.package_,o.version):null}async getDocumentsByNamespaceAsync(e,o){return Array.from(this.produced.values()).filter(t=>{let r=t.metadata.namespace_;return r!=null&&r.publisher===e&&r.package_===o})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,o){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,o){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 Ae={async authorize(){return{allowed:!0}}},Le={async record(){}},G=class extends Error{constructor(o,t){let r=`${o.publisher}/${o.package_}${o.version?`@${o.version.major}.${o.version.minor}.${o.version.patch}`:""}`;super(`Not entitled to produce ${r}${t?`: ${t}`:""}`);this.address=o;this.reason=t;this.name="EntitlementDeniedError"}address;reason},ie=class{inner;ctx;policy;meter;constructor(e,o,t=Ae,r=Le){this.inner=e,this.ctx=o,this.policy=t,this.meter=r}canProduce(e,o){return this.inner.canProduce(e,o)}async resolveVersion(e,o,t){return await this.assertAllowed({publisher:e,package_:o,version:t.version}),this.inner.resolveVersion(e,o,t)}async produce(e,o,t){let r={publisher:e,package_:o,version:t};await this.assertAllowed(r);let a=await this.inner.produce(e,o,t);return await this.meter.record(this.ctx,r,a),a}async assertAllowed(e){let o=await this.policy.authorize(this.ctx,e);if(!o.allowed)throw new G(e,o.reason)}};var R="kanonak.org",v="view",Qn="core-kanonak",_r={publisher:R,package_:v,name:"rootView"},Cr={publisher:R,package_:v,name:"bind"},Ir={publisher:R,package_:v,name:"produces"},Kr={publisher:R,package_:v,name:"projections"},vr={publisher:R,package_:v,name:"where"},wr={publisher:R,package_:v,name:"value"},Nr={publisher:R,package_:v,name:"as"},se=class{constructor(e,o=new L){this.repository=e;this.parser=o;this.objectParser=new O(this.parser),this.builder=new A(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,o={}){let t=await this.objectParser.parseKanonaks(this.repository),r=this.resolveView(t,e),a=h(r,Cr);if(!a)throw new Error(`View ${r.namespace}/${r.name} declares no view.bind; cannot materialize.`);let s=h(r,Ir);if(!s)throw new Error(`View ${r.namespace}/${r.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 i=Or(r),u=et(t,R,Qn),d=et(t,R,v),m=this.builder.imports(),b=m.ensure(R,Qn,u,"ck"),E=m.ensure(R,v,d,"v"),l=m.ref(s),f=new ze(this.repository,this.parser,this.objectParser),y=new Ge(f,t),P=this.readProjections(t,r),j=Vr(r,vr),U=this.findInstances(t,a,await this.reason(o)),Ve={},tt=new Set;for(let W of U){if(!await this.passesWhere(y,t,j,W))continue;let ue={type:l};for(let Ue of P){let ot=await this.evaluateValue(y,t,Ue.value,W),He=this.builder.serializeValue(nt(ot),m);He!==void 0&&(ue[m.ref(Ue.as)]=He)}let je=g(W);je&&(ue[`${E}.derivedFrom`]=m.ref(je)),Ve[this.rowName(W,tt)]=ue}let ce={};o.resolvedAt&&(ce[`${b}.resolvedAt`]=o.resolvedAt),o.invocationId&&(ce[`${b}.id`]=o.invocationId);let M=await this.builder.buildContentAddressed({publisher:i,book:m,body:Ve,contentHashProperty:`${b}.contentHash`,header:ce});return{yaml:M.yaml,contentHash:M.contentHash,packageName:M.packageName,publisher:M.publisher,rowCount:M.resourceCount}}resolveView(e,o){let t=_(e,o);if(!t)throw new Error(`View ${o.publisher}/${o.package_}/${o.name} not found in the catalog.`);let r=h(t,_r);if(r){let a=_(e,r);if(!a)throw new Error(`ViewPackage ${o.name} names rootView ${r.name}, which is not in the catalog.`);return a}return t}readProjections(e,o){let t=[];for(let r of N(o,Kr)){let a=r instanceof x?r:r instanceof k?_(e,r.subject):void 0;if(!a)continue;let s=ge(a,wr),i=h(a,Nr);s&&i&&t.push({value:s,as:i})}return t}async reason(e){return new T({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,o,t){let r=Lr(e),a=[],s=new Set;for(let i of t.getInstancesOfClass(o)){if(s.has(i))continue;s.add(i);let u=r.get(i);u&&a.push(u)}return a.sort((i,u)=>{let d=$(g(i)),m=$(g(u));return d<m?-1:d>m?1:0}),a}async passesWhere(e,o,t,r){for(let a of t){let s=await this.evaluateValue(e,o,a,r);if(!jr(s))return!1}return!0}async evaluateValue(e,o,t,r){let a=We(t,"view-projection",{catalog:o,depth:0}),s=new Map([["input",r]]);return e.evaluate(a,s)}rowName(e,o){let t=B(e.name)||"row",r=t,a=2;for(;o.has(r);)r=`${t}-${a++}`;return o.add(r),r}};function nt(n){return be(n)?n.value:Array.isArray(n)?n.map(nt):n}function Or(n){let e=g(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function et(n,e,o){let t=Ar(n,e,o);if(!t)throw new Error(`Package ${e}/${o} is not in the catalog; it must be importable to materialize a view.`);return t}function Ar(n,e,o){let t;for(let r of n){if(!(r instanceof S))continue;let a=g(r);!a||a.publisher!==e||a.package_!==o||!a.version||(!t||z(a.version,t)>0)&&(t=a.version)}return t?I(t):void 0}function Lr(n){let e=new Map,o=new Map;for(let t of n){if(!(t instanceof S))continue;let r=g(t);if(!r||!r.version)continue;let a=$(r),s=o.get(a);(!s||z(r.version,s)>0)&&(o.set(a,r.version),e.set(a,t))}return e}function Vr(n,e){let o=ge(n,e);return o?[o]:N(n,e).filter(t=>t instanceof x)}function jr(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:be(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{vo as AmbiguousReferenceRule,fe as BooleanStatement,Xo as CANONICAL_FORM_VERSION,V as Carrier,Vo as ClassDefinitionRule,Po as ClassHierarchyCycleRule,ft as CompositeKanonakDocumentRepository,Jo as DEFAULT_CONSENT_BINDING_PARAM,Ot as DefinedKanonak,Wo as DiamondNameClashRule,Uo as DisplayLensScopeRule,mt as DocumentLocation,Xt as EdgeType,x as EmbeddedKanonak,So as EmbeddedKanonakTypeRule,ye as EmbeddedStatement,G as EntitlementDeniedError,ie as EntitlementProducer,dt as FileSystemKanonakDocumentRepository,no as GitIgnoreFilter,Yt as GraphBuilder,Ct as HttpKanonakDocumentRepository,Me as INTEGRITY_PREFIX,F as ImportBook,bo as ImportExistenceRule,le as InMemoryKanonakDocumentRepository,ht as KANONAK_USER_AGENT,Nt as Kanonak,oo as KanonakDocumentPositions,O as KanonakObjectParser,zo as KanonakObjectValidator,L as KanonakParser,At as KanonakUri,io as KanonakUriBuilder,so as KanonakUrlResolver,Tt as KanonakVocabulary,X as ListStatement,D as LiteralKanonak,It as LocalFirstRepository,Kt as LockAwareRepository,Mo as LookBandPathRule,$o as LookRenderer,Ho as LookSemanticSvgPathRule,jo as MarkdownLinkRule,ke as MarkdownStatement,Io as NamespaceImportCycleRule,fo as NamespacePrefixRule,qt as NodeType,me as NumberStatement,Zo as OAuthDiscovery,Qt as OWL_RL_CLASSIFICATION_RULES,No as ObjectPropertyValueValidationRule,po as OntologyValidationError,co as OntologyValidationResult,Go as OwlOneOfRule,A as PackageBuilder,go as PackageHeaderRule,ae as ProducerRepository,Oo as PropertyDomainRule,Ro as PropertyHierarchyCycleRule,Ao as PropertyKindRangeConsistencyRule,to as PropertyMetadata,wo as PropertyRangeReferenceRule,xo as PropertyRangeRequiredRule,ko as PropertyTypeSpecificityRule,Rt as PublisherConfigResolver,xt as PublisherIndex,Zt as RDFS_RULES,T as Reasoner,eo as ReasoningResult,k as ReferenceKanonak,q as ReferenceStatement,kt as RepositoryFactory,Lo as ReservedNameShadowRule,yo as ResourceNamingRule,jt as ResourceResolver,Ft as ResourceTypeClassifier,Vt as ScalarStatement,Bo as ShaclShapeRule,Lt as Statement,de as StringStatement,_o as SubClassOfReferenceRule,Co as SubPropertyOfReferenceRule,S as SubjectKanonak,ho as SubjectKanonakTypeRequiredRule,nr as TokenCredentialProvider,Jt as TripleStore,Fo as TxExpressionPathRule,Ut as TypeResolver,Ko as UnresolvedPredicateRule,Eo as UnresolvedReferenceRule,mo as ValidationCache,lo as ValidationContext,uo as ValidationSeverity,Hi as VersionOperator,se as ViewMaterializer,Ae as allowAllPolicy,bt as assertHttpsUrl,_t as assertPackageIdentity,wt as buildLocalFirstRepository,or as buildOntologyModel,Zn as buildReportPackageAsync,ee as buildShapesModel,qo as canonicalForm,Ee as canonicalHash,Se as carrierOf,vt as collectKanonakFiles,z as compareVersions,Ye as computeIntegrity,Te as computeIntegrityAsync,Oe as contentAddressedName,Q as contextTypesOf,er as createCredentialedFetch,it as createVersion,Wn as evaluateConformance,zt as extractMarkdownLinks,tr as findDerivation,Wt as findMalformedReferences,ao as findMarkdownLinkAt,ve as foldFlagsIntoPattern,Ht as formatKanonakAddress,I as formatVersion,yt as getGlobalCachePath,St as getKanonakUserAgent,ct as isCompatibleVersion,ut as isMajorCompatible,Et as kanonakFetch,qe as loadLockFile,oe as lowerConstraint,Mt as makeUriKey,Le as noopMeter,Yo as normalizeHost,Qo as parseAuthChallenge,he as parseKanonakAddress,De as parseLockFile,st as parseVersionString,ro as parseWithPositions,lt as pickHighestDocument,Bt as propertiesInScope,Do as resolveDisplayValue,Gt as resolvePropertyStep,B as sanitizeName,pt as satisfiesVersionOperator,Xe as saveLockFile,Ze as scopeFromCatalog,Qe as scopeFromDocumentAsync,Je as scopeFromRepositoryAsync,$e as serializeLockFile,Pt as setKanonakFetchRetries,gt as setKanonakUserAgent,g as subjectUri,Z as superClassChain,To as supportedBandKeys,Dt as tripleKey,$ as uriKey,$t as uriTriple,rt as versionOperatorFromChar,pe as versionOperatorToChar,at as versionsEqual};
|
|
1
|
+
import{a as Jt,b as Zt,c as Qt,d as eo,e as T}from"./chunk-USQLCG3Q.js";import{a as qe,b as Xe,c as Ye}from"./chunk-D66LUZDB.js";import{a as qt,b as Xt,c as Yt,d as qo,e as Ee,f as Xo,g as Yo,h as Jo,i as Zo,j as Qo,k as er,l as nr,m as or}from"./chunk-I3UXFEJA.js";import{a as tr}from"./chunk-5GFOZL7D.js";import{a as dt,b as mt,c as ft,d as yt,e as kt,f as It,g as Kt,h as vt,i as wt}from"./chunk-JFBPQN6T.js";import{a as ht,b as gt,c as St,d as bt,e as Et,f as Pt,h as Rt,i as Me,j as De,k as $e,l as Te,m as xt,n as Ct}from"./chunk-P5VQEDBS.js";import{a as to,b as oo,c as ro,d as ao}from"./chunk-6YX2TDI5.js";import{a as io}from"./chunk-PEB52US5.js";import{a as _t}from"./chunk-SC5M74NM.js";import{A as Vo,B as jo,C as Uo,D as Ho,E as Mo,F as Fo,G as Bo,H as Go,K as Wo,L as zo,a as co,b as uo,c as po,d as lo,e as mo,f as fo,g as yo,h as ko,i as ho,j as go,k as So,l as bo,m as Eo,n as Po,o as Ro,p as xo,q as _o,r as Co,s as Io,t as Ko,u as vo,v as wo,w as No,x as Oo,y as Ao,z as Lo}from"./chunk-3XOXKMYB.js";import"./chunk-BRCVOR7A.js";import{a as Do,c as be,e as Ge,h as We,i as ze,j as $o,k as To}from"./chunk-AND44TIS.js";import{a as le}from"./chunk-6VIUXP4N.js";import{a as x,b as D,c as ke,i as V,j as Se,k as Wt,l as zt,m as O}from"./chunk-YU2VGLOT.js";import{a as L}from"./chunk-KOWDHKBN.js";import{a as so}from"./chunk-PEJALHXK.js";import{a as jt,b as Ut,c as he,d as Ht,e as $,f as Mt,g as Dt,i as $t,m as Tt,o as Ft,p as g,q as Z,v as Bt,w as Gt,x as Q}from"./chunk-O6YV2SDB.js";import{a as Nt,b as Ot,c as S,d as k,e as Lt,f as Vt,g as de,h as me,i as fe,j as q,k as ye,l as X,m as p,p as Fe,r as _,t as Be,u as w,v as Y,w as h,x as ge,y as N,z as J}from"./chunk-H6UAD2LP.js";import{a as At}from"./chunk-FUUTGGJS.js";import{a as rt,b as pe,c as z,d as at,e as I,f as it,g as st,h as ct,i as ut,j as pt,k as lt}from"./chunk-QILEJIFU.js";import{a as no}from"./chunk-ODIECDN7.js";async function Je(n){let e=await new O().parseKanonaks(n),o=await new T().reason(n);return{kind:"merged",catalog:e,reasoning:o}}function Ze(n,e){return{kind:"merged",catalog:n,reasoning:e}}async function Qe(n,e){let o=e??new le(new L);return{kind:"standalone",catalog:await new O().parseKanonaks(new J(n,o))}}var Pe="kanonak.org",Re="core-shacl",c=n=>({publisher:Pe,package_:Re,name:n}),en=c("NodeShape"),Fr=c("PropertyShape"),nn=c("targetClass"),tn=c("property"),on=c("path"),rn=c("minCount"),an=c("maxCount"),sn=c("datatype"),cn=c("class"),xe=c("in"),un=c("pattern"),pn=c("flags"),ln=c("minLength"),dn=c("maxLength"),mn=c("minInclusive"),fn=c("maxInclusive"),yn=c("message"),kn=c("targetNode"),hn=c("targetSubjectsOf"),gn=c("targetObjectsOf"),Sn=c("closed"),bn=c("ignoredProperties"),En=c("nodeKind"),Pn=c("IRI"),Rn=c("BlankNode"),xn=c("Literal"),_e=c("severity"),_n=c("Violation"),Cn=c("Warning"),In=c("Info"),Br=c("ValidationReport"),Gr=c("conforms"),Wr=c("result"),zr=c("ValidationResult"),qr=c("focusNode"),Xr=c("resultPath"),Yr=c("resultMessage"),Jr=c("resultSeverity"),Zr=c("sourceShape"),Qr=c("value"),ea=c("sourceConstraintComponent"),Kn=c("MinCountConstraintComponent"),vn=c("MaxCountConstraintComponent"),wn=c("DatatypeConstraintComponent"),Nn=c("ClassConstraintComponent"),On=c("InConstraintComponent"),An=c("PatternConstraintComponent"),Ln=c("MinLengthConstraintComponent"),Vn=c("MaxLengthConstraintComponent"),jn=c("MinInclusiveConstraintComponent"),Un=c("MaxInclusiveConstraintComponent"),Hn=c("NodeKindConstraintComponent"),Ce=c("ClosedConstraintComponent");function H(n){return typeof n=="number"?n:void 0}function rr(n){if(!n)return;let e=p(n);if(e===p(Pn))return"IRI";if(e===p(Rn))return"BlankNode";if(e===p(xn))return"Literal"}function Mn(n){if(!n)return;let e=p(n);if(e===p(_n))return"Violation";if(e===p(Cn))return"Warning";if(e===p(In))return"Info"}function Ie(n,e){let o=h(n,e);if(o)return[o];let t=[];for(let r of N(n,e))r instanceof k&&t.push(r.subject);return t}function ar(n,e){let o=h(n,on);if(!o)return;let t={path:o},r=H(w(n,rn)),a=H(w(n,an));r!==void 0&&(t.minCount=r),a!==void 0&&(t.maxCount=a);let s=H(w(n,ln)),i=H(w(n,dn));s!==void 0&&(t.minLength=s),i!==void 0&&(t.maxLength=i);let u=H(w(n,mn)),d=H(w(n,fn));u!==void 0&&(t.minInclusive=u),d!==void 0&&(t.maxInclusive=d);let m=Y(n,un);if(m!==void 0){let P=Y(n,pn);t.pattern=P!==void 0?{regex:m,flags:P}:{regex:m}}if(Be(n,xe)){let P=[],j=[];for(let U of N(n,xe))U instanceof D?P.push(U.value):U instanceof k&&j.push(U.subject);P.length>0&&(t.inValues=P),j.length>0&&(t.inRefs=j)}let b=h(n,sn);b&&(t.datatype=b);let E=h(n,cn);E&&(t.classRef=E);let l=rr(h(n,En));l&&(t.nodeKind=l);let f=Y(n,yn);f!==void 0&&(t.message=f);let y=Mn(h(n,_e))??e;return y&&(t.severity=y),t}function ee(n){let e=[];for(let o of n){if(!(o instanceof S)||!Fe(o,en))continue;let t=Mn(h(o,_e)),r={name:o.name,uri:g(o),targetClass:h(o,nn),targetNodes:Ie(o,kn),targetSubjectsOf:Ie(o,hn),targetObjectsOf:Ie(o,gn),closed:w(o,Sn)===!0,ignoredProperties:[],severity:t,properties:[]};for(let a of N(o,bn))a instanceof k&&r.ignoredProperties.push(a.subject);for(let a of N(o,tn)){let s;if(a instanceof x?s=a:a instanceof k&&(s=_(n,a.subject)),!s)continue;let i=ar(s,t);i&&r.properties.push(i)}e.push(r)}return e}var C="kanonak.org/transformations",ne="values";var te="allowed",K=n=>({type:`${C}/VarRef`,varName:n}),Ke=n=>({type:`${C}/IntegerLiteral`,integerLiteral:n}),ir=n=>({type:`${C}/DecimalLiteral`,decimalLiteral:n}),Dn=n=>Number.isInteger(n)?Ke(n):ir(n),$n=n=>({type:`${C}/Count`,source:n}),Tn=(n,e)=>({type:`${C}/GreaterThanOrEqual`,compareLeft:n,compareRight:e}),Fn=(n,e)=>({type:`${C}/LessThanOrEqual`,compareLeft:n,compareRight:e});function ve(n,e){if(!e||e.length===0)return n;let o=new Set(["i","m","s"]),t=[...new Set(e.split(""))];if(t.filter(a=>!o.has(a)).length>0)throw new Error(`sh:flags '${e}' is outside the pinned regex subset (supported: i, m, s)`);return`(?${t.sort().join("")})${n}`}function oe(n){let e=[];return n.minCount!==void 0&&e.push({component:"minCount",per:"node",expr:Tn($n(K(ne)),Ke(n.minCount))}),n.maxCount!==void 0&&e.push({component:"maxCount",per:"node",expr:Fn($n(K(ne)),Ke(n.maxCount))}),(n.inValues!==void 0||n.inRefs!==void 0)&&e.push({component:"in",per:"value",expr:{type:`${C}/Contains`,haystack:K(te),needle:K("v")}}),n.pattern!==void 0&&e.push({component:"pattern",per:"value",expr:{type:`${C}/Matches`,matchSource:K("v"),pattern:ve(n.pattern.regex,n.pattern.flags)}}),n.minLength!==void 0&&e.push({component:"minLength",per:"value",expr:{type:`${C}/Matches`,matchSource:K("v"),pattern:`(?s)^.{${n.minLength},}$`}}),n.maxLength!==void 0&&e.push({component:"maxLength",per:"value",expr:{type:`${C}/Matches`,matchSource:K("v"),pattern:`(?s)^.{0,${n.maxLength}}$`}}),n.minInclusive!==void 0&&e.push({component:"minInclusive",per:"value",expr:Tn(K("v"),Dn(n.minInclusive))}),n.maxInclusive!==void 0&&e.push({component:"maxInclusive",per:"value",expr:Fn(K("v"),Dn(n.maxInclusive))}),e}import{evaluate as cr,ExpressionError as ur}from"@kanonak-protocol/expression";function Wn(n,e){let o=pr(e)?e:ee(e),t=[];for(let r of o)for(let a of lr(n,r))fr(n,r,a,t);return{conforms:!t.some(r=>r.severity==="Violation"),results:t}}function pr(n){return n.length>0&&!(n[0]instanceof Object&&"statement"in n[0])&&typeof n[0].name=="string"&&"properties"in n[0]}function re(n){let e=n.predicate;return e instanceof k?e:void 0}function lr(n,e){let o=new Map,t=n.catalog.filter(a=>a instanceof S),r=a=>{let s=g(a);o.set(s?p(s):`${a.namespace}/${a.name}`,a)};if(e.targetClass){let a=p(e.targetClass);if(n.reasoning){let s=new Set(n.reasoning.getInstancesOfClass(e.targetClass));for(let i of t){let u=g(i);u&&s.has(p(u))&&r(i)}}else for(let s of t)Q(s).some(u=>p(u)===a||Z(n.catalog,u).some(d=>p(d)===a))&&r(s)}for(let a of e.targetNodes){let s=_(n.catalog,a);s instanceof S&&r(s)}for(let a of e.targetSubjectsOf){let s=p(a);for(let i of t)i.statement.some(u=>{let d=re(u);return d&&p(d.subject)===s})&&r(i)}for(let a of e.targetObjectsOf){let s=p(a);for(let i of t)for(let u of i.statement){let d=re(u);if(!(!d||p(d.subject)!==s))for(let m of dr(u)){let b=_(n.catalog,m);b instanceof S&&r(b)}}}return[...o.values()]}function dr(n){return n instanceof q?[n.object.subject]:n instanceof X?(n.object??[]).filter(e=>e instanceof k).map(e=>e.subject):[]}function mr(n,e,o){let t=[];for(let r of n.statement){let a=re(r);if(!(!a||p(a.subject)!==e)){if(r instanceof de||r instanceof ke)t.push({kernel:r.object,kind:"string",literal:r.object});else if(r instanceof me)t.push({kernel:r.object,kind:"number",literal:r.object});else if(r instanceof fe)t.push({kernel:r.object?1:0,kind:"boolean",literal:r.object});else if(r instanceof q)t.push({kernel:{ref:p(r.object.subject)},kind:"reference",ref:r.object.subject});else if(r instanceof ye)t.push(Bn(r.object,o,t.length));else if(r instanceof X){for(let s of r.object??[])if(s instanceof k)t.push({kernel:{ref:p(s.subject)},kind:"reference",ref:s.subject});else if(s instanceof x)t.push(Bn(s,o,t.length));else if(s instanceof D){let i=s.value;typeof i=="boolean"?t.push({kernel:i?1:0,kind:"boolean",literal:i}):t.push({kernel:i,kind:typeof i=="number"?"number":"string",literal:i})}}}}return t}function Bn(n,e,o){let t=n.name&&n.name.length>0?n.name:String(o);return{kernel:{ref:`${e}#${t}`},kind:"embedded"}}function fr(n,e,o,t){let r=g(o),a=r?p(r):`${o.namespace}/${o.name}`;for(let s of e.properties)kr(n,e,o,a,r,s,t);e.closed&&Er(e,o,a,r,t)}function we(n,e,o,t,r,a={},s){return{focusNode:e,focusUri:o,constraintComponent:t,severity:s??zn(n),message:r,sourceShape:n.name,sourceShapeUri:n.uri,...a}}function zn(n){return n.severity??"Violation"}var yr={minCount:Kn,maxCount:vn,in:On,pattern:An,minLength:Ln,maxLength:Vn,minInclusive:jn,maxInclusive:Un};function kr(n,e,o,t,r,a,s){let i=p(a.path),u=mr(o,i,t),d=a.severity??zn(e),m=a.path.name,b=[...(a.inValues??[]).map(l=>typeof l=="boolean"?l?1:0:l),...(a.inRefs??[]).map(l=>({ref:p(l)}))],E=(l,f,y)=>{s.push(we(e,t,r,l,a.message??f,{resultPath:a.path,value:y?.literal,valueRef:y?.ref},d))};for(let l of oe(a)){let f=yr[l.component];if(l.per==="node"){Gn(l,{[ne]:u.map(P=>P.kernel),[te]:b})||E(f,l.component==="minCount"?`'${m}' has ${u.length} value(s); minCount is ${a.minCount}.`:`'${m}' has ${u.length} value(s); maxCount is ${a.maxCount}.`);continue}for(let y of u){if((l.component==="pattern"||l.component==="minLength"||l.component==="maxLength")&&y.kind!=="string"){E(f,`'${m}' value is not a string; ${l.component} applies to string values.`,y);continue}Gn(l,{v:y.kernel,[te]:b})||E(f,hr(l,m,a,y),y)}}if(a.nodeKind)for(let l of u)gr(a.nodeKind,l)||E(Hn,`'${m}' value is ${l.kind}; nodeKind requires ${a.nodeKind}.`,l);if(a.datatype)for(let l of u){let f=Sr(a.datatype,l);f&&E(wn,`'${m}' ${f}`,l)}if(a.classRef)for(let l of u){let f=br(n,a.classRef,l);f&&E(Nn,`'${m}' ${f}`,l)}}function hr(n,e,o,t){let r=t.ref?p(t.ref):JSON.stringify(t.literal);switch(n.component){case"in":return`'${e}' value ${r} is not in the permitted set.`;case"pattern":return`'${e}' value ${r} does not match pattern ${o.pattern?.regex}.`;case"minLength":return`'${e}' value ${r} is shorter than minLength ${o.minLength}.`;case"maxLength":return`'${e}' value ${r} is longer than maxLength ${o.maxLength}.`;case"minInclusive":return`'${e}' value ${r} is below minInclusive ${o.minInclusive} (or not numeric).`;case"maxInclusive":return`'${e}' value ${r} is above maxInclusive ${o.maxInclusive} (or not numeric).`;default:return`'${e}' value ${r} violates ${n.component}.`}}function Gn(n,e){let o=t=>{let r=t.varName;if(t.type==="kanonak.org/transformations/VarRef"&&typeof r=="string"&&r in e)return e[r];throw new ur(`Conformance lowering produced an unexpected leaf '${t.type}'`)};return cr(n.expr,void 0,o)===1}function gr(n,e){switch(n){case"IRI":return e.kind==="reference";case"BlankNode":return e.kind==="embedded";case"Literal":return e.kind==="string"||e.kind==="number"||e.kind==="boolean"}}function Sr(n,e){if(e.kind==="reference"||e.kind==="embedded")return`value is a ${e.kind}; sh:datatype requires a literal of ${n.name}.`;let o=Se(n);if(o!==void 0)switch(o){case V.Boolean:return e.kind==="boolean"?void 0:`value is not a boolean (${n.name}).`;case V.Integer:return e.kind!=="number"?`value is not a number (${n.name}).`:Number.isInteger(e.literal)?void 0:`value is not an integer (${n.name}).`;case V.Decimal:case V.Double:case V.Float:return e.kind==="number"?void 0:`value is not a number (${n.name}).`;default:return e.kind==="string"?void 0:`value is not a string-carried literal (${n.name}).`}}function br(n,e,o){if(o.kind!=="reference"||!o.ref)return`value is not a reference; sh:class requires an instance of ${e.name}.`;let t=p(e);if(n.reasoning)return n.reasoning.isInstanceOf(o.ref,e)?void 0:`value ${p(o.ref)} is not an instance of ${e.name}.`;let r=_(n.catalog,o.ref);return r instanceof S?Q(r).some(s=>p(s)===t||Z(n.catalog,s).some(i=>p(i)===t))?void 0:`value ${p(o.ref)} is not an instance of ${e.name}.`:`value ${p(o.ref)} does not resolve in this scope (sh:class ${e.name}).`}function Er(n,e,o,t,r){let a=new Set([...n.properties.map(i=>p(i.path)),...n.ignoredProperties.map(i=>p(i))]),s=new Set;for(let i of e.statement){let u=re(i);if(!u)continue;let d=p(u.subject);a.has(d)||s.has(d)||(s.add(d),r.push(we(n,o,t,Ce,`'${e.name}' carries undeclared property '${u.subject.name}' (closed shape).`,{resultPath:u.subject})))}for(let i of e.unresolvedPredicates)s.has(i.key)||(s.add(i.key),r.push(we(n,o,t,Ce,`'${e.name}' carries unresolvable property '${i.key}' (closed shape).`,{value:i.key})))}import*as Ne from"js-yaml";import{VersionOperator as qn}from"@kanonak-protocol/types/document/models/enums";var Pr="0.0.0",A=class{constructor(e,o=new L,t){this.repository=e;this.parser=o;this.objectParser=t??new O(this.parser)}repository;parser;objectParser;imports(){return new F}serializeValue(e,o){return Jn(e,o)}async buildContentAddressed(e){let o=e.book.toImports(),t=await this.hashBody(e.publisher,o,e.body),r=Oe(t),a={type:"EphemeralPackage",publisher:e.publisher,imports:o};e.contentHashProperty&&(a[e.contentHashProperty]=t),Object.assign(a,e.header??{}),a.imports=o;let s={[r]:a,...e.body},i=this.dump(s);return{yaml:i,byteCount:Yn(i),contentHash:t,packageName:r,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let o=e.book.toImports(),t={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:o},r;e.contentHashProperty&&(r=await this.hashBody(e.publisher,o,e.body),t[e.contentHashProperty]=r),Object.assign(t,e.header??{}),t.imports=o;let a={[e.name]:t,...e.body},s=this.dump(a),i={yaml:s,byteCount:Yn(s),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return r!==void 0&&(i.contentHash=r),i}dump(e){return Ne.dump(e,{lineWidth:-1})}async hashBody(e,o,t){let r={[Xn]:{type:"EphemeralPackage",publisher:e,imports:o},...t},a=this.parser.parse(Ne.dump(r,{lineWidth:-1})),s=a.metadata.namespace_?.toString(),u=(await this.objectParser.parseKanonaks(new J(a,this.repository))).filter(d=>d instanceof S&&d.namespace===s&&d.name!==Xn);for(let d of u)d.namespace="ephemeral";return Ee(u)}},Xn="__pkgbuilder_probe__";function Yn(n){return new TextEncoder().encode(n).length}function Oe(n){let e="sha256:",o=n.startsWith(e)?e.length:0;return`q-${n.slice(o,o+16)}`}var F=class{byKey=new Map;aliases=new Set;ensure(e,o,t,r,a=qn.Major){let s=`${e}/${o}@${t}`,i=this.byKey.get(s);if(i)return i.alias;let u=this.uniqueAlias(r);return this.byKey.set(s,{publisher:e,package_:o,version:t,alias:u,match:a}),u}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_,I(e.version),e.package_)}.${e.name}`}refLatest(e,o,t,r){return`${this.ensure(e,o,Pr,r??o,qn.Any)}.${t}`}toImports(){let e=new Map;for(let t of this.byKey.values()){let r=e.get(t.publisher)??[];r.push(t),e.set(t.publisher,r)}return[...e.keys()].sort().map(t=>({publisher:t,packages:e.get(t).sort((r,a)=>r.package_<a.package_?-1:1).map(r=>({package:r.package_,match:pe(r.match),version:r.version,alias:r.alias}))}))}uniqueAlias(e){let o=B(e)||"pkg",t=o,r=2;for(;this.aliases.has(t);)t=`${o}${r++}`;return this.aliases.add(t),t}};function Jn(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof k)return e.ref(n.subject);if(Array.isArray(n)){let o=n.map(t=>Jn(t,e)).filter(t=>t!==void 0);return o.length>0?o:void 0}if(n instanceof x)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(Rr(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function B(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Rr(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var xr="1.1.0";async function Zn(n){let e=new A(n.repository),o=e.imports(),t=o.ensure(Pe,Re,xr,"sh"),r=(i,u)=>i&&i.version&&typeof i.version.major=="number"?`${o.ensure(i.publisher,i.package_,I(i.version),i.package_)}.${i.name}`:u,a={},s=[];return n.result.results.forEach((i,u)=>{let d=`result-${u+1}`;s.push(d);let m={type:`${t}.ValidationResult`,[`${t}.focusNode`]:r(i.focusUri,i.focusNode),[`${t}.resultMessage`]:i.message,[`${t}.resultSeverity`]:`${t}.${i.severity}`,[`${t}.sourceConstraintComponent`]:`${t}.${i.constraintComponent.name}`};i.resultPath&&(m[`${t}.resultPath`]=r(i.resultPath,p(i.resultPath))),i.sourceShapeUri&&(m[`${t}.sourceShape`]=r(i.sourceShapeUri,i.sourceShape)),i.valueRef?m[`${t}.value`]=r(i.valueRef,p(i.valueRef)):i.value!==void 0&&(m[`${t}.value`]=i.value),a[d]=m}),a.report={type:`${t}.ValidationReport`,[`${t}.conforms`]:n.result.conforms,...s.length>0?{[`${t}.result`]:s}:{}},e.buildContentAddressed({publisher:n.publisher,book:o,body:a,...n.header!==void 0?{header:n.header}:{},contentHashProperty:"contentHash"})}import{VersionOperator as Hi}from"@kanonak-protocol/types/document/models/enums";var ae=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,o){return this.producers.find(t=>t.canProduce(e,o))}async produceCached(e,o,t,r){let a=`${o}/${t}@${I(r)}`,s=this.produced.get(a);if(s)return s;let{document:i}=await e.produce(o,t,r);return this.produced.set(a,i),i}async getHighestCompatibleVersionAsync(e,o){let t=this.producerFor(e,o.packageName);if(!t)return null;let r={operator:o.versionOperator,version:o.version},a=await t.resolveVersion(e,o.packageName,r);return a?this.produceCached(t,e,o.packageName,a):null}async getDocumentAsync(e){let o;try{o=he(e)}catch{return null}if(o.kind!=="package"||!o.version)return null;let t=this.producerFor(o.publisher,o.package_);return t?this.produceCached(t,o.publisher,o.package_,o.version):null}async getDocumentsByNamespaceAsync(e,o){return Array.from(this.produced.values()).filter(t=>{let r=t.metadata.namespace_;return r!=null&&r.publisher===e&&r.package_===o})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,o){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,o){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 Ae={async authorize(){return{allowed:!0}}},Le={async record(){}},G=class extends Error{constructor(o,t){let r=`${o.publisher}/${o.package_}${o.version?`@${o.version.major}.${o.version.minor}.${o.version.patch}`:""}`;super(`Not entitled to produce ${r}${t?`: ${t}`:""}`);this.address=o;this.reason=t;this.name="EntitlementDeniedError"}address;reason},ie=class{inner;ctx;policy;meter;constructor(e,o,t=Ae,r=Le){this.inner=e,this.ctx=o,this.policy=t,this.meter=r}canProduce(e,o){return this.inner.canProduce(e,o)}async resolveVersion(e,o,t){return await this.assertAllowed({publisher:e,package_:o,version:t.version}),this.inner.resolveVersion(e,o,t)}async produce(e,o,t){let r={publisher:e,package_:o,version:t};await this.assertAllowed(r);let a=await this.inner.produce(e,o,t);return await this.meter.record(this.ctx,r,a),a}async assertAllowed(e){let o=await this.policy.authorize(this.ctx,e);if(!o.allowed)throw new G(e,o.reason)}};var R="kanonak.org",v="view",Qn="core-kanonak",_r={publisher:R,package_:v,name:"rootView"},Cr={publisher:R,package_:v,name:"bind"},Ir={publisher:R,package_:v,name:"produces"},Kr={publisher:R,package_:v,name:"projections"},vr={publisher:R,package_:v,name:"where"},wr={publisher:R,package_:v,name:"value"},Nr={publisher:R,package_:v,name:"as"},se=class{constructor(e,o=new L){this.repository=e;this.parser=o;this.objectParser=new O(this.parser),this.builder=new A(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,o={}){let t=await this.objectParser.parseKanonaks(this.repository),r=this.resolveView(t,e),a=h(r,Cr);if(!a)throw new Error(`View ${r.namespace}/${r.name} declares no view.bind; cannot materialize.`);let s=h(r,Ir);if(!s)throw new Error(`View ${r.namespace}/${r.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 i=Or(r),u=et(t,R,Qn),d=et(t,R,v),m=this.builder.imports(),b=m.ensure(R,Qn,u,"ck"),E=m.ensure(R,v,d,"v"),l=m.ref(s),f=new ze(this.repository,this.parser,this.objectParser),y=new Ge(f,t),P=this.readProjections(t,r),j=Vr(r,vr),U=this.findInstances(t,a,await this.reason(o)),Ve={},tt=new Set;for(let W of U){if(!await this.passesWhere(y,t,j,W))continue;let ue={type:l};for(let Ue of P){let ot=await this.evaluateValue(y,t,Ue.value,W),He=this.builder.serializeValue(nt(ot),m);He!==void 0&&(ue[m.ref(Ue.as)]=He)}let je=g(W);je&&(ue[`${E}.derivedFrom`]=m.ref(je)),Ve[this.rowName(W,tt)]=ue}let ce={};o.resolvedAt&&(ce[`${b}.resolvedAt`]=o.resolvedAt),o.invocationId&&(ce[`${b}.id`]=o.invocationId);let M=await this.builder.buildContentAddressed({publisher:i,book:m,body:Ve,contentHashProperty:`${b}.contentHash`,header:ce});return{yaml:M.yaml,contentHash:M.contentHash,packageName:M.packageName,publisher:M.publisher,rowCount:M.resourceCount}}resolveView(e,o){let t=_(e,o);if(!t)throw new Error(`View ${o.publisher}/${o.package_}/${o.name} not found in the catalog.`);let r=h(t,_r);if(r){let a=_(e,r);if(!a)throw new Error(`ViewPackage ${o.name} names rootView ${r.name}, which is not in the catalog.`);return a}return t}readProjections(e,o){let t=[];for(let r of N(o,Kr)){let a=r instanceof x?r:r instanceof k?_(e,r.subject):void 0;if(!a)continue;let s=ge(a,wr),i=h(a,Nr);s&&i&&t.push({value:s,as:i})}return t}async reason(e){return new T({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,o,t){let r=Lr(e),a=[],s=new Set;for(let i of t.getInstancesOfClass(o)){if(s.has(i))continue;s.add(i);let u=r.get(i);u&&a.push(u)}return a.sort((i,u)=>{let d=$(g(i)),m=$(g(u));return d<m?-1:d>m?1:0}),a}async passesWhere(e,o,t,r){for(let a of t){let s=await this.evaluateValue(e,o,a,r);if(!jr(s))return!1}return!0}async evaluateValue(e,o,t,r){let a=We(t,"view-projection",{catalog:o,depth:0}),s=new Map([["input",r]]);return e.evaluate(a,s)}rowName(e,o){let t=B(e.name)||"row",r=t,a=2;for(;o.has(r);)r=`${t}-${a++}`;return o.add(r),r}};function nt(n){return be(n)?n.value:Array.isArray(n)?n.map(nt):n}function Or(n){let e=g(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function et(n,e,o){let t=Ar(n,e,o);if(!t)throw new Error(`Package ${e}/${o} is not in the catalog; it must be importable to materialize a view.`);return t}function Ar(n,e,o){let t;for(let r of n){if(!(r instanceof S))continue;let a=g(r);!a||a.publisher!==e||a.package_!==o||!a.version||(!t||z(a.version,t)>0)&&(t=a.version)}return t?I(t):void 0}function Lr(n){let e=new Map,o=new Map;for(let t of n){if(!(t instanceof S))continue;let r=g(t);if(!r||!r.version)continue;let a=$(r),s=o.get(a);(!s||z(r.version,s)>0)&&(o.set(a,r.version),e.set(a,t))}return e}function Vr(n,e){let o=ge(n,e);return o?[o]:N(n,e).filter(t=>t instanceof x)}function jr(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:be(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{vo as AmbiguousReferenceRule,fe as BooleanStatement,Xo as CANONICAL_FORM_VERSION,V as Carrier,Vo as ClassDefinitionRule,Po as ClassHierarchyCycleRule,ft as CompositeKanonakDocumentRepository,Jo as DEFAULT_CONSENT_BINDING_PARAM,Ot as DefinedKanonak,Wo as DiamondNameClashRule,Uo as DisplayLensScopeRule,mt as DocumentLocation,Xt as EdgeType,x as EmbeddedKanonak,So as EmbeddedKanonakTypeRule,ye as EmbeddedStatement,G as EntitlementDeniedError,ie as EntitlementProducer,dt as FileSystemKanonakDocumentRepository,no as GitIgnoreFilter,Yt as GraphBuilder,Ct as HttpKanonakDocumentRepository,Me as INTEGRITY_PREFIX,F as ImportBook,bo as ImportExistenceRule,le as InMemoryKanonakDocumentRepository,ht as KANONAK_USER_AGENT,Nt as Kanonak,oo as KanonakDocumentPositions,O as KanonakObjectParser,zo as KanonakObjectValidator,L as KanonakParser,At as KanonakUri,io as KanonakUriBuilder,so as KanonakUrlResolver,Tt as KanonakVocabulary,X as ListStatement,D as LiteralKanonak,It as LocalFirstRepository,Kt as LockAwareRepository,Mo as LookBandPathRule,$o as LookRenderer,Ho as LookSemanticSvgPathRule,jo as MarkdownLinkRule,ke as MarkdownStatement,Io as NamespaceImportCycleRule,fo as NamespacePrefixRule,qt as NodeType,me as NumberStatement,Zo as OAuthDiscovery,Qt as OWL_RL_CLASSIFICATION_RULES,No as ObjectPropertyValueValidationRule,po as OntologyValidationError,co as OntologyValidationResult,Go as OwlOneOfRule,A as PackageBuilder,go as PackageHeaderRule,ae as ProducerRepository,Oo as PropertyDomainRule,Ro as PropertyHierarchyCycleRule,Ao as PropertyKindRangeConsistencyRule,to as PropertyMetadata,wo as PropertyRangeReferenceRule,xo as PropertyRangeRequiredRule,ko as PropertyTypeSpecificityRule,Rt as PublisherConfigResolver,xt as PublisherIndex,Zt as RDFS_RULES,T as Reasoner,eo as ReasoningResult,k as ReferenceKanonak,q as ReferenceStatement,kt as RepositoryFactory,Lo as ReservedNameShadowRule,yo as ResourceNamingRule,jt as ResourceResolver,Ft as ResourceTypeClassifier,Vt as ScalarStatement,Bo as ShaclShapeRule,Lt as Statement,de as StringStatement,_o as SubClassOfReferenceRule,Co as SubPropertyOfReferenceRule,S as SubjectKanonak,ho as SubjectKanonakTypeRequiredRule,nr as TokenCredentialProvider,Jt as TripleStore,Fo as TxExpressionPathRule,Ut as TypeResolver,Ko as UnresolvedPredicateRule,Eo as UnresolvedReferenceRule,mo as ValidationCache,lo as ValidationContext,uo as ValidationSeverity,Hi as VersionOperator,se as ViewMaterializer,Ae as allowAllPolicy,bt as assertHttpsUrl,_t as assertPackageIdentity,wt as buildLocalFirstRepository,or as buildOntologyModel,Zn as buildReportPackageAsync,ee as buildShapesModel,qo as canonicalForm,Ee as canonicalHash,Se as carrierOf,vt as collectKanonakFiles,z as compareVersions,Ye as computeIntegrity,Te as computeIntegrityAsync,Oe as contentAddressedName,Q as contextTypesOf,er as createCredentialedFetch,it as createVersion,Wn as evaluateConformance,zt as extractMarkdownLinks,tr as findDerivation,Wt as findMalformedReferences,ao as findMarkdownLinkAt,ve as foldFlagsIntoPattern,Ht as formatKanonakAddress,I as formatVersion,yt as getGlobalCachePath,St as getKanonakUserAgent,ct as isCompatibleVersion,ut as isMajorCompatible,Et as kanonakFetch,qe as loadLockFile,oe as lowerConstraint,Mt as makeUriKey,Le as noopMeter,Yo as normalizeHost,Qo as parseAuthChallenge,he as parseKanonakAddress,De as parseLockFile,st as parseVersionString,ro as parseWithPositions,lt as pickHighestDocument,Bt as propertiesInScope,Do as resolveDisplayValue,Gt as resolvePropertyStep,B as sanitizeName,pt as satisfiesVersionOperator,Xe as saveLockFile,Ze as scopeFromCatalog,Qe as scopeFromDocumentAsync,Je as scopeFromRepositoryAsync,$e as serializeLockFile,Pt as setKanonakFetchRetries,gt as setKanonakUserAgent,g as subjectUri,Z as superClassChain,To as supportedBandKeys,Dt as tripleKey,$ as uriKey,$t as uriTriple,rt as versionOperatorFromChar,pe as versionOperatorToChar,at as versionsEqual};
|
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
|
|
2
2
|
import type { KanonakDocument, Import, DocumentReference } from '@kanonak-protocol/types/document/models/types';
|
|
3
3
|
import type { AuthenticatedFetchFn } from '../auth/index.js';
|
|
4
|
+
/**
|
|
5
|
+
* Whether the lock's pinned version satisfies an import's operator — a
|
|
6
|
+
* COMPATIBILITY ASSERTION, not a selector. The served lock pins one version per
|
|
7
|
+
* package; this only checks the pin is acceptable for the requested operator
|
|
8
|
+
* (off-latest selection is intentionally unsupported). `*` accepts anything;
|
|
9
|
+
* `=` requires equality; `^` requires the same major and pin ≥ requested; `~`
|
|
10
|
+
* requires the same major.minor and pin patch ≥ requested. A failure means the
|
|
11
|
+
* publisher has moved past what the import allows → resolve as "not found" (the
|
|
12
|
+
* caller can surface it; pin exact to hold an old line).
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* Read a package's source from the caller's cache by exact coordinate.
|
|
16
|
+
* `null`/`undefined` means "not cached"; any string — including an empty one —
|
|
17
|
+
* is a hit and is identity-checked. May be async.
|
|
18
|
+
*/
|
|
19
|
+
export type HttpCacheRead = (publisher: string, packageName: string, version: string) => string | null | undefined | Promise<string | null | undefined>;
|
|
20
|
+
/**
|
|
21
|
+
* Write-through after a network fetch. May be async; the repository awaits it
|
|
22
|
+
* before the resolution returns.
|
|
23
|
+
*/
|
|
24
|
+
export type HttpCacheWrite = (publisher: string, packageName: string, version: string, content: string) => void | Promise<void>;
|
|
4
25
|
export declare class HttpKanonakDocumentRepository implements IKanonakDocumentRepository {
|
|
5
26
|
private readonly parser;
|
|
6
27
|
private readonly publisherIndex;
|
|
@@ -9,9 +30,15 @@ export declare class HttpKanonakDocumentRepository implements IKanonakDocumentRe
|
|
|
9
30
|
private readonly fetchFn;
|
|
10
31
|
private readonly onFetch;
|
|
11
32
|
private readonly getFromCache;
|
|
33
|
+
/**
|
|
34
|
+
* `getFromCache` / `onFetch` form ONE seam, symmetric and optionally async:
|
|
35
|
+
* a consumer whose cache is a network KV returns promises, and the
|
|
36
|
+
* repository awaits them where they fire — a resolution does not return
|
|
37
|
+
* until its write-through has settled, and a read is never raced.
|
|
38
|
+
*/
|
|
12
39
|
constructor(options?: {
|
|
13
|
-
onFetch?:
|
|
14
|
-
getFromCache?:
|
|
40
|
+
onFetch?: HttpCacheWrite;
|
|
41
|
+
getFromCache?: HttpCacheRead;
|
|
15
42
|
fetchFn?: AuthenticatedFetchFn;
|
|
16
43
|
});
|
|
17
44
|
getHighestCompatibleVersionAsync(publisher: string, import_: Import): Promise<KanonakDocument | null>;
|
|
@@ -25,6 +52,18 @@ export declare class HttpKanonakDocumentRepository implements IKanonakDocumentRe
|
|
|
25
52
|
* guard plus the integrity-verified install that populated the cache.
|
|
26
53
|
*/
|
|
27
54
|
private fetchPinned;
|
|
55
|
+
/**
|
|
56
|
+
* A copy of `publisher/packageName@version` already in hand: the in-memory
|
|
57
|
+
* memo first, then the caller's cache. The ONE read path for both the
|
|
58
|
+
* served-lock and the exact-pin routes.
|
|
59
|
+
*
|
|
60
|
+
* A cache hit is never downgraded to a miss. Content that does not parse,
|
|
61
|
+
* or that parses but declares a different identity, THROWS — naming the
|
|
62
|
+
* coordinate — rather than falling through to a fetch that would hide a
|
|
63
|
+
* poisoned entry. An empty string is a hit, not an absence: only
|
|
64
|
+
* `null`/`undefined` mean "not cached".
|
|
65
|
+
*/
|
|
66
|
+
private fromMemoOrCache;
|
|
28
67
|
/**
|
|
29
68
|
* The not-in-lock fallback: a package the publisher's lock doesn't pin is a
|
|
30
69
|
* dynamic / producer origin (e.g. a snapshot feed). Fetch the package source
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as e,m as r,n}from"../chunk-
|
|
1
|
+
import{h as e,m as r,n}from"../chunk-P5VQEDBS.js";import"../chunk-SC5M74NM.js";import{a as o}from"../chunk-6VIUXP4N.js";import"../chunk-KOWDHKBN.js";import"../chunk-QILEJIFU.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
|
|
2
2
|
import { KanonakParser } from '../parsing/KanonakParser.js';
|
|
3
|
+
import { type HttpCacheRead, type HttpCacheWrite } from './HttpKanonakDocumentRepository.js';
|
|
3
4
|
/**
|
|
4
5
|
* Recursively collect every `.kan.yml` file under `dir`, skipping build/output
|
|
5
6
|
* and dependency directories. Pure filesystem walk — no YAML parsing.
|
|
@@ -7,8 +8,8 @@ import { KanonakParser } from '../parsing/KanonakParser.js';
|
|
|
7
8
|
export declare function collectKanonakFiles(dir: string, files?: string[]): string[];
|
|
8
9
|
/** Hook for persisting / reading HTTP-fetched documents (e.g. a disk cache). */
|
|
9
10
|
export interface HttpCacheHooks {
|
|
10
|
-
getFromCache
|
|
11
|
-
onFetch
|
|
11
|
+
getFromCache: HttpCacheRead;
|
|
12
|
+
onFetch: HttpCacheWrite;
|
|
12
13
|
}
|
|
13
14
|
/**
|
|
14
15
|
* Build the canonical three-tier resolution repository, workspace-first:
|
|
@@ -2,7 +2,7 @@ export { InMemoryKanonakDocumentRepository } from './InMemoryKanonakDocumentRepo
|
|
|
2
2
|
export { FileSystemKanonakDocumentRepository } from './FileSystemKanonakDocumentRepository.js';
|
|
3
3
|
export { CompositeKanonakDocumentRepository, DocumentLocation } from './CompositeKanonakDocumentRepository.js';
|
|
4
4
|
export { RepositoryFactory } from './RepositoryFactory.js';
|
|
5
|
-
export { HttpKanonakDocumentRepository } from './HttpKanonakDocumentRepository.js';
|
|
5
|
+
export { HttpKanonakDocumentRepository, type HttpCacheRead, type HttpCacheWrite } from './HttpKanonakDocumentRepository.js';
|
|
6
6
|
export { LocalFirstRepository } from './LocalFirstRepository.js';
|
|
7
7
|
export { LockAwareRepository } from './LockAwareRepository.js';
|
|
8
8
|
export { buildLocalFirstRepository, collectKanonakFiles, type HttpCacheHooks, } from './buildLocalFirstRepository.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m,i as n}from"../chunk-
|
|
1
|
+
import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m,i as n}from"../chunk-JFBPQN6T.js";import{g,h,m as i,n as j}from"../chunk-P5VQEDBS.js";import"../chunk-SC5M74NM.js";import{a}from"../chunk-6VIUXP4N.js";import"../chunk-KOWDHKBN.js";import"../chunk-QILEJIFU.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,l as LockAwareRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,n as buildLocalFirstRepository,m as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
|
package/dist/server/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{c as Pe}from"../chunk-DUM5Q4MH.js";import{a as be,d as X,f as Se,h as ee}from"../chunk-WKLSD5DQ.js";import{e as ve,g as $e,m as U,n as Z}from"../chunk-M7OWTFTC.js";import"../chunk-PEB52US5.js";import"../chunk-SC5M74NM.js";import{a as H,b as G}from"../chunk-BRCVOR7A.js";import{j as oe}from"../chunk-AND44TIS.js";import{a as ye}from"../chunk-6VIUXP4N.js";import{m as te}from"../chunk-YU2VGLOT.js";import{a as O}from"../chunk-KOWDHKBN.js";import{a as xe}from"../chunk-PEJALHXK.js";import{c as Re}from"../chunk-O6YV2SDB.js";import{c as we,s as re}from"../chunk-H6UAD2LP.js";import"../chunk-FUUTGGJS.js";import{c as V,e as K,f as W,g as ke}from"../chunk-QILEJIFU.js";import{readFileSync as de,writeFileSync as Ce,mkdirSync as Fe}from"fs";import{join as se}from"path";import Me from"js-yaml";var _e=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function q(t){return _e}function N(t){return`${t.publisher}/${t.package_}`}function z(t,e=[]){let c={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},r=[];for(let o of t)if(o.origin==="missing"){let s=N(o),m=c[s]??"whatever this package contributes to rendering is lost";r.push(`Render-stack package ${s} is MISSING (${o.reason??"unknown reason"}) \u2014 ${m}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${o.publisher}.`)}else o.resolvedButNotInCatalog&&r.push(`Render-stack package ${N(o)} resolved (${o.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let o of e)r.push(`Import edge ${o.fromNamespace} \u2192 ${o.publisher}/${o.packageName} ${o.constraint} did NOT resolve (${o.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${o.fromNamespace} authors against ${o.publisher}/${o.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${o.constraint}-compatible version of ${o.publisher}/${o.packageName} to the workspace or cache (kanonak install ${o.publisher}/${o.packageName}), or bump the import in ${o.fromNamespace}.`);return r}function ne(t){let{publisher:e,availablePublishers:c,catalog:r,lookRenderer:o,localNamespaces:s,rawByNsKey:m,renderStack:d,producers:f,lockSource:l,configSource:h}=t,a=new Map,g=new Map,S=new Map,v=new Set;for(let $ of r){if(!($ instanceof we))continue;let w=$.namespace||"";if(!s.has(w))continue;a.set(`${w}/${$.name}`,$);let P=w.split("/")[1]??"",[_,M]=P.split("@");if(!_||!M)continue;let D=ke(M);D&&(v.has(P)||(v.add(P),g.has(_)||g.set(_,[]),g.get(_).push({verStr:M,version:D})),$.name===_&&S.set(P,$))}for(let $ of g.values())$.sort((w,P)=>V(P.version,w.version));return{publisher:e,availablePublishers:c,catalog:r,lookRenderer:o,localNamespaces:s,rawByNsKey:m,bySubject:a,pkgVersions:g,pkgSelfByVer:S,renderStack:d,...f?{producers:f}:{},...l?{lockSource:l}:{},...h?{configSource:h}:{}}}async function pe(t,e={}){let c=new O,r=new ye(c),o=[],s=[];for(let i of ee(t)){let u;try{u=de(i,"utf-8")}catch{continue}let n;try{n=c.parse(u).metadata?.namespace_}catch{continue}if(!n?.version)continue;let p=n.version;s.push({publisher:n.publisher,package_:n.package_,verStr:K(p),version:p,source:u})}s.sort((i,u)=>V(u.version,i.version));for(let i of s)await r.saveDocumentAsync(c.parse(i.source),`${i.publisher}/${i.package_}@${i.verStr}`),o.push({publisher:i.publisher,package_:i.package_,verStr:i.verStr,source:i.source});let m=[...new Set(o.map(i=>i.publisher))].sort(),d=e.publisher;if(d){if(!m.includes(d))throw new Error(`Publisher "${d}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)d=m[0];else throw m.length===0?new Error(`No Kanonak packages found under ${t}`):new Error(`Workspace has multiple publishers (${m.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,l=new Map;for(let i of o)i.publisher===d&&(f.add(`${i.publisher}/${i.package_}@${i.verStr}`),l.set(`${i.package_}@${i.verStr}`,i.source));let h=X(),a=new be(h,!0,c),g={};e.httpCache&&(g.getFromCache=e.httpCache.getFromCache,g.onFetch=e.httpCache.onFetch),e.fetchFn&&(g.fetchFn=e.fetchFn);let S=e.repository??new Se(r,a,new Z(g)),v=e.log??(()=>{}),$=q(void 0),w=[],P=i=>i.map(u=>u.metadata.namespace_?.version).filter(u=>u!==void 0).sort((u,n)=>V(n,u)).map(K);if(!e.repository){v(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${h}`);let i=e.fetchFn?new U({fetchFn:e.fetchFn}):new U;for(let u of $){let n=N(u),p=await r.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(p.length>0){let y=P(p);w.push({...u,origin:"workspace",versions:y}),v(`[render-stack] ${n} \u2014 workspace (${y.join(", ")})`);continue}let k=await a.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(k.length>0){let y=P(k);w.push({...u,origin:"cache",versions:y}),v(`[render-stack] ${n} \u2014 cache (${y.join(", ")})`);continue}try{let b=(await i.getLock(u.publisher))?.packages[`${u.publisher}/${u.package_}`];if(!b){let j=`publisher ${u.publisher} reachable but its lock does not pin ${u.package_}`;w.push({...u,origin:"missing",reason:j}),v(`[render-stack] ${n} \u2014 MISSING: ${j}`);continue}let C=b.version,T=b.resolved,Q=await(e.fetchFn?e.fetchFn(T,u.publisher):ve(T));if(!Q.ok){let j=`fetch ${T} failed: HTTP ${Q.status} ${Q.statusText}`;w.push({...u,origin:"missing",reason:j}),v(`[render-stack] ${n} \u2014 MISSING: ${j}`);continue}let fe=await Q.text();await r.saveDocumentAsync(c.parse(fe),`${u.publisher}/${u.package_}@${C}`);try{let j=se(h,u.publisher);Fe(j,{recursive:!0}),Ce(se(j,`${u.package_}@${C}.kan.yml`),fe,"utf-8"),w.push({...u,origin:"fetched",versions:[C]}),v(`[render-stack] ${n}@${C} \u2014 fetched from ${T}, installed to cache`)}catch(j){w.push({...u,origin:"fetched",versions:[C]}),v(`[render-stack] ${n}@${C} \u2014 fetched from ${T}, but cache ${h} is NOT WRITABLE (${j.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(y){let b=`fetch failed: ${y.message}`;w.push({...u,origin:"missing",reason:b}),v(`[render-stack] ${n} \u2014 MISSING: ${b}`)}}}let _=(await r.getAllDocumentsAsync()).filter(i=>i.metadata.namespace_?.publisher===d);for(let i of $)_.push(...await S.getDocumentsByNamespaceAsync(i.publisher,i.package_));let M=[],D=await H(_,S,{onUnresolvedEdge:i=>M.push(i)}),A=S;if(!e.repository){for(let i of $)D.add(N(i));A=new G(S,D)}let B=await new te(c).parseKanonaks(A),ce=new oe(B),le=(i,u)=>re(B,{publisher:i,package_:u,name:u}).length>0,I;if(e.repository){I=[];for(let i of $){let u=await S.getDocumentsByNamespaceAsync(i.publisher,i.package_);I.push(u.length>0?{...i,origin:"repository",versions:P(u)}:{...i,origin:"missing",reason:"not present in the caller-supplied repository"})}}else I=w.map(i=>i.origin==="missing"||le(i.publisher,i.package_)?i:{...i,resolvedButNotInCatalog:!0});let Y=z(I,M);for(let i of Y)v(`[render-stack] WARNING: ${i}`);let J={contractSource:"universal-default",cachePath:h,packages:I,warnings:Y},E;try{E=de(se(t,"kanonak.lock"),"utf-8")}catch{E=De(d,o,c)}let L;try{L=de(se(t,".well-known","kanonak.json"),"utf-8")}catch{L=void 0}return ne({publisher:d,availablePublishers:m,catalog:B,lookRenderer:ce,localNamespaces:f,rawByNsKey:l,renderStack:J,...E?{lockSource:E}:{},...L?{configSource:L}:{}})}function De(t,e,c){let r=new Map;for(let s of e)s.publisher===t&&(r.has(s.package_)||r.set(s.package_,{verStr:s.verStr,source:s.source}));if(r.size===0)return;let o={};for(let s of[...r.keys()].sort()){let{verStr:m,source:d}=r.get(s),f={},l;try{l=c.parse(d).metadata?.imports}catch{l=void 0}for(let a of l?.[t]??[]){let g=r.get(a.packageName);g&&(f[`${t}/${a.packageName}`]=g.verStr)}let h={};for(let a of Object.keys(f).sort())h[a]=f[a];o[`${t}/${s}`]={version:m,resolved:`https://${t}/${s}/${m}.kan.yml`,integrity:Pe(d),dependencies:h}}return Me.dump({version:"1",lastUpdated:"",packages:o},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as Ke,readFileSync as Ee,writeFileSync as Ve,mkdirSync as Ae}from"fs";import{join as je}from"path";async function ue(t,e={}){let c=new O,r=Re(t),o=r.kind==="resource"?r.uri.publisher:r.publisher,s=e.log??(()=>{}),m=e.cacheRoot??X(),d=(n,p,k)=>je(m,n,`${p}@${k}.kan.yml`),f=new Set,l=new Set,h=new Map,a=new Z({getFromCache:(n,p,k)=>{let y=d(n,p,k),b=Ke(y)?Ee(y,"utf-8"):null;return b!==null&&f.add(`${n}/${p}`),b},onFetch:(n,p,k,y)=>{l.add(`${n}/${p}`);try{let b=je(m,n);Ae(b,{recursive:!0}),Ve(d(n,p,k),y,"utf-8")}catch(b){h.set(`${n}/${p}`,b.message),s(`[render] fetched ${n}/${p}@${k} but cache ${m} is NOT WRITABLE (${b.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),g=new U(e.fetchFn?{fetchFn:e.fetchFn}:void 0),S;if(r.kind==="resource"){let n=r.uri.version;S=[n?{package_:r.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let n=r.version;S=[n?{package_:r.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:r.package_}]}else S=((await g.getConfig(o)).featured_packages??[]).map(p=>({package_:p}));let v=async(n,p,k)=>{try{let y=k?c.buildImport(p,"=",k,n):c.buildImport(p,"*","0.0.0",n),b=await a.getHighestCompatibleVersionAsync(n,y);return b?{doc:b}:{doc:null,error:`${n} did not resolve ${p}${k?`@${k}`:""} (not in its index, or unreachable)`}}catch(y){return{doc:null,error:y.message}}},$=[],w=[];for(let n of S){let{doc:p,error:k}=await v(o,n.package_,n.version);p?$.push(p):k&&w.push(k)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${o}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let P=q(),_="universal-default",M=n=>n.map(p=>p.metadata.namespace_?.version).filter(p=>p!==void 0).sort((p,k)=>V(k,p)).map(K);s(`[render-stack] resolving ${P.length} ambient look-stack package(s) (contract: ${_}); cache: ${m}`);let D=[],A=[];for(let n of P){let p=N(n),{doc:k,error:y}=await v(n.publisher,n.package_,void 0);if(k){D.push(k);let b=M([k]),C=l.has(p)?"fetched":f.has(p)?"cache":"fetched";A.push({...n,origin:C,versions:b}),s(`[render-stack] ${p} \u2014 ${C} (${b.join(", ")})`+(h.has(p)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...n,origin:"missing",reason:y??"unresolved"}),s(`[render-stack] ${p} \u2014 MISSING: ${y??"unresolved"}`)}let B=[],ce=await H([...$,...D],a,{onUnresolvedEdge:n=>B.push(n)}),le=new G(a,ce),I=await new te(c).parseKanonaks(le),Y=new oe(I),J=A.map(n=>n.origin==="missing"||re(I,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),E=z(J,B);for(let n of E)s(`[render-stack] WARNING: ${n}`);let L={contractSource:_,cachePath:m,packages:J,warnings:E},i=new Set,u=new Map;for(let n of await a.getAllDocumentsAsync()){let p=n.metadata.namespace_;if(!p?.version||p.publisher!==o)continue;let k=K(p.version),y=`${p.publisher}/${p.package_}@${k}`;i.add(y);let b=await a.getDocumentContentAsync(y);b!==null&&u.set(`${p.package_}@${k}`,b)}return ne({publisher:o,availablePublishers:[o],catalog:I,lookRenderer:Y,localNamespaces:i,rawByNsKey:u,renderStack:L})}import{VersionOperator as ie}from"@kanonak-protocol/types/document/models/enums";function ae(t){let{lookRenderer:e,publisher:c,renderStack:r,catalog:o}=t,s=e.explainStylesheet(e.publisherSubject(c)),m=[...s.tokens.entries()].map(([a,g])=>({name:a,value:g.value,source:`${g.sourceNamespace}/${g.sourceName}`,level:g.level})),d=s.baseStylesheet,f={present:d.css!==void 0,...d.sourceNamespace!==void 0?{source:d.sourceNamespace}:{},...d.scope!==void 0?{scope:d.scope}:{},...d.css!==void 0?{bytes:d.css.length}:{},...d.problem!==void 0?{problem:d.problem}:{},candidates:d.candidates},l=new Map;for(let a of o){let g=a.namespace;g&&l.set(g,(l.get(g)??0)+1)}let h=[...l.entries()].map(([a,g])=>({namespace:a,resources:g})).sort((a,g)=>a.namespace.localeCompare(g.namespace));return{publisher:c,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(a=>({package_:N(a),origin:a.origin,...a.versions!==void 0?{versions:a.versions}:{},...a.reason!==void 0?{reason:a.reason}:{},...a.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:a.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:f,...s.look?{look:{sourceClass:`${s.look.sourceClass.publisher}/${s.look.sourceClass.package_}/${s.look.sourceClass.name}`}}:{}},catalog:h,warnings:[...r.warnings,...s.warnings.filter(a=>!r.warnings.includes(a))]}}function Be(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ge(t){let e=Be,c=t.warnings.length===0,r=t.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':t.warnings.map(l=>`<div class="warn">\u26A0 ${e(l)}</div>`).join(`
|
|
2
|
-
`),o
|
|
3
|
-
`),s=
|
|
4
|
-
`),f=
|
|
1
|
+
import{c as Pe}from"../chunk-D66LUZDB.js";import{a as be,d as X,f as Se,h as ee}from"../chunk-JFBPQN6T.js";import{e as ve,g as $e,m as U,n as Z}from"../chunk-P5VQEDBS.js";import"../chunk-PEB52US5.js";import"../chunk-SC5M74NM.js";import{a as H,b as G}from"../chunk-BRCVOR7A.js";import{j as te}from"../chunk-AND44TIS.js";import{a as ye}from"../chunk-6VIUXP4N.js";import{m as oe}from"../chunk-YU2VGLOT.js";import{a as O}from"../chunk-KOWDHKBN.js";import{a as xe}from"../chunk-PEJALHXK.js";import{c as Re}from"../chunk-O6YV2SDB.js";import{c as we,s as re}from"../chunk-H6UAD2LP.js";import"../chunk-FUUTGGJS.js";import{c as V,e as K,f as W,g as ke}from"../chunk-QILEJIFU.js";import{readFileSync as de,writeFileSync as Ce,mkdirSync as Me}from"fs";import{join as se}from"path";import Fe from"js-yaml";var _e=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function q(o){return _e}function N(o){return`${o.publisher}/${o.package_}`}function z(o,e=[]){let c={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},r=[];for(let t of o)if(t.origin==="missing"){let s=N(t),m=c[s]??"whatever this package contributes to rendering is lost";r.push(`Render-stack package ${s} is MISSING (${t.reason??"unknown reason"}) \u2014 ${m}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${t.publisher}.`)}else t.resolvedButNotInCatalog&&r.push(`Render-stack package ${N(t)} resolved (${t.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let t of e)r.push(`Import edge ${t.fromNamespace} \u2192 ${t.publisher}/${t.packageName} ${t.constraint} did NOT resolve (${t.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${t.fromNamespace} authors against ${t.publisher}/${t.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${t.constraint}-compatible version of ${t.publisher}/${t.packageName} to the workspace or cache (kanonak install ${t.publisher}/${t.packageName}), or bump the import in ${t.fromNamespace}.`);return r}function ne(o){let{publisher:e,availablePublishers:c,catalog:r,lookRenderer:t,localNamespaces:s,rawByNsKey:m,renderStack:d,producers:f,lockSource:l,configSource:h}=o,a=new Map,g=new Map,S=new Map,v=new Set;for(let $ of r){if(!($ instanceof we))continue;let w=$.namespace||"";if(!s.has(w))continue;a.set(`${w}/${$.name}`,$);let P=w.split("/")[1]??"",[_,F]=P.split("@");if(!_||!F)continue;let D=ke(F);D&&(v.has(P)||(v.add(P),g.has(_)||g.set(_,[]),g.get(_).push({verStr:F,version:D})),$.name===_&&S.set(P,$))}for(let $ of g.values())$.sort((w,P)=>V(P.version,w.version));return{publisher:e,availablePublishers:c,catalog:r,lookRenderer:t,localNamespaces:s,rawByNsKey:m,bySubject:a,pkgVersions:g,pkgSelfByVer:S,renderStack:d,...f?{producers:f}:{},...l?{lockSource:l}:{},...h?{configSource:h}:{}}}async function pe(o,e={}){let c=new O,r=new ye(c),t=[],s=[];for(let i of ee(o)){let u;try{u=de(i,"utf-8")}catch{continue}let n;try{n=c.parse(u).metadata?.namespace_}catch{continue}if(!n?.version)continue;let p=n.version;s.push({publisher:n.publisher,package_:n.package_,verStr:K(p),version:p,source:u})}s.sort((i,u)=>V(u.version,i.version));for(let i of s)await r.saveDocumentAsync(c.parse(i.source),`${i.publisher}/${i.package_}@${i.verStr}`),t.push({publisher:i.publisher,package_:i.package_,verStr:i.verStr,source:i.source});let m=[...new Set(t.map(i=>i.publisher))].sort(),d=e.publisher;if(d){if(!m.includes(d))throw new Error(`Publisher "${d}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)d=m[0];else throw m.length===0?new Error(`No Kanonak packages found under ${o}`):new Error(`Workspace has multiple publishers (${m.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,l=new Map;for(let i of t)i.publisher===d&&(f.add(`${i.publisher}/${i.package_}@${i.verStr}`),l.set(`${i.package_}@${i.verStr}`,i.source));let h=X(),a=new be(h,!0,c),g={};e.httpCache&&(g.getFromCache=e.httpCache.getFromCache,g.onFetch=e.httpCache.onFetch),e.fetchFn&&(g.fetchFn=e.fetchFn);let S=e.repository??new Se(r,a,new Z(g)),v=e.log??(()=>{}),$=q(void 0),w=[],P=i=>i.map(u=>u.metadata.namespace_?.version).filter(u=>u!==void 0).sort((u,n)=>V(n,u)).map(K);if(!e.repository){v(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${h}`);let i=e.fetchFn?new U({fetchFn:e.fetchFn}):new U;for(let u of $){let n=N(u),p=await r.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(p.length>0){let y=P(p);w.push({...u,origin:"workspace",versions:y}),v(`[render-stack] ${n} \u2014 workspace (${y.join(", ")})`);continue}let k=await a.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(k.length>0){let y=P(k);w.push({...u,origin:"cache",versions:y}),v(`[render-stack] ${n} \u2014 cache (${y.join(", ")})`);continue}try{let b=(await i.getLock(u.publisher))?.packages[`${u.publisher}/${u.package_}`];if(!b){let j=`publisher ${u.publisher} reachable but its lock does not pin ${u.package_}`;w.push({...u,origin:"missing",reason:j}),v(`[render-stack] ${n} \u2014 MISSING: ${j}`);continue}let C=b.version,T=b.resolved,Q=await(e.fetchFn?e.fetchFn(T,u.publisher):ve(T));if(!Q.ok){let j=`fetch ${T} failed: HTTP ${Q.status} ${Q.statusText}`;w.push({...u,origin:"missing",reason:j}),v(`[render-stack] ${n} \u2014 MISSING: ${j}`);continue}let fe=await Q.text();await r.saveDocumentAsync(c.parse(fe),`${u.publisher}/${u.package_}@${C}`);try{let j=se(h,u.publisher);Me(j,{recursive:!0}),Ce(se(j,`${u.package_}@${C}.kan.yml`),fe,"utf-8"),w.push({...u,origin:"fetched",versions:[C]}),v(`[render-stack] ${n}@${C} \u2014 fetched from ${T}, installed to cache`)}catch(j){w.push({...u,origin:"fetched",versions:[C]}),v(`[render-stack] ${n}@${C} \u2014 fetched from ${T}, but cache ${h} is NOT WRITABLE (${j.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(y){let b=`fetch failed: ${y.message}`;w.push({...u,origin:"missing",reason:b}),v(`[render-stack] ${n} \u2014 MISSING: ${b}`)}}}let _=(await r.getAllDocumentsAsync()).filter(i=>i.metadata.namespace_?.publisher===d);for(let i of $)_.push(...await S.getDocumentsByNamespaceAsync(i.publisher,i.package_));let F=[],D=await H(_,S,{onUnresolvedEdge:i=>F.push(i)}),A=S;if(!e.repository){for(let i of $)D.add(N(i));A=new G(S,D)}let B=await new oe(c).parseKanonaks(A),ce=new te(B),le=(i,u)=>re(B,{publisher:i,package_:u,name:u}).length>0,I;if(e.repository){I=[];for(let i of $){let u=await S.getDocumentsByNamespaceAsync(i.publisher,i.package_);I.push(u.length>0?{...i,origin:"repository",versions:P(u)}:{...i,origin:"missing",reason:"not present in the caller-supplied repository"})}}else I=w.map(i=>i.origin==="missing"||le(i.publisher,i.package_)?i:{...i,resolvedButNotInCatalog:!0});let Y=z(I,F);for(let i of Y)v(`[render-stack] WARNING: ${i}`);let J={contractSource:"universal-default",cachePath:h,packages:I,warnings:Y},E;try{E=de(se(o,"kanonak.lock"),"utf-8")}catch{E=De(d,t,c)}let L;try{L=de(se(o,".well-known","kanonak.json"),"utf-8")}catch{L=void 0}return ne({publisher:d,availablePublishers:m,catalog:B,lookRenderer:ce,localNamespaces:f,rawByNsKey:l,renderStack:J,...E?{lockSource:E}:{},...L?{configSource:L}:{}})}function De(o,e,c){let r=new Map;for(let s of e)s.publisher===o&&(r.has(s.package_)||r.set(s.package_,{verStr:s.verStr,source:s.source}));if(r.size===0)return;let t={};for(let s of[...r.keys()].sort()){let{verStr:m,source:d}=r.get(s),f={},l;try{l=c.parse(d).metadata?.imports}catch{l=void 0}for(let a of l?.[o]??[]){let g=r.get(a.packageName);g&&(f[`${o}/${a.packageName}`]=g.verStr)}let h={};for(let a of Object.keys(f).sort())h[a]=f[a];t[`${o}/${s}`]={version:m,resolved:`https://${o}/${s}/${m}.kan.yml`,integrity:Pe(d),dependencies:h}}return Fe.dump({version:"1",lastUpdated:"",packages:t},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as Ke,readFileSync as Ee,writeFileSync as Ve,mkdirSync as Ae}from"fs";import{join as je}from"path";async function ue(o,e={}){let c=new O,r=Re(o),t=r.kind==="resource"?r.uri.publisher:r.publisher,s=e.log??(()=>{}),m=e.cacheRoot??X(),d=(n,p,k)=>je(m,n,`${p}@${k}.kan.yml`),f=new Set,l=new Set,h=new Map,a=new Z({getFromCache:(n,p,k)=>{let y=d(n,p,k),b=Ke(y)?Ee(y,"utf-8"):null;return b!==null&&f.add(`${n}/${p}`),b},onFetch:(n,p,k,y)=>{l.add(`${n}/${p}`);try{let b=je(m,n);Ae(b,{recursive:!0}),Ve(d(n,p,k),y,"utf-8")}catch(b){h.set(`${n}/${p}`,b.message),s(`[render] fetched ${n}/${p}@${k} but cache ${m} is NOT WRITABLE (${b.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),g=new U(e.fetchFn?{fetchFn:e.fetchFn}:void 0),S;if(r.kind==="resource"){let n=r.uri.version;S=[n?{package_:r.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let n=r.version;S=[n?{package_:r.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:r.package_}]}else S=((await g.getConfig(t)).featured_packages??[]).map(p=>({package_:p}));let v=async(n,p,k)=>{try{let y=k?c.buildImport(p,"=",k,n):c.buildImport(p,"*","0.0.0",n),b=await a.getHighestCompatibleVersionAsync(n,y);return b?{doc:b}:{doc:null,error:`${n} did not resolve ${p}${k?`@${k}`:""} (not in its index, or unreachable)`}}catch(y){return{doc:null,error:y.message}}},$=[],w=[];for(let n of S){let{doc:p,error:k}=await v(t,n.package_,n.version);p?$.push(p):k&&w.push(k)}if($.length===0)throw new Error(`Could not fetch any package for address "${o}" from publisher "${t}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let P=q(),_="universal-default",F=n=>n.map(p=>p.metadata.namespace_?.version).filter(p=>p!==void 0).sort((p,k)=>V(k,p)).map(K);s(`[render-stack] resolving ${P.length} ambient look-stack package(s) (contract: ${_}); cache: ${m}`);let D=[],A=[];for(let n of P){let p=N(n),{doc:k,error:y}=await v(n.publisher,n.package_,void 0);if(k){D.push(k);let b=F([k]),C=l.has(p)?"fetched":f.has(p)?"cache":"fetched";A.push({...n,origin:C,versions:b}),s(`[render-stack] ${p} \u2014 ${C} (${b.join(", ")})`+(h.has(p)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...n,origin:"missing",reason:y??"unresolved"}),s(`[render-stack] ${p} \u2014 MISSING: ${y??"unresolved"}`)}let B=[],ce=await H([...$,...D],a,{onUnresolvedEdge:n=>B.push(n)}),le=new G(a,ce),I=await new oe(c).parseKanonaks(le),Y=new te(I),J=A.map(n=>n.origin==="missing"||re(I,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),E=z(J,B);for(let n of E)s(`[render-stack] WARNING: ${n}`);let L={contractSource:_,cachePath:m,packages:J,warnings:E},i=new Set,u=new Map;for(let n of await a.getAllDocumentsAsync()){let p=n.metadata.namespace_;if(!p?.version||p.publisher!==t)continue;let k=K(p.version),y=`${p.publisher}/${p.package_}@${k}`;i.add(y);let b=await a.getDocumentContentAsync(y);b!==null&&u.set(`${p.package_}@${k}`,b)}return ne({publisher:t,availablePublishers:[t],catalog:I,lookRenderer:Y,localNamespaces:i,rawByNsKey:u,renderStack:L})}import{VersionOperator as ie}from"@kanonak-protocol/types/document/models/enums";function ae(o){let{lookRenderer:e,publisher:c,renderStack:r,catalog:t}=o,s=e.explainStylesheet(e.publisherSubject(c)),m=[...s.tokens.entries()].map(([a,g])=>({name:a,value:g.value,source:`${g.sourceNamespace}/${g.sourceName}`,level:g.level})),d=s.baseStylesheet,f={present:d.css!==void 0,...d.sourceNamespace!==void 0?{source:d.sourceNamespace}:{},...d.scope!==void 0?{scope:d.scope}:{},...d.css!==void 0?{bytes:d.css.length}:{},...d.problem!==void 0?{problem:d.problem}:{},candidates:d.candidates},l=new Map;for(let a of t){let g=a.namespace;g&&l.set(g,(l.get(g)??0)+1)}let h=[...l.entries()].map(([a,g])=>({namespace:a,resources:g})).sort((a,g)=>a.namespace.localeCompare(g.namespace));return{publisher:c,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(a=>({package_:N(a),origin:a.origin,...a.versions!==void 0?{versions:a.versions}:{},...a.reason!==void 0?{reason:a.reason}:{},...a.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:a.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:f,...s.look?{look:{sourceClass:`${s.look.sourceClass.publisher}/${s.look.sourceClass.package_}/${s.look.sourceClass.name}`}}:{}},catalog:h,warnings:[...r.warnings,...s.warnings.filter(a=>!r.warnings.includes(a))]}}function Be(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ge(o){let e=Be,c=o.warnings.length===0,r=o.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':o.warnings.map(l=>`<div class="warn">\u26A0 ${e(l)}</div>`).join(`
|
|
2
|
+
`),t=o.renderStack.packages.map(l=>{let h=l.origin!=="missing"&&!l.resolvedButNotInCatalog,a=l.origin==="missing"?'<span class="bad">MISSING</span>':l.resolvedButNotInCatalog?`<span class="bad">${e(l.origin)} (not in catalog)</span>`:`<span class="good">${e(l.origin)}</span>`,g=l.reason?e(l.reason):e((l.versions??[]).join(", "));return`<tr class="${h?"":"row-bad"}"><td><code>${e(l.package_)}</code></td><td>${a}</td><td>${g}</td></tr>`}).join(`
|
|
3
|
+
`),s=o.stylesheet.baseStylesheet,m=s.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(s.source??"")}</code> (${s.bytes} bytes, ${e(s.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${s.problem?` \u2014 ${e(s.problem)}`:""}${s.candidates.length>0?`<br>candidates considered: ${s.candidates.map(l=>`<code>${e(l)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,d=o.stylesheet.tokens.map(l=>`<tr><td><code>--kan-${e(l.name)}</code></td><td><code>${e(l.value)}</code></td><td><code>${e(l.source)}</code></td><td>${e(l.level)}</td></tr>`).join(`
|
|
4
|
+
`),f=o.catalog.map(l=>`<tr><td><code>${e(l.namespace)}</code></td><td>${l.resources}</td></tr>`).join(`
|
|
5
5
|
`);return`<!doctype html>
|
|
6
6
|
<html lang="en">
|
|
7
7
|
<head>
|
|
8
8
|
<meta charset="utf-8">
|
|
9
9
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
10
|
-
<title>Render diagnostics \u2014 ${e(
|
|
10
|
+
<title>Render diagnostics \u2014 ${e(o.publisher)}</title>
|
|
11
11
|
<style>
|
|
12
12
|
body { font-family: system-ui, sans-serif; max-width: 64rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; color: #1a1a1a; background: #fff; }
|
|
13
13
|
h1 { font-size: 1.5rem; } h2 { font-size: 1.15rem; margin-top: 2rem; border-bottom: 1px solid #ddd; padding-bottom: .25rem; }
|
|
@@ -25,8 +25,8 @@ import{c as Pe}from"../chunk-DUM5Q4MH.js";import{a as be,d as X,f as Se,h as ee}
|
|
|
25
25
|
</style>
|
|
26
26
|
</head>
|
|
27
27
|
<body>
|
|
28
|
-
<h1>Render diagnostics \u2014 ${e(
|
|
29
|
-
<p class="status-banner">${c?"\u2713 Healthy":`\u2717 ${
|
|
28
|
+
<h1>Render diagnostics \u2014 ${e(o.publisher)}</h1>
|
|
29
|
+
<p class="status-banner">${c?"\u2713 Healthy":`\u2717 ${o.warnings.length} problem(s) found`}</p>
|
|
30
30
|
<p class="meta">Machine-readable version: <a href="/.well-known/kanonak-render.json"><code>/.well-known/kanonak-render.json</code></a></p>
|
|
31
31
|
|
|
32
32
|
<h2>Problems</h2>
|
|
@@ -34,10 +34,10 @@ ${r}
|
|
|
34
34
|
|
|
35
35
|
<h2>Ambient render stack</h2>
|
|
36
36
|
<p class="meta">The look stack is discovered, not imported \u2014 these packages must be resolvable for any publisher's pages to render styled.
|
|
37
|
-
Contract: <code>${e(
|
|
37
|
+
Contract: <code>${e(o.renderStack.contractSource)}</code> \xB7 Package cache: <code>${e(o.renderStack.cachePath)}</code></p>
|
|
38
38
|
<table>
|
|
39
39
|
<tr><th>Package</th><th>Origin</th><th>Versions / reason</th></tr>
|
|
40
|
-
${
|
|
40
|
+
${t}
|
|
41
41
|
</table>
|
|
42
42
|
|
|
43
43
|
<h2>Base stylesheet</h2>
|
|
@@ -46,19 +46,19 @@ ${m}
|
|
|
46
46
|
|
|
47
47
|
<h2>Design tokens (:root)</h2>
|
|
48
48
|
<p class="meta">Resolved for the publisher landing page. Each token shows which resource in the cascade supplied it.</p>
|
|
49
|
-
${
|
|
49
|
+
${o.stylesheet.tokens.length===0?'<p><span class="bad">\u2717 No tokens resolved</span></p>':`<table>
|
|
50
50
|
<tr><th>Token</th><th>Value</th><th>Declared by</th><th>Cascade level</th></tr>
|
|
51
51
|
${d}
|
|
52
52
|
</table>`}
|
|
53
53
|
|
|
54
54
|
<h2>Look (page body)</h2>
|
|
55
|
-
${
|
|
55
|
+
${o.stylesheet.look?`<p><span class="good">\u2713</span> Bands resolve from <code>${e(o.stylesheet.look.sourceClass)}</code></p>`:'<p><span class="bad">\u2717 No look resolved</span> \u2014 the page body renders as an empty comment.</p>'}
|
|
56
56
|
|
|
57
|
-
<h2>Render catalog (${
|
|
57
|
+
<h2>Render catalog (${o.catalog.length} package version(s))</h2>
|
|
58
58
|
<p class="meta">Everything the renderer can see for this publisher \u2014 the served packages, their import closure, and the ambient render stack.</p>
|
|
59
59
|
<table>
|
|
60
60
|
<tr><th>Package version</th><th>Resources</th></tr>
|
|
61
61
|
${f}
|
|
62
62
|
</table>
|
|
63
63
|
</body>
|
|
64
|
-
</html>`}var R={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},x=(
|
|
64
|
+
</html>`}var R={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},x=(o,e,c,r)=>({status:o,headers:{"Content-Type":e,...r||{}},body:c}),M=o=>x(404,R[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${o}</p>`),Le=o=>({status:301,headers:{Location:o},body:""}),Oe=o=>({status:302,headers:{Location:o},body:""});function Te(o){switch(o.kind){case"exact":return{operator:ie.Exact,version:W(o.major,o.minor,o.patch)};case"minor-pin":return{operator:ie.Compatible,version:W(o.major,o.minor,0)};case"major-pin":return{operator:ie.Major,version:W(o.major,0,0)};default:return{operator:ie.Any,version:W(0,0,0)}}}async function We(o,e,c,r){if(!r)return null;let t=o.producers?.find(f=>f.canProduce(o.publisher,e));if(!t)return null;let s=await t.resolveVersion(o.publisher,e,Te(c));if(!s)return null;let m=K(s);if(c.kind!=="exact")return Oe(`/${e}/${m}.kan.yml`);let{source:d}=await t.produce(o.publisher,e,s);return x(200,R[".kan.yml"],d)}function Ne(o,e,c){let r=o.pkgVersions.get(e);if(!r||r.length===0)return null;switch(c.kind){case"any":return r[0].verStr;case"major-pin":return r.find(t=>t.version.major===c.major)?.verStr??null;case"minor-pin":return r.find(t=>t.version.major===c.major&&t.version.minor===c.minor)?.verStr??null;case"exact":return r.find(t=>t.version.major===c.major&&t.version.minor===c.minor&&t.version.patch===c.patch)?.verStr??null;default:return null}}async function he(o,e,c=""){let{lookRenderer:r,publisher:t}=o;if(e==="/.well-known/kanonak.json")return o.configSource?x(200,R[".json"],o.configSource):x(200,R[".json"],JSON.stringify($e(),null,2));if(e==="/kanonak.lock")return o.lockSource?x(200,R[".kan.yml"],o.lockSource):M(e);if(e==="/.well-known/kanonak-render.json")return x(200,R[".json"],JSON.stringify(ae(o),null,2));if(e==="/.well-known/kanonak-render")return x(200,R[".html"],ge(ae(o)));if(e==="/"||e==="/index.html"||e==="/index.css"){let a=r.publisherSubject(t);return e==="/index.css"?x(200,R[".css"],r.renderStylesheet(a)):x(200,R[".html"],await r.renderDocument(a,{rootIndex:!0}))}let s=".html",m=!1,d=e;for(let a of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(a)){s=a,m=!0,d=e.slice(0,-a.length);break}let f=!m&&/application\/yaml|text\/yaml/i.test(c),l=d.endsWith("/");l&&d!=="/"&&(d=d.slice(0,-1));let h=xe.parse(d,t);if(!h)return M(e);if(h.kind==="package"){let a=Ne(o,h.package_,h.versionSpec);if(!a)return await We(o,h.package_,h.versionSpec,s===".kan.yml"||f)??M(e);if(s===".kan.yml"||f){let v=o.rawByNsKey.get(`${h.package_}@${a}`);return v!==void 0?x(200,R[".kan.yml"],v):M(e)}let g=o.pkgSelfByVer.get(`${h.package_}@${a}`);if(!g)return M(e);if(s===".css")return x(200,R[".css"],r.renderStylesheet(g));if(!l)return Le(d+"/");let S=h.versionSpec.kind==="any";if(S&&!r.hasDeclaredView(g)){let v=(o.pkgVersions.get(h.package_)||[]).map($=>$.verStr);return x(200,R[".html"],r.renderPackageVersionList(h.package_,v,g))}return x(200,R[".html"],await r.renderDocument(g,S?{bareOverview:!0}:void 0))}if(h.kind==="resource"){let a=Ne(o,h.package_,h.versionSpec);if(!a)return M(e);let g=o.bySubject.get(`${t}/${h.package_}@${a}/${h.name}`);if(!g)return M(e);switch(s){case".css":return x(200,R[".css"],r.renderStylesheet(g));case".svg":return x(200,R[".svg"],await r.renderSvg(g));case".md":{let S=r.renderRawMarkdown(g);return S===void 0?M(e):x(200,R[".md"],S)}default:return x(200,R[".html"],await r.renderDocument(g))}}return M(e)}import{readFileSync as Ue}from"fs";var me=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,c=new Set;if(this.options.root!==void 0){let r=new O;for(let t of ee(this.options.root))try{let s=r.parse(Ue(t,"utf-8")).metadata?.namespace_;if(!s?.version)continue;let m=s.version;e.add(`${s.publisher}/${s.package_}@${m.major}.${m.minor}.${m.patch}`),c.add(`${s.publisher}/${s.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:c},this.workspaceIndex}async modelFor(e,c,r){let t=this.getWorkspaceIndex(),s={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},m=c?r?t.exact.has(`${e}/${c}@${r}`):t.pkgs.has(`${e}/${c}`):[...t.pkgs].some(a=>a.startsWith(`${e}/`)),d,f;if(m&&this.options.root!==void 0){let a=this.options.root;d=`ws:${e}`,f=()=>pe(a,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let a=c?r?`${e}/${c}@${r}`:`${e}/${c}`:e;d=`rm:${a}`,f=()=>ue(a,s)}let l=this.models.get(d);if(l)return l;let h=await f();return h.lookRenderer.setLinkMode("open-world"),this.models.set(d,h),h}async handle(e,c=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Ie()};let t=r[0];if(!t.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let s=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="kanonak.lock"||r[1]===".well-known"),m=!s&&r.length>=2?r[1]:void 0,d=!s&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,f=await this.modelFor(t,m,d),l=e.endsWith("/")&&r.length>1?"/":"",h="/"+r.slice(1).join("/")+l,a=await he(f,h,c);return a.headers.Location?{...a,headers:{...a.headers,Location:`/${t}${a.headers.Location}`}}:a}};function Ie(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{G as ClosureScopedRepository,me as RequestRouter,_e as UNIVERSAL_RENDER_BASE,ae as buildRenderDiagnostics,z as buildRenderStackWarnings,H as deriveImportClosure,Ie as landingPage,ue as loadResourceModel,pe as loadServerModel,ge as renderDiagnosticsHtml,N as renderRefKey,q as resolveRenderContract,he as route};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanonak-protocol/sdk",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.25.0",
|
|
4
4
|
"description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -126,7 +126,7 @@
|
|
|
126
126
|
],
|
|
127
127
|
"dependencies": {
|
|
128
128
|
"@kanonak-protocol/canonical": "^0.1.3",
|
|
129
|
-
"@kanonak-protocol/types": "^5.
|
|
129
|
+
"@kanonak-protocol/types": "^5.25.0",
|
|
130
130
|
"ignore": "^7.0.5",
|
|
131
131
|
"js-yaml": "^4.1.0",
|
|
132
132
|
"yaml": "^2.7.0",
|
package/dist/chunk-M7OWTFTC.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{a as F}from"./chunk-SC5M74NM.js";import{a as A}from"./chunk-KOWDHKBN.js";import{e as y,g as P,j as R}from"./chunk-QILEJIFU.js";var b="@kanonak-protocol/sdk (+https://kanonak.org)",v=b;function V(o){v=o}function G(){return v}function p(o){let t;try{t=typeof o=="string"?new URL(o):o}catch{throw new Error(`Kanonak requires an absolute https:// URL \u2014 got an unparseable or relative URL: ${String(o)}`)}if(t.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${t.href} (only https:// is supported).`)}var K=new Set([429,502,503,504]),I=4,T=500,C=2e4;function u(o,t){p(o);let e=new Headers(t?.headers);return e.has("User-Agent")||e.set("User-Agent",v),N(o,{...t,headers:e})}var d=I;function W(o){d=Math.max(0,o)}async function N(o,t){let e;for(let n=0;n<=d;n++){let r;try{r=await fetch(o,t)}catch(s){if(e=s,n>=d)throw s;await E(x(n,null));continue}if(!K.has(r.status)||n>=d)return r;await E(x(n,r.headers.get("retry-after")))}throw e??new Error("kanonakFetch: exhausted retries")}function x(o,t){let e=M(t);if(e!=null)return Math.min(e,C);let n=Math.min(C,T*2**o);return Math.floor(n/2+Math.random()*(n/2))}function M(o){if(!o)return null;let t=Number(o);if(Number.isFinite(t))return Math.max(0,t*1e3);let e=Date.parse(o);return Number.isNaN(e)?null:Math.max(0,e-Date.now())}function E(o){return new Promise(t=>setTimeout(t,o))}var S="https://{publisher}/{package}/{version}.kan.yml",L={version:1};function Y(){return{version:1}}var k=class{constructor(t){this.fetchFn=t}fetchFn;cache=new Map;getConfig(t){let e=this.cache.get(t);return e||(e=this.fetchConfig(t),this.cache.set(t,e),e.catch(()=>{this.cache.get(t)===e&&this.cache.delete(t)})),e}async fetchConfig(t){let e=`https://${t}/.well-known/kanonak.json`,n;try{n=await(this.fetchFn?this.fetchFn(e,t):u(e))}catch{return L}if(n.status===404)return L;if(!n.ok)throw new Error(`Failed to fetch publisher config: ${e} (${n.status} ${n.statusText})`);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let s={version:r.version};return typeof r.package_url_template=="string"&&(j(e,"package_url_template",r.package_url_template),s.package_url_template=r.package_url_template),Array.isArray(r.featured_packages)&&r.featured_packages.every(i=>typeof i=="string")&&(s.featured_packages=r.featured_packages),s}resolvePackageUrl(t,e,n,r){let s=r.package_url_template??S,i=H(s,{publisher:t,package:e,version:n});return p(i),i}};function j(o,t,e){if(!e.startsWith("https://"))throw new Error(`Invalid publisher config at ${o}: ${t} must be an absolute https:// URL template (got "${e}").`)}function H(o,t){let e=o;for(let[r,s]of Object.entries(t))e=e.replaceAll(`{${r}}`,s);let n=e.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${o}`);return e}import $ from"js-yaml";var O=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
2
|
-
`,B="sha256:";function _(o){let t=$.load(o);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??"",packages:t.packages??{}}}function Z(o){let t={};for(let n of Object.keys(o.packages).sort())t[n]=o.packages[n];let e=$.dump({...o,packages:t},{lineWidth:-1,sortKeys:!1,quotingType:'"'});return O+e}async function tt(o){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)),e=Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("");return`${B}${e}`}var m=class{configResolver;fetchFn;lockCache=new Map;constructor(t){this.configResolver=t?.configResolver??new k(t?.fetchFn),this.fetchFn=t?.fetchFn}getConfig(t){return this.configResolver.getConfig(t)}async getPackageUrl(t,e,n){let r=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,e,n,r)}getLock(t){let e=this.lockCache.get(t);return e||(e=this.fetchLock(t),this.lockCache.set(t,e),e.catch(()=>{this.lockCache.get(t)===e&&this.lockCache.delete(t)})),e}async fetchLock(t){let e=`https://${t}/kanonak.lock`,n;try{n=this.fetchFn?await this.fetchFn(e,t):await u(e)}catch{return null}if(n.status===404)return null;if(!n.ok)throw new Error(`Failed to fetch publisher lock: ${e} (${n.status} ${n.statusText})`);return _(await n.text())}};import{VersionOperator as U}from"@kanonak-protocol/types/document/models/enums";function q(o,t){let e=P(o);return e?R(e,t):!1}var D=class{parser=new A;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new m({fetchFn:t.fetchFn}):new m}async getHighestCompatibleVersionAsync(t,e){let r=(await this.publisherIndex.getLock(t))?.packages[`${t}/${e.packageName}`];return r&&q(r.version,e)?this.fetchPinned(t,e.packageName,r):r&&e.versionOperator!==U.Exact?null:this.resolveByDirectFetch(t,e)}async fetchPinned(t,e,n){let r=n.version,s=`${t}/${e}@${r}`,i=this.documents.get(s);if(i)return i;let a=h=>{let f=this.parser.parse(h);return F(f,t,e,r),f};if(this.getFromCache){let h=this.getFromCache(t,e,r);if(h){let f=a(h);return this.documents.set(s,f),this.contentCache.set(s,h),f}}let l=n.resolved,c=this.fetchFn?await this.fetchFn(l,t):await u(l);if(!c.ok)throw new Error(`Failed to fetch Kanonak package: ${l} (${c.status} ${c.statusText})`);let g=await c.text(),w=a(g);return this.onFetch&&this.onFetch(t,e,r,g),this.documents.set(s,w),this.contentCache.set(s,g),w}async resolveByDirectFetch(t,e){let n=e.packageName,s=e.versionOperator===U.Exact?await this.publisherIndex.getPackageUrl(t,n,y(e.version)):`https://${t}/${n}.kan.yml`,i=await this.fetchFollowing(s,t);if(!i)return null;let a=this.parser.parse(i.content),l=a.metadata.namespace_;if(!l||!l.version)throw new Error(`Producer origin returned a package with no namespace/version for ${t}/${n}`);let c=y(l.version);F(a,t,n,c);let g=`${t}/${n}@${c}`;return this.onFetch&&this.onFetch(t,n,c,i.content),this.documents.set(g,a),this.contentCache.set(g,i.content),a}async fetchFollowing(t,e,n=4){let r=t;for(let s=0;s<n;s++){p(r);let i=this.fetchFn?await this.fetchFn(r,e):await u(r,{redirect:"manual"});if(i.status===301||i.status===302){let a=i.headers.get("location");if(!a)throw new Error(`Redirect with no Location header from ${r}`);r=new URL(a,r).toString();continue}if(i.status===404)return null;if(!i.ok)throw new Error(`Failed to fetch Kanonak package: ${r} (${i.status} ${i.statusText})`);return{url:r,content:await i.text()}}throw new Error(`Too many redirects resolving ${t}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===t&&r.package_===e})}async saveDocumentAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let e=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,n,r,s]=e;return this.publisherIndex.getPackageUrl(n,r,s)}};export{b as a,V as b,G as c,p as d,u as e,W as f,Y as g,k as h,B as i,_ as j,Z as k,tt as l,m,D as n};
|