@kanonak-protocol/sdk 4.8.0 → 4.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.d.ts CHANGED
@@ -31,6 +31,7 @@ export { buildOntologyModel } from './introspection/index.js';
31
31
  export type { OntologyModel, ClassDef, PropertyDef, ClassRef, TypeRef, BuildOntologyModelOptions, } from './introspection/index.js';
32
32
  export { BrowserCredentialBackend, BrowserOAuthFlow, generateBrowserDPoPKeys, generateBrowserDPoPKeyPair, importDPoPKeys, createBrowserDPoPProof, browserServerSupportsDPoP, isExpired, hasValidToken, normalizeHost, } from './auth/browser.js';
33
33
  export type { BrowserDPoPKeys, BrowserOAuthResult, CredentialBackend, StoredCredential, DPoPKeyPair, } from './auth/browser.js';
34
+ export { kanonakFetch, setKanonakUserAgent, getKanonakUserAgent, KANONAK_USER_AGENT, } from './http/kanonakFetch.js';
34
35
  export type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
35
36
  export type { IKanonakParser } from '@kanonak-protocol/types/document/parsing';
36
37
  export type { KanonakDocument, KanonakMetadata, Namespace, Import, Version, DocumentReference, ParseResult, ParseError } from '@kanonak-protocol/types/document/models/types';
