@kanonak-protocol/sdk 5.6.0 → 5.8.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/auth/DeviceCertificateStore.d.ts +9 -0
- package/dist/browser.js +1 -1
- package/dist/{chunk-3BNJXSVZ.js → chunk-CC44JAOT.js} +1 -1
- package/dist/chunk-L2KE7B3K.js +2 -0
- package/dist/chunk-UXYCUGSF.js +1 -0
- package/dist/http/kanonakFetch.d.ts +13 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +15 -16
- package/dist/repositories/browser.js +1 -1
- package/dist/repositories/index.js +1 -1
- package/dist/server/index.js +8 -8
- package/package.json +2 -2
- package/dist/chunk-XGTUVPR3.js +0 -1
|
@@ -26,6 +26,15 @@ export interface DeviceEnrollmentRecord {
|
|
|
26
26
|
scopes: string[];
|
|
27
27
|
/** A human-facing device label shown on the consent screen. */
|
|
28
28
|
deviceName?: string;
|
|
29
|
+
/**
|
|
30
|
+
* The PUBLISHER the user connected/enrolled through (e.g. `paul.kanonak.com`).
|
|
31
|
+
* Enrollments are keyed by the AUTHORITY (e.g. `oauth--paul.kanonak.com`), but
|
|
32
|
+
* users only know the publisher — this records it so `device list`/`show`/
|
|
33
|
+
* `remove` can be publisher-centric (display it, and resolve a publisher to its
|
|
34
|
+
* enrollment locally without a network round-trip). Optional: records written
|
|
35
|
+
* before this field, or by a non-publisher enroll, won't carry it.
|
|
36
|
+
*/
|
|
37
|
+
publisher?: string;
|
|
29
38
|
}
|
|
30
39
|
/**
|
|
31
40
|
* The portion of a {@link DeviceEnrollmentRecord} kept in the platform-secure
|
package/dist/browser.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as B,b as H,c as L,d as Pe,e as ge,f as Ke,g as Ce,h as be,i as Ie,j as Ve}from"./chunk-VOJ6BGAR.js";import{a as Se}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as m,b as u,c,e as d,
|
|
1
|
+
import{a as B,b as H,c as L,d as Pe,e as ge,f as Ke,g as Ce,h as be,i as Ie,j as Ve}from"./chunk-VOJ6BGAR.js";import{a as Se}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as m,b as u,c,e as d,h as y,j as R,k as f}from"./chunk-UXYCUGSF.js";import{a as p}from"./chunk-4NO7MHS7.js";import{a as G,b as w,c as _}from"./chunk-S6VSAKXB.js";import{a as q,b as F}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as fe,B as ke,K as xe,a as W,b as z,c as J,d as Q,f as X,g as Y,h as Z,i as $,k as ee,l as oe,m as te,n as re,o as ne,p as ae,q as ie,r as se,s as pe,t as le,u as me,v as ue,w as ce,x as de,y as ye,z as Re}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as g,c as E,h as T,i as M,l as A}from"./chunk-MX3DEXMV.js";import{a as l}from"./chunk-NJ3AZYQD.js";import{a as U}from"./chunk-ZP6P7HNU.js";import"./chunk-6U26UASC.js";import{a as N,b as v}from"./chunk-GZPLWII7.js";import{a as k,b as x,c as P,d as S,e as C,f as b,g as I,h as V,i as h,j,k as D,l as O}from"./chunk-7BHDZHJY.js";import{a as K}from"./chunk-FUUTGGJS.js";import{c as e,d as o,e as t,f as r,g as n,h as a,i,j as s}from"./chunk-2ACBWC7K.js";export{me as AmbiguousReferenceRule,h as BooleanStatement,Ie as CANONICAL_FORM_VERSION,T as Carrier,fe as ClassDefinitionRule,re as ClassHierarchyCycleRule,x as DefinedKanonak,H as EdgeType,g as EmbeddedKanonak,ee as EmbeddedKanonakTypeRule,D as EmbeddedStatement,L as GraphBuilder,f as HttpKanonakDocumentRepository,oe as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,m as KANONAK_USER_AGENT,k as Kanonak,w as KanonakDocumentPositions,A as KanonakObjectParser,xe as KanonakObjectValidator,l as KanonakParser,K as KanonakUri,q as KanonakUriBuilder,O as ListStatement,ke as MarkdownLinkRule,E as MarkdownStatement,pe as NamespaceImportCycleRule,X as NamespacePrefixRule,B as NodeType,V as NumberStatement,ce as ObjectPropertyValueValidationRule,J as OntologyValidationError,W as OntologyValidationResult,de as PropertyDomainRule,ne as PropertyHierarchyCycleRule,ye as PropertyKindRangeConsistencyRule,G as PropertyMetadata,ue as PropertyRangeReferenceRule,ae as PropertyRangeRequiredRule,Z as PropertyTypeSpecificityRule,y as PublisherConfigResolver,R as PublisherIndex,S as ReferenceKanonak,j as ReferenceStatement,Re as ReservedNameShadowRule,Y as ResourceNamingRule,N as ResourceResolver,U as ResourceTypeClassifier,b as ScalarStatement,C as Statement,I as StringStatement,ie as SubClassOfReferenceRule,se as SubPropertyOfReferenceRule,P as SubjectKanonak,$ as SubjectKanonakTypeRequiredRule,v as TypeResolver,le as UnresolvedPredicateRule,te as UnresolvedReferenceRule,Q as ValidationContext,z as ValidationSeverity,Ve as buildOntologyModel,Ce as canonicalForm,be as canonicalHash,M as carrierOf,e as compareVersions,r as createVersion,Se as findDerivation,F as findInstancesByType,t as formatVersion,c as getKanonakUserAgent,ge as hasValidToken,a as isCompatibleVersion,Pe as isExpired,i as isMajorCompatible,d as kanonakFetch,Ke as normalizeHost,n as parseVersionString,_ as parseWithPositions,s as pickHighestDocument,u as setKanonakUserAgent,o as versionsEqual};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as v}from"./chunk-XGTUVPR3.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{k as v}from"./chunk-UXYCUGSF.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{i}from"./chunk-UXYCUGSF.js";import{readFileSync as a,writeFileSync as c,existsSync as l}from"fs";import{createHash as p}from"crypto";import u from"js-yaml";var s="kanonak.lock",f=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
2
|
+
`;function m(e=s){return l(e)?i(a(e,"utf-8")):null}function F(e,t=s){e.lastUpdated=new Date().toISOString();let o={};for(let n of Object.keys(e.packages).sort())o[n]=e.packages[n];e.packages=o;let r=u.dump(e,{lineWidth:-1,sortKeys:!1,quotingType:'"'});c(t,f+r,"utf-8")}function L(e){return`sha256:${p("sha256").update(e).digest("hex")}`}export{m as a,F as b,L as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as F}from"./chunk-SC5M74NM.js";import{a as A}from"./chunk-NJ3AZYQD.js";import{e as v,g as R}from"./chunk-2ACBWC7K.js";var U="@kanonak-protocol/sdk (+https://kanonak.org)",w=U;function B(o){w=o}function O(){return w}function m(o){let t;try{t=typeof o=="string"?new URL(o):o}catch{throw new Error(`Kanonak requires an absolute https:// URL \u2014 got an unparseable or relative URL: ${String(o)}`)}if(t.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${t.href} (only https:// is supported).`)}var D=new Set([429,502,503,504]),b=4,K=500,C=2e4;function u(o,t){m(o);let e=new Headers(t?.headers);return e.has("User-Agent")||e.set("User-Agent",w),I(o,{...t,headers:e})}var k=b;function q(o){k=Math.max(0,o)}async function I(o,t){let e;for(let n=0;n<=k;n++){let r;try{r=await fetch(o,t)}catch(s){if(e=s,n>=k)throw s;await $(x(n,null));continue}if(!D.has(r.status)||n>=k)return r;await $(x(n,r.headers.get("retry-after")))}throw e??new Error("kanonakFetch: exhausted retries")}function x(o,t){let e=T(t);if(e!=null)return Math.min(e,C);let n=Math.min(C,K*2**o);return Math.floor(n/2+Math.random()*(n/2))}function T(o){if(!o)return null;let t=Number(o);if(Number.isFinite(t))return Math.max(0,t*1e3);let e=Date.parse(o);return Number.isNaN(e)?null:Math.max(0,e-Date.now())}function $(o){return new Promise(t=>setTimeout(t,o))}var M="https://{publisher}/{package}/{version}.kan.yml",E={version:1};function W(){return{version:1}}var y=class{constructor(t){this.fetchFn=t}fetchFn;cache=new Map;getConfig(t){let e=this.cache.get(t);return e||(e=this.fetchConfig(t),this.cache.set(t,e),e.catch(()=>{this.cache.get(t)===e&&this.cache.delete(t)})),e}async fetchConfig(t){let e=`https://${t}/.well-known/kanonak.json`,n;try{n=await(this.fetchFn?this.fetchFn(e,t):u(e))}catch{return E}if(n.status===404)return E;if(!n.ok)throw new Error(`Failed to fetch publisher config: ${e} (${n.status} ${n.statusText})`);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let s={version:r.version};return typeof r.package_url_template=="string"&&(j(e,"package_url_template",r.package_url_template),s.package_url_template=r.package_url_template),Array.isArray(r.featured_packages)&&r.featured_packages.every(i=>typeof i=="string")&&(s.featured_packages=r.featured_packages),s}resolvePackageUrl(t,e,n,r){let s=r.package_url_template??M,i=N(s,{publisher:t,package:e,version:n});return m(i),i}};function j(o,t,e){if(!e.startsWith("https://"))throw new Error(`Invalid publisher config at ${o}: ${t} must be an absolute https:// URL template (got "${e}").`)}function N(o,t){let e=o;for(let[r,s]of Object.entries(t))e=e.replaceAll(`{${r}}`,s);let n=e.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${o}`);return e}import S from"js-yaml";function L(o){let t=S.load(o);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??"",packages:t.packages??{}}}var p=class{configResolver;fetchFn;lockCache=new Map;constructor(t){this.configResolver=t?.configResolver??new y(t?.fetchFn),this.fetchFn=t?.fetchFn}getConfig(t){return this.configResolver.getConfig(t)}async getPackageUrl(t,e,n){let r=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,e,n,r)}getLock(t){let e=this.lockCache.get(t);return e||(e=this.fetchLock(t),this.lockCache.set(t,e),e.catch(()=>{this.lockCache.get(t)===e&&this.lockCache.delete(t)})),e}async fetchLock(t){let e=`https://${t}/kanonak.lock`,n;try{n=this.fetchFn?await this.fetchFn(e,t):await u(e)}catch{return null}if(n.status===404)return null;if(!n.ok)throw new Error(`Failed to fetch publisher lock: ${e} (${n.status} ${n.statusText})`);return L(await n.text())}};import{VersionOperator as d}from"@kanonak-protocol/types/document/models/enums";function H(o,t){let e=R(o);if(!e)return!1;let n=t.version;switch(t.versionOperator){case d.Any:return!0;case d.Exact:return e.major===n.major&&e.minor===n.minor&&e.patch===n.patch;case d.Compatible:return e.major===n.major&&e.minor===n.minor&&e.patch>=n.patch;case d.Major:return e.major!==n.major?!1:e.minor!==n.minor?e.minor>n.minor:e.patch>=n.patch;default:return!1}}var _=class{parser=new A;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new p({fetchFn:t.fetchFn}):new p}async getHighestCompatibleVersionAsync(t,e){let r=(await this.publisherIndex.getLock(t))?.packages[`${t}/${e.packageName}`];return r?H(r.version,e)?this.fetchPinned(t,e.packageName,r):null:this.resolveByDirectFetch(t,e)}async fetchPinned(t,e,n){let r=n.version,s=`${t}/${e}@${r}`,i=this.documents.get(s);if(i)return i;let a=g=>{let f=this.parser.parse(g);return F(f,t,e,r),f};if(this.getFromCache){let g=this.getFromCache(t,e,r);if(g){let f=a(g);return this.documents.set(s,f),this.contentCache.set(s,g),f}}let l=n.resolved,c=this.fetchFn?await this.fetchFn(l,t):await u(l);if(!c.ok)throw new Error(`Failed to fetch Kanonak package: ${l} (${c.status} ${c.statusText})`);let h=await c.text(),P=a(h);return this.onFetch&&this.onFetch(t,e,r,h),this.documents.set(s,P),this.contentCache.set(s,h),P}async resolveByDirectFetch(t,e){let n=e.packageName,s=e.versionOperator===d.Exact?await this.publisherIndex.getPackageUrl(t,n,v(e.version)):`https://${t}/${n}.kan.yml`,i=await this.fetchFollowing(s,t);if(!i)return null;let a=this.parser.parse(i.content),l=a.metadata.namespace_;if(!l||!l.version)throw new Error(`Producer origin returned a package with no namespace/version for ${t}/${n}`);let c=v(l.version);F(a,t,n,c);let h=`${t}/${n}@${c}`;return this.onFetch&&this.onFetch(t,n,c,i.content),this.documents.set(h,a),this.contentCache.set(h,i.content),a}async fetchFollowing(t,e,n=4){let r=t;for(let s=0;s<n;s++){m(r);let i=this.fetchFn?await this.fetchFn(r,e):await u(r,{redirect:"manual"});if(i.status===301||i.status===302){let a=i.headers.get("location");if(!a)throw new Error(`Redirect with no Location header from ${r}`);r=new URL(a,r).toString();continue}if(i.status===404)return null;if(!i.ok)throw new Error(`Failed to fetch Kanonak package: ${r} (${i.status} ${i.statusText})`);return{url:r,content:await i.text()}}throw new Error(`Too many redirects resolving ${t}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===t&&r.package_===e})}async saveDocumentAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let e=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,n,r,s]=e;return this.publisherIndex.getPackageUrl(n,r,s)}};export{U as a,B as b,O as c,m as d,u as e,q as f,W as g,y as h,L as i,p as j,_ as k};
|
|
@@ -53,5 +53,18 @@ export declare function assertHttpsUrl(url: string | URL): void;
|
|
|
53
53
|
* `fetch` with the SDK's User-Agent added — unless the caller already set one,
|
|
54
54
|
* which is preserved. All other `init` fields pass through untouched. Rejects
|
|
55
55
|
* any non-https target up front via {@link assertHttpsUrl}.
|
|
56
|
+
*
|
|
57
|
+
* Retries transient failures (429/502/503/504 and network errors) with
|
|
58
|
+
* EXPONENTIAL BACKOFF + jitter, honoring a `Retry-After` header when present, so
|
|
59
|
+
* a rate-limited or struggling origin (e.g. kanonak.org) is backed off rather
|
|
60
|
+
* than hammered. Retries are bounded ({@link MAX_RETRIES}); a non-retryable
|
|
61
|
+
* status (200/404/302/4xx) returns immediately, and a final 429/5xx is returned
|
|
62
|
+
* to the caller to handle. The {@link setKanonakFetchRetries} seam disables the
|
|
63
|
+
* waits in tests.
|
|
56
64
|
*/
|
|
57
65
|
export declare function kanonakFetch(input: string | URL, init?: RequestInit): Promise<Response>;
|
|
66
|
+
/**
|
|
67
|
+
* Override the retry count for {@link kanonakFetch} — set to 0 to disable
|
|
68
|
+
* backoff entirely (tests that simulate 429/5xx without waiting on real timers).
|
|
69
|
+
*/
|
|
70
|
+
export declare function setKanonakFetchRetries(n: number): void;
|
package/dist/index.d.ts
CHANGED
|
@@ -23,7 +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, DeviceCertificateStore, SessionStore, sessionNeedsRefresh, OAuthDiscovery, DEFAULT_CONSENT_BINDING_PARAM, SessionExchange, SessionExchangeError, SessionManager, SessionError, CredentialResolver, createAuthenticatedFetch, generateDPoPKeyPair, createDPoPProof, serverSupportsDPoP, isExpired, hasValidToken, normalizeHost, } from './auth/index.js';
|
|
25
25
|
export type { SecretBackend, CredentialBackend, StoredCredential, DeviceEnrollmentRecord, SessionRecord, SessionStoreDeps, OAuthServerMetadata, ExchangedSession, MtlsTransport, SessionManagerDeps, SessionDiscovery, DeviceStoreLike, ResolvedCredential, CredentialResolverDeps, DPoPKeyPair, AuthenticatedFetchFn, } from './auth/index.js';
|
|
26
|
-
export { kanonakFetch, assertHttpsUrl, setKanonakUserAgent, getKanonakUserAgent, KANONAK_USER_AGENT, } from './http/kanonakFetch.js';
|
|
26
|
+
export { kanonakFetch, assertHttpsUrl, setKanonakFetchRetries, setKanonakUserAgent, getKanonakUserAgent, KANONAK_USER_AGENT, } from './http/kanonakFetch.js';
|
|
27
27
|
export { loadLockFile, saveLockFile, computeIntegrity, } from './lock/index.js';
|
|
28
28
|
export type { LockFile, LockEntry } from './lock/index.js';
|
|
29
29
|
export { findDerivation } from './derivation/index.js';
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if(
|
|
1
|
+
import{a as Er,b as xr,c as Cr,d as Ar,e as ke}from"./chunk-TVSHIXLA.js";import{a as je,b as Me,c as Ve}from"./chunk-L2KE7B3K.js";import{a as Sn,c as ve,e as Le,h as Ue,i as Fe,j as vn}from"./chunk-IHB7UVEH.js";import{a as wr,b as br,c as Rr,d as Z,e as Y,f as c,g as Pn,h as Pe,i as wn,j as bn}from"./chunk-VOJ6BGAR.js";import{a as kn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as It,b as Nt,c as Bt,d as Ot,e as jt,f as Jt,g as qt,h as Xt,i as Zt}from"./chunk-CC44JAOT.js";import{a as Mt,b as Vt,c as Lt,d as Ut,e as C,f as Ft,h as Ht,j as zt,k as Gt}from"./chunk-UXYCUGSF.js";import{a as Kt}from"./chunk-4NO7MHS7.js";import{a as Tr,b as $r,c as _r,d as Kr}from"./chunk-S6VSAKXB.js";import{a as Ir,b as Lr}from"./chunk-PEUTCG3B.js";import{a as Br}from"./chunk-PEJALHXK.js";import{a as Wt}from"./chunk-SC5M74NM.js";import{A as fn,B as hn,K as gn,a as Ur,b as Fr,c as Hr,d as zr,e as Wr,f as Gr,g as Jr,h as qr,i as Xr,j as Zr,k as Yr,l as Qr,m as en,n as tn,o as rn,p as nn,q as on,r as sn,s as an,t as cn,u as ln,v as dn,w as pn,x as un,y as mn,z as yn}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as D,b as tr,c as dr,h as mr,i as yr,j as Sr,k as vr,l as L}from"./chunk-MX3DEXMV.js";import{a as O}from"./chunk-NJ3AZYQD.js";import{a as Pr,b as Se,c as Nr,d as P,e as Or,f as jr,g as Mr,h as Vr}from"./chunk-ZP6P7HNU.js";import{a as Oe}from"./chunk-6U26UASC.js";import{a as pr,b as ur,c as V,d as fr,e as hr,g as gr,k as kr}from"./chunk-GZPLWII7.js";import{a as Yt,b as Qt,c as A,d as j,e as rr,f as nr,g as or,h as sr,i as ir,j as ar,k as cr,l as lr,r as X,w as M,x as he,y as ge}from"./chunk-7BHDZHJY.js";import{a as er}from"./chunk-FUUTGGJS.js";import{a as xt,b as fe,c as q,d as Ct,e as R,f as At,g as Dt,h as Tt,i as $t,j as _t}from"./chunk-2ACBWC7K.js";import{a as Dr}from"./chunk-ODIECDN7.js";import{VersionOperator as aa}from"@kanonak-protocol/types/document/models/enums";import{existsSync as zn,readFileSync as Wn}from"fs";import{homedir as Gn}from"os";import{join as Jn}from"path";import{execFile as Rn}from"child_process";import{promisify as En}from"util";var Q=En(Rn),xn="kanonak",ee="/usr/bin/security",m=class{constructor(e=xn){this.service=e}service;async get(e){let t=c(e);try{let{stdout:r}=await Q(ee,["find-generic-password","-s",this.service,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
|
|
2
|
+
Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if(He(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${te(r)}
|
|
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,t){let r=c(e),n=JSON.stringify(t);try{await Q(ee,["add-generic-password","-s",this.service,"-a",r,"-U","-w",n],{timeout:1e4})}catch(s){throw new Error(`macOS Keychain write failed for '${r}': ${te(s)}
|
|
5
5
|
Ensure the Keychain is unlocked and the CLI has write permission.
|
|
6
|
-
On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=c(e);try{await Q(ee,["delete-generic-password","-s",this.service,"-a",t],{timeout:1e4})}catch(r){if(
|
|
6
|
+
On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=c(e);try{await Q(ee,["delete-generic-password","-s",this.service,"-a",t],{timeout:1e4})}catch(r){if(He(r,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${te(r)}
|
|
7
7
|
The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await Q(ee,["dump-keychain"],{timeout:1e4}),t=[],r=!1;for(let n of e.split(`
|
|
8
|
-
`))if(n.includes(`"svce"<blob>="${this.service}"`)&&(r=!0),r&&n.includes('"acct"<blob>=')){let s=n.match(/"acct"<blob>="([^"]+)"/);s&&t.push(s[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${te(e)}`),[]}}};function
|
|
8
|
+
`))if(n.includes(`"svce"<blob>="${this.service}"`)&&(r=!0),r&&n.includes('"acct"<blob>=')){let s=n.match(/"acct"<blob>="([^"]+)"/);s&&t.push(s[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${te(e)}`),[]}}};function He(o,e){return typeof o=="object"&&o!==null&&"code"in o&&o.code===e}function te(o){return o instanceof Error?o.message:String(o)}import{execFile as Cn}from"child_process";import{promisify as An}from"util";var Dn=An(Cn),Tn="kanonak:",ze=2560,y=class{constructor(e=Tn){this.targetPrefix=e}targetPrefix;async get(e){let t=this.targetPrefix+c(e),r=`
|
|
9
9
|
${ne}
|
|
10
10
|
$target = $env:KANONAK_CRED_TARGET
|
|
11
11
|
$ptr = [IntPtr]::Zero
|
|
@@ -18,7 +18,7 @@ try {
|
|
|
18
18
|
[System.Text.Encoding]::Unicode.GetString($bytes)
|
|
19
19
|
} finally {
|
|
20
20
|
[CredMan]::CredFree($ptr)
|
|
21
|
-
}`;try{let{stdout:n}=await re(r,{KANONAK_CRED_TARGET:t}),s=n.trim();return s?JSON.parse(s):null}catch{return null}}async store(e,t){let r=this.targetPrefix+c(e),n=JSON.stringify(t),s=Buffer.byteLength(n,"utf16le");if(s>
|
|
21
|
+
}`;try{let{stdout:n}=await re(r,{KANONAK_CRED_TARGET:t}),s=n.trim();return s?JSON.parse(s):null}catch{return null}}async store(e,t){let r=this.targetPrefix+c(e),n=JSON.stringify(t),s=Buffer.byteLength(n,"utf16le");if(s>ze)throw new Error(`Credential '${r}' is ${s} bytes (UTF-16), over the Windows Credential Manager limit of ${ze} (CRED_MAX_CREDENTIAL_BLOB_SIZE). Keep only the secret here and store large/public material (certificates, chains) on disk.`);let i=`
|
|
22
22
|
${ne}
|
|
23
23
|
$target = $env:KANONAK_CRED_TARGET
|
|
24
24
|
$json = $env:KANONAK_CRED_JSON
|
|
@@ -40,7 +40,7 @@ ${ne}
|
|
|
40
40
|
$target = $env:KANONAK_CRED_TARGET
|
|
41
41
|
[CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await re(r,{KANONAK_CRED_TARGET:t})}catch{}}async list(){let e=`
|
|
42
42
|
${ne}
|
|
43
|
-
${
|
|
43
|
+
${$n}
|
|
44
44
|
$prefix = $env:KANONAK_CRED_PREFIX
|
|
45
45
|
$count = 0
|
|
46
46
|
$pCreds = [IntPtr]::Zero
|
|
@@ -58,7 +58,7 @@ if ([CredMan]::CredEnumerate(($prefix + "*"), 0, [ref]$count, [ref]$pCreds)) {
|
|
|
58
58
|
}
|
|
59
59
|
[CredMan]::CredFree($pCreds)
|
|
60
60
|
}`;try{let{stdout:t}=await re(e,{KANONAK_CRED_PREFIX:this.targetPrefix});return t.trim().split(`
|
|
61
|
-
`).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function re(o,e){let t=Buffer.from(o,"utf16le").toString("base64");for(let r of["pwsh","powershell"])try{return await
|
|
61
|
+
`).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function re(o,e){let t=Buffer.from(o,"utf16le").toString("base64");for(let r of["pwsh","powershell"])try{return await Dn(r,["-NoProfile","-NonInteractive","-EncodedCommand",t],{timeout:15e3,...e&&{env:{...process.env,...e}}})}catch(n){if(r==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var ne=`
|
|
62
62
|
Add-Type -TypeDefinition @"
|
|
63
63
|
using System;
|
|
64
64
|
using System.Runtime.InteropServices;
|
|
@@ -89,15 +89,14 @@ public class CredMan {
|
|
|
89
89
|
[DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
90
90
|
public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
|
|
91
91
|
}
|
|
92
|
-
"
|
|
93
|
-
`)){let n=r.match(/attribute\.publisher\s*=\s*(.+)/);n&&t.push(n[1].trim())}return t}catch{return[]}}};async function
|
|
92
|
+
"@`,$n="";import{execFile as _n,spawn as Kn}from"child_process";import{promisify as In}from"util";var oe=In(_n),Nn="kanonak",f=class{constructor(e=Nn){this.service=e}service;async get(e){let t=c(e);try{let{stdout:r}=await oe("secret-tool",["lookup","service",this.service,"publisher",t],{timeout:1e4}),n=r.trim();return n?JSON.parse(n):null}catch{return null}}async store(e,t){let r=c(e),n=JSON.stringify(t);await new Promise((s,i)=>{let a=Kn("secret-tool",["store","--label",`Kanonak: ${r}`,"service",this.service,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});a.stdin.write(n),a.stdin.end(),a.on("close",l=>{l===0?s():i(new Error(`secret-tool store exited with code ${l}`))}),a.on("error",i)})}async remove(e){let t=c(e);try{await oe("secret-tool",["clear","service",this.service,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await oe("secret-tool",["search","service",this.service],{timeout:1e4}),t=[];for(let r of e.split(`
|
|
93
|
+
`)){let n=r.match(/attribute\.publisher\s*=\s*(.+)/);n&&t.push(n[1].trim())}return t}catch{return[]}}};async function E(){try{return await oe("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as We,mkdirSync as Ge,readFileSync as Je,writeFileSync as qe}from"fs";import{createCipheriv as Bn,createDecipheriv as On,randomBytes as Xe}from"crypto";import{homedir as jn}from"os";import{join as Re,dirname as Ze}from"path";var Qe=Re(jn(),".config","kanonak"),U=Re(Qe,"keyring.key"),Mn=Re(Qe,"credentials.enc"),Ye="aes-256-gcm",we=32,T=12,be=16,h=class{constructor(e=Mn){this.secretsFile=e}secretsFile;async get(e){let t=this.loadStore(),r=c(e);return t[r]??null}async store(e,t){let r=this.loadStore(),n=c(e);r[n]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=c(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!We(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=Je(this.secretsFile);if(t.length<T+be)return{};let r=t.subarray(0,T),n=t.subarray(T,T+be),s=t.subarray(T+be),i=On(Ye,e,r);i.setAuthTag(n);let a=Buffer.concat([i.update(s),i.final()]);return JSON.parse(a.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),r=Xe(T),n=Bn(Ye,t,r),s=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([n.update(s),n.final()]),a=n.getAuthTag(),l=Buffer.concat([r,a,i]);Ge(Ze(this.secretsFile),{recursive:!0}),qe(this.secretsFile,l,{mode:384})}getOrCreateKey(){if(We(U)){let t=Je(U);if(t.length!==we)throw new Error(`Credential keyring key is corrupted (expected ${we} bytes, got ${t.length}). Delete ${U} and re-authenticate.`);return t}let e=Xe(we);return Ge(Ze(U),{recursive:!0}),qe(U,e,{mode:384}),e}};import{execFile as Vn}from"child_process";import{promisify as Ln}from"util";var Un=Ln(Vn),et=3e4,F=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=c(e);try{let n=(await this.runHelper("get",{publisher:t})).trim();return n?JSON.parse(n):null}catch(r){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${se(r)}
|
|
94
94
|
Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
|
|
95
95
|
Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let r=c(e);try{await this.runHelper("store",{publisher:r,credential:t})}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${r}': ${se(n)}
|
|
96
|
-
Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=c(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${se(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: ${se(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await Un(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:
|
|
97
|
-
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):
|
|
98
|
-
The helper may be waiting for authentication to an external vault.`):r}}};function se(o){return o instanceof Error?o.message:String(o)}function
|
|
99
|
-
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as
|
|
96
|
+
Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=c(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${se(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: ${se(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await Un(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:et});return r}catch(r){throw Fn(r)?new Error(`Credential helper not found at '${this.helperPath}'.
|
|
97
|
+
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Hn(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${et/1e3}s on '${e}'.
|
|
98
|
+
The helper may be waiting for authentication to an external vault.`):r}}};function se(o){return o instanceof Error?o.message:String(o)}function Fn(o){return o instanceof Error&&"code"in o&&o.code==="ENOENT"}function Hn(o){return o instanceof Error&&"killed"in o&&o.killed}var Ee=Jn(Gn(),".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=qn(e);if(t)return t;let n=await(await this.getBackend()).get(e);return!n||!Y(n)?null:n.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=Xn();return e.credentialHelper?new F(e.credentialHelper):process.platform==="darwin"?new m:process.platform==="win32"?new y:await E()?new f:new h}};function qn(o){let t="KANONAK_TOKEN_"+c(o).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Xn(){if(!zn(Ee))return{};try{return JSON.parse(Wn(Ee,"utf-8"))}catch(o){let e=o instanceof Error?o.message:String(o);return console.warn(` Warning: Failed to parse ${Ee}: ${e}
|
|
99
|
+
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as ot}from"os";import{join as x}from"path";import{mkdir as Zn,writeFile as tt,readFile as rt,rm as nt}from"fs/promises";var xe="kanonak-device",Yn=x(ot(),".config","kanonak","device-credentials.enc"),Qn=x(ot(),".kanonak","devices"),w=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;certDir(e){let t=c(e).replace(/[^a-zA-Z0-9._-]/g,"_");return x(this.deps.certBaseDir??Qn,t)}async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async get(e){let t=await(await this.getBackend()).get(e);if(!t)return null;if(typeof t.certificatePem=="string"&&typeof t.chainPem=="string")return t;let r=this.certDir(e),n,s;try{n=await rt(x(r,"cert.pem"),"utf-8"),s=await rt(x(r,"chain.pem"),"utf-8")}catch{return null}return{...t,certificatePem:n,chainPem:s}}async store(e,t){let{certificatePem:r,chainPem:n,...s}=t,i=this.certDir(e);await Zn(i,{recursive:!0}),await tt(x(i,"cert.pem"),r,"utf-8"),await tt(x(i,"chain.pem"),n,"utf-8");try{await(await this.getBackend()).store(e,s)}catch(a){throw await nt(i,{recursive:!0,force:!0}).catch(()=>{}),a}}async remove(e){await(await this.getBackend()).remove(e),await nt(this.certDir(e),{recursive:!0,force:!0})}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(xe):process.platform==="win32"?new y(`${xe}:`):await E()?new f(xe):new h(Yn)}};import{homedir as eo}from"os";import{join as to}from"path";var Ce="kanonak-session",ro=to(eo(),".config","kanonak","session-credentials.enc"),$=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async get(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(Ce):process.platform==="win32"?new y(`${Ce}:`):await E()?new f(Ce):new h(ro)}};function ae(o,e=5*6e4,t=Date.now()){let r=Date.parse(o.expiresAt);return Number.isNaN(r)?!0:t>=r-e}var st="key_thumbprint",b=class{cache=new Map;prCache=new Map;async discoverProtectedResource(e){let t=c(e);if(this.prCache.has(t))return this.prCache.get(t);let r=`https://${t}/.well-known/oauth-protected-resource`,n=await no(r),s=n&&Array.isArray(n.authorization_servers)?n.authorization_servers.filter(a=>typeof a=="string"):[],i=s.length>0?s:null;return this.prCache.set(t,i),i}async discover(e){let t=c(e);if(this.cache.has(t))return this.cache.get(t);let r=`https://${t}/.well-known/oauth-authorization-server`,n=await this.tryEndpoint(r);if(!n){let s=`https://${t}/.well-known/openid-configuration`;n=await this.tryEndpoint(s)}return this.cache.set(t,n),n}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let t;try{t=await fetch(e)}catch(n){let s=n instanceof Error?n.message:String(n);return s.includes("ENOTFOUND")||s.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${s})`),console.error(" If the server is behind a VPN, ensure you are connected.")):s.includes("CERT")||s.includes("SSL")||s.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${s})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${e} \u2014 network error: ${s}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let r;try{r=await t.json()}catch{return console.error(` OAuth discovery: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:g(r.issuer),authorizationEndpoint:g(r.authorization_endpoint),tokenEndpoint:g(r.token_endpoint),registrationEndpoint:g(r.registration_endpoint),revocationEndpoint:g(r.revocation_endpoint),scopesSupported:k(r.scopes_supported),responseTypesSupported:k(r.response_types_supported),grantTypesSupported:k(r.grant_types_supported),codeChallengeMethodsSupported:k(r.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:k(r.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:k(r.dpop_signing_alg_values_supported),enrollmentEndpoint:g(r.enrollment_endpoint),enrollmentIssuanceProtocols:k(r.enrollment_issuance_protocols),enrollmentKeyTypes:k(r.enrollment_key_types),enrollmentScopesSupported:k(r.enrollment_scopes_supported),enrollmentConsentBindingParam:g(r.enrollment_consent_binding_param),sessionEndpoint:g(r.session_endpoint),sessionEndpointAuthMethod:g(r.session_endpoint_auth_method)}}};async function no(o){try{let e=await fetch(o);return e.ok?await e.json():null}catch{return null}}function g(o){return typeof o=="string"?o:null}function k(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"):null}import*as it from"https";import{createPrivateKey as oo}from"crypto";var S=class extends Error{},_=class{constructor(e=ao){this.transport=e}transport;async exchange(e,t,r={}){let n=io(t.keyMaterial),s="{}",i;try{i=await this.transport({url:e,certPem:so(t),keyPem:n,body:s,contentType:"application/json"})}catch(p){throw new S(`mTLS session exchange to ${e} failed: ${p.message}`)}if(i.status<200||i.status>=300){let p=i.status===401?" \u2014 the gateway did not accept the device client certificate (invalid_client)":"";throw new S(`Session endpoint ${e} returned HTTP ${i.status}${p}: ${i.body.slice(0,300)}`)}let a;try{a=JSON.parse(i.body)}catch{throw new S(`Session endpoint returned a non-JSON response: ${i.body.slice(0,200)}`)}if(typeof a.access_token!="string"||!a.access_token)throw new S("Session response had no access_token.");let l=typeof a.expires_in=="number"?a.expires_in:0,d=r.nowMs??Date.now();return{token:a.access_token,tokenType:typeof a.token_type=="string"&&a.token_type?a.token_type:"Bearer",expiresAt:new Date(d+l*1e3).toISOString(),scope:typeof a.scope=="string"?a.scope:""}}};function so(o){let e=o.chainPem.trim();return e?`${o.certificatePem.replace(/\s+$/,"")}
|
|
100
100
|
${e}
|
|
101
|
-
`:o.certificatePem}function
|
|
102
|
-
The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${s.accessToken}`}}else i.Authorization=`Bearer ${s.accessToken}`;let a=await C(t,{method:n,headers:i});if(a.status===401&&s.dpopKeyPair){let l=a.headers.get("DPoP-Nonce");if(l){e.set(r,l);try{let d=H(s.dpopKeyPair.privateKey,s.dpopKeyPair.publicKey,n,t,s.accessToken,l);i.DPoP=d,a=await C(t,{method:n,headers:i})}catch{}}}return a}}import{readFileSync as go,writeFileSync as ko,existsSync as So}from"fs";import{createHash as vo}from"crypto";import Po from"js-yaml";var lt="kanonak.lock",wo=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
103
|
-
`;function dt(o=lt){return So(o)?he(go(o,"utf-8")):null}function pt(o,e=lt){o.lastUpdated=new Date().toISOString();let t={};for(let n of Object.keys(o.packages).sort())t[n]=o.packages[n];o.packages=t;let r=Po.dump(o,{lineWidth:-1,sortKeys:!1,quotingType:'"'});ko(e,wo+r,"utf-8")}function ut(o){return`sha256:${vo("sha256").update(o).digest("hex")}`}import*as De from"js-yaml";import{VersionOperator as mt}from"@kanonak-protocol/types/document/models/enums";var bo="0.0.0",N=class{constructor(e,t=new B,r){this.repository=e;this.parser=t;this.objectParser=r??new L(this.parser)}repository;parser;objectParser;imports(){return new z}serializeValue(e,t){return ht(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),n=Te(r),s={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(s[e.contentHashProperty]=r),Object.assign(s,e.header??{}),s.imports=t;let i={[n]:s,...e.body},a=this.dump(i);return{yaml:a,byteCount:ft(a),contentHash:r,packageName:n,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},n;e.contentHashProperty&&(n=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=n),Object.assign(r,e.header??{}),r.imports=t;let s={[e.name]:r,...e.body},i=this.dump(s),a={yaml:i,byteCount:ft(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return n!==void 0&&(a.contentHash=n),a}dump(e){return De.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let n={[yt]:{type:"EphemeralPackage",publisher:e,imports:t},...r},s=this.parser.parse(De.dump(n,{lineWidth:-1})),i=s.metadata.namespace_?.toString(),l=(await this.objectParser.parseKanonaks(new je(s,this.repository))).filter(d=>d instanceof A&&d.namespace===i&&d.name!==yt);for(let d of l)d.namespace="ephemeral";return we(l)}},yt="__pkgbuilder_probe__";function ft(o){return new TextEncoder().encode(o).length}function Te(o){let e="sha256:",t=o.startsWith(e)?e.length:0;return`q-${o.slice(t,t+16)}`}var z=class{byKey=new Map;aliases=new Set;ensure(e,t,r,n,s=mt.Major){let i=`${e}/${t}@${r}`,a=this.byKey.get(i);if(a)return a.alias;let l=this.uniqueAlias(n);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:l,match:s}),l}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,E(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,n){return`${this.ensure(e,t,bo,n??t,mt.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let n=e.get(r.publisher)??[];n.push(r),e.set(r.publisher,n)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((n,s)=>n.package_<s.package_?-1:1).map(n=>({package:n.package_,match:fe(n.match),version:n.version,alias:n.alias}))}))}uniqueAlias(e){let t=W(e)||"pkg",r=t,n=2;for(;this.aliases.has(r);)r=`${t}${n++}`;return this.aliases.add(r),r}};function ht(o,e){if(o!=null){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(o instanceof j)return e.ref(o.subject);if(Array.isArray(o)){let t=o.map(r=>ht(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(o instanceof D)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(Eo(o))throw new Error(`Value produced a bare URI without a version (${o.publisher}/${o.package_}/${o.name}); cannot serialize it as a reference.`)}}function W(o){return o.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Eo(o){return typeof o=="object"&&o!==null&&typeof o.publisher=="string"&&typeof o.package_=="string"&&typeof o.name=="string"}var le=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,n){let s=`${t}/${r}@${E(n)}`,i=this.produced.get(s);if(i)return i;let{document:a}=await e.produce(t,r,n);return this.produced.set(s,a),a}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let n={operator:t.versionOperator,version:t.version},s=await r.resolveVersion(e,t.packageName,n);return s?this.produceCached(r,e,t.packageName,s):null}async getDocumentAsync(e){let t;try{t=ve(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let n=r.metadata.namespace_;return n!=null&&n.publisher===e&&n.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var $e={async authorize(){return{allowed:!0}}},_e={async record(){}},G=class extends Error{constructor(t,r){let n=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${n}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},de=class{inner;ctx;policy;meter;constructor(e,t,r=$e,n=_e){this.inner=e,this.ctx=t,this.policy=r,this.meter=n}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let n={publisher:e,package_:t,version:r};await this.assertAllowed(n);let s=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,n,s),s}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new G(e,t.reason)}};var u="kanonak.org",v="view",gt="core-kanonak",Ro={publisher:u,package_:v,name:"rootView"},xo={publisher:u,package_:v,name:"bind"},Co={publisher:u,package_:v,name:"produces"},Ao={publisher:u,package_:v,name:"projections"},Do={publisher:u,package_:v,name:"where"},To={publisher:u,package_:v,name:"value"},$o={publisher:u,package_:v,name:"as"},pe=class{constructor(e,t=new B){this.repository=e;this.parser=t;this.objectParser=new L(this.parser),this.builder=new N(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),n=this.resolveView(r,e),s=M(n,xo);if(!s)throw new Error(`View ${n.namespace}/${n.name} declares no view.bind; cannot materialize.`);let i=M(n,Co);if(!i)throw new Error(`View ${n.namespace}/${n.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let a=_o(n),l=kt(r,u,gt),d=kt(r,u,v),p=this.builder.imports(),ue=p.ensure(u,gt,l,"ck"),vt=p.ensure(u,v,d,"v"),Pt=p.ref(i),wt=new Le(this.repository,this.parser,this.objectParser),Ke=new Me(wt,r),bt=this.readProjections(r,n),Et=No(n,Do),Rt=this.findInstances(r,s,await this.reason(t)),Ie={},xt=new Set;for(let J of Rt){if(!await this.passesWhere(Ke,r,Et,J))continue;let ye={type:Pt};for(let Oe of bt){let Ct=await this.evaluateValue(Ke,r,Oe.value,J),Be=this.builder.serializeValue(St(Ct),p);Be!==void 0&&(ye[p.ref(Oe.as)]=Be)}let Ne=P(J);Ne&&(ye[`${vt}.derivedFrom`]=p.ref(Ne)),Ie[this.rowName(J,xt)]=ye}let me={};t.resolvedAt&&(me[`${ue}.resolvedAt`]=t.resolvedAt),t.invocationId&&(me[`${ue}.id`]=t.invocationId);let O=await this.builder.buildContentAddressed({publisher:a,book:p,body:Ie,contentHashProperty:`${ue}.contentHash`,header:me});return{yaml:O.yaml,contentHash:O.contentHash,packageName:O.packageName,publisher:O.publisher,rowCount:O.resourceCount}}resolveView(e,t){let r=X(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let n=M(r,Ro);if(n){let s=X(e,n);if(!s)throw new Error(`ViewPackage ${t.name} names rootView ${n.name}, which is not in the catalog.`);return s}return r}readProjections(e,t){let r=[];for(let n of ke(t,Ao)){let s=n instanceof D?n:n instanceof j?X(e,n.subject):void 0;if(!s)continue;let i=ge(s,To),a=M(s,$o);i&&a&&r.push({value:i,as:a})}return r}async reason(e){return new Se({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let n=Io(e),s=[],i=new Set;for(let a of r.getInstancesOfClass(t)){if(i.has(a))continue;i.add(a);let l=n.get(a);l&&s.push(l)}return s.sort((a,l)=>{let d=V(P(a)),p=V(P(l));return d<p?-1:d>p?1:0}),s}async passesWhere(e,t,r,n){for(let s of r){let i=await this.evaluateValue(e,t,s,n);if(!Oo(i))return!1}return!0}async evaluateValue(e,t,r,n){let s=Ve(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",n]]);return e.evaluate(s,i)}rowName(e,t){let r=W(e.name)||"row",n=r,s=2;for(;t.has(n);)n=`${r}-${s++}`;return t.add(n),n}};function St(o){return Pe(o)?o.value:Array.isArray(o)?o.map(St):o}function _o(o){let e=P(o);if(!e)throw new Error(`Could not derive a publisher from view ${o.namespace}/${o.name}.`);return e.publisher}function kt(o,e,t){let r=Ko(o,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function Ko(o,e,t){let r;for(let n of o){if(!(n instanceof A))continue;let s=P(n);!s||s.publisher!==e||s.package_!==t||!s.version||(!r||q(s.version,r)>0)&&(r=s.version)}return r?E(r):void 0}function Io(o){let e=new Map,t=new Map;for(let r of o){if(!(r instanceof A))continue;let n=P(r);if(!n||!n.version)continue;let s=V(n),i=t.get(s);(!i||q(n.version,i)>0)&&(t.set(s,n.version),e.set(s,r))}return e}function No(o,e){let t=ge(o,e);return t?[t]:ke(o,e).filter(r=>r instanceof D)}function Oo(o){return o===!0?!0:o===!1||o===void 0||o===null?!1:typeof o=="string"?o.length>0:typeof o=="number"?o!==0:Pe(o)?o.value.length>0:Array.isArray(o)?o.length>0:!!o}export{dn as AmbiguousReferenceRule,ar as BooleanStatement,bn as CANONICAL_FORM_VERSION,yr as Carrier,hn as ClassDefinitionRule,rn as ClassHierarchyCycleRule,jt as CompositeKanonakDocumentRepository,ce as CredentialResolver,ie as CredentialStore,nt as DEFAULT_CONSENT_BINDING_PARAM,er as DefinedKanonak,w as DeviceCertificateStore,Bt as DocumentLocation,Er as EdgeType,D as EmbeddedKanonak,Qr as EmbeddedKanonakTypeRule,lr as EmbeddedStatement,G as EntitlementDeniedError,de as EntitlementProducer,Ot as FileSystemKanonakDocumentRepository,Tr as GitIgnoreFilter,Rr as GraphBuilder,Jt as HttpKanonakDocumentRepository,z as ImportBook,en as ImportExistenceRule,Nt as InMemoryKanonakDocumentRepository,Lt as KANONAK_USER_AGENT,Qt as Kanonak,_r as KanonakDocumentPositions,L as KanonakObjectParser,kn as KanonakObjectValidator,B as KanonakParser,tr as KanonakUri,Nr as KanonakUriBuilder,Br as KanonakUrlResolver,Sr as KanonakVocabulary,dr as ListStatement,rr as LiteralKanonak,qt as LocalFirstRepository,Xt as LockAwareRepository,Pn as LookRenderer,gn as MarkdownLinkRule,pr as MarkdownStatement,cn as NamespaceImportCycleRule,Jr as NamespacePrefixRule,br as NodeType,ir as NumberStatement,b as OAuthDiscovery,Ar as OWL_RL_CLASSIFICATION_RULES,un as ObjectPropertyValueValidationRule,zr as OntologyValidationError,Ur as OntologyValidationResult,N as PackageBuilder,Yr as PackageHeaderRule,le as ProducerRepository,mn as PropertyDomainRule,nn as PropertyHierarchyCycleRule,yn as PropertyKindRangeConsistencyRule,$r as PropertyMetadata,pn as PropertyRangeReferenceRule,on as PropertyRangeRequiredRule,Xr as PropertyTypeSpecificityRule,zt as PublisherConfigResolver,Wt as PublisherIndex,Cr as RDFS_RULES,Se as Reasoner,Dr as ReasoningResult,j as ReferenceKanonak,cr as ReferenceStatement,Vt as RepositoryFactory,fn as ReservedNameShadowRule,qr as ResourceNamingRule,ur as ResourceResolver,wr as ResourceTypeClassifier,or as ScalarStatement,K as SessionError,_ as SessionExchange,S as SessionExchangeError,I as SessionManager,$ as SessionStore,nr as Statement,sr as StringStatement,sn as SubClassOfReferenceRule,an as SubPropertyOfReferenceRule,A as SubjectKanonak,Zr as SubjectKanonakTypeRequiredRule,xr as TripleStore,mr as TypeResolver,ln as UnresolvedPredicateRule,tn as UnresolvedReferenceRule,Gr as ValidationCache,Wr as ValidationContext,Hr as ValidationSeverity,ka as VersionOperator,pe as ViewMaterializer,$e as allowAllPolicy,Ht as assertHttpsUrl,Gt as assertPackageIdentity,Yt as buildLocalFirstRepository,En as buildOntologyModel,wn as canonicalForm,we as canonicalHash,fr as carrierOf,Zt as collectKanonakFiles,q as compareVersions,ut as computeIntegrity,Te as contentAddressedName,Lr as contextTypesOf,ct as createAuthenticatedFetch,H as createDPoPProof,Tt as createVersion,Pr as extractMarkdownLinks,Sn as findDerivation,Fr as findInstancesByType,vr as findMalformedReferences,Ir as findMarkdownLinkAt,Or as formatKanonakAddress,E as formatVersion,it as generateDPoPKeyPair,Mt as getGlobalCachePath,Ut as getKanonakUserAgent,Y as hasValidToken,_t as isCompatibleVersion,Z as isExpired,Kt as isMajorCompatible,C as kanonakFetch,dt as loadLockFile,hr as makeUriKey,_e as noopMeter,c as normalizeHost,ve as parseKanonakAddress,$t as parseVersionString,Kr as parseWithPositions,It as pickHighestDocument,Mr as propertiesInScope,vn as resolveDisplayValue,Vr as resolvePropertyStep,W as sanitizeName,pt as saveLockFile,at as serverSupportsDPoP,ae as sessionNeedsRefresh,Ft as setKanonakUserAgent,P as subjectUri,jr as superClassChain,gr as tripleKey,V as uriKey,kr as uriTriple,At as versionOperatorFromChar,fe as versionOperatorToChar,Dt as versionsEqual};
|
|
101
|
+
`:o.certificatePem}function io(o){try{return oo({key:o,format:"jwk"}).export({type:"pkcs8",format:"pem"})}catch(e){throw new S(`The device key is not an exportable software private key, so it cannot present mTLS in software (a future hardware key provider would do the handshake itself): ${e.message}`)}}var ao=o=>new Promise((e,t)=>{let r=new URL(o.url),n=it.request({method:"POST",hostname:r.hostname,port:r.port||443,path:r.pathname+r.search,cert:o.certPem,key:o.keyPem,headers:{"Content-Type":o.contentType,"Content-Length":Buffer.byteLength(o.body),Accept:"application/json"},timeout:3e4},s=>{let i=[];s.on("data",a=>i.push(a)),s.on("end",()=>e({status:s.statusCode??0,body:Buffer.concat(i).toString("utf-8")}))});n.on("error",t),n.on("timeout",()=>n.destroy(new Error("mTLS request timed out"))),n.write(o.body),n.end()});var K=class extends Error{},I=class{discovery;deviceStore;sessionStore;exchange;constructor(e={}){this.discovery=e.discovery??new b,this.deviceStore=e.deviceStore??new w,this.sessionStore=e.sessionStore??new $,this.exchange=e.exchange??new _}async acquire(e){let t=c(e),r=await this.sessionEndpoint(e);if(!r)throw new K(`'${t}' does not advertise a session endpoint \u2014 it issues no scoped sessions (public registries need no credential).`);let n=await this.deviceStore.get(e);if(!n)throw new K(`No device certificate enrolled for '${t}'. Run 'kanonak device enroll ${e}' first.`);let s=await this.exchange.exchange(r,n),i={token:s.token,tokenType:s.tokenType,expiresAt:s.expiresAt,scope:s.scope};return await this.sessionStore.store(t,i),i}async getValidSession(e){let t=c(e),r=await this.sessionStore.get(t);return r&&!ae(r)?r:!await this.sessionEndpoint(e)||!await this.deviceStore.get(e)?null:this.acquire(e)}async clear(e){await this.sessionStore.remove(c(e))}async sessionEndpoint(e){return(await this.discovery.discover(e))?.sessionEndpoint??null}};var ce=class{discovery;sessions;devices;constructor(e={}){this.discovery=e.discovery??new b,this.sessions=e.sessionManager??new I({discovery:this.discovery}),this.devices=e.deviceStore??new w}async resolve(e){let t=await this.discovery.discoverProtectedResource(e);if(!t||t.length===0)return null;let r=t.map(co).filter(i=>i!==void 0);for(let i of r){let a=await this.sessionFor(i);if(a)return a}let s=(await this.devices.list()).map(c).filter(i=>!r.includes(i));if(s.length===0)return null;for(let i of r){let a=(await this.discovery.discover(i))?.sessionEndpoint;if(a)for(let l of s){if((await this.discovery.discover(l))?.sessionEndpoint!==a)continue;let p=await this.sessionFor(l);if(p)return p}}return null}async sessionFor(e){let t=await this.sessions.getValidSession(e);return t?{authority:e,token:t.token,expiresAt:t.expiresAt,scope:t.scope}:null}};function co(o){try{return new URL(o).host}catch{return}}import{createHash as lo,createPrivateKey as po,generateKeyPairSync as uo,randomUUID as mo,sign as yo}from"crypto";function ct(){let{publicKey:o,privateKey:e}=uo("ec",{namedCurve:"P-256"});return{publicKey:o.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function H(o,e,t,r,n,s){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},a={jti:mo(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return n&&(a.ath=lo("sha256").update(n).digest("base64url")),s&&(a.nonce=s),fo(i,a,o)}function lt(o){return!o||o.length===0?!1:o.some(e=>e.toUpperCase()==="ES256")}function fo(o,e,t){let r=at(JSON.stringify(o)),n=at(JSON.stringify(e)),s=`${r}.${n}`,i=po({key:t,format:"jwk"}),l=yo("SHA256",Buffer.from(s),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${l}`}function at(o){return Buffer.from(o,"utf-8").toString("base64url")}function dt(o){let e=new Map;return async(t,r,n="GET")=>{if(!o)return C(t,{method:n});let s=await o.getCredential(r);if(!s?.accessToken)return C(t,{method:n});Z(s)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let i={};if(s.dpopKeyPair){let l=e.get(r);try{let d=H(s.dpopKeyPair.privateKey,s.dpopKeyPair.publicKey,n,t,s.accessToken,l);i.Authorization=`DPoP ${s.accessToken}`,i.DPoP=d}catch(d){let p=d instanceof Error?d.message:String(d);console.error(` Error: Failed to create DPoP proof for '${r}': ${p}
|
|
102
|
+
The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${s.accessToken}`}}else i.Authorization=`Bearer ${s.accessToken}`;let a=await C(t,{method:n,headers:i});if(a.status===401&&s.dpopKeyPair){let l=a.headers.get("DPoP-Nonce");if(l){e.set(r,l);try{let d=H(s.dpopKeyPair.privateKey,s.dpopKeyPair.publicKey,n,t,s.accessToken,l);i.DPoP=d,a=await C(t,{method:n,headers:i})}catch{}}}return a}}import*as Ae from"js-yaml";import{VersionOperator as pt}from"@kanonak-protocol/types/document/models/enums";var ho="0.0.0",N=class{constructor(e,t=new O,r){this.repository=e;this.parser=t;this.objectParser=r??new L(this.parser)}repository;parser;objectParser;imports(){return new z}serializeValue(e,t){return yt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),n=De(r),s={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(s[e.contentHashProperty]=r),Object.assign(s,e.header??{}),s.imports=t;let i={[n]:s,...e.body},a=this.dump(i);return{yaml:a,byteCount:mt(a),contentHash:r,packageName:n,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},n;e.contentHashProperty&&(n=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=n),Object.assign(r,e.header??{}),r.imports=t;let s={[e.name]:r,...e.body},i=this.dump(s),a={yaml:i,byteCount:mt(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return n!==void 0&&(a.contentHash=n),a}dump(e){return Ae.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let n={[ut]:{type:"EphemeralPackage",publisher:e,imports:t},...r},s=this.parser.parse(Ae.dump(n,{lineWidth:-1})),i=s.metadata.namespace_?.toString(),l=(await this.objectParser.parseKanonaks(new Oe(s,this.repository))).filter(d=>d instanceof A&&d.namespace===i&&d.name!==ut);for(let d of l)d.namespace="ephemeral";return Pe(l)}},ut="__pkgbuilder_probe__";function mt(o){return new TextEncoder().encode(o).length}function De(o){let e="sha256:",t=o.startsWith(e)?e.length:0;return`q-${o.slice(t,t+16)}`}var z=class{byKey=new Map;aliases=new Set;ensure(e,t,r,n,s=pt.Major){let i=`${e}/${t}@${r}`,a=this.byKey.get(i);if(a)return a.alias;let l=this.uniqueAlias(n);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:l,match:s}),l}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_,R(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,n){return`${this.ensure(e,t,ho,n??t,pt.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let n=e.get(r.publisher)??[];n.push(r),e.set(r.publisher,n)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((n,s)=>n.package_<s.package_?-1:1).map(n=>({package:n.package_,match:fe(n.match),version:n.version,alias:n.alias}))}))}uniqueAlias(e){let t=W(e)||"pkg",r=t,n=2;for(;this.aliases.has(r);)r=`${t}${n++}`;return this.aliases.add(r),r}};function yt(o,e){if(o!=null){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(o instanceof j)return e.ref(o.subject);if(Array.isArray(o)){let t=o.map(r=>yt(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(o instanceof D)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(go(o))throw new Error(`Value produced a bare URI without a version (${o.publisher}/${o.package_}/${o.name}); cannot serialize it as a reference.`)}}function W(o){return o.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function go(o){return typeof o=="object"&&o!==null&&typeof o.publisher=="string"&&typeof o.package_=="string"&&typeof o.name=="string"}var le=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,n){let s=`${t}/${r}@${R(n)}`,i=this.produced.get(s);if(i)return i;let{document:a}=await e.produce(t,r,n);return this.produced.set(s,a),a}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let n={operator:t.versionOperator,version:t.version},s=await r.resolveVersion(e,t.packageName,n);return s?this.produceCached(r,e,t.packageName,s):null}async getDocumentAsync(e){let t;try{t=Se(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let n=r.metadata.namespace_;return n!=null&&n.publisher===e&&n.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Te={async authorize(){return{allowed:!0}}},$e={async record(){}},G=class extends Error{constructor(t,r){let n=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${n}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},de=class{inner;ctx;policy;meter;constructor(e,t,r=Te,n=$e){this.inner=e,this.ctx=t,this.policy=r,this.meter=n}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let n={publisher:e,package_:t,version:r};await this.assertAllowed(n);let s=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,n,s),s}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new G(e,t.reason)}};var u="kanonak.org",v="view",ft="core-kanonak",ko={publisher:u,package_:v,name:"rootView"},So={publisher:u,package_:v,name:"bind"},vo={publisher:u,package_:v,name:"produces"},Po={publisher:u,package_:v,name:"projections"},wo={publisher:u,package_:v,name:"where"},bo={publisher:u,package_:v,name:"value"},Ro={publisher:u,package_:v,name:"as"},pe=class{constructor(e,t=new O){this.repository=e;this.parser=t;this.objectParser=new L(this.parser),this.builder=new N(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),n=this.resolveView(r,e),s=M(n,So);if(!s)throw new Error(`View ${n.namespace}/${n.name} declares no view.bind; cannot materialize.`);let i=M(n,vo);if(!i)throw new Error(`View ${n.namespace}/${n.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let a=Eo(n),l=ht(r,u,ft),d=ht(r,u,v),p=this.builder.imports(),ue=p.ensure(u,ft,l,"ck"),kt=p.ensure(u,v,d,"v"),St=p.ref(i),vt=new Fe(this.repository,this.parser,this.objectParser),_e=new Le(vt,r),Pt=this.readProjections(r,n),wt=Ao(n,wo),bt=this.findInstances(r,s,await this.reason(t)),Ke={},Rt=new Set;for(let J of bt){if(!await this.passesWhere(_e,r,wt,J))continue;let ye={type:St};for(let Ne of Pt){let Et=await this.evaluateValue(_e,r,Ne.value,J),Be=this.builder.serializeValue(gt(Et),p);Be!==void 0&&(ye[p.ref(Ne.as)]=Be)}let Ie=P(J);Ie&&(ye[`${kt}.derivedFrom`]=p.ref(Ie)),Ke[this.rowName(J,Rt)]=ye}let me={};t.resolvedAt&&(me[`${ue}.resolvedAt`]=t.resolvedAt),t.invocationId&&(me[`${ue}.id`]=t.invocationId);let B=await this.builder.buildContentAddressed({publisher:a,book:p,body:Ke,contentHashProperty:`${ue}.contentHash`,header:me});return{yaml:B.yaml,contentHash:B.contentHash,packageName:B.packageName,publisher:B.publisher,rowCount:B.resourceCount}}resolveView(e,t){let r=X(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let n=M(r,ko);if(n){let s=X(e,n);if(!s)throw new Error(`ViewPackage ${t.name} names rootView ${n.name}, which is not in the catalog.`);return s}return r}readProjections(e,t){let r=[];for(let n of ge(t,Po)){let s=n instanceof D?n:n instanceof j?X(e,n.subject):void 0;if(!s)continue;let i=he(s,bo),a=M(s,Ro);i&&a&&r.push({value:i,as:a})}return r}async reason(e){return new ke({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let n=Co(e),s=[],i=new Set;for(let a of r.getInstancesOfClass(t)){if(i.has(a))continue;i.add(a);let l=n.get(a);l&&s.push(l)}return s.sort((a,l)=>{let d=V(P(a)),p=V(P(l));return d<p?-1:d>p?1:0}),s}async passesWhere(e,t,r,n){for(let s of r){let i=await this.evaluateValue(e,t,s,n);if(!Do(i))return!1}return!0}async evaluateValue(e,t,r,n){let s=Ue(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",n]]);return e.evaluate(s,i)}rowName(e,t){let r=W(e.name)||"row",n=r,s=2;for(;t.has(n);)n=`${r}-${s++}`;return t.add(n),n}};function gt(o){return ve(o)?o.value:Array.isArray(o)?o.map(gt):o}function Eo(o){let e=P(o);if(!e)throw new Error(`Could not derive a publisher from view ${o.namespace}/${o.name}.`);return e.publisher}function ht(o,e,t){let r=xo(o,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function xo(o,e,t){let r;for(let n of o){if(!(n instanceof A))continue;let s=P(n);!s||s.publisher!==e||s.package_!==t||!s.version||(!r||q(s.version,r)>0)&&(r=s.version)}return r?R(r):void 0}function Co(o){let e=new Map,t=new Map;for(let r of o){if(!(r instanceof A))continue;let n=P(r);if(!n||!n.version)continue;let s=V(n),i=t.get(s);(!i||q(n.version,i)>0)&&(t.set(s,n.version),e.set(s,r))}return e}function Ao(o,e){let t=he(o,e);return t?[t]:ge(o,e).filter(r=>r instanceof D)}function Do(o){return o===!0?!0:o===!1||o===void 0||o===null?!1:typeof o=="string"?o.length>0:typeof o=="number"?o!==0:ve(o)?o.value.length>0:Array.isArray(o)?o.length>0:!!o}export{ln as AmbiguousReferenceRule,ir as BooleanStatement,wn as CANONICAL_FORM_VERSION,mr as Carrier,fn as ClassDefinitionRule,tn as ClassHierarchyCycleRule,Bt as CompositeKanonakDocumentRepository,ce as CredentialResolver,ie as CredentialStore,st as DEFAULT_CONSENT_BINDING_PARAM,Qt as DefinedKanonak,w as DeviceCertificateStore,Nt as DocumentLocation,br as EdgeType,D as EmbeddedKanonak,Yr as EmbeddedKanonakTypeRule,cr as EmbeddedStatement,G as EntitlementDeniedError,de as EntitlementProducer,It as FileSystemKanonakDocumentRepository,Dr as GitIgnoreFilter,Rr as GraphBuilder,Gt as HttpKanonakDocumentRepository,z as ImportBook,Qr as ImportExistenceRule,Kt as InMemoryKanonakDocumentRepository,Mt as KANONAK_USER_AGENT,Yt as Kanonak,$r as KanonakDocumentPositions,L as KanonakObjectParser,gn as KanonakObjectValidator,O as KanonakParser,er as KanonakUri,Ir as KanonakUriBuilder,Br as KanonakUrlResolver,kr as KanonakVocabulary,lr as ListStatement,tr as LiteralKanonak,Jt as LocalFirstRepository,qt as LockAwareRepository,vn as LookRenderer,hn as MarkdownLinkRule,dr as MarkdownStatement,an as NamespaceImportCycleRule,Gr as NamespacePrefixRule,wr as NodeType,sr as NumberStatement,b as OAuthDiscovery,Cr as OWL_RL_CLASSIFICATION_RULES,pn as ObjectPropertyValueValidationRule,Hr as OntologyValidationError,Ur as OntologyValidationResult,N as PackageBuilder,Zr as PackageHeaderRule,le as ProducerRepository,un as PropertyDomainRule,rn as PropertyHierarchyCycleRule,mn as PropertyKindRangeConsistencyRule,Tr as PropertyMetadata,dn as PropertyRangeReferenceRule,nn as PropertyRangeRequiredRule,qr as PropertyTypeSpecificityRule,Ht as PublisherConfigResolver,zt as PublisherIndex,xr as RDFS_RULES,ke as Reasoner,Ar as ReasoningResult,j as ReferenceKanonak,ar as ReferenceStatement,jt as RepositoryFactory,yn as ReservedNameShadowRule,Jr as ResourceNamingRule,pr as ResourceResolver,Pr as ResourceTypeClassifier,nr as ScalarStatement,K as SessionError,_ as SessionExchange,S as SessionExchangeError,I as SessionManager,$ as SessionStore,rr as Statement,or as StringStatement,on as SubClassOfReferenceRule,sn as SubPropertyOfReferenceRule,A as SubjectKanonak,Xr as SubjectKanonakTypeRequiredRule,Er as TripleStore,ur as TypeResolver,cn as UnresolvedPredicateRule,en as UnresolvedReferenceRule,Wr as ValidationCache,zr as ValidationContext,Fr as ValidationSeverity,aa as VersionOperator,pe as ViewMaterializer,Te as allowAllPolicy,Ut as assertHttpsUrl,Wt as assertPackageIdentity,Zt as buildLocalFirstRepository,bn as buildOntologyModel,Pn as canonicalForm,Pe as canonicalHash,yr as carrierOf,Xt as collectKanonakFiles,q as compareVersions,Ve as computeIntegrity,De as contentAddressedName,Vr as contextTypesOf,dt as createAuthenticatedFetch,H as createDPoPProof,At as createVersion,vr as extractMarkdownLinks,kn as findDerivation,Lr as findInstancesByType,Sr as findMalformedReferences,Kr as findMarkdownLinkAt,Nr as formatKanonakAddress,R as formatVersion,ct as generateDPoPKeyPair,Ot as getGlobalCachePath,Lt as getKanonakUserAgent,Y as hasValidToken,Tt as isCompatibleVersion,Z as isExpired,$t as isMajorCompatible,C as kanonakFetch,je as loadLockFile,fr as makeUriKey,$e as noopMeter,c as normalizeHost,Se as parseKanonakAddress,Dt as parseVersionString,_r as parseWithPositions,_t as pickHighestDocument,jr as propertiesInScope,Sn as resolveDisplayValue,Mr as resolvePropertyStep,W as sanitizeName,Me as saveLockFile,lt as serverSupportsDPoP,ae as sessionNeedsRefresh,Ft as setKanonakFetchRetries,Vt as setKanonakUserAgent,P as subjectUri,Or as superClassChain,hr as tripleKey,V as uriKey,gr as uriTriple,xt as versionOperatorFromChar,fe as versionOperatorToChar,Ct as versionsEqual};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{h as e,j as r,k as n}from"../chunk-UXYCUGSF.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-
|
|
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-CC44JAOT.js";import{g,h,j as i,k as j}from"../chunk-UXYCUGSF.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};
|
package/dist/server/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{j as te}from"../chunk-IHB7UVEH.js";import"../chunk-QHABFCRC.js";import{a as fe,d as Q,f as be,h as Z}from"../chunk-3BNJXSVZ.js";import{e as ke,f as ye,i as G,j as X}from"../chunk-XGTUVPR3.js";import{a as me}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as $e}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import{a as q,b as z}from"../chunk-ITKOKDBG.js";import{l as re}from"../chunk-MX3DEXMV.js";import{a as O}from"../chunk-NJ3AZYQD.js";import{b as Se}from"../chunk-ZP6P7HNU.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import{c as ve,s as ee}from"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import{c as B,e as D,f as H,g as he}from"../chunk-2ACBWC7K.js";import{readFileSync as ie,writeFileSync as _e,mkdirSync as je}from"fs";import{join as ne}from"path";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 U(t){return we}function F(t){return`${t.publisher}/${t.package_}`}function Y(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"},a=[];for(let r of t)if(r.origin==="missing"){let i=F(r),n=e[i]??"whatever this package contributes to rendering is lost";a.push(`Render-stack package ${i} is MISSING (${r.reason??"unknown reason"}) \u2014 ${n}. Fix: kanonak install ${i} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&a.push(`Render-stack package ${F(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return a}function oe(t){let{publisher:e,availablePublishers:a,catalog:r,lookRenderer:i,localNamespaces:n,rawByNsKey:m,renderStack:u,producers:k,lockSource:p,configSource:h}=t,o=new Map,g=new Map,w=new Map,v=new Set;for(let $ of r){if(!($ instanceof ve))continue;let R=$.namespace||"";if(!n.has(R))continue;o.set(`${R}/${$.name}`,$);let _=R.split("/")[1]??"",[j,M]=_.split("@");if(!j||!M)continue;let K=he(M);K&&(v.has(_)||(v.add(_),g.has(j)||g.set(j,[]),g.get(j).push({verStr:M,version:K})),$.name===j&&w.set(_,$))}for(let $ of g.values())$.sort((R,_)=>B(_.version,R.version));return{publisher:e,availablePublishers:a,catalog:r,lookRenderer:i,localNamespaces:n,rawByNsKey:m,bySubject:o,pkgVersions:g,pkgSelfByVer:w,renderStack:u,...k?{producers:k}:{},...p?{lockSource:p}:{},...h?{configSource:h}:{}}}async function ce(t,e={}){let a=new O,r=new me(a),i=[],n=[];for(let c of Z(t)){let d;try{d=ie(c,"utf-8")}catch{continue}let y;try{y=a.parse(d).metadata?.namespace_}catch{continue}if(!y?.version)continue;let I=y.version;n.push({publisher:y.publisher,package_:y.package_,verStr:D(I),version:I,source:d})}n.sort((c,d)=>B(d.version,c.version));for(let c of n)await r.saveDocumentAsync(a.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),i.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let m=[...new Set(i.map(c=>c.publisher))].sort(),u=e.publisher;if(u){if(!m.includes(u))throw new Error(`Publisher "${u}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)u=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,p=new Map;for(let c of i)c.publisher===u&&(k.add(`${c.publisher}/${c.package_}@${c.verStr}`),p.set(`${c.package_}@${c.verStr}`,c.source));let h=Q(),o=new fe(h,!0,a),g={};e.httpCache&&(g.getFromCache=e.httpCache.getFromCache,g.onFetch=e.httpCache.onFetch),e.fetchFn&&(g.fetchFn=e.fetchFn);let w=e.repository??new be(r,o,new X(g)),v=e.log??(()=>{}),$=U(void 0),R=[],_=c=>c.map(d=>d.metadata.namespace_?.version).filter(d=>d!==void 0).sort((d,y)=>B(y,d)).map(D);if(!e.repository){v(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${h}`);let c=e.fetchFn?new G({fetchFn:e.fetchFn}):new G;for(let d of $){let y=F(d),I=await r.getDocumentsByNamespaceAsync(d.publisher,d.package_);if(I.length>0){let l=_(I);R.push({...d,origin:"workspace",versions:l}),v(`[render-stack] ${y} \u2014 workspace (${l.join(", ")})`);continue}let s=await o.getDocumentsByNamespaceAsync(d.publisher,d.package_);if(s.length>0){let l=_(s);R.push({...d,origin:"cache",versions:l}),v(`[render-stack] ${y} \u2014 cache (${l.join(", ")})`);continue}try{let f=(await c.getLock(d.publisher))?.packages[`${d.publisher}/${d.package_}`];if(!f){let C=`publisher ${d.publisher} reachable but its lock does not pin ${d.package_}`;R.push({...d,origin:"missing",reason:C}),v(`[render-stack] ${y} \u2014 MISSING: ${C}`);continue}let S=f.version,b=f.resolved,E=await(e.fetchFn?e.fetchFn(b,d.publisher):ke(b));if(!E.ok){let C=`fetch ${b} failed: HTTP ${E.status} ${E.statusText}`;R.push({...d,origin:"missing",reason:C}),v(`[render-stack] ${y} \u2014 MISSING: ${C}`);continue}let ge=await E.text();await r.saveDocumentAsync(a.parse(ge),`${d.publisher}/${d.package_}@${S}`);try{let C=ne(h,d.publisher);je(C,{recursive:!0}),_e(ne(C,`${d.package_}@${S}.kan.yml`),ge,"utf-8"),R.push({...d,origin:"fetched",versions:[S]}),v(`[render-stack] ${y}@${S} \u2014 fetched from ${b}, installed to cache`)}catch(C){R.push({...d,origin:"fetched",versions:[S]}),v(`[render-stack] ${y}@${S} \u2014 fetched from ${b}, but cache ${h} is NOT WRITABLE (${C.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(l){let f=`fetch failed: ${l.message}`;R.push({...d,origin:"missing",reason:f}),v(`[render-stack] ${y} \u2014 MISSING: ${f}`)}}}let j=w;if(!e.repository){let c=(await r.getAllDocumentsAsync()).filter(y=>y.metadata.namespace_?.publisher===u),d=await q(c,w);for(let y of $)d.add(F(y));j=new z(w,d)}let M=await new re(a).parseKanonaks(j),K=new te(M),T=(c,d)=>ee(M,{publisher:c,package_:d,name:d}).length>0,V;if(e.repository){V=[];for(let c of $){let d=await w.getDocumentsByNamespaceAsync(c.publisher,c.package_);V.push(d.length>0?{...c,origin:"repository",versions:_(d)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else V=R.map(c=>c.origin==="missing"||T(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let J=Y(V);for(let c of J)v(`[render-stack] WARNING: ${c}`);let W={contractSource:"universal-default",cachePath:h,packages:V,warnings:J},L;try{L=ie(ne(t,"kanonak.lock"),"utf-8")}catch{L=void 0}let A;try{A=ie(ne(t,".well-known","kanonak.json"),"utf-8")}catch{A=void 0}return oe({publisher:u,availablePublishers:m,catalog:M,lookRenderer:K,localNamespaces:k,rawByNsKey:p,renderStack:W,...L?{lockSource:L}:{},...A?{configSource:A}:{}})}import{existsSync as Ce,readFileSync as Fe,writeFileSync as Me,mkdirSync as Ne}from"fs";import{join as Re}from"path";async function le(t,e={}){let a=new O,r=Se(t),i=r.kind==="resource"?r.uri.publisher:r.publisher,n=e.log??(()=>{}),m=e.cacheRoot??Q(),u=(s,l,f)=>Re(m,s,`${l}@${f}.kan.yml`),k=new Set,p=new Set,h=new Map,o=new X({getFromCache:(s,l,f)=>{let S=u(s,l,f),b=Ce(S)?Fe(S,"utf-8"):null;return b!==null&&k.add(`${s}/${l}`),b},onFetch:(s,l,f,S)=>{p.add(`${s}/${l}`);try{let b=Re(m,s);Ne(b,{recursive:!0}),Me(u(s,l,f),S,"utf-8")}catch(b){h.set(`${s}/${l}`,b.message),n(`[render] fetched ${s}/${l}@${f} but cache ${m} is NOT WRITABLE (${b.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),g=new G(e.fetchFn?{fetchFn:e.fetchFn}:void 0),w;if(r.kind==="resource"){let s=r.uri.version;w=[s?{package_:r.uri.package_,version:`${s.major}.${s.minor}.${s.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let s=r.version;w=[s?{package_:r.package_,version:`${s.major}.${s.minor}.${s.patch}`}:{package_:r.package_}]}else w=((await g.getConfig(i)).featured_packages??[]).map(l=>({package_:l}));let v=async(s,l,f)=>{try{let S=f?a.buildImport(l,"=",f,s):a.buildImport(l,"*","0.0.0",s),b=await o.getHighestCompatibleVersionAsync(s,S);return b?{doc:b}:{doc:null,error:`${s} did not resolve ${l}${f?`@${f}`:""} (not in its index, or unreachable)`}}catch(S){return{doc:null,error:S.message}}},$=[],R=[];for(let s of w){let{doc:l,error:f}=await v(i,s.package_,s.version);l?$.push(l):f&&R.push(f)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${i}".`+(R.length>0?` Reasons: ${R.join("; ")}`:""));let _=U(),j="universal-default",M=s=>s.map(l=>l.metadata.namespace_?.version).filter(l=>l!==void 0).sort((l,f)=>B(f,l)).map(D);n(`[render-stack] resolving ${_.length} ambient look-stack package(s) (contract: ${j}); cache: ${m}`);let K=[],T=[];for(let s of _){let l=F(s),{doc:f,error:S}=await v(s.publisher,s.package_,void 0);if(f){K.push(f);let b=M([f]),E=p.has(l)?"fetched":k.has(l)?"cache":"fetched";T.push({...s,origin:E,versions:b}),n(`[render-stack] ${l} \u2014 ${E} (${b.join(", ")})`+(h.has(l)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else T.push({...s,origin:"missing",reason:S??"unresolved"}),n(`[render-stack] ${l} \u2014 MISSING: ${S??"unresolved"}`)}let V=await q([...$,...K],o),J=new z(o,V),W=await new re(a).parseKanonaks(J),L=new te(W),A=T.map(s=>s.origin==="missing"||ee(W,{publisher:s.publisher,package_:s.package_,name:s.package_}).length>0?s:{...s,resolvedButNotInCatalog:!0}),c=Y(A);for(let s of c)n(`[render-stack] WARNING: ${s}`);let d={contractSource:j,cachePath:m,packages:A,warnings:c},y=new Set,I=new Map;for(let s of await o.getAllDocumentsAsync()){let l=s.metadata.namespace_;if(!l?.version||l.publisher!==i)continue;let f=D(l.version),S=`${l.publisher}/${l.package_}@${f}`;y.add(S);let b=await o.getDocumentContentAsync(S);b!==null&&I.set(`${l.package_}@${f}`,b)}return oe({publisher:i,availablePublishers:[i],catalog:W,lookRenderer:L,localNamespaces:y,rawByNsKey:I,renderStack:d})}import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";function se(t){let{lookRenderer:e,publisher:a,renderStack:r,catalog:i}=t,n=e.explainStylesheet(e.publisherSubject(a)),m=[...n.tokens.entries()].map(([o,g])=>({name:o,value:g.value,source:`${g.sourceNamespace}/${g.sourceName}`,level:g.level})),u=n.baseStylesheet,k={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 i){let g=o.namespace;g&&p.set(g,(p.get(g)??0)+1)}let h=[...p.entries()].map(([o,g])=>({namespace:o,resources:g})).sort((o,g)=>o.namespace.localeCompare(g.namespace));return{publisher:a,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(o=>({package_:F(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,...n.look?{look:{sourceClass:`${n.look.sourceClass.publisher}/${n.look.sourceClass.package_}/${n.look.sourceClass.name}`}}:{}},catalog:h,warnings:[...r.warnings,...n.warnings.filter(o=>!r.warnings.includes(o))]}}function Ie(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function de(t){let e=Ie,a=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(p=>`<div class="warn">\u26A0 ${e(p)}</div>`).join(`
|
|
2
|
-
`),i=t.renderStack.packages.map(
|
|
3
|
-
`),
|
|
4
|
-
`),k=t.catalog.map(
|
|
1
|
+
import{c as we}from"../chunk-L2KE7B3K.js";import{j as te}from"../chunk-IHB7UVEH.js";import"../chunk-QHABFCRC.js";import{a as fe,d as Q,f as be,h as Z}from"../chunk-CC44JAOT.js";import{e as ke,g as ye,j as G,k as X}from"../chunk-UXYCUGSF.js";import{a as me}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as $e}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import{a as q,b as z}from"../chunk-ITKOKDBG.js";import{l as re}from"../chunk-MX3DEXMV.js";import{a as O}from"../chunk-NJ3AZYQD.js";import{b as Se}from"../chunk-ZP6P7HNU.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import{c as ve,s as ee}from"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import{c as L,e as D,f as H,g as he}from"../chunk-2ACBWC7K.js";import{readFileSync as ie,writeFileSync as je,mkdirSync as Ce}from"fs";import{join as oe}from"path";import Fe from"js-yaml";var Re=[{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 U(t){return Re}function F(t){return`${t.publisher}/${t.package_}`}function Y(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"},s=[];for(let r of t)if(r.origin==="missing"){let i=F(r),o=e[i]??"whatever this package contributes to rendering is lost";s.push(`Render-stack package ${i} is MISSING (${r.reason??"unknown reason"}) \u2014 ${o}. Fix: kanonak install ${i} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&s.push(`Render-stack package ${F(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return s}function ne(t){let{publisher:e,availablePublishers:s,catalog:r,lookRenderer:i,localNamespaces:o,rawByNsKey:m,renderStack:p,producers:k,lockSource:c,configSource:h}=t,n=new Map,g=new Map,w=new Map,v=new Set;for(let $ of r){if(!($ instanceof ve))continue;let R=$.namespace||"";if(!o.has(R))continue;n.set(`${R}/${$.name}`,$);let _=R.split("/")[1]??"",[j,N]=_.split("@");if(!j||!N)continue;let K=he(N);K&&(v.has(_)||(v.add(_),g.has(j)||g.set(j,[]),g.get(j).push({verStr:N,version:K})),$.name===j&&w.set(_,$))}for(let $ of g.values())$.sort((R,_)=>L(_.version,R.version));return{publisher:e,availablePublishers:s,catalog:r,lookRenderer:i,localNamespaces:o,rawByNsKey:m,bySubject:n,pkgVersions:g,pkgSelfByVer:w,renderStack:p,...k?{producers:k}:{},...c?{lockSource:c}:{},...h?{configSource:h}:{}}}async function ce(t,e={}){let s=new O,r=new me(s),i=[],o=[];for(let l of Z(t)){let u;try{u=ie(l,"utf-8")}catch{continue}let y;try{y=s.parse(u).metadata?.namespace_}catch{continue}if(!y?.version)continue;let I=y.version;o.push({publisher:y.publisher,package_:y.package_,verStr:D(I),version:I,source:u})}o.sort((l,u)=>L(u.version,l.version));for(let l of o)await r.saveDocumentAsync(s.parse(l.source),`${l.publisher}/${l.package_}@${l.verStr}`),i.push({publisher:l.publisher,package_:l.package_,verStr:l.verStr,source:l.source});let m=[...new Set(i.map(l=>l.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,c=new Map;for(let l of i)l.publisher===p&&(k.add(`${l.publisher}/${l.package_}@${l.verStr}`),c.set(`${l.package_}@${l.verStr}`,l.source));let h=Q(),n=new fe(h,!0,s),g={};e.httpCache&&(g.getFromCache=e.httpCache.getFromCache,g.onFetch=e.httpCache.onFetch),e.fetchFn&&(g.fetchFn=e.fetchFn);let w=e.repository??new be(r,n,new X(g)),v=e.log??(()=>{}),$=U(void 0),R=[],_=l=>l.map(u=>u.metadata.namespace_?.version).filter(u=>u!==void 0).sort((u,y)=>L(y,u)).map(D);if(!e.repository){v(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${h}`);let l=e.fetchFn?new G({fetchFn:e.fetchFn}):new G;for(let u of $){let y=F(u),I=await r.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(I.length>0){let d=_(I);R.push({...u,origin:"workspace",versions:d}),v(`[render-stack] ${y} \u2014 workspace (${d.join(", ")})`);continue}let a=await n.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(a.length>0){let d=_(a);R.push({...u,origin:"cache",versions:d}),v(`[render-stack] ${y} \u2014 cache (${d.join(", ")})`);continue}try{let f=(await l.getLock(u.publisher))?.packages[`${u.publisher}/${u.package_}`];if(!f){let C=`publisher ${u.publisher} reachable but its lock does not pin ${u.package_}`;R.push({...u,origin:"missing",reason:C}),v(`[render-stack] ${y} \u2014 MISSING: ${C}`);continue}let S=f.version,b=f.resolved,E=await(e.fetchFn?e.fetchFn(b,u.publisher):ke(b));if(!E.ok){let C=`fetch ${b} failed: HTTP ${E.status} ${E.statusText}`;R.push({...u,origin:"missing",reason:C}),v(`[render-stack] ${y} \u2014 MISSING: ${C}`);continue}let ge=await E.text();await r.saveDocumentAsync(s.parse(ge),`${u.publisher}/${u.package_}@${S}`);try{let C=oe(h,u.publisher);Ce(C,{recursive:!0}),je(oe(C,`${u.package_}@${S}.kan.yml`),ge,"utf-8"),R.push({...u,origin:"fetched",versions:[S]}),v(`[render-stack] ${y}@${S} \u2014 fetched from ${b}, installed to cache`)}catch(C){R.push({...u,origin:"fetched",versions:[S]}),v(`[render-stack] ${y}@${S} \u2014 fetched from ${b}, but cache ${h} is NOT WRITABLE (${C.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(d){let f=`fetch failed: ${d.message}`;R.push({...u,origin:"missing",reason:f}),v(`[render-stack] ${y} \u2014 MISSING: ${f}`)}}}let j=w;if(!e.repository){let l=(await r.getAllDocumentsAsync()).filter(y=>y.metadata.namespace_?.publisher===p),u=await q(l,w);for(let y of $)u.add(F(y));j=new z(w,u)}let N=await new re(s).parseKanonaks(j),K=new te(N),T=(l,u)=>ee(N,{publisher:l,package_:u,name:u}).length>0,V;if(e.repository){V=[];for(let l of $){let u=await w.getDocumentsByNamespaceAsync(l.publisher,l.package_);V.push(u.length>0?{...l,origin:"repository",versions:_(u)}:{...l,origin:"missing",reason:"not present in the caller-supplied repository"})}}else V=R.map(l=>l.origin==="missing"||T(l.publisher,l.package_)?l:{...l,resolvedButNotInCatalog:!0});let J=Y(V);for(let l of J)v(`[render-stack] WARNING: ${l}`);let W={contractSource:"universal-default",cachePath:h,packages:V,warnings:J},B;try{B=ie(oe(t,"kanonak.lock"),"utf-8")}catch{B=Ne(p,i,s)}let A;try{A=ie(oe(t,".well-known","kanonak.json"),"utf-8")}catch{A=void 0}return ne({publisher:p,availablePublishers:m,catalog:N,lookRenderer:K,localNamespaces:k,rawByNsKey:c,renderStack:W,...B?{lockSource:B}:{},...A?{configSource:A}:{}})}function Ne(t,e,s){let r=new Map;for(let o of e)o.publisher===t&&(r.has(o.package_)||r.set(o.package_,{verStr:o.verStr,source:o.source}));if(r.size===0)return;let i={};for(let o of[...r.keys()].sort()){let{verStr:m,source:p}=r.get(o),k={},c;try{c=s.parse(p).metadata?.imports}catch{c=void 0}for(let n of c?.[t]??[]){let g=r.get(n.packageName);g&&(k[`${t}/${n.packageName}`]=g.verStr)}let h={};for(let n of Object.keys(k).sort())h[n]=k[n];i[`${t}/${o}`]={version:m,resolved:`https://${t}/${o}/${m}.kan.yml`,integrity:we(p),dependencies:h}}return Fe.dump({version:"1",lastUpdated:"",packages:i},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as Me,readFileSync as Ie,writeFileSync as De,mkdirSync as Ke}from"fs";import{join as xe}from"path";async function le(t,e={}){let s=new O,r=Se(t),i=r.kind==="resource"?r.uri.publisher:r.publisher,o=e.log??(()=>{}),m=e.cacheRoot??Q(),p=(a,d,f)=>xe(m,a,`${d}@${f}.kan.yml`),k=new Set,c=new Set,h=new Map,n=new X({getFromCache:(a,d,f)=>{let S=p(a,d,f),b=Me(S)?Ie(S,"utf-8"):null;return b!==null&&k.add(`${a}/${d}`),b},onFetch:(a,d,f,S)=>{c.add(`${a}/${d}`);try{let b=xe(m,a);Ke(b,{recursive:!0}),De(p(a,d,f),S,"utf-8")}catch(b){h.set(`${a}/${d}`,b.message),o(`[render] fetched ${a}/${d}@${f} but cache ${m} is NOT WRITABLE (${b.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),g=new G(e.fetchFn?{fetchFn:e.fetchFn}:void 0),w;if(r.kind==="resource"){let a=r.uri.version;w=[a?{package_:r.uri.package_,version:`${a.major}.${a.minor}.${a.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let a=r.version;w=[a?{package_:r.package_,version:`${a.major}.${a.minor}.${a.patch}`}:{package_:r.package_}]}else w=((await g.getConfig(i)).featured_packages??[]).map(d=>({package_:d}));let v=async(a,d,f)=>{try{let S=f?s.buildImport(d,"=",f,a):s.buildImport(d,"*","0.0.0",a),b=await n.getHighestCompatibleVersionAsync(a,S);return b?{doc:b}:{doc:null,error:`${a} did not resolve ${d}${f?`@${f}`:""} (not in its index, or unreachable)`}}catch(S){return{doc:null,error:S.message}}},$=[],R=[];for(let a of w){let{doc:d,error:f}=await v(i,a.package_,a.version);d?$.push(d):f&&R.push(f)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${i}".`+(R.length>0?` Reasons: ${R.join("; ")}`:""));let _=U(),j="universal-default",N=a=>a.map(d=>d.metadata.namespace_?.version).filter(d=>d!==void 0).sort((d,f)=>L(f,d)).map(D);o(`[render-stack] resolving ${_.length} ambient look-stack package(s) (contract: ${j}); cache: ${m}`);let K=[],T=[];for(let a of _){let d=F(a),{doc:f,error:S}=await v(a.publisher,a.package_,void 0);if(f){K.push(f);let b=N([f]),E=c.has(d)?"fetched":k.has(d)?"cache":"fetched";T.push({...a,origin:E,versions:b}),o(`[render-stack] ${d} \u2014 ${E} (${b.join(", ")})`+(h.has(d)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else T.push({...a,origin:"missing",reason:S??"unresolved"}),o(`[render-stack] ${d} \u2014 MISSING: ${S??"unresolved"}`)}let V=await q([...$,...K],n),J=new z(n,V),W=await new re(s).parseKanonaks(J),B=new te(W),A=T.map(a=>a.origin==="missing"||ee(W,{publisher:a.publisher,package_:a.package_,name:a.package_}).length>0?a:{...a,resolvedButNotInCatalog:!0}),l=Y(A);for(let a of l)o(`[render-stack] WARNING: ${a}`);let u={contractSource:j,cachePath:m,packages:A,warnings:l},y=new Set,I=new Map;for(let a of await n.getAllDocumentsAsync()){let d=a.metadata.namespace_;if(!d?.version||d.publisher!==i)continue;let f=D(d.version),S=`${d.publisher}/${d.package_}@${f}`;y.add(S);let b=await n.getDocumentContentAsync(S);b!==null&&I.set(`${d.package_}@${f}`,b)}return ne({publisher:i,availablePublishers:[i],catalog:W,lookRenderer:B,localNamespaces:y,rawByNsKey:I,renderStack:u})}import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";function se(t){let{lookRenderer:e,publisher:s,renderStack:r,catalog:i}=t,o=e.explainStylesheet(e.publisherSubject(s)),m=[...o.tokens.entries()].map(([n,g])=>({name:n,value:g.value,source:`${g.sourceNamespace}/${g.sourceName}`,level:g.level})),p=o.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},c=new Map;for(let n of i){let g=n.namespace;g&&c.set(g,(c.get(g)??0)+1)}let h=[...c.entries()].map(([n,g])=>({namespace:n,resources:g})).sort((n,g)=>n.namespace.localeCompare(g.namespace));return{publisher:s,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(n=>({package_:F(n),origin:n.origin,...n.versions!==void 0?{versions:n.versions}:{},...n.reason!==void 0?{reason:n.reason}:{},...n.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:n.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:k,...o.look?{look:{sourceClass:`${o.look.sourceClass.publisher}/${o.look.sourceClass.package_}/${o.look.sourceClass.name}`}}:{}},catalog:h,warnings:[...r.warnings,...o.warnings.filter(n=>!r.warnings.includes(n))]}}function Ve(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function de(t){let e=Ve,s=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(c=>`<div class="warn">\u26A0 ${e(c)}</div>`).join(`
|
|
2
|
+
`),i=t.renderStack.packages.map(c=>{let h=c.origin!=="missing"&&!c.resolvedButNotInCatalog,n=c.origin==="missing"?'<span class="bad">MISSING</span>':c.resolvedButNotInCatalog?`<span class="bad">${e(c.origin)} (not in catalog)</span>`:`<span class="good">${e(c.origin)}</span>`,g=c.reason?e(c.reason):e((c.versions??[]).join(", "));return`<tr class="${h?"":"row-bad"}"><td><code>${e(c.package_)}</code></td><td>${n}</td><td>${g}</td></tr>`}).join(`
|
|
3
|
+
`),o=t.stylesheet.baseStylesheet,m=o.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(o.source??"")}</code> (${o.bytes} bytes, ${e(o.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${o.problem?` \u2014 ${e(o.problem)}`:""}${o.candidates.length>0?`<br>candidates considered: ${o.candidates.map(c=>`<code>${e(c)}</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(c=>`<tr><td><code>--kan-${e(c.name)}</code></td><td><code>${e(c.value)}</code></td><td><code>${e(c.source)}</code></td><td>${e(c.level)}</td></tr>`).join(`
|
|
4
|
+
`),k=t.catalog.map(c=>`<tr><td><code>${e(c.namespace)}</code></td><td>${c.resources}</td></tr>`).join(`
|
|
5
5
|
`);return`<!doctype html>
|
|
6
6
|
<html lang="en">
|
|
7
7
|
<head>
|
|
@@ -21,12 +21,12 @@ import{j as te}from"../chunk-IHB7UVEH.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: ${
|
|
24
|
+
background: ${s?"#ecfdf3":"#fef2f2"}; border: 1px solid ${s?"#0a7d33":"#b91c1c"}; }
|
|
25
25
|
</style>
|
|
26
26
|
</head>
|
|
27
27
|
<body>
|
|
28
28
|
<h1>Render diagnostics \u2014 ${e(t.publisher)}</h1>
|
|
29
|
-
<p class="status-banner">${
|
|
29
|
+
<p class="status-banner">${s?"\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>
|
|
@@ -48,7 +48,7 @@ ${m}
|
|
|
48
48
|
<p class="meta">Resolved for the publisher landing page. Each token shows which resource in the cascade supplied it.</p>
|
|
49
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
|
-
${
|
|
51
|
+
${p}
|
|
52
52
|
</table>`}
|
|
53
53
|
|
|
54
54
|
<h2>Look (page body)</h2>
|
|
@@ -61,4 +61,4 @@ ${t.stylesheet.look?`<p><span class="good">\u2713</span> Bands resolve from <cod
|
|
|
61
61
|
${k}
|
|
62
62
|
</table>
|
|
63
63
|
</body>
|
|
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,
|
|
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,s,r)=>({status:t,headers:{"Content-Type":e,...r||{}},body:s}),M=t=>P(404,x[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${t}</p>`),Ae=t=>({status:301,headers:{Location:t},body:""}),Ee=t=>({status:302,headers:{Location:t},body:""});function Le(t){switch(t.kind){case"exact":return{operator:ae.Exact,version:H(t.major,t.minor,t.patch)};case"minor-pin":return{operator:ae.Compatible,version:H(t.major,t.minor,0)};case"major-pin":return{operator:ae.Major,version:H(t.major,0,0)};default:return{operator:ae.Any,version:H(0,0,0)}}}async function Be(t,e,s,r){if(!r)return null;let i=t.producers?.find(k=>k.canProduce(t.publisher,e));if(!i)return null;let o=await i.resolveVersion(t.publisher,e,Le(s));if(!o)return null;let m=D(o);if(s.kind!=="exact")return Ee(`/${e}/${m}.kan.yml`);let{source:p}=await i.produce(t.publisher,e,o);return P(200,x[".kan.yml"],p)}function Pe(t,e,s){let r=t.pkgVersions.get(e);if(!r||r.length===0)return null;switch(s.kind){case"any":return r[0].verStr;case"major-pin":return r.find(i=>i.version.major===s.major)?.verStr??null;case"minor-pin":return r.find(i=>i.version.major===s.major&&i.version.minor===s.minor)?.verStr??null;case"exact":return r.find(i=>i.version.major===s.major&&i.version.minor===s.minor&&i.version.patch===s.patch)?.verStr??null;default:return null}}async function pe(t,e,s=""){let{lookRenderer:r,publisher:i}=t;if(e==="/.well-known/kanonak.json")return t.configSource?P(200,x[".json"],t.configSource):P(200,x[".json"],JSON.stringify(ye(),null,2));if(e==="/kanonak.lock")return t.lockSource?P(200,x[".kan.yml"],t.lockSource):M(e);if(e==="/.well-known/kanonak-render.json")return P(200,x[".json"],JSON.stringify(se(t),null,2));if(e==="/.well-known/kanonak-render")return P(200,x[".html"],de(se(t)));if(e==="/"||e==="/index.html"||e==="/index.css"){let n=r.publisherSubject(i);return e==="/index.css"?P(200,x[".css"],r.renderStylesheet(n)):P(200,x[".html"],await r.renderDocument(n,{rootIndex:!0}))}let o=".html",m=!1,p=e;for(let n of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(n)){o=n,m=!0,p=e.slice(0,-n.length);break}let k=!m&&/application\/yaml|text\/yaml/i.test(s),c=p.endsWith("/");c&&p!=="/"&&(p=p.slice(0,-1));let h=$e.parse(p,i);if(!h)return M(e);if(h.kind==="package"){let n=Pe(t,h.package_,h.versionSpec);if(!n)return await Be(t,h.package_,h.versionSpec,o===".kan.yml"||k)??M(e);if(o===".kan.yml"||k){let v=t.rawByNsKey.get(`${h.package_}@${n}`);return v!==void 0?P(200,x[".kan.yml"],v):M(e)}let g=t.pkgSelfByVer.get(`${h.package_}@${n}`);if(!g)return M(e);if(o===".css")return P(200,x[".css"],r.renderStylesheet(g));if(!c)return Ae(p+"/");let w=h.versionSpec.kind==="any";if(w&&!r.hasDeclaredView(g)){let v=(t.pkgVersions.get(h.package_)||[]).map($=>$.verStr);return P(200,x[".html"],r.renderPackageVersionList(h.package_,v,g))}return P(200,x[".html"],await r.renderDocument(g,w?{bareOverview:!0}:void 0))}if(h.kind==="resource"){let n=Pe(t,h.package_,h.versionSpec);if(!n)return M(e);let g=t.bySubject.get(`${i}/${h.package_}@${n}/${h.name}`);if(!g)return M(e);switch(o){case".css":return P(200,x[".css"],r.renderStylesheet(g));case".svg":return P(200,x[".svg"],await r.renderSvg(g));case".md":{let w=r.renderRawMarkdown(g);return w===void 0?M(e):P(200,x[".md"],w)}default:return P(200,x[".html"],await r.renderDocument(g))}}return M(e)}import{readFileSync as Oe}from"fs";var ue=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,s=new Set;if(this.options.root!==void 0){let r=new O;for(let i of Z(this.options.root))try{let o=r.parse(Oe(i,"utf-8")).metadata?.namespace_;if(!o?.version)continue;let m=o.version;e.add(`${o.publisher}/${o.package_}@${m.major}.${m.minor}.${m.patch}`),s.add(`${o.publisher}/${o.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:s},this.workspaceIndex}async modelFor(e,s,r){let i=this.getWorkspaceIndex(),o={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},m=s?r?i.exact.has(`${e}/${s}@${r}`):i.pkgs.has(`${e}/${s}`):[...i.pkgs].some(n=>n.startsWith(`${e}/`)),p,k;if(m&&this.options.root!==void 0){let n=this.options.root;p=`ws:${e}`,k=()=>ce(n,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let n=s?r?`${e}/${s}@${r}`:`${e}/${s}`:e;p=`rm:${n}`,k=()=>le(n,o)}let c=this.models.get(p);if(c)return c;let h=await k();return h.lookRenderer.setLinkMode("open-world"),this.models.set(p,h),h}async handle(e,s=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:_e()};let i=r[0];if(!i.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 o=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),m=!o&&r.length>=2?r[1]:void 0,p=!o&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,k=await this.modelFor(i,m,p),c=e.endsWith("/")&&r.length>1?"/":"",h="/"+r.slice(1).join("/")+c,n=await pe(k,h,s);return n.headers.Location?{...n,headers:{...n.headers,Location:`/${i}${n.headers.Location}`}}:n}};function _e(){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{z as ClosureScopedRepository,ue as RequestRouter,Re as UNIVERSAL_RENDER_BASE,se as buildRenderDiagnostics,Y as buildRenderStackWarnings,q as deriveImportClosure,_e as landingPage,le as loadResourceModel,ce as loadServerModel,de as renderDiagnosticsHtml,F as renderRefKey,U as resolveRenderContract,pe as route};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanonak-protocol/sdk",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.8.0",
|
|
4
4
|
"description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -126,7 +126,7 @@
|
|
|
126
126
|
],
|
|
127
127
|
"dependencies": {
|
|
128
128
|
"@kanonak-protocol/canonical": "^0.1.1",
|
|
129
|
-
"@kanonak-protocol/types": "^5.
|
|
129
|
+
"@kanonak-protocol/types": "^5.8.0",
|
|
130
130
|
"ignore": "^7.0.5",
|
|
131
131
|
"js-yaml": "^4.1.0",
|
|
132
132
|
"yaml": "^2.7.0"
|
package/dist/chunk-XGTUVPR3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as v}from"./chunk-SC5M74NM.js";import{a as C}from"./chunk-NJ3AZYQD.js";import{e as y,g as P}from"./chunk-2ACBWC7K.js";var x="@kanonak-protocol/sdk (+https://kanonak.org)",F=x;function K(o){F=o}function b(){return F}function p(o){let t;try{t=typeof o=="string"?new URL(o):o}catch{throw new Error(`Kanonak requires an absolute https:// URL \u2014 got an unparseable or relative URL: ${String(o)}`)}if(t.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${t.href} (only https:// is supported).`)}function g(o,t){p(o);let e=new Headers(t?.headers);return e.has("User-Agent")||e.set("User-Agent",F),fetch(o,{...t,headers:e})}var L="https://{publisher}/{package}/{version}.kan.yml",A={version:1};function T(){return{version:1}}var k=class{constructor(t){this.fetchFn=t}fetchFn;cache=new Map;getConfig(t){let e=this.cache.get(t);return e||(e=this.fetchConfig(t),this.cache.set(t,e),e.catch(()=>{this.cache.get(t)===e&&this.cache.delete(t)})),e}async fetchConfig(t){let e=`https://${t}/.well-known/kanonak.json`,n;try{n=await(this.fetchFn?this.fetchFn(e,t):g(e))}catch{return A}if(n.status===404)return A;if(!n.ok)throw new Error(`Failed to fetch publisher config: ${e} (${n.status} ${n.statusText})`);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let i={version:r.version};return typeof r.package_url_template=="string"&&(U(e,"package_url_template",r.package_url_template),i.package_url_template=r.package_url_template),Array.isArray(r.featured_packages)&&r.featured_packages.every(s=>typeof s=="string")&&(i.featured_packages=r.featured_packages),i}resolvePackageUrl(t,e,n,r){let i=r.package_url_template??L,s=E(i,{publisher:t,package:e,version:n});return p(s),s}};function U(o,t,e){if(!e.startsWith("https://"))throw new Error(`Invalid publisher config at ${o}: ${t} must be an absolute https:// URL template (got "${e}").`)}function E(o,t){let e=o;for(let[r,i]of Object.entries(t))e=e.replaceAll(`{${r}}`,i);let n=e.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${o}`);return e}import D from"js-yaml";function R(o){let t=D.load(o);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??"",packages:t.packages??{}}}var m=class{configResolver;fetchFn;lockCache=new Map;constructor(t){this.configResolver=t?.configResolver??new k(t?.fetchFn),this.fetchFn=t?.fetchFn}getConfig(t){return this.configResolver.getConfig(t)}async getPackageUrl(t,e,n){let r=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,e,n,r)}getLock(t){let e=this.lockCache.get(t);return e||(e=this.fetchLock(t),this.lockCache.set(t,e),e.catch(()=>{this.lockCache.get(t)===e&&this.lockCache.delete(t)})),e}async fetchLock(t){let e=`https://${t}/kanonak.lock`,n;try{n=this.fetchFn?await this.fetchFn(e,t):await g(e)}catch{return null}if(n.status===404)return null;if(!n.ok)throw new Error(`Failed to fetch publisher lock: ${e} (${n.status} ${n.statusText})`);return R(await n.text())}};import{VersionOperator as d}from"@kanonak-protocol/types/document/models/enums";function _(o,t){let e=P(o);if(!e)return!1;let n=t.version;switch(t.versionOperator){case d.Any:return!0;case d.Exact:return e.major===n.major&&e.minor===n.minor&&e.patch===n.patch;case d.Compatible:return e.major===n.major&&e.minor===n.minor&&e.patch>=n.patch;case d.Major:return e.major!==n.major?!1:e.minor!==n.minor?e.minor>n.minor:e.patch>=n.patch;default:return!1}}var $=class{parser=new C;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new m({fetchFn:t.fetchFn}):new m}async getHighestCompatibleVersionAsync(t,e){let r=(await this.publisherIndex.getLock(t))?.packages[`${t}/${e.packageName}`];return r?_(r.version,e)?this.fetchPinned(t,e.packageName,r):null:this.resolveByDirectFetch(t,e)}async fetchPinned(t,e,n){let r=n.version,i=`${t}/${e}@${r}`,s=this.documents.get(i);if(s)return s;let a=u=>{let f=this.parser.parse(u);return v(f,t,e,r),f};if(this.getFromCache){let u=this.getFromCache(t,e,r);if(u){let f=a(u);return this.documents.set(i,f),this.contentCache.set(i,u),f}}let l=n.resolved,c=this.fetchFn?await this.fetchFn(l,t):await g(l);if(!c.ok)throw new Error(`Failed to fetch Kanonak package: ${l} (${c.status} ${c.statusText})`);let h=await c.text(),w=a(h);return this.onFetch&&this.onFetch(t,e,r,h),this.documents.set(i,w),this.contentCache.set(i,h),w}async resolveByDirectFetch(t,e){let n=e.packageName,i=e.versionOperator===d.Exact?await this.publisherIndex.getPackageUrl(t,n,y(e.version)):`https://${t}/${n}.kan.yml`,s=await this.fetchFollowing(i,t);if(!s)return null;let a=this.parser.parse(s.content),l=a.metadata.namespace_;if(!l||!l.version)throw new Error(`Producer origin returned a package with no namespace/version for ${t}/${n}`);let c=y(l.version);v(a,t,n,c);let h=`${t}/${n}@${c}`;return this.onFetch&&this.onFetch(t,n,c,s.content),this.documents.set(h,a),this.contentCache.set(h,s.content),a}async fetchFollowing(t,e,n=4){let r=t;for(let i=0;i<n;i++){p(r);let s=this.fetchFn?await this.fetchFn(r,e):await g(r,{redirect:"manual"});if(s.status===301||s.status===302){let a=s.headers.get("location");if(!a)throw new Error(`Redirect with no Location header from ${r}`);r=new URL(a,r).toString();continue}if(s.status===404)return null;if(!s.ok)throw new Error(`Failed to fetch Kanonak package: ${r} (${s.status} ${s.statusText})`);return{url:r,content:await s.text()}}throw new Error(`Too many redirects resolving ${t}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===t&&r.package_===e})}async saveDocumentAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let e=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,n,r,i]=e;return this.publisherIndex.getPackageUrl(n,r,i)}};export{x as a,K as b,b as c,p as d,g as e,T as f,k as g,R as h,m as i,$ as j};
|