@kanonak-protocol/sdk 6.6.0 → 6.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/browser.d.ts +1 -1
  2. package/dist/browser.js +1 -1
  3. package/dist/{chunk-OHF4RIKS.js → chunk-2GV6GXRF.js} +1 -1
  4. package/dist/{chunk-BDTJIUS4.js → chunk-3ABGZHKM.js} +1 -1
  5. package/dist/{chunk-5ZRVFYCP.js → chunk-6CI3HTKF.js} +1 -1
  6. package/dist/chunk-6USORWEP.js +1 -0
  7. package/dist/chunk-7IMLHHSA.js +1 -0
  8. package/dist/{chunk-CPENAANM.js → chunk-AZFLKLPB.js} +1 -1
  9. package/dist/{chunk-K76UUREI.js → chunk-F4UHQVGA.js} +1 -1
  10. package/dist/{chunk-I2T6ORSG.js → chunk-FCRP7KXR.js} +16 -16
  11. package/dist/{chunk-DQGXJDQU.js → chunk-FKLZDYWF.js} +1 -1
  12. package/dist/{chunk-IWPCPQQY.js → chunk-FYAZ345F.js} +1 -1
  13. package/dist/{chunk-FS7UGDEX.js → chunk-IT37WOHT.js} +1 -1
  14. package/dist/{chunk-WXXZOJ4O.js → chunk-NYCGUDVW.js} +1 -1
  15. package/dist/{chunk-TF23WBSZ.js → chunk-PXUSA72Q.js} +1 -1
  16. package/dist/chunk-Q2ZUKZEU.js +1 -0
  17. package/dist/{chunk-VJUZKHQU.js → chunk-QRF7AT2M.js} +1 -1
  18. package/dist/{chunk-LIN5SG5I.js → chunk-TR7PC72M.js} +1 -1
  19. package/dist/chunk-TVMOJ2QS.js +1 -0
  20. package/dist/{chunk-Z2444SWM.js → chunk-X2URIXH7.js} +1 -1
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +3 -3
  23. package/dist/parsing/KanonakObjectParser.d.ts +22 -2
  24. package/dist/parsing/index.js +1 -1
  25. package/dist/producer/index.js +1 -1
  26. package/dist/reasoning/index.js +1 -1
  27. package/dist/repositories/browser.js +1 -1
  28. package/dist/repositories/index.js +1 -1
  29. package/dist/resolution/index.js +1 -1
  30. package/dist/resolution/linkTargets.d.ts +45 -0
  31. package/dist/search/index.js +1 -1
  32. package/dist/server/index.js +1 -1
  33. package/dist/shacl/ConformanceScope.d.ts +34 -6
  34. package/dist/shacl/index.d.ts +2 -2
  35. package/dist/transformations/index.js +1 -1
  36. package/dist/uri-helpers/index.js +1 -1
  37. package/dist/validation/index.js +1 -1
  38. package/package.json +2 -2
  39. package/dist/KanonakUri-4VJGV3FN.js +0 -1
  40. package/dist/chunk-6WOPXTIL.js +0 -1
  41. package/dist/chunk-FUUTGGJS.js +0 -1
  42. package/dist/chunk-GGK6A6QK.js +0 -1
  43. package/dist/chunk-LK5SHY4B.js +0 -1
  44. package/dist/chunk-SBWD7EOG.js +0 -1
@@ -0,0 +1,45 @@
1
+ import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
2
+ import type { KanonakDocument, Import } from '@kanonak-protocol/types/document/models/types';
3
+ import type { Kanonak } from '../kanonaks/Kanonak.js';
4
+ import type { KanonakUri } from './KanonakUri.js';
5
+ /** One reference through a link import, and where it was written. */
6
+ export interface LinkReference {
7
+ uri: KanonakUri;
8
+ /** The locator of the node it was written on (`walkDefinedKanonaks`' path). */
9
+ where: string;
10
+ /** The local name of the property it is a value of. */
11
+ predicate: string;
12
+ }
13
+ /** A package a document references through a link import, resolved one hop out. */
14
+ export interface LinkedPackage {
15
+ /** `publisher/package`, as the URI of a reference through the link carries it. */
16
+ key: string;
17
+ publisher: string;
18
+ import_: Import;
19
+ /** Every reference through this link, in walk order. */
20
+ references: LinkReference[];
21
+ /** The version the link import resolves to; null when it did not resolve. */
22
+ target: KanonakDocument | null;
23
+ /** The repository's error, when resolving threw. */
24
+ failure?: string | undefined;
25
+ }
26
+ /**
27
+ * The packages `roots` reference through `document`'s `mode: link` imports,
28
+ * each resolved ONE HOP out through `repository` (typescript#111): the target
29
+ * package at the version its link import resolves to (workspace, cache, then
30
+ * HTTP, as the repository tiers them), never its own imports. A link import
31
+ * no reference uses is not resolved: declaring a link is harmless, and only
32
+ * following it costs.
33
+ *
34
+ * THE dereference of a link. `LinkTargetRule` verifies links with it, and a
35
+ * conformance scope reads link values through it (typescript#138), so the two
36
+ * passes cannot disagree about where a link points. References are object
37
+ * property values, list items and prose links.
38
+ */
39
+ export declare function resolveLinkedPackagesAsync(document: KanonakDocument, roots: Kanonak[], repository: IKanonakDocumentRepository): Promise<LinkedPackage[]>;
40
+ /**
41
+ * Whether a link's target package defines a resource with this name: its
42
+ * body, the dictionary the entity index is built from. The package's own
43
+ * imports are never consulted, which is what keeps a link one hop.
44
+ */
45
+ export declare function linkTargetDefines(target: KanonakDocument, name: string): boolean;
@@ -1,4 +1,4 @@
1
- import"../chunk-LIN5SG5I.js";import"../chunk-SC5M74NM.js";import{f as g}from"../chunk-CPENAANM.js";import"../chunk-QHABFCRC.js";import"../chunk-WXXZOJ4O.js";import"../chunk-SBWD7EOG.js";import"../chunk-5ZRVFYCP.js";import"../chunk-PEJALHXK.js";import{pa as m,xa as S}from"../chunk-6WOPXTIL.js";import{c as v,p,y as E}from"../chunk-LK5SHY4B.js";import"../chunk-F67UH4FD.js";import{c as x}from"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
1
+ import"../chunk-TR7PC72M.js";import"../chunk-SC5M74NM.js";import{f as g}from"../chunk-AZFLKLPB.js";import"../chunk-QHABFCRC.js";import"../chunk-NYCGUDVW.js";import"../chunk-Q2ZUKZEU.js";import"../chunk-6CI3HTKF.js";import"../chunk-PEJALHXK.js";import{pa as m,xa as S}from"../chunk-TVMOJ2QS.js";import{c as v,p,y as E}from"../chunk-6USORWEP.js";import"../chunk-F67UH4FD.js";import{c as x}from"../chunk-7IMLHHSA.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
2
2
  Install it with:
3
3
  npm install @huggingface/transformers
4
4
  (underlying import error: ${e.message})`)}return F({transformers:r})})()),y}function H(r,e){let t=0;for(let n=0;n<r.length;n++)t+=r[n]*e[n];return t}function R(r,e){return e?r.version?e.version?x(r.version,e.version)>0:!0:!1:!0}function K(r,e){let t=g(r,e),n=[t.label],s=S(e);if(s.length>0){let i=E(r,s[0]),a=i?g(r,i).label:s[0].name;a&&n.push(`\u2014 a ${a}.`)}return t.summary&&n.push(t.summary),n.join(" ")}function q(r){let e=new Map;for(let t of r){if(!(t instanceof v))continue;let n=m(t);if(!n)continue;let s=p(n),i=e.get(s);(!i||R(n,m(i)))&&e.set(s,t)}return[...e.values()].sort((t,n)=>{let s=m(t)?p(m(t)):t.name,i=m(n)?p(m(n)):n.name;return s.localeCompare(i)})}var k=class{entries=[];embedder;constructor(e={}){this.embedder=e.embedder}resolveEmbedder(){return this.embedder?Promise.resolve(this.embedder):U()}get size(){return this.entries.length}async build(e,t={}){let n=q(e);if(t.include&&(n=n.filter(t.include)),n.length===0)return this.entries=[],{size:0,cached:!1};let s=n.map(o=>K(e,o)),i=t.cacheDir,a;if(i){let o=C("sha256").update(h+"|"+w+`