package/dist/browser.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as fe,b as ge,c as me,d as C,e as E,f as d,g as Ye}from"./chunk-KGWDV7FW.js";import{a as Qe}from"./chunk-NV63IOB7.js";import"./chunk-QHABFCRC.js";import{b as L,c as W,d as F}from"./chunk-F26XWM5K.js";import{a as H}from"./chunk-4NO7MHS7.js";import{a as Pe,b as we,c as he}from"./chunk-RYOZTXI7.js";import{a as ke,b as be}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as Le,B as We,C as Fe,D as Ge,M as Xe,a as Ke,b as xe,c as Se,d as Re,f as De,g as Be,h as Ce,i as Ee,k as je,l as ve,m as _e,n as Ie,o as Ae,p as Te,q as Oe,r as Ve,s as $e,t as Ue,u as Me,v as ze,w as Ne,x as Je,y as He,z as qe}from"./chunk-IZRPJCQW.js";import"./chunk-SHDHMKMJ.js";import{a as Y,c as le,i as pe}from"./chunk-DSHPAWJQ.js";import{a as q}from"./chunk-NJ3AZYQD.js";import{a as ye}from"./chunk-UK2OIPAB.js";import"./chunk-PBNVHBS3.js";import{b as ue,c as de}from"./chunk-VKTFLHCW.js";import{a as G,b as X,c as Q,d as ee,e as re,f as te,g as ne,h as oe,i as se,j as ie,k as ae,l as ce}from"./chunk-T3JR2SV6.js";import{a as Z}from"./chunk-FUUTGGJS.js";import{c as O,d as V,e as $,f as U,g as M,h as z,i as N,j as J}from"./chunk-2ACBWC7K.js";var j="kanonak-credentials",u="credentials",Ze=1,g=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,Ze);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
2
- Credential storage requires IndexedDB support in your browser.`))})}async function _(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey);return{signingKey:n.privateKey,publicKeyJwk:r}}async function k(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey),e=await crypto.subtle.exportKey("jwk",n.privateKey);return{keys:{signingKey:n.privateKey,publicKeyJwk:r},dpopKeyPair:{publicKey:r,privateKey:e}}}async function b(n){return{signingKey:await crypto.subtle.importKey("jwk",n.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:n.publicKey}}async function K(n,r,e,t,o){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:n.publicKeyJwk.kty,crv:n.publicKeyJwk.crv,x:n.publicKeyJwk.x,y:n.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:r.toUpperCase(),htu:e,iat:Math.floor(Date.now()/1e3)};return t&&(s.ath=await rr(t)),o&&(s.nonce=o),await er(a,s,n.signingKey)}function x(n){return!n||n.length===0?!1:n.some(r=>r.toUpperCase()==="ES256")}async function er(n,r,e){let t=v(JSON.stringify(n)),o=v(JSON.stringify(r)),a=new TextEncoder().encode(`${t}.${o}`),s=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,a),l=D(s);return`${t}.${o}.${l}`}async function rr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return D(e)}function v(n){let r=new TextEncoder().encode(n);return D(r.buffer)}function D(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var tr=300*1e3,S=class{credentialBackend;callbackUrl;constructor(r){this.credentialBackend=new g,this.callbackUrl=r??`${window.location.origin}/browser/callback.html`}async authorize(r){let e=d(r),t=await this.discover(e);if(!t)return{success:!1,error:`No OAuth discovery endpoint found for '${e}'.`};if(!t.authorizationEndpoint||!t.tokenEndpoint)return{success:!1,error:`OAuth metadata incomplete for '${e}'.`};let o=x(t.dpopSigningAlgValuesSupported),a=null,s=null;if(o){let f=await k();a=f.keys,s=f.dpopKeyPair}let l=await this.credentialBackend.get(e),i=l?.clientId??null,c=l?.clientSecret??null;if(!i&&t.registrationEndpoint){let f=await this.registerClient(t.registrationEndpoint);if(!f)return{success:!1,error:`Dynamic client registration failed for '${e}'.`};i=f.clientId,c=f.clientSecret??null}if(!i)return{success:!1,error:`No OAuth client credentials for '${e}'.`};let m=nr(),p=await or(m),R=sr(),A=ir(t.authorizationEndpoint,i,this.callbackUrl,R,p),y=await this.openAuthPopup(A,R);if(!y)return{success:!1,error:"Authorization timed out or was cancelled."};if(y.error)return{success:!1,error:`Authorization failed: ${y.error}`};if(!y.code)return{success:!1,error:"No authorization code received."};if(y.state!==R)return{success:!1,error:"State mismatch \u2014 possible CSRF attack."};let P=await this.exchangeCode(t.tokenEndpoint,i,c,y.code,this.callbackUrl,m,a);if(!P)return{success:!1,error:"Token exchange failed."};let T={clientId:i,clientSecret:c,accessToken:P.accessToken??null,refreshToken:P.refreshToken??null,expiresAt:P.expiresIn?new Date(Date.now()+P.expiresIn*1e3).toISOString():null,tokenEndpoint:t.tokenEndpoint,dpopKeyPair:s};return await this.credentialBackend.store(e,T),{success:!0,host:e}}async getCredentialWithKeys(r){let e=await this.credentialBackend.get(r);if(!e)return null;let t=null;return e.dpopKeyPair&&(t=await b(e.dpopKeyPair)),{credential:e,dpopKeys:t}}async logout(r){let e=d(r);return await this.credentialBackend.remove(e),{success:!0,host:e}}async listAuthenticated(){return this.credentialBackend.list()}async discover(r){for(let e of[`https://${r}/.well-known/oauth-authorization-server`,`https://${r}/.well-known/openid-configuration`])try{let t=await fetch(e);if(!t.ok)continue;let o=await t.json();return{issuer:w(o.issuer),authorizationEndpoint:w(o.authorization_endpoint),tokenEndpoint:w(o.token_endpoint),registrationEndpoint:w(o.registration_endpoint),revocationEndpoint:w(o.revocation_endpoint),dpopSigningAlgValuesSupported:I(o.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:I(o.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(r){try{let e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak Browser",redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})});if(!e.ok)return null;let t=await e.json(),o=t.client_id;return o?{clientId:o,clientSecret:t.client_secret}:null}catch{return null}}openAuthPopup(r,e){return new Promise(t=>{let o=window.open(r,"kanonak-auth","width=500,height=700,menubar=no,toolbar=no,location=yes,status=no");if(!o){t(null);return}let a=setTimeout(()=>{i(),t(null)},tr),s=c=>{c.origin===window.location.origin&&(!c.data||c.data.type!=="kanonak-auth-callback"||(i(),t({code:c.data.code??void 0,state:c.data.state??void 0,error:c.data.error??void 0})))},l=setInterval(()=>{o.closed&&(i(),t(null))},500),i=()=>{clearTimeout(a),clearInterval(l),window.removeEventListener("message",s);try{o.close()}catch{}};window.addEventListener("message",s)})}async exchangeCode(r,e,t,o,a,s,l){let i=new URLSearchParams({grant_type:"authorization_code",client_id:e,code:o,redirect_uri:a,code_verifier:s});t&&i.set("client_secret",t);let c={"Content-Type":"application/x-www-form-urlencoded"};l&&(c.DPoP=await K(l,"POST",r));try{let m=await fetch(r,{method:"POST",headers:c,body:i.toString()});if(!m.ok)return null;let p=await m.json();return{accessToken:p.access_token,refreshToken:p.refresh_token,expiresIn:typeof p.expires_in=="number"?p.expires_in:void 0}}catch{return null}}};function nr(){let n=new Uint8Array(32);return crypto.getRandomValues(n),B(n.buffer)}async function or(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return B(e)}function sr(){let n=new Uint8Array(16);return crypto.getRandomValues(n),B(n.buffer)}function ir(n,r,e,t,o){let a=new URLSearchParams({client_id:r,response_type:"code",redirect_uri:e,state:t,code_challenge:o,code_challenge_method:"S256"});return`${n}?${a}`}function B(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(n){return typeof n=="string"?n:null}function I(n){return Array.isArray(n)?n.filter(r=>typeof r=="string"):null}export{Ne as AmbiguousReferenceRule,se as BooleanStatement,g as BrowserCredentialBackend,S as BrowserOAuthFlow,Fe as ClassDefinitionRule,Ie as ClassHierarchyCycleRule,X as DefinedKanonak,Me as DefinitionPropertyReferenceRule,ge as EdgeType,Y as EmbeddedKanonak,je as EmbeddedKanonakTypeRule,ae as EmbeddedStatement,me as GraphBuilder,F as HttpKanonakDocumentRepository,ve as ImportExistenceRule,H as InMemoryKanonakDocumentRepository,Ue as InstancePropertyReferenceRule,G as Kanonak,we as KanonakDocumentPositions,pe as KanonakObjectParser,Xe as KanonakObjectValidator,q as KanonakParser,Z as KanonakUri,ke as KanonakUriBuilder,ce as ListStatement,Ge as MarkdownLinkRule,le as MarkdownStatement,$e as NamespaceImportCycleRule,De as NamespacePrefixRule,fe as NodeType,oe as NumberStatement,He as ObjectPropertyImportRule,qe as ObjectPropertyValueValidationRule,Se as OntologyValidationError,Ke as OntologyValidationResult,Le as PropertyDomainRule,Ae as PropertyHierarchyCycleRule,Pe as PropertyMetadata,Je as PropertyRangeReferenceRule,Te as PropertyRangeRequiredRule,Ce as PropertyTypeSpecificityRule,We as PropertyValueTypeRule,L as PublisherConfigResolver,W as PublisherIndex,ee as ReferenceKanonak,ie as ReferenceStatement,Be as ResourceNamingRule,ue as ResourceResolver,ye as ResourceTypeClassifier,te as ScalarStatement,re as Statement,ne as StringStatement,Oe as SubClassOfReferenceRule,Ve as SubPropertyOfReferenceRule,Q as SubjectKanonak,Ee as SubjectKanonakTypeRequiredRule,de as TypeResolver,_e as UnresolvedReferenceRule,Re as ValidationContext,xe as ValidationSeverity,ze as XsdImportRule,x as browserServerSupportsDPoP,Ye as buildOntologyModel,O as compareVersions,K as createBrowserDPoPProof,U as createVersion,Qe as findDerivation,be as findInstancesByType,$ as formatVersion,k as generateBrowserDPoPKeyPair,_ as generateBrowserDPoPKeys,E as hasValidToken,b as importDPoPKeys,z as isCompatibleVersion,C as isExpired,N as isMajorCompatible,d as normalizeHost,M as parseVersionString,he as parseWithPositions,J as pickHighestDocument,V as versionsEqual};
1
+ import{a as we,b as ke,c as he,d as E,e as _,f as d,g as tr}from"./chunk-KGWDV7FW.js";import{a as rr}from"./chunk-NV63IOB7.js";import"./chunk-QHABFCRC.js";import{a as F,b as W,c as G,d as w,f as X,g as Q,h as Y}from"./chunk-JYBKSBB5.js";import{a as q}from"./chunk-4NO7MHS7.js";import{a as Ke,b as be,c as xe}from"./chunk-RYOZTXI7.js";import{a as Se,b as Re}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as Xe,B as Qe,C as Ye,D as Ze,M as er,a as De,b as Be,c as Ce,d as Ee,f as _e,g as je,h as Ae,i as ve,k as Ie,l as Te,m as Oe,n as Ve,o as Ue,p as $e,q as Me,r as Ne,s as ze,t as Je,u as He,v as qe,w as Le,x as Fe,y as We,z as Ge}from"./chunk-IZRPJCQW.js";import"./chunk-SHDHMKMJ.js";import{a as te,c as ye,i as me}from"./chunk-DSHPAWJQ.js";import{a as L}from"./chunk-NJ3AZYQD.js";import{a as Pe}from"./chunk-UK2OIPAB.js";import"./chunk-PBNVHBS3.js";import{b as ge,c as fe}from"./chunk-VKTFLHCW.js";import{a as Z,b as ee,c as re,d as oe,e as se,f as ie,g as ae,h as ce,i as le,j as ue,k as de,l as pe}from"./chunk-T3JR2SV6.js";import{a as ne}from"./chunk-FUUTGGJS.js";import{c as V,d as U,e as $,f as M,g as N,h as z,i as J,j as H}from"./chunk-2ACBWC7K.js";var j="kanonak-credentials",u="credentials",nr=1,f=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,nr);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
2
+ Credential storage requires IndexedDB support in your browser.`))})}async function v(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey);return{signingKey:n.privateKey,publicKeyJwk:r}}async function K(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey),e=await crypto.subtle.exportKey("jwk",n.privateKey);return{keys:{signingKey:n.privateKey,publicKeyJwk:r},dpopKeyPair:{publicKey:r,privateKey:e}}}async function b(n){return{signingKey:await crypto.subtle.importKey("jwk",n.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:n.publicKey}}async function x(n,r,e,t,o){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:n.publicKeyJwk.kty,crv:n.publicKeyJwk.crv,x:n.publicKeyJwk.x,y:n.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:r.toUpperCase(),htu:e,iat:Math.floor(Date.now()/1e3)};return t&&(s.ath=await sr(t)),o&&(s.nonce=o),await or(a,s,n.signingKey)}function S(n){return!n||n.length===0?!1:n.some(r=>r.toUpperCase()==="ES256")}async function or(n,r,e){let t=A(JSON.stringify(n)),o=A(JSON.stringify(r)),a=new TextEncoder().encode(`${t}.${o}`),s=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,a),l=B(s);return`${t}.${o}.${l}`}async function sr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return B(e)}function A(n){let r=new TextEncoder().encode(n);return B(r.buffer)}function B(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var ir=300*1e3,R=class{credentialBackend;callbackUrl;constructor(r){this.credentialBackend=new f,this.callbackUrl=r??`${window.location.origin}/browser/callback.html`}async authorize(r){let e=d(r),t=await this.discover(e);if(!t)return{success:!1,error:`No OAuth discovery endpoint found for '${e}'.`};if(!t.authorizationEndpoint||!t.tokenEndpoint)return{success:!1,error:`OAuth metadata incomplete for '${e}'.`};let o=S(t.dpopSigningAlgValuesSupported),a=null,s=null;if(o){let g=await K();a=g.keys,s=g.dpopKeyPair}let l=await this.credentialBackend.get(e),i=l?.clientId??null,c=l?.clientSecret??null;if(!i&&t.registrationEndpoint){let g=await this.registerClient(t.registrationEndpoint);if(!g)return{success:!1,error:`Dynamic client registration failed for '${e}'.`};i=g.clientId,c=g.clientSecret??null}if(!i)return{success:!1,error:`No OAuth client credentials for '${e}'.`};let m=ar(),p=await cr(m),D=lr(),T=ur(t.authorizationEndpoint,i,this.callbackUrl,D,p),y=await this.openAuthPopup(T,D);if(!y)return{success:!1,error:"Authorization timed out or was cancelled."};if(y.error)return{success:!1,error:`Authorization failed: ${y.error}`};if(!y.code)return{success:!1,error:"No authorization code received."};if(y.state!==D)return{success:!1,error:"State mismatch \u2014 possible CSRF attack."};let P=await this.exchangeCode(t.tokenEndpoint,i,c,y.code,this.callbackUrl,m,a);if(!P)return{success:!1,error:"Token exchange failed."};let O={clientId:i,clientSecret:c,accessToken:P.accessToken??null,refreshToken:P.refreshToken??null,expiresAt:P.expiresIn?new Date(Date.now()+P.expiresIn*1e3).toISOString():null,tokenEndpoint:t.tokenEndpoint,dpopKeyPair:s};return await this.credentialBackend.store(e,O),{success:!0,host:e}}async getCredentialWithKeys(r){let e=await this.credentialBackend.get(r);if(!e)return null;let t=null;return e.dpopKeyPair&&(t=await b(e.dpopKeyPair)),{credential:e,dpopKeys:t}}async logout(r){let e=d(r);return await this.credentialBackend.remove(e),{success:!0,host:e}}async listAuthenticated(){return this.credentialBackend.list()}async discover(r){for(let e of[`https://${r}/.well-known/oauth-authorization-server`,`https://${r}/.well-known/openid-configuration`])try{let t=await w(e);if(!t.ok)continue;let o=await t.json();return{issuer:k(o.issuer),authorizationEndpoint:k(o.authorization_endpoint),tokenEndpoint:k(o.token_endpoint),registrationEndpoint:k(o.registration_endpoint),revocationEndpoint:k(o.revocation_endpoint),dpopSigningAlgValuesSupported:I(o.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:I(o.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(r){try{let e=await w(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak Browser",redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})});if(!e.ok)return null;let t=await e.json(),o=t.client_id;return o?{clientId:o,clientSecret:t.client_secret}:null}catch{return null}}openAuthPopup(r,e){return new Promise(t=>{let o=window.open(r,"kanonak-auth","width=500,height=700,menubar=no,toolbar=no,location=yes,status=no");if(!o){t(null);return}let a=setTimeout(()=>{i(),t(null)},ir),s=c=>{c.origin===window.location.origin&&(!c.data||c.data.type!=="kanonak-auth-callback"||(i(),t({code:c.data.code??void 0,state:c.data.state??void 0,error:c.data.error??void 0})))},l=setInterval(()=>{o.closed&&(i(),t(null))},500),i=()=>{clearTimeout(a),clearInterval(l),window.removeEventListener("message",s);try{o.close()}catch{}};window.addEventListener("message",s)})}async exchangeCode(r,e,t,o,a,s,l){let i=new URLSearchParams({grant_type:"authorization_code",client_id:e,code:o,redirect_uri:a,code_verifier:s});t&&i.set("client_secret",t);let c={"Content-Type":"application/x-www-form-urlencoded"};l&&(c.DPoP=await x(l,"POST",r));try{let m=await w(r,{method:"POST",headers:c,body:i.toString()});if(!m.ok)return null;let p=await m.json();return{accessToken:p.access_token,refreshToken:p.refresh_token,expiresIn:typeof p.expires_in=="number"?p.expires_in:void 0}}catch{return null}}};function ar(){let n=new Uint8Array(32);return crypto.getRandomValues(n),C(n.buffer)}async function cr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return C(e)}function lr(){let n=new Uint8Array(16);return crypto.getRandomValues(n),C(n.buffer)}function ur(n,r,e,t,o){let a=new URLSearchParams({client_id:r,response_type:"code",redirect_uri:e,state:t,code_challenge:o,code_challenge_method:"S256"});return`${n}?${a}`}function C(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(n){return typeof n=="string"?n:null}function I(n){return Array.isArray(n)?n.filter(r=>typeof r=="string"):null}export{Le as AmbiguousReferenceRule,le as BooleanStatement,f as BrowserCredentialBackend,R as BrowserOAuthFlow,Ye as ClassDefinitionRule,Ve as ClassHierarchyCycleRule,ee as DefinedKanonak,He as DefinitionPropertyReferenceRule,ke as EdgeType,te as EmbeddedKanonak,Ie as EmbeddedKanonakTypeRule,de as EmbeddedStatement,he as GraphBuilder,Y as HttpKanonakDocumentRepository,Te as ImportExistenceRule,q as InMemoryKanonakDocumentRepository,Je as InstancePropertyReferenceRule,F as KANONAK_USER_AGENT,Z as Kanonak,be as KanonakDocumentPositions,me as KanonakObjectParser,er as KanonakObjectValidator,L as KanonakParser,ne as KanonakUri,Se as KanonakUriBuilder,pe as ListStatement,Ze as MarkdownLinkRule,ye as MarkdownStatement,ze as NamespaceImportCycleRule,_e as NamespacePrefixRule,we as NodeType,ce as NumberStatement,We as ObjectPropertyImportRule,Ge as ObjectPropertyValueValidationRule,Ce as OntologyValidationError,De as OntologyValidationResult,Xe as PropertyDomainRule,Ue as PropertyHierarchyCycleRule,Ke as PropertyMetadata,Fe as PropertyRangeReferenceRule,$e as PropertyRangeRequiredRule,Ae as PropertyTypeSpecificityRule,Qe as PropertyValueTypeRule,X as PublisherConfigResolver,Q as PublisherIndex,oe as ReferenceKanonak,ue as ReferenceStatement,je as ResourceNamingRule,ge as ResourceResolver,Pe as ResourceTypeClassifier,ie as ScalarStatement,se as Statement,ae as StringStatement,Me as SubClassOfReferenceRule,Ne as SubPropertyOfReferenceRule,re as SubjectKanonak,ve as SubjectKanonakTypeRequiredRule,fe as TypeResolver,Oe as UnresolvedReferenceRule,Ee as ValidationContext,Be as ValidationSeverity,qe as XsdImportRule,S as browserServerSupportsDPoP,tr as buildOntologyModel,V as compareVersions,x as createBrowserDPoPProof,M as createVersion,rr as findDerivation,Re as findInstancesByType,$ as formatVersion,K as generateBrowserDPoPKeyPair,v as generateBrowserDPoPKeys,G as getKanonakUserAgent,_ as hasValidToken,b as importDPoPKeys,z as isCompatibleVersion,E as isExpired,J as isMajorCompatible,w as kanonakFetch,d as normalizeHost,N as parseVersionString,xe as parseWithPositions,H as pickHighestDocument,W as setKanonakUserAgent,U as versionsEqual};
@@ -1 +1 @@
1
- import{d as v}from"./chunk-F26XWM5K.js";import{a as w}from"./chunk-4NO7MHS7.js";import{a as f}from"./chunk-NJ3AZYQD.js";import{c as A,d as R,g as b,h as F,i as S}from"./chunk-2ACBWC7K.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as x}from"url";import{VersionOperator as P}from"@kanonak-protocol/types/document/models/enums";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case P.Exact:return R(r,t.version);case P.Compatible:return F(r,t.version);case P.Major:return S(r,t.version);case P.Any:return A(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return A(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],h=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,h)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=x(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return x(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as g from"fs";var _=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(_||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as $}from"os";import{join as B}from"path";function d(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||B($(),".kanonak","packages")}var C=class u{static createComposite(e,t,n){let o=e??d(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{VersionOperator as H}from"@kanonak-protocol/types/document/models/enums";var K=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return this.lock.packages[`${e}/${t}`]?.version}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=b(n);if(o){let s={...t,versionOperator:H.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as V,readdirSync as j}from"fs";import{join as N}from"path";var E=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function I(u,e=[]){for(let t of j(u,{withFileTypes:!0}))t.isDirectory()?E.has(t.name)||I(N(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(N(u,t.name));return e}async function z(u,e=new f,t={}){let n=new w(e);for(let m of I(u))try{let l=e.parse(V(m,"utf-8")),p=l.metadata?.namespace_,h=p?.version;p&&h&&await n.saveDocumentAsync(l,`${p.publisher}/${p.package_}@${h.major}.${h.minor}.${h.patch}`)}catch{}let o=new y(d(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,p)=>s.get(`${m}|${l}|${p}`)??null,onFetch:(m,l,p,h)=>{s.set(`${m}|${l}|${p}`,h)}},r=new v({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,_ as b,k as c,d,C as e,D as f,K as g,I as h,z as i};
1
+ import{h as v}from"./chunk-JYBKSBB5.js";import{a as w}from"./chunk-4NO7MHS7.js";import{a as f}from"./chunk-NJ3AZYQD.js";import{c as A,d as R,g as b,h as F,i as S}from"./chunk-2ACBWC7K.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as x}from"url";import{VersionOperator as P}from"@kanonak-protocol/types/document/models/enums";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case P.Exact:return R(r,t.version);case P.Compatible:return F(r,t.version);case P.Major:return S(r,t.version);case P.Any:return A(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return A(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],h=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,h)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=x(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return x(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as g from"fs";var _=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(_||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as $}from"os";import{join as B}from"path";function d(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||B($(),".kanonak","packages")}var C=class u{static createComposite(e,t,n){let o=e??d(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{VersionOperator as H}from"@kanonak-protocol/types/document/models/enums";var K=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return this.lock.packages[`${e}/${t}`]?.version}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=b(n);if(o){let s={...t,versionOperator:H.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as V,readdirSync as j}from"fs";import{join as N}from"path";var E=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function I(u,e=[]){for(let t of j(u,{withFileTypes:!0}))t.isDirectory()?E.has(t.name)||I(N(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(N(u,t.name));return e}async function z(u,e=new f,t={}){let n=new w(e);for(let m of I(u))try{let l=e.parse(V(m,"utf-8")),p=l.metadata?.namespace_,h=p?.version;p&&h&&await n.saveDocumentAsync(l,`${p.publisher}/${p.package_}@${h.major}.${h.minor}.${h.patch}`)}catch{}let o=new y(d(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,p)=>s.get(`${m}|${l}|${p}`)??null,onFetch:(m,l,p,h)=>{s.set(`${m}|${l}|${p}`,h)}},r=new v({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,_ as b,k as c,d,C as e,D as f,K as g,I as h,z as i};
@@ -0,0 +1,2 @@
1
+ import{a as f}from"./chunk-SC5M74NM.js";import{a as w}from"./chunk-NJ3AZYQD.js";import{e as v}from"./chunk-2ACBWC7K.js";var R="@kanonak-protocol/sdk (+https://kanonak.org)",y=R;function b(a){y=a}function N(){return y}function h(a,e){let t=new Headers(e?.headers);return t.has("User-Agent")||t.set("User-Agent",y),fetch(a,{...e,headers:t})}var P="https://{publisher}/index.txt",C="https://{publisher}/{package}/{version}.kan.yml",F={version:1};function E(a){return{version:1,index:P.replaceAll("{publisher}",a),package:C.replaceAll("{publisher}",a),auth:"none"}}var m=class{constructor(e){this.fetchFn=e}fetchFn;cache=new Map;getConfig(e){let t=this.cache.get(e);return t||(t=this.fetchConfig(e),this.cache.set(e,t),t.catch(()=>{this.cache.get(e)===t&&this.cache.delete(e)})),t}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,r;try{r=await(this.fetchFn?this.fetchFn(t,e):h(t))}catch{return F}if(r.status===404)return F;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${t} (${r.status} ${r.statusText})`);let n=await r.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let s={version:n.version};return typeof n.index=="string"&&(s.index=n.index),typeof n.package=="string"&&(s.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(s.auth=n.auth),Array.isArray(n.render)&&n.render.every(o=>typeof o=="string")&&(s.render=n.render),typeof n.resolveByRedirect=="boolean"&&(s.resolveByRedirect=n.resolveByRedirect),s}resolveIndexUrl(e,t){let r=t.index??P;return x(r,{publisher:e})}resolvePackageUrl(e,t,r,n){let s=n.package??C;return x(s,{publisher:e,package:t,version:r})}};function x(a,e){let t=a;for(let[n,s]of Object.entries(e))t=t.replaceAll(`{${n}}`,s);let r=t.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${a}`);return t}import{VersionOperator as p}from"@kanonak-protocol/types/document/models/enums";var u=class a{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new m(e?.fetchFn),this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let r=await this.getPackageVersions(e,t.packageName);if(r.length===0)return null;let n=r.filter(s=>this.isVersionCompatible(s,t.version,t.versionOperator));return n.length===0?null:(n.sort((s,o)=>this.compareVersionStrings(o,s)),n[0])}async getHighestVersion(e,t){let r=await this.getPackageVersions(e,t);return r.length===0?null:[...r].sort((s,o)=>this.compareVersionStrings(o,s))[0]}async listLatestPackages(e){let t=await this.getIndex(e),r=[];for(let[n,s]of t){if(s.length===0)continue;let o=[...s].sort((i,c)=>this.compareVersionStrings(c,i));r.push({packageName:n,version:o[0]})}return r.sort((n,s)=>n.packageName.localeCompare(s.packageName)),r}async getPackageUrl(e,t,r){let n=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,n)}getConfig(e){return this.configResolver.getConfig(e)}async getPackageVersions(e,t){return(await this.getIndex(e)).get(t)??[]}getIndex(e){let t=this.indexCache.get(e);return t||(t=this.fetchIndex(e),this.indexCache.set(e,t),t.catch(()=>{this.indexCache.get(e)===t&&this.indexCache.delete(e)})),t}async fetchIndex(e){let t=await this.configResolver.getConfig(e),r=this.configResolver.resolveIndexUrl(e,t),n=this.fetchFn?await this.fetchFn(r,e):await h(r);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${r} (${n.status} ${n.statusText})`);let s=await n.text();return a.parseIndex(s)}static parseIndex(e){let t=new Map;for(let r of e.split(`
2
+ `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("/");if(s===-1)continue;let o=n.substring(0,s),i=n.substring(s+1);if(!o||!i)continue;let c=t.get(o);c?c.push(i):t.set(o,[i])}return t}isVersionCompatible(e,t,r){let n=a.parseVersion(e);if(!n)return!1;switch(r){case p.Any:return!0;case p.Exact:return n.major===t.major&&n.minor===t.minor&&n.patch===t.patch;case p.Compatible:return n.major===t.major&&n.minor===t.minor&&n.patch>=t.patch;case p.Major:return n.major!==t.major?!1:n.minor>t.minor?!0:n.minor===t.minor?n.patch>=t.patch:!1;default:return!1}}static parseVersion(e){let t=e.split(".");if(t.length<2)return null;let r=parseInt(t[0],10),n=parseInt(t[1],10),s=t.length>=3?parseInt(t[2],10):0;return isNaN(r)||isNaN(n)||isNaN(s)?null:{major:r,minor:n,patch:s}}compareVersionStrings(e,t){let r=a.parseVersion(e),n=a.parseVersion(t);return!r&&!n?0:r?n?r.major!==n.major?r.major-n.major:r.minor!==n.minor?r.minor-n.minor:r.patch-n.patch:1:-1}};import{VersionOperator as I}from"@kanonak-protocol/types/document/models/enums";var A=class{parser=new w;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new u({fetchFn:e.fetchFn}):new u}async getHighestCompatibleVersionAsync(e,t){if((await this.publisherIndex.getConfig(e)).resolveByRedirect)return this.resolveByRedirect(e,t);let n=await this.publisherIndex.resolveVersion(e,t);if(!n)return null;let s=`${e}/${t.packageName}@${n}`,o=this.documents.get(s);if(o)return o;if(this.getFromCache){let d=this.getFromCache(e,t.packageName,n);if(d){let k=this.parser.parse(d);return f(k,e,t.packageName,n),this.documents.set(s,k),this.contentCache.set(s,d),k}}let i=await this.publisherIndex.getPackageUrl(e,t.packageName,n),c=this.fetchFn?await this.fetchFn(i,e):await h(i);if(!c.ok)throw new Error(`Failed to fetch Kanonak package: ${i} (${c.status} ${c.statusText})`);let g=await c.text(),l=this.parser.parse(g);return f(l,e,t.packageName,n),this.onFetch&&this.onFetch(e,t.packageName,n,g),this.documents.set(s,l),this.contentCache.set(s,g),l}async resolveByRedirect(e,t){let r=t.packageName,s=t.versionOperator===I.Exact?await this.publisherIndex.getPackageUrl(e,r,v(t.version)):`https://${e}/${r}.kan.yml`,o=await this.fetchFollowing(s,e);if(!o)return null;let i=this.parser.parse(o.content),c=i.metadata.namespace_;if(!c||!c.version)throw new Error(`Producer origin returned a package with no namespace/version for ${e}/${r}`);let g=v(c.version);f(i,e,r,g);let l=`${e}/${r}@${g}`;return this.onFetch&&this.onFetch(e,r,g,o.content),this.documents.set(l,i),this.contentCache.set(l,o.content),i}async fetchFollowing(e,t,r=4){let n=e;for(let s=0;s<r;s++){let o=this.fetchFn?await this.fetchFn(n,t):await h(n,{redirect:"manual"});if(o.status===301||o.status===302){let i=o.headers.get("location");if(!i)throw new Error(`Redirect with no Location header from ${n}`);n=new URL(i,n).toString();continue}if(o.status===404)return null;if(!o.ok)throw new Error(`Failed to fetch Kanonak package: ${n} (${o.status} ${o.statusText})`);return{url:n,content:await o.text()}}throw new Error(`Too many redirects resolving ${e}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(r=>{let n=r.metadata.namespace_;return n&&n.publisher===e&&n.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,r,n,s]=t;return this.publisherIndex.getPackageUrl(r,n,s)}};export{R as a,b,N as c,h as d,E as e,m as f,u as g,A as h};
@@ -0,0 +1,41 @@
1
+ /**
2
+ * THE canonical way SDK code makes outbound HTTP requests. Use `kanonakFetch`
3
+ * instead of the global `fetch` so every SDK-originated request carries an
4
+ * identifiable `User-Agent`.
5
+ *
6
+ * Why this exists: a generic or absent User-Agent (Node/undici sends a bare
7
+ * `node`) is a common bot signal that trips edge risk engines — e.g. a
8
+ * Cloudflare Turnstile challenge returning 429 on `.well-known/kanonak.json`.
9
+ * Sending an identifiable product token avoids that whole class of failure.
10
+ *
11
+ * `User-Agent` is a FORBIDDEN header in browsers (the platform silently drops
12
+ * it), but it IS honored in Node and Cloudflare Workers — exactly the contexts
13
+ * where the generic UA shows up. So always setting it is safe everywhere: it
14
+ * helps where it can and is a no-op where it can't.
15
+ *
16
+ * NOTE: when a consumer injects its own transport (an `AuthenticatedFetchFn` /
17
+ * `fetchFn`), that transport OWNS the request and this wrapper is bypassed — a
18
+ * `fetchFn`-only consumer (e.g. the app-look Worker) must set its own UA. This
19
+ * wrapper covers the SDK's DEFAULT fetch paths.
20
+ */
21
+ /**
22
+ * The default product token the SDK identifies itself with. Intentionally
23
+ * version-less: the SDK version lives only in `package.json` (not reliably
24
+ * resolvable from a minified/split bundle at runtime), and the risk-engine
25
+ * goal is an identifiable client, not precise telemetry. A host that wants a
26
+ * richer identity overrides it via {@link setKanonakUserAgent}.
27
+ */
28
+ export declare const KANONAK_USER_AGENT = "@kanonak-protocol/sdk (+https://kanonak.org)";
29
+ /**
30
+ * Override the User-Agent the SDK sends on its default fetch paths — e.g. a
31
+ * host app identifying itself (`Kanonak-VSCode/4.8.0`). Process-global: it is
32
+ * the SDK's client identity, the same for every publisher.
33
+ */
34
+ export declare function setKanonakUserAgent(ua: string): void;
35
+ /** The User-Agent the SDK currently sends (the default, or a host override). */
36
+ export declare function getKanonakUserAgent(): string;
37
+ /**
38
+ * `fetch` with the SDK's User-Agent added — unless the caller already set one,
39
+ * which is preserved. All other `init` fields pass through untouched.
40
+ */
41
+ export declare function kanonakFetch(input: string | URL, init?: RequestInit): Promise<Response>;
package/dist/index.d.ts CHANGED
@@ -23,6 +23,7 @@ export type { KanonakDocument, KanonakMetadata, Namespace, Import, Version, Docu
23
23
  export { VersionOperator } from '@kanonak-protocol/types/document/models/enums';
24
24
  export { CredentialStore, createAuthenticatedFetch, generateDPoPKeyPair, createDPoPProof, serverSupportsDPoP, isExpired, hasValidToken, normalizeHost, } from './auth/index.js';
25
25
  export type { CredentialBackend, StoredCredential, DPoPKeyPair, AuthenticatedFetchFn, } from './auth/index.js';
26
+ export { kanonakFetch, setKanonakUserAgent, getKanonakUserAgent, KANONAK_USER_AGENT, } from './http/kanonakFetch.js';
26
27
  export { loadLockFile, saveLockFile, computeIntegrity, } from './lock/index.js';
27
28
  export type { LockFile, LockEntry } from './lock/index.js';
28
29
  export { findDerivation } from './derivation/index.js';
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import{a as Pn,b as wn,c as Sn,d as Cn,e as be}from"./chunk-RWEGPZ23.js";import{a as yr,c as Ce,e as He,h as ze,i as We,j as gr}from"./chunk-OOR5SVNQ.js";import{a as hn,b as kn,c as bn,d as W,e as G,f as l,g as hr}from"./chunk-KGWDV7FW.js";import{a as fr}from"./chunk-NV63IOB7.js";import"./chunk-QHABFCRC.js";import{a as zt,b as Wt,c as Gt,d as Jt,e as qt,f as en,g as tn,h as nn,i as rn}from"./chunk-MPBNEKCQ.js";import{b as Yt,c as Zt,d as Qt}from"./chunk-F26XWM5K.js";import{a as Ht}from"./chunk-4NO7MHS7.js";import{a as En,b as xn,c as In,d as vn}from"./chunk-RYOZTXI7.js";import{a as Kn,b as Dn}from"./chunk-PEUTCG3B.js";import{a as jn}from"./chunk-PEJALHXK.js";import{a as Xt}from"./chunk-SC5M74NM.js";import{A as lr,B as ur,C as pr,D as dr,M as mr,a as Nn,b as Tn,c as Ln,d as _n,e as Un,f as Fn,g as Mn,h as Hn,i as zn,j as Wn,k as Gn,l as Jn,m as qn,n as Yn,o as Zn,p as Xn,q as Qn,r as er,s as tr,t as nr,u as rr,v as or,w as ar,x as ir,y as sr,z as cr}from"./chunk-IZRPJCQW.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as C,c as sn,d as Fe,e as v,f as ke,g as fn,h as yn,i as $}from"./chunk-DSHPAWJQ.js";import{a as S}from"./chunk-NJ3AZYQD.js";import{a as gn,b as Pe,c as $n,d as h,e as An,f as Vn,g as Bn,h as On}from"./chunk-UK2OIPAB.js";import{f as z,k as j,l as we,m as Se,n as Me}from"./chunk-PBNVHBS3.js";import{b as cn,c as ln,d as K,e as un,f as pn,h as dn,j as mn}from"./chunk-VKTFLHCW.js";import{a as on,b as fe,c as f,d as p,e as an,f as ye,g as R,h as ge,i as he,j as E,k as x,l as I}from"./chunk-T3JR2SV6.js";import{a as H}from"./chunk-FUUTGGJS.js";import{a as Nt,b as me,c as M,d as Tt,e as k,f as Lt,g as _t,h as Ut,i as Ft,j as Mt}from"./chunk-2ACBWC7K.js";import{a as Rn}from"./chunk-ODIECDN7.js";import{VersionOperator as Ni}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Or,readFileSync as Dr}from"fs";import{homedir as Nr}from"os";import{join as Tr}from"path";import{execFile as kr}from"child_process";import{promisify as br}from"util";var J=br(kr),q="kanonak",Y="/usr/bin/security",A=class{async get(e){let t=l(e);try{let{stdout:r}=await J(Y,["find-generic-password","-s",q,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
2
- Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if(Ge(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${Z(r)}
1
+ import{a as Rn,b as En,c as xn,d as In,e as Pe}from"./chunk-RWEGPZ23.js";import{a as br,c as Re,e as ze,h as We,i as Ge,j as Pr}from"./chunk-OOR5SVNQ.js";import{a as wn,b as Sn,c as Cn,d as G,e as J,f as l,g as wr}from"./chunk-KGWDV7FW.js";import{a as hr}from"./chunk-NV63IOB7.js";import"./chunk-QHABFCRC.js";import{a as Wt,b as Gt,c as Jt,d as qt,e as Yt,f as on,g as an,h as sn,i as cn}from"./chunk-GMEPM2QQ.js";import{a as Zt,b as Xt,c as Qt,d as b,f as en,g as tn,h as rn}from"./chunk-JYBKSBB5.js";import{a as zt}from"./chunk-4NO7MHS7.js";import{a as Kn,b as $n,c as jn,d as An}from"./chunk-RYOZTXI7.js";import{a as Vn,b as Ln}from"./chunk-PEUTCG3B.js";import{a as On}from"./chunk-PEJALHXK.js";import{a as nn}from"./chunk-SC5M74NM.js";import{A as mr,B as fr,C as yr,D as gr,M as kr,a as Un,b as Fn,c as Mn,d as Hn,e as zn,f as Wn,g as Gn,h as Jn,i as qn,j as Yn,k as Zn,l as Xn,m as Qn,n as er,o as tr,p as nr,q as rr,r as or,s as ar,t as ir,u as sr,v as cr,w as lr,x as ur,y as pr,z as dr}from"./chunk-IZRPJCQW.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as R,c as pn,d as Me,e as K,f as be,g as hn,h as bn,i as j}from"./chunk-DSHPAWJQ.js";import{a as C}from"./chunk-NJ3AZYQD.js";import{a as Pn,b as we,c as Bn,d as k,e as Nn,f as Dn,g as Tn,h as _n}from"./chunk-UK2OIPAB.js";import{f as W,k as A,l as Se,m as Ce,n as He}from"./chunk-PBNVHBS3.js";import{b as dn,c as mn,d as $,e as fn,f as yn,h as gn,j as kn}from"./chunk-VKTFLHCW.js";import{a as ln,b as ye,c as f,d as p,e as un,f as ge,g as E,h as ke,i as he,j as x,k as I,l as v}from"./chunk-T3JR2SV6.js";import{a as z}from"./chunk-FUUTGGJS.js";import{a as Tt,b as fe,c as H,d as _t,e as h,f as Lt,g as Ut,h as Ft,i as Mt,j as Ht}from"./chunk-2ACBWC7K.js";import{a as vn}from"./chunk-ODIECDN7.js";import{VersionOperator as Fi}from"@kanonak-protocol/types/document/models/enums";import{existsSync as _r,readFileSync as Lr}from"fs";import{homedir as Ur}from"os";import{join as Fr}from"path";import{execFile as Sr}from"child_process";import{promisify as Cr}from"util";var q=Cr(Sr),Y="kanonak",Z="/usr/bin/security",V=class{async get(e){let t=l(e);try{let{stdout:r}=await q(Z,["find-generic-password","-s",Y,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
2
+ Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if(Je(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${X(r)}
3
3
  The Keychain may be locked or inaccessible.
4
- Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let r=l(e),o=JSON.stringify(t);try{await J(Y,["add-generic-password","-s",q,"-a",r,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${r}': ${Z(a)}
4
+ Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let r=l(e),o=JSON.stringify(t);try{await q(Z,["add-generic-password","-s",Y,"-a",r,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${r}': ${X(a)}
5
5
  Ensure the Keychain is unlocked and the CLI has write permission.
6
- On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await J(Y,["delete-generic-password","-s",q,"-a",t],{timeout:1e4})}catch(r){if(Ge(r,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${Z(r)}
7
- The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await J(Y,["dump-keychain"],{timeout:1e4}),t=[],r=!1;for(let o of e.split(`
8
- `))if(o.includes(`"svce"<blob>="${q}"`)&&(r=!0),r&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&t.push(a[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${Z(e)}`),[]}}};function Ge(n,e){return typeof n=="object"&&n!==null&&"code"in n&&n.code===e}function Z(n){return n instanceof Error?n.message:String(n)}import{execFile as Pr}from"child_process";import{promisify as wr}from"util";var Sr=wr(Pr),X="kanonak:",V=class{async get(e){let t=X+l(e),r=`
9
- ${ee}
6
+ On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await q(Z,["delete-generic-password","-s",Y,"-a",t],{timeout:1e4})}catch(r){if(Je(r,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${X(r)}
7
+ The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await q(Z,["dump-keychain"],{timeout:1e4}),t=[],r=!1;for(let o of e.split(`
8
+ `))if(o.includes(`"svce"<blob>="${Y}"`)&&(r=!0),r&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&t.push(a[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${X(e)}`),[]}}};function Je(n,e){return typeof n=="object"&&n!==null&&"code"in n&&n.code===e}function X(n){return n instanceof Error?n.message:String(n)}import{execFile as Rr}from"child_process";import{promisify as Er}from"util";var xr=Er(Rr),Q="kanonak:",B=class{async get(e){let t=Q+l(e),r=`
9
+ ${te}
10
10
  $target = [Console]::In.ReadLine()
11
11
  $ptr = [IntPtr]::Zero
12
12
  $result = [CredMan]::CredRead($target, 1, 0, [ref]$ptr)
@@ -18,8 +18,8 @@ try {
18
18
  [System.Text.Encoding]::Unicode.GetString($bytes)
19
19
  } finally {
20
20
  [CredMan]::CredFree($ptr)
21
- }`;try{let{stdout:o}=await Q(r,t),a=o.trim();return a?JSON.parse(a):null}catch{return null}}async store(e,t){let r=X+l(e),o=JSON.stringify(t),a=`
22
- ${ee}
21
+ }`;try{let{stdout:o}=await ee(r,t),a=o.trim();return a?JSON.parse(a):null}catch{return null}}async store(e,t){let r=Q+l(e),o=JSON.stringify(t),a=`
22
+ ${te}
23
23
  $target = [Console]::In.ReadLine()
24
24
  $json = [Console]::In.ReadLine()
25
25
  $bytes = [System.Text.Encoding]::Unicode.GetBytes($json)
@@ -35,13 +35,13 @@ try {
35
35
  if (-not $result) { throw "CredWrite failed" }
36
36
  } finally {
37
37
  [System.Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
38
- }`;try{await Q(a,`${r}
39
- ${o}`)}catch(i){throw new Error(`Windows Credential Manager write failed: ${String(i)}`)}}async remove(e){let t=X+l(e),r=`
40
- ${ee}
38
+ }`;try{await ee(a,`${r}
39
+ ${o}`)}catch(i){throw new Error(`Windows Credential Manager write failed: ${String(i)}`)}}async remove(e){let t=Q+l(e),r=`
40
+ ${te}
41
41
  $target = [Console]::In.ReadLine()
42
- [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await Q(r,t)}catch{}}async list(){let e=`
43
- ${ee}
44
- ${Cr}
42
+ [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await ee(r,t)}catch{}}async list(){let e=`
43
+ ${te}
44
+ ${Ir}
45
45
  $prefix = [Console]::In.ReadLine()
46
46
  $count = 0
47
47
  $pCreds = [IntPtr]::Zero
@@ -55,8 +55,8 @@ if ([CredMan]::CredEnumerate($null, 0, [ref]$count, [ref]$pCreds)) {
55
55
  }
56
56
  }
57
57
  [CredMan]::CredFree($pCreds)
58
- }`;try{let{stdout:t}=await Q(e,X);return t.trim().split(`
59
- `).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function Q(n,e){for(let t of["pwsh","powershell"])try{return await Sr(t,["-NoProfile","-NonInteractive","-Command",n],{timeout:15e3,...e!==void 0&&{input:e}})}catch(r){if(t==="powershell")throw r}throw new Error("Neither pwsh nor powershell found")}var ee=`
58
+ }`;try{let{stdout:t}=await ee(e,Q);return t.trim().split(`
59
+ `).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function ee(n,e){for(let t of["pwsh","powershell"])try{return await xr(t,["-NoProfile","-NonInteractive","-Command",n],{timeout:15e3,...e!==void 0&&{input:e}})}catch(r){if(t==="powershell")throw r}throw new Error("Neither pwsh nor powershell found")}var te=`
60
60
  Add-Type -TypeDefinition @"
61
61
  using System;
62
62
  using System.Runtime.InteropServices;
@@ -87,13 +87,13 @@ public class CredMan {
87
87
  [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
88
88
  public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
89
89
  }
90
- "@`,Cr="";import{execFile as Rr,spawn as Er}from"child_process";import{promisify as xr}from"util";var ne=xr(Rr),te="kanonak",B=class{async get(e){let t=l(e);try{let{stdout:r}=await ne("secret-tool",["lookup","service",te,"publisher",t],{timeout:1e4}),o=r.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let r=l(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=Er("secret-tool",["store","--label",`Kanonak: ${r}`,"service",te,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",c=>{c===0?a():i(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",i)})}async remove(e){let t=l(e);try{await ne("secret-tool",["clear","service",te,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await ne("secret-tool",["search","service",te],{timeout:1e4}),t=[];for(let r of e.split(`
91
- `)){let o=r.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function Re(){try{return await ne("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Je,mkdirSync as qe,readFileSync as Ye,writeFileSync as Ze}from"fs";import{createCipheriv as Ir,createDecipheriv as vr,randomBytes as Xe}from"crypto";import{homedir as Kr}from"os";import{join as Ie,dirname as Qe}from"path";var tt=Ie(Kr(),".config","kanonak"),O=Ie(tt,"keyring.key"),re=Ie(tt,"credentials.enc"),et="aes-256-gcm",Ee=32,b=12,xe=16,D=class{async get(e){let t=this.loadStore(),r=l(e);return t[r]??null}async store(e,t){let r=this.loadStore(),o=l(e);r[o]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=l(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Je(re))return{};try{let e=this.getOrCreateKey(),t=Ye(re);if(t.length<b+xe)return{};let r=t.subarray(0,b),o=t.subarray(b,b+xe),a=t.subarray(b+xe),i=vr(et,e,r);i.setAuthTag(o);let s=Buffer.concat([i.update(a),i.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),r=Xe(b),o=Ir(et,t,r),a=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([o.update(a),o.final()]),s=o.getAuthTag(),c=Buffer.concat([r,s,i]);qe(Qe(re),{recursive:!0}),Ze(re,c,{mode:384})}getOrCreateKey(){if(Je(O)){let t=Ye(O);if(t.length!==Ee)throw new Error(`Credential keyring key is corrupted (expected ${Ee} bytes, got ${t.length}). Delete ${O} and re-authenticate.`);return t}let e=Xe(Ee);return qe(Qe(O),{recursive:!0}),Ze(O,e,{mode:384}),e}};import{execFile as $r}from"child_process";import{promisify as jr}from"util";var Ar=jr($r),nt=3e4,N=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(r){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${oe(r)}
90
+ "@`,Ir="";import{execFile as vr,spawn as Kr}from"child_process";import{promisify as $r}from"util";var re=$r(vr),ne="kanonak",O=class{async get(e){let t=l(e);try{let{stdout:r}=await re("secret-tool",["lookup","service",ne,"publisher",t],{timeout:1e4}),o=r.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let r=l(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=Kr("secret-tool",["store","--label",`Kanonak: ${r}`,"service",ne,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",c=>{c===0?a():i(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",i)})}async remove(e){let t=l(e);try{await re("secret-tool",["clear","service",ne,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await re("secret-tool",["search","service",ne],{timeout:1e4}),t=[];for(let r of e.split(`
91
+ `)){let o=r.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function Ee(){try{return await re("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as qe,mkdirSync as Ye,readFileSync as Ze,writeFileSync as Xe}from"fs";import{createCipheriv as jr,createDecipheriv as Ar,randomBytes as Qe}from"crypto";import{homedir as Vr}from"os";import{join as ve,dirname as et}from"path";var nt=ve(Vr(),".config","kanonak"),N=ve(nt,"keyring.key"),oe=ve(nt,"credentials.enc"),tt="aes-256-gcm",xe=32,P=12,Ie=16,D=class{async get(e){let t=this.loadStore(),r=l(e);return t[r]??null}async store(e,t){let r=this.loadStore(),o=l(e);r[o]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=l(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!qe(oe))return{};try{let e=this.getOrCreateKey(),t=Ze(oe);if(t.length<P+Ie)return{};let r=t.subarray(0,P),o=t.subarray(P,P+Ie),a=t.subarray(P+Ie),i=Ar(tt,e,r);i.setAuthTag(o);let s=Buffer.concat([i.update(a),i.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),r=Qe(P),o=jr(tt,t,r),a=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([o.update(a),o.final()]),s=o.getAuthTag(),c=Buffer.concat([r,s,i]);Ye(et(oe),{recursive:!0}),Xe(oe,c,{mode:384})}getOrCreateKey(){if(qe(N)){let t=Ze(N);if(t.length!==xe)throw new Error(`Credential keyring key is corrupted (expected ${xe} bytes, got ${t.length}). Delete ${N} and re-authenticate.`);return t}let e=Qe(xe);return Ye(et(N),{recursive:!0}),Xe(N,e,{mode:384}),e}};import{execFile as Br}from"child_process";import{promisify as Or}from"util";var Nr=Or(Br),rt=3e4,T=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(r){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${ae(r)}
92
92
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
93
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let r=l(e);try{await this.runHelper("store",{publisher:r,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${r}': ${oe(o)}
94
- Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${oe(r)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${oe(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await Ar(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:nt});return r}catch(r){throw Vr(r)?new Error(`Credential helper not found at '${this.helperPath}'.
95
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Br(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${nt/1e3}s on '${e}'.
96
- The helper may be waiting for authentication to an external vault.`):r}}};function oe(n){return n instanceof Error?n.message:String(n)}function Vr(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"}function Br(n){return n instanceof Error&&"killed"in n&&n.killed}var ve=Tr(Nr(),".kanonak","config.json"),ae=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=Lr(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!G(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=_r();return e.credentialHelper?new N(e.credentialHelper):process.platform==="darwin"?new A:process.platform==="win32"?new V:await Re()?new B:new D}};function Lr(n){let t="KANONAK_TOKEN_"+l(n).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function _r(){if(!Or(ve))return{};try{return JSON.parse(Dr(ve,"utf-8"))}catch(n){let e=n instanceof Error?n.message:String(n);return console.warn(` Warning: Failed to parse ${ve}: ${e}
97
- Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Ur,createPrivateKey as Fr,generateKeyPairSync as Mr,randomUUID as Hr,sign as zr}from"crypto";function ot(){let{publicKey:n,privateKey:e}=Mr("ec",{namedCurve:"P-256"});return{publicKey:n.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function T(n,e,t,r,o,a){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Hr(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Ur("sha256").update(o).digest("base64url")),a&&(s.nonce=a),Wr(i,s,n)}function at(n){return!n||n.length===0?!1:n.some(e=>e.toUpperCase()==="ES256")}function Wr(n,e,t){let r=rt(JSON.stringify(n)),o=rt(JSON.stringify(e)),a=`${r}.${o}`,i=Fr({key:t,format:"jwk"}),c=zr("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${c}`}function rt(n){return Buffer.from(n,"utf-8").toString("base64url")}function it(n){let e=new Map;return async(t,r,o="GET")=>{if(!n)return fetch(t,{method:o});let a=await n.getCredential(r);if(!a?.accessToken)return fetch(t,{method:o});W(a)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let i={};if(a.dpopKeyPair){let c=e.get(r);try{let u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.Authorization=`DPoP ${a.accessToken}`,i.DPoP=u}catch(u){let d=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${r}': ${d}
98
- The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${a.accessToken}`}}else i.Authorization=`Bearer ${a.accessToken}`;let s=await fetch(t,{method:o,headers:i});if(s.status===401&&a.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(r,c);try{let u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=u,s=await fetch(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as Gr,writeFileSync as Jr,existsSync as qr}from"fs";import{createHash as Yr}from"crypto";import st from"js-yaml";var ct="kanonak.lock",Zr=`# This file is generated by Kanonak CLI. Do not edit manually.
99
- `;function lt(n=ct){if(!qr(n))return null;let e=Gr(n,"utf-8"),t=st.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function ut(n,e=ct){n.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(n.packages).sort())t[o]=n.packages[o];n.packages=t;let r=st.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Jr(e,Zr+r,"utf-8")}function pt(n){return`sha256:${Yr("sha256").update(n).digest("hex")}`}import*as Ve from"js-yaml";import{createHash as Qr}from"crypto";function Ke(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}function $e(n){return n.subjects.map(e=>{let t=new f,r=e.uri.lastIndexOf("/");return t.namespace=e.uri.slice(0,r),t.name=e.uri.slice(r+1),t.statement=(e.statements??[]).map(o=>mt(o.predicate,o.value)),t})}function dt(n,e,t){let r=new R;return r.predicate=p.parse(n),r.object=t,e&&(r.carrier=e,r.lexical=t),r}function mt(n,e){if("lit"in e)return dt(n,v(H.parse(e.datatype)),e.lit);if("raw"in e)return dt(n,void 0,e.raw);if("ref"in e){let t=new E;return t.predicate=p.parse(n),t.object=p.parse(e.ref),t}if("embed"in e){let t=new x;return t.predicate=p.parse(n),t.object=ft(e.embed),t}if("list"in e){let t=new I;return t.predicate=p.parse(n),t.object=e.list.map(Xr),t}throw new Error(`canonical input: unknown value shape ${JSON.stringify(e)}`)}function ft(n){let e=new y;return n.name&&(e.name=n.name),e.statement=(n.statements??[]).map(t=>mt(t.predicate,t.value)),e}function Xr(n){if("ref"in n)return p.parse(n.ref);if("embed"in n)return ft(n.embed);let e=new C;if("lit"in n){e.value=n.lit;let t=v(H.parse(n.datatype));t&&(e.carrier=t,e.lexical=n.lit)}else if("raw"in n)e.value=n.raw;else throw new Error(`canonical input: unknown list item shape ${JSON.stringify(n)}`);return e}var gt="1",yt=new TextEncoder;function ht(n,e){let t=yt.encode(n),r=yt.encode(e),o=Math.min(t.length,r.length);for(let a=0;a<o;a++)if(t[a]!==r[a])return t[a]-r[a];return t.length-r.length}function je(n){let e=Ke(n)?$e(n):n,t=[];for(let o of e)o instanceof f&&t.push(eo(o));return t.sort((o,a)=>ht(o.uri,a.uri)),JSON.stringify({subjects:t})}function ie(n){let e=Ke(n)?$e(n):n,t=je(e);return`sha256:${Qr("sha256").update(t,"utf8").digest("hex")}`}function eo(n){let e=io(n),t=Ae(n.statement);return{uri:e,statements:t}}function Ae(n){let e=[];for(let t of n){let r=to(t);r&&e.push(r)}return e.sort((t,r)=>ht(t.predicate,r.predicate)),e}function to(n){let e=ao(n);if(!e)return;let t=no(n);if(t)return oo(e,t)}function no(n){if(n instanceof ye&&n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.object))};if(n instanceof R)return{type:"string",value:n.object};if(n instanceof ge)return{type:"number",value:wt(n.object)};if(n instanceof he)return{type:"boolean",value:n.object};if(n instanceof E)return{type:"ref",value:bt(n.object)};if(n instanceof x){let e=n.object;return kt(e)}if(n instanceof I)return{type:"list",items:n.object.map(ro)}}function kt(n){let e=Ae(n.statement);return n.name&&n.name.length>0?{type:"embedded",name:n.name,statements:e}:{type:"embedded",statements:e}}function ro(n){if(n instanceof p)return{type:"ref",value:bt(n)};if(n instanceof y)return kt(n);if(n instanceof C){if(n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.value))};let e=n.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:wt(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(n instanceof fe)return{type:"embedded",statements:Ae(n.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${n.constructor?.name??typeof n}); add canonicalization support before hashing data that contains it`)}function oo(n,e){switch(e.type){case"string":return{predicate:n,type:"string",value:e.value};case"number":return{predicate:n,type:"number",value:e.value};case"boolean":return{predicate:n,type:"boolean",value:e.value};case"typed":return{predicate:n,type:"typed",carrier:e.carrier,value:e.value};case"ref":return{predicate:n,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:n,type:"embedded",name:e.name,statements:e.statements}:{predicate:n,type:"embedded",statements:e.statements};case"list":return{predicate:n,type:"list",items:e.items}}}function ao(n){let e=n.predicate;if(e)return Pt(e.subject)}function io(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function bt(n){return Pt(n.subject)}function Pt(n){let e=n.version;return e&&typeof e.major=="number"?`${n.publisher}/${n.package_}@${e.major}.${e.minor}.${e.patch}/${n.name}`:`${n.publisher}/${n.package_}/${n.name}`}function wt(n){if(Number.isNaN(n))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(n))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(n,-0)?"0":String(n)}import{VersionOperator as St}from"@kanonak-protocol/types/document/models/enums";var so="0.0.0",P=class{constructor(e,t=new S,r){this.repository=e;this.parser=t;this.objectParser=r??new $(this.parser)}repository;parser;objectParser;imports(){return new L}serializeValue(e,t){return Et(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Be(r),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=r),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:Rt(s),contentHash:r,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=o),Object.assign(r,e.header??{}),r.imports=t;let a={[e.name]:r,...e.body},i=this.dump(a),s={yaml:i,byteCount:Rt(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ve.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[Ct]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(Ve.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Me(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==Ct);for(let u of c)u.namespace="ephemeral";return ie(c)}},Ct="__pkgbuilder_probe__";function Rt(n){return new TextEncoder().encode(n).length}function Be(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var L=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=St.Major){let i=`${e}/${t}@${r}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:a}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,o){return`${this.ensure(e,t,so,o??t,St.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let o=e.get(r.publisher)??[];o.push(r),e.set(r.publisher,o)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:me(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=_(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function Et(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof p)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>Et(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(co(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function _(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function co(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var se=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,o){let a=`${t}/${r}@${k(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,r,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let o={operator:t.versionOperator,version:t.version},a=await r.resolveVersion(e,t.packageName,o);return a?this.produceCached(r,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=Pe(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let o=r.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Oe={async authorize(){return{allowed:!0}}},De={async record(){}},U=class extends Error{constructor(t,r){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},ce=class{inner;ctx;policy;meter;constructor(e,t,r=Oe,o=De){this.inner=e,this.ctx=t,this.policy=r,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let o={publisher:e,package_:t,version:r};await this.assertAllowed(o);let a=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new U(e,t.reason)}};var m="kanonak.org",g="view",xt="core-kanonak",lo={publisher:m,package_:g,name:"rootView"},uo={publisher:m,package_:g,name:"bind"},po={publisher:m,package_:g,name:"produces"},mo={publisher:m,package_:g,name:"projections"},fo={publisher:m,package_:g,name:"where"},yo={publisher:m,package_:g,name:"value"},go={publisher:m,package_:g,name:"as"},le=class{constructor(e,t=new S){this.repository=e;this.parser=t;this.objectParser=new $(this.parser),this.builder=new P(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(r,e),a=j(o,uo);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=j(o,po);if(!i)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=ho(o),c=It(r,m,xt),u=It(r,m,g),d=this.builder.imports(),ue=d.ensure(m,xt,c,"ck"),Kt=d.ensure(m,g,u,"v"),$t=d.ref(i),jt=new We(this.repository,this.parser,this.objectParser),Ne=new He(jt,r),At=this.readProjections(r,o),Vt=Po(o,fo),Bt=this.findInstances(r,a,await this.reason(t)),Te={},Ot=new Set;for(let F of Bt){if(!await this.passesWhere(Ne,r,Vt,F))continue;let de={type:$t};for(let _e of At){let Dt=await this.evaluateValue(Ne,r,_e.value,F),Ue=this.builder.serializeValue(vt(Dt),d);Ue!==void 0&&(de[d.ref(_e.as)]=Ue)}let Le=h(F);Le&&(de[`${Kt}.derivedFrom`]=d.ref(Le)),Te[this.rowName(F,Ot)]=de}let pe={};t.resolvedAt&&(pe[`${ue}.resolvedAt`]=t.resolvedAt),t.invocationId&&(pe[`${ue}.id`]=t.invocationId);let w=await this.builder.buildContentAddressed({publisher:s,book:d,body:Te,contentHashProperty:`${ue}.contentHash`,header:pe});return{yaml:w.yaml,contentHash:w.contentHash,packageName:w.packageName,publisher:w.publisher,rowCount:w.resourceCount}}resolveView(e,t){let r=z(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=j(r,lo);if(o){let a=z(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return r}readProjections(e,t){let r=[];for(let o of Se(t,mo)){let a=o instanceof y?o:o instanceof p?z(e,o.subject):void 0;if(!a)continue;let i=we(a,yo),s=j(a,go);i&&s&&r.push({value:i,as:s})}return r}async reason(e){return new be({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let o=bo(e),a=[],i=new Set;for(let s of r.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let c=o.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=K(h(s)),d=K(h(c));return u<d?-1:u>d?1:0}),a}async passesWhere(e,t,r,o){for(let a of r){let i=await this.evaluateValue(e,t,a,o);if(!wo(i))return!1}return!0}async evaluateValue(e,t,r,o){let a=ze(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let r=_(e.name)||"row",o=r,a=2;for(;t.has(o);)o=`${r}-${a++}`;return t.add(o),o}};function vt(n){return Ce(n)?n.value:Array.isArray(n)?n.map(vt):n}function ho(n){let e=h(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function It(n,e,t){let r=ko(n,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function ko(n,e,t){let r;for(let o of n){if(!(o instanceof f))continue;let a=h(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!r||M(a.version,r)>0)&&(r=a.version)}return r?k(r):void 0}function bo(n){let e=new Map,t=new Map;for(let r of n){if(!(r instanceof f))continue;let o=h(r);if(!o||!o.version)continue;let a=K(o),i=t.get(a);(!i||M(o.version,i)>0)&&(t.set(a,o.version),e.set(a,r))}return e}function Po(n,e){let t=we(n,e);return t?[t]:Se(n,e).filter(r=>r instanceof y)}function wo(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Ce(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{ar as AmbiguousReferenceRule,he as BooleanStatement,gt as CANONICAL_FORM_VERSION,Fe as Carrier,pr as ClassDefinitionRule,Yn as ClassHierarchyCycleRule,Gt as CompositeKanonakDocumentRepository,ae as CredentialStore,fe as DefinedKanonak,rr as DefinitionPropertyReferenceRule,Wt as DocumentLocation,kn as EdgeType,y as EmbeddedKanonak,Gn as EmbeddedKanonakTypeRule,x as EmbeddedStatement,U as EntitlementDeniedError,ce as EntitlementProducer,zt as FileSystemKanonakDocumentRepository,Rn as GitIgnoreFilter,bn as GraphBuilder,Qt as HttpKanonakDocumentRepository,L as ImportBook,Jn as ImportExistenceRule,Ht as InMemoryKanonakDocumentRepository,nr as InstancePropertyReferenceRule,on as Kanonak,xn as KanonakDocumentPositions,$ as KanonakObjectParser,mr as KanonakObjectValidator,S as KanonakParser,H as KanonakUri,Kn as KanonakUriBuilder,jn as KanonakUrlResolver,mn as KanonakVocabulary,I as ListStatement,C as LiteralKanonak,en as LocalFirstRepository,tn as LockAwareRepository,gr as LookRenderer,dr as MarkdownLinkRule,sn as MarkdownStatement,tr as NamespaceImportCycleRule,Fn as NamespacePrefixRule,hn as NodeType,ge as NumberStatement,Sn as OWL_RL_CLASSIFICATION_RULES,sr as ObjectPropertyImportRule,cr as ObjectPropertyValueValidationRule,Ln as OntologyValidationError,Nn as OntologyValidationResult,P as PackageBuilder,Wn as PackageHeaderRule,se as ProducerRepository,lr as PropertyDomainRule,Zn as PropertyHierarchyCycleRule,En as PropertyMetadata,ir as PropertyRangeReferenceRule,Xn as PropertyRangeRequiredRule,Hn as PropertyTypeSpecificityRule,ur as PropertyValueTypeRule,Yt as PublisherConfigResolver,Zt as PublisherIndex,wn as RDFS_RULES,be as Reasoner,Cn as ReasoningResult,p as ReferenceKanonak,E as ReferenceStatement,qt as RepositoryFactory,Mn as ResourceNamingRule,cn as ResourceResolver,gn as ResourceTypeClassifier,ye as ScalarStatement,an as Statement,R as StringStatement,Qn as SubClassOfReferenceRule,er as SubPropertyOfReferenceRule,f as SubjectKanonak,zn as SubjectKanonakTypeRequiredRule,Pn as TripleStore,ln as TypeResolver,qn as UnresolvedReferenceRule,Un as ValidationCache,_n as ValidationContext,Tn as ValidationSeverity,Ni as VersionOperator,le as ViewMaterializer,or as XsdImportRule,Oe as allowAllPolicy,Xt as assertPackageIdentity,rn as buildLocalFirstRepository,hr as buildOntologyModel,je as canonicalForm,ie as canonicalHash,v as carrierOf,nn as collectKanonakFiles,M as compareVersions,pt as computeIntegrity,Be as contentAddressedName,On as contextTypesOf,it as createAuthenticatedFetch,T as createDPoPProof,Lt as createVersion,yn as extractMarkdownLinks,fr as findDerivation,Dn as findInstancesByType,fn as findMalformedReferences,vn as findMarkdownLinkAt,$n as formatKanonakAddress,k as formatVersion,ot as generateDPoPKeyPair,Jt as getGlobalCachePath,G as hasValidToken,Ut as isCompatibleVersion,W as isExpired,Ft as isMajorCompatible,lt as loadLockFile,un as makeUriKey,De as noopMeter,l as normalizeHost,Pe as parseKanonakAddress,_t as parseVersionString,In as parseWithPositions,Mt as pickHighestDocument,Vn as propertiesInScope,yr as resolveDisplayValue,Bn as resolvePropertyStep,_ as sanitizeName,ut as saveLockFile,at as serverSupportsDPoP,h as subjectUri,An as superClassChain,pn as tripleKey,K as uriKey,dn as uriTriple,Nt as versionOperatorFromChar,me as versionOperatorToChar,Tt as versionsEqual};
93
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let r=l(e);try{await this.runHelper("store",{publisher:r,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${r}': ${ae(o)}
94
+ Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${ae(r)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${ae(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await Nr(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:rt});return r}catch(r){throw Dr(r)?new Error(`Credential helper not found at '${this.helperPath}'.
95
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Tr(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${rt/1e3}s on '${e}'.
96
+ The helper may be waiting for authentication to an external vault.`):r}}};function ae(n){return n instanceof Error?n.message:String(n)}function Dr(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"}function Tr(n){return n instanceof Error&&"killed"in n&&n.killed}var Ke=Fr(Ur(),".kanonak","config.json"),ie=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=Mr(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!J(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=Hr();return e.credentialHelper?new T(e.credentialHelper):process.platform==="darwin"?new V:process.platform==="win32"?new B:await Ee()?new O:new D}};function Mr(n){let t="KANONAK_TOKEN_"+l(n).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Hr(){if(!_r(Ke))return{};try{return JSON.parse(Lr(Ke,"utf-8"))}catch(n){let e=n instanceof Error?n.message:String(n);return console.warn(` Warning: Failed to parse ${Ke}: ${e}
97
+ Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as zr,createPrivateKey as Wr,generateKeyPairSync as Gr,randomUUID as Jr,sign as qr}from"crypto";function at(){let{publicKey:n,privateKey:e}=Gr("ec",{namedCurve:"P-256"});return{publicKey:n.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function _(n,e,t,r,o,a){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Jr(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=zr("sha256").update(o).digest("base64url")),a&&(s.nonce=a),Yr(i,s,n)}function it(n){return!n||n.length===0?!1:n.some(e=>e.toUpperCase()==="ES256")}function Yr(n,e,t){let r=ot(JSON.stringify(n)),o=ot(JSON.stringify(e)),a=`${r}.${o}`,i=Wr({key:t,format:"jwk"}),c=qr("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${c}`}function ot(n){return Buffer.from(n,"utf-8").toString("base64url")}function st(n){let e=new Map;return async(t,r,o="GET")=>{if(!n)return b(t,{method:o});let a=await n.getCredential(r);if(!a?.accessToken)return b(t,{method:o});G(a)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let i={};if(a.dpopKeyPair){let c=e.get(r);try{let u=_(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.Authorization=`DPoP ${a.accessToken}`,i.DPoP=u}catch(u){let d=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${r}': ${d}
98
+ The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${a.accessToken}`}}else i.Authorization=`Bearer ${a.accessToken}`;let s=await b(t,{method:o,headers:i});if(s.status===401&&a.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(r,c);try{let u=_(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=u,s=await b(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as Zr,writeFileSync as Xr,existsSync as Qr}from"fs";import{createHash as eo}from"crypto";import ct from"js-yaml";var lt="kanonak.lock",to=`# This file is generated by Kanonak CLI. Do not edit manually.
99
+ `;function ut(n=lt){if(!Qr(n))return null;let e=Zr(n,"utf-8"),t=ct.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function pt(n,e=lt){n.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(n.packages).sort())t[o]=n.packages[o];n.packages=t;let r=ct.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Xr(e,to+r,"utf-8")}function dt(n){return`sha256:${eo("sha256").update(n).digest("hex")}`}import*as Be from"js-yaml";import{createHash as ro}from"crypto";function $e(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}function je(n){return n.subjects.map(e=>{let t=new f,r=e.uri.lastIndexOf("/");return t.namespace=e.uri.slice(0,r),t.name=e.uri.slice(r+1),t.statement=(e.statements??[]).map(o=>ft(o.predicate,o.value)),t})}function mt(n,e,t){let r=new E;return r.predicate=p.parse(n),r.object=t,e&&(r.carrier=e,r.lexical=t),r}function ft(n,e){if("lit"in e)return mt(n,K(z.parse(e.datatype)),e.lit);if("raw"in e)return mt(n,void 0,e.raw);if("ref"in e){let t=new x;return t.predicate=p.parse(n),t.object=p.parse(e.ref),t}if("embed"in e){let t=new I;return t.predicate=p.parse(n),t.object=yt(e.embed),t}if("list"in e){let t=new v;return t.predicate=p.parse(n),t.object=e.list.map(no),t}throw new Error(`canonical input: unknown value shape ${JSON.stringify(e)}`)}function yt(n){let e=new y;return n.name&&(e.name=n.name),e.statement=(n.statements??[]).map(t=>ft(t.predicate,t.value)),e}function no(n){if("ref"in n)return p.parse(n.ref);if("embed"in n)return yt(n.embed);let e=new R;if("lit"in n){e.value=n.lit;let t=K(z.parse(n.datatype));t&&(e.carrier=t,e.lexical=n.lit)}else if("raw"in n)e.value=n.raw;else throw new Error(`canonical input: unknown list item shape ${JSON.stringify(n)}`);return e}var kt="1",gt=new TextEncoder;function ht(n,e){let t=gt.encode(n),r=gt.encode(e),o=Math.min(t.length,r.length);for(let a=0;a<o;a++)if(t[a]!==r[a])return t[a]-r[a];return t.length-r.length}function Ae(n){let e=$e(n)?je(n):n,t=[];for(let o of e)o instanceof f&&t.push(oo(o));return t.sort((o,a)=>ht(o.uri,a.uri)),JSON.stringify({subjects:t})}function se(n){let e=$e(n)?je(n):n,t=Ae(e);return`sha256:${ro("sha256").update(t,"utf8").digest("hex")}`}function oo(n){let e=uo(n),t=Ve(n.statement);return{uri:e,statements:t}}function Ve(n){let e=[];for(let t of n){let r=ao(t);r&&e.push(r)}return e.sort((t,r)=>ht(t.predicate,r.predicate)),e}function ao(n){let e=lo(n);if(!e)return;let t=io(n);if(t)return co(e,t)}function io(n){if(n instanceof ge&&n.carrier)return{type:"typed",carrier:n.carrier,value:be(n.carrier,n.lexical??String(n.object))};if(n instanceof E)return{type:"string",value:n.object};if(n instanceof ke)return{type:"number",value:St(n.object)};if(n instanceof he)return{type:"boolean",value:n.object};if(n instanceof x)return{type:"ref",value:Pt(n.object)};if(n instanceof I){let e=n.object;return bt(e)}if(n instanceof v)return{type:"list",items:n.object.map(so)}}function bt(n){let e=Ve(n.statement);return n.name&&n.name.length>0?{type:"embedded",name:n.name,statements:e}:{type:"embedded",statements:e}}function so(n){if(n instanceof p)return{type:"ref",value:Pt(n)};if(n instanceof y)return bt(n);if(n instanceof R){if(n.carrier)return{type:"typed",carrier:n.carrier,value:be(n.carrier,n.lexical??String(n.value))};let e=n.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:St(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(n instanceof ye)return{type:"embedded",statements:Ve(n.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${n.constructor?.name??typeof n}); add canonicalization support before hashing data that contains it`)}function co(n,e){switch(e.type){case"string":return{predicate:n,type:"string",value:e.value};case"number":return{predicate:n,type:"number",value:e.value};case"boolean":return{predicate:n,type:"boolean",value:e.value};case"typed":return{predicate:n,type:"typed",carrier:e.carrier,value:e.value};case"ref":return{predicate:n,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:n,type:"embedded",name:e.name,statements:e.statements}:{predicate:n,type:"embedded",statements:e.statements};case"list":return{predicate:n,type:"list",items:e.items}}}function lo(n){let e=n.predicate;if(e)return wt(e.subject)}function uo(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function Pt(n){return wt(n.subject)}function wt(n){let e=n.version;return e&&typeof e.major=="number"?`${n.publisher}/${n.package_}@${e.major}.${e.minor}.${e.patch}/${n.name}`:`${n.publisher}/${n.package_}/${n.name}`}function St(n){if(Number.isNaN(n))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(n))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(n,-0)?"0":String(n)}import{VersionOperator as Ct}from"@kanonak-protocol/types/document/models/enums";var po="0.0.0",w=class{constructor(e,t=new C,r){this.repository=e;this.parser=t;this.objectParser=r??new j(this.parser)}repository;parser;objectParser;imports(){return new L}serializeValue(e,t){return xt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Oe(r),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=r),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:Et(s),contentHash:r,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=o),Object.assign(r,e.header??{}),r.imports=t;let a={[e.name]:r,...e.body},i=this.dump(a),s={yaml:i,byteCount:Et(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Be.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[Rt]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(Be.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new He(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==Rt);for(let u of c)u.namespace="ephemeral";return se(c)}},Rt="__pkgbuilder_probe__";function Et(n){return new TextEncoder().encode(n).length}function Oe(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var L=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=Ct.Major){let i=`${e}/${t}@${r}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:a}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,h(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,o){return`${this.ensure(e,t,po,o??t,Ct.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let o=e.get(r.publisher)??[];o.push(r),e.set(r.publisher,o)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:fe(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=U(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function xt(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof p)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>xt(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(mo(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 U(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function mo(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var ce=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,o){let a=`${t}/${r}@${h(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,r,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let o={operator:t.versionOperator,version:t.version},a=await r.resolveVersion(e,t.packageName,o);return a?this.produceCached(r,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=we(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let o=r.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Ne={async authorize(){return{allowed:!0}}},De={async record(){}},F=class extends Error{constructor(t,r){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},le=class{inner;ctx;policy;meter;constructor(e,t,r=Ne,o=De){this.inner=e,this.ctx=t,this.policy=r,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let o={publisher:e,package_:t,version:r};await this.assertAllowed(o);let a=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new F(e,t.reason)}};var m="kanonak.org",g="view",It="core-kanonak",fo={publisher:m,package_:g,name:"rootView"},yo={publisher:m,package_:g,name:"bind"},go={publisher:m,package_:g,name:"produces"},ko={publisher:m,package_:g,name:"projections"},ho={publisher:m,package_:g,name:"where"},bo={publisher:m,package_:g,name:"value"},Po={publisher:m,package_:g,name:"as"},ue=class{constructor(e,t=new C){this.repository=e;this.parser=t;this.objectParser=new j(this.parser),this.builder=new w(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(r,e),a=A(o,yo);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=A(o,go);if(!i)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=wo(o),c=vt(r,m,It),u=vt(r,m,g),d=this.builder.imports(),pe=d.ensure(m,It,c,"ck"),$t=d.ensure(m,g,u,"v"),jt=d.ref(i),At=new Ge(this.repository,this.parser,this.objectParser),Te=new ze(At,r),Vt=this.readProjections(r,o),Bt=Ro(o,ho),Ot=this.findInstances(r,a,await this.reason(t)),_e={},Nt=new Set;for(let M of Ot){if(!await this.passesWhere(Te,r,Bt,M))continue;let me={type:jt};for(let Ue of Vt){let Dt=await this.evaluateValue(Te,r,Ue.value,M),Fe=this.builder.serializeValue(Kt(Dt),d);Fe!==void 0&&(me[d.ref(Ue.as)]=Fe)}let Le=k(M);Le&&(me[`${$t}.derivedFrom`]=d.ref(Le)),_e[this.rowName(M,Nt)]=me}let de={};t.resolvedAt&&(de[`${pe}.resolvedAt`]=t.resolvedAt),t.invocationId&&(de[`${pe}.id`]=t.invocationId);let S=await this.builder.buildContentAddressed({publisher:s,book:d,body:_e,contentHashProperty:`${pe}.contentHash`,header:de});return{yaml:S.yaml,contentHash:S.contentHash,packageName:S.packageName,publisher:S.publisher,rowCount:S.resourceCount}}resolveView(e,t){let r=W(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=A(r,fo);if(o){let a=W(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return r}readProjections(e,t){let r=[];for(let o of Ce(t,ko)){let a=o instanceof y?o:o instanceof p?W(e,o.subject):void 0;if(!a)continue;let i=Se(a,bo),s=A(a,Po);i&&s&&r.push({value:i,as:s})}return r}async reason(e){return new Pe({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let o=Co(e),a=[],i=new Set;for(let s of r.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let c=o.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=$(k(s)),d=$(k(c));return u<d?-1:u>d?1:0}),a}async passesWhere(e,t,r,o){for(let a of r){let i=await this.evaluateValue(e,t,a,o);if(!Eo(i))return!1}return!0}async evaluateValue(e,t,r,o){let a=We(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let r=U(e.name)||"row",o=r,a=2;for(;t.has(o);)o=`${r}-${a++}`;return t.add(o),o}};function Kt(n){return Re(n)?n.value:Array.isArray(n)?n.map(Kt):n}function wo(n){let e=k(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function vt(n,e,t){let r=So(n,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function So(n,e,t){let r;for(let o of n){if(!(o instanceof f))continue;let a=k(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!r||H(a.version,r)>0)&&(r=a.version)}return r?h(r):void 0}function Co(n){let e=new Map,t=new Map;for(let r of n){if(!(r instanceof f))continue;let o=k(r);if(!o||!o.version)continue;let a=$(o),i=t.get(a);(!i||H(o.version,i)>0)&&(t.set(a,o.version),e.set(a,r))}return e}function Ro(n,e){let t=Se(n,e);return t?[t]:Ce(n,e).filter(r=>r instanceof y)}function Eo(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Re(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{lr as AmbiguousReferenceRule,he as BooleanStatement,kt as CANONICAL_FORM_VERSION,Me as Carrier,yr as ClassDefinitionRule,er as ClassHierarchyCycleRule,Jt as CompositeKanonakDocumentRepository,ie as CredentialStore,ye as DefinedKanonak,sr as DefinitionPropertyReferenceRule,Gt as DocumentLocation,Sn as EdgeType,y as EmbeddedKanonak,Zn as EmbeddedKanonakTypeRule,I as EmbeddedStatement,F as EntitlementDeniedError,le as EntitlementProducer,Wt as FileSystemKanonakDocumentRepository,vn as GitIgnoreFilter,Cn as GraphBuilder,rn as HttpKanonakDocumentRepository,L as ImportBook,Xn as ImportExistenceRule,zt as InMemoryKanonakDocumentRepository,ir as InstancePropertyReferenceRule,Zt as KANONAK_USER_AGENT,ln as Kanonak,$n as KanonakDocumentPositions,j as KanonakObjectParser,kr as KanonakObjectValidator,C as KanonakParser,z as KanonakUri,Vn as KanonakUriBuilder,On as KanonakUrlResolver,kn as KanonakVocabulary,v as ListStatement,R as LiteralKanonak,on as LocalFirstRepository,an as LockAwareRepository,Pr as LookRenderer,gr as MarkdownLinkRule,pn as MarkdownStatement,ar as NamespaceImportCycleRule,Wn as NamespacePrefixRule,wn as NodeType,ke as NumberStatement,xn as OWL_RL_CLASSIFICATION_RULES,pr as ObjectPropertyImportRule,dr as ObjectPropertyValueValidationRule,Mn as OntologyValidationError,Un as OntologyValidationResult,w as PackageBuilder,Yn as PackageHeaderRule,ce as ProducerRepository,mr as PropertyDomainRule,tr as PropertyHierarchyCycleRule,Kn as PropertyMetadata,ur as PropertyRangeReferenceRule,nr as PropertyRangeRequiredRule,Jn as PropertyTypeSpecificityRule,fr as PropertyValueTypeRule,en as PublisherConfigResolver,tn as PublisherIndex,En as RDFS_RULES,Pe as Reasoner,In as ReasoningResult,p as ReferenceKanonak,x as ReferenceStatement,Yt as RepositoryFactory,Gn as ResourceNamingRule,dn as ResourceResolver,Pn as ResourceTypeClassifier,ge as ScalarStatement,un as Statement,E as StringStatement,rr as SubClassOfReferenceRule,or as SubPropertyOfReferenceRule,f as SubjectKanonak,qn as SubjectKanonakTypeRequiredRule,Rn as TripleStore,mn as TypeResolver,Qn as UnresolvedReferenceRule,zn as ValidationCache,Hn as ValidationContext,Fn as ValidationSeverity,Fi as VersionOperator,ue as ViewMaterializer,cr as XsdImportRule,Ne as allowAllPolicy,nn as assertPackageIdentity,cn as buildLocalFirstRepository,wr as buildOntologyModel,Ae as canonicalForm,se as canonicalHash,K as carrierOf,sn as collectKanonakFiles,H as compareVersions,dt as computeIntegrity,Oe as contentAddressedName,_n as contextTypesOf,st as createAuthenticatedFetch,_ as createDPoPProof,Lt as createVersion,bn as extractMarkdownLinks,hr as findDerivation,Ln as findInstancesByType,hn as findMalformedReferences,An as findMarkdownLinkAt,Bn as formatKanonakAddress,h as formatVersion,at as generateDPoPKeyPair,qt as getGlobalCachePath,Qt as getKanonakUserAgent,J as hasValidToken,Ft as isCompatibleVersion,G as isExpired,Mt as isMajorCompatible,b as kanonakFetch,ut as loadLockFile,fn as makeUriKey,De as noopMeter,l as normalizeHost,we as parseKanonakAddress,Ut as parseVersionString,jn as parseWithPositions,Ht as pickHighestDocument,Dn as propertiesInScope,br as resolveDisplayValue,Tn as resolvePropertyStep,U as sanitizeName,pt as saveLockFile,it as serverSupportsDPoP,Xt as setKanonakUserAgent,k as subjectUri,Nn as superClassChain,yn as tripleKey,$ as uriKey,gn as uriTriple,Tt as versionOperatorFromChar,fe as versionOperatorToChar,_t as versionsEqual};
@@ -1,3 +1,4 @@
1
+ import type { AuthenticatedFetchFn } from '../auth/index.js';
1
2
  export interface PublisherConfig {
2
3
  version: number;
3
4
  index?: string;
@@ -43,7 +44,9 @@ export interface PublisherConfig {
43
44
  */
44
45
  export declare function defaultPublisherConfig(publisher: string): PublisherConfig;
45
46
  export declare class PublisherConfigResolver {
47
+ private readonly fetchFn?;
46
48
  private readonly cache;
49
+ constructor(fetchFn?: AuthenticatedFetchFn | undefined);
47
50
  getConfig(publisher: string): Promise<PublisherConfig>;
48
51
  private fetchConfig;
49
52
  resolveIndexUrl(publisher: string, config: PublisherConfig): string;
@@ -1 +1 @@
1
- import{b as e,c as r,d as n}from"../chunk-F26XWM5K.js";import{a as o}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-NJ3AZYQD.js";import"../chunk-2ACBWC7K.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
1
+ import{f as e,g as r,h as n}from"../chunk-JYBKSBB5.js";import{a as o}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-NJ3AZYQD.js";import"../chunk-2ACBWC7K.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
@@ -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-MPBNEKCQ.js";import{a as g,b as h,c as i,d as j}from"../chunk-F26XWM5K.js";import{a}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-NJ3AZYQD.js";import"../chunk-2ACBWC7K.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,l as LockAwareRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,n as buildLocalFirstRepository,m as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
1
+ 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-GMEPM2QQ.js";import{e as g,f as h,g as i,h as j}from"../chunk-JYBKSBB5.js";import{a}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-NJ3AZYQD.js";import"../chunk-2ACBWC7K.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,l as LockAwareRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,n as buildLocalFirstRepository,m as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
@@ -1,13 +1,13 @@
1
- import{j as ee}from"../chunk-OOR5SVNQ.js";import"../chunk-QHABFCRC.js";import{a as me,d as U,f as fe,h as J}from"../chunk-MPBNEKCQ.js";import{a as he,b as ke,c as z,d as Y}from"../chunk-F26XWM5K.js";import{a as ge}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as be}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{i as Q}from"../chunk-DSHPAWJQ.js";import{a as L}from"../chunk-NJ3AZYQD.js";import{b as X}from"../chunk-UK2OIPAB.js";import{g as Z}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as ye}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{c as F,e as K,f as H,g as ue}from"../chunk-2ACBWC7K.js";import{readFileSync as Pe,writeFileSync as De,mkdirSync as _e}from"fs";import{join as $e}from"path";function ve(n){let e=n.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function T(n,e){let t=new Set,r=[...n];for(;r.length>0;){let s=r.shift(),a=ve(s);if(!a||t.has(a))continue;t.add(a);let h=s.metadata?.imports;if(h)for(let[u,f]of Object.entries(h))for(let p of f)try{let g=await e.getHighestCompatibleVersionAsync(u,p);g&&r.push(g)}catch{}}return t}var B=class{constructor(e,t){this.inner=e;this.scope=t}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(t=>{let r=ve(t);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.inner.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.inner.getHighestCompatibleVersionAsync(e,t)}saveDocumentAsync(e,t){return this.inner.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.inner.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var Se=[{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 W(n){let e=n?.render;if(e&&e.length>0){let t=[];for(let r of e)try{let s=X(r);s.kind==="package"?t.push({publisher:s.publisher,package_:s.package_}):s.kind==="resource"&&t.push({publisher:s.uri.publisher,package_:s.uri.package_})}catch{}if(t.length>0)return t}return Se}function C(n){return`${n.publisher}/${n.package_}`}function G(n){let e={"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"},t=[];for(let r of n)if(r.origin==="missing"){let s=C(r),a=e[s]??"whatever this package contributes to rendering is lost";t.push(`Render-stack package ${s} is MISSING (${r.reason??"unknown reason"}) \u2014 ${a}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&t.push(`Render-stack package ${C(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return t}function re(n){let{publisher:e,availablePublishers:t,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:h,renderStack:u,producers:f}=n,p=new Map,g=new Map,o=new Map,m=new Set;for(let k of r){if(!(k instanceof ye))continue;let S=k.namespace||"";if(!a.has(S))continue;p.set(`${S}/${k.name}`,k);let b=S.split("/")[1]??"",[D,_]=b.split("@");if(!D||!_)continue;let I=ue(_);I&&(m.has(b)||(m.add(b),g.has(D)||g.set(D,[]),g.get(D).push({verStr:_,version:I})),k.name===D&&o.set(b,k))}for(let k of g.values())k.sort((S,b)=>F(b.version,S.version));return{publisher:e,availablePublishers:t,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:h,bySubject:p,pkgVersions:g,pkgSelfByVer:o,renderStack:u,...f?{producers:f}:{}}}async function se(n,e={}){let t=new L,r=new ge(t),s=[],a=[];for(let l of J(n)){let d;try{d=Pe(l,"utf-8")}catch{continue}let v;try{v=t.parse(d).metadata?.namespace_}catch{continue}if(!v?.version)continue;let N=v.version;a.push({publisher:v.publisher,package_:v.package_,verStr:K(N),version:N,source:d})}a.sort((l,d)=>F(d.version,l.version));for(let l of a)await r.saveDocumentAsync(t.parse(l.source),`${l.publisher}/${l.package_}@${l.verStr}`),s.push({publisher:l.publisher,package_:l.package_,verStr:l.verStr,source:l.source});let h=[...new Set(s.map(l=>l.publisher))].sort(),u=e.publisher;if(u){if(!h.includes(u))throw new Error(`Publisher "${u}" not found in workspace. Available: ${h.join(", ")||"(none)"}`)}else if(h.length===1)u=h[0];else throw h.length===0?new Error(`No Kanonak packages found under ${n}`):new Error(`Workspace has multiple publishers (${h.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,p=new Map;for(let l of s)l.publisher===u&&(f.add(`${l.publisher}/${l.package_}@${l.verStr}`),p.set(`${l.package_}@${l.verStr}`,l.source));let g=U(),o=new me(g,!0,t),m=e.repository??new fe(r,o,new Y(e.httpCache?{getFromCache:e.httpCache.getFromCache,onFetch:e.httpCache.onFetch}:void 0)),k=e.log??(()=>{}),S=W(void 0),b=[],D=l=>l.map(d=>d.metadata.namespace_?.version).filter(d=>d!==void 0).sort((d,v)=>F(v,d)).map(K);if(!e.repository){k(`[render-stack] resolving ${S.length} ambient look-stack package(s); cache: ${g}`);let l=new z;for(let d of S){let v=C(d),N=await r.getDocumentsByNamespaceAsync(d.publisher,d.package_);if(N.length>0){let $=D(N);b.push({...d,origin:"workspace",versions:$}),k(`[render-stack] ${v} \u2014 workspace (${$.join(", ")})`);continue}let O=await o.getDocumentsByNamespaceAsync(d.publisher,d.package_);if(O.length>0){let $=D(O);b.push({...d,origin:"cache",versions:$}),k(`[render-stack] ${v} \u2014 cache (${$.join(", ")})`);continue}try{let $=await l.getHighestVersion(d.publisher,d.package_);if(!$){let c=`publisher ${d.publisher} reachable but its index does not list ${d.package_}`;b.push({...d,origin:"missing",reason:c}),k(`[render-stack] ${v} \u2014 MISSING: ${c}`);continue}let j=await l.getPackageUrl(d.publisher,d.package_,$),V=await fetch(j);if(!V.ok){let c=`fetch ${j} failed: HTTP ${V.status} ${V.statusText}`;b.push({...d,origin:"missing",reason:c}),k(`[render-stack] ${v} \u2014 MISSING: ${c}`);continue}let i=await V.text();await r.saveDocumentAsync(t.parse(i),`${d.publisher}/${d.package_}@${$}`);try{let c=$e(g,d.publisher);_e(c,{recursive:!0}),De($e(c,`${d.package_}@${$}.kan.yml`),i,"utf-8"),b.push({...d,origin:"fetched",versions:[$]}),k(`[render-stack] ${v}@${$} \u2014 fetched from ${j}, installed to cache`)}catch(c){b.push({...d,origin:"fetched",versions:[$]}),k(`[render-stack] ${v}@${$} \u2014 fetched from ${j}, but cache ${g} is NOT WRITABLE (${c.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch($){let j=`fetch failed: ${$.message}`;b.push({...d,origin:"missing",reason:j}),k(`[render-stack] ${v} \u2014 MISSING: ${j}`)}}}let _=m;if(!e.repository){let l=(await r.getAllDocumentsAsync()).filter(v=>v.metadata.namespace_?.publisher===u),d=await T(l,m);for(let v of S)d.add(C(v));_=new B(m,d)}let I=await new Q(t).parseKanonaks(_),q=new ee(I),oe=(l,d)=>Z(I,{publisher:l,package_:d,name:d}).length>0,A;if(e.repository){A=[];for(let l of S){let d=await m.getDocumentsByNamespaceAsync(l.publisher,l.package_);A.push(d.length>0?{...l,origin:"repository",versions:D(d)}:{...l,origin:"missing",reason:"not present in the caller-supplied repository"})}}else A=b.map(l=>l.origin==="missing"||oe(l.publisher,l.package_)?l:{...l,resolvedButNotInCatalog:!0});let E=G(A);for(let l of E)k(`[render-stack] WARNING: ${l}`);return re({publisher:u,availablePublishers:h,catalog:I,lookRenderer:q,localNamespaces:f,rawByNsKey:p,renderStack:{contractSource:"universal-default",cachePath:g,packages:A,warnings:E}})}import{existsSync as je,readFileSync as Ce,writeFileSync as Ie,mkdirSync as Ae}from"fs";import{join as we}from"path";async function ae(n,e={}){let t=new L,r=X(n),s=r.kind==="resource"?r.uri.publisher:r.publisher,a=e.log??(()=>{}),h=e.cacheRoot??U(),u=(i,c,y)=>we(h,i,`${c}@${y}.kan.yml`),f=new Set,p=new Set,g=new Map,o=new Y({getFromCache:(i,c,y)=>{let P=u(i,c,y),w=je(P)?Ce(P,"utf-8"):null;return w!==null&&f.add(`${i}/${c}`),w},onFetch:(i,c,y,P)=>{p.add(`${i}/${c}`);try{let w=we(h,i);Ae(w,{recursive:!0}),Ie(u(i,c,y),P,"utf-8")}catch(w){g.set(`${i}/${c}`,w.message),a(`[render] fetched ${i}/${c}@${y} but cache ${h} is NOT WRITABLE (${w.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),m=new z(e.fetchFn?{fetchFn:e.fetchFn}:void 0),k;if(r.kind==="resource"){let i=r.uri.version;k=[i?{package_:r.uri.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let i=r.version;k=[i?{package_:r.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.package_}]}else k=(await m.listLatestPackages(s)).map(c=>({package_:c.packageName}));let S=async(i,c,y)=>{try{let P=y?t.buildImport(c,"=",y,i):t.buildImport(c,"*","0.0.0",i),w=await o.getHighestCompatibleVersionAsync(i,P);return w?{doc:w}:{doc:null,error:`${i} did not resolve ${c}${y?`@${y}`:""} (not in its index, or unreachable)`}}catch(P){return{doc:null,error:P.message}}},b=[],D=[];for(let i of k){let{doc:c,error:y}=await S(s,i.package_,i.version);c?b.push(c):y&&D.push(y)}if(b.length===0)throw new Error(`Could not fetch any package for address "${n}" from publisher "${s}".`+(D.length>0?` Reasons: ${D.join("; ")}`:""));let _=await new ke().getConfig(s).catch(()=>{}),I=W(_),q=_?.render&&_.render.length>0?"publisher-well-known":"universal-default",oe=i=>i.map(c=>c.metadata.namespace_?.version).filter(c=>c!==void 0).sort((c,y)=>F(y,c)).map(K);a(`[render-stack] resolving ${I.length} ambient look-stack package(s) (contract: ${q}); cache: ${h}`);let A=[],E=[];for(let i of I){let c=C(i),{doc:y,error:P}=await S(i.publisher,i.package_,void 0);if(y){A.push(y);let w=oe([y]),pe=p.has(c)?"fetched":f.has(c)?"cache":"fetched";E.push({...i,origin:pe,versions:w}),a(`[render-stack] ${c} \u2014 ${pe} (${w.join(", ")})`+(g.has(c)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else E.push({...i,origin:"missing",reason:P??"unresolved"}),a(`[render-stack] ${c} \u2014 MISSING: ${P??"unresolved"}`)}let de=await T([...b,...A],o),l=new B(o,de),d=await new Q(t).parseKanonaks(l),v=new ee(d),N=E.map(i=>i.origin==="missing"||Z(d,{publisher:i.publisher,package_:i.package_,name:i.package_}).length>0?i:{...i,resolvedButNotInCatalog:!0}),O=G(N);for(let i of O)a(`[render-stack] WARNING: ${i}`);let $={contractSource:q,cachePath:h,packages:N,warnings:O},j=new Set,V=new Map;for(let i of await o.getAllDocumentsAsync()){let c=i.metadata.namespace_;if(!c?.version||c.publisher!==s)continue;let y=K(c.version),P=`${c.publisher}/${c.package_}@${y}`;j.add(P);let w=await o.getDocumentContentAsync(P);w!==null&&V.set(`${c.package_}@${y}`,w)}return re({publisher:s,availablePublishers:[s],catalog:d,lookRenderer:v,localNamespaces:j,rawByNsKey:V,renderStack:$})}import{VersionOperator as te}from"@kanonak-protocol/types/document/models/enums";function ne(n){let{lookRenderer:e,publisher:t,renderStack:r,catalog:s}=n,a=e.explainStylesheet(e.publisherSubject(t)),h=[...a.tokens.entries()].map(([o,m])=>({name:o,value:m.value,source:`${m.sourceNamespace}/${m.sourceName}`,level:m.level})),u=a.baseStylesheet,f={present:u.css!==void 0,...u.sourceNamespace!==void 0?{source:u.sourceNamespace}:{},...u.scope!==void 0?{scope:u.scope}:{},...u.css!==void 0?{bytes:u.css.length}:{},...u.problem!==void 0?{problem:u.problem}:{},candidates:u.candidates},p=new Map;for(let o of s){let m=o.namespace;m&&p.set(m,(p.get(m)??0)+1)}let g=[...p.entries()].map(([o,m])=>({namespace:o,resources:m})).sort((o,m)=>o.namespace.localeCompare(m.namespace));return{publisher:t,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(o=>({package_:C(o),origin:o.origin,...o.versions!==void 0?{versions:o.versions}:{},...o.reason!==void 0?{reason:o.reason}:{},...o.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:o.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:h,baseStylesheet:f,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},catalog:g,warnings:[...r.warnings,...a.warnings.filter(o=>!r.warnings.includes(o))]}}function Ne(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ie(n){let e=Ne,t=n.warnings.length===0,r=n.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':n.warnings.map(p=>`<div class="warn">\u26A0 ${e(p)}</div>`).join(`
2
- `),s=n.renderStack.packages.map(p=>{let g=p.origin!=="missing"&&!p.resolvedButNotInCatalog,o=p.origin==="missing"?'<span class="bad">MISSING</span>':p.resolvedButNotInCatalog?`<span class="bad">${e(p.origin)} (not in catalog)</span>`:`<span class="good">${e(p.origin)}</span>`,m=p.reason?e(p.reason):e((p.versions??[]).join(", "));return`<tr class="${g?"":"row-bad"}"><td><code>${e(p.package_)}</code></td><td>${o}</td><td>${m}</td></tr>`}).join(`
3
- `),a=n.stylesheet.baseStylesheet,h=a.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(a.source??"")}</code> (${a.bytes} bytes, ${e(a.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${a.problem?` \u2014 ${e(a.problem)}`:""}${a.candidates.length>0?`<br>candidates considered: ${a.candidates.map(p=>`<code>${e(p)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,u=n.stylesheet.tokens.map(p=>`<tr><td><code>--kan-${e(p.name)}</code></td><td><code>${e(p.value)}</code></td><td><code>${e(p.source)}</code></td><td>${e(p.level)}</td></tr>`).join(`
4
- `),f=n.catalog.map(p=>`<tr><td><code>${e(p.namespace)}</code></td><td>${p.resources}</td></tr>`).join(`
1
+ import{j as ee}from"../chunk-OOR5SVNQ.js";import"../chunk-QHABFCRC.js";import{a as he,d as z,f as ye,h as J}from"../chunk-GMEPM2QQ.js";import{d as me,e as fe,f as ke,g as O,h as Y}from"../chunk-JYBKSBB5.js";import{a as ge}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as ve}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{i as Q}from"../chunk-DSHPAWJQ.js";import{a as E}from"../chunk-NJ3AZYQD.js";import{b as X}from"../chunk-UK2OIPAB.js";import{g as Z}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as be}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{c as M,e as F,f as L,g as ue}from"../chunk-2ACBWC7K.js";import{readFileSync as De,writeFileSync as _e,mkdirSync as je}from"fs";import{join as $e}from"path";function Se(t){let e=t.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function H(t,e){let n=new Set,r=[...t];for(;r.length>0;){let s=r.shift(),a=Se(s);if(!a||n.has(a))continue;n.add(a);let m=s.metadata?.imports;if(m)for(let[p,k]of Object.entries(m))for(let d of k)try{let u=await e.getHighestCompatibleVersionAsync(p,d);u&&r.push(u)}catch{}}return n}var V=class{constructor(e,n){this.inner=e;this.scope=n}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(n=>{let r=Se(n);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,n){return this.inner.getDocumentsByNamespaceAsync(e,n)}getHighestCompatibleVersionAsync(e,n){return this.inner.getHighestCompatibleVersionAsync(e,n)}saveDocumentAsync(e,n){return this.inner.saveDocumentAsync(e,n)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,n){return this.inner.clearNamespaceAsync(e,n)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var we=[{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 T(t){let e=t?.render;if(e&&e.length>0){let n=[];for(let r of e)try{let s=X(r);s.kind==="package"?n.push({publisher:s.publisher,package_:s.package_}):s.kind==="resource"&&n.push({publisher:s.uri.publisher,package_:s.uri.package_})}catch{}if(n.length>0)return n}return we}function C(t){return`${t.publisher}/${t.package_}`}function W(t){let e={"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"},n=[];for(let r of t)if(r.origin==="missing"){let s=C(r),a=e[s]??"whatever this package contributes to rendering is lost";n.push(`Render-stack package ${s} is MISSING (${r.reason??"unknown reason"}) \u2014 ${a}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&n.push(`Render-stack package ${C(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return n}function re(t){let{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,renderStack:p,producers:k}=t,d=new Map,u=new Map,o=new Map,h=new Set;for(let y of r){if(!(y instanceof be))continue;let b=y.namespace||"";if(!a.has(b))continue;d.set(`${b}/${y.name}`,y);let $=b.split("/")[1]??"",[w,_]=$.split("@");if(!w||!_)continue;let I=ue(_);I&&(h.has($)||(h.add($),u.has(w)||u.set(w,[]),u.get(w).push({verStr:_,version:I})),y.name===w&&o.set($,y))}for(let y of u.values())y.sort((b,$)=>M($.version,b.version));return{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,bySubject:d,pkgVersions:u,pkgSelfByVer:o,renderStack:p,...k?{producers:k}:{}}}async function se(t,e={}){let n=new E,r=new ge(n),s=[],a=[];for(let c of J(t)){let l;try{l=De(c,"utf-8")}catch{continue}let v;try{v=n.parse(l).metadata?.namespace_}catch{continue}if(!v?.version)continue;let N=v.version;a.push({publisher:v.publisher,package_:v.package_,verStr:F(N),version:N,source:l})}a.sort((c,l)=>M(l.version,c.version));for(let c of a)await r.saveDocumentAsync(n.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),s.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let m=[...new Set(s.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!m.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)p=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 k=new Set,d=new Map;for(let c of s)c.publisher===p&&(k.add(`${c.publisher}/${c.package_}@${c.verStr}`),d.set(`${c.package_}@${c.verStr}`,c.source));let u=z(),o=new he(u,!0,n),h={};e.httpCache&&(h.getFromCache=e.httpCache.getFromCache,h.onFetch=e.httpCache.onFetch),e.fetchFn&&(h.fetchFn=e.fetchFn);let y=e.repository??new ye(r,o,new Y(h)),b=e.log??(()=>{}),$=T(void 0),w=[],_=c=>c.map(l=>l.metadata.namespace_?.version).filter(l=>l!==void 0).sort((l,v)=>M(v,l)).map(F);if(!e.repository){b(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${u}`);let c=e.fetchFn?new O({fetchFn:e.fetchFn}):new O;for(let l of $){let v=C(l),N=await r.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(N.length>0){let S=_(N);w.push({...l,origin:"workspace",versions:S}),b(`[render-stack] ${v} \u2014 workspace (${S.join(", ")})`);continue}let U=await o.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(U.length>0){let S=_(U);w.push({...l,origin:"cache",versions:S}),b(`[render-stack] ${v} \u2014 cache (${S.join(", ")})`);continue}try{let S=await c.getHighestVersion(l.publisher,l.package_);if(!S){let f=`publisher ${l.publisher} reachable but its index does not list ${l.package_}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let j=await c.getPackageUrl(l.publisher,l.package_,S),i=await(e.fetchFn?e.fetchFn(j,l.publisher):me(j));if(!i.ok){let f=`fetch ${j} failed: HTTP ${i.status} ${i.statusText}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let g=await i.text();await r.saveDocumentAsync(n.parse(g),`${l.publisher}/${l.package_}@${S}`);try{let f=$e(u,l.publisher);je(f,{recursive:!0}),_e($e(f,`${l.package_}@${S}.kan.yml`),g,"utf-8"),w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, installed to cache`)}catch(f){w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, but cache ${u} is NOT WRITABLE (${f.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(S){let j=`fetch failed: ${S.message}`;w.push({...l,origin:"missing",reason:j}),b(`[render-stack] ${v} \u2014 MISSING: ${j}`)}}}let I=y;if(!e.repository){let c=(await r.getAllDocumentsAsync()).filter(v=>v.metadata.namespace_?.publisher===p),l=await H(c,y);for(let v of $)l.add(C(v));I=new V(y,l)}let B=await new Q(n).parseKanonaks(I),oe=new ee(B),G=(c,l)=>Z(B,{publisher:c,package_:l,name:l}).length>0,A;if(e.repository){A=[];for(let c of $){let l=await y.getDocumentsByNamespaceAsync(c.publisher,c.package_);A.push(l.length>0?{...c,origin:"repository",versions:_(l)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else A=w.map(c=>c.origin==="missing"||G(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let q=W(A);for(let c of q)b(`[render-stack] WARNING: ${c}`);return re({publisher:p,availablePublishers:m,catalog:B,lookRenderer:oe,localNamespaces:k,rawByNsKey:d,renderStack:{contractSource:"universal-default",cachePath:u,packages:A,warnings:q}})}import{existsSync as Ce,readFileSync as Ae,writeFileSync as Ie,mkdirSync as Ne}from"fs";import{join as Re}from"path";async function ae(t,e={}){let n=new E,r=X(t),s=r.kind==="resource"?r.uri.publisher:r.publisher,a=e.log??(()=>{}),m=e.cacheRoot??z(),p=(i,g,f)=>Re(m,i,`${g}@${f}.kan.yml`),k=new Set,d=new Set,u=new Map,o=new Y({getFromCache:(i,g,f)=>{let D=p(i,g,f),R=Ce(D)?Ae(D,"utf-8"):null;return R!==null&&k.add(`${i}/${g}`),R},onFetch:(i,g,f,D)=>{d.add(`${i}/${g}`);try{let R=Re(m,i);Ne(R,{recursive:!0}),Ie(p(i,g,f),D,"utf-8")}catch(R){u.set(`${i}/${g}`,R.message),a(`[render] fetched ${i}/${g}@${f} but cache ${m} is NOT WRITABLE (${R.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),h=new O(e.fetchFn?{fetchFn:e.fetchFn}:void 0),y;if(r.kind==="resource"){let i=r.uri.version;y=[i?{package_:r.uri.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let i=r.version;y=[i?{package_:r.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.package_}]}else y=(await h.listLatestPackages(s)).map(g=>({package_:g.packageName}));let b=async(i,g,f)=>{try{let D=f?n.buildImport(g,"=",f,i):n.buildImport(g,"*","0.0.0",i),R=await o.getHighestCompatibleVersionAsync(i,D);return R?{doc:R}:{doc:null,error:`${i} did not resolve ${g}${f?`@${f}`:""} (not in its index, or unreachable)`}}catch(D){return{doc:null,error:D.message}}},$=[],w=[];for(let i of y){let{doc:g,error:f}=await b(s,i.package_,i.version);g?$.push(g):f&&w.push(f)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${s}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=await new ke(e.fetchFn).getConfig(s).catch(()=>{}),I=T(_),B=_?.render&&_.render.length>0?"publisher-well-known":"universal-default",oe=i=>i.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,f)=>M(f,g)).map(F);a(`[render-stack] resolving ${I.length} ambient look-stack package(s) (contract: ${B}); cache: ${m}`);let G=[],A=[];for(let i of I){let g=C(i),{doc:f,error:D}=await b(i.publisher,i.package_,void 0);if(f){G.push(f);let R=oe([f]),pe=d.has(g)?"fetched":k.has(g)?"cache":"fetched";A.push({...i,origin:pe,versions:R}),a(`[render-stack] ${g} \u2014 ${pe} (${R.join(", ")})`+(u.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...i,origin:"missing",reason:D??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${D??"unresolved"}`)}let q=await H([...$,...G],o),de=new V(o,q),c=await new Q(n).parseKanonaks(de),l=new ee(c),v=A.map(i=>i.origin==="missing"||Z(c,{publisher:i.publisher,package_:i.package_,name:i.package_}).length>0?i:{...i,resolvedButNotInCatalog:!0}),N=W(v);for(let i of N)a(`[render-stack] WARNING: ${i}`);let U={contractSource:B,cachePath:m,packages:v,warnings:N},S=new Set,j=new Map;for(let i of await o.getAllDocumentsAsync()){let g=i.metadata.namespace_;if(!g?.version||g.publisher!==s)continue;let f=F(g.version),D=`${g.publisher}/${g.package_}@${f}`;S.add(D);let R=await o.getDocumentContentAsync(D);R!==null&&j.set(`${g.package_}@${f}`,R)}return re({publisher:s,availablePublishers:[s],catalog:c,lookRenderer:l,localNamespaces:S,rawByNsKey:j,renderStack:U})}import{VersionOperator as ne}from"@kanonak-protocol/types/document/models/enums";function te(t){let{lookRenderer:e,publisher:n,renderStack:r,catalog:s}=t,a=e.explainStylesheet(e.publisherSubject(n)),m=[...a.tokens.entries()].map(([o,h])=>({name:o,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=a.baseStylesheet,k={present:p.css!==void 0,...p.sourceNamespace!==void 0?{source:p.sourceNamespace}:{},...p.scope!==void 0?{scope:p.scope}:{},...p.css!==void 0?{bytes:p.css.length}:{},...p.problem!==void 0?{problem:p.problem}:{},candidates:p.candidates},d=new Map;for(let o of s){let h=o.namespace;h&&d.set(h,(d.get(h)??0)+1)}let u=[...d.entries()].map(([o,h])=>({namespace:o,resources:h})).sort((o,h)=>o.namespace.localeCompare(h.namespace));return{publisher:n,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(o=>({package_:C(o),origin:o.origin,...o.versions!==void 0?{versions:o.versions}:{},...o.reason!==void 0?{reason:o.reason}:{},...o.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:o.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:k,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},catalog:u,warnings:[...r.warnings,...a.warnings.filter(o=>!r.warnings.includes(o))]}}function Fe(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ie(t){let e=Fe,n=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(d=>`<div class="warn">\u26A0 ${e(d)}</div>`).join(`
2
+ `),s=t.renderStack.packages.map(d=>{let u=d.origin!=="missing"&&!d.resolvedButNotInCatalog,o=d.origin==="missing"?'<span class="bad">MISSING</span>':d.resolvedButNotInCatalog?`<span class="bad">${e(d.origin)} (not in catalog)</span>`:`<span class="good">${e(d.origin)}</span>`,h=d.reason?e(d.reason):e((d.versions??[]).join(", "));return`<tr class="${u?"":"row-bad"}"><td><code>${e(d.package_)}</code></td><td>${o}</td><td>${h}</td></tr>`}).join(`
3
+ `),a=t.stylesheet.baseStylesheet,m=a.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(a.source??"")}</code> (${a.bytes} bytes, ${e(a.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${a.problem?` \u2014 ${e(a.problem)}`:""}${a.candidates.length>0?`<br>candidates considered: ${a.candidates.map(d=>`<code>${e(d)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,p=t.stylesheet.tokens.map(d=>`<tr><td><code>--kan-${e(d.name)}</code></td><td><code>${e(d.value)}</code></td><td><code>${e(d.source)}</code></td><td>${e(d.level)}</td></tr>`).join(`
4
+ `),k=t.catalog.map(d=>`<tr><td><code>${e(d.namespace)}</code></td><td>${d.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(n.publisher)}</title>
10
+ <title>Render diagnostics \u2014 ${e(t.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; }
@@ -21,12 +21,12 @@ import{j as ee}from"../chunk-OOR5SVNQ.js";import"../chunk-QHABFCRC.js";import{a
21
21
  .row-bad td { background: #fff5f5; }
22
22
  .meta { color: #666; font-size: .85rem; }
23
23
  .status-banner { font-size: 1.1rem; padding: .5rem 1rem; border-radius: 6px; display: inline-block; margin-bottom: 1rem;
24
- background: ${t?"#ecfdf3":"#fef2f2"}; border: 1px solid ${t?"#0a7d33":"#b91c1c"}; }
24
+ background: ${n?"#ecfdf3":"#fef2f2"}; border: 1px solid ${n?"#0a7d33":"#b91c1c"}; }
25
25
  </style>
26
26
  </head>
27
27
  <body>
28
- <h1>Render diagnostics \u2014 ${e(n.publisher)}</h1>
29
- <p class="status-banner">${t?"\u2713 Healthy":`\u2717 ${n.warnings.length} problem(s) found`}</p>
28
+ <h1>Render diagnostics \u2014 ${e(t.publisher)}</h1>
29
+ <p class="status-banner">${n?"\u2713 Healthy":`\u2717 ${t.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,7 +34,7 @@ ${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(n.renderStack.contractSource)}</code> \xB7 Package cache: <code>${e(n.renderStack.cachePath)}</code></p>
37
+ Contract: <code>${e(t.renderStack.contractSource)}</code> \xB7 Package cache: <code>${e(t.renderStack.cachePath)}</code></p>
38
38
  <table>
39
39
  <tr><th>Package</th><th>Origin</th><th>Versions / reason</th></tr>
40
40
  ${s}
@@ -42,25 +42,25 @@ ${s}
42
42
 
43
43
  <h2>Base stylesheet</h2>
44
44
  <p class="meta">Everything after the <code>:root</code> block in generated CSS comes from a <code>look-styles/base-stylesheet</code> asset in the render catalog.</p>
45
- ${h}
45
+ ${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
- ${n.stylesheet.tokens.length===0?'<p><span class="bad">\u2717 No tokens resolved</span></p>':`<table>
49
+ ${t.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
- ${u}
51
+ ${p}
52
52
  </table>`}
53
53
 
54
54
  <h2>Look (page body)</h2>
55
- ${n.stylesheet.look?`<p><span class="good">\u2713</span> Bands resolve from <code>${e(n.stylesheet.look.sourceClass)}</code></p>`:'<p><span class="bad">\u2717 No look resolved</span> \u2014 the page body renders as an empty comment.</p>'}
55
+ ${t.stylesheet.look?`<p><span class="good">\u2713</span> Bands resolve from <code>${e(t.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 (${n.catalog.length} package version(s))</h2>
57
+ <h2>Render catalog (${t.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
- ${f}
61
+ ${k}
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=(n,e,t,r)=>({status:n,headers:{"Content-Type":e,...r||{}},body:t}),M=n=>x(404,R[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${n}</p>`),Ke=n=>({status:301,headers:{Location:n},body:""}),Me=n=>({status:302,headers:{Location:n},body:""});function Ve(n){switch(n.kind){case"exact":return{operator:te.Exact,version:H(n.major,n.minor,n.patch)};case"minor-pin":return{operator:te.Compatible,version:H(n.major,n.minor,0)};case"major-pin":return{operator:te.Major,version:H(n.major,0,0)};default:return{operator:te.Any,version:H(0,0,0)}}}async function Fe(n,e,t,r){if(!r)return null;let s=n.producers?.find(f=>f.canProduce(n.publisher,e));if(!s)return null;let a=await s.resolveVersion(n.publisher,e,Ve(t));if(!a)return null;let h=K(a);if(t.kind!=="exact")return Me(`/${e}/${h}.kan.yml`);let{source:u}=await s.produce(n.publisher,e,a);return x(200,R[".kan.yml"],u)}function Re(n,e,t){let r=n.pkgVersions.get(e);if(!r||r.length===0)return null;switch(t.kind){case"any":return r[0].verStr;case"major-pin":return r.find(s=>s.version.major===t.major)?.verStr??null;case"minor-pin":return r.find(s=>s.version.major===t.major&&s.version.minor===t.minor)?.verStr??null;case"exact":return r.find(s=>s.version.major===t.major&&s.version.minor===t.minor&&s.version.patch===t.patch)?.verStr??null;default:return null}}async function ce(n,e,t=""){let{lookRenderer:r,publisher:s}=n;if(e==="/.well-known/kanonak.json"){let o=he(s);return n.producers&&n.producers.length>0&&(o.resolveByRedirect=!0),x(200,R[".json"],JSON.stringify(o,null,2))}if(e==="/index.txt"){let o=[...n.localNamespaces].map(m=>m.split("/")[1].replace("@","/")).sort();return x(200,R[".txt"],o.join(`
64
+ </html>`}var x={".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"},P=(t,e,n,r)=>({status:t,headers:{"Content-Type":e,...r||{}},body:n}),K=t=>P(404,x[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${t}</p>`),Ke=t=>({status:301,headers:{Location:t},body:""}),Me=t=>({status:302,headers:{Location:t},body:""});function Ve(t){switch(t.kind){case"exact":return{operator:ne.Exact,version:L(t.major,t.minor,t.patch)};case"minor-pin":return{operator:ne.Compatible,version:L(t.major,t.minor,0)};case"major-pin":return{operator:ne.Major,version:L(t.major,0,0)};default:return{operator:ne.Any,version:L(0,0,0)}}}async function Be(t,e,n,r){if(!r)return null;let s=t.producers?.find(k=>k.canProduce(t.publisher,e));if(!s)return null;let a=await s.resolveVersion(t.publisher,e,Ve(n));if(!a)return null;let m=F(a);if(n.kind!=="exact")return Me(`/${e}/${m}.kan.yml`);let{source:p}=await s.produce(t.publisher,e,a);return P(200,x[".kan.yml"],p)}function xe(t,e,n){let r=t.pkgVersions.get(e);if(!r||r.length===0)return null;switch(n.kind){case"any":return r[0].verStr;case"major-pin":return r.find(s=>s.version.major===n.major)?.verStr??null;case"minor-pin":return r.find(s=>s.version.major===n.major&&s.version.minor===n.minor)?.verStr??null;case"exact":return r.find(s=>s.version.major===n.major&&s.version.minor===n.minor&&s.version.patch===n.patch)?.verStr??null;default:return null}}async function ce(t,e,n=""){let{lookRenderer:r,publisher:s}=t;if(e==="/.well-known/kanonak.json"){let o=fe(s);return t.producers&&t.producers.length>0&&(o.resolveByRedirect=!0),P(200,x[".json"],JSON.stringify(o,null,2))}if(e==="/index.txt"){let o=[...t.localNamespaces].map(h=>h.split("/")[1].replace("@","/")).sort();return P(200,x[".txt"],o.join(`
65
65
  `)+`
66
- `)}if(e==="/.well-known/kanonak-render.json")return x(200,R[".json"],JSON.stringify(ne(n),null,2));if(e==="/.well-known/kanonak-render")return x(200,R[".html"],ie(ne(n)));if(e==="/"||e==="/index.html"||e==="/index.css"){let o=r.publisherSubject(s);return e==="/index.css"?x(200,R[".css"],r.renderStylesheet(o)):x(200,R[".html"],await r.renderDocument(o,{rootIndex:!0}))}let a=".html",h=!1,u=e;for(let o of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(o)){a=o,h=!0,u=e.slice(0,-o.length);break}let f=!h&&/application\/yaml|text\/yaml/i.test(t),p=u.endsWith("/");p&&u!=="/"&&(u=u.slice(0,-1));let g=be.parse(u,s);if(!g)return M(e);if(g.kind==="package"){let o=Re(n,g.package_,g.versionSpec);if(!o)return await Fe(n,g.package_,g.versionSpec,a===".kan.yml"||f)??M(e);if(a===".kan.yml"||f){let S=n.rawByNsKey.get(`${g.package_}@${o}`);return S!==void 0?x(200,R[".kan.yml"],S):M(e)}let m=n.pkgSelfByVer.get(`${g.package_}@${o}`);if(!m)return M(e);if(a===".css")return x(200,R[".css"],r.renderStylesheet(m));if(!p)return Ke(u+"/");let k=g.versionSpec.kind==="any";if(k&&!r.hasDeclaredView(m)){let S=(n.pkgVersions.get(g.package_)||[]).map(b=>b.verStr);return x(200,R[".html"],r.renderPackageVersionList(g.package_,S,m))}return x(200,R[".html"],await r.renderDocument(m,k?{bareOverview:!0}:void 0))}if(g.kind==="resource"){let o=Re(n,g.package_,g.versionSpec);if(!o)return M(e);let m=n.bySubject.get(`${s}/${g.package_}@${o}/${g.name}`);if(!m)return M(e);switch(a){case".css":return x(200,R[".css"],r.renderStylesheet(m));case".svg":return x(200,R[".svg"],await r.renderSvg(m));case".md":{let k=r.renderRawMarkdown(m);return k===void 0?M(e):x(200,R[".md"],k)}default:return x(200,R[".html"],await r.renderDocument(m))}}return M(e)}import{readFileSync as Be}from"fs";var le=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,t=new Set;if(this.options.root!==void 0){let r=new L;for(let s of J(this.options.root))try{let a=r.parse(Be(s,"utf-8")).metadata?.namespace_;if(!a?.version)continue;let h=a.version;e.add(`${a.publisher}/${a.package_}@${h.major}.${h.minor}.${h.patch}`),t.add(`${a.publisher}/${a.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:t},this.workspaceIndex}async modelFor(e,t,r){let s=this.getWorkspaceIndex(),a={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},h=t?r?s.exact.has(`${e}/${t}@${r}`):s.pkgs.has(`${e}/${t}`):[...s.pkgs].some(o=>o.startsWith(`${e}/`)),u,f;if(h&&this.options.root!==void 0){let o=this.options.root;u=`ws:${e}`,f=()=>se(o,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let o=t?r?`${e}/${t}@${r}`:`${e}/${t}`:e;u=`rm:${o}`,f=()=>ae(o,a)}let p=this.models.get(u);if(p)return p;let g=await f();return g.lookRenderer.setLinkMode("open-world"),this.models.set(u,g),g}async handle(e,t=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:xe()};let s=r[0];if(!s.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 a=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),h=!a&&r.length>=2?r[1]:void 0,u=!a&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,f=await this.modelFor(s,h,u),p=e.endsWith("/")&&r.length>1?"/":"",g="/"+r.slice(1).join("/")+p,o=await ce(f,g,t);return o.headers.Location?{...o,headers:{...o.headers,Location:`/${s}${o.headers.Location}`}}:o}};function xe(){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{B as ClosureScopedRepository,le as RequestRouter,Se as UNIVERSAL_RENDER_BASE,ne as buildRenderDiagnostics,G as buildRenderStackWarnings,T as deriveImportClosure,xe as landingPage,ae as loadResourceModel,se as loadServerModel,ie as renderDiagnosticsHtml,C as renderRefKey,W as resolveRenderContract,ce as route};
66
+ `)}if(e==="/.well-known/kanonak-render.json")return P(200,x[".json"],JSON.stringify(te(t),null,2));if(e==="/.well-known/kanonak-render")return P(200,x[".html"],ie(te(t)));if(e==="/"||e==="/index.html"||e==="/index.css"){let o=r.publisherSubject(s);return e==="/index.css"?P(200,x[".css"],r.renderStylesheet(o)):P(200,x[".html"],await r.renderDocument(o,{rootIndex:!0}))}let a=".html",m=!1,p=e;for(let o of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(o)){a=o,m=!0,p=e.slice(0,-o.length);break}let k=!m&&/application\/yaml|text\/yaml/i.test(n),d=p.endsWith("/");d&&p!=="/"&&(p=p.slice(0,-1));let u=ve.parse(p,s);if(!u)return K(e);if(u.kind==="package"){let o=xe(t,u.package_,u.versionSpec);if(!o)return await Be(t,u.package_,u.versionSpec,a===".kan.yml"||k)??K(e);if(a===".kan.yml"||k){let b=t.rawByNsKey.get(`${u.package_}@${o}`);return b!==void 0?P(200,x[".kan.yml"],b):K(e)}let h=t.pkgSelfByVer.get(`${u.package_}@${o}`);if(!h)return K(e);if(a===".css")return P(200,x[".css"],r.renderStylesheet(h));if(!d)return Ke(p+"/");let y=u.versionSpec.kind==="any";if(y&&!r.hasDeclaredView(h)){let b=(t.pkgVersions.get(u.package_)||[]).map($=>$.verStr);return P(200,x[".html"],r.renderPackageVersionList(u.package_,b,h))}return P(200,x[".html"],await r.renderDocument(h,y?{bareOverview:!0}:void 0))}if(u.kind==="resource"){let o=xe(t,u.package_,u.versionSpec);if(!o)return K(e);let h=t.bySubject.get(`${s}/${u.package_}@${o}/${u.name}`);if(!h)return K(e);switch(a){case".css":return P(200,x[".css"],r.renderStylesheet(h));case".svg":return P(200,x[".svg"],await r.renderSvg(h));case".md":{let y=r.renderRawMarkdown(h);return y===void 0?K(e):P(200,x[".md"],y)}default:return P(200,x[".html"],await r.renderDocument(h))}}return K(e)}import{readFileSync as Ee}from"fs";var le=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,n=new Set;if(this.options.root!==void 0){let r=new E;for(let s of J(this.options.root))try{let a=r.parse(Ee(s,"utf-8")).metadata?.namespace_;if(!a?.version)continue;let m=a.version;e.add(`${a.publisher}/${a.package_}@${m.major}.${m.minor}.${m.patch}`),n.add(`${a.publisher}/${a.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:n},this.workspaceIndex}async modelFor(e,n,r){let s=this.getWorkspaceIndex(),a={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},m=n?r?s.exact.has(`${e}/${n}@${r}`):s.pkgs.has(`${e}/${n}`):[...s.pkgs].some(o=>o.startsWith(`${e}/`)),p,k;if(m&&this.options.root!==void 0){let o=this.options.root;p=`ws:${e}`,k=()=>se(o,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let o=n?r?`${e}/${n}@${r}`:`${e}/${n}`:e;p=`rm:${o}`,k=()=>ae(o,a)}let d=this.models.get(p);if(d)return d;let u=await k();return u.lookRenderer.setLinkMode("open-world"),this.models.set(p,u),u}async handle(e,n=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Pe()};let s=r[0];if(!s.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 a=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),m=!a&&r.length>=2?r[1]:void 0,p=!a&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,k=await this.modelFor(s,m,p),d=e.endsWith("/")&&r.length>1?"/":"",u="/"+r.slice(1).join("/")+d,o=await ce(k,u,n);return o.headers.Location?{...o,headers:{...o.headers,Location:`/${s}${o.headers.Location}`}}:o}};function Pe(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{V as ClosureScopedRepository,le as RequestRouter,we as UNIVERSAL_RENDER_BASE,te as buildRenderDiagnostics,W as buildRenderStackWarnings,H as deriveImportClosure,Pe as landingPage,ae as loadResourceModel,se as loadServerModel,ie as renderDiagnosticsHtml,C as renderRefKey,T as resolveRenderContract,ce as route};
@@ -4,6 +4,7 @@ import type { Kanonak } from '../kanonaks/index.js';
4
4
  import { SubjectKanonak } from '../kanonaks/index.js';
5
5
  import type { LookRenderer } from '../look/index.js';
6
6
  import type { HttpCacheHooks } from '../repositories/index.js';
7
+ import type { AuthenticatedFetchFn } from '../auth/index.js';
7
8
  import type { IPackageProducer } from '../producer/index.js';
8
9
  import type { RenderStackReport } from './renderStack.js';
9
10
  /** A package version present in the served workspace. */
@@ -76,6 +77,15 @@ export interface LoadServerModelOptions {
76
77
  repository?: IKanonakDocumentRepository;
77
78
  /** HTTP write-through cache hook for the default stack (e.g. a disk cache). */
78
79
  httpCache?: HttpCacheHooks;
80
+ /**
81
+ * Transport for ALL remote fetches the default stack performs — the HTTP
82
+ * repository's index/package fetches, the publisher config fetch, AND the
83
+ * ambient render-stack package fetch below. A consumer that must control
84
+ * fetching (a sandboxed/no-disk environment, or one synthesizing sources
85
+ * from a non-HTTP store) provides this so no request escapes to a raw
86
+ * `fetch`. Ignored when `repository` is supplied (the caller owns transport).
87
+ */
88
+ fetchFn?: AuthenticatedFetchFn;
79
89
  /**
80
90
  * Progress/observability sink. When provided, model loading narrates what it
81
91
  * is doing — workspace scan results, where each render-stack package
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "4.8.0",
3
+ "version": "4.10.0",
4
4
  "description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -125,7 +125,7 @@
125
125
  "yaml-parser"
126
126
  ],
127
127
  "dependencies": {
128
- "@kanonak-protocol/types": "^4.8.0",
128
+ "@kanonak-protocol/types": "^4.10.0",
129
129
  "ignore": "^7.0.5",
130
130
  "js-yaml": "^4.1.0",
131
131
  "yaml": "^2.7.0"
@@ -1,2 +0,0 @@
1
- import{a as u}from"./chunk-SC5M74NM.js";import{a as y}from"./chunk-NJ3AZYQD.js";import{e as v}from"./chunk-2ACBWC7K.js";var x="https://{publisher}/index.txt",P="https://{publisher}/{package}/{version}.kan.yml",k={version:1};function A(c){return{version:1,index:x.replaceAll("{publisher}",c),package:P.replaceAll("{publisher}",c),auth:"none"}}var f=class{cache=new Map;getConfig(t){let n=this.cache.get(t);return n||(n=this.fetchConfig(t),this.cache.set(t,n),n.catch(()=>{this.cache.get(t)===n&&this.cache.delete(t)})),n}async fetchConfig(t){let n=`https://${t}/.well-known/kanonak.json`,r;try{r=await fetch(n)}catch{return k}if(r.status===404)return k;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${n} (${r.status} ${r.statusText})`);let e=await r.json();if(typeof e.version!="number")throw new Error(`Invalid publisher config at ${n}: missing or invalid "version" field`);let s={version:e.version};return typeof e.index=="string"&&(s.index=e.index),typeof e.package=="string"&&(s.package=e.package),(e.auth==="none"||e.auth==="oauth"||e.auth==="bearer")&&(s.auth=e.auth),Array.isArray(e.render)&&e.render.every(i=>typeof i=="string")&&(s.render=e.render),typeof e.resolveByRedirect=="boolean"&&(s.resolveByRedirect=e.resolveByRedirect),s}resolveIndexUrl(t,n){let r=n.index??x;return w(r,{publisher:t})}resolvePackageUrl(t,n,r,e){let s=e.package??P;return w(s,{publisher:t,package:n,version:r})}};function w(c,t){let n=c;for(let[e,s]of Object.entries(t))n=n.replaceAll(`{${e}}`,s);let r=n.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${c}`);return n}import{VersionOperator as m}from"@kanonak-protocol/types/document/models/enums";var l=class c{indexCache=new Map;configResolver;fetchFn;constructor(t){this.configResolver=t?.configResolver??new f,this.fetchFn=t?.fetchFn}async resolveVersion(t,n){let r=await this.getPackageVersions(t,n.packageName);if(r.length===0)return null;let e=r.filter(s=>this.isVersionCompatible(s,n.version,n.versionOperator));return e.length===0?null:(e.sort((s,i)=>this.compareVersionStrings(i,s)),e[0])}async getHighestVersion(t,n){let r=await this.getPackageVersions(t,n);return r.length===0?null:[...r].sort((s,i)=>this.compareVersionStrings(i,s))[0]}async listLatestPackages(t){let n=await this.getIndex(t),r=[];for(let[e,s]of n){if(s.length===0)continue;let i=[...s].sort((o,a)=>this.compareVersionStrings(a,o));r.push({packageName:e,version:i[0]})}return r.sort((e,s)=>e.packageName.localeCompare(s.packageName)),r}async getPackageUrl(t,n,r){let e=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,n,r,e)}getConfig(t){return this.configResolver.getConfig(t)}async getPackageVersions(t,n){return(await this.getIndex(t)).get(n)??[]}getIndex(t){let n=this.indexCache.get(t);return n||(n=this.fetchIndex(t),this.indexCache.set(t,n),n.catch(()=>{this.indexCache.get(t)===n&&this.indexCache.delete(t)})),n}async fetchIndex(t){let n=await this.configResolver.getConfig(t),r=this.configResolver.resolveIndexUrl(t,n),e=this.fetchFn?await this.fetchFn(r,t):await fetch(r);if(!e.ok)throw new Error(`Failed to fetch publisher index: ${r} (${e.status} ${e.statusText})`);let s=await e.text();return c.parseIndex(s)}static parseIndex(t){let n=new Map;for(let r of t.split(`
2
- `)){let e=r.trim();if(!e||e.startsWith("#"))continue;let s=e.indexOf("/");if(s===-1)continue;let i=e.substring(0,s),o=e.substring(s+1);if(!i||!o)continue;let a=n.get(i);a?a.push(o):n.set(i,[o])}return n}isVersionCompatible(t,n,r){let e=c.parseVersion(t);if(!e)return!1;switch(r){case m.Any:return!0;case m.Exact:return e.major===n.major&&e.minor===n.minor&&e.patch===n.patch;case m.Compatible:return e.major===n.major&&e.minor===n.minor&&e.patch>=n.patch;case m.Major:return e.major!==n.major?!1:e.minor>n.minor?!0:e.minor===n.minor?e.patch>=n.patch:!1;default:return!1}}static parseVersion(t){let n=t.split(".");if(n.length<2)return null;let r=parseInt(n[0],10),e=parseInt(n[1],10),s=n.length>=3?parseInt(n[2],10):0;return isNaN(r)||isNaN(e)||isNaN(s)?null:{major:r,minor:e,patch:s}}compareVersionStrings(t,n){let r=c.parseVersion(t),e=c.parseVersion(n);return!r&&!e?0:r?e?r.major!==e.major?r.major-e.major:r.minor!==e.minor?r.minor-e.minor:r.patch-e.patch:1:-1}};import{VersionOperator as C}from"@kanonak-protocol/types/document/models/enums";var F=class{parser=new y;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new l({fetchFn:t.fetchFn}):new l}async getHighestCompatibleVersionAsync(t,n){if((await this.publisherIndex.getConfig(t)).resolveByRedirect)return this.resolveByRedirect(t,n);let e=await this.publisherIndex.resolveVersion(t,n);if(!e)return null;let s=`${t}/${n.packageName}@${e}`,i=this.documents.get(s);if(i)return i;if(this.getFromCache){let p=this.getFromCache(t,n.packageName,e);if(p){let d=this.parser.parse(p);return u(d,t,n.packageName,e),this.documents.set(s,d),this.contentCache.set(s,p),d}}let o=await this.publisherIndex.getPackageUrl(t,n.packageName,e),a=this.fetchFn?await this.fetchFn(o,t):await fetch(o);if(!a.ok)throw new Error(`Failed to fetch Kanonak package: ${o} (${a.status} ${a.statusText})`);let g=await a.text(),h=this.parser.parse(g);return u(h,t,n.packageName,e),this.onFetch&&this.onFetch(t,n.packageName,e,g),this.documents.set(s,h),this.contentCache.set(s,g),h}async resolveByRedirect(t,n){let r=n.packageName,s=n.versionOperator===C.Exact?await this.publisherIndex.getPackageUrl(t,r,v(n.version)):`https://${t}/${r}.kan.yml`,i=await this.fetchFollowing(s,t);if(!i)return null;let o=this.parser.parse(i.content),a=o.metadata.namespace_;if(!a||!a.version)throw new Error(`Producer origin returned a package with no namespace/version for ${t}/${r}`);let g=v(a.version);u(o,t,r,g);let h=`${t}/${r}@${g}`;return this.onFetch&&this.onFetch(t,r,g,i.content),this.documents.set(h,o),this.contentCache.set(h,i.content),o}async fetchFollowing(t,n,r=4){let e=t;for(let s=0;s<r;s++){let i=this.fetchFn?await this.fetchFn(e,n):await fetch(e,{redirect:"manual"});if(i.status===301||i.status===302){let o=i.headers.get("location");if(!o)throw new Error(`Redirect with no Location header from ${e}`);e=new URL(o,e).toString();continue}if(i.status===404)return null;if(!i.ok)throw new Error(`Failed to fetch Kanonak package: ${e} (${i.status} ${i.statusText})`);return{url:e,content:await i.text()}}throw new Error(`Too many redirects resolving ${t}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,n){return Array.from(this.documents.values()).filter(r=>{let e=r.metadata.namespace_;return e&&e.publisher===t&&e.package_===n})}async saveDocumentAsync(t,n){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,n){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let n=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!n)return null;let[,r,e,s]=n;return this.publisherIndex.getPackageUrl(r,e,s)}};export{A as a,f as b,l as c,F as d};