@kanonak-protocol/sdk 3.45.0 → 3.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as ge,b as fe,c as me,d as C,e as E,f as d}from"./chunk-RCI34BYO.js";import{a as Qe}from"./chunk-BFZZ6YGX.js";import{a as H,b as L,c as W,d as F}from"./chunk-VHUJSHH7.js";import{a as Pe,b as we,c as he}from"./chunk-NIJV5UYW.js";import{a as ye,b as ke,e as be}from"./chunk-4TJZIM7A.js";import"./chunk-NIGFQYVA.js";import{A as We,B as Fe,C as Ge,D as Xe,a as Ke,b as xe,c as Se,d as Re,f as De,g as Be,h as Ce,i as Ee,j as je,k as ve,l as _e,m as Ie,n as Ae,o as Te,p as Oe,q as Ve,r as $e,s as Ue,t as ze,u as Me,v as Ne,w as Je,x as He,y as qe,z as Le}from"./chunk-SKTXJV4T.js";import"./chunk-FJ35VIV6.js";import{a as Y,c as le,f as pe}from"./chunk-FMYLEPMC.js";import{a as G,b as X,c as Q,d as ee,e as re,f as te,g as ne,h as oe,i as se,j as ie,k as ae,l as ce}from"./chunk-W6T7MOKY.js";import{a as q}from"./chunk-7CUTGGH3.js";import{a as O,b as V,c as $,d as U,e as z,f as M,g as N,h as J}from"./chunk-FQHALFRR.js";import{b as ue,c as de}from"./chunk-HEMBMX7T.js";import{a as Z}from"./chunk-FUUTGGJS.js";var j="kanonak-credentials",u="credentials",Ye=1,f=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,Ye);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
1
+ import{a as ge,b as fe,c as me,d as C,e as E,f as d}from"./chunk-RCI34BYO.js";import{a as Qe}from"./chunk-JGVDV6PM.js";import{a as H,b as L,c as W,d as F}from"./chunk-VHUJSHH7.js";import{a as Pe,b as we,c as he}from"./chunk-NIJV5UYW.js";import{a as ye,b as ke,e as be}from"./chunk-4TJZIM7A.js";import"./chunk-NIGFQYVA.js";import{A as We,B as Fe,C as Ge,D as Xe,a as Ke,b as xe,c as Se,d as Re,f as De,g as Be,h as Ce,i as Ee,j as je,k as ve,l as _e,m as Ie,n as Ae,o as Te,p as Oe,q as Ve,r as $e,s as Ue,t as ze,u as Me,v as Ne,w as Je,x as He,y as qe,z as Le}from"./chunk-SKTXJV4T.js";import"./chunk-FJ35VIV6.js";import{a as Y,c as le,f as pe}from"./chunk-FMYLEPMC.js";import{a as G,b as X,c as Q,d as ee,e as re,f as te,g as ne,h as oe,i as se,j as ie,k as ae,l as ce}from"./chunk-W6T7MOKY.js";import{a as q}from"./chunk-7CUTGGH3.js";import{a as O,b as V,c as $,d as U,e as z,f as M,g as N,h as J}from"./chunk-FQHALFRR.js";import{b as ue,c as de}from"./chunk-HEMBMX7T.js";import{a as Z}from"./chunk-FUUTGGJS.js";var j="kanonak-credentials",u="credentials",Ye=1,f=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,Ye);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
2
2
  Credential storage requires IndexedDB support in your browser.`))})}async function _(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey);return{signingKey:n.privateKey,publicKeyJwk:r}}async function k(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey),e=await crypto.subtle.exportKey("jwk",n.privateKey);return{keys:{signingKey:n.privateKey,publicKeyJwk:r},dpopKeyPair:{publicKey:r,privateKey:e}}}async function b(n){return{signingKey:await crypto.subtle.importKey("jwk",n.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:n.publicKey}}async function K(n,r,e,t,o){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:n.publicKeyJwk.kty,crv:n.publicKeyJwk.crv,x:n.publicKeyJwk.x,y:n.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:r.toUpperCase(),htu:e,iat:Math.floor(Date.now()/1e3)};return t&&(s.ath=await er(t)),o&&(s.nonce=o),await Ze(a,s,n.signingKey)}function x(n){return!n||n.length===0?!1:n.some(r=>r.toUpperCase()==="ES256")}async function Ze(n,r,e){let t=v(JSON.stringify(n)),o=v(JSON.stringify(r)),a=new TextEncoder().encode(`${t}.${o}`),s=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,a),l=D(s);return`${t}.${o}.${l}`}async function er(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return D(e)}function v(n){let r=new TextEncoder().encode(n);return D(r.buffer)}function D(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var rr=300*1e3,S=class{credentialBackend;callbackUrl;constructor(r){this.credentialBackend=new f,this.callbackUrl=r??`${window.location.origin}/browser/callback.html`}async authorize(r){let e=d(r),t=await this.discover(e);if(!t)return{success:!1,error:`No OAuth discovery endpoint found for '${e}'.`};if(!t.authorizationEndpoint||!t.tokenEndpoint)return{success:!1,error:`OAuth metadata incomplete for '${e}'.`};let o=x(t.dpopSigningAlgValuesSupported),a=null,s=null;if(o){let g=await k();a=g.keys,s=g.dpopKeyPair}let l=await this.credentialBackend.get(e),i=l?.clientId??null,c=l?.clientSecret??null;if(!i&&t.registrationEndpoint){let g=await this.registerClient(t.registrationEndpoint);if(!g)return{success:!1,error:`Dynamic client registration failed for '${e}'.`};i=g.clientId,c=g.clientSecret??null}if(!i)return{success:!1,error:`No OAuth client credentials for '${e}'.`};let m=tr(),p=await nr(m),R=or(),A=sr(t.authorizationEndpoint,i,this.callbackUrl,R,p),y=await this.openAuthPopup(A,R);if(!y)return{success:!1,error:"Authorization timed out or was cancelled."};if(y.error)return{success:!1,error:`Authorization failed: ${y.error}`};if(!y.code)return{success:!1,error:"No authorization code received."};if(y.state!==R)return{success:!1,error:"State mismatch \u2014 possible CSRF attack."};let P=await this.exchangeCode(t.tokenEndpoint,i,c,y.code,this.callbackUrl,m,a);if(!P)return{success:!1,error:"Token exchange failed."};let T={clientId:i,clientSecret:c,accessToken:P.accessToken??null,refreshToken:P.refreshToken??null,expiresAt:P.expiresIn?new Date(Date.now()+P.expiresIn*1e3).toISOString():null,tokenEndpoint:t.tokenEndpoint,dpopKeyPair:s};return await this.credentialBackend.store(e,T),{success:!0,host:e}}async getCredentialWithKeys(r){let e=await this.credentialBackend.get(r);if(!e)return null;let t=null;return e.dpopKeyPair&&(t=await b(e.dpopKeyPair)),{credential:e,dpopKeys:t}}async logout(r){let e=d(r);return await this.credentialBackend.remove(e),{success:!0,host:e}}async listAuthenticated(){return this.credentialBackend.list()}async discover(r){for(let e of[`https://${r}/.well-known/oauth-authorization-server`,`https://${r}/.well-known/openid-configuration`])try{let t=await fetch(e);if(!t.ok)continue;let o=await t.json();return{issuer:w(o.issuer),authorizationEndpoint:w(o.authorization_endpoint),tokenEndpoint:w(o.token_endpoint),registrationEndpoint:w(o.registration_endpoint),revocationEndpoint:w(o.revocation_endpoint),dpopSigningAlgValuesSupported:I(o.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:I(o.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(r){try{let e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak Browser",redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})});if(!e.ok)return null;let t=await e.json(),o=t.client_id;return o?{clientId:o,clientSecret:t.client_secret}:null}catch{return null}}openAuthPopup(r,e){return new Promise(t=>{let o=window.open(r,"kanonak-auth","width=500,height=700,menubar=no,toolbar=no,location=yes,status=no");if(!o){t(null);return}let a=setTimeout(()=>{i(),t(null)},rr),s=c=>{c.origin===window.location.origin&&(!c.data||c.data.type!=="kanonak-auth-callback"||(i(),t({code:c.data.code??void 0,state:c.data.state??void 0,error:c.data.error??void 0})))},l=setInterval(()=>{o.closed&&(i(),t(null))},500),i=()=>{clearTimeout(a),clearInterval(l),window.removeEventListener("message",s);try{o.close()}catch{}};window.addEventListener("message",s)})}async exchangeCode(r,e,t,o,a,s,l){let i=new URLSearchParams({grant_type:"authorization_code",client_id:e,code:o,redirect_uri:a,code_verifier:s});t&&i.set("client_secret",t);let c={"Content-Type":"application/x-www-form-urlencoded"};l&&(c.DPoP=await K(l,"POST",r));try{let m=await fetch(r,{method:"POST",headers:c,body:i.toString()});if(!m.ok)return null;let p=await m.json();return{accessToken:p.access_token,refreshToken:p.refresh_token,expiresIn:typeof p.expires_in=="number"?p.expires_in:void 0}}catch{return null}}};function tr(){let n=new Uint8Array(32);return crypto.getRandomValues(n),B(n.buffer)}async function nr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return B(e)}function or(){let n=new Uint8Array(16);return crypto.getRandomValues(n),B(n.buffer)}function sr(n,r,e,t,o){let a=new URLSearchParams({client_id:r,response_type:"code",redirect_uri:e,state:t,code_challenge:o,code_challenge_method:"S256"});return`${n}?${a}`}function B(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(n){return typeof n=="string"?n:null}function I(n){return Array.isArray(n)?n.filter(r=>typeof r=="string"):null}export{Ne as AmbiguousReferenceRule,se as BooleanStatement,f as BrowserCredentialBackend,S as BrowserOAuthFlow,Fe as ClassDefinitionRule,Ie as ClassHierarchyCycleRule,X as DefinedKanonak,ze as DefinitionPropertyReferenceRule,fe as EdgeType,Y as EmbeddedKanonak,je as EmbeddedKanonakTypeRule,ae as EmbeddedStatement,me as GraphBuilder,F as HttpKanonakDocumentRepository,ve as ImportExistenceRule,H as InMemoryKanonakDocumentRepository,Ue as InstancePropertyReferenceRule,G as Kanonak,we as KanonakDocumentPositions,pe as KanonakObjectParser,Xe as KanonakObjectValidator,q as KanonakParser,Z as KanonakUri,ke as KanonakUriBuilder,ce as ListStatement,Ge as MarkdownLinkRule,le as MarkdownStatement,$e as NamespaceImportCycleRule,De as NamespacePrefixRule,ge as NodeType,oe as NumberStatement,He as ObjectPropertyImportRule,qe as ObjectPropertyValueValidationRule,Se as OntologyValidationError,Ke as OntologyValidationResult,Le as PropertyDomainRule,Ae as PropertyHierarchyCycleRule,Pe as PropertyMetadata,Je as PropertyRangeReferenceRule,Te as PropertyRangeRequiredRule,Ce as PropertyTypeSpecificityRule,We as PropertyValueTypeRule,L as PublisherConfigResolver,W as PublisherIndex,ee as ReferenceKanonak,ie as ReferenceStatement,Be as ResourceNamingRule,ue as ResourceResolver,ye as ResourceTypeClassifier,te as ScalarStatement,re as Statement,ne as StringStatement,Oe as SubClassOfReferenceRule,Ve as SubPropertyOfReferenceRule,Q as SubjectKanonak,Ee as SubjectKanonakTypeRequiredRule,de as TypeResolver,_e as UnresolvedReferenceRule,Re as ValidationContext,xe as ValidationSeverity,Me as XsdImportRule,x as browserServerSupportsDPoP,O as compareVersions,K as createBrowserDPoPProof,U as createVersion,Qe as findDerivation,be as findInstancesByType,$ as formatVersion,k as generateBrowserDPoPKeyPair,_ as generateBrowserDPoPKeys,E as hasValidToken,b as importDPoPKeys,M as isCompatibleVersion,C as isExpired,N as isMajorCompatible,d as normalizeHost,z as parseVersionString,he as parseWithPositions,J as pickHighestDocument,V as versionsEqual};