@@ -1,4 +1,4 @@
1
- import{c as xe}from"../chunk-BDTJIUS4.js";import{a as ye,d as J,f as Se,h as Z}from"../chunk-K76UUREI.js";import{l as $e,t as X,u as Q}from"../chunk-Z2444SWM.js";import"../chunk-LIN5SG5I.js";import"../chunk-SC5M74NM.js";import{a as O,b as W}from"../chunk-VJUZKHQU.js";import{u as te}from"../chunk-CPENAANM.js";import"../chunk-QHABFCRC.js";import"../chunk-5FVUBF7N.js";import{a as fe}from"../chunk-WXXZOJ4O.js";import{k as re}from"../chunk-SBWD7EOG.js";import{a as B}from"../chunk-5ZRVFYCP.js";import{a as Re}from"../chunk-PEJALHXK.js";import"../chunk-6WOPXTIL.js";import{c as we,z as ee}from"../chunk-LK5SHY4B.js";import"../chunk-F67UH4FD.js";import{c as V,e as j,f as L,g as Y,l as ve}from"../chunk-GGK6A6QK.js";import{a as be}from"../chunk-FUUTGGJS.js";import{readFileSync as le,writeFileSync as Ie,mkdirSync as Fe}from"fs";import{join as ne}from"path";import Me from"js-yaml";var Pe=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function q(r){return Pe}function C(r){return`${r.publisher}/${r.package_}`}function H(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"},t=[];for(let o of r)if(o.origin==="missing"){let a=C(o),u=i[a]??"whatever this package contributes to rendering is lost";t.push(`Render-stack package ${a} is MISSING (${o.reason??"unknown reason"}) \u2014 ${u}. Fix: kanonak install ${a} (as the user running the render), or restore network access to ${o.publisher}.`)}else o.resolvedButNotInCatalog&&t.push(`Render-stack package ${C(o)} resolved (${o.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let o of e)t.push(`Import edge ${o.fromNamespace} \u2192 ${o.publisher}/${o.packageName} ${o.constraint} did NOT resolve (${o.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${o.fromNamespace} authors against ${o.publisher}/${o.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${o.constraint}-compatible version of ${o.publisher}/${o.packageName} to the workspace or cache (kanonak install ${o.publisher}/${o.packageName}), or bump the import in ${o.fromNamespace}.`);return t}function oe(r){let{publisher:e,availablePublishers:i,catalog:t,lookRenderer:o,localNamespaces:a,rawByNsKey:u,renderStack:p,producers:f,lockSource:y,configSource:s}=r,d=new Map,k=new Map,l=new Map,h=new Set;for(let S of t){if(!(S instanceof we))continue;let w=S.namespace||"";if(!a.has(w))continue;d.set(`${w}/${S.name}`,S);let P=w.split("/")[1]??"",[_,M]=P.split("@");if(!_||!M)continue;let E=Y(M);E&&(h.has(P)||(h.add(P),k.has(_)||k.set(_,[]),k.get(_).push({verStr:M,version:E})),S.name===_&&l.set(P,S))}for(let S of k.values())S.sort((w,P)=>V(P.version,w.version));return{publisher:e,availablePublishers:i,catalog:t,lookRenderer:o,localNamespaces:a,rawByNsKey:u,bySubject:d,pkgVersions:k,pkgSelfByVer:l,renderStack:p,...f?{producers:f}:{},...y?{lockSource:y}:{},...s?{configSource:s}:{}}}async function de(r,e={}){let i=new B,t=new fe(i),o=[],a=[];for(let c of Z(r)){let m;try{m=le(c,"utf-8")}catch{continue}let n;try{n=i.parse(m).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:m})}a.sort((c,m)=>V(m.version,c.version));for(let c of a)await t.saveDocumentAsync(i.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),o.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let u=[...new Set(o.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!u.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${u.join(", ")||"(none)"}`)}else if(u.length===1)p=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 o)c.publisher===p&&(f.add(`${c.publisher}/${c.package_}@${c.verStr}`),y.set(`${c.package_}@${c.verStr}`,c.source));let s=J(),d=new ye(s,!0,i),k={};e.httpCache&&(k.getFromCache=e.httpCache.getFromCache,k.onFetch=e.httpCache.onFetch),e.fetchFn&&(k.fetchFn=e.fetchFn),e.packageUrlTemplates&&(k.packageUrlTemplates=e.packageUrlTemplates);let l=e.repository??new Se(t,d,new Q(k)),h=e.log??(()=>{}),S=q(void 0),w=[],P=c=>c.map(m=>m.metadata.namespace_?.version).filter(m=>m!==void 0).sort((m,n)=>V(n,m)).map(j);if(!e.repository){h(`[render-stack] resolving ${S.length} ambient look-stack package(s); cache: ${s}`);let c=new X({...e.fetchFn?{fetchFn:e.fetchFn}:{},...e.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}});for(let m of S){let n=C(m),g=await t.getDocumentsByNamespaceAsync(m.publisher,m.package_);if(g.length>0){let v=P(g);w.push({...m,origin:"workspace",versions:v}),h(`[render-stack] ${n} \u2014 workspace (${v.join(", ")})`);continue}let b=await d.getDocumentsByNamespaceAsync(m.publisher,m.package_);if(b.length>0){let v=P(b);w.push({...m,origin:"cache",versions:v}),h(`[render-stack] ${n} \u2014 cache (${v.join(", ")})`);continue}try{let $=(await c.getLock(m.publisher))?.packages[`${m.publisher}/${m.package_}`];if(!$){let K=`publisher ${m.publisher} reachable but its lock does not pin ${m.package_}`;w.push({...m,origin:"missing",reason:K}),h(`[render-stack] ${n} \u2014 MISSING: ${K}`);continue}let I=$.version,{url:he,content:ke}=await c.fetchLockedSource(m.publisher,m.package_,$);await t.saveDocumentAsync(i.parse(ke),`${m.publisher}/${m.package_}@${I}`);try{let K=ne(s,m.publisher);Fe(K,{recursive:!0}),Ie(ne(K,`${m.package_}@${I}.kan.yml`),ke,"utf-8"),w.push({...m,origin:"fetched",versions:[I]}),h(`[render-stack] ${n}@${I} \u2014 fetched from ${he}, installed to cache`)}catch(K){w.push({...m,origin:"fetched",versions:[I]}),h(`[render-stack] ${n}@${I} \u2014 fetched from ${he}, but cache ${s} is NOT WRITABLE (${K.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(v){let $=`fetch failed: ${v.message}`;w.push({...m,origin:"missing",reason:$}),h(`[render-stack] ${n} \u2014 MISSING: ${$}`)}}}let _=(await t.getAllDocumentsAsync()).filter(c=>c.metadata.namespace_?.publisher===p);for(let c of S)_.push(...await l.getDocumentsByNamespaceAsync(c.publisher,c.package_));let M=[],E=await O(_,l,{onUnresolvedEdge:c=>M.push(c)}),A=l;if(!e.repository){for(let c of S)E.add(C(c));A=new W(l,E)}let T=await new re(i).parseKanonaks(A),ie=new te(T),ce=(c,m)=>ee(T,{publisher:c,package_:m,name:m}).length>0,N;if(e.repository){N=[];for(let c of S){let m=await l.getDocumentsByNamespaceAsync(c.publisher,c.package_);N.push(m.length>0?{...c,origin:"repository",versions:P(m)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else N=w.map(c=>c.origin==="missing"||ce(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let G=H(N,M);for(let c of G)h(`[render-stack] WARNING: ${c}`);let z={contractSource:"universal-default",cachePath:s,packages:N,warnings:G},D;try{D=le(ne(r,"kanonak.lock"),"utf-8")}catch{D=Ee(p,o,i)}let U;try{U=le(ne(r,".well-known","kanonak.json"),"utf-8")}catch{U=void 0}return oe({publisher:p,availablePublishers:u,catalog:T,lookRenderer:ie,localNamespaces:f,rawByNsKey:y,renderStack:z,...D?{lockSource:D}:{},...U?{configSource:U}:{}})}function Ee(r,e,i){let t=new Map;for(let a of e)a.publisher===r&&(t.has(a.package_)||t.set(a.package_,{verStr:a.verStr,source:a.source}));if(t.size===0)return;let o={};for(let a of[...t.keys()].sort()){let{verStr:u,source:p}=t.get(a),f={},y;try{y=i.parse(p).metadata?.imports}catch{y=void 0}for(let d of y?.[r]??[]){let k=t.get(d.packageName);k&&(f[`${r}/${d.packageName}`]=k.verStr)}let s={};for(let d of Object.keys(f).sort())s[d]=f[d];o[`${r}/${a}`]={version:u,resolved:`https://${r}/${a}/${u}.kan.yml`,integrity:xe(p),dependencies:s}}return Me.dump({version:"1",lastUpdated:"",packages:o},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as De,readFileSync as Ke,writeFileSync as Ve,mkdirSync as Ae}from"fs";import{join as _e}from"path";async function pe(r,e={}){let i=new B,t=ve(r),o=t.kind==="resource"?t.uri.publisher:t.publisher,a=e.log??(()=>{}),u=e.cacheRoot??J(),p=(n,g,b)=>_e(u,n,`${g}@${b}.kan.yml`),f=new Set,y=new Set,s=new Map,d=new Q({getFromCache:(n,g,b)=>{let v=p(n,g,b),$=De(v)?Ke(v,"utf-8"):null;return $!==null&&f.add(`${n}/${g}`),$},onFetch:(n,g,b,v)=>{y.add(`${n}/${g}`);try{let $=_e(u,n);Ae($,{recursive:!0}),Ve(p(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}:{},...e.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}}),k=new X(e.fetchFn?{fetchFn:e.fetchFn}:void 0),l;if(t.kind==="resource"){let n=t.uri.version;l=[n?{package_:t.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:t.uri.package_}]}else if(t.kind==="package"){let n=t.version;l=[n?{package_:t.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:t.package_}]}else l=((await k.getConfig(o)).featured_packages??[]).map(g=>({package_:g}));let h=async(n,g,b)=>{try{let v=b?i.buildImport(g,"=",b,n):i.buildImport(g,"*","0.0.0",n),$=await d.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 l){let{doc:g,error:b}=await h(o,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 "${o}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let P=q(),_="universal-default",M=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 ${P.length} ambient look-stack package(s) (contract: ${_}); cache: ${u}`);let E=[],A=[];for(let n of P){let g=C(n),{doc:b,error:v}=await h(n.publisher,n.package_,void 0);if(b){E.push(b);let $=M([b]),I=y.has(g)?"fetched":f.has(g)?"cache":"fetched";A.push({...n,origin:I,versions:$}),a(`[render-stack] ${g} \u2014 ${I} (${$.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 T=[],ie=await O([...S,...E],d,{onUnresolvedEdge:n=>T.push(n)}),ce=new W(d,ie),N=await new re(i).parseKanonaks(ce),G=new te(N),z=A.map(n=>n.origin==="missing"||ee(N,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),D=H(z,T);for(let n of D)a(`[render-stack] WARNING: ${n}`);let U={contractSource:_,cachePath:u,packages:z,warnings:D},c=new Set,m=new Map;for(let n of await d.getAllDocumentsAsync()){let g=n.metadata.namespace_;if(!g?.version||g.publisher!==o)continue;let b=j(g.version),v=`${g.publisher}/${g.package_}@${b}`;c.add(v);let $=await d.getDocumentContentAsync(v);$!==null&&m.set(`${g.package_}@${b}`,$)}return oe({publisher:o,availablePublishers:[o],catalog:N,lookRenderer:G,localNamespaces:c,rawByNsKey:m,renderStack:U})}import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";function se(r){let{lookRenderer:e,publisher:i,renderStack:t,catalog:o}=r,a=e.explainStylesheet(e.publisherSubject(i)),u=[...a.tokens.entries()].map(([l,h])=>({name:l,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=a.baseStylesheet,f={present:p.css!==void 0,...p.sourceNamespace!==void 0?{source:p.sourceNamespace}:{},...p.scope!==void 0?{scope:p.scope}:{},...p.css!==void 0?{bytes:p.css.length}:{},...p.problem!==void 0?{problem:p.problem}:{},candidates:p.candidates},y=new Map;for(let l of o){let h=l.namespace;h&&y.set(h,(y.get(h)??0)+1)}let s=[...y.entries()].map(([l,h])=>({namespace:l,resources:h})).sort((l,h)=>l.namespace.localeCompare(h.namespace)),d=e.expressionFailures().map(l=>({carrier:l.carrier,stage:l.stage,reason:l.reason})),k=d.map(l=>l.stage==="compile"?`Expression carrier "${l.carrier}" did not compile: ${l.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.`:`Expression carrier "${l.carrier}" failed to evaluate: ${l.reason} Consequence: that value renders as nothing. Fix: correct the expression, or make a value that may be absent explicitly optional.`);return{publisher:i,renderStack:{contractSource:t.contractSource,cachePath:t.cachePath,packages:t.packages.map(l=>({package_:C(l),origin:l.origin,...l.versions!==void 0?{versions:l.versions}:{},...l.reason!==void 0?{reason:l.reason}:{},...l.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:l.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:u,baseStylesheet:f,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},expressionCarriers:d,catalog:s,warnings:[...t.warnings,...a.warnings.filter(l=>!t.warnings.includes(l)),...k]}}function Te(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ue(r){let e=Te,i=r.warnings.length===0,t=r.expressionCarriers.map(s=>`<tr><td><code>${e(s.carrier)}</code></td><td>${e(s.reason)}</td></tr>`).join(`
1
+ import{c as xe}from"../chunk-3ABGZHKM.js";import{a as ye,d as J,f as Se,h as Z}from"../chunk-F4UHQVGA.js";import{l as $e,t as X,u as Q}from"../chunk-X2URIXH7.js";import"../chunk-TR7PC72M.js";import"../chunk-SC5M74NM.js";import{a as O,b as W}from"../chunk-QRF7AT2M.js";import{u as te}from"../chunk-AZFLKLPB.js";import"../chunk-QHABFCRC.js";import"../chunk-5FVUBF7N.js";import{a as fe}from"../chunk-NYCGUDVW.js";import{k as re}from"../chunk-Q2ZUKZEU.js";import{a as B}from"../chunk-6CI3HTKF.js";import{a as Re}from"../chunk-PEJALHXK.js";import"../chunk-TVMOJ2QS.js";import{c as we,z as ee}from"../chunk-6USORWEP.js";import"../chunk-F67UH4FD.js";import{c as V,e as j,f as L,g as Y,l as be,m as ve}from"../chunk-7IMLHHSA.js";import{readFileSync as le,writeFileSync as Ie,mkdirSync as Fe}from"fs";import{join as ne}from"path";import Me from"js-yaml";var Pe=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function q(r){return Pe}function C(r){return`${r.publisher}/${r.package_}`}function H(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"},t=[];for(let o of r)if(o.origin==="missing"){let a=C(o),u=i[a]??"whatever this package contributes to rendering is lost";t.push(`Render-stack package ${a} is MISSING (${o.reason??"unknown reason"}) \u2014 ${u}. Fix: kanonak install ${a} (as the user running the render), or restore network access to ${o.publisher}.`)}else o.resolvedButNotInCatalog&&t.push(`Render-stack package ${C(o)} resolved (${o.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let o of e)t.push(`Import edge ${o.fromNamespace} \u2192 ${o.publisher}/${o.packageName} ${o.constraint} did NOT resolve (${o.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${o.fromNamespace} authors against ${o.publisher}/${o.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${o.constraint}-compatible version of ${o.publisher}/${o.packageName} to the workspace or cache (kanonak install ${o.publisher}/${o.packageName}), or bump the import in ${o.fromNamespace}.`);return t}function oe(r){let{publisher:e,availablePublishers:i,catalog:t,lookRenderer:o,localNamespaces:a,rawByNsKey:u,renderStack:p,producers:f,lockSource:y,configSource:s}=r,d=new Map,k=new Map,l=new Map,h=new Set;for(let S of t){if(!(S instanceof we))continue;let w=S.namespace||"";if(!a.has(w))continue;d.set(`${w}/${S.name}`,S);let P=w.split("/")[1]??"",[_,M]=P.split("@");if(!_||!M)continue;let E=Y(M);E&&(h.has(P)||(h.add(P),k.has(_)||k.set(_,[]),k.get(_).push({verStr:M,version:E})),S.name===_&&l.set(P,S))}for(let S of k.values())S.sort((w,P)=>V(P.version,w.version));return{publisher:e,availablePublishers:i,catalog:t,lookRenderer:o,localNamespaces:a,rawByNsKey:u,bySubject:d,pkgVersions:k,pkgSelfByVer:l,renderStack:p,...f?{producers:f}:{},...y?{lockSource:y}:{},...s?{configSource:s}:{}}}async function de(r,e={}){let i=new B,t=new fe(i),o=[],a=[];for(let c of Z(r)){let m;try{m=le(c,"utf-8")}catch{continue}let n;try{n=i.parse(m).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:m})}a.sort((c,m)=>V(m.version,c.version));for(let c of a)await t.saveDocumentAsync(i.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),o.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let u=[...new Set(o.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!u.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${u.join(", ")||"(none)"}`)}else if(u.length===1)p=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 o)c.publisher===p&&(f.add(`${c.publisher}/${c.package_}@${c.verStr}`),y.set(`${c.package_}@${c.verStr}`,c.source));let s=J(),d=new ye(s,!0,i),k={};e.httpCache&&(k.getFromCache=e.httpCache.getFromCache,k.onFetch=e.httpCache.onFetch),e.fetchFn&&(k.fetchFn=e.fetchFn),e.packageUrlTemplates&&(k.packageUrlTemplates=e.packageUrlTemplates);let l=e.repository??new Se(t,d,new Q(k)),h=e.log??(()=>{}),S=q(void 0),w=[],P=c=>c.map(m=>m.metadata.namespace_?.version).filter(m=>m!==void 0).sort((m,n)=>V(n,m)).map(j);if(!e.repository){h(`[render-stack] resolving ${S.length} ambient look-stack package(s); cache: ${s}`);let c=new X({...e.fetchFn?{fetchFn:e.fetchFn}:{},...e.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}});for(let m of S){let n=C(m),g=await t.getDocumentsByNamespaceAsync(m.publisher,m.package_);if(g.length>0){let v=P(g);w.push({...m,origin:"workspace",versions:v}),h(`[render-stack] ${n} \u2014 workspace (${v.join(", ")})`);continue}let b=await d.getDocumentsByNamespaceAsync(m.publisher,m.package_);if(b.length>0){let v=P(b);w.push({...m,origin:"cache",versions:v}),h(`[render-stack] ${n} \u2014 cache (${v.join(", ")})`);continue}try{let $=(await c.getLock(m.publisher))?.packages[`${m.publisher}/${m.package_}`];if(!$){let K=`publisher ${m.publisher} reachable but its lock does not pin ${m.package_}`;w.push({...m,origin:"missing",reason:K}),h(`[render-stack] ${n} \u2014 MISSING: ${K}`);continue}let I=$.version,{url:he,content:ke}=await c.fetchLockedSource(m.publisher,m.package_,$);await t.saveDocumentAsync(i.parse(ke),`${m.publisher}/${m.package_}@${I}`);try{let K=ne(s,m.publisher);Fe(K,{recursive:!0}),Ie(ne(K,`${m.package_}@${I}.kan.yml`),ke,"utf-8"),w.push({...m,origin:"fetched",versions:[I]}),h(`[render-stack] ${n}@${I} \u2014 fetched from ${he}, installed to cache`)}catch(K){w.push({...m,origin:"fetched",versions:[I]}),h(`[render-stack] ${n}@${I} \u2014 fetched from ${he}, but cache ${s} is NOT WRITABLE (${K.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(v){let $=`fetch failed: ${v.message}`;w.push({...m,origin:"missing",reason:$}),h(`[render-stack] ${n} \u2014 MISSING: ${$}`)}}}let _=(await t.getAllDocumentsAsync()).filter(c=>c.metadata.namespace_?.publisher===p);for(let c of S)_.push(...await l.getDocumentsByNamespaceAsync(c.publisher,c.package_));let M=[],E=await O(_,l,{onUnresolvedEdge:c=>M.push(c)}),A=l;if(!e.repository){for(let c of S)E.add(C(c));A=new W(l,E)}let T=await new re(i).parseKanonaks(A),ie=new te(T),ce=(c,m)=>ee(T,{publisher:c,package_:m,name:m}).length>0,N;if(e.repository){N=[];for(let c of S){let m=await l.getDocumentsByNamespaceAsync(c.publisher,c.package_);N.push(m.length>0?{...c,origin:"repository",versions:P(m)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else N=w.map(c=>c.origin==="missing"||ce(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let G=H(N,M);for(let c of G)h(`[render-stack] WARNING: ${c}`);let z={contractSource:"universal-default",cachePath:s,packages:N,warnings:G},D;try{D=le(ne(r,"kanonak.lock"),"utf-8")}catch{D=Ee(p,o,i)}let U;try{U=le(ne(r,".well-known","kanonak.json"),"utf-8")}catch{U=void 0}return oe({publisher:p,availablePublishers:u,catalog:T,lookRenderer:ie,localNamespaces:f,rawByNsKey:y,renderStack:z,...D?{lockSource:D}:{},...U?{configSource:U}:{}})}function Ee(r,e,i){let t=new Map;for(let a of e)a.publisher===r&&(t.has(a.package_)||t.set(a.package_,{verStr:a.verStr,source:a.source}));if(t.size===0)return;let o={};for(let a of[...t.keys()].sort()){let{verStr:u,source:p}=t.get(a),f={},y;try{y=i.parse(p).metadata?.imports}catch{y=void 0}for(let d of y?.[r]??[]){let k=t.get(d.packageName);k&&(f[`${r}/${d.packageName}`]=k.verStr)}let s={};for(let d of Object.keys(f).sort())s[d]=f[d];o[`${r}/${a}`]={version:u,resolved:`https://${r}/${a}/${u}.kan.yml`,integrity:xe(p),dependencies:s}}return Me.dump({version:"1",lastUpdated:"",packages:o},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as De,readFileSync as Ke,writeFileSync as Ve,mkdirSync as Ae}from"fs";import{join as _e}from"path";async function pe(r,e={}){let i=new B,t=ve(r),o=t.kind==="resource"?t.uri.publisher:t.publisher,a=e.log??(()=>{}),u=e.cacheRoot??J(),p=(n,g,b)=>_e(u,n,`${g}@${b}.kan.yml`),f=new Set,y=new Set,s=new Map,d=new Q({getFromCache:(n,g,b)=>{let v=p(n,g,b),$=De(v)?Ke(v,"utf-8"):null;return $!==null&&f.add(`${n}/${g}`),$},onFetch:(n,g,b,v)=>{y.add(`${n}/${g}`);try{let $=_e(u,n);Ae($,{recursive:!0}),Ve(p(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}:{},...e.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}}),k=new X(e.fetchFn?{fetchFn:e.fetchFn}:void 0),l;if(t.kind==="resource"){let n=t.uri.version;l=[n?{package_:t.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:t.uri.package_}]}else if(t.kind==="package"){let n=t.version;l=[n?{package_:t.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:t.package_}]}else l=((await k.getConfig(o)).featured_packages??[]).map(g=>({package_:g}));let h=async(n,g,b)=>{try{let v=b?i.buildImport(g,"=",b,n):i.buildImport(g,"*","0.0.0",n),$=await d.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 l){let{doc:g,error:b}=await h(o,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 "${o}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let P=q(),_="universal-default",M=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 ${P.length} ambient look-stack package(s) (contract: ${_}); cache: ${u}`);let E=[],A=[];for(let n of P){let g=C(n),{doc:b,error:v}=await h(n.publisher,n.package_,void 0);if(b){E.push(b);let $=M([b]),I=y.has(g)?"fetched":f.has(g)?"cache":"fetched";A.push({...n,origin:I,versions:$}),a(`[render-stack] ${g} \u2014 ${I} (${$.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 T=[],ie=await O([...S,...E],d,{onUnresolvedEdge:n=>T.push(n)}),ce=new W(d,ie),N=await new re(i).parseKanonaks(ce),G=new te(N),z=A.map(n=>n.origin==="missing"||ee(N,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),D=H(z,T);for(let n of D)a(`[render-stack] WARNING: ${n}`);let U={contractSource:_,cachePath:u,packages:z,warnings:D},c=new Set,m=new Map;for(let n of await d.getAllDocumentsAsync()){let g=n.metadata.namespace_;if(!g?.version||g.publisher!==o)continue;let b=j(g.version),v=`${g.publisher}/${g.package_}@${b}`;c.add(v);let $=await d.getDocumentContentAsync(v);$!==null&&m.set(`${g.package_}@${b}`,$)}return oe({publisher:o,availablePublishers:[o],catalog:N,lookRenderer:G,localNamespaces:c,rawByNsKey:m,renderStack:U})}import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";function se(r){let{lookRenderer:e,publisher:i,renderStack:t,catalog:o}=r,a=e.explainStylesheet(e.publisherSubject(i)),u=[...a.tokens.entries()].map(([l,h])=>({name:l,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=a.baseStylesheet,f={present:p.css!==void 0,...p.sourceNamespace!==void 0?{source:p.sourceNamespace}:{},...p.scope!==void 0?{scope:p.scope}:{},...p.css!==void 0?{bytes:p.css.length}:{},...p.problem!==void 0?{problem:p.problem}:{},candidates:p.candidates},y=new Map;for(let l of o){let h=l.namespace;h&&y.set(h,(y.get(h)??0)+1)}let s=[...y.entries()].map(([l,h])=>({namespace:l,resources:h})).sort((l,h)=>l.namespace.localeCompare(h.namespace)),d=e.expressionFailures().map(l=>({carrier:l.carrier,stage:l.stage,reason:l.reason})),k=d.map(l=>l.stage==="compile"?`Expression carrier "${l.carrier}" did not compile: ${l.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.`:`Expression carrier "${l.carrier}" failed to evaluate: ${l.reason} Consequence: that value renders as nothing. Fix: correct the expression, or make a value that may be absent explicitly optional.`);return{publisher:i,renderStack:{contractSource:t.contractSource,cachePath:t.cachePath,packages:t.packages.map(l=>({package_:C(l),origin:l.origin,...l.versions!==void 0?{versions:l.versions}:{},...l.reason!==void 0?{reason:l.reason}:{},...l.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:l.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:u,baseStylesheet:f,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},expressionCarriers:d,catalog:s,warnings:[...t.warnings,...a.warnings.filter(l=>!t.warnings.includes(l)),...k]}}function Te(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ue(r){let e=Te,i=r.warnings.length===0,t=r.expressionCarriers.map(s=>`<tr><td><code>${e(s.carrier)}</code></td><td>${e(s.reason)}</td></tr>`).join(`
2
2
  `),o=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 d=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>`,l=s.reason?e(s.reason):e((s.versions??[]).join(", "));return`<tr class="${d?"":"row-bad"}"><td><code>${e(s.package_)}</code></td><td>${k}</td><td>${l}</td></tr>`}).join(`
4
4
  `),u=r.stylesheet.baseStylesheet,p=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(`
@@ -44,6 +44,27 @@ export interface ConformanceScope {
44
44
  * node in the catalog is judged.
45
45
  */
46
46
  focus?: ReadonlySet<string> | undefined;
47
+ /**
48
+ * What the judged documents' `mode: link` references point at, read one hop
49
+ * out (typescript#138). A link is data, not a dependency (#111): its target
50
+ * package is not in the catalog, so nothing in it is judged, its shapes and
51
+ * keys bind nothing, and its classes are not the scope's. A value that is a
52
+ * link is checked against the subject it names, as `LinkTargetRule`
53
+ * dereferences it. Absent: the scope reads no links.
54
+ */
55
+ links?: ScopeLinks | undefined;
56
+ }
57
+ /** The targets of a scope's link references; see {@link ConformanceScope.links}. */
58
+ export interface ScopeLinks {
59
+ /**
60
+ * The subjects of each linked package the judged documents reference, at
61
+ * the version its link import resolves to: the package's own statements,
62
+ * with its names resolved through the repository. A reference value the
63
+ * catalog does not resolve is looked up here, as `findSubjectByUri` matches.
64
+ */
65
+ subjects: Kanonak[];
66
+ /** Why a link reference does not dereference, by the referenced subject's key (`uriKey`). */
67
+ unresolved: ReadonlyMap<string, string>;
47
68
  }
48
69
  /**
49
70
  * Build a merged scope from a repository — the pinned load-set. One parse
@@ -61,15 +82,22 @@ export declare function scopeFromRepositoryAsync(repository: IKanonakDocumentRep
61
82
  *
62
83
  * The catalog is the closure and nothing else: a version of a package that no
63
84
  * import resolved to does not enter it, wherever it is stored (the workspace,
64
- * the global cache), so its shapes cannot bind the seeds' nodes. Names still
65
- * resolve through the whole repository, so a `mode: link` target resolves
66
- * without joining the closure. Only the seeds' own nodes are judged
67
- * ({@link ConformanceScope.focus}), including subjects of other packages that
68
- * a seed augments; the rest of the closure supplies their contracts.
85
+ * the global cache), so its shapes cannot bind the seeds' nodes. Only the
86
+ * seeds' own nodes are judged ({@link ConformanceScope.focus}), including
87
+ * subjects of other packages that a seed augments; the rest of the closure
88
+ * supplies their contracts.
89
+ *
90
+ * A seed's `mode: link` references are read one hop out
91
+ * ({@link ConformanceScope.links}): each linked package a seed references is
92
+ * resolved by its link import and parsed on its own, without joining the
93
+ * catalog. A link that does not dereference is not an error here: a check on
94
+ * that value fails, and says why.
69
95
  *
70
96
  * Every seed must be a document of `repository`, and every import in the
71
97
  * closure must resolve. A partial closure would judge the seeds against fewer
72
- * contracts than they declare, so an unresolved import is an error.
98
+ * contracts than they declare, so an unresolved import is an error. So is a
99
+ * package that two seeds link at different versions, since a link value
100
+ * names one subject: judge such seeds in separate scopes.
73
101
  */
74
102
  export declare function scopeFromClosureAsync(seeds: KanonakDocument[], repository: IKanonakDocumentRepository): Promise<ConformanceScope>;
75
103
  /**
@@ -1,5 +1,5 @@
1
1
  export { scopeFromRepositoryAsync, scopeFromClosureAsync, scopeFromCatalog, scopeFromDocumentAsync, } from './ConformanceScope.js';
2
- export type { ConformanceScope } from './ConformanceScope.js';
2
+ export type { ConformanceScope, ScopeLinks } from './ConformanceScope.js';
3
3
  export { buildShapesModel, buildKeysModel } from './ShapesModel.js';
4
4
  export type { ShaclNodeShapeModel, ShaclClassKeyModel, ShaclPropertyConstraint, ShaclNodeKind, ShaclSeverity, } from './ShapesModel.js';
5
5
  export { lowerConstraint, foldFlagsIntoPattern } from './lowering.js';
@@ -7,4 +7,4 @@ export type { LoweredCheck, LoweredExprNode } from './lowering.js';
7
7
  export { evaluateConformance } from './ConformanceEvaluator.js';
8
8
  export type { ShaclConformanceResult, ShaclFinding } from './ConformanceEvaluator.js';
9
9
  export { buildReportPackageAsync } from './ReportBuilder.js';
10
- export { SHACL_PUBLISHER, SHACL_PACKAGE, SH_SHAPE, SH_NODE_SHAPE, SH_PROPERTY_SHAPE, } from './uris.js';
10
+ export { SHACL_PUBLISHER, SHACL_PACKAGE, SH_SHAPE, SH_NODE_SHAPE, SH_PROPERTY_SHAPE, SH_COMP_MIN_COUNT, SH_COMP_MAX_COUNT, SH_COMP_DATATYPE, SH_COMP_CLASS, SH_COMP_IN, SH_COMP_PATTERN, SH_COMP_MIN_LENGTH, SH_COMP_MAX_LENGTH, SH_COMP_MIN_INCLUSIVE, SH_COMP_MAX_INCLUSIVE, SH_COMP_NODE_KIND, SH_COMP_CLOSED, SH_COMP_HAS_VALUE, SH_COMP_QUALIFIED_MIN_COUNT, SH_COMP_QUALIFIED_MAX_COUNT, SH_COMP_HAS_KEY, } from './uris.js';
@@ -1,4 +1,4 @@
1
- import{a as pe}from"../chunk-IWPCPQQY.js";import"../chunk-OHF4RIKS.js";import{a as ve,b as M,c as Vn,n as X,o as Rn,p as vn,q as le,r as Ln,s as q,u as G}from"../chunk-CPENAANM.js";import"../chunk-QHABFCRC.js";import"../chunk-WXXZOJ4O.js";import{b as $n,c as Tn,d as Bn,e as xn,f as Un,k as fe}from"../chunk-SBWD7EOG.js";import{a as se}from"../chunk-5ZRVFYCP.js";import"../chunk-PEJALHXK.js";import{c as U}from"../chunk-6WOPXTIL.js";import{b as Y,c as D,d as ce,e as E,f as ue,i as $,j as T,k as B,l as w,m as me,n as x,o as de,q as N,r as S,y as A}from"../chunk-LK5SHY4B.js";import"../chunk-F67UH4FD.js";import{g as ie}from"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.js";var Le="kanonak.org",Oe="document-ast",i=e=>({publisher:Le,package_:Oe,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ge(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var V=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=Ie(n.metadata,t),o=Ke(n.children),s=["---",...r,"---","",o].join(`
1
+ import{a as pe}from"../chunk-FYAZ345F.js";import"../chunk-2GV6GXRF.js";import{a as ve,b as M,c as Vn,n as X,o as Rn,p as vn,q as le,r as Ln,s as q,u as G}from"../chunk-AZFLKLPB.js";import"../chunk-QHABFCRC.js";import"../chunk-NYCGUDVW.js";import{b as $n,c as Tn,d as Bn,e as xn,f as Un,k as fe}from"../chunk-Q2ZUKZEU.js";import{a as se}from"../chunk-6CI3HTKF.js";import"../chunk-PEJALHXK.js";import{c as U}from"../chunk-TVMOJ2QS.js";import{b as Y,c as D,d as ce,e as E,f as ue,i as $,j as T,k as B,l as w,m as me,n as x,o as de,q as N,r as S,y as A}from"../chunk-6USORWEP.js";import"../chunk-F67UH4FD.js";import{g as ie}from"../chunk-7IMLHHSA.js";var Le="kanonak.org",Oe="document-ast",i=e=>({publisher:Le,package_:Oe,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ge(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var V=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=Ie(n.metadata,t),o=Ke(n.children),s=["---",...r,"---","",o].join(`
2
2
  `);return t?.trailingNewline&&(s.endsWith(`
3
3
  `)||(s+=`
4
4
  `)),s}};function Ie(e,n){if(!e)return[];let t=new Map;for(let c of e.entries)t.set(P(c.key),c);let r=new Map;if(n?.metadataRenames)for(let[c,u]of n.metadataRenames)r.set(P(c),u);let a=(n?.metadataKeys??e.entries.map(c=>c.key)).map(P),s=[];for(let c of a){let u=t.get(c);if(!u)continue;let f=r.get(c),l=P(f??c),d=ye(u.value,u.escapeHint);d!==void 0&&s.push(`${l}: ${d}`)}return s}function P(e){let n=e.lastIndexOf(".");return n===-1?e:e.substring(n+1)||e}function ye(e,n){switch(e.kind){case"StringScalar":return _e(e.stringValue,n);case"IntegerScalar":return String(e.integerValue);case"StructuredList":{let t=[];for(let r of e.items){let o=ye(r,n);o!==void 0&&t.push(o)}return t.join(", ")}case"StructuredMap":return;default:return}}function _e(e,n){return!n||ge(n,m.ESC_RAW)?e:ge(n,m.ESC_YAML_SAFE)?Ce(e):e}function Ce(e){return e.includes(`
@@ -1 +1 @@
1
- import{A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,I as t,K as u,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"../chunk-LK5SHY4B.js";import"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.js";export{u as SingleDocumentRepository,k as findAllResourcesByCanonicalUri,l as findStatement,j as findSubjectByUri,i as findSubjectsByType,n as getDatatypeValue,q as getEmbeddedValue,r as getListValues,p as getReferenceUri,o as getStringValue,m as hasProperty,h as hasType,g as rawValuesByStatementOf,f as rawValuesOf,e as referenceUris,t as subjectAddress,c as toCanonicalUrl,d as typeReferenceUris,a as uriKey,b as uriMatches,s as valuesOf};
1
+ import{A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,I as t,K as u,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"../chunk-6USORWEP.js";import"../chunk-7IMLHHSA.js";export{u as SingleDocumentRepository,k as findAllResourcesByCanonicalUri,l as findStatement,j as findSubjectByUri,i as findSubjectsByType,n as getDatatypeValue,q as getEmbeddedValue,r as getListValues,p as getReferenceUri,o as getStringValue,m as hasProperty,h as hasType,g as rawValuesByStatementOf,f as rawValuesOf,e as referenceUris,t as subjectAddress,c as toCanonicalUrl,d as typeReferenceUris,a as uriKey,b as uriMatches,s as valuesOf};
@@ -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-I2T6ORSG.js";import"../chunk-VJUZKHQU.js";import"../chunk-CPENAANM.js";import"../chunk-QHABFCRC.js";import"../chunk-5FVUBF7N.js";import"../chunk-WXXZOJ4O.js";import"../chunk-SBWD7EOG.js";import"../chunk-5ZRVFYCP.js";import"../chunk-PEJALHXK.js";import"../chunk-6WOPXTIL.js";import"../chunk-LK5SHY4B.js";import"../chunk-F67UH4FD.js";import"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.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 as y,B as z,C as A,D as B,E as C,F as D,G as E,H as F,I as G,J as H,K as I,L as J,M as K,N as L,O as M,a,b,c,d,e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,r as p,s as q,t as r,u as s,v as t,w as u,x as v,y as w,z as x}from"../chunk-FCRP7KXR.js";import"../chunk-QRF7AT2M.js";import"../chunk-AZFLKLPB.js";import"../chunk-QHABFCRC.js";import"../chunk-5FVUBF7N.js";import"../chunk-NYCGUDVW.js";import"../chunk-Q2ZUKZEU.js";import"../chunk-6CI3HTKF.js";import"../chunk-PEJALHXK.js";import"../chunk-TVMOJ2QS.js";import"../chunk-6USORWEP.js";import"../chunk-F67UH4FD.js";import"../chunk-7IMLHHSA.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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "6.6.0",
3
+ "version": "6.8.0",
4
4
  "description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -135,7 +135,7 @@
135
135
  ],
136
136
  "dependencies": {
137
137
  "@kanonak-protocol/canonical": "^0.1.3",
138
- "@kanonak-protocol/types": "^6.6.0",
138
+ "@kanonak-protocol/types": "^6.8.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{a}from"./chunk-FUUTGGJS.js";export{a as KanonakUri};
@@ -1 +0,0 @@
1
- import{D as w,E as Q,c as G,d as X,p as S,q as Y,s as q,t as I,y as W,z as L}from"./chunk-LK5SHY4B.js";import{b as H}from"./chunk-F67UH4FD.js";import{l as B}from"./chunk-GGK6A6QK.js";import{a as x}from"./chunk-FUUTGGJS.js";var z=class{cache=new Map;repository;logger;constructor(e,n){this.repository=e,this.logger=n}async resolveEntityAsync(e,n){let o=n.metadata?.namespace_?.toString()??"unknown",s=this.cache.get(o);if(s){let i=s.get(e);if(i)return i}let a=await this.buildEntityIndexAsyncInternal(n,new Set,"",new Map);return this.cache.set(o,a),a.get(e)??null}async resolveAllEntitiesAsync(e,n){let o=await this.buildAllEntitiesIndexAsync(n,new Set,"");if(e.includes(".")){let s=e.split("."),a=s[0],i=s[1],y=await this.findDocumentForAlias(n,a);return y?await this.resolveAllEntitiesAsync(i,y):[]}return o.filter(s=>s.entityName===e)}async buildAllEntitiesIndexAsync(e,n,o){let s=[],a=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${a}`),n.has(a))return this.logger?.debug?.(`Skipping ${a} - already visited (circular import prevention)`),s;n.add(a);let i=o.length===0?a:`${o} \u2192 ${a}`;for(let[y,l]of Object.entries(e.body))if(!y.includes(".")&&l&&typeof l=="object"&&!Array.isArray(l)){if(!e.metadata.namespace_)continue;let g=e.metadata.namespace_.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};s.push({entityName:y,uri:new x(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,y,g),entity:l,definedInNamespace:a,isImported:o.length>0,importPath:i})}if(this.logger?.debug?.(`Collected ${s.length} entities from ${a}`),e.metadata?.imports){let y=Object.values(e.metadata.imports).reduce((l,g)=>l+g.length,0);this.logger?.debug?.(`Processing ${y} import(s) for ${a}`);for(let[l,g]of Object.entries(e.metadata.imports))for(let d of g)if(!H(d))try{this.logger?.debug?.(`Resolving import: ${l}/${d.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(l,d);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let k=await this.buildAllEntitiesIndexAsync(m,n,i);s.push(...k),this.logger?.debug?.(`Added ${k.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${l}/${d.packageName}`)}catch(m){let k=m;throw this.logger?.error?.(`Failed to process import ${l}/${d.packageName} for namespace ${a}. Error: ${k.message}`,k),new Error(`Failed to process import ${l}/${d.packageName} for namespace ${a}. See inner exception for details.`,{cause:m})}}return s}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"",new Map)}async buildEntityIndexAsyncInternal(e,n,o,s){let a=new Map,i=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${i}`),n.has(i))return this.logger?.debug?.(`Skipping ${i} - circular import in progress`),a;let y=s.get(i);if(y)return y;n.add(i);let l=o.length===0?i:`${o} \u2192 ${i}`,g=0;for(let[d,m]of Object.entries(e.body))if(!d.includes(".")&&m&&typeof m=="object"&&!Array.isArray(m)){if(!e.metadata.namespace_)continue;if(!a.has(d)){let k=e.metadata.namespace_.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.set(d,{entityName:d,uri:new x(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,d,k),entity:m,definedInNamespace:i,isImported:o.length>0,importPath:l}),g++}}if(this.logger?.debug?.(`Indexed ${g} entities from ${i}`),e.metadata?.imports){let d=Object.values(e.metadata.imports).reduce((m,k)=>m+k.length,0);this.logger?.debug?.(`Processing ${d} import(s) for ${i}`);for(let[m,k]of Object.entries(e.metadata.imports))for(let b of k)if(!H(b))try{this.logger?.debug?.(`Resolving import: ${m}/${b.packageName}`);let h=await this.repository.getHighestCompatibleVersionAsync(m,b);if(h){this.logger?.debug?.(`Successfully loaded import: ${h.metadata?.namespace_?.toString()}`);let U=await this.buildEntityIndexAsyncInternal(h,n,l,s),v=0;for(let[A,P]of U.entries()){let _=a.get(A);if(!_)a.set(A,P),v++;else if(_.isImported&&P.isImported&&(_.uri.publisher!==P.uri.publisher||_.uri.package_!==P.uri.package_)){let C=_.isAmbiguous?_:{..._,isAmbiguous:!0,ambiguousNamespaces:[_.definedInNamespace]};C.ambiguousNamespaces.includes(P.definedInNamespace)||C.ambiguousNamespaces.push(P.definedInNamespace),a.set(A,C),this.logger?.warn?.(`Ambiguous reference '${A}': defined in ${C.ambiguousNamespaces.join(", ")}`)}if(b.alias&&!A.includes(".")){let C=`${b.alias}.${A}`;a.has(C)||(a.set(C,P),v++)}}this.logger?.debug?.(`Merged ${v} entities from import ${h.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${m}/${b.packageName}`)}catch(h){let U=h;throw this.logger?.error?.(`Failed to process import ${m}/${b.packageName} for namespace ${i}. Error: ${U.message}`,U),new Error(`Failed to process import ${m}/${b.packageName} for namespace ${i}. See inner exception for details.`,{cause:h})}}return n.delete(i),s.set(i,a),a}async findDocumentForAlias(e,n){if(!e.metadata?.imports)return null;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s)if(!H(a)){if(a.alias===n)return await this.repository.getHighestCompatibleVersionAsync(o,a);if(!a.alias&&a.packageName===n)return await this.repository.getHighestCompatibleVersionAsync(o,a)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}};var J=class t{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-xsd"&&t.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-rdf"&&e.name==="Literal":!1}isMarkdownDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-prose"&&e.name==="Markdown":!1}isSubstitutableDatatype(e){return t.isSubstitutableDatatypeUri(e)}static isSubstitutableDatatypeUri(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-prose"&&(e.name==="SubstitutableString"||e.name==="Markdown"):!1}isKnownXsdDatatypeName(e){let n=e.includes(".")?e.split(".")[1]:e;return t.KNOWN_XSD_DATATYPES.has(n.toLowerCase())}async isClassTypeAsync(e,n){if(this.isKnownXsdDatatypeName(e))return!1;let o=await this.resourceResolver.resolveEntityAsync(e,n);if(o){let s=o.entity.type;if(s){let a=String(s);return a==="Class"||a==="rdfs.Class"||a.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,n){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(n)||e==="Property"&&this.isLiteralType(n))}isEffectiveObjectProperty(e,n){return!!(e==="ObjectProperty"||e==="Property"&&n&&!this.isXsdDatatype(n)&&!this.isLiteralType(n))}};function He(t){return`${t.publisher}/${t.package_}/${t.name}`}function u(t,e,n){return`${t}/${e}/${n}`}function Ie(t){return`${t.s}|${t.p}|${ae(t.o)}`}function ae(t){switch(t.kind){case"uri":return`u:${t.key}`;case"literal":return`l:${t.datatype}:${t.lexical}`;case"blank":return`b:${t.id}`}}function De(t,e,n){return{s:t,p:e,o:{kind:"uri",key:n}}}var se="kanonak.org",ie="core-shacl",r=t=>({publisher:se,package_:ie,name:t}),D=r("Shape"),N=r("NodeShape"),T=r("PropertyShape"),Te=r("targetClass"),je=r("property"),$e=r("path"),Me=r("minCount"),ve=r("maxCount"),Le=r("datatype"),we=r("class"),Ve=r("in"),Fe=r("pattern"),Be=r("flags"),Ge=r("minLength"),Xe=r("maxLength"),Ye=r("minInclusive"),qe=r("maxInclusive"),We=r("message"),Qe=r("targetNode"),ze=r("targetSubjectsOf"),Je=r("targetObjectsOf"),Ze=r("closed"),et=r("ignoredProperties"),tt=r("nodeKind"),nt=r("IRI"),rt=r("BlankNode"),ot=r("Literal"),at=r("severity"),st=r("Violation"),it=r("Warning"),pt=r("Info"),ct=r("ValidationReport"),lt=r("conforms"),ut=r("result"),yt=r("ValidationResult"),mt=r("focusNode"),dt=r("resultPath"),gt=r("resultMessage"),ft=r("resultSeverity"),kt=r("sourceShape"),St=r("value"),bt=r("sourceConstraintComponent"),_t=r("MinCountConstraintComponent"),ht=r("MaxCountConstraintComponent"),Pt=r("DatatypeConstraintComponent"),Ct=r("ClassConstraintComponent"),Kt=r("InConstraintComponent"),Et=r("PatternConstraintComponent"),At=r("MinLengthConstraintComponent"),xt=r("MaxLengthConstraintComponent"),Rt=r("MinInclusiveConstraintComponent"),Ot=r("MaxInclusiveConstraintComponent"),Ut=r("NodeKindConstraintComponent"),Ht=r("ClosedConstraintComponent"),It=r("hasValue"),Dt=r("qualifiedValueShape"),Nt=r("qualifiedMinCount"),Tt=r("qualifiedMaxCount"),jt=r("HasValueConstraintComponent"),$t=r("QualifiedMinCountConstraintComponent"),Mt=r("QualifiedMaxCountConstraintComponent"),vt=r("HasKeyConstraintComponent");var p="kanonak.org",c="core-rdf",f="core-owl",ee="core-kanonak",pe={publisher:p,package_:f,name:"hasKey"},$=new Map([["type",c],["subClassOf",c],["subPropertyOf",c],["domain",c],["range",c],["label",c],["comment",c],["seeAlso",c],["isDefinedBy",c],["member",c],["Resource",c],["Class",c],["Property",c],["Datatype",c],["Literal",c],["List",c],["ObjectProperty",f],["DatatypeProperty",f],["AnnotationProperty",f],["Thing",f],["Nothing",f],["Package",ee]]),ce=new Set(["type","subClassOf","subPropertyOf","domain","range"]);function Ft(t){return $.has(t)}function le(t){let e=$.get(t);return e?{publisher:p,package_:e}:void 0}function Bt(){return[...new Set($.values())].map(t=>({publisher:p,package_:t}))}function Gt(t){let e=le(t);if(!e)throw new Error(`builtinUri: '${t}' is not a reserved built-in term.`);return{...e,name:t}}function V(t,e,n){if(!t||!t.name)return;let o=$.get(t.name);if(!o)return;let s=()=>{t.publisher=p,t.package_=o,n&&(t.version=n.get(o))};if(ce.has(t.name)){let a=t.publisher===p&&t.package_===o;t.publisher=p,t.package_=o,!a&&n&&(t.version=n.get(o));return}t.publisher===p&&t.package_===o||t.publisher&&t.publisher.length>0&&(!e||e(t))||s()}var Z=class{type=u(p,c,"type");subClassOf=u(p,c,"subClassOf");subPropertyOf=u(p,c,"subPropertyOf");domain=u(p,c,"domain");range=u(p,c,"range");label=u(p,c,"label");comment=u(p,c,"comment");resource=u(p,c,"Resource");class_=u(p,c,"Class");datatype=u(p,c,"Datatype");literal=u(p,c,"Literal");equivalentClass=u(p,f,"equivalentClass");equivalentProperty=u(p,f,"equivalentProperty");inverseOf=u(p,f,"inverseOf");sameAs=u(p,f,"sameAs");transitiveProperty=u(p,f,"TransitiveProperty");symmetricProperty=u(p,f,"SymmetricProperty");objectProperty=u(p,f,"ObjectProperty");datatypeProperty=u(p,f,"DatatypeProperty");annotationProperty=u(p,f,"AnnotationProperty");hasKey=j(pe);package_=u(p,ee,"Package");shape=j(D);nodeShape=j(N);propertyShape=j(T)};function j(t){return u(t.publisher,t.package_,t.name)}var ue=new Set(["kanonak.org/core-rdf","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]);function R(t){let e=t;if(e.entity&&typeof e.entity=="object"){let n=e.entity.type;if(typeof n=="string"){let s={publisher:"",package_:"",name:n.includes(".")?n.substring(n.lastIndexOf(".")+1):n};return V(s),{publisher:s.publisher,package_:s.package_,name:s.name}}}return ne(t)[0]??null}function ne(t){let e=t;if(e.entity&&typeof e.entity=="object"){let n=R(t);return n?[n]:[]}return Array.isArray(e.statement)?q(t).map(n=>{let o={publisher:n.publisher??"",package_:n.package_??"",name:n.name};return V(o),{publisher:o.publisher,package_:o.package_,name:o.name}}):[]}var ye=[D,N,T];function O(t,e){return ue.has(`${t}/${e}`)}var me=new Set(["Property","ObjectProperty","DatatypeProperty","AnnotationProperty"]);function F(t){if(O(t.publisher,t.package_))return me.has(t.name)?t.name:void 0}var te=class t{static getTypeUri(e){return R(e)}static isCoreOntologyType(e){return O(e.publisher,e.package_)}static hasCoreType(e,n){return ne(e).some(o=>O(o.publisher,o.package_)&&o.name===n)}static isClassType(e){return t.hasCoreType(e,"Class")}static isDatatypeType(e){return t.hasCoreType(e,"Datatype")}static isDatatypePropertyType(e){return t.hasCoreType(e,"DatatypeProperty")}static isObjectPropertyType(e){return t.hasCoreType(e,"ObjectProperty")}static isAnnotationPropertyType(e){return t.hasCoreType(e,"AnnotationProperty")}static isGenericPropertyType(e){return t.hasCoreType(e,"Property")}static isAnyPropertyType(e){let n=R(e);return!n||!O(n.publisher,n.package_)?!1:n.name==="Property"||n.name==="DatatypeProperty"||n.name==="ObjectProperty"||n.name==="AnnotationProperty"}static isShapeType(e){let n=R(e);return n?ye.some(o=>Y(n,o)):!1}static isSchemaDefinitionType(e){if(t.isShapeType(e))return!0;let n=R(e);return!n||!O(n.publisher,n.package_)?!1:n.name==="Class"||n.name==="Property"||n.name==="DatatypeProperty"||n.name==="ObjectProperty"||n.name==="AnnotationProperty"||n.name==="Datatype"}static isInstanceOfKnownClass(e,n){if(t.isSchemaDefinitionType(e))return!1;let o=R(e);return o?n.has(o.name):!1}};var K="kanonak.org",E="core-rdf",de={publisher:K,package_:E,name:"domain"},ge={publisher:K,package_:E,name:"range"},fe={publisher:K,package_:E,name:"subClassOf"},ke={publisher:K,package_:E,name:"type"},Se={publisher:K,package_:E,name:"label"},be={publisher:K,package_:E,name:"comment"},_e=new x(K,E,"Resource");function he(t){try{let e=B(`${t.namespace}/${t.name}`);return e.kind==="resource"?e.uri:void 0}catch{return}}function oe(t,e){let n=[],o=new Set,s="version"in e?e.version:void 0,a=[new x(e.publisher,e.package_,e.name,s??void 0)];for(;a.length>0;){let i=a.shift(),y=S(i);if(o.has(y))continue;o.add(y),n.push(i);let l=Pe(t,i);l&&a.push(...I(l,fe))}return n}function Pe(t,e){return e.version&&typeof e.version.major=="number"?W(t,e)??L(t,e)[0]:L(t,e)[0]}function M(t,e){let n;for(let o of Ae(e)){let s=Ce(t,o);if(s){if(s!=="Property")return s;n??=s}}return n}function Ce(t,e){let n=F(e);if(n)return n;let o=re.get(t);o||(o=new Map,re.set(t,o));let s=e.version,a=s&&typeof s.major=="number"?`${S(e)}@${s.major}.${s.minor}.${s.patch}`:S(e),i=o.get(a);if(i!==void 0)return i??void 0;let y;for(let l of oe(t,e)){let g=F(l);if(g){if(g!=="Property"){y=g;break}y??="Property"}}return o.set(a,y??null),y}var re=new WeakMap;function on(t,e){return M(t,e)!==void 0}function an(t,e){return M(t,e)==="ObjectProperty"}function sn(t,e){return M(t,e)==="DatatypeProperty"}function Ke(t,e){let n=new Set([S(_e)]);for(let o of oe(t,e))n.add(S(o));return n}function Ee(t,e){let n=Ke(t,e),o=[],s=new Set;for(let a of t){if(!(a instanceof G))continue;let i=M(t,a);if(!i)continue;let y=I(a,de);if(!y.some(d=>n.has(S(d))))continue;let l=he(a);if(!l)continue;let g=S(l);s.has(g)||(s.add(g),o.push({uri:l,label:w(a,Se),comment:w(a,be),kind:i==="ObjectProperty"?"object":i==="DatatypeProperty"?"datatype":"other",range:Q(a,ge),domains:y}))}return o}function pn(t,e,n){let o=Ee(t,e).find(s=>S(s.uri)===S(n));return o?{ok:!0,descriptor:o}:{ok:!1,message:`Property ${n.publisher}/${n.package_}/${n.name} is not in scope for ${e.publisher}/${e.package_}/${e.name}.`}}function Ae(t){let e=I(t,ke);return e.length>0?e:t instanceof X&&t.rangeType?[t.rangeType]:[]}export{z as a,J as b,He as c,u as d,Ie as e,ae as f,De as g,se as h,ie as i,D as j,N as k,T as l,Te as m,je as n,$e as o,Me as p,ve as q,Le as r,we as s,Ve as t,Fe as u,Be as v,Ge as w,Xe as x,Ye as y,qe as z,We as A,Qe as B,ze as C,Je as D,Ze as E,et as F,tt as G,nt as H,rt as I,ot as J,at as K,st as L,it as M,pt as N,_t as O,ht as P,Pt as Q,Ct as R,Kt as S,Et as T,At as U,xt as V,Rt as W,Ot as X,Ut as Y,Ht as Z,It as _,Dt as $,Nt as aa,Tt as ba,jt as ca,$t as da,Mt as ea,vt as fa,pe as ga,Ft as ha,le as ia,Bt as ja,Gt as ka,V as la,Z as ma,F as na,te as oa,he as pa,oe as qa,M as ra,on as sa,an as ta,sn as ua,Ee as va,pn as wa,Ae as xa};
@@ -1 +0,0 @@
1
- var c=class n{constructor(r,s,e,t){this.publisher=r;this.package_=s;this.name=e;this.version=t}publisher;package_;name;version;static parse(r){if(!r||r.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let s=r.split("/");if(s.length!==3)throw new Error(`Invalid Kanonak URI: ${r}. Expected format: publisher/package[@version]/name`);let[e,t,i]=s;if(!e||!t||!i)throw new Error(`Invalid Kanonak URI: ${r}. Expected format: publisher/package[@version]/name`);let o=t.indexOf("@");if(o===-1)return new n(e,t,i,void 0);let p=t.substring(0,o),u=t.substring(o+1);if(!p||!u)throw new Error(`Invalid Kanonak URI: ${r}. Expected format: publisher/package[@version]/name`);let a=u.split(".").map(Number),l=m(a[0]||0,a[1]||0,a[2]||0);return new n(e,p,i,l)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}};function m(n,r,s){return{major:n,minor:r,patch:s,toString:()=>`${n}.${r}.${s}`,equals:e=>!e||typeof e!="object"?!1:e.major===n&&e.minor===r&&e.patch===s,getHashCode:()=>n<<20|r<<10|s,compareTo:e=>n!==e.major?n-e.major:r!==e.minor?r-e.minor:s-e.patch}}export{c as a};
@@ -1 +0,0 @@
1
- import{a as l}from"./chunk-FUUTGGJS.js";import{VersionOperator as s}from"@kanonak-protocol/types/document/models/enums";function x(e){switch(e){case"=":return s.Exact;case"~":return s.Compatible;case"^":return s.Major;case"*":return s.Any;default:return s.Compatible}}function d(e){switch(e){case s.Exact:return"=";case s.Compatible:return"~";case s.Major:return"^";case s.Any:return"*";default:return"~"}}function c(e,r){return e.major!==r.major?e.major-r.major:e.minor!==r.minor?e.minor-r.minor:e.patch-r.patch}function m(e,r){return e.major===r.major&&e.minor===r.minor&&e.patch===r.patch}function f(e){return`${e.major}.${e.minor}.${e.patch}`}function g(e,r,o){let n=`${e}.${r}.${o}`;return{major:e,minor:r,patch:o,toString:()=>n,equals:t=>t?.major===e&&t?.minor===r&&t?.patch===o,getHashCode:()=>e<<20|r<<10|o,compareTo:t=>e!==t.major?e-t.major:r!==t.minor?r-t.minor:o-t.patch}}function y(e){let r=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);return r?g(Number(r[1]),Number(r[2]),Number(r[3])):null}function k(e,r){return c(e,r)>=0&&e.major===r.major&&e.minor===r.minor}function h(e,r){return r.major===0?c(e,r)>=0&&e.major===0&&e.minor===r.minor:c(e,r)>=0&&e.major===r.major}function $(e,r){switch(r.versionOperator){case s.Exact:return m(e,r.version);case s.Compatible:return k(e,r.version);case s.Major:return h(e,r.version);case s.Any:return c(e,r.minVersion)>=0;default:return!1}}function K(e,r={}){let{requestedVersion:o}=r;if(e.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!o};if(o){let t=e.find(i=>{let a=i.metadata.namespace_?.version;return!!a&&f(a)===o});return t?{chosen:t,alternatives:e.filter(i=>i!==t),multipleVersionsPresent:e.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:e,multipleVersionsPresent:e.length>1,exactRequestedVersionMissing:!0}}if(e.length===1)return{chosen:e[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let n=[...e].sort((t,i)=>{let a=t.metadata.namespace_?.version,u=i.metadata.namespace_?.version;return!a&&!u?0:a?u?c(u,a):-1:1});return{chosen:n[0],alternatives:n.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}function M(e){if(!e||e.trim().length===0)throw new Error("Kanonak address string cannot be null or empty");let r=e.trim(),o=r.split("/");if(o.length===1){let n=o[0];if(!n)throw new Error(`Invalid Kanonak address: "${e}". Expected publisher, publisher/package[@version], or publisher/package[@version]/name.`);if(n.includes("@"))throw new Error(`Invalid Kanonak address: "${e}". A bare publisher cannot carry an @version qualifier \u2014 versions belong to packages.`);return{kind:"publisher",publisher:n}}if(o.length===2){let[n,t]=o;if(!n||!t)throw new Error(`Invalid Kanonak address: "${e}". Expected publisher/package[@version].`);let i=t.indexOf("@");if(i===-1)return{kind:"package",publisher:n,package_:t};let a=t.substring(0,i),u=t.substring(i+1);if(!a||!u)throw new Error(`Invalid Kanonak address: "${e}". Expected publisher/package[@version].`);let p=V(u);return{kind:"package",publisher:n,package_:a,version:p}}return{kind:"resource",uri:l.parse(r)}}function C(e){switch(e.kind){case"publisher":return e.publisher;case"package":return e.version?`${e.publisher}/${e.package_}@${e.version.major}.${e.version.minor}.${e.version.patch}`:`${e.publisher}/${e.package_}`;case"resource":return e.uri.toString()}}function V(e){let r=e.split(".").map(Number);return b(r[0]||0,r[1]||0,r[2]||0)}function b(e,r,o){return{major:e,minor:r,patch:o,toString:()=>`${e}.${r}.${o}`,equals:n=>!n||typeof n!="object"?!1:n.major===e&&n.minor===r&&n.patch===o,getHashCode:()=>e<<20|r<<10|o,compareTo:n=>e!==n.major?e-n.major:r!==n.minor?r-n.minor:o-n.patch}}export{x as a,d as b,c,m as d,f as e,g as f,y as g,k as h,h as i,$ as j,K as k,M as l,C as m};
@@ -1 +0,0 @@
1
- import{c as v,g as D,l as I}from"./chunk-GGK6A6QK.js";import{a as L}from"./chunk-FUUTGGJS.js";var u=class{};var f=class extends u{statement=[];unresolvedPredicates=[];sourceDoc="";sourceKey};var p=class extends f{namespace;name;icon};var k=class extends f{name;rangeType};var s=class e extends u{subject;sourceKey;static parse(n){let t=new e;return t.subject=L.parse(n),t}};var h=class extends u{value;carrier;lexical;links;sourceKey};var c=class{predicate;object;sourceKey};var l=class extends c{carrier;lexical};var y=class e extends l{static parse(n,t){let r=new e;return r.predicate=s.parse(n),r.object=t,r}};var K=class e extends l{static parse(n,t){let r=new e;return r.predicate=s.parse(n),r.object=t,r}};var x=class extends l{};var b=class e extends c{static parse(n,t){let r=new e;return r.predicate=s.parse(n),r.object=s.parse(t),r}};var j=class extends c{};var S=class extends c{};var U=class extends y{links=[]};function R(e){return`${e.publisher}/${e.package_}/${e.name}`}function w(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}function T(e){let n=e.version;return n&&typeof n.major=="number"?`https://${e.publisher}/${e.package_}/${n.major}.${n.minor}.${n.patch}/${e.name}`:`https://${e.publisher}/${e.package_}/${e.name}`}function B(e){return A(e,N)}var N={publisher:"kanonak.org",package_:"core-rdf",name:"type"};function A(e,n){let t=[];for(let r of $(e,n))r.item instanceof s&&t.push(r.item.subject);return t}function $(e,n){return M(e,n).flat()}function M(e,n){if(!(e instanceof f))return[];let t=[];for(let r of e.statement){let o=r.predicate;if(!(!o?.subject||!w(o.subject,n)))if(r instanceof b)t.push([{item:r.object,fromList:!1}]);else if(r instanceof j)t.push([{item:r.object,fromList:!1}]);else if(r instanceof U)t.push([{item:{literal:!0,value:r.object,carrier:r.carrier,lexical:r.lexical,links:r.links},fromList:!1}]);else if(r instanceof y||r instanceof K||r instanceof x)t.push([{item:{literal:!0,value:r.object,carrier:r.carrier,lexical:r.lexical},fromList:!1}]);else if(r instanceof S){let i=[];for(let a of r.object??[])if(a instanceof s||a instanceof k)i.push({item:a,fromList:!0});else if(a instanceof h)i.push({item:{literal:!0,value:a.value,carrier:a.carrier,lexical:a.lexical,links:a.links},fromList:!0});else throw new Error(`rawValuesOf: a list value of '${n.name}' is a ${a?.constructor?.name??typeof a}; list items are references, embedded values or literals.`);t.push(i)}else throw new Error(`rawValuesOf: '${n.name}' has a statement of unknown kind ${r?.constructor?.name??typeof r}.`)}return t}function O(e,n){if(!(e instanceof f))return!1;for(let t of e.statement)if(t.predicate?.subject?.name==="type"&&t instanceof b){let o=t.object;if(w(o.subject,n))return!0}return!1}function H(e,n){let t=[];for(let r of e)r instanceof p&&O(r,n)&&t.push(r);return t}function W(e,n){let t=n.version,r=t&&typeof t.major=="number"?`${n.publisher}/${n.package_}@${t.major}.${t.minor}.${t.patch}`:void 0;for(let o of e){if(!(o instanceof p)||o.name!==n.name)continue;let i=o.namespace||"";if(r!==void 0){if(i===r)return o}else if(i.startsWith(`${n.publisher}/${n.package_}@`))return o}}function F(e,n){let t=[];for(let r of e){if(!(r instanceof p)||r.name!==n.name)continue;(r.namespace||"").startsWith(`${n.publisher}/${n.package_}@`)&&t.push(r)}return t.sort((r,o)=>{let i=D((r.namespace||"").split("@")[1]??""),a=D((o.namespace||"").split("@")[1]??"");return i?a?v(a,i):-1:a?1:0}),t}function g(e,n){for(let t of e.statement){let r=t.predicate;if(r?.subject&&w(r.subject,n))return t}}function Y(e,n){return g(e,n)!==void 0}function _(e,n){let t=g(e,n);if(t&&(t instanceof y||t instanceof K||t instanceof x))return t.object}function q(e,n){let t=_(e,n);return typeof t=="string"?t:void 0}function z(e,n){let t=g(e,n);if(t instanceof b)return t.object.subject}function G(e,n){let t=g(e,n);if(t instanceof j)return t.object}function J(e,n){let t=g(e,n);return t instanceof S?t.object??[]:[]}function Q(e,n,t,r){let o=Z(e,n,r);if(o.length===0)return[];let i=ee(t);return o.map(({value:a,address:m})=>{let d=a.fromList;if(a.item instanceof s){let P=i.resolve(a.item.subject);return P?{kind:"subject",node:P,uri:a.item.subject,address:m,fromList:d}:{kind:"unresolved",uri:a.item.subject,address:m,fromList:d}}if(a.item instanceof k)return{kind:"embedded",node:a.item,address:m,fromList:d};let V={kind:"literal",value:a.item.value,carrier:a.item.carrier,lexical:a.item.lexical,address:m,fromList:d};return a.item.links&&(V.links=a.item.links),V})}function X(e){let n=I(`${e.namespace}/${e.name}`);if(n.kind!=="resource")throw new Error(`subjectAddress: '${e.namespace}/${e.name}' is not a resource address`);return R(n.uri)}function Z(e,n,t){let r=$(e,n);if(r.length===0)return[];let o=t.includes("#")?`${t}.${n.name}`:`${t}#${n.name}`,i=r.length>1||r.some(a=>a.fromList);return r.map((a,m)=>({value:a,address:a.item instanceof k&&a.item.name?`${o}.${a.item.name}`:i?`${o}[${m}]`:o}))}var C=new WeakMap;function ee(e){let n=C.get(e);if(n)return n;let t=new Map,r=new Map;for(let o of e){if(!(o instanceof p))continue;let i=o.namespace||"",a=`${i}\0${o.name}`;t.has(a)||t.set(a,o);let m=i.indexOf("@");if(m>=0){let d=`${i.slice(0,m)}\0${o.name}`;r.has(d)||r.set(d,o)}}return n={resolve(o){let i=o.version;return i&&typeof i.major=="number"?t.get(`${o.publisher}/${o.package_}@${i.major}.${i.minor}.${i.patch}\0${o.name}`):r.get(`${o.publisher}/${o.package_}\0${o.name}`)}},C.set(e,n),n}var E=class{constructor(n,t){this.doc=n;this.broader=t}doc;broader;async getAllDocumentsAsync(){return[this.doc]}async getDocumentAsync(n){return this.broader.getDocumentAsync(n)}async getDocumentsByNamespaceAsync(n,t){return this.broader.getDocumentsByNamespaceAsync(n,t)}async getHighestCompatibleVersionAsync(n,t){return this.broader.getHighestCompatibleVersionAsync(n,t)}async saveDocumentAsync(){throw new Error("SingleDocumentRepository is read-only")}async deleteDocumentAsync(){throw new Error("SingleDocumentRepository is read-only")}async clearNamespaceAsync(){throw new Error("SingleDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(n){return this.broader.getDocumentContentAsync(n)}async getDocumentUriAsync(n){return this.broader.getDocumentUriAsync(n)}};export{u as a,f as b,p as c,k as d,s as e,h as f,c as g,l as h,y as i,K as j,x as k,b as l,j as m,S as n,U as o,R as p,w as q,T as r,B as s,A as t,$ as u,M as v,O as w,H as x,W as y,F as z,g as A,Y as B,_ as C,q as D,z as E,G as F,J as G,Q as H,X as I,Z as J,E as K};
@@ -1 +0,0 @@
1
- import{a as X}from"./chunk-5ZRVFYCP.js";import{a as H,b as J,ha as Q,ia as _,ja as Z,la as E,ra as ne}from"./chunk-6WOPXTIL.js";import{I as ee,J as te,c as P,d as w,e as k,f as L,g as q,i as M,j as I,k as T,l as O,m as R,n as j,o as N,p as x,q as U,y as Y}from"./chunk-LK5SHY4B.js";import{b as G}from"./chunk-F67UH4FD.js";import{k as W}from"./chunk-GGK6A6QK.js";import{a as D}from"./chunk-FUUTGGJS.js";function re(p,t){for(let n of p)n instanceof P&&ae(n,ee(n),n.name,t)}function ae(p,t,n,r){let a=t.indexOf("#");r({kanonak:p,address:t,path:a<0?n:`${n}.${t.slice(a+1)}`});for(let i of ce(p))for(let{value:o,address:c}of te(p,i,t))o.item instanceof w&&ae(o.item,c,n,r)}function ce(p){let t=new Map;for(let n of p.statement){let r=n.predicate?.subject;if(!r)continue;let a=`${r.publisher}/${r.package_}/${r.name}`;t.has(a)||t.set(a,r)}return[...t.values()]}var oe="kanonak.org",pe="transformations",je=3,e=p=>({publisher:oe,package_:pe,name:p}),h=p=>({publisher:oe,package_:"math",name:p}),ve={Power:h("Power"),Modulo:h("Modulo"),Minimum:h("Minimum"),Maximum:h("Maximum"),Exp:h("Exp"),Ln:h("Ln"),Log10:h("Log10"),Sqrt:h("Sqrt"),Floor:h("Floor"),Ceil:h("Ceil"),Round:h("Round"),Sign:h("Sign"),Clip:h("Clip"),clipValue:h("clipValue"),clipLower:h("clipLower"),clipUpper:h("clipUpper")},A={Transformation:e("Transformation"),InstanceTransformation:e("InstanceTransformation"),SetTransformation:e("SetTransformation"),inputPattern:e("inputPattern"),rule:e("rule"),artifactName:e("artifactName"),outputs:e("outputs"),formatOverrides:e("formatOverrides"),partitionBy:e("partitionBy"),InputPattern:e("InputPattern"),matchesClass:e("matchesClass"),requires:e("requires"),sortBy:e("sortBy"),SortKey:e("SortKey"),byProperty:e("byProperty"),order:e("order"),SortOrder:e("SortOrder"),ascending:e("ascending"),descending:e("descending"),OutputFormat:e("OutputFormat"),backendUri:e("backendUri"),FormatOverride:e("FormatOverride"),formatTarget:e("formatTarget"),metadataKeys:e("metadataKeys"),metadataRenames:e("metadataRenames"),trailingNewline:e("trailingNewline"),omitWrapper:e("omitWrapper"),RenameEntry:e("RenameEntry"),fromKey:e("fromKey"),toKey:e("toKey"),FMT_MARKDOWN_FRONTMATTER:e("markdown-with-frontmatter"),FMT_PLAIN_MARKDOWN:e("plain-markdown"),FMT_TOML:e("toml"),FMT_JSON:e("json"),FMT_HTML:e("html"),FMT_SVG:e("svg"),Expression:e("Expression"),ListSourcedExpression:e("ListSourcedExpression"),ListAggregate:e("ListAggregate"),IteratingExpression:e("IteratingExpression"),BuildAstNode:e("BuildAstNode"),astClass:e("astClass"),set:e("set"),AstFieldBinding:e("AstFieldBinding"),field:e("field"),bindValue:e("bindValue"),When:e("When"),condition:e("condition"),thenBuild:e("thenBuild"),elseBuild:e("elseBuild"),Concat:e("Concat"),parts:e("parts"),Fallback:e("Fallback"),primary:e("primary"),alternate:e("alternate"),StringLiteral:e("StringLiteral"),stringLiteral:e("stringLiteral"),IntegerLiteral:e("IntegerLiteral"),integerLiteral:e("integerLiteral"),DecimalLiteral:e("DecimalLiteral"),decimalLiteral:e("decimalLiteral"),BooleanLiteral:e("BooleanLiteral"),booleanLiteral:e("booleanLiteral"),VarRef:e("VarRef"),varName:e("varName"),PropertyRead:e("PropertyRead"),readSource:e("readSource"),readProp:e("readProp"),Traverse:e("Traverse"),traverseSource:e("traverseSource"),through:e("through"),step:e("step"),UriName:e("UriName"),uriNameOf:e("uriNameOf"),UriPublisher:e("UriPublisher"),uriPublisherOf:e("uriPublisherOf"),UriPackage:e("UriPackage"),uriPackageOf:e("uriPackageOf"),UriVersion:e("UriVersion"),uriVersionOf:e("uriVersionOf"),SubjectUri:e("SubjectUri"),subjectOf:e("subjectOf"),UriLiteral:e("UriLiteral"),refTo:e("refTo"),DisplayLabel:e("DisplayLabel"),labelTarget:e("labelTarget"),labelSource:e("labelSource"),ResolveRef:e("ResolveRef"),resolveSource:e("resolveSource"),Normalize:e("Normalize"),normSource:e("normSource"),normKind:e("normKind"),NormalizeKind:e("NormalizeKind"),NORM_TRIM_END:e("trim-end"),NORM_TO_UPPER:e("to-upper"),NORM_TO_LOWER:e("to-lower"),NORM_FIRST_CHAR:e("first-char"),UnescapedString:e("UnescapedString"),unescapedSource:e("unescapedSource"),IsSet:e("IsSet"),checkExpr:e("checkExpr"),ExpressionFragment:e("ExpressionFragment"),body:e("body"),CallFragment:e("CallFragment"),fragmentRef:e("fragmentRef"),source:e("source"),Join:e("Join"),separator:e("separator"),Count:e("Count"),Sum:e("Sum"),Min:e("Min"),Max:e("Max"),Average:e("Average"),loopVar:e("loopVar"),ForEach:e("ForEach"),emit:e("emit"),ListMap:e("ListMap"),mapBody:e("mapBody"),Filter:e("Filter"),predicate:e("predicate"),PartitionBy:e("PartitionBy"),partitionKey:e("partitionKey"),DistinctBy:e("DistinctBy"),distinctKey:e("distinctKey"),Partition:e("Partition"),key:e("key"),members:e("members"),AllStatements:e("AllStatements"),statementsOf:e("statementsOf"),StatementPredicate:e("StatementPredicate"),predicateOf:e("predicateOf"),StatementValue:e("StatementValue"),valueOf:e("valueOf"),DateFormat:e("DateFormat"),dateSource:e("dateSource"),dateFormat:e("dateFormat"),NumberFormat:e("NumberFormat"),numberSource:e("numberSource"),numberStyle:e("numberStyle"),fractionDigits:e("fractionDigits"),currencyCode:e("currencyCode"),BinaryArithmetic:e("BinaryArithmetic"),arithLeft:e("arithLeft"),arithRight:e("arithRight"),Add:e("Add"),Subtract:e("Subtract"),Multiply:e("Multiply"),Divide:e("Divide"),Reverse:e("Reverse"),WindowedMap:e("WindowedMap"),windowSize:e("windowSize"),windowVar:e("windowVar"),windowBody:e("windowBody"),PairwiseMap:e("PairwiseMap"),firstVar:e("firstVar"),secondVar:e("secondVar"),pairBody:e("pairBody"),Scan:e("Scan"),initialState:e("initialState"),stateVar:e("stateVar"),elementVar:e("elementVar"),accumulate:e("accumulate"),ListItemAt:e("ListItemAt"),itemIndex:e("itemIndex"),BinaryComparison:e("BinaryComparison"),compareLeft:e("compareLeft"),compareRight:e("compareRight"),Equals:e("Equals"),GreaterThan:e("GreaterThan"),LessThan:e("LessThan"),GreaterThanOrEqual:e("GreaterThanOrEqual"),LessThanOrEqual:e("LessThanOrEqual"),Not:e("Not"),operand:e("operand"),BooleanLogic:e("BooleanLogic"),operands:e("operands"),And:e("And"),Or:e("Or"),Contains:e("Contains"),haystack:e("haystack"),needle:e("needle"),Matches:e("Matches"),matchSource:e("matchSource"),pattern:e("pattern"),UnaryNumericOp:e("UnaryNumericOp"),value:e("value"),Abs:e("Abs"),Negate:e("Negate"),KindPredicate:e("KindPredicate"),IsReference:e("IsReference"),IsEmbedded:e("IsEmbedded"),IsList:e("IsList"),kindCheck:e("kindCheck"),IsString:e("IsString"),IsNumber:e("IsNumber"),IsBoolean:e("IsBoolean"),StatementObject:e("StatementObject"),statementSource:e("statementSource"),Let:e("Let"),letName:e("letName"),letValue:e("letValue"),letBody:e("letBody"),GetStatementByName:e("GetStatementByName"),inSubject:e("inSubject"),byName:e("byName"),RenderMarkdown:e("RenderMarkdown"),renderSource:e("renderSource"),renderProp:e("renderProp"),renderFormat:e("renderFormat"),RenderFormat:e("RenderFormat"),RENDER_HTML:e("render-html"),RENDER_MARKDOWN:e("render-markdown")};import{Carrier as K,carrierOf as me}from"@kanonak-protocol/canonical";function V(p){return me(`${p.publisher}/${p.package_}/${p.name}`)}var ue=/\[\[([^\[\]\n]+)\]\]/g,fe=/\[\[/g,ie=/```[\s\S]*?```|`[^`\n]*`/g;function le(p){let t=[];for(let n of p.matchAll(ie))t.push([n.index,n.index+n[0].length]);return t}function Me(p){if(!p||!p.includes("[["))return[];let t=le(p),n=i=>t.some(([o,c])=>i>=o&&i<c),r=new Set(C(p).map(i=>i.startOffset)),a=[];for(let i of p.matchAll(fe)){let o=i.index;if(n(o)||r.has(o))continue;let c=p.slice(o,o+48).replace(/\s+/g," ").trim();a.push({startOffset:o,snippet:c})}return a}function C(p){if(!p||!p.includes("[["))return[];let t=[];for(let a of p.matchAll(ie))t.push([a.index,a.index+a[0].length]);let n=a=>t.some(([i,o])=>a>=i&&a<o),r=[];for(let a of p.matchAll(ue)){let i=a.index;if(n(i))continue;let o=a[1],c=o.indexOf("|"),m=(c===-1?o:o.slice(0,c)).trim();if(m.length===0)continue;let s=c===-1?"":o.slice(c+1).trim(),u={reference:m,startOffset:i,endOffset:i+a[0].length};s.length>0&&(u.displayText=s),r.push(u)}return r}import{VersionOperator as de}from"@kanonak-protocol/types/document/models/enums";var ye={..._("range"),name:"range"};function ge(p){let t=p.lastIndexOf(".");return t===-1?p:p.slice(t+1)}var se=class{constructor(t){}async parseKanonaks(t,n){let r=await t.getAllDocumentsAsync(),a=new H(t),i=new J(a);this.knownPropertyClasses.clear();let o=await this.parseAllDocumentsAsync(r,a,i,t),c=await this.mergeAndCanonicalizeAsync(o,t);return await this.learnPropertyClassesAsync(c,r,a)&&(o=await this.parseAllDocumentsAsync(r,a,i,t),c=await this.mergeAndCanonicalizeAsync(o,t)),n&&(n.authored=o),c}knownPropertyClasses=new Map;async learnPropertyClassesAsync(t,n,r){let a=new Map;for(let m of n){let s=m.metadata.namespace_?.toString();s&&a.set(s,m)}let i=[],o=new Set;re(t,({kanonak:m})=>{for(let s of m.unresolvedPredicates){let u=`${s.sourceDoc}::${s.key}`;o.has(u)||(o.add(u),i.push(s))}});let c=!1;for(let m of i){let s=a.get(m.sourceDoc);if(!s)continue;let u=await r.resolveEntityAsync(m.key,s);if(!u)continue;let l=x(u.uri);if(this.knownPropertyClasses.has(l))continue;let d=Y(t,u.uri);if(!d)continue;let f=ne(t,d);f&&(this.knownPropertyClasses.set(l,f),c=!0)}return c}async parseAllDocumentsAsync(t,n,r,a){let i=[];for(let o of t){let c=o.metadata.namespace_?.toString()??"";for(let[m,s]of Object.entries(o.body)){let u=new P,l=this.resolveCanonicalEntity(m,o,c);u.namespace=l.namespace,u.name=l.name,u.sourceKey=m,u.statement=[];let d=await this.parseStatements(s,o,n,r,a);u.statement.push(...d.statements),u.unresolvedPredicates=d.unresolved,F(u,c),i.push(u)}}return i}async mergeAndCanonicalizeAsync(t,n){let r=new Map,a=new Map,i=[];for(let s of t)if(s instanceof P){let u=`${s.namespace}/${s.name}`,l=r.get(u);if(l){let d=a.get(u);for(let f of s.statement){let g=$(f);d.has(g)||(d.add(g),l.statement.push(f))}for(let f of s.unresolvedPredicates)l.unresolvedPredicates.some(g=>g.key===f.key&&g.sourceDoc===f.sourceDoc)||l.unresolvedPredicates.push(f)}else{let d=new P;d.namespace=s.namespace,d.name=s.name,d.sourceDoc=s.sourceDoc,s.sourceKey!==void 0&&(d.sourceKey=s.sourceKey);let f=new Set;for(let g of s.statement){let S=$(g);f.has(S)||(f.add(S),d.statement.push(g))}d.unresolvedPredicates=[...s.unresolvedPredicates],a.set(u,f),r.set(u,d),i.push(d)}}else i.push(s);let o=new Set;for(let s of i)if(s instanceof P){let u=s.namespace||"",l=u.indexOf("/"),d=l>=0?u.slice(0,l):"",f=l>=0?u.slice(l+1):"",g=f.indexOf("@"),S=g>=0?f.slice(0,g):f;o.add(`${d}/${S}/${s.name}`)}let c=s=>o.has(`${s.publisher}/${s.package_}/${s.name}`),m=new Map;for(let s of Z()){let u=await n.getDocumentsByNamespaceAsync(s.publisher,s.package_);m.set(s.package_,W(u).chosen?.metadata.namespace_?.version??void 0)}for(let s of t)s instanceof P&&this.canonicalizeStatementBuiltins(s.statement,c,m);return i}canonicalizeStatementBuiltins(t,n,r){for(let a of t){let i=a.predicate?.subject;if(E(i,n,r),a instanceof O)a.object instanceof k&&E(a.object.subject,n,r);else if(a instanceof R)a.object&&this.canonicalizeStatementBuiltins(a.object.statement,n,r);else if(a instanceof j)for(let o of a.object??[])o instanceof k?E(o.subject,n,r):o instanceof w&&this.canonicalizeStatementBuiltins(o.statement,n,r)}}resolveCanonicalEntity(t,n,r){if(!t.includes(".")||!n.metadata?.imports)return{namespace:r,name:t};let a=t.indexOf("."),i=t.substring(0,a),o=t.substring(a+1);for(let[c,m]of Object.entries(n.metadata.imports))for(let s of m)if((s.alias??s.packageName)===i){let l=s.version;return{namespace:`${c}/${s.packageName}@${l.major}.${l.minor}.${l.patch}`,name:o}}return{namespace:r,name:t}}async parseStatements(t,n,r,a,i){let o=[],c=[];if(typeof t!="object"||t===null||Array.isArray(t))return{statements:o,unresolved:c};let m=n.metadata.namespace_?.toString()??"";for(let[s,u]of Object.entries(t))try{let l=await this.getPropertyMetadata(s,n,r,i,a);if(!l){let f=s.includes(".")?s.slice(s.lastIndexOf(".")+1):s;Q(f)||c.push({key:s,sourceDoc:m});continue}let d=await this.parsePropertyValue(s,u,l,n,r,a,i);d&&(d instanceof q&&(d.sourceKey=s),o.push(d))}catch(l){throw new Error(`Failed to parse property '${s}': ${l.message}`,{cause:l})}return{statements:o,unresolved:c}}async getPropertyMetadata(t,n,r,a,i){let o=await r.resolveEntityAsync(t,n);if(!o)return;let c=o.entity,m=c.type?.toString()??"",s=m.includes(".")?m.substring(m.lastIndexOf(".")+1):m,u=new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]),l=this.knownPropertyClasses.get(x(o.uri));if(!u.has(s)&&!l)return;let d=l??i.getPropertyTypeClassification(m),f,g=async()=>{if(f)return f;if(!(o.isImported&&o.definedInNamespace))return f=n,n;if(typeof a.getDocumentAsync!="function")throw new Error(`Cannot resolve the range of imported property '${t}': the parse repository cannot fetch defining document '${o.definedInNamespace}'. Thread the real repository through to embedded-object parsing \u2014 no stub, no fallback.`);let v=await a.getDocumentAsync(o.definedInNamespace);if(!v)throw new Error(`Cannot resolve the range of imported property '${t}': defining document '${o.definedInNamespace}' was not found in the repository.`);return f=v,v},S=await this.readDefinitionSlot(c,ye,g,r),y=S==null?void 0:String(S),b;if(d==="ObjectProperty")b="ObjectProperty";else if(d==="DatatypeProperty")b="DatatypeProperty";else{let v=y&&y.includes(".")?y.substring(y.lastIndexOf(".")+1):y??"";(y?i.isKnownXsdDatatypeName(y):!1)||v==="Literal"?b="DatatypeProperty":b="ObjectProperty"}let z;return y&&(z=(await r.resolveEntityAsync(y,await g()))?.uri),{propertyUri:o.uri.toString(),propertyType:b,range:y,rangeUri:z,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async readDefinitionSlot(t,n,r,a){let i=Object.keys(t).filter(s=>ge(s)===n.name);if(i.length===0)return;let o=await r(),c=_(n.name),m=c!==void 0&&c.publisher===n.publisher&&c.package_===n.package_;for(let s of i){let u=await a.resolveEntityAsync(s,o);if(u){if(U(u.uri,n))return t[s];continue}if(!s.includes(".")&&m)return t[s]}}async parsePropertyValue(t,n,r,a,i,o,c){let m=r.propertyUri;if(n!=null){if(Array.isArray(n))return this.parseListValue(m,n,r,a,i,o,c);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(m,n,r,a,i,o);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(m,n,r,a,i,o,c)}}async parseDatatypeValue(t,n,r,a,i,o){let c;if(typeof n=="string"){if(o.isSubstitutableDatatype(r.rangeUri))return await this.parseSubstitutableValue(t,n,a,i);c=n}else if(typeof n=="number"||typeof n=="boolean")c=String(n);else return;return this.typedScalarStatement(t,c,r)}typedScalarStatement(t,n,r){let a=k.parse(t),i=r.rangeUri?V(r.rangeUri):void 0;if(i===K.Boolean){let c=new T;return c.predicate=a,c.object=n==="true"||n==="1",c.carrier=i,c.lexical=n,c}if(i===K.Integer||i===K.Decimal||i===K.Double||i===K.Float){let c=new I;return c.predicate=a,c.object=Number(n),c.carrier=i,c.lexical=n,c}let o=M.parse(t,n);return i&&(o.carrier=i,o.lexical=n),o}typedListLiteral(t,n){let r=new L,a=n.rangeUri?V(n.rangeUri):void 0;return a===K.Boolean?r.value=t==="true"||t==="1":a===K.Integer||a===K.Decimal||a===K.Double||a===K.Float?r.value=Number(t):r.value=t,a&&(r.carrier=a,r.lexical=t),r}async parseSubstitutableValue(t,n,r,a){let i=new N;return i.predicate=k.parse(t),i.object=n,i.links=await this.resolveMarkdownLinks(n,r,a),i}async resolveMarkdownLinks(t,n,r){let a=[];for(let i of C(t)){let o=this.linkReference(i.reference,n);if(!o){let m=await r.resolveEntityAsync(i.reference,n);m&&(o=new k,o.subject=m.uri)}let c={reference:i.reference,startOffset:i.startOffset,endOffset:i.endOffset};i.displayText!==void 0&&(c.displayText=i.displayText),o!==void 0&&(c.target=o),a.push(c)}return a}async parseObjectValue(t,n,r,a,i,o,c){if(typeof n=="string"){if(r.rangeUri&&U(r.rangeUri,A.Expression))return this.coerceExpressionLiteral(t,n,r.rangeUri);let m=await this.resolveReference(n,a,i);if(!m)return;let s=new O;return s.predicate=k.parse(t),s.object=m,s}if(typeof n=="object"&&!Array.isArray(n)){let m=await this.parseStatements(n,a,i,o,c);if(m.statements.length>0){let l=new w;l.statement=m.statements,l.unresolvedPredicates=m.unresolved,r.rangeUri&&(l.rangeType=r.rangeUri);let d=new R;return d.predicate=k.parse(t),d.object=l,d}let s=[];for(let[l,d]of Object.entries(n))if(typeof d=="object"&&d!==null&&!Array.isArray(d)){let f=new w;f.name=l,f.sourceKey=l,r.rangeUri&&(f.rangeType=r.rangeUri);let g=await this.parseStatements(d,a,i,o,c);f.statement=g.statements,f.unresolvedPredicates=g.unresolved,s.push(f)}else if(typeof d=="string"){let f=await this.resolveReference(d,a,i);f&&(f.sourceKey=l,s.push(f))}if(s.length>0){let l=new j;return l.predicate=k.parse(t),l.object=s,l}let u=new R;return u.predicate=k.parse(t),u.object=new w,r.rangeUri&&(u.object.rangeType=r.rangeUri),u}}coerceExpressionLiteral(t,n,r){let a=new w,i=new O,o=new k;o.subject=new D("kanonak.org","core-rdf","type"),i.predicate=o;let c=new k;c.subject=new D(r.publisher,r.package_,A.StringLiteral.name,r.version),i.object=c;let m=new M,s=new k;s.subject=new D(r.publisher,r.package_,A.stringLiteral.name,r.version),m.predicate=s,m.object=n,a.statement=[i,m];let u=new R;return u.predicate=k.parse(t),u.object=a,u}async parseListValue(t,n,r,a,i,o,c){let m=[],s=r.propertyType==="DatatypeProperty",u=r.rangeUri?.publisher==="kanonak.org"&&r.rangeUri?.package_==="core-rdf"&&r.rangeUri?.name==="List"||!r.rangeUri&&(r.range?.includes(".")?r.range.substring(r.range.lastIndexOf(".")+1):r.range)==="List";for(let d=0;d<n.length;d++){let f=n[d],g=y=>{y.sourceKey=d,m.push(y)},S=typeof f=="string"||typeof f=="number"||typeof f=="boolean";if(s&&S){let y=typeof f=="string"?f:String(f),b=this.typedListLiteral(y,r);o.isSubstitutableDatatype(r.rangeUri)&&(b.links=await this.resolveMarkdownLinks(y,a,i)),g(b);continue}if(u&&S){if(typeof f=="string"){let y=await i.resolveEntityAsync(f,a);if(y){let b=new k;b.subject=y.uri,g(b)}else{let b=new L;b.value=f,g(b)}}else{let y=new L;y.value=f,g(y)}continue}if(typeof f=="string"){let y=await this.resolveReference(f,a,i);y&&g(y)}else if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let y=new w;r.rangeUri&&(y.rangeType=r.rangeUri);let b=await this.parseStatements(f,a,i,o,c);y.statement=b.statements,y.unresolvedPredicates=b.unresolved,g(y)}}let l=new j;return l.predicate=k.parse(t),l.object=m,l}linkReference(t,n){let r=t.indexOf(".");if(r<=0||!n.metadata?.imports)return;let a=t.substring(0,r),i=t.substring(r+1);for(let[o,c]of Object.entries(n.metadata.imports))for(let m of c){if(!G(m)||(m.alias??m.packageName)!==a)continue;let s=new k,u=m.versionOperator===de.Exact?m.version:void 0;return s.subject=new D(o,m.packageName,i,u),s}}async resolveReference(t,n,r){let a=this.linkReference(t,n);if(a)return a;let i=await r.resolveEntityAsync(t,n);if(i){let c=new k;return c.subject=i.uri,c}let o=n.metadata?.namespace_;if(o){let{KanonakUri:c}=await import("./KanonakUri-4VJGV3FN.js");if(t.includes(".")){let s=t.indexOf("."),u=t.substring(0,s),l=t.substring(s+1);if(n.metadata?.imports){for(let[d,f]of Object.entries(n.metadata.imports))for(let g of f)if((g.alias??g.packageName)===u){let y=new k;return y.subject=new c(d,g.packageName,l,g.version),y}}}let m=new k;return m.subject=new c(o.publisher,o.package_,t,o.version??void 0),m}return null}async saveKanonaks(t,n){let r=new Map;for(let a of t)a instanceof P&&a.namespace&&(r.has(a.namespace)||r.set(a.namespace,[]),r.get(a.namespace).push(a));for(let[a,i]of r){let o=await this.convertKanonaksToDocument(a,i),c=`${a.split("@")[0]}.yml`;await n.saveDocumentAsync(o,c)}}async serializeToYaml(t,n){let r=t.filter(o=>o instanceof P&&o.namespace===n);if(r.length===0)throw new Error(`No kanonaks found with namespace '${n}'`);let a=await this.convertKanonaksToDocument(n,r);return new X().save(a)}async convertKanonaksToDocument(t,n){let a={metadata:{namespace_:t,get allImports(){if(!this.imports)return[];let o=[];for(let c of Object.values(this.imports))o.push(...c);return o}},body:{}},i=new Map;for(let o of n){let c={};for(let m of o.statement){let[s,u]=this.convertStatementToProperty(m);s&&u!==null&&u!==void 0&&(c[s]=u),this.collectImportsFromStatement(m,t,i)}a.body[o.name]=c}return a}convertStatementToProperty(t){if(t instanceof M)return[t.predicate.subject.name,t.object];if(t instanceof I)return[t.predicate.subject.name,t.object];if(t instanceof T)return[t.predicate.subject.name,t.object];if(t instanceof O)return[t.predicate.subject.name,t.object.subject.name];if(t instanceof j){let n=this.convertKanonakListToValue(t.object);return[t.predicate.subject.name,n]}else if(t instanceof R){let n=this.convertEmbeddedKanonakToValue(t.object);return[t.predicate.subject.name,n]}return[null,null]}convertKanonakListToValue(t){let n=[];for(let r of t)r instanceof k?n.push(r.subject.name):r instanceof w&&n.push(this.convertEmbeddedKanonakToValue(r));return n}convertEmbeddedKanonakToValue(t){let n={};for(let r of t.statement){let[a,i]=this.convertStatementToProperty(r);a&&i!==null&&i!==void 0&&(n[a]=i)}return n}collectImportsFromStatement(t,n,r){}};function F(p,t){p.sourceDoc=t;for(let n of p.statement)if(n instanceof R)F(n.object,t);else if(n instanceof j)for(let r of n.object)r instanceof w&&F(r,t)}function $(p){let t=p.predicate?.subject;return(t?`${t.publisher}/${t.package_}/${t.name}`:"?")+"="+ke(p)}function ke(p){return p instanceof N?"m:"+String(p.object):p instanceof M?"s:"+String(p.object):p instanceof I?"n:"+String(p.object):p instanceof T?"b:"+String(p.object):p instanceof O?"r:"+B(p.object):p instanceof R?"e:"+B(p.object):p instanceof j?"l:["+(p.object??[]).map(B).join("|")+"]":"x"}function B(p){if(!p)return"";if(p instanceof k){let t=p.subject;return"R("+(t?`${t.publisher}/${t.package_}/${t.name}`:"")+")"}return p instanceof w?"E("+(p.statement??[]).map($).join(";")+")":p instanceof L?"L("+String(p.value)+")":"N"}export{re as a,oe as b,pe as c,je as d,ve as e,A as f,K as g,V as h,Me as i,C as j,se as k};