@kanonak-protocol/sdk 3.44.7 → 3.44.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as ge,b as fe,c as me,d as C,e as E,f as d}from"./chunk-RCI34BYO.js";import{a as Qe}from"./chunk-BFZZ6YGX.js";import{a as H,b as L,c as W,d as F}from"./chunk-VQFL5C7Q.js";import{a as Pe,b as we,c as he}from"./chunk-NIJV5UYW.js";import{a as ye,b as ke,e as be}from"./chunk-4TJZIM7A.js";import"./chunk-NIGFQYVA.js";import{A as We,B as Fe,C as Ge,D 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,j as je,k as ve,l as _e,m as Ie,n as Ae,o as Te,p as Oe,q as Ve,r as $e,s as Ue,t as ze,u as Me,v as Ne,w as Je,x as He,y as qe,z as Le}from"./chunk-SKTXJV4T.js";import"./chunk-FJ35VIV6.js";import{a as Y,c as le,f as pe}from"./chunk-FMYLEPMC.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-W6T7MOKY.js";import{a as q}from"./chunk-7CUTGGH3.js";import{a as O,b as V,c as $,d as U,e as z,f as M,g as N,h as J}from"./chunk-FQHALFRR.js";import{b as ue,c as de}from"./chunk-HEMBMX7T.js";import{a as Z}from"./chunk-FUUTGGJS.js";var j="kanonak-credentials",u="credentials",Ye=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,Ye);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
1
+ import{a as ge,b as fe,c as me,d as C,e as E,f as d}from"./chunk-RCI34BYO.js";import{a as Qe}from"./chunk-BFZZ6YGX.js";import{a as H,b as L,c as W,d as F}from"./chunk-VHUJSHH7.js";import{a as Pe,b as we,c as he}from"./chunk-NIJV5UYW.js";import{a as ye,b as ke,e as be}from"./chunk-4TJZIM7A.js";import"./chunk-NIGFQYVA.js";import{A as We,B as Fe,C as Ge,D 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,j as je,k as ve,l as _e,m as Ie,n as Ae,o as Te,p as Oe,q as Ve,r as $e,s as Ue,t as ze,u as Me,v as Ne,w as Je,x as He,y as qe,z as Le}from"./chunk-SKTXJV4T.js";import"./chunk-FJ35VIV6.js";import{a as Y,c as le,f as pe}from"./chunk-FMYLEPMC.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-W6T7MOKY.js";import{a as q}from"./chunk-7CUTGGH3.js";import{a as O,b as V,c as $,d as U,e as z,f as M,g as N,h as J}from"./chunk-FQHALFRR.js";import{b as ue,c as de}from"./chunk-HEMBMX7T.js";import{a as Z}from"./chunk-FUUTGGJS.js";var j="kanonak-credentials",u="credentials",Ye=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,Ye);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
2
2
  Credential storage requires IndexedDB support in your browser.`))})}async function _(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey);return{signingKey:n.privateKey,publicKeyJwk:r}}async function k(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey),e=await crypto.subtle.exportKey("jwk",n.privateKey);return{keys:{signingKey:n.privateKey,publicKeyJwk:r},dpopKeyPair:{publicKey:r,privateKey:e}}}async function b(n){return{signingKey:await crypto.subtle.importKey("jwk",n.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:n.publicKey}}async function K(n,r,e,t,o){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:n.publicKeyJwk.kty,crv:n.publicKeyJwk.crv,x:n.publicKeyJwk.x,y:n.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:r.toUpperCase(),htu:e,iat:Math.floor(Date.now()/1e3)};return t&&(s.ath=await er(t)),o&&(s.nonce=o),await Ze(a,s,n.signingKey)}function x(n){return!n||n.length===0?!1:n.some(r=>r.toUpperCase()==="ES256")}async function Ze(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 er(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 rr=300*1e3,S=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=x(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=tr(),p=await nr(m),R=or(),A=sr(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)},rr),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 tr(){let n=new Uint8Array(32);return crypto.getRandomValues(n),B(n.buffer)}async function nr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return B(e)}function or(){let n=new Uint8Array(16);return crypto.getRandomValues(n),B(n.buffer)}function sr(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,f as BrowserCredentialBackend,S as BrowserOAuthFlow,Fe as ClassDefinitionRule,Ie as ClassHierarchyCycleRule,X as DefinedKanonak,ze as DefinitionPropertyReferenceRule,fe 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,ge 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,Me as XsdImportRule,x as browserServerSupportsDPoP,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,M as isCompatibleVersion,C as isExpired,N as isMajorCompatible,d as normalizeHost,z as parseVersionString,he as parseWithPositions,J as pickHighestDocument,V as versionsEqual};
@@ -1,2 +1,2 @@
1
- import{a as v}from"./chunk-7CUTGGH3.js";import{a as h,b as d,f as y,g as k}from"./chunk-FQHALFRR.js";var P=class{documents=new Map;documentContents=new Map;parser;constructor(t){this.parser=t}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){let s=[];for(let n of this.documents.values())n.metadata?.namespace_?.publisher===t&&n.metadata?.namespace_?.package_===e&&s.push(n);return s}async getHighestCompatibleVersionAsync(t,e){let s=[];for(let r of this.documents.values())r.metadata?.namespace_?.publisher===t&&r.metadata?.namespace_?.package_===e.packageName&&r.metadata?.namespace_?.version!==void 0&&s.push(r);if(s.length===0)return null;let n=s.filter(r=>{let a=r.metadata.namespace_.version;if(!a)return!1;switch(e.versionOperator){case 0:return d(a,e.version);case 1:return y(a,e.version);case 2:return k(a,e.version);case 3:return h(a,e.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((r,a)=>{let o=r.metadata.namespace_.version,i=a.metadata.namespace_.version;return!o&&!i?0:o?i?h(i,o):-1:1}),n[0])}async saveDocumentAsync(t,e){this.documents.set(e,t);let s=this.parser.save(t);this.documentContents.set(e,s)}async deleteDocumentAsync(t){this.documents.delete(t),this.documentContents.delete(t)}async clearNamespaceAsync(t,e){let s=[];for(let[n,r]of this.documents.entries())r.metadata?.namespace_?.publisher===t&&r.metadata?.namespace_?.package_===e&&s.push(n);for(let n of s)this.documents.delete(n),this.documentContents.delete(n)}async getAllDocumentReferencesAsync(){let t=[];for(let e of this.documents.values())e.metadata?.namespace_&&t.push({identifier:e.metadata.namespace_.toString(),uri:`kanonak://${e.metadata.namespace_}`,hasParseError:!1});return t}async getDocumentContentAsync(t){let e=this.documentContents.get(t);if(e!==void 0)return e;let s=this.documents.get(t);return s!==void 0?this.parser.save(s):null}async getDocumentUriAsync(t){let e=this.documents.get(t);return e?e.metadata?.namespace_?`kanonak://${e.metadata.namespace_}`:`kanonak://${t}`:null}};var x="https://{publisher}/index.txt",F="https://{publisher}/{package}/{version}.kan.yml",C={version:1},m=class{cache=new Map;async getConfig(t){let e=this.cache.get(t);if(e)return e;let s=await this.fetchConfig(t);return this.cache.set(t,s),s}async fetchConfig(t){let e=`https://${t}/.well-known/kanonak.json`,s;try{s=await fetch(e)}catch{return C}if(s.status===404)return C;if(!s.ok)throw new Error(`Failed to fetch publisher config: ${e} (${s.status} ${s.statusText})`);let n=await s.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let r={version:n.version};return typeof n.index=="string"&&(r.index=n.index),typeof n.package=="string"&&(r.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(r.auth=n.auth),r}resolveIndexUrl(t,e){let s=e.index??x;return w(s,{publisher:t})}resolvePackageUrl(t,e,s,n){let r=n.package??F;return w(r,{publisher:t,package:e,version:s})}};function w(c,t){let e=c;for(let[n,r]of Object.entries(t))e=e.replaceAll(`{${n}}`,r);let s=e.match(/\{[a-z]+\}/);if(s)throw new Error(`Unresolved variable ${s[0]} in URL template: ${c}`);return e}import{VersionOperator as g}from"@kanonak-protocol/types/document/models/enums";var u=class c{indexCache=new Map;configResolver;fetchFn;constructor(t){this.configResolver=t?.configResolver??new m,this.fetchFn=t?.fetchFn}async resolveVersion(t,e){let s=await this.getPackageVersions(t,e.packageName);if(s.length===0)return null;let n=s.filter(r=>this.isVersionCompatible(r,e.version,e.versionOperator));return n.length===0?null:(n.sort((r,a)=>this.compareVersionStrings(a,r)),n[0])}async getHighestVersion(t,e){let s=await this.getPackageVersions(t,e);return s.length===0?null:[...s].sort((r,a)=>this.compareVersionStrings(a,r))[0]}async listLatestPackages(t){let e=this.indexCache.get(t);e||(e=await this.fetchIndex(t),this.indexCache.set(t,e));let s=[];for(let[n,r]of e){if(r.length===0)continue;let a=[...r].sort((o,i)=>this.compareVersionStrings(i,o));s.push({packageName:n,version:a[0]})}return s.sort((n,r)=>n.packageName.localeCompare(r.packageName)),s}async getPackageUrl(t,e,s){let n=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,e,s,n)}async getPackageVersions(t,e){let s=this.indexCache.get(t);return s||(s=await this.fetchIndex(t),this.indexCache.set(t,s)),s.get(e)??[]}async fetchIndex(t){let e=await this.configResolver.getConfig(t),s=this.configResolver.resolveIndexUrl(t,e),n=this.fetchFn?await this.fetchFn(s,t):await fetch(s);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${s} (${n.status} ${n.statusText})`);let r=await n.text();return c.parseIndex(r)}static parseIndex(t){let e=new Map;for(let s of t.split(`
2
- `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("/");if(r===-1)continue;let a=n.substring(0,r),o=n.substring(r+1);if(!a||!o)continue;let i=e.get(a);i?i.push(o):e.set(a,[o])}return e}isVersionCompatible(t,e,s){let n=c.parseVersion(t);if(!n)return!1;switch(s){case g.Any:return!0;case g.Exact:return n.major===e.major&&n.minor===e.minor&&n.patch===e.patch;case g.Compatible:return n.major===e.major&&n.minor===e.minor&&n.patch>=e.patch;case g.Major:return n.major!==e.major?!1:n.minor>e.minor?!0:n.minor===e.minor?n.patch>=e.patch:!1;default:return!1}}static parseVersion(t){let e=t.split(".");if(e.length<2)return null;let s=parseInt(e[0],10),n=parseInt(e[1],10),r=e.length>=3?parseInt(e[2],10):0;return isNaN(s)||isNaN(n)||isNaN(r)?null:{major:s,minor:n,patch:r}}compareVersionStrings(t,e){let s=c.parseVersion(t),n=c.parseVersion(e);return!s&&!n?0:s?n?s.major!==n.major?s.major-n.major:s.minor!==n.minor?s.minor-n.minor:s.patch-n.patch:1:-1}};var D=class{parser=new v;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 u({fetchFn:t.fetchFn}):new u}async getHighestCompatibleVersionAsync(t,e){let s=await this.publisherIndex.resolveVersion(t,e);if(!s)return null;let n=`${t}/${e.packageName}@${s}`,r=this.documents.get(n);if(r)return r;if(this.getFromCache){let l=this.getFromCache(t,e.packageName,s);if(l){let f=this.parser.parse(l);return this.documents.set(n,f),this.contentCache.set(n,l),f}}let a=await this.publisherIndex.getPackageUrl(t,e.packageName,s),o=this.fetchFn?await this.fetchFn(a,t):await fetch(a);if(!o.ok)throw new Error(`Failed to fetch Kanonak package: ${a} (${o.status} ${o.statusText})`);let i=await o.text();this.onFetch&&this.onFetch(t,e.packageName,s,i);let p=this.parser.parse(i);return this.documents.set(n,p),this.contentCache.set(n,i),p}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){return Array.from(this.documents.values()).filter(s=>{let n=s.metadata.namespace_;return n&&n.publisher===t&&n.package_===e})}async saveDocumentAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let e=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,s,n,r]=e;return this.publisherIndex.getPackageUrl(s,n,r)}};export{P as a,m as b,u as c,D as d};
1
+ import{a as k}from"./chunk-7CUTGGH3.js";import{a as h,b as d,f as y,g as v}from"./chunk-FQHALFRR.js";var P=class{documents=new Map;documentContents=new Map;parser;constructor(t){this.parser=t}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){let s=[];for(let n of this.documents.values())n.metadata?.namespace_?.publisher===t&&n.metadata?.namespace_?.package_===e&&s.push(n);return s}async getHighestCompatibleVersionAsync(t,e){let s=[];for(let r of this.documents.values())r.metadata?.namespace_?.publisher===t&&r.metadata?.namespace_?.package_===e.packageName&&r.metadata?.namespace_?.version!==void 0&&s.push(r);if(s.length===0)return null;let n=s.filter(r=>{let a=r.metadata.namespace_.version;if(!a)return!1;switch(e.versionOperator){case 0:return d(a,e.version);case 1:return y(a,e.version);case 2:return v(a,e.version);case 3:return h(a,e.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((r,a)=>{let o=r.metadata.namespace_.version,i=a.metadata.namespace_.version;return!o&&!i?0:o?i?h(i,o):-1:1}),n[0])}async saveDocumentAsync(t,e){this.documents.set(e,t);let s=this.parser.save(t);this.documentContents.set(e,s)}async deleteDocumentAsync(t){this.documents.delete(t),this.documentContents.delete(t)}async clearNamespaceAsync(t,e){let s=[];for(let[n,r]of this.documents.entries())r.metadata?.namespace_?.publisher===t&&r.metadata?.namespace_?.package_===e&&s.push(n);for(let n of s)this.documents.delete(n),this.documentContents.delete(n)}async getAllDocumentReferencesAsync(){let t=[];for(let e of this.documents.values())e.metadata?.namespace_&&t.push({identifier:e.metadata.namespace_.toString(),uri:`kanonak://${e.metadata.namespace_}`,hasParseError:!1});return t}async getDocumentContentAsync(t){let e=this.documentContents.get(t);if(e!==void 0)return e;let s=this.documents.get(t);return s!==void 0?this.parser.save(s):null}async getDocumentUriAsync(t){let e=this.documents.get(t);return e?e.metadata?.namespace_?`kanonak://${e.metadata.namespace_}`:`kanonak://${t}`:null}};var D="https://{publisher}/index.txt",F="https://{publisher}/{package}/{version}.kan.yml",C={version:1},u=class{cache=new Map;getConfig(t){let e=this.cache.get(t);return e||(e=this.fetchConfig(t),this.cache.set(t,e),e.catch(()=>{this.cache.get(t)===e&&this.cache.delete(t)})),e}async fetchConfig(t){let e=`https://${t}/.well-known/kanonak.json`,s;try{s=await fetch(e)}catch{return C}if(s.status===404)return C;if(!s.ok)throw new Error(`Failed to fetch publisher config: ${e} (${s.status} ${s.statusText})`);let n=await s.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let r={version:n.version};return typeof n.index=="string"&&(r.index=n.index),typeof n.package=="string"&&(r.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(r.auth=n.auth),r}resolveIndexUrl(t,e){let s=e.index??D;return x(s,{publisher:t})}resolvePackageUrl(t,e,s,n){let r=n.package??F;return x(r,{publisher:t,package:e,version:s})}};function x(c,t){let e=c;for(let[n,r]of Object.entries(t))e=e.replaceAll(`{${n}}`,r);let s=e.match(/\{[a-z]+\}/);if(s)throw new Error(`Unresolved variable ${s[0]} in URL template: ${c}`);return e}import{VersionOperator as g}from"@kanonak-protocol/types/document/models/enums";var m=class c{indexCache=new Map;configResolver;fetchFn;constructor(t){this.configResolver=t?.configResolver??new u,this.fetchFn=t?.fetchFn}async resolveVersion(t,e){let s=await this.getPackageVersions(t,e.packageName);if(s.length===0)return null;let n=s.filter(r=>this.isVersionCompatible(r,e.version,e.versionOperator));return n.length===0?null:(n.sort((r,a)=>this.compareVersionStrings(a,r)),n[0])}async getHighestVersion(t,e){let s=await this.getPackageVersions(t,e);return s.length===0?null:[...s].sort((r,a)=>this.compareVersionStrings(a,r))[0]}async listLatestPackages(t){let e=await this.getIndex(t),s=[];for(let[n,r]of e){if(r.length===0)continue;let a=[...r].sort((o,i)=>this.compareVersionStrings(i,o));s.push({packageName:n,version:a[0]})}return s.sort((n,r)=>n.packageName.localeCompare(r.packageName)),s}async getPackageUrl(t,e,s){let n=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,e,s,n)}async getPackageVersions(t,e){return(await this.getIndex(t)).get(e)??[]}getIndex(t){let e=this.indexCache.get(t);return e||(e=this.fetchIndex(t),this.indexCache.set(t,e),e.catch(()=>{this.indexCache.get(t)===e&&this.indexCache.delete(t)})),e}async fetchIndex(t){let e=await this.configResolver.getConfig(t),s=this.configResolver.resolveIndexUrl(t,e),n=this.fetchFn?await this.fetchFn(s,t):await fetch(s);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${s} (${n.status} ${n.statusText})`);let r=await n.text();return c.parseIndex(r)}static parseIndex(t){let e=new Map;for(let s of t.split(`
2
+ `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("/");if(r===-1)continue;let a=n.substring(0,r),o=n.substring(r+1);if(!a||!o)continue;let i=e.get(a);i?i.push(o):e.set(a,[o])}return e}isVersionCompatible(t,e,s){let n=c.parseVersion(t);if(!n)return!1;switch(s){case g.Any:return!0;case g.Exact:return n.major===e.major&&n.minor===e.minor&&n.patch===e.patch;case g.Compatible:return n.major===e.major&&n.minor===e.minor&&n.patch>=e.patch;case g.Major:return n.major!==e.major?!1:n.minor>e.minor?!0:n.minor===e.minor?n.patch>=e.patch:!1;default:return!1}}static parseVersion(t){let e=t.split(".");if(e.length<2)return null;let s=parseInt(e[0],10),n=parseInt(e[1],10),r=e.length>=3?parseInt(e[2],10):0;return isNaN(s)||isNaN(n)||isNaN(r)?null:{major:s,minor:n,patch:r}}compareVersionStrings(t,e){let s=c.parseVersion(t),n=c.parseVersion(e);return!s&&!n?0:s?n?s.major!==n.major?s.major-n.major:s.minor!==n.minor?s.minor-n.minor:s.patch-n.patch:1:-1}};var w=class{parser=new k;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new m({fetchFn:t.fetchFn}):new m}async getHighestCompatibleVersionAsync(t,e){let s=await this.publisherIndex.resolveVersion(t,e);if(!s)return null;let n=`${t}/${e.packageName}@${s}`,r=this.documents.get(n);if(r)return r;if(this.getFromCache){let l=this.getFromCache(t,e.packageName,s);if(l){let f=this.parser.parse(l);return this.documents.set(n,f),this.contentCache.set(n,l),f}}let a=await this.publisherIndex.getPackageUrl(t,e.packageName,s),o=this.fetchFn?await this.fetchFn(a,t):await fetch(a);if(!o.ok)throw new Error(`Failed to fetch Kanonak package: ${a} (${o.status} ${o.statusText})`);let i=await o.text();this.onFetch&&this.onFetch(t,e.packageName,s,i);let p=this.parser.parse(i);return this.documents.set(n,p),this.contentCache.set(n,i),p}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){return Array.from(this.documents.values()).filter(s=>{let n=s.metadata.namespace_;return n&&n.publisher===t&&n.package_===e})}async saveDocumentAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let e=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,s,n,r]=e;return this.publisherIndex.getPackageUrl(s,n,r)}};export{P as a,u as b,m as c,w as d};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as et,b as tt,c as rt,d as nt,e as ot,f as at,g as it,h as st,i as ct,j as lt}from"./chunk-IOJMTW4T.js";import{b as Xt}from"./chunk-ZI7Y5RI3.js";import{a as Xe,b as Ze,c as Qe,d as b,e as S,f as i}from"./chunk-RCI34BYO.js";import{a as Yt}from"./chunk-BFZZ6YGX.js";import{a as Te,b as je,c as Le,d as Fe,e as Ne}from"./chunk-5AH6GIPO.js";import{a as Be,b as De,c as Oe,d as Ae}from"./chunk-VQFL5C7Q.js";import{a as ut,b as pt,c as mt,d as ft}from"./chunk-NIJV5UYW.js";import{a as Ye,b as yt,c as gt,d as ht,e as bt}from"./chunk-4TJZIM7A.js";import{a as kt}from"./chunk-NIGFQYVA.js";import{A as Gt,B as Wt,C as Jt,D as qt,a as St,b as Ct,c as Pt,d as Rt,e as wt,f as xt,g as $t,h as vt,i as Et,j as Kt,k as Bt,l as It,m as Tt,n as jt,o as Lt,p as Ft,q as Nt,r as Dt,s as Ot,t as At,u as Ut,v as Mt,w as Vt,x as Ht,y as _t,z as zt}from"./chunk-SKTXJV4T.js";import"./chunk-FJ35VIV6.js";import{a as F,b as D,c as _e,d as We,e as Je,f as qe}from"./chunk-FMYLEPMC.js";import{a as Ue,b as j,c as L,d as N,e as Ve,f as He,g as O,h as A,i as U,j as M,k as V,l as H}from"./chunk-W6T7MOKY.js";import{a as Ie}from"./chunk-7CUTGGH3.js";import{a as Pe,b as Re,c as we,d as xe,e as $e,f as ve,g as Ee,h as Ke}from"./chunk-FQHALFRR.js";import{b as ze,c as Ge}from"./chunk-HEMBMX7T.js";import{a as Me}from"./chunk-FUUTGGJS.js";import{a as dt}from"./chunk-ODIECDN7.js";import{VersionOperator as io}from"@kanonak-protocol/types/document/models/enums";import{existsSync as yr,readFileSync as gr}from"fs";import{homedir as hr}from"os";import{join as kr}from"path";import{execFile as Zt}from"child_process";import{promisify as Qt}from"util";var C=Qt(Zt),P="kanonak",R="/usr/bin/security",p=class{async get(e){let r=i(e);try{let{stdout:n}=await C(R,["find-generic-password","-s",P,"-a",r,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${r}' is corrupted (not valid JSON).
1
+ import{a as et,b as tt,c as rt,d as nt,e as ot,f as at,g as it,h as st,i as ct,j as lt}from"./chunk-IOJMTW4T.js";import{b as Xt}from"./chunk-ZI7Y5RI3.js";import{a as Xe,b as Ze,c as Qe,d as b,e as S,f as i}from"./chunk-RCI34BYO.js";import{a as Yt}from"./chunk-BFZZ6YGX.js";import{a as Te,b as je,c as Le,d as Fe,e as Ne}from"./chunk-5AH6GIPO.js";import{a as Be,b as De,c as Oe,d as Ae}from"./chunk-VHUJSHH7.js";import{a as ut,b as pt,c as mt,d as ft}from"./chunk-NIJV5UYW.js";import{a as Ye,b as yt,c as gt,d as ht,e as bt}from"./chunk-4TJZIM7A.js";import{a as kt}from"./chunk-NIGFQYVA.js";import{A as Gt,B as Wt,C as Jt,D as qt,a as St,b as Ct,c as Pt,d as Rt,e as wt,f as xt,g as $t,h as vt,i as Et,j as Kt,k as Bt,l as It,m as Tt,n as jt,o as Lt,p as Ft,q as Nt,r as Dt,s as Ot,t as At,u as Ut,v as Mt,w as Vt,x as Ht,y as _t,z as zt}from"./chunk-SKTXJV4T.js";import"./chunk-FJ35VIV6.js";import{a as F,b as D,c as _e,d as We,e as Je,f as qe}from"./chunk-FMYLEPMC.js";import{a as Ue,b as j,c as L,d as N,e as Ve,f as He,g as O,h as A,i as U,j as M,k as V,l as H}from"./chunk-W6T7MOKY.js";import{a as Ie}from"./chunk-7CUTGGH3.js";import{a as Pe,b as Re,c as we,d as xe,e as $e,f as ve,g as Ee,h as Ke}from"./chunk-FQHALFRR.js";import{b as ze,c as Ge}from"./chunk-HEMBMX7T.js";import{a as Me}from"./chunk-FUUTGGJS.js";import{a as dt}from"./chunk-ODIECDN7.js";import{VersionOperator as io}from"@kanonak-protocol/types/document/models/enums";import{existsSync as yr,readFileSync as gr}from"fs";import{homedir as hr}from"os";import{join as kr}from"path";import{execFile as Zt}from"child_process";import{promisify as Qt}from"util";var C=Qt(Zt),P="kanonak",R="/usr/bin/security",p=class{async get(e){let r=i(e);try{let{stdout:n}=await C(R,["find-generic-password","-s",P,"-a",r,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${r}' is corrupted (not valid JSON).
2
2
  Run 'kanonak logout ${r}' then 'kanonak login ${r}' to fix.`)}}catch(n){if(X(n,44))return null;throw new Error(`macOS Keychain read failed for '${r}': ${w(n)}
3
3
  The Keychain may be locked or inaccessible.
4
4
  Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,r){let n=i(e),o=JSON.stringify(r);try{await C(R,["add-generic-password","-s",P,"-a",n,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${n}': ${w(a)}
@@ -25,6 +25,12 @@ export declare class PublisherIndex {
25
25
  }[]>;
26
26
  getPackageUrl(publisher: string, packageName: string, version: string): Promise<string>;
27
27
  private getPackageVersions;
28
+ /**
29
+ * Resolve the publisher's index, de-duplicating concurrent fetches by
30
+ * memoizing the in-flight promise. Evicts on failure so a transient error
31
+ * doesn't poison the cache for the process lifetime.
32
+ */
33
+ private getIndex;
28
34
  private fetchIndex;
29
35
  static parseIndex(text: string): Map<string, string[]>;
30
36
  private isVersionCompatible;
@@ -1 +1 @@
1
- import{a as o,b as e,c as r,d as n}from"../chunk-VQFL5C7Q.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
1
+ import{a as o,b as e,c as r,d as n}from"../chunk-VHUJSHH7.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.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}from"../chunk-5AH6GIPO.js";import{a,b as g,c as h,d as i}from"../chunk-VQFL5C7Q.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,i as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,g as PublisherConfigResolver,h as PublisherIndex,f as RepositoryFactory,e as getGlobalCachePath};
1
+ import{a as b,b as c,c as d,d as e,e as f}from"../chunk-5AH6GIPO.js";import{a,b as g,c as h,d as i}from"../chunk-VHUJSHH7.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,i as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,g as PublisherConfigResolver,h as PublisherIndex,f as RepositoryFactory,e as getGlobalCachePath};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "3.44.7",
3
+ "version": "3.44.8",
4
4
  "description": "Kanonak Protocol SDK - Document repository and parsing implementations for TypeScript",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -113,7 +113,7 @@
113
113
  "yaml-parser"
114
114
  ],
115
115
  "dependencies": {
116
- "@kanonak-protocol/types": "^3.44.7",
116
+ "@kanonak-protocol/types": "^3.44.8",
117
117
  "ignore": "^7.0.5",
118
118
  "js-yaml": "^4.1.0",
119
119
  "yaml": "^2.7.0"