@@ -0,0 +1 @@
1
+ import{a as g}from"./chunk-FMYLEPMC.js";import{c as l,d as u,g as v,j as p,k as h,l as d}from"./chunk-W6T7MOKY.js";import{a as K,e as b}from"./chunk-FQHALFRR.js";function pe(t,n,e,i){let r=S(t);if(r.length>0){let s=j(r,n,e);return s?{transformation:s.transformation,source:"instance"}:void 0}let a=new Set,o=I(t);for(;o.length>0;){let s=o.shift(),c=x(s.subject);if(a.has(c))continue;a.add(c);let m=R(i,s.subject);if(!m)continue;let _=S(m),D=j(_,n,e);if(D)return{transformation:D.transformation,source:{publisher:s.subject.publisher,package_:s.subject.package_,name:s.subject.name}};for(let U of L(m))o.push(U)}let f={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"};if(!a.has(x(f))){let s=R(i,f);if(s){let c=S(s),m=j(c,n,e);if(m)return{transformation:m.transformation,source:f}}}}function S(t){let n=[];for(let e of t.statement)if(e instanceof d&&k(e,"kanonak.org","derivation","derivations"))for(let i of e.object??[]){if(!(i instanceof g))continue;let r=T(i);r&&n.push(r)}return n}function j(t,n,e){let i=t.filter(o=>E(o.format,n)&&E(o.variant,e));if(i.length<=1)return i[0];let r=i[0].transformation,a=i[0];for(let o of i){let f=o.transformation;if(f.publisher!==r.publisher||f.package_!==r.package_||f.name!==r.name)continue;let s=b(a.transformation.version),c=b(f.version);s&&c&&K(c,s)>0&&(a=o)}return a}function T(t){let n,e,i;for(let r of t.statement)r instanceof p?k(r,"kanonak.org","derivation","format")?n=y(r):k(r,"kanonak.org","derivation","variant")&&(e=y(r)):r instanceof h&&k(r,"kanonak.org","derivation","transformation")&&(i=P(r.object));if(!(!n||!i))return e||(e={publisher:"kanonak.org",package_:"derivation",name:"default"}),{format:n,variant:e,transformation:i}}function P(t){let n,e,i,r;for(let a of t.statement){if(!(a instanceof v))continue;let o=a.predicate?.subject?.name;o==="publisher"?n=a.object:o==="package"?e=a.object:o==="version"?i=a.object:o==="name"&&(r=a.object)}if(!(!n||!e||!i||!r))return{publisher:n,package_:e,version:i,name:r}}function I(t){let n=[];for(let e of t.statement)e instanceof p&&e.predicate?.subject?.name==="type"&&e.object instanceof u&&n.push(e.object);return n}function L(t){let n=[];for(let e of t.statement)if(e instanceof p){if(e.predicate?.subject?.name!=="subClassOf")continue;e.object instanceof u&&n.push(e.object)}else if(e instanceof d){if(e.predicate?.subject?.name!=="subClassOf")continue;for(let i of e.object??[])i instanceof u&&n.push(i)}return n}function R(t,n){for(let e of t){if(!(e instanceof l)||e.name!==n.name)continue;if((e.namespace||"").startsWith(`${n.publisher}/${n.package_}@`))return e}}function k(t,n,e,i){let r=t.predicate?.subject;return r?r.publisher===n&&r.package_===e&&r.name===i:!1}function y(t){let n=t.object.subject;return{publisher:n.publisher,package_:n.package_,name:n.name}}function E(t,n){return t.publisher===n.publisher&&t.package_===n.package_&&t.name===n.name}function x(t){return`${t.publisher}/${t.package_}/${t.name}`}export{pe as a};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as et,b as tt,c as rt,d as nt,e as ot,f as at,g as it,h as st,i as ct,j as lt}from"./chunk-IOJMTW4T.js";import{b as Xt}from"./chunk-VBTBY53W.js";import{a as Xe,b as Ze,c as Qe,d as b,e as S,f as i}from"./chunk-RCI34BYO.js";import{a as Yt}from"./chunk-BFZZ6YGX.js";import{a as Te,b as je,c as Le,d as Fe,e as Ne}from"./chunk-5AH6GIPO.js";import{a as Be,b as De,c as Oe,d as Ae}from"./chunk-VHUJSHH7.js";import{a as ut,b as pt,c as mt,d as ft}from"./chunk-NIJV5UYW.js";import{a as Ye,b as yt,c as gt,d as ht,e as bt}from"./chunk-4TJZIM7A.js";import{a as kt}from"./chunk-NIGFQYVA.js";import{A as Gt,B as Wt,C as Jt,D as qt,a as St,b as Ct,c as Pt,d as Rt,e as wt,f as xt,g as $t,h as vt,i as Et,j as Kt,k as Bt,l as It,m as Tt,n as jt,o as Lt,p as Ft,q as Nt,r as Dt,s as Ot,t as At,u as Ut,v as Mt,w as Vt,x as Ht,y as _t,z as zt}from"./chunk-SKTXJV4T.js";import"./chunk-FJ35VIV6.js";import{a as F,b as D,c as _e,d as We,e as Je,f as qe}from"./chunk-FMYLEPMC.js";import{a as Ue,b as j,c as L,d as N,e as Ve,f as He,g as O,h as A,i as U,j as M,k as V,l as H}from"./chunk-W6T7MOKY.js";import{a as Ie}from"./chunk-7CUTGGH3.js";import{a as Pe,b as Re,c as we,d as xe,e as $e,f as ve,g as Ee,h as Ke}from"./chunk-FQHALFRR.js";import{b as ze,c as Ge}from"./chunk-HEMBMX7T.js";import{a as Me}from"./chunk-FUUTGGJS.js";import{a as dt}from"./chunk-ODIECDN7.js";import{VersionOperator as io}from"@kanonak-protocol/types/document/models/enums";import{existsSync as yr,readFileSync as gr}from"fs";import{homedir as hr}from"os";import{join as kr}from"path";import{execFile as Zt}from"child_process";import{promisify as Qt}from"util";var C=Qt(Zt),P="kanonak",R="/usr/bin/security",p=class{async get(e){let r=i(e);try{let{stdout:n}=await C(R,["find-generic-password","-s",P,"-a",r,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${r}' is corrupted (not valid JSON).
1
+ import{a as et,b as tt,c as rt,d as nt,e as ot,f as at,g as it,h as st,i as ct,j as lt}from"./chunk-IOJMTW4T.js";import{b as Xt}from"./chunk-VBTBY53W.js";import{a as Xe,b as Ze,c as Qe,d as b,e as S,f as i}from"./chunk-RCI34BYO.js";import{a as Yt}from"./chunk-JGVDV6PM.js";import{a as Te,b as je,c as Le,d as Fe,e as Ne}from"./chunk-5AH6GIPO.js";import{a as Be,b as De,c as Oe,d as Ae}from"./chunk-VHUJSHH7.js";import{a as ut,b as pt,c as mt,d as ft}from"./chunk-NIJV5UYW.js";import{a as Ye,b as yt,c as gt,d as ht,e as bt}from"./chunk-4TJZIM7A.js";import{a as kt}from"./chunk-NIGFQYVA.js";import{A as Gt,B as Wt,C as Jt,D as qt,a as St,b as Ct,c as Pt,d as Rt,e as wt,f as xt,g as $t,h as vt,i as Et,j as Kt,k as Bt,l as It,m as Tt,n as jt,o as Lt,p as Ft,q as Nt,r as Dt,s as Ot,t as At,u as Ut,v as Mt,w as Vt,x as Ht,y as _t,z as zt}from"./chunk-SKTXJV4T.js";import"./chunk-FJ35VIV6.js";import{a as F,b as D,c as _e,d as We,e as Je,f as qe}from"./chunk-FMYLEPMC.js";import{a as Ue,b as j,c as L,d as N,e as Ve,f as He,g as O,h as A,i as U,j as M,k as V,l as H}from"./chunk-W6T7MOKY.js";import{a as Ie}from"./chunk-7CUTGGH3.js";import{a as Pe,b as Re,c as we,d as xe,e as $e,f as ve,g as Ee,h as Ke}from"./chunk-FQHALFRR.js";import{b as ze,c as Ge}from"./chunk-HEMBMX7T.js";import{a as Me}from"./chunk-FUUTGGJS.js";import{a as dt}from"./chunk-ODIECDN7.js";import{VersionOperator as io}from"@kanonak-protocol/types/document/models/enums";import{existsSync as yr,readFileSync as gr}from"fs";import{homedir as hr}from"os";import{join as kr}from"path";import{execFile as Zt}from"child_process";import{promisify as Qt}from"util";var C=Qt(Zt),P="kanonak",R="/usr/bin/security",p=class{async get(e){let r=i(e);try{let{stdout:n}=await C(R,["find-generic-password","-s",P,"-a",r,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${r}' is corrupted (not valid JSON).
2
2
  Run 'kanonak logout ${r}' then 'kanonak login ${r}' to fix.`)}}catch(n){if(X(n,44))return null;throw new Error(`macOS Keychain read failed for '${r}': ${w(n)}
3
3
  The Keychain may be locked or inaccessible.
4
4
  Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,r){let n=i(e),o=JSON.stringify(r);try{await C(R,["add-generic-password","-s",P,"-a",n,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${n}': ${w(a)}
@@ -15,6 +15,7 @@
15
15
  import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
16
16
  import { KanonakParser, KanonakObjectParser } from '../parsing/index.js';
17
17
  import { type EntityUri } from '../uri-helpers/index.js';
18
+ import type { Version } from '@kanonak-protocol/types/document/models/types';
18
19
  import { type DerivationLookupResult } from '../derivation/findDerivation.js';
19
20
  export interface RenderedArtifact {
20
21
  /** Serialized output content. */
@@ -106,7 +107,9 @@ export declare class TransformationEngine {
106
107
  * findDerivation).
107
108
  */
108
109
  runTransformation(opts: {
109
- transformation: EntityUri;
110
+ transformation: EntityUri & {
111
+ version?: Version;
112
+ };
110
113
  input: EntityUri;
111
114
  format: EntityUri;
112
115
  /** Suppress backend default chrome. See render's omitWrapper. */
@@ -1,33 +1,33 @@
1
- import{b as E,c as F,d as f,f as M}from"../chunk-2JQMUZWN.js";import{a as X,b as ye}from"../chunk-VBTBY53W.js";import{a as Oe}from"../chunk-BFZZ6YGX.js";import"../chunk-NIJV5UYW.js";import"../chunk-NIGFQYVA.js";import{a as Ue}from"../chunk-FJ35VIV6.js";import{a as C,c as Re,f as Ce}from"../chunk-FMYLEPMC.js";import{b as K,c as w,d as b,g as L,h as U,i as O,j,k as T,l as S}from"../chunk-W6T7MOKY.js";import{a as Le}from"../chunk-7CUTGGH3.js";import"../chunk-HEMBMX7T.js";import"../chunk-FUUTGGJS.js";var gt="kanonak.org",yt="document-ast",m=t=>({publisher:gt,package_:yt,name:t}),k={Document:m("Document"),Block:m("Block"),Inline:m("Inline"),StructuredValue:m("StructuredValue"),Heading:m("Heading"),Paragraph:m("Paragraph"),RawBlock:m("RawBlock"),Text:m("Text"),StructuredMap:m("StructuredMap"),StructuredEntry:m("StructuredEntry"),StructuredList:m("StructuredList"),StringScalar:m("StringScalar"),IntegerScalar:m("IntegerScalar"),EscapeHint:m("EscapeHint"),MediaType:m("MediaType"),metadata:m("metadata"),children:m("children"),level:m("level"),inlines:m("inlines"),text:m("text"),entries:m("entries"),key:m("key"),value:m("value"),escapeHint:m("escapeHint"),items:m("items"),stringValue:m("stringValue"),integerValue:m("integerValue"),rawContent:m("rawContent"),mediaType:m("mediaType"),mimeType:m("mimeType"),ESC_RAW:m("esc-raw"),ESC_YAML_SAFE:m("esc-yaml-safe"),ESC_TOML_STRING:m("esc-toml-string"),ESC_TOML_MULTILINE:m("esc-toml-multiline"),ESC_JSON:m("esc-json"),ESC_DYNAMODB_BOOL:m("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:m("esc-dynamodb-number"),ESC_DYNAMODB_NULL:m("esc-dynamodb-null"),TEXT_PLAIN:m("text-plain"),TEXT_MARKDOWN:m("text-markdown"),TEXT_HTML:m("text-html"),TEXT_CSS:m("text-css"),APPLICATION_JSON:m("application-json"),TEXT_YAML:m("text-yaml"),IMAGE_SVG_XML:m("image-svg-xml"),ResourceLink:m("ResourceLink"),target:m("target"),linkLabel:m("linkLabel"),PropertyList:m("PropertyList"),propertyEntries:m("propertyEntries"),PropertyEntry:m("PropertyEntry"),propertyKey:m("propertyKey"),propertyValue:m("propertyValue"),Table:m("Table"),tableColumnLabels:m("tableColumnLabels"),tableRows:m("tableRows"),TableRow:m("TableRow"),tableCells:m("tableCells")};function Ne(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Y=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(e,n){let r=kt(e.metadata,n),a=wt(e.children),u=["---",...r,"---","",a].join(`
1
+ import{b as E,c as F,d as f,f as M}from"../chunk-2JQMUZWN.js";import{a as X,b as ye}from"../chunk-VBTBY53W.js";import{a as Ne}from"../chunk-JGVDV6PM.js";import"../chunk-NIJV5UYW.js";import"../chunk-NIGFQYVA.js";import{a as Oe}from"../chunk-FJ35VIV6.js";import{a as C,c as Ce,f as Ue}from"../chunk-FMYLEPMC.js";import{b as K,c as w,d as b,g as L,h as U,i as O,j,k as T,l as S}from"../chunk-W6T7MOKY.js";import{a as Re}from"../chunk-7CUTGGH3.js";import{e as Le}from"../chunk-FQHALFRR.js";import"../chunk-HEMBMX7T.js";import"../chunk-FUUTGGJS.js";var yt="kanonak.org",kt="document-ast",m=t=>({publisher:yt,package_:kt,name:t}),k={Document:m("Document"),Block:m("Block"),Inline:m("Inline"),StructuredValue:m("StructuredValue"),Heading:m("Heading"),Paragraph:m("Paragraph"),RawBlock:m("RawBlock"),Text:m("Text"),StructuredMap:m("StructuredMap"),StructuredEntry:m("StructuredEntry"),StructuredList:m("StructuredList"),StringScalar:m("StringScalar"),IntegerScalar:m("IntegerScalar"),EscapeHint:m("EscapeHint"),MediaType:m("MediaType"),metadata:m("metadata"),children:m("children"),level:m("level"),inlines:m("inlines"),text:m("text"),entries:m("entries"),key:m("key"),value:m("value"),escapeHint:m("escapeHint"),items:m("items"),stringValue:m("stringValue"),integerValue:m("integerValue"),rawContent:m("rawContent"),mediaType:m("mediaType"),mimeType:m("mimeType"),ESC_RAW:m("esc-raw"),ESC_YAML_SAFE:m("esc-yaml-safe"),ESC_TOML_STRING:m("esc-toml-string"),ESC_TOML_MULTILINE:m("esc-toml-multiline"),ESC_JSON:m("esc-json"),ESC_DYNAMODB_BOOL:m("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:m("esc-dynamodb-number"),ESC_DYNAMODB_NULL:m("esc-dynamodb-null"),TEXT_PLAIN:m("text-plain"),TEXT_MARKDOWN:m("text-markdown"),TEXT_HTML:m("text-html"),TEXT_CSS:m("text-css"),APPLICATION_JSON:m("application-json"),TEXT_YAML:m("text-yaml"),IMAGE_SVG_XML:m("image-svg-xml"),ResourceLink:m("ResourceLink"),target:m("target"),linkLabel:m("linkLabel"),PropertyList:m("PropertyList"),propertyEntries:m("propertyEntries"),PropertyEntry:m("PropertyEntry"),propertyKey:m("propertyKey"),propertyValue:m("propertyValue"),Table:m("Table"),tableColumnLabels:m("tableColumnLabels"),tableRows:m("tableRows"),TableRow:m("TableRow"),tableCells:m("tableCells")};function Ie(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Y=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(e,n){let r=ht(e.metadata,n),a=St(e.children),u=["---",...r,"---","",a].join(`
2
2
  `);return n?.trailingNewline&&(u.endsWith(`
3
3
  `)||(u+=`
4
- `)),u}};function kt(t,e){if(!t)return[];let n=new Map;for(let c of t.entries)n.set(ue(c.key),c);let r=new Map;if(e?.metadataRenames)for(let[c,l]of e.metadataRenames)r.set(ue(c),l);let i=(e?.metadataKeys??t.entries.map(c=>c.key)).map(ue),u=[];for(let c of i){let l=n.get(c);if(!l)continue;let p=r.get(c),y=ue(p??c),h=Ie(l.value,l.escapeHint);h!==void 0&&u.push(`${y}: ${h}`)}return u}function ue(t){let e=t.lastIndexOf(".");return e===-1?t:t.substring(e+1)||t}function Ie(t,e){switch(t.kind){case"StringScalar":return ht(t.stringValue,e);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let n=[];for(let r of t.items){let a=Ie(r,e);a!==void 0&&n.push(a)}return n.join(", ")}case"StructuredMap":return;default:return}}function ht(t,e){return!e||Ne(e,k.ESC_RAW)?t:Ne(e,k.ESC_YAML_SAFE)?bt(t):t}function bt(t){return t.includes(`
4
+ `)),u}};function ht(t,e){if(!t)return[];let n=new Map;for(let c of t.entries)n.set(ue(c.key),c);let r=new Map;if(e?.metadataRenames)for(let[c,l]of e.metadataRenames)r.set(ue(c),l);let i=(e?.metadataKeys??t.entries.map(c=>c.key)).map(ue),u=[];for(let c of i){let l=n.get(c);if(!l)continue;let p=r.get(c),y=ue(p??c),h=Me(l.value,l.escapeHint);h!==void 0&&u.push(`${y}: ${h}`)}return u}function ue(t){let e=t.lastIndexOf(".");return e===-1?t:t.substring(e+1)||t}function Me(t,e){switch(t.kind){case"StringScalar":return bt(t.stringValue,e);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let n=[];for(let r of t.items){let a=Me(r,e);a!==void 0&&n.push(a)}return n.join(", ")}case"StructuredMap":return;default:return}}function bt(t,e){return!e||Ie(e,k.ESC_RAW)?t:Ie(e,k.ESC_YAML_SAFE)?wt(t):t}function wt(t){return t.includes(`
5
5
  `)?`|-
6
6
  ${t.replace(/\n/g,`
7
- `).trimEnd()}`:/[:#\[\]{}&*!|>'"%@`,]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function wt(t){let e=[];for(let n of t){let r=he(n);r&&e.push(r)}return e.join(`
7
+ `).trimEnd()}`:/[:#\[\]{}&*!|>'"%@`,]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function St(t){let e=[];for(let n of t){let r=he(n);r&&e.push(r)}return e.join(`
8
8
 
9
- `)}function he(t){switch(t.kind){case"Heading":return`${"#".repeat(t.level)} ${ce(t.inlines)}`;case"Paragraph":return ce(t.inlines);case"RawBlock":return t.rawContent;case"PropertyList":return Me(t);case"Table":return St(t);default:return""}}function St(t){let e=t.tableColumnLabels??[],n=t.tableRows??[];if(e.length===0&&n.length===0)return"";let r=`| ${e.map(ke).join(" | ")} |`,a=`| ${e.map(()=>"---").join(" | ")} |`,i=n.map(u=>`| ${(u.tableCells??[]).map(Et).join(" | ")} |`);return[r,a,...i].join(`
10
- `)}function Et(t){let e=t;return!e||typeof e!="object"||!e.kind?"":e.kind==="Text"||e.kind==="ResourceLink"||e.kind==="Badge"?ke(ce([e])):ke(he(e).replace(/\n+/g," "))}function ke(t){return t==null?"":String(t).replace(/\|/g,"\\|")}function Me(t,e=0){if(!t.propertyEntries||t.propertyEntries.length===0)return"";let n=" ".repeat(e),r=[];for(let a of t.propertyEntries){let i=`${n}**${a.propertyKey}:**`,u=vt(a.propertyValue,e+1);u.includes(`
9
+ `)}function he(t){switch(t.kind){case"Heading":return`${"#".repeat(t.level)} ${ce(t.inlines)}`;case"Paragraph":return ce(t.inlines);case"RawBlock":return t.rawContent;case"PropertyList":return _e(t);case"Table":return Et(t);default:return""}}function Et(t){let e=t.tableColumnLabels??[],n=t.tableRows??[];if(e.length===0&&n.length===0)return"";let r=`| ${e.map(ke).join(" | ")} |`,a=`| ${e.map(()=>"---").join(" | ")} |`,i=n.map(u=>`| ${(u.tableCells??[]).map(vt).join(" | ")} |`);return[r,a,...i].join(`
10
+ `)}function vt(t){let e=t;return!e||typeof e!="object"||!e.kind?"":e.kind==="Text"||e.kind==="ResourceLink"||e.kind==="Badge"?ke(ce([e])):ke(he(e).replace(/\n+/g," "))}function ke(t){return t==null?"":String(t).replace(/\|/g,"\\|")}function _e(t,e=0){if(!t.propertyEntries||t.propertyEntries.length===0)return"";let n=" ".repeat(e),r=[];for(let a of t.propertyEntries){let i=`${n}**${a.propertyKey}:**`,u=$t(a.propertyValue,e+1);u.includes(`
11
11
  `)?r.push(`${i}
12
12
  ${u}`):r.push(`${i} ${u}`)}return r.join(`
13
13
 
14
- `)}function vt(t,e){if(!t||t.length===0)return"";let n=[],r=[];for(let a of t){let i=a;!i||typeof i!="object"||!i.kind||(i.kind==="Text"||i.kind==="ResourceLink"||i.kind==="Badge"?n.push(ce([i])):i.kind==="PropertyList"?r.push(Me(i,e)):r.push(he(i)))}return r.length===0?n.join(""):n.length===0?r.join(`
14
+ `)}function $t(t,e){if(!t||t.length===0)return"";let n=[],r=[];for(let a of t){let i=a;!i||typeof i!="object"||!i.kind||(i.kind==="Text"||i.kind==="ResourceLink"||i.kind==="Badge"?n.push(ce([i])):i.kind==="PropertyList"?r.push(_e(i,e)):r.push(he(i)))}return r.length===0?n.join(""):n.length===0?r.join(`
15
15
 
16
16
  `):`${n.join("")}
17
17
 
18
18
  ${r.join(`
19
19
 
20
- `)}`}function ce(t){let e=[];for(let n of t)n.kind==="Text"?e.push(n.text):n.kind==="ResourceLink"?e.push($t(n)):n.kind==="Badge"&&e.push(Vt(n));return e.join("")}function $t(t){let e=Pe(t.target);if(!e)return t.linkLabel??"[unresolved link]";let n=F(e),r=t.linkLabel&&t.linkLabel.length>0?t.linkLabel:e.name,a=t.linkTooltip?` "${_e(t.linkTooltip)}"`:"";return`[${r}](${n}${a})`}function Vt(t){if(!t.badgeTarget)return`*${t.badgeLabel}*`;let e=Pe(t.badgeTarget);if(!e)return`*${t.badgeLabel}*`;let n=F(e),r=t.badgeTooltip?` "${_e(t.badgeTooltip)}"`:"";return`*[${t.badgeLabel}](${n}${r})*`}function _e(t){return t==null?"":String(t).replace(/"/g,'\\"')}function Pe(t){if(!t||typeof t!="object")return;let e=t;if(e.subject&&e.subject.publisher&&e.subject.package_&&e.subject.name){let r={publisher:e.subject.publisher,package_:e.subject.package_,name:e.subject.name};return e.subject.version&&(r.version=e.subject.version),r}let n=t;if(typeof n.namespace=="string"&&typeof n.name=="string"&&n.name.length>0){let r=/^([^/]+)\/([^@]+)@(\d+)\.(\d+)\.(\d+)$/.exec(n.namespace);if(r)return{publisher:r[1],package_:r[2],name:n.name,version:{major:Number(r[3]),minor:Number(r[4]),patch:Number(r[5])}}}}function jt(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Z=class{backendUri="kanonak.org/transformations/toml";render(e,n){let a=At(e.metadata,n).join(`
20
+ `)}`}function ce(t){let e=[];for(let n of t)n.kind==="Text"?e.push(n.text):n.kind==="ResourceLink"?e.push(Vt(n)):n.kind==="Badge"&&e.push(jt(n));return e.join("")}function Vt(t){let e=Fe(t.target);if(!e)return t.linkLabel??"[unresolved link]";let n=F(e),r=t.linkLabel&&t.linkLabel.length>0?t.linkLabel:e.name,a=t.linkTooltip?` "${Pe(t.linkTooltip)}"`:"";return`[${r}](${n}${a})`}function jt(t){if(!t.badgeTarget)return`*${t.badgeLabel}*`;let e=Fe(t.badgeTarget);if(!e)return`*${t.badgeLabel}*`;let n=F(e),r=t.badgeTooltip?` "${Pe(t.badgeTooltip)}"`:"";return`*[${t.badgeLabel}](${n}${r})*`}function Pe(t){return t==null?"":String(t).replace(/"/g,'\\"')}function Fe(t){if(!t||typeof t!="object")return;let e=t;if(e.subject&&e.subject.publisher&&e.subject.package_&&e.subject.name){let r={publisher:e.subject.publisher,package_:e.subject.package_,name:e.subject.name};return e.subject.version&&(r.version=e.subject.version),r}let n=t;if(typeof n.namespace=="string"&&typeof n.name=="string"&&n.name.length>0){let r=/^([^/]+)\/([^@]+)@(\d+)\.(\d+)\.(\d+)$/.exec(n.namespace);if(r)return{publisher:r[1],package_:r[2],name:n.name,version:{major:Number(r[3]),minor:Number(r[4]),patch:Number(r[5])}}}}function At(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Z=class{backendUri="kanonak.org/transformations/toml";render(e,n){let a=Dt(e.metadata,n).join(`
21
21
  `);return n?.trailingNewline&&(a.endsWith(`
22
22
  `)||(a+=`
23
- `)),a}};function At(t,e){if(!t)return[];let n=new Map;for(let i of t.entries)n.set(i.key,i);let r=e?.metadataKeys??t.entries.map(i=>i.key),a=[];for(let i of r){let u=n.get(i);if(!u)continue;let c=e?.metadataRenames.get(i)??i,l=Fe(u.value,u.escapeHint);l!==void 0&&a.push(`${c} = ${l}`)}return a}function Fe(t,e){switch(t.kind){case"StringScalar":return Dt(t.stringValue,e);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let n=[];for(let r of t.items){let a=Fe(r,e);a!==void 0&&n.push(a)}return`[${n.join(", ")}]`}case"StructuredMap":return;default:return}}function Dt(t,e){return e&&jt(e,k.ESC_TOML_MULTILINE)?Tt(t):Kt(t)}function Kt(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n")}"`}function Tt(t){return`"""
23
+ `)),a}};function Dt(t,e){if(!t)return[];let n=new Map;for(let i of t.entries)n.set(i.key,i);let r=e?.metadataKeys??t.entries.map(i=>i.key),a=[];for(let i of r){let u=n.get(i);if(!u)continue;let c=e?.metadataRenames.get(i)??i,l=qe(u.value,u.escapeHint);l!==void 0&&a.push(`${c} = ${l}`)}return a}function qe(t,e){switch(t.kind){case"StringScalar":return Kt(t.stringValue,e);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let n=[];for(let r of t.items){let a=qe(r,e);a!==void 0&&n.push(a)}return`[${n.join(", ")}]`}case"StructuredMap":return;default:return}}function Kt(t,e){return e&&At(e,k.ESC_TOML_MULTILINE)?Bt(t):Tt(t)}function Tt(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n")}"`}function Bt(t){return`"""
24
24
  ${t.replace(/"""/g,'\\"\\"\\"')}
25
25
  """`}var Q=class{backendUri="kanonak.org/transformations/json";render(e,n){let r=JSON.stringify(e,null,2);return n?.trailingNewline&&!r.endsWith(`
26
26
  `)?r+`
27
- `:r}};function be(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var x=class{backendUri="kanonak.org/transformations/html";render(e,n){let r=Rt(e.children);if(n?.omitWrapper){let c=r.endsWith(`
27
+ `:r}};function be(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var x=class{backendUri="kanonak.org/transformations/html";render(e,n){let r=Ct(e.children);if(n?.omitWrapper){let c=r.endsWith(`
28
28
  `)?r:`${r}
29
29
  `;return n.trailingNewline===!1&&c.endsWith(`
30
- `)?c.slice(0,-1):c}let a=Bt(e.metadata)??"Untitled",i=Lt(e.metadata,n),u=`<!DOCTYPE html>
30
+ `)?c.slice(0,-1):c}let a=Lt(e.metadata)??"Untitled",i=Rt(e.metadata,n),u=`<!DOCTYPE html>
31
31
  <html lang="en">
32
32
  <head>
33
33
  <meta charset="utf-8">
@@ -57,35 +57,35 @@ ${i}${r}
57
57
  </body>
58
58
  </html>
59
59
  `;return n?.trailingNewline===!1&&u.endsWith(`
60
- `)?u.slice(0,-1):u}};function Bt(t){if(t){for(let e of t.entries)if((e.key==="title"||e.key==="name")&&e.value.kind==="StringScalar")return e.value.stringValue}}function Lt(t,e){if(!t||t.entries.length===0)return"";let n=e?.metadataKeys??t.entries.map(i=>i.key),r=new Map(t.entries.map(i=>[i.key,i])),a=[];for(let i of n){let u=r.get(i);if(!u)continue;let c=e?.metadataRenames.get(i)??i,l=qe(u.value);l!==void 0&&a.push(` <dt>${N(c)}</dt>
60
+ `)?u.slice(0,-1):u}};function Lt(t){if(t){for(let e of t.entries)if((e.key==="title"||e.key==="name")&&e.value.kind==="StringScalar")return e.value.stringValue}}function Rt(t,e){if(!t||t.entries.length===0)return"";let n=e?.metadataKeys??t.entries.map(i=>i.key),r=new Map(t.entries.map(i=>[i.key,i])),a=[];for(let i of n){let u=r.get(i);if(!u)continue;let c=e?.metadataRenames.get(i)??i,l=We(u.value);l!==void 0&&a.push(` <dt>${N(c)}</dt>
61
61
  <dd>${l}</dd>`)}return a.length===0?"":`<dl class="metadata">
62
62
  ${a.join(`
63
63
  `)}
64
64
  </dl>
65
- `}function qe(t){switch(t.kind){case"StringScalar":return N(t.stringValue);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let e=[];for(let n of t.items){let r=qe(n);r!==void 0&&e.push(`<code>${r}</code>`)}return e.join(", ")}case"StructuredMap":return;default:return}}function Rt(t){let e=[];for(let n of t){let r=we(n);r&&e.push(r)}return e.join(`
66
- `)}function we(t){switch(t.kind){case"Heading":{let e=Math.max(1,Math.min(6,t.level));return`<h${e}>${de(t.inlines)}</h${e}>`}case"Paragraph":return`<p>${de(t.inlines)}</p>`;case"RawBlock":return Mt(t);case"PropertyList":return Nt(t);case"Table":return Ct(t);default:return""}}function Ct(t){let e=t.tableColumnLabels??[],n=t.tableRows??[],r=e.length>0?`<thead>
65
+ `}function We(t){switch(t.kind){case"StringScalar":return N(t.stringValue);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let e=[];for(let n of t.items){let r=We(n);r!==void 0&&e.push(`<code>${r}</code>`)}return e.join(", ")}case"StructuredMap":return;default:return}}function Ct(t){let e=[];for(let n of t){let r=we(n);r&&e.push(r)}return e.join(`
66
+ `)}function we(t){switch(t.kind){case"Heading":{let e=Math.max(1,Math.min(6,t.level));return`<h${e}>${de(t.inlines)}</h${e}>`}case"Paragraph":return`<p>${de(t.inlines)}</p>`;case"RawBlock":return _t(t);case"PropertyList":return It(t);case"Table":return Ut(t);default:return""}}function Ut(t){let e=t.tableColumnLabels??[],n=t.tableRows??[],r=e.length>0?`<thead>
67
67
  <tr>${e.map(i=>`<th>${N(i)}</th>`).join("")}</tr>
68
68
  </thead>
69
69
  `:"",a=n.length>0?`<tbody>
70
- ${n.map(Ut).join(`
70
+ ${n.map(Ot).join(`
71
71
  `)}
72
72
  </tbody>
73
73
  `:"";return`<table class="property-table">
74
- ${r}${a}</table>`}function Ut(t){return` <tr>${(t.tableCells??[]).map(r=>`<td>${Ot(r)}</td>`).join("")}</tr>`}function Ot(t){let e=t;return!e||typeof e!="object"||!e.kind?"":e.kind==="Text"||e.kind==="ResourceLink"||e.kind==="Badge"?de([e]):we(e)}function Nt(t){if(!t.propertyEntries||t.propertyEntries.length===0)return"";let e=[];for(let n of t.propertyEntries){let a=`<dt${n.propertyTooltip?` title="${H(n.propertyTooltip)}"`:""}>${N(n.propertyKey)}</dt>`,i=`<dd>${It(n.propertyValue)}</dd>`;e.push(a,i)}return`<dl class="property-list">
74
+ ${r}${a}</table>`}function Ot(t){return` <tr>${(t.tableCells??[]).map(r=>`<td>${Nt(r)}</td>`).join("")}</tr>`}function Nt(t){let e=t;return!e||typeof e!="object"||!e.kind?"":e.kind==="Text"||e.kind==="ResourceLink"||e.kind==="Badge"?de([e]):we(e)}function It(t){if(!t.propertyEntries||t.propertyEntries.length===0)return"";let e=[];for(let n of t.propertyEntries){let a=`<dt${n.propertyTooltip?` title="${H(n.propertyTooltip)}"`:""}>${N(n.propertyKey)}</dt>`,i=`<dd>${Mt(n.propertyValue)}</dd>`;e.push(a,i)}return`<dl class="property-list">
75
75
  ${e.join(`
76
76
  `)}
77
- </dl>`}function It(t){if(!t||t.length===0)return"";let e=[];for(let n of t){let r=n;!r||typeof r!="object"||!r.kind||(r.kind==="Text"||r.kind==="ResourceLink"||r.kind==="Badge"?e.push(de([r])):e.push(we(r)))}return e.join("")}function Mt(t){let e=t.mediaType;return e&&be(e,k.TEXT_MARKDOWN)?X(t.rawContent):e&&be(e,k.TEXT_HTML)?t.rawContent:e&&be(e,k.IMAGE_SVG_XML)?`<figure class="svg-figure">
77
+ </dl>`}function Mt(t){if(!t||t.length===0)return"";let e=[];for(let n of t){let r=n;!r||typeof r!="object"||!r.kind||(r.kind==="Text"||r.kind==="ResourceLink"||r.kind==="Badge"?e.push(de([r])):e.push(we(r)))}return e.join("")}function _t(t){let e=t.mediaType;return e&&be(e,k.TEXT_MARKDOWN)?X(t.rawContent):e&&be(e,k.TEXT_HTML)?t.rawContent:e&&be(e,k.IMAGE_SVG_XML)?`<figure class="svg-figure">
78
78
  ${t.rawContent}
79
- </figure>`:`<pre${e?` class="media-${H(e.name)}"`:""}><code>${N(t.rawContent)}</code></pre>`}function de(t){let e=[];for(let n of t)n.kind==="Text"?e.push(N(n.text)):n.kind==="ResourceLink"?e.push(_t(n)):n.kind==="Badge"&&e.push(Pt(n));return e.join("")}function _t(t){let e=We(t.target);if(!e)return N(t.linkLabel??"[unresolved link]");let n=F(e),r=t.linkLabel&&t.linkLabel.length>0?t.linkLabel:e.name,a=t.linkTooltip?` title="${H(t.linkTooltip)}"`:"";return`<a class="kan-link" href="${H(n)}"${a}>${N(r)}</a>`}function Pt(t){let e=t.badgeTooltip?` title="${H(t.badgeTooltip)}"`:"",n=N(t.badgeLabel);if(!t.badgeTarget)return`<span class="kan-badge"${e}>${n}</span>`;let r=We(t.badgeTarget);if(!r)return`<span class="kan-badge"${e}>${n}</span>`;let a=F(r);return`<a class="kan-badge" href="${H(a)}"${e}>${n}</a>`}function We(t){if(!t||typeof t!="object")return;let e=t;if(e.subject&&e.subject.publisher&&e.subject.package_&&e.subject.name){let r={publisher:e.subject.publisher,package_:e.subject.package_,name:e.subject.name};return e.subject.version&&(r.version=e.subject.version),r}let n=t;if(typeof n.namespace=="string"&&typeof n.name=="string"&&n.name.length>0){let r=/^([^/]+)\/([^@]+)@(\d+)\.(\d+)\.(\d+)$/.exec(n.namespace);if(r)return{publisher:r[1],package_:r[2],name:n.name,version:{major:Number(r[3]),minor:Number(r[4]),patch:Number(r[5])}}}}function N(t){return t==null?"":String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function H(t){return t==null?"":String(t).replace(/"/g,"&quot;").replace(/&/g,"&amp;")}function Ft(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var ee=class{backendUri="kanonak.org/transformations/svg";render(e,n){for(let r of e.children)if(r.kind==="RawBlock"&&r.mediaType&&Ft(r.mediaType,k.IMAGE_SVG_XML)){let a=r.rawContent;return n?.trailingNewline&&!a.endsWith(`
79
+ </figure>`:`<pre${e?` class="media-${H(e.name)}"`:""}><code>${N(t.rawContent)}</code></pre>`}function de(t){let e=[];for(let n of t)n.kind==="Text"?e.push(N(n.text)):n.kind==="ResourceLink"?e.push(Pt(n)):n.kind==="Badge"&&e.push(Ft(n));return e.join("")}function Pt(t){let e=He(t.target);if(!e)return N(t.linkLabel??"[unresolved link]");let n=F(e),r=t.linkLabel&&t.linkLabel.length>0?t.linkLabel:e.name,a=t.linkTooltip?` title="${H(t.linkTooltip)}"`:"";return`<a class="kan-link" href="${H(n)}"${a}>${N(r)}</a>`}function Ft(t){let e=t.badgeTooltip?` title="${H(t.badgeTooltip)}"`:"",n=N(t.badgeLabel);if(!t.badgeTarget)return`<span class="kan-badge"${e}>${n}</span>`;let r=He(t.badgeTarget);if(!r)return`<span class="kan-badge"${e}>${n}</span>`;let a=F(r);return`<a class="kan-badge" href="${H(a)}"${e}>${n}</a>`}function He(t){if(!t||typeof t!="object")return;let e=t;if(e.subject&&e.subject.publisher&&e.subject.package_&&e.subject.name){let r={publisher:e.subject.publisher,package_:e.subject.package_,name:e.subject.name};return e.subject.version&&(r.version=e.subject.version),r}let n=t;if(typeof n.namespace=="string"&&typeof n.name=="string"&&n.name.length>0){let r=/^([^/]+)\/([^@]+)@(\d+)\.(\d+)\.(\d+)$/.exec(n.namespace);if(r)return{publisher:r[1],package_:r[2],name:n.name,version:{major:Number(r[3]),minor:Number(r[4]),patch:Number(r[5])}}}}function N(t){return t==null?"":String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function H(t){return t==null?"":String(t).replace(/"/g,"&quot;").replace(/&/g,"&amp;")}function qt(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var ee=class{backendUri="kanonak.org/transformations/svg";render(e,n){for(let r of e.children)if(r.kind==="RawBlock"&&r.mediaType&&qt(r.mediaType,k.IMAGE_SVG_XML)){let a=r.rawContent;return n?.trailingNewline&&!a.endsWith(`
80
80
  `)&&(a+=`
81
- `),a}return'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'}};function qt(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var te=class{backendUri="kanonak.org/transformations/stylesheet";render(e,n){let r=[];for(let i of e.children)i.kind==="RawBlock"&&i.mediaType&&qt(i.mediaType,k.TEXT_CSS)&&r.push(i.rawContent);let a=r.join(`
81
+ `),a}return'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'}};function Wt(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var te=class{backendUri="kanonak.org/transformations/stylesheet";render(e,n){let r=[];for(let i of e.children)i.kind==="RawBlock"&&i.mediaType&&Wt(i.mediaType,k.TEXT_CSS)&&r.push(i.rawContent);let a=r.join(`
82
82
 
83
83
  `);return n?.trailingNewline&&a.length>0&&!a.endsWith(`
84
84
  `)&&(a+=`
85
- `),a}};function Wt(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var ne=class{backendUri="kanonak.org/transformations/yaml";render(e,n){let r=[];for(let i of e.children)i.kind==="RawBlock"&&i.mediaType&&Wt(i.mediaType,k.TEXT_YAML)&&r.push(i.rawContent);let a=r.join(`
85
+ `),a}};function Ht(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var ne=class{backendUri="kanonak.org/transformations/yaml";render(e,n){let r=[];for(let i of e.children)i.kind==="RawBlock"&&i.mediaType&&Ht(i.mediaType,k.TEXT_YAML)&&r.push(i.rawContent);let a=r.join(`
86
86
 
87
87
  `);return n?.trailingNewline&&a.length>0&&!a.endsWith(`
88
88
  `)&&(a+=`
89
- `),a}};function re(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var ae=class{backendUri="kanonak.org/transformations/dynamodb-json";render(e,n){if(!e.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=He(e.metadata,n),a=JSON.stringify(r,null,2);return n?.trailingNewline&&!a.endsWith(`
89
+ `),a}};function re(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var ae=class{backendUri="kanonak.org/transformations/dynamodb-json";render(e,n){if(!e.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=ze(e.metadata,n),a=JSON.stringify(r,null,2);return n?.trailingNewline&&!a.endsWith(`
90
90
  `)&&(a+=`
91
- `),a}};function He(t,e){let n=new Map;for(let i of t.entries)n.set(i.key,i);let r=e?.metadataKeys??t.entries.map(i=>i.key),a={};for(let i of r){let u=n.get(i);if(!u)continue;let c=e?.metadataRenames.get(i)??i;a[c]=ze(u.value,u.escapeHint)}return{M:a}}function ze(t,e){switch(t.kind){case"StructuredMap":return He(t);case"StructuredList":return{L:t.items.map(n=>ze(n,void 0))};case"StringScalar":return Ht(t.stringValue,e??t.escapeHint);case"IntegerScalar":return zt(t.integerValue,e??t.escapeHint)}}function Ht(t,e){if(e&&re(e,k.ESC_DYNAMODB_BOOL)){if(t==="true")return{BOOL:!0};if(t==="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(t)}.`)}if(e&&re(e,k.ESC_DYNAMODB_NULL))return{NULL:!0};if(e&&re(e,k.ESC_DYNAMODB_NUMBER)){if(t.trim()===""||Number.isNaN(Number(t)))throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-number must hold a numeric literal; got ${JSON.stringify(t)}.`);return{N:t}}return{S:t}}function zt(t,e){if(e&&re(e,k.ESC_DYNAMODB_BOOL))throw new Error(`dynamodb-json backend: esc-dynamodb-bool cannot apply to an IntegerScalar (value ${t}). Use a StringScalar "true"/"false".`);if(e&&re(e,k.ESC_DYNAMODB_NULL))throw new Error(`dynamodb-json backend: esc-dynamodb-null cannot apply to an IntegerScalar (value ${t}). Use a StringScalar hinted esc-dynamodb-null.`);return{N:String(t)}}var ie=class{constructor(e,n,r){this.repository=e;this.parser=n;this.objectParser=r}repository;parser;objectParser;cache=new Map;async resolveSubject(e,n){let r=M(n,e);if(r)return r;let a=e.version,i=a&&typeof a.major=="number"?`@${a.major}.${a.minor}.${a.patch}`:"",u=`${e.publisher}/${e.package_}${i}`,c=this.cache.get(u);if(!c){let p=await this.repository.getDocumentsByNamespaceAsync(e.publisher,e.package_);if(p.length===0)return;let y=a&&typeof a.major=="number"?p.find(D=>{let $=D.metadata?.namespace_?.version;return $&&$.major===a.major&&$.minor===a.minor&&$.patch===a.patch})??p[0]:p[0],h=new Ue(y,this.repository);c=await this.objectParser.parseKanonaks(h),this.cache.set(u,c)}let l=M(c,e);if(l)return l;for(let p of c)if(p instanceof w&&p.name===e.name)return p}};var Gt="kanonak.org",Jt="transformations",Zn=3,s=t=>({publisher:Gt,package_:Jt,name:t}),o={Transformation:s("Transformation"),InstanceTransformation:s("InstanceTransformation"),SetTransformation:s("SetTransformation"),inputPattern:s("inputPattern"),rule:s("rule"),artifactName:s("artifactName"),outputs:s("outputs"),formatOverrides:s("formatOverrides"),partitionBy:s("partitionBy"),InputPattern:s("InputPattern"),matchesClass:s("matchesClass"),requires:s("requires"),sortBy:s("sortBy"),SortKey:s("SortKey"),byProperty:s("byProperty"),order:s("order"),SortOrder:s("SortOrder"),ascending:s("ascending"),descending:s("descending"),OutputFormat:s("OutputFormat"),backendUri:s("backendUri"),FormatOverride:s("FormatOverride"),formatTarget:s("formatTarget"),metadataKeys:s("metadataKeys"),metadataRenames:s("metadataRenames"),trailingNewline:s("trailingNewline"),omitWrapper:s("omitWrapper"),RenameEntry:s("RenameEntry"),fromKey:s("fromKey"),toKey:s("toKey"),FMT_MARKDOWN_FRONTMATTER:s("markdown-with-frontmatter"),FMT_PLAIN_MARKDOWN:s("plain-markdown"),FMT_TOML:s("toml"),FMT_JSON:s("json"),FMT_HTML:s("html"),FMT_SVG:s("svg"),Expression:s("Expression"),ListSourcedExpression:s("ListSourcedExpression"),ListAggregate:s("ListAggregate"),IteratingExpression:s("IteratingExpression"),BuildAstNode:s("BuildAstNode"),astClass:s("astClass"),set:s("set"),AstFieldBinding:s("AstFieldBinding"),field:s("field"),bindValue:s("bindValue"),When:s("When"),condition:s("condition"),thenBuild:s("thenBuild"),elseBuild:s("elseBuild"),Concat:s("Concat"),parts:s("parts"),Fallback:s("Fallback"),primary:s("primary"),alternate:s("alternate"),StringLiteral:s("StringLiteral"),stringLiteral:s("stringLiteral"),IntegerLiteral:s("IntegerLiteral"),integerLiteral:s("integerLiteral"),DecimalLiteral:s("DecimalLiteral"),decimalLiteral:s("decimalLiteral"),BooleanLiteral:s("BooleanLiteral"),booleanLiteral:s("booleanLiteral"),VarRef:s("VarRef"),varName:s("varName"),PropertyRead:s("PropertyRead"),readSource:s("readSource"),readProp:s("readProp"),Traverse:s("Traverse"),traverseSource:s("traverseSource"),through:s("through"),step:s("step"),UriName:s("UriName"),uriNameOf:s("uriNameOf"),UriPublisher:s("UriPublisher"),uriPublisherOf:s("uriPublisherOf"),UriPackage:s("UriPackage"),uriPackageOf:s("uriPackageOf"),UriVersion:s("UriVersion"),uriVersionOf:s("uriVersionOf"),SubjectUri:s("SubjectUri"),subjectOf:s("subjectOf"),UriLiteral:s("UriLiteral"),refTo:s("refTo"),DisplayLabel:s("DisplayLabel"),labelTarget:s("labelTarget"),labelSource:s("labelSource"),ResolveRef:s("ResolveRef"),resolveSource:s("resolveSource"),Normalize:s("Normalize"),normSource:s("normSource"),normKind:s("normKind"),NormalizeKind:s("NormalizeKind"),NORM_TRIM_END:s("trim-end"),IsSet:s("IsSet"),checkExpr:s("checkExpr"),ExpressionFragment:s("ExpressionFragment"),body:s("body"),CallFragment:s("CallFragment"),fragmentRef:s("fragmentRef"),source:s("source"),Join:s("Join"),separator:s("separator"),Count:s("Count"),Sum:s("Sum"),Min:s("Min"),Max:s("Max"),Average:s("Average"),loopVar:s("loopVar"),ForEach:s("ForEach"),emit:s("emit"),ListMap:s("ListMap"),mapBody:s("mapBody"),Filter:s("Filter"),predicate:s("predicate"),PartitionBy:s("PartitionBy"),partitionKey:s("partitionKey"),DistinctBy:s("DistinctBy"),distinctKey:s("distinctKey"),Partition:s("Partition"),key:s("key"),members:s("members"),AllStatements:s("AllStatements"),statementsOf:s("statementsOf"),StatementPredicate:s("StatementPredicate"),predicateOf:s("predicateOf"),StatementValue:s("StatementValue"),valueOf:s("valueOf"),DateFormat:s("DateFormat"),dateSource:s("dateSource"),dateFormat:s("dateFormat"),BinaryArithmetic:s("BinaryArithmetic"),arithLeft:s("arithLeft"),arithRight:s("arithRight"),Add:s("Add"),Subtract:s("Subtract"),Multiply:s("Multiply"),Divide:s("Divide"),Reverse:s("Reverse"),WindowedMap:s("WindowedMap"),windowSize:s("windowSize"),windowVar:s("windowVar"),windowBody:s("windowBody"),PairwiseMap:s("PairwiseMap"),firstVar:s("firstVar"),secondVar:s("secondVar"),pairBody:s("pairBody"),Scan:s("Scan"),initialState:s("initialState"),stateVar:s("stateVar"),elementVar:s("elementVar"),accumulate:s("accumulate"),ListItemAt:s("ListItemAt"),itemIndex:s("itemIndex"),BinaryComparison:s("BinaryComparison"),compareLeft:s("compareLeft"),compareRight:s("compareRight"),Equals:s("Equals"),GreaterThan:s("GreaterThan"),LessThan:s("LessThan"),GreaterThanOrEqual:s("GreaterThanOrEqual"),LessThanOrEqual:s("LessThanOrEqual"),Not:s("Not"),operand:s("operand"),BooleanLogic:s("BooleanLogic"),operands:s("operands"),And:s("And"),Or:s("Or"),Contains:s("Contains"),haystack:s("haystack"),needle:s("needle"),UnaryNumericOp:s("UnaryNumericOp"),value:s("value"),Abs:s("Abs"),Negate:s("Negate"),KindPredicate:s("KindPredicate"),IsReference:s("IsReference"),IsEmbedded:s("IsEmbedded"),IsList:s("IsList"),kindCheck:s("kindCheck"),IsString:s("IsString"),IsNumber:s("IsNumber"),IsBoolean:s("IsBoolean"),StatementObject:s("StatementObject"),statementSource:s("statementSource"),Let:s("Let"),letName:s("letName"),letValue:s("letValue"),letBody:s("letBody"),GetStatementByName:s("GetStatementByName"),inSubject:s("inSubject"),byName:s("byName"),RenderMarkdown:s("RenderMarkdown"),renderSource:s("renderSource"),renderProp:s("renderProp"),renderFormat:s("renderFormat"),RenderFormat:s("RenderFormat"),RENDER_HTML:s("render-html"),RENDER_MARKDOWN:s("render-markdown")};var g=class extends Error{constructor(n,r){super(`${n} (at ${r})`);this.path=r}path};function fe(t,e){let n=t.name,r=on(e),a={catalog:e,depth:0};if(f(t,o.InstanceTransformation))return Xt(t,n,a,r);if(f(t,o.SetTransformation))return Yt(t,n,a,r);throw new g("Subject is not a recognized v3 transformation type \u2014 expected InstanceTransformation or SetTransformation",n)}function Xt(t,e,n,r){return{kind:"instance",name:t.name,inputPattern:Qe(t,e),rule:le(t,o.rule,`${e}.rule`,n),artifactName:le(t,o.artifactName,`${e}.artifactName`,n),outputs:xe(t,`${e}.outputs`),overrides:et(t,`${e}.formatOverrides`,n),fragments:r}}function Yt(t,e,n,r){let a=_(t,o.partitionBy);return{kind:"set",name:t.name,inputPattern:Qe(t,e),rule:le(t,o.rule,`${e}.rule`,n),artifactName:le(t,o.artifactName,`${e}.artifactName`,n),outputs:xe(t,`${e}.outputs`),overrides:et(t,`${e}.formatOverrides`,n),partitionBy:a,fragments:r}}function Qe(t,e){let n=oe(t,o.inputPattern);if(!n)throw new g("inputPattern is required",e);return Zt(n,`${e}.inputPattern`)}function Zt(t,e){let n=_(t,o.matchesClass);if(!n)throw new g("matchesClass is required",e);let r=[];for(let u of A(t,o.requires))if(u instanceof j)r.push(ve(u.object.subject));else if(u instanceof S)for(let c of u.object)c instanceof b&&r.push(ve(c.subject));let a=[],i=0;for(let u of A(t,o.sortBy))if(u instanceof S)for(let c of u.object)c instanceof C&&a.push(Ge(c,`${e}.sortBy[${i++}]`));else u instanceof T&&a.push(Ge(u.object,`${e}.sortBy[${i++}]`));return{matchesClass:n,requires:r,sortBy:a}}function Ge(t,e){let n=_(t,o.byProperty);if(!n)throw new g("SortKey.byProperty is required",e);let r=_(t,o.order);if(!r)throw new g("SortKey.order is required",e);if(E(r,o.ascending))return{byProperty:n,order:"ascending"};if(E(r,o.descending))return{byProperty:n,order:"descending"};throw new g(`SortKey.order must reference tx.ascending or tx.descending; got ${r.publisher}/${r.package_}/${r.name}`,e)}function le(t,e,n,r){let a=oe(t,e);if(!a)throw new g("expression is required",n);return G(a,n,r)}function G(t,e,n){if(f(t,o.StringLiteral))return{kind:"string-literal",value:V(t,o.stringLiteral,e)};if(f(t,o.IntegerLiteral))return{kind:"integer-literal",value:Ze(t,o.integerLiteral,e)};if(f(t,o.DecimalLiteral))return{kind:"decimal-literal",value:Ze(t,o.decimalLiteral,e)};if(f(t,o.BooleanLiteral))return{kind:"boolean-literal",value:cn(t,o.booleanLiteral,e)};if(f(t,o.VarRef))return{kind:"var-ref",varName:V(t,o.varName,e)};if(f(t,o.PropertyRead))return{kind:"property-read",source:d(t,o.readSource,`${e}.readSource`,n),readProp:q(t,o.readProp,e,"readProp")};if(f(t,o.Traverse))return{kind:"traverse",source:d(t,o.traverseSource,`${e}.traverseSource`,n),through:q(t,o.through,e,"through"),step:d(t,o.step,`${e}.step`,n)};if(f(t,o.BuildAstNode))return{kind:"build-ast-node",astClass:q(t,o.astClass,e,"astClass"),set:xt(t,`${e}.set`,n)};if(f(t,o.When))return{kind:"when",condition:d(t,o.condition,`${e}.condition`,n),thenBuild:d(t,o.thenBuild,`${e}.thenBuild`,n),elseBuild:Qt(t,o.elseBuild,`${e}.elseBuild`,n)};if(f(t,o.Concat))return{kind:"concat",parts:Se(t,o.parts,`${e}.parts`,n)};if(f(t,o.Fallback))return{kind:"fallback",primary:d(t,o.primary,`${e}.primary`,n),alternate:d(t,o.alternate,`${e}.alternate`,n)};if(f(t,o.UriName))return{kind:"uri-name",source:d(t,o.uriNameOf,`${e}.uriNameOf`,n)};if(f(t,o.UriPublisher))return{kind:"uri-publisher",source:d(t,o.uriPublisherOf,`${e}.uriPublisherOf`,n)};if(f(t,o.UriPackage))return{kind:"uri-package",source:d(t,o.uriPackageOf,`${e}.uriPackageOf`,n)};if(f(t,o.UriVersion))return{kind:"uri-version",source:d(t,o.uriVersionOf,`${e}.uriVersionOf`,n)};if(f(t,o.SubjectUri))return{kind:"subject-uri",source:d(t,o.subjectOf,`${e}.subjectOf`,n)};if(f(t,o.UriLiteral))return{kind:"uri-literal",refTo:q(t,o.refTo,e,"refTo")};if(f(t,o.DisplayLabel))return{kind:"display-label",labelTarget:q(t,o.labelTarget,e,"labelTarget"),labelSource:q(t,o.labelSource,e,"labelSource")};if(f(t,o.ResolveRef))return{kind:"resolve-ref",source:d(t,o.resolveSource,`${e}.resolveSource`,n)};if(f(t,o.Normalize))return{kind:"normalize",source:d(t,o.normSource,`${e}.normSource`,n),normKind:en(t,e)};if(f(t,o.RenderMarkdown))return{kind:"render-markdown",source:d(t,o.renderSource,`${e}.renderSource`,n),readProp:q(t,o.renderProp,e,"renderProp"),format:tn(t,e)};if(f(t,o.IsSet))return{kind:"is-set",check:d(t,o.checkExpr,`${e}.checkExpr`,n)};if(f(t,o.CallFragment))return rn(t,e,n);if(f(t,o.Join))return{kind:"join",source:d(t,o.source,`${e}.source`,n),separator:V(t,o.separator,e)};if(f(t,o.Count))return{kind:"count",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.Sum))return{kind:"sum",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.Min))return{kind:"min",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.Max))return{kind:"max",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.Average))return{kind:"average",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.ForEach))return{kind:"for-each",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),emit:d(t,o.emit,`${e}.emit`,n)};if(f(t,o.ListMap))return{kind:"list-map",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),mapBody:d(t,o.mapBody,`${e}.mapBody`,n)};if(f(t,o.Filter))return{kind:"filter",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),predicate:d(t,o.predicate,`${e}.predicate`,n)};if(f(t,o.PartitionBy))return{kind:"partition-by",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),partitionKey:d(t,o.partitionKey,`${e}.partitionKey`,n)};if(f(t,o.DistinctBy))return{kind:"distinct-by",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),distinctKey:d(t,o.distinctKey,`${e}.distinctKey`,n)};if(f(t,o.AllStatements))return{kind:"all-statements",source:d(t,o.statementsOf,`${e}.statementsOf`,n)};if(f(t,o.StatementPredicate))return{kind:"statement-predicate",source:d(t,o.predicateOf,`${e}.predicateOf`,n)};if(f(t,o.StatementValue))return{kind:"statement-value",source:d(t,o.valueOf,`${e}.valueOf`,n)};if(f(t,o.DateFormat))return{kind:"date-format",source:d(t,o.dateSource,`${e}.dateSource`,n),format:nn(t,e)};if(f(t,o.Add))return{kind:"add",left:d(t,o.arithLeft,`${e}.arithLeft`,n),right:d(t,o.arithRight,`${e}.arithRight`,n)};if(f(t,o.Subtract))return{kind:"subtract",left:d(t,o.arithLeft,`${e}.arithLeft`,n),right:d(t,o.arithRight,`${e}.arithRight`,n)};if(f(t,o.Multiply))return{kind:"multiply",left:d(t,o.arithLeft,`${e}.arithLeft`,n),right:d(t,o.arithRight,`${e}.arithRight`,n)};if(f(t,o.Divide))return{kind:"divide",left:d(t,o.arithLeft,`${e}.arithLeft`,n),right:d(t,o.arithRight,`${e}.arithRight`,n)};if(f(t,o.Reverse))return{kind:"reverse",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.WindowedMap)){let r=tt(t,o.windowSize);if(r===void 0||!Number.isInteger(r)||r<1)throw new g("windowSize must be a positive integer",`${e}.windowSize`);return{kind:"windowed-map",source:d(t,o.source,`${e}.source`,n),windowSize:r,windowVar:V(t,o.windowVar,e),windowBody:d(t,o.windowBody,`${e}.windowBody`,n)}}if(f(t,o.PairwiseMap))return{kind:"pairwise-map",source:d(t,o.source,`${e}.source`,n),firstVar:V(t,o.firstVar,e),secondVar:V(t,o.secondVar,e),pairBody:d(t,o.pairBody,`${e}.pairBody`,n)};if(f(t,o.Scan))return{kind:"scan",source:d(t,o.source,`${e}.source`,n),initialState:d(t,o.initialState,`${e}.initialState`,n),stateVar:V(t,o.stateVar,e),elementVar:V(t,o.elementVar,e),accumulate:d(t,o.accumulate,`${e}.accumulate`,n)};if(f(t,o.ListItemAt))return{kind:"list-item-at",source:d(t,o.source,`${e}.source`,n),itemIndex:d(t,o.itemIndex,`${e}.itemIndex`,n)};if(f(t,o.Equals))return{kind:"equals",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.GreaterThan))return{kind:"greater-than",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.LessThan))return{kind:"less-than",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.GreaterThanOrEqual))return{kind:"greater-than-or-equal",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.LessThanOrEqual))return{kind:"less-than-or-equal",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.Not))return{kind:"not",operand:d(t,o.operand,`${e}.operand`,n)};if(f(t,o.And))return{kind:"and",operands:Se(t,o.operands,`${e}.operands`,n)};if(f(t,o.Or))return{kind:"or",operands:Se(t,o.operands,`${e}.operands`,n)};if(f(t,o.Contains))return{kind:"contains",haystack:d(t,o.haystack,`${e}.haystack`,n),needle:d(t,o.needle,`${e}.needle`,n)};if(f(t,o.Abs))return{kind:"abs",value:d(t,o.value,`${e}.value`,n)};if(f(t,o.Negate))return{kind:"negate",value:d(t,o.value,`${e}.value`,n)};if(f(t,o.IsReference))return{kind:"is-reference",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsEmbedded))return{kind:"is-embedded",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsList))return{kind:"is-list",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsString))return{kind:"is-string",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsNumber))return{kind:"is-number",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsBoolean))return{kind:"is-boolean",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.StatementObject))return{kind:"statement-object",source:d(t,o.statementSource,`${e}.statementSource`,n)};if(f(t,o.Let))return{kind:"let",bindName:V(t,o.letName,e),bindValue:d(t,o.letValue,`${e}.letValue`,n),body:d(t,o.letBody,`${e}.letBody`,n)};if(f(t,o.GetStatementByName))return{kind:"get-statement-by-name",inSubject:d(t,o.inSubject,`${e}.inSubject`,n),byName:d(t,o.byName,`${e}.byName`,n)};throw new g("Expression is not of a recognized v3 type \u2014 embedded has no matching subclass of tx.Expression",e)}function d(t,e,n,r){let a=oe(t,e);if(!a)throw new g("child expression is required",n);return G(a,n,r)}function Qt(t,e,n,r){let a=oe(t,e);if(a)return G(a,n,r)}function Se(t,e,n,r){let a=[],i=0;for(let u of A(t,e))if(u instanceof S)for(let c of u.object)c instanceof C&&a.push(G(c,`${n}[${i++}]`,r));else u instanceof T&&a.push(G(u.object,`${n}[${i++}]`,r));return a}function xt(t,e,n){let r=[],a=0;for(let i of A(t,o.set))if(i instanceof S)for(let u of i.object)u instanceof C&&r.push(Je(u,`${e}[${a++}]`,n));else i instanceof T&&r.push(Je(i.object,`${e}[${a++}]`,n));return r}function Je(t,e,n){return{field:q(t,o.field,e,"field"),value:d(t,o.bindValue,`${e}.bindValue`,n)}}function en(t,e){let n=_(t,o.normKind);if(!n)throw new g("normKind is required",e);if(E(n,o.NORM_TRIM_END))return"trim-end";throw new g(`Unknown NormalizeKind: ${n.publisher}/${n.package_}/${n.name}`,e)}function tn(t,e){let n=_(t,o.renderFormat);if(!n)throw new g("renderFormat is required",e);if(E(n,o.RENDER_HTML))return"html";if(E(n,o.RENDER_MARKDOWN))return"markdown";throw new g(`Unknown RenderFormat: ${n.publisher}/${n.package_}/${n.name}`,e)}var Xe=new Set(["iso-date","iso-datetime","short-date","long-date","year","month-year"]);function nn(t,e){let n=z(t,o.dateFormat);if(!n)throw new g("dateFormat is required",e);if(!Xe.has(n))throw new g(`Unknown dateFormat "${n}"; supported: ${[...Xe].join(", ")}`,e);return n}function rn(t,e,n){let r=_(t,o.fragmentRef);if(!r)throw new g("fragmentRef is required",e);if(!sn(n.catalog,r))throw new g(`ExpressionFragment not found: ${r.publisher}/${r.package_}/${r.name}`,e);return{kind:"call-fragment",fragmentKey:an(r)}}function an(t){return`${t.publisher}/${t.package_}/${t.name}`}function on(t){let e=new Map,n=[];for(let r of t){if(!(r instanceof w)||!f(r,o.ExpressionFragment))continue;let a=oe(r,o.body);if(!a)continue;let i=(r.namespace||"").split("@")[0]||"",u=i.indexOf("/");if(u<0)continue;let c=i.substring(0,u),l=i.substring(u+1),p=`${c}/${l}/${r.name}`;n.push({key:p,subject:r,bodyEmb:a,pubPkgName:`${i}/${r.name}`})}for(let r of n){let a=G(r.bodyEmb,`fragment(${r.pubPkgName})`,{catalog:t,depth:0});e.set(r.key,a)}return e}function sn(t,e){for(let n of t)if(!(!(n instanceof w)||n.name!==e.name||!(n.namespace||"").startsWith(`${e.publisher}/${e.package_}@`))&&f(n,o.ExpressionFragment))return n}function xe(t,e){let n=new Set;for(let r of A(t,o.outputs))if(r instanceof j)n.add(r.object.subject.name);else if(r instanceof S)for(let a of r.object)a instanceof b&&n.add(a.subject.name);if(n.size===0)throw new g("outputs is required (at least one OutputFormat)",e);return n}function et(t,e,n){let r=new Map,a=0;for(let i of A(t,o.formatOverrides))if(i instanceof S){for(let u of i.object)if(u instanceof C){let[c,l]=Ye(u,`${e}[${a++}]`);r.set(c,l)}}else if(i instanceof T){let[u,c]=Ye(i.object,`${e}[${a++}]`);r.set(u,c)}return r}function Ye(t,e){let n=_(t,o.formatTarget);if(!n)throw new g("formatTarget is required",e);let r=[];for(let c of A(t,o.metadataKeys))if(c instanceof L)r.push(c.object);else if(c instanceof S)for(let l of c.object){let p=l.value;typeof p=="string"&&r.push(p)}let a=new Map;for(let c of A(t,o.metadataRenames))if(c instanceof S){for(let l of c.object)if(l instanceof C){let p=z(l,o.fromKey),y=z(l,o.toKey);p&&y&&a.set(p,y)}}else if(c instanceof T){let l=c.object,p=z(l,o.fromKey),y=z(l,o.toKey);p&&y&&a.set(p,y)}let i=Ee(t,o.trailingNewline),u=Ee(t,o.omitWrapper);return[n.name,{metadataKeys:r.length>0?r:void 0,metadataRenames:a,trailingNewline:i,omitWrapper:u}]}function un(t){return t.predicate?.subject}function A(t,e){let n=[];for(let r of t.statement){let a=un(r);a&&E(a,e)&&n.push(r)}return n}function oe(t,e){for(let n of A(t,e))if(n instanceof T)return n.object}function _(t,e){for(let n of A(t,e))if(n instanceof j)return ve(n.object.subject)}function z(t,e){for(let n of A(t,e))if(n instanceof L)return n.object}function tt(t,e){for(let n of A(t,e))if(n instanceof U)return n.object}function Ee(t,e){for(let n of A(t,e))if(n instanceof O)return n.object}function V(t,e,n){let r=z(t,e);if(r===void 0)throw new g(`${e.name} (string) is required`,n);return r}function Ze(t,e,n){let r=tt(t,e);if(r===void 0)throw new g(`${e.name} (number) is required`,n);return r}function cn(t,e,n){let r=Ee(t,e);if(r===void 0)throw new g(`${e.name} (boolean) is required`,n);return r}function q(t,e,n,r){let a=_(t,e);if(!a)throw new g(`${r} (URI reference) is required`,n);return a}function ve(t){return{publisher:t.publisher,package_:t.package_,name:t.name}}var dn={publisher:"kanonak.org",package_:"core-rdf",name:"label"},I=class extends Error{},pe=class{constructor(e,n,r=new Map){this.resolver=e;this.catalog=n;this.fragments=r}resolver;catalog;fragments;async evaluate(e,n){switch(e.kind){case"string-literal":return e.value;case"integer-literal":return e.value;case"decimal-literal":return e.value;case"boolean-literal":return e.value;case"uri-literal":return{...e.refTo};case"var-ref":{if(!n.has(e.varName))throw new I(`Unbound variable "${e.varName}"`);return n.get(e.varName)}case"concat":{let r=[];for(let a of e.parts){let i=await this.evaluate(a,n);if(i!=null)if(Array.isArray(i))for(let u of i)r.push(u);else r.push(i)}return r}case"fallback":{let r=await this.evaluate(e.primary,n);return nt(r)?r:this.evaluate(e.alternate,n)}case"when":return await this.evaluate(e.condition,n)===!0?this.evaluate(e.thenBuild,n):e.elseBuild?this.evaluate(e.elseBuild,n):void 0;case"is-set":{let r=await this.evaluate(e.check,n);return nt(r)}case"property-read":{let r=await this.evaluate(e.source,n);return me(r,e.readProp)}case"traverse":{let r=await this.evaluate(e.source,n);if(!(r instanceof K))return;let a=fn(r,e.through),i=[];for(let u of a){let c=await this.resolver.resolveSubject(u,this.catalog);if(!c)continue;let l=new Map(n);l.set("input",c);let p=await this.evaluate(e.step,l);p!=null&&i.push(se(p))}return i.join("")}case"uri-name":{let r=await this.evaluate(e.source,n);return J(r)?r.name:r instanceof b?r.subject.name:r instanceof w?r.name:r instanceof C?r.name??"":void 0}case"uri-publisher":{let r=await this.evaluate(e.source,n);return $e(r)?.publisher}case"uri-package":{let r=await this.evaluate(e.source,n);return $e(r)?.package_}case"uri-version":{let r=await this.evaluate(e.source,n);return $e(r)?.version}case"subject-uri":{let r=await this.evaluate(e.source,n);if(r instanceof w){let a=r.namespace??"",i=r.name??"";return!a||!i?void 0:`${a}/${i}`}if(r instanceof b){let a=r.subject,i=a.version;return i&&typeof i.major=="number"?`${a.publisher}/${a.package_}@${i.major}.${i.minor}.${i.patch}/${a.name}`:`${a.publisher}/${a.package_}/${a.name}`}return}case"display-label":{let r=await this.resolver.resolveSubject({...e.labelTarget},this.catalog);return r?me(r,e.labelSource):void 0}case"resolve-ref":{let r=await this.evaluate(e.source,n);return r instanceof w?r:r instanceof b?await this.resolver.resolveSubject(r.subject,this.catalog):J(r)?await this.resolver.resolveSubject(r,this.catalog):void 0}case"normalize":{let r=await this.evaluate(e.source,n),a=r==null?"":se(r);return e.normKind==="trim-end"?a.replace(/[\s\r\n]+$/u,""):a}case"render-markdown":{let r=await this.evaluate(e.source,n);if(!(r instanceof K))return;let a;for(let u of r.statement){let c=je(u);if(c&&E(c,e.readProp)){a=u;break}}if(!(a instanceof Re)){let u=me(r,e.readProp);return u==null?void 0:se(u)}let i=await this.renderMarkdownLinks(a);return e.format==="html"?X(i):i}case"build-ast-node":{let r={kind:e.astClass.name};for(let a of e.set){let i=await this.evaluate(a.value,n);if(i==null||Array.isArray(i)&&i.length===0)continue;let u=a.field.name;pn.has(u)&&(Array.isArray(i)&&i.every(c=>rt(c))?i=i.map(c=>String(c)).join(""):rt(i)&&(i=String(i))),r[u]=i}return r}case"call-fragment":{let r=this.fragments.get(e.fragmentKey);if(!r)throw new I(`ExpressionFragment ${e.fragmentKey} not found in registry`);return this.evaluate(r,n)}case"join":return(await this.evaluateList(e.source,n)).map(a=>a==null?"":se(a)).join(e.separator);case"count":return(await this.evaluateList(e.source,n)).length;case"sum":{let r=await this.evaluateList(e.source,n),a=0;for(let i of r)a+=v(i,"Sum");return a}case"min":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new I("Min on an empty list is undefined; guard with IsSet");let a=v(r[0],"Min");for(let i=1;i<r.length;i++){let u=v(r[i],"Min");u<a&&(a=u)}return a}case"max":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new I("Max on an empty list is undefined; guard with IsSet");let a=v(r[0],"Max");for(let i=1;i<r.length;i++){let u=v(r[i],"Max");u>a&&(a=u)}return a}case"average":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new I("Average on an empty list is undefined; guard with IsSet");let a=0;for(let i of r)a+=v(i,"Average");return a/r.length}case"for-each":{let r=await this.evaluateList(e.source,n),a=[];for(let i of r){let u=new Map(n);u.set(e.loopVar,B(i));let c=await this.evaluate(e.emit,u);if(c!=null)if(Array.isArray(c))for(let l of c)a.push(l);else a.push(c)}return a}case"list-map":{let r=await this.evaluateList(e.source,n),a=[];for(let i of r){let u=new Map(n);u.set(e.loopVar,B(i)),a.push(await this.evaluate(e.mapBody,u))}return a}case"filter":{let r=await this.evaluateList(e.source,n),a=[];for(let i of r){let u=new Map(n);u.set(e.loopVar,B(i)),await this.evaluate(e.predicate,u)===!0&&a.push(i)}return a}case"partition-by":{let r=await this.evaluateList(e.source,n),a=new Map,i=[];for(let u of r){let c=new Map(n);c.set(e.loopVar,B(u));let l=await this.evaluate(e.partitionKey,c),p=ot(l),y=a.get(p);y||(y={kind:"Partition",key:l,members:[]},a.set(p,y),i.push(p)),y.members.push(u)}return i.map(u=>a.get(u))}case"distinct-by":{let r=await this.evaluateList(e.source,n),a=new Set,i=[];for(let u of r){let c=new Map(n);c.set(e.loopVar,B(u));let l=await this.evaluate(e.distinctKey,c),p=ot(l);a.has(p)||(a.add(p),i.push(u))}return i}case"all-statements":{let r=await this.evaluate(e.source,n);return r instanceof K?r.statement:[]}case"statement-predicate":{let r=await this.evaluate(e.source,n);if(Ve(r)){let a=r.predicate;if(a instanceof b)return a}return}case"statement-value":{let r=await this.evaluate(e.source,n);return Ve(r)?kn(r):void 0}case"date-format":{let r=await this.evaluate(e.source,n),a=r==null?"":se(r);return a?yn(a,e.format):""}case"add":{let r=v(await this.evaluate(e.left,n),"Add"),a=v(await this.evaluate(e.right,n),"Add");return r+a}case"subtract":{let r=v(await this.evaluate(e.left,n),"Subtract"),a=v(await this.evaluate(e.right,n),"Subtract");return r-a}case"multiply":{let r=v(await this.evaluate(e.left,n),"Multiply"),a=v(await this.evaluate(e.right,n),"Multiply");return r*a}case"divide":{let r=v(await this.evaluate(e.left,n),"Divide"),a=v(await this.evaluate(e.right,n),"Divide");if(a===0)throw new I("Divide by zero; guard with When");return r/a}case"reverse":{if(e.source.kind==="reverse")return this.evaluate(e.source.source,n);let r=await this.evaluateReverseIterator(e.source,n);return r!==void 0?r:[...await this.evaluateList(e.source,n)].reverse()}case"windowed-map":{let r=await this.evaluateList(e.source,n);if(r.length<e.windowSize)return[];let a=[];for(let i=0;i+e.windowSize<=r.length;i++){let u=r.slice(i,i+e.windowSize),c=new Map(n);c.set(e.windowVar,u);let l=await this.evaluate(e.windowBody,c);if(l!=null)if(Array.isArray(l))for(let p of l)a.push(p);else a.push(l)}return a}case"pairwise-map":{let r=await this.evaluateList(e.source,n);if(r.length<2)return[];let a=[];for(let i=0;i+1<r.length;i++){let u=new Map(n);u.set(e.firstVar,B(r[i])),u.set(e.secondVar,B(r[i+1]));let c=await this.evaluate(e.pairBody,u);if(c!=null)if(Array.isArray(c))for(let l of c)a.push(l);else a.push(c)}return a}case"scan":{let r=await this.evaluateList(e.source,n);if(r.length===0)return[];let a=await this.evaluate(e.initialState,n),i=[];for(let u of r){let c=new Map(n);c.set(e.stateVar,a),c.set(e.elementVar,B(u));let l=await this.evaluate(e.accumulate,c);i.push(l),a=l}return i}case"list-item-at":{let r=await this.evaluateList(e.source,n),a=await this.evaluate(e.itemIndex,n);return typeof a!="number"||!Number.isInteger(a)||a<0||a>=r.length?void 0:r[a]}case"equals":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return at(r,a)}case"greater-than":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return typeof r!="number"||typeof a!="number"?!1:r>a}case"less-than":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return typeof r!="number"||typeof a!="number"?!1:r<a}case"greater-than-or-equal":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return typeof r!="number"||typeof a!="number"?!1:r>=a}case"less-than-or-equal":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return typeof r!="number"||typeof a!="number"?!1:r<=a}case"not":{let r=await this.evaluate(e.operand,n);return r===!0?!1:r===!1?!0:void 0}case"and":{for(let r of e.operands)if(await this.evaluate(r,n)!==!0)return!1;return!0}case"or":{for(let r of e.operands)if(await this.evaluate(r,n)===!0)return!0;return!1}case"contains":{let r=await this.evaluateList(e.haystack,n),a=await this.evaluate(e.needle,n);for(let i of r)if(at(i,a))return!0;return!1}case"abs":{let r=v(await this.evaluate(e.value,n),"Abs");return Math.abs(r)}case"negate":return-v(await this.evaluate(e.value,n),"Negate");case"is-reference":{let r=await this.evaluate(e.check,n);return r instanceof b||r instanceof w}case"is-embedded":return await this.evaluate(e.check,n)instanceof C;case"is-list":{let r=await this.evaluate(e.check,n);return Array.isArray(r)}case"is-string":return typeof await this.evaluate(e.check,n)=="string";case"is-number":return typeof await this.evaluate(e.check,n)=="number";case"is-boolean":return typeof await this.evaluate(e.check,n)=="boolean";case"statement-object":{let r=await this.evaluate(e.source,n);if(!Ve(r))return;let a=r;return a instanceof L||a instanceof U||a instanceof O||a instanceof j||a instanceof T||a instanceof S?a.object:void 0}case"let":{let r=await this.evaluate(e.bindValue,n),a=new Map(n);return a.set(e.bindName,r),this.evaluate(e.body,a)}case"get-statement-by-name":{let r=await this.evaluate(e.inSubject,n),a=await this.evaluate(e.byName,n);if(!(r instanceof K)||typeof a!="string")return;for(let i of r.statement)if(i.predicate?.subject?.name===a)return i;return}default:{let r=e;throw new I("Unknown expression kind")}}}async renderMarkdownLinks(e){let n=e.object,r="",a=0;for(let i of e.links){if(r+=n.slice(a,i.startOffset),i.target){let u=i.target.subject,c=i.displayText??await this.resolveLabel(u)??u.name;r+=`[${c}](${F(u)})`}else r+=i.displayText??i.reference;a=i.endOffset}return r+=n.slice(a),r}async resolveLabel(e){let n=await this.resolver.resolveSubject(e,this.catalog);if(!n)return;let r=me(n,dn);return typeof r=="string"?r:void 0}async evaluateList(e,n){let r=await this.evaluate(e,n);return r==null?[]:Array.isArray(r)?r:[r]}async evaluateReverseIterator(e,n){if(e.kind==="pairwise-map"){let r=await this.evaluateList(e.source,n);if(r.length<2)return[];let a=[];for(let i=r.length-1;i>=1;i--){let u=new Map(n);u.set(e.firstVar,B(r[i-1])),u.set(e.secondVar,B(r[i]));let c=await this.evaluate(e.pairBody,u);if(c!=null)if(Array.isArray(c))for(let l of c)a.push(l);else a.push(c)}return a}if(e.kind==="for-each"){let r=await this.evaluateList(e.source,n),a=[];for(let i=r.length-1;i>=0;i--){let u=new Map(n);u.set(e.loopVar,B(r[i]));let c=await this.evaluate(e.emit,u);if(c!=null)if(Array.isArray(c))for(let l of c)a.push(l);else a.push(c)}return a}if(e.kind==="list-map"){let r=await this.evaluateList(e.source,n),a=[];for(let i=r.length-1;i>=0;i--){let u=new Map(n);u.set(e.loopVar,B(r[i])),a.push(await this.evaluate(e.mapBody,u))}return a}if(e.kind==="windowed-map"){let r=await this.evaluateList(e.source,n);if(r.length<e.windowSize)return[];let a=[];for(let i=r.length-e.windowSize;i>=0;i--){let u=r.slice(i,i+e.windowSize),c=new Map(n);c.set(e.windowVar,u);let l=await this.evaluate(e.windowBody,c);if(l!=null)if(Array.isArray(l))for(let p of l)a.push(p);else a.push(l)}return a}}};function me(t,e){if(t instanceof K)return ln(t,e);if(mn(t))return E(e,o.key)?t.key:E(e,o.members)?t.members:void 0}function ln(t,e){for(let n of t.statement){let r=je(n);if(!(!r||!E(r,e))&&(n instanceof L||n instanceof U||n instanceof O||n instanceof j||n instanceof T||n instanceof S))return n.object}}function fn(t,e){let n=[];for(let r of t.statement){let a=je(r);if(!(!a||!E(a,e))){if(r instanceof j)n.push(r.object.subject);else if(r instanceof S)for(let i of r.object)i instanceof b&&n.push(i.subject)}}return n}function je(t){return t.predicate?.subject}function se(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(t instanceof K)return t.name??"";if(t instanceof b)return t.subject.name;if(J(t))return t.name;let e=t.value;return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function B(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof K)&&!(t instanceof b)&&!(t instanceof C)&&"value"in t?t.value:t}function nt(t){return t==null?!1:typeof t=="string"||Array.isArray(t)?t.length>0:typeof t=="boolean"?t===!0:!0}function J(t){return typeof t=="object"&&t!==null&&typeof t.publisher=="string"&&typeof t.package_=="string"&&typeof t.name=="string"}function mn(t){return typeof t=="object"&&t!==null&&t.kind==="Partition"&&Array.isArray(t.members)}function v(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;throw new I(`${e} requires numeric elements; got ${gn(t)}`)}function $e(t){if(t instanceof w){let e=t.namespace??"",n=e.indexOf("/"),r=e.indexOf("@",n+1);return n<0||r<0?void 0:{publisher:e.substring(0,n),package_:e.substring(n+1,r),version:e.substring(r+1),name:t.name??""}}if(t instanceof b){let e=t.subject,n=e.version;return{publisher:e.publisher,package_:e.package_,version:n&&typeof n.major=="number"?`${n.major}.${n.minor}.${n.patch}`:"",name:e.name}}if(J(t))return{publisher:t.publisher,package_:t.package_,version:"",name:t.name}}var pn=new Set(["stringValue","text","rawContent","key","propertyKey","linkLabel"]);function rt(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function gn(t){return t===void 0?"undefined":t===null?"null":Array.isArray(t)?`array(${t.length})`:typeof t}function yn(t,e){let n=new Date(t);if(isNaN(n.getTime()))return"";let r=n.getUTCFullYear(),a=["January","February","March","April","May","June","July","August","September","October","November","December"][n.getUTCMonth()],i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n.getUTCMonth()],u=n.getUTCDate(),c=(l,p=2)=>String(l).padStart(p,"0");switch(e){case"iso-date":return`${r}-${c(n.getUTCMonth()+1)}-${c(u)}`;case"iso-datetime":return`${r}-${c(n.getUTCMonth()+1)}-${c(u)}T${c(n.getUTCHours())}:${c(n.getUTCMinutes())}:${c(n.getUTCSeconds())}Z`;case"short-date":return`${i} ${u}`;case"long-date":return`${a} ${u}, ${r}`;case"year":return String(r);case"month-year":return`${a} ${r}`}}function at(t,e){if(t==null||e===void 0||e===null)return!1;if(t===e)return!0;let n=typeof t=="object"&&"value"in t?t.value:void 0,r=typeof e=="object"&&"value"in e?e.value:void 0,a=n??t,i=r??e,u=it(t),c=it(e);return u&&c?u.publisher===c.publisher&&u.package_===c.package_&&u.name===c.name:typeof a=="string"&&typeof i=="string"||typeof a=="number"&&typeof i=="number"||typeof a=="boolean"&&typeof i=="boolean"?a===i:!1}function it(t){if(t instanceof b){let e=t.subject;return{publisher:e.publisher,package_:e.package_,name:e.name}}if(t instanceof w){let e=t.namespace??"",n=e.indexOf("/"),r=e.indexOf("@",n+1);if(n<0)return;let a=e.substring(0,n),i=r>=0?e.substring(n+1,r):e.substring(n+1);return{publisher:a,package_:i,name:t.name??""}}if(J(t))return{publisher:t.publisher,package_:t.package_,name:t.name}}function Ve(t){return t instanceof L||t instanceof U||t instanceof O||t instanceof j||t instanceof T||t instanceof S}function kn(t){return t instanceof L||t instanceof U||t instanceof O?String(t.object??""):t instanceof j?t.object?.subject?.name??"":t instanceof T?"[embedded]":t instanceof S?(t.object??[]).map(n=>{if(n instanceof b)return n.subject.name;let r=n.name;if(r&&r.length>0)return r;let a=n.value;return typeof a=="string"||typeof a=="number"||typeof a=="boolean"?String(a):"[embedded]"}).join(", "):""}function ot(t){if(t===void 0)return"\0undef";if(t===null)return"\0null";if(typeof t=="string")return`s:${t}`;if(typeof t=="number")return`n:${t}`;if(typeof t=="boolean")return`b:${t}`;if(t instanceof b){let e=t.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(t instanceof K){let e=t.name??"";return`k:${t.namespace??""}/${e}`}return J(t)?`u:${t.publisher}/${t.package_}/${t.name}`:`o:${JSON.stringify(t)}`}var hn={"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"}},W=class extends Error{},ge=class{backends=new Map;constructor(){this.register(new Y),this.register(new Z),this.register(new Q),this.register(new x),this.register(new ee),this.register(new te),this.register(new ne),this.register(new ae)}register(e){this.backends.set(e.backendUri,e)}async run(e){let n=e.transformationKanonaks??e.allKanonaks,r=fe(e.transformation,n);if(!r.outputs.has(e.outputFormat))throw new W(`Transformation "${r.name}" does not declare output format "${e.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let a=this.findBackend(e.outputFormat);if(!a)throw new W(`No backend registered for OutputFormat "${e.outputFormat}".`);let i=new ie(e.repository,e.parser,e.objectParser),u=new pe(i,e.allKanonaks,r.fragments);return r.kind==="instance"?this.runInstance(r,e,a,u):this.runSet(r,e,a,u)}async runInstance(e,n,r,a){let i=st(n.instances,e.inputPattern.requires),u=ut(i,e.inputPattern.sortBy),c=[];for(let l of u){let p=new Map;p.set("input",l);let y=await a.evaluate(e.rule,p);Ae(y,e.name,`input "${l.name}"`);let h=De(await a.evaluate(e.artifactName,p),e.name,`input "${l.name}"`),D=Ke(e.overrides.get(n.outputFormat),n.runtimeOverride),$=r.render(y,D);c.push({fileName:h,format:n.outputFormat,content:$,source:{kind:"instance",sourceName:l.name}})}return c}async runSet(e,n,r,a){let i=st(n.instances,e.inputPattern.requires),u=ut(i,e.inputPattern.sortBy);return e.partitionBy?this.runSetWithPartition(e,u,n,r,a):this.runSetSingle(e,u,n,r,a)}async runSetSingle(e,n,r,a,i){let u=new Map;u.set("inputs",n);let c=await i.evaluate(e.rule,u);Ae(c,e.name,"set");let l=De(await i.evaluate(e.artifactName,u),e.name,"set"),p=Ke(e.overrides.get(r.outputFormat),r.runtimeOverride),y=a.render(c,p);return[{fileName:l,format:r.outputFormat,content:y,source:{kind:"set",memberCount:n.length}}]}async runSetWithPartition(e,n,r,a,i){let u=e.partitionBy,c=new Map,l=[];for(let y of n){let h=Sn(y,u);if(h==null)continue;let D=En(h),$=c.get(D);$||($={keyValue:h,keyDisplay:vn(h),members:[]},c.set(D,$),l.push(D)),$.members.push(y)}let p=[];for(let y of l){let h=c.get(y),D=new Map;D.set("inputs",h.members),D.set("key",h.keyValue);let $=await i.evaluate(e.rule,D);Ae($,e.name,`partition "${h.keyDisplay}"`);let ft=De(await i.evaluate(e.artifactName,D),e.name,`partition "${h.keyDisplay}"`),mt=Ke(e.overrides.get(r.outputFormat),r.runtimeOverride),pt=a.render($,mt);p.push({fileName:ft,format:r.outputFormat,content:pt,source:{kind:"set",memberCount:h.members.length,partitionKey:h.keyDisplay}})}return p}findBackend(e){let n=hn[e];if(n)return this.backends.get(n.formatUri)}};function st(t,e){return e.length===0?t:t.filter(n=>{for(let r of e)if(!wn(n,r))return!1;return!0})}function ut(t,e){if(e.length===0)return t;let n=[...t];return n.sort((r,a)=>{for(let i of e){let u=ct(r,i.byProperty),c=ct(a,i.byProperty),l=bn(u,c,i.order);if(l!==0)return l}return 0}),n}function ct(t,e){for(let n of t.statement){let r=Te(n);if(!(!r||!E(r,e))){if(n instanceof L||n instanceof U||n instanceof O)return n.object;if(n instanceof S)throw new W(`Sort property "${e.name}" on instance "${t.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(n instanceof j)throw new W(`Sort property "${e.name}" on instance "${t.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function bn(t,e,n){if(t===void 0&&e===void 0)return 0;if(t===void 0)return n==="ascending"?1:-1;if(e===void 0)return n==="ascending"?-1:1;let r;return typeof t=="number"&&typeof e=="number"?r=t-e:r=String(t).localeCompare(String(e)),n==="ascending"?r:-r}function wn(t,e){for(let n of t.statement){let r=Te(n);if(!r||!E(r,e))continue;let a=n.object;if(a!=null&&!(typeof a=="string"&&a.length===0)&&!(Array.isArray(a)&&a.length===0))return!0}return!1}function Sn(t,e){for(let n of t.statement){let r=Te(n);if(!(!r||!E(r,e))&&(n instanceof L||n instanceof U||n instanceof O||n instanceof j||n instanceof S))return n.object}}function Te(t){return t.predicate?.subject}function En(t){if(t===void 0)return" undef";if(t===null)return" null";if(typeof t=="string")return`s:${t}`;if(typeof t=="number")return`n:${t}`;if(typeof t=="boolean")return`b:${t}`;if(t instanceof b){let e=t.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(t instanceof K){let e=t.name??"";return`k:${t.namespace??""}/${e}`}if(typeof t=="object"&&t!==null&&typeof t.name=="string"&&typeof t.publisher=="string"){let e=t;return`u:${e.publisher}/${e.package_}/${e.name}`}return`o:${JSON.stringify(t)}`}function vn(t){return t==null?"":typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):t instanceof b?t.subject.name:t instanceof K?t.name??"":typeof t=="object"&&t!==null&&typeof t.name=="string"?t.name:""}function Ae(t,e,n){if(typeof t!="object"||t===null||t.kind!=="Document")throw new W(`Transformation "${e}" rule did not yield a Document for ${n}. Got: ${dt(t)}`)}function De(t,e,n){if(typeof t=="string")return t;if(Array.isArray(t)&&t.every($n))return t.map(r=>String(r)).join("");throw new W(`Transformation "${e}" artifactName did not yield a string for ${n}. Got: ${dt(t)}`)}function $n(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function dt(t){if(t===void 0)return"undefined";if(t===null)return"null";if(Array.isArray(t))return`array(${t.length})`;if(typeof t=="object"){let e=t.kind;return e?`object(kind=${e})`:"object"}return typeof t}function Ke(t,e){if(!t&&!e)return;let n={metadataRenames:e?.metadataRenames??t?.metadataRenames??new Map},r=e?.metadataKeys??t?.metadataKeys;r!==void 0&&(n.metadataKeys=r);let a=e?.trailingNewline??t?.trailingNewline;a!==void 0&&(n.trailingNewline=a);let i=e?.omitWrapper??t?.omitWrapper;return i!==void 0&&(n.omitWrapper=i),n}var R=class extends Error{constructor(n,r){super(n);this.cause=r;this.name="RenderError"}cause},lt={publisher:"kanonak.org",package_:"derivation",name:"default"},Be=class{constructor(e,n=new Le,r=new Ce){this.repository=e;this.parser=n;this.objectParser=r}repository;parser;objectParser;runner=new ge;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async renderViaLook(e){let n=await this.getCatalog(),r=M(n,e.resource);if(!(r instanceof w))throw new R(`Resource not found: ${P(e.resource)}`);let a=new ye(n),i;if(e.format.name==="html")i=a.renderHtml(r);else if(e.format.name==="stylesheet")i=a.renderStylesheet(r);else throw new R(`LookRenderer does not support format ${P(e.format)} \u2014 only formats.html and formats.stylesheet are implemented in v0.1.`);return{content:i,format:e.format,filename:r.name}}async findDerivation(e){let n=await this.getCatalog(),r=M(n,e.resource);if(!(r instanceof w))return;let a=e.variant??lt;return Oe(r,e.format,a,n)}async render(e){if(e.format.name==="html"||e.format.name==="stylesheet"){let a=await this.getCatalog(),i=M(a,e.resource);if(i instanceof w){let c=new ye(a).findCascadedLook(i);if(c&&!jn(c.sourceClass)){let l=await this.findDerivation(e);if(!l||Vn(l))return this.renderViaLook({resource:e.resource,format:e.format})}}}let n=await this.findDerivation(e);if(!n)throw new R(`No derivation found for ${P(e.resource)} \u2192 format ${P(e.format)}`+(e.variant?` variant ${P(e.variant)}`:""));let r={transformation:{publisher:n.transformation.publisher,package_:n.transformation.package_,name:n.transformation.name},input:e.resource,format:e.format};return e.omitWrapper!==void 0&&(r.omitWrapper=e.omitWrapper),this.runTransformation(r)}async runTransformation(e){let n=await this.getCatalog(),r=M(n,e.transformation);if(!(r instanceof w))throw new R(`Transformation not found: ${P(e.transformation)}`);let a=M(n,e.input);if(!(a instanceof w))throw new R(`Input resource not found: ${P(e.input)}`);let i=fe(r,n),u=An(i.outputs,e.format);if(!u)throw new R(`Transformation ${P(e.transformation)} declares outputs [${[...i.outputs].join(", ")}], none of which corresponds to format ${P(e.format)}`);let c;try{c=await this.runner.run({transformation:r,instances:[a],allKanonaks:n,repository:this.repository,parser:this.parser,objectParser:this.objectParser,outputFormat:u,...e.omitWrapper!==void 0?{runtimeOverride:{metadataRenames:new Map,omitWrapper:e.omitWrapper}}:{}})}catch(l){throw new R(`Transformation execution failed: ${l.message}`,l)}if(c.length===0)throw new R("Transformation produced no artifacts");return{content:c[0].content,format:e.format,filename:c[0].fileName}}async getCatalog(){return this.cachedCatalog||(this.cachedCatalog=await this.objectParser.parseKanonaks(this.repository)),this.cachedCatalog}};function P(t){return`${t.publisher}/${t.package_}/${t.name}`}function Vn(t){return typeof t.source=="string"?!1:t.source.publisher==="kanonak.org"&&t.source.package_==="core-rdf"&&t.source.name==="Resource"}function jn(t){return t.publisher==="kanonak.org"&&t.package_==="core-rdf"&&t.name==="Resource"}function An(t,e){let n=e.name;if(t.has(n))return n;for(let r of t)if(r.startsWith(n+"-")||r===n)return r}export{te as CssBackend,lt as DEFAULT_VARIANT,k as DOCAST,yt as DOCAST_PKG,gt as DOCAST_PUB,ae as DynamoDbBackend,pe as ExpressionEngineV3,I as ExpressionEvalErrorV3,x as HtmlBackend,Q as JsonBackend,Y as MarkdownFrontmatterBackend,ie as ReferenceResolver,R as RenderError,hn as SUPPORTED_FORMATS_V3,ee as SvgBackend,o as TX_V3,Jt as TX_V3_PKG,Gt as TX_V3_PUB,Zn as TX_V3_VERSION_MAJOR,Z as TomlBackend,Be as TransformationEngine,g as TransformationLoadErrorV3,W as TransformationRunnerErrorV3,ge as TransformationRunnerV3,ne as YamlBackend,fe as compileTransformationV3,X as renderMarkdownToHtml};
91
+ `),a}};function ze(t,e){let n=new Map;for(let i of t.entries)n.set(i.key,i);let r=e?.metadataKeys??t.entries.map(i=>i.key),a={};for(let i of r){let u=n.get(i);if(!u)continue;let c=e?.metadataRenames.get(i)??i;a[c]=Ge(u.value,u.escapeHint)}return{M:a}}function Ge(t,e){switch(t.kind){case"StructuredMap":return ze(t);case"StructuredList":return{L:t.items.map(n=>Ge(n,void 0))};case"StringScalar":return zt(t.stringValue,e??t.escapeHint);case"IntegerScalar":return Gt(t.integerValue,e??t.escapeHint)}}function zt(t,e){if(e&&re(e,k.ESC_DYNAMODB_BOOL)){if(t==="true")return{BOOL:!0};if(t==="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(t)}.`)}if(e&&re(e,k.ESC_DYNAMODB_NULL))return{NULL:!0};if(e&&re(e,k.ESC_DYNAMODB_NUMBER)){if(t.trim()===""||Number.isNaN(Number(t)))throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-number must hold a numeric literal; got ${JSON.stringify(t)}.`);return{N:t}}return{S:t}}function Gt(t,e){if(e&&re(e,k.ESC_DYNAMODB_BOOL))throw new Error(`dynamodb-json backend: esc-dynamodb-bool cannot apply to an IntegerScalar (value ${t}). Use a StringScalar "true"/"false".`);if(e&&re(e,k.ESC_DYNAMODB_NULL))throw new Error(`dynamodb-json backend: esc-dynamodb-null cannot apply to an IntegerScalar (value ${t}). Use a StringScalar hinted esc-dynamodb-null.`);return{N:String(t)}}var ie=class{constructor(e,n,r){this.repository=e;this.parser=n;this.objectParser=r}repository;parser;objectParser;cache=new Map;async resolveSubject(e,n){let r=M(n,e);if(r)return r;let a=e.version,i=a&&typeof a.major=="number"?`@${a.major}.${a.minor}.${a.patch}`:"",u=`${e.publisher}/${e.package_}${i}`,c=this.cache.get(u);if(!c){let p=await this.repository.getDocumentsByNamespaceAsync(e.publisher,e.package_);if(p.length===0)return;let y=a&&typeof a.major=="number"?p.find(D=>{let $=D.metadata?.namespace_?.version;return $&&$.major===a.major&&$.minor===a.minor&&$.patch===a.patch})??p[0]:p[0],h=new Oe(y,this.repository);c=await this.objectParser.parseKanonaks(h),this.cache.set(u,c)}let l=M(c,e);if(l)return l;for(let p of c)if(p instanceof w&&p.name===e.name)return p}};var Jt="kanonak.org",Xt="transformations",Qn=3,s=t=>({publisher:Jt,package_:Xt,name:t}),o={Transformation:s("Transformation"),InstanceTransformation:s("InstanceTransformation"),SetTransformation:s("SetTransformation"),inputPattern:s("inputPattern"),rule:s("rule"),artifactName:s("artifactName"),outputs:s("outputs"),formatOverrides:s("formatOverrides"),partitionBy:s("partitionBy"),InputPattern:s("InputPattern"),matchesClass:s("matchesClass"),requires:s("requires"),sortBy:s("sortBy"),SortKey:s("SortKey"),byProperty:s("byProperty"),order:s("order"),SortOrder:s("SortOrder"),ascending:s("ascending"),descending:s("descending"),OutputFormat:s("OutputFormat"),backendUri:s("backendUri"),FormatOverride:s("FormatOverride"),formatTarget:s("formatTarget"),metadataKeys:s("metadataKeys"),metadataRenames:s("metadataRenames"),trailingNewline:s("trailingNewline"),omitWrapper:s("omitWrapper"),RenameEntry:s("RenameEntry"),fromKey:s("fromKey"),toKey:s("toKey"),FMT_MARKDOWN_FRONTMATTER:s("markdown-with-frontmatter"),FMT_PLAIN_MARKDOWN:s("plain-markdown"),FMT_TOML:s("toml"),FMT_JSON:s("json"),FMT_HTML:s("html"),FMT_SVG:s("svg"),Expression:s("Expression"),ListSourcedExpression:s("ListSourcedExpression"),ListAggregate:s("ListAggregate"),IteratingExpression:s("IteratingExpression"),BuildAstNode:s("BuildAstNode"),astClass:s("astClass"),set:s("set"),AstFieldBinding:s("AstFieldBinding"),field:s("field"),bindValue:s("bindValue"),When:s("When"),condition:s("condition"),thenBuild:s("thenBuild"),elseBuild:s("elseBuild"),Concat:s("Concat"),parts:s("parts"),Fallback:s("Fallback"),primary:s("primary"),alternate:s("alternate"),StringLiteral:s("StringLiteral"),stringLiteral:s("stringLiteral"),IntegerLiteral:s("IntegerLiteral"),integerLiteral:s("integerLiteral"),DecimalLiteral:s("DecimalLiteral"),decimalLiteral:s("decimalLiteral"),BooleanLiteral:s("BooleanLiteral"),booleanLiteral:s("booleanLiteral"),VarRef:s("VarRef"),varName:s("varName"),PropertyRead:s("PropertyRead"),readSource:s("readSource"),readProp:s("readProp"),Traverse:s("Traverse"),traverseSource:s("traverseSource"),through:s("through"),step:s("step"),UriName:s("UriName"),uriNameOf:s("uriNameOf"),UriPublisher:s("UriPublisher"),uriPublisherOf:s("uriPublisherOf"),UriPackage:s("UriPackage"),uriPackageOf:s("uriPackageOf"),UriVersion:s("UriVersion"),uriVersionOf:s("uriVersionOf"),SubjectUri:s("SubjectUri"),subjectOf:s("subjectOf"),UriLiteral:s("UriLiteral"),refTo:s("refTo"),DisplayLabel:s("DisplayLabel"),labelTarget:s("labelTarget"),labelSource:s("labelSource"),ResolveRef:s("ResolveRef"),resolveSource:s("resolveSource"),Normalize:s("Normalize"),normSource:s("normSource"),normKind:s("normKind"),NormalizeKind:s("NormalizeKind"),NORM_TRIM_END:s("trim-end"),IsSet:s("IsSet"),checkExpr:s("checkExpr"),ExpressionFragment:s("ExpressionFragment"),body:s("body"),CallFragment:s("CallFragment"),fragmentRef:s("fragmentRef"),source:s("source"),Join:s("Join"),separator:s("separator"),Count:s("Count"),Sum:s("Sum"),Min:s("Min"),Max:s("Max"),Average:s("Average"),loopVar:s("loopVar"),ForEach:s("ForEach"),emit:s("emit"),ListMap:s("ListMap"),mapBody:s("mapBody"),Filter:s("Filter"),predicate:s("predicate"),PartitionBy:s("PartitionBy"),partitionKey:s("partitionKey"),DistinctBy:s("DistinctBy"),distinctKey:s("distinctKey"),Partition:s("Partition"),key:s("key"),members:s("members"),AllStatements:s("AllStatements"),statementsOf:s("statementsOf"),StatementPredicate:s("StatementPredicate"),predicateOf:s("predicateOf"),StatementValue:s("StatementValue"),valueOf:s("valueOf"),DateFormat:s("DateFormat"),dateSource:s("dateSource"),dateFormat:s("dateFormat"),BinaryArithmetic:s("BinaryArithmetic"),arithLeft:s("arithLeft"),arithRight:s("arithRight"),Add:s("Add"),Subtract:s("Subtract"),Multiply:s("Multiply"),Divide:s("Divide"),Reverse:s("Reverse"),WindowedMap:s("WindowedMap"),windowSize:s("windowSize"),windowVar:s("windowVar"),windowBody:s("windowBody"),PairwiseMap:s("PairwiseMap"),firstVar:s("firstVar"),secondVar:s("secondVar"),pairBody:s("pairBody"),Scan:s("Scan"),initialState:s("initialState"),stateVar:s("stateVar"),elementVar:s("elementVar"),accumulate:s("accumulate"),ListItemAt:s("ListItemAt"),itemIndex:s("itemIndex"),BinaryComparison:s("BinaryComparison"),compareLeft:s("compareLeft"),compareRight:s("compareRight"),Equals:s("Equals"),GreaterThan:s("GreaterThan"),LessThan:s("LessThan"),GreaterThanOrEqual:s("GreaterThanOrEqual"),LessThanOrEqual:s("LessThanOrEqual"),Not:s("Not"),operand:s("operand"),BooleanLogic:s("BooleanLogic"),operands:s("operands"),And:s("And"),Or:s("Or"),Contains:s("Contains"),haystack:s("haystack"),needle:s("needle"),UnaryNumericOp:s("UnaryNumericOp"),value:s("value"),Abs:s("Abs"),Negate:s("Negate"),KindPredicate:s("KindPredicate"),IsReference:s("IsReference"),IsEmbedded:s("IsEmbedded"),IsList:s("IsList"),kindCheck:s("kindCheck"),IsString:s("IsString"),IsNumber:s("IsNumber"),IsBoolean:s("IsBoolean"),StatementObject:s("StatementObject"),statementSource:s("statementSource"),Let:s("Let"),letName:s("letName"),letValue:s("letValue"),letBody:s("letBody"),GetStatementByName:s("GetStatementByName"),inSubject:s("inSubject"),byName:s("byName"),RenderMarkdown:s("RenderMarkdown"),renderSource:s("renderSource"),renderProp:s("renderProp"),renderFormat:s("renderFormat"),RenderFormat:s("RenderFormat"),RENDER_HTML:s("render-html"),RENDER_MARKDOWN:s("render-markdown")};var g=class extends Error{constructor(n,r){super(`${n} (at ${r})`);this.path=r}path};function fe(t,e){let n=t.name,r=sn(e),a={catalog:e,depth:0};if(f(t,o.InstanceTransformation))return Yt(t,n,a,r);if(f(t,o.SetTransformation))return Zt(t,n,a,r);throw new g("Subject is not a recognized v3 transformation type \u2014 expected InstanceTransformation or SetTransformation",n)}function Yt(t,e,n,r){return{kind:"instance",name:t.name,inputPattern:xe(t,e),rule:le(t,o.rule,`${e}.rule`,n),artifactName:le(t,o.artifactName,`${e}.artifactName`,n),outputs:et(t,`${e}.outputs`),overrides:tt(t,`${e}.formatOverrides`,n),fragments:r}}function Zt(t,e,n,r){let a=_(t,o.partitionBy);return{kind:"set",name:t.name,inputPattern:xe(t,e),rule:le(t,o.rule,`${e}.rule`,n),artifactName:le(t,o.artifactName,`${e}.artifactName`,n),outputs:et(t,`${e}.outputs`),overrides:tt(t,`${e}.formatOverrides`,n),partitionBy:a,fragments:r}}function xe(t,e){let n=oe(t,o.inputPattern);if(!n)throw new g("inputPattern is required",e);return Qt(n,`${e}.inputPattern`)}function Qt(t,e){let n=_(t,o.matchesClass);if(!n)throw new g("matchesClass is required",e);let r=[];for(let u of A(t,o.requires))if(u instanceof j)r.push(ve(u.object.subject));else if(u instanceof S)for(let c of u.object)c instanceof b&&r.push(ve(c.subject));let a=[],i=0;for(let u of A(t,o.sortBy))if(u instanceof S)for(let c of u.object)c instanceof C&&a.push(Je(c,`${e}.sortBy[${i++}]`));else u instanceof T&&a.push(Je(u.object,`${e}.sortBy[${i++}]`));return{matchesClass:n,requires:r,sortBy:a}}function Je(t,e){let n=_(t,o.byProperty);if(!n)throw new g("SortKey.byProperty is required",e);let r=_(t,o.order);if(!r)throw new g("SortKey.order is required",e);if(E(r,o.ascending))return{byProperty:n,order:"ascending"};if(E(r,o.descending))return{byProperty:n,order:"descending"};throw new g(`SortKey.order must reference tx.ascending or tx.descending; got ${r.publisher}/${r.package_}/${r.name}`,e)}function le(t,e,n,r){let a=oe(t,e);if(!a)throw new g("expression is required",n);return G(a,n,r)}function G(t,e,n){if(f(t,o.StringLiteral))return{kind:"string-literal",value:V(t,o.stringLiteral,e)};if(f(t,o.IntegerLiteral))return{kind:"integer-literal",value:Qe(t,o.integerLiteral,e)};if(f(t,o.DecimalLiteral))return{kind:"decimal-literal",value:Qe(t,o.decimalLiteral,e)};if(f(t,o.BooleanLiteral))return{kind:"boolean-literal",value:dn(t,o.booleanLiteral,e)};if(f(t,o.VarRef))return{kind:"var-ref",varName:V(t,o.varName,e)};if(f(t,o.PropertyRead))return{kind:"property-read",source:d(t,o.readSource,`${e}.readSource`,n),readProp:q(t,o.readProp,e,"readProp")};if(f(t,o.Traverse))return{kind:"traverse",source:d(t,o.traverseSource,`${e}.traverseSource`,n),through:q(t,o.through,e,"through"),step:d(t,o.step,`${e}.step`,n)};if(f(t,o.BuildAstNode))return{kind:"build-ast-node",astClass:q(t,o.astClass,e,"astClass"),set:en(t,`${e}.set`,n)};if(f(t,o.When))return{kind:"when",condition:d(t,o.condition,`${e}.condition`,n),thenBuild:d(t,o.thenBuild,`${e}.thenBuild`,n),elseBuild:xt(t,o.elseBuild,`${e}.elseBuild`,n)};if(f(t,o.Concat))return{kind:"concat",parts:Se(t,o.parts,`${e}.parts`,n)};if(f(t,o.Fallback))return{kind:"fallback",primary:d(t,o.primary,`${e}.primary`,n),alternate:d(t,o.alternate,`${e}.alternate`,n)};if(f(t,o.UriName))return{kind:"uri-name",source:d(t,o.uriNameOf,`${e}.uriNameOf`,n)};if(f(t,o.UriPublisher))return{kind:"uri-publisher",source:d(t,o.uriPublisherOf,`${e}.uriPublisherOf`,n)};if(f(t,o.UriPackage))return{kind:"uri-package",source:d(t,o.uriPackageOf,`${e}.uriPackageOf`,n)};if(f(t,o.UriVersion))return{kind:"uri-version",source:d(t,o.uriVersionOf,`${e}.uriVersionOf`,n)};if(f(t,o.SubjectUri))return{kind:"subject-uri",source:d(t,o.subjectOf,`${e}.subjectOf`,n)};if(f(t,o.UriLiteral))return{kind:"uri-literal",refTo:q(t,o.refTo,e,"refTo")};if(f(t,o.DisplayLabel))return{kind:"display-label",labelTarget:q(t,o.labelTarget,e,"labelTarget"),labelSource:q(t,o.labelSource,e,"labelSource")};if(f(t,o.ResolveRef))return{kind:"resolve-ref",source:d(t,o.resolveSource,`${e}.resolveSource`,n)};if(f(t,o.Normalize))return{kind:"normalize",source:d(t,o.normSource,`${e}.normSource`,n),normKind:tn(t,e)};if(f(t,o.RenderMarkdown))return{kind:"render-markdown",source:d(t,o.renderSource,`${e}.renderSource`,n),readProp:q(t,o.renderProp,e,"renderProp"),format:nn(t,e)};if(f(t,o.IsSet))return{kind:"is-set",check:d(t,o.checkExpr,`${e}.checkExpr`,n)};if(f(t,o.CallFragment))return an(t,e,n);if(f(t,o.Join))return{kind:"join",source:d(t,o.source,`${e}.source`,n),separator:V(t,o.separator,e)};if(f(t,o.Count))return{kind:"count",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.Sum))return{kind:"sum",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.Min))return{kind:"min",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.Max))return{kind:"max",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.Average))return{kind:"average",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.ForEach))return{kind:"for-each",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),emit:d(t,o.emit,`${e}.emit`,n)};if(f(t,o.ListMap))return{kind:"list-map",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),mapBody:d(t,o.mapBody,`${e}.mapBody`,n)};if(f(t,o.Filter))return{kind:"filter",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),predicate:d(t,o.predicate,`${e}.predicate`,n)};if(f(t,o.PartitionBy))return{kind:"partition-by",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),partitionKey:d(t,o.partitionKey,`${e}.partitionKey`,n)};if(f(t,o.DistinctBy))return{kind:"distinct-by",source:d(t,o.source,`${e}.source`,n),loopVar:V(t,o.loopVar,e),distinctKey:d(t,o.distinctKey,`${e}.distinctKey`,n)};if(f(t,o.AllStatements))return{kind:"all-statements",source:d(t,o.statementsOf,`${e}.statementsOf`,n)};if(f(t,o.StatementPredicate))return{kind:"statement-predicate",source:d(t,o.predicateOf,`${e}.predicateOf`,n)};if(f(t,o.StatementValue))return{kind:"statement-value",source:d(t,o.valueOf,`${e}.valueOf`,n)};if(f(t,o.DateFormat))return{kind:"date-format",source:d(t,o.dateSource,`${e}.dateSource`,n),format:rn(t,e)};if(f(t,o.Add))return{kind:"add",left:d(t,o.arithLeft,`${e}.arithLeft`,n),right:d(t,o.arithRight,`${e}.arithRight`,n)};if(f(t,o.Subtract))return{kind:"subtract",left:d(t,o.arithLeft,`${e}.arithLeft`,n),right:d(t,o.arithRight,`${e}.arithRight`,n)};if(f(t,o.Multiply))return{kind:"multiply",left:d(t,o.arithLeft,`${e}.arithLeft`,n),right:d(t,o.arithRight,`${e}.arithRight`,n)};if(f(t,o.Divide))return{kind:"divide",left:d(t,o.arithLeft,`${e}.arithLeft`,n),right:d(t,o.arithRight,`${e}.arithRight`,n)};if(f(t,o.Reverse))return{kind:"reverse",source:d(t,o.source,`${e}.source`,n)};if(f(t,o.WindowedMap)){let r=nt(t,o.windowSize);if(r===void 0||!Number.isInteger(r)||r<1)throw new g("windowSize must be a positive integer",`${e}.windowSize`);return{kind:"windowed-map",source:d(t,o.source,`${e}.source`,n),windowSize:r,windowVar:V(t,o.windowVar,e),windowBody:d(t,o.windowBody,`${e}.windowBody`,n)}}if(f(t,o.PairwiseMap))return{kind:"pairwise-map",source:d(t,o.source,`${e}.source`,n),firstVar:V(t,o.firstVar,e),secondVar:V(t,o.secondVar,e),pairBody:d(t,o.pairBody,`${e}.pairBody`,n)};if(f(t,o.Scan))return{kind:"scan",source:d(t,o.source,`${e}.source`,n),initialState:d(t,o.initialState,`${e}.initialState`,n),stateVar:V(t,o.stateVar,e),elementVar:V(t,o.elementVar,e),accumulate:d(t,o.accumulate,`${e}.accumulate`,n)};if(f(t,o.ListItemAt))return{kind:"list-item-at",source:d(t,o.source,`${e}.source`,n),itemIndex:d(t,o.itemIndex,`${e}.itemIndex`,n)};if(f(t,o.Equals))return{kind:"equals",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.GreaterThan))return{kind:"greater-than",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.LessThan))return{kind:"less-than",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.GreaterThanOrEqual))return{kind:"greater-than-or-equal",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.LessThanOrEqual))return{kind:"less-than-or-equal",left:d(t,o.compareLeft,`${e}.compareLeft`,n),right:d(t,o.compareRight,`${e}.compareRight`,n)};if(f(t,o.Not))return{kind:"not",operand:d(t,o.operand,`${e}.operand`,n)};if(f(t,o.And))return{kind:"and",operands:Se(t,o.operands,`${e}.operands`,n)};if(f(t,o.Or))return{kind:"or",operands:Se(t,o.operands,`${e}.operands`,n)};if(f(t,o.Contains))return{kind:"contains",haystack:d(t,o.haystack,`${e}.haystack`,n),needle:d(t,o.needle,`${e}.needle`,n)};if(f(t,o.Abs))return{kind:"abs",value:d(t,o.value,`${e}.value`,n)};if(f(t,o.Negate))return{kind:"negate",value:d(t,o.value,`${e}.value`,n)};if(f(t,o.IsReference))return{kind:"is-reference",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsEmbedded))return{kind:"is-embedded",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsList))return{kind:"is-list",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsString))return{kind:"is-string",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsNumber))return{kind:"is-number",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.IsBoolean))return{kind:"is-boolean",check:d(t,o.kindCheck,`${e}.kindCheck`,n)};if(f(t,o.StatementObject))return{kind:"statement-object",source:d(t,o.statementSource,`${e}.statementSource`,n)};if(f(t,o.Let))return{kind:"let",bindName:V(t,o.letName,e),bindValue:d(t,o.letValue,`${e}.letValue`,n),body:d(t,o.letBody,`${e}.letBody`,n)};if(f(t,o.GetStatementByName))return{kind:"get-statement-by-name",inSubject:d(t,o.inSubject,`${e}.inSubject`,n),byName:d(t,o.byName,`${e}.byName`,n)};throw new g("Expression is not of a recognized v3 type \u2014 embedded has no matching subclass of tx.Expression",e)}function d(t,e,n,r){let a=oe(t,e);if(!a)throw new g("child expression is required",n);return G(a,n,r)}function xt(t,e,n,r){let a=oe(t,e);if(a)return G(a,n,r)}function Se(t,e,n,r){let a=[],i=0;for(let u of A(t,e))if(u instanceof S)for(let c of u.object)c instanceof C&&a.push(G(c,`${n}[${i++}]`,r));else u instanceof T&&a.push(G(u.object,`${n}[${i++}]`,r));return a}function en(t,e,n){let r=[],a=0;for(let i of A(t,o.set))if(i instanceof S)for(let u of i.object)u instanceof C&&r.push(Xe(u,`${e}[${a++}]`,n));else i instanceof T&&r.push(Xe(i.object,`${e}[${a++}]`,n));return r}function Xe(t,e,n){return{field:q(t,o.field,e,"field"),value:d(t,o.bindValue,`${e}.bindValue`,n)}}function tn(t,e){let n=_(t,o.normKind);if(!n)throw new g("normKind is required",e);if(E(n,o.NORM_TRIM_END))return"trim-end";throw new g(`Unknown NormalizeKind: ${n.publisher}/${n.package_}/${n.name}`,e)}function nn(t,e){let n=_(t,o.renderFormat);if(!n)throw new g("renderFormat is required",e);if(E(n,o.RENDER_HTML))return"html";if(E(n,o.RENDER_MARKDOWN))return"markdown";throw new g(`Unknown RenderFormat: ${n.publisher}/${n.package_}/${n.name}`,e)}var Ye=new Set(["iso-date","iso-datetime","short-date","long-date","year","month-year"]);function rn(t,e){let n=z(t,o.dateFormat);if(!n)throw new g("dateFormat is required",e);if(!Ye.has(n))throw new g(`Unknown dateFormat "${n}"; supported: ${[...Ye].join(", ")}`,e);return n}function an(t,e,n){let r=_(t,o.fragmentRef);if(!r)throw new g("fragmentRef is required",e);if(!un(n.catalog,r))throw new g(`ExpressionFragment not found: ${r.publisher}/${r.package_}/${r.name}`,e);return{kind:"call-fragment",fragmentKey:on(r)}}function on(t){return`${t.publisher}/${t.package_}/${t.name}`}function sn(t){let e=new Map,n=[];for(let r of t){if(!(r instanceof w)||!f(r,o.ExpressionFragment))continue;let a=oe(r,o.body);if(!a)continue;let i=(r.namespace||"").split("@")[0]||"",u=i.indexOf("/");if(u<0)continue;let c=i.substring(0,u),l=i.substring(u+1),p=`${c}/${l}/${r.name}`;n.push({key:p,subject:r,bodyEmb:a,pubPkgName:`${i}/${r.name}`})}for(let r of n){let a=G(r.bodyEmb,`fragment(${r.pubPkgName})`,{catalog:t,depth:0});e.set(r.key,a)}return e}function un(t,e){for(let n of t)if(!(!(n instanceof w)||n.name!==e.name||!(n.namespace||"").startsWith(`${e.publisher}/${e.package_}@`))&&f(n,o.ExpressionFragment))return n}function et(t,e){let n=new Set;for(let r of A(t,o.outputs))if(r instanceof j)n.add(r.object.subject.name);else if(r instanceof S)for(let a of r.object)a instanceof b&&n.add(a.subject.name);if(n.size===0)throw new g("outputs is required (at least one OutputFormat)",e);return n}function tt(t,e,n){let r=new Map,a=0;for(let i of A(t,o.formatOverrides))if(i instanceof S){for(let u of i.object)if(u instanceof C){let[c,l]=Ze(u,`${e}[${a++}]`);r.set(c,l)}}else if(i instanceof T){let[u,c]=Ze(i.object,`${e}[${a++}]`);r.set(u,c)}return r}function Ze(t,e){let n=_(t,o.formatTarget);if(!n)throw new g("formatTarget is required",e);let r=[];for(let c of A(t,o.metadataKeys))if(c instanceof L)r.push(c.object);else if(c instanceof S)for(let l of c.object){let p=l.value;typeof p=="string"&&r.push(p)}let a=new Map;for(let c of A(t,o.metadataRenames))if(c instanceof S){for(let l of c.object)if(l instanceof C){let p=z(l,o.fromKey),y=z(l,o.toKey);p&&y&&a.set(p,y)}}else if(c instanceof T){let l=c.object,p=z(l,o.fromKey),y=z(l,o.toKey);p&&y&&a.set(p,y)}let i=Ee(t,o.trailingNewline),u=Ee(t,o.omitWrapper);return[n.name,{metadataKeys:r.length>0?r:void 0,metadataRenames:a,trailingNewline:i,omitWrapper:u}]}function cn(t){return t.predicate?.subject}function A(t,e){let n=[];for(let r of t.statement){let a=cn(r);a&&E(a,e)&&n.push(r)}return n}function oe(t,e){for(let n of A(t,e))if(n instanceof T)return n.object}function _(t,e){for(let n of A(t,e))if(n instanceof j)return ve(n.object.subject)}function z(t,e){for(let n of A(t,e))if(n instanceof L)return n.object}function nt(t,e){for(let n of A(t,e))if(n instanceof U)return n.object}function Ee(t,e){for(let n of A(t,e))if(n instanceof O)return n.object}function V(t,e,n){let r=z(t,e);if(r===void 0)throw new g(`${e.name} (string) is required`,n);return r}function Qe(t,e,n){let r=nt(t,e);if(r===void 0)throw new g(`${e.name} (number) is required`,n);return r}function dn(t,e,n){let r=Ee(t,e);if(r===void 0)throw new g(`${e.name} (boolean) is required`,n);return r}function q(t,e,n,r){let a=_(t,e);if(!a)throw new g(`${r} (URI reference) is required`,n);return a}function ve(t){return{publisher:t.publisher,package_:t.package_,name:t.name}}var ln={publisher:"kanonak.org",package_:"core-rdf",name:"label"},I=class extends Error{},pe=class{constructor(e,n,r=new Map){this.resolver=e;this.catalog=n;this.fragments=r}resolver;catalog;fragments;async evaluate(e,n){switch(e.kind){case"string-literal":return e.value;case"integer-literal":return e.value;case"decimal-literal":return e.value;case"boolean-literal":return e.value;case"uri-literal":return{...e.refTo};case"var-ref":{if(!n.has(e.varName))throw new I(`Unbound variable "${e.varName}"`);return n.get(e.varName)}case"concat":{let r=[];for(let a of e.parts){let i=await this.evaluate(a,n);if(i!=null)if(Array.isArray(i))for(let u of i)r.push(u);else r.push(i)}return r}case"fallback":{let r=await this.evaluate(e.primary,n);return rt(r)?r:this.evaluate(e.alternate,n)}case"when":return await this.evaluate(e.condition,n)===!0?this.evaluate(e.thenBuild,n):e.elseBuild?this.evaluate(e.elseBuild,n):void 0;case"is-set":{let r=await this.evaluate(e.check,n);return rt(r)}case"property-read":{let r=await this.evaluate(e.source,n);return me(r,e.readProp)}case"traverse":{let r=await this.evaluate(e.source,n);if(!(r instanceof K))return;let a=mn(r,e.through),i=[];for(let u of a){let c=await this.resolver.resolveSubject(u,this.catalog);if(!c)continue;let l=new Map(n);l.set("input",c);let p=await this.evaluate(e.step,l);p!=null&&i.push(se(p))}return i.join("")}case"uri-name":{let r=await this.evaluate(e.source,n);return J(r)?r.name:r instanceof b?r.subject.name:r instanceof w?r.name:r instanceof C?r.name??"":void 0}case"uri-publisher":{let r=await this.evaluate(e.source,n);return $e(r)?.publisher}case"uri-package":{let r=await this.evaluate(e.source,n);return $e(r)?.package_}case"uri-version":{let r=await this.evaluate(e.source,n);return $e(r)?.version}case"subject-uri":{let r=await this.evaluate(e.source,n);if(r instanceof w){let a=r.namespace??"",i=r.name??"";return!a||!i?void 0:`${a}/${i}`}if(r instanceof b){let a=r.subject,i=a.version;return i&&typeof i.major=="number"?`${a.publisher}/${a.package_}@${i.major}.${i.minor}.${i.patch}/${a.name}`:`${a.publisher}/${a.package_}/${a.name}`}return}case"display-label":{let r=await this.resolver.resolveSubject({...e.labelTarget},this.catalog);return r?me(r,e.labelSource):void 0}case"resolve-ref":{let r=await this.evaluate(e.source,n);return r instanceof w?r:r instanceof b?await this.resolver.resolveSubject(r.subject,this.catalog):J(r)?await this.resolver.resolveSubject(r,this.catalog):void 0}case"normalize":{let r=await this.evaluate(e.source,n),a=r==null?"":se(r);return e.normKind==="trim-end"?a.replace(/[\s\r\n]+$/u,""):a}case"render-markdown":{let r=await this.evaluate(e.source,n);if(!(r instanceof K))return;let a;for(let u of r.statement){let c=je(u);if(c&&E(c,e.readProp)){a=u;break}}if(!(a instanceof Ce)){let u=me(r,e.readProp);return u==null?void 0:se(u)}let i=await this.renderMarkdownLinks(a);return e.format==="html"?X(i):i}case"build-ast-node":{let r={kind:e.astClass.name};for(let a of e.set){let i=await this.evaluate(a.value,n);if(i==null||Array.isArray(i)&&i.length===0)continue;let u=a.field.name;gn.has(u)&&(Array.isArray(i)&&i.every(c=>at(c))?i=i.map(c=>String(c)).join(""):at(i)&&(i=String(i))),r[u]=i}return r}case"call-fragment":{let r=this.fragments.get(e.fragmentKey);if(!r)throw new I(`ExpressionFragment ${e.fragmentKey} not found in registry`);return this.evaluate(r,n)}case"join":return(await this.evaluateList(e.source,n)).map(a=>a==null?"":se(a)).join(e.separator);case"count":return(await this.evaluateList(e.source,n)).length;case"sum":{let r=await this.evaluateList(e.source,n),a=0;for(let i of r)a+=v(i,"Sum");return a}case"min":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new I("Min on an empty list is undefined; guard with IsSet");let a=v(r[0],"Min");for(let i=1;i<r.length;i++){let u=v(r[i],"Min");u<a&&(a=u)}return a}case"max":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new I("Max on an empty list is undefined; guard with IsSet");let a=v(r[0],"Max");for(let i=1;i<r.length;i++){let u=v(r[i],"Max");u>a&&(a=u)}return a}case"average":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new I("Average on an empty list is undefined; guard with IsSet");let a=0;for(let i of r)a+=v(i,"Average");return a/r.length}case"for-each":{let r=await this.evaluateList(e.source,n),a=[];for(let i of r){let u=new Map(n);u.set(e.loopVar,B(i));let c=await this.evaluate(e.emit,u);if(c!=null)if(Array.isArray(c))for(let l of c)a.push(l);else a.push(c)}return a}case"list-map":{let r=await this.evaluateList(e.source,n),a=[];for(let i of r){let u=new Map(n);u.set(e.loopVar,B(i)),a.push(await this.evaluate(e.mapBody,u))}return a}case"filter":{let r=await this.evaluateList(e.source,n),a=[];for(let i of r){let u=new Map(n);u.set(e.loopVar,B(i)),await this.evaluate(e.predicate,u)===!0&&a.push(i)}return a}case"partition-by":{let r=await this.evaluateList(e.source,n),a=new Map,i=[];for(let u of r){let c=new Map(n);c.set(e.loopVar,B(u));let l=await this.evaluate(e.partitionKey,c),p=st(l),y=a.get(p);y||(y={kind:"Partition",key:l,members:[]},a.set(p,y),i.push(p)),y.members.push(u)}return i.map(u=>a.get(u))}case"distinct-by":{let r=await this.evaluateList(e.source,n),a=new Set,i=[];for(let u of r){let c=new Map(n);c.set(e.loopVar,B(u));let l=await this.evaluate(e.distinctKey,c),p=st(l);a.has(p)||(a.add(p),i.push(u))}return i}case"all-statements":{let r=await this.evaluate(e.source,n);return r instanceof K?r.statement:[]}case"statement-predicate":{let r=await this.evaluate(e.source,n);if(Ve(r)){let a=r.predicate;if(a instanceof b)return a}return}case"statement-value":{let r=await this.evaluate(e.source,n);return Ve(r)?hn(r):void 0}case"date-format":{let r=await this.evaluate(e.source,n),a=r==null?"":se(r);return a?kn(a,e.format):""}case"add":{let r=v(await this.evaluate(e.left,n),"Add"),a=v(await this.evaluate(e.right,n),"Add");return r+a}case"subtract":{let r=v(await this.evaluate(e.left,n),"Subtract"),a=v(await this.evaluate(e.right,n),"Subtract");return r-a}case"multiply":{let r=v(await this.evaluate(e.left,n),"Multiply"),a=v(await this.evaluate(e.right,n),"Multiply");return r*a}case"divide":{let r=v(await this.evaluate(e.left,n),"Divide"),a=v(await this.evaluate(e.right,n),"Divide");if(a===0)throw new I("Divide by zero; guard with When");return r/a}case"reverse":{if(e.source.kind==="reverse")return this.evaluate(e.source.source,n);let r=await this.evaluateReverseIterator(e.source,n);return r!==void 0?r:[...await this.evaluateList(e.source,n)].reverse()}case"windowed-map":{let r=await this.evaluateList(e.source,n);if(r.length<e.windowSize)return[];let a=[];for(let i=0;i+e.windowSize<=r.length;i++){let u=r.slice(i,i+e.windowSize),c=new Map(n);c.set(e.windowVar,u);let l=await this.evaluate(e.windowBody,c);if(l!=null)if(Array.isArray(l))for(let p of l)a.push(p);else a.push(l)}return a}case"pairwise-map":{let r=await this.evaluateList(e.source,n);if(r.length<2)return[];let a=[];for(let i=0;i+1<r.length;i++){let u=new Map(n);u.set(e.firstVar,B(r[i])),u.set(e.secondVar,B(r[i+1]));let c=await this.evaluate(e.pairBody,u);if(c!=null)if(Array.isArray(c))for(let l of c)a.push(l);else a.push(c)}return a}case"scan":{let r=await this.evaluateList(e.source,n);if(r.length===0)return[];let a=await this.evaluate(e.initialState,n),i=[];for(let u of r){let c=new Map(n);c.set(e.stateVar,a),c.set(e.elementVar,B(u));let l=await this.evaluate(e.accumulate,c);i.push(l),a=l}return i}case"list-item-at":{let r=await this.evaluateList(e.source,n),a=await this.evaluate(e.itemIndex,n);return typeof a!="number"||!Number.isInteger(a)||a<0||a>=r.length?void 0:r[a]}case"equals":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return it(r,a)}case"greater-than":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return typeof r!="number"||typeof a!="number"?!1:r>a}case"less-than":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return typeof r!="number"||typeof a!="number"?!1:r<a}case"greater-than-or-equal":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return typeof r!="number"||typeof a!="number"?!1:r>=a}case"less-than-or-equal":{let r=await this.evaluate(e.left,n),a=await this.evaluate(e.right,n);return typeof r!="number"||typeof a!="number"?!1:r<=a}case"not":{let r=await this.evaluate(e.operand,n);return r===!0?!1:r===!1?!0:void 0}case"and":{for(let r of e.operands)if(await this.evaluate(r,n)!==!0)return!1;return!0}case"or":{for(let r of e.operands)if(await this.evaluate(r,n)===!0)return!0;return!1}case"contains":{let r=await this.evaluateList(e.haystack,n),a=await this.evaluate(e.needle,n);for(let i of r)if(it(i,a))return!0;return!1}case"abs":{let r=v(await this.evaluate(e.value,n),"Abs");return Math.abs(r)}case"negate":return-v(await this.evaluate(e.value,n),"Negate");case"is-reference":{let r=await this.evaluate(e.check,n);return r instanceof b||r instanceof w}case"is-embedded":return await this.evaluate(e.check,n)instanceof C;case"is-list":{let r=await this.evaluate(e.check,n);return Array.isArray(r)}case"is-string":return typeof await this.evaluate(e.check,n)=="string";case"is-number":return typeof await this.evaluate(e.check,n)=="number";case"is-boolean":return typeof await this.evaluate(e.check,n)=="boolean";case"statement-object":{let r=await this.evaluate(e.source,n);if(!Ve(r))return;let a=r;return a instanceof L||a instanceof U||a instanceof O||a instanceof j||a instanceof T||a instanceof S?a.object:void 0}case"let":{let r=await this.evaluate(e.bindValue,n),a=new Map(n);return a.set(e.bindName,r),this.evaluate(e.body,a)}case"get-statement-by-name":{let r=await this.evaluate(e.inSubject,n),a=await this.evaluate(e.byName,n);if(!(r instanceof K)||typeof a!="string")return;for(let i of r.statement)if(i.predicate?.subject?.name===a)return i;return}default:{let r=e;throw new I("Unknown expression kind")}}}async renderMarkdownLinks(e){let n=e.object,r="",a=0;for(let i of e.links){if(r+=n.slice(a,i.startOffset),i.target){let u=i.target.subject,c=i.displayText??await this.resolveLabel(u)??u.name;r+=`[${c}](${F(u)})`}else r+=i.displayText??i.reference;a=i.endOffset}return r+=n.slice(a),r}async resolveLabel(e){let n=await this.resolver.resolveSubject(e,this.catalog);if(!n)return;let r=me(n,ln);return typeof r=="string"?r:void 0}async evaluateList(e,n){let r=await this.evaluate(e,n);return r==null?[]:Array.isArray(r)?r:[r]}async evaluateReverseIterator(e,n){if(e.kind==="pairwise-map"){let r=await this.evaluateList(e.source,n);if(r.length<2)return[];let a=[];for(let i=r.length-1;i>=1;i--){let u=new Map(n);u.set(e.firstVar,B(r[i-1])),u.set(e.secondVar,B(r[i]));let c=await this.evaluate(e.pairBody,u);if(c!=null)if(Array.isArray(c))for(let l of c)a.push(l);else a.push(c)}return a}if(e.kind==="for-each"){let r=await this.evaluateList(e.source,n),a=[];for(let i=r.length-1;i>=0;i--){let u=new Map(n);u.set(e.loopVar,B(r[i]));let c=await this.evaluate(e.emit,u);if(c!=null)if(Array.isArray(c))for(let l of c)a.push(l);else a.push(c)}return a}if(e.kind==="list-map"){let r=await this.evaluateList(e.source,n),a=[];for(let i=r.length-1;i>=0;i--){let u=new Map(n);u.set(e.loopVar,B(r[i])),a.push(await this.evaluate(e.mapBody,u))}return a}if(e.kind==="windowed-map"){let r=await this.evaluateList(e.source,n);if(r.length<e.windowSize)return[];let a=[];for(let i=r.length-e.windowSize;i>=0;i--){let u=r.slice(i,i+e.windowSize),c=new Map(n);c.set(e.windowVar,u);let l=await this.evaluate(e.windowBody,c);if(l!=null)if(Array.isArray(l))for(let p of l)a.push(p);else a.push(l)}return a}}};function me(t,e){if(t instanceof K)return fn(t,e);if(pn(t))return E(e,o.key)?t.key:E(e,o.members)?t.members:void 0}function fn(t,e){for(let n of t.statement){let r=je(n);if(!(!r||!E(r,e))&&(n instanceof L||n instanceof U||n instanceof O||n instanceof j||n instanceof T||n instanceof S))return n.object}}function mn(t,e){let n=[];for(let r of t.statement){let a=je(r);if(!(!a||!E(a,e))){if(r instanceof j)n.push(r.object.subject);else if(r instanceof S)for(let i of r.object)i instanceof b&&n.push(i.subject)}}return n}function je(t){return t.predicate?.subject}function se(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(t instanceof K)return t.name??"";if(t instanceof b)return t.subject.name;if(J(t))return t.name;let e=t.value;return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function B(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof K)&&!(t instanceof b)&&!(t instanceof C)&&"value"in t?t.value:t}function rt(t){return t==null?!1:typeof t=="string"||Array.isArray(t)?t.length>0:typeof t=="boolean"?t===!0:!0}function J(t){return typeof t=="object"&&t!==null&&typeof t.publisher=="string"&&typeof t.package_=="string"&&typeof t.name=="string"}function pn(t){return typeof t=="object"&&t!==null&&t.kind==="Partition"&&Array.isArray(t.members)}function v(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;throw new I(`${e} requires numeric elements; got ${yn(t)}`)}function $e(t){if(t instanceof w){let e=t.namespace??"",n=e.indexOf("/"),r=e.indexOf("@",n+1);return n<0||r<0?void 0:{publisher:e.substring(0,n),package_:e.substring(n+1,r),version:e.substring(r+1),name:t.name??""}}if(t instanceof b){let e=t.subject,n=e.version;return{publisher:e.publisher,package_:e.package_,version:n&&typeof n.major=="number"?`${n.major}.${n.minor}.${n.patch}`:"",name:e.name}}if(J(t))return{publisher:t.publisher,package_:t.package_,version:"",name:t.name}}var gn=new Set(["stringValue","text","rawContent","key","propertyKey","linkLabel"]);function at(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function yn(t){return t===void 0?"undefined":t===null?"null":Array.isArray(t)?`array(${t.length})`:typeof t}function kn(t,e){let n=new Date(t);if(isNaN(n.getTime()))return"";let r=n.getUTCFullYear(),a=["January","February","March","April","May","June","July","August","September","October","November","December"][n.getUTCMonth()],i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n.getUTCMonth()],u=n.getUTCDate(),c=(l,p=2)=>String(l).padStart(p,"0");switch(e){case"iso-date":return`${r}-${c(n.getUTCMonth()+1)}-${c(u)}`;case"iso-datetime":return`${r}-${c(n.getUTCMonth()+1)}-${c(u)}T${c(n.getUTCHours())}:${c(n.getUTCMinutes())}:${c(n.getUTCSeconds())}Z`;case"short-date":return`${i} ${u}`;case"long-date":return`${a} ${u}, ${r}`;case"year":return String(r);case"month-year":return`${a} ${r}`}}function it(t,e){if(t==null||e===void 0||e===null)return!1;if(t===e)return!0;let n=typeof t=="object"&&"value"in t?t.value:void 0,r=typeof e=="object"&&"value"in e?e.value:void 0,a=n??t,i=r??e,u=ot(t),c=ot(e);return u&&c?u.publisher===c.publisher&&u.package_===c.package_&&u.name===c.name:typeof a=="string"&&typeof i=="string"||typeof a=="number"&&typeof i=="number"||typeof a=="boolean"&&typeof i=="boolean"?a===i:!1}function ot(t){if(t instanceof b){let e=t.subject;return{publisher:e.publisher,package_:e.package_,name:e.name}}if(t instanceof w){let e=t.namespace??"",n=e.indexOf("/"),r=e.indexOf("@",n+1);if(n<0)return;let a=e.substring(0,n),i=r>=0?e.substring(n+1,r):e.substring(n+1);return{publisher:a,package_:i,name:t.name??""}}if(J(t))return{publisher:t.publisher,package_:t.package_,name:t.name}}function Ve(t){return t instanceof L||t instanceof U||t instanceof O||t instanceof j||t instanceof T||t instanceof S}function hn(t){return t instanceof L||t instanceof U||t instanceof O?String(t.object??""):t instanceof j?t.object?.subject?.name??"":t instanceof T?"[embedded]":t instanceof S?(t.object??[]).map(n=>{if(n instanceof b)return n.subject.name;let r=n.name;if(r&&r.length>0)return r;let a=n.value;return typeof a=="string"||typeof a=="number"||typeof a=="boolean"?String(a):"[embedded]"}).join(", "):""}function st(t){if(t===void 0)return"\0undef";if(t===null)return"\0null";if(typeof t=="string")return`s:${t}`;if(typeof t=="number")return`n:${t}`;if(typeof t=="boolean")return`b:${t}`;if(t instanceof b){let e=t.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(t instanceof K){let e=t.name??"";return`k:${t.namespace??""}/${e}`}return J(t)?`u:${t.publisher}/${t.package_}/${t.name}`:`o:${JSON.stringify(t)}`}var bn={"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"}},W=class extends Error{},ge=class{backends=new Map;constructor(){this.register(new Y),this.register(new Z),this.register(new Q),this.register(new x),this.register(new ee),this.register(new te),this.register(new ne),this.register(new ae)}register(e){this.backends.set(e.backendUri,e)}async run(e){let n=e.transformationKanonaks??e.allKanonaks,r=fe(e.transformation,n);if(!r.outputs.has(e.outputFormat))throw new W(`Transformation "${r.name}" does not declare output format "${e.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let a=this.findBackend(e.outputFormat);if(!a)throw new W(`No backend registered for OutputFormat "${e.outputFormat}".`);let i=new ie(e.repository,e.parser,e.objectParser),u=new pe(i,e.allKanonaks,r.fragments);return r.kind==="instance"?this.runInstance(r,e,a,u):this.runSet(r,e,a,u)}async runInstance(e,n,r,a){let i=ut(n.instances,e.inputPattern.requires),u=ct(i,e.inputPattern.sortBy),c=[];for(let l of u){let p=new Map;p.set("input",l);let y=await a.evaluate(e.rule,p);Ae(y,e.name,`input "${l.name}"`);let h=De(await a.evaluate(e.artifactName,p),e.name,`input "${l.name}"`),D=Ke(e.overrides.get(n.outputFormat),n.runtimeOverride),$=r.render(y,D);c.push({fileName:h,format:n.outputFormat,content:$,source:{kind:"instance",sourceName:l.name}})}return c}async runSet(e,n,r,a){let i=ut(n.instances,e.inputPattern.requires),u=ct(i,e.inputPattern.sortBy);return e.partitionBy?this.runSetWithPartition(e,u,n,r,a):this.runSetSingle(e,u,n,r,a)}async runSetSingle(e,n,r,a,i){let u=new Map;u.set("inputs",n);let c=await i.evaluate(e.rule,u);Ae(c,e.name,"set");let l=De(await i.evaluate(e.artifactName,u),e.name,"set"),p=Ke(e.overrides.get(r.outputFormat),r.runtimeOverride),y=a.render(c,p);return[{fileName:l,format:r.outputFormat,content:y,source:{kind:"set",memberCount:n.length}}]}async runSetWithPartition(e,n,r,a,i){let u=e.partitionBy,c=new Map,l=[];for(let y of n){let h=En(y,u);if(h==null)continue;let D=vn(h),$=c.get(D);$||($={keyValue:h,keyDisplay:$n(h),members:[]},c.set(D,$),l.push(D)),$.members.push(y)}let p=[];for(let y of l){let h=c.get(y),D=new Map;D.set("inputs",h.members),D.set("key",h.keyValue);let $=await i.evaluate(e.rule,D);Ae($,e.name,`partition "${h.keyDisplay}"`);let mt=De(await i.evaluate(e.artifactName,D),e.name,`partition "${h.keyDisplay}"`),pt=Ke(e.overrides.get(r.outputFormat),r.runtimeOverride),gt=a.render($,pt);p.push({fileName:mt,format:r.outputFormat,content:gt,source:{kind:"set",memberCount:h.members.length,partitionKey:h.keyDisplay}})}return p}findBackend(e){let n=bn[e];if(n)return this.backends.get(n.formatUri)}};function ut(t,e){return e.length===0?t:t.filter(n=>{for(let r of e)if(!Sn(n,r))return!1;return!0})}function ct(t,e){if(e.length===0)return t;let n=[...t];return n.sort((r,a)=>{for(let i of e){let u=dt(r,i.byProperty),c=dt(a,i.byProperty),l=wn(u,c,i.order);if(l!==0)return l}return 0}),n}function dt(t,e){for(let n of t.statement){let r=Te(n);if(!(!r||!E(r,e))){if(n instanceof L||n instanceof U||n instanceof O)return n.object;if(n instanceof S)throw new W(`Sort property "${e.name}" on instance "${t.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(n instanceof j)throw new W(`Sort property "${e.name}" on instance "${t.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function wn(t,e,n){if(t===void 0&&e===void 0)return 0;if(t===void 0)return n==="ascending"?1:-1;if(e===void 0)return n==="ascending"?-1:1;let r;return typeof t=="number"&&typeof e=="number"?r=t-e:r=String(t).localeCompare(String(e)),n==="ascending"?r:-r}function Sn(t,e){for(let n of t.statement){let r=Te(n);if(!r||!E(r,e))continue;let a=n.object;if(a!=null&&!(typeof a=="string"&&a.length===0)&&!(Array.isArray(a)&&a.length===0))return!0}return!1}function En(t,e){for(let n of t.statement){let r=Te(n);if(!(!r||!E(r,e))&&(n instanceof L||n instanceof U||n instanceof O||n instanceof j||n instanceof S))return n.object}}function Te(t){return t.predicate?.subject}function vn(t){if(t===void 0)return" undef";if(t===null)return" null";if(typeof t=="string")return`s:${t}`;if(typeof t=="number")return`n:${t}`;if(typeof t=="boolean")return`b:${t}`;if(t instanceof b){let e=t.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(t instanceof K){let e=t.name??"";return`k:${t.namespace??""}/${e}`}if(typeof t=="object"&&t!==null&&typeof t.name=="string"&&typeof t.publisher=="string"){let e=t;return`u:${e.publisher}/${e.package_}/${e.name}`}return`o:${JSON.stringify(t)}`}function $n(t){return t==null?"":typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):t instanceof b?t.subject.name:t instanceof K?t.name??"":typeof t=="object"&&t!==null&&typeof t.name=="string"?t.name:""}function Ae(t,e,n){if(typeof t!="object"||t===null||t.kind!=="Document")throw new W(`Transformation "${e}" rule did not yield a Document for ${n}. Got: ${lt(t)}`)}function De(t,e,n){if(typeof t=="string")return t;if(Array.isArray(t)&&t.every(Vn))return t.map(r=>String(r)).join("");throw new W(`Transformation "${e}" artifactName did not yield a string for ${n}. Got: ${lt(t)}`)}function Vn(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function lt(t){if(t===void 0)return"undefined";if(t===null)return"null";if(Array.isArray(t))return`array(${t.length})`;if(typeof t=="object"){let e=t.kind;return e?`object(kind=${e})`:"object"}return typeof t}function Ke(t,e){if(!t&&!e)return;let n={metadataRenames:e?.metadataRenames??t?.metadataRenames??new Map},r=e?.metadataKeys??t?.metadataKeys;r!==void 0&&(n.metadataKeys=r);let a=e?.trailingNewline??t?.trailingNewline;a!==void 0&&(n.trailingNewline=a);let i=e?.omitWrapper??t?.omitWrapper;return i!==void 0&&(n.omitWrapper=i),n}var R=class extends Error{constructor(n,r){super(n);this.cause=r;this.name="RenderError"}cause},ft={publisher:"kanonak.org",package_:"derivation",name:"default"},Be=class{constructor(e,n=new Re,r=new Ue){this.repository=e;this.parser=n;this.objectParser=r}repository;parser;objectParser;runner=new ge;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async renderViaLook(e){let n=await this.getCatalog(),r=M(n,e.resource);if(!(r instanceof w))throw new R(`Resource not found: ${P(e.resource)}`);let a=new ye(n),i;if(e.format.name==="html")i=a.renderHtml(r);else if(e.format.name==="stylesheet")i=a.renderStylesheet(r);else throw new R(`LookRenderer does not support format ${P(e.format)} \u2014 only formats.html and formats.stylesheet are implemented in v0.1.`);return{content:i,format:e.format,filename:r.name}}async findDerivation(e){let n=await this.getCatalog(),r=M(n,e.resource);if(!(r instanceof w))return;let a=e.variant??ft;return Ne(r,e.format,a,n)}async render(e){if(e.format.name==="html"||e.format.name==="stylesheet"){let i=await this.getCatalog(),u=M(i,e.resource);if(u instanceof w){let l=new ye(i).findCascadedLook(u);if(l&&!An(l.sourceClass)){let p=await this.findDerivation(e);if(!p||jn(p))return this.renderViaLook({resource:e.resource,format:e.format})}}}let n=await this.findDerivation(e);if(!n)throw new R(`No derivation found for ${P(e.resource)} \u2192 format ${P(e.format)}`+(e.variant?` variant ${P(e.variant)}`:""));let r=Le(n.transformation.version),a={transformation:{publisher:n.transformation.publisher,package_:n.transformation.package_,name:n.transformation.name,...r?{version:r}:{}},input:e.resource,format:e.format};return e.omitWrapper!==void 0&&(a.omitWrapper=e.omitWrapper),this.runTransformation(a)}async runTransformation(e){let n=await this.getCatalog(),r=M(n,e.transformation);if(!(r instanceof w))throw new R(`Transformation not found: ${P(e.transformation)}`);let a=M(n,e.input);if(!(a instanceof w))throw new R(`Input resource not found: ${P(e.input)}`);let i=fe(r,n),u=Dn(i.outputs,e.format);if(!u)throw new R(`Transformation ${P(e.transformation)} declares outputs [${[...i.outputs].join(", ")}], none of which corresponds to format ${P(e.format)}`);let c;try{c=await this.runner.run({transformation:r,instances:[a],allKanonaks:n,repository:this.repository,parser:this.parser,objectParser:this.objectParser,outputFormat:u,...e.omitWrapper!==void 0?{runtimeOverride:{metadataRenames:new Map,omitWrapper:e.omitWrapper}}:{}})}catch(l){throw new R(`Transformation execution failed: ${l.message}`,l)}if(c.length===0)throw new R("Transformation produced no artifacts");return{content:c[0].content,format:e.format,filename:c[0].fileName}}async getCatalog(){return this.cachedCatalog||(this.cachedCatalog=await this.objectParser.parseKanonaks(this.repository)),this.cachedCatalog}};function P(t){return`${t.publisher}/${t.package_}/${t.name}`}function jn(t){return typeof t.source=="string"?!1:t.source.publisher==="kanonak.org"&&t.source.package_==="core-rdf"&&t.source.name==="Resource"}function An(t){return t.publisher==="kanonak.org"&&t.package_==="core-rdf"&&t.name==="Resource"}function Dn(t,e){let n=e.name;if(t.has(n))return n;for(let r of t)if(r.startsWith(n+"-")||r===n)return r}export{te as CssBackend,ft as DEFAULT_VARIANT,k as DOCAST,kt as DOCAST_PKG,yt as DOCAST_PUB,ae as DynamoDbBackend,pe as ExpressionEngineV3,I as ExpressionEvalErrorV3,x as HtmlBackend,Q as JsonBackend,Y as MarkdownFrontmatterBackend,ie as ReferenceResolver,R as RenderError,bn as SUPPORTED_FORMATS_V3,ee as SvgBackend,o as TX_V3,Xt as TX_V3_PKG,Jt as TX_V3_PUB,Qn as TX_V3_VERSION_MAJOR,Z as TomlBackend,Be as TransformationEngine,g as TransformationLoadErrorV3,W as TransformationRunnerErrorV3,ge as TransformationRunnerV3,ne as YamlBackend,fe as compileTransformationV3,X as renderMarkdownToHtml};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "3.45.0",
3
+ "version": "3.46.0",
4
4
  "description": "Kanonak Protocol SDK - Document repository and parsing implementations for TypeScript",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -113,7 +113,7 @@
113
113
  "yaml-parser"
114
114
  ],
115
115
  "dependencies": {
116
- "@kanonak-protocol/types": "^3.45.0",
116
+ "@kanonak-protocol/types": "^3.46.0",
117
117
  "ignore": "^7.0.5",
118
118
  "js-yaml": "^4.1.0",
119
119
  "yaml": "^2.7.0"
@@ -1 +0,0 @@
1
- import{a as S}from"./chunk-FMYLEPMC.js";import{c as v,d as u,g as j,j as p,k as h,l as k}from"./chunk-W6T7MOKY.js";function fe(t,n,e,a){let r=D(t);if(r.length>0){let i=r.find(f=>m(f.format,n)&&m(f.variant,e));return i?{transformation:i.transformation,source:"instance"}:void 0}let o=new Set,s=U(t);for(;s.length>0;){let i=s.shift(),f=y(i.subject);if(o.has(f))continue;o.add(f);let c=R(a,i.subject);if(!c)continue;let K=D(c).find(d=>m(d.format,n)&&m(d.variant,e));if(K)return{transformation:K.transformation,source:{publisher:i.subject.publisher,package_:i.subject.package_,name:i.subject.name}};for(let d of T(c))s.push(d)}let l={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"};if(!o.has(y(l))){let i=R(a,l);if(i){let c=D(i).find(g=>m(g.format,n)&&m(g.variant,e));if(c)return{transformation:c.transformation,source:l}}}}function D(t){let n=[];for(let e of t.statement)if(e instanceof k&&b(e,"kanonak.org","derivation","derivations"))for(let a of e.object??[]){if(!(a instanceof S))continue;let r=E(a);r&&n.push(r)}return n}function E(t){let n,e,a;for(let r of t.statement)r instanceof p?b(r,"kanonak.org","derivation","format")?n=x(r):b(r,"kanonak.org","derivation","variant")&&(e=x(r)):r instanceof h&&b(r,"kanonak.org","derivation","transformation")&&(a=_(r.object));if(!(!n||!a))return e||(e={publisher:"kanonak.org",package_:"derivation",name:"default"}),{format:n,variant:e,transformation:a}}function _(t){let n,e,a,r;for(let o of t.statement){if(!(o instanceof j))continue;let s=o.predicate?.subject?.name;s==="publisher"?n=o.object:s==="package"?e=o.object:s==="version"?a=o.object:s==="name"&&(r=o.object)}if(!(!n||!e||!a||!r))return{publisher:n,package_:e,version:a,name:r}}function U(t){let n=[];for(let e of t.statement)e instanceof p&&e.predicate?.subject?.name==="type"&&e.object instanceof u&&n.push(e.object);return n}function T(t){let n=[];for(let e of t.statement)if(e instanceof p){if(e.predicate?.subject?.name!=="subClassOf")continue;e.object instanceof u&&n.push(e.object)}else if(e instanceof k){if(e.predicate?.subject?.name!=="subClassOf")continue;for(let a of e.object??[])a instanceof u&&n.push(a)}return n}function R(t,n){for(let e of t){if(!(e instanceof v)||e.name!==n.name)continue;if((e.namespace||"").startsWith(`${n.publisher}/${n.package_}@`))return e}}function b(t,n,e,a){let r=t.predicate?.subject;return r?r.publisher===n&&r.package_===e&&r.name===a:!1}function x(t){let n=t.object.subject;return{publisher:n.publisher,package_:n.package_,name:n.name}}function m(t,n){return t.publisher===n.publisher&&t.package_===n.package_&&t.name===n.name}function y(t){return`${t.publisher}/${t.package_}/${t.name}`}export{fe as a};