@kanonak-protocol/sdk 3.71.0 → 3.73.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.
@@ -0,0 +1,6 @@
1
+ export { PackageBuilder, ImportBook, contentAddressedName, sanitizeName } from './PackageBuilder.js';
2
+ export type { BuiltPackage, ImportEntry } from './PackageBuilder.js';
3
+ export { ProducerRepository } from './ProducerRepository.js';
4
+ export type { IPackageProducer, ProduceResult, VersionRange } from './IPackageProducer.js';
5
+ export { EntitlementProducer, EntitlementDeniedError, allowAllPolicy, noopMeter, } from './Entitlement.js';
6
+ export type { IEntitlementPolicy, IMeter, ProduceContext, PackageAddress, EntitlementDecision, RequestPrincipal, } from './Entitlement.js';
@@ -15,6 +15,26 @@ export declare class HttpKanonakDocumentRepository implements IKanonakDocumentRe
15
15
  fetchFn?: AuthenticatedFetchFn;
16
16
  });
17
17
  getHighestCompatibleVersionAsync(publisher: string, import_: Import): Promise<KanonakDocument | null>;
18
+ /**
19
+ * Resolve against a live producer origin (`config.resolveByRedirect`): fetch
20
+ * the package source and follow the latest→pinned redirect, instead of
21
+ * downloading and filtering an index. An exact pin fetches the pinned URL;
22
+ * any range fetches the bare-name "latest" pointer (`/{package}.kan.yml`),
23
+ * which the origin 302s to the resolved pinned source. The resolved version
24
+ * is read from the returned document.
25
+ *
26
+ * A range resolves to the origin's LATEST — correct for a snapshot feed,
27
+ * where `^`/`~` are inert on the time axis; range-constrained resolution
28
+ * over redirect would need the range encoded in the request (future work).
29
+ */
30
+ private resolveByRedirect;
31
+ /**
32
+ * Fetch a URL following 301/302 redirects explicitly — so an authenticated
33
+ * `fetchFn` re-signs each hop (and plain fetch doesn't transparently swallow
34
+ * the redirect). Returns null on 404; throws on other non-OK statuses or a
35
+ * redirect loop.
36
+ */
37
+ private fetchFollowing;
18
38
  getAllDocumentsAsync(): Promise<KanonakDocument[]>;
19
39
  getDocumentAsync(identifier: string): Promise<KanonakDocument | null>;
20
40
  getDocumentsByNamespaceAsync(publisher: string, package_: string): Promise<KanonakDocument[]>;
@@ -14,6 +14,16 @@ export interface PublisherConfig {
14
14
  * through `parseKanonakAddress`, not string-matched.
15
15
  */
16
16
  render?: string[];
17
+ /**
18
+ * When true, this is a LIVE producer origin: it resolves version ranges
19
+ * server-side and 302-redirects a "latest" request to the pinned source,
20
+ * rather than publishing an enumerable `index.txt`. A consumer then resolves
21
+ * by fetching the package URL and following the redirect, instead of
22
+ * downloading and filtering the index — essential for a snapshot feed whose
23
+ * version history is unbounded. ABSENT/false means an ordinary static
24
+ * publisher (resolve via `index.txt`), which is the unchanged default.
25
+ */
26
+ resolveByRedirect?: boolean;
17
27
  }
18
28
  /**
19
29
  * The explicit, self-describing config a publisher advertises at
@@ -1,5 +1,5 @@
1
1
  import type { Import } from '@kanonak-protocol/types/document/models/types';
2
- import { PublisherConfigResolver } from './PublisherConfig.js';
2
+ import { PublisherConfigResolver, type PublisherConfig } from './PublisherConfig.js';
3
3
  import type { AuthenticatedFetchFn } from '../auth/index.js';
4
4
  export declare class PublisherIndex {
5
5
  private readonly indexCache;
@@ -24,6 +24,8 @@ export declare class PublisherIndex {
24
24
  version: string;
25
25
  }[]>;
26
26
  getPackageUrl(publisher: string, packageName: string, version: string): Promise<string>;
27
+ /** The publisher's `.well-known` config — e.g. to check `resolveByRedirect`. */
28
+ getConfig(publisher: string): Promise<PublisherConfig>;
27
29
  private getPackageVersions;
