@kanonak-protocol/sdk 5.37.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/auth/CredentialProvider.d.ts +69 -49
  2. package/dist/auth/ExecCredentialProvider.d.ts +55 -0
  3. package/dist/auth/OAuthDiscovery.d.ts +38 -10
  4. package/dist/auth/TokenCredentialProvider.d.ts +26 -6
  5. package/dist/auth/challenges.d.ts +17 -0
  6. package/dist/auth/credentialAnswer.d.ts +34 -0
  7. package/dist/auth/credentialConfig.d.ts +32 -0
  8. package/dist/auth/credentialedFetch.d.ts +33 -22
  9. package/dist/auth/index.d.ts +10 -4
  10. package/dist/auth/scope.d.ts +30 -0
  11. package/dist/browser.d.ts +4 -2
  12. package/dist/browser.js +1 -1
  13. package/dist/chunk-22DSABP6.js +1 -0
  14. package/dist/{chunk-HKX27KBZ.js → chunk-7F2EAT5Y.js} +1 -1
  15. package/dist/{chunk-LE26SEJU.js → chunk-A3HRXFVX.js} +1 -1
  16. package/dist/{chunk-4CXAZH3C.js → chunk-ADSDFJUO.js} +1 -1
  17. package/dist/{chunk-W5AOJ5SJ.js → chunk-GKIX3OD6.js} +1 -1
  18. package/dist/chunk-HKQTB65D.js +2 -0
  19. package/dist/{chunk-R4QCVB5M.js → chunk-O6SOU5Y2.js} +1 -1
  20. package/dist/chunk-PNBTIGX7.js +2 -0
  21. package/dist/{chunk-DONOB6RA.js → chunk-SBO34ENZ.js} +1 -1
  22. package/dist/chunk-TYVZXABI.js +155 -0
  23. package/dist/http/HttpError.d.ts +38 -0
  24. package/dist/http/kanonakFetch.d.ts +5 -2
  25. package/dist/index.d.ts +8 -2
  26. package/dist/index.js +2 -1
  27. package/dist/parsing/index.js +1 -1
  28. package/dist/producer/index.js +1 -1
  29. package/dist/reasoning/index.js +1 -1
  30. package/dist/repositories/browser.js +1 -1
  31. package/dist/repositories/index.js +1 -1
  32. package/dist/search/index.js +1 -1
  33. package/dist/server/index.js +5 -5
  34. package/dist/transformations/index.js +2 -2
  35. package/dist/transformations/v3/CompiledTransformationV3.d.ts +28 -27
  36. package/dist/transformations/v3/TransformationUriConstantsV3.d.ts +27 -0
  37. package/dist/validation/index.js +1 -1
  38. package/package.json +5 -4
  39. package/vectors/credential-helper-vectors.json +1039 -0
  40. package/dist/chunk-2WUZKSLB.js +0 -2
  41. package/dist/chunk-3353RWDC.js +0 -1
  42. package/dist/chunk-EG47OOJC.js +0 -155
  43. package/dist/chunk-OOYGILH4.js +0 -2
package/dist/index.d.ts CHANGED
@@ -23,9 +23,15 @@ export type { IKanonakDocumentRepository } from '@kanonak-protocol/types/documen
23
23
  export type { IKanonakParser } from '@kanonak-protocol/types/document/parsing';
24
24
  export type { KanonakDocument, KanonakMetadata, Namespace, Import, Version, DocumentReference, ParseResult, ParseError } from '@kanonak-protocol/types/document/models/types';
25
25
  export { VersionOperator } from '@kanonak-protocol/types/document/models/enums';
26
- export { OAuthDiscovery, DEFAULT_CONSENT_BINDING_PARAM, normalizeHost, createCredentialedFetch, parseAuthChallenge, TokenCredentialProvider, } from './auth/index.js';
27
- export type { OAuthServerMetadata, AuthenticatedFetchFn, CredentialProvider, RequestCredential, AuthChallenge, ResolveOptions, CredentialedFetchDeps, TokenCredentialProviderOptions, } from './auth/index.js';
26
+ export { DEFAULT_CONSENT_BINDING_PARAM, OAuthDiscovery, normalizeHost, CredentialError, createCredentialedFetch, CREDENTIAL_EXPIRY_SKEW_SECONDS, parseWwwAuthenticate, parseScope, scopeContains, narrowestScope, CREDENTIAL_HELPER_PROTOCOL_VERSION, checkCredentialAnswer, checkHelperAnswer, checkHelperEraseAnswer, TokenCredentialProvider, TOKEN_ENV, tokenEnvKeyFor, } from './auth/index.js';
27
+ export type { OAuthServerMetadata, AuthenticatedFetchFn, AuthChallenge, Credential, CredentialAnswer, CredentialEraseRequest, CredentialProvider, CredentialRequest, CredentialedFetchDeps, ParsedScope, AnswerCheck, AnswerProblem, ProtectedResourceMetadata, TokenCredentialProviderOptions, } from './auth/index.js';
28
+ export { ExecCredentialProvider, CREDENTIAL_HELPER_TIMEOUT_MS, splitCommandLine, } from './auth/ExecCredentialProvider.js';
29
+ export type { ExecCredentialProviderOptions } from './auth/ExecCredentialProvider.js';
30
+ export { credentialProviderFromConfig, CREDENTIAL_HELPER_ENV, userConfigPath, } from './auth/credentialConfig.js';
31
+ export type { CredentialProviderConfigOptions } from './auth/credentialConfig.js';
28
32
  export { kanonakFetch, assertHttpsUrl, setKanonakFetchRetries, setKanonakUserAgent, getKanonakUserAgent, KANONAK_USER_AGENT, } from './http/kanonakFetch.js';
33
+ export { KanonakHttpError, httpError, describeResponse, retryAfterSecondsOf } from './http/HttpError.js';
34
+ export type { ProblemDetails } from './http/HttpError.js';
29
35
  export { loadLockFile, saveLockFile, computeIntegrity, parseLockFile, serializeLockFile, computeIntegrityAsync, lockedVersion, INTEGRITY_PREFIX, } from './lock/index.js';
30
36
  export type { LockFile, LockEntry } from './lock/index.js';
