@kanonak-protocol/sdk 6.1.0 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1 +1 @@
1
- import{a as ne,b as ae,c as ie,d as We,e as ze,f as Ye,g as Xe,i as Je,j as Qe,k as Ze,l as $e,m as eo,n as oo,o as ro,p as to,q as no,r as ao,s as io}from"./chunk-PNBTIGX7.js";import{a as so}from"./chunk-ED35OFGD.js";import{a as we,b as Me,c as Fe,d as Ue,e as Be,f as Ge,g as qe,h as po,i as lo,j as co,k as mo,l as uo}from"./chunk-ADSDFJUO.js";import{a as c,b as m,c as d,d as u,e as R,f,g as y,h as k,j as x,m as P,o as E,p as C,q as S,r as g,s as I,t as K}from"./chunk-HKQTB65D.js";import{a as se,b as pe,c as le}from"./chunk-GKIX3OD6.js";import{a as ce}from"./chunk-D2X6J77P.js";import"./chunk-SC5M74NM.js";import{A as He,B as Te,C as ve,M as Le,a as me,b as de,c as ue,d as Re,g as fe,h as ye,i as ke,j as xe,l as Pe,m as Ee,n as Ce,o as Se,p as ge,q as Ie,r as Ke,s as he,t as Ae,u as Oe,v as De,w as be,x as je,y as Ne,z as Ve}from"./chunk-O6SOU5Y2.js";import"./chunk-VORVR5BZ.js";import{m as _e}from"./chunk-TYVZXABI.js";import"./chunk-QHABFCRC.js";import{a as p}from"./chunk-6VIUXP4N.js";import{a as ee,g as oe,h as re,k as te}from"./chunk-22DSABP6.js";import{a as l}from"./chunk-7JBKOJB4.js";import"./chunk-PEJALHXK.js";import{a as F,b as U,h as q,i as W,j as z,k as Y,ka as J,l as X,ma as Q}from"./chunk-NUTHBBDZ.js";import{I as Z,J as $,a as h,b as A,c as O,d as D,e as j,g as N,h as V,i as H,j as T,k as v,l as _,m as L,n as w,o as M,u as B,v as G}from"./chunk-D4QGPMRW.js";import{a as b}from"./chunk-FUUTGGJS.js";import"./chunk-F67UH4FD.js";import{c as e,d as o,e as r,f as t,g as n,h as a,i,k as s}from"./chunk-QILEJIFU.js";export{De as AmbiguousReferenceRule,v as BooleanStatement,Fe as CANONICAL_FORM_VERSION,ro as CREDENTIAL_EXPIRY_SKEW_SECONDS,Qe as CREDENTIAL_HELPER_PROTOCOL_VERSION,oe as Carrier,Te as ClassDefinitionRule,Se as ClassHierarchyCycleRule,R as CredentialError,A as DefinedKanonak,ae as EdgeType,D as EmbeddedKanonak,Pe as EmbeddedKanonakTypeRule,L as EmbeddedStatement,mo as EntitlementDeniedError,uo as EntitlementProducer,ie as GraphBuilder,K as HttpKanonakDocumentRepository,E as INTEGRITY_PREFIX,Ge as ImportBook,Ee as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,f as KANONAK_USER_AGENT,h as Kanonak,pe as KanonakDocumentPositions,c as KanonakHttpError,te as KanonakObjectParser,Le as KanonakObjectValidator,l as KanonakParser,b as KanonakUri,ce as KanonakUriBuilder,J as KanonakVocabulary,w as ListStatement,ve as MarkdownLinkRule,M as MarkdownStatement,Ae as NamespaceImportCycleRule,fe as NamespacePrefixRule,ne as NodeType,T as NumberStatement,Je as OAuthDiscovery,je as ObjectPropertyValueValidationRule,ue as OntologyValidationError,me as OntologyValidationResult,Ue as PackageBuilder,po as ProducerRepository,Ne as PropertyDomainRule,ge as PropertyHierarchyCycleRule,Ve as PropertyKindRangeConsistencyRule,se as PropertyMetadata,be as PropertyRangeReferenceRule,Ie as PropertyRangeRequiredRule,ke as PropertyTypeSpecificityRule,P as PublisherConfigResolver,I as PublisherIndex,j as ReferenceKanonak,_ as ReferenceStatement,He as ReservedNameShadowRule,ye as ResourceNamingRule,F as ResourceResolver,Q as ResourceTypeClassifier,W as SHACL_PACKAGE,q as SHACL_PUBLISHER,Y as SH_NODE_SHAPE,X as SH_PROPERTY_SHAPE,z as SH_SHAPE,V as ScalarStatement,N as Statement,H as StringStatement,Ke as SubClassOfReferenceRule,he as SubPropertyOfReferenceRule,O as SubjectKanonak,xe as SubjectKanonakTypeRequiredRule,no as TOKEN_ENV,io as TokenCredentialProvider,U as TypeResolver,Oe as UnresolvedPredicateRule,Ce as UnresolvedReferenceRule,Re as ValidationContext,de as ValidationSeverity,lo as allowAllPolicy,_e as buildOntologyModel,we as canonicalForm,Me as canonicalHash,re as carrierOf,Ze as checkCredentialAnswer,$e as checkHelperAnswer,eo as checkHelperEraseAnswer,e as compareVersions,g as computeIntegrityAsync,Be as contentAddressedName,to as createCredentialedFetch,t as createVersion,d as describeResponse,so as findDerivation,r as formatVersion,k as getKanonakUserAgent,m as httpError,a as isCompatibleVersion,i as isMajorCompatible,x as kanonakFetch,Xe as narrowestScope,co as noopMeter,We as normalizeHost,C as parseLockFile,ze as parseScope,n as parseVersionString,le as parseWithPositions,oo as parseWwwAuthenticate,s as pickHighestDocument,G as referenceUris,u as retryAfterSecondsOf,qe as sanitizeName,Ye as scopeContains,S as serializeLockFile,y as setKanonakUserAgent,$ as subjectAddress,ao as tokenEnvKeyFor,B as typeReferenceUris,Z as valuesOf,o as versionsEqual,ee as walkDefinedKanonaks};
1
+ import{a as ne,b as ae,c as ie,d as We,e as ze,f as Ye,g as Xe,i as Je,j as Qe,k as Ze,l as $e,m as eo,n as oo,o as ro,p as to,q as no,r as ao,s as io}from"./chunk-EKD2ZLKQ.js";import{a as so}from"./chunk-ED35OFGD.js";import{a as we,b as Me,c as Fe,d as Ue,e as Be,f as Ge,g as qe,h as po,i as lo,j as co,k as mo,l as uo}from"./chunk-ADSDFJUO.js";import{a as f,b as y,c as k,e as x,h as P,j as E,k as C,l as S,m as g,n as I,o as K}from"./chunk-MD4CAJIO.js";import{a as se,b as pe,c as le}from"./chunk-GKIX3OD6.js";import{a as ce}from"./chunk-D2X6J77P.js";import"./chunk-SC5M74NM.js";import{A as He,B as Te,C as ve,M as Le,a as me,b as de,c as ue,d as Re,g as fe,h as ye,i as ke,j as xe,l as Pe,m as Ee,n as Ce,o as Se,p as ge,q as Ie,r as Ke,s as he,t as Ae,u as Oe,v as De,w as be,x as je,y as Ne,z as Ve}from"./chunk-MWJSYONH.js";import"./chunk-VORVR5BZ.js";import{m as _e}from"./chunk-TYVZXABI.js";import"./chunk-QHABFCRC.js";import{a as c,b as m,c as d,d as u,e as R}from"./chunk-5FVUBF7N.js";import{a as p}from"./chunk-6VIUXP4N.js";import{a as ee,g as oe,h as re,k as te}from"./chunk-22DSABP6.js";import{a as l}from"./chunk-7JBKOJB4.js";import"./chunk-PEJALHXK.js";import{a as F,b as U,h as q,i as W,j as z,k as Y,ka as J,l as X,ma as Q}from"./chunk-NUTHBBDZ.js";import{I as Z,J as $,a as h,b as A,c as O,d as D,e as j,g as N,h as V,i as H,j as T,k as v,l as _,m as L,n as w,o as M,u as B,v as G}from"./chunk-D4QGPMRW.js";import{a as b}from"./chunk-FUUTGGJS.js";import"./chunk-F67UH4FD.js";import{c as e,d as o,e as r,f as t,g as n,h as a,i,k as s}from"./chunk-QILEJIFU.js";export{De as AmbiguousReferenceRule,v as BooleanStatement,Fe as CANONICAL_FORM_VERSION,ro as CREDENTIAL_EXPIRY_SKEW_SECONDS,Qe as CREDENTIAL_HELPER_PROTOCOL_VERSION,oe as Carrier,Te as ClassDefinitionRule,Se as ClassHierarchyCycleRule,R as CredentialError,A as DefinedKanonak,ae as EdgeType,D as EmbeddedKanonak,Pe as EmbeddedKanonakTypeRule,L as EmbeddedStatement,mo as EntitlementDeniedError,uo as EntitlementProducer,ie as GraphBuilder,K as HttpKanonakDocumentRepository,E as INTEGRITY_PREFIX,Ge as ImportBook,Ee as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,f as KANONAK_USER_AGENT,h as Kanonak,pe as KanonakDocumentPositions,c as KanonakHttpError,te as KanonakObjectParser,Le as KanonakObjectValidator,l as KanonakParser,b as KanonakUri,ce as KanonakUriBuilder,J as KanonakVocabulary,w as ListStatement,ve as MarkdownLinkRule,M as MarkdownStatement,Ae as NamespaceImportCycleRule,fe as NamespacePrefixRule,ne as NodeType,T as NumberStatement,Je as OAuthDiscovery,je as ObjectPropertyValueValidationRule,ue as OntologyValidationError,me as OntologyValidationResult,Ue as PackageBuilder,po as ProducerRepository,Ne as PropertyDomainRule,ge as PropertyHierarchyCycleRule,Ve as PropertyKindRangeConsistencyRule,se as PropertyMetadata,be as PropertyRangeReferenceRule,Ie as PropertyRangeRequiredRule,ke as PropertyTypeSpecificityRule,P as PublisherConfigResolver,I as PublisherIndex,j as ReferenceKanonak,_ as ReferenceStatement,He as ReservedNameShadowRule,ye as ResourceNamingRule,F as ResourceResolver,Q as ResourceTypeClassifier,W as SHACL_PACKAGE,q as SHACL_PUBLISHER,Y as SH_NODE_SHAPE,X as SH_PROPERTY_SHAPE,z as SH_SHAPE,V as ScalarStatement,N as Statement,H as StringStatement,Ke as SubClassOfReferenceRule,he as SubPropertyOfReferenceRule,O as SubjectKanonak,xe as SubjectKanonakTypeRequiredRule,no as TOKEN_ENV,io as TokenCredentialProvider,U as TypeResolver,Oe as UnresolvedPredicateRule,Ce as UnresolvedReferenceRule,Re as ValidationContext,de as ValidationSeverity,lo as allowAllPolicy,_e as buildOntologyModel,we as canonicalForm,Me as canonicalHash,re as carrierOf,Ze as checkCredentialAnswer,$e as checkHelperAnswer,eo as checkHelperEraseAnswer,e as compareVersions,g as computeIntegrityAsync,Be as contentAddressedName,to as createCredentialedFetch,t as createVersion,d as describeResponse,so as findDerivation,r as formatVersion,k as getKanonakUserAgent,m as httpError,a as isCompatibleVersion,i as isMajorCompatible,x as kanonakFetch,Xe as narrowestScope,co as noopMeter,We as normalizeHost,C as parseLockFile,ze as parseScope,n as parseVersionString,le as parseWithPositions,oo as parseWwwAuthenticate,s as pickHighestDocument,G as referenceUris,u as retryAfterSecondsOf,qe as sanitizeName,Ye as scopeContains,S as serializeLockFile,y as setKanonakUserAgent,$ as subjectAddress,ao as tokenEnvKeyFor,B as typeReferenceUris,Z as valuesOf,o as versionsEqual,ee as walkDefinedKanonaks};
@@ -0,0 +1 @@
1
+ var i=class extends Error{constructor(e,n,s,a,m){super(e);this.url=n;this.status=s;this.problem=a;this.retryAfterSeconds=m;this.name="KanonakHttpError"}url;status;problem;retryAfterSeconds},o=300;async function y(t,r,e){let n=await u(e),s=c(e.headers.get("retry-after")),a=`Failed to fetch ${t}: ${r} ${await f(e)}`;return new i(a,r,e.status,n,s)}async function f(t){let r=await u(t),e=c(t.headers.get("retry-after")),n=r?p(r):await g(t),s=`(${t.status}${t.statusText?` ${t.statusText}`:""})`;return n&&(s+=`: ${n}`),e!==void 0&&(s+=` [the server asks to retry after ${e}s]`),s}function c(t){if(!t)return;let r=t.trim();if(/^\d+$/.test(r))return Number(r);let e=Date.parse(r);if(!Number.isNaN(e))return Math.max(0,Math.ceil((e-Date.now())/1e3))}function l(t){return(t.headers.get("content-type")??"").split(";")[0].trim().toLowerCase()}async function u(t){if(l(t)!=="application/problem+json")return;let r;try{r=await t.clone().json()}catch{return}if(!r||typeof r!="object")return;let e=r,n={};return typeof e.type=="string"&&(n.type=e.type),typeof e.title=="string"&&(n.title=e.title),typeof e.status=="number"&&(n.status=e.status),typeof e.detail=="string"&&(n.detail=e.detail),typeof e.instance=="string"&&(n.instance=e.instance),n}function p(t){return[t.title,t.detail].filter(r=>!!r&&r.trim()!=="").join(" \u2014 ")}async function g(t){let r=l(t);if(r!=="text/plain"&&r!=="application/json")return"";let e;try{e=await t.clone().text()}catch{return""}let n=e.replace(/\s+/g," ").trim();return n.length>o?`${n.slice(0,o)}\u2026`:n}var d=class extends Error{constructor(r){super(r),this.name="CredentialError"}};export{i as a,y as b,f as c,c as d,d as e};
@@ -0,0 +1 @@
1
+ import{i as F,o as P}from"./chunk-MD4CAJIO.js";import{a as A}from"./chunk-6VIUXP4N.js";import{a as f}from"./chunk-7JBKOJB4.js";import{c as K,g as I,j as R}from"./chunk-QILEJIFU.js";import*as m from"fs/promises";import*as i from"path";import{pathToFileURL as b}from"url";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=i.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=i.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=i.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;return R(r,t)});return s.length===0?null:(s.sort((a,r)=>{let u=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return K(l,u)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let u=o.split("/"),l=u[0],h=u[1].replace("@","@")+".kan.yml";n=i.join(this.rootPath,l,h)}else n=i.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=i.dirname(n);await m.mkdir(s,{recursive:!0});let a=this.parser.save(e);await m.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=i.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 m.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=i.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=i.join(this.rootPath,e);try{let s=await m.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await m.unlink(i.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=b(n).toString(),s;for(let[u,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(u)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??i.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 m.access(e),t=e}catch{let n=i.join(this.rootPath,e);try{await m.access(n),t=n}catch{return null}}try{return await m.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await m.access(e),t=e}catch{let n=i.join(this.rootPath,e);try{await m.access(n),t=n}catch{return null}}return b(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await m.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await m.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=i.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let u=s.metadata.namespace_.toString();this.documentCache.set(u,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(u,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 m.readdir(e,{withFileTypes:!0});for(let s of o){let a=i.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 S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),D=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 H}from"os";import{join as N}from"path";function d(){let c=process.env.KANONAK_PACKAGE_CACHE;return c||N(H(),".kanonak","packages")}var w=class c{static createComposite(e,t,n){let o=e??d(),s=t??".";return new D(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return c.createComposite(t,n,e)}};var k=class{repos;constructor(...e){this.repos=e}async firstAnswer(e,t,n){let o=[];for(let s of this.repos)try{let a=await e(s);if(t(a))return a}catch(a){o.push(a)}return x(o),n}async getHighestCompatibleVersionAsync(e,t){return this.firstAnswer(n=>n.getHighestCompatibleVersionAsync(e,t),n=>n!==null,null)}async getAllDocumentsAsync(){let e=[],t=new Set,n=[];for(let o of this.repos)try{for(let s of await o.getAllDocumentsAsync()){let a=s.metadata?.namespace_,r=a?a.version?`${a.publisher}/${a.package_}@${a.version.major}.${a.version.minor}.${a.version.patch}`:`${a.publisher}/${a.package_}`:void 0;if(r!==void 0){if(t.has(r))continue;t.add(r)}e.push(s)}}catch(s){n.push(s)}return x(n),e}async getDocumentAsync(e){return this.firstAnswer(t=>t.getDocumentAsync(e),t=>t!==null,null)}async getDocumentsByNamespaceAsync(e,t){return this.firstAnswer(n=>n.getDocumentsByNamespaceAsync(e,t),n=>n.length>0,[])}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){return this.firstAnswer(t=>t.getDocumentContentAsync(e),t=>!!t,null)}async getDocumentUriAsync(e){return this.firstAnswer(t=>t.getDocumentUriAsync(e),t=>!!t,null)}};function x(c){if(c.length===1)throw c[0];if(c.length>1)throw new Error(c.map(e=>e instanceof Error?e.message:String(e)).join("; "))}import{VersionOperator as B}from"@kanonak-protocol/types/document/models/enums";var v=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return F(this.lock,e,t)}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=I(n);if(o){let s={...t,versionOperator:B.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 $}from"fs";import{join as _}from"path";var j=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function C(c,e=[]){for(let t of $(c,{withFileTypes:!0}))t.isDirectory()?j.has(t.name)||C(_(c,t.name),e):t.name.endsWith(".kan.yml")&&e.push(_(c,t.name));return e}async function E(c,e=new f,t={}){let n=new A(e);for(let u of C(c))try{let l=e.parse(V(u,"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);if(t.offline)return new k(n,o);let s=new Map,a=t.httpCache??{getFromCache:(u,l,p)=>s.get(`${u}|${l}|${p}`)??null,onFetch:(u,l,p,h)=>{s.set(`${u}|${l}|${p}`,h)}},r=new P({getFromCache:a.getFromCache,onFetch:a.onFetch,...t.fetchFn?{fetchFn:t.fetchFn}:{}});return new k(n,o,r)}export{y as a,S as b,D as c,d,w as e,k as f,v as g,C as h,E as i};
@@ -1,2 +1,2 @@
1
- import{a as I,b as K,c as ee,e as T,j}from"./chunk-HKQTB65D.js";import{k as re}from"./chunk-22DSABP6.js";import{ma as _,pa as z}from"./chunk-NUTHBBDZ.js";import{c as G,o as te}from"./chunk-D4QGPMRW.js";var se=(i=>(i.Class="Class",i.DatatypeProperty="DatatypeProperty",i.ObjectProperty="ObjectProperty",i.AnnotationProperty="AnnotationProperty",i.Instance="Instance",i.Datatype="Datatype",i.Shape="Shape",i.Unknown="Unknown",i))(se||{}),ae=(i=>(i.InstanceOf="instanceOf",i.SubClassOf="subClassOf",i.Domain="domain",i.Range="range",i.ObjectRelationship="objectRelationship",i.SubPropertyOf="subPropertyOf",i.PropertyValue="propertyValue",i.EmbeddedLink="embeddedLink",i))(ae||{}),H=class{static async buildFromRepository(e,r){let s=await new re().parseKanonaks(e),o=await e.getAllDocumentsAsync(),c=[],p=[],i=new Set,h=new Set,b=new Map;for(let g of s){let a=g;if(a.name&&(_.isClassType(a)&&i.add(a.name),g instanceof G)){let d=z(s,g);(d==="ObjectProperty"||d==="Property")&&h.add(a.name)}}for(let g of o)for(let[a,d]of Object.entries(g.body))h.has(a)&&d?.range&&typeof d.range=="string"&&b.set(a,d.range);let w=new Map;for(let g of s){let a=g;a.name&&w.set(a.name,a)}for(let g of o){let a=g.metadata.namespace_,d=a?`${a.publisher}/${a.package_}`:"",u=a?.version?`${a.version.major}.${a.version.minor}.${a.version.patch}`:"",y=ne(g);for(let[f,l]of Object.entries(g.body)){if(!l||typeof l!="object")continue;let A=w.get(f),m="Unknown";if(A){let E=A,k=A instanceof G?z(s,A):void 0;_.isClassType(E)?m="Class":k==="ObjectProperty"?m="ObjectProperty":k==="DatatypeProperty"?m="DatatypeProperty":k==="AnnotationProperty"?m="AnnotationProperty":_.isDatatypeType(E)?m="Datatype":k==="Property"?m="ObjectProperty":_.isShapeType(E)?m="Shape":_.isInstanceOfKnownClass(E,i)&&(m="Instance")}let C=d&&u?`${d}/${f}@${u}`:f,R={};for(let[E,k]of Object.entries(l))E!=="type"&&(typeof k!="object"||k===null)&&(R[E]=k);c.push({id:C,label:l.label??f,type:m,namespace:d,properties:R}),oe(C,l,m,i,h,p,d,u,y,r),q(C,l,h,b,c,p,d,u,y),Ce(C,A,p)}}return{nodes:c,edges:p}}static buildFromDocument(e,r){let n=[],s=[],o=e.metadata.namespace_,c=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",p=o?`${o.publisher}/${o.package_}`:"",i=new Set,h=new Set,b=new Map,w=ne(e);for(let[d,u]of Object.entries(e.body)){let y=u?.type;y&&(be(y,w)&&i.add(d),Pe(y,w)&&(h.add(d),u.range&&typeof u.range=="string"&&b.set(d,u.range)))}for(let[d,u]of Object.entries(e.body)){if(!u||typeof u!="object")continue;let y=u.type,f=Ae(y,d,i,w),l=p&&c?`${p}/${d}@${c}`:d,A={};for(let[m,C]of Object.entries(u))m!=="type"&&(typeof C!="object"||C===null)&&(A[m]=C);n.push({id:l,label:u.label??d,type:f,namespace:p,properties:A}),oe(l,u,f,i,h,s,p,c,w,r),q(l,u,h,b,n,s,p,c,w)}let g=new Set(n.map(d=>d.id)),a=s.filter(d=>g.has(d.source)&&g.has(d.target));return{nodes:n,edges:a}}};function ne(t,e){let r=new Map;if(t.metadata?.imports)for(let[n,s]of Object.entries(t.metadata.imports))for(let o of s){let c=o.alias??o.packageName,p=o.version,i=`${p.major}.${p.minor}.${p.patch}`;r.set(c,{publisher:n,package_:o.packageName,version:i})}return r}var ie={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},ke=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function W(t,e){if(t.includes(".")){let r=t.indexOf("."),n=t.substring(0,r),s=t.substring(r+1),o=e.get(n);if(o)return`${o.publisher}/${o.package_}/${s}`}return null}function be(t,e){let r=W(t,e);return r?ie[r]==="Class":!1}function Pe(t,e){let r=W(t,e);return r?ke.has(r):!1}function Ae(t,e,r,n){if(!t||t==="Package")return"Unknown";let s=W(t,n);if(s){let c=ie[s];if(c)return c;let p=s.split("/").pop()?.split("@")[0]??"";return r.has(p)?"Instance":"Unknown"}let o=t.split(".").pop()??t;return r.has(o)?"Instance":"Unknown"}var ce=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function oe(t,e,r,n,s,o,c,p,i,h){let b=e.type,w=e.subClassOf;if(w){let f=Array.isArray(w)?w:[w];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subClassOf",label:"subClassOf"})}let g=e.subPropertyOf;if(g){let f=Array.isArray(g)?g:[g];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subPropertyOf",label:"subPropertyOf"})}let a=e.domain,d=e.range;if(h?.includePropertyEdges){let f=[[a,"domain","domain"],[d,"range","range"]];for(let[l,A,m]of f)if(l!=null)for(let C of Array.isArray(l)?l:[l])typeof C=="string"&&o.push({source:t,target:O(C,c,p,i),type:A,label:m})}if(r==="Instance"&&b){let f=b.split(".").pop()??b;o.push({source:t,target:O(f,c,p,i),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[f,l]of Object.entries(e)){if(ce.has(f)||!s.has(f))continue;let A=Array.isArray(l)?l:[l];for(let m of A)typeof m=="string"&&Ee(m)&&o.push({source:t,target:O(m,c,p,i),type:"propertyValue",label:f,propertyId:O(f,c,p,i)})}if((r==="ObjectProperty"||r==="DatatypeProperty"||a&&d)&&a&&d){let f=typeof a=="string"?a:null,l=typeof d=="string"?d:null;f&&l&&o.push({source:O(f,c,p,i),target:O(l,c,p,i),type:"objectRelationship",label:e.label??t.split("/").pop()??"",propertyId:t})}}function q(t,e,r,n,s,o,c,p,i){for(let[h,b]of Object.entries(e)){if(ce.has(h)||typeof b!="object"||b===null||Array.isArray(b))continue;let w=b,g=`${t}/${h}`,a=n.get(h),d=a?a.split(".").pop()??a:"Unknown",u={};for(let[f,l]of Object.entries(w))(typeof l!="object"||l===null)&&(u[f]=l);s.push({id:g,label:`${d} (embedded)`,type:"Instance",namespace:c,properties:u});let y=c&&p?`${c}/${h}@${p}`:h;o.push({source:t,target:g,type:"propertyValue",label:h,propertyId:r.has(h)?y:void 0}),a&&o.push({source:g,target:O(d,c,p,i),type:"instanceOf",label:"type (inferred)"}),q(g,w,r,n,s,o,c,p,i)}}function Ce(t,e,r){let n=e?.statement;if(Array.isArray(n))for(let s of n){if(!(s instanceof te))continue;let o=s.predicate?.subject?.name??"";for(let c of s.links){let p=c.target?.subject;if(!p)continue;let i=p.version,h=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"";r.push({source:t,target:`${p.publisher}/${p.package_}/${p.name}${h}`,type:"embeddedLink",label:o})}}}function Ee(t){return!(!t||t.includes(" ")||t.includes(`
1
+ import{e as j}from"./chunk-MD4CAJIO.js";import{a as I,b as K,c as ee,e as T}from"./chunk-5FVUBF7N.js";import{k as re}from"./chunk-22DSABP6.js";import{ma as _,pa as z}from"./chunk-NUTHBBDZ.js";import{c as G,o as te}from"./chunk-D4QGPMRW.js";var se=(i=>(i.Class="Class",i.DatatypeProperty="DatatypeProperty",i.ObjectProperty="ObjectProperty",i.AnnotationProperty="AnnotationProperty",i.Instance="Instance",i.Datatype="Datatype",i.Shape="Shape",i.Unknown="Unknown",i))(se||{}),ae=(i=>(i.InstanceOf="instanceOf",i.SubClassOf="subClassOf",i.Domain="domain",i.Range="range",i.ObjectRelationship="objectRelationship",i.SubPropertyOf="subPropertyOf",i.PropertyValue="propertyValue",i.EmbeddedLink="embeddedLink",i))(ae||{}),H=class{static async buildFromRepository(e,r){let s=await new re().parseKanonaks(e),o=await e.getAllDocumentsAsync(),c=[],p=[],i=new Set,h=new Set,b=new Map;for(let g of s){let a=g;if(a.name&&(_.isClassType(a)&&i.add(a.name),g instanceof G)){let d=z(s,g);(d==="ObjectProperty"||d==="Property")&&h.add(a.name)}}for(let g of o)for(let[a,d]of Object.entries(g.body))h.has(a)&&d?.range&&typeof d.range=="string"&&b.set(a,d.range);let w=new Map;for(let g of s){let a=g;a.name&&w.set(a.name,a)}for(let g of o){let a=g.metadata.namespace_,d=a?`${a.publisher}/${a.package_}`:"",u=a?.version?`${a.version.major}.${a.version.minor}.${a.version.patch}`:"",y=ne(g);for(let[f,l]of Object.entries(g.body)){if(!l||typeof l!="object")continue;let A=w.get(f),m="Unknown";if(A){let E=A,k=A instanceof G?z(s,A):void 0;_.isClassType(E)?m="Class":k==="ObjectProperty"?m="ObjectProperty":k==="DatatypeProperty"?m="DatatypeProperty":k==="AnnotationProperty"?m="AnnotationProperty":_.isDatatypeType(E)?m="Datatype":k==="Property"?m="ObjectProperty":_.isShapeType(E)?m="Shape":_.isInstanceOfKnownClass(E,i)&&(m="Instance")}let C=d&&u?`${d}/${f}@${u}`:f,R={};for(let[E,k]of Object.entries(l))E!=="type"&&(typeof k!="object"||k===null)&&(R[E]=k);c.push({id:C,label:l.label??f,type:m,namespace:d,properties:R}),oe(C,l,m,i,h,p,d,u,y,r),q(C,l,h,b,c,p,d,u,y),Ce(C,A,p)}}return{nodes:c,edges:p}}static buildFromDocument(e,r){let n=[],s=[],o=e.metadata.namespace_,c=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",p=o?`${o.publisher}/${o.package_}`:"",i=new Set,h=new Set,b=new Map,w=ne(e);for(let[d,u]of Object.entries(e.body)){let y=u?.type;y&&(be(y,w)&&i.add(d),Pe(y,w)&&(h.add(d),u.range&&typeof u.range=="string"&&b.set(d,u.range)))}for(let[d,u]of Object.entries(e.body)){if(!u||typeof u!="object")continue;let y=u.type,f=Ae(y,d,i,w),l=p&&c?`${p}/${d}@${c}`:d,A={};for(let[m,C]of Object.entries(u))m!=="type"&&(typeof C!="object"||C===null)&&(A[m]=C);n.push({id:l,label:u.label??d,type:f,namespace:p,properties:A}),oe(l,u,f,i,h,s,p,c,w,r),q(l,u,h,b,n,s,p,c,w)}let g=new Set(n.map(d=>d.id)),a=s.filter(d=>g.has(d.source)&&g.has(d.target));return{nodes:n,edges:a}}};function ne(t,e){let r=new Map;if(t.metadata?.imports)for(let[n,s]of Object.entries(t.metadata.imports))for(let o of s){let c=o.alias??o.packageName,p=o.version,i=`${p.major}.${p.minor}.${p.patch}`;r.set(c,{publisher:n,package_:o.packageName,version:i})}return r}var ie={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},ke=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function W(t,e){if(t.includes(".")){let r=t.indexOf("."),n=t.substring(0,r),s=t.substring(r+1),o=e.get(n);if(o)return`${o.publisher}/${o.package_}/${s}`}return null}function be(t,e){let r=W(t,e);return r?ie[r]==="Class":!1}function Pe(t,e){let r=W(t,e);return r?ke.has(r):!1}function Ae(t,e,r,n){if(!t||t==="Package")return"Unknown";let s=W(t,n);if(s){let c=ie[s];if(c)return c;let p=s.split("/").pop()?.split("@")[0]??"";return r.has(p)?"Instance":"Unknown"}let o=t.split(".").pop()??t;return r.has(o)?"Instance":"Unknown"}var ce=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function oe(t,e,r,n,s,o,c,p,i,h){let b=e.type,w=e.subClassOf;if(w){let f=Array.isArray(w)?w:[w];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subClassOf",label:"subClassOf"})}let g=e.subPropertyOf;if(g){let f=Array.isArray(g)?g:[g];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subPropertyOf",label:"subPropertyOf"})}let a=e.domain,d=e.range;if(h?.includePropertyEdges){let f=[[a,"domain","domain"],[d,"range","range"]];for(let[l,A,m]of f)if(l!=null)for(let C of Array.isArray(l)?l:[l])typeof C=="string"&&o.push({source:t,target:O(C,c,p,i),type:A,label:m})}if(r==="Instance"&&b){let f=b.split(".").pop()??b;o.push({source:t,target:O(f,c,p,i),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[f,l]of Object.entries(e)){if(ce.has(f)||!s.has(f))continue;let A=Array.isArray(l)?l:[l];for(let m of A)typeof m=="string"&&Ee(m)&&o.push({source:t,target:O(m,c,p,i),type:"propertyValue",label:f,propertyId:O(f,c,p,i)})}if((r==="ObjectProperty"||r==="DatatypeProperty"||a&&d)&&a&&d){let f=typeof a=="string"?a:null,l=typeof d=="string"?d:null;f&&l&&o.push({source:O(f,c,p,i),target:O(l,c,p,i),type:"objectRelationship",label:e.label??t.split("/").pop()??"",propertyId:t})}}function q(t,e,r,n,s,o,c,p,i){for(let[h,b]of Object.entries(e)){if(ce.has(h)||typeof b!="object"||b===null||Array.isArray(b))continue;let w=b,g=`${t}/${h}`,a=n.get(h),d=a?a.split(".").pop()??a:"Unknown",u={};for(let[f,l]of Object.entries(w))(typeof l!="object"||l===null)&&(u[f]=l);s.push({id:g,label:`${d} (embedded)`,type:"Instance",namespace:c,properties:u});let y=c&&p?`${c}/${h}@${p}`:h;o.push({source:t,target:g,type:"propertyValue",label:h,propertyId:r.has(h)?y:void 0}),a&&o.push({source:g,target:O(d,c,p,i),type:"instanceOf",label:"type (inferred)"}),q(g,w,r,n,s,o,c,p,i)}}function Ce(t,e,r){let n=e?.statement;if(Array.isArray(n))for(let s of n){if(!(s instanceof te))continue;let o=s.predicate?.subject?.name??"";for(let c of s.links){let p=c.target?.subject;if(!p)continue;let i=p.version,h=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"";r.push({source:t,target:`${p.publisher}/${p.package_}/${p.name}${h}`,type:"embeddedLink",label:o})}}}function Ee(t){return!(!t||t.includes(" ")||t.includes(`
2
2
  `)||t.startsWith("http://")||t.startsWith("https://")||/^\d{4}-\d{2}/.test(t)||/^\d+(\.\d+)?$/.test(t))}function O(t,e,r,n){if(t.includes("@")&&t.includes("/"))return t;if(t.includes(".")){let s=t.indexOf("."),o=t.substring(0,s),c=t.substring(s+1);if(n){let p=n.get(o);if(p)return`${p.publisher}/${p.package_}/${c}@${p.version}`}return e&&r?`${e}/${c}@${r}`:c}return e&&r?`${e}/${t}@${r}`:t}function M(t){let e=t.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}function v(t){let e;try{e=new URL(t)}catch{throw new Error(`credential scope '${t}' is not an absolute URL`)}if(e.protocol!=="https:")throw new Error(`credential scope '${t}' is not https`);if(e.username||e.password)throw new Error(`credential scope '${t}' carries userinfo`);if(e.search||t.includes("?"))throw new Error(`credential scope '${t}' has a query`);if(e.hash||t.includes("#"))throw new Error(`credential scope '${t}' has a fragment`);let r=e.pathname;return{origin:e.origin,prefix:r.endsWith("/")?r:`${r}/`}}function N(t,e){let r=typeof t=="string"?v(t):t,n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="https:"||n.origin!==r.origin)return!1;let s=n.pathname;return s.startsWith(r.prefix)||`${s}/`===r.prefix}function V(t,e){let r,n=-1;for(let s of t){let o=v(s.scope);N(o,e)&&o.prefix.length>n&&(r=s,n=o.prefix.length)}return r}var Oe="key_thumbprint",x=class{cache=new Map;wellKnownCache=new Map;metadataUrlCache=new Map;async protectedResourceMetadata(e){let r=new URL(e).href,n=this.wellKnownCache.get(r);return n||(n=this.fetchWellKnown(r),this.wellKnownCache.set(r,n)),n}async protectedResourceMetadataAt(e,r){let n=new URL(e).href,s=this.metadataUrlCache.get(n);s||(s=this.fetchMetadataAt(n),this.metadataUrlCache.set(n,s));let o=await s,c;try{c=N(v(o.resource),r)}catch(p){throw new Error(`Protected resource metadata at ${n} names an unusable resource '${o.resource}': ${p.message}`)}if(!c)throw new Error(`Protected resource metadata at ${n} names the resource '${o.resource}', which does not contain the requested ${r}. RFC 9728 \xA73.3 forbids using it.`);return o}async fetchWellKnown(e){let r=new URL(e),n=r.pathname==="/"?"":r.pathname,s=`${r.origin}/.well-known/oauth-protected-resource${n}`,o=await j(s,{redirect:"manual"});if(o.status===404||o.status===410||o.status>=300&&o.status<400)return null;if(!o.ok)throw await K("protected resource metadata",s,o);if(!pe(o.headers.get("content-type")))return null;let c=de(s,await o.text());if(!URL.canParse(c.resource)||new URL(c.resource).href!==e)throw new Error(`Protected resource metadata at ${s} names the resource '${c.resource}', not '${e}'. RFC 9728 \xA73.3 forbids using it.`);return c}async fetchMetadataAt(e){let r=await j(e,{redirect:"manual"});if(!r.ok)throw await K("protected resource metadata",e,r);if(!pe(r.headers.get("content-type")))throw new Error(`Protected resource metadata at ${e} is not a JSON document (${r.headers.get("content-type")??"no content type"})`);return de(e,await r.text())}async discover(e){let r=M(e);if(this.cache.has(r))return this.cache.get(r);let n=`https://${r}/.well-known/oauth-authorization-server`,s=await this.tryEndpoint(n);if(!s){let o=`https://${r}/.well-known/openid-configuration`;s=await this.tryEndpoint(o)}return this.cache.set(r,s),s}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(r=>r.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(r=>r.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let r;try{r=await fetch(e)}catch(s){let o=s instanceof Error?s.message:String(s);return o.includes("ENOTFOUND")||o.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${o})`),console.error(" If the server is behind a VPN, ensure you are connected.")):o.includes("CERT")||o.includes("SSL")||o.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${o})`),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: ${o}`),null}if(!r.ok)return r.status===404||(r.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):r.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${r.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let n;try{n=await r.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:$(n.issuer),authorizationEndpoint:$(n.authorization_endpoint),tokenEndpoint:$(n.token_endpoint),registrationEndpoint:$(n.registration_endpoint),revocationEndpoint:$(n.revocation_endpoint),scopesSupported:S(n.scopes_supported),responseTypesSupported:S(n.response_types_supported),grantTypesSupported:S(n.grant_types_supported),codeChallengeMethodsSupported:S(n.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:S(n.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:S(n.dpop_signing_alg_values_supported),enrollmentEndpoint:$(n.enrollment_endpoint),enrollmentIssuanceProtocols:S(n.enrollment_issuance_protocols),enrollmentKeyTypes:S(n.enrollment_key_types),enrollmentScopesSupported:S(n.enrollment_scopes_supported),enrollmentConsentBindingParam:$(n.enrollment_consent_binding_param),sessionEndpoint:$(n.session_endpoint),sessionEndpointAuthMethod:$(n.session_endpoint_auth_method)}}};function pe(t){let e=(t??"").split(";")[0].trim().toLowerCase();return e==="application/json"||e.endsWith("+json")}function de(t,e){let r;try{r=JSON.parse(e)}catch{throw new Error(`Protected resource metadata at ${t} is not valid JSON`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`Protected resource metadata at ${t} is not a JSON object`);let n=r;if(typeof n.resource!="string")throw new Error(`Protected resource metadata at ${t} has no "resource"`);let s=n.authorization_servers;if(s!==void 0&&!(Array.isArray(s)&&s.every(o=>typeof o=="string")))throw new Error(`Protected resource metadata at ${t} has an "authorization_servers" that is not a list of strings`);return{resource:n.resource,authorizationServers:s??[]}}function $(t){return typeof t=="string"?t:null}function S(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):null}var D=1,$e=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Se=/[\r\n\0]/;function P(t,e){return{ok:!1,problem:t,message:e}}function L(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function U(t,e,r){if(!L(e))return P("malformed","the answer is not a JSON object");if(e.status==="declined")return e.reason!==void 0&&typeof e.reason!="string"?P("reason",`a decline's "reason" must be a string`):{ok:!0,answer:e.reason===void 0?{status:"declined"}:{status:"declined",reason:e.reason}};if(e.status!=="credential")return P("status",`"status" must be "credential" or "declined", not ${JSON.stringify(e.status)}`);let n=e.headers;if(!L(n)||Object.keys(n).length===0)return P("headers",'a credential needs "headers": an object with at least one header');let s={};for(let[i,h]of Object.entries(n)){if(!$e.test(i))return P("headers",`header name ${JSON.stringify(i)} is not a valid field name`);if(typeof h!="string"||Se.test(h))return P("headers",`header '${i}' must be a string without CR, LF or NUL`);s[i]=h}if(typeof e.scope!="string")return P("scope",'a credential needs a "scope" string');let o;try{o=v(e.scope)}catch(i){return P("scope",i.message)}if(!N(o,t.resource))return P("scope-excludes-resource",`scope '${e.scope}' does not contain the requested resource ${t.resource}`);let c;if(e.expiresAt!==void 0){if(typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt))return P("expires-at",'"expiresAt" must be a number of Unix seconds');if(e.expiresAt<=r)return P("expired",`the credential expired at ${e.expiresAt} (now ${Math.floor(r)})`);c=e.expiresAt}let p={status:"credential",headers:s,scope:e.scope};return c!==void 0&&(p.expiresAt=c),{ok:!0,answer:p}}function Re(t,e,r){return L(e)?e.version!==D?P("version",`"version" must be ${D}, not ${JSON.stringify(e.version)}`):U(t,e,r):P("malformed","the answer is not a JSON object")}function Te(t){return L(t)?t.version!==D?P("version",`"version" must be ${D}, not ${JSON.stringify(t.version)}`):t.status!=="erased"?P("status",`"status" must be "erased", not ${JSON.stringify(t.status)}`):{ok:!0,answer:{status:"erased"}}:P("malformed","the answer is not a JSON object")}function B(t){let e=new J(t),r=[];for(e.skipListSeparators();!e.atEnd();){let n=e.token();if(!n)throw e.error("expected an auth-scheme");let s={scheme:n,params:{}};r.push(s);let o=e.skipSpaces();if(e.atEnd()||e.peek()===","){e.skipListSeparators();continue}if(!o)throw e.error(`expected a space after the auth-scheme '${n}'`);let c=e.tryParam();if(c)for(ue(s,c,e);e.skipOws(),!e.atEnd();){if(e.peek()!==",")throw e.error('expected "," between auth-params');if(e.skipListSeparators(),e.atEnd())break;let p=e.pos,i=e.tryParam();if(!i){e.pos=p;break}ue(s,i,e)}else{let p=e.token68();if(!p)throw e.error(`expected a token68 or auth-params after '${n}'`);if(s.token68=p,e.skipOws(),!e.atEnd()&&e.peek()!==",")throw e.error("unexpected text after token68")}e.skipListSeparators()}return r}function ue(t,[e,r],n){if(Object.prototype.hasOwnProperty.call(t.params,e))throw n.error(`auth-param '${e}' appears twice in the '${t.scheme}' challenge`);t.params[e]=r}var ve=/[!#$%&'*+\-.^_`|~0-9A-Za-z]/,xe=/[A-Za-z0-9\-._~+/]/,J=class{constructor(e){this.s=e}s;pos=0;atEnd(){return this.pos>=this.s.length}peek(){return this.s[this.pos]}error(e){return new Error(`Malformed WWW-Authenticate (${e} at offset ${this.pos}): ${this.s}`)}skipSpaces(){let e=this.pos;for(;!this.atEnd()&&(this.peek()===" "||this.peek()===" ");)this.pos++;return this.pos>e}skipOws(){this.skipSpaces()}skipListSeparators(){for(;;){if(this.skipOws(),this.peek()!==",")return;this.pos++}}token(){let e=this.pos;for(;!this.atEnd()&&ve.test(this.peek());)this.pos++;return this.s.slice(e,this.pos)}token68(){let e=this.pos;for(;!this.atEnd()&&xe.test(this.peek());)this.pos++;if(this.pos===e)return"";for(;!this.atEnd()&&this.peek()==="=";)this.pos++;return this.s.slice(e,this.pos)}tryParam(){let e=this.pos,r=this.token();if(!r)return null;if(this.skipOws(),this.peek()!=="=")return this.pos=e,null;this.pos++,this.skipOws();let n;if(this.peek()==='"')n=this.quotedString();else if(n=this.token(),!n)return this.pos=e,null;return[r.toLowerCase(),n]}quotedString(){this.pos++;let e="";for(;;){if(this.atEnd())throw this.error("unterminated quoted-string");let r=this.s[this.pos++];if(r==='"')return e;if(r==="\\"){if(this.atEnd())throw this.error("unterminated quoted-pair");e+=this.s[this.pos++]}else e+=r}}};var ye=30;function _e(t,e={}){let r=e.discovery??new x,n=e.nowSeconds??(()=>Date.now()/1e3),s=[],o=new WeakSet,c=new Map,p=new Map,i=a=>{let d=n();return s=s.filter(u=>u.expiresAt===void 0||u.expiresAt-ye>d),V(s,a)},h=(a,d)=>{let u=(p.get(a)??Promise.resolve()).then(d);return p.set(a,u.then(()=>{},()=>{})),u},b=a=>{let d=c.get(a);return d||(d=r.protectedResourceMetadata(a).then(u=>u!==null,u=>{if(u instanceof I&&(u.status===401||u.status===403))return!0;throw new T(`Could not learn whether ${a} requires a credential: ${me(u)}`)}),c.set(a,d)),d},w=async(a,d)=>{let u=U(d,await le(()=>a.get(d),d.resource),n());if(!u.ok)throw new T(`The credential provider answered for ${d.resource} outside the protocol (${u.problem}): ${u.message}`);let y=u.answer;if(y.status==="declined")return y.reason===void 0?{}:{declined:y.reason};let f={headers:y.headers,scope:y.scope};return y.expiresAt!==void 0&&(f.expiresAt=y.expiresAt),s=s.filter(l=>l.scope!==f.scope),s.push(f),f},g=(a,d,u)=>j(a,{method:d,redirect:"manual",headers:u?.headers??{}});return async(a,d,u="GET")=>{let y=new URL(a).origin,f=i(a);if(!f&&t&&await b(y)){let k=await h(y,async()=>i(a)??w(t,{resource:a,method:u}));fe(k)&&(f=k)}let l=await g(a,u,f);if(l.status!==401&&l.status!==403)return l;let A=ge(l,a),m=l.status===401;if(!m&&!he(A))return l;if(c.set(y,Promise.resolve(!0)),!t)throw await Y(`${a} requires a credential, and no credential provider is configured`,l);let C={resource:a,method:u,challenges:A},R=await h(y,async()=>{let k=i(a);if(k&&k!==f)return k;if(m&&f&&!o.has(f)){o.add(f);let Q=f;s=s.filter(we=>we!==Q),await le(()=>t.erase({...C,scope:Q.scope}),a)}return w(t,C)});if(!fe(R)){let k=R.declined?`: ${R.declined}`:"";throw await Y(`${a} requires a credential, and the credential provider declined${k}`,l)}let E=await g(a,u,R);if(E.status===401||E.status===403&&he(ge(E,a)))throw await Y(`${a} rejected the credential for ${R.scope} after asking the provider again`,E);return E}}async function le(t,e){try{return await t()}catch(r){throw r instanceof T?r:new T(`The credential provider failed for ${e}: ${me(r)}`)}}function me(t){return t instanceof Error?t.message:String(t)}function fe(t){return"scope"in t}function he(t){return t.some(e=>e.params.error==="insufficient_scope")}function ge(t,e){let r=t.headers.get("www-authenticate");if(!r)return[];try{return B(r)}catch(n){throw new T(`${e} answered ${t.status} with a challenge that cannot be read: ${n.message}`)}}async function Y(t,e){return new T(`${t}. The server answered ${await ee(e)}`)}var F="KANONAK_TOKEN";function Ne(){return typeof process<"u"&&process.env?process.env:{}}function Z(t){return`${F}_${M(t).toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}var X=class{tokens;env;discovery;constructor(e={}){this.tokens=e.tokens??{},this.env=e.env??Ne(),this.discovery=e.discovery??new x}async get(e){let r=await this.metadataFor(e);if("declined"in r)return{status:"declined",reason:r.declined};let n=r.metadata;if(n.authorizationServers.length===0)return{status:"declined",reason:`the protected-resource metadata for ${n.resource} names no authorization server`};let s=n.authorizationServers.map(o=>new URL(o).host);for(let o of s){let c=this.tokens[o]??this.env[Z(o)]??this.env[F];if(c)return{status:"credential",headers:{Authorization:`Bearer ${c}`},scope:n.resource}}return{status:"declined",reason:`no token is configured for ${s.join(" or ")}: set ${s.map(Z).join(" or ")}, or ${F}`}}async erase(){}async metadataFor(e){let r=e.challenges?.find(o=>o.params.resource_metadata!==void 0)?.params.resource_metadata;if(r!==void 0)return{metadata:await this.discovery.protectedResourceMetadataAt(r,e.resource)};let n=new URL(e.resource).origin,s;try{s=await this.discovery.protectedResourceMetadata(n)}catch(o){if(o instanceof I&&(o.status===401||o.status===403))return{declined:`${n} requires a credential even for its protected-resource metadata, and its challenge names no resource_metadata`};throw o}return s?{metadata:s}:{declined:`${n} publishes no RFC 9728 protected-resource metadata naming its authorization server, so no token is presented to it`}}};export{se as a,ae as b,H as c,M as d,v as e,N as f,V as g,Oe as h,x as i,D as j,U as k,Re as l,Te as m,B as n,ye as o,_e as p,F as q,Z as r,X as s};
@@ -0,0 +1,2 @@
1
+ import{a as k}from"./chunk-SC5M74NM.js";import{b as l,d as L,e as d}from"./chunk-5FVUBF7N.js";import{a as R}from"./chunk-7JBKOJB4.js";import{e as m,g as P,j as C}from"./chunk-QILEJIFU.js";var K="@kanonak-protocol/sdk (+https://kanonak.org)",v=K;function W(o){v=o}function q(){return v}function f(o){let e;try{e=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(e.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${e.href} (only https:// is supported).`)}var I=new Set([429,502,503,504]),b=4,T=500,x=2e4;function g(o,e){f(o);let t=new Headers(e?.headers);return t.has("User-Agent")||t.set("User-Agent",v),H(o,{...e,headers:t})}var y=b;function G(o){y=Math.max(0,o)}async function H(o,e){let t;for(let r=0;r<=y;r++){let n;try{n=await fetch(o,e)}catch(i){if(t=i,r>=y)throw i;await E(A(r,void 0));continue}if(!I.has(n.status)||r>=y)return n;let s=L(n.headers.get("retry-after"));if(s!==void 0&&s*1e3>x)return n;await E(A(r,s))}throw t??new Error("kanonakFetch: exhausted retries")}function A(o,e){if(e!==void 0)return e*1e3;let t=Math.min(x,T*2**o);return Math.floor(t/2+Math.random()*(t/2))}function E(o){return new Promise(e=>setTimeout(e,o))}var M="https://{publisher}/{package}/{version}.kan.yml",$={version:1};function Q(){return{version:1}}var w=class{constructor(e){this.fetchFn=e}fetchFn;cache=new Map;getConfig(e){let t=this.cache.get(e);return t||(t=this.fetchConfig(e),this.cache.set(e,t),t.catch(()=>{this.cache.get(e)===t&&this.cache.delete(e)})),t}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,r;try{r=await(this.fetchFn?this.fetchFn(t,e):g(t))}catch(i){if(i instanceof d)throw i;return $}if(r.status===404)return $;if(!r.ok)throw await l("publisher config",t,r);let n=await r.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let s={version:n.version};return typeof n.package_url_template=="string"&&(O(t,"package_url_template",n.package_url_template),s.package_url_template=n.package_url_template),Array.isArray(n.featured_packages)&&n.featured_packages.every(i=>typeof i=="string")&&(s.featured_packages=n.featured_packages),s}resolvePackageUrl(e,t,r,n){let s=n.package_url_template??M,i=S(s,{publisher:e,package:t,version:r});return f(i),i}};function O(o,e,t){if(!t.startsWith("https://"))throw new Error(`Invalid publisher config at ${o}: ${e} must be an absolute https:// URL template (got "${t}").`)}function S(o,e){let t=o;for(let[n,s]of Object.entries(e))t=t.replaceAll(`{${n}}`,s);let r=t.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${o}`);return t}import U from"js-yaml";function te(o,e,t){return o.packages[`${e}/${t}`]?.version}var j=`# This file is generated by Kanonak CLI. Do not edit manually.
2
+ `,B="sha256:";function _(o){let e=U.load(o);return!e||typeof e!="object"||e.version!=="1"?null:{version:"1",lastUpdated:e.lastUpdated??"",packages:e.packages??{}}}function ne(o){let e={};for(let r of Object.keys(o.packages).sort())e[r]=o.packages[r];let t=U.dump({...o,packages:e},{lineWidth:-1,sortKeys:!1,quotingType:'"'});return j+t}async function re(o){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)),t=Array.from(new Uint8Array(e),r=>r.toString(16).padStart(2,"0")).join("");return`${B}${t}`}var p=class{configResolver;fetchFn;lockCache=new Map;packageLockCache=new Map;constructor(e){this.configResolver=e?.configResolver??new w(e?.fetchFn),this.fetchFn=e?.fetchFn}getConfig(e){return this.configResolver.getConfig(e)}async getPackageUrl(e,t,r){let n=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,n)}getLock(e){let t=this.lockCache.get(e);return t||(t=this.fetchLock(e),this.lockCache.set(e,t),t.catch(()=>{this.lockCache.get(e)===t&&this.lockCache.delete(e)})),t}async getPackageLockEntry(e,t){let r=`${e}/${t}`,n=this.packageLockCache.get(r);return n||(n=this.fetchLock(e,t),this.packageLockCache.set(r,n),n.catch(()=>{this.packageLockCache.get(r)===n&&this.packageLockCache.delete(r)})),(await n)?.packages[r]??null}async fetchLock(e,t){let r=t?`https://${e}/${t}/kanonak.lock`:`https://${e}/kanonak.lock`,n;try{n=this.fetchFn?await this.fetchFn(r,e):await g(r)}catch(s){if(s instanceof d)throw s;return null}if(n.status===404)return null;if(!n.ok)throw await l("publisher lock",r,n);return _(await n.text())}};import{VersionOperator as F}from"@kanonak-protocol/types/document/models/enums";function N(o,e){let t=P(o);return t?C(t,e):!1}var D=class{parser=new R;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new p({fetchFn:e.fetchFn}):new p}async getHighestCompatibleVersionAsync(e,t){if(t.versionOperator===F.Exact){let s=await this.fromMemoOrCache(e,t.packageName,m(t.version));if(s)return s}let n=(await this.publisherIndex.getLock(e))?.packages[`${e}/${t.packageName}`]??await this.publisherIndex.getPackageLockEntry(e,t.packageName)??void 0;return n&&N(n.version,t)?this.fetchPinned(e,t.packageName,n):n&&t.versionOperator!==F.Exact?null:this.resolveByDirectFetch(e,t)}async fetchPinned(e,t,r){let n=r.version,s=`${e}/${t}@${n}`,i=await this.fromMemoOrCache(e,t,n);if(i)return i;let a=r.resolved,c=this.fetchFn?await this.fetchFn(a,e):await g(a);if(!c.ok)throw await l("Kanonak package",a,c);let h=await c.text(),u=this.parser.parse(h);return k(u,e,t,n),this.onFetch&&await this.onFetch(e,t,n,h),this.documents.set(s,u),this.contentCache.set(s,h),u}async fromMemoOrCache(e,t,r){let n=`${e}/${t}@${r}`,s=this.documents.get(n);if(s)return s;if(!this.getFromCache)return null;let i=await this.getFromCache(e,t,r);if(i==null)return null;let a;try{a=this.parser.parse(i),k(a,e,t,r)}catch(c){throw new Error(`Cached content for ${n} is not a usable copy of that package \u2014 refusing to fall through to a fetch that would hide it. ${c.message}`,{cause:c})}return this.documents.set(n,a),this.contentCache.set(n,i),a}async resolveByDirectFetch(e,t){let r=t.packageName,s=t.versionOperator===F.Exact?await this.publisherIndex.getPackageUrl(e,r,m(t.version)):`https://${e}/${r}.kan.yml`,i=await this.fetchFollowing(s,e);if(!i)return null;let a=this.parser.parse(i.content),c=a.metadata.namespace_;if(!c||!c.version)throw new Error(`Producer origin returned a package with no namespace/version for ${e}/${r}`);let h=m(c.version);k(a,e,r,h);let u=`${e}/${r}@${h}`;return this.onFetch&&await this.onFetch(e,r,h,i.content),this.documents.set(u,a),this.contentCache.set(u,i.content),a}async fetchFollowing(e,t,r=4){let n=e;for(let s=0;s<r;s++){f(n);let i=this.fetchFn?await this.fetchFn(n,t):await g(n,{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 ${n}`);n=new URL(a,n).toString();continue}if(i.status===404)return null;if(!i.ok)throw await l("Kanonak package",n,i);return{url:n,content:await i.text()}}throw new Error(`Too many redirects resolving ${e}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(r=>{let n=r.metadata.namespace_;return n&&n.publisher===e&&n.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,r,n,s]=t;return this.publisherIndex.getPackageUrl(r,n,s)}};export{K as a,W as b,q as c,f as d,g as e,G as f,Q as g,w as h,te as i,B as j,_ as k,ne as l,re as m,p as n,D as o};
@@ -0,0 +1,68 @@
1
+ import{a as Ut}from"./chunk-VORVR5BZ.js";import{c as At,g as Nt,h as ct,i as pt,j as Tt,k as xt,l as _t,s as lt,t as Lt,u as Mt}from"./chunk-TYVZXABI.js";import{a as Et,e as vt}from"./chunk-5FVUBF7N.js";import{a as F,f as z,i as Pt,k as O}from"./chunk-22DSABP6.js";import{a as Vt}from"./chunk-7JBKOJB4.js";import{$ as ne,_ as st,aa as jt,b as St,ba as Ot,fa as nt,ga as Ct,ma as j,na as x,oa as W,pa as q,qa as Q,ta as wt,ua as Y,va as pe}from"./chunk-NUTHBBDZ.js";import{A as It,C as H,D as ee,E as te,F as E,G as C,H as T,L as B,c as k,d as V,e as N,f as tt,l as ce,m as J,n as L,o as ot,r as R,s as Z,u as $t,v as M,w as oe,x as A,z as b}from"./chunk-D4QGPMRW.js";import{a as Dt}from"./chunk-FUUTGGJS.js";import{b as se,c as Kt}from"./chunk-F67UH4FD.js";import{e as U}from"./chunk-QILEJIFU.js";var le=class{isValid=!1;errors=[];warnings=[];infos=[];get totalIssues(){return this.errors.length+this.warnings.length+this.infos.length}get allDiagnostics(){return[...this.errors,...this.warnings,...this.infos]}};var K=(o=>(o.Info="Info",o.Warning="Warning",o.Error="Error",o))(K||{});var d=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var mt=class p{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new p;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var re=class{constructor(e){this.underlying=e;this.repository=new ut(e)}underlying;repository;parsePromise=null;getKanonaks(){return this.parseOnce().then(e=>e.merged)}getAuthoredKanonaks(){return this.parseOnce().then(e=>e.authored)}parseOnce(){return this.parsePromise||(this.parsePromise=(async()=>{let e=await this.underlying.getAllDocumentsAsync();await Ut(e,this.repository);let t={};return{merged:await new O().parseKanonaks(this.underlying,t),authored:t.authored??[]}})()),this.parsePromise}},ut=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){let o=`${e}/${t}`,n=this.byNamespaceCache.get(o);return n||(n=this.inner.getDocumentsByNamespaceAsync(e,t),this.byNamespaceCache.set(o,n),n)}getHighestCompatibleVersionAsync(e,t){let o=t.version,n=o?`${o.major}.${o.minor}.${o.patch}`:"",r=`${e}/${t.packageName}@${t.versionOperator}:${n}`,a=this.highestVersionCache.get(r);return a||(a=this.inner.getHighestCompatibleVersionAsync(e,t),this.highestVersionCache.set(r,a),a)}saveDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}deleteDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}clearNamespaceAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};async function $(p,e,t){return t?t.getKanonaks():new O().parseKanonaks(new me(p,e))}async function w(p,e,t){let o=await $(p,e,t),n=rt(p);return n?o.filter(r=>r instanceof k&&r.namespace===n):[]}async function ue(p,e,t){let o=rt(p);if(!o)return[];let n;if(t)n=await t.getAuthoredKanonaks();else{let r={};await new O().parseKanonaks(new me(p,e),r),n=r.authored??[]}return n.filter(r=>r instanceof k&&r.sourceDoc===o)}function rt(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var me=class{constructor(e,t){this.document=e;this.broader=t}document;broader;async getAllDocumentsAsync(){let e=this.document.metadata.namespace_?.toString(),t=(await this.broader.getAllDocumentsAsync()).filter(o=>o.metadata.namespace_?.toString()!==e);return[this.document,...t]}getDocumentAsync(e){return this.broader.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.broader.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.broader.getHighestCompatibleVersionAsync(e,t)}getAllDocumentReferencesAsync(){return this.broader.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.broader.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.broader.getDocumentUriAsync(e)}saveDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}deleteDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}clearNamespaceAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}};var de=class{constructor(e={}){this.options=e}options;ruleName="LinkTarget";async validateAsync(e,t,o){let n=[],r=new Map;for(let[c,l]of Object.entries(e.metadata?.imports??{}))for(let m of l)se(m)&&r.set(`${c}/${m.packageName}`,{publisher:c,import_:m});if(r.size===0)return n;let a=new Map,i=(c,l,m)=>{let u=`${c.publisher}/${c.package_}`;if(!r.has(u))return;let f=a.get(u)??[];f.push({uri:c,where:l,predicate:m}),a.set(u,f)},s=await w(e,t,o);F(s,({kanonak:c,path:l})=>{for(let m of c.statement){let u=m.predicate?.subject?.name??"(unknown)";if(m instanceof ce)i(m.object.subject,l,u);else if(m instanceof L)for(let f of m.object)f instanceof N&&i(f.subject,l,u);else if(m instanceof ot)for(let f of m.links)f.target&&i(f.target.subject,l,u)}});for(let[c,l]of a){let{publisher:m,import_:u}=r.get(c),f=null,h;try{f=await t.getHighestCompatibleVersionAsync(m,u)}catch(y){h=y instanceof Error?y.message:String(y)}if(!f){let y=l[0],g=`${l.length} reference${l.length===1?"":"s"}, first at '${y.where}.${y.predicate}'`;this.options.offline?n.push(this.finding("Warning",y.where,y.predicate,c,`Link target package '${c}' could not be resolved offline (${g}); the link is UNVERIFIED, not known to be broken.`,"Run without --offline to verify the link over HTTP, or add the package to the workspace or cache.")):n.push(this.finding("Error",y.where,y.predicate,c,`Link target package '${c}' could not be resolved${h?` (${h})`:""} \u2014 ${g}.`,"Check the publisher and package name of the link import; a link must dereference even though it is not a dependency. Use --offline to validate without the network (the link is then reported as unverified)."));continue}for(let{uri:y,where:g,predicate:D}of l)Object.prototype.hasOwnProperty.call(f.body,y.name)||n.push(this.finding("Error",g,D,`${c}/${y.name}`,`Link to '${y.name}' in '${D}' at '${g}' does not dereference: package '${c}' (resolved to ${f.metadata.namespace_?.toString()??c}) defines no resource named '${y.name}'.`,`Check for a typo, or a resource renamed or removed in '${c}'; a link addresses a resource by name in its package's current version unless the import is pinned with '='.`))}return n}finding(e,t,o,n,r,a){let i=new d;return i.ruleType=this.ruleName,i.severity=e,i.entityName=t,i.propertyName=o,i.actualValue=n,i.expectedValue="A link that dereferences to a resource its target package defines",i.message=r,i.suggestion=a,i}};var fe=class p{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):[A-Za-z_][A-Za-z0-9_.-]*$/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[o,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(o,n,t);return t}validateEntity(e,t,o){for(let[n,r]of Object.entries(t)){let a=r?.toString()??"";if(a&&p.NAMESPACE_PREFIX_PATTERN.test(a)){let i=this.getSuggestionForPrefixedValue(a),s=e.split(".")[0],c=new d;c.ruleType=this.ruleName,c.severity="Error",c.entityName=s,c.propertyName=e,c.actualValue=n,c.expectedValue=i,c.message=`Invalid namespace prefix '${a}'. Use '${i}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",o.push(c)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validateEntity(`${e}.${n}`,r,o)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let o=e.indexOf(":");return o>=0?e.substring(o+1):e}};var ye=class p{static RESERVED_WORDS=new Set(["imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],o=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,r]of Object.entries(e.body)){let a=p.VALID_AUGMENTATION_PATTERN.test(n);if(!a&&!o&&p.RESERVED_WORDS.has(n.toLowerCase())){let i=new d;i.ruleType=this.ruleName,i.severity="Error",i.entityName=n,i.message=`Entity name '${n}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(i);continue}if(!a&&!p.VALID_NAME_PATTERN.test(n)){let i;/^\d/.test(n)?i="Entity names must start with a letter, not a number.":n.includes(" ")?i="Entity names cannot contain spaces. Use camelCase or underscores instead.":i="Entity names must start with a letter and contain only letters, numbers, and underscores.";let s=new d;s.ruleType=this.ruleName,s.severity="Error",s.entityName=n,s.message=`Invalid entity name '${n}'. ${i}`,s.suggestion=i,t.push(s)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(n,r,t)}return t}validatePropertyNames(e,t,o){for(let n of Object.keys(t))if(!p.VALID_PROPERTIES.has(n)&&!p.VALID_PROPERTY_NAME_PATTERN.test(n)){let r=new d;r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,r.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,r.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",o.push(r)}}};var he=class p{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let o=this.isPropertyDefinedAsClass(e);for(let[n,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r,i=a.type;if(i){let s=[];if(Array.isArray(i))for(let c of i){let l=c?.toString();l&&l==="Property"&&!o&&s.push(l)}else{let c=i?.toString();c&&c==="Property"&&!o&&s.push(c)}for(let c of s){let l=this.getPropertyValue(a,"range"),m=this.determinePropertyType(l),u=new d;u.ruleType=this.ruleName,u.severity="Error",u.entityName=n,u.propertyName="type",u.actualValue=c,u.expectedValue=m,u.message=`Invalid property type '${c}'. Use '${m}' instead.`,u.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(u)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":p.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let o=e[t];return o?o.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let r=n.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var ke=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[o,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||o.includes("."))continue;let r=n,a="type"in r,i=r.type?.toString().trim();if(!a||!i){let s=new d;s.ruleType=this.ruleName,s.severity="Error",s.entityName=o,s.propertyName="type",s.message=`Subject Kanonak '${o}' must have a 'type' property.`,s.suggestion=`Add a type statement like:
2
+ type: Scene
3
+
4
+ Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,s.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(s)}}return t}};var uo=new Set(["EphemeralPackage"]),ge=class{get ruleName(){return"PackageHeader"}validate(e){let t=e.metadata;if(!t.type_)return[];let o=[],n=this.packageKey(e,t.type_);return t.namespace_?(!uo.has(t.type_)&&!t.namespace_.version&&o.push(this.error(n,"version",`Package resource '${n}' requires a 'version' property \u2014 packages are addressed by name@version.`,`Add a version, e.g.:
5
+ version: 1.0.0`)),o):(o.push(this.error(n,"publisher",`Package resource '${n}' requires a 'publisher' property.`,`Add a publisher, e.g.:
6
+ publisher: example.org`)),o)}packageKey(e,t){for(let[o,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type===t)return o;return t}error(e,t,o,n){let r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.message=o,r.suggestion=n,r}};var fo={publisher:"kanonak.org",package_:"core-rdf",name:"type"},yo={publisher:"kanonak.org",package_:"core-rdf",name:"range"},ho={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},ko={publisher:"kanonak.org",package_:"core-rdf",name:"Class"},Re=class{ruleName="EmbeddedKanonakType";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await ue(e,t,o);for(let i of a)i instanceof k&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof J){let a=r.predicate?.subject,i=`${o}.${a?.name??"<embedded>"}`;this.check(e,a,r.object,o,i,n),this.walk(e,r.object,i,n)}else if(r instanceof L){let a=r.predicate?.subject,i=0;for(let s of r.object){if(s instanceof V){let c=`${o}.${a?.name??"<embedded>"}[${i}]`;this.check(e,a,s,o,c,n),this.walk(e,s,c,n)}i++}}}check(e,t,o,n,r,a){if(!t)return;let i=E(o,fo);if(!i)return;let s=b(e,t);if(!s)return;let c=E(s,yo);if(c&&!(Z(c,ho)||Z(c,ko))){if(R(i)===R(c)){a.push(this.redundant(n,r,i,c));return}W(e,i).some(l=>R(l)===R(c))||a.push(this.notSubclass(n,r,i,c))}}redundant(e,t,o,n){let r=new d;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' declares 'type: ${o.name}', which equals the parent property's range '${n.name}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,r.suggestion=`Remove the 'type: ${o.name}' line, or keep it if explicitness is preferred over concision.`,r}notSubclass(e,t,o,n){let r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' has 'type: ${o.name}', which is not a subclass of the parent property's range '${n.name}'.`,r.suggestion=`Either remove the 'type: ${o.name}' line (so the type is inferred from the property's range '${n.name}'), or add 'subClassOf: ${n.name}' to the '${o.name}' class definition so the relationship holds.`,r}};import{VersionOperator as at}from"@kanonak-protocol/types/document/models/enums";var be=class{ruleName="ImportExistence";async validateAsync(e,t){let o=[];if(!e.metadata?.imports)return o;for(let[n,r]of Object.entries(e.metadata.imports))for(let a of r){if(se(a))continue;let i;try{i=await t.getHighestCompatibleVersionAsync(n,a)}catch(s){o.push(this.unresolvable(n,a,s));continue}if(!i){let s=await this.determineImportErrorAsync(t,n,a),c=new d;c.ruleType=this.ruleName,c.severity="Error",c.message=s.message,c.suggestion=s.suggestion,c.entityName=`Import: ${n}/${a.packageName}`,c.actualValue=a.toString(),c.expectedValue=s.expectedValue,o.push(c)}}return o}unresolvable(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.message=`Import '${e}/${t.toString()}' could not be resolved: ${o instanceof Error?o.message:String(o)}`,n.suggestion=this.suggestionFor(o),n.entityName=`Import: ${e}/${t.packageName}`,n.actualValue=t.toString(),n.expectedValue="A resolvable package",n}suggestionFor(e){return e instanceof vt?"The publisher requires a credential. Configure a credential helper or a token for it; the message says what the provider or the server answered.":e instanceof Et?e.status===429||e.retryAfterSeconds!==void 0?`The publisher is limiting requests${e.retryAfterSeconds!==void 0?`; retry after ${e.retryAfterSeconds}s`:""}.`:`The publisher answered HTTP ${e.status}; the message carries its explanation.`:"Check the network and the publisher name, or validate with --offline to use only the workspace and cache."}async determineImportErrorAsync(e,t,o){let n=await e.getDocumentsByNamespaceAsync(t,o.packageName);if(n.length===0){let s=(await e.getAllDocumentsAsync()).filter(u=>u.metadata.namespace_?.publisher===t).map(u=>u.metadata.namespace_.package_).filter((u,f,h)=>h.indexOf(u)===f),c=this.findSimilarPackages(o.packageName,s),l=`Import '${t}/${o.package_}' not found - package does not exist`,m=c.length>0?`Did you mean: ${c.slice(0,3).join(", ")}?`:s.length>0?`Packages from ${t} known to this validation (workspace, cache, fetched): ${s.slice(0,5).join(", ")}`:`No packages from '${t}' are known to this validation. Verify the publisher name is correct.`;return{message:l,suggestion:m,expectedValue:"Existing package"}}let a=n.filter(s=>s.metadata.namespace_?.version).map(s=>s.metadata.namespace_.version.toString()).sort().join(", "),i=this.getAcceptableVersionRange(o);return{message:`Import '${t}/${o.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${a}. Required: ${i}`,expectedValue:i}}getAcceptableVersionRange(e){switch(e.versionOperator){case at.Exact:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case at.Compatible:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case at.Major:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case at.Any:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let o=t.filter(a=>a.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(a.toLowerCase()));if(o.length>0)return o.sort((a,i)=>a.length-i.length);let n=t.map(a=>({package:a,distance:this.levenshteinDistance(e.toLowerCase(),a.toLowerCase())})).sort((a,i)=>a.distance-i.distance),r=Math.max(3,Math.floor(e.length*.4));return n.filter(a=>a.distance<=r).map(a=>a.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let o=e.length,n=t.length,r=Array(o+1).fill(null).map(()=>Array(n+1).fill(0));for(let a=0;a<=o;a++)r[a][0]=a;for(let a=0;a<=n;a++)r[0][a]=a;for(let a=1;a<=o;a++)for(let i=1;i<=n;i++){let s=e[a-1]===t[i-1]?0:1;r[a][i]=Math.min(Math.min(r[a-1][i]+1,r[a][i-1]+1),r[a-1][i-1]+s)}return r[o][n]}};var go="kanonak.org",Ro="core-rdf",bo=new Set(["type","subClassOf","subPropertyOf","domain","range"].map(p=>R({publisher:go,package_:Ro,name:p}))),Ke=class{ruleName="UnresolvedReference";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await w(e,t,o),i=Kt(e),s=c=>i.has(`${c.subject.publisher}/${c.subject.package_}`);return F(a,({kanonak:c,path:l})=>{for(let m of c.statement){let u=Ko(m);if(!(!u||bo.has(R(u)))){if(m instanceof ce)s(m.object)||this.check(r,l,u,m.object,n);else if(m instanceof L)for(let f of m.object)f instanceof N&&!s(f)&&this.check(r,l,u,f,n)}}}),n}check(e,t,o,n,r){b(e,n.subject)||r.push(this.unresolvedError(t,o.name,n.subject))}unresolvedError(e,t,o){let n=`${o.publisher}/${o.package_}/${o.name}`,r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=n,r.expectedValue="A reference that resolves to a defined or imported resource",r.message=`Reference to '${o.name}' in '${t}' could not be resolved`,r.suggestion=`The entity '${n}' is not defined in this namespace or any imported namespace.
7
+ \u2022 Import the package that defines it, or check for a typo in '${o.name}'
8
+ \u2022 If it lives in an imported namespace, alias-qualify the reference`,r}};function Ko(p){return p.predicate?.subject}var Bt={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},qt={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"};function it(p,e,t){let o=[],n=new Set,r=new Set,a=i=>{let s=b(p,i),c=s?`${s.namespace}/${s.name}`:R(i);if(n.has(c)){let l=o.findIndex(u=>u.key===c),m=o.slice(l);return m.length<=1?null:[...m.map(u=>u.uri),i]}if(r.has(c))return null;if(n.add(c),o.push({key:c,uri:i}),s)for(let l of M(s,t)){let m=a(l);if(m)return m}return o.pop(),n.delete(c),r.add(c),null};return a(e)}var Ft=p=>p,Ve=class{ruleName="ClassHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await w(e,t,o);for(let i of a){if(!(i instanceof k)||!(j.isClassType(Ft(i))||j.isDatatypeType(Ft(i))))continue;let s=x(i);if(!s)continue;let c=it(r,s,Bt);if(c){let l=c.map(u=>u.name).join(" \u2192 "),m=new d;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular class hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",m.entityName=i.name,m.propertyName="subClassOf",m.actualValue=l,n.push(m);break}}return n}};var Ee=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await w(e,t,o);for(let i of a){if(!(i instanceof k)||!Q(r,i))continue;let s=x(i);if(!s)continue;let c=it(r,s,qt);if(c){let l=c.map(u=>u.name).join(" \u2192 "),m=new d;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular property hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",m.entityName=i.name,m.propertyName="subPropertyOf",m.actualValue=l,n.push(m);break}}return n}};var Vo={publisher:"kanonak.org",package_:"core-rdf",name:"range"},ve=class{ruleName="PropertyRangeRequired";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await w(e,t,o);for(let i of a){if(!(i instanceof k))continue;let s=q(r,i);if(s!=="ObjectProperty"&&s!=="DatatypeProperty")continue;let c=s==="ObjectProperty";H(i,Vo)||n.push(this.error(i.name,c))}return n}error(e,t){let o=new d;return o.ruleType=this.ruleName,o.severity="Error",o.entityName=e,o.propertyName="range",o.message=`Property '${e}' must have a 'range' defined.`,o.suggestion=t?"Add a range like: range: ClassName (the class this property expects)":"Add a range like: range: string (or integer, boolean, etc.)",o.expectedValue=t?"A class name (Character, Scene, Story, etc.)":"A datatype (string, integer, boolean, decimal, etc.)",o}};var Eo={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},Ht=p=>p,De=class{ruleName="SubClassOfReference";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await w(e,t,o);for(let i of a){if(!(i instanceof k)||!Wt(Ht(i)))continue;let s=M(i,Eo);for(let c=0;c<s.length;c++)this.resolvesToClassLike(r,s[c])||n.push(this.error(i.name,s[c],s.length>1?`[${c}]`:""))}return n}resolvesToClassLike(e,t){let o=b(e,t);return o?Wt(Ht(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subClassOf",r.actualValue=n,r.expectedValue="Defined or imported class",r.message=`Class '${t.name}' referenced in subClassOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a Class, or import a namespace that contains it`,r}};function Wt(p){return j.isClassType(p)||j.isDatatypeType(p)}var vo={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"},Se=class{ruleName="SubPropertyOfReference";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await w(e,t,o);for(let i of a){if(!(i instanceof k)||!Q(r,i))continue;let s=M(i,vo);for(let c=0;c<s.length;c++)this.resolvesToProperty(r,s[c])||n.push(this.error(i.name,s[c],s.length>1?`[${c}]`:""))}return n}resolvesToProperty(e,t){let o=b(e,t);return o?Q(e,o):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subPropertyOf",r.actualValue=n,r.expectedValue="Defined or imported property",r.message=`Property '${t.name}' referenced in subPropertyOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a property, or import a namespace that contains it`,r}};var $e=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,t){let o=[],n=e.metadata.namespace_?.toString();if(!n)return o;let r=new Map,a=new Set;await this.buildImportGraph(e,t,r,a);let i=this.detectCycle(n,r);if(i){let s=i.join(" \u2192 "),c=new d;c.ruleType=this.ruleName,c.severity="Error",c.message=`Circular namespace import detected: ${s}`,c.suggestion="Remove one of the imports to break the circular dependency, or \u2014 if one direction is a DATA reference rather than a schema dependency (an object-property value naming a resource in the other package) \u2014 mark that import `mode: link`: links are dereferenced on demand, are not in the closure, and are exempt from this rule. Circular dependencies prevent proper package resolution.",c.entityName="imports",c.propertyName="imports",c.actualValue=s,o.push(c)}return o}async buildImportGraph(e,t,o,n){let r=e.metadata.namespace_?.toString()??"";if(!(!r||n.has(r))&&(n.add(r),e.metadata.imports)){let a=[];for(let[i,s]of Object.entries(e.metadata.imports))for(let c of s){if(se(c))continue;let l=`${i}/${c.packageName}@${c.version}`;a.push(l);let m=await t.getHighestCompatibleVersionAsync(i,c);m&&await this.buildImportGraph(m,t,o,n)}a.length>0&&o.set(r,a)}}detectCycle(e,t){let o=[],n=new Set;return this.detectCycleRecursive(e,t,o,n)}detectCycleRecursive(e,t,o,n){let r=o.indexOf(e);if(r>=0){let i=o.slice(r);return i.push(e),i}if(n.has(e))return null;o.push(e),n.add(e);let a=t.get(e);if(a)for(let i of a){let s=this.detectCycleRecursive(i,t,o,n);if(s)return s}return o.pop(),null}};var Ie=class{ruleName="UnresolvedPredicate";async validateAsync(e,t,o){let n=[],r=rt(e);if(!r)return n;let a=await $(e,t,o);return F(a,({kanonak:i,path:s})=>{for(let c of i.unresolvedPredicates)c.sourceDoc===r&&n.push(this.unresolvedPredicateError(s,c.key))}),n}unresolvedPredicateError(e,t){let o=t.lastIndexOf("."),n=o>0?t.slice(0,o):null,r=o>0?t.slice(o+1):t,a=new d;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=t,a.expectedValue="A defined or imported property",a.message=`Property '${t}' is not defined or imported`,a.suggestion=n?`The property '${r}' was not found in the namespace imported as '${n}'.
9
+ 1. Check '${r}' is spelled correctly
10
+ 2. Verify '${n}' is imported with the right alias and version
11
+ 3. Ensure that namespace version actually defines '${r}'`:`The property '${t}' is not defined in this namespace or any imported namespace.
12
+ 1. Define '${t}' as an ObjectProperty or DatatypeProperty here, OR
13
+ 2. Import the namespace that defines it, OR
14
+ 3. Alias-qualify it if it lives in an imported namespace ('alias.${t}')`,a}};var je=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,t){let o=[],{entitySources:n,importPaths:r}=await this.buildEntitySourceMapAsync(e,t),a=await this.buildDatatypePropertyNamesAsync(e,t);for(let[i,s]of Object.entries(e.body))typeof s=="object"&&s!==null&&!Array.isArray(s)&&this.validateEntityReferences(i,s,n,r,a,e,o);return o}async buildEntitySourceMapAsync(e,t){let o=new Map,n=new Set,r=new Map;for(let a of Object.keys(e.body)){let i=e.metadata.namespace_?.toString()??"";o.has(a)||o.set(a,[]),o.get(a).push(`(local:${i})`)}if(e.metadata.imports)for(let[a,i]of Object.entries(e.metadata.imports))for(let s of i){let c=await t.getHighestCompatibleVersionAsync(a,s);if(c){let l=c.metadata.namespace_?.toString()??"";await this.collectEntitiesRecursivelyAsync(c,o,n,r,[l],t)}}return{entitySources:o,importPaths:r}}async collectEntitiesRecursivelyAsync(e,t,o,n,r,a){let i=e.metadata.namespace_?.toString()??"";if(!o.has(i)){o.add(i),n.has(i)||n.set(i,r);for(let s of Object.keys(e.body)){t.has(s)||t.set(s,[]);let c=t.get(s);c.includes(i)||c.push(i)}if(e.metadata.imports)for(let[s,c]of Object.entries(e.metadata.imports))for(let l of c){let m=await a.getHighestCompatibleVersionAsync(s,l);if(m){let u=m.metadata.namespace_?.toString()??"";await this.collectEntitiesRecursivelyAsync(m,t,o,n,[...r,u],a)}}}}async buildDatatypePropertyNamesAsync(e,t){let o=new Set,n=new Set;if(await this.collectDatatypePropertiesAsync(e,o,n,t),e.metadata.imports)for(let[r,a]of Object.entries(e.metadata.imports))for(let i of a){let s=await t.getHighestCompatibleVersionAsync(r,i);s&&await this.collectDatatypePropertiesAsync(s,o,n,t)}return o}async collectDatatypePropertiesAsync(e,t,o,n){let r=e.metadata.namespace_?.toString()??"";if(!o.has(r)){o.add(r);for(let[a,i]of Object.entries(e.body)){if(typeof i!="object"||i===null||Array.isArray(i))continue;let s=i.type;if(typeof s!="string")continue;(s.includes(".")?s.substring(s.lastIndexOf(".")+1):s)==="DatatypeProperty"&&t.add(a)}if(e.metadata.imports)for(let[a,i]of Object.entries(e.metadata.imports))for(let s of i){let c=await n.getHighestCompatibleVersionAsync(a,s);c&&await this.collectDatatypePropertiesAsync(c,t,o,n)}}}validateEntityReferences(e,t,o,n,r,a,i){for(let[s,c]of Object.entries(t)){let l=s;if(l&&!l.includes(".")){let m=o.get(l);if(m&&m.length>1&&!m.some(f=>f.startsWith("(local:"))){let f=m.filter(h=>!h.startsWith("(local:"));f.length>1&&i.push(this.createAmbiguityError(e,l,`Property '${l}'`,f,n,a,!0,l))}}this.validatePropertyValue(e,l,c,o,n,r,a,i)}}validatePropertyValue(e,t,o,n,r,a,i,s){if(o==null)return;let c=t&&t.includes(".")?t.substring(t.lastIndexOf(".")+1):t,l=!!c&&a.has(c);if(typeof o=="string"&&!o.includes(".")&&!l){let m=n.get(o);if(m&&m.length>1&&!m.some(f=>f.startsWith("(local:"))){let f=m.filter(h=>!h.startsWith("(local:"));f.length>1&&s.push(this.createAmbiguityError(e,t,`Reference '${o}'`,f,r,i,!1,o))}}else if(Array.isArray(o))for(let m=0;m<o.length;m++){let u=`${e}.${t}[${m}]`;this.validatePropertyValue(u,t,o[m],n,r,a,i,s)}else if(typeof o=="object"&&!Array.isArray(o)){let m=t?`${e}.${t}`:e;this.validateEntityReferences(m,o,n,r,a,i,s)}}createAmbiguityError(e,t,o,n,r,a,i,s){let c=[];for(let g of n){let D=this.findAliasForNamespace(a,g);if(D){let P=t?.split(".").pop()??t;c.push(`${D}.${P}`)}}let l=c.length>0?`Use one of: ${c.map(g=>`'${g}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${t}')`,m=n.map(g=>{let D=r.get(g);return!D||D.length===0?` \u2022 ${g}`:D.length===1?` \u2022 ${g} (direct import)`:` \u2022 ${g}
15
+ imported via: ${D.join(" \u2192 ")}`}).join(`
16
+ `),u=e.split(".")[0],f=e.includes(".")?e:t,h=new d;h.ruleType=this.ruleName,h.severity="Error",h.entityName=u,f&&(h.propertyName=f);let y=s??t;return y&&(h.actualValue=y),h.message=`${o} is ambiguous - defined in multiple imported namespaces`,h.suggestion=`${l}
17
+
18
+ Defined in:
19
+ ${m}`,h.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",h}findAliasForNamespace(e,t){if(!e.metadata.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n)if(`${o}/${r.packageName}@${r.version}`===t&&r.alias)return r.alias;return null}};var Do={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Yt=p=>p,Oe=class{ruleName="PropertyRangeReference";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await w(e,t,o);for(let i of a){if(!(i instanceof k))continue;let s=q(r,i);if(s!=="ObjectProperty"&&s!=="DatatypeProperty")continue;let c=s==="ObjectProperty";for(let l of M(i,Do))this.resolvesToClassLike(r,l)||n.push(this.error(i.name,l,c))}return n}resolvesToClassLike(e,t){let o=b(e,t);return o?j.isClassType(Yt(o))||j.isDatatypeType(Yt(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="range",r.actualValue=n,r.expectedValue=o?"A defined or imported class":"A datatype or defined class",r.message=`Property '${e}' has range '${t.name}' which is not defined or imported`,r.suggestion=o?`Define '${t.name}' as a Class here, or import the namespace that contains it (alias-qualify it if imported under an alias).`:`Use a datatype (xsd type, rdfs.Literal, or a datatype-derived type), or \u2014 if '${t.name}' is a class \u2014 make this an ObjectProperty.`,r}};var So={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Ce="kanonak.org",dt="core-rdf",ft="core-owl",yt=p=>p,$o=[{uri:{publisher:Ce,package_:dt,name:"Class"},ok:(p,e)=>j.isClassType(yt(e))||j.isDatatypeType(yt(e))},{uri:{publisher:Ce,package_:dt,name:"Datatype"},ok:(p,e)=>j.isDatatypeType(yt(e))},{uri:{publisher:Ce,package_:dt,name:"Property"},ok:(p,e)=>Q(p,e)},{uri:{publisher:Ce,package_:ft,name:"ObjectProperty"},ok:(p,e)=>q(p,e)==="ObjectProperty"},{uri:{publisher:Ce,package_:ft,name:"DatatypeProperty"},ok:(p,e)=>q(p,e)==="DatatypeProperty"},{uri:{publisher:Ce,package_:ft,name:"AnnotationProperty"},ok:(p,e)=>q(p,e)==="AnnotationProperty"}],we=class{ruleName="ObjectPropertyValue";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await ue(e,t,o);for(let i of a)i instanceof k&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof ce)this.check(e,r.predicate?.subject,r.object.subject,o,n);else if(r instanceof J)this.walk(e,r.object,Gt(o,r.predicate?.subject),n);else if(r instanceof L){let a=r.predicate?.subject;for(let i of r.object)i instanceof N?this.check(e,a,i.subject,o,n):i instanceof V&&this.walk(e,i,Gt(o,a),n)}}check(e,t,o,n,r){if(!t)return;let a=b(e,t);if(!a)return;let i=E(a,So);if(!i)return;let s=$o.find(l=>Z(i,l.uri));if(!s)return;let c=b(e,o);c&&(s.ok(e,c)||r.push(this.warn(n,t,i,o)))}warn(e,t,o,n){let r=new d;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e.split(".")[0],r.propertyName=e,r.actualValue=n.name,r.expectedValue=o.name,r.message=`Property '${t.name}' expects a ${o.name}, but '${n.name}' is not a ${o.name}`,r.suggestion=`Reference a resource that is a ${o.name}, or correct the type of '${n.name}'.`,r}};function Gt(p,e){return`${p}.${e?.name??"<embedded>"}`}var Io={publisher:"kanonak.org",package_:"core-rdf",name:"domain"},jo={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},Pe=class{ruleName="PropertyDomain";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await ue(e,t,o);for(let i of a)i instanceof k&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){this.checkNode(e,t,o,n);for(let r of t.statement)if(r instanceof J)this.walk(e,r.object,zt(o,r.predicate?.subject),n);else if(r instanceof L)for(let a of r.object)a instanceof V&&this.walk(e,a,zt(o,r.predicate?.subject),n)}checkNode(e,t,o,n){let r=pe(t);if(r.length===0)return;let a,i=()=>{if(!a){a=new Set([R(jo)]);for(let c of r)for(let l of W(e,c))a.add(R(l))}return a},s=new Set;for(let c of t.statement){let l=Oo(c);if(!l||nt(l.name)||s.has(R(l)))continue;s.add(R(l));let m=b(e,l);if(!m)continue;let u=M(m,Io);u.length!==0&&(u.some(f=>i().has(R(f)))||n.push(this.error(o,l,u,r[0])))}}error(e,t,o,n){let r=o.map(i=>i.name).join(" | "),a=new d;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e.split(".")[0],a.propertyName=e,a.actualValue=t.name,a.expectedValue=`Property used on ${r} or its subclasses`,a.message=`Property '${t.name}' has domain '${r}' but is used on '${n.name}' at '${e}'`,a.suggestion=`Either:
20
+ 1. Use '${t.name}' only on '${r}' (or a subclass) instances
21
+ 2. Widen the property's domain to include '${n.name}'
22
+ 3. Use a different property for '${n.name}'`,a}};function Oo(p){return p.predicate?.subject}function zt(p,e){return`${p}.${e?.name??"<embedded>"}`}var Co={publisher:"kanonak.org",package_:"core-rdf",name:"range"},wo={publisher:"kanonak.org",package_:"core-rdf",name:"Literal"},Po=p=>p,Ue=class{ruleName="PropertyKindRangeConsistency";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await w(e,t,o);for(let i of a){if(!(i instanceof k))continue;let s=q(r,i);if(s!=="ObjectProperty"&&s!=="DatatypeProperty")continue;let c=s==="ObjectProperty",l=s==="DatatypeProperty",m=E(i,Co);if(!m||!b(r,m))continue;let u=Uo(r,m);l&&!u?n.push(this.error(i.name,m,"datatype")):c&&u&&n.push(this.error(i.name,m,"object"))}return n}error(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="range",n.actualValue=t.name,o==="datatype"?(n.expectedValue="A datatype (xsd type, rdfs.Literal, or a datatype-derived class)",n.message=`DatatypeProperty '${e}' has range '${t.name}', which is a class, not a datatype. A datatype property's values are literals.`,n.suggestion=`Use a datatype range (e.g. xsd.string, rdfs.Literal, or a datatype-derived class), or \u2014 if '${t.name}' is the intended target \u2014 declare '${e}' an ObjectProperty.`):(n.expectedValue="A plain class (not datatype-derived)",n.message=`ObjectProperty '${e}' has range '${t.name}', which is a datatype, not a class. An object property's values are references to resources.`,n.suggestion=`Declare '${e}' a DatatypeProperty (its values are literals of '${t.name}'), or change the range to a plain class.`),n}};function Uo(p,e){for(let t of W(p,e)){if(Z(t,wo))return!0;let o=b(p,t);if(o&&j.isDatatypeType(Po(o)))return!0}return!1}var Ae=class{ruleName="ReservedNameShadow";async validateAsync(e,t,o){let n=[],r=await w(e,t,o);for(let a of r){if(!(a instanceof k))continue;let i=Ct(a.name);if(!i)continue;let s=x(a);s&&(i.publisher===s.publisher&&i.package_===s.package_||n.push(this.info(a.name,s,i)))}return n}info(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Info",n.entityName=e,n.propertyName=e,n.actualValue=`${t.publisher}/${t.package_}/${e}`,n.expectedValue=`${o.publisher}/${o.package_}/${e}`,n.message=`'${e}' is also the reserved built-in '${o.publisher}/${o.package_}/${e}'. This local definition shadows it \u2014 a bare '${e}' reference in this package resolves to the local entity, not the built-in.`,n.suggestion=`If this is intentional, qualify bare references to '${e}' explicitly (this local one vs. the built-in '${o.publisher}/${o.package_}/${e}') so the choice is unambiguous to readers and tools \u2014 e.g. a self-referential 'subClassOf: ${e}' silently resolves to this local entity.`,n}};var Ao={publisher:"kanonak.org",package_:"core-rdf",name:"type"},Xt=p=>p,Ne=class{ruleName="ClassDefinition";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await w(e,t,o);return F(a,({kanonak:i,path:s})=>{for(let c of M(i,Ao))this.resolvesToClassLike(r,c)||n.push(this.error(s,c))}),n}resolvesToClassLike(e,t){if(nt(t.name))return!0;let o=b(e,t);return o?j.isClassType(Xt(o))||j.isDatatypeType(Xt(o)):!1}error(e,t){let o=`${t.publisher}/${t.package_}/${t.name}`,n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="type",n.actualValue=o,n.expectedValue="Defined or imported class",n.message=`Class '${t.name}' is not defined or imported`,n.suggestion=`Define '${t.name}' as a Class in this document, or import a namespace that contains it`,n}};var Te=class{ruleName="MarkdownLink";async validateAsync(e,t,o){let n=[],r=await w(e,t,o);return F(r,({kanonak:a,path:i})=>{this.checkNode(a,i,n)}),n}checkNode(e,t,o){for(let n of e.statement)if(n instanceof ot)this.checkProse(n.object,n.links,t,n.predicate.subject?.name??"(unknown)",o);else if(n instanceof L){let r=n.predicate.subject?.name??"(unknown)";(n.object??[]).forEach((a,i)=>{a instanceof tt&&a.links&&this.checkProse(String(a.value),a.links,t,`${r}[${i}]`,o)})}}checkProse(e,t,o,n,r){for(let a of t)a.target||r.push(this.unresolvedLinkError(o,n,a.reference));for(let a of Pt(e))r.push(this.malformedLinkError(o,n,a.snippet))}unresolvedLinkError(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`Embedded link [[${o}]] in '${t}' could not be resolved`,n.expectedValue="A reference resolvable through the document's import closure",n.suggestion=`The reference '${o}' inside a markdown value cannot be found in the current document or any imported namespace.
23
+
24
+ Possible solutions:
25
+ \u2022 Import the package that defines '${o}' so the link can resolve
26
+ \u2022 Check for typos in the reference name
27
+ \u2022 If the name collides across imports, alias-qualify it: [[alias.${o}]]`,n}malformedLinkError(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`Malformed embedded reference near '${o}' in '${t}'`,n.expectedValue="A single-line [[reference]] with no internal line break",n.suggestion=`A '[[' in '${t}' does not form a complete [[reference]] link.
28
+
29
+ A reference may not span a line break \u2014 the most common cause is wrapping a
30
+ long reference across two lines in a block scalar, e.g.:
31
+ ... read for [[persistent-energy-
32
+ shock]] held ...
33
+ which is parsed as literal text, not a link. Keep each [[reference]] on one
34
+ line (let the line run long), or check for an unterminated [[.`,n}};var Zt="kanonak.org",Qt="look",No={publisher:Zt,package_:Qt,name:"displayLabel"},To={publisher:Zt,package_:Qt,name:"displaySummary"},xe=class{ruleName="DisplayLensScope";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new O().parseKanonaks(new B(e,t));let a=xo(e);if(!a)return n;for(let i of r)i instanceof k&&i.namespace===a&&(this.checkLens(r,i,No,"displayLabel",n),this.checkLens(r,i,To,"displaySummary",n));return n}checkLens(e,t,o,n,r){let a=E(t,o);if(!a)return;let i=[],s=x(t);if(s&&i.push(s),i.push(...pe(t)),i.length===0)return;i.some(l=>Y(e,l,a).ok)||r.push(this.scopeError(t.name,n,a.name))}scopeError(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`${t} points at '${o}', which is not a property in scope for '${e}'`,n.expectedValue="A property whose domain is this resource's class, an ancestor, or rdfs.Resource",n.suggestion=`'${o}' resolves, but its domain does not cover '${e}', so the lens would silently fall back to the resource's name at render time.
35
+
36
+ Possible solutions:
37
+ \u2022 Point ${t} at a property declared on this class (or an ancestor / rdfs.Resource)
38
+ \u2022 Set the property's domain to this class if it should apply here
39
+ \u2022 Use rdfs.label / rdfs.comment for the universal default`,n}};function xo(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}function ae(p,e,t){let o=[];return ze(p,t,{input:e},o),o}function ze(p,e,t,o){if(A(e,z.VarRef)){let a=te(e,z.varName);return a?t[a]:void 0}if(A(e,z.PropertyRead)){let a=C(e,z.readSource),i=a?ze(p,a,t,o):void 0,s=E(e,z.readProp);if(!i||!s)return;let c=Y(p,i,s);if(!c.ok){o.push({contextClass:i,propertyUri:s,via:"PropertyRead"});return}return c.descriptor?.range}if(A(e,z.Traverse)){let a=C(e,z.traverseSource),i=a?ze(p,a,t,o):void 0,s=E(e,z.through),c;if(i&&s){let m=Y(p,i,s);m.ok?c=m.descriptor?.range:o.push({contextClass:i,propertyUri:s,via:"Traverse"})}let l=C(e,z.step);return l?ze(p,l,{...t,input:c},o):void 0}let n=te(e,z.loopVar),r=n?{...t,[n]:void 0}:t;for(let a of _o(e))ze(p,a,r,o)}function _o(p){let e=[];for(let t of p.statement){let o=t.object;if(o instanceof V)e.push(o);else if(Array.isArray(o))for(let n of o)n instanceof V&&e.push(n)}return e}var Xe="kanonak.org",Ze="look",Lo={publisher:Xe,package_:Ze,name:"semanticSvg"},Mo={publisher:Xe,package_:Ze,name:"tierChip"},Bo={publisher:Xe,package_:Ze,name:"tierIcon"},qo={publisher:Xe,package_:Ze,name:"tierCard"},Fo={publisher:Xe,package_:Ze,name:"tierFull"},Ho=[Mo,Bo,qo,Fo],_e=class{ruleName="LookSemanticSvgPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new O().parseKanonaks(new B(e,t));let a=Wo(e);if(!a)return n;for(let i of r)i instanceof k&&i.namespace===a&&this.checkSemanticSvg(r,i,n);return n}checkSemanticSvg(e,t,o){let n=C(t,Lo);if(!n)return;let r=x(t);if(r)for(let a of Ho){let i=C(n,a);if(i)for(let s of ae(e,r,i))o.push(this.toError(t.name,a.name,s))}}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=r===e?`'${e}' (the class this SemanticSvg is declared on)`:`'${r}', reached by traversal from '${e}' (the class this SemanticSvg is declared on)`,i=new d;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=`look.semanticSvg.${t}`,i.actualValue=n,i.message=`tx.${o.via} reads property '${o.propertyUri.name}' off the rendered instance, but its domain is not in scope for ${a}. The read would silently return undefined at render time.`,i.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,i.suggestion=`Property '${n}' is not in scope for '${r}'.
40
+
41
+ Possible solutions:
42
+ \u2022 Read a property declared on '${r}' (or an ancestor / rdfs.Resource)
43
+ \u2022 If the property should apply to '${r}', adjust its domain
44
+ \u2022 If the value comes from a pre-computed env binding, use tx.VarRef instead of PropertyRead`,i}};function Wo(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Jt={publisher:"kanonak.org",package_:"transformations",name:"Expression"},Yo=new Map([["look","the look renderer"],["view","the view materializer"],["transformations","the transformation runner"]]);function eo(p){if(!(!p||p.publisher!=="kanonak.org"))return Yo.get(p.package_)}var Le=class{ruleName="TxExpressionCompiles";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(new B(e,t)),a=Xo(e);if(!a)return n;let i=r.filter(y=>y instanceof k&&y.namespace===a);if(i.length===0)return n;let s=new Map,c=y=>{for(let g of $t(y)){let D=R(g),P=s.get(D);if(P===void 0&&(P=Z(g,Jt)||W(r,g).some(I=>Z(I,Jt)),s.set(D,P)),P)return!0}return!1},l=[],m=new Map,u=new Map,f=new Set;for(let y of i)F([y],({kanonak:g,path:D})=>{let P=g instanceof V&&c(g);P&&l.push({node:g,path:D,subject:y.name});for(let{child:I,predicate:S}of zo(g))c(I)&&(S&&m.set(I,S),P&&f.add(I));if(!P){for(let I of Go(g))if(eo(I))for(let S of oe(g,I)){if(!(S.item instanceof N))continue;let G=b(r,S.item.subject);G&&c(G)&&(l.push({node:G,path:`${D}.${I.name}`,subject:y.name}),u.set(G,I))}}});let h=new Set;for(let{node:y,path:g,subject:D}of l){if(y instanceof V&&f.has(y))continue;let P=eo(y instanceof V?m.get(y):u.get(y));if(P)try{At(y,g,{catalog:r,depth:0})}catch(I){let S=I instanceof Error?I.message:String(I),G=`${D} ${g} ${S}`;if(h.has(G))continue;h.add(G),n.push(this.toError(D,g,S,P))}}return n}toError(e,t,o,n){let r=new d;r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=o;let a=/[.!?]$/.test(o)?o:`${o}.`;return r.message=`A tx.Expression at '${t}' is in a slot ${n} evaluates, but it cannot be compiled: ${a} The value would be silently absent wherever this slot is used.`,r.expectedValue=`A tx.Expression built from node classes ${n} implements`,r.suggestion=`This slot is evaluated by ${n}, which is part of this SDK, so its node classes are the ones available here. (An Expression subclass meant for a DIFFERENT runner is fine in that runner's own slots \u2014 this rule does not look at those.)
45
+
46
+ Possible solutions:
47
+ \u2022 Rebuild the expression from tx primitives this SDK supports
48
+ \u2022 For numeric presentation (rounding, percentages, fixed precision), use tx.NumberFormat \u2014 it scales internally, so no arithmetic is needed
49
+ \u2022 If the node class should be supported, implement it in the runner first`,r}};function Go(p){let e=new Map;for(let t of p.statement){let o=t.predicate?.subject;o&&!e.has(R(o))&&e.set(R(o),o)}return[...e.values()]}function zo(p){let e=[];for(let t of p.statement){let o=t.predicate?.subject;if(t instanceof J)e.push({child:t.object,predicate:o});else if(t instanceof L)for(let n of t.object)n instanceof V&&e.push({child:n,predicate:o})}return e}function Xo(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Zo="kanonak.org",Qe=(p,e)=>({publisher:Zo,package_:p,name:e}),Qo=Qe("derivation","look"),to=Qe("look","bands"),oo=Qe("look","Sequence"),Jo=Qe("core-rdf","range"),en=Qe("look","nodeTier"),Me=class{ruleName="SequenceNarrative";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(new B(e,t)),a=tn(e);if(!a)return n;let i=r.filter(c=>c instanceof k&&c.namespace===a);if(i.length===0)return n;for(let c of i){let l=C(c,Qo);l&&T(l,to).forEach((m,u)=>{!(m instanceof V)||!A(m,oo)||n.push(...this.checkBand(r,c,m,`${c.name}.look.bands[${u}]`))})}let s=new Lt(r);for(let c of i){let l=s.findCascadedLook(c);if(l)for(let m of T(l.declaration,to))!(m instanceof V)||!A(m,oo)||this.checkBand(r,c,m,"").length>0||n.push(...this.checkInstance(r,c,m,Tt(r,c,m)))}return n}checkBand(e,t,o,n){let r=[],a=(l,m,u)=>r.push(this.toError("Error",t.name,n,l,m,u)),i=ct(o);if(!i)a("A look.Sequence band declares no look.source. The order of a sequence comes from the [[references]] in a prose property, so without one nothing can be sequenced.","Set look.source to a property of this class whose rdfs.range is prose.Markdown (or prose.SubstitutableString), and render the same property with a look.Markdown band so the narrative and the diagram cannot drift.");else{let l=It(e,i)[0],m=l?M(l,Jo):[];l&&!m.some(u=>St.isSubstitutableDatatypeUri(u))&&a(`look.source names '${i.name}', whose rdfs.range is ${m.map(u=>R(u)).join(", ")||"undeclared"} \u2014 not prose.Markdown. A Sequence orders its participants by the [[references]] in prose, so a value of this property carries no order.`,"Point look.source at a prose.Markdown-ranged property, or give this property that range if its values are narrative.",R(i))}let s=pt(e,o);s.length===0&&a("A look.Sequence band declares no look.connectors, so no property counts as a message and every narrative renders empty.","List the object properties that constitute messages: look.connectors: [{ look.relation: calls }, ...]. The domain ontology declares nothing about sequences; the look layer says which of its relations are interactions.");for(let l of s)(!l.subject||q(e,l.subject)===void 0)&&a(`look.connectors names '${l.relation.name}' as a relation, but it is not a property${l.subject?"":" in the closure"}. A message is a triple, so its relation must be an object property whose values are the participants.`,"Use an owl.ObjectProperty (or a subclass such as owl.SymmetricProperty) for look.relation.",R(l.relation)),l.invalidStyle!==void 0&&a(`look.lineStyle '${l.invalidStyle}' on connector '${l.relation.name}' is not a supported value. Supported: ${[...Nt].join(", ")}.`,"Use one of the supported values, or omit look.lineStyle: a reply is derived from owl.inverseOf and an undirected edge from owl.SymmetricProperty, so the overlay is only needed for what the ontology cannot say.",l.invalidStyle);let c=te(o,en);return c!==void 0&&lt[c]===void 0&&a(`look.nodeTier '${c}' is not a tier. Supported: ${Object.keys(lt).join(", ")}.`,"Use one of the semantic-zoom tiers \u2014 chip (56), icon (120, the default), card (240), full (420) \u2014 or omit look.nodeTier to take the participants' class-level look.diagramTier.",c),r}checkInstance(e,t,o,n){let r=[],a=ct(o),i=`${t.name}.${a.name}`,s=pt(e,o).map(c=>c.relation.name).join(", ");if(n.problem)return r.push(this.toError("Error",t.name,i,`The look.Sequence band cannot walk this instance: ${n.problem}.`,"Check the value authored for the source property.")),r;if(n.sourceAbsent)return r.push(this.toError("Warning",t.name,i,`'${t.name}' carries no value for '${a.name}', so its look.Sequence band renders nothing.`,`Author the narrative in '${a.name}' with [[references]] to the participants, or leave it if the band is meant to be empty here.`)),r;for(let c of n.strayPropertyRefs)r.push(this.toError("Error",t.name,i,`The narrative references property '${c.name}', which is not a declared connector of the look.Sequence band (declared: ${s}). A property reference between two participants selects the edge for that pair; one the band does not declare selects nothing, and the sentence draws no message.`,`Add { look.relation: ${c.name} } to look.connectors on the band, or reference one of the declared connectors instead.`,R(c)));if(n.mentions>=2&&n.messages.length===0)return r.push(this.toError("Error",t.name,i,`The narrative mentions ${n.mentions} participant references but joins nothing: no declared connector (${s}) holds between any consecutive pair, so the look.Sequence band renders no message.`,"Either the graph is missing the triples the prose describes (declare them on the participants), the band is missing the relation the prose relies on (add it to look.connectors), or the prose orders participants no relation joins (reorder it).")),r;for(let c of n.gaps){let l=c.selected?`'${c.selected.name}' does not hold`:`no declared connector (${s}) holds`;r.push(this.toError("Warning",t.name,i,`The narrative orders '${c.prev.name}' then '${c.next.name}', but ${l} between them in the graph, so no message is drawn for that pair.`,`If the prose is right, declare the relation on '${c.prev.name}' or '${c.next.name}' (or add it to look.connectors); if the graph is right, reorder the prose so consecutive references are joined. A mention that is meant to connect to nothing is fine \u2014 it simply gets no lifeline.`,`${c.prev.name} \u2192 ${c.next.name}`))}return r}toError(e,t,o,n,r,a){let i=new d;return i.ruleType=this.ruleName,i.severity=e,i.entityName=t,i.propertyName=o,i.message=n,i.suggestion=r,a!==void 0&&(i.actualValue=a),i}};function tn(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var on="kanonak.org",v=(p,e)=>({publisher:on,package_:p,name:e}),nn=v("derivation","look"),rn=v("look","bands"),an=v("look","Distribution"),sn=v("look","StatRow"),cn=v("look","VersionDelta"),pn=v("look","Timeline"),ln=v("look","VersionDiff"),mn=v("look","TimePlot"),un=v("look","ReferenceList"),dn=v("look","Diagram"),fn=v("look","alphaPath"),yn=v("look","betaPath"),ht=v("look","metricPath"),no=v("look","lowerPath"),ro=v("look","upperPath"),ao=v("look","hueBy"),hn=v("look","statPath"),kn=v("look","laneBy"),io=v("look","labelPath"),gn=v("look","badgePath"),Rn=v("look","mapPath"),bn=v("look","nodeNote"),Kn=v("look","edgeValue"),Vn=v("look","stats"),En=v("look","facets"),vn=v("look","channels"),Dn=v("look","track"),Sn=v("look","source"),$n=v("look","relation"),In=v("look","entries"),Be=class{ruleName="LookBandPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new O().parseKanonaks(new B(e,t));let a=On(e);if(!a)return n;for(let i of r)i instanceof k&&i.namespace===a&&this.checkDeclaration(r,i,n);return n}checkDeclaration(e,t,o){let n=C(t,nn);if(!n)return;let r=x(t);if(!r)return;let a=T(n,rn).filter(i=>i instanceof V);for(let i of a)for(let s of this.carriersOf(e,i,r))for(let c of ae(e,s.context,s.expr))o.push(this.toError(t.name,s.slot,c))}carriersOf(e,t,o){let n=[],r=(a,i)=>{let s=C(t,a);s&&n.push({slot:`look.${a.name}`,context:i,expr:s})};if(A(t,an))for(let a of[fn,yn,ht,no,ro,ao])r(a,o);if(A(t,cn)&&r(ht,o),A(t,sn)){let a=T(t,Vn).filter(i=>i instanceof V);for(let i of a){let s=C(i,hn);s&&n.push({slot:"look.stats[].statPath",context:o,expr:s})}}if(A(t,pn)||A(t,ln)){let a=this.rangeOf(e,o,E(t,Dn));if(a)for(let i of[ht,no,ro,ao])r(i,a)}if(A(t,mn)){let a=this.rangeOf(e,o,E(t,Sn));if(a)for(let i of[kn,io])r(i,a)}if(A(t,un))for(let a of T(t,In)){let i=a instanceof V?void 0:jn(a),s=this.rangeOf(e,o,i);if(s)for(let c of[io,gn])r(c,s)}if(A(t,dn)){let a=T(t,En).filter(i=>i instanceof V);for(let i of a){let s=this.rangeOf(e,o,E(i,$n));if(!s)continue;let c=C(i,bn);c&&n.push({slot:"look.facets[].nodeNote",context:s,expr:c});let l=C(i,Kn);l&&n.push({slot:"look.facets[].edgeValue",context:s,expr:l});let m=T(i,vn).filter(u=>u instanceof V);for(let u of m){let f=C(u,Rn);f&&n.push({slot:"look.facets[].channels[].mapPath",context:s,expr:f})}}}return n}rangeOf(e,t,o){if(!o)return;let n=Y(e,t,o);return n.ok?n.descriptor?.range:void 0}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=new d;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=n,a.message=`tx.${o.via} reads property '${o.propertyUri.name}', but its domain is not in scope for '${r}' (the class this band carrier is evaluated against). The read would silently return undefined at render time and the band would render empty.`,a.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${n}' is not in scope for '${r}'.
50
+
51
+ Possible solutions:
52
+ \u2022 Read a property declared on '${r}' (or an ancestor / rdfs.Resource)
53
+ \u2022 If the property should apply to '${r}', adjust its domain
54
+ \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,a}};function jn(p){let e=p.subject;return e&&typeof e.name=="string"?e:void 0}function On(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Cn="kanonak.org",kt=(p,e)=>({publisher:Cn,package_:p,name:e}),wn=kt("derivation","look"),Pn=kt("look","bands"),Un=kt("core-rdf","type"),Je=class{ruleName="UnrenderableBand";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(new B(e,t)),a=An(e);if(!a)return n;let i=Mt();for(let s of r){if(!(s instanceof k)||s.namespace!==a)continue;let c=C(s,wn);if(!c)continue;let l=T(c,Pn).filter(m=>m instanceof V);for(let m of l){let u=this.typeOf(m);if(!u)continue;let f=`${u.publisher}/${u.package_}/${u.name}`;if(i.has(f))continue;let h=new d;h.ruleType=this.ruleName,h.severity="Warning",h.entityName=s.name,h.propertyName="derivation.look",h.actualValue=f,h.message=`Band '${u.name}' has no renderer, so this region of the page will be empty. The declaration is valid against the look vocabulary, but the renderer emits only an HTML comment for it \u2014 which a browser does not display, so the loss is silent. Use a band the renderer implements, or remove it until it is supported.`,n.push(h)}}return n}typeOf(e){let t=E(e,Un);if(t)return{publisher:t.publisher,package_:t.package_,name:t.name}}};function An(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Fe="kanonak.org",He="view",Nn={publisher:Fe,package_:He,name:"bind"},Tn={publisher:Fe,package_:He,name:"produces"},xn={publisher:Fe,package_:He,name:"projections"},_n={publisher:Fe,package_:He,name:"where"},Ln={publisher:Fe,package_:He,name:"value"},Mn={publisher:Fe,package_:He,name:"as"},qe=class{ruleName="TxExpressionPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new O().parseKanonaks(new B(e,t));let a=Fn(e);if(!a)return n;for(let i of r)i instanceof k&&i.namespace===a&&this.checkView(r,i,n);return n}checkView(e,t,o){let n=E(t,Nn);if(!n)return;let r=E(t,Tn),a=0;for(let s of qn(e,T(t,xn))){let c=C(s,Ln);if(c)for(let m of ae(e,n,c))o.push(this.toError(t.name,`view.projections[${a}].value`,n,m));let l=E(s,Mn);l&&r&&(Y(e,r,l).ok||o.push(this.asError(t.name,a,r,l))),a+=1}let i=0;for(let s of Bn(t,_n)){for(let c of ae(e,n,s))o.push(this.toError(t.name,`view.where[${i}]`,n,c));i+=1}}asError(e,t,o,n){let r=`${n.publisher}/${n.package_}/${n.name}`,a=new d;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=`view.projections[${t}].as`,a.actualValue=r,a.message=`Projection stores its value under property '${n.name}', but that property's domain is not in scope for the view's produces class '${o.name}'. The materialized result instance could not carry this value.`,a.expectedValue=`A property whose domain is '${o.name}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${r}' is not in scope for produces class '${o.name}'.
55
+
56
+ Possible solutions:
57
+ \u2022 Use an output property whose domain covers '${o.name}'
58
+ \u2022 Define a new property in the ViewPackage with domain '${o.name}' and the right range
59
+ \u2022 If the value belongs on a different output class, adjust the view's produces`,a}toError(e,t,o,n){let r=`${n.propertyUri.publisher}/${n.propertyUri.package_}/${n.propertyUri.name}`,a=n.contextClass.name,i=a===o.name?`the view's bound class '${o.name}'`:`'${a}', reached by traversal from the view's bound class '${o.name}'`,s=new d;return s.ruleType=this.ruleName,s.severity="Error",s.entityName=e,s.propertyName=t,s.actualValue=r,s.message=`tx.${n.via} reads property '${n.propertyUri.name}', but its domain is not in scope for ${i}. The read would silently return undefined when the view materializes.`,s.expectedValue=`A property whose domain is '${a}', an ancestor, or rdfs.Resource`,s.suggestion=`Property '${r}' is not in scope for '${a}'.
60
+
61
+ Possible solutions:
62
+ \u2022 Read a property declared on '${a}' (or an ancestor / rdfs.Resource)
63
+ \u2022 If the property should apply to '${a}', adjust its domain
64
+ \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,s}};function Bn(p,e){let t=C(p,e);return t?[t]:T(p,e).filter(o=>o instanceof V)}function qn(p,e){let t=[];for(let o of e)if(o instanceof V)t.push(o);else if(o instanceof N){let n=b(p,o.subject);n&&t.push(n)}return t}function Fn(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var et="kanonak.org",Hn="core-shacl",_=p=>({publisher:et,package_:Hn,name:p}),so=_("NodeShape"),co=_("PropertyShape"),Wn=_("targetClass"),gt=_("property"),Rt=_("path"),Yn=_("minCount"),Gn=_("maxCount"),zn=_("datatype"),Xn=_("class"),po=_("in"),Zn=_("pattern"),Qn=_("flags"),Jn=_("minLength"),er=_("maxLength"),tr=_("minInclusive"),or=_("maxInclusive"),nr={publisher:et,package_:"core-rdf",name:"range"},rr=new Set(["decimal","integer","int","long","short","byte","float","double","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte"]),lo=p=>p,We=class{ruleName="ShaclShape";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(t),a=ar(e);if(!a)return n;let i=new Set;for(let s of r){if(!(s instanceof k)||s.namespace!==a||!A(s,so))continue;let c=E(s,Wn);c?this.resolvesToClass(r,c)||n.push(this.err(s.name,"targetClass","Error",`NodeShape '${s.name}' sh:targetClass '${c.name}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",X(c))):n.push(this.err(s.name,"targetClass","Error",`NodeShape '${s.name}' has no sh:targetClass; it constrains nothing.`,"Add sh:targetClass naming the class this shape applies to."));for(let{item:l}of oe(s,gt)){let m;if(l instanceof V)m=l;else if(l instanceof N){let u=b(r,l.subject);u&&(m=u,i.add(R(l.subject)))}m&&this.checkPropertyShape(r,s.name,m,c??void 0,n)}}for(let s of r){if(!(s instanceof k)||s.namespace!==a||!A(s,co))continue;let c=x(s);c&&i.has(R(c))||this.checkPropertyShape(r,s.name,s,void 0,n)}return n}checkPropertyShape(e,t,o,n,r){let a=E(o,Rt);if(!a){r.push(this.err(t,"property.path","Error",`A PropertyShape on '${t}' has no sh:path; a PropertyShape must name the property it constrains.`,"Add sh:path naming a property."));return}let i=b(e,a),s=i?Q(e,i):!1;s?n&&(Y(e,n,a).ok||r.push(this.err(t,"property.path","Warning",`sh:path '${a.name}' is not in scope for sh:targetClass '${n.name}'; the constraint would never bind a value.`,`Constrain a property whose domain is '${n.name}', an ancestor, or rdfs.Resource.`,X(a)))):r.push(this.err(t,"property.path","Error",`sh:path '${a.name}' on '${t}' does not resolve to a property.`,"Reference a defined or imported property.",X(a)));let c=E(o,zn),l=E(o,Xn);c&&l&&r.push(this.err(t,"property","Error",`A PropertyShape on '${t}' sets both sh:datatype and sh:class; a value is a literal or a node, not both.`,"Keep sh:datatype (literal values) or sh:class (node values), not both.")),c&&!this.resolvesToDatatype(e,c)&&r.push(this.err(t,"datatype","Error",`sh:datatype '${c.name}' on '${t}' does not resolve to a datatype.`,"Reference an xsd datatype or rdfs.Datatype.",X(c))),l&&!this.resolvesToClass(e,l)&&r.push(this.err(t,"class","Error",`sh:class '${l.name}' on '${t}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",X(l)));let m=ie(ee(o,Yn)),u=ie(ee(o,Gn));this.checkOrder(t,"minCount",m,"maxCount",u,r);let f=ie(ee(o,Jn)),h=ie(ee(o,er));this.checkOrder(t,"minLength",f,"maxLength",h,r);let y=ie(ee(o,tr)),g=ie(ee(o,or));this.checkOrder(t,"minInclusive",y,"maxInclusive",g,r);let D=te(o,Zn);if(D!==void 0){let S=te(o,Qn);try{new RegExp(D,S)}catch{r.push(this.err(t,"pattern","Error",`sh:pattern on '${t}' is not a valid regular expression`+(S!==void 0?` (with flags '${S}')`:"")+`: ${D}`,"Provide a valid regular expression and flags.",D))}}if(H(o,po)&&oe(o,po).length===0&&r.push(this.err(t,"in","Error",`sh:in on '${t}' is empty; an enumeration must list at least one permitted value.`,"List the permitted literal values, or remove sh:in.")),s&&n){let G=Y(e,n,a).descriptor;G&&((D!==void 0||f!==void 0||h!==void 0)&&G.kind==="object"&&r.push(this.err(t,"pattern/minLength/maxLength","Warning",`String facets on '${t}' apply to '${a.name}', which is an object property; string facets constrain literal values.`,"Apply string facets to a datatype property, or use sh:class for node values.",X(a))),(y!==void 0||g!==void 0)&&!this.isNumericDatatypeRange(G.range)&&r.push(this.err(t,"minInclusive/maxInclusive","Warning",`Numeric bounds on '${t}' apply to '${a.name}', whose range is not a numeric datatype.`,"Apply numeric bounds to a numeric datatype property.",X(a))))}let P=i&&s?E(i,nr):void 0,I=i&&s?this.isDatatypeProperty(e,i,P):!1;if(H(o,st)){let S=E(o,st);I?r.push(this.err(t,"hasValue","Error",`sh:hasValue on '${t}' constrains '${a.name}', a datatype property; a literal hasValue is not supported yet.`,"Use sh:hasValue on an object property, naming an individual; literal values arrive with structured literals (typescript#115).",S?X(S):void 0)):!S||!b(e,S)?r.push(this.err(t,"hasValue","Error",`sh:hasValue${S?` '${S.name}'`:""} on '${t}' does not resolve to an individual.`,"Name a defined or imported individual.",S?X(S):void 0)):P&&this.resolvesToClass(e,P)&&!this.isInstanceOf(e,S,P)&&r.push(this.err(t,"hasValue","Warning",`sh:hasValue '${S.name}' on '${t}' is not an instance of '${P.name}', the range of '${a.name}'; no well-typed value can equal it.`,`Name an instance of '${P.name}'.`,X(S)))}this.checkQualified(e,t,o,P,r)}checkQualified(e,t,o,n,r){let a=H(o,ne),i=[{name:"qualifiedMinCount",uri:jt,value:void 0},{name:"qualifiedMaxCount",uri:Ot,value:void 0}],s=!1;for(let y of i){if(!H(o,y.uri))continue;s=!0;let g=ie(ee(o,y.uri));g===void 0||!Number.isInteger(g)||g<0?r.push(this.err(t,y.name,"Error",`sh:${y.name} on '${t}' must be a non-negative integer.`,`Set sh:${y.name} to 0 or more.`)):y.value=g}if(!a&&!s)return;if(!a){r.push(this.err(t,"qualifiedValueShape","Error",`A qualified count on '${t}' has no sh:qualifiedValueShape; it counts values conforming to nothing.`,"Add sh:qualifiedValueShape naming the shape the counted values conform to."));return}s||r.push(this.err(t,"qualifiedValueShape","Error",`sh:qualifiedValueShape on '${t}' has no sh:qualifiedMinCount or sh:qualifiedMaxCount; it bounds nothing.`,"Add sh:qualifiedMinCount and/or sh:qualifiedMaxCount.")),this.checkOrder(t,"qualifiedMinCount",i[0].value,"qualifiedMaxCount",i[1].value,r);let c=n&&this.resolvesToClass(e,n)?n:void 0,l=`${t} (qualified shape)`,m=C(o,ne);if(m){this.checkNestedShape(e,l,m,c,r);let y=this.qualifiedCycle(e,m,new Set);y&&this.pushCycle(t,y,r);return}let u=E(o,ne),f=u?b(e,u):void 0;if(!u||!f||!(A(f,so)||A(f,co)||H(f,Rt))){r.push(this.err(t,"qualifiedValueShape","Error",`sh:qualifiedValueShape${u?` '${u.name}'`:""} on '${t}' does not resolve to a shape.`,"Reference a NodeShape or PropertyShape, or write the shape inline.",u?X(u):void 0));return}let h=this.qualifiedCycle(e,f,new Set([R(u)]));h&&this.pushCycle(t,[u.name,...h],r)}checkNestedShape(e,t,o,n,r){if(H(o,Rt)){this.checkPropertyShape(e,t,o,n,r);return}for(let{item:a}of oe(o,gt)){let i=a instanceof V?a:a instanceof N?b(e,a.subject):void 0;i&&this.checkPropertyShape(e,t,i,n,r)}}qualifiedCycle(e,t,o){let n=(r,a)=>{if(a){let i=R(a);if(o.has(i))return[a.name];let s=b(e,a);if(!s)return;let c=this.qualifiedCycle(e,s,new Set([...o,i]));return c?[a.name,...c]:void 0}return r?this.qualifiedCycle(e,r,o):void 0};if(H(t,ne)){let r=n(C(t,ne),E(t,ne));if(r)return r}for(let{item:r}of oe(t,gt)){let a=r instanceof V?n(r,void 0):r instanceof N?n(void 0,r.subject):void 0;if(a)return a}}pushCycle(e,t,o){o.push(this.err(e,"qualifiedValueShape","Error",`sh:qualifiedValueShape on '${e}' leads back to a shape already being checked (${t.join(" -> ")}); recursive shapes are not evaluated.`,"Break the cycle: a qualified value shape must not reference, directly or through other shapes, a shape that contains it."))}isDatatypeProperty(e,t,o){let n=q(e,t);return n==="DatatypeProperty"?!0:n==="ObjectProperty"?!1:o?this.resolvesToDatatype(e,o):!1}isInstanceOf(e,t,o){let n=b(e,t);if(!n)return!1;let r=R(o);return pe(n).some(a=>R(a)===r||W(e,a).some(i=>R(i)===r))}checkOrder(e,t,o,n,r,a){o!==void 0&&r!==void 0&&o>r&&a.push(this.err(e,`${t}/${n}`,"Error",`${t} (${o}) exceeds ${n} (${r}) on '${e}'.`,`Set ${t} <= ${n}.`))}resolvesToClass(e,t){let o=b(e,t);return o?j.isClassType(lo(o)):!1}resolvesToDatatype(e,t){if(t.publisher===et&&t.package_==="core-rdf"&&t.name==="Literal")return!0;let o=b(e,t);return o?j.isDatatypeType(lo(o)):!1}isNumericDatatypeRange(e){return!e||e.publisher===et&&e.package_==="core-rdf"&&e.name==="Literal"?!0:e.publisher===et&&e.package_==="core-xsd"&&rr.has(e.name)}err(e,t,o,n,r,a){let i=new d;return i.ruleType=this.ruleName,i.severity=o,i.entityName=e,i.propertyName=t,i.message=n,i.suggestion=r,a!==void 0&&(i.actualValue=a),i}};function ie(p){return typeof p=="number"?p:void 0}function X(p){return`${p.publisher}/${p.package_}/${p.name}`}function ar(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var mo={publisher:"kanonak.org",package_:"core-owl",name:"oneOf"},ir=p=>p,Ye=class{ruleName="OwlOneOf";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(t),a=sr(e);if(!a)return n;for(let i of r){if(!(i instanceof k)||i.namespace!==a||!H(i,mo))continue;let s=T(i,mo);if(s.length===0){n.push(this.err(i.name,"Warning",`owl:oneOf on '${i.name}' is empty; a closed enumeration must list at least one individual.`,"List the individuals that make up the enumeration, or remove owl:oneOf."));continue}for(let c of s)if(c instanceof tt)n.push(this.err(i.name,"Error",`owl:oneOf member '${String(c.value)}' on '${i.name}' is not a named individual; a class enumeration is of individuals (a misspelled or unimported individual reads as a literal). For a closed set of literal VALUES, constrain a property with sh:in instead.`,"Reference a defined or imported individual, or move literal value sets to a property sh:in.",String(c.value)));else if(c instanceof N){let l=b(r,c.subject);l&&j.isSchemaDefinitionType(ir(l))&&n.push(this.err(i.name,"Error",`owl:oneOf member '${c.subject.name}' on '${i.name}' is a class/property/datatype, not an individual.`,"List named individuals (instances), not schema definitions.",`${c.subject.publisher}/${c.subject.package_}/${c.subject.name}`))}}return n}err(e,t,o,n,r){let a=new d;return a.ruleType=this.ruleName,a.severity=t,a.entityName=e,a.propertyName="oneOf",a.message=o,a.suggestion=n,r!==void 0&&(a.actualValue=r),a}};function sr(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var cr=p=>p,pr=new Dt("kanonak.org","core-rdf","Resource"),Ge=class{ruleName="DiamondNameClash";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(t),a=lr(e);if(!a)return n;let i=xt(r);for(let s of r){if(!(s instanceof k)||s.namespace!==a||!j.isClassType(cr(s)))continue;let c=x(s);if(!c)continue;let l=W(r,c),m=R(c),u=new Set(l.map(h=>R(h)));u.delete(m),u.delete(R(pr));let f=new Map;for(let h of wt(r,c)){if(!h.domains.some(D=>u.has(R(D))))continue;let g=f.get(h.uri.name);g?g.push(h):f.set(h.uri.name,[h])}for(let[h,y]of f){if(y.length<2)continue;let g=I=>_t(i,l,I.uri)?.cardinality,D=new Set(y.map(I=>I.range?R(I.range):void 0).filter(I=>I!==void 0)),P=new Set(y.map(g).filter(I=>I!==void 0));D.size<=1&&P.size<=1||n.push(this.toError(s.name,h,y,g))}}return n}toError(e,t,o,n){let r=s=>{let c=`${s.uri.publisher}/${s.uri.package_}/${s.uri.name}`,l=s.range?`${s.range.publisher}/${s.range.package_}/${s.range.name}`:"no range",m=n(s);return`${c} (range ${l}${m?`, ${m}`:""})`},a=o.map(r).join("; "),i=new d;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=t,i.actualValue=a,i.message=`Class '${e}' inherits ${o.length} distinct properties named '${t}' with incompatible range or cardinality: ${a}. The generated interface would multiply-inherit '${t}' with conflicting types and could not compile.`,i.suggestion=`Disambiguate the diamond name-clash on '${t}':
65
+ \u2022 rename one of the properties, or
66
+ \u2022 re-domain one so it is not inherited by '${e}', or
67
+ \u2022 restructure the hierarchy so '${e}' inherits only one '${t}', or
68
+ \u2022 make the ranges/cardinalities compatible (identical) if they are meant to be the same property.`,i}};function lr(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var bt=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e,t={}){this.parser=e??new Vt,this.documentRules=[new fe,new ye,new he,new ke,new ge],this.repositoryRules=[new Re,new be,new Ke,new de({offline:t.offline}),new Ve,new Ee,new ve,new De,new Se,new $e,new Ie,new je,new Oe,new we,new Pe,new Ue,new Ae,new Ne,new Te,new xe,new _e,new Be,new Je,new Me,new Le,new qe,new We,new Ye,new Ge]}async validateAsync(e,t,o){let n=new le;for(let r of this.documentRules)try{let a=r.validate(e);this.addErrorsToResult(n,a)}catch(a){let i=new d;i.ruleType=r.ruleName,i.severity="Error",i.message=`Validation rule '${r.ruleName}' failed: ${a instanceof Error?a.message:String(a)}`,n.errors.push(i)}if(t){let r=[],a=o??new re(new me(e,t)),i=a.repository;for(let s of this.repositoryRules)try{let c=await s.validateAsync(e,i,a);this.addErrorsToResult(n,c)}catch(c){let l=c instanceof Error?c.message:String(c);r.push({ruleName:s.ruleName,cause:l})}if(r.length>0){let s=new Map;for(let{ruleName:c,cause:l}of r){let m=s.get(l);m?m.push(c):s.set(l,[c])}for(let[c,l]of s){let m=new d;m.ruleType=l[0],m.severity="Error",l.length===1?m.message=`Validation rule '${l[0]}' failed: ${c}`:m.message=`${c} (affects ${l.length} rules: ${l.join(", ")})`,n.errors.push(m)}}}return n.isValid=n.errors.length===0,n}async validateDocumentsAsync(e,t){let o=t instanceof re?t:new re(t),n=[];for(let r of e){let a=await this.validateAsync(r,o.repository,o);n.push({document:r,result:a})}return n}async validateYamlAsync(e,t,o){let n=this.parser.parseWithErrors(e);if(!n.isValid){let r=new le;r.isValid=!1;for(let a of n.errors){let i=new d;i.ruleType="ParseError",i.severity="Error",i.lineNumber=a.line,i.column=a.column,i.message=a.message,a.keyName&&(i.entityName=a.keyName),a.errorType==="DuplicateKey"&&(i.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),r.errors.push(i)}return r}return await this.validateAsync(n.document,t,o)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let t=this.documentRules.findIndex(o=>o instanceof e);t>=0&&this.documentRules.splice(t,1)}removeRepositoryRule(e){let t=this.repositoryRules.findIndex(o=>o instanceof e);t>=0&&this.repositoryRules.splice(t,1)}addErrorsToResult(e,t){for(let o of t)o.severity==="Error"?e.errors.push(o):o.severity==="Info"?this.includeWarnings&&e.infos.push(o):this.includeWarnings&&e.warnings.push(o)}};export{le as a,K as b,d as c,mt as d,re as e,de as f,fe as g,ye as h,he as i,ke as j,ge as k,Re as l,be as m,Ke as n,Ve as o,Ee as p,ve as q,De as r,Se as s,$e as t,Ie as u,je as v,Oe as w,we as x,Pe as y,Ue as z,Ae as A,Ne as B,Te as C,xe as D,_e as E,Le as F,Me as G,Be as H,qe as I,We as J,Ye as K,Ge as L,bt as M};
@@ -1 +1 @@
1
- import{o as i,p as o,q as r}from"./chunk-HKQTB65D.js";import{readFileSync as c,writeFileSync as l,existsSync as s}from"fs";import{createHash as a}from"crypto";var n="kanonak.lock";function f(e=n){return s(e)?o(c(e,"utf-8")):null}function k(e,t=n){e.lastUpdated=new Date().toISOString(),l(t,r(e),"utf-8")}function L(e){let t=a("sha256").update(e).digest("hex");return`${i}${t}`}export{f as a,k as b,L as c};
1
+ import{j as i,k as o,l as r}from"./chunk-MD4CAJIO.js";import{readFileSync as c,writeFileSync as l,existsSync as s}from"fs";import{createHash as a}from"crypto";var n="kanonak.lock";function f(e=n){return s(e)?o(c(e,"utf-8")):null}function k(e,t=n){e.lastUpdated=new Date().toISOString(),l(t,r(e),"utf-8")}function L(e){let t=a("sha256").update(e).digest("hex");return`${i}${t}`}export{f as a,k as b,L as c};
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as xt,b as Kt,c as Nt,d as Lt,e as z}from"./chunk-A3HRXFVX.js";import{a as Dn,b as jn,c as Hn}from"./chunk-SBO34ENZ.js";import{a as Pt,b as _t,c as wt,d as Hr,e as Fr,f as Tr,g as Wr,h as qr,i as Br,j as Le,k as Gr,l as Ie,m as Oe,n as zr,o as Qr,p as Xr,q as de,r as Yr,s as Ae}from"./chunk-PNBTIGX7.js";import{a as Jr}from"./chunk-ED35OFGD.js";import{a as $r,b as Ur,c as Mr,d as Q,e as Dr,f as jr,g as Ne,h as Zr,i as ei,j as ni,k as oi,l as ti}from"./chunk-ADSDFJUO.js";import{a as Po,b as _o,c as wo,d as xo,e as Ko,f as Wo,g as qo,h as Bo,i as Go}from"./chunk-7F2EAT5Y.js";import{a as No,b as Lo,c as Io,d as Oo,e as N,f as Ao,g as Vo,h as $o,i as Uo,j as Mo,k as Do,m as jo,n as qe,o as Be,p as Ge,q as ze,r as Qe,s as Ho,t as To}from"./chunk-HKQTB65D.js";import{a as Ot,b as At,c as Vt,d as $t,e as Ut,f as Mt}from"./chunk-GKIX3OD6.js";import{a as Dt,b as Ht}from"./chunk-D2X6J77P.js";import{a as Fo}from"./chunk-SC5M74NM.js";import{A as mr,B as hr,C as Sr,D as kr,E as gr,F as yr,G as Kr,H as Nr,I as Lr,J as Ir,K as Or,L as Ar,M as Vr,a as Ft,b as Tt,c as Wt,d as qt,e as Bt,f as Gt,g as zt,h as Qt,i as Xt,j as Yt,k as Jt,l as Zt,m as er,n as nr,o as or,p as tr,q as rr,r as ir,s as ar,t as sr,u as cr,v as dr,w as ur,x as lr,y as pr,z as fr}from"./chunk-O6SOU5Y2.js";import"./chunk-VORVR5BZ.js";import{c as $n,d as Er,e as br,f as Cr,g as Rr,i as vr,j as Pr,m as _r,o as Ke,q as Un,r as Mn,t as wr,u as xr}from"./chunk-TYVZXABI.js";import"./chunk-QHABFCRC.js";import{a as Se}from"./chunk-6VIUXP4N.js";import{a as we,g as $,h as xe,i as Rt,j as vt,k as H}from"./chunk-22DSABP6.js";import{a as F}from"./chunk-7JBKOJB4.js";import{a as jt}from"./chunk-PEJALHXK.js";import{$ as ae,A as un,B as ln,C as pn,D as fn,E as mn,F as hn,G as Sn,H as kn,I as gn,J as yn,K as be,L as En,M as bn,N as Cn,O as Rn,P as vn,Q as Pn,R as _n,S as wn,T as xn,U as Kn,V as Nn,W as Ln,X as In,Y as On,Z as Ce,_ as An,a as st,aa as Re,b as ct,ba as ve,c as W,ca as se,d as pt,da as B,e as ft,ea as G,g as mt,h as te,ha as ht,i as re,ia as St,j as Xe,k as q,ka as kt,l as ie,m as Ye,ma as gt,n as Je,na as k,o as ye,oa as _e,p as Ze,pa as yt,q as en,qa as Et,r as nn,s as on,t as Ee,ta as bt,u as tn,ua as Ct,v as rn,va as j,w as an,x as sn,y as cn,z as dn}from"./chunk-NUTHBBDZ.js";import{C as D,D as R,E as oe,F as S,G as T,H as ge,I as ce,J as Pe,L as Vn,a as zo,b as Qo,c as g,d as L,e as I,f as Yo,g as Jo,h as Zo,i as et,j as nt,k as ot,l as tt,m as rt,n as it,o as at,p as dt,q as ut,r as l,u as lt,v as M,w as ke,x as ne,z as _}from"./chunk-D4QGPMRW.js";import{a as Xo}from"./chunk-FUUTGGJS.js";import"./chunk-F67UH4FD.js";import{a as So,b as ko,c as ee,d as go,e as V,f as yo,g as Eo,h as bo,i as Co,j as Ro,k as vo}from"./chunk-QILEJIFU.js";import{a as It}from"./chunk-ODIECDN7.js";async function Fn(n){let e=await new H().parseKanonaks(n),t=await new z().reason(n);return{kind:"merged",catalog:e,reasoning:t}}function Tn(n,e){return{kind:"merged",catalog:n,reasoning:e}}async function Wn(n,e){let t=e??new Se(new F);return{kind:"standalone",catalog:await new H().parseKanonaks(new Vn(n,t))}}function O(n){return typeof n=="number"?n:void 0}function ri(n){if(!n)return;let e=l(n);if(e===l(kn))return"IRI";if(e===l(gn))return"BlankNode";if(e===l(yn))return"Literal"}function Bn(n){if(!n)return;let e=l(n);if(e===l(En))return"Violation";if(e===l(bn))return"Warning";if(e===l(Cn))return"Info"}function Gn(n,e,t,o){let r=S(e,ye);if(!r)return;let i={path:r},d=O(R(e,Ze)),s=O(R(e,en));d!==void 0&&(i.minCount=d),s!==void 0&&(i.maxCount=s);let a=O(R(e,an)),u=O(R(e,sn));a!==void 0&&(i.minLength=a),u!==void 0&&(i.maxLength=u);let c=O(R(e,cn)),p=O(R(e,dn));c!==void 0&&(i.minInclusive=c),p!==void 0&&(i.maxInclusive=p);let m=oe(e,tn);if(m!==void 0){let h=oe(e,rn);i.pattern=h!==void 0?{regex:m,flags:h}:{regex:m}}if(D(e,Ee)){let h=[],K=[];for(let{item:y}of ke(e,Ee))"literal"in y?h.push(y.value):y instanceof I&&K.push(y.subject);h.length>0&&(i.inValues=h),K.length>0&&(i.inRefs=K)}let f=S(e,nn);f&&(i.datatype=f);let A=S(e,on);A&&(i.classRef=A);let v=ri(S(e,Sn));v&&(i.nodeKind=v);let U=S(e,An);if(U&&(i.hasValue=U),D(e,ae)||D(e,Re)||D(e,ve)){let h={},K=O(R(e,Re)),y=O(R(e,ve));K!==void 0&&(h.minCount=K),y!==void 0&&(h.maxCount=y);let P=ii(n,e,o);"problem"in P?h.problem=P.problem:h.shape=P.shape,i.qualified=h}let x=oe(e,un);x!==void 0&&(i.message=x);let J=Bn(S(e,be))??t;return J&&(i.severity=J),i}function ii(n,e,t){let o=T(e,ae);if(o)return qn(n,o,void 0,t);let r=S(e,ae);if(!r)return{problem:"sh:qualifiedValueShape is missing"};let i=l(r);if(t.has(i))return{problem:`sh:qualifiedValueShape '${r.name}' leads back to itself (a cycle through named shapes)`};let d=_(n,r);return d?qn(n,d,i,t):{problem:`sh:qualifiedValueShape '${r.name}' does not resolve`}}function qn(n,e,t,o){let r=t?new Set([...o,t]):o,i=ne(e,q);if((ne(e,ie)||D(e,ye))&&!i){let a=Gn(n,e,void 0,r);return a?{shape:{kind:"property",constraint:a}}:{problem:"the qualified property shape has no sh:path"}}return e instanceof g&&!i?{problem:`sh:qualifiedValueShape '${e.name}' is not a shape`}:{shape:{kind:"node",shape:zn(n,e,r)}}}function zn(n,e,t){let o=Bn(S(e,be)),r={name:e instanceof g?e.name:"(inline shape)",uri:e instanceof g?k(e):void 0,targetClass:S(e,Ye),targetNodes:M(e,ln),targetSubjectsOf:M(e,pn),targetObjectsOf:M(e,fn),closed:R(e,mn)===!0,ignoredProperties:[],severity:o,properties:[]};r.ignoredProperties.push(...M(e,hn));for(let{item:i}of ke(e,Je)){let d;if(i instanceof L?d=i:i instanceof I&&(d=_(n,i.subject)),!d)continue;let s=Gn(n,d,o,t);s&&r.properties.push(s)}return r}function ue(n){let e=[];for(let t of n){if(!(t instanceof g)||!ne(t,q))continue;let o=k(t);e.push(zn(n,t,new Set(o?[l(o)]:[])))}return e}var b="kanonak.org/transformations",X="values";var le="allowed",$e="expected",E=n=>({type:`${b}/VarRef`,varName:n}),Ve=n=>({type:`${b}/IntegerLiteral`,integerLiteral:n}),ai=n=>({type:`${b}/DecimalLiteral`,decimalLiteral:n}),Qn=n=>Number.isInteger(n)?Ve(n):ai(n),Xn=n=>({type:`${b}/Count`,source:n}),Yn=(n,e)=>({type:`${b}/GreaterThanOrEqual`,compareLeft:n,compareRight:e}),Jn=(n,e)=>({type:`${b}/LessThanOrEqual`,compareLeft:n,compareRight:e});function Ue(n,e){if(!e||e.length===0)return n;let t=new Set(["i","m","s"]),o=[...new Set(e.split(""))];if(o.filter(i=>!t.has(i)).length>0)throw new Error(`sh:flags '${e}' is outside the pinned regex subset (supported: i, m, s)`);return`(?${o.sort().join("")})${n}`}function pe(n){let e=[];return n.minCount!==void 0&&e.push({component:"minCount",per:"node",expr:Yn(Xn(E(X)),Ve(n.minCount))}),n.maxCount!==void 0&&e.push({component:"maxCount",per:"node",expr:Jn(Xn(E(X)),Ve(n.maxCount))}),n.hasValue!==void 0&&e.push({component:"hasValue",per:"node",expr:{type:`${b}/Contains`,haystack:E(X),needle:E($e)}}),(n.inValues!==void 0||n.inRefs!==void 0)&&e.push({component:"in",per:"value",expr:{type:`${b}/Contains`,haystack:E(le),needle:E("v")}}),n.pattern!==void 0&&e.push({component:"pattern",per:"value",expr:{type:`${b}/Matches`,matchSource:E("v"),pattern:Ue(n.pattern.regex,n.pattern.flags)}}),n.minLength!==void 0&&e.push({component:"minLength",per:"value",expr:{type:`${b}/Matches`,matchSource:E("v"),pattern:`(?s)^.{${n.minLength},}$`}}),n.maxLength!==void 0&&e.push({component:"maxLength",per:"value",expr:{type:`${b}/Matches`,matchSource:E("v"),pattern:`(?s)^.{0,${n.maxLength}}$`}}),n.minInclusive!==void 0&&e.push({component:"minInclusive",per:"value",expr:Yn(E("v"),Qn(n.minInclusive))}),n.maxInclusive!==void 0&&e.push({component:"maxInclusive",per:"value",expr:Jn(E("v"),Qn(n.maxInclusive))}),e}import{evaluate as ci,ExpressionError as di}from"@kanonak-protocol/expression";function eo(n,e){let t=ui(e)?e:ue(e),o=[],r=n.catalog.filter(s=>s instanceof g).map(fe),i=new Map;li(r,i);let d={scope:n,membership:new Me(n),embeddedFocus:i};for(let s of t)for(let a of pi(d,s,r))oo(d,s,a,o);return{conforms:!o.some(s=>s.severity==="Violation"),results:o}}function ui(n){return n.length>0&&!(n[0]instanceof Object&&"statement"in n[0])&&typeof n[0].name=="string"&&"properties"in n[0]}function no(n){let e=n.predicate;return e instanceof I?e:void 0}function fe(n){return{node:n,key:Pe(n),uri:k(n),label:n.name}}function je(n,e){return{node:n,key:e,label:e.includes("#")?e.slice(e.indexOf("#")):e}}function li(n,e){we(n.map(t=>t.node),({kanonak:t,address:o})=>{t instanceof L&&!e.has(t)&&e.set(t,je(t,o))})}var Me=class{constructor(e){this.scope=e}scope;ancestors=new Map;isInstance(e,t){let o=l(t);return e.some(r=>l(r)===o||this.ancestorsOf(r).has(o))}ancestorsOf(e){let t=e.version&&typeof e.version.major=="number"?`${l(e)}@${V(e.version)}`:l(e),o=this.ancestors.get(t);return o||(o=this.scope.reasoning?new Set(this.scope.reasoning.getSuperclasses(e)):new Set(_e(this.scope.catalog,e).map(r=>l(r))),this.ancestors.set(t,o)),o}};function pi(n,e,t){let{scope:o}=n,r=new Map,i=s=>{r.set(s.key,s)},d=()=>[...t,...n.embeddedFocus.values()];if(e.targetClass){let s=e.targetClass;if(o.reasoning){let a=new Set(o.reasoning.getInstancesOfClass(s));for(let u of t)u.uri&&a.has(l(u.uri))&&i(u)}else for(let a of t)n.membership.isInstance(j(a.node),s)&&i(a);for(let a of n.embeddedFocus.values())n.membership.isInstance(j(a.node),s)&&i(a)}for(let s of e.targetNodes){let a=_(o.catalog,s);a instanceof g&&i(fe(a))}for(let s of e.targetSubjectsOf){let a=l(s);for(let u of d())u.node.statement.some(c=>{let p=no(c);return p&&l(p.subject)===a})&&i(u)}for(let s of e.targetObjectsOf)for(let a of d())for(let u of ce(a.node,s,o.catalog,a.key))u.kind==="subject"?i(fe(u.node)):u.kind==="embedded"&&i(n.embeddedFocus.get(u.node)??je(u.node,u.address));return[...r.values()]}function fi(n,e,t){return e.node?ce(e.node,t,n.scope.catalog,e.key).map(o=>mi(n,o)):[]}function mi(n,e){switch(e.kind){case"subject":return{kernel:{ref:l(e.uri)},kind:"reference",ref:e.uri,subject:e.node};case"unresolved":return{kernel:{ref:l(e.uri)},kind:"reference",ref:e.uri};case"embedded":{let t=n.embeddedFocus.get(e.node)??je(e.node,e.address);return{kernel:{ref:t.key},kind:"embedded",embedded:t}}case"literal":return typeof e.value=="boolean"?{kernel:e.value?1:0,kind:"boolean",literal:e.value}:{kernel:e.value,kind:typeof e.value=="number"?"number":"string",literal:e.value}}}function oo(n,e,t,o){for(let r of e.properties)ro(n,e,t,r,o);e.closed&&Pi(e,t,o)}function De(n,e,t,o,r={},i){return{focusNode:e.key,focusUri:e.uri,constraintComponent:t,severity:i??to(n),message:o,sourceShape:n.name,sourceShapeUri:n.uri,...r}}function to(n){return n.severity??"Violation"}var hi={minCount:Rn,maxCount:vn,hasValue:se,in:wn,pattern:xn,minLength:Kn,maxLength:Nn,minInclusive:Ln,maxInclusive:In};function ro(n,e,t,o,r){let i=fi(n,t,o.path),d=o.severity??to(e),s=o.path.name,a=[...(o.inValues??[]).map(c=>typeof c=="boolean"?c?1:0:c),...(o.inRefs??[]).map(c=>({ref:l(c)}))],u=(c,p,m)=>{let f=De(e,t,c,o.message??p,{resultPath:o.path,value:m?.literal,valueRef:m?.ref},d);return r.push(f),f};for(let c of pe(o)){let p=hi[c.component];if(c.per==="node"){let m={[X]:i.map(f=>f.kernel),[le]:a};o.hasValue&&(m[$e]={ref:l(o.hasValue)}),Zn(c,m)||u(p,Si(c,s,o,i.length));continue}for(let m of i){if((c.component==="pattern"||c.component==="minLength"||c.component==="maxLength")&&m.kind!=="string"){u(p,`'${s}' value is not a string; ${c.component} applies to string values.`,m);continue}Zn(c,{v:m.kernel,[le]:a})||u(p,bi(c,s,o,m),m)}}if(o.nodeKind)for(let c of i)Ci(o.nodeKind,c)||u(On,`'${s}' value is ${c.kind}; nodeKind requires ${o.nodeKind}.`,c);if(o.datatype)for(let c of i){let p=Ri(o.datatype,c);p&&u(Pn,`'${s}' ${p}`,c)}if(o.classRef)for(let c of i){let p=vi(n,o.classRef,c);p&&u(_n,`'${s}' ${p}`,c)}o.qualified&&ki(n,o,i,s,u)}function Si(n,e,t,o){switch(n.component){case"minCount":return`'${e}' has ${o} value(s); minCount is ${t.minCount}.`;case"maxCount":return`'${e}' has ${o} value(s); maxCount is ${t.maxCount}.`;case"hasValue":return`'${e}' has no value equal to ${t.hasValue?l(t.hasValue):"(unset)"}.`;default:return`'${e}' violates ${n.component}.`}}function ki(n,e,t,o,r){let i=e.qualified,d=i.maxCount!==void 0?G:B,s=(u,c)=>{io.add(r(d,u,c))};if(!i.shape){s(`'${o}' qualified value shape cannot be evaluated: ${i.problem??"it could not be built"}.`);return}let a=0;for(let u of t){let c=u.ref?l(u.ref):u.embedded?u.embedded.label:JSON.stringify(u.literal),p=gi(n,u);if(!p){s(`'${o}' value ${c} does not resolve in this scope; whether it conforms to the qualified shape cannot be decided.`,u);continue}let m=Ei(n,i.shape,p);if(m.kind==="undecided"){s(`'${o}' value ${c}: whether it conforms to the qualified shape cannot be decided \u2014 ${m.reason}`,u);continue}m.kind==="conforms"&&a++}i.minCount!==void 0&&a<i.minCount&&r(B,`'${o}' has ${a} value(s) that conform to the qualified shape; qualifiedMinCount is ${i.minCount}.`),i.maxCount!==void 0&&a>i.maxCount&&r(G,`'${o}' has ${a} value(s) that conform to the qualified shape; qualifiedMaxCount is ${i.maxCount}.`)}function gi(n,e){switch(e.kind){case"reference":return e.subject?fe(e.subject):void 0;case"embedded":return e.embedded;default:{let t=JSON.stringify(e.literal);return{key:t,label:t}}}}var yi={name:"(qualified value shape)",targetNodes:[],targetSubjectsOf:[],targetObjectsOf:[],closed:!1,ignoredProperties:[],properties:[]},io=new WeakSet;function Ei(n,e,t){let o=[];e.kind==="property"?ro(n,yi,t,e.constraint,o):oo(n,e.shape,t,o);let r=o.find(i=>io.has(i));return r?{kind:"undecided",reason:r.message}:o.length===0?{kind:"conforms"}:{kind:"fails"}}function bi(n,e,t,o){let r=o.ref?l(o.ref):o.embedded?o.embedded.label:JSON.stringify(o.literal);switch(n.component){case"in":return`'${e}' value ${r} is not in the permitted set.`;case"pattern":return`'${e}' value ${r} does not match pattern ${t.pattern?.regex}.`;case"minLength":return`'${e}' value ${r} is shorter than minLength ${t.minLength}.`;case"maxLength":return`'${e}' value ${r} is longer than maxLength ${t.maxLength}.`;case"minInclusive":return`'${e}' value ${r} is below minInclusive ${t.minInclusive} (or not numeric).`;case"maxInclusive":return`'${e}' value ${r} is above maxInclusive ${t.maxInclusive} (or not numeric).`;default:return`'${e}' value ${r} violates ${n.component}.`}}function Zn(n,e){let t=o=>{let r=o.varName;if(o.type==="kanonak.org/transformations/VarRef"&&typeof r=="string"&&r in e)return e[r];throw new di(`Conformance lowering produced an unexpected leaf '${o.type}'`)};return ci(n.expr,void 0,t)===1}function Ci(n,e){switch(n){case"IRI":return e.kind==="reference";case"BlankNode":return e.kind==="embedded";case"Literal":return e.kind==="string"||e.kind==="number"||e.kind==="boolean"}}function Ri(n,e){if(e.kind==="reference"||e.kind==="embedded")return`value is a ${e.kind}; sh:datatype requires a literal of ${n.name}.`;let t=xe(n);if(t!==void 0)switch(t){case $.Boolean:return e.kind==="boolean"?void 0:`value is not a boolean (${n.name}).`;case $.Integer:return e.kind!=="number"?`value is not a number (${n.name}).`:Number.isInteger(e.literal)?void 0:`value is not an integer (${n.name}).`;case $.Decimal:case $.Double:case $.Float:return e.kind==="number"?void 0:`value is not a number (${n.name}).`;default:return e.kind==="string"?void 0:`value is not a string-carried literal (${n.name}).`}}function vi(n,e,t){if(t.kind==="embedded"&&t.embedded?.node){let r=j(t.embedded.node);return r.length===0?`value ${t.embedded.label} has no type; sh:class requires an instance of ${e.name}.`:n.membership.isInstance(r,e)?void 0:`value ${t.embedded.label} is not an instance of ${e.name}.`}if(t.kind!=="reference"||!t.ref)return`value is not a reference; sh:class requires an instance of ${e.name}.`;if(n.scope.reasoning)return n.scope.reasoning.isInstanceOf(t.ref,e)?void 0:`value ${l(t.ref)} is not an instance of ${e.name}.`;let o=t.subject;return o?n.membership.isInstance(j(o),e)?void 0:`value ${l(t.ref)} is not an instance of ${e.name}.`:`value ${l(t.ref)} does not resolve in this scope (sh:class ${e.name}).`}function Pi(n,e,t){if(!e.node)return;let o=new Set([...n.properties.map(i=>l(i.path)),...n.ignoredProperties.map(i=>l(i))]),r=new Set;for(let i of e.node.statement){let d=no(i);if(!d)continue;let s=l(d.subject);o.has(s)||r.has(s)||(r.add(s),t.push(De(n,e,Ce,`'${e.label}' carries undeclared property '${d.subject.name}' (closed shape).`,{resultPath:d.subject})))}for(let i of e.node.unresolvedPredicates)r.has(i.key)||(r.add(i.key),t.push(De(n,e,Ce,`'${e.label}' carries unresolvable property '${i.key}' (closed shape).`,{value:i.key})))}var _i="1.1.0",wi=new Set([se,B,G].map(n=>n.name));async function ao(n){let e=new Q(n.repository),t=e.imports(),o=n.result.results.some(a=>wi.has(a.constraintComponent.name))?"1.2.0":_i,r=t.ensure(te,re,o,"sh"),i=(a,u)=>a&&a.version&&typeof a.version.major=="number"?`${t.ensure(a.publisher,a.package_,V(a.version),a.package_)}.${a.name}`:u,d={},s=[];return n.result.results.forEach((a,u)=>{let c=`result-${u+1}`;s.push(c);let p={type:`${r}.ValidationResult`,[`${r}.focusNode`]:i(a.focusUri,a.focusNode),[`${r}.resultMessage`]:a.message,[`${r}.resultSeverity`]:`${r}.${a.severity}`,[`${r}.sourceConstraintComponent`]:`${r}.${a.constraintComponent.name}`};a.resultPath&&(p[`${r}.resultPath`]=i(a.resultPath,l(a.resultPath))),a.sourceShapeUri&&(p[`${r}.sourceShape`]=i(a.sourceShapeUri,a.sourceShape)),a.valueRef?p[`${r}.value`]=i(a.valueRef,l(a.valueRef)):a.value!==void 0&&(p[`${r}.value`]=a.value),d[c]=p}),d.report={type:`${r}.ValidationReport`,[`${r}.conforms`]:n.result.conforms,...s.length>0?{[`${r}.result`]:s}:{}},e.buildContentAddressed({publisher:n.publisher,book:t,body:d,...n.header!==void 0?{header:n.header}:{},contentHashProperty:"contentHash"})}import{VersionOperator as Cs}from"@kanonak-protocol/types/document/models/enums";import{spawn as xi}from"child_process";var co=12e4,Ki=4096,Y=class{argv;interactive;timeoutMs;stderr;now;constructor(e){this.argv=uo(e.command),this.interactive=e.interactive??!1,this.timeoutMs=e.timeoutMs??co,this.stderr=e.stderr??process.stderr,this.now=e.nowSeconds??(()=>Date.now()/1e3)}get command(){return this.argv.join(" ")}async get(e){let t=await this.run("get",this.wireRequest("get",e)),o=Ie(e,t,this.now());if(!o.ok)throw new N(`credential helper '${this.command}' answered get for ${e.resource} outside the protocol (${o.problem}): ${o.message}`);return o.answer}async erase(e){let t=await this.run("erase",{...this.wireRequest("erase",e),scope:e.scope}),o=Oe(t);if(!o.ok)throw new N(`credential helper '${this.command}' answered erase for ${e.resource} outside the protocol (${o.problem}): ${o.message}`)}wireRequest(e,t){let o={version:Le,operation:e,resource:t.resource,method:t.method};return t.challenges&&(o.challenges=t.challenges),o.interactive=this.interactive,o}run(e,t){let o=`credential helper '${this.command}' ${e}`;return new Promise((r,i)=>{let d=!1,s=f=>{d||(d=!0,f())},a;try{a=xi(this.argv[0],[...this.argv.slice(1),e],{stdio:["pipe","pipe","pipe"],shell:!1,windowsHide:!0})}catch(f){i(so(o,f));return}let u=[],c="",p=!1,m=setTimeout(()=>{p=!0,a.kill()},this.timeoutMs);a.stdout.on("data",f=>u.push(f)),a.stderr.on("data",f=>{this.stderr.write(f),c=(c+f.toString("utf8")).slice(-Ki)}),a.on("error",f=>{clearTimeout(m),s(()=>i(so(o,f)))}),a.on("close",(f,A)=>{clearTimeout(m);let v=c.trim()?`: ${c.trim()}`:"";if(p){s(()=>i(new N(`${o} did not finish within ${Math.round(this.timeoutMs/1e3)}s${v}`)));return}if(f!==0){let x=f!==null?`exit ${f}`:`signal ${A}`;s(()=>i(new N(`${o} failed (${x})${v}`)));return}let U=Buffer.concat(u).toString("utf8").trim();try{let x=JSON.parse(U);s(()=>r(x))}catch{s(()=>i(new N(`${o} exited 0 without printing one JSON answer${v}`)))}}),a.stdin.on("error",()=>{}),a.stdin.end(`${JSON.stringify(t)}
1
+ import{a as xt,b as Kt,c as Nt,d as Lt,e as z}from"./chunk-A3HRXFVX.js";import{a as Dn,b as jn,c as Hn}from"./chunk-R4LVLXAC.js";import{a as Pt,b as _t,c as wt,d as Hr,e as Fr,f as Tr,g as Wr,h as qr,i as Br,j as Le,k as Gr,l as Ie,m as Oe,n as zr,o as Qr,p as Xr,q as de,r as Yr,s as Ae}from"./chunk-EKD2ZLKQ.js";import{a as Jr}from"./chunk-ED35OFGD.js";import{a as $r,b as Ur,c as Mr,d as Q,e as Dr,f as jr,g as Ne,h as Zr,i as ei,j as ni,k as oi,l as ti}from"./chunk-ADSDFJUO.js";import{a as Po,b as _o,c as wo,d as xo,e as Ko,f as Wo,g as qo,h as Bo,i as Go}from"./chunk-66GZUKYS.js";import{a as Ao,b as Vo,c as $o,d as Uo,e as Mo,f as Do,h as jo,i as qe,j as Be,k as Ge,l as ze,m as Qe,n as Ho,o as To}from"./chunk-MD4CAJIO.js";import{a as Ot,b as At,c as Vt,d as $t,e as Ut,f as Mt}from"./chunk-GKIX3OD6.js";import{a as Dt,b as Ht}from"./chunk-D2X6J77P.js";import{a as Fo}from"./chunk-SC5M74NM.js";import{A as mr,B as hr,C as Sr,D as kr,E as gr,F as yr,G as Kr,H as Nr,I as Lr,J as Ir,K as Or,L as Ar,M as Vr,a as Ft,b as Tt,c as Wt,d as qt,e as Bt,f as Gt,g as zt,h as Qt,i as Xt,j as Yt,k as Jt,l as Zt,m as er,n as nr,o as or,p as tr,q as rr,r as ir,s as ar,t as sr,u as cr,v as dr,w as ur,x as lr,y as pr,z as fr}from"./chunk-MWJSYONH.js";import"./chunk-VORVR5BZ.js";import{c as $n,d as Er,e as br,f as Cr,g as Rr,i as vr,j as Pr,m as _r,o as Ke,q as Un,r as Mn,t as wr,u as xr}from"./chunk-TYVZXABI.js";import"./chunk-QHABFCRC.js";import{a as No,b as Lo,c as Io,d as Oo,e as N}from"./chunk-5FVUBF7N.js";import{a as Se}from"./chunk-6VIUXP4N.js";import{a as we,g as $,h as xe,i as Rt,j as vt,k as H}from"./chunk-22DSABP6.js";import{a as F}from"./chunk-7JBKOJB4.js";import{a as jt}from"./chunk-PEJALHXK.js";import{$ as ae,A as un,B as ln,C as pn,D as fn,E as mn,F as hn,G as Sn,H as kn,I as gn,J as yn,K as be,L as En,M as bn,N as Cn,O as Rn,P as vn,Q as Pn,R as _n,S as wn,T as xn,U as Kn,V as Nn,W as Ln,X as In,Y as On,Z as Ce,_ as An,a as st,aa as Re,b as ct,ba as ve,c as W,ca as se,d as pt,da as B,e as ft,ea as G,g as mt,h as te,ha as ht,i as re,ia as St,j as Xe,k as q,ka as kt,l as ie,m as Ye,ma as gt,n as Je,na as k,o as ye,oa as _e,p as Ze,pa as yt,q as en,qa as Et,r as nn,s as on,t as Ee,ta as bt,u as tn,ua as Ct,v as rn,va as j,w as an,x as sn,y as cn,z as dn}from"./chunk-NUTHBBDZ.js";import{C as D,D as R,E as oe,F as S,G as T,H as ge,I as ce,J as Pe,L as Vn,a as zo,b as Qo,c as g,d as L,e as I,f as Yo,g as Jo,h as Zo,i as et,j as nt,k as ot,l as tt,m as rt,n as it,o as at,p as dt,q as ut,r as l,u as lt,v as M,w as ke,x as ne,z as _}from"./chunk-D4QGPMRW.js";import{a as Xo}from"./chunk-FUUTGGJS.js";import"./chunk-F67UH4FD.js";import{a as So,b as ko,c as ee,d as go,e as V,f as yo,g as Eo,h as bo,i as Co,j as Ro,k as vo}from"./chunk-QILEJIFU.js";import{a as It}from"./chunk-ODIECDN7.js";async function Fn(n){let e=await new H().parseKanonaks(n),t=await new z().reason(n);return{kind:"merged",catalog:e,reasoning:t}}function Tn(n,e){return{kind:"merged",catalog:n,reasoning:e}}async function Wn(n,e){let t=e??new Se(new F);return{kind:"standalone",catalog:await new H().parseKanonaks(new Vn(n,t))}}function O(n){return typeof n=="number"?n:void 0}function ri(n){if(!n)return;let e=l(n);if(e===l(kn))return"IRI";if(e===l(gn))return"BlankNode";if(e===l(yn))return"Literal"}function Bn(n){if(!n)return;let e=l(n);if(e===l(En))return"Violation";if(e===l(bn))return"Warning";if(e===l(Cn))return"Info"}function Gn(n,e,t,o){let r=S(e,ye);if(!r)return;let i={path:r},d=O(R(e,Ze)),s=O(R(e,en));d!==void 0&&(i.minCount=d),s!==void 0&&(i.maxCount=s);let a=O(R(e,an)),u=O(R(e,sn));a!==void 0&&(i.minLength=a),u!==void 0&&(i.maxLength=u);let c=O(R(e,cn)),p=O(R(e,dn));c!==void 0&&(i.minInclusive=c),p!==void 0&&(i.maxInclusive=p);let m=oe(e,tn);if(m!==void 0){let h=oe(e,rn);i.pattern=h!==void 0?{regex:m,flags:h}:{regex:m}}if(D(e,Ee)){let h=[],K=[];for(let{item:y}of ke(e,Ee))"literal"in y?h.push(y.value):y instanceof I&&K.push(y.subject);h.length>0&&(i.inValues=h),K.length>0&&(i.inRefs=K)}let f=S(e,nn);f&&(i.datatype=f);let A=S(e,on);A&&(i.classRef=A);let v=ri(S(e,Sn));v&&(i.nodeKind=v);let U=S(e,An);if(U&&(i.hasValue=U),D(e,ae)||D(e,Re)||D(e,ve)){let h={},K=O(R(e,Re)),y=O(R(e,ve));K!==void 0&&(h.minCount=K),y!==void 0&&(h.maxCount=y);let P=ii(n,e,o);"problem"in P?h.problem=P.problem:h.shape=P.shape,i.qualified=h}let x=oe(e,un);x!==void 0&&(i.message=x);let J=Bn(S(e,be))??t;return J&&(i.severity=J),i}function ii(n,e,t){let o=T(e,ae);if(o)return qn(n,o,void 0,t);let r=S(e,ae);if(!r)return{problem:"sh:qualifiedValueShape is missing"};let i=l(r);if(t.has(i))return{problem:`sh:qualifiedValueShape '${r.name}' leads back to itself (a cycle through named shapes)`};let d=_(n,r);return d?qn(n,d,i,t):{problem:`sh:qualifiedValueShape '${r.name}' does not resolve`}}function qn(n,e,t,o){let r=t?new Set([...o,t]):o,i=ne(e,q);if((ne(e,ie)||D(e,ye))&&!i){let a=Gn(n,e,void 0,r);return a?{shape:{kind:"property",constraint:a}}:{problem:"the qualified property shape has no sh:path"}}return e instanceof g&&!i?{problem:`sh:qualifiedValueShape '${e.name}' is not a shape`}:{shape:{kind:"node",shape:zn(n,e,r)}}}function zn(n,e,t){let o=Bn(S(e,be)),r={name:e instanceof g?e.name:"(inline shape)",uri:e instanceof g?k(e):void 0,targetClass:S(e,Ye),targetNodes:M(e,ln),targetSubjectsOf:M(e,pn),targetObjectsOf:M(e,fn),closed:R(e,mn)===!0,ignoredProperties:[],severity:o,properties:[]};r.ignoredProperties.push(...M(e,hn));for(let{item:i}of ke(e,Je)){let d;if(i instanceof L?d=i:i instanceof I&&(d=_(n,i.subject)),!d)continue;let s=Gn(n,d,o,t);s&&r.properties.push(s)}return r}function ue(n){let e=[];for(let t of n){if(!(t instanceof g)||!ne(t,q))continue;let o=k(t);e.push(zn(n,t,new Set(o?[l(o)]:[])))}return e}var b="kanonak.org/transformations",X="values";var le="allowed",$e="expected",E=n=>({type:`${b}/VarRef`,varName:n}),Ve=n=>({type:`${b}/IntegerLiteral`,integerLiteral:n}),ai=n=>({type:`${b}/DecimalLiteral`,decimalLiteral:n}),Qn=n=>Number.isInteger(n)?Ve(n):ai(n),Xn=n=>({type:`${b}/Count`,source:n}),Yn=(n,e)=>({type:`${b}/GreaterThanOrEqual`,compareLeft:n,compareRight:e}),Jn=(n,e)=>({type:`${b}/LessThanOrEqual`,compareLeft:n,compareRight:e});function Ue(n,e){if(!e||e.length===0)return n;let t=new Set(["i","m","s"]),o=[...new Set(e.split(""))];if(o.filter(i=>!t.has(i)).length>0)throw new Error(`sh:flags '${e}' is outside the pinned regex subset (supported: i, m, s)`);return`(?${o.sort().join("")})${n}`}function pe(n){let e=[];return n.minCount!==void 0&&e.push({component:"minCount",per:"node",expr:Yn(Xn(E(X)),Ve(n.minCount))}),n.maxCount!==void 0&&e.push({component:"maxCount",per:"node",expr:Jn(Xn(E(X)),Ve(n.maxCount))}),n.hasValue!==void 0&&e.push({component:"hasValue",per:"node",expr:{type:`${b}/Contains`,haystack:E(X),needle:E($e)}}),(n.inValues!==void 0||n.inRefs!==void 0)&&e.push({component:"in",per:"value",expr:{type:`${b}/Contains`,haystack:E(le),needle:E("v")}}),n.pattern!==void 0&&e.push({component:"pattern",per:"value",expr:{type:`${b}/Matches`,matchSource:E("v"),pattern:Ue(n.pattern.regex,n.pattern.flags)}}),n.minLength!==void 0&&e.push({component:"minLength",per:"value",expr:{type:`${b}/Matches`,matchSource:E("v"),pattern:`(?s)^.{${n.minLength},}$`}}),n.maxLength!==void 0&&e.push({component:"maxLength",per:"value",expr:{type:`${b}/Matches`,matchSource:E("v"),pattern:`(?s)^.{0,${n.maxLength}}$`}}),n.minInclusive!==void 0&&e.push({component:"minInclusive",per:"value",expr:Yn(E("v"),Qn(n.minInclusive))}),n.maxInclusive!==void 0&&e.push({component:"maxInclusive",per:"value",expr:Jn(E("v"),Qn(n.maxInclusive))}),e}import{evaluate as ci,ExpressionError as di}from"@kanonak-protocol/expression";function eo(n,e){let t=ui(e)?e:ue(e),o=[],r=n.catalog.filter(s=>s instanceof g).map(fe),i=new Map;li(r,i);let d={scope:n,membership:new Me(n),embeddedFocus:i};for(let s of t)for(let a of pi(d,s,r))oo(d,s,a,o);return{conforms:!o.some(s=>s.severity==="Violation"),results:o}}function ui(n){return n.length>0&&!(n[0]instanceof Object&&"statement"in n[0])&&typeof n[0].name=="string"&&"properties"in n[0]}function no(n){let e=n.predicate;return e instanceof I?e:void 0}function fe(n){return{node:n,key:Pe(n),uri:k(n),label:n.name}}function je(n,e){return{node:n,key:e,label:e.includes("#")?e.slice(e.indexOf("#")):e}}function li(n,e){we(n.map(t=>t.node),({kanonak:t,address:o})=>{t instanceof L&&!e.has(t)&&e.set(t,je(t,o))})}var Me=class{constructor(e){this.scope=e}scope;ancestors=new Map;isInstance(e,t){let o=l(t);return e.some(r=>l(r)===o||this.ancestorsOf(r).has(o))}ancestorsOf(e){let t=e.version&&typeof e.version.major=="number"?`${l(e)}@${V(e.version)}`:l(e),o=this.ancestors.get(t);return o||(o=this.scope.reasoning?new Set(this.scope.reasoning.getSuperclasses(e)):new Set(_e(this.scope.catalog,e).map(r=>l(r))),this.ancestors.set(t,o)),o}};function pi(n,e,t){let{scope:o}=n,r=new Map,i=s=>{r.set(s.key,s)},d=()=>[...t,...n.embeddedFocus.values()];if(e.targetClass){let s=e.targetClass;if(o.reasoning){let a=new Set(o.reasoning.getInstancesOfClass(s));for(let u of t)u.uri&&a.has(l(u.uri))&&i(u)}else for(let a of t)n.membership.isInstance(j(a.node),s)&&i(a);for(let a of n.embeddedFocus.values())n.membership.isInstance(j(a.node),s)&&i(a)}for(let s of e.targetNodes){let a=_(o.catalog,s);a instanceof g&&i(fe(a))}for(let s of e.targetSubjectsOf){let a=l(s);for(let u of d())u.node.statement.some(c=>{let p=no(c);return p&&l(p.subject)===a})&&i(u)}for(let s of e.targetObjectsOf)for(let a of d())for(let u of ce(a.node,s,o.catalog,a.key))u.kind==="subject"?i(fe(u.node)):u.kind==="embedded"&&i(n.embeddedFocus.get(u.node)??je(u.node,u.address));return[...r.values()]}function fi(n,e,t){return e.node?ce(e.node,t,n.scope.catalog,e.key).map(o=>mi(n,o)):[]}function mi(n,e){switch(e.kind){case"subject":return{kernel:{ref:l(e.uri)},kind:"reference",ref:e.uri,subject:e.node};case"unresolved":return{kernel:{ref:l(e.uri)},kind:"reference",ref:e.uri};case"embedded":{let t=n.embeddedFocus.get(e.node)??je(e.node,e.address);return{kernel:{ref:t.key},kind:"embedded",embedded:t}}case"literal":return typeof e.value=="boolean"?{kernel:e.value?1:0,kind:"boolean",literal:e.value}:{kernel:e.value,kind:typeof e.value=="number"?"number":"string",literal:e.value}}}function oo(n,e,t,o){for(let r of e.properties)ro(n,e,t,r,o);e.closed&&Pi(e,t,o)}function De(n,e,t,o,r={},i){return{focusNode:e.key,focusUri:e.uri,constraintComponent:t,severity:i??to(n),message:o,sourceShape:n.name,sourceShapeUri:n.uri,...r}}function to(n){return n.severity??"Violation"}var hi={minCount:Rn,maxCount:vn,hasValue:se,in:wn,pattern:xn,minLength:Kn,maxLength:Nn,minInclusive:Ln,maxInclusive:In};function ro(n,e,t,o,r){let i=fi(n,t,o.path),d=o.severity??to(e),s=o.path.name,a=[...(o.inValues??[]).map(c=>typeof c=="boolean"?c?1:0:c),...(o.inRefs??[]).map(c=>({ref:l(c)}))],u=(c,p,m)=>{let f=De(e,t,c,o.message??p,{resultPath:o.path,value:m?.literal,valueRef:m?.ref},d);return r.push(f),f};for(let c of pe(o)){let p=hi[c.component];if(c.per==="node"){let m={[X]:i.map(f=>f.kernel),[le]:a};o.hasValue&&(m[$e]={ref:l(o.hasValue)}),Zn(c,m)||u(p,Si(c,s,o,i.length));continue}for(let m of i){if((c.component==="pattern"||c.component==="minLength"||c.component==="maxLength")&&m.kind!=="string"){u(p,`'${s}' value is not a string; ${c.component} applies to string values.`,m);continue}Zn(c,{v:m.kernel,[le]:a})||u(p,bi(c,s,o,m),m)}}if(o.nodeKind)for(let c of i)Ci(o.nodeKind,c)||u(On,`'${s}' value is ${c.kind}; nodeKind requires ${o.nodeKind}.`,c);if(o.datatype)for(let c of i){let p=Ri(o.datatype,c);p&&u(Pn,`'${s}' ${p}`,c)}if(o.classRef)for(let c of i){let p=vi(n,o.classRef,c);p&&u(_n,`'${s}' ${p}`,c)}o.qualified&&ki(n,o,i,s,u)}function Si(n,e,t,o){switch(n.component){case"minCount":return`'${e}' has ${o} value(s); minCount is ${t.minCount}.`;case"maxCount":return`'${e}' has ${o} value(s); maxCount is ${t.maxCount}.`;case"hasValue":return`'${e}' has no value equal to ${t.hasValue?l(t.hasValue):"(unset)"}.`;default:return`'${e}' violates ${n.component}.`}}function ki(n,e,t,o,r){let i=e.qualified,d=i.maxCount!==void 0?G:B,s=(u,c)=>{io.add(r(d,u,c))};if(!i.shape){s(`'${o}' qualified value shape cannot be evaluated: ${i.problem??"it could not be built"}.`);return}let a=0;for(let u of t){let c=u.ref?l(u.ref):u.embedded?u.embedded.label:JSON.stringify(u.literal),p=gi(n,u);if(!p){s(`'${o}' value ${c} does not resolve in this scope; whether it conforms to the qualified shape cannot be decided.`,u);continue}let m=Ei(n,i.shape,p);if(m.kind==="undecided"){s(`'${o}' value ${c}: whether it conforms to the qualified shape cannot be decided \u2014 ${m.reason}`,u);continue}m.kind==="conforms"&&a++}i.minCount!==void 0&&a<i.minCount&&r(B,`'${o}' has ${a} value(s) that conform to the qualified shape; qualifiedMinCount is ${i.minCount}.`),i.maxCount!==void 0&&a>i.maxCount&&r(G,`'${o}' has ${a} value(s) that conform to the qualified shape; qualifiedMaxCount is ${i.maxCount}.`)}function gi(n,e){switch(e.kind){case"reference":return e.subject?fe(e.subject):void 0;case"embedded":return e.embedded;default:{let t=JSON.stringify(e.literal);return{key:t,label:t}}}}var yi={name:"(qualified value shape)",targetNodes:[],targetSubjectsOf:[],targetObjectsOf:[],closed:!1,ignoredProperties:[],properties:[]},io=new WeakSet;function Ei(n,e,t){let o=[];e.kind==="property"?ro(n,yi,t,e.constraint,o):oo(n,e.shape,t,o);let r=o.find(i=>io.has(i));return r?{kind:"undecided",reason:r.message}:o.length===0?{kind:"conforms"}:{kind:"fails"}}function bi(n,e,t,o){let r=o.ref?l(o.ref):o.embedded?o.embedded.label:JSON.stringify(o.literal);switch(n.component){case"in":return`'${e}' value ${r} is not in the permitted set.`;case"pattern":return`'${e}' value ${r} does not match pattern ${t.pattern?.regex}.`;case"minLength":return`'${e}' value ${r} is shorter than minLength ${t.minLength}.`;case"maxLength":return`'${e}' value ${r} is longer than maxLength ${t.maxLength}.`;case"minInclusive":return`'${e}' value ${r} is below minInclusive ${t.minInclusive} (or not numeric).`;case"maxInclusive":return`'${e}' value ${r} is above maxInclusive ${t.maxInclusive} (or not numeric).`;default:return`'${e}' value ${r} violates ${n.component}.`}}function Zn(n,e){let t=o=>{let r=o.varName;if(o.type==="kanonak.org/transformations/VarRef"&&typeof r=="string"&&r in e)return e[r];throw new di(`Conformance lowering produced an unexpected leaf '${o.type}'`)};return ci(n.expr,void 0,t)===1}function Ci(n,e){switch(n){case"IRI":return e.kind==="reference";case"BlankNode":return e.kind==="embedded";case"Literal":return e.kind==="string"||e.kind==="number"||e.kind==="boolean"}}function Ri(n,e){if(e.kind==="reference"||e.kind==="embedded")return`value is a ${e.kind}; sh:datatype requires a literal of ${n.name}.`;let t=xe(n);if(t!==void 0)switch(t){case $.Boolean:return e.kind==="boolean"?void 0:`value is not a boolean (${n.name}).`;case $.Integer:return e.kind!=="number"?`value is not a number (${n.name}).`:Number.isInteger(e.literal)?void 0:`value is not an integer (${n.name}).`;case $.Decimal:case $.Double:case $.Float:return e.kind==="number"?void 0:`value is not a number (${n.name}).`;default:return e.kind==="string"?void 0:`value is not a string-carried literal (${n.name}).`}}function vi(n,e,t){if(t.kind==="embedded"&&t.embedded?.node){let r=j(t.embedded.node);return r.length===0?`value ${t.embedded.label} has no type; sh:class requires an instance of ${e.name}.`:n.membership.isInstance(r,e)?void 0:`value ${t.embedded.label} is not an instance of ${e.name}.`}if(t.kind!=="reference"||!t.ref)return`value is not a reference; sh:class requires an instance of ${e.name}.`;if(n.scope.reasoning)return n.scope.reasoning.isInstanceOf(t.ref,e)?void 0:`value ${l(t.ref)} is not an instance of ${e.name}.`;let o=t.subject;return o?n.membership.isInstance(j(o),e)?void 0:`value ${l(t.ref)} is not an instance of ${e.name}.`:`value ${l(t.ref)} does not resolve in this scope (sh:class ${e.name}).`}function Pi(n,e,t){if(!e.node)return;let o=new Set([...n.properties.map(i=>l(i.path)),...n.ignoredProperties.map(i=>l(i))]),r=new Set;for(let i of e.node.statement){let d=no(i);if(!d)continue;let s=l(d.subject);o.has(s)||r.has(s)||(r.add(s),t.push(De(n,e,Ce,`'${e.label}' carries undeclared property '${d.subject.name}' (closed shape).`,{resultPath:d.subject})))}for(let i of e.node.unresolvedPredicates)r.has(i.key)||(r.add(i.key),t.push(De(n,e,Ce,`'${e.label}' carries unresolvable property '${i.key}' (closed shape).`,{value:i.key})))}var _i="1.1.0",wi=new Set([se,B,G].map(n=>n.name));async function ao(n){let e=new Q(n.repository),t=e.imports(),o=n.result.results.some(a=>wi.has(a.constraintComponent.name))?"1.2.0":_i,r=t.ensure(te,re,o,"sh"),i=(a,u)=>a&&a.version&&typeof a.version.major=="number"?`${t.ensure(a.publisher,a.package_,V(a.version),a.package_)}.${a.name}`:u,d={},s=[];return n.result.results.forEach((a,u)=>{let c=`result-${u+1}`;s.push(c);let p={type:`${r}.ValidationResult`,[`${r}.focusNode`]:i(a.focusUri,a.focusNode),[`${r}.resultMessage`]:a.message,[`${r}.resultSeverity`]:`${r}.${a.severity}`,[`${r}.sourceConstraintComponent`]:`${r}.${a.constraintComponent.name}`};a.resultPath&&(p[`${r}.resultPath`]=i(a.resultPath,l(a.resultPath))),a.sourceShapeUri&&(p[`${r}.sourceShape`]=i(a.sourceShapeUri,a.sourceShape)),a.valueRef?p[`${r}.value`]=i(a.valueRef,l(a.valueRef)):a.value!==void 0&&(p[`${r}.value`]=a.value),d[c]=p}),d.report={type:`${r}.ValidationReport`,[`${r}.conforms`]:n.result.conforms,...s.length>0?{[`${r}.result`]:s}:{}},e.buildContentAddressed({publisher:n.publisher,book:t,body:d,...n.header!==void 0?{header:n.header}:{},contentHashProperty:"contentHash"})}import{VersionOperator as Cs}from"@kanonak-protocol/types/document/models/enums";import{spawn as xi}from"child_process";var co=12e4,Ki=4096,Y=class{argv;interactive;timeoutMs;stderr;now;constructor(e){this.argv=uo(e.command),this.interactive=e.interactive??!1,this.timeoutMs=e.timeoutMs??co,this.stderr=e.stderr??process.stderr,this.now=e.nowSeconds??(()=>Date.now()/1e3)}get command(){return this.argv.join(" ")}async get(e){let t=await this.run("get",this.wireRequest("get",e)),o=Ie(e,t,this.now());if(!o.ok)throw new N(`credential helper '${this.command}' answered get for ${e.resource} outside the protocol (${o.problem}): ${o.message}`);return o.answer}async erase(e){let t=await this.run("erase",{...this.wireRequest("erase",e),scope:e.scope}),o=Oe(t);if(!o.ok)throw new N(`credential helper '${this.command}' answered erase for ${e.resource} outside the protocol (${o.problem}): ${o.message}`)}wireRequest(e,t){let o={version:Le,operation:e,resource:t.resource,method:t.method};return t.challenges&&(o.challenges=t.challenges),o.interactive=this.interactive,o}run(e,t){let o=`credential helper '${this.command}' ${e}`;return new Promise((r,i)=>{let d=!1,s=f=>{d||(d=!0,f())},a;try{a=xi(this.argv[0],[...this.argv.slice(1),e],{stdio:["pipe","pipe","pipe"],shell:!1,windowsHide:!0})}catch(f){i(so(o,f));return}let u=[],c="",p=!1,m=setTimeout(()=>{p=!0,a.kill()},this.timeoutMs);a.stdout.on("data",f=>u.push(f)),a.stderr.on("data",f=>{this.stderr.write(f),c=(c+f.toString("utf8")).slice(-Ki)}),a.on("error",f=>{clearTimeout(m),s(()=>i(so(o,f)))}),a.on("close",(f,A)=>{clearTimeout(m);let v=c.trim()?`: ${c.trim()}`:"";if(p){s(()=>i(new N(`${o} did not finish within ${Math.round(this.timeoutMs/1e3)}s${v}`)));return}if(f!==0){let x=f!==null?`exit ${f}`:`signal ${A}`;s(()=>i(new N(`${o} failed (${x})${v}`)));return}let U=Buffer.concat(u).toString("utf8").trim();try{let x=JSON.parse(U);s(()=>r(x))}catch{s(()=>i(new N(`${o} exited 0 without printing one JSON answer${v}`)))}}),a.stdin.on("error",()=>{}),a.stdin.end(`${JSON.stringify(t)}
2
2
  `)})}};function uo(n){let e=n.trim().split(/\s+/).filter(t=>t!=="");if(e.length===0)throw new Error("the credential helper command is empty");return e}function so(n,e){let t=e.code,o="";return t==="ENOENT"&&(o=" (not found: give its path, or put it on PATH)"),t==="EINVAL"&&process.platform==="win32"&&(o=" (a .cmd or .bat file cannot run without a shell: configure an executable, e.g. `node path/to/helper.js`)"),new N(`${n} could not be started: ${e.message}${o}`)}import{existsSync as Ni,readFileSync as Li}from"fs";import{homedir as Ii}from"os";import{join as Oi}from"path";var He="KANONAK_CREDENTIAL_HELPER";function lo(){return Oi(Ii(),".kanonak","config.json")}function Ai(n={}){let e=n.env??process.env,t=n.configPath??lo(),o=Vi(e,t);if(o){let i=Object.keys(e).filter(d=>(d===de||d.startsWith(`${de}_`))&&(e[d]??"").trim()!=="").sort();if(i.length>0)throw new Error(`A credential helper is configured (${o.source}: ${o.command}) and so is ${i.join(", ")}. Configure one or the other.`);return new Y({command:o.command,interactive:n.interactive??!1})}let r={env:e};return n.discovery&&(r.discovery=n.discovery),new Ae(r)}function Vi(n,e){let t=(n[He]??"").trim();if(t)return{command:t,source:He};if(!Ni(e))return;let o;try{o=JSON.parse(Li(e,"utf-8"))}catch(i){throw new Error(`${e} is not valid JSON: ${i.message}`)}if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`${e} must hold a JSON object`);let r=o.credentialHelper;if(r!==void 0){if(typeof r!="string"||r.trim()==="")throw new Error(`"credentialHelper" in ${e} must be a non-empty command line`);return{command:r.trim(),source:e}}}var C="kanonak.org",w="view",po="core-kanonak",$i={publisher:C,package_:w,name:"rootView"},Ui={publisher:C,package_:w,name:"bind"},Mi={publisher:C,package_:w,name:"produces"},Di={publisher:C,package_:w,name:"projections"},ji={publisher:C,package_:w,name:"where"},Hi={publisher:C,package_:w,name:"value"},Fi={publisher:C,package_:w,name:"as"},me=class{constructor(e,t=new F){this.repository=e;this.parser=t;this.objectParser=new H(this.parser),this.builder=new Q(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let o=await this.objectParser.parseKanonaks(this.repository),r=this.resolveView(o,e),i=S(r,Ui);if(!i)throw new Error(`View ${r.namespace}/${r.name} declares no view.bind; cannot materialize.`);let d=S(r,Mi);if(!d)throw new Error(`View ${r.namespace}/${r.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=Ti(r),a=fo(o,C,po),u=fo(o,C,w),c=this.builder.imports(),p=c.ensure(C,po,a,"ck"),m=c.ensure(C,w,u,"v"),f=c.ref(d),A=new Mn(this.repository,this.parser,this.objectParser),v=new Un(A,o),U=this.readProjections(o,r),x=Bi(r,ji),J=this.findInstances(o,i,await this.reason(t)),h={},K=new Set;for(let Z of J){if(!await this.passesWhere(v,o,x,Z))continue;let he={type:f};for(let Te of U){let ho=await this.evaluateValue(v,o,Te.value,Z),We=this.builder.serializeValue(mo(ho),c);We!==void 0&&(he[c.ref(Te.as)]=We)}let Fe=k(Z);Fe&&(he[`${m}.derivedFrom`]=c.ref(Fe)),h[this.rowName(Z,K)]=he}let y={};t.resolvedAt&&(y[`${p}.resolvedAt`]=t.resolvedAt),t.invocationId&&(y[`${p}.id`]=t.invocationId);let P=await this.builder.buildContentAddressed({publisher:s,book:c,body:h,contentHashProperty:`${p}.contentHash`,header:y});return{yaml:P.yaml,contentHash:P.contentHash,packageName:P.packageName,publisher:P.publisher,rowCount:P.resourceCount}}resolveView(e,t){let o=_(e,t);if(!o)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let r=S(o,$i);if(r){let i=_(e,r);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${r.name}, which is not in the catalog.`);return i}return o}readProjections(e,t){let o=[];for(let r of ge(t,Di)){let i=r instanceof L?r:r instanceof I?_(e,r.subject):void 0;if(!i)continue;let d=T(i,Hi),s=S(i,Fi);d&&s&&o.push({value:d,as:s})}return o}async reason(e){return new z({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,o){let r=qi(e),i=[],d=new Set;for(let s of o.getInstancesOfClass(t)){if(d.has(s))continue;d.add(s);let a=r.get(s);a&&i.push(a)}return i.sort((s,a)=>{let u=W(k(s)),c=W(k(a));return u<c?-1:u>c?1:0}),i}async passesWhere(e,t,o,r){for(let i of o){let d=await this.evaluateValue(e,t,i,r);if(!Gi(d))return!1}return!0}async evaluateValue(e,t,o,r){let i=$n(o,"view-projection",{catalog:t,depth:0}),d=new Map([["input",r]]);return e.evaluate(i,d)}rowName(e,t){let o=Ne(e.name)||"row",r=o,i=2;for(;t.has(r);)r=`${o}-${i++}`;return t.add(r),r}};function mo(n){return Ke(n)?n.value:Array.isArray(n)?n.map(mo):n}function Ti(n){let e=k(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function fo(n,e,t){let o=Wi(n,e,t);if(!o)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return o}function Wi(n,e,t){let o;for(let r of n){if(!(r instanceof g))continue;let i=k(r);!i||i.publisher!==e||i.package_!==t||!i.version||(!o||ee(i.version,o)>0)&&(o=i.version)}return o?V(o):void 0}function qi(n){let e=new Map,t=new Map;for(let o of n){if(!(o instanceof g))continue;let r=k(o);if(!r||!r.version)continue;let i=W(r),d=t.get(i);(!d||ee(r.version,d)>0)&&(t.set(i,r.version),e.set(i,o))}return e}function Bi(n,e){let t=T(n,e);return t?[t]:ge(n,e).filter(o=>o instanceof L)}function Gi(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Ke(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{dr as AmbiguousReferenceRule,ot as BooleanStatement,Mr as CANONICAL_FORM_VERSION,Qr as CREDENTIAL_EXPIRY_SKEW_SECONDS,He as CREDENTIAL_HELPER_ENV,Le as CREDENTIAL_HELPER_PROTOCOL_VERSION,co as CREDENTIAL_HELPER_TIMEOUT_MS,$ as Carrier,hr as ClassDefinitionRule,or as ClassHierarchyCycleRule,wo as CompositeKanonakDocumentRepository,N as CredentialError,qr as DEFAULT_CONSENT_BINDING_PARAM,Qo as DefinedKanonak,Ar as DiamondNameClashRule,kr as DisplayLensScopeRule,_o as DocumentLocation,_t as EdgeType,L as EmbeddedKanonak,Zt as EmbeddedKanonakTypeRule,rt as EmbeddedStatement,oi as EntitlementDeniedError,ti as EntitlementProducer,Y as ExecCredentialProvider,Po as FileSystemKanonakDocumentRepository,It as GitIgnoreFilter,wt as GraphBuilder,To as HttpKanonakDocumentRepository,Be as INTEGRITY_PREFIX,jr as ImportBook,er as ImportExistenceRule,Se as InMemoryKanonakDocumentRepository,Ao as KANONAK_USER_AGENT,zo as Kanonak,At as KanonakDocumentPositions,No as KanonakHttpError,H as KanonakObjectParser,Vr as KanonakObjectValidator,F as KanonakParser,Xo as KanonakUri,Dt as KanonakUriBuilder,jt as KanonakUrlResolver,kt as KanonakVocabulary,Rr as LINE_STYLES,Gt as LinkTargetRule,it as ListStatement,Yo as LiteralKanonak,Wo as LocalFirstRepository,qo as LockAwareRepository,Nr as LookBandPathRule,wr as LookRenderer,gr as LookSemanticSvgPathRule,Sr as MarkdownLinkRule,at as MarkdownStatement,sr as NamespaceImportCycleRule,zt as NamespacePrefixRule,Pt as NodeType,nt as NumberStatement,Br as OAuthDiscovery,Nt as OWL_RL_CLASSIFICATION_RULES,lr as ObjectPropertyValueValidationRule,Wt as OntologyValidationError,Ft as OntologyValidationResult,Or as OwlOneOfRule,Q as PackageBuilder,Jt as PackageHeaderRule,Zr as ProducerRepository,pr as PropertyDomainRule,tr as PropertyHierarchyCycleRule,fr as PropertyKindRangeConsistencyRule,Ot as PropertyMetadata,ur as PropertyRangeReferenceRule,rr as PropertyRangeRequiredRule,Xt as PropertyTypeSpecificityRule,jo as PublisherConfigResolver,Ho as PublisherIndex,Kt as RDFS_RULES,z as Reasoner,Lt as ReasoningResult,I as ReferenceKanonak,tt as ReferenceStatement,Ko as RepositoryFactory,mr as ReservedNameShadowRule,Qt as ResourceNamingRule,st as ResourceResolver,gt as ResourceTypeClassifier,re as SHACL_PACKAGE,te as SHACL_PUBLISHER,q as SH_NODE_SHAPE,ie as SH_PROPERTY_SHAPE,Xe as SH_SHAPE,Zo as ScalarStatement,Kr as SequenceNarrativeRule,Ir as ShaclShapeRule,Jo as Statement,et as StringStatement,ir as SubClassOfReferenceRule,ar as SubPropertyOfReferenceRule,g as SubjectKanonak,Yt as SubjectKanonakTypeRequiredRule,de as TOKEN_ENV,Ae as TokenCredentialProvider,xt as TripleStore,yr as TxExpressionCompilesRule,Lr as TxExpressionPathRule,ct as TypeResolver,Er as URI_DISPLAY_LABEL,br as URI_DISPLAY_SUMMARY,cr as UnresolvedPredicateRule,nr as UnresolvedReferenceRule,Bt as ValidationCache,qt as ValidationContext,Tt as ValidationSeverity,Cs as VersionOperator,me as ViewMaterializer,ei as allowAllPolicy,Uo as assertHttpsUrl,Fo as assertPackageIdentity,Go as buildLocalFirstRepository,_r as buildOntologyModel,ao as buildReportPackageAsync,ue as buildShapesModel,ht as builtinHomePackages,St as builtinUri,$r as canonicalForm,Ur as canonicalHash,xe as carrierOf,Gr as checkCredentialAnswer,Ie as checkHelperAnswer,Oe as checkHelperEraseAnswer,Bo as collectKanonakFiles,ee as compareVersions,Hn as computeIntegrity,Qe as computeIntegrityAsync,Dr as contentAddressedName,j as contextTypesOf,Xr as createCredentialedFetch,yo as createVersion,Ai as credentialProviderFromConfig,Io as describeResponse,eo as evaluateConformance,vt as extractMarkdownLinks,Jr as findDerivation,Rt as findMalformedReferences,$t as findMarkdownLinkAt,Ue as foldFlagsIntoPattern,ut as formatKanonakAddress,V as formatVersion,xo as getGlobalCachePath,$o as getKanonakUserAgent,Lo as httpError,bo as isCompatibleVersion,Co as isMajorCompatible,Et as isPropertySubject,Mo as kanonakFetch,Dn as loadLockFile,qe as lockedVersion,pe as lowerConstraint,pt as makeUriKey,Wr as narrowestScope,ni as noopMeter,Hr as normalizeHost,dt as parseKanonakAddress,Ge as parseLockFile,Fr as parseScope,Eo as parseVersionString,Vt as parseWithPositions,zr as parseWwwAuthenticate,vo as pickHighestDocument,bt as propertiesInScope,yt as propertyClassOf,vr as readSequenceConnectors,Ht as referenceSpelling,M as referenceUris,Cr as resolveDisplayValue,Ct as resolvePropertyStep,Oo as retryAfterSecondsOf,Ne as sanitizeName,Ro as satisfiesVersionOperator,jn as saveLockFile,Tr as scopeContains,Tn as scopeFromCatalog,Wn as scopeFromDocumentAsync,Fn as scopeFromRepositoryAsync,ze as serializeLockFile,Do as setKanonakFetchRetries,Vo as setKanonakUserAgent,Mt as sourceSymbolAt,Ut as sourceSymbols,uo as splitCommandLine,Pe as subjectAddress,k as subjectUri,_e as superClassChain,xr as supportedBandKeys,Yr as tokenEnvKeyFor,ft as tripleKey,lt as typeReferenceUris,W as uriKey,mt as uriTriple,lo as userConfigPath,ce as valuesOf,So as versionOperatorFromChar,ko as versionOperatorToChar,go as versionsEqual,we as walkDefinedKanonaks,Pr as walkSequence};
@@ -11,10 +11,18 @@ import type { KanonakDocument, Import, DocumentReference } from '@kanonak-protoc
11
11
  * for renders to match what the workspace authored. Use this rather than
12
12
  * `CompositeKanonakDocumentRepository` (cache-first, no HTTP tier) when that
13
13
  * ordering matters — notably anything that renders via `LookRenderer`.
14
+ *
15
+ * A tier that FAILS (a server refusal, a credential error, the network) has
16
+ * not said "not here". A later tier may still answer; but when none does, the
17
+ * failure is thrown rather than reported as absence, so a 401 or 429 is never
18
+ * read as "package does not exist" (#127).
14
19
  */
15
20
  export declare class LocalFirstRepository implements IKanonakDocumentRepository {
16
21
  private readonly repos;
17
22
  constructor(...repos: IKanonakDocumentRepository[]);
23
+ /** The first tier's answer that `found` accepts; else the tiers' failure, if
24
+ * any failed; else `none`. */
25
+ private firstAnswer;
18
26
  getHighestCompatibleVersionAsync(publisher: string, import_: Import): Promise<KanonakDocument | null>;
19
27
  getAllDocumentsAsync(): Promise<KanonakDocument[]>;
20
28
  getDocumentAsync(identifier: string): Promise<KanonakDocument | null>;
@@ -1 +1 @@
1
- import{m as e,s as r,t as n}from"../chunk-HKQTB65D.js";import"../chunk-SC5M74NM.js";import{a as o}from"../chunk-6VIUXP4N.js";import"../chunk-7JBKOJB4.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
1
+ import{h as e,n as r,o as n}from"../chunk-MD4CAJIO.js";import"../chunk-SC5M74NM.js";import"../chunk-5FVUBF7N.js";import{a as o}from"../chunk-6VIUXP4N.js";import"../chunk-7JBKOJB4.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
@@ -1,6 +1,7 @@
1
1
  import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
2
2
  import { KanonakParser } from '../parsing/KanonakParser.js';
3
3
  import { type HttpCacheRead, type HttpCacheWrite } from './HttpKanonakDocumentRepository.js';
4
+ import type { AuthenticatedFetchFn } from '../auth/CredentialProvider.js';
4
5
  /**
5
6
  * Recursively collect every `.kan.yml` file under `dir`, skipping build/output
6
7
  * and dependency directories. Pure filesystem walk — no YAML parsing.
@@ -19,7 +20,9 @@ export interface HttpCacheHooks {
19
20
  * augmentations merge in workspace order).
20
21
  * 2. **Global cache** — `~/.kanonak/packages/` (`getGlobalCachePath()`).
21
22
  * 3. **HTTP** — on-demand fetch from publisher origins, write-through to the
22
- * caller-supplied `httpCache` (defaults to an in-memory map).
23
+ * caller-supplied `httpCache` (defaults to an in-memory map), through the
24
+ * caller's `fetchFn` (a credentialed transport) when it supplies one, so a
25
+ * gated import resolves wherever an install can reach it.
23
26
  *
24
27
  * This is the stack every Kanonak-aware tool should resolve through; it is the
25
28
  * order that makes `LookRenderer` output deterministic. The CLI's
@@ -28,4 +31,5 @@ export interface HttpCacheHooks {
28
31
  export declare function buildLocalFirstRepository(workspaceRoot: string, parser?: KanonakParser, options?: {
29
32
  httpCache?: HttpCacheHooks;
30
33
  offline?: boolean;
34
+ fetchFn?: AuthenticatedFetchFn;
31
35
  }): Promise<IKanonakDocumentRepository>;
@@ -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-7F2EAT5Y.js";import{l as g,m as h,s as i,t as j}from"../chunk-HKQTB65D.js";import"../chunk-SC5M74NM.js";import{a}from"../chunk-6VIUXP4N.js";import"../chunk-7JBKOJB4.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,l as LockAwareRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,n as buildLocalFirstRepository,m as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
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-66GZUKYS.js";import{g,h,n as i,o as j}from"../chunk-MD4CAJIO.js";import"../chunk-SC5M74NM.js";import"../chunk-5FVUBF7N.js";import{a}from"../chunk-6VIUXP4N.js";import"../chunk-7JBKOJB4.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,l as LockAwareRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,n as buildLocalFirstRepository,m as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
@@ -1,4 +1,4 @@
1
- import{c as je}from"../chunk-SBO34ENZ.js";import{a as be,d as Q,f as we,h as ee}from"../chunk-7F2EAT5Y.js";import{b as ve,j as $e,l as Se,s as U,t as Z}from"../chunk-HKQTB65D.js";import"../chunk-D2X6J77P.js";import"../chunk-SC5M74NM.js";import{a as q,b as H}from"../chunk-VORVR5BZ.js";import{t as te}from"../chunk-TYVZXABI.js";import"../chunk-QHABFCRC.js";import{a as ye}from"../chunk-6VIUXP4N.js";import{k as oe}from"../chunk-22DSABP6.js";import{a as O}from"../chunk-7JBKOJB4.js";import{a as Pe}from"../chunk-PEJALHXK.js";import"../chunk-NUTHBBDZ.js";import{A as re,c as Re,p as _e}from"../chunk-D4QGPMRW.js";import{a as xe}from"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import{c as V,e as j,f as W,g as X}from"../chunk-QILEJIFU.js";import{readFileSync as pe,writeFileSync as Ee,mkdirSync as De}from"fs";import{join as se}from"path";import Ke from"js-yaml";var Ce=[{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 G(r){return Ce}function N(r){return`${r.publisher}/${r.package_}`}function z(r,e=[]){let i={"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"},o=[];for(let t of r)if(t.origin==="missing"){let a=N(t),u=i[a]??"whatever this package contributes to rendering is lost";o.push(`Render-stack package ${a} is MISSING (${t.reason??"unknown reason"}) \u2014 ${u}. Fix: kanonak install ${a} (as the user running the render), or restore network access to ${t.publisher}.`)}else t.resolvedButNotInCatalog&&o.push(`Render-stack package ${N(t)} resolved (${t.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let t of e)o.push(`Import edge ${t.fromNamespace} \u2192 ${t.publisher}/${t.packageName} ${t.constraint} did NOT resolve (${t.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${t.fromNamespace} authors against ${t.publisher}/${t.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${t.constraint}-compatible version of ${t.publisher}/${t.packageName} to the workspace or cache (kanonak install ${t.publisher}/${t.packageName}), or bump the import in ${t.fromNamespace}.`);return o}function ne(r){let{publisher:e,availablePublishers:i,catalog:o,lookRenderer:t,localNamespaces:a,rawByNsKey:u,renderStack:d,producers:f,lockSource:y,configSource:s}=r,l=new Map,k=new Map,p=new Map,m=new Set;for(let S of o){if(!(S instanceof Re))continue;let w=S.namespace||"";if(!a.has(w))continue;l.set(`${w}/${S.name}`,S);let _=w.split("/")[1]??"",[P,E]=_.split("@");if(!P||!E)continue;let D=X(E);D&&(m.has(_)||(m.add(_),k.has(P)||k.set(P,[]),k.get(P).push({verStr:E,version:D})),S.name===P&&p.set(_,S))}for(let S of k.values())S.sort((w,_)=>V(_.version,w.version));return{publisher:e,availablePublishers:i,catalog:o,lookRenderer:t,localNamespaces:a,rawByNsKey:u,bySubject:l,pkgVersions:k,pkgSelfByVer:p,renderStack:d,...f?{producers:f}:{},...y?{lockSource:y}:{},...s?{configSource:s}:{}}}async function ue(r,e={}){let i=new O,o=new ye(i),t=[],a=[];for(let c of ee(r)){let h;try{h=pe(c,"utf-8")}catch{continue}let n;try{n=i.parse(h).metadata?.namespace_}catch{continue}if(!n?.version)continue;let g=n.version;a.push({publisher:n.publisher,package_:n.package_,verStr:j(g),version:g,source:h})}a.sort((c,h)=>V(h.version,c.version));for(let c of a)await o.saveDocumentAsync(i.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),t.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let u=[...new Set(t.map(c=>c.publisher))].sort(),d=e.publisher;if(d){if(!u.includes(d))throw new Error(`Publisher "${d}" not found in workspace. Available: ${u.join(", ")||"(none)"}`)}else if(u.length===1)d=u[0];else throw u.length===0?new Error(`No Kanonak packages found under ${r}`):new Error(`Workspace has multiple publishers (${u.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,y=new Map;for(let c of t)c.publisher===d&&(f.add(`${c.publisher}/${c.package_}@${c.verStr}`),y.set(`${c.package_}@${c.verStr}`,c.source));let s=Q(),l=new be(s,!0,i),k={};e.httpCache&&(k.getFromCache=e.httpCache.getFromCache,k.onFetch=e.httpCache.onFetch),e.fetchFn&&(k.fetchFn=e.fetchFn);let p=e.repository??new we(o,l,new Z(k)),m=e.log??(()=>{}),S=G(void 0),w=[],_=c=>c.map(h=>h.metadata.namespace_?.version).filter(h=>h!==void 0).sort((h,n)=>V(n,h)).map(j);if(!e.repository){m(`[render-stack] resolving ${S.length} ambient look-stack package(s); cache: ${s}`);let c=e.fetchFn?new U({fetchFn:e.fetchFn}):new U;for(let h of S){let n=N(h),g=await o.getDocumentsByNamespaceAsync(h.publisher,h.package_);if(g.length>0){let v=_(g);w.push({...h,origin:"workspace",versions:v}),m(`[render-stack] ${n} \u2014 workspace (${v.join(", ")})`);continue}let b=await l.getDocumentsByNamespaceAsync(h.publisher,h.package_);if(b.length>0){let v=_(b);w.push({...h,origin:"cache",versions:v}),m(`[render-stack] ${n} \u2014 cache (${v.join(", ")})`);continue}try{let $=(await c.getLock(h.publisher))?.packages[`${h.publisher}/${h.package_}`];if(!$){let C=`publisher ${h.publisher} reachable but its lock does not pin ${h.package_}`;w.push({...h,origin:"missing",reason:C}),m(`[render-stack] ${n} \u2014 MISSING: ${C}`);continue}let F=$.version,T=$.resolved,de=await(e.fetchFn?e.fetchFn(T,h.publisher):$e(T));if(!de.ok){let C=(await ve("render-stack package",T,de)).message;w.push({...h,origin:"missing",reason:C}),m(`[render-stack] ${n} \u2014 MISSING: ${C}`);continue}let fe=await de.text();await o.saveDocumentAsync(i.parse(fe),`${h.publisher}/${h.package_}@${F}`);try{let C=se(s,h.publisher);De(C,{recursive:!0}),Ee(se(C,`${h.package_}@${F}.kan.yml`),fe,"utf-8"),w.push({...h,origin:"fetched",versions:[F]}),m(`[render-stack] ${n}@${F} \u2014 fetched from ${T}, installed to cache`)}catch(C){w.push({...h,origin:"fetched",versions:[F]}),m(`[render-stack] ${n}@${F} \u2014 fetched from ${T}, but cache ${s} is NOT WRITABLE (${C.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(v){let $=`fetch failed: ${v.message}`;w.push({...h,origin:"missing",reason:$}),m(`[render-stack] ${n} \u2014 MISSING: ${$}`)}}}let P=(await o.getAllDocumentsAsync()).filter(c=>c.metadata.namespace_?.publisher===d);for(let c of S)P.push(...await p.getDocumentsByNamespaceAsync(c.publisher,c.package_));let E=[],D=await q(P,p,{onUnresolvedEdge:c=>E.push(c)}),A=p;if(!e.repository){for(let c of S)D.add(N(c));A=new H(p,D)}let B=await new oe(i).parseKanonaks(A),ce=new te(B),le=(c,h)=>re(B,{publisher:c,package_:h,name:h}).length>0,I;if(e.repository){I=[];for(let c of S){let h=await p.getDocumentsByNamespaceAsync(c.publisher,c.package_);I.push(h.length>0?{...c,origin:"repository",versions:_(h)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else I=w.map(c=>c.origin==="missing"||le(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let Y=z(I,E);for(let c of Y)m(`[render-stack] WARNING: ${c}`);let J={contractSource:"universal-default",cachePath:s,packages:I,warnings:Y},K;try{K=pe(se(r,"kanonak.lock"),"utf-8")}catch{K=Ve(d,t,i)}let L;try{L=pe(se(r,".well-known","kanonak.json"),"utf-8")}catch{L=void 0}return ne({publisher:d,availablePublishers:u,catalog:B,lookRenderer:ce,localNamespaces:f,rawByNsKey:y,renderStack:J,...K?{lockSource:K}:{},...L?{configSource:L}:{}})}function Ve(r,e,i){let o=new Map;for(let a of e)a.publisher===r&&(o.has(a.package_)||o.set(a.package_,{verStr:a.verStr,source:a.source}));if(o.size===0)return;let t={};for(let a of[...o.keys()].sort()){let{verStr:u,source:d}=o.get(a),f={},y;try{y=i.parse(d).metadata?.imports}catch{y=void 0}for(let l of y?.[r]??[]){let k=o.get(l.packageName);k&&(f[`${r}/${l.packageName}`]=k.verStr)}let s={};for(let l of Object.keys(f).sort())s[l]=f[l];t[`${r}/${a}`]={version:u,resolved:`https://${r}/${a}/${u}.kan.yml`,integrity:je(d),dependencies:s}}return Ke.dump({version:"1",lastUpdated:"",packages:t},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as Ae,readFileSync as Be,writeFileSync as Le,mkdirSync as Oe}from"fs";import{join as Ne}from"path";async function ge(r,e={}){let i=new O,o=_e(r),t=o.kind==="resource"?o.uri.publisher:o.publisher,a=e.log??(()=>{}),u=e.cacheRoot??Q(),d=(n,g,b)=>Ne(u,n,`${g}@${b}.kan.yml`),f=new Set,y=new Set,s=new Map,l=new Z({getFromCache:(n,g,b)=>{let v=d(n,g,b),$=Ae(v)?Be(v,"utf-8"):null;return $!==null&&f.add(`${n}/${g}`),$},onFetch:(n,g,b,v)=>{y.add(`${n}/${g}`);try{let $=Ne(u,n);Oe($,{recursive:!0}),Le(d(n,g,b),v,"utf-8")}catch($){s.set(`${n}/${g}`,$.message),a(`[render] fetched ${n}/${g}@${b} but cache ${u} is NOT WRITABLE (${$.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),k=new U(e.fetchFn?{fetchFn:e.fetchFn}:void 0),p;if(o.kind==="resource"){let n=o.uri.version;p=[n?{package_:o.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:o.uri.package_}]}else if(o.kind==="package"){let n=o.version;p=[n?{package_:o.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:o.package_}]}else p=((await k.getConfig(t)).featured_packages??[]).map(g=>({package_:g}));let m=async(n,g,b)=>{try{let v=b?i.buildImport(g,"=",b,n):i.buildImport(g,"*","0.0.0",n),$=await l.getHighestCompatibleVersionAsync(n,v);return $?{doc:$}:{doc:null,error:`${n} did not resolve ${g}${b?`@${b}`:""} (not in its index, or unreachable)`}}catch(v){return{doc:null,error:v.message}}},S=[],w=[];for(let n of p){let{doc:g,error:b}=await m(t,n.package_,n.version);g?S.push(g):b&&w.push(b)}if(S.length===0)throw new Error(`Could not fetch any package for address "${r}" from publisher "${t}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=G(),P="universal-default",E=n=>n.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,b)=>V(b,g)).map(j);a(`[render-stack] resolving ${_.length} ambient look-stack package(s) (contract: ${P}); cache: ${u}`);let D=[],A=[];for(let n of _){let g=N(n),{doc:b,error:v}=await m(n.publisher,n.package_,void 0);if(b){D.push(b);let $=E([b]),F=y.has(g)?"fetched":f.has(g)?"cache":"fetched";A.push({...n,origin:F,versions:$}),a(`[render-stack] ${g} \u2014 ${F} (${$.join(", ")})`+(s.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...n,origin:"missing",reason:v??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${v??"unresolved"}`)}let B=[],ce=await q([...S,...D],l,{onUnresolvedEdge:n=>B.push(n)}),le=new H(l,ce),I=await new oe(i).parseKanonaks(le),Y=new te(I),J=A.map(n=>n.origin==="missing"||re(I,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),K=z(J,B);for(let n of K)a(`[render-stack] WARNING: ${n}`);let L={contractSource:P,cachePath:u,packages:J,warnings:K},c=new Set,h=new Map;for(let n of await l.getAllDocumentsAsync()){let g=n.metadata.namespace_;if(!g?.version||g.publisher!==t)continue;let b=j(g.version),v=`${g.publisher}/${g.package_}@${b}`;c.add(v);let $=await l.getDocumentContentAsync(v);$!==null&&h.set(`${g.package_}@${b}`,$)}return ne({publisher:t,availablePublishers:[t],catalog:I,lookRenderer:Y,localNamespaces:c,rawByNsKey:h,renderStack:L})}import{VersionOperator as ie}from"@kanonak-protocol/types/document/models/enums";function ae(r){let{lookRenderer:e,publisher:i,renderStack:o,catalog:t}=r,a=e.explainStylesheet(e.publisherSubject(i)),u=[...a.tokens.entries()].map(([p,m])=>({name:p,value:m.value,source:`${m.sourceNamespace}/${m.sourceName}`,level:m.level})),d=a.baseStylesheet,f={present:d.css!==void 0,...d.sourceNamespace!==void 0?{source:d.sourceNamespace}:{},...d.scope!==void 0?{scope:d.scope}:{},...d.css!==void 0?{bytes:d.css.length}:{},...d.problem!==void 0?{problem:d.problem}:{},candidates:d.candidates},y=new Map;for(let p of t){let m=p.namespace;m&&y.set(m,(y.get(m)??0)+1)}let s=[...y.entries()].map(([p,m])=>({namespace:p,resources:m})).sort((p,m)=>p.namespace.localeCompare(m.namespace)),l=e.expressionFailures().map(p=>({carrier:p.carrier,reason:p.reason})),k=l.map(p=>`Expression carrier "${p.carrier}" did not compile: ${p.reason} Consequence: that value renders as nothing (and a parent operation consuming it may drop its whole tier). Fix: use a tx.Expression node class the runner implements, or remove the carrier.`);return{publisher:i,renderStack:{contractSource:o.contractSource,cachePath:o.cachePath,packages:o.packages.map(p=>({package_:N(p),origin:p.origin,...p.versions!==void 0?{versions:p.versions}:{},...p.reason!==void 0?{reason:p.reason}:{},...p.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:p.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:u,baseStylesheet:f,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},expressionCarriers:l,catalog:s,warnings:[...o.warnings,...a.warnings.filter(p=>!o.warnings.includes(p)),...k]}}function Te(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function he(r){let e=Te,i=r.warnings.length===0,o=r.expressionCarriers.map(s=>`<tr><td><code>${e(s.carrier)}</code></td><td>${e(s.reason)}</td></tr>`).join(`
1
+ import{c as je}from"../chunk-R4LVLXAC.js";import{a as be,d as Q,f as we,h as ee}from"../chunk-66GZUKYS.js";import{e as $e,g as Se,n as U,o as Z}from"../chunk-MD4CAJIO.js";import"../chunk-D2X6J77P.js";import"../chunk-SC5M74NM.js";import{a as q,b as H}from"../chunk-VORVR5BZ.js";import{t as te}from"../chunk-TYVZXABI.js";import"../chunk-QHABFCRC.js";import{b as ve}from"../chunk-5FVUBF7N.js";import{a as ye}from"../chunk-6VIUXP4N.js";import{k as oe}from"../chunk-22DSABP6.js";import{a as O}from"../chunk-7JBKOJB4.js";import{a as Pe}from"../chunk-PEJALHXK.js";import"../chunk-NUTHBBDZ.js";import{A as re,c as Re,p as _e}from"../chunk-D4QGPMRW.js";import{a as xe}from"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import{c as V,e as j,f as W,g as X}from"../chunk-QILEJIFU.js";import{readFileSync as pe,writeFileSync as Ee,mkdirSync as De}from"fs";import{join as se}from"path";import Ke from"js-yaml";var Ce=[{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 G(r){return Ce}function N(r){return`${r.publisher}/${r.package_}`}function z(r,e=[]){let i={"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"},o=[];for(let t of r)if(t.origin==="missing"){let a=N(t),u=i[a]??"whatever this package contributes to rendering is lost";o.push(`Render-stack package ${a} is MISSING (${t.reason??"unknown reason"}) \u2014 ${u}. Fix: kanonak install ${a} (as the user running the render), or restore network access to ${t.publisher}.`)}else t.resolvedButNotInCatalog&&o.push(`Render-stack package ${N(t)} resolved (${t.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let t of e)o.push(`Import edge ${t.fromNamespace} \u2192 ${t.publisher}/${t.packageName} ${t.constraint} did NOT resolve (${t.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${t.fromNamespace} authors against ${t.publisher}/${t.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${t.constraint}-compatible version of ${t.publisher}/${t.packageName} to the workspace or cache (kanonak install ${t.publisher}/${t.packageName}), or bump the import in ${t.fromNamespace}.`);return o}function ne(r){let{publisher:e,availablePublishers:i,catalog:o,lookRenderer:t,localNamespaces:a,rawByNsKey:u,renderStack:d,producers:f,lockSource:y,configSource:s}=r,l=new Map,k=new Map,p=new Map,m=new Set;for(let S of o){if(!(S instanceof Re))continue;let w=S.namespace||"";if(!a.has(w))continue;l.set(`${w}/${S.name}`,S);let _=w.split("/")[1]??"",[P,E]=_.split("@");if(!P||!E)continue;let D=X(E);D&&(m.has(_)||(m.add(_),k.has(P)||k.set(P,[]),k.get(P).push({verStr:E,version:D})),S.name===P&&p.set(_,S))}for(let S of k.values())S.sort((w,_)=>V(_.version,w.version));return{publisher:e,availablePublishers:i,catalog:o,lookRenderer:t,localNamespaces:a,rawByNsKey:u,bySubject:l,pkgVersions:k,pkgSelfByVer:p,renderStack:d,...f?{producers:f}:{},...y?{lockSource:y}:{},...s?{configSource:s}:{}}}async function ue(r,e={}){let i=new O,o=new ye(i),t=[],a=[];for(let c of ee(r)){let h;try{h=pe(c,"utf-8")}catch{continue}let n;try{n=i.parse(h).metadata?.namespace_}catch{continue}if(!n?.version)continue;let g=n.version;a.push({publisher:n.publisher,package_:n.package_,verStr:j(g),version:g,source:h})}a.sort((c,h)=>V(h.version,c.version));for(let c of a)await o.saveDocumentAsync(i.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),t.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let u=[...new Set(t.map(c=>c.publisher))].sort(),d=e.publisher;if(d){if(!u.includes(d))throw new Error(`Publisher "${d}" not found in workspace. Available: ${u.join(", ")||"(none)"}`)}else if(u.length===1)d=u[0];else throw u.length===0?new Error(`No Kanonak packages found under ${r}`):new Error(`Workspace has multiple publishers (${u.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,y=new Map;for(let c of t)c.publisher===d&&(f.add(`${c.publisher}/${c.package_}@${c.verStr}`),y.set(`${c.package_}@${c.verStr}`,c.source));let s=Q(),l=new be(s,!0,i),k={};e.httpCache&&(k.getFromCache=e.httpCache.getFromCache,k.onFetch=e.httpCache.onFetch),e.fetchFn&&(k.fetchFn=e.fetchFn);let p=e.repository??new we(o,l,new Z(k)),m=e.log??(()=>{}),S=G(void 0),w=[],_=c=>c.map(h=>h.metadata.namespace_?.version).filter(h=>h!==void 0).sort((h,n)=>V(n,h)).map(j);if(!e.repository){m(`[render-stack] resolving ${S.length} ambient look-stack package(s); cache: ${s}`);let c=e.fetchFn?new U({fetchFn:e.fetchFn}):new U;for(let h of S){let n=N(h),g=await o.getDocumentsByNamespaceAsync(h.publisher,h.package_);if(g.length>0){let v=_(g);w.push({...h,origin:"workspace",versions:v}),m(`[render-stack] ${n} \u2014 workspace (${v.join(", ")})`);continue}let b=await l.getDocumentsByNamespaceAsync(h.publisher,h.package_);if(b.length>0){let v=_(b);w.push({...h,origin:"cache",versions:v}),m(`[render-stack] ${n} \u2014 cache (${v.join(", ")})`);continue}try{let $=(await c.getLock(h.publisher))?.packages[`${h.publisher}/${h.package_}`];if(!$){let C=`publisher ${h.publisher} reachable but its lock does not pin ${h.package_}`;w.push({...h,origin:"missing",reason:C}),m(`[render-stack] ${n} \u2014 MISSING: ${C}`);continue}let F=$.version,T=$.resolved,de=await(e.fetchFn?e.fetchFn(T,h.publisher):$e(T));if(!de.ok){let C=(await ve("render-stack package",T,de)).message;w.push({...h,origin:"missing",reason:C}),m(`[render-stack] ${n} \u2014 MISSING: ${C}`);continue}let fe=await de.text();await o.saveDocumentAsync(i.parse(fe),`${h.publisher}/${h.package_}@${F}`);try{let C=se(s,h.publisher);De(C,{recursive:!0}),Ee(se(C,`${h.package_}@${F}.kan.yml`),fe,"utf-8"),w.push({...h,origin:"fetched",versions:[F]}),m(`[render-stack] ${n}@${F} \u2014 fetched from ${T}, installed to cache`)}catch(C){w.push({...h,origin:"fetched",versions:[F]}),m(`[render-stack] ${n}@${F} \u2014 fetched from ${T}, but cache ${s} is NOT WRITABLE (${C.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(v){let $=`fetch failed: ${v.message}`;w.push({...h,origin:"missing",reason:$}),m(`[render-stack] ${n} \u2014 MISSING: ${$}`)}}}let P=(await o.getAllDocumentsAsync()).filter(c=>c.metadata.namespace_?.publisher===d);for(let c of S)P.push(...await p.getDocumentsByNamespaceAsync(c.publisher,c.package_));let E=[],D=await q(P,p,{onUnresolvedEdge:c=>E.push(c)}),A=p;if(!e.repository){for(let c of S)D.add(N(c));A=new H(p,D)}let B=await new oe(i).parseKanonaks(A),ce=new te(B),le=(c,h)=>re(B,{publisher:c,package_:h,name:h}).length>0,I;if(e.repository){I=[];for(let c of S){let h=await p.getDocumentsByNamespaceAsync(c.publisher,c.package_);I.push(h.length>0?{...c,origin:"repository",versions:_(h)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else I=w.map(c=>c.origin==="missing"||le(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let Y=z(I,E);for(let c of Y)m(`[render-stack] WARNING: ${c}`);let J={contractSource:"universal-default",cachePath:s,packages:I,warnings:Y},K;try{K=pe(se(r,"kanonak.lock"),"utf-8")}catch{K=Ve(d,t,i)}let L;try{L=pe(se(r,".well-known","kanonak.json"),"utf-8")}catch{L=void 0}return ne({publisher:d,availablePublishers:u,catalog:B,lookRenderer:ce,localNamespaces:f,rawByNsKey:y,renderStack:J,...K?{lockSource:K}:{},...L?{configSource:L}:{}})}function Ve(r,e,i){let o=new Map;for(let a of e)a.publisher===r&&(o.has(a.package_)||o.set(a.package_,{verStr:a.verStr,source:a.source}));if(o.size===0)return;let t={};for(let a of[...o.keys()].sort()){let{verStr:u,source:d}=o.get(a),f={},y;try{y=i.parse(d).metadata?.imports}catch{y=void 0}for(let l of y?.[r]??[]){let k=o.get(l.packageName);k&&(f[`${r}/${l.packageName}`]=k.verStr)}let s={};for(let l of Object.keys(f).sort())s[l]=f[l];t[`${r}/${a}`]={version:u,resolved:`https://${r}/${a}/${u}.kan.yml`,integrity:je(d),dependencies:s}}return Ke.dump({version:"1",lastUpdated:"",packages:t},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as Ae,readFileSync as Be,writeFileSync as Le,mkdirSync as Oe}from"fs";import{join as Ne}from"path";async function ge(r,e={}){let i=new O,o=_e(r),t=o.kind==="resource"?o.uri.publisher:o.publisher,a=e.log??(()=>{}),u=e.cacheRoot??Q(),d=(n,g,b)=>Ne(u,n,`${g}@${b}.kan.yml`),f=new Set,y=new Set,s=new Map,l=new Z({getFromCache:(n,g,b)=>{let v=d(n,g,b),$=Ae(v)?Be(v,"utf-8"):null;return $!==null&&f.add(`${n}/${g}`),$},onFetch:(n,g,b,v)=>{y.add(`${n}/${g}`);try{let $=Ne(u,n);Oe($,{recursive:!0}),Le(d(n,g,b),v,"utf-8")}catch($){s.set(`${n}/${g}`,$.message),a(`[render] fetched ${n}/${g}@${b} but cache ${u} is NOT WRITABLE (${$.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),k=new U(e.fetchFn?{fetchFn:e.fetchFn}:void 0),p;if(o.kind==="resource"){let n=o.uri.version;p=[n?{package_:o.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:o.uri.package_}]}else if(o.kind==="package"){let n=o.version;p=[n?{package_:o.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:o.package_}]}else p=((await k.getConfig(t)).featured_packages??[]).map(g=>({package_:g}));let m=async(n,g,b)=>{try{let v=b?i.buildImport(g,"=",b,n):i.buildImport(g,"*","0.0.0",n),$=await l.getHighestCompatibleVersionAsync(n,v);return $?{doc:$}:{doc:null,error:`${n} did not resolve ${g}${b?`@${b}`:""} (not in its index, or unreachable)`}}catch(v){return{doc:null,error:v.message}}},S=[],w=[];for(let n of p){let{doc:g,error:b}=await m(t,n.package_,n.version);g?S.push(g):b&&w.push(b)}if(S.length===0)throw new Error(`Could not fetch any package for address "${r}" from publisher "${t}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=G(),P="universal-default",E=n=>n.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,b)=>V(b,g)).map(j);a(`[render-stack] resolving ${_.length} ambient look-stack package(s) (contract: ${P}); cache: ${u}`);let D=[],A=[];for(let n of _){let g=N(n),{doc:b,error:v}=await m(n.publisher,n.package_,void 0);if(b){D.push(b);let $=E([b]),F=y.has(g)?"fetched":f.has(g)?"cache":"fetched";A.push({...n,origin:F,versions:$}),a(`[render-stack] ${g} \u2014 ${F} (${$.join(", ")})`+(s.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...n,origin:"missing",reason:v??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${v??"unresolved"}`)}let B=[],ce=await q([...S,...D],l,{onUnresolvedEdge:n=>B.push(n)}),le=new H(l,ce),I=await new oe(i).parseKanonaks(le),Y=new te(I),J=A.map(n=>n.origin==="missing"||re(I,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),K=z(J,B);for(let n of K)a(`[render-stack] WARNING: ${n}`);let L={contractSource:P,cachePath:u,packages:J,warnings:K},c=new Set,h=new Map;for(let n of await l.getAllDocumentsAsync()){let g=n.metadata.namespace_;if(!g?.version||g.publisher!==t)continue;let b=j(g.version),v=`${g.publisher}/${g.package_}@${b}`;c.add(v);let $=await l.getDocumentContentAsync(v);$!==null&&h.set(`${g.package_}@${b}`,$)}return ne({publisher:t,availablePublishers:[t],catalog:I,lookRenderer:Y,localNamespaces:c,rawByNsKey:h,renderStack:L})}import{VersionOperator as ie}from"@kanonak-protocol/types/document/models/enums";function ae(r){let{lookRenderer:e,publisher:i,renderStack:o,catalog:t}=r,a=e.explainStylesheet(e.publisherSubject(i)),u=[...a.tokens.entries()].map(([p,m])=>({name:p,value:m.value,source:`${m.sourceNamespace}/${m.sourceName}`,level:m.level})),d=a.baseStylesheet,f={present:d.css!==void 0,...d.sourceNamespace!==void 0?{source:d.sourceNamespace}:{},...d.scope!==void 0?{scope:d.scope}:{},...d.css!==void 0?{bytes:d.css.length}:{},...d.problem!==void 0?{problem:d.problem}:{},candidates:d.candidates},y=new Map;for(let p of t){let m=p.namespace;m&&y.set(m,(y.get(m)??0)+1)}let s=[...y.entries()].map(([p,m])=>({namespace:p,resources:m})).sort((p,m)=>p.namespace.localeCompare(m.namespace)),l=e.expressionFailures().map(p=>({carrier:p.carrier,reason:p.reason})),k=l.map(p=>`Expression carrier "${p.carrier}" did not compile: ${p.reason} Consequence: that value renders as nothing (and a parent operation consuming it may drop its whole tier). Fix: use a tx.Expression node class the runner implements, or remove the carrier.`);return{publisher:i,renderStack:{contractSource:o.contractSource,cachePath:o.cachePath,packages:o.packages.map(p=>({package_:N(p),origin:p.origin,...p.versions!==void 0?{versions:p.versions}:{},...p.reason!==void 0?{reason:p.reason}:{},...p.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:p.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:u,baseStylesheet:f,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},expressionCarriers:l,catalog:s,warnings:[...o.warnings,...a.warnings.filter(p=>!o.warnings.includes(p)),...k]}}function Te(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function he(r){let e=Te,i=r.warnings.length===0,o=r.expressionCarriers.map(s=>`<tr><td><code>${e(s.carrier)}</code></td><td>${e(s.reason)}</td></tr>`).join(`
2
2
  `),t=r.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':r.warnings.map(s=>`<div class="warn">\u26A0 ${e(s)}</div>`).join(`
3
3
  `),a=r.renderStack.packages.map(s=>{let l=s.origin!=="missing"&&!s.resolvedButNotInCatalog,k=s.origin==="missing"?'<span class="bad">MISSING</span>':s.resolvedButNotInCatalog?`<span class="bad">${e(s.origin)} (not in catalog)</span>`:`<span class="good">${e(s.origin)}</span>`,p=s.reason?e(s.reason):e((s.versions??[]).join(", "));return`<tr class="${l?"":"row-bad"}"><td><code>${e(s.package_)}</code></td><td>${k}</td><td>${p}</td></tr>`}).join(`
4
4
  `),u=r.stylesheet.baseStylesheet,d=u.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(u.source??"")}</code> (${u.bytes} bytes, ${e(u.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${u.problem?` \u2014 ${e(u.problem)}`:""}${u.candidates.length>0?`<br>candidates considered: ${u.candidates.map(s=>`<code>${e(s)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,f=r.stylesheet.tokens.map(s=>`<tr><td><code>--kan-${e(s.name)}</code></td><td><code>${e(s.value)}</code></td><td><code>${e(s.source)}</code></td><td>${e(s.level)}</td></tr>`).join(`
@@ -69,4 +69,4 @@ ${o}
69
69
  ${y}
70
70
  </table>
71
71
  </body>
72
- </html>`}var R={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},x=(r,e,i,o)=>({status:r,headers:{"Content-Type":e,...o||{}},body:i}),M=r=>x(404,R[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${r}</p>`),We=r=>({status:301,headers:{Location:r},body:""}),Ue=r=>({status:302,headers:{Location:r},body:""});function qe(r){switch(r.kind){case"exact":return{operator:ie.Exact,version:W(r.major,r.minor,r.patch)};case"minor-pin":return{operator:ie.Compatible,version:W(r.major,r.minor,0)};case"major-pin":return{operator:ie.Major,version:W(r.major,0,0)};default:return{operator:ie.Any,version:W(0,0,0)}}}async function He(r,e,i,o){if(!o)return null;let t=r.producers?.find(f=>f.canProduce(r.publisher,e));if(!t)return null;let a=await t.resolveVersion(r.publisher,e,qe(i));if(!a)return null;let u=j(a);if(i.kind!=="exact")return Ue(`/${e}/${u}.kan.yml`);let{source:d}=await t.produce(r.publisher,e,a);return x(200,R[".kan.yml"],d)}function Ie(r,e,i){let o=r.pkgVersions.get(e);if(!o||o.length===0)return null;switch(i.kind){case"any":return o[0].verStr;case"major-pin":return o.find(t=>t.version.major===i.major)?.verStr??null;case"minor-pin":return o.find(t=>t.version.major===i.major&&t.version.minor===i.minor)?.verStr??null;case"exact":return o.find(t=>t.version.major===i.major&&t.version.minor===i.minor&&t.version.patch===i.patch)?.verStr??null;default:return null}}async function me(r,e,i=""){let{lookRenderer:o,publisher:t}=r;if(e==="/.well-known/kanonak.json")return r.configSource?x(200,R[".json"],r.configSource):x(200,R[".json"],JSON.stringify(Se(),null,2));if(e==="/kanonak.lock")return r.lockSource?x(200,R[".kan.yml"],r.lockSource):M(e);if(e==="/.well-known/kanonak-render.json")return x(200,R[".json"],JSON.stringify(ae(r),null,2));if(e==="/.well-known/kanonak-render")return x(200,R[".html"],he(ae(r)));if(e==="/"||e==="/index.html"||e==="/index.css"){let l=o.publisherSubject(t);return e==="/index.css"?x(200,R[".css"],o.renderStylesheet(l)):x(200,R[".html"],await o.renderDocument(l,{rootIndex:!0}))}let a=".html",u=!1,d=e;for(let l of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(l)){a=l,u=!0,d=e.slice(0,-l.length);break}let f=!u&&/application\/yaml|text\/yaml/i.test(i),y=d.endsWith("/");y&&d!=="/"&&(d=d.slice(0,-1));let s=Pe.parse(d,t);if(!s)return M(e);if(s.kind==="package"){let l=Ie(r,s.package_,s.versionSpec);if(!l)return await He(r,s.package_,s.versionSpec,a===".kan.yml"||f)??M(e);if(a===".kan.yml"||f){let m=r.rawByNsKey.get(`${s.package_}@${l}`);return m!==void 0?x(200,R[".kan.yml"],m):M(e)}let k=r.pkgSelfByVer.get(`${s.package_}@${l}`);if(!k)return M(e);if(a===".css")return x(200,R[".css"],o.renderStylesheet(k));if(!y)return We(d+"/");let p=s.versionSpec.kind==="any";if(p&&!o.hasDeclaredView(k)){let m=(r.pkgVersions.get(s.package_)||[]).map(S=>S.verStr);return x(200,R[".html"],o.renderPackageVersionList(s.package_,m,k))}return x(200,R[".html"],await o.renderDocument(k,p?{bareOverview:!0}:void 0))}if(s.kind==="resource"){let l=Ie(r,s.package_,s.versionSpec);if(!l)return M(e);let k=r.bySubject.get(`${t}/${s.package_}@${l}/${s.name}`);if(!k)return M(e);switch(a){case".css":return x(200,R[".css"],o.renderStylesheet(k));case".svg":return x(200,R[".svg"],await o.renderSvg(k));case".md":{let p=o.renderRawMarkdown(k);return p===void 0?M(e):x(200,R[".md"],p)}default:return x(200,R[".html"],await o.renderDocument(k))}}return M(e)}import{readFileSync as Ge}from"fs";var Fe=/^\d+\.\d+\.\d+$/,ke=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,i=new Set;if(this.options.root!==void 0){let o=new O;for(let t of ee(this.options.root))try{let a=o.parse(Ge(t,"utf-8")).metadata?.namespace_;if(!a?.version)continue;let u=a.version;e.add(`${a.publisher}/${a.package_}@${u.major}.${u.minor}.${u.patch}`),i.add(`${a.publisher}/${a.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:i},this.workspaceIndex}async modelFor(e,i,o){let t=this.getWorkspaceIndex(),a={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},u=i?o?t.exact.has(`${e}/${i}@${o}`):t.pkgs.has(`${e}/${i}`):[...t.pkgs].some(l=>l.startsWith(`${e}/`)),d,f;if(u&&this.options.root!==void 0){let l=this.options.root;d=`ws:${e}`,f=()=>ue(l,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let l=i?o?`${e}/${i}@${o}`:`${e}/${i}`:e;d=`rm:${l}`,f=()=>ge(l,a)}let y=this.models.get(d);if(y)return y;let s=await f();return s.lookRenderer.setLinkMode("open-world"),this.models.set(d,s),s}async handle(e,i=""){let o=e.split("/").filter(Boolean);if(o.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Me()};let t=o[0];if(!t.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let a=o.length>=2&&(o[1]==="index.html"||o[1]==="index.css"||o[1]==="kanonak.lock"||o[1]===".well-known"),u=!a&&o.length>=2?o[1]:void 0,d=!a&&o.length>=3&&Fe.test(o[2])?o[2]:void 0,f=await this.modelFor(t,u,d),y=e.endsWith("/")&&o.length>1?"/":"",s="/"+o.slice(1).join("/")+y,l=await me(f,s,i);return l.headers.Location?{...l,headers:{...l.headers,Location:`/${t}${l.headers.Location}`}}:l}};function ze(r){switch(r.kind){case"publisher":return`/${r.publisher}/`;case"package":return r.version?`/${r.publisher}/${r.package_}/${j(r.version)}/`:`/${r.publisher}/${r.package_}/`;case"resource":{let e=r.uri;return e.version?`/${e.publisher}/${e.package_}/${j(e.version)}/${e.name}`:`/${e.publisher}/${e.package_}/${e.name}`}}}function Ye(r){let e=r.split("/").filter(Boolean),i=e[0];if(!i||!i.includes("."))return;let o=e[1];if(!o)return{kind:"publisher",publisher:i};let t=e[2]&&Fe.test(e[2])?X(e[2])??void 0:void 0,a=t?e[3]:e[2];return a?{kind:"resource",uri:new xe(i,o,a,t)}:t?{kind:"package",publisher:i,package_:o,version:t}:{kind:"package",publisher:i,package_:o}}function Me(){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{H as ClosureScopedRepository,ke as RequestRouter,Ce as UNIVERSAL_RENDER_BASE,Ye as addressForRequestPath,ae as buildRenderDiagnostics,z as buildRenderStackWarnings,q as deriveImportClosure,Me as landingPage,ge as loadResourceModel,ue as loadServerModel,he as renderDiagnosticsHtml,N as renderRefKey,ze as requestPathFor,G as resolveRenderContract,me as route};
72
+ </html>`}var R={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},x=(r,e,i,o)=>({status:r,headers:{"Content-Type":e,...o||{}},body:i}),M=r=>x(404,R[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${r}</p>`),We=r=>({status:301,headers:{Location:r},body:""}),Ue=r=>({status:302,headers:{Location:r},body:""});function qe(r){switch(r.kind){case"exact":return{operator:ie.Exact,version:W(r.major,r.minor,r.patch)};case"minor-pin":return{operator:ie.Compatible,version:W(r.major,r.minor,0)};case"major-pin":return{operator:ie.Major,version:W(r.major,0,0)};default:return{operator:ie.Any,version:W(0,0,0)}}}async function He(r,e,i,o){if(!o)return null;let t=r.producers?.find(f=>f.canProduce(r.publisher,e));if(!t)return null;let a=await t.resolveVersion(r.publisher,e,qe(i));if(!a)return null;let u=j(a);if(i.kind!=="exact")return Ue(`/${e}/${u}.kan.yml`);let{source:d}=await t.produce(r.publisher,e,a);return x(200,R[".kan.yml"],d)}function Ie(r,e,i){let o=r.pkgVersions.get(e);if(!o||o.length===0)return null;switch(i.kind){case"any":return o[0].verStr;case"major-pin":return o.find(t=>t.version.major===i.major)?.verStr??null;case"minor-pin":return o.find(t=>t.version.major===i.major&&t.version.minor===i.minor)?.verStr??null;case"exact":return o.find(t=>t.version.major===i.major&&t.version.minor===i.minor&&t.version.patch===i.patch)?.verStr??null;default:return null}}async function me(r,e,i=""){let{lookRenderer:o,publisher:t}=r;if(e==="/.well-known/kanonak.json")return r.configSource?x(200,R[".json"],r.configSource):x(200,R[".json"],JSON.stringify(Se(),null,2));if(e==="/kanonak.lock")return r.lockSource?x(200,R[".kan.yml"],r.lockSource):M(e);if(e==="/.well-known/kanonak-render.json")return x(200,R[".json"],JSON.stringify(ae(r),null,2));if(e==="/.well-known/kanonak-render")return x(200,R[".html"],he(ae(r)));if(e==="/"||e==="/index.html"||e==="/index.css"){let l=o.publisherSubject(t);return e==="/index.css"?x(200,R[".css"],o.renderStylesheet(l)):x(200,R[".html"],await o.renderDocument(l,{rootIndex:!0}))}let a=".html",u=!1,d=e;for(let l of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(l)){a=l,u=!0,d=e.slice(0,-l.length);break}let f=!u&&/application\/yaml|text\/yaml/i.test(i),y=d.endsWith("/");y&&d!=="/"&&(d=d.slice(0,-1));let s=Pe.parse(d,t);if(!s)return M(e);if(s.kind==="package"){let l=Ie(r,s.package_,s.versionSpec);if(!l)return await He(r,s.package_,s.versionSpec,a===".kan.yml"||f)??M(e);if(a===".kan.yml"||f){let m=r.rawByNsKey.get(`${s.package_}@${l}`);return m!==void 0?x(200,R[".kan.yml"],m):M(e)}let k=r.pkgSelfByVer.get(`${s.package_}@${l}`);if(!k)return M(e);if(a===".css")return x(200,R[".css"],o.renderStylesheet(k));if(!y)return We(d+"/");let p=s.versionSpec.kind==="any";if(p&&!o.hasDeclaredView(k)){let m=(r.pkgVersions.get(s.package_)||[]).map(S=>S.verStr);return x(200,R[".html"],o.renderPackageVersionList(s.package_,m,k))}return x(200,R[".html"],await o.renderDocument(k,p?{bareOverview:!0}:void 0))}if(s.kind==="resource"){let l=Ie(r,s.package_,s.versionSpec);if(!l)return M(e);let k=r.bySubject.get(`${t}/${s.package_}@${l}/${s.name}`);if(!k)return M(e);switch(a){case".css":return x(200,R[".css"],o.renderStylesheet(k));case".svg":return x(200,R[".svg"],await o.renderSvg(k));case".md":{let p=o.renderRawMarkdown(k);return p===void 0?M(e):x(200,R[".md"],p)}default:return x(200,R[".html"],await o.renderDocument(k))}}return M(e)}import{readFileSync as Ge}from"fs";var Fe=/^\d+\.\d+\.\d+$/,ke=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,i=new Set;if(this.options.root!==void 0){let o=new O;for(let t of ee(this.options.root))try{let a=o.parse(Ge(t,"utf-8")).metadata?.namespace_;if(!a?.version)continue;let u=a.version;e.add(`${a.publisher}/${a.package_}@${u.major}.${u.minor}.${u.patch}`),i.add(`${a.publisher}/${a.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:i},this.workspaceIndex}async modelFor(e,i,o){let t=this.getWorkspaceIndex(),a={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},u=i?o?t.exact.has(`${e}/${i}@${o}`):t.pkgs.has(`${e}/${i}`):[...t.pkgs].some(l=>l.startsWith(`${e}/`)),d,f;if(u&&this.options.root!==void 0){let l=this.options.root;d=`ws:${e}`,f=()=>ue(l,{publisher:e,...a})}else{let l=i?o?`${e}/${i}@${o}`:`${e}/${i}`:e;d=`rm:${l}`,f=()=>ge(l,a)}let y=this.models.get(d);if(y)return y;let s=await f();return s.lookRenderer.setLinkMode("open-world"),this.models.set(d,s),s}async handle(e,i=""){let o=e.split("/").filter(Boolean);if(o.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Me()};let t=o[0];if(!t.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let a=o.length>=2&&(o[1]==="index.html"||o[1]==="index.css"||o[1]==="kanonak.lock"||o[1]===".well-known"),u=!a&&o.length>=2?o[1]:void 0,d=!a&&o.length>=3&&Fe.test(o[2])?o[2]:void 0,f=await this.modelFor(t,u,d),y=e.endsWith("/")&&o.length>1?"/":"",s="/"+o.slice(1).join("/")+y,l=await me(f,s,i);return l.headers.Location?{...l,headers:{...l.headers,Location:`/${t}${l.headers.Location}`}}:l}};function ze(r){switch(r.kind){case"publisher":return`/${r.publisher}/`;case"package":return r.version?`/${r.publisher}/${r.package_}/${j(r.version)}/`:`/${r.publisher}/${r.package_}/`;case"resource":{let e=r.uri;return e.version?`/${e.publisher}/${e.package_}/${j(e.version)}/${e.name}`:`/${e.publisher}/${e.package_}/${e.name}`}}}function Ye(r){let e=r.split("/").filter(Boolean),i=e[0];if(!i||!i.includes("."))return;let o=e[1];if(!o)return{kind:"publisher",publisher:i};let t=e[2]&&Fe.test(e[2])?X(e[2])??void 0:void 0,a=t?e[3]:e[2];return a?{kind:"resource",uri:new xe(i,o,a,t)}:t?{kind:"package",publisher:i,package_:o,version:t}:{kind:"package",publisher:i,package_:o}}function Me(){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{H as ClosureScopedRepository,ke as RequestRouter,Ce as UNIVERSAL_RENDER_BASE,Ye as addressForRequestPath,ae as buildRenderDiagnostics,z as buildRenderStackWarnings,q as deriveImportClosure,Me as landingPage,ge as loadResourceModel,ue as loadServerModel,he as renderDiagnosticsHtml,N as renderRefKey,ze as requestPathFor,G as resolveRenderContract,me as route};
@@ -1 +1 @@
1
- import{A,B,C,D,E,F,G,H,I,J,K,L,M,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-O6SOU5Y2.js";import"../chunk-VORVR5BZ.js";import"../chunk-TYVZXABI.js";import"../chunk-QHABFCRC.js";import"../chunk-6VIUXP4N.js";import"../chunk-22DSABP6.js";import"../chunk-7JBKOJB4.js";import"../chunk-PEJALHXK.js";import"../chunk-NUTHBBDZ.js";import"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{v as AmbiguousReferenceRule,B as ClassDefinitionRule,o as ClassHierarchyCycleRule,L as DiamondNameClashRule,D as DisplayLensScopeRule,l as EmbeddedKanonakTypeRule,m as ImportExistenceRule,M as KanonakObjectValidator,f as LinkTargetRule,H as LookBandPathRule,E as LookSemanticSvgPathRule,C as MarkdownLinkRule,t as NamespaceImportCycleRule,g as NamespacePrefixRule,x as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,K as OwlOneOfRule,k as PackageHeaderRule,y as PropertyDomainRule,p as PropertyHierarchyCycleRule,z as PropertyKindRangeConsistencyRule,w as PropertyRangeReferenceRule,q as PropertyRangeRequiredRule,i as PropertyTypeSpecificityRule,A as ReservedNameShadowRule,h as ResourceNamingRule,G as SequenceNarrativeRule,J as ShaclShapeRule,r as SubClassOfReferenceRule,s as SubPropertyOfReferenceRule,j as SubjectKanonakTypeRequiredRule,F as TxExpressionCompilesRule,I as TxExpressionPathRule,u as UnresolvedPredicateRule,n as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity};
1
+ import{A,B,C,D,E,F,G,H,I,J,K,L,M,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-MWJSYONH.js";import"../chunk-VORVR5BZ.js";import"../chunk-TYVZXABI.js";import"../chunk-QHABFCRC.js";import"../chunk-5FVUBF7N.js";import"../chunk-6VIUXP4N.js";import"../chunk-22DSABP6.js";import"../chunk-7JBKOJB4.js";import"../chunk-PEJALHXK.js";import"../chunk-NUTHBBDZ.js";import"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{v as AmbiguousReferenceRule,B as ClassDefinitionRule,o as ClassHierarchyCycleRule,L as DiamondNameClashRule,D as DisplayLensScopeRule,l as EmbeddedKanonakTypeRule,m as ImportExistenceRule,M as KanonakObjectValidator,f as LinkTargetRule,H as LookBandPathRule,E as LookSemanticSvgPathRule,C as MarkdownLinkRule,t as NamespaceImportCycleRule,g as NamespacePrefixRule,x as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,K as OwlOneOfRule,k as PackageHeaderRule,y as PropertyDomainRule,p as PropertyHierarchyCycleRule,z as PropertyKindRangeConsistencyRule,w as PropertyRangeReferenceRule,q as PropertyRangeRequiredRule,i as PropertyTypeSpecificityRule,A as ReservedNameShadowRule,h as ResourceNamingRule,G as SequenceNarrativeRule,J as ShaclShapeRule,r as SubClassOfReferenceRule,s as SubPropertyOfReferenceRule,j as SubjectKanonakTypeRequiredRule,F as TxExpressionCompilesRule,I as TxExpressionPathRule,u as UnresolvedPredicateRule,n as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity};
@@ -5,6 +5,8 @@ import type { IRepositoryValidationRule } from './IRepositoryValidationRule.js';
5
5
  export declare class ImportExistenceRule implements IRepositoryValidationRule {
6
6
  readonly ruleName = "ImportExistence";
7
7
  validateAsync(document: KanonakDocument, repository: IKanonakDocumentRepository): Promise<OntologyValidationError[]>;
8
+ private unresolvable;
9
+ private suggestionFor;
8
10
  private determineImportErrorAsync;
9
11
  private getAcceptableVersionRange;
10
12
  private findSimilarPackages;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "6.1.0",
3
+ "version": "6.2.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",
@@ -135,7 +135,7 @@
135
135
  ],
136
136
  "dependencies": {
137
137
  "@kanonak-protocol/canonical": "^0.1.3",
138
- "@kanonak-protocol/types": "^6.1.0",
138
+ "@kanonak-protocol/types": "^6.2.0",
139
139
  "ignore": "^7.0.5",
140
140
  "js-yaml": "^4.1.0",
141
141
  "yaml": "^2.7.0",
@@ -1 +0,0 @@
1
- import{n as b,t as A}from"./chunk-HKQTB65D.js";import{a as P}from"./chunk-6VIUXP4N.js";import{a as f}from"./chunk-7JBKOJB4.js";import{c as K,g as I,j as R}from"./chunk-QILEJIFU.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as F}from"url";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;return R(r,t)});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,p=r.metadata.namespace_.version;return K(p,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),p=m[0],h=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,p,h)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=F(n).toString(),s;for(let[m,p]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&p.metadata.namespace_){s=p.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return F(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 S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),D=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 H}from"path";function d(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||H(_(),".kanonak","packages")}var w=class u{static createComposite(e,t,n){let o=e??d(),s=t??".";return new D(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var k=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{VersionOperator as N}from"@kanonak-protocol/types/document/models/enums";var v=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return b(this.lock,e,t)}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=I(n);if(o){let s={...t,versionOperator:N.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as B,readdirSync as V}from"fs";import{join as x}from"path";var $=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function C(u,e=[]){for(let t of V(u,{withFileTypes:!0}))t.isDirectory()?$.has(t.name)||C(x(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(x(u,t.name));return e}async function j(u,e=new f,t={}){let n=new P(e);for(let m of C(u))try{let p=e.parse(B(m,"utf-8")),l=p.metadata?.namespace_,h=l?.version;l&&h&&await n.saveDocumentAsync(p,`${l.publisher}/${l.package_}@${h.major}.${h.minor}.${h.patch}`)}catch{}let o=new y(d(),!0,e);if(t.offline)return new k(n,o);let s=new Map,a=t.httpCache??{getFromCache:(m,p,l)=>s.get(`${m}|${p}|${l}`)??null,onFetch:(m,p,l,h)=>{s.set(`${m}|${p}|${l}`,h)}},r=new A({getFromCache:a.getFromCache,onFetch:a.onFetch});return new k(n,o,r)}export{y as a,S as b,D as c,d,w as e,k as f,v as g,C as h,j as i};
@@ -1,2 +0,0 @@
1
- import{a as k}from"./chunk-SC5M74NM.js";import{a as A}from"./chunk-7JBKOJB4.js";import{e as m,g as R,j as x}from"./chunk-QILEJIFU.js";var F=class extends Error{constructor(t,n,r,s,i){super(t);this.url=n;this.status=r;this.problem=s;this.retryAfterSeconds=i;this.name="KanonakHttpError"}url;status;problem;retryAfterSeconds},E=300;async function u(o,e,t){let n=await $(t),r=y(t.headers.get("retry-after")),s=`Failed to fetch ${o}: ${e} ${await M(t)}`;return new F(s,e,t.status,n,r)}async function M(o){let e=await $(o),t=y(o.headers.get("retry-after")),n=e?O(e):await S(o),r=`(${o.status}${o.statusText?` ${o.statusText}`:""})`;return n&&(r+=`: ${n}`),t!==void 0&&(r+=` [the server asks to retry after ${t}s]`),r}function y(o){if(!o)return;let e=o.trim();if(/^\d+$/.test(e))return Number(e);let t=Date.parse(e);if(!Number.isNaN(t))return Math.max(0,Math.ceil((t-Date.now())/1e3))}function L(o){return(o.headers.get("content-type")??"").split(";")[0].trim().toLowerCase()}async function $(o){if(L(o)!=="application/problem+json")return;let e;try{e=await o.clone().json()}catch{return}if(!e||typeof e!="object")return;let t=e,n={};return typeof t.type=="string"&&(n.type=t.type),typeof t.title=="string"&&(n.title=t.title),typeof t.status=="number"&&(n.status=t.status),typeof t.detail=="string"&&(n.detail=t.detail),typeof t.instance=="string"&&(n.instance=t.instance),n}function O(o){return[o.title,o.detail].filter(e=>!!e&&e.trim()!=="").join(" \u2014 ")}async function S(o){let e=L(o);if(e!=="text/plain"&&e!=="application/json")return"";let t;try{t=await o.clone().text()}catch{return""}let n=t.replace(/\s+/g," ").trim();return n.length>E?`${n.slice(0,E)}\u2026`:n}var h=class extends Error{constructor(e){super(e),this.name="CredentialError"}};var H="@kanonak-protocol/sdk (+https://kanonak.org)",P=H;function ee(o){P=o}function te(){return P}function p(o){let e;try{e=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(e.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${e.href} (only https:// is supported).`)}var j=new Set([429,502,503,504]),q=4,N=500,_=2e4;function g(o,e){p(o);let t=new Headers(e?.headers);return t.has("User-Agent")||t.set("User-Agent",P),B(o,{...e,headers:t})}var w=q;function ne(o){w=Math.max(0,o)}async function B(o,e){let t;for(let n=0;n<=w;n++){let r;try{r=await fetch(o,e)}catch(i){if(t=i,n>=w)throw i;await D(b(n,void 0));continue}if(!j.has(r.status)||n>=w)return r;let s=y(r.headers.get("retry-after"));if(s!==void 0&&s*1e3>_)return r;await D(b(n,s))}throw t??new Error("kanonakFetch: exhausted retries")}function b(o,e){if(e!==void 0)return e*1e3;let t=Math.min(_,N*2**o);return Math.floor(t/2+Math.random()*(t/2))}function D(o){return new Promise(e=>setTimeout(e,o))}var V="https://{publisher}/{package}/{version}.kan.yml",U={version:1};function ae(){return{version:1}}var v=class{constructor(e){this.fetchFn=e}fetchFn;cache=new Map;getConfig(e){let t=this.cache.get(e);return t||(t=this.fetchConfig(e),this.cache.set(e,t),t.catch(()=>{this.cache.get(e)===t&&this.cache.delete(e)})),t}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,n;try{n=await(this.fetchFn?this.fetchFn(t,e):g(t))}catch(i){if(i instanceof h)throw i;return U}if(n.status===404)return U;if(!n.ok)throw await u("publisher config",t,n);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let s={version:r.version};return typeof r.package_url_template=="string"&&(W(t,"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(e,t,n,r){let s=r.package_url_template??V,i=G(s,{publisher:e,package:t,version:n});return p(i),i}};function W(o,e,t){if(!t.startsWith("https://"))throw new Error(`Invalid publisher config at ${o}: ${e} must be an absolute https:// URL template (got "${t}").`)}function G(o,e){let t=o;for(let[r,s]of Object.entries(e))t=t.replaceAll(`{${r}}`,s);let n=t.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${o}`);return t}import K from"js-yaml";function ue(o,e,t){return o.packages[`${e}/${t}`]?.version}var X=`# This file is generated by Kanonak CLI. Do not edit manually.
2
- `,z="sha256:";function I(o){let e=K.load(o);return!e||typeof e!="object"||e.version!=="1"?null:{version:"1",lastUpdated:e.lastUpdated??"",packages:e.packages??{}}}function ge(o){let e={};for(let n of Object.keys(o.packages).sort())e[n]=o.packages[n];let t=K.dump({...o,packages:e},{lineWidth:-1,sortKeys:!1,quotingType:'"'});return X+t}async function fe(o){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)),t=Array.from(new Uint8Array(e),n=>n.toString(16).padStart(2,"0")).join("");return`${z}${t}`}var d=class{configResolver;fetchFn;lockCache=new Map;packageLockCache=new Map;constructor(e){this.configResolver=e?.configResolver??new v(e?.fetchFn),this.fetchFn=e?.fetchFn}getConfig(e){return this.configResolver.getConfig(e)}async getPackageUrl(e,t,n){let r=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,n,r)}getLock(e){let t=this.lockCache.get(e);return t||(t=this.fetchLock(e),this.lockCache.set(e,t),t.catch(()=>{this.lockCache.get(e)===t&&this.lockCache.delete(e)})),t}async getPackageLockEntry(e,t){let n=`${e}/${t}`,r=this.packageLockCache.get(n);return r||(r=this.fetchLock(e,t),this.packageLockCache.set(n,r),r.catch(()=>{this.packageLockCache.get(n)===r&&this.packageLockCache.delete(n)})),(await r)?.packages[n]??null}async fetchLock(e,t){let n=t?`https://${e}/${t}/kanonak.lock`:`https://${e}/kanonak.lock`,r;try{r=this.fetchFn?await this.fetchFn(n,e):await g(n)}catch(s){if(s instanceof h)throw s;return null}if(r.status===404)return null;if(!r.ok)throw await u("publisher lock",n,r);return I(await r.text())}};import{VersionOperator as C}from"@kanonak-protocol/types/document/models/enums";function Y(o,e){let t=R(o);return t?x(t,e):!1}var T=class{parser=new A;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new d({fetchFn:e.fetchFn}):new d}async getHighestCompatibleVersionAsync(e,t){if(t.versionOperator===C.Exact){let s=await this.fromMemoOrCache(e,t.packageName,m(t.version));if(s)return s}let r=(await this.publisherIndex.getLock(e))?.packages[`${e}/${t.packageName}`]??await this.publisherIndex.getPackageLockEntry(e,t.packageName)??void 0;return r&&Y(r.version,t)?this.fetchPinned(e,t.packageName,r):r&&t.versionOperator!==C.Exact?null:this.resolveByDirectFetch(e,t)}async fetchPinned(e,t,n){let r=n.version,s=`${e}/${t}@${r}`,i=await this.fromMemoOrCache(e,t,r);if(i)return i;let a=n.resolved,c=this.fetchFn?await this.fetchFn(a,e):await g(a);if(!c.ok)throw await u("Kanonak package",a,c);let l=await c.text(),f=this.parser.parse(l);return k(f,e,t,r),this.onFetch&&await this.onFetch(e,t,r,l),this.documents.set(s,f),this.contentCache.set(s,l),f}async fromMemoOrCache(e,t,n){let r=`${e}/${t}@${n}`,s=this.documents.get(r);if(s)return s;if(!this.getFromCache)return null;let i=await this.getFromCache(e,t,n);if(i==null)return null;let a;try{a=this.parser.parse(i),k(a,e,t,n)}catch(c){throw new Error(`Cached content for ${r} is not a usable copy of that package \u2014 refusing to fall through to a fetch that would hide it. ${c.message}`,{cause:c})}return this.documents.set(r,a),this.contentCache.set(r,i),a}async resolveByDirectFetch(e,t){let n=t.packageName,s=t.versionOperator===C.Exact?await this.publisherIndex.getPackageUrl(e,n,m(t.version)):`https://${e}/${n}.kan.yml`,i=await this.fetchFollowing(s,e);if(!i)return null;let a=this.parser.parse(i.content),c=a.metadata.namespace_;if(!c||!c.version)throw new Error(`Producer origin returned a package with no namespace/version for ${e}/${n}`);let l=m(c.version);k(a,e,n,l);let f=`${e}/${n}@${l}`;return this.onFetch&&await this.onFetch(e,n,l,i.content),this.documents.set(f,a),this.contentCache.set(f,i.content),a}async fetchFollowing(e,t,n=4){let r=e;for(let s=0;s<n;s++){p(r);let i=this.fetchFn?await this.fetchFn(r,t):await g(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 await u("Kanonak package",r,i);return{url:r,content:await i.text()}}throw new Error(`Too many redirects resolving ${e}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===e&&r.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,n,r,s]=t;return this.publisherIndex.getPackageUrl(n,r,s)}};export{F as a,u as b,M as c,y as d,h as e,H as f,ee as g,te as h,p as i,g as j,ne as k,ae as l,v as m,ue as n,z as o,I as p,ge as q,fe as r,d as s,T as t};
@@ -1,68 +0,0 @@
1
- import{a as Pt}from"./chunk-VORVR5BZ.js";import{c as wt,g as Ut,h as ct,i as pt,j as At,k as Nt,l as Tt,s as lt,t as xt,u as _t}from"./chunk-TYVZXABI.js";import{a as F,f as z,i as Ct,k as O}from"./chunk-22DSABP6.js";import{a as Vt}from"./chunk-7JBKOJB4.js";import{$ as ne,_ as st,aa as $t,b as vt,ba as It,fa as nt,ga as jt,ma as j,na as x,oa as H,pa as q,qa as Q,ta as Ot,ua as Y,va as pe}from"./chunk-NUTHBBDZ.js";import{A as St,C as W,D as ee,E as te,F as E,G as C,H as T,L as B,c as k,d as V,e as N,f as tt,l as ce,m as J,n as L,o as ot,r as R,s as Z,u as Dt,v as M,w as oe,x as A,z as b}from"./chunk-D4QGPMRW.js";import{a as Et}from"./chunk-FUUTGGJS.js";import{b as se,c as Kt}from"./chunk-F67UH4FD.js";import{e as U}from"./chunk-QILEJIFU.js";var le=class{isValid=!1;errors=[];warnings=[];infos=[];get totalIssues(){return this.errors.length+this.warnings.length+this.infos.length}get allDiagnostics(){return[...this.errors,...this.warnings,...this.infos]}};var K=(o=>(o.Info="Info",o.Warning="Warning",o.Error="Error",o))(K||{});var d=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var mt=class p{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new p;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var re=class{constructor(e){this.underlying=e;this.repository=new ut(e)}underlying;repository;parsePromise=null;getKanonaks(){return this.parseOnce().then(e=>e.merged)}getAuthoredKanonaks(){return this.parseOnce().then(e=>e.authored)}parseOnce(){return this.parsePromise||(this.parsePromise=(async()=>{let e=await this.underlying.getAllDocumentsAsync();await Pt(e,this.repository);let t={};return{merged:await new O().parseKanonaks(this.underlying,t),authored:t.authored??[]}})()),this.parsePromise}},ut=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){let o=`${e}/${t}`,n=this.byNamespaceCache.get(o);return n||(n=this.inner.getDocumentsByNamespaceAsync(e,t),this.byNamespaceCache.set(o,n),n)}getHighestCompatibleVersionAsync(e,t){let o=t.version,n=o?`${o.major}.${o.minor}.${o.patch}`:"",r=`${e}/${t.packageName}@${t.versionOperator}:${n}`,a=this.highestVersionCache.get(r);return a||(a=this.inner.getHighestCompatibleVersionAsync(e,t),this.highestVersionCache.set(r,a),a)}saveDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}deleteDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}clearNamespaceAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};async function $(p,e,t){return t?t.getKanonaks():new O().parseKanonaks(new me(p,e))}async function P(p,e,t){let o=await $(p,e,t),n=rt(p);return n?o.filter(r=>r instanceof k&&r.namespace===n):[]}async function ue(p,e,t){let o=rt(p);if(!o)return[];let n;if(t)n=await t.getAuthoredKanonaks();else{let r={};await new O().parseKanonaks(new me(p,e),r),n=r.authored??[]}return n.filter(r=>r instanceof k&&r.sourceDoc===o)}function rt(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var me=class{constructor(e,t){this.document=e;this.broader=t}document;broader;async getAllDocumentsAsync(){let e=this.document.metadata.namespace_?.toString(),t=(await this.broader.getAllDocumentsAsync()).filter(o=>o.metadata.namespace_?.toString()!==e);return[this.document,...t]}getDocumentAsync(e){return this.broader.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.broader.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.broader.getHighestCompatibleVersionAsync(e,t)}getAllDocumentReferencesAsync(){return this.broader.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.broader.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.broader.getDocumentUriAsync(e)}saveDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}deleteDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}clearNamespaceAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}};var de=class{constructor(e={}){this.options=e}options;ruleName="LinkTarget";async validateAsync(e,t,o){let n=[],r=new Map;for(let[s,l]of Object.entries(e.metadata?.imports??{}))for(let m of l)se(m)&&r.set(`${s}/${m.packageName}`,{publisher:s,import_:m});if(r.size===0)return n;let a=new Map,i=(s,l,m)=>{let u=`${s.publisher}/${s.package_}`;if(!r.has(u))return;let f=a.get(u)??[];f.push({uri:s,where:l,predicate:m}),a.set(u,f)},c=await P(e,t,o);F(c,({kanonak:s,path:l})=>{for(let m of s.statement){let u=m.predicate?.subject?.name??"(unknown)";if(m instanceof ce)i(m.object.subject,l,u);else if(m instanceof L)for(let f of m.object)f instanceof N&&i(f.subject,l,u);else if(m instanceof ot)for(let f of m.links)f.target&&i(f.target.subject,l,u)}});for(let[s,l]of a){let{publisher:m,import_:u}=r.get(s),f=null,h;try{f=await t.getHighestCompatibleVersionAsync(m,u)}catch(y){h=y instanceof Error?y.message:String(y)}if(!f){let y=l[0],g=`${l.length} reference${l.length===1?"":"s"}, first at '${y.where}.${y.predicate}'`;this.options.offline?n.push(this.finding("Warning",y.where,y.predicate,s,`Link target package '${s}' could not be resolved offline (${g}); the link is UNVERIFIED, not known to be broken.`,"Run without --offline to verify the link over HTTP, or add the package to the workspace or cache.")):n.push(this.finding("Error",y.where,y.predicate,s,`Link target package '${s}' could not be resolved${h?` (${h})`:""} \u2014 ${g}.`,"Check the publisher and package name of the link import; a link must dereference even though it is not a dependency. Use --offline to validate without the network (the link is then reported as unverified)."));continue}for(let{uri:y,where:g,predicate:D}of l)Object.prototype.hasOwnProperty.call(f.body,y.name)||n.push(this.finding("Error",g,D,`${s}/${y.name}`,`Link to '${y.name}' in '${D}' at '${g}' does not dereference: package '${s}' (resolved to ${f.metadata.namespace_?.toString()??s}) defines no resource named '${y.name}'.`,`Check for a typo, or a resource renamed or removed in '${s}'; a link addresses a resource by name in its package's current version unless the import is pinned with '='.`))}return n}finding(e,t,o,n,r,a){let i=new d;return i.ruleType=this.ruleName,i.severity=e,i.entityName=t,i.propertyName=o,i.actualValue=n,i.expectedValue="A link that dereferences to a resource its target package defines",i.message=r,i.suggestion=a,i}};var fe=class p{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):[A-Za-z_][A-Za-z0-9_.-]*$/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[o,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(o,n,t);return t}validateEntity(e,t,o){for(let[n,r]of Object.entries(t)){let a=r?.toString()??"";if(a&&p.NAMESPACE_PREFIX_PATTERN.test(a)){let i=this.getSuggestionForPrefixedValue(a),c=e.split(".")[0],s=new d;s.ruleType=this.ruleName,s.severity="Error",s.entityName=c,s.propertyName=e,s.actualValue=n,s.expectedValue=i,s.message=`Invalid namespace prefix '${a}'. Use '${i}' without prefix.`,s.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",o.push(s)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validateEntity(`${e}.${n}`,r,o)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let o=e.indexOf(":");return o>=0?e.substring(o+1):e}};var ye=class p{static RESERVED_WORDS=new Set(["imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],o=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,r]of Object.entries(e.body)){let a=p.VALID_AUGMENTATION_PATTERN.test(n);if(!a&&!o&&p.RESERVED_WORDS.has(n.toLowerCase())){let i=new d;i.ruleType=this.ruleName,i.severity="Error",i.entityName=n,i.message=`Entity name '${n}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(i);continue}if(!a&&!p.VALID_NAME_PATTERN.test(n)){let i;/^\d/.test(n)?i="Entity names must start with a letter, not a number.":n.includes(" ")?i="Entity names cannot contain spaces. Use camelCase or underscores instead.":i="Entity names must start with a letter and contain only letters, numbers, and underscores.";let c=new d;c.ruleType=this.ruleName,c.severity="Error",c.entityName=n,c.message=`Invalid entity name '${n}'. ${i}`,c.suggestion=i,t.push(c)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(n,r,t)}return t}validatePropertyNames(e,t,o){for(let n of Object.keys(t))if(!p.VALID_PROPERTIES.has(n)&&!p.VALID_PROPERTY_NAME_PATTERN.test(n)){let r=new d;r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,r.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,r.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",o.push(r)}}};var he=class p{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let o=this.isPropertyDefinedAsClass(e);for(let[n,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r,i=a.type;if(i){let c=[];if(Array.isArray(i))for(let s of i){let l=s?.toString();l&&l==="Property"&&!o&&c.push(l)}else{let s=i?.toString();s&&s==="Property"&&!o&&c.push(s)}for(let s of c){let l=this.getPropertyValue(a,"range"),m=this.determinePropertyType(l),u=new d;u.ruleType=this.ruleName,u.severity="Error",u.entityName=n,u.propertyName="type",u.actualValue=s,u.expectedValue=m,u.message=`Invalid property type '${s}'. Use '${m}' instead.`,u.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(u)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":p.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let o=e[t];return o?o.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let r=n.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var ke=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[o,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||o.includes("."))continue;let r=n,a="type"in r,i=r.type?.toString().trim();if(!a||!i){let c=new d;c.ruleType=this.ruleName,c.severity="Error",c.entityName=o,c.propertyName="type",c.message=`Subject Kanonak '${o}' must have a 'type' property.`,c.suggestion=`Add a type statement like:
2
- type: Scene
3
-
4
- Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,c.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(c)}}return t}};var lo=new Set(["EphemeralPackage"]),ge=class{get ruleName(){return"PackageHeader"}validate(e){let t=e.metadata;if(!t.type_)return[];let o=[],n=this.packageKey(e,t.type_);return t.namespace_?(!lo.has(t.type_)&&!t.namespace_.version&&o.push(this.error(n,"version",`Package resource '${n}' requires a 'version' property \u2014 packages are addressed by name@version.`,`Add a version, e.g.:
5
- version: 1.0.0`)),o):(o.push(this.error(n,"publisher",`Package resource '${n}' requires a 'publisher' property.`,`Add a publisher, e.g.:
6
- publisher: example.org`)),o)}packageKey(e,t){for(let[o,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type===t)return o;return t}error(e,t,o,n){let r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.message=o,r.suggestion=n,r}};var mo={publisher:"kanonak.org",package_:"core-rdf",name:"type"},uo={publisher:"kanonak.org",package_:"core-rdf",name:"range"},fo={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},yo={publisher:"kanonak.org",package_:"core-rdf",name:"Class"},Re=class{ruleName="EmbeddedKanonakType";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await ue(e,t,o);for(let i of a)i instanceof k&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof J){let a=r.predicate?.subject,i=`${o}.${a?.name??"<embedded>"}`;this.check(e,a,r.object,o,i,n),this.walk(e,r.object,i,n)}else if(r instanceof L){let a=r.predicate?.subject,i=0;for(let c of r.object){if(c instanceof V){let s=`${o}.${a?.name??"<embedded>"}[${i}]`;this.check(e,a,c,o,s,n),this.walk(e,c,s,n)}i++}}}check(e,t,o,n,r,a){if(!t)return;let i=E(o,mo);if(!i)return;let c=b(e,t);if(!c)return;let s=E(c,uo);if(s&&!(Z(s,fo)||Z(s,yo))){if(R(i)===R(s)){a.push(this.redundant(n,r,i,s));return}H(e,i).some(l=>R(l)===R(s))||a.push(this.notSubclass(n,r,i,s))}}redundant(e,t,o,n){let r=new d;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' declares 'type: ${o.name}', which equals the parent property's range '${n.name}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,r.suggestion=`Remove the 'type: ${o.name}' line, or keep it if explicitness is preferred over concision.`,r}notSubclass(e,t,o,n){let r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' has 'type: ${o.name}', which is not a subclass of the parent property's range '${n.name}'.`,r.suggestion=`Either remove the 'type: ${o.name}' line (so the type is inferred from the property's range '${n.name}'), or add 'subClassOf: ${n.name}' to the '${o.name}' class definition so the relationship holds.`,r}};import{VersionOperator as at}from"@kanonak-protocol/types/document/models/enums";var be=class{ruleName="ImportExistence";async validateAsync(e,t){let o=[];if(!e.metadata?.imports)return o;let n=await t.getAllDocumentsAsync();for(let[r,a]of Object.entries(e.metadata.imports))for(let i of a){if(se(i))continue;if(!await t.getHighestCompatibleVersionAsync(r,i)){let s=await this.determineImportErrorAsync(t,r,i,n),l=new d;l.ruleType=this.ruleName,l.severity="Error",l.message=s.message,l.suggestion=s.suggestion,l.entityName=`Import: ${r}/${i.packageName}`,l.actualValue=i.toString(),l.expectedValue=s.expectedValue,o.push(l)}}return o}async determineImportErrorAsync(e,t,o,n){let r=await e.getDocumentsByNamespaceAsync(t,o.packageName);if(r.length===0){let s=n.filter(f=>f.metadata.namespace_?.publisher===t).map(f=>f.metadata.namespace_.package_).filter((f,h,y)=>y.indexOf(f)===h),l=this.findSimilarPackages(o.packageName,s),m=`Import '${t}/${o.package_}' not found - package does not exist`,u=l.length>0?`Did you mean: ${l.slice(0,3).join(", ")}?`:s.length>0?`Available packages in ${t}: ${s.slice(0,5).join(", ")}`:`No packages found for publisher '${t}'. Verify the publisher name is correct.`;return{message:m,suggestion:u,expectedValue:"Existing package"}}let i=r.filter(s=>s.metadata.namespace_?.version).map(s=>s.metadata.namespace_.version.toString()).sort().join(", "),c=this.getAcceptableVersionRange(o);return{message:`Import '${t}/${o.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${i}. Required: ${c}`,expectedValue:c}}getAcceptableVersionRange(e){switch(e.versionOperator){case at.Exact:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case at.Compatible:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case at.Major:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case at.Any:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let o=t.filter(a=>a.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(a.toLowerCase()));if(o.length>0)return o.sort((a,i)=>a.length-i.length);let n=t.map(a=>({package:a,distance:this.levenshteinDistance(e.toLowerCase(),a.toLowerCase())})).sort((a,i)=>a.distance-i.distance),r=Math.max(3,Math.floor(e.length*.4));return n.filter(a=>a.distance<=r).map(a=>a.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let o=e.length,n=t.length,r=Array(o+1).fill(null).map(()=>Array(n+1).fill(0));for(let a=0;a<=o;a++)r[a][0]=a;for(let a=0;a<=n;a++)r[0][a]=a;for(let a=1;a<=o;a++)for(let i=1;i<=n;i++){let c=e[a-1]===t[i-1]?0:1;r[a][i]=Math.min(Math.min(r[a-1][i]+1,r[a][i-1]+1),r[a-1][i-1]+c)}return r[o][n]}};var ho="kanonak.org",ko="core-rdf",go=new Set(["type","subClassOf","subPropertyOf","domain","range"].map(p=>R({publisher:ho,package_:ko,name:p}))),Ke=class{ruleName="UnresolvedReference";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await P(e,t,o),i=Kt(e),c=s=>i.has(`${s.subject.publisher}/${s.subject.package_}`);return F(a,({kanonak:s,path:l})=>{for(let m of s.statement){let u=Ro(m);if(!(!u||go.has(R(u)))){if(m instanceof ce)c(m.object)||this.check(r,l,u,m.object,n);else if(m instanceof L)for(let f of m.object)f instanceof N&&!c(f)&&this.check(r,l,u,f,n)}}}),n}check(e,t,o,n,r){b(e,n.subject)||r.push(this.unresolvedError(t,o.name,n.subject))}unresolvedError(e,t,o){let n=`${o.publisher}/${o.package_}/${o.name}`,r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=n,r.expectedValue="A reference that resolves to a defined or imported resource",r.message=`Reference to '${o.name}' in '${t}' could not be resolved`,r.suggestion=`The entity '${n}' is not defined in this namespace or any imported namespace.
7
- \u2022 Import the package that defines it, or check for a typo in '${o.name}'
8
- \u2022 If it lives in an imported namespace, alias-qualify the reference`,r}};function Ro(p){return p.predicate?.subject}var Lt={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},Mt={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"};function it(p,e,t){let o=[],n=new Set,r=new Set,a=i=>{let c=b(p,i),s=c?`${c.namespace}/${c.name}`:R(i);if(n.has(s)){let l=o.findIndex(u=>u.key===s),m=o.slice(l);return m.length<=1?null:[...m.map(u=>u.uri),i]}if(r.has(s))return null;if(n.add(s),o.push({key:s,uri:i}),c)for(let l of M(c,t)){let m=a(l);if(m)return m}return o.pop(),n.delete(s),r.add(s),null};return a(e)}var Bt=p=>p,Ve=class{ruleName="ClassHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await P(e,t,o);for(let i of a){if(!(i instanceof k)||!(j.isClassType(Bt(i))||j.isDatatypeType(Bt(i))))continue;let c=x(i);if(!c)continue;let s=it(r,c,Lt);if(s){let l=s.map(u=>u.name).join(" \u2192 "),m=new d;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular class hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",m.entityName=i.name,m.propertyName="subClassOf",m.actualValue=l,n.push(m);break}}return n}};var Ee=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await P(e,t,o);for(let i of a){if(!(i instanceof k)||!Q(r,i))continue;let c=x(i);if(!c)continue;let s=it(r,c,Mt);if(s){let l=s.map(u=>u.name).join(" \u2192 "),m=new d;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular property hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",m.entityName=i.name,m.propertyName="subPropertyOf",m.actualValue=l,n.push(m);break}}return n}};var bo={publisher:"kanonak.org",package_:"core-rdf",name:"range"},ve=class{ruleName="PropertyRangeRequired";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await P(e,t,o);for(let i of a){if(!(i instanceof k))continue;let c=q(r,i);if(c!=="ObjectProperty"&&c!=="DatatypeProperty")continue;let s=c==="ObjectProperty";W(i,bo)||n.push(this.error(i.name,s))}return n}error(e,t){let o=new d;return o.ruleType=this.ruleName,o.severity="Error",o.entityName=e,o.propertyName="range",o.message=`Property '${e}' must have a 'range' defined.`,o.suggestion=t?"Add a range like: range: ClassName (the class this property expects)":"Add a range like: range: string (or integer, boolean, etc.)",o.expectedValue=t?"A class name (Character, Scene, Story, etc.)":"A datatype (string, integer, boolean, decimal, etc.)",o}};var Ko={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},qt=p=>p,De=class{ruleName="SubClassOfReference";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await P(e,t,o);for(let i of a){if(!(i instanceof k)||!Ft(qt(i)))continue;let c=M(i,Ko);for(let s=0;s<c.length;s++)this.resolvesToClassLike(r,c[s])||n.push(this.error(i.name,c[s],c.length>1?`[${s}]`:""))}return n}resolvesToClassLike(e,t){let o=b(e,t);return o?Ft(qt(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subClassOf",r.actualValue=n,r.expectedValue="Defined or imported class",r.message=`Class '${t.name}' referenced in subClassOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a Class, or import a namespace that contains it`,r}};function Ft(p){return j.isClassType(p)||j.isDatatypeType(p)}var Vo={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"},Se=class{ruleName="SubPropertyOfReference";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await P(e,t,o);for(let i of a){if(!(i instanceof k)||!Q(r,i))continue;let c=M(i,Vo);for(let s=0;s<c.length;s++)this.resolvesToProperty(r,c[s])||n.push(this.error(i.name,c[s],c.length>1?`[${s}]`:""))}return n}resolvesToProperty(e,t){let o=b(e,t);return o?Q(e,o):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subPropertyOf",r.actualValue=n,r.expectedValue="Defined or imported property",r.message=`Property '${t.name}' referenced in subPropertyOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a property, or import a namespace that contains it`,r}};var $e=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,t){let o=[],n=e.metadata.namespace_?.toString();if(!n)return o;let r=new Map,a=new Set;await this.buildImportGraph(e,t,r,a);let i=this.detectCycle(n,r);if(i){let c=i.join(" \u2192 "),s=new d;s.ruleType=this.ruleName,s.severity="Error",s.message=`Circular namespace import detected: ${c}`,s.suggestion="Remove one of the imports to break the circular dependency, or \u2014 if one direction is a DATA reference rather than a schema dependency (an object-property value naming a resource in the other package) \u2014 mark that import `mode: link`: links are dereferenced on demand, are not in the closure, and are exempt from this rule. Circular dependencies prevent proper package resolution.",s.entityName="imports",s.propertyName="imports",s.actualValue=c,o.push(s)}return o}async buildImportGraph(e,t,o,n){let r=e.metadata.namespace_?.toString()??"";if(!(!r||n.has(r))&&(n.add(r),e.metadata.imports)){let a=[];for(let[i,c]of Object.entries(e.metadata.imports))for(let s of c){if(se(s))continue;let l=`${i}/${s.packageName}@${s.version}`;a.push(l);let m=await t.getHighestCompatibleVersionAsync(i,s);m&&await this.buildImportGraph(m,t,o,n)}a.length>0&&o.set(r,a)}}detectCycle(e,t){let o=[],n=new Set;return this.detectCycleRecursive(e,t,o,n)}detectCycleRecursive(e,t,o,n){let r=o.indexOf(e);if(r>=0){let i=o.slice(r);return i.push(e),i}if(n.has(e))return null;o.push(e),n.add(e);let a=t.get(e);if(a)for(let i of a){let c=this.detectCycleRecursive(i,t,o,n);if(c)return c}return o.pop(),null}};var Ie=class{ruleName="UnresolvedPredicate";async validateAsync(e,t,o){let n=[],r=rt(e);if(!r)return n;let a=await $(e,t,o);return F(a,({kanonak:i,path:c})=>{for(let s of i.unresolvedPredicates)s.sourceDoc===r&&n.push(this.unresolvedPredicateError(c,s.key))}),n}unresolvedPredicateError(e,t){let o=t.lastIndexOf("."),n=o>0?t.slice(0,o):null,r=o>0?t.slice(o+1):t,a=new d;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=t,a.expectedValue="A defined or imported property",a.message=`Property '${t}' is not defined or imported`,a.suggestion=n?`The property '${r}' was not found in the namespace imported as '${n}'.
9
- 1. Check '${r}' is spelled correctly
10
- 2. Verify '${n}' is imported with the right alias and version
11
- 3. Ensure that namespace version actually defines '${r}'`:`The property '${t}' is not defined in this namespace or any imported namespace.
12
- 1. Define '${t}' as an ObjectProperty or DatatypeProperty here, OR
13
- 2. Import the namespace that defines it, OR
14
- 3. Alias-qualify it if it lives in an imported namespace ('alias.${t}')`,a}};var je=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,t){let o=[],{entitySources:n,importPaths:r}=await this.buildEntitySourceMapAsync(e,t),a=await this.buildDatatypePropertyNamesAsync(e,t);for(let[i,c]of Object.entries(e.body))typeof c=="object"&&c!==null&&!Array.isArray(c)&&this.validateEntityReferences(i,c,n,r,a,e,o);return o}async buildEntitySourceMapAsync(e,t){let o=new Map,n=new Set,r=new Map;for(let a of Object.keys(e.body)){let i=e.metadata.namespace_?.toString()??"";o.has(a)||o.set(a,[]),o.get(a).push(`(local:${i})`)}if(e.metadata.imports)for(let[a,i]of Object.entries(e.metadata.imports))for(let c of i){let s=await t.getHighestCompatibleVersionAsync(a,c);if(s){let l=s.metadata.namespace_?.toString()??"";await this.collectEntitiesRecursivelyAsync(s,o,n,r,[l],t)}}return{entitySources:o,importPaths:r}}async collectEntitiesRecursivelyAsync(e,t,o,n,r,a){let i=e.metadata.namespace_?.toString()??"";if(!o.has(i)){o.add(i),n.has(i)||n.set(i,r);for(let c of Object.keys(e.body)){t.has(c)||t.set(c,[]);let s=t.get(c);s.includes(i)||s.push(i)}if(e.metadata.imports)for(let[c,s]of Object.entries(e.metadata.imports))for(let l of s){let m=await a.getHighestCompatibleVersionAsync(c,l);if(m){let u=m.metadata.namespace_?.toString()??"";await this.collectEntitiesRecursivelyAsync(m,t,o,n,[...r,u],a)}}}}async buildDatatypePropertyNamesAsync(e,t){let o=new Set,n=new Set;if(await this.collectDatatypePropertiesAsync(e,o,n,t),e.metadata.imports)for(let[r,a]of Object.entries(e.metadata.imports))for(let i of a){let c=await t.getHighestCompatibleVersionAsync(r,i);c&&await this.collectDatatypePropertiesAsync(c,o,n,t)}return o}async collectDatatypePropertiesAsync(e,t,o,n){let r=e.metadata.namespace_?.toString()??"";if(!o.has(r)){o.add(r);for(let[a,i]of Object.entries(e.body)){if(typeof i!="object"||i===null||Array.isArray(i))continue;let c=i.type;if(typeof c!="string")continue;(c.includes(".")?c.substring(c.lastIndexOf(".")+1):c)==="DatatypeProperty"&&t.add(a)}if(e.metadata.imports)for(let[a,i]of Object.entries(e.metadata.imports))for(let c of i){let s=await n.getHighestCompatibleVersionAsync(a,c);s&&await this.collectDatatypePropertiesAsync(s,t,o,n)}}}validateEntityReferences(e,t,o,n,r,a,i){for(let[c,s]of Object.entries(t)){let l=c;if(l&&!l.includes(".")){let m=o.get(l);if(m&&m.length>1&&!m.some(f=>f.startsWith("(local:"))){let f=m.filter(h=>!h.startsWith("(local:"));f.length>1&&i.push(this.createAmbiguityError(e,l,`Property '${l}'`,f,n,a,!0,l))}}this.validatePropertyValue(e,l,s,o,n,r,a,i)}}validatePropertyValue(e,t,o,n,r,a,i,c){if(o==null)return;let s=t&&t.includes(".")?t.substring(t.lastIndexOf(".")+1):t,l=!!s&&a.has(s);if(typeof o=="string"&&!o.includes(".")&&!l){let m=n.get(o);if(m&&m.length>1&&!m.some(f=>f.startsWith("(local:"))){let f=m.filter(h=>!h.startsWith("(local:"));f.length>1&&c.push(this.createAmbiguityError(e,t,`Reference '${o}'`,f,r,i,!1,o))}}else if(Array.isArray(o))for(let m=0;m<o.length;m++){let u=`${e}.${t}[${m}]`;this.validatePropertyValue(u,t,o[m],n,r,a,i,c)}else if(typeof o=="object"&&!Array.isArray(o)){let m=t?`${e}.${t}`:e;this.validateEntityReferences(m,o,n,r,a,i,c)}}createAmbiguityError(e,t,o,n,r,a,i,c){let s=[];for(let g of n){let D=this.findAliasForNamespace(a,g);if(D){let w=t?.split(".").pop()??t;s.push(`${D}.${w}`)}}let l=s.length>0?`Use one of: ${s.map(g=>`'${g}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${t}')`,m=n.map(g=>{let D=r.get(g);return!D||D.length===0?` \u2022 ${g}`:D.length===1?` \u2022 ${g} (direct import)`:` \u2022 ${g}
15
- imported via: ${D.join(" \u2192 ")}`}).join(`
16
- `),u=e.split(".")[0],f=e.includes(".")?e:t,h=new d;h.ruleType=this.ruleName,h.severity="Error",h.entityName=u,f&&(h.propertyName=f);let y=c??t;return y&&(h.actualValue=y),h.message=`${o} is ambiguous - defined in multiple imported namespaces`,h.suggestion=`${l}
17
-
18
- Defined in:
19
- ${m}`,h.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",h}findAliasForNamespace(e,t){if(!e.metadata.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n)if(`${o}/${r.packageName}@${r.version}`===t&&r.alias)return r.alias;return null}};var Eo={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Wt=p=>p,Oe=class{ruleName="PropertyRangeReference";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await P(e,t,o);for(let i of a){if(!(i instanceof k))continue;let c=q(r,i);if(c!=="ObjectProperty"&&c!=="DatatypeProperty")continue;let s=c==="ObjectProperty";for(let l of M(i,Eo))this.resolvesToClassLike(r,l)||n.push(this.error(i.name,l,s))}return n}resolvesToClassLike(e,t){let o=b(e,t);return o?j.isClassType(Wt(o))||j.isDatatypeType(Wt(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new d;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="range",r.actualValue=n,r.expectedValue=o?"A defined or imported class":"A datatype or defined class",r.message=`Property '${e}' has range '${t.name}' which is not defined or imported`,r.suggestion=o?`Define '${t.name}' as a Class here, or import the namespace that contains it (alias-qualify it if imported under an alias).`:`Use a datatype (xsd type, rdfs.Literal, or a datatype-derived type), or \u2014 if '${t.name}' is a class \u2014 make this an ObjectProperty.`,r}};var vo={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Ce="kanonak.org",dt="core-rdf",ft="core-owl",yt=p=>p,Do=[{uri:{publisher:Ce,package_:dt,name:"Class"},ok:(p,e)=>j.isClassType(yt(e))||j.isDatatypeType(yt(e))},{uri:{publisher:Ce,package_:dt,name:"Datatype"},ok:(p,e)=>j.isDatatypeType(yt(e))},{uri:{publisher:Ce,package_:dt,name:"Property"},ok:(p,e)=>Q(p,e)},{uri:{publisher:Ce,package_:ft,name:"ObjectProperty"},ok:(p,e)=>q(p,e)==="ObjectProperty"},{uri:{publisher:Ce,package_:ft,name:"DatatypeProperty"},ok:(p,e)=>q(p,e)==="DatatypeProperty"},{uri:{publisher:Ce,package_:ft,name:"AnnotationProperty"},ok:(p,e)=>q(p,e)==="AnnotationProperty"}],Pe=class{ruleName="ObjectPropertyValue";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await ue(e,t,o);for(let i of a)i instanceof k&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof ce)this.check(e,r.predicate?.subject,r.object.subject,o,n);else if(r instanceof J)this.walk(e,r.object,Ht(o,r.predicate?.subject),n);else if(r instanceof L){let a=r.predicate?.subject;for(let i of r.object)i instanceof N?this.check(e,a,i.subject,o,n):i instanceof V&&this.walk(e,i,Ht(o,a),n)}}check(e,t,o,n,r){if(!t)return;let a=b(e,t);if(!a)return;let i=E(a,vo);if(!i)return;let c=Do.find(l=>Z(i,l.uri));if(!c)return;let s=b(e,o);s&&(c.ok(e,s)||r.push(this.warn(n,t,i,o)))}warn(e,t,o,n){let r=new d;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e.split(".")[0],r.propertyName=e,r.actualValue=n.name,r.expectedValue=o.name,r.message=`Property '${t.name}' expects a ${o.name}, but '${n.name}' is not a ${o.name}`,r.suggestion=`Reference a resource that is a ${o.name}, or correct the type of '${n.name}'.`,r}};function Ht(p,e){return`${p}.${e?.name??"<embedded>"}`}var So={publisher:"kanonak.org",package_:"core-rdf",name:"domain"},$o={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},we=class{ruleName="PropertyDomain";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await ue(e,t,o);for(let i of a)i instanceof k&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){this.checkNode(e,t,o,n);for(let r of t.statement)if(r instanceof J)this.walk(e,r.object,Yt(o,r.predicate?.subject),n);else if(r instanceof L)for(let a of r.object)a instanceof V&&this.walk(e,a,Yt(o,r.predicate?.subject),n)}checkNode(e,t,o,n){let r=pe(t);if(r.length===0)return;let a,i=()=>{if(!a){a=new Set([R($o)]);for(let s of r)for(let l of H(e,s))a.add(R(l))}return a},c=new Set;for(let s of t.statement){let l=Io(s);if(!l||nt(l.name)||c.has(R(l)))continue;c.add(R(l));let m=b(e,l);if(!m)continue;let u=M(m,So);u.length!==0&&(u.some(f=>i().has(R(f)))||n.push(this.error(o,l,u,r[0])))}}error(e,t,o,n){let r=o.map(i=>i.name).join(" | "),a=new d;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e.split(".")[0],a.propertyName=e,a.actualValue=t.name,a.expectedValue=`Property used on ${r} or its subclasses`,a.message=`Property '${t.name}' has domain '${r}' but is used on '${n.name}' at '${e}'`,a.suggestion=`Either:
20
- 1. Use '${t.name}' only on '${r}' (or a subclass) instances
21
- 2. Widen the property's domain to include '${n.name}'
22
- 3. Use a different property for '${n.name}'`,a}};function Io(p){return p.predicate?.subject}function Yt(p,e){return`${p}.${e?.name??"<embedded>"}`}var jo={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Oo={publisher:"kanonak.org",package_:"core-rdf",name:"Literal"},Co=p=>p,Ue=class{ruleName="PropertyKindRangeConsistency";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await P(e,t,o);for(let i of a){if(!(i instanceof k))continue;let c=q(r,i);if(c!=="ObjectProperty"&&c!=="DatatypeProperty")continue;let s=c==="ObjectProperty",l=c==="DatatypeProperty",m=E(i,jo);if(!m||!b(r,m))continue;let u=Po(r,m);l&&!u?n.push(this.error(i.name,m,"datatype")):s&&u&&n.push(this.error(i.name,m,"object"))}return n}error(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="range",n.actualValue=t.name,o==="datatype"?(n.expectedValue="A datatype (xsd type, rdfs.Literal, or a datatype-derived class)",n.message=`DatatypeProperty '${e}' has range '${t.name}', which is a class, not a datatype. A datatype property's values are literals.`,n.suggestion=`Use a datatype range (e.g. xsd.string, rdfs.Literal, or a datatype-derived class), or \u2014 if '${t.name}' is the intended target \u2014 declare '${e}' an ObjectProperty.`):(n.expectedValue="A plain class (not datatype-derived)",n.message=`ObjectProperty '${e}' has range '${t.name}', which is a datatype, not a class. An object property's values are references to resources.`,n.suggestion=`Declare '${e}' a DatatypeProperty (its values are literals of '${t.name}'), or change the range to a plain class.`),n}};function Po(p,e){for(let t of H(p,e)){if(Z(t,Oo))return!0;let o=b(p,t);if(o&&j.isDatatypeType(Co(o)))return!0}return!1}var Ae=class{ruleName="ReservedNameShadow";async validateAsync(e,t,o){let n=[],r=await P(e,t,o);for(let a of r){if(!(a instanceof k))continue;let i=jt(a.name);if(!i)continue;let c=x(a);c&&(i.publisher===c.publisher&&i.package_===c.package_||n.push(this.info(a.name,c,i)))}return n}info(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Info",n.entityName=e,n.propertyName=e,n.actualValue=`${t.publisher}/${t.package_}/${e}`,n.expectedValue=`${o.publisher}/${o.package_}/${e}`,n.message=`'${e}' is also the reserved built-in '${o.publisher}/${o.package_}/${e}'. This local definition shadows it \u2014 a bare '${e}' reference in this package resolves to the local entity, not the built-in.`,n.suggestion=`If this is intentional, qualify bare references to '${e}' explicitly (this local one vs. the built-in '${o.publisher}/${o.package_}/${e}') so the choice is unambiguous to readers and tools \u2014 e.g. a self-referential 'subClassOf: ${e}' silently resolves to this local entity.`,n}};var wo={publisher:"kanonak.org",package_:"core-rdf",name:"type"},Gt=p=>p,Ne=class{ruleName="ClassDefinition";async validateAsync(e,t,o){let n=[],r=await $(e,t,o),a=await P(e,t,o);return F(a,({kanonak:i,path:c})=>{for(let s of M(i,wo))this.resolvesToClassLike(r,s)||n.push(this.error(c,s))}),n}resolvesToClassLike(e,t){if(nt(t.name))return!0;let o=b(e,t);return o?j.isClassType(Gt(o))||j.isDatatypeType(Gt(o)):!1}error(e,t){let o=`${t.publisher}/${t.package_}/${t.name}`,n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="type",n.actualValue=o,n.expectedValue="Defined or imported class",n.message=`Class '${t.name}' is not defined or imported`,n.suggestion=`Define '${t.name}' as a Class in this document, or import a namespace that contains it`,n}};var Te=class{ruleName="MarkdownLink";async validateAsync(e,t,o){let n=[],r=await P(e,t,o);return F(r,({kanonak:a,path:i})=>{this.checkNode(a,i,n)}),n}checkNode(e,t,o){for(let n of e.statement)if(n instanceof ot)this.checkProse(n.object,n.links,t,n.predicate.subject?.name??"(unknown)",o);else if(n instanceof L){let r=n.predicate.subject?.name??"(unknown)";(n.object??[]).forEach((a,i)=>{a instanceof tt&&a.links&&this.checkProse(String(a.value),a.links,t,`${r}[${i}]`,o)})}}checkProse(e,t,o,n,r){for(let a of t)a.target||r.push(this.unresolvedLinkError(o,n,a.reference));for(let a of Ct(e))r.push(this.malformedLinkError(o,n,a.snippet))}unresolvedLinkError(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`Embedded link [[${o}]] in '${t}' could not be resolved`,n.expectedValue="A reference resolvable through the document's import closure",n.suggestion=`The reference '${o}' inside a markdown value cannot be found in the current document or any imported namespace.
23
-
24
- Possible solutions:
25
- \u2022 Import the package that defines '${o}' so the link can resolve
26
- \u2022 Check for typos in the reference name
27
- \u2022 If the name collides across imports, alias-qualify it: [[alias.${o}]]`,n}malformedLinkError(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`Malformed embedded reference near '${o}' in '${t}'`,n.expectedValue="A single-line [[reference]] with no internal line break",n.suggestion=`A '[[' in '${t}' does not form a complete [[reference]] link.
28
-
29
- A reference may not span a line break \u2014 the most common cause is wrapping a
30
- long reference across two lines in a block scalar, e.g.:
31
- ... read for [[persistent-energy-
32
- shock]] held ...
33
- which is parsed as literal text, not a link. Keep each [[reference]] on one
34
- line (let the line run long), or check for an unterminated [[.`,n}};var zt="kanonak.org",Xt="look",Uo={publisher:zt,package_:Xt,name:"displayLabel"},Ao={publisher:zt,package_:Xt,name:"displaySummary"},xe=class{ruleName="DisplayLensScope";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new O().parseKanonaks(new B(e,t));let a=No(e);if(!a)return n;for(let i of r)i instanceof k&&i.namespace===a&&(this.checkLens(r,i,Uo,"displayLabel",n),this.checkLens(r,i,Ao,"displaySummary",n));return n}checkLens(e,t,o,n,r){let a=E(t,o);if(!a)return;let i=[],c=x(t);if(c&&i.push(c),i.push(...pe(t)),i.length===0)return;i.some(l=>Y(e,l,a).ok)||r.push(this.scopeError(t.name,n,a.name))}scopeError(e,t,o){let n=new d;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`${t} points at '${o}', which is not a property in scope for '${e}'`,n.expectedValue="A property whose domain is this resource's class, an ancestor, or rdfs.Resource",n.suggestion=`'${o}' resolves, but its domain does not cover '${e}', so the lens would silently fall back to the resource's name at render time.
35
-
36
- Possible solutions:
37
- \u2022 Point ${t} at a property declared on this class (or an ancestor / rdfs.Resource)
38
- \u2022 Set the property's domain to this class if it should apply here
39
- \u2022 Use rdfs.label / rdfs.comment for the universal default`,n}};function No(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}function ae(p,e,t){let o=[];return ze(p,t,{input:e},o),o}function ze(p,e,t,o){if(A(e,z.VarRef)){let a=te(e,z.varName);return a?t[a]:void 0}if(A(e,z.PropertyRead)){let a=C(e,z.readSource),i=a?ze(p,a,t,o):void 0,c=E(e,z.readProp);if(!i||!c)return;let s=Y(p,i,c);if(!s.ok){o.push({contextClass:i,propertyUri:c,via:"PropertyRead"});return}return s.descriptor?.range}if(A(e,z.Traverse)){let a=C(e,z.traverseSource),i=a?ze(p,a,t,o):void 0,c=E(e,z.through),s;if(i&&c){let m=Y(p,i,c);m.ok?s=m.descriptor?.range:o.push({contextClass:i,propertyUri:c,via:"Traverse"})}let l=C(e,z.step);return l?ze(p,l,{...t,input:s},o):void 0}let n=te(e,z.loopVar),r=n?{...t,[n]:void 0}:t;for(let a of To(e))ze(p,a,r,o)}function To(p){let e=[];for(let t of p.statement){let o=t.object;if(o instanceof V)e.push(o);else if(Array.isArray(o))for(let n of o)n instanceof V&&e.push(n)}return e}var Xe="kanonak.org",Ze="look",xo={publisher:Xe,package_:Ze,name:"semanticSvg"},_o={publisher:Xe,package_:Ze,name:"tierChip"},Lo={publisher:Xe,package_:Ze,name:"tierIcon"},Mo={publisher:Xe,package_:Ze,name:"tierCard"},Bo={publisher:Xe,package_:Ze,name:"tierFull"},qo=[_o,Lo,Mo,Bo],_e=class{ruleName="LookSemanticSvgPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new O().parseKanonaks(new B(e,t));let a=Fo(e);if(!a)return n;for(let i of r)i instanceof k&&i.namespace===a&&this.checkSemanticSvg(r,i,n);return n}checkSemanticSvg(e,t,o){let n=C(t,xo);if(!n)return;let r=x(t);if(r)for(let a of qo){let i=C(n,a);if(i)for(let c of ae(e,r,i))o.push(this.toError(t.name,a.name,c))}}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=r===e?`'${e}' (the class this SemanticSvg is declared on)`:`'${r}', reached by traversal from '${e}' (the class this SemanticSvg is declared on)`,i=new d;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=`look.semanticSvg.${t}`,i.actualValue=n,i.message=`tx.${o.via} reads property '${o.propertyUri.name}' off the rendered instance, but its domain is not in scope for ${a}. The read would silently return undefined at render time.`,i.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,i.suggestion=`Property '${n}' is not in scope for '${r}'.
40
-
41
- Possible solutions:
42
- \u2022 Read a property declared on '${r}' (or an ancestor / rdfs.Resource)
43
- \u2022 If the property should apply to '${r}', adjust its domain
44
- \u2022 If the value comes from a pre-computed env binding, use tx.VarRef instead of PropertyRead`,i}};function Fo(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Zt={publisher:"kanonak.org",package_:"transformations",name:"Expression"},Wo=new Map([["look","the look renderer"],["view","the view materializer"],["transformations","the transformation runner"]]);function Qt(p){if(!(!p||p.publisher!=="kanonak.org"))return Wo.get(p.package_)}var Le=class{ruleName="TxExpressionCompiles";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(new B(e,t)),a=Go(e);if(!a)return n;let i=r.filter(y=>y instanceof k&&y.namespace===a);if(i.length===0)return n;let c=new Map,s=y=>{for(let g of Dt(y)){let D=R(g),w=c.get(D);if(w===void 0&&(w=Z(g,Zt)||H(r,g).some(I=>Z(I,Zt)),c.set(D,w)),w)return!0}return!1},l=[],m=new Map,u=new Map,f=new Set;for(let y of i)F([y],({kanonak:g,path:D})=>{let w=g instanceof V&&s(g);w&&l.push({node:g,path:D,subject:y.name});for(let{child:I,predicate:S}of Yo(g))s(I)&&(S&&m.set(I,S),w&&f.add(I));if(!w){for(let I of Ho(g))if(Qt(I))for(let S of oe(g,I)){if(!(S.item instanceof N))continue;let G=b(r,S.item.subject);G&&s(G)&&(l.push({node:G,path:`${D}.${I.name}`,subject:y.name}),u.set(G,I))}}});let h=new Set;for(let{node:y,path:g,subject:D}of l){if(y instanceof V&&f.has(y))continue;let w=Qt(y instanceof V?m.get(y):u.get(y));if(w)try{wt(y,g,{catalog:r,depth:0})}catch(I){let S=I instanceof Error?I.message:String(I),G=`${D} ${g} ${S}`;if(h.has(G))continue;h.add(G),n.push(this.toError(D,g,S,w))}}return n}toError(e,t,o,n){let r=new d;r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=o;let a=/[.!?]$/.test(o)?o:`${o}.`;return r.message=`A tx.Expression at '${t}' is in a slot ${n} evaluates, but it cannot be compiled: ${a} The value would be silently absent wherever this slot is used.`,r.expectedValue=`A tx.Expression built from node classes ${n} implements`,r.suggestion=`This slot is evaluated by ${n}, which is part of this SDK, so its node classes are the ones available here. (An Expression subclass meant for a DIFFERENT runner is fine in that runner's own slots \u2014 this rule does not look at those.)
45
-
46
- Possible solutions:
47
- \u2022 Rebuild the expression from tx primitives this SDK supports
48
- \u2022 For numeric presentation (rounding, percentages, fixed precision), use tx.NumberFormat \u2014 it scales internally, so no arithmetic is needed
49
- \u2022 If the node class should be supported, implement it in the runner first`,r}};function Ho(p){let e=new Map;for(let t of p.statement){let o=t.predicate?.subject;o&&!e.has(R(o))&&e.set(R(o),o)}return[...e.values()]}function Yo(p){let e=[];for(let t of p.statement){let o=t.predicate?.subject;if(t instanceof J)e.push({child:t.object,predicate:o});else if(t instanceof L)for(let n of t.object)n instanceof V&&e.push({child:n,predicate:o})}return e}function Go(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var zo="kanonak.org",Qe=(p,e)=>({publisher:zo,package_:p,name:e}),Xo=Qe("derivation","look"),Jt=Qe("look","bands"),eo=Qe("look","Sequence"),Zo=Qe("core-rdf","range"),Qo=Qe("look","nodeTier"),Me=class{ruleName="SequenceNarrative";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(new B(e,t)),a=Jo(e);if(!a)return n;let i=r.filter(s=>s instanceof k&&s.namespace===a);if(i.length===0)return n;for(let s of i){let l=C(s,Xo);l&&T(l,Jt).forEach((m,u)=>{!(m instanceof V)||!A(m,eo)||n.push(...this.checkBand(r,s,m,`${s.name}.look.bands[${u}]`))})}let c=new xt(r);for(let s of i){let l=c.findCascadedLook(s);if(l)for(let m of T(l.declaration,Jt))!(m instanceof V)||!A(m,eo)||this.checkBand(r,s,m,"").length>0||n.push(...this.checkInstance(r,s,m,At(r,s,m)))}return n}checkBand(e,t,o,n){let r=[],a=(l,m,u)=>r.push(this.toError("Error",t.name,n,l,m,u)),i=ct(o);if(!i)a("A look.Sequence band declares no look.source. The order of a sequence comes from the [[references]] in a prose property, so without one nothing can be sequenced.","Set look.source to a property of this class whose rdfs.range is prose.Markdown (or prose.SubstitutableString), and render the same property with a look.Markdown band so the narrative and the diagram cannot drift.");else{let l=St(e,i)[0],m=l?M(l,Zo):[];l&&!m.some(u=>vt.isSubstitutableDatatypeUri(u))&&a(`look.source names '${i.name}', whose rdfs.range is ${m.map(u=>R(u)).join(", ")||"undeclared"} \u2014 not prose.Markdown. A Sequence orders its participants by the [[references]] in prose, so a value of this property carries no order.`,"Point look.source at a prose.Markdown-ranged property, or give this property that range if its values are narrative.",R(i))}let c=pt(e,o);c.length===0&&a("A look.Sequence band declares no look.connectors, so no property counts as a message and every narrative renders empty.","List the object properties that constitute messages: look.connectors: [{ look.relation: calls }, ...]. The domain ontology declares nothing about sequences; the look layer says which of its relations are interactions.");for(let l of c)(!l.subject||q(e,l.subject)===void 0)&&a(`look.connectors names '${l.relation.name}' as a relation, but it is not a property${l.subject?"":" in the closure"}. A message is a triple, so its relation must be an object property whose values are the participants.`,"Use an owl.ObjectProperty (or a subclass such as owl.SymmetricProperty) for look.relation.",R(l.relation)),l.invalidStyle!==void 0&&a(`look.lineStyle '${l.invalidStyle}' on connector '${l.relation.name}' is not a supported value. Supported: ${[...Ut].join(", ")}.`,"Use one of the supported values, or omit look.lineStyle: a reply is derived from owl.inverseOf and an undirected edge from owl.SymmetricProperty, so the overlay is only needed for what the ontology cannot say.",l.invalidStyle);let s=te(o,Qo);return s!==void 0&&lt[s]===void 0&&a(`look.nodeTier '${s}' is not a tier. Supported: ${Object.keys(lt).join(", ")}.`,"Use one of the semantic-zoom tiers \u2014 chip (56), icon (120, the default), card (240), full (420) \u2014 or omit look.nodeTier to take the participants' class-level look.diagramTier.",s),r}checkInstance(e,t,o,n){let r=[],a=ct(o),i=`${t.name}.${a.name}`,c=pt(e,o).map(s=>s.relation.name).join(", ");if(n.problem)return r.push(this.toError("Error",t.name,i,`The look.Sequence band cannot walk this instance: ${n.problem}.`,"Check the value authored for the source property.")),r;if(n.sourceAbsent)return r.push(this.toError("Warning",t.name,i,`'${t.name}' carries no value for '${a.name}', so its look.Sequence band renders nothing.`,`Author the narrative in '${a.name}' with [[references]] to the participants, or leave it if the band is meant to be empty here.`)),r;for(let s of n.strayPropertyRefs)r.push(this.toError("Error",t.name,i,`The narrative references property '${s.name}', which is not a declared connector of the look.Sequence band (declared: ${c}). A property reference between two participants selects the edge for that pair; one the band does not declare selects nothing, and the sentence draws no message.`,`Add { look.relation: ${s.name} } to look.connectors on the band, or reference one of the declared connectors instead.`,R(s)));if(n.mentions>=2&&n.messages.length===0)return r.push(this.toError("Error",t.name,i,`The narrative mentions ${n.mentions} participant references but joins nothing: no declared connector (${c}) holds between any consecutive pair, so the look.Sequence band renders no message.`,"Either the graph is missing the triples the prose describes (declare them on the participants), the band is missing the relation the prose relies on (add it to look.connectors), or the prose orders participants no relation joins (reorder it).")),r;for(let s of n.gaps){let l=s.selected?`'${s.selected.name}' does not hold`:`no declared connector (${c}) holds`;r.push(this.toError("Warning",t.name,i,`The narrative orders '${s.prev.name}' then '${s.next.name}', but ${l} between them in the graph, so no message is drawn for that pair.`,`If the prose is right, declare the relation on '${s.prev.name}' or '${s.next.name}' (or add it to look.connectors); if the graph is right, reorder the prose so consecutive references are joined. A mention that is meant to connect to nothing is fine \u2014 it simply gets no lifeline.`,`${s.prev.name} \u2192 ${s.next.name}`))}return r}toError(e,t,o,n,r,a){let i=new d;return i.ruleType=this.ruleName,i.severity=e,i.entityName=t,i.propertyName=o,i.message=n,i.suggestion=r,a!==void 0&&(i.actualValue=a),i}};function Jo(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var en="kanonak.org",v=(p,e)=>({publisher:en,package_:p,name:e}),tn=v("derivation","look"),on=v("look","bands"),nn=v("look","Distribution"),rn=v("look","StatRow"),an=v("look","VersionDelta"),sn=v("look","Timeline"),cn=v("look","VersionDiff"),pn=v("look","TimePlot"),ln=v("look","ReferenceList"),mn=v("look","Diagram"),un=v("look","alphaPath"),dn=v("look","betaPath"),ht=v("look","metricPath"),to=v("look","lowerPath"),oo=v("look","upperPath"),no=v("look","hueBy"),fn=v("look","statPath"),yn=v("look","laneBy"),ro=v("look","labelPath"),hn=v("look","badgePath"),kn=v("look","mapPath"),gn=v("look","nodeNote"),Rn=v("look","edgeValue"),bn=v("look","stats"),Kn=v("look","facets"),Vn=v("look","channels"),En=v("look","track"),vn=v("look","source"),Dn=v("look","relation"),Sn=v("look","entries"),Be=class{ruleName="LookBandPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new O().parseKanonaks(new B(e,t));let a=In(e);if(!a)return n;for(let i of r)i instanceof k&&i.namespace===a&&this.checkDeclaration(r,i,n);return n}checkDeclaration(e,t,o){let n=C(t,tn);if(!n)return;let r=x(t);if(!r)return;let a=T(n,on).filter(i=>i instanceof V);for(let i of a)for(let c of this.carriersOf(e,i,r))for(let s of ae(e,c.context,c.expr))o.push(this.toError(t.name,c.slot,s))}carriersOf(e,t,o){let n=[],r=(a,i)=>{let c=C(t,a);c&&n.push({slot:`look.${a.name}`,context:i,expr:c})};if(A(t,nn))for(let a of[un,dn,ht,to,oo,no])r(a,o);if(A(t,an)&&r(ht,o),A(t,rn)){let a=T(t,bn).filter(i=>i instanceof V);for(let i of a){let c=C(i,fn);c&&n.push({slot:"look.stats[].statPath",context:o,expr:c})}}if(A(t,sn)||A(t,cn)){let a=this.rangeOf(e,o,E(t,En));if(a)for(let i of[ht,to,oo,no])r(i,a)}if(A(t,pn)){let a=this.rangeOf(e,o,E(t,vn));if(a)for(let i of[yn,ro])r(i,a)}if(A(t,ln))for(let a of T(t,Sn)){let i=a instanceof V?void 0:$n(a),c=this.rangeOf(e,o,i);if(c)for(let s of[ro,hn])r(s,c)}if(A(t,mn)){let a=T(t,Kn).filter(i=>i instanceof V);for(let i of a){let c=this.rangeOf(e,o,E(i,Dn));if(!c)continue;let s=C(i,gn);s&&n.push({slot:"look.facets[].nodeNote",context:c,expr:s});let l=C(i,Rn);l&&n.push({slot:"look.facets[].edgeValue",context:c,expr:l});let m=T(i,Vn).filter(u=>u instanceof V);for(let u of m){let f=C(u,kn);f&&n.push({slot:"look.facets[].channels[].mapPath",context:c,expr:f})}}}return n}rangeOf(e,t,o){if(!o)return;let n=Y(e,t,o);return n.ok?n.descriptor?.range:void 0}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=new d;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=n,a.message=`tx.${o.via} reads property '${o.propertyUri.name}', but its domain is not in scope for '${r}' (the class this band carrier is evaluated against). The read would silently return undefined at render time and the band would render empty.`,a.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${n}' is not in scope for '${r}'.
50
-
51
- Possible solutions:
52
- \u2022 Read a property declared on '${r}' (or an ancestor / rdfs.Resource)
53
- \u2022 If the property should apply to '${r}', adjust its domain
54
- \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,a}};function $n(p){let e=p.subject;return e&&typeof e.name=="string"?e:void 0}function In(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var jn="kanonak.org",kt=(p,e)=>({publisher:jn,package_:p,name:e}),On=kt("derivation","look"),Cn=kt("look","bands"),Pn=kt("core-rdf","type"),Je=class{ruleName="UnrenderableBand";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(new B(e,t)),a=wn(e);if(!a)return n;let i=_t();for(let c of r){if(!(c instanceof k)||c.namespace!==a)continue;let s=C(c,On);if(!s)continue;let l=T(s,Cn).filter(m=>m instanceof V);for(let m of l){let u=this.typeOf(m);if(!u)continue;let f=`${u.publisher}/${u.package_}/${u.name}`;if(i.has(f))continue;let h=new d;h.ruleType=this.ruleName,h.severity="Warning",h.entityName=c.name,h.propertyName="derivation.look",h.actualValue=f,h.message=`Band '${u.name}' has no renderer, so this region of the page will be empty. The declaration is valid against the look vocabulary, but the renderer emits only an HTML comment for it \u2014 which a browser does not display, so the loss is silent. Use a band the renderer implements, or remove it until it is supported.`,n.push(h)}}return n}typeOf(e){let t=E(e,Pn);if(t)return{publisher:t.publisher,package_:t.package_,name:t.name}}};function wn(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Fe="kanonak.org",We="view",Un={publisher:Fe,package_:We,name:"bind"},An={publisher:Fe,package_:We,name:"produces"},Nn={publisher:Fe,package_:We,name:"projections"},Tn={publisher:Fe,package_:We,name:"where"},xn={publisher:Fe,package_:We,name:"value"},_n={publisher:Fe,package_:We,name:"as"},qe=class{ruleName="TxExpressionPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new O().parseKanonaks(new B(e,t));let a=Bn(e);if(!a)return n;for(let i of r)i instanceof k&&i.namespace===a&&this.checkView(r,i,n);return n}checkView(e,t,o){let n=E(t,Un);if(!n)return;let r=E(t,An),a=0;for(let c of Mn(e,T(t,Nn))){let s=C(c,xn);if(s)for(let m of ae(e,n,s))o.push(this.toError(t.name,`view.projections[${a}].value`,n,m));let l=E(c,_n);l&&r&&(Y(e,r,l).ok||o.push(this.asError(t.name,a,r,l))),a+=1}let i=0;for(let c of Ln(t,Tn)){for(let s of ae(e,n,c))o.push(this.toError(t.name,`view.where[${i}]`,n,s));i+=1}}asError(e,t,o,n){let r=`${n.publisher}/${n.package_}/${n.name}`,a=new d;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=`view.projections[${t}].as`,a.actualValue=r,a.message=`Projection stores its value under property '${n.name}', but that property's domain is not in scope for the view's produces class '${o.name}'. The materialized result instance could not carry this value.`,a.expectedValue=`A property whose domain is '${o.name}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${r}' is not in scope for produces class '${o.name}'.
55
-
56
- Possible solutions:
57
- \u2022 Use an output property whose domain covers '${o.name}'
58
- \u2022 Define a new property in the ViewPackage with domain '${o.name}' and the right range
59
- \u2022 If the value belongs on a different output class, adjust the view's produces`,a}toError(e,t,o,n){let r=`${n.propertyUri.publisher}/${n.propertyUri.package_}/${n.propertyUri.name}`,a=n.contextClass.name,i=a===o.name?`the view's bound class '${o.name}'`:`'${a}', reached by traversal from the view's bound class '${o.name}'`,c=new d;return c.ruleType=this.ruleName,c.severity="Error",c.entityName=e,c.propertyName=t,c.actualValue=r,c.message=`tx.${n.via} reads property '${n.propertyUri.name}', but its domain is not in scope for ${i}. The read would silently return undefined when the view materializes.`,c.expectedValue=`A property whose domain is '${a}', an ancestor, or rdfs.Resource`,c.suggestion=`Property '${r}' is not in scope for '${a}'.
60
-
61
- Possible solutions:
62
- \u2022 Read a property declared on '${a}' (or an ancestor / rdfs.Resource)
63
- \u2022 If the property should apply to '${a}', adjust its domain
64
- \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,c}};function Ln(p,e){let t=C(p,e);return t?[t]:T(p,e).filter(o=>o instanceof V)}function Mn(p,e){let t=[];for(let o of e)if(o instanceof V)t.push(o);else if(o instanceof N){let n=b(p,o.subject);n&&t.push(n)}return t}function Bn(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var et="kanonak.org",qn="core-shacl",_=p=>({publisher:et,package_:qn,name:p}),ao=_("NodeShape"),io=_("PropertyShape"),Fn=_("targetClass"),gt=_("property"),Rt=_("path"),Wn=_("minCount"),Hn=_("maxCount"),Yn=_("datatype"),Gn=_("class"),so=_("in"),zn=_("pattern"),Xn=_("flags"),Zn=_("minLength"),Qn=_("maxLength"),Jn=_("minInclusive"),er=_("maxInclusive"),tr={publisher:et,package_:"core-rdf",name:"range"},or=new Set(["decimal","integer","int","long","short","byte","float","double","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte"]),co=p=>p,He=class{ruleName="ShaclShape";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(t),a=nr(e);if(!a)return n;let i=new Set;for(let c of r){if(!(c instanceof k)||c.namespace!==a||!A(c,ao))continue;let s=E(c,Fn);s?this.resolvesToClass(r,s)||n.push(this.err(c.name,"targetClass","Error",`NodeShape '${c.name}' sh:targetClass '${s.name}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",X(s))):n.push(this.err(c.name,"targetClass","Error",`NodeShape '${c.name}' has no sh:targetClass; it constrains nothing.`,"Add sh:targetClass naming the class this shape applies to."));for(let{item:l}of oe(c,gt)){let m;if(l instanceof V)m=l;else if(l instanceof N){let u=b(r,l.subject);u&&(m=u,i.add(R(l.subject)))}m&&this.checkPropertyShape(r,c.name,m,s??void 0,n)}}for(let c of r){if(!(c instanceof k)||c.namespace!==a||!A(c,io))continue;let s=x(c);s&&i.has(R(s))||this.checkPropertyShape(r,c.name,c,void 0,n)}return n}checkPropertyShape(e,t,o,n,r){let a=E(o,Rt);if(!a){r.push(this.err(t,"property.path","Error",`A PropertyShape on '${t}' has no sh:path; a PropertyShape must name the property it constrains.`,"Add sh:path naming a property."));return}let i=b(e,a),c=i?Q(e,i):!1;c?n&&(Y(e,n,a).ok||r.push(this.err(t,"property.path","Warning",`sh:path '${a.name}' is not in scope for sh:targetClass '${n.name}'; the constraint would never bind a value.`,`Constrain a property whose domain is '${n.name}', an ancestor, or rdfs.Resource.`,X(a)))):r.push(this.err(t,"property.path","Error",`sh:path '${a.name}' on '${t}' does not resolve to a property.`,"Reference a defined or imported property.",X(a)));let s=E(o,Yn),l=E(o,Gn);s&&l&&r.push(this.err(t,"property","Error",`A PropertyShape on '${t}' sets both sh:datatype and sh:class; a value is a literal or a node, not both.`,"Keep sh:datatype (literal values) or sh:class (node values), not both.")),s&&!this.resolvesToDatatype(e,s)&&r.push(this.err(t,"datatype","Error",`sh:datatype '${s.name}' on '${t}' does not resolve to a datatype.`,"Reference an xsd datatype or rdfs.Datatype.",X(s))),l&&!this.resolvesToClass(e,l)&&r.push(this.err(t,"class","Error",`sh:class '${l.name}' on '${t}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",X(l)));let m=ie(ee(o,Wn)),u=ie(ee(o,Hn));this.checkOrder(t,"minCount",m,"maxCount",u,r);let f=ie(ee(o,Zn)),h=ie(ee(o,Qn));this.checkOrder(t,"minLength",f,"maxLength",h,r);let y=ie(ee(o,Jn)),g=ie(ee(o,er));this.checkOrder(t,"minInclusive",y,"maxInclusive",g,r);let D=te(o,zn);if(D!==void 0){let S=te(o,Xn);try{new RegExp(D,S)}catch{r.push(this.err(t,"pattern","Error",`sh:pattern on '${t}' is not a valid regular expression`+(S!==void 0?` (with flags '${S}')`:"")+`: ${D}`,"Provide a valid regular expression and flags.",D))}}if(W(o,so)&&oe(o,so).length===0&&r.push(this.err(t,"in","Error",`sh:in on '${t}' is empty; an enumeration must list at least one permitted value.`,"List the permitted literal values, or remove sh:in.")),c&&n){let G=Y(e,n,a).descriptor;G&&((D!==void 0||f!==void 0||h!==void 0)&&G.kind==="object"&&r.push(this.err(t,"pattern/minLength/maxLength","Warning",`String facets on '${t}' apply to '${a.name}', which is an object property; string facets constrain literal values.`,"Apply string facets to a datatype property, or use sh:class for node values.",X(a))),(y!==void 0||g!==void 0)&&!this.isNumericDatatypeRange(G.range)&&r.push(this.err(t,"minInclusive/maxInclusive","Warning",`Numeric bounds on '${t}' apply to '${a.name}', whose range is not a numeric datatype.`,"Apply numeric bounds to a numeric datatype property.",X(a))))}let w=i&&c?E(i,tr):void 0,I=i&&c?this.isDatatypeProperty(e,i,w):!1;if(W(o,st)){let S=E(o,st);I?r.push(this.err(t,"hasValue","Error",`sh:hasValue on '${t}' constrains '${a.name}', a datatype property; a literal hasValue is not supported yet.`,"Use sh:hasValue on an object property, naming an individual; literal values arrive with structured literals (typescript#115).",S?X(S):void 0)):!S||!b(e,S)?r.push(this.err(t,"hasValue","Error",`sh:hasValue${S?` '${S.name}'`:""} on '${t}' does not resolve to an individual.`,"Name a defined or imported individual.",S?X(S):void 0)):w&&this.resolvesToClass(e,w)&&!this.isInstanceOf(e,S,w)&&r.push(this.err(t,"hasValue","Warning",`sh:hasValue '${S.name}' on '${t}' is not an instance of '${w.name}', the range of '${a.name}'; no well-typed value can equal it.`,`Name an instance of '${w.name}'.`,X(S)))}this.checkQualified(e,t,o,w,r)}checkQualified(e,t,o,n,r){let a=W(o,ne),i=[{name:"qualifiedMinCount",uri:$t,value:void 0},{name:"qualifiedMaxCount",uri:It,value:void 0}],c=!1;for(let y of i){if(!W(o,y.uri))continue;c=!0;let g=ie(ee(o,y.uri));g===void 0||!Number.isInteger(g)||g<0?r.push(this.err(t,y.name,"Error",`sh:${y.name} on '${t}' must be a non-negative integer.`,`Set sh:${y.name} to 0 or more.`)):y.value=g}if(!a&&!c)return;if(!a){r.push(this.err(t,"qualifiedValueShape","Error",`A qualified count on '${t}' has no sh:qualifiedValueShape; it counts values conforming to nothing.`,"Add sh:qualifiedValueShape naming the shape the counted values conform to."));return}c||r.push(this.err(t,"qualifiedValueShape","Error",`sh:qualifiedValueShape on '${t}' has no sh:qualifiedMinCount or sh:qualifiedMaxCount; it bounds nothing.`,"Add sh:qualifiedMinCount and/or sh:qualifiedMaxCount.")),this.checkOrder(t,"qualifiedMinCount",i[0].value,"qualifiedMaxCount",i[1].value,r);let s=n&&this.resolvesToClass(e,n)?n:void 0,l=`${t} (qualified shape)`,m=C(o,ne);if(m){this.checkNestedShape(e,l,m,s,r);let y=this.qualifiedCycle(e,m,new Set);y&&this.pushCycle(t,y,r);return}let u=E(o,ne),f=u?b(e,u):void 0;if(!u||!f||!(A(f,ao)||A(f,io)||W(f,Rt))){r.push(this.err(t,"qualifiedValueShape","Error",`sh:qualifiedValueShape${u?` '${u.name}'`:""} on '${t}' does not resolve to a shape.`,"Reference a NodeShape or PropertyShape, or write the shape inline.",u?X(u):void 0));return}let h=this.qualifiedCycle(e,f,new Set([R(u)]));h&&this.pushCycle(t,[u.name,...h],r)}checkNestedShape(e,t,o,n,r){if(W(o,Rt)){this.checkPropertyShape(e,t,o,n,r);return}for(let{item:a}of oe(o,gt)){let i=a instanceof V?a:a instanceof N?b(e,a.subject):void 0;i&&this.checkPropertyShape(e,t,i,n,r)}}qualifiedCycle(e,t,o){let n=(r,a)=>{if(a){let i=R(a);if(o.has(i))return[a.name];let c=b(e,a);if(!c)return;let s=this.qualifiedCycle(e,c,new Set([...o,i]));return s?[a.name,...s]:void 0}return r?this.qualifiedCycle(e,r,o):void 0};if(W(t,ne)){let r=n(C(t,ne),E(t,ne));if(r)return r}for(let{item:r}of oe(t,gt)){let a=r instanceof V?n(r,void 0):r instanceof N?n(void 0,r.subject):void 0;if(a)return a}}pushCycle(e,t,o){o.push(this.err(e,"qualifiedValueShape","Error",`sh:qualifiedValueShape on '${e}' leads back to a shape already being checked (${t.join(" -> ")}); recursive shapes are not evaluated.`,"Break the cycle: a qualified value shape must not reference, directly or through other shapes, a shape that contains it."))}isDatatypeProperty(e,t,o){let n=q(e,t);return n==="DatatypeProperty"?!0:n==="ObjectProperty"?!1:o?this.resolvesToDatatype(e,o):!1}isInstanceOf(e,t,o){let n=b(e,t);if(!n)return!1;let r=R(o);return pe(n).some(a=>R(a)===r||H(e,a).some(i=>R(i)===r))}checkOrder(e,t,o,n,r,a){o!==void 0&&r!==void 0&&o>r&&a.push(this.err(e,`${t}/${n}`,"Error",`${t} (${o}) exceeds ${n} (${r}) on '${e}'.`,`Set ${t} <= ${n}.`))}resolvesToClass(e,t){let o=b(e,t);return o?j.isClassType(co(o)):!1}resolvesToDatatype(e,t){if(t.publisher===et&&t.package_==="core-rdf"&&t.name==="Literal")return!0;let o=b(e,t);return o?j.isDatatypeType(co(o)):!1}isNumericDatatypeRange(e){return!e||e.publisher===et&&e.package_==="core-rdf"&&e.name==="Literal"?!0:e.publisher===et&&e.package_==="core-xsd"&&or.has(e.name)}err(e,t,o,n,r,a){let i=new d;return i.ruleType=this.ruleName,i.severity=o,i.entityName=e,i.propertyName=t,i.message=n,i.suggestion=r,a!==void 0&&(i.actualValue=a),i}};function ie(p){return typeof p=="number"?p:void 0}function X(p){return`${p.publisher}/${p.package_}/${p.name}`}function nr(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var po={publisher:"kanonak.org",package_:"core-owl",name:"oneOf"},rr=p=>p,Ye=class{ruleName="OwlOneOf";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(t),a=ar(e);if(!a)return n;for(let i of r){if(!(i instanceof k)||i.namespace!==a||!W(i,po))continue;let c=T(i,po);if(c.length===0){n.push(this.err(i.name,"Warning",`owl:oneOf on '${i.name}' is empty; a closed enumeration must list at least one individual.`,"List the individuals that make up the enumeration, or remove owl:oneOf."));continue}for(let s of c)if(s instanceof tt)n.push(this.err(i.name,"Error",`owl:oneOf member '${String(s.value)}' on '${i.name}' is not a named individual; a class enumeration is of individuals (a misspelled or unimported individual reads as a literal). For a closed set of literal VALUES, constrain a property with sh:in instead.`,"Reference a defined or imported individual, or move literal value sets to a property sh:in.",String(s.value)));else if(s instanceof N){let l=b(r,s.subject);l&&j.isSchemaDefinitionType(rr(l))&&n.push(this.err(i.name,"Error",`owl:oneOf member '${s.subject.name}' on '${i.name}' is a class/property/datatype, not an individual.`,"List named individuals (instances), not schema definitions.",`${s.subject.publisher}/${s.subject.package_}/${s.subject.name}`))}}return n}err(e,t,o,n,r){let a=new d;return a.ruleType=this.ruleName,a.severity=t,a.entityName=e,a.propertyName="oneOf",a.message=o,a.suggestion=n,r!==void 0&&(a.actualValue=r),a}};function ar(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var ir=p=>p,sr=new Et("kanonak.org","core-rdf","Resource"),Ge=class{ruleName="DiamondNameClash";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new O().parseKanonaks(t),a=cr(e);if(!a)return n;let i=Nt(r);for(let c of r){if(!(c instanceof k)||c.namespace!==a||!j.isClassType(ir(c)))continue;let s=x(c);if(!s)continue;let l=H(r,s),m=R(s),u=new Set(l.map(h=>R(h)));u.delete(m),u.delete(R(sr));let f=new Map;for(let h of Ot(r,s)){if(!h.domains.some(D=>u.has(R(D))))continue;let g=f.get(h.uri.name);g?g.push(h):f.set(h.uri.name,[h])}for(let[h,y]of f){if(y.length<2)continue;let g=I=>Tt(i,l,I.uri)?.cardinality,D=new Set(y.map(I=>I.range?R(I.range):void 0).filter(I=>I!==void 0)),w=new Set(y.map(g).filter(I=>I!==void 0));D.size<=1&&w.size<=1||n.push(this.toError(c.name,h,y,g))}}return n}toError(e,t,o,n){let r=c=>{let s=`${c.uri.publisher}/${c.uri.package_}/${c.uri.name}`,l=c.range?`${c.range.publisher}/${c.range.package_}/${c.range.name}`:"no range",m=n(c);return`${s} (range ${l}${m?`, ${m}`:""})`},a=o.map(r).join("; "),i=new d;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=t,i.actualValue=a,i.message=`Class '${e}' inherits ${o.length} distinct properties named '${t}' with incompatible range or cardinality: ${a}. The generated interface would multiply-inherit '${t}' with conflicting types and could not compile.`,i.suggestion=`Disambiguate the diamond name-clash on '${t}':
65
- \u2022 rename one of the properties, or
66
- \u2022 re-domain one so it is not inherited by '${e}', or
67
- \u2022 restructure the hierarchy so '${e}' inherits only one '${t}', or
68
- \u2022 make the ranges/cardinalities compatible (identical) if they are meant to be the same property.`,i}};function cr(p){let e=p.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var bt=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e,t={}){this.parser=e??new Vt,this.documentRules=[new fe,new ye,new he,new ke,new ge],this.repositoryRules=[new Re,new be,new Ke,new de({offline:t.offline}),new Ve,new Ee,new ve,new De,new Se,new $e,new Ie,new je,new Oe,new Pe,new we,new Ue,new Ae,new Ne,new Te,new xe,new _e,new Be,new Je,new Me,new Le,new qe,new He,new Ye,new Ge]}async validateAsync(e,t,o){let n=new le;for(let r of this.documentRules)try{let a=r.validate(e);this.addErrorsToResult(n,a)}catch(a){let i=new d;i.ruleType=r.ruleName,i.severity="Error",i.message=`Validation rule '${r.ruleName}' failed: ${a instanceof Error?a.message:String(a)}`,n.errors.push(i)}if(t){let r=[],a=o??new re(new me(e,t)),i=a.repository;for(let c of this.repositoryRules)try{let s=await c.validateAsync(e,i,a);this.addErrorsToResult(n,s)}catch(s){let l=s instanceof Error?s.message:String(s);r.push({ruleName:c.ruleName,cause:l})}if(r.length>0){let c=new Map;for(let{ruleName:s,cause:l}of r){let m=c.get(l);m?m.push(s):c.set(l,[s])}for(let[s,l]of c){let m=new d;m.ruleType=l[0],m.severity="Error",l.length===1?m.message=`Validation rule '${l[0]}' failed: ${s}`:m.message=`${s} (affects ${l.length} rules: ${l.join(", ")})`,n.errors.push(m)}}}return n.isValid=n.errors.length===0,n}async validateDocumentsAsync(e,t){let o=t instanceof re?t:new re(t),n=[];for(let r of e){let a=await this.validateAsync(r,o.repository,o);n.push({document:r,result:a})}return n}async validateYamlAsync(e,t,o){let n=this.parser.parseWithErrors(e);if(!n.isValid){let r=new le;r.isValid=!1;for(let a of n.errors){let i=new d;i.ruleType="ParseError",i.severity="Error",i.lineNumber=a.line,i.column=a.column,i.message=a.message,a.keyName&&(i.entityName=a.keyName),a.errorType==="DuplicateKey"&&(i.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),r.errors.push(i)}return r}return await this.validateAsync(n.document,t,o)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let t=this.documentRules.findIndex(o=>o instanceof e);t>=0&&this.documentRules.splice(t,1)}removeRepositoryRule(e){let t=this.repositoryRules.findIndex(o=>o instanceof e);t>=0&&this.repositoryRules.splice(t,1)}addErrorsToResult(e,t){for(let o of t)o.severity==="Error"?e.errors.push(o):o.severity==="Info"?this.includeWarnings&&e.infos.push(o):this.includeWarnings&&e.warnings.push(o)}};export{le as a,K as b,d as c,mt as d,re as e,de as f,fe as g,ye as h,he as i,ke as j,ge as k,Re as l,be as m,Ke as n,Ve as o,Ee as p,ve as q,De as r,Se as s,$e as t,Ie as u,je as v,Oe as w,Pe as x,we as y,Ue as z,Ae as A,Ne as B,Te as C,xe as D,_e as E,Le as F,Me as G,Be as H,qe as I,He as J,Ye as K,Ge as L,bt as M};