28
30
  /**
29
31
  * Resolve the publisher's index, de-duplicating concurrent fetches by
@@ -1 +1 @@
1
- import{b as e,c as r,d as n}from"../chunk-HAR3BNTB.js";import{a as o}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-TJPQETHV.js";import"../chunk-2ACBWC7K.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
1
+ import{b as e,c as r,d as n}from"../chunk-LKBG2MK6.js";import{a as o}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-TJPQETHV.js";import"../chunk-2ACBWC7K.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
@@ -1 +1 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m}from"../chunk-OFSARZX6.js";import{a as g,b as h,c as i,d as j}from"../chunk-HAR3BNTB.js";import{a}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-TJPQETHV.js";import"../chunk-2ACBWC7K.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,m as buildLocalFirstRepository,l as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m}from"../chunk-ATH6636H.js";import{a as g,b as h,c as i,d as j}from"../chunk-LKBG2MK6.js";import{a}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-TJPQETHV.js";import"../chunk-2ACBWC7K.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,m as buildLocalFirstRepository,l as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
@@ -1,4 +1,4 @@
1
- import{a as g}from"../chunk-MCU5IAMS.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import"../chunk-G2DKKSZ4.js";import"../chunk-TJPQETHV.js";import{d as m,g as S}from"../chunk-BGQKZBNE.js";import{a as p,f as E}from"../chunk-CRKSKIAL.js";import"../chunk-IOMNZBK4.js";import{c as v}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.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{a as g}from"../chunk-X5TYWQRA.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import"../chunk-G2DKKSZ4.js";import"../chunk-TJPQETHV.js";import{d as m,g as S}from"../chunk-BGQKZBNE.js";import{a as p,f as E}from"../chunk-CRKSKIAL.js";import"../chunk-IOMNZBK4.js";import{c as v}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.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,5 +1,6 @@
1
1
  import type { Kanonak } from '../kanonaks/index.js';
2
2
  import type { LookRenderer } from '../look/index.js';
3
+ import type { IPackageProducer } from '../producer/index.js';
3
4
  import type { ServerModel } from './types.js';
4
5
  /**
5
6
  * Build the route-facing indexes for a {@link ServerModel} from an already-built
@@ -18,4 +19,5 @@ export declare function assembleServerModel(params: {
18
19
  lookRenderer: LookRenderer;
19
20
  localNamespaces: Set<string>;
20
21
  rawByNsKey: Map<string, string>;
22
+ producers?: readonly IPackageProducer[];
21
23
  }): ServerModel;
@@ -1,3 +1,3 @@
1
- import{j as O}from"../chunk-MCU5IAMS.js";import"../chunk-QHABFCRC.js";import{a as z,d as j,f as Z,g as V}from"../chunk-OFSARZX6.js";import{a as Q,b as X,c as F,d as I}from"../chunk-HAR3BNTB.js";import{a as J}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as te}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{f as N}from"../chunk-G2DKKSZ4.js";import{a as K}from"../chunk-TJPQETHV.js";import{b as L}from"../chunk-BGQKZBNE.js";import"../chunk-CRKSKIAL.js";import"../chunk-IOMNZBK4.js";import{c as ee}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{c as C,g as Y}from"../chunk-2ACBWC7K.js";import{readFileSync as ce,existsSync as le,readdirSync as pe,writeFileSync as ue,mkdirSync as de}from"fs";import{join as W}from"path";function re(a){let e=a.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function A(a,e){let r=new Set,t=[...a];for(;t.length>0;){let n=t.shift(),u=re(n);if(!u||r.has(u))continue;r.add(u);let d=n.metadata?.imports;if(d)for(let[i,g]of Object.entries(d))for(let f of g)try{let p=await e.getHighestCompatibleVersionAsync(i,f);p&&t.push(p)}catch{}}return r}var D=class{constructor(e,r){this.inner=e;this.scope=r}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(r=>{let t=re(r);return t!==void 0&&this.scope.has(t)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,r){return this.inner.getDocumentsByNamespaceAsync(e,r)}getHighestCompatibleVersionAsync(e,r){return this.inner.getHighestCompatibleVersionAsync(e,r)}saveDocumentAsync(e,r){return this.inner.saveDocumentAsync(e,r)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,r){return this.inner.clearNamespaceAsync(e,r)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var ne=[{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 M(a){let e=a?.render;if(e&&e.length>0){let r=[];for(let t of e)try{let n=L(t);n.kind==="package"?r.push({publisher:n.publisher,package_:n.package_}):n.kind==="resource"&&r.push({publisher:n.uri.publisher,package_:n.uri.package_})}catch{}if(r.length>0)return r}return ne}function B(a){return`${a.publisher}/${a.package_}`}function E(a){let{publisher:e,availablePublishers:r,catalog:t,lookRenderer:n,localNamespaces:u,rawByNsKey:d}=a,i=new Map,g=new Map,f=new Map,p=new Set;for(let o of t){if(!(o instanceof ee))continue;let m=o.namespace||"";if(!u.has(m))continue;i.set(`${m}/${o.name}`,o);let k=m.split("/")[1]??"",[v,$]=k.split("@");if(!v||!$)continue;let c=Y($);c&&(p.has(k)||(p.add(k),g.has(v)||g.set(v,[]),g.get(v).push({verStr:$,version:c})),o.name===v&&f.set(k,o))}for(let o of g.values())o.sort((m,k)=>C(k.version,m.version));return{publisher:e,availablePublishers:r,catalog:t,lookRenderer:n,localNamespaces:u,rawByNsKey:d,bySubject:i,pkgVersions:g,pkgSelfByVer:f}}async function H(a,e={}){let r=new K,t=new J(r),n=[],u=[];for(let c of V(a)){let R;try{R=ce(c,"utf-8")}catch{continue}let b;try{b=r.parse(R).metadata?.namespace_}catch{continue}if(!b?.version)continue;let x=b.version;u.push({publisher:b.publisher,package_:b.package_,verStr:`${x.major}.${x.minor}.${x.patch}`,version:x,source:R})}u.sort((c,R)=>C(R.version,c.version));for(let c of u)await t.saveDocumentAsync(r.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),n.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let d=[...new Set(n.map(c=>c.publisher))].sort(),i=e.publisher;if(i){if(!d.includes(i))throw new Error(`Publisher "${i}" not found in workspace. Available: ${d.join(", ")||"(none)"}`)}else if(d.length===1)i=d[0];else throw d.length===0?new Error(`No Kanonak packages found under ${a}`):new Error(`Workspace has multiple publishers (${d.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let g=new Set,f=new Map;for(let c of n)c.publisher===i&&(g.add(`${c.publisher}/${c.package_}@${c.verStr}`),f.set(`${c.package_}@${c.verStr}`,c.source));let p=new z(j(),!0,r),o=e.repository??new Z(t,p,new I(e.httpCache?{getFromCache:e.httpCache.getFromCache,onFetch:e.httpCache.onFetch}:void 0)),m=M(void 0);if(!e.repository){let c=j(),R=s=>{let h=W(c,s);return le(h)?new Set(pe(h).filter(y=>y.endsWith(".kan.yml")).map(y=>y.split("@")[0])):new Set},b=(s,h)=>n.some(y=>y.publisher===s&&y.package_===h),x=new F,l=new Map;for(let s of m)if(l.has(s.publisher)||l.set(s.publisher,R(s.publisher)),!(l.get(s.publisher).has(s.package_)||b(s.publisher,s.package_)))try{let h=await x.getHighestVersion(s.publisher,s.package_);if(!h)continue;let y=await x.getPackageUrl(s.publisher,s.package_,h),P=await fetch(y);if(!P.ok)continue;let ie=await P.text(),G=W(c,s.publisher);de(G,{recursive:!0}),ue(W(G,`${s.package_}@${h}.kan.yml`),ie,"utf-8")}catch{}}let k=o;if(!e.repository){let c=(await t.getAllDocumentsAsync()).filter(b=>b.metadata.namespace_?.publisher===i),R=await A(c,o);for(let b of m)R.add(B(b));k=new D(o,R)}let v=await new N(r).parseKanonaks(k),$=new O(v);return E({publisher:i,availablePublishers:d,catalog:v,lookRenderer:$,localNamespaces:g,rawByNsKey:f})}import{existsSync as me,readFileSync as ge,writeFileSync as fe,mkdirSync as he}from"fs";import{join as oe}from"path";async function q(a,e={}){let r=new K,t=L(a),n=t.kind==="resource"?t.uri.publisher:t.publisher,u=e.cacheRoot??j(),d=(l,s,h)=>oe(u,l,`${s}@${h}.kan.yml`),i=new I({getFromCache:(l,s,h)=>{let y=d(l,s,h);return me(y)?ge(y,"utf-8"):null},onFetch:(l,s,h,y)=>{let P=oe(u,l);he(P,{recursive:!0}),fe(d(l,s,h),y,"utf-8")},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),g=new F(e.fetchFn?{fetchFn:e.fetchFn}:void 0),f;if(t.kind==="resource"){let l=t.uri.version;f=[l?{package_:t.uri.package_,version:`${l.major}.${l.minor}.${l.patch}`}:{package_:t.uri.package_}]}else if(t.kind==="package"){let l=t.version;f=[l?{package_:t.package_,version:`${l.major}.${l.minor}.${l.patch}`}:{package_:t.package_}]}else f=(await g.listLatestPackages(n)).map(s=>({package_:s.packageName}));let p=async(l,s,h)=>{try{let y=h?r.buildImport(s,"=",h,l):r.buildImport(s,"*","0.0.0",l);return await i.getHighestCompatibleVersionAsync(l,y)}catch{return null}},o=[];for(let l of f){let s=await p(n,l.package_,l.version);s&&o.push(s)}if(o.length===0)throw new Error(`Could not fetch any package for address "${a}" from publisher "${n}".`);let m=await new X().getConfig(n).catch(()=>{}),k=[];for(let l of M(m)){let s=await p(l.publisher,l.package_,void 0);s&&k.push(s)}let v=await A([...o,...k],i),$=new D(i,v),c=await new N(r).parseKanonaks($),R=new O(c),b=new Set,x=new Map;for(let l of await i.getAllDocumentsAsync()){let s=l.metadata.namespace_;if(!s||s.publisher!==n)continue;let h=`${s.version.major}.${s.version.minor}.${s.version.patch}`,y=`${s.publisher}/${s.package_}@${h}`;b.add(y);let P=await i.getDocumentContentAsync(y);P!==null&&x.set(`${s.package_}@${h}`,P)}return E({publisher:n,availablePublishers:[n],catalog:c,lookRenderer:R,localNamespaces:b,rawByNsKey:x})}var w={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},S=(a,e,r,t)=>({status:a,headers:{"Content-Type":e,...t||{}},body:r}),_=a=>S(404,w[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${a}</p>`),ke=a=>({status:301,headers:{Location:a},body:""});function se(a,e,r){let t=a.pkgVersions.get(e);if(!t||t.length===0)return null;switch(r.kind){case"any":return t[0].verStr;case"major-pin":return t.find(n=>n.version.major===r.major)?.verStr??null;case"minor-pin":return t.find(n=>n.version.major===r.major&&n.version.minor===r.minor)?.verStr??null;case"exact":return t.find(n=>n.version.major===r.major&&n.version.minor===r.minor&&n.version.patch===r.patch)?.verStr??null;default:return null}}async function T(a,e,r=""){let{lookRenderer:t,publisher:n}=a;if(e==="/.well-known/kanonak.json")return S(200,w[".json"],JSON.stringify(Q(n),null,2));if(e==="/index.txt"){let o=[...a.localNamespaces].map(m=>m.split("/")[1].replace("@","/")).sort();return S(200,w[".txt"],o.join(`
1
+ import{j as E}from"../chunk-X5TYWQRA.js";import"../chunk-QHABFCRC.js";import{a as Z,d as A,f as te,g as N}from"../chunk-ATH6636H.js";import{a as ee,b as re,c as V,d as I}from"../chunk-LKBG2MK6.js";import{a as X}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as oe}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{f as L}from"../chunk-G2DKKSZ4.js";import{a as D}from"../chunk-TJPQETHV.js";import{b as O}from"../chunk-BGQKZBNE.js";import"../chunk-CRKSKIAL.js";import"../chunk-IOMNZBK4.js";import{c as ne}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{c as F,e as z,f as K,g as Q}from"../chunk-2ACBWC7K.js";import{readFileSync as ue,existsSync as de,readdirSync as me,writeFileSync as ge,mkdirSync as fe}from"fs";import{join as q}from"path";function se(n){let e=n.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function M(n,e){let t=new Set,r=[...n];for(;r.length>0;){let o=r.shift(),i=se(o);if(!i||t.has(i))continue;t.add(i);let d=o.metadata?.imports;if(d)for(let[c,f]of Object.entries(d))for(let g of f)try{let l=await e.getHighestCompatibleVersionAsync(c,g);l&&r.push(l)}catch{}}return t}var j=class{constructor(e,t){this.inner=e;this.scope=t}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(t=>{let r=se(t);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.inner.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.inner.getHighestCompatibleVersionAsync(e,t)}saveDocumentAsync(e,t){return this.inner.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.inner.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var ae=[{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 C(n){let e=n?.render;if(e&&e.length>0){let t=[];for(let r of e)try{let o=O(r);o.kind==="package"?t.push({publisher:o.publisher,package_:o.package_}):o.kind==="resource"&&t.push({publisher:o.uri.publisher,package_:o.uri.package_})}catch{}if(t.length>0)return t}return ae}function H(n){return`${n.publisher}/${n.package_}`}function B(n){let{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,producers:c}=n,f=new Map,g=new Map,l=new Map,a=new Set;for(let m of r){if(!(m instanceof ne))continue;let y=m.namespace||"";if(!i.has(y))continue;f.set(`${y}/${m.name}`,m);let v=y.split("/")[1]??"",[x,p]=v.split("@");if(!x||!p)continue;let b=Q(p);b&&(a.has(v)||(a.add(v),g.has(x)||g.set(x,[]),g.get(x).push({verStr:p,version:b})),m.name===x&&l.set(v,m))}for(let m of g.values())m.sort((y,v)=>F(v.version,y.version));return{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,bySubject:f,pkgVersions:g,pkgSelfByVer:l,...c?{producers:c}:{}}}async function T(n,e={}){let t=new D,r=new X(t),o=[],i=[];for(let p of N(n)){let b;try{b=ue(p,"utf-8")}catch{continue}let w;try{w=t.parse(b).metadata?.namespace_}catch{continue}if(!w?.version)continue;let $=w.version;i.push({publisher:w.publisher,package_:w.package_,verStr:`${$.major}.${$.minor}.${$.patch}`,version:$,source:b})}i.sort((p,b)=>F(b.version,p.version));for(let p of i)await r.saveDocumentAsync(t.parse(p.source),`${p.publisher}/${p.package_}@${p.verStr}`),o.push({publisher:p.publisher,package_:p.package_,verStr:p.verStr,source:p.source});let d=[...new Set(o.map(p=>p.publisher))].sort(),c=e.publisher;if(c){if(!d.includes(c))throw new Error(`Publisher "${c}" not found in workspace. Available: ${d.join(", ")||"(none)"}`)}else if(d.length===1)c=d[0];else throw d.length===0?new Error(`No Kanonak packages found under ${n}`):new Error(`Workspace has multiple publishers (${d.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,g=new Map;for(let p of o)p.publisher===c&&(f.add(`${p.publisher}/${p.package_}@${p.verStr}`),g.set(`${p.package_}@${p.verStr}`,p.source));let l=new Z(A(),!0,t),a=e.repository??new te(r,l,new I(e.httpCache?{getFromCache:e.httpCache.getFromCache,onFetch:e.httpCache.onFetch}:void 0)),m=C(void 0);if(!e.repository){let p=A(),b=s=>{let h=q(p,s);return de(h)?new Set(me(h).filter(k=>k.endsWith(".kan.yml")).map(k=>k.split("@")[0])):new Set},w=(s,h)=>o.some(k=>k.publisher===s&&k.package_===h),$=new V,u=new Map;for(let s of m)if(u.has(s.publisher)||u.set(s.publisher,b(s.publisher)),!(u.get(s.publisher).has(s.package_)||w(s.publisher,s.package_)))try{let h=await $.getHighestVersion(s.publisher,s.package_);if(!h)continue;let k=await $.getPackageUrl(s.publisher,s.package_,h),_=await fetch(k);if(!_.ok)continue;let le=await _.text(),J=q(p,s.publisher);fe(J,{recursive:!0}),ge(q(J,`${s.package_}@${h}.kan.yml`),le,"utf-8")}catch{}}let y=a;if(!e.repository){let p=(await r.getAllDocumentsAsync()).filter(w=>w.metadata.namespace_?.publisher===c),b=await M(p,a);for(let w of m)b.add(H(w));y=new j(a,b)}let v=await new L(t).parseKanonaks(y),x=new E(v);return B({publisher:c,availablePublishers:d,catalog:v,lookRenderer:x,localNamespaces:f,rawByNsKey:g})}import{existsSync as he,readFileSync as ke,writeFileSync as ye,mkdirSync as ve}from"fs";import{join as ie}from"path";async function U(n,e={}){let t=new D,r=O(n),o=r.kind==="resource"?r.uri.publisher:r.publisher,i=e.cacheRoot??A(),d=(u,s,h)=>ie(i,u,`${s}@${h}.kan.yml`),c=new I({getFromCache:(u,s,h)=>{let k=d(u,s,h);return he(k)?ke(k,"utf-8"):null},onFetch:(u,s,h,k)=>{let _=ie(i,u);ve(_,{recursive:!0}),ye(d(u,s,h),k,"utf-8")},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),f=new V(e.fetchFn?{fetchFn:e.fetchFn}:void 0),g;if(r.kind==="resource"){let u=r.uri.version;g=[u?{package_:r.uri.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let u=r.version;g=[u?{package_:r.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.package_}]}else g=(await f.listLatestPackages(o)).map(s=>({package_:s.packageName}));let l=async(u,s,h)=>{try{let k=h?t.buildImport(s,"=",h,u):t.buildImport(s,"*","0.0.0",u);return await c.getHighestCompatibleVersionAsync(u,k)}catch{return null}},a=[];for(let u of g){let s=await l(o,u.package_,u.version);s&&a.push(s)}if(a.length===0)throw new Error(`Could not fetch any package for address "${n}" from publisher "${o}".`);let m=await new re().getConfig(o).catch(()=>{}),y=[];for(let u of C(m)){let s=await l(u.publisher,u.package_,void 0);s&&y.push(s)}let v=await M([...a,...y],c),x=new j(c,v),p=await new L(t).parseKanonaks(x),b=new E(p),w=new Set,$=new Map;for(let u of await c.getAllDocumentsAsync()){let s=u.metadata.namespace_;if(!s||s.publisher!==o)continue;let h=`${s.version.major}.${s.version.minor}.${s.version.patch}`,k=`${s.publisher}/${s.package_}@${h}`;w.add(k);let _=await c.getDocumentContentAsync(k);_!==null&&$.set(`${s.package_}@${h}`,_)}return B({publisher:o,availablePublishers:[o],catalog:p,lookRenderer:b,localNamespaces:w,rawByNsKey:$})}import{VersionOperator as W}from"@kanonak-protocol/types/document/models/enums";var S={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},R=(n,e,t,r)=>({status:n,headers:{"Content-Type":e,...r||{}},body:t}),P=n=>R(404,S[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${n}</p>`),be=n=>({status:301,headers:{Location:n},body:""}),we=n=>({status:302,headers:{Location:n},body:""});function Se(n){switch(n.kind){case"exact":return{operator:W.Exact,version:K(n.major,n.minor,n.patch)};case"minor-pin":return{operator:W.Compatible,version:K(n.major,n.minor,0)};case"major-pin":return{operator:W.Major,version:K(n.major,0,0)};default:return{operator:W.Any,version:K(0,0,0)}}}async function Re(n,e,t,r){if(!r)return null;let o=n.producers?.find(f=>f.canProduce(n.publisher,e));if(!o)return null;let i=await o.resolveVersion(n.publisher,e,Se(t));if(!i)return null;let d=z(i);if(t.kind!=="exact")return we(`/${e}/${d}.kan.yml`);let{source:c}=await o.produce(n.publisher,e,i);return R(200,S[".kan.yml"],c)}function ce(n,e,t){let r=n.pkgVersions.get(e);if(!r||r.length===0)return null;switch(t.kind){case"any":return r[0].verStr;case"major-pin":return r.find(o=>o.version.major===t.major)?.verStr??null;case"minor-pin":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor)?.verStr??null;case"exact":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor&&o.version.patch===t.patch)?.verStr??null;default:return null}}async function G(n,e,t=""){let{lookRenderer:r,publisher:o}=n;if(e==="/.well-known/kanonak.json"){let a=ee(o);return n.producers&&n.producers.length>0&&(a.resolveByRedirect=!0),R(200,S[".json"],JSON.stringify(a,null,2))}if(e==="/index.txt"){let a=[...n.localNamespaces].map(m=>m.split("/")[1].replace("@","/")).sort();return R(200,S[".txt"],a.join(`
2
2
  `)+`
3
- `)}if(e==="/"||e==="/index.html"||e==="/index.css"){let o=t.publisherSubject(n);return e==="/index.css"?S(200,w[".css"],t.renderStylesheet(o)):S(200,w[".html"],t.renderDocument(o,{rootIndex:!0}))}let u=".html",d=!1,i=e;for(let o of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(o)){u=o,d=!0,i=e.slice(0,-o.length);break}let g=!d&&/application\/yaml|text\/yaml/i.test(r),f=i.endsWith("/");f&&i!=="/"&&(i=i.slice(0,-1));let p=te.parse(i,n);if(!p)return _(e);if(p.kind==="package"){let o=se(a,p.package_,p.versionSpec);if(!o)return _(e);if(u===".kan.yml"||g){let v=a.rawByNsKey.get(`${p.package_}@${o}`);return v!==void 0?S(200,w[".kan.yml"],v):_(e)}let m=a.pkgSelfByVer.get(`${p.package_}@${o}`);if(!m)return _(e);if(u===".css")return S(200,w[".css"],t.renderStylesheet(m));if(!f)return ke(i+"/");let k=p.versionSpec.kind==="any";if(k&&!t.hasDeclaredView(m)){let v=(a.pkgVersions.get(p.package_)||[]).map($=>$.verStr);return S(200,w[".html"],t.renderPackageVersionList(p.package_,v,m))}return S(200,w[".html"],t.renderDocument(m,k?{bareOverview:!0}:void 0))}if(p.kind==="resource"){let o=se(a,p.package_,p.versionSpec);if(!o)return _(e);let m=a.bySubject.get(`${n}/${p.package_}@${o}/${p.name}`);if(!m)return _(e);switch(u){case".css":return S(200,w[".css"],t.renderStylesheet(m));case".svg":return S(200,w[".svg"],await t.renderSvg(m));case".md":{let k=t.renderRawMarkdown(m);return k===void 0?_(e):S(200,w[".md"],k)}default:return S(200,w[".html"],t.renderDocument(m))}}return _(e)}import{readFileSync as ye}from"fs";var U=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,r=new Set;if(this.options.root!==void 0){let t=new K;for(let n of V(this.options.root))try{let u=t.parse(ye(n,"utf-8")).metadata?.namespace_;if(!u?.version)continue;let d=u.version;e.add(`${u.publisher}/${u.package_}@${d.major}.${d.minor}.${d.patch}`),r.add(`${u.publisher}/${u.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:r},this.workspaceIndex}async modelFor(e,r,t){let n=this.getWorkspaceIndex(),u=this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},d=r?t?n.exact.has(`${e}/${r}@${t}`):n.pkgs.has(`${e}/${r}`):[...n.pkgs].some(o=>o.startsWith(`${e}/`)),i,g;if(d&&this.options.root!==void 0){let o=this.options.root;i=`ws:${e}`,g=()=>H(o,{publisher:e})}else{let o=r?t?`${e}/${r}@${t}`:`${e}/${r}`:e;i=`rm:${o}`,g=()=>q(o,u)}let f=this.models.get(i);if(f)return f;let p=await g();return p.lookRenderer.setLinkMode("open-world"),this.models.set(i,p),p}async handle(e,r=""){let t=e.split("/").filter(Boolean);if(t.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:ae()};let n=t[0];if(!n.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let u=t.length>=2&&(t[1]==="index.html"||t[1]==="index.css"||t[1]==="index.txt"||t[1]===".well-known"),d=!u&&t.length>=2?t[1]:void 0,i=!u&&t.length>=3&&/^\d+\.\d+\.\d+$/.test(t[2])?t[2]:void 0,g=await this.modelFor(n,d,i),f=e.endsWith("/")&&t.length>1?"/":"",p="/"+t.slice(1).join("/")+f,o=await T(g,p,r);return o.headers.Location?{...o,headers:{...o.headers,Location:`/${n}${o.headers.Location}`}}:o}};function ae(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{D as ClosureScopedRepository,U as RequestRouter,ne as UNIVERSAL_RENDER_BASE,A as deriveImportClosure,ae as landingPage,q as loadResourceModel,H as loadServerModel,B as renderRefKey,M as resolveRenderContract,T as route};
3
+ `)}if(e==="/"||e==="/index.html"||e==="/index.css"){let a=r.publisherSubject(o);return e==="/index.css"?R(200,S[".css"],r.renderStylesheet(a)):R(200,S[".html"],await r.renderDocument(a,{rootIndex:!0}))}let i=".html",d=!1,c=e;for(let a of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(a)){i=a,d=!0,c=e.slice(0,-a.length);break}let f=!d&&/application\/yaml|text\/yaml/i.test(t),g=c.endsWith("/");g&&c!=="/"&&(c=c.slice(0,-1));let l=oe.parse(c,o);if(!l)return P(e);if(l.kind==="package"){let a=ce(n,l.package_,l.versionSpec);if(!a)return await Re(n,l.package_,l.versionSpec,i===".kan.yml"||f)??P(e);if(i===".kan.yml"||f){let v=n.rawByNsKey.get(`${l.package_}@${a}`);return v!==void 0?R(200,S[".kan.yml"],v):P(e)}let m=n.pkgSelfByVer.get(`${l.package_}@${a}`);if(!m)return P(e);if(i===".css")return R(200,S[".css"],r.renderStylesheet(m));if(!g)return be(c+"/");let y=l.versionSpec.kind==="any";if(y&&!r.hasDeclaredView(m)){let v=(n.pkgVersions.get(l.package_)||[]).map(x=>x.verStr);return R(200,S[".html"],r.renderPackageVersionList(l.package_,v,m))}return R(200,S[".html"],await r.renderDocument(m,y?{bareOverview:!0}:void 0))}if(l.kind==="resource"){let a=ce(n,l.package_,l.versionSpec);if(!a)return P(e);let m=n.bySubject.get(`${o}/${l.package_}@${a}/${l.name}`);if(!m)return P(e);switch(i){case".css":return R(200,S[".css"],r.renderStylesheet(m));case".svg":return R(200,S[".svg"],await r.renderSvg(m));case".md":{let y=r.renderRawMarkdown(m);return y===void 0?P(e):R(200,S[".md"],y)}default:return R(200,S[".html"],await r.renderDocument(m))}}return P(e)}import{readFileSync as xe}from"fs";var Y=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,t=new Set;if(this.options.root!==void 0){let r=new D;for(let o of N(this.options.root))try{let i=r.parse(xe(o,"utf-8")).metadata?.namespace_;if(!i?.version)continue;let d=i.version;e.add(`${i.publisher}/${i.package_}@${d.major}.${d.minor}.${d.patch}`),t.add(`${i.publisher}/${i.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:t},this.workspaceIndex}async modelFor(e,t,r){let o=this.getWorkspaceIndex(),i=this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},d=t?r?o.exact.has(`${e}/${t}@${r}`):o.pkgs.has(`${e}/${t}`):[...o.pkgs].some(a=>a.startsWith(`${e}/`)),c,f;if(d&&this.options.root!==void 0){let a=this.options.root;c=`ws:${e}`,f=()=>T(a,{publisher:e})}else{let a=t?r?`${e}/${t}@${r}`:`${e}/${t}`:e;c=`rm:${a}`,f=()=>U(a,i)}let g=this.models.get(c);if(g)return g;let l=await f();return l.lookRenderer.setLinkMode("open-world"),this.models.set(c,l),l}async handle(e,t=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:pe()};let o=r[0];if(!o.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let i=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),d=!i&&r.length>=2?r[1]:void 0,c=!i&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,f=await this.modelFor(o,d,c),g=e.endsWith("/")&&r.length>1?"/":"",l="/"+r.slice(1).join("/")+g,a=await G(f,l,t);return a.headers.Location?{...a,headers:{...a.headers,Location:`/${o}${a.headers.Location}`}}:a}};function pe(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{j as ClosureScopedRepository,Y as RequestRouter,ae as UNIVERSAL_RENDER_BASE,M as deriveImportClosure,pe as landingPage,U as loadResourceModel,T as loadServerModel,H as renderRefKey,C as resolveRenderContract,G as route};
@@ -4,6 +4,7 @@ import type { Kanonak } from '../kanonaks/index.js';
4
4
  import { SubjectKanonak } from '../kanonaks/index.js';
5
5
  import type { LookRenderer } from '../look/index.js';
6
6
  import type { HttpCacheHooks } from '../repositories/index.js';
7
+ import type { IPackageProducer } from '../producer/index.js';
7
8
  /** A package version present in the served workspace. */