31
37
  export { findDerivation } from './derivation/index.js';
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- import{a as pt,b as ft,c as mt,d as ht,e as W}from"./chunk-LE26SEJU.js";import{a as Vn,b as Nn,c as On}from"./chunk-DONOB6RA.js";import{a as ut,b as dt,c as lt,d as _r,e as xr,f as Pr,g as vr,h as Ir,i as Lr}from"./chunk-2WUZKSLB.js";import{a as Vr}from"./chunk-ED35OFGD.js";import{a as br,b as Er,c as Rr,d as B,e as Cr,f as Kr,g as Pe,h as Nr,i as Or,j as wr,k as Ar,l as Ur}from"./chunk-4CXAZH3C.js";import{a as fo,b as mo,c as ho,d as So,e as ko,f as vo,g as Io,h as Lo,i as Vo}from"./chunk-HKX27KBZ.js";import{a as yo,b as go,c as bo,d as Eo,e as Ro,f as Co,h as Ko,i as $e,j as Me,k as je,l as De,m as Fe,n as _o,o as Po}from"./chunk-OOYGILH4.js";import{a as kt,b as yt,c as gt,d as bt,e as Et,f as Rt}from"./chunk-W5AOJ5SJ.js";import{a as Ct,b as _t}from"./chunk-D2X6J77P.js";import{a as xo}from"./chunk-SC5M74NM.js";import{A as Jt,B as Zt,C as er,D as nr,E as or,F as tr,G as fr,H as mr,I as hr,J as Sr,K as kr,L as yr,M as gr,a as xt,b as Pt,c as vt,d as It,e as Lt,f as Vt,g as Nt,h as Ot,i as wt,j as At,k as Ut,l as $t,m as Mt,n as jt,o as Dt,p as Ft,q as Ht,r as Tt,s as qt,t as Wt,u as Bt,v as Gt,w as zt,x as Qt,y as Xt,z as Yt}from"./chunk-R4QCVB5M.js";import"./chunk-VORVR5BZ.js";import{c as vn,d as rr,e as ar,f as ir,g as sr,i as cr,j as ur,m as dr,o as xe,q as In,r as Ln,t as lr,u as pr}from"./chunk-EG47OOJC.js";import"./chunk-QHABFCRC.js";import{a as fe}from"./chunk-6VIUXP4N.js";import{a as Ke,f as N,g as _e,h as st,i as ct,j as U}from"./chunk-3353RWDC.js";import{a as j}from"./chunk-7JBKOJB4.js";import{a as Kt}from"./chunk-PEJALHXK.js";import{$ as re,A as nn,B as on,C as tn,D as rn,E as an,F as sn,G as cn,H as un,I as dn,J as ln,K as ye,L as pn,M as fn,N as mn,O as hn,P as Sn,Q as kn,R as yn,S as gn,T as bn,U as En,V as Rn,W as Cn,X as Kn,Y as _n,Z as ge,_ as xn,a as Wo,aa as be,b as Bo,ba as Ee,c as F,ca as ae,d as Xo,da as T,e as Yo,ea as q,g as Jo,h as ne,ha as Zo,i as oe,ia as et,j as He,k as H,ka as nt,l as te,m as Te,ma as ot,n as qe,na as S,o as Se,oa as Ce,p as We,pa as tt,q as Be,qa as rt,r as Ge,s as ze,t as ke,ta as at,u as Qe,ua as it,v as Xe,va as A,w as Ye,x as Je,y as Ze,z as en}from"./chunk-NUTHBBDZ.js";import{C as w,D as C,E as ee,F as h,G as D,H as he,I as ie,J as Re,L as Pn,a as No,b as Oo,c as k,d as v,e as I,f as Ao,g as Uo,h as $o,i as Mo,j as jo,k as Do,l as Fo,m as Ho,n as To,o as qo,p as Go,q as zo,r as l,u as Qo,v as O,w as me,x as Z,z as _}from"./chunk-D4QGPMRW.js";import{a as wo}from"./chunk-FUUTGGJS.js";import"./chunk-F67UH4FD.js";import{a as to,b as ro,c as J,d as ao,e as V,f as io,g as so,h as co,i as uo,j as lo,k as po}from"./chunk-QILEJIFU.js";import{a as St}from"./chunk-ODIECDN7.js";async function wn(n){let e=await new U().parseKanonaks(n),t=await new W().reason(n);return{kind:"merged",catalog:e,reasoning:t}}function An(n,e){return{kind:"merged",catalog:n,reasoning:e}}async function Un(n,e){let t=e??new fe(new j);return{kind:"standalone",catalog:await new U().parseKanonaks(new Pn(n,t))}}function L(n){return typeof n=="number"?n:void 0}function $r(n){if(!n)return;let e=l(n);if(e===l(un))return"IRI";if(e===l(dn))return"BlankNode";if(e===l(ln))return"Literal"}function Mn(n){if(!n)return;let e=l(n);if(e===l(pn))return"Violation";if(e===l(fn))return"Warning";if(e===l(mn))return"Info"}function jn(n,e,t,o){let r=h(e,Se);if(!r)return;let a={path:r},u=L(C(e,We)),s=L(C(e,Be));u!==void 0&&(a.minCount=u),s!==void 0&&(a.maxCount=s);let i=L(C(e,Ye)),d=L(C(e,Je));i!==void 0&&(a.minLength=i),d!==void 0&&(a.maxLength=d);let c=L(C(e,Ze)),p=L(C(e,en));c!==void 0&&(a.minInclusive=c),p!==void 0&&(a.maxInclusive=p);let f=ee(e,Qe);if(f!==void 0){let m=ee(e,Xe);a.pattern=m!==void 0?{regex:f,flags:m}:{regex:f}}if(w(e,ke)){let m=[],P=[];for(let{item:y}of me(e,ke))"literal"in y?m.push(y.value):y instanceof I&&P.push(y.subject);m.length>0&&(a.inValues=m),P.length>0&&(a.inRefs=P)}let R=h(e,Ge);R&&(a.datatype=R);let $=h(e,ze);$&&(a.classRef=$);let M=$r(h(e,cn));M&&(a.nodeKind=M);let z=h(e,xn);if(z&&(a.hasValue=z),w(e,re)||w(e,be)||w(e,Ee)){let m={},P=L(C(e,be)),y=L(C(e,Ee));P!==void 0&&(m.minCount=P),y!==void 0&&(m.maxCount=y);let K=Mr(n,e,o);"problem"in K?m.problem=K.problem:m.shape=K.shape,a.qualified=m}let Q=ee(e,nn);Q!==void 0&&(a.message=Q);let X=Mn(h(e,ye))??t;return X&&(a.severity=X),a}function Mr(n,e,t){let o=D(e,re);if(o)return $n(n,o,void 0,t);let r=h(e,re);if(!r)return{problem:"sh:qualifiedValueShape is missing"};let a=l(r);if(t.has(a))return{problem:`sh:qualifiedValueShape '${r.name}' leads back to itself (a cycle through named shapes)`};let u=_(n,r);return u?$n(n,u,a,t):{problem:`sh:qualifiedValueShape '${r.name}' does not resolve`}}function $n(n,e,t,o){let r=t?new Set([...o,t]):o,a=Z(e,H);if((Z(e,te)||w(e,Se))&&!a){let i=jn(n,e,void 0,r);return i?{shape:{kind:"property",constraint:i}}:{problem:"the qualified property shape has no sh:path"}}return e instanceof k&&!a?{problem:`sh:qualifiedValueShape '${e.name}' is not a shape`}:{shape:{kind:"node",shape:Dn(n,e,r)}}}function Dn(n,e,t){let o=Mn(h(e,ye)),r={name:e instanceof k?e.name:"(inline shape)",uri:e instanceof k?S(e):void 0,targetClass:h(e,Te),targetNodes:O(e,on),targetSubjectsOf:O(e,tn),targetObjectsOf:O(e,rn),closed:C(e,an)===!0,ignoredProperties:[],severity:o,properties:[]};r.ignoredProperties.push(...O(e,sn));for(let{item:a}of me(e,qe)){let u;if(a instanceof v?u=a:a instanceof I&&(u=_(n,a.subject)),!u)continue;let s=jn(n,u,o,t);s&&r.properties.push(s)}return r}function se(n){let e=[];for(let t of n){if(!(t instanceof k)||!Z(t,H))continue;let o=S(t);e.push(Dn(n,t,new Set(o?[l(o)]:[])))}return e}var b="kanonak.org/transformations",G="values";var ce="allowed",Ie="expected",g=n=>({type:`${b}/VarRef`,varName:n}),ve=n=>({type:`${b}/IntegerLiteral`,integerLiteral:n}),jr=n=>({type:`${b}/DecimalLiteral`,decimalLiteral:n}),Fn=n=>Number.isInteger(n)?ve(n):jr(n),Hn=n=>({type:`${b}/Count`,source:n}),Tn=(n,e)=>({type:`${b}/GreaterThanOrEqual`,compareLeft:n,compareRight:e}),qn=(n,e)=>({type:`${b}/LessThanOrEqual`,compareLeft:n,compareRight:e});function Le(n,e){if(!e||e.length===0)return n;let t=new Set(["i","m","s"]),o=[...new Set(e.split(""))];if(o.filter(a=>!t.has(a)).length>0)throw new Error(`sh:flags '${e}' is outside the pinned regex subset (supported: i, m, s)`);return`(?${o.sort().join("")})${n}`}function ue(n){let e=[];return n.minCount!==void 0&&e.push({component:"minCount",per:"node",expr:Tn(Hn(g(G)),ve(n.minCount))}),n.maxCount!==void 0&&e.push({component:"maxCount",per:"node",expr:qn(Hn(g(G)),ve(n.maxCount))}),n.hasValue!==void 0&&e.push({component:"hasValue",per:"node",expr:{type:`${b}/Contains`,haystack:g(G),needle:g(Ie)}}),(n.inValues!==void 0||n.inRefs!==void 0)&&e.push({component:"in",per:"value",expr:{type:`${b}/Contains`,haystack:g(ce),needle:g("v")}}),n.pattern!==void 0&&e.push({component:"pattern",per:"value",expr:{type:`${b}/Matches`,matchSource:g("v"),pattern:Le(n.pattern.regex,n.pattern.flags)}}),n.minLength!==void 0&&e.push({component:"minLength",per:"value",expr:{type:`${b}/Matches`,matchSource:g("v"),pattern:`(?s)^.{${n.minLength},}$`}}),n.maxLength!==void 0&&e.push({component:"maxLength",per:"value",expr:{type:`${b}/Matches`,matchSource:g("v"),pattern:`(?s)^.{0,${n.maxLength}}$`}}),n.minInclusive!==void 0&&e.push({component:"minInclusive",per:"value",expr:Tn(g("v"),Fn(n.minInclusive))}),n.maxInclusive!==void 0&&e.push({component:"maxInclusive",per:"value",expr:qn(g("v"),Fn(n.maxInclusive))}),e}import{evaluate as Fr,ExpressionError as Hr}from"@kanonak-protocol/expression";function Bn(n,e){let t=Tr(e)?e:se(e),o=[],r=n.catalog.filter(s=>s instanceof k).map(de),a=new Map;qr(r,a);let u={scope:n,membership:new Ve(n),embeddedFocus:a};for(let s of t)for(let i of Wr(u,s,r))zn(u,s,i,o);return{conforms:!o.some(s=>s.severity==="Violation"),results:o}}function Tr(n){return n.length>0&&!(n[0]instanceof Object&&"statement"in n[0])&&typeof n[0].name=="string"&&"properties"in n[0]}function Gn(n){let e=n.predicate;return e instanceof I?e:void 0}function de(n){return{node:n,key:Re(n),uri:S(n),label:n.name}}function Oe(n,e){return{node:n,key:e,label:e.includes("#")?e.slice(e.indexOf("#")):e}}function qr(n,e){Ke(n.map(t=>t.node),({kanonak:t,address:o})=>{t instanceof v&&!e.has(t)&&e.set(t,Oe(t,o))})}var Ve=class{constructor(e){this.scope=e}scope;ancestors=new Map;isInstance(e,t){let o=l(t);return e.some(r=>l(r)===o||this.ancestorsOf(r).has(o))}ancestorsOf(e){let t=e.version&&typeof e.version.major=="number"?`${l(e)}@${V(e.version)}`:l(e),o=this.ancestors.get(t);return o||(o=this.scope.reasoning?new Set(this.scope.reasoning.getSuperclasses(e)):new Set(Ce(this.scope.catalog,e).map(r=>l(r))),this.ancestors.set(t,o)),o}};function Wr(n,e,t){let{scope:o}=n,r=new Map,a=s=>{r.set(s.key,s)},u=()=>[...t,...n.embeddedFocus.values()];if(e.targetClass){let s=e.targetClass;if(o.reasoning){let i=new Set(o.reasoning.getInstancesOfClass(s));for(let d of t)d.uri&&i.has(l(d.uri))&&a(d)}else for(let i of t)n.membership.isInstance(A(i.node),s)&&a(i);for(let i of n.embeddedFocus.values())n.membership.isInstance(A(i.node),s)&&a(i)}for(let s of e.targetNodes){let i=_(o.catalog,s);i instanceof k&&a(de(i))}for(let s of e.targetSubjectsOf){let i=l(s);for(let d of u())d.node.statement.some(c=>{let p=Gn(c);return p&&l(p.subject)===i})&&a(d)}for(let s of e.targetObjectsOf)for(let i of u())for(let d of ie(i.node,s,o.catalog,i.key))d.kind==="subject"?a(de(d.node)):d.kind==="embedded"&&a(n.embeddedFocus.get(d.node)??Oe(d.node,d.address));return[...r.values()]}function Br(n,e,t){return e.node?ie(e.node,t,n.scope.catalog,e.key).map(o=>Gr(n,o)):[]}function Gr(n,e){switch(e.kind){case"subject":return{kernel:{ref:l(e.uri)},kind:"reference",ref:e.uri,subject:e.node};case"unresolved":return{kernel:{ref:l(e.uri)},kind:"reference",ref:e.uri};case"embedded":{let t=n.embeddedFocus.get(e.node)??Oe(e.node,e.address);return{kernel:{ref:t.key},kind:"embedded",embedded:t}}case"literal":return typeof e.value=="boolean"?{kernel:e.value?1:0,kind:"boolean",literal:e.value}:{kernel:e.value,kind:typeof e.value=="number"?"number":"string",literal:e.value}}}function zn(n,e,t,o){for(let r of e.properties)Xn(n,e,t,r,o);e.closed&&ra(e,t,o)}function Ne(n,e,t,o,r={},a){return{focusNode:e.key,focusUri:e.uri,constraintComponent:t,severity:a??Qn(n),message:o,sourceShape:n.name,sourceShapeUri:n.uri,...r}}function Qn(n){return n.severity??"Violation"}var zr={minCount:hn,maxCount:Sn,hasValue:ae,in:gn,pattern:bn,minLength:En,maxLength:Rn,minInclusive:Cn,maxInclusive:Kn};function Xn(n,e,t,o,r){let a=Br(n,t,o.path),u=o.severity??Qn(e),s=o.path.name,i=[...(o.inValues??[]).map(c=>typeof c=="boolean"?c?1:0:c),...(o.inRefs??[]).map(c=>({ref:l(c)}))],d=(c,p,f)=>{let R=Ne(e,t,c,o.message??p,{resultPath:o.path,value:f?.literal,valueRef:f?.ref},u);return r.push(R),R};for(let c of ue(o)){let p=zr[c.component];if(c.per==="node"){let f={[G]:a.map(R=>R.kernel),[ce]:i};o.hasValue&&(f[Ie]={ref:l(o.hasValue)}),Wn(c,f)||d(p,Qr(c,s,o,a.length));continue}for(let f of a){if((c.component==="pattern"||c.component==="minLength"||c.component==="maxLength")&&f.kind!=="string"){d(p,`'${s}' value is not a string; ${c.component} applies to string values.`,f);continue}Wn(c,{v:f.kernel,[ce]:i})||d(p,ea(c,s,o,f),f)}}if(o.nodeKind)for(let c of a)na(o.nodeKind,c)||d(_n,`'${s}' value is ${c.kind}; nodeKind requires ${o.nodeKind}.`,c);if(o.datatype)for(let c of a){let p=oa(o.datatype,c);p&&d(kn,`'${s}' ${p}`,c)}if(o.classRef)for(let c of a){let p=ta(n,o.classRef,c);p&&d(yn,`'${s}' ${p}`,c)}o.qualified&&Xr(n,o,a,s,d)}function Qr(n,e,t,o){switch(n.component){case"minCount":return`'${e}' has ${o} value(s); minCount is ${t.minCount}.`;case"maxCount":return`'${e}' has ${o} value(s); maxCount is ${t.maxCount}.`;case"hasValue":return`'${e}' has no value equal to ${t.hasValue?l(t.hasValue):"(unset)"}.`;default:return`'${e}' violates ${n.component}.`}}function Xr(n,e,t,o,r){let a=e.qualified,u=a.maxCount!==void 0?q:T,s=(d,c)=>{Yn.add(r(u,d,c))};if(!a.shape){s(`'${o}' qualified value shape cannot be evaluated: ${a.problem??"it could not be built"}.`);return}let i=0;for(let d of t){let c=d.ref?l(d.ref):d.embedded?d.embedded.label:JSON.stringify(d.literal),p=Yr(n,d);if(!p){s(`'${o}' value ${c} does not resolve in this scope; whether it conforms to the qualified shape cannot be decided.`,d);continue}let f=Zr(n,a.shape,p);if(f.kind==="undecided"){s(`'${o}' value ${c}: whether it conforms to the qualified shape cannot be decided \u2014 ${f.reason}`,d);continue}f.kind==="conforms"&&i++}a.minCount!==void 0&&i<a.minCount&&r(T,`'${o}' has ${i} value(s) that conform to the qualified shape; qualifiedMinCount is ${a.minCount}.`),a.maxCount!==void 0&&i>a.maxCount&&r(q,`'${o}' has ${i} value(s) that conform to the qualified shape; qualifiedMaxCount is ${a.maxCount}.`)}function Yr(n,e){switch(e.kind){case"reference":return e.subject?de(e.subject):void 0;case"embedded":return e.embedded;default:{let t=JSON.stringify(e.literal);return{key:t,label:t}}}}var Jr={name:"(qualified value shape)",targetNodes:[],targetSubjectsOf:[],targetObjectsOf:[],closed:!1,ignoredProperties:[],properties:[]},Yn=new WeakSet;function Zr(n,e,t){let o=[];e.kind==="property"?Xn(n,Jr,t,e.constraint,o):zn(n,e.shape,t,o);let r=o.find(a=>Yn.has(a));return r?{kind:"undecided",reason:r.message}:o.length===0?{kind:"conforms"}:{kind:"fails"}}function ea(n,e,t,o){let r=o.ref?l(o.ref):o.embedded?o.embedded.label:JSON.stringify(o.literal);switch(n.component){case"in":return`'${e}' value ${r} is not in the permitted set.`;case"pattern":return`'${e}' value ${r} does not match pattern ${t.pattern?.regex}.`;case"minLength":return`'${e}' value ${r} is shorter than minLength ${t.minLength}.`;case"maxLength":return`'${e}' value ${r} is longer than maxLength ${t.maxLength}.`;case"minInclusive":return`'${e}' value ${r} is below minInclusive ${t.minInclusive} (or not numeric).`;case"maxInclusive":return`'${e}' value ${r} is above maxInclusive ${t.maxInclusive} (or not numeric).`;default:return`'${e}' value ${r} violates ${n.component}.`}}function Wn(n,e){let t=o=>{let r=o.varName;if(o.type==="kanonak.org/transformations/VarRef"&&typeof r=="string"&&r in e)return e[r];throw new Hr(`Conformance lowering produced an unexpected leaf '${o.type}'`)};return Fr(n.expr,void 0,t)===1}function na(n,e){switch(n){case"IRI":return e.kind==="reference";case"BlankNode":return e.kind==="embedded";case"Literal":return e.kind==="string"||e.kind==="number"||e.kind==="boolean"}}function oa(n,e){if(e.kind==="reference"||e.kind==="embedded")return`value is a ${e.kind}; sh:datatype requires a literal of ${n.name}.`;let t=_e(n);if(t!==void 0)switch(t){case N.Boolean:return e.kind==="boolean"?void 0:`value is not a boolean (${n.name}).`;case N.Integer:return e.kind!=="number"?`value is not a number (${n.name}).`:Number.isInteger(e.literal)?void 0:`value is not an integer (${n.name}).`;case N.Decimal:case N.Double:case N.Float:return e.kind==="number"?void 0:`value is not a number (${n.name}).`;default:return e.kind==="string"?void 0:`value is not a string-carried literal (${n.name}).`}}function ta(n,e,t){if(t.kind==="embedded"&&t.embedded?.node){let r=A(t.embedded.node);return r.length===0?`value ${t.embedded.label} has no type; sh:class requires an instance of ${e.name}.`:n.membership.isInstance(r,e)?void 0:`value ${t.embedded.label} is not an instance of ${e.name}.`}if(t.kind!=="reference"||!t.ref)return`value is not a reference; sh:class requires an instance of ${e.name}.`;if(n.scope.reasoning)return n.scope.reasoning.isInstanceOf(t.ref,e)?void 0:`value ${l(t.ref)} is not an instance of ${e.name}.`;let o=t.subject;return o?n.membership.isInstance(A(o),e)?void 0:`value ${l(t.ref)} is not an instance of ${e.name}.`:`value ${l(t.ref)} does not resolve in this scope (sh:class ${e.name}).`}function ra(n,e,t){if(!e.node)return;let o=new Set([...n.properties.map(a=>l(a.path)),...n.ignoredProperties.map(a=>l(a))]),r=new Set;for(let a of e.node.statement){let u=Gn(a);if(!u)continue;let s=l(u.subject);o.has(s)||r.has(s)||(r.add(s),t.push(Ne(n,e,ge,`'${e.label}' carries undeclared property '${u.subject.name}' (closed shape).`,{resultPath:u.subject})))}for(let a of e.node.unresolvedPredicates)r.has(a.key)||(r.add(a.key),t.push(Ne(n,e,ge,`'${e.label}' carries unresolvable property '${a.key}' (closed shape).`,{value:a.key})))}var aa="1.1.0",ia=new Set([ae,T,q].map(n=>n.name));async function Jn(n){let e=new B(n.repository),t=e.imports(),o=n.result.results.some(i=>ia.has(i.constraintComponent.name))?"1.2.0":aa,r=t.ensure(ne,oe,o,"sh"),a=(i,d)=>i&&i.version&&typeof i.version.major=="number"?`${t.ensure(i.publisher,i.package_,V(i.version),i.package_)}.${i.name}`:d,u={},s=[];return n.result.results.forEach((i,d)=>{let c=`result-${d+1}`;s.push(c);let p={type:`${r}.ValidationResult`,[`${r}.focusNode`]:a(i.focusUri,i.focusNode),[`${r}.resultMessage`]:i.message,[`${r}.resultSeverity`]:`${r}.${i.severity}`,[`${r}.sourceConstraintComponent`]:`${r}.${i.constraintComponent.name}`};i.resultPath&&(p[`${r}.resultPath`]=a(i.resultPath,l(i.resultPath))),i.sourceShapeUri&&(p[`${r}.sourceShape`]=a(i.sourceShapeUri,i.sourceShape)),i.valueRef?p[`${r}.value`]=a(i.valueRef,l(i.valueRef)):i.value!==void 0&&(p[`${r}.value`]=i.value),u[c]=p}),u.report={type:`${r}.ValidationReport`,[`${r}.conforms`]:n.result.conforms,...s.length>0?{[`${r}.result`]:s}:{}},e.buildContentAddressed({publisher:n.publisher,book:t,body:u,...n.header!==void 0?{header:n.header}:{},contentHashProperty:"contentHash"})}import{VersionOperator as $i}from"@kanonak-protocol/types/document/models/enums";var E="kanonak.org",x="view",Zn="core-kanonak",sa={publisher:E,package_:x,name:"rootView"},ca={publisher:E,package_:x,name:"bind"},ua={publisher:E,package_:x,name:"produces"},da={publisher:E,package_:x,name:"projections"},la={publisher:E,package_:x,name:"where"},pa={publisher:E,package_:x,name:"value"},fa={publisher:E,package_:x,name:"as"},le=class{constructor(e,t=new j){this.repository=e;this.parser=t;this.objectParser=new U(this.parser),this.builder=new B(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let o=await this.objectParser.parseKanonaks(this.repository),r=this.resolveView(o,e),a=h(r,ca);if(!a)throw new Error(`View ${r.namespace}/${r.name} declares no view.bind; cannot materialize.`);let u=h(r,ua);if(!u)throw new Error(`View ${r.namespace}/${r.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=ma(r),i=eo(o,E,Zn),d=eo(o,E,x),c=this.builder.imports(),p=c.ensure(E,Zn,i,"ck"),f=c.ensure(E,x,d,"v"),R=c.ref(u),$=new Ln(this.repository,this.parser,this.objectParser),M=new In($,o),z=this.readProjections(o,r),Q=ka(r,la),X=this.findInstances(o,a,await this.reason(t)),m={},P=new Set;for(let Y of X){if(!await this.passesWhere(M,o,Q,Y))continue;let pe={type:R};for(let Ae of z){let oo=await this.evaluateValue(M,o,Ae.value,Y),Ue=this.builder.serializeValue(no(oo),c);Ue!==void 0&&(pe[c.ref(Ae.as)]=Ue)}let we=S(Y);we&&(pe[`${f}.derivedFrom`]=c.ref(we)),m[this.rowName(Y,P)]=pe}let y={};t.resolvedAt&&(y[`${p}.resolvedAt`]=t.resolvedAt),t.invocationId&&(y[`${p}.id`]=t.invocationId);let K=await this.builder.buildContentAddressed({publisher:s,book:c,body:m,contentHashProperty:`${p}.contentHash`,header:y});return{yaml:K.yaml,contentHash:K.contentHash,packageName:K.packageName,publisher:K.publisher,rowCount:K.resourceCount}}resolveView(e,t){let o=_(e,t);if(!o)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let r=h(o,sa);if(r){let a=_(e,r);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${r.name}, which is not in the catalog.`);return a}return o}readProjections(e,t){let o=[];for(let r of he(t,da)){let a=r instanceof v?r:r instanceof I?_(e,r.subject):void 0;if(!a)continue;let u=D(a,pa),s=h(a,fa);u&&s&&o.push({value:u,as:s})}return o}async reason(e){return new W({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,o){let r=Sa(e),a=[],u=new Set;for(let s of o.getInstancesOfClass(t)){if(u.has(s))continue;u.add(s);let i=r.get(s);i&&a.push(i)}return a.sort((s,i)=>{let d=F(S(s)),c=F(S(i));return d<c?-1:d>c?1:0}),a}async passesWhere(e,t,o,r){for(let a of o){let u=await this.evaluateValue(e,t,a,r);if(!ya(u))return!1}return!0}async evaluateValue(e,t,o,r){let a=vn(o,"view-projection",{catalog:t,depth:0}),u=new Map([["input",r]]);return e.evaluate(a,u)}rowName(e,t){let o=Pe(e.name)||"row",r=o,a=2;for(;t.has(r);)r=`${o}-${a++}`;return t.add(r),r}};function no(n){return xe(n)?n.value:Array.isArray(n)?n.map(no):n}function ma(n){let e=S(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function eo(n,e,t){let o=ha(n,e,t);if(!o)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return o}function ha(n,e,t){let o;for(let r of n){if(!(r instanceof k))continue;let a=S(r);!a||a.publisher!==e||a.package_!==t||!a.version||(!o||J(a.version,o)>0)&&(o=a.version)}return o?V(o):void 0}function Sa(n){let e=new Map,t=new Map;for(let o of n){if(!(o instanceof k))continue;let r=S(o);if(!r||!r.version)continue;let a=F(r),u=t.get(a);(!u||J(r.version,u)>0)&&(t.set(a,r.version),e.set(a,o))}return e}function ka(n,e){let t=D(n,e);return t?[t]:he(n,e).filter(o=>o instanceof v)}function ya(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:xe(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{Gt as AmbiguousReferenceRule,Do as BooleanStatement,Rr as CANONICAL_FORM_VERSION,N as Carrier,Zt as ClassDefinitionRule,Dt as ClassHierarchyCycleRule,ho as CompositeKanonakDocumentRepository,xr as DEFAULT_CONSENT_BINDING_PARAM,Oo as DefinedKanonak,yr as DiamondNameClashRule,nr as DisplayLensScopeRule,mo as DocumentLocation,dt as EdgeType,v as EmbeddedKanonak,$t as EmbeddedKanonakTypeRule,Ho as EmbeddedStatement,Ar as EntitlementDeniedError,Ur as EntitlementProducer,fo as FileSystemKanonakDocumentRepository,St as GitIgnoreFilter,lt as GraphBuilder,Po as HttpKanonakDocumentRepository,Me as INTEGRITY_PREFIX,Kr as ImportBook,Mt as ImportExistenceRule,fe as InMemoryKanonakDocumentRepository,yo as KANONAK_USER_AGENT,No as Kanonak,yt as KanonakDocumentPositions,U as KanonakObjectParser,gr as KanonakObjectValidator,j as KanonakParser,wo as KanonakUri,Ct as KanonakUriBuilder,Kt as KanonakUrlResolver,nt as KanonakVocabulary,sr as LINE_STYLES,Vt as LinkTargetRule,To as ListStatement,Ao as LiteralKanonak,vo as LocalFirstRepository,Io as LockAwareRepository,mr as LookBandPathRule,lr as LookRenderer,or as LookSemanticSvgPathRule,er as MarkdownLinkRule,qo as MarkdownStatement,Wt as NamespaceImportCycleRule,Nt as NamespacePrefixRule,ut as NodeType,jo as NumberStatement,Pr as OAuthDiscovery,mt as OWL_RL_CLASSIFICATION_RULES,Qt as ObjectPropertyValueValidationRule,vt as OntologyValidationError,xt as OntologyValidationResult,kr as OwlOneOfRule,B as PackageBuilder,Ut as PackageHeaderRule,Nr as ProducerRepository,Xt as PropertyDomainRule,Ft as PropertyHierarchyCycleRule,Yt as PropertyKindRangeConsistencyRule,kt as PropertyMetadata,zt as PropertyRangeReferenceRule,Ht as PropertyRangeRequiredRule,wt as PropertyTypeSpecificityRule,Ko as PublisherConfigResolver,_o as PublisherIndex,ft as RDFS_RULES,W as Reasoner,ht as ReasoningResult,I as ReferenceKanonak,Fo as ReferenceStatement,ko as RepositoryFactory,Jt as ReservedNameShadowRule,Ot as ResourceNamingRule,Wo as ResourceResolver,ot as ResourceTypeClassifier,oe as SHACL_PACKAGE,ne as SHACL_PUBLISHER,H as SH_NODE_SHAPE,te as SH_PROPERTY_SHAPE,He as SH_SHAPE,$o as ScalarStatement,fr as SequenceNarrativeRule,Sr as ShaclShapeRule,Uo as Statement,Mo as StringStatement,Tt as SubClassOfReferenceRule,qt as SubPropertyOfReferenceRule,k as SubjectKanonak,At as SubjectKanonakTypeRequiredRule,Lr as TokenCredentialProvider,pt as TripleStore,tr as TxExpressionCompilesRule,hr as TxExpressionPathRule,Bo as TypeResolver,rr as URI_DISPLAY_LABEL,ar as URI_DISPLAY_SUMMARY,Bt as UnresolvedPredicateRule,jt as UnresolvedReferenceRule,Lt as ValidationCache,It as ValidationContext,Pt as ValidationSeverity,$i as VersionOperator,le as ViewMaterializer,Or as allowAllPolicy,Eo as assertHttpsUrl,xo as assertPackageIdentity,Vo as buildLocalFirstRepository,dr as buildOntologyModel,Jn as buildReportPackageAsync,se as buildShapesModel,Zo as builtinHomePackages,et as builtinUri,br as canonicalForm,Er as canonicalHash,_e as carrierOf,Lo as collectKanonakFiles,J as compareVersions,On as computeIntegrity,Fe as computeIntegrityAsync,Cr as contentAddressedName,A as contextTypesOf,Ir as createCredentialedFetch,io as createVersion,Bn as evaluateConformance,ct as extractMarkdownLinks,Vr as findDerivation,st as findMalformedReferences,bt as findMarkdownLinkAt,Le as foldFlagsIntoPattern,zo as formatKanonakAddress,V as formatVersion,So as getGlobalCachePath,bo as getKanonakUserAgent,co as isCompatibleVersion,uo as isMajorCompatible,rt as isPropertySubject,Ro as kanonakFetch,Vn as loadLockFile,$e as lockedVersion,ue as lowerConstraint,Xo as makeUriKey,wr as noopMeter,_r as normalizeHost,vr as parseAuthChallenge,Go as parseKanonakAddress,je as parseLockFile,so as parseVersionString,gt as parseWithPositions,po as pickHighestDocument,at as propertiesInScope,tt as propertyClassOf,cr as readSequenceConnectors,_t as referenceSpelling,O as referenceUris,ir as resolveDisplayValue,it as resolvePropertyStep,Pe as sanitizeName,lo as satisfiesVersionOperator,Nn as saveLockFile,An as scopeFromCatalog,Un as scopeFromDocumentAsync,wn as scopeFromRepositoryAsync,De as serializeLockFile,Co as setKanonakFetchRetries,go as setKanonakUserAgent,Rt as sourceSymbolAt,Et as sourceSymbols,Re as subjectAddress,S as subjectUri,Ce as superClassChain,pr as supportedBandKeys,Yo as tripleKey,Qo as typeReferenceUris,F as uriKey,Jo as uriTriple,ie as valuesOf,to as versionOperatorFromChar,ro as versionOperatorToChar,ao as versionsEqual,Ke as walkDefinedKanonaks,ur as walkSequence};
1
+ import{a as xt,b as Kt,c as Nt,d as Lt,e as z}from"./chunk-A3HRXFVX.js";import{a as Dn,b as jn,c as Hn}from"./chunk-SBO34ENZ.js";import{a as Pt,b as _t,c as wt,d as Hr,e as Fr,f as Tr,g as Wr,h as qr,i as Br,j as Le,k as Gr,l as Ie,m as Oe,n as zr,o as Qr,p as Xr,q as de,r as Yr,s as Ae}from"./chunk-PNBTIGX7.js";import{a as Jr}from"./chunk-ED35OFGD.js";import{a as $r,b as Ur,c as Mr,d as Q,e as Dr,f as jr,g as Ne,h as Zr,i as ei,j as ni,k as oi,l as ti}from"./chunk-ADSDFJUO.js";import{a as Po,b as _o,c as wo,d as xo,e as Ko,f as Wo,g as qo,h as Bo,i as Go}from"./chunk-7F2EAT5Y.js";import{a as No,b as Lo,c as Io,d as Oo,e as N,f as Ao,g as Vo,h as $o,i as Uo,j as Mo,k as Do,m as jo,n as qe,o as Be,p as Ge,q as ze,r as Qe,s as Ho,t as To}from"./chunk-HKQTB65D.js";import{a as Ot,b as At,c as Vt,d as $t,e as Ut,f as Mt}from"./chunk-GKIX3OD6.js";import{a as Dt,b as Ht}from"./chunk-D2X6J77P.js";import{a as Fo}from"./chunk-SC5M74NM.js";import{A as mr,B as hr,C as Sr,D as kr,E as gr,F as yr,G as Kr,H as Nr,I as Lr,J as Ir,K as Or,L as Ar,M as Vr,a as Ft,b as Tt,c as Wt,d as qt,e as Bt,f as Gt,g as zt,h as Qt,i as Xt,j as Yt,k as Jt,l as Zt,m as er,n as nr,o as or,p as tr,q as rr,r as ir,s as ar,t as sr,u as cr,v as dr,w as ur,x as lr,y as pr,z as fr}from"./chunk-O6SOU5Y2.js";import"./chunk-VORVR5BZ.js";import{c as $n,d as Er,e as br,f as Cr,g as Rr,i as vr,j as Pr,m as _r,o as Ke,q as Un,r as Mn,t as wr,u as xr}from"./chunk-TYVZXABI.js";import"./chunk-QHABFCRC.js";import{a as Se}from"./chunk-6VIUXP4N.js";import{a as we,g as $,h as xe,i as Rt,j as vt,k as H}from"./chunk-22DSABP6.js";import{a as F}from"./chunk-7JBKOJB4.js";import{a as jt}from"./chunk-PEJALHXK.js";import{$ as ae,A as un,B as ln,C as pn,D as fn,E as mn,F as hn,G as Sn,H as kn,I as gn,J as yn,K as be,L as En,M as bn,N as Cn,O as Rn,P as vn,Q as Pn,R as _n,S as wn,T as xn,U as Kn,V as Nn,W as Ln,X as In,Y as On,Z as Ce,_ as An,a as st,aa as Re,b as ct,ba as ve,c as W,ca as se,d as pt,da as B,e as ft,ea as G,g as mt,h as te,ha as ht,i as re,ia as St,j as Xe,k as q,ka as kt,l as ie,m as Ye,ma as gt,n as Je,na as k,o as ye,oa as _e,p as Ze,pa as yt,q as en,qa as Et,r as nn,s as on,t as Ee,ta as bt,u as tn,ua as Ct,v as rn,va as j,w as an,x as sn,y as cn,z as dn}from"./chunk-NUTHBBDZ.js";import{C as D,D as R,E as oe,F as S,G as T,H as ge,I as ce,J as Pe,L as Vn,a as zo,b as Qo,c as g,d as L,e as I,f as Yo,g as Jo,h as Zo,i as et,j as nt,k as ot,l as tt,m as rt,n as it,o as at,p as dt,q as ut,r as l,u as lt,v as M,w as ke,x as ne,z as _}from"./chunk-D4QGPMRW.js";import{a as Xo}from"./chunk-FUUTGGJS.js";import"./chunk-F67UH4FD.js";import{a as So,b as ko,c as ee,d as go,e as V,f as yo,g as Eo,h as bo,i as Co,j as Ro,k as vo}from"./chunk-QILEJIFU.js";import{a as It}from"./chunk-ODIECDN7.js";async function Fn(n){let e=await new H().parseKanonaks(n),t=await new z().reason(n);return{kind:"merged",catalog:e,reasoning:t}}function Tn(n,e){return{kind:"merged",catalog:n,reasoning:e}}async function Wn(n,e){let t=e??new Se(new F);return{kind:"standalone",catalog:await new H().parseKanonaks(new Vn(n,t))}}function O(n){return typeof n=="number"?n:void 0}function ri(n){if(!n)return;let e=l(n);if(e===l(kn))return"IRI";if(e===l(gn))return"BlankNode";if(e===l(yn))return"Literal"}function Bn(n){if(!n)return;let e=l(n);if(e===l(En))return"Violation";if(e===l(bn))return"Warning";if(e===l(Cn))return"Info"}function Gn(n,e,t,o){let r=S(e,ye);if(!r)return;let i={path:r},d=O(R(e,Ze)),s=O(R(e,en));d!==void 0&&(i.minCount=d),s!==void 0&&(i.maxCount=s);let a=O(R(e,an)),u=O(R(e,sn));a!==void 0&&(i.minLength=a),u!==void 0&&(i.maxLength=u);let c=O(R(e,cn)),p=O(R(e,dn));c!==void 0&&(i.minInclusive=c),p!==void 0&&(i.maxInclusive=p);let m=oe(e,tn);if(m!==void 0){let h=oe(e,rn);i.pattern=h!==void 0?{regex:m,flags:h}:{regex:m}}if(D(e,Ee)){let h=[],K=[];for(let{item:y}of ke(e,Ee))"literal"in y?h.push(y.value):y instanceof I&&K.push(y.subject);h.length>0&&(i.inValues=h),K.length>0&&(i.inRefs=K)}let f=S(e,nn);f&&(i.datatype=f);let A=S(e,on);A&&(i.classRef=A);let v=ri(S(e,Sn));v&&(i.nodeKind=v);let U=S(e,An);if(U&&(i.hasValue=U),D(e,ae)||D(e,Re)||D(e,ve)){let h={},K=O(R(e,Re)),y=O(R(e,ve));K!==void 0&&(h.minCount=K),y!==void 0&&(h.maxCount=y);let P=ii(n,e,o);"problem"in P?h.problem=P.problem:h.shape=P.shape,i.qualified=h}let x=oe(e,un);x!==void 0&&(i.message=x);let J=Bn(S(e,be))??t;return J&&(i.severity=J),i}function ii(n,e,t){let o=T(e,ae);if(o)return qn(n,o,void 0,t);let r=S(e,ae);if(!r)return{problem:"sh:qualifiedValueShape is missing"};let i=l(r);if(t.has(i))return{problem:`sh:qualifiedValueShape '${r.name}' leads back to itself (a cycle through named shapes)`};let d=_(n,r);return d?qn(n,d,i,t):{problem:`sh:qualifiedValueShape '${r.name}' does not resolve`}}function qn(n,e,t,o){let r=t?new Set([...o,t]):o,i=ne(e,q);if((ne(e,ie)||D(e,ye))&&!i){let a=Gn(n,e,void 0,r);return a?{shape:{kind:"property",constraint:a}}:{problem:"the qualified property shape has no sh:path"}}return e instanceof g&&!i?{problem:`sh:qualifiedValueShape '${e.name}' is not a shape`}:{shape:{kind:"node",shape:zn(n,e,r)}}}function zn(n,e,t){let o=Bn(S(e,be)),r={name:e instanceof g?e.name:"(inline shape)",uri:e instanceof g?k(e):void 0,targetClass:S(e,Ye),targetNodes:M(e,ln),targetSubjectsOf:M(e,pn),targetObjectsOf:M(e,fn),closed:R(e,mn)===!0,ignoredProperties:[],severity:o,properties:[]};r.ignoredProperties.push(...M(e,hn));for(let{item:i}of ke(e,Je)){let d;if(i instanceof L?d=i:i instanceof I&&(d=_(n,i.subject)),!d)continue;let s=Gn(n,d,o,t);s&&r.properties.push(s)}return r}function ue(n){let e=[];for(let t of n){if(!(t instanceof g)||!ne(t,q))continue;let o=k(t);e.push(zn(n,t,new Set(o?[l(o)]:[])))}return e}var b="kanonak.org/transformations",X="values";var le="allowed",$e="expected",E=n=>({type:`${b}/VarRef`,varName:n}),Ve=n=>({type:`${b}/IntegerLiteral`,integerLiteral:n}),ai=n=>({type:`${b}/DecimalLiteral`,decimalLiteral:n}),Qn=n=>Number.isInteger(n)?Ve(n):ai(n),Xn=n=>({type:`${b}/Count`,source:n}),Yn=(n,e)=>({type:`${b}/GreaterThanOrEqual`,compareLeft:n,compareRight:e}),Jn=(n,e)=>({type:`${b}/LessThanOrEqual`,compareLeft:n,compareRight:e});function Ue(n,e){if(!e||e.length===0)return n;let t=new Set(["i","m","s"]),o=[...new Set(e.split(""))];if(o.filter(i=>!t.has(i)).length>0)throw new Error(`sh:flags '${e}' is outside the pinned regex subset (supported: i, m, s)`);return`(?${o.sort().join("")})${n}`}function pe(n){let e=[];return n.minCount!==void 0&&e.push({component:"minCount",per:"node",expr:Yn(Xn(E(X)),Ve(n.minCount))}),n.maxCount!==void 0&&e.push({component:"maxCount",per:"node",expr:Jn(Xn(E(X)),Ve(n.maxCount))}),n.hasValue!==void 0&&e.push({component:"hasValue",per:"node",expr:{type:`${b}/Contains`,haystack:E(X),needle:E($e)}}),(n.inValues!==void 0||n.inRefs!==void 0)&&e.push({component:"in",per:"value",expr:{type:`${b}/Contains`,haystack:E(le),needle:E("v")}}),n.pattern!==void 0&&e.push({component:"pattern",per:"value",expr:{type:`${b}/Matches`,matchSource:E("v"),pattern:Ue(n.pattern.regex,n.pattern.flags)}}),n.minLength!==void 0&&e.push({component:"minLength",per:"value",expr:{type:`${b}/Matches`,matchSource:E("v"),pattern:`(?s)^.{${n.minLength},}$`}}),n.maxLength!==void 0&&e.push({component:"maxLength",per:"value",expr:{type:`${b}/Matches`,matchSource:E("v"),pattern:`(?s)^.{0,${n.maxLength}}$`}}),n.minInclusive!==void 0&&e.push({component:"minInclusive",per:"value",expr:Yn(E("v"),Qn(n.minInclusive))}),n.maxInclusive!==void 0&&e.push({component:"maxInclusive",per:"value",expr:Jn(E("v"),Qn(n.maxInclusive))}),e}import{evaluate as ci,ExpressionError as di}from"@kanonak-protocol/expression";function eo(n,e){let t=ui(e)?e:ue(e),o=[],r=n.catalog.filter(s=>s instanceof g).map(fe),i=new Map;li(r,i);let d={scope:n,membership:new Me(n),embeddedFocus:i};for(let s of t)for(let a of pi(d,s,r))oo(d,s,a,o);return{conforms:!o.some(s=>s.severity==="Violation"),results:o}}function ui(n){return n.length>0&&!(n[0]instanceof Object&&"statement"in n[0])&&typeof n[0].name=="string"&&"properties"in n[0]}function no(n){let e=n.predicate;return e instanceof I?e:void 0}function fe(n){return{node:n,key:Pe(n),uri:k(n),label:n.name}}function je(n,e){return{node:n,key:e,label:e.includes("#")?e.slice(e.indexOf("#")):e}}function li(n,e){we(n.map(t=>t.node),({kanonak:t,address:o})=>{t instanceof L&&!e.has(t)&&e.set(t,je(t,o))})}var Me=class{constructor(e){this.scope=e}scope;ancestors=new Map;isInstance(e,t){let o=l(t);return e.some(r=>l(r)===o||this.ancestorsOf(r).has(o))}ancestorsOf(e){let t=e.version&&typeof e.version.major=="number"?`${l(e)}@${V(e.version)}`:l(e),o=this.ancestors.get(t);return o||(o=this.scope.reasoning?new Set(this.scope.reasoning.getSuperclasses(e)):new Set(_e(this.scope.catalog,e).map(r=>l(r))),this.ancestors.set(t,o)),o}};function pi(n,e,t){let{scope:o}=n,r=new Map,i=s=>{r.set(s.key,s)},d=()=>[...t,...n.embeddedFocus.values()];if(e.targetClass){let s=e.targetClass;if(o.reasoning){let a=new Set(o.reasoning.getInstancesOfClass(s));for(let u of t)u.uri&&a.has(l(u.uri))&&i(u)}else for(let a of t)n.membership.isInstance(j(a.node),s)&&i(a);for(let a of n.embeddedFocus.values())n.membership.isInstance(j(a.node),s)&&i(a)}for(let s of e.targetNodes){let a=_(o.catalog,s);a instanceof g&&i(fe(a))}for(let s of e.targetSubjectsOf){let a=l(s);for(let u of d())u.node.statement.some(c=>{let p=no(c);return p&&l(p.subject)===a})&&i(u)}for(let s of e.targetObjectsOf)for(let a of d())for(let u of ce(a.node,s,o.catalog,a.key))u.kind==="subject"?i(fe(u.node)):u.kind==="embedded"&&i(n.embeddedFocus.get(u.node)??je(u.node,u.address));return[...r.values()]}function fi(n,e,t){return e.node?ce(e.node,t,n.scope.catalog,e.key).map(o=>mi(n,o)):[]}function mi(n,e){switch(e.kind){case"subject":return{kernel:{ref:l(e.uri)},kind:"reference",ref:e.uri,subject:e.node};case"unresolved":return{kernel:{ref:l(e.uri)},kind:"reference",ref:e.uri};case"embedded":{let t=n.embeddedFocus.get(e.node)??je(e.node,e.address);return{kernel:{ref:t.key},kind:"embedded",embedded:t}}case"literal":return typeof e.value=="boolean"?{kernel:e.value?1:0,kind:"boolean",literal:e.value}:{kernel:e.value,kind:typeof e.value=="number"?"number":"string",literal:e.value}}}function oo(n,e,t,o){for(let r of e.properties)ro(n,e,t,r,o);e.closed&&Pi(e,t,o)}function De(n,e,t,o,r={},i){return{focusNode:e.key,focusUri:e.uri,constraintComponent:t,severity:i??to(n),message:o,sourceShape:n.name,sourceShapeUri:n.uri,...r}}function to(n){return n.severity??"Violation"}var hi={minCount:Rn,maxCount:vn,hasValue:se,in:wn,pattern:xn,minLength:Kn,maxLength:Nn,minInclusive:Ln,maxInclusive:In};function ro(n,e,t,o,r){let i=fi(n,t,o.path),d=o.severity??to(e),s=o.path.name,a=[...(o.inValues??[]).map(c=>typeof c=="boolean"?c?1:0:c),...(o.inRefs??[]).map(c=>({ref:l(c)}))],u=(c,p,m)=>{let f=De(e,t,c,o.message??p,{resultPath:o.path,value:m?.literal,valueRef:m?.ref},d);return r.push(f),f};for(let c of pe(o)){let p=hi[c.component];if(c.per==="node"){let m={[X]:i.map(f=>f.kernel),[le]:a};o.hasValue&&(m[$e]={ref:l(o.hasValue)}),Zn(c,m)||u(p,Si(c,s,o,i.length));continue}for(let m of i){if((c.component==="pattern"||c.component==="minLength"||c.component==="maxLength")&&m.kind!=="string"){u(p,`'${s}' value is not a string; ${c.component} applies to string values.`,m);continue}Zn(c,{v:m.kernel,[le]:a})||u(p,bi(c,s,o,m),m)}}if(o.nodeKind)for(let c of i)Ci(o.nodeKind,c)||u(On,`'${s}' value is ${c.kind}; nodeKind requires ${o.nodeKind}.`,c);if(o.datatype)for(let c of i){let p=Ri(o.datatype,c);p&&u(Pn,`'${s}' ${p}`,c)}if(o.classRef)for(let c of i){let p=vi(n,o.classRef,c);p&&u(_n,`'${s}' ${p}`,c)}o.qualified&&ki(n,o,i,s,u)}function Si(n,e,t,o){switch(n.component){case"minCount":return`'${e}' has ${o} value(s); minCount is ${t.minCount}.`;case"maxCount":return`'${e}' has ${o} value(s); maxCount is ${t.maxCount}.`;case"hasValue":return`'${e}' has no value equal to ${t.hasValue?l(t.hasValue):"(unset)"}.`;default:return`'${e}' violates ${n.component}.`}}function ki(n,e,t,o,r){let i=e.qualified,d=i.maxCount!==void 0?G:B,s=(u,c)=>{io.add(r(d,u,c))};if(!i.shape){s(`'${o}' qualified value shape cannot be evaluated: ${i.problem??"it could not be built"}.`);return}let a=0;for(let u of t){let c=u.ref?l(u.ref):u.embedded?u.embedded.label:JSON.stringify(u.literal),p=gi(n,u);if(!p){s(`'${o}' value ${c} does not resolve in this scope; whether it conforms to the qualified shape cannot be decided.`,u);continue}let m=Ei(n,i.shape,p);if(m.kind==="undecided"){s(`'${o}' value ${c}: whether it conforms to the qualified shape cannot be decided \u2014 ${m.reason}`,u);continue}m.kind==="conforms"&&a++}i.minCount!==void 0&&a<i.minCount&&r(B,`'${o}' has ${a} value(s) that conform to the qualified shape; qualifiedMinCount is ${i.minCount}.`),i.maxCount!==void 0&&a>i.maxCount&&r(G,`'${o}' has ${a} value(s) that conform to the qualified shape; qualifiedMaxCount is ${i.maxCount}.`)}function gi(n,e){switch(e.kind){case"reference":return e.subject?fe(e.subject):void 0;case"embedded":return e.embedded;default:{let t=JSON.stringify(e.literal);return{key:t,label:t}}}}var yi={name:"(qualified value shape)",targetNodes:[],targetSubjectsOf:[],targetObjectsOf:[],closed:!1,ignoredProperties:[],properties:[]},io=new WeakSet;function Ei(n,e,t){let o=[];e.kind==="property"?ro(n,yi,t,e.constraint,o):oo(n,e.shape,t,o);let r=o.find(i=>io.has(i));return r?{kind:"undecided",reason:r.message}:o.length===0?{kind:"conforms"}:{kind:"fails"}}function bi(n,e,t,o){let r=o.ref?l(o.ref):o.embedded?o.embedded.label:JSON.stringify(o.literal);switch(n.component){case"in":return`'${e}' value ${r} is not in the permitted set.`;case"pattern":return`'${e}' value ${r} does not match pattern ${t.pattern?.regex}.`;case"minLength":return`'${e}' value ${r} is shorter than minLength ${t.minLength}.`;case"maxLength":return`'${e}' value ${r} is longer than maxLength ${t.maxLength}.`;case"minInclusive":return`'${e}' value ${r} is below minInclusive ${t.minInclusive} (or not numeric).`;case"maxInclusive":return`'${e}' value ${r} is above maxInclusive ${t.maxInclusive} (or not numeric).`;default:return`'${e}' value ${r} violates ${n.component}.`}}function Zn(n,e){let t=o=>{let r=o.varName;if(o.type==="kanonak.org/transformations/VarRef"&&typeof r=="string"&&r in e)return e[r];throw new di(`Conformance lowering produced an unexpected leaf '${o.type}'`)};return ci(n.expr,void 0,t)===1}function Ci(n,e){switch(n){case"IRI":return e.kind==="reference";case"BlankNode":return e.kind==="embedded";case"Literal":return e.kind==="string"||e.kind==="number"||e.kind==="boolean"}}function Ri(n,e){if(e.kind==="reference"||e.kind==="embedded")return`value is a ${e.kind}; sh:datatype requires a literal of ${n.name}.`;let t=xe(n);if(t!==void 0)switch(t){case $.Boolean:return e.kind==="boolean"?void 0:`value is not a boolean (${n.name}).`;case $.Integer:return e.kind!=="number"?`value is not a number (${n.name}).`:Number.isInteger(e.literal)?void 0:`value is not an integer (${n.name}).`;case $.Decimal:case $.Double:case $.Float:return e.kind==="number"?void 0:`value is not a number (${n.name}).`;default:return e.kind==="string"?void 0:`value is not a string-carried literal (${n.name}).`}}function vi(n,e,t){if(t.kind==="embedded"&&t.embedded?.node){let r=j(t.embedded.node);return r.length===0?`value ${t.embedded.label} has no type; sh:class requires an instance of ${e.name}.`:n.membership.isInstance(r,e)?void 0:`value ${t.embedded.label} is not an instance of ${e.name}.`}if(t.kind!=="reference"||!t.ref)return`value is not a reference; sh:class requires an instance of ${e.name}.`;if(n.scope.reasoning)return n.scope.reasoning.isInstanceOf(t.ref,e)?void 0:`value ${l(t.ref)} is not an instance of ${e.name}.`;let o=t.subject;return o?n.membership.isInstance(j(o),e)?void 0:`value ${l(t.ref)} is not an instance of ${e.name}.`:`value ${l(t.ref)} does not resolve in this scope (sh:class ${e.name}).`}function Pi(n,e,t){if(!e.node)return;let o=new Set([...n.properties.map(i=>l(i.path)),...n.ignoredProperties.map(i=>l(i))]),r=new Set;for(let i of e.node.statement){let d=no(i);if(!d)continue;let s=l(d.subject);o.has(s)||r.has(s)||(r.add(s),t.push(De(n,e,Ce,`'${e.label}' carries undeclared property '${d.subject.name}' (closed shape).`,{resultPath:d.subject})))}for(let i of e.node.unresolvedPredicates)r.has(i.key)||(r.add(i.key),t.push(De(n,e,Ce,`'${e.label}' carries unresolvable property '${i.key}' (closed shape).`,{value:i.key})))}var _i="1.1.0",wi=new Set([se,B,G].map(n=>n.name));async function ao(n){let e=new Q(n.repository),t=e.imports(),o=n.result.results.some(a=>wi.has(a.constraintComponent.name))?"1.2.0":_i,r=t.ensure(te,re,o,"sh"),i=(a,u)=>a&&a.version&&typeof a.version.major=="number"?`${t.ensure(a.publisher,a.package_,V(a.version),a.package_)}.${a.name}`:u,d={},s=[];return n.result.results.forEach((a,u)=>{let c=`result-${u+1}`;s.push(c);let p={type:`${r}.ValidationResult`,[`${r}.focusNode`]:i(a.focusUri,a.focusNode),[`${r}.resultMessage`]:a.message,[`${r}.resultSeverity`]:`${r}.${a.severity}`,[`${r}.sourceConstraintComponent`]:`${r}.${a.constraintComponent.name}`};a.resultPath&&(p[`${r}.resultPath`]=i(a.resultPath,l(a.resultPath))),a.sourceShapeUri&&(p[`${r}.sourceShape`]=i(a.sourceShapeUri,a.sourceShape)),a.valueRef?p[`${r}.value`]=i(a.valueRef,l(a.valueRef)):a.value!==void 0&&(p[`${r}.value`]=a.value),d[c]=p}),d.report={type:`${r}.ValidationReport`,[`${r}.conforms`]:n.result.conforms,...s.length>0?{[`${r}.result`]:s}:{}},e.buildContentAddressed({publisher:n.publisher,book:t,body:d,...n.header!==void 0?{header:n.header}:{},contentHashProperty:"contentHash"})}import{VersionOperator as Cs}from"@kanonak-protocol/types/document/models/enums";import{spawn as xi}from"child_process";var co=12e4,Ki=4096,Y=class{argv;interactive;timeoutMs;stderr;now;constructor(e){this.argv=uo(e.command),this.interactive=e.interactive??!1,this.timeoutMs=e.timeoutMs??co,this.stderr=e.stderr??process.stderr,this.now=e.nowSeconds??(()=>Date.now()/1e3)}get command(){return this.argv.join(" ")}async get(e){let t=await this.run("get",this.wireRequest("get",e)),o=Ie(e,t,this.now());if(!o.ok)throw new N(`credential helper '${this.command}' answered get for ${e.resource} outside the protocol (${o.problem}): ${o.message}`);return o.answer}async erase(e){let t=await this.run("erase",{...this.wireRequest("erase",e),scope:e.scope}),o=Oe(t);if(!o.ok)throw new N(`credential helper '${this.command}' answered erase for ${e.resource} outside the protocol (${o.problem}): ${o.message}`)}wireRequest(e,t){let o={version:Le,operation:e,resource:t.resource,method:t.method};return t.challenges&&(o.challenges=t.challenges),o.interactive=this.interactive,o}run(e,t){let o=`credential helper '${this.command}' ${e}`;return new Promise((r,i)=>{let d=!1,s=f=>{d||(d=!0,f())},a;try{a=xi(this.argv[0],[...this.argv.slice(1),e],{stdio:["pipe","pipe","pipe"],shell:!1,windowsHide:!0})}catch(f){i(so(o,f));return}let u=[],c="",p=!1,m=setTimeout(()=>{p=!0,a.kill()},this.timeoutMs);a.stdout.on("data",f=>u.push(f)),a.stderr.on("data",f=>{this.stderr.write(f),c=(c+f.toString("utf8")).slice(-Ki)}),a.on("error",f=>{clearTimeout(m),s(()=>i(so(o,f)))}),a.on("close",(f,A)=>{clearTimeout(m);let v=c.trim()?`: ${c.trim()}`:"";if(p){s(()=>i(new N(`${o} did not finish within ${Math.round(this.timeoutMs/1e3)}s${v}`)));return}if(f!==0){let x=f!==null?`exit ${f}`:`signal ${A}`;s(()=>i(new N(`${o} failed (${x})${v}`)));return}let U=Buffer.concat(u).toString("utf8").trim();try{let x=JSON.parse(U);s(()=>r(x))}catch{s(()=>i(new N(`${o} exited 0 without printing one JSON answer${v}`)))}}),a.stdin.on("error",()=>{}),a.stdin.end(`${JSON.stringify(t)}
2
+ `)})}};function uo(n){let e=n.trim().split(/\s+/).filter(t=>t!=="");if(e.length===0)throw new Error("the credential helper command is empty");return e}function so(n,e){let t=e.code,o="";return t==="ENOENT"&&(o=" (not found: give its path, or put it on PATH)"),t==="EINVAL"&&process.platform==="win32"&&(o=" (a .cmd or .bat file cannot run without a shell: configure an executable, e.g. `node path/to/helper.js`)"),new N(`${n} could not be started: ${e.message}${o}`)}import{existsSync as Ni,readFileSync as Li}from"fs";import{homedir as Ii}from"os";import{join as Oi}from"path";var He="KANONAK_CREDENTIAL_HELPER";function lo(){return Oi(Ii(),".kanonak","config.json")}function Ai(n={}){let e=n.env??process.env,t=n.configPath??lo(),o=Vi(e,t);if(o){let i=Object.keys(e).filter(d=>(d===de||d.startsWith(`${de}_`))&&(e[d]??"").trim()!=="").sort();if(i.length>0)throw new Error(`A credential helper is configured (${o.source}: ${o.command}) and so is ${i.join(", ")}. Configure one or the other.`);return new Y({command:o.command,interactive:n.interactive??!1})}let r={env:e};return n.discovery&&(r.discovery=n.discovery),new Ae(r)}function Vi(n,e){let t=(n[He]??"").trim();if(t)return{command:t,source:He};if(!Ni(e))return;let o;try{o=JSON.parse(Li(e,"utf-8"))}catch(i){throw new Error(`${e} is not valid JSON: ${i.message}`)}if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`${e} must hold a JSON object`);let r=o.credentialHelper;if(r!==void 0){if(typeof r!="string"||r.trim()==="")throw new Error(`"credentialHelper" in ${e} must be a non-empty command line`);return{command:r.trim(),source:e}}}var C="kanonak.org",w="view",po="core-kanonak",$i={publisher:C,package_:w,name:"rootView"},Ui={publisher:C,package_:w,name:"bind"},Mi={publisher:C,package_:w,name:"produces"},Di={publisher:C,package_:w,name:"projections"},ji={publisher:C,package_:w,name:"where"},Hi={publisher:C,package_:w,name:"value"},Fi={publisher:C,package_:w,name:"as"},me=class{constructor(e,t=new F){this.repository=e;this.parser=t;this.objectParser=new H(this.parser),this.builder=new Q(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let o=await this.objectParser.parseKanonaks(this.repository),r=this.resolveView(o,e),i=S(r,Ui);if(!i)throw new Error(`View ${r.namespace}/${r.name} declares no view.bind; cannot materialize.`);let d=S(r,Mi);if(!d)throw new Error(`View ${r.namespace}/${r.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=Ti(r),a=fo(o,C,po),u=fo(o,C,w),c=this.builder.imports(),p=c.ensure(C,po,a,"ck"),m=c.ensure(C,w,u,"v"),f=c.ref(d),A=new Mn(this.repository,this.parser,this.objectParser),v=new Un(A,o),U=this.readProjections(o,r),x=Bi(r,ji),J=this.findInstances(o,i,await this.reason(t)),h={},K=new Set;for(let Z of J){if(!await this.passesWhere(v,o,x,Z))continue;let he={type:f};for(let Te of U){let ho=await this.evaluateValue(v,o,Te.value,Z),We=this.builder.serializeValue(mo(ho),c);We!==void 0&&(he[c.ref(Te.as)]=We)}let Fe=k(Z);Fe&&(he[`${m}.derivedFrom`]=c.ref(Fe)),h[this.rowName(Z,K)]=he}let y={};t.resolvedAt&&(y[`${p}.resolvedAt`]=t.resolvedAt),t.invocationId&&(y[`${p}.id`]=t.invocationId);let P=await this.builder.buildContentAddressed({publisher:s,book:c,body:h,contentHashProperty:`${p}.contentHash`,header:y});return{yaml:P.yaml,contentHash:P.contentHash,packageName:P.packageName,publisher:P.publisher,rowCount:P.resourceCount}}resolveView(e,t){let o=_(e,t);if(!o)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let r=S(o,$i);if(r){let i=_(e,r);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${r.name}, which is not in the catalog.`);return i}return o}readProjections(e,t){let o=[];for(let r of ge(t,Di)){let i=r instanceof L?r:r instanceof I?_(e,r.subject):void 0;if(!i)continue;let d=T(i,Hi),s=S(i,Fi);d&&s&&o.push({value:d,as:s})}return o}async reason(e){return new z({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,o){let r=qi(e),i=[],d=new Set;for(let s of o.getInstancesOfClass(t)){if(d.has(s))continue;d.add(s);let a=r.get(s);a&&i.push(a)}return i.sort((s,a)=>{let u=W(k(s)),c=W(k(a));return u<c?-1:u>c?1:0}),i}async passesWhere(e,t,o,r){for(let i of o){let d=await this.evaluateValue(e,t,i,r);if(!Gi(d))return!1}return!0}async evaluateValue(e,t,o,r){let i=$n(o,"view-projection",{catalog:t,depth:0}),d=new Map([["input",r]]);return e.evaluate(i,d)}rowName(e,t){let o=Ne(e.name)||"row",r=o,i=2;for(;t.has(r);)r=`${o}-${i++}`;return t.add(r),r}};function mo(n){return Ke(n)?n.value:Array.isArray(n)?n.map(mo):n}function Ti(n){let e=k(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function fo(n,e,t){let o=Wi(n,e,t);if(!o)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return o}function Wi(n,e,t){let o;for(let r of n){if(!(r instanceof g))continue;let i=k(r);!i||i.publisher!==e||i.package_!==t||!i.version||(!o||ee(i.version,o)>0)&&(o=i.version)}return o?V(o):void 0}function qi(n){let e=new Map,t=new Map;for(let o of n){if(!(o instanceof g))continue;let r=k(o);if(!r||!r.version)continue;let i=W(r),d=t.get(i);(!d||ee(r.version,d)>0)&&(t.set(i,r.version),e.set(i,o))}return e}function Bi(n,e){let t=T(n,e);return t?[t]:ge(n,e).filter(o=>o instanceof L)}function Gi(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Ke(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{dr as AmbiguousReferenceRule,ot as BooleanStatement,Mr as CANONICAL_FORM_VERSION,Qr as CREDENTIAL_EXPIRY_SKEW_SECONDS,He as CREDENTIAL_HELPER_ENV,Le as CREDENTIAL_HELPER_PROTOCOL_VERSION,co as CREDENTIAL_HELPER_TIMEOUT_MS,$ as Carrier,hr as ClassDefinitionRule,or as ClassHierarchyCycleRule,wo as CompositeKanonakDocumentRepository,N as CredentialError,qr as DEFAULT_CONSENT_BINDING_PARAM,Qo as DefinedKanonak,Ar as DiamondNameClashRule,kr as DisplayLensScopeRule,_o as DocumentLocation,_t as EdgeType,L as EmbeddedKanonak,Zt as EmbeddedKanonakTypeRule,rt as EmbeddedStatement,oi as EntitlementDeniedError,ti as EntitlementProducer,Y as ExecCredentialProvider,Po as FileSystemKanonakDocumentRepository,It as GitIgnoreFilter,wt as GraphBuilder,To as HttpKanonakDocumentRepository,Be as INTEGRITY_PREFIX,jr as ImportBook,er as ImportExistenceRule,Se as InMemoryKanonakDocumentRepository,Ao as KANONAK_USER_AGENT,zo as Kanonak,At as KanonakDocumentPositions,No as KanonakHttpError,H as KanonakObjectParser,Vr as KanonakObjectValidator,F as KanonakParser,Xo as KanonakUri,Dt as KanonakUriBuilder,jt as KanonakUrlResolver,kt as KanonakVocabulary,Rr as LINE_STYLES,Gt as LinkTargetRule,it as ListStatement,Yo as LiteralKanonak,Wo as LocalFirstRepository,qo as LockAwareRepository,Nr as LookBandPathRule,wr as LookRenderer,gr as LookSemanticSvgPathRule,Sr as MarkdownLinkRule,at as MarkdownStatement,sr as NamespaceImportCycleRule,zt as NamespacePrefixRule,Pt as NodeType,nt as NumberStatement,Br as OAuthDiscovery,Nt as OWL_RL_CLASSIFICATION_RULES,lr as ObjectPropertyValueValidationRule,Wt as OntologyValidationError,Ft as OntologyValidationResult,Or as OwlOneOfRule,Q as PackageBuilder,Jt as PackageHeaderRule,Zr as ProducerRepository,pr as PropertyDomainRule,tr as PropertyHierarchyCycleRule,fr as PropertyKindRangeConsistencyRule,Ot as PropertyMetadata,ur as PropertyRangeReferenceRule,rr as PropertyRangeRequiredRule,Xt as PropertyTypeSpecificityRule,jo as PublisherConfigResolver,Ho as PublisherIndex,Kt as RDFS_RULES,z as Reasoner,Lt as ReasoningResult,I as ReferenceKanonak,tt as ReferenceStatement,Ko as RepositoryFactory,mr as ReservedNameShadowRule,Qt as ResourceNamingRule,st as ResourceResolver,gt as ResourceTypeClassifier,re as SHACL_PACKAGE,te as SHACL_PUBLISHER,q as SH_NODE_SHAPE,ie as SH_PROPERTY_SHAPE,Xe as SH_SHAPE,Zo as ScalarStatement,Kr as SequenceNarrativeRule,Ir as ShaclShapeRule,Jo as Statement,et as StringStatement,ir as SubClassOfReferenceRule,ar as SubPropertyOfReferenceRule,g as SubjectKanonak,Yt as SubjectKanonakTypeRequiredRule,de as TOKEN_ENV,Ae as TokenCredentialProvider,xt as TripleStore,yr as TxExpressionCompilesRule,Lr as TxExpressionPathRule,ct as TypeResolver,Er as URI_DISPLAY_LABEL,br as URI_DISPLAY_SUMMARY,cr as UnresolvedPredicateRule,nr as UnresolvedReferenceRule,Bt as ValidationCache,qt as ValidationContext,Tt as ValidationSeverity,Cs as VersionOperator,me as ViewMaterializer,ei as allowAllPolicy,Uo as assertHttpsUrl,Fo as assertPackageIdentity,Go as buildLocalFirstRepository,_r as buildOntologyModel,ao as buildReportPackageAsync,ue as buildShapesModel,ht as builtinHomePackages,St as builtinUri,$r as canonicalForm,Ur as canonicalHash,xe as carrierOf,Gr as checkCredentialAnswer,Ie as checkHelperAnswer,Oe as checkHelperEraseAnswer,Bo as collectKanonakFiles,ee as compareVersions,Hn as computeIntegrity,Qe as computeIntegrityAsync,Dr as contentAddressedName,j as contextTypesOf,Xr as createCredentialedFetch,yo as createVersion,Ai as credentialProviderFromConfig,Io as describeResponse,eo as evaluateConformance,vt as extractMarkdownLinks,Jr as findDerivation,Rt as findMalformedReferences,$t as findMarkdownLinkAt,Ue as foldFlagsIntoPattern,ut as formatKanonakAddress,V as formatVersion,xo as getGlobalCachePath,$o as getKanonakUserAgent,Lo as httpError,bo as isCompatibleVersion,Co as isMajorCompatible,Et as isPropertySubject,Mo as kanonakFetch,Dn as loadLockFile,qe as lockedVersion,pe as lowerConstraint,pt as makeUriKey,Wr as narrowestScope,ni as noopMeter,Hr as normalizeHost,dt as parseKanonakAddress,Ge as parseLockFile,Fr as parseScope,Eo as parseVersionString,Vt as parseWithPositions,zr as parseWwwAuthenticate,vo as pickHighestDocument,bt as propertiesInScope,yt as propertyClassOf,vr as readSequenceConnectors,Ht as referenceSpelling,M as referenceUris,Cr as resolveDisplayValue,Ct as resolvePropertyStep,Oo as retryAfterSecondsOf,Ne as sanitizeName,Ro as satisfiesVersionOperator,jn as saveLockFile,Tr as scopeContains,Tn as scopeFromCatalog,Wn as scopeFromDocumentAsync,Fn as scopeFromRepositoryAsync,ze as serializeLockFile,Do as setKanonakFetchRetries,Vo as setKanonakUserAgent,Mt as sourceSymbolAt,Ut as sourceSymbols,uo as splitCommandLine,Pe as subjectAddress,k as subjectUri,_e as superClassChain,xr as supportedBandKeys,Yr as tokenEnvKeyFor,ft as tripleKey,lt as typeReferenceUris,W as uriKey,mt as uriTriple,lo as userConfigPath,ce as valuesOf,So as versionOperatorFromChar,ko as versionOperatorToChar,go as versionsEqual,we as walkDefinedKanonaks,Pr as walkSequence};
@@ -1 +1 @@
1
- import{a as c,b as d,c as e,d as f,e as g,f as h}from"../chunk-W5AOJ5SJ.js";import{j as b}from"../chunk-3353RWDC.js";import{a}from"../chunk-7JBKOJB4.js";import"../chunk-NUTHBBDZ.js";import"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{d as KanonakDocumentPositions,b as KanonakObjectParser,a as KanonakParser,c as PropertyMetadata,f as findMarkdownLinkAt,e as parseWithPositions,h as sourceSymbolAt,g as sourceSymbols};
1
+ import{a as c,b as d,c as e,d as f,e as g,f as h}from"../chunk-GKIX3OD6.js";import{k as b}from"../chunk-22DSABP6.js";import{a}from"../chunk-7JBKOJB4.js";import"../chunk-NUTHBBDZ.js";import"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{d as KanonakDocumentPositions,b as KanonakObjectParser,a as KanonakParser,c as PropertyMetadata,f as findMarkdownLinkAt,e as parseWithPositions,h as sourceSymbolAt,g as sourceSymbols};
@@ -1 +1 @@
1
- import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i}from"../chunk-4CXAZH3C.js";import"../chunk-QHABFCRC.js";import"../chunk-3353RWDC.js";import"../chunk-7JBKOJB4.js";import"../chunk-NUTHBBDZ.js";import"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{h as EntitlementDeniedError,i as EntitlementProducer,c as ImportBook,a as PackageBuilder,e as ProducerRepository,f as allowAllPolicy,b as contentAddressedName,g as noopMeter,d as sanitizeName};
1
+ import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i}from"../chunk-ADSDFJUO.js";import"../chunk-QHABFCRC.js";import"../chunk-22DSABP6.js";import"../chunk-7JBKOJB4.js";import"../chunk-NUTHBBDZ.js";import"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{h as EntitlementDeniedError,i as EntitlementProducer,c as ImportBook,a as PackageBuilder,e as ProducerRepository,f as allowAllPolicy,b as contentAddressedName,g as noopMeter,d as sanitizeName};
@@ -1 +1 @@
1
- import{a as i,b as j,c as k,d as l,e as m}from"../chunk-LE26SEJU.js";import"../chunk-3353RWDC.js";import"../chunk-7JBKOJB4.js";import{c as a,d as b,e as c,g as d,ha as e,ia as f,ja as g,ka as h}from"../chunk-NUTHBBDZ.js";import"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{h as KanonakVocabulary,k as OWL_RL_CLASSIFICATION_RULES,j as RDFS_RULES,m as Reasoner,l as ReasoningResult,i as TripleStore,e as builtinHomePackages,f as builtinUri,g as canonicalizeBuiltinUri,b as makeUriKey,c as tripleKey,a as uriKey,d as uriTriple};
1
+ import{a as i,b as j,c as k,d as l,e as m}from"../chunk-A3HRXFVX.js";import"../chunk-22DSABP6.js";import"../chunk-7JBKOJB4.js";import{c as a,d as b,e as c,g as d,ha as e,ia as f,ja as g,ka as h}from"../chunk-NUTHBBDZ.js";import"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{h as KanonakVocabulary,k as OWL_RL_CLASSIFICATION_RULES,j as RDFS_RULES,m as Reasoner,l as ReasoningResult,i as TripleStore,e as builtinHomePackages,f as builtinUri,g as canonicalizeBuiltinUri,b as makeUriKey,c as tripleKey,a as uriKey,d as uriTriple};
@@ -1 +1 @@
1
- import{h as e,n as r,o as n}from"../chunk-OOYGILH4.js";import"../chunk-SC5M74NM.js";import{a as o}from"../chunk-6VIUXP4N.js";import"../chunk-7JBKOJB4.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
1
+ import{m as e,s as r,t as n}from"../chunk-HKQTB65D.js";import"../chunk-SC5M74NM.js";import{a as o}from"../chunk-6VIUXP4N.js";import"../chunk-7JBKOJB4.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
@@ -1 +1 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m,i as n}from"../chunk-HKX27KBZ.js";import{g,h,n as i,o as j}from"../chunk-OOYGILH4.js";import"../chunk-SC5M74NM.js";import{a}from"../chunk-6VIUXP4N.js";import"../chunk-7JBKOJB4.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,l as LockAwareRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,n as buildLocalFirstRepository,m as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m,i as n}from"../chunk-7F2EAT5Y.js";import{l as g,m as h,s as i,t as j}from"../chunk-HKQTB65D.js";import"../chunk-SC5M74NM.js";import{a}from"../chunk-6VIUXP4N.js";import"../chunk-7JBKOJB4.js";import"../chunk-F67UH4FD.js";import"../chunk-QILEJIFU.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,l as LockAwareRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,n as buildLocalFirstRepository,m as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
@@ -1,4 +1,4 @@
1
- import"../chunk-D2X6J77P.js";import"../chunk-SC5M74NM.js";import{f as g}from"../chunk-EG47OOJC.js";import"../chunk-QHABFCRC.js";import"../chunk-6VIUXP4N.js";import"../chunk-3353RWDC.js";import"../chunk-7JBKOJB4.js";import"../chunk-PEJALHXK.js";import{na as m,va as S}from"../chunk-NUTHBBDZ.js";import{c as v,r as p,z as E}from"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import{c as x}from"../chunk-QILEJIFU.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
1
+ import"../chunk-D2X6J77P.js";import"../chunk-SC5M74NM.js";import{f as g}from"../chunk-TYVZXABI.js";import"../chunk-QHABFCRC.js";import"../chunk-6VIUXP4N.js";import"../chunk-22DSABP6.js";import"../chunk-7JBKOJB4.js";import"../chunk-PEJALHXK.js";import{na as m,va as S}from"../chunk-NUTHBBDZ.js";import{c as v,r as p,z as E}from"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import{c as x}from"../chunk-QILEJIFU.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
2
2
  Install it with:
3
3
  npm install @huggingface/transformers
4
4
  (underlying import error: ${e.message})`)}return F({transformers:r})})()),y}function H(r,e){let t=0;for(let n=0;n<r.length;n++)t+=r[n]*e[n];return t}function R(r,e){return e?r.version?e.version?x(r.version,e.version)>0:!0:!1:!0}function K(r,e){let t=g(r,e),n=[t.label],s=S(e);if(s.length>0){let i=E(r,s[0]),a=i?g(r,i).label:s[0].name;a&&n.push(`\u2014 a ${a}.`)}return t.summary&&n.push(t.summary),n.join(" ")}function q(r){let e=new Map;for(let t of r){if(!(t instanceof v))continue;let n=m(t);if(!n)continue;let s=p(n),i=e.get(s);(!i||R(n,m(i)))&&e.set(s,t)}return[...e.values()].sort((t,n)=>{let s=m(t)?p(m(t)):t.name,i=m(n)?p(m(n)):n.name;return s.localeCompare(i)})}var k=class{entries=[];embedder;constructor(e={}){this.embedder=e.embedder}resolveEmbedder(){return this.embedder?Promise.resolve(this.embedder):U()}get size(){return this.entries.length}async build(e,t={}){let n=q(e);if(t.include&&(n=n.filter(t.include)),n.length===0)return this.entries=[],{size:0,cached:!1};let s=n.map(o=>K(e,o)),i=t.cacheDir,a;if(i){let o=C("sha256").update(h+"|"+w+`
@@ -1,7 +1,7 @@
1
- import{c as Pe}from"../chunk-DONOB6RA.js";import{a as be,d as Z,f as Se,h as re}from"../chunk-HKX27KBZ.js";import{e as ve,g as $e,n as U,o as ee}from"../chunk-OOYGILH4.js";import"../chunk-D2X6J77P.js";import"../chunk-SC5M74NM.js";import{a as H,b as q}from"../chunk-VORVR5BZ.js";import{t as ne}from"../chunk-EG47OOJC.js";import"../chunk-QHABFCRC.js";import{a as ye}from"../chunk-6VIUXP4N.js";import{j as te}from"../chunk-3353RWDC.js";import{a as O}from"../chunk-7JBKOJB4.js";import{a as _e}from"../chunk-PEJALHXK.js";import"../chunk-NUTHBBDZ.js";import{A as oe,c as we,p as xe}from"../chunk-D4QGPMRW.js";import{a as Re}from"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import{c as V,e as j,f as W,g as Q}from"../chunk-QILEJIFU.js";import{readFileSync as pe,writeFileSync as Me,mkdirSync as Ee}from"fs";import{join as ae}from"path";import De from"js-yaml";var je=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function G(r){return je}function N(r){return`${r.publisher}/${r.package_}`}function z(r,e=[]){let i={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},o=[];for(let t of r)if(t.origin==="missing"){let a=N(t),u=i[a]??"whatever this package contributes to rendering is lost";o.push(`Render-stack package ${a} is MISSING (${t.reason??"unknown reason"}) \u2014 ${u}. Fix: kanonak install ${a} (as the user running the render), or restore network access to ${t.publisher}.`)}else t.resolvedButNotInCatalog&&o.push(`Render-stack package ${N(t)} resolved (${t.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let t of e)o.push(`Import edge ${t.fromNamespace} \u2192 ${t.publisher}/${t.packageName} ${t.constraint} did NOT resolve (${t.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${t.fromNamespace} authors against ${t.publisher}/${t.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${t.constraint}-compatible version of ${t.publisher}/${t.packageName} to the workspace or cache (kanonak install ${t.publisher}/${t.packageName}), or bump the import in ${t.fromNamespace}.`);return o}function se(r){let{publisher:e,availablePublishers:i,catalog:o,lookRenderer:t,localNamespaces:a,rawByNsKey:u,renderStack:d,producers:k,lockSource:y,configSource:s}=r,l=new Map,f=new Map,p=new Map,m=new Set;for(let S of o){if(!(S instanceof we))continue;let w=S.namespace||"";if(!a.has(w))continue;l.set(`${w}/${S.name}`,S);let _=w.split("/")[1]??"",[P,E]=_.split("@");if(!P||!E)continue;let D=Q(E);D&&(m.has(_)||(m.add(_),f.has(P)||f.set(P,[]),f.get(P).push({verStr:E,version:D})),S.name===P&&p.set(_,S))}for(let S of f.values())S.sort((w,_)=>V(_.version,w.version));return{publisher:e,availablePublishers:i,catalog:o,lookRenderer:t,localNamespaces:a,rawByNsKey:u,bySubject:l,pkgVersions:f,pkgSelfByVer:p,renderStack:d,...k?{producers:k}:{},...y?{lockSource:y}:{},...s?{configSource:s}:{}}}async function ue(r,e={}){let i=new O,o=new ye(i),t=[],a=[];for(let c of re(r)){let h;try{h=pe(c,"utf-8")}catch{continue}let n;try{n=i.parse(h).metadata?.namespace_}catch{continue}if(!n?.version)continue;let g=n.version;a.push({publisher:n.publisher,package_:n.package_,verStr:j(g),version:g,source:h})}a.sort((c,h)=>V(h.version,c.version));for(let c of a)await o.saveDocumentAsync(i.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),t.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let u=[...new Set(t.map(c=>c.publisher))].sort(),d=e.publisher;if(d){if(!u.includes(d))throw new Error(`Publisher "${d}" not found in workspace. Available: ${u.join(", ")||"(none)"}`)}else if(u.length===1)d=u[0];else throw u.length===0?new Error(`No Kanonak packages found under ${r}`):new Error(`Workspace has multiple publishers (${u.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let k=new Set,y=new Map;for(let c of t)c.publisher===d&&(k.add(`${c.publisher}/${c.package_}@${c.verStr}`),y.set(`${c.package_}@${c.verStr}`,c.source));let s=Z(),l=new be(s,!0,i),f={};e.httpCache&&(f.getFromCache=e.httpCache.getFromCache,f.onFetch=e.httpCache.onFetch),e.fetchFn&&(f.fetchFn=e.fetchFn);let p=e.repository??new Se(o,l,new ee(f)),m=e.log??(()=>{}),S=G(void 0),w=[],_=c=>c.map(h=>h.metadata.namespace_?.version).filter(h=>h!==void 0).sort((h,n)=>V(n,h)).map(j);if(!e.repository){m(`[render-stack] resolving ${S.length} ambient look-stack package(s); cache: ${s}`);let c=e.fetchFn?new U({fetchFn:e.fetchFn}):new U;for(let h of S){let n=N(h),g=await o.getDocumentsByNamespaceAsync(h.publisher,h.package_);if(g.length>0){let v=_(g);w.push({...h,origin:"workspace",versions:v}),m(`[render-stack] ${n} \u2014 workspace (${v.join(", ")})`);continue}let b=await l.getDocumentsByNamespaceAsync(h.publisher,h.package_);if(b.length>0){let v=_(b);w.push({...h,origin:"cache",versions:v}),m(`[render-stack] ${n} \u2014 cache (${v.join(", ")})`);continue}try{let $=(await c.getLock(h.publisher))?.packages[`${h.publisher}/${h.package_}`];if(!$){let C=`publisher ${h.publisher} reachable but its lock does not pin ${h.package_}`;w.push({...h,origin:"missing",reason:C}),m(`[render-stack] ${n} \u2014 MISSING: ${C}`);continue}let F=$.version,T=$.resolved,X=await(e.fetchFn?e.fetchFn(T,h.publisher):ve(T));if(!X.ok){let C=`fetch ${T} failed: HTTP ${X.status} ${X.statusText}`;w.push({...h,origin:"missing",reason:C}),m(`[render-stack] ${n} \u2014 MISSING: ${C}`);continue}let ke=await X.text();await o.saveDocumentAsync(i.parse(ke),`${h.publisher}/${h.package_}@${F}`);try{let C=ae(s,h.publisher);Ee(C,{recursive:!0}),Me(ae(C,`${h.package_}@${F}.kan.yml`),ke,"utf-8"),w.push({...h,origin:"fetched",versions:[F]}),m(`[render-stack] ${n}@${F} \u2014 fetched from ${T}, installed to cache`)}catch(C){w.push({...h,origin:"fetched",versions:[F]}),m(`[render-stack] ${n}@${F} \u2014 fetched from ${T}, but cache ${s} is NOT WRITABLE (${C.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(v){let $=`fetch failed: ${v.message}`;w.push({...h,origin:"missing",reason:$}),m(`[render-stack] ${n} \u2014 MISSING: ${$}`)}}}let P=(await o.getAllDocumentsAsync()).filter(c=>c.metadata.namespace_?.publisher===d);for(let c of S)P.push(...await p.getDocumentsByNamespaceAsync(c.publisher,c.package_));let E=[],D=await H(P,p,{onUnresolvedEdge:c=>E.push(c)}),A=p;if(!e.repository){for(let c of S)D.add(N(c));A=new q(p,D)}let B=await new te(i).parseKanonaks(A),le=new ne(B),de=(c,h)=>oe(B,{publisher:c,package_:h,name:h}).length>0,I;if(e.repository){I=[];for(let c of S){let h=await p.getDocumentsByNamespaceAsync(c.publisher,c.package_);I.push(h.length>0?{...c,origin:"repository",versions:_(h)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else I=w.map(c=>c.origin==="missing"||de(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let Y=z(I,E);for(let c of Y)m(`[render-stack] WARNING: ${c}`);let J={contractSource:"universal-default",cachePath:s,packages:I,warnings:Y},K;try{K=pe(ae(r,"kanonak.lock"),"utf-8")}catch{K=Ke(d,t,i)}let L;try{L=pe(ae(r,".well-known","kanonak.json"),"utf-8")}catch{L=void 0}return se({publisher:d,availablePublishers:u,catalog:B,lookRenderer:le,localNamespaces:k,rawByNsKey:y,renderStack:J,...K?{lockSource:K}:{},...L?{configSource:L}:{}})}function Ke(r,e,i){let o=new Map;for(let a of e)a.publisher===r&&(o.has(a.package_)||o.set(a.package_,{verStr:a.verStr,source:a.source}));if(o.size===0)return;let t={};for(let a of[...o.keys()].sort()){let{verStr:u,source:d}=o.get(a),k={},y;try{y=i.parse(d).metadata?.imports}catch{y=void 0}for(let l of y?.[r]??[]){let f=o.get(l.packageName);f&&(k[`${r}/${l.packageName}`]=f.verStr)}let s={};for(let l of Object.keys(k).sort())s[l]=k[l];t[`${r}/${a}`]={version:u,resolved:`https://${r}/${a}/${u}.kan.yml`,integrity:Pe(d),dependencies:s}}return De.dump({version:"1",lastUpdated:"",packages:t},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as Ve,readFileSync as Ae,writeFileSync as Be,mkdirSync as Le}from"fs";import{join as Ce}from"path";async function ge(r,e={}){let i=new O,o=xe(r),t=o.kind==="resource"?o.uri.publisher:o.publisher,a=e.log??(()=>{}),u=e.cacheRoot??Z(),d=(n,g,b)=>Ce(u,n,`${g}@${b}.kan.yml`),k=new Set,y=new Set,s=new Map,l=new ee({getFromCache:(n,g,b)=>{let v=d(n,g,b),$=Ve(v)?Ae(v,"utf-8"):null;return $!==null&&k.add(`${n}/${g}`),$},onFetch:(n,g,b,v)=>{y.add(`${n}/${g}`);try{let $=Ce(u,n);Le($,{recursive:!0}),Be(d(n,g,b),v,"utf-8")}catch($){s.set(`${n}/${g}`,$.message),a(`[render] fetched ${n}/${g}@${b} but cache ${u} is NOT WRITABLE (${$.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),f=new U(e.fetchFn?{fetchFn:e.fetchFn}:void 0),p;if(o.kind==="resource"){let n=o.uri.version;p=[n?{package_:o.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:o.uri.package_}]}else if(o.kind==="package"){let n=o.version;p=[n?{package_:o.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:o.package_}]}else p=((await f.getConfig(t)).featured_packages??[]).map(g=>({package_:g}));let m=async(n,g,b)=>{try{let v=b?i.buildImport(g,"=",b,n):i.buildImport(g,"*","0.0.0",n),$=await l.getHighestCompatibleVersionAsync(n,v);return $?{doc:$}:{doc:null,error:`${n} did not resolve ${g}${b?`@${b}`:""} (not in its index, or unreachable)`}}catch(v){return{doc:null,error:v.message}}},S=[],w=[];for(let n of p){let{doc:g,error:b}=await m(t,n.package_,n.version);g?S.push(g):b&&w.push(b)}if(S.length===0)throw new Error(`Could not fetch any package for address "${r}" from publisher "${t}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=G(),P="universal-default",E=n=>n.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,b)=>V(b,g)).map(j);a(`[render-stack] resolving ${_.length} ambient look-stack package(s) (contract: ${P}); cache: ${u}`);let D=[],A=[];for(let n of _){let g=N(n),{doc:b,error:v}=await m(n.publisher,n.package_,void 0);if(b){D.push(b);let $=E([b]),F=y.has(g)?"fetched":k.has(g)?"cache":"fetched";A.push({...n,origin:F,versions:$}),a(`[render-stack] ${g} \u2014 ${F} (${$.join(", ")})`+(s.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...n,origin:"missing",reason:v??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${v??"unresolved"}`)}let B=[],le=await H([...S,...D],l,{onUnresolvedEdge:n=>B.push(n)}),de=new q(l,le),I=await new te(i).parseKanonaks(de),Y=new ne(I),J=A.map(n=>n.origin==="missing"||oe(I,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),K=z(J,B);for(let n of K)a(`[render-stack] WARNING: ${n}`);let L={contractSource:P,cachePath:u,packages:J,warnings:K},c=new Set,h=new Map;for(let n of await l.getAllDocumentsAsync()){let g=n.metadata.namespace_;if(!g?.version||g.publisher!==t)continue;let b=j(g.version),v=`${g.publisher}/${g.package_}@${b}`;c.add(v);let $=await l.getDocumentContentAsync(v);$!==null&&h.set(`${g.package_}@${b}`,$)}return se({publisher:t,availablePublishers:[t],catalog:I,lookRenderer:Y,localNamespaces:c,rawByNsKey:h,renderStack:L})}import{VersionOperator as ce}from"@kanonak-protocol/types/document/models/enums";function ie(r){let{lookRenderer:e,publisher:i,renderStack:o,catalog:t}=r,a=e.explainStylesheet(e.publisherSubject(i)),u=[...a.tokens.entries()].map(([p,m])=>({name:p,value:m.value,source:`${m.sourceNamespace}/${m.sourceName}`,level:m.level})),d=a.baseStylesheet,k={present:d.css!==void 0,...d.sourceNamespace!==void 0?{source:d.sourceNamespace}:{},...d.scope!==void 0?{scope:d.scope}:{},...d.css!==void 0?{bytes:d.css.length}:{},...d.problem!==void 0?{problem:d.problem}:{},candidates:d.candidates},y=new Map;for(let p of t){let m=p.namespace;m&&y.set(m,(y.get(m)??0)+1)}let s=[...y.entries()].map(([p,m])=>({namespace:p,resources:m})).sort((p,m)=>p.namespace.localeCompare(m.namespace)),l=e.expressionFailures().map(p=>({carrier:p.carrier,reason:p.reason})),f=l.map(p=>`Expression carrier "${p.carrier}" did not compile: ${p.reason} Consequence: that value renders as nothing (and a parent operation consuming it may drop its whole tier). Fix: use a tx.Expression node class the runner implements, or remove the carrier.`);return{publisher:i,renderStack:{contractSource:o.contractSource,cachePath:o.cachePath,packages:o.packages.map(p=>({package_:N(p),origin:p.origin,...p.versions!==void 0?{versions:p.versions}:{},...p.reason!==void 0?{reason:p.reason}:{},...p.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:p.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:u,baseStylesheet:k,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},expressionCarriers:l,catalog:s,warnings:[...o.warnings,...a.warnings.filter(p=>!o.warnings.includes(p)),...f]}}function Oe(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function he(r){let e=Oe,i=r.warnings.length===0,o=r.expressionCarriers.map(s=>`<tr><td><code>${e(s.carrier)}</code></td><td>${e(s.reason)}</td></tr>`).join(`
1
+ import{c as je}from"../chunk-SBO34ENZ.js";import{a as be,d as Q,f as we,h as ee}from"../chunk-7F2EAT5Y.js";import{b as ve,j as $e,l as Se,s as U,t as Z}from"../chunk-HKQTB65D.js";import"../chunk-D2X6J77P.js";import"../chunk-SC5M74NM.js";import{a as q,b as H}from"../chunk-VORVR5BZ.js";import{t as te}from"../chunk-TYVZXABI.js";import"../chunk-QHABFCRC.js";import{a as ye}from"../chunk-6VIUXP4N.js";import{k as oe}from"../chunk-22DSABP6.js";import{a as O}from"../chunk-7JBKOJB4.js";import{a as Pe}from"../chunk-PEJALHXK.js";import"../chunk-NUTHBBDZ.js";import{A as re,c as Re,p as _e}from"../chunk-D4QGPMRW.js";import{a as xe}from"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import{c as V,e as j,f as W,g as X}from"../chunk-QILEJIFU.js";import{readFileSync as pe,writeFileSync as Ee,mkdirSync as De}from"fs";import{join as se}from"path";import Ke from"js-yaml";var Ce=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function G(r){return Ce}function N(r){return`${r.publisher}/${r.package_}`}function z(r,e=[]){let i={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},o=[];for(let t of r)if(t.origin==="missing"){let a=N(t),u=i[a]??"whatever this package contributes to rendering is lost";o.push(`Render-stack package ${a} is MISSING (${t.reason??"unknown reason"}) \u2014 ${u}. Fix: kanonak install ${a} (as the user running the render), or restore network access to ${t.publisher}.`)}else t.resolvedButNotInCatalog&&o.push(`Render-stack package ${N(t)} resolved (${t.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let t of e)o.push(`Import edge ${t.fromNamespace} \u2192 ${t.publisher}/${t.packageName} ${t.constraint} did NOT resolve (${t.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${t.fromNamespace} authors against ${t.publisher}/${t.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${t.constraint}-compatible version of ${t.publisher}/${t.packageName} to the workspace or cache (kanonak install ${t.publisher}/${t.packageName}), or bump the import in ${t.fromNamespace}.`);return o}function ne(r){let{publisher:e,availablePublishers:i,catalog:o,lookRenderer:t,localNamespaces:a,rawByNsKey:u,renderStack:d,producers:f,lockSource:y,configSource:s}=r,l=new Map,k=new Map,p=new Map,m=new Set;for(let S of o){if(!(S instanceof Re))continue;let w=S.namespace||"";if(!a.has(w))continue;l.set(`${w}/${S.name}`,S);let _=w.split("/")[1]??"",[P,E]=_.split("@");if(!P||!E)continue;let D=X(E);D&&(m.has(_)||(m.add(_),k.has(P)||k.set(P,[]),k.get(P).push({verStr:E,version:D})),S.name===P&&p.set(_,S))}for(let S of k.values())S.sort((w,_)=>V(_.version,w.version));return{publisher:e,availablePublishers:i,catalog:o,lookRenderer:t,localNamespaces:a,rawByNsKey:u,bySubject:l,pkgVersions:k,pkgSelfByVer:p,renderStack:d,...f?{producers:f}:{},...y?{lockSource:y}:{},...s?{configSource:s}:{}}}async function ue(r,e={}){let i=new O,o=new ye(i),t=[],a=[];for(let c of ee(r)){let h;try{h=pe(c,"utf-8")}catch{continue}let n;try{n=i.parse(h).metadata?.namespace_}catch{continue}if(!n?.version)continue;let g=n.version;a.push({publisher:n.publisher,package_:n.package_,verStr:j(g),version:g,source:h})}a.sort((c,h)=>V(h.version,c.version));for(let c of a)await o.saveDocumentAsync(i.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),t.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let u=[...new Set(t.map(c=>c.publisher))].sort(),d=e.publisher;if(d){if(!u.includes(d))throw new Error(`Publisher "${d}" not found in workspace. Available: ${u.join(", ")||"(none)"}`)}else if(u.length===1)d=u[0];else throw u.length===0?new Error(`No Kanonak packages found under ${r}`):new Error(`Workspace has multiple publishers (${u.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,y=new Map;for(let c of t)c.publisher===d&&(f.add(`${c.publisher}/${c.package_}@${c.verStr}`),y.set(`${c.package_}@${c.verStr}`,c.source));let s=Q(),l=new be(s,!0,i),k={};e.httpCache&&(k.getFromCache=e.httpCache.getFromCache,k.onFetch=e.httpCache.onFetch),e.fetchFn&&(k.fetchFn=e.fetchFn);let p=e.repository??new we(o,l,new Z(k)),m=e.log??(()=>{}),S=G(void 0),w=[],_=c=>c.map(h=>h.metadata.namespace_?.version).filter(h=>h!==void 0).sort((h,n)=>V(n,h)).map(j);if(!e.repository){m(`[render-stack] resolving ${S.length} ambient look-stack package(s); cache: ${s}`);let c=e.fetchFn?new U({fetchFn:e.fetchFn}):new U;for(let h of S){let n=N(h),g=await o.getDocumentsByNamespaceAsync(h.publisher,h.package_);if(g.length>0){let v=_(g);w.push({...h,origin:"workspace",versions:v}),m(`[render-stack] ${n} \u2014 workspace (${v.join(", ")})`);continue}let b=await l.getDocumentsByNamespaceAsync(h.publisher,h.package_);if(b.length>0){let v=_(b);w.push({...h,origin:"cache",versions:v}),m(`[render-stack] ${n} \u2014 cache (${v.join(", ")})`);continue}try{let $=(await c.getLock(h.publisher))?.packages[`${h.publisher}/${h.package_}`];if(!$){let C=`publisher ${h.publisher} reachable but its lock does not pin ${h.package_}`;w.push({...h,origin:"missing",reason:C}),m(`[render-stack] ${n} \u2014 MISSING: ${C}`);continue}let F=$.version,T=$.resolved,de=await(e.fetchFn?e.fetchFn(T,h.publisher):$e(T));if(!de.ok){let C=(await ve("render-stack package",T,de)).message;w.push({...h,origin:"missing",reason:C}),m(`[render-stack] ${n} \u2014 MISSING: ${C}`);continue}let fe=await de.text();await o.saveDocumentAsync(i.parse(fe),`${h.publisher}/${h.package_}@${F}`);try{let C=se(s,h.publisher);De(C,{recursive:!0}),Ee(se(C,`${h.package_}@${F}.kan.yml`),fe,"utf-8"),w.push({...h,origin:"fetched",versions:[F]}),m(`[render-stack] ${n}@${F} \u2014 fetched from ${T}, installed to cache`)}catch(C){w.push({...h,origin:"fetched",versions:[F]}),m(`[render-stack] ${n}@${F} \u2014 fetched from ${T}, but cache ${s} is NOT WRITABLE (${C.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(v){let $=`fetch failed: ${v.message}`;w.push({...h,origin:"missing",reason:$}),m(`[render-stack] ${n} \u2014 MISSING: ${$}`)}}}let P=(await o.getAllDocumentsAsync()).filter(c=>c.metadata.namespace_?.publisher===d);for(let c of S)P.push(...await p.getDocumentsByNamespaceAsync(c.publisher,c.package_));let E=[],D=await q(P,p,{onUnresolvedEdge:c=>E.push(c)}),A=p;if(!e.repository){for(let c of S)D.add(N(c));A=new H(p,D)}let B=await new oe(i).parseKanonaks(A),ce=new te(B),le=(c,h)=>re(B,{publisher:c,package_:h,name:h}).length>0,I;if(e.repository){I=[];for(let c of S){let h=await p.getDocumentsByNamespaceAsync(c.publisher,c.package_);I.push(h.length>0?{...c,origin:"repository",versions:_(h)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else I=w.map(c=>c.origin==="missing"||le(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let Y=z(I,E);for(let c of Y)m(`[render-stack] WARNING: ${c}`);let J={contractSource:"universal-default",cachePath:s,packages:I,warnings:Y},K;try{K=pe(se(r,"kanonak.lock"),"utf-8")}catch{K=Ve(d,t,i)}let L;try{L=pe(se(r,".well-known","kanonak.json"),"utf-8")}catch{L=void 0}return ne({publisher:d,availablePublishers:u,catalog:B,lookRenderer:ce,localNamespaces:f,rawByNsKey:y,renderStack:J,...K?{lockSource:K}:{},...L?{configSource:L}:{}})}function Ve(r,e,i){let o=new Map;for(let a of e)a.publisher===r&&(o.has(a.package_)||o.set(a.package_,{verStr:a.verStr,source:a.source}));if(o.size===0)return;let t={};for(let a of[...o.keys()].sort()){let{verStr:u,source:d}=o.get(a),f={},y;try{y=i.parse(d).metadata?.imports}catch{y=void 0}for(let l of y?.[r]??[]){let k=o.get(l.packageName);k&&(f[`${r}/${l.packageName}`]=k.verStr)}let s={};for(let l of Object.keys(f).sort())s[l]=f[l];t[`${r}/${a}`]={version:u,resolved:`https://${r}/${a}/${u}.kan.yml`,integrity:je(d),dependencies:s}}return Ke.dump({version:"1",lastUpdated:"",packages:t},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as Ae,readFileSync as Be,writeFileSync as Le,mkdirSync as Oe}from"fs";import{join as Ne}from"path";async function ge(r,e={}){let i=new O,o=_e(r),t=o.kind==="resource"?o.uri.publisher:o.publisher,a=e.log??(()=>{}),u=e.cacheRoot??Q(),d=(n,g,b)=>Ne(u,n,`${g}@${b}.kan.yml`),f=new Set,y=new Set,s=new Map,l=new Z({getFromCache:(n,g,b)=>{let v=d(n,g,b),$=Ae(v)?Be(v,"utf-8"):null;return $!==null&&f.add(`${n}/${g}`),$},onFetch:(n,g,b,v)=>{y.add(`${n}/${g}`);try{let $=Ne(u,n);Oe($,{recursive:!0}),Le(d(n,g,b),v,"utf-8")}catch($){s.set(`${n}/${g}`,$.message),a(`[render] fetched ${n}/${g}@${b} but cache ${u} is NOT WRITABLE (${$.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),k=new U(e.fetchFn?{fetchFn:e.fetchFn}:void 0),p;if(o.kind==="resource"){let n=o.uri.version;p=[n?{package_:o.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:o.uri.package_}]}else if(o.kind==="package"){let n=o.version;p=[n?{package_:o.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:o.package_}]}else p=((await k.getConfig(t)).featured_packages??[]).map(g=>({package_:g}));let m=async(n,g,b)=>{try{let v=b?i.buildImport(g,"=",b,n):i.buildImport(g,"*","0.0.0",n),$=await l.getHighestCompatibleVersionAsync(n,v);return $?{doc:$}:{doc:null,error:`${n} did not resolve ${g}${b?`@${b}`:""} (not in its index, or unreachable)`}}catch(v){return{doc:null,error:v.message}}},S=[],w=[];for(let n of p){let{doc:g,error:b}=await m(t,n.package_,n.version);g?S.push(g):b&&w.push(b)}if(S.length===0)throw new Error(`Could not fetch any package for address "${r}" from publisher "${t}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=G(),P="universal-default",E=n=>n.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,b)=>V(b,g)).map(j);a(`[render-stack] resolving ${_.length} ambient look-stack package(s) (contract: ${P}); cache: ${u}`);let D=[],A=[];for(let n of _){let g=N(n),{doc:b,error:v}=await m(n.publisher,n.package_,void 0);if(b){D.push(b);let $=E([b]),F=y.has(g)?"fetched":f.has(g)?"cache":"fetched";A.push({...n,origin:F,versions:$}),a(`[render-stack] ${g} \u2014 ${F} (${$.join(", ")})`+(s.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...n,origin:"missing",reason:v??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${v??"unresolved"}`)}let B=[],ce=await q([...S,...D],l,{onUnresolvedEdge:n=>B.push(n)}),le=new H(l,ce),I=await new oe(i).parseKanonaks(le),Y=new te(I),J=A.map(n=>n.origin==="missing"||re(I,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),K=z(J,B);for(let n of K)a(`[render-stack] WARNING: ${n}`);let L={contractSource:P,cachePath:u,packages:J,warnings:K},c=new Set,h=new Map;for(let n of await l.getAllDocumentsAsync()){let g=n.metadata.namespace_;if(!g?.version||g.publisher!==t)continue;let b=j(g.version),v=`${g.publisher}/${g.package_}@${b}`;c.add(v);let $=await l.getDocumentContentAsync(v);$!==null&&h.set(`${g.package_}@${b}`,$)}return ne({publisher:t,availablePublishers:[t],catalog:I,lookRenderer:Y,localNamespaces:c,rawByNsKey:h,renderStack:L})}import{VersionOperator as ie}from"@kanonak-protocol/types/document/models/enums";function ae(r){let{lookRenderer:e,publisher:i,renderStack:o,catalog:t}=r,a=e.explainStylesheet(e.publisherSubject(i)),u=[...a.tokens.entries()].map(([p,m])=>({name:p,value:m.value,source:`${m.sourceNamespace}/${m.sourceName}`,level:m.level})),d=a.baseStylesheet,f={present:d.css!==void 0,...d.sourceNamespace!==void 0?{source:d.sourceNamespace}:{},...d.scope!==void 0?{scope:d.scope}:{},...d.css!==void 0?{bytes:d.css.length}:{},...d.problem!==void 0?{problem:d.problem}:{},candidates:d.candidates},y=new Map;for(let p of t){let m=p.namespace;m&&y.set(m,(y.get(m)??0)+1)}let s=[...y.entries()].map(([p,m])=>({namespace:p,resources:m})).sort((p,m)=>p.namespace.localeCompare(m.namespace)),l=e.expressionFailures().map(p=>({carrier:p.carrier,reason:p.reason})),k=l.map(p=>`Expression carrier "${p.carrier}" did not compile: ${p.reason} Consequence: that value renders as nothing (and a parent operation consuming it may drop its whole tier). Fix: use a tx.Expression node class the runner implements, or remove the carrier.`);return{publisher:i,renderStack:{contractSource:o.contractSource,cachePath:o.cachePath,packages:o.packages.map(p=>({package_:N(p),origin:p.origin,...p.versions!==void 0?{versions:p.versions}:{},...p.reason!==void 0?{reason:p.reason}:{},...p.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:p.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:u,baseStylesheet:f,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},expressionCarriers:l,catalog:s,warnings:[...o.warnings,...a.warnings.filter(p=>!o.warnings.includes(p)),...k]}}function Te(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function he(r){let e=Te,i=r.warnings.length===0,o=r.expressionCarriers.map(s=>`<tr><td><code>${e(s.carrier)}</code></td><td>${e(s.reason)}</td></tr>`).join(`
2
2
  `),t=r.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':r.warnings.map(s=>`<div class="warn">\u26A0 ${e(s)}</div>`).join(`
3
- `),a=r.renderStack.packages.map(s=>{let l=s.origin!=="missing"&&!s.resolvedButNotInCatalog,f=s.origin==="missing"?'<span class="bad">MISSING</span>':s.resolvedButNotInCatalog?`<span class="bad">${e(s.origin)} (not in catalog)</span>`:`<span class="good">${e(s.origin)}</span>`,p=s.reason?e(s.reason):e((s.versions??[]).join(", "));return`<tr class="${l?"":"row-bad"}"><td><code>${e(s.package_)}</code></td><td>${f}</td><td>${p}</td></tr>`}).join(`
4
- `),u=r.stylesheet.baseStylesheet,d=u.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(u.source??"")}</code> (${u.bytes} bytes, ${e(u.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${u.problem?` \u2014 ${e(u.problem)}`:""}${u.candidates.length>0?`<br>candidates considered: ${u.candidates.map(s=>`<code>${e(s)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,k=r.stylesheet.tokens.map(s=>`<tr><td><code>--kan-${e(s.name)}</code></td><td><code>${e(s.value)}</code></td><td><code>${e(s.source)}</code></td><td>${e(s.level)}</td></tr>`).join(`
3
+ `),a=r.renderStack.packages.map(s=>{let l=s.origin!=="missing"&&!s.resolvedButNotInCatalog,k=s.origin==="missing"?'<span class="bad">MISSING</span>':s.resolvedButNotInCatalog?`<span class="bad">${e(s.origin)} (not in catalog)</span>`:`<span class="good">${e(s.origin)}</span>`,p=s.reason?e(s.reason):e((s.versions??[]).join(", "));return`<tr class="${l?"":"row-bad"}"><td><code>${e(s.package_)}</code></td><td>${k}</td><td>${p}</td></tr>`}).join(`
4
+ `),u=r.stylesheet.baseStylesheet,d=u.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(u.source??"")}</code> (${u.bytes} bytes, ${e(u.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${u.problem?` \u2014 ${e(u.problem)}`:""}${u.candidates.length>0?`<br>candidates considered: ${u.candidates.map(s=>`<code>${e(s)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,f=r.stylesheet.tokens.map(s=>`<tr><td><code>--kan-${e(s.name)}</code></td><td><code>${e(s.value)}</code></td><td><code>${e(s.source)}</code></td><td>${e(s.level)}</td></tr>`).join(`
5
5
  `),y=r.catalog.map(s=>`<tr><td><code>${e(s.namespace)}</code></td><td>${s.resources}</td></tr>`).join(`
6
6
  `);return`<!doctype html>
7
7
  <html lang="en">
@@ -49,7 +49,7 @@ ${d}
49
49
  <p class="meta">Resolved for the publisher landing page. Each token shows which resource in the cascade supplied it.</p>
50
50
  ${r.stylesheet.tokens.length===0?'<p><span class="bad">\u2717 No tokens resolved</span></p>':`<table>
51
51
  <tr><th>Token</th><th>Value</th><th>Declared by</th><th>Cascade level</th></tr>
52
- ${k}
52
+ ${f}
53
53
  </table>`}
54
54
 
55
55
  <h2>Look (page body)</h2>
@@ -69,4 +69,4 @@ ${o}
69
69
  ${y}
70
70
  </table>
71
71
  </body>
72
- </html>`}var R={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},x=(r,e,i,o)=>({status:r,headers:{"Content-Type":e,...o||{}},body:i}),M=r=>x(404,R[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${r}</p>`),Te=r=>({status:301,headers:{Location:r},body:""}),We=r=>({status:302,headers:{Location:r},body:""});function Ue(r){switch(r.kind){case"exact":return{operator:ce.Exact,version:W(r.major,r.minor,r.patch)};case"minor-pin":return{operator:ce.Compatible,version:W(r.major,r.minor,0)};case"major-pin":return{operator:ce.Major,version:W(r.major,0,0)};default:return{operator:ce.Any,version:W(0,0,0)}}}async function He(r,e,i,o){if(!o)return null;let t=r.producers?.find(k=>k.canProduce(r.publisher,e));if(!t)return null;let a=await t.resolveVersion(r.publisher,e,Ue(i));if(!a)return null;let u=j(a);if(i.kind!=="exact")return We(`/${e}/${u}.kan.yml`);let{source:d}=await t.produce(r.publisher,e,a);return x(200,R[".kan.yml"],d)}function Ne(r,e,i){let o=r.pkgVersions.get(e);if(!o||o.length===0)return null;switch(i.kind){case"any":return o[0].verStr;case"major-pin":return o.find(t=>t.version.major===i.major)?.verStr??null;case"minor-pin":return o.find(t=>t.version.major===i.major&&t.version.minor===i.minor)?.verStr??null;case"exact":return o.find(t=>t.version.major===i.major&&t.version.minor===i.minor&&t.version.patch===i.patch)?.verStr??null;default:return null}}async function me(r,e,i=""){let{lookRenderer:o,publisher:t}=r;if(e==="/.well-known/kanonak.json")return r.configSource?x(200,R[".json"],r.configSource):x(200,R[".json"],JSON.stringify($e(),null,2));if(e==="/kanonak.lock")return r.lockSource?x(200,R[".kan.yml"],r.lockSource):M(e);if(e==="/.well-known/kanonak-render.json")return x(200,R[".json"],JSON.stringify(ie(r),null,2));if(e==="/.well-known/kanonak-render")return x(200,R[".html"],he(ie(r)));if(e==="/"||e==="/index.html"||e==="/index.css"){let l=o.publisherSubject(t);return e==="/index.css"?x(200,R[".css"],o.renderStylesheet(l)):x(200,R[".html"],await o.renderDocument(l,{rootIndex:!0}))}let a=".html",u=!1,d=e;for(let l of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(l)){a=l,u=!0,d=e.slice(0,-l.length);break}let k=!u&&/application\/yaml|text\/yaml/i.test(i),y=d.endsWith("/");y&&d!=="/"&&(d=d.slice(0,-1));let s=_e.parse(d,t);if(!s)return M(e);if(s.kind==="package"){let l=Ne(r,s.package_,s.versionSpec);if(!l)return await He(r,s.package_,s.versionSpec,a===".kan.yml"||k)??M(e);if(a===".kan.yml"||k){let m=r.rawByNsKey.get(`${s.package_}@${l}`);return m!==void 0?x(200,R[".kan.yml"],m):M(e)}let f=r.pkgSelfByVer.get(`${s.package_}@${l}`);if(!f)return M(e);if(a===".css")return x(200,R[".css"],o.renderStylesheet(f));if(!y)return Te(d+"/");let p=s.versionSpec.kind==="any";if(p&&!o.hasDeclaredView(f)){let m=(r.pkgVersions.get(s.package_)||[]).map(S=>S.verStr);return x(200,R[".html"],o.renderPackageVersionList(s.package_,m,f))}return x(200,R[".html"],await o.renderDocument(f,p?{bareOverview:!0}:void 0))}if(s.kind==="resource"){let l=Ne(r,s.package_,s.versionSpec);if(!l)return M(e);let f=r.bySubject.get(`${t}/${s.package_}@${l}/${s.name}`);if(!f)return M(e);switch(a){case".css":return x(200,R[".css"],o.renderStylesheet(f));case".svg":return x(200,R[".svg"],await o.renderSvg(f));case".md":{let p=o.renderRawMarkdown(f);return p===void 0?M(e):x(200,R[".md"],p)}default:return x(200,R[".html"],await o.renderDocument(f))}}return M(e)}import{readFileSync as qe}from"fs";var Ie=/^\d+\.\d+\.\d+$/,fe=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,i=new Set;if(this.options.root!==void 0){let o=new O;for(let t of re(this.options.root))try{let a=o.parse(qe(t,"utf-8")).metadata?.namespace_;if(!a?.version)continue;let u=a.version;e.add(`${a.publisher}/${a.package_}@${u.major}.${u.minor}.${u.patch}`),i.add(`${a.publisher}/${a.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:i},this.workspaceIndex}async modelFor(e,i,o){let t=this.getWorkspaceIndex(),a={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},u=i?o?t.exact.has(`${e}/${i}@${o}`):t.pkgs.has(`${e}/${i}`):[...t.pkgs].some(l=>l.startsWith(`${e}/`)),d,k;if(u&&this.options.root!==void 0){let l=this.options.root;d=`ws:${e}`,k=()=>ue(l,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let l=i?o?`${e}/${i}@${o}`:`${e}/${i}`:e;d=`rm:${l}`,k=()=>ge(l,a)}let y=this.models.get(d);if(y)return y;let s=await k();return s.lookRenderer.setLinkMode("open-world"),this.models.set(d,s),s}async handle(e,i=""){let o=e.split("/").filter(Boolean);if(o.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Fe()};let t=o[0];if(!t.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let a=o.length>=2&&(o[1]==="index.html"||o[1]==="index.css"||o[1]==="kanonak.lock"||o[1]===".well-known"),u=!a&&o.length>=2?o[1]:void 0,d=!a&&o.length>=3&&Ie.test(o[2])?o[2]:void 0,k=await this.modelFor(t,u,d),y=e.endsWith("/")&&o.length>1?"/":"",s="/"+o.slice(1).join("/")+y,l=await me(k,s,i);return l.headers.Location?{...l,headers:{...l.headers,Location:`/${t}${l.headers.Location}`}}:l}};function Ge(r){switch(r.kind){case"publisher":return`/${r.publisher}/`;case"package":return r.version?`/${r.publisher}/${r.package_}/${j(r.version)}/`:`/${r.publisher}/${r.package_}/`;case"resource":{let e=r.uri;return e.version?`/${e.publisher}/${e.package_}/${j(e.version)}/${e.name}`:`/${e.publisher}/${e.package_}/${e.name}`}}}function ze(r){let e=r.split("/").filter(Boolean),i=e[0];if(!i||!i.includes("."))return;let o=e[1];if(!o)return{kind:"publisher",publisher:i};let t=e[2]&&Ie.test(e[2])?Q(e[2])??void 0:void 0,a=t?e[3]:e[2];return a?{kind:"resource",uri:new Re(i,o,a,t)}:t?{kind:"package",publisher:i,package_:o,version:t}:{kind:"package",publisher:i,package_:o}}function Fe(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{q as ClosureScopedRepository,fe as RequestRouter,je as UNIVERSAL_RENDER_BASE,ze as addressForRequestPath,ie as buildRenderDiagnostics,z as buildRenderStackWarnings,H as deriveImportClosure,Fe as landingPage,ge as loadResourceModel,ue as loadServerModel,he as renderDiagnosticsHtml,N as renderRefKey,Ge as requestPathFor,G as resolveRenderContract,me as route};
72
+ </html>`}var R={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},x=(r,e,i,o)=>({status:r,headers:{"Content-Type":e,...o||{}},body:i}),M=r=>x(404,R[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${r}</p>`),We=r=>({status:301,headers:{Location:r},body:""}),Ue=r=>({status:302,headers:{Location:r},body:""});function qe(r){switch(r.kind){case"exact":return{operator:ie.Exact,version:W(r.major,r.minor,r.patch)};case"minor-pin":return{operator:ie.Compatible,version:W(r.major,r.minor,0)};case"major-pin":return{operator:ie.Major,version:W(r.major,0,0)};default:return{operator:ie.Any,version:W(0,0,0)}}}async function He(r,e,i,o){if(!o)return null;let t=r.producers?.find(f=>f.canProduce(r.publisher,e));if(!t)return null;let a=await t.resolveVersion(r.publisher,e,qe(i));if(!a)return null;let u=j(a);if(i.kind!=="exact")return Ue(`/${e}/${u}.kan.yml`);let{source:d}=await t.produce(r.publisher,e,a);return x(200,R[".kan.yml"],d)}function Ie(r,e,i){let o=r.pkgVersions.get(e);if(!o||o.length===0)return null;switch(i.kind){case"any":return o[0].verStr;case"major-pin":return o.find(t=>t.version.major===i.major)?.verStr??null;case"minor-pin":return o.find(t=>t.version.major===i.major&&t.version.minor===i.minor)?.verStr??null;case"exact":return o.find(t=>t.version.major===i.major&&t.version.minor===i.minor&&t.version.patch===i.patch)?.verStr??null;default:return null}}async function me(r,e,i=""){let{lookRenderer:o,publisher:t}=r;if(e==="/.well-known/kanonak.json")return r.configSource?x(200,R[".json"],r.configSource):x(200,R[".json"],JSON.stringify(Se(),null,2));if(e==="/kanonak.lock")return r.lockSource?x(200,R[".kan.yml"],r.lockSource):M(e);if(e==="/.well-known/kanonak-render.json")return x(200,R[".json"],JSON.stringify(ae(r),null,2));if(e==="/.well-known/kanonak-render")return x(200,R[".html"],he(ae(r)));if(e==="/"||e==="/index.html"||e==="/index.css"){let l=o.publisherSubject(t);return e==="/index.css"?x(200,R[".css"],o.renderStylesheet(l)):x(200,R[".html"],await o.renderDocument(l,{rootIndex:!0}))}let a=".html",u=!1,d=e;for(let l of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(l)){a=l,u=!0,d=e.slice(0,-l.length);break}let f=!u&&/application\/yaml|text\/yaml/i.test(i),y=d.endsWith("/");y&&d!=="/"&&(d=d.slice(0,-1));let s=Pe.parse(d,t);if(!s)return M(e);if(s.kind==="package"){let l=Ie(r,s.package_,s.versionSpec);if(!l)return await He(r,s.package_,s.versionSpec,a===".kan.yml"||f)??M(e);if(a===".kan.yml"||f){let m=r.rawByNsKey.get(`${s.package_}@${l}`);return m!==void 0?x(200,R[".kan.yml"],m):M(e)}let k=r.pkgSelfByVer.get(`${s.package_}@${l}`);if(!k)return M(e);if(a===".css")return x(200,R[".css"],o.renderStylesheet(k));if(!y)return We(d+"/");let p=s.versionSpec.kind==="any";if(p&&!o.hasDeclaredView(k)){let m=(r.pkgVersions.get(s.package_)||[]).map(S=>S.verStr);return x(200,R[".html"],o.renderPackageVersionList(s.package_,m,k))}return x(200,R[".html"],await o.renderDocument(k,p?{bareOverview:!0}:void 0))}if(s.kind==="resource"){let l=Ie(r,s.package_,s.versionSpec);if(!l)return M(e);let k=r.bySubject.get(`${t}/${s.package_}@${l}/${s.name}`);if(!k)return M(e);switch(a){case".css":return x(200,R[".css"],o.renderStylesheet(k));case".svg":return x(200,R[".svg"],await o.renderSvg(k));case".md":{let p=o.renderRawMarkdown(k);return p===void 0?M(e):x(200,R[".md"],p)}default:return x(200,R[".html"],await o.renderDocument(k))}}return M(e)}import{readFileSync as Ge}from"fs";var Fe=/^\d+\.\d+\.\d+$/,ke=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,i=new Set;if(this.options.root!==void 0){let o=new O;for(let t of ee(this.options.root))try{let a=o.parse(Ge(t,"utf-8")).metadata?.namespace_;if(!a?.version)continue;let u=a.version;e.add(`${a.publisher}/${a.package_}@${u.major}.${u.minor}.${u.patch}`),i.add(`${a.publisher}/${a.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:i},this.workspaceIndex}async modelFor(e,i,o){let t=this.getWorkspaceIndex(),a={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},u=i?o?t.exact.has(`${e}/${i}@${o}`):t.pkgs.has(`${e}/${i}`):[...t.pkgs].some(l=>l.startsWith(`${e}/`)),d,f;if(u&&this.options.root!==void 0){let l=this.options.root;d=`ws:${e}`,f=()=>ue(l,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let l=i?o?`${e}/${i}@${o}`:`${e}/${i}`:e;d=`rm:${l}`,f=()=>ge(l,a)}let y=this.models.get(d);if(y)return y;let s=await f();return s.lookRenderer.setLinkMode("open-world"),this.models.set(d,s),s}async handle(e,i=""){let o=e.split("/").filter(Boolean);if(o.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Me()};let t=o[0];if(!t.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let a=o.length>=2&&(o[1]==="index.html"||o[1]==="index.css"||o[1]==="kanonak.lock"||o[1]===".well-known"),u=!a&&o.length>=2?o[1]:void 0,d=!a&&o.length>=3&&Fe.test(o[2])?o[2]:void 0,f=await this.modelFor(t,u,d),y=e.endsWith("/")&&o.length>1?"/":"",s="/"+o.slice(1).join("/")+y,l=await me(f,s,i);return l.headers.Location?{...l,headers:{...l.headers,Location:`/${t}${l.headers.Location}`}}:l}};function ze(r){switch(r.kind){case"publisher":return`/${r.publisher}/`;case"package":return r.version?`/${r.publisher}/${r.package_}/${j(r.version)}/`:`/${r.publisher}/${r.package_}/`;case"resource":{let e=r.uri;return e.version?`/${e.publisher}/${e.package_}/${j(e.version)}/${e.name}`:`/${e.publisher}/${e.package_}/${e.name}`}}}function Ye(r){let e=r.split("/").filter(Boolean),i=e[0];if(!i||!i.includes("."))return;let o=e[1];if(!o)return{kind:"publisher",publisher:i};let t=e[2]&&Fe.test(e[2])?X(e[2])??void 0:void 0,a=t?e[3]:e[2];return a?{kind:"resource",uri:new xe(i,o,a,t)}:t?{kind:"package",publisher:i,package_:o,version:t}:{kind:"package",publisher:i,package_:o}}function Me(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{H as ClosureScopedRepository,ke as RequestRouter,Ce as UNIVERSAL_RENDER_BASE,Ye as addressForRequestPath,ae as buildRenderDiagnostics,z as buildRenderStackWarnings,q as deriveImportClosure,Me as landingPage,ge as loadResourceModel,ue as loadServerModel,he as renderDiagnosticsHtml,N as renderRefKey,ze as requestPathFor,G as resolveRenderContract,me as route};
@@ -1,4 +1,4 @@
1
- import{a as pe}from"../chunk-ED35OFGD.js";import"../chunk-W5AOJ5SJ.js";import{a as ve,b as M,c as Un,n as X,o as Vn,p as Rn,q as le,r as q,t as G}from"../chunk-EG47OOJC.js";import"../chunk-QHABFCRC.js";import"../chunk-6VIUXP4N.js";import{b as $n,c as Tn,d as Bn,e as xn,j as fe}from"../chunk-3353RWDC.js";import{a as se}from"../chunk-7JBKOJB4.js";import"../chunk-PEJALHXK.js";import{c as U}from"../chunk-NUTHBBDZ.js";import{b as Y,c as D,d as ce,e as E,f as ue,i as $,j as T,k as B,l as w,m as me,n as x,o as de,s as N,t as S,z as A}from"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import{g as ie}from"../chunk-QILEJIFU.js";var Le="kanonak.org",Oe="document-ast",i=e=>({publisher:Le,package_:Oe,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ge(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var V=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=Ie(n.metadata,t),o=Ke(n.children),s=["---",...r,"---","",o].join(`
1
+ import{a as pe}from"../chunk-ED35OFGD.js";import"../chunk-GKIX3OD6.js";import{a as ve,b as M,c as Vn,n as X,o as Rn,p as vn,q as le,r as q,t as G}from"../chunk-TYVZXABI.js";import"../chunk-QHABFCRC.js";import"../chunk-6VIUXP4N.js";import{b as $n,c as Tn,d as Bn,e as xn,f as Un,k as fe}from"../chunk-22DSABP6.js";import{a as se}from"../chunk-7JBKOJB4.js";import"../chunk-PEJALHXK.js";import{c as U}from"../chunk-NUTHBBDZ.js";import{b as Y,c as D,d as ce,e as E,f as ue,i as $,j as T,k as B,l as w,m as me,n as x,o as de,s as N,t as S,z as A}from"../chunk-D4QGPMRW.js";import"../chunk-FUUTGGJS.js";import"../chunk-F67UH4FD.js";import{g as ie}from"../chunk-QILEJIFU.js";var Le="kanonak.org",Oe="document-ast",i=e=>({publisher:Le,package_:Oe,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ge(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var V=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=Ie(n.metadata,t),o=Ke(n.children),s=["---",...r,"---","",o].join(`
2
2
  `);return t?.trailingNewline&&(s.endsWith(`
3
3
  `)||(s+=`
4
4
  `)),s}};function Ie(e,n){if(!e)return[];let t=new Map;for(let c of e.entries)t.set(P(c.key),c);let r=new Map;if(n?.metadataRenames)for(let[c,u]of n.metadataRenames)r.set(P(c),u);let a=(n?.metadataKeys??e.entries.map(c=>c.key)).map(P),s=[];for(let c of a){let u=t.get(c);if(!u)continue;let f=r.get(c),l=P(f??c),d=ye(u.value,u.escapeHint);d!==void 0&&s.push(`${l}: ${d}`)}return s}function P(e){let n=e.lastIndexOf(".");return n===-1?e:e.substring(n+1)||e}function ye(e,n){switch(e.kind){case"StringScalar":return _e(e.stringValue,n);case"IntegerScalar":return String(e.integerValue);case"StructuredList":{let t=[];for(let r of e.items){let o=ye(r,n);o!==void 0&&t.push(o)}return t.join(", ")}case"StructuredMap":return;default:return}}function _e(e,n){return!n||ge(n,m.ESC_RAW)?e:ge(n,m.ESC_YAML_SAFE)?Ce(e):e}function Ce(e){return e.includes(`
@@ -88,4 +88,4 @@ ${e.rawContent}
88
88
  `)&&(o+=`
89
89
  `),o}};function C(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var K=class{backendUri="kanonak.org/transformations/dynamodb-json";render(n,t){if(!n.metadata)throw new Error("dynamodb-json backend: Document has no `metadata` channel. This backend serializes Document.metadata into DynamoDB attribute-value JSON \u2014 the transformation must populate that channel. (No silent empty artifact.)");let r=Ae(n.metadata,t),o=JSON.stringify(r,null,2);return t?.trailingNewline&&!o.endsWith(`
90
90
  `)&&(o+=`
91
- `),o}};function Ae(e,n){let t=new Map;for(let a of e.entries)t.set(a.key,a);let r=n?.metadataKeys??e.entries.map(a=>a.key),o={};for(let a of r){let s=t.get(a);if(!s)continue;let c=n?.metadataRenames.get(a)??a;o[c]=je(s.value,s.escapeHint)}return{M:o}}function je(e,n){switch(e.kind){case"StructuredMap":return Ae(e);case"StructuredList":return{L:e.items.map(t=>je(t,void 0))};case"StringScalar":return dn(e.stringValue,n??e.escapeHint);case"IntegerScalar":return fn(e.integerValue,n??e.escapeHint)}}function dn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL)){if(e==="true")return{BOOL:!0};if(e==="false")return{BOOL:!1};throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-bool must have the value "true" or "false"; got ${JSON.stringify(e)}.`)}if(n&&C(n,m.ESC_DYNAMODB_NULL))return{NULL:!0};if(n&&C(n,m.ESC_DYNAMODB_NUMBER)){if(e.trim()===""||Number.isNaN(Number(e)))throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-number must hold a numeric literal; got ${JSON.stringify(e)}.`);return{N:e}}return{S:e}}function fn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL))throw new Error(`dynamodb-json backend: esc-dynamodb-bool cannot apply to an IntegerScalar (value ${e}). Use a StringScalar "true"/"false".`);if(n&&C(n,m.ESC_DYNAMODB_NULL))throw new Error(`dynamodb-json backend: esc-dynamodb-null cannot apply to an IntegerScalar (value ${e}). Use a StringScalar hinted esc-dynamodb-null.`);return{N:String(e)}}var ln={"markdown-with-frontmatter":{formatUri:"kanonak.org/transformations/markdown-with-frontmatter",extension:".md"},"plain-markdown":{formatUri:"kanonak.org/transformations/plain-markdown",extension:".md"},toml:{formatUri:"kanonak.org/transformations/toml",extension:".toml"},json:{formatUri:"kanonak.org/transformations/json",extension:".json"},html:{formatUri:"kanonak.org/transformations/html",extension:".html"},svg:{formatUri:"kanonak.org/transformations/svg",extension:".svg"},stylesheet:{formatUri:"kanonak.org/transformations/stylesheet",extension:".css"},yaml:{formatUri:"kanonak.org/transformations/yaml",extension:".yaml"},"dynamodb-json":{formatUri:"kanonak.org/transformations/dynamodb-json",extension:".json"}},h=class extends Error{},H=class{backends=new Map;constructor(){this.register(new V),this.register(new R),this.register(new v),this.register(new L),this.register(new O),this.register(new I),this.register(new _),this.register(new K)}register(n){this.backends.set(n.backendUri,n)}async run(n){let t=n.transformationKanonaks??n.allKanonaks,r=M(n.transformation,t);if(!r.outputs.has(n.outputFormat))throw new h(`Transformation "${r.name}" does not declare output format "${n.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let o=this.findBackend(n.outputFormat);if(!o)throw new h(`No backend registered for OutputFormat "${n.outputFormat}".`);let a=new q(n.repository,n.parser,n.objectParser),s=new le(a,n.allKanonaks,r.fragments);return r.kind==="instance"?this.runInstance(r,n,o,s):this.runSet(r,n,o,s)}async runInstance(n,t,r,o){let a=Ee(t.instances,n.inputPattern.requires),s=$e(a,n.inputPattern.sortBy),c=[];for(let u of s){let f=new Map;f.set("input",u);let l=await o.evaluate(n.rule,f);ee(l,n.name,`input "${u.name}"`);let d=ne(await o.evaluate(n.artifactName,f),n.name,`input "${u.name}"`),g=te(n.overrides.get(t.outputFormat),t.runtimeOverride),k=r.render(l,g);c.push({fileName:d,format:t.outputFormat,content:k,source:{kind:"instance",sourceName:u.name}})}return c}async runSet(n,t,r,o){let a=Ee(t.instances,n.inputPattern.requires),s=$e(a,n.inputPattern.sortBy);return n.partitionBy?this.runSetWithPartition(n,s,t,r,o):this.runSetSingle(n,s,t,r,o)}async runSetSingle(n,t,r,o,a){let s=new Map;s.set("inputs",t);let c=await a.evaluate(n.rule,s);ee(c,n.name,"set");let u=ne(await a.evaluate(n.artifactName,s),n.name,"set"),f=te(n.overrides.get(r.outputFormat),r.runtimeOverride),l=o.render(c,f);return[{fileName:u,format:r.outputFormat,content:l,source:{kind:"set",memberCount:t.length}}]}async runSetWithPartition(n,t,r,o,a){let s=n.partitionBy,c=new Map,u=[];for(let l of t){let d=yn(l,s);if(d==null)continue;let g=kn(d),k=c.get(g);k||(k={keyValue:d,keyDisplay:bn(d),members:[]},c.set(g,k),u.push(g)),k.members.push(l)}let f=[];for(let l of u){let d=c.get(l),g=new Map;g.set("inputs",d.members),g.set("key",d.keyValue);let k=await a.evaluate(n.rule,g);ee(k,n.name,`partition "${d.keyDisplay}"`);let Ue=ne(await a.evaluate(n.artifactName,g),n.name,`partition "${d.keyDisplay}"`),Ve=te(n.overrides.get(r.outputFormat),r.runtimeOverride),Re=o.render(k,Ve);f.push({fileName:Ue,format:r.outputFormat,content:Re,source:{kind:"set",memberCount:d.members.length,partitionKey:d.keyDisplay}})}return f}findBackend(n){let t=ln[n];if(t)return this.backends.get(t.formatUri)}};function Ee(e,n){return n.length===0?e:e.filter(t=>{for(let r of n)if(!gn(t,r))return!1;return!0})}function $e(e,n){if(n.length===0)return e;let t=[...e];return t.sort((r,o)=>{for(let a of n){let s=Te(r,a.byProperty),c=Te(o,a.byProperty),u=pn(s,c,a.order);if(u!==0)return u}return 0}),t}function Te(e,n){for(let t of e.statement){let r=re(t);if(!(!r||!N(r,n))){if(t instanceof $||t instanceof T||t instanceof B)return t.object;if(t instanceof x)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(t instanceof w)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function pn(e,n,t){if(e===void 0&&n===void 0)return 0;if(e===void 0)return t==="ascending"?1:-1;if(n===void 0)return t==="ascending"?-1:1;let r;return typeof e=="number"&&typeof n=="number"?r=e-n:r=String(e).localeCompare(String(n)),t==="ascending"?r:-r}function gn(e,n){for(let t of e.statement){let r=re(t);if(!r||!N(r,n))continue;let o=t.object;if(o!=null&&!(typeof o=="string"&&o.length===0)&&!(Array.isArray(o)&&o.length===0))return!0}return!1}function yn(e,n){for(let t of e.statement){let r=re(t);if(!(!r||!N(r,n))&&(t instanceof $||t instanceof T||t instanceof B||t instanceof w||t instanceof x))return t.object}}function re(e){return e.predicate?.subject}function kn(e){if(e===void 0)return" undef";if(e===null)return" null";if(typeof e=="string")return`s:${e}`;if(typeof e=="number")return`n:${e}`;if(typeof e=="boolean")return`b:${e}`;if(e instanceof E){let n=e.subject;return`r:${n.publisher}/${n.package_}/${n.name}`}if(e instanceof Y){let n=e.name??"";return`k:${e.namespace??""}/${n}`}if(typeof e=="object"&&e!==null&&typeof e.name=="string"&&typeof e.publisher=="string"){let n=e;return`u:${n.publisher}/${n.package_}/${n.name}`}return`o:${JSON.stringify(e,(n,t)=>n==="sourceKey"?void 0:t)}`}function bn(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e instanceof E?e.subject.name:e instanceof Y?e.name??"":typeof e=="object"&&e!==null&&typeof e.name=="string"?e.name:""}function ee(e,n,t){if(typeof e!="object"||e===null||e.kind!=="Document")throw new h(`Transformation "${n}" rule did not yield a Document for ${t}. Got: ${Be(e)}`)}function ne(e,n,t){if(typeof e=="string")return e;if(Array.isArray(e)&&e.every(hn))return e.map(r=>String(r)).join("");throw new h(`Transformation "${n}" artifactName did not yield a string for ${t}. Got: ${Be(e)}`)}function hn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Be(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"){let n=e.kind;return n?`object(kind=${n})`:"object"}return typeof e}function te(e,n){if(!e&&!n)return;let t={metadataRenames:n?.metadataRenames??e?.metadataRenames??new Map},r=n?.metadataKeys??e?.metadataKeys;r!==void 0&&(t.metadataKeys=r);let o=n?.trailingNewline??e?.trailingNewline;o!==void 0&&(t.trailingNewline=o);let a=n?.omitWrapper??e?.omitWrapper;return a!==void 0&&(t.omitWrapper=a),t}var p=class extends Error{constructor(t,r){super(t);this.cause=r;this.name="RenderError"}cause},xe={publisher:"kanonak.org",package_:"derivation",name:"default"},oe=class{constructor(n,t=new se,r=new fe){this.repository=n;this.parser=t;this.objectParser=r}repository;parser;objectParser;runner=new H;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async renderViaLook(n){let t=await this.getCatalog(),r=A(t,n.resource);if(!(r instanceof D))throw new p(`Resource not found: ${b(n.resource)}`);let o=new G(t),a;if(n.format.name==="html")a=await o.renderHtml(r);else if(n.format.name==="stylesheet")a=o.renderStylesheet(r);else throw new p(`LookRenderer does not support format ${b(n.format)} \u2014 only formats.html and formats.stylesheet are implemented in v0.1.`);return{content:a,format:n.format,filename:r.name}}async findDerivation(n){let t=await this.getCatalog(),r=A(t,n.resource);if(!(r instanceof D))return;let o=n.variant??xe;return pe(r,n.format,o,t)}async render(n){if(n.format.name==="html"||n.format.name==="stylesheet"){let a=await this.getCatalog(),s=A(a,n.resource);if(s instanceof D){let u=new G(a).findCascadedLook(s);if(u&&!wn(u.sourceClass)){let f=await this.findDerivation(n);if(!f||Dn(f))return this.renderViaLook({resource:n.resource,format:n.format})}}}let t=await this.findDerivation(n);if(!t)throw new p(`No derivation found for ${b(n.resource)} \u2192 format ${b(n.format)}`+(n.variant?` variant ${b(n.variant)}`:""));let r=ie(t.transformation.version),o={transformation:{publisher:t.transformation.publisher,package_:t.transformation.package_,name:t.transformation.name,...r?{version:r}:{}},input:n.resource,format:n.format};return n.omitWrapper!==void 0&&(o.omitWrapper=n.omitWrapper),this.runTransformation(o)}async runTransformation(n){let t=await this.getCatalog(),r=A(t,n.transformation);if(!(r instanceof D))throw new p(`Transformation not found: ${b(n.transformation)}`);let o=A(t,n.input);if(!(o instanceof D))throw new p(`Input resource not found: ${b(n.input)}`);let a=M(r,t),s=Sn(a.outputs,n.format);if(!s)throw new p(`Transformation ${b(n.transformation)} declares outputs [${[...a.outputs].join(", ")}], none of which corresponds to format ${b(n.format)}`);let c;try{c=await this.runner.run({transformation:r,instances:[o],allKanonaks:t,repository:this.repository,parser:this.parser,objectParser:this.objectParser,outputFormat:s,...n.omitWrapper!==void 0?{runtimeOverride:{metadataRenames:new Map,omitWrapper:n.omitWrapper}}:{}})}catch(u){throw new p(`Transformation execution failed: ${u.message}`,u)}if(c.length===0)throw new p("Transformation produced no artifacts");return{content:c[0].content,format:n.format,filename:c[0].fileName}}async getCatalog(){return this.cachedCatalog||(this.cachedCatalog=await this.objectParser.parseKanonaks(this.repository)),this.cachedCatalog}};function b(e){return`${e.publisher}/${e.package_}/${e.name}`}function Dn(e){return typeof e.source=="string"?!1:e.source.publisher==="kanonak.org"&&e.source.package_==="core-rdf"&&e.source.name==="Resource"}function wn(e){return e.publisher==="kanonak.org"&&e.package_==="core-rdf"&&e.name==="Resource"}function Sn(e,n){let t=n.name;if(e.has(t))return t;for(let r of e)if(r.startsWith(t+"-")||r===t)return r}var An="kanonak.org/core-rdf/type";function ae(e){let n=En(e),t,r={type:""};for(let o of e.statement){let a=o.predicate?.subject;if(!a)throw new Error(`Expression node ${n} has a statement with no resolved predicate`);if(U(a)===An){if(!(o instanceof w))throw new Error(`Expression node ${n} has a non-reference 'type' statement`);if(t!==void 0)throw new Error(`Expression node ${n} declares more than one type \u2014 a runtime tree node is exactly one operator/literal/leaf class`);t=U(o.object.subject);continue}let s=a.name;if(s in r)throw new Error(`Expression node ${n} declares operand '${s}' more than once`);r[s]=jn(o,n,s)}if(t===void 0)throw new Error(`Expression node ${n} declares no type \u2014 the runtime dispatches on it`);return r.type=t,r}function jn(e,n,t){if(e instanceof $||e instanceof de||e instanceof T||e instanceof B)return e.object;if(e instanceof w)return U(e.object.subject);if(e instanceof me)return ae(e.object);if(e instanceof x)return(e.object??[]).map((r,o)=>{if(r instanceof E)return U(r.subject);if(r instanceof ce)return ae(r);if(r instanceof ue)return r.value;throw new Error(`Expression node ${n}: '${t}'[${o}] is not a serializable list item`)});throw new Error(`Expression node ${n}: operand '${t}' has an unserializable statement kind`)}function En(e){let n=e;return n.name?`'${n.name}'`:"(embedded)"}export{I as CssBackend,xe as DEFAULT_VARIANT,m as DOCAST,Oe as DOCAST_PKG,Le as DOCAST_PUB,K as DynamoDbBackend,le as ExpressionEngineV3,Rn as ExpressionEvalErrorV3,L as HtmlBackend,v as JsonBackend,V as MarkdownFrontmatterBackend,q as ReferenceResolver,p as RenderError,ln as SUPPORTED_FORMATS_V3,O as SvgBackend,xn as TX_V3,Tn as TX_V3_PKG,$n as TX_V3_PUB,Bn as TX_V3_VERSION_MAJOR,R as TomlBackend,oe as TransformationEngine,ve as TransformationLoadErrorV3,h as TransformationRunnerErrorV3,H as TransformationRunnerV3,_ as YamlBackend,Un as compileExpression,M as compileTransformationV3,Vn as isRawStringV3,X as renderMarkdownToHtml,ae as toExpressionRuntimeTree};
91
+ `),o}};function Ae(e,n){let t=new Map;for(let a of e.entries)t.set(a.key,a);let r=n?.metadataKeys??e.entries.map(a=>a.key),o={};for(let a of r){let s=t.get(a);if(!s)continue;let c=n?.metadataRenames.get(a)??a;o[c]=je(s.value,s.escapeHint)}return{M:o}}function je(e,n){switch(e.kind){case"StructuredMap":return Ae(e);case"StructuredList":return{L:e.items.map(t=>je(t,void 0))};case"StringScalar":return dn(e.stringValue,n??e.escapeHint);case"IntegerScalar":return fn(e.integerValue,n??e.escapeHint)}}function dn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL)){if(e==="true")return{BOOL:!0};if(e==="false")return{BOOL:!1};throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-bool must have the value "true" or "false"; got ${JSON.stringify(e)}.`)}if(n&&C(n,m.ESC_DYNAMODB_NULL))return{NULL:!0};if(n&&C(n,m.ESC_DYNAMODB_NUMBER)){if(e.trim()===""||Number.isNaN(Number(e)))throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-number must hold a numeric literal; got ${JSON.stringify(e)}.`);return{N:e}}return{S:e}}function fn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL))throw new Error(`dynamodb-json backend: esc-dynamodb-bool cannot apply to an IntegerScalar (value ${e}). Use a StringScalar "true"/"false".`);if(n&&C(n,m.ESC_DYNAMODB_NULL))throw new Error(`dynamodb-json backend: esc-dynamodb-null cannot apply to an IntegerScalar (value ${e}). Use a StringScalar hinted esc-dynamodb-null.`);return{N:String(e)}}var ln={"markdown-with-frontmatter":{formatUri:"kanonak.org/transformations/markdown-with-frontmatter",extension:".md"},"plain-markdown":{formatUri:"kanonak.org/transformations/plain-markdown",extension:".md"},toml:{formatUri:"kanonak.org/transformations/toml",extension:".toml"},json:{formatUri:"kanonak.org/transformations/json",extension:".json"},html:{formatUri:"kanonak.org/transformations/html",extension:".html"},svg:{formatUri:"kanonak.org/transformations/svg",extension:".svg"},stylesheet:{formatUri:"kanonak.org/transformations/stylesheet",extension:".css"},yaml:{formatUri:"kanonak.org/transformations/yaml",extension:".yaml"},"dynamodb-json":{formatUri:"kanonak.org/transformations/dynamodb-json",extension:".json"}},h=class extends Error{},H=class{backends=new Map;constructor(){this.register(new V),this.register(new R),this.register(new v),this.register(new L),this.register(new O),this.register(new I),this.register(new _),this.register(new K)}register(n){this.backends.set(n.backendUri,n)}async run(n){let t=n.transformationKanonaks??n.allKanonaks,r=M(n.transformation,t);if(!r.outputs.has(n.outputFormat))throw new h(`Transformation "${r.name}" does not declare output format "${n.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let o=this.findBackend(n.outputFormat);if(!o)throw new h(`No backend registered for OutputFormat "${n.outputFormat}".`);let a=new q(n.repository,n.parser,n.objectParser),s=new le(a,n.allKanonaks,r.fragments);return r.kind==="instance"?this.runInstance(r,n,o,s):this.runSet(r,n,o,s)}async runInstance(n,t,r,o){let a=Ee(t.instances,n.inputPattern.requires),s=$e(a,n.inputPattern.sortBy),c=[];for(let u of s){let f=new Map;f.set("input",u);let l=await o.evaluate(n.rule,f);ee(l,n.name,`input "${u.name}"`);let d=ne(await o.evaluate(n.artifactName,f),n.name,`input "${u.name}"`),g=te(n.overrides.get(t.outputFormat),t.runtimeOverride),k=r.render(l,g);c.push({fileName:d,format:t.outputFormat,content:k,source:{kind:"instance",sourceName:u.name}})}return c}async runSet(n,t,r,o){let a=Ee(t.instances,n.inputPattern.requires),s=$e(a,n.inputPattern.sortBy);return n.partitionBy?this.runSetWithPartition(n,s,t,r,o):this.runSetSingle(n,s,t,r,o)}async runSetSingle(n,t,r,o,a){let s=new Map;s.set("inputs",t);let c=await a.evaluate(n.rule,s);ee(c,n.name,"set");let u=ne(await a.evaluate(n.artifactName,s),n.name,"set"),f=te(n.overrides.get(r.outputFormat),r.runtimeOverride),l=o.render(c,f);return[{fileName:u,format:r.outputFormat,content:l,source:{kind:"set",memberCount:t.length}}]}async runSetWithPartition(n,t,r,o,a){let s=n.partitionBy,c=new Map,u=[];for(let l of t){let d=yn(l,s);if(d==null)continue;let g=kn(d),k=c.get(g);k||(k={keyValue:d,keyDisplay:bn(d),members:[]},c.set(g,k),u.push(g)),k.members.push(l)}let f=[];for(let l of u){let d=c.get(l),g=new Map;g.set("inputs",d.members),g.set("key",d.keyValue);let k=await a.evaluate(n.rule,g);ee(k,n.name,`partition "${d.keyDisplay}"`);let Ue=ne(await a.evaluate(n.artifactName,g),n.name,`partition "${d.keyDisplay}"`),Ve=te(n.overrides.get(r.outputFormat),r.runtimeOverride),Re=o.render(k,Ve);f.push({fileName:Ue,format:r.outputFormat,content:Re,source:{kind:"set",memberCount:d.members.length,partitionKey:d.keyDisplay}})}return f}findBackend(n){let t=ln[n];if(t)return this.backends.get(t.formatUri)}};function Ee(e,n){return n.length===0?e:e.filter(t=>{for(let r of n)if(!gn(t,r))return!1;return!0})}function $e(e,n){if(n.length===0)return e;let t=[...e];return t.sort((r,o)=>{for(let a of n){let s=Te(r,a.byProperty),c=Te(o,a.byProperty),u=pn(s,c,a.order);if(u!==0)return u}return 0}),t}function Te(e,n){for(let t of e.statement){let r=re(t);if(!(!r||!N(r,n))){if(t instanceof $||t instanceof T||t instanceof B)return t.object;if(t instanceof x)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(t instanceof w)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function pn(e,n,t){if(e===void 0&&n===void 0)return 0;if(e===void 0)return t==="ascending"?1:-1;if(n===void 0)return t==="ascending"?-1:1;let r;return typeof e=="number"&&typeof n=="number"?r=e-n:r=String(e).localeCompare(String(n)),t==="ascending"?r:-r}function gn(e,n){for(let t of e.statement){let r=re(t);if(!r||!N(r,n))continue;let o=t.object;if(o!=null&&!(typeof o=="string"&&o.length===0)&&!(Array.isArray(o)&&o.length===0))return!0}return!1}function yn(e,n){for(let t of e.statement){let r=re(t);if(!(!r||!N(r,n))&&(t instanceof $||t instanceof T||t instanceof B||t instanceof w||t instanceof x))return t.object}}function re(e){return e.predicate?.subject}function kn(e){if(e===void 0)return" undef";if(e===null)return" null";if(typeof e=="string")return`s:${e}`;if(typeof e=="number")return`n:${e}`;if(typeof e=="boolean")return`b:${e}`;if(e instanceof E){let n=e.subject;return`r:${n.publisher}/${n.package_}/${n.name}`}if(e instanceof Y){let n=e.name??"";return`k:${e.namespace??""}/${n}`}if(typeof e=="object"&&e!==null&&typeof e.name=="string"&&typeof e.publisher=="string"){let n=e;return`u:${n.publisher}/${n.package_}/${n.name}`}return`o:${JSON.stringify(e,(n,t)=>n==="sourceKey"?void 0:t)}`}function bn(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e instanceof E?e.subject.name:e instanceof Y?e.name??"":typeof e=="object"&&e!==null&&typeof e.name=="string"?e.name:""}function ee(e,n,t){if(typeof e!="object"||e===null||e.kind!=="Document")throw new h(`Transformation "${n}" rule did not yield a Document for ${t}. Got: ${Be(e)}`)}function ne(e,n,t){if(typeof e=="string")return e;if(Array.isArray(e)&&e.every(hn))return e.map(r=>String(r)).join("");throw new h(`Transformation "${n}" artifactName did not yield a string for ${t}. Got: ${Be(e)}`)}function hn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Be(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"){let n=e.kind;return n?`object(kind=${n})`:"object"}return typeof e}function te(e,n){if(!e&&!n)return;let t={metadataRenames:n?.metadataRenames??e?.metadataRenames??new Map},r=n?.metadataKeys??e?.metadataKeys;r!==void 0&&(t.metadataKeys=r);let o=n?.trailingNewline??e?.trailingNewline;o!==void 0&&(t.trailingNewline=o);let a=n?.omitWrapper??e?.omitWrapper;return a!==void 0&&(t.omitWrapper=a),t}var p=class extends Error{constructor(t,r){super(t);this.cause=r;this.name="RenderError"}cause},xe={publisher:"kanonak.org",package_:"derivation",name:"default"},oe=class{constructor(n,t=new se,r=new fe){this.repository=n;this.parser=t;this.objectParser=r}repository;parser;objectParser;runner=new H;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async renderViaLook(n){let t=await this.getCatalog(),r=A(t,n.resource);if(!(r instanceof D))throw new p(`Resource not found: ${b(n.resource)}`);let o=new G(t),a;if(n.format.name==="html")a=await o.renderHtml(r);else if(n.format.name==="stylesheet")a=o.renderStylesheet(r);else throw new p(`LookRenderer does not support format ${b(n.format)} \u2014 only formats.html and formats.stylesheet are implemented in v0.1.`);return{content:a,format:n.format,filename:r.name}}async findDerivation(n){let t=await this.getCatalog(),r=A(t,n.resource);if(!(r instanceof D))return;let o=n.variant??xe;return pe(r,n.format,o,t)}async render(n){if(n.format.name==="html"||n.format.name==="stylesheet"){let a=await this.getCatalog(),s=A(a,n.resource);if(s instanceof D){let u=new G(a).findCascadedLook(s);if(u&&!wn(u.sourceClass)){let f=await this.findDerivation(n);if(!f||Dn(f))return this.renderViaLook({resource:n.resource,format:n.format})}}}let t=await this.findDerivation(n);if(!t)throw new p(`No derivation found for ${b(n.resource)} \u2192 format ${b(n.format)}`+(n.variant?` variant ${b(n.variant)}`:""));let r=ie(t.transformation.version),o={transformation:{publisher:t.transformation.publisher,package_:t.transformation.package_,name:t.transformation.name,...r?{version:r}:{}},input:n.resource,format:n.format};return n.omitWrapper!==void 0&&(o.omitWrapper=n.omitWrapper),this.runTransformation(o)}async runTransformation(n){let t=await this.getCatalog(),r=A(t,n.transformation);if(!(r instanceof D))throw new p(`Transformation not found: ${b(n.transformation)}`);let o=A(t,n.input);if(!(o instanceof D))throw new p(`Input resource not found: ${b(n.input)}`);let a=M(r,t),s=Sn(a.outputs,n.format);if(!s)throw new p(`Transformation ${b(n.transformation)} declares outputs [${[...a.outputs].join(", ")}], none of which corresponds to format ${b(n.format)}`);let c;try{c=await this.runner.run({transformation:r,instances:[o],allKanonaks:t,repository:this.repository,parser:this.parser,objectParser:this.objectParser,outputFormat:s,...n.omitWrapper!==void 0?{runtimeOverride:{metadataRenames:new Map,omitWrapper:n.omitWrapper}}:{}})}catch(u){throw new p(`Transformation execution failed: ${u.message}`,u)}if(c.length===0)throw new p("Transformation produced no artifacts");return{content:c[0].content,format:n.format,filename:c[0].fileName}}async getCatalog(){return this.cachedCatalog||(this.cachedCatalog=await this.objectParser.parseKanonaks(this.repository)),this.cachedCatalog}};function b(e){return`${e.publisher}/${e.package_}/${e.name}`}function Dn(e){return typeof e.source=="string"?!1:e.source.publisher==="kanonak.org"&&e.source.package_==="core-rdf"&&e.source.name==="Resource"}function wn(e){return e.publisher==="kanonak.org"&&e.package_==="core-rdf"&&e.name==="Resource"}function Sn(e,n){let t=n.name;if(e.has(t))return t;for(let r of e)if(r.startsWith(t+"-")||r===t)return r}var An="kanonak.org/core-rdf/type";function ae(e){let n=En(e),t,r={type:""};for(let o of e.statement){let a=o.predicate?.subject;if(!a)throw new Error(`Expression node ${n} has a statement with no resolved predicate`);if(U(a)===An){if(!(o instanceof w))throw new Error(`Expression node ${n} has a non-reference 'type' statement`);if(t!==void 0)throw new Error(`Expression node ${n} declares more than one type \u2014 a runtime tree node is exactly one operator/literal/leaf class`);t=U(o.object.subject);continue}let s=a.name;if(s in r)throw new Error(`Expression node ${n} declares operand '${s}' more than once`);r[s]=jn(o,n,s)}if(t===void 0)throw new Error(`Expression node ${n} declares no type \u2014 the runtime dispatches on it`);return r.type=t,r}function jn(e,n,t){if(e instanceof $||e instanceof de||e instanceof T||e instanceof B)return e.object;if(e instanceof w)return U(e.object.subject);if(e instanceof me)return ae(e.object);if(e instanceof x)return(e.object??[]).map((r,o)=>{if(r instanceof E)return U(r.subject);if(r instanceof ce)return ae(r);if(r instanceof ue)return r.value;throw new Error(`Expression node ${n}: '${t}'[${o}] is not a serializable list item`)});throw new Error(`Expression node ${n}: operand '${t}' has an unserializable statement kind`)}function En(e){let n=e;return n.name?`'${n.name}'`:"(embedded)"}export{I as CssBackend,xe as DEFAULT_VARIANT,m as DOCAST,Oe as DOCAST_PKG,Le as DOCAST_PUB,K as DynamoDbBackend,le as ExpressionEngineV3,vn as ExpressionEvalErrorV3,L as HtmlBackend,v as JsonBackend,xn as MATH_V1,V as MarkdownFrontmatterBackend,q as ReferenceResolver,p as RenderError,ln as SUPPORTED_FORMATS_V3,O as SvgBackend,Un as TX_V3,Tn as TX_V3_PKG,$n as TX_V3_PUB,Bn as TX_V3_VERSION_MAJOR,R as TomlBackend,oe as TransformationEngine,ve as TransformationLoadErrorV3,h as TransformationRunnerErrorV3,H as TransformationRunnerV3,_ as YamlBackend,Vn as compileExpression,M as compileTransformationV3,Rn as isRawStringV3,X as renderMarkdownToHtml,ae as toExpressionRuntimeTree};
@@ -90,7 +90,7 @@ export interface CompiledFormatOverrideV3 {
90
90
  * doctype + style + metadata <dl>; analogous in other backends). */
91
91
  omitWrapper?: boolean | undefined;
92
92
  }
93
- export type CompiledExpressionV3 = CompiledStringLiteralV3 | CompiledIntegerLiteralV3 | CompiledDecimalLiteralV3 | CompiledBooleanLiteralV3 | CompiledVarRefV3 | CompiledPropertyReadV3 | CompiledTraverseV3 | CompiledBuildAstNodeV3 | CompiledWhenV3 | CompiledConcatV3 | CompiledFallbackV3 | CompiledUriNameV3 | CompiledUriPublisherV3 | CompiledUriPackageV3 | CompiledUriVersionV3 | CompiledSubjectUriV3 | CompiledUriLiteralV3 | CompiledDisplayLabelV3 | CompiledResolveRefV3 | CompiledNormalizeV3 | CompiledUnescapedStringV3 | CompiledIsSetV3 | CompiledCallFragmentV3 | CompiledJoinV3 | CompiledCountV3 | CompiledSumV3 | CompiledMinV3 | CompiledMaxV3 | CompiledAverageV3 | CompiledForEachV3 | CompiledListMapV3 | CompiledFilterV3 | CompiledPartitionByV3 | CompiledDistinctByV3 | CompiledAllStatementsV3 | CompiledStatementPredicateV3 | CompiledStatementValueV3 | CompiledDateFormatV3 | CompiledNumberFormatV3 | CompiledAddV3 | CompiledSubtractV3 | CompiledMultiplyV3 | CompiledDivideV3 | CompiledReverseV3 | CompiledWindowedMapV3 | CompiledPairwiseMapV3 | CompiledScanV3 | CompiledListItemAtV3 | CompiledEqualsV3 | CompiledGreaterThanV3 | CompiledLessThanV3 | CompiledGreaterThanOrEqualV3 | CompiledLessThanOrEqualV3 | CompiledNotV3 | CompiledAndV3 | CompiledOrV3 | CompiledContainsV3 | CompiledAbsV3 | CompiledNegateV3 | CompiledIsReferenceV3 | CompiledIsEmbeddedV3 | CompiledIsListV3 | CompiledStatementObjectV3 | CompiledIsStringV3 | CompiledIsNumberV3 | CompiledIsBooleanV3 | CompiledLetV3 | CompiledGetStatementByNameV3 | CompiledRenderMarkdownV3;
93
+ export type CompiledExpressionV3 = CompiledStringLiteralV3 | CompiledIntegerLiteralV3 | CompiledDecimalLiteralV3 | CompiledBooleanLiteralV3 | CompiledVarRefV3 | CompiledPropertyReadV3 | CompiledTraverseV3 | CompiledBuildAstNodeV3 | CompiledWhenV3 | CompiledConcatV3 | CompiledFallbackV3 | CompiledUriNameV3 | CompiledUriPublisherV3 | CompiledUriPackageV3 | CompiledUriVersionV3 | CompiledSubjectUriV3 | CompiledUriLiteralV3 | CompiledDisplayLabelV3 | CompiledResolveRefV3 | CompiledNormalizeV3 | CompiledUnescapedStringV3 | CompiledIsSetV3 | CompiledCallFragmentV3 | CompiledJoinV3 | CompiledCountV3 | CompiledSumV3 | CompiledMinV3 | CompiledMaxV3 | CompiledAverageV3 | CompiledForEachV3 | CompiledListMapV3 | CompiledFilterV3 | CompiledPartitionByV3 | CompiledDistinctByV3 | CompiledAllStatementsV3 | CompiledStatementPredicateV3 | CompiledStatementValueV3 | CompiledDateFormatV3 | CompiledNumberFormatV3 | CompiledNumericOpV3 | CompiledReverseV3 | CompiledWindowedMapV3 | CompiledPairwiseMapV3 | CompiledScanV3 | CompiledListItemAtV3 | CompiledEqualsV3 | CompiledGreaterThanV3 | CompiledLessThanV3 | CompiledGreaterThanOrEqualV3 | CompiledLessThanOrEqualV3 | CompiledNotV3 | CompiledAndV3 | CompiledOrV3 | CompiledContainsV3 | CompiledMatchesV3 | CompiledIsReferenceV3 | CompiledIsEmbeddedV3 | CompiledIsListV3 | CompiledStatementObjectV3 | CompiledIsStringV3 | CompiledIsNumberV3 | CompiledIsBooleanV3 | CompiledLetV3 | CompiledGetStatementByNameV3 | CompiledRenderMarkdownV3;
94
94
  export interface CompiledStringLiteralV3 {
95
95
  kind: 'string-literal';
96
96
  value: string;
@@ -228,25 +228,23 @@ export interface CompiledNumberFormatV3 {
228
228
  /** ISO 4217; only meaningful for the `currency` style. Defaults to USD. */
229
229
  currencyCode?: string;
230
230
  }
231
- export interface CompiledAddV3 {
232
- kind: 'add';
233
- left: CompiledExpressionV3;
234
- right: CompiledExpressionV3;
235
- }
236
- export interface CompiledSubtractV3 {
237
- kind: 'subtract';
238
- left: CompiledExpressionV3;
239
- right: CompiledExpressionV3;
240
- }
241
- export interface CompiledMultiplyV3 {
242
- kind: 'multiply';
243
- left: CompiledExpressionV3;
244
- right: CompiledExpressionV3;
245
- }
246
- export interface CompiledDivideV3 {
247
- kind: 'divide';
248
- left: CompiledExpressionV3;
249
- right: CompiledExpressionV3;
231
+ /**
232
+ * A numeric operator — tx arithmetic (Add … Divide, Abs, Negate) and the
233
+ * `kanonak.org/math` family (Power … Sign, Clip). Computed by the expression runtime (`@kanonak-protocol/expression`
234
+ * `evaluate`), so its determinism-bearing primitives — Round half away from
235
+ * zero, floored Modulo, Sign(0), the domain errors — are defined once, there.
236
+ */
237
+ export interface CompiledNumericOpV3 {
238
+ kind: 'numeric-op';
239
+ /** The operator's canonical versionless URI — the runtime's node `type`. */
240
+ type: string;
241
+ /** Its local name, for messages. */
242
+ name: string;
243
+ /** Operands in evaluation order, each under the runtime's operand key. */
244
+ operands: {
245
+ name: string;
246
+ expr: CompiledExpressionV3;
247
+ }[];
250
248
  }
251
249
  export interface CompiledReverseV3 {
252
250
  kind: 'reverse';
@@ -321,13 +319,16 @@ export interface CompiledContainsV3 {
321
319
  haystack: CompiledExpressionV3;
322
320
  needle: CompiledExpressionV3;
323
321
  }
324
- export interface CompiledAbsV3 {
325
- kind: 'abs';
326
- value: CompiledExpressionV3;
327
- }
328
- export interface CompiledNegateV3 {
329
- kind: 'negate';
330
- value: CompiledExpressionV3;
322
+ /**
323
+ * `tx.Matches` (transformations@3.16.0): the string value of `source` tested
324
+ * against `pattern` — a fixed, authored pattern, validated when compiled — by
325
+ * the expression runtime's own matcher (`@kanonak-protocol/expression`
326
+ * `matches`), so the pinned regex subset is defined once.
327
+ */
328
+ export interface CompiledMatchesV3 {
329
+ kind: 'matches';
330
+ source: CompiledExpressionV3;
331
+ pattern: string;
331
332
  }
332
333
  export interface CompiledIsReferenceV3 {
333
334
  kind: 'is-reference';
@@ -14,6 +14,30 @@ import type { EntityUri } from '../../uri-helpers/UriHelpers.js';
14
14
  export declare const TX_V3_PUB = "kanonak.org";
15
15
  export declare const TX_V3_PKG = "transformations";
16
16
  export declare const TX_V3_VERSION_MAJOR = 3;
17
+ /**
18
+ * `kanonak.org/math` (1.0.0) — the numeric operators beyond tx arithmetic.
19
+ * The binary ones take `tx.arithLeft`/`tx.arithRight` and the unary ones
20
+ * `tx.value` (they subclass `tx.BinaryArithmetic` / `tx.UnaryNumericOp`);
21
+ * `Clip` is the one ternary, over its own three operands.
22
+ */
23
+ export declare const MATH_V1: {
24
+ readonly Power: EntityUri;
25
+ readonly Modulo: EntityUri;
26
+ readonly Minimum: EntityUri;
27
+ readonly Maximum: EntityUri;
28
+ readonly Exp: EntityUri;
29
+ readonly Ln: EntityUri;
30
+ readonly Log10: EntityUri;
31
+ readonly Sqrt: EntityUri;
32
+ readonly Floor: EntityUri;
33
+ readonly Ceil: EntityUri;
34
+ readonly Round: EntityUri;
35
+ readonly Sign: EntityUri;
36
+ readonly Clip: EntityUri;
37
+ readonly clipValue: EntityUri;
38
+ readonly clipLower: EntityUri;
39
+ readonly clipUpper: EntityUri;
40
+ };
17
41
  export declare const TX_V3: {
18
42
  readonly Transformation: EntityUri;
19
43
  readonly InstanceTransformation: EntityUri;
@@ -196,6 +220,9 @@ export declare const TX_V3: {
196
220
  readonly Contains: EntityUri;
197
221
  readonly haystack: EntityUri;
198
222
  readonly needle: EntityUri;
223
+ readonly Matches: EntityUri;
224
+ readonly matchSource: EntityUri;
225
+ readonly pattern: EntityUri;
199
226
  readonly UnaryNumericOp: EntityUri;
200
227
  readonly value: EntityUri;
201
228
  readonly Abs: EntityUri;