8
9
  export interface PackageVersion {
9
10
  /** "major.minor.patch" string form. */
@@ -36,6 +37,14 @@ export interface ServerModel {
36
37
  readonly pkgVersions: Map<string, PackageVersion[]>;
37
38
  /** `pkg@ver` → the package self-resource subject. */
38
39
  readonly pkgSelfByVer: Map<string, SubjectKanonak>;
40
+ /**
41
+ * Package producers this origin hosts (optional). When a requested package
42
+ * is not preloaded but a producer claims it, `route` generates the package
43
+ * on demand: a range request 302-redirects to the resolved pinned source,
44
+ * an exact `.kan.yml` request is produced and served. Compose
45
+ * `EntitlementProducer` here for a gated origin.
46
+ */
47
+ readonly producers?: readonly IPackageProducer[];
39
48
  }
40
49
  /** A routed response. `body` is always a string (HTML/CSS/SVG/MD/YAML/JSON). */
41
50
  export interface RouteResponse {
@@ -1,4 +1,4 @@
1
- import{b as Y,c as An,d as Sn,e as ce,f as Te,g as O,h as wn,i as X,j as q}from"../chunk-MCU5IAMS.js";import{a as se}from"../chunk-F5ANO7MJ.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-GN2XODVC.js";import"../chunk-PEJALHXK.js";import{a as kn,b as bn,c as hn,d as Dn}from"../chunk-SHDHMKMJ.js";import{f as ie}from"../chunk-G2DKKSZ4.js";import{a as ae}from"../chunk-TJPQETHV.js";import{b as L,c as A,f as S}from"../chunk-CRKSKIAL.js";import"../chunk-IOMNZBK4.js";import{b as N,c as D,d as K,g as M,h as P,i as F,j as W,l as H}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{g as oe}from"../chunk-2ACBWC7K.js";var $e="kanonak.org",Ue="document-ast",i=e=>({publisher:$e,package_:Ue,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 ue(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var j=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=xe(n.metadata,t),o=Le(n.children),s=["---",...r,"---","",o].join(`
1
+ import{b as Y,c as An,d as Sn,e as ce,f as Te,g as O,h as wn,i as X,j as q}from"../chunk-X5TYWQRA.js";import{a as se}from"../chunk-F5ANO7MJ.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-GN2XODVC.js";import"../chunk-PEJALHXK.js";import{a as kn,b as bn,c as hn,d as Dn}from"../chunk-SHDHMKMJ.js";import{f as ie}from"../chunk-G2DKKSZ4.js";import{a as ae}from"../chunk-TJPQETHV.js";import{b as L,c as A,f as S}from"../chunk-CRKSKIAL.js";import"../chunk-IOMNZBK4.js";import{b as N,c as D,d as K,g as M,h as P,i as F,j as W,l as H}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{g as oe}from"../chunk-2ACBWC7K.js";var $e="kanonak.org",Ue="document-ast",i=e=>({publisher:$e,package_:Ue,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 ue(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var j=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=xe(n.metadata,t),o=Le(n.children),s=["---",...r,"---","",o].join(`
2
2
  `);return t?.trailingNewline&&(s.endsWith(`
3
3
  `)||(s+=`
4
4
  `)),s}};function xe(e,n){if(!e)return[];let t=new Map;for(let c of e.entries)t.set(I(c.key),c);let r=new Map;if(n?.metadataRenames)for(let[c,u]of n.metadataRenames)r.set(I(c),u);let a=(n?.metadataKeys??e.entries.map(c=>c.key)).map(I),s=[];for(let c of a){let u=t.get(c);if(!u)continue;let f=r.get(c),l=I(f??c),d=me(u.value,u.escapeHint);d!==void 0&&s.push(`${l}: ${d}`)}return s}function I(e){let n=e.lastIndexOf(".");return n===-1?e:e.substring(n+1)||e}function me(e,n){switch(e.kind){case"StringScalar":return Ve(e.stringValue,n);case"IntegerScalar":return String(e.integerValue);case"StructuredList":{let t=[];for(let r of e.items){let o=me(r,n);o!==void 0&&t.push(o)}return t.join(", ")}case"StructuredMap":return;default:return}}function Ve(e,n){return!n||ue(n,m.ESC_RAW)?e:ue(n,m.ESC_YAML_SAFE)?ve(e):e}function ve(e){return e.includes(`
@@ -88,4 +88,4 @@ ${e.rawContent}
88
88
  `)&&(o+=`
89
89
  `),o}};function V(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var v=class{backendUri="kanonak.org/transformations/dynamodb-json";render(n,t){if(!n.metadata)throw new Error("dynamodb-json backend: Document has no `metadata` channel. This backend serializes Document.metadata into DynamoDB attribute-value JSON \u2014 the transformation must populate that channel. (No silent empty artifact.)");let r=ke(n.metadata,t),o=JSON.stringify(r,null,2);return t?.trailingNewline&&!o.endsWith(`
90
90
  `)&&(o+=`
91
- `),o}};function ke(e,n){let t=new Map;for(let a of e.entries)t.set(a.key,a);let r=n?.metadataKeys??e.entries.map(a=>a.key),o={};for(let a of r){let s=t.get(a);if(!s)continue;let c=n?.metadataRenames.get(a)??a;o[c]=be(s.value,s.escapeHint)}return{M:o}}function be(e,n){switch(e.kind){case"StructuredMap":return ke(e);case"StructuredList":return{L:e.items.map(t=>be(t,void 0))};case"StringScalar":return on(e.stringValue,n??e.escapeHint);case"IntegerScalar":return an(e.integerValue,n??e.escapeHint)}}function on(e,n){if(n&&V(n,m.ESC_DYNAMODB_BOOL)){if(e==="true")return{BOOL:!0};if(e==="false")return{BOOL:!1};throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-bool must have the value "true" or "false"; got ${JSON.stringify(e)}.`)}if(n&&V(n,m.ESC_DYNAMODB_NULL))return{NULL:!0};if(n&&V(n,m.ESC_DYNAMODB_NUMBER)){if(e.trim()===""||Number.isNaN(Number(e)))throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-number must hold a numeric literal; got ${JSON.stringify(e)}.`);return{N:e}}return{S:e}}function an(e,n){if(n&&V(n,m.ESC_DYNAMODB_BOOL))throw new Error(`dynamodb-json backend: esc-dynamodb-bool cannot apply to an IntegerScalar (value ${e}). Use a StringScalar "true"/"false".`);if(n&&V(n,m.ESC_DYNAMODB_NULL))throw new Error(`dynamodb-json backend: esc-dynamodb-null cannot apply to an IntegerScalar (value ${e}). Use a StringScalar hinted esc-dynamodb-null.`);return{N:String(e)}}var sn={"markdown-with-frontmatter":{formatUri:"kanonak.org/transformations/markdown-with-frontmatter",extension:".md"},"plain-markdown":{formatUri:"kanonak.org/transformations/plain-markdown",extension:".md"},toml:{formatUri:"kanonak.org/transformations/toml",extension:".toml"},json:{formatUri:"kanonak.org/transformations/json",extension:".json"},html:{formatUri:"kanonak.org/transformations/html",extension:".html"},svg:{formatUri:"kanonak.org/transformations/svg",extension:".svg"},stylesheet:{formatUri:"kanonak.org/transformations/stylesheet",extension:".css"},yaml:{formatUri:"kanonak.org/transformations/yaml",extension:".yaml"},"dynamodb-json":{formatUri:"kanonak.org/transformations/dynamodb-json",extension:".json"}},h=class extends Error{},C=class{backends=new Map;constructor(){this.register(new j),this.register(new E),this.register(new B),this.register(new T),this.register(new $),this.register(new U),this.register(new x),this.register(new v)}register(n){this.backends.set(n.backendUri,n)}async run(n){let t=n.transformationKanonaks??n.allKanonaks,r=O(n.transformation,t);if(!r.outputs.has(n.outputFormat))throw new h(`Transformation "${r.name}" does not declare output format "${n.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let o=this.findBackend(n.outputFormat);if(!o)throw new h(`No backend registered for OutputFormat "${n.outputFormat}".`);let a=new X(n.repository,n.parser,n.objectParser),s=new ce(a,n.allKanonaks,r.fragments);return r.kind==="instance"?this.runInstance(r,n,o,s):this.runSet(r,n,o,s)}async runInstance(n,t,r,o){let a=he(t.instances,n.inputPattern.requires),s=De(a,n.inputPattern.sortBy),c=[];for(let u of s){let f=new Map;f.set("input",u);let l=await o.evaluate(n.rule,f);Z(l,n.name,`input "${u.name}"`);let d=ee(await o.evaluate(n.artifactName,f),n.name,`input "${u.name}"`),g=ne(n.overrides.get(t.outputFormat),t.runtimeOverride),k=r.render(l,g);c.push({fileName:d,format:t.outputFormat,content:k,source:{kind:"instance",sourceName:u.name}})}return c}async runSet(n,t,r,o){let a=he(t.instances,n.inputPattern.requires),s=De(a,n.inputPattern.sortBy);return n.partitionBy?this.runSetWithPartition(n,s,t,r,o):this.runSetSingle(n,s,t,r,o)}async runSetSingle(n,t,r,o,a){let s=new Map;s.set("inputs",t);let c=await a.evaluate(n.rule,s);Z(c,n.name,"set");let u=ee(await a.evaluate(n.artifactName,s),n.name,"set"),f=ne(n.overrides.get(r.outputFormat),r.runtimeOverride),l=o.render(c,f);return[{fileName:u,format:r.outputFormat,content:l,source:{kind:"set",memberCount:t.length}}]}async runSetWithPartition(n,t,r,o,a){let s=n.partitionBy,c=new Map,u=[];for(let l of t){let d=mn(l,s);if(d==null)continue;let g=dn(d),k=c.get(g);k||(k={keyValue:d,keyDisplay:fn(d),members:[]},c.set(g,k),u.push(g)),k.members.push(l)}let f=[];for(let l of u){let d=c.get(l),g=new Map;g.set("inputs",d.members),g.set("key",d.keyValue);let k=await a.evaluate(n.rule,g);Z(k,n.name,`partition "${d.keyDisplay}"`);let je=ee(await a.evaluate(n.artifactName,g),n.name,`partition "${d.keyDisplay}"`),Ee=ne(n.overrides.get(r.outputFormat),r.runtimeOverride),Be=o.render(k,Ee);f.push({fileName:je,format:r.outputFormat,content:Be,source:{kind:"set",memberCount:d.members.length,partitionKey:d.keyDisplay}})}return f}findBackend(n){let t=sn[n];if(t)return this.backends.get(t.formatUri)}};function he(e,n){return n.length===0?e:e.filter(t=>{for(let r of n)if(!un(t,r))return!1;return!0})}function De(e,n){if(n.length===0)return e;let t=[...e];return t.sort((r,o)=>{for(let a of n){let s=Ae(r,a.byProperty),c=Ae(o,a.byProperty),u=cn(s,c,a.order);if(u!==0)return u}return 0}),t}function Ae(e,n){for(let t of e.statement){let r=te(t);if(!(!r||!L(r,n))){if(t instanceof M||t instanceof P||t instanceof F)return t.object;if(t instanceof H)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(t instanceof W)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function cn(e,n,t){if(e===void 0&&n===void 0)return 0;if(e===void 0)return t==="ascending"?1:-1;if(n===void 0)return t==="ascending"?-1:1;let r;return typeof e=="number"&&typeof n=="number"?r=e-n:r=String(e).localeCompare(String(n)),t==="ascending"?r:-r}function un(e,n){for(let t of e.statement){let r=te(t);if(!r||!L(r,n))continue;let o=t.object;if(o!=null&&!(typeof o=="string"&&o.length===0)&&!(Array.isArray(o)&&o.length===0))return!0}return!1}function mn(e,n){for(let t of e.statement){let r=te(t);if(!(!r||!L(r,n))&&(t instanceof M||t instanceof P||t instanceof F||t instanceof W||t instanceof H))return t.object}}function te(e){return e.predicate?.subject}function dn(e){if(e===void 0)return" undef";if(e===null)return" null";if(typeof e=="string")return`s:${e}`;if(typeof e=="number")return`n:${e}`;if(typeof e=="boolean")return`b:${e}`;if(e instanceof K){let n=e.subject;return`r:${n.publisher}/${n.package_}/${n.name}`}if(e instanceof N){let n=e.name??"";return`k:${e.namespace??""}/${n}`}if(typeof e=="object"&&e!==null&&typeof e.name=="string"&&typeof e.publisher=="string"){let n=e;return`u:${n.publisher}/${n.package_}/${n.name}`}return`o:${JSON.stringify(e)}`}function fn(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e instanceof K?e.subject.name:e instanceof N?e.name??"":typeof e=="object"&&e!==null&&typeof e.name=="string"?e.name:""}function Z(e,n,t){if(typeof e!="object"||e===null||e.kind!=="Document")throw new h(`Transformation "${n}" rule did not yield a Document for ${t}. Got: ${Se(e)}`)}function ee(e,n,t){if(typeof e=="string")return e;if(Array.isArray(e)&&e.every(ln))return e.map(r=>String(r)).join("");throw new h(`Transformation "${n}" artifactName did not yield a string for ${t}. Got: ${Se(e)}`)}function ln(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Se(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"){let n=e.kind;return n?`object(kind=${n})`:"object"}return typeof e}function ne(e,n){if(!e&&!n)return;let t={metadataRenames:n?.metadataRenames??e?.metadataRenames??new Map},r=n?.metadataKeys??e?.metadataKeys;r!==void 0&&(t.metadataKeys=r);let o=n?.trailingNewline??e?.trailingNewline;o!==void 0&&(t.trailingNewline=o);let a=n?.omitWrapper??e?.omitWrapper;return a!==void 0&&(t.omitWrapper=a),t}var p=class extends Error{constructor(t,r){super(t);this.cause=r;this.name="RenderError"}cause},we={publisher:"kanonak.org",package_:"derivation",name:"default"},re=class{constructor(n,t=new ae,r=new ie){this.repository=n;this.parser=t;this.objectParser=r}repository;parser;objectParser;runner=new C;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async renderViaLook(n){let t=await this.getCatalog(),r=S(t,n.resource);if(!(r instanceof D))throw new p(`Resource not found: ${b(n.resource)}`);let o=new q(t),a;if(n.format.name==="html")a=o.renderHtml(r);else if(n.format.name==="stylesheet")a=o.renderStylesheet(r);else throw new p(`LookRenderer does not support format ${b(n.format)} \u2014 only formats.html and formats.stylesheet are implemented in v0.1.`);return{content:a,format:n.format,filename:r.name}}async findDerivation(n){let t=await this.getCatalog(),r=S(t,n.resource);if(!(r instanceof D))return;let o=n.variant??we;return se(r,n.format,o,t)}async render(n){if(n.format.name==="html"||n.format.name==="stylesheet"){let a=await this.getCatalog(),s=S(a,n.resource);if(s instanceof D){let u=new q(a).findCascadedLook(s);if(u&&!gn(u.sourceClass)){let f=await this.findDerivation(n);if(!f||pn(f))return this.renderViaLook({resource:n.resource,format:n.format})}}}let t=await this.findDerivation(n);if(!t)throw new p(`No derivation found for ${b(n.resource)} \u2192 format ${b(n.format)}`+(n.variant?` variant ${b(n.variant)}`:""));let r=oe(t.transformation.version),o={transformation:{publisher:t.transformation.publisher,package_:t.transformation.package_,name:t.transformation.name,...r?{version:r}:{}},input:n.resource,format:n.format};return n.omitWrapper!==void 0&&(o.omitWrapper=n.omitWrapper),this.runTransformation(o)}async runTransformation(n){let t=await this.getCatalog(),r=S(t,n.transformation);if(!(r instanceof D))throw new p(`Transformation not found: ${b(n.transformation)}`);let o=S(t,n.input);if(!(o instanceof D))throw new p(`Input resource not found: ${b(n.input)}`);let a=O(r,t),s=yn(a.outputs,n.format);if(!s)throw new p(`Transformation ${b(n.transformation)} declares outputs [${[...a.outputs].join(", ")}], none of which corresponds to format ${b(n.format)}`);let c;try{c=await this.runner.run({transformation:r,instances:[o],allKanonaks:t,repository:this.repository,parser:this.parser,objectParser:this.objectParser,outputFormat:s,...n.omitWrapper!==void 0?{runtimeOverride:{metadataRenames:new Map,omitWrapper:n.omitWrapper}}:{}})}catch(u){throw new p(`Transformation execution failed: ${u.message}`,u)}if(c.length===0)throw new p("Transformation produced no artifacts");return{content:c[0].content,format:n.format,filename:c[0].fileName}}async getCatalog(){return this.cachedCatalog||(this.cachedCatalog=await this.objectParser.parseKanonaks(this.repository)),this.cachedCatalog}};function b(e){return`${e.publisher}/${e.package_}/${e.name}`}function pn(e){return typeof e.source=="string"?!1:e.source.publisher==="kanonak.org"&&e.source.package_==="core-rdf"&&e.source.name==="Resource"}function gn(e){return e.publisher==="kanonak.org"&&e.package_==="core-rdf"&&e.name==="Resource"}function yn(e,n){let t=n.name;if(e.has(t))return t;for(let r of e)if(r.startsWith(t+"-")||r===t)return r}export{U as CssBackend,we as DEFAULT_VARIANT,m as DOCAST,Ue as DOCAST_PKG,$e as DOCAST_PUB,v as DynamoDbBackend,ce as ExpressionEngineV3,Sn as ExpressionEvalErrorV3,T as HtmlBackend,B as JsonBackend,j as MarkdownFrontmatterBackend,X as ReferenceResolver,p as RenderError,sn as SUPPORTED_FORMATS_V3,$ as SvgBackend,Dn as TX_V3,bn as TX_V3_PKG,kn as TX_V3_PUB,hn as TX_V3_VERSION_MAJOR,E as TomlBackend,re as TransformationEngine,Te as TransformationLoadErrorV3,h as TransformationRunnerErrorV3,C as TransformationRunnerV3,x as YamlBackend,wn as compileExpression,O as compileTransformationV3,An as isRawStringV3,Y as renderMarkdownToHtml};
91
+ `),o}};function ke(e,n){let t=new Map;for(let a of e.entries)t.set(a.key,a);let r=n?.metadataKeys??e.entries.map(a=>a.key),o={};for(let a of r){let s=t.get(a);if(!s)continue;let c=n?.metadataRenames.get(a)??a;o[c]=be(s.value,s.escapeHint)}return{M:o}}function be(e,n){switch(e.kind){case"StructuredMap":return ke(e);case"StructuredList":return{L:e.items.map(t=>be(t,void 0))};case"StringScalar":return on(e.stringValue,n??e.escapeHint);case"IntegerScalar":return an(e.integerValue,n??e.escapeHint)}}function on(e,n){if(n&&V(n,m.ESC_DYNAMODB_BOOL)){if(e==="true")return{BOOL:!0};if(e==="false")return{BOOL:!1};throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-bool must have the value "true" or "false"; got ${JSON.stringify(e)}.`)}if(n&&V(n,m.ESC_DYNAMODB_NULL))return{NULL:!0};if(n&&V(n,m.ESC_DYNAMODB_NUMBER)){if(e.trim()===""||Number.isNaN(Number(e)))throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-number must hold a numeric literal; got ${JSON.stringify(e)}.`);return{N:e}}return{S:e}}function an(e,n){if(n&&V(n,m.ESC_DYNAMODB_BOOL))throw new Error(`dynamodb-json backend: esc-dynamodb-bool cannot apply to an IntegerScalar (value ${e}). Use a StringScalar "true"/"false".`);if(n&&V(n,m.ESC_DYNAMODB_NULL))throw new Error(`dynamodb-json backend: esc-dynamodb-null cannot apply to an IntegerScalar (value ${e}). Use a StringScalar hinted esc-dynamodb-null.`);return{N:String(e)}}var sn={"markdown-with-frontmatter":{formatUri:"kanonak.org/transformations/markdown-with-frontmatter",extension:".md"},"plain-markdown":{formatUri:"kanonak.org/transformations/plain-markdown",extension:".md"},toml:{formatUri:"kanonak.org/transformations/toml",extension:".toml"},json:{formatUri:"kanonak.org/transformations/json",extension:".json"},html:{formatUri:"kanonak.org/transformations/html",extension:".html"},svg:{formatUri:"kanonak.org/transformations/svg",extension:".svg"},stylesheet:{formatUri:"kanonak.org/transformations/stylesheet",extension:".css"},yaml:{formatUri:"kanonak.org/transformations/yaml",extension:".yaml"},"dynamodb-json":{formatUri:"kanonak.org/transformations/dynamodb-json",extension:".json"}},h=class extends Error{},C=class{backends=new Map;constructor(){this.register(new j),this.register(new E),this.register(new B),this.register(new T),this.register(new $),this.register(new U),this.register(new x),this.register(new v)}register(n){this.backends.set(n.backendUri,n)}async run(n){let t=n.transformationKanonaks??n.allKanonaks,r=O(n.transformation,t);if(!r.outputs.has(n.outputFormat))throw new h(`Transformation "${r.name}" does not declare output format "${n.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let o=this.findBackend(n.outputFormat);if(!o)throw new h(`No backend registered for OutputFormat "${n.outputFormat}".`);let a=new X(n.repository,n.parser,n.objectParser),s=new ce(a,n.allKanonaks,r.fragments);return r.kind==="instance"?this.runInstance(r,n,o,s):this.runSet(r,n,o,s)}async runInstance(n,t,r,o){let a=he(t.instances,n.inputPattern.requires),s=De(a,n.inputPattern.sortBy),c=[];for(let u of s){let f=new Map;f.set("input",u);let l=await o.evaluate(n.rule,f);Z(l,n.name,`input "${u.name}"`);let d=ee(await o.evaluate(n.artifactName,f),n.name,`input "${u.name}"`),g=ne(n.overrides.get(t.outputFormat),t.runtimeOverride),k=r.render(l,g);c.push({fileName:d,format:t.outputFormat,content:k,source:{kind:"instance",sourceName:u.name}})}return c}async runSet(n,t,r,o){let a=he(t.instances,n.inputPattern.requires),s=De(a,n.inputPattern.sortBy);return n.partitionBy?this.runSetWithPartition(n,s,t,r,o):this.runSetSingle(n,s,t,r,o)}async runSetSingle(n,t,r,o,a){let s=new Map;s.set("inputs",t);let c=await a.evaluate(n.rule,s);Z(c,n.name,"set");let u=ee(await a.evaluate(n.artifactName,s),n.name,"set"),f=ne(n.overrides.get(r.outputFormat),r.runtimeOverride),l=o.render(c,f);return[{fileName:u,format:r.outputFormat,content:l,source:{kind:"set",memberCount:t.length}}]}async runSetWithPartition(n,t,r,o,a){let s=n.partitionBy,c=new Map,u=[];for(let l of t){let d=mn(l,s);if(d==null)continue;let g=dn(d),k=c.get(g);k||(k={keyValue:d,keyDisplay:fn(d),members:[]},c.set(g,k),u.push(g)),k.members.push(l)}let f=[];for(let l of u){let d=c.get(l),g=new Map;g.set("inputs",d.members),g.set("key",d.keyValue);let k=await a.evaluate(n.rule,g);Z(k,n.name,`partition "${d.keyDisplay}"`);let je=ee(await a.evaluate(n.artifactName,g),n.name,`partition "${d.keyDisplay}"`),Ee=ne(n.overrides.get(r.outputFormat),r.runtimeOverride),Be=o.render(k,Ee);f.push({fileName:je,format:r.outputFormat,content:Be,source:{kind:"set",memberCount:d.members.length,partitionKey:d.keyDisplay}})}return f}findBackend(n){let t=sn[n];if(t)return this.backends.get(t.formatUri)}};function he(e,n){return n.length===0?e:e.filter(t=>{for(let r of n)if(!un(t,r))return!1;return!0})}function De(e,n){if(n.length===0)return e;let t=[...e];return t.sort((r,o)=>{for(let a of n){let s=Ae(r,a.byProperty),c=Ae(o,a.byProperty),u=cn(s,c,a.order);if(u!==0)return u}return 0}),t}function Ae(e,n){for(let t of e.statement){let r=te(t);if(!(!r||!L(r,n))){if(t instanceof M||t instanceof P||t instanceof F)return t.object;if(t instanceof H)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(t instanceof W)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function cn(e,n,t){if(e===void 0&&n===void 0)return 0;if(e===void 0)return t==="ascending"?1:-1;if(n===void 0)return t==="ascending"?-1:1;let r;return typeof e=="number"&&typeof n=="number"?r=e-n:r=String(e).localeCompare(String(n)),t==="ascending"?r:-r}function un(e,n){for(let t of e.statement){let r=te(t);if(!r||!L(r,n))continue;let o=t.object;if(o!=null&&!(typeof o=="string"&&o.length===0)&&!(Array.isArray(o)&&o.length===0))return!0}return!1}function mn(e,n){for(let t of e.statement){let r=te(t);if(!(!r||!L(r,n))&&(t instanceof M||t instanceof P||t instanceof F||t instanceof W||t instanceof H))return t.object}}function te(e){return e.predicate?.subject}function dn(e){if(e===void 0)return" undef";if(e===null)return" null";if(typeof e=="string")return`s:${e}`;if(typeof e=="number")return`n:${e}`;if(typeof e=="boolean")return`b:${e}`;if(e instanceof K){let n=e.subject;return`r:${n.publisher}/${n.package_}/${n.name}`}if(e instanceof N){let n=e.name??"";return`k:${e.namespace??""}/${n}`}if(typeof e=="object"&&e!==null&&typeof e.name=="string"&&typeof e.publisher=="string"){let n=e;return`u:${n.publisher}/${n.package_}/${n.name}`}return`o:${JSON.stringify(e)}`}function fn(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e instanceof K?e.subject.name:e instanceof N?e.name??"":typeof e=="object"&&e!==null&&typeof e.name=="string"?e.name:""}function Z(e,n,t){if(typeof e!="object"||e===null||e.kind!=="Document")throw new h(`Transformation "${n}" rule did not yield a Document for ${t}. Got: ${Se(e)}`)}function ee(e,n,t){if(typeof e=="string")return e;if(Array.isArray(e)&&e.every(ln))return e.map(r=>String(r)).join("");throw new h(`Transformation "${n}" artifactName did not yield a string for ${t}. Got: ${Se(e)}`)}function ln(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Se(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"){let n=e.kind;return n?`object(kind=${n})`:"object"}return typeof e}function ne(e,n){if(!e&&!n)return;let t={metadataRenames:n?.metadataRenames??e?.metadataRenames??new Map},r=n?.metadataKeys??e?.metadataKeys;r!==void 0&&(t.metadataKeys=r);let o=n?.trailingNewline??e?.trailingNewline;o!==void 0&&(t.trailingNewline=o);let a=n?.omitWrapper??e?.omitWrapper;return a!==void 0&&(t.omitWrapper=a),t}var p=class extends Error{constructor(t,r){super(t);this.cause=r;this.name="RenderError"}cause},we={publisher:"kanonak.org",package_:"derivation",name:"default"},re=class{constructor(n,t=new ae,r=new ie){this.repository=n;this.parser=t;this.objectParser=r}repository;parser;objectParser;runner=new C;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async renderViaLook(n){let t=await this.getCatalog(),r=S(t,n.resource);if(!(r instanceof D))throw new p(`Resource not found: ${b(n.resource)}`);let o=new q(t),a;if(n.format.name==="html")a=await o.renderHtml(r);else if(n.format.name==="stylesheet")a=o.renderStylesheet(r);else throw new p(`LookRenderer does not support format ${b(n.format)} \u2014 only formats.html and formats.stylesheet are implemented in v0.1.`);return{content:a,format:n.format,filename:r.name}}async findDerivation(n){let t=await this.getCatalog(),r=S(t,n.resource);if(!(r instanceof D))return;let o=n.variant??we;return se(r,n.format,o,t)}async render(n){if(n.format.name==="html"||n.format.name==="stylesheet"){let a=await this.getCatalog(),s=S(a,n.resource);if(s instanceof D){let u=new q(a).findCascadedLook(s);if(u&&!gn(u.sourceClass)){let f=await this.findDerivation(n);if(!f||pn(f))return this.renderViaLook({resource:n.resource,format:n.format})}}}let t=await this.findDerivation(n);if(!t)throw new p(`No derivation found for ${b(n.resource)} \u2192 format ${b(n.format)}`+(n.variant?` variant ${b(n.variant)}`:""));let r=oe(t.transformation.version),o={transformation:{publisher:t.transformation.publisher,package_:t.transformation.package_,name:t.transformation.name,...r?{version:r}:{}},input:n.resource,format:n.format};return n.omitWrapper!==void 0&&(o.omitWrapper=n.omitWrapper),this.runTransformation(o)}async runTransformation(n){let t=await this.getCatalog(),r=S(t,n.transformation);if(!(r instanceof D))throw new p(`Transformation not found: ${b(n.transformation)}`);let o=S(t,n.input);if(!(o instanceof D))throw new p(`Input resource not found: ${b(n.input)}`);let a=O(r,t),s=yn(a.outputs,n.format);if(!s)throw new p(`Transformation ${b(n.transformation)} declares outputs [${[...a.outputs].join(", ")}], none of which corresponds to format ${b(n.format)}`);let c;try{c=await this.runner.run({transformation:r,instances:[o],allKanonaks:t,repository:this.repository,parser:this.parser,objectParser:this.objectParser,outputFormat:s,...n.omitWrapper!==void 0?{runtimeOverride:{metadataRenames:new Map,omitWrapper:n.omitWrapper}}:{}})}catch(u){throw new p(`Transformation execution failed: ${u.message}`,u)}if(c.length===0)throw new p("Transformation produced no artifacts");return{content:c[0].content,format:n.format,filename:c[0].fileName}}async getCatalog(){return this.cachedCatalog||(this.cachedCatalog=await this.objectParser.parseKanonaks(this.repository)),this.cachedCatalog}};function b(e){return`${e.publisher}/${e.package_}/${e.name}`}function pn(e){return typeof e.source=="string"?!1:e.source.publisher==="kanonak.org"&&e.source.package_==="core-rdf"&&e.source.name==="Resource"}function gn(e){return e.publisher==="kanonak.org"&&e.package_==="core-rdf"&&e.name==="Resource"}function yn(e,n){let t=n.name;if(e.has(t))return t;for(let r of e)if(r.startsWith(t+"-")||r===t)return r}export{U as CssBackend,we as DEFAULT_VARIANT,m as DOCAST,Ue as DOCAST_PKG,$e as DOCAST_PUB,v as DynamoDbBackend,ce as ExpressionEngineV3,Sn as ExpressionEvalErrorV3,T as HtmlBackend,B as JsonBackend,j as MarkdownFrontmatterBackend,X as ReferenceResolver,p as RenderError,sn as SUPPORTED_FORMATS_V3,$ as SvgBackend,Dn as TX_V3,bn as TX_V3_PKG,kn as TX_V3_PUB,hn as TX_V3_VERSION_MAJOR,E as TomlBackend,re as TransformationEngine,Te as TransformationLoadErrorV3,h as TransformationRunnerErrorV3,C as TransformationRunnerV3,x as YamlBackend,wn as compileExpression,O as compileTransformationV3,An as isRawStringV3,Y as renderMarkdownToHtml};
@@ -1 +1 @@
1
- import{A,B,C,D,E,F,G,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-RRODBYIK.js";import"../chunk-SHDHMKMJ.js";import"../chunk-G2DKKSZ4.js";import"../chunk-TJPQETHV.js";import"../chunk-BGQKZBNE.js";import"../chunk-CRKSKIAL.js";import"../chunk-IOMNZBK4.js";import"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{v as AmbiguousReferenceRule,B as ClassDefinitionRule,m as ClassHierarchyCycleRule,t as DefinitionPropertyReferenceRule,D as DisplayLensScopeRule,j as EmbeddedKanonakTypeRule,k as ImportExistenceRule,s as InstancePropertyReferenceRule,G as KanonakObjectValidator,E as LookSemanticSvgPathRule,C as MarkdownLinkRule,r as NamespaceImportCycleRule,f as NamespacePrefixRule,x as ObjectPropertyImportRule,y as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,z as PropertyDomainRule,n as PropertyHierarchyCycleRule,w as PropertyRangeReferenceRule,o as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,A as PropertyValueTypeRule,g as ResourceNamingRule,p as SubClassOfReferenceRule,q as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,F as TxExpressionPathRule,l as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,u as XsdImportRule};
1
+ import{A,B,C,D,E,F,G,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-C7RZIMEH.js";import"../chunk-SHDHMKMJ.js";import"../chunk-G2DKKSZ4.js";import"../chunk-TJPQETHV.js";import"../chunk-BGQKZBNE.js";import"../chunk-CRKSKIAL.js";import"../chunk-IOMNZBK4.js";import"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{v as AmbiguousReferenceRule,B as ClassDefinitionRule,m as ClassHierarchyCycleRule,t as DefinitionPropertyReferenceRule,D as DisplayLensScopeRule,j as EmbeddedKanonakTypeRule,k as ImportExistenceRule,s as InstancePropertyReferenceRule,G as KanonakObjectValidator,E as LookSemanticSvgPathRule,C as MarkdownLinkRule,r as NamespaceImportCycleRule,f as NamespacePrefixRule,x as ObjectPropertyImportRule,y as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,z as PropertyDomainRule,n as PropertyHierarchyCycleRule,w as PropertyRangeReferenceRule,o as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,A as PropertyValueTypeRule,g as ResourceNamingRule,p as SubClassOfReferenceRule,q as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,F as TxExpressionPathRule,l as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,u as XsdImportRule};
@@ -0,0 +1,38 @@
1
+ import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
2
+ import type { KanonakDocument } from '@kanonak-protocol/types/document/models/types';
3
+ import { OntologyValidationError } from '../../OntologyValidationError.js';
4
+ import type { IRepositoryValidationRule } from './IRepositoryValidationRule.js';
5
+ import type { ValidationCache } from '../../ValidationCache.js';
6
+ /**
7
+ * Validates that `tx.PropertyRead` / `tx.Traverse` steps inside a look
8
+ * band's path carriers (`metricPath`, `statPath`, `mapPath`, `labelPath`,
9
+ * …) reference properties in scope for the class context that carrier is
10
+ * evaluated against. As of look@2.0.0 these carriers are `tx.Expression`s
11
+ * rather than `/`-separated path strings, so each property reference
12
+ * resolves through the object model — this rule additionally checks the
13
+ * DOMAIN of each read so a path that resolves but reads an inapplicable
14
+ * property is reported rather than silently rendering empty.
15
+ *
16
+ * The context depends on the band: instance-level carriers (Distribution,
17
+ * StatRow, VersionDelta) evaluate against the page instance — the class
18
+ * the `derivation.look` is declared on. Sub-resource carriers evaluate
19
+ * against the nodes reached through a sibling property: Timeline /
20
+ * VersionDiff through `track`, TimePlot through `source`, ReferenceList
21
+ * through each `entries` property, Diagram facets through `relation`.
22
+ *
23
+ * The path walk is the shared, context-advancing `checkTxExpressionPaths`
24
+ * — the same engine behind `LookSemanticSvgPathRule` and
25
+ * `TxExpressionPathRule`. This rule supplies the band-specific root
26
+ * context and diagnostic wording. (The generalized chain walker tracked in
27
+ * typescript#48.)
28
+ */
29
+ export declare class LookBandPathRule implements IRepositoryValidationRule {
30
+ readonly ruleName = "LookBandPath";
31
+ validateAsync(document: KanonakDocument, repository: IKanonakDocumentRepository, cache?: ValidationCache): Promise<OntologyValidationError[]>;
32
+ private checkDeclaration;
33
+ /** Enumerate the carrier expressions of one band with their class context. */
34
+ private carriersOf;
35
+ /** The declared range of the property `propUri` resolved against `context`. */
36
+ private rangeOf;
37
+ private toError;
38
+ }
@@ -21,4 +21,5 @@ export { EmbeddedKanonakTypeRule } from './EmbeddedKanonakTypeRule.js';
21
21
  export { MarkdownLinkRule } from './MarkdownLinkRule.js';
22
22
  export { DisplayLensScopeRule } from './DisplayLensScopeRule.js';
23
23
  export { LookSemanticSvgPathRule } from './LookSemanticSvgPathRule.js';
24
+ export { LookBandPathRule } from './LookBandPathRule.js';
24
25
  export { TxExpressionPathRule } from './TxExpressionPathRule.js';
@@ -52,6 +52,7 @@ export declare class ViewMaterializer {
52
52
  private readonly repository;
53
53
  private readonly parser;
54
54
  private readonly objectParser;
55
+ private readonly builder;
55
56
  constructor(repository: IKanonakDocumentRepository, parser?: KanonakParser);
56
57
  materialize(viewRef: EntityUri, opts?: MaterializeOptions): Promise<MaterializeResult>;
57
58
  private resolveView;
@@ -61,11 +62,4 @@ export declare class ViewMaterializer {
61
62
  private passesWhere;
62
63
  private evaluateValue;
63
64
  private rowName;
64
- /**
65
- * Content hash of the body, independent of the EphemeralPackage's own
66
- * (not-yet-assigned) name. Parses the rows under a fixed probe header,
67
- * neutralizes each body subject's namespace to a constant, and hashes —
68
- * so the same projected data always yields the same `sha256:`.
69
- */
70
- private hashBody;
71
65
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "3.71.0",
3
+ "version": "3.73.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",
@@ -122,7 +122,7 @@
122
122
  "yaml-parser"
123
123
  ],
124
124
  "dependencies": {
125
- "@kanonak-protocol/types": "^3.71.0",
125
+ "@kanonak-protocol/types": "^3.73.0",
126
126
  "ignore": "^7.0.5",
127
127
  "js-yaml": "^4.1.0",
128
128
  "yaml": "^2.7.0"
@@ -1,2 +0,0 @@
1
- import{a as f}from"./chunk-SC5M74NM.js";import{a as d}from"./chunk-TJPQETHV.js";var k="https://{publisher}/index.txt",x="https://{publisher}/{package}/{version}.kan.yml",v={version:1};function F(a){return{version:1,index:k.replaceAll("{publisher}",a),package:x.replaceAll("{publisher}",a),auth:"none"}}var h=class{cache=new Map;getConfig(n){let e=this.cache.get(n);return e||(e=this.fetchConfig(n),this.cache.set(n,e),e.catch(()=>{this.cache.get(n)===e&&this.cache.delete(n)})),e}async fetchConfig(n){let e=`https://${n}/.well-known/kanonak.json`,r;try{r=await fetch(e)}catch{return v}if(r.status===404)return v;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${e} (${r.status} ${r.statusText})`);let t=await r.json();if(typeof t.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let s={version:t.version};return typeof t.index=="string"&&(s.index=t.index),typeof t.package=="string"&&(s.package=t.package),(t.auth==="none"||t.auth==="oauth"||t.auth==="bearer")&&(s.auth=t.auth),Array.isArray(t.render)&&t.render.every(i=>typeof i=="string")&&(s.render=t.render),s}resolveIndexUrl(n,e){let r=e.index??k;return y(r,{publisher:n})}resolvePackageUrl(n,e,r,t){let s=t.package??x;return y(s,{publisher:n,package:e,version:r})}};function y(a,n){let e=a;for(let[t,s]of Object.entries(n))e=e.replaceAll(`{${t}}`,s);let r=e.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${a}`);return e}import{VersionOperator as l}from"@kanonak-protocol/types/document/models/enums";var g=class a{indexCache=new Map;configResolver;fetchFn;constructor(n){this.configResolver=n?.configResolver??new h,this.fetchFn=n?.fetchFn}async resolveVersion(n,e){let r=await this.getPackageVersions(n,e.packageName);if(r.length===0)return null;let t=r.filter(s=>this.isVersionCompatible(s,e.version,e.versionOperator));return t.length===0?null:(t.sort((s,i)=>this.compareVersionStrings(i,s)),t[0])}async getHighestVersion(n,e){let r=await this.getPackageVersions(n,e);return r.length===0?null:[...r].sort((s,i)=>this.compareVersionStrings(i,s))[0]}async listLatestPackages(n){let e=await this.getIndex(n),r=[];for(let[t,s]of e){if(s.length===0)continue;let i=[...s].sort((o,c)=>this.compareVersionStrings(c,o));r.push({packageName:t,version:i[0]})}return r.sort((t,s)=>t.packageName.localeCompare(s.packageName)),r}async getPackageUrl(n,e,r){let t=await this.configResolver.getConfig(n);return this.configResolver.resolvePackageUrl(n,e,r,t)}async getPackageVersions(n,e){return(await this.getIndex(n)).get(e)??[]}getIndex(n){let e=this.indexCache.get(n);return e||(e=this.fetchIndex(n),this.indexCache.set(n,e),e.catch(()=>{this.indexCache.get(n)===e&&this.indexCache.delete(n)})),e}async fetchIndex(n){let e=await this.configResolver.getConfig(n),r=this.configResolver.resolveIndexUrl(n,e),t=this.fetchFn?await this.fetchFn(r,n):await fetch(r);if(!t.ok)throw new Error(`Failed to fetch publisher index: ${r} (${t.status} ${t.statusText})`);let s=await t.text();return a.parseIndex(s)}static parseIndex(n){let e=new Map;for(let r of n.split(`
2
- `)){let t=r.trim();if(!t||t.startsWith("#"))continue;let s=t.indexOf("/");if(s===-1)continue;let i=t.substring(0,s),o=t.substring(s+1);if(!i||!o)continue;let c=e.get(i);c?c.push(o):e.set(i,[o])}return e}isVersionCompatible(n,e,r){let t=a.parseVersion(n);if(!t)return!1;switch(r){case l.Any:return!0;case l.Exact:return t.major===e.major&&t.minor===e.minor&&t.patch===e.patch;case l.Compatible:return t.major===e.major&&t.minor===e.minor&&t.patch>=e.patch;case l.Major:return t.major!==e.major?!1:t.minor>e.minor?!0:t.minor===e.minor?t.patch>=e.patch:!1;default:return!1}}static parseVersion(n){let e=n.split(".");if(e.length<2)return null;let r=parseInt(e[0],10),t=parseInt(e[1],10),s=e.length>=3?parseInt(e[2],10):0;return isNaN(r)||isNaN(t)||isNaN(s)?null:{major:r,minor:t,patch:s}}compareVersionStrings(n,e){let r=a.parseVersion(n),t=a.parseVersion(e);return!r&&!t?0:r?t?r.major!==t.major?r.major-t.major:r.minor!==t.minor?r.minor-t.minor:r.patch-t.patch:1:-1}};var P=class{parser=new d;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(n){this.onFetch=n?.onFetch,this.getFromCache=n?.getFromCache,this.fetchFn=n?.fetchFn,this.publisherIndex=n?.fetchFn?new g({fetchFn:n.fetchFn}):new g}async getHighestCompatibleVersionAsync(n,e){let r=await this.publisherIndex.resolveVersion(n,e);if(!r)return null;let t=`${n}/${e.packageName}@${r}`,s=this.documents.get(t);if(s)return s;if(this.getFromCache){let m=this.getFromCache(n,e.packageName,r);if(m){let p=this.parser.parse(m);return f(p,n,e.packageName,r),this.documents.set(t,p),this.contentCache.set(t,m),p}}let i=await this.publisherIndex.getPackageUrl(n,e.packageName,r),o=this.fetchFn?await this.fetchFn(i,n):await fetch(i);if(!o.ok)throw new Error(`Failed to fetch Kanonak package: ${i} (${o.status} ${o.statusText})`);let c=await o.text(),u=this.parser.parse(c);return f(u,n,e.packageName,r),this.onFetch&&this.onFetch(n,e.packageName,r,c),this.documents.set(t,u),this.contentCache.set(t,c),u}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(n){return this.documents.get(n)??null}async getDocumentsByNamespaceAsync(n,e){return Array.from(this.documents.values()).filter(r=>{let t=r.metadata.namespace_;return t&&t.publisher===n&&t.package_===e})}async saveDocumentAsync(n,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(n){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(n,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(n){return this.contentCache.get(n)??null}async getDocumentUriAsync(n){let e=n.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,r,t,s]=e;return this.publisherIndex.getPackageUrl(r,t,s)}};export{F as a,h as b,g as c,P as d};