@kanonak-protocol/sdk 3.73.0 → 3.75.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -34,3 +34,5 @@ export type { MaterializeOptions, MaterializeResult } from './view/index.js';
34
34
  export { PackageBuilder, ImportBook, contentAddressedName, sanitizeName, ProducerRepository, EntitlementProducer, EntitlementDeniedError, allowAllPolicy, noopMeter, } from './producer/index.js';
35
35
  export type { BuiltPackage, ImportEntry, IPackageProducer, ProduceResult, VersionRange, IEntitlementPolicy, IMeter, ProduceContext, PackageAddress, EntitlementDecision, RequestPrincipal, } from './producer/index.js';
36
36
  export { canonicalForm, canonicalHash } from './canonical/index.js';
37
+ export { buildOntologyModel } from './introspection/index.js';
38
+ export type { OntologyModel, ClassDef, PropertyDef, ClassRef, TypeRef, BuildOntologyModelOptions, } from './introspection/index.js';
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import{a as ir,b as sr,c as cr,d as lr,e as fe}from"./chunk-FX7JDGL6.js";import{a as Qr,c as ke,e as Te,h as Ne,i as Oe,j as en}from"./chunk-X5TYWQRA.js";import{a as nr,b as or,c as ar,d as U,e as _,f as c}from"./chunk-Y7TGQ7UF.js";import{a as Xr}from"./chunk-F5ANO7MJ.js";import"./chunk-QHABFCRC.js";import{a as jt,b as Bt,c as At,d as Vt,e as Dt,f as _t,g as Lt,h as Ft}from"./chunk-ATH6636H.js";import{b as Tt,c as Nt,d as Ut}from"./chunk-LKBG2MK6.js";import{a as It}from"./chunk-4NO7MHS7.js";import{a as dr,b as pr,c as mr,d as fr}from"./chunk-GN2XODVC.js";import{a as yr,b as wr}from"./chunk-PEUTCG3B.js";import{a as hr}from"./chunk-PEJALHXK.js";import{a as Ot}from"./chunk-SC5M74NM.js";import{A as Jr,B as qr,C as Yr,G as Zr,a as Sr,b as Rr,c as vr,d as Er,e as Cr,f as xr,g as Kr,h as $r,i as Ir,j as jr,k as Br,l as Ar,m as Vr,n as Dr,o as Tr,p as Nr,q as Or,r as Ur,s as _r,t as Lr,u as Fr,v as Mr,w as Hr,x as zr,y as Wr,z as Gr}from"./chunk-C7RZIMEH.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as se,c as Gt,d as er,e as tr,f as v}from"./chunk-G2DKKSZ4.js";import{a as S}from"./chunk-TJPQETHV.js";import{a as rr,b as ye,c as gr,d as g,e as kr,f as br,g as Pr}from"./chunk-BGQKZBNE.js";import{f as O,j as E,k as ge,l as he,m as De}from"./chunk-CRKSKIAL.js";import{b as Jt,c as qt,d as R,e as Yt,f as Zt,h as Xt,j as Qt}from"./chunk-IOMNZBK4.js";import{a as Mt,b as ie,c as f,d as k,e as zt,f as Wt,g as ce,h as le,i as ue,j as de,k as pe,l as me}from"./chunk-W6T7MOKY.js";import{a as Ht}from"./chunk-FUUTGGJS.js";import{a as St,b as Rt,c as N,d as vt,e as h,f as Et,g as Ct,h as xt,i as Kt,j as $t}from"./chunk-2ACBWC7K.js";import{a as ur}from"./chunk-ODIECDN7.js";import{VersionOperator as ni}from"@kanonak-protocol/types/document/models/enums";import{existsSync as bn,readFileSync as Pn}from"fs";import{homedir as wn}from"os";import{join as Sn}from"path";import{execFile as tn}from"child_process";import{promisify as rn}from"util";var L=rn(tn),F="kanonak",M="/usr/bin/security",C=class{async get(e){let t=c(e);try{let{stdout:n}=await L(M,["find-generic-password","-s",F,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
2
- Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(n){if(Ue(n,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${H(n)}
1
+ import{a as hn,b as bn,c as Pn,d as wn,e as $e}from"./chunk-FX7JDGL6.js";import{a as pr,c as De,e as Ye,h as Ze,i as Qe,j as dr}from"./chunk-X5TYWQRA.js";import{a as yn,b as gn,c as kn,d as Y,e as Z,f as u}from"./chunk-Y7TGQ7UF.js";import{a as ur}from"./chunk-F5ANO7MJ.js";import"./chunk-QHABFCRC.js";import{a as Ht,b as zt,c as Wt,d as Gt,e as Jt,f as Qt,g as en,h as tn}from"./chunk-ATH6636H.js";import{b as qt,c as Xt,d as Zt}from"./chunk-LKBG2MK6.js";import{a as Ft}from"./chunk-4NO7MHS7.js";import{a as Rn,b as Cn,c as En,d as vn}from"./chunk-GN2XODVC.js";import{a as Kn,b as Dn}from"./chunk-PEUTCG3B.js";import{a as In}from"./chunk-PEJALHXK.js";import{a as Yt}from"./chunk-SC5M74NM.js";import{A as ir,B as sr,C as cr,G as lr,a as An,b as On,c as Tn,d as Vn,e as Un,f as Nn,g as _n,h as Ln,i as Mn,j as Fn,k as Hn,l as zn,m as Wn,n as Gn,o as Jn,p as qn,q as Xn,r as Yn,s as Zn,t as Qn,u as er,v as tr,w as nr,x as rr,y as or,z as ar}from"./chunk-C7RZIMEH.js";import"./chunk-SHDHMKMJ.js";import{a as b,b as Re,c as an,d as mn,e as fn,f as C}from"./chunk-G2DKKSZ4.js";import{a as A}from"./chunk-TJPQETHV.js";import{a as P,b as je,c as xn,d,e as $n,f as jn,g as Bn}from"./chunk-BGQKZBNE.js";import{a as E,f as v,i as T,j as w,k as Be,l as V,m as Xe}from"./chunk-CRKSKIAL.js";import{b as sn,c as cn,d as O,e as ln,f as un,h as pn,j as dn}from"./chunk-IOMNZBK4.js";import{a as nn,b as we,c as m,d as y,e as rn,f as on,g as Ce,h as Ee,i as ve,j as Ke,k as xe,l as Ie}from"./chunk-W6T7MOKY.js";import{a as Se}from"./chunk-FUUTGGJS.js";import{a as Vt,b as be,c as X,d as Pe,e as R,f as Ut,g as Nt,h as _t,i as Lt,j as Mt}from"./chunk-2ACBWC7K.js";import{a as Sn}from"./chunk-ODIECDN7.js";import{VersionOperator as Oi}from"@kanonak-protocol/types/document/models/enums";import{existsSync as $r,readFileSync as jr}from"fs";import{homedir as Br}from"os";import{join as Dr}from"path";import{execFile as mr}from"child_process";import{promisify as fr}from"util";var Q=fr(mr),ee="kanonak",te="/usr/bin/security",U=class{async get(e){let t=u(e);try{let{stdout:r}=await Q(te,["find-generic-password","-s",ee,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
2
+ Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if(et(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${ne(r)}
3
3
  The Keychain may be locked or inaccessible.
4
- Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let n=c(e),o=JSON.stringify(t);try{await L(M,["add-generic-password","-s",F,"-a",n,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${n}': ${H(a)}
4
+ Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let r=u(e),o=JSON.stringify(t);try{await Q(te,["add-generic-password","-s",ee,"-a",r,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${r}': ${ne(a)}
5
5
  Ensure the Keychain is unlocked and the CLI has write permission.
6
- On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=c(e);try{await L(M,["delete-generic-password","-s",F,"-a",t],{timeout:1e4})}catch(n){if(Ue(n,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${H(n)}
7
- The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await L(M,["dump-keychain"],{timeout:1e4}),t=[],n=!1;for(let o of e.split(`
8
- `))if(o.includes(`"svce"<blob>="${F}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&t.push(a[1]),n=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${H(e)}`),[]}}};function Ue(r,e){return typeof r=="object"&&r!==null&&"code"in r&&r.code===e}function H(r){return r instanceof Error?r.message:String(r)}import{execFile as nn}from"child_process";import{promisify as on}from"util";var an=on(nn),z="kanonak:",x=class{async get(e){let t=z+c(e),n=`
9
- ${G}
6
+ On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=u(e);try{await Q(te,["delete-generic-password","-s",ee,"-a",t],{timeout:1e4})}catch(r){if(et(r,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${ne(r)}
7
+ The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await Q(te,["dump-keychain"],{timeout:1e4}),t=[],r=!1;for(let o of e.split(`
8
+ `))if(o.includes(`"svce"<blob>="${ee}"`)&&(r=!0),r&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&t.push(a[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${ne(e)}`),[]}}};function et(n,e){return typeof n=="object"&&n!==null&&"code"in n&&n.code===e}function ne(n){return n instanceof Error?n.message:String(n)}import{execFile as yr}from"child_process";import{promisify as gr}from"util";var kr=gr(yr),re="kanonak:",N=class{async get(e){let t=re+u(e),r=`
9
+ ${ae}
10
10
  $target = [Console]::In.ReadLine()
11
11
  $ptr = [IntPtr]::Zero
12
12
  $result = [CredMan]::CredRead($target, 1, 0, [ref]$ptr)
@@ -18,8 +18,8 @@ try {
18
18
  [System.Text.Encoding]::Unicode.GetString($bytes)
19
19
  } finally {
20
20
  [CredMan]::CredFree($ptr)
21
- }`;try{let{stdout:o}=await W(n,t),a=o.trim();return a?JSON.parse(a):null}catch{return null}}async store(e,t){let n=z+c(e),o=JSON.stringify(t),a=`
22
- ${G}
21
+ }`;try{let{stdout:o}=await oe(r,t),a=o.trim();return a?JSON.parse(a):null}catch{return null}}async store(e,t){let r=re+u(e),o=JSON.stringify(t),a=`
22
+ ${ae}
23
23
  $target = [Console]::In.ReadLine()
24
24
  $json = [Console]::In.ReadLine()
25
25
  $bytes = [System.Text.Encoding]::Unicode.GetBytes($json)
@@ -35,13 +35,13 @@ try {
35
35
  if (-not $result) { throw "CredWrite failed" }
36
36
  } finally {
37
37
  [System.Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
38
- }`;try{await W(a,`${n}
39
- ${o}`)}catch(i){throw new Error(`Windows Credential Manager write failed: ${String(i)}`)}}async remove(e){let t=z+c(e),n=`
40
- ${G}
38
+ }`;try{await oe(a,`${r}
39
+ ${o}`)}catch(i){throw new Error(`Windows Credential Manager write failed: ${String(i)}`)}}async remove(e){let t=re+u(e),r=`
40
+ ${ae}
41
41
  $target = [Console]::In.ReadLine()
42
- [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await W(n,t)}catch{}}async list(){let e=`
43
- ${G}
44
- ${sn}
42
+ [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await oe(r,t)}catch{}}async list(){let e=`
43
+ ${ae}
44
+ ${hr}
45
45
  $prefix = [Console]::In.ReadLine()
46
46
  $count = 0
47
47
  $pCreds = [IntPtr]::Zero
@@ -55,8 +55,8 @@ if ([CredMan]::CredEnumerate($null, 0, [ref]$count, [ref]$pCreds)) {
55
55
  }
56
56
  }
57
57
  [CredMan]::CredFree($pCreds)
58
- }`;try{let{stdout:t}=await W(e,z);return t.trim().split(`
59
- `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function W(r,e){for(let t of["pwsh","powershell"])try{return await an(t,["-NoProfile","-NonInteractive","-Command",r],{timeout:15e3,...e!==void 0&&{input:e}})}catch(n){if(t==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var G=`
58
+ }`;try{let{stdout:t}=await oe(e,re);return t.trim().split(`
59
+ `).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function oe(n,e){for(let t of["pwsh","powershell"])try{return await kr(t,["-NoProfile","-NonInteractive","-Command",n],{timeout:15e3,...e!==void 0&&{input:e}})}catch(r){if(t==="powershell")throw r}throw new Error("Neither pwsh nor powershell found")}var ae=`
60
60
  Add-Type -TypeDefinition @"
61
61
  using System;
62
62
  using System.Runtime.InteropServices;
@@ -87,13 +87,13 @@ public class CredMan {
87
87
  [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
88
88
  public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
89
89
  }
90
- "@`,sn="";import{execFile as cn,spawn as ln}from"child_process";import{promisify as un}from"util";var q=un(cn),J="kanonak",K=class{async get(e){let t=c(e);try{let{stdout:n}=await q("secret-tool",["lookup","service",J,"publisher",t],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let n=c(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=ln("secret-tool",["store","--label",`Kanonak: ${n}`,"service",J,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",l=>{l===0?a():i(new Error(`secret-tool store exited with code ${l}`))}),s.on("error",i)})}async remove(e){let t=c(e);try{await q("secret-tool",["clear","service",J,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await q("secret-tool",["search","service",J],{timeout:1e4}),t=[];for(let n of e.split(`
91
- `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function be(){try{return await q("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as _e,mkdirSync as Le,readFileSync as Fe,writeFileSync as Me}from"fs";import{createCipheriv as dn,createDecipheriv as pn,randomBytes as He}from"crypto";import{homedir as mn}from"os";import{join as Se,dirname as ze}from"path";var Ge=Se(mn(),".config","kanonak"),$=Se(Ge,"keyring.key"),Y=Se(Ge,"credentials.enc"),We="aes-256-gcm",Pe=32,b=12,we=16,I=class{async get(e){let t=this.loadStore(),n=c(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=c(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=c(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!_e(Y))return{};try{let e=this.getOrCreateKey(),t=Fe(Y);if(t.length<b+we)return{};let n=t.subarray(0,b),o=t.subarray(b,b+we),a=t.subarray(b+we),i=pn(We,e,n);i.setAuthTag(o);let s=Buffer.concat([i.update(a),i.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),n=He(b),o=dn(We,t,n),a=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([o.update(a),o.final()]),s=o.getAuthTag(),l=Buffer.concat([n,s,i]);Le(ze(Y),{recursive:!0}),Me(Y,l,{mode:384})}getOrCreateKey(){if(_e($)){let t=Fe($);if(t.length!==Pe)throw new Error(`Credential keyring key is corrupted (expected ${Pe} bytes, got ${t.length}). Delete ${$} and re-authenticate.`);return t}let e=He(Pe);return Le(ze($),{recursive:!0}),Me($,e,{mode:384}),e}};import{execFile as fn}from"child_process";import{promisify as yn}from"util";var gn=yn(fn),Je=3e4,j=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=c(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${Z(n)}
90
+ "@`,hr="";import{execFile as br,spawn as Pr}from"child_process";import{promisify as wr}from"util";var se=wr(br),ie="kanonak",_=class{async get(e){let t=u(e);try{let{stdout:r}=await se("secret-tool",["lookup","service",ie,"publisher",t],{timeout:1e4}),o=r.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let r=u(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=Pr("secret-tool",["store","--label",`Kanonak: ${r}`,"service",ie,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",c=>{c===0?a():i(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",i)})}async remove(e){let t=u(e);try{await se("secret-tool",["clear","service",ie,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await se("secret-tool",["search","service",ie],{timeout:1e4}),t=[];for(let r of e.split(`
91
+ `)){let o=r.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function Ae(){try{return await se("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as tt,mkdirSync as nt,readFileSync as rt,writeFileSync as ot}from"fs";import{createCipheriv as Sr,createDecipheriv as Rr,randomBytes as at}from"crypto";import{homedir as Cr}from"os";import{join as Ve,dirname as it}from"path";var ct=Ve(Cr(),".config","kanonak"),L=Ve(ct,"keyring.key"),ce=Ve(ct,"credentials.enc"),st="aes-256-gcm",Oe=32,I=12,Te=16,M=class{async get(e){let t=this.loadStore(),r=u(e);return t[r]??null}async store(e,t){let r=this.loadStore(),o=u(e);r[o]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=u(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!tt(ce))return{};try{let e=this.getOrCreateKey(),t=rt(ce);if(t.length<I+Te)return{};let r=t.subarray(0,I),o=t.subarray(I,I+Te),a=t.subarray(I+Te),i=Rr(st,e,r);i.setAuthTag(o);let s=Buffer.concat([i.update(a),i.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),r=at(I),o=Sr(st,t,r),a=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([o.update(a),o.final()]),s=o.getAuthTag(),c=Buffer.concat([r,s,i]);nt(it(ce),{recursive:!0}),ot(ce,c,{mode:384})}getOrCreateKey(){if(tt(L)){let t=rt(L);if(t.length!==Oe)throw new Error(`Credential keyring key is corrupted (expected ${Oe} bytes, got ${t.length}). Delete ${L} and re-authenticate.`);return t}let e=at(Oe);return nt(it(L),{recursive:!0}),ot(L,e,{mode:384}),e}};import{execFile as Er}from"child_process";import{promisify as vr}from"util";var Kr=vr(Er),lt=3e4,F=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=u(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(r){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${le(r)}
92
92
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
93
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let n=c(e);try{await this.runHelper("store",{publisher:n,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${n}': ${Z(o)}
94
- Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=c(e);try{await this.runHelper("erase",{publisher:t})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${Z(n)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${Z(e)}`),[]}}async runHelper(e,t){try{let{stdout:n}=await gn(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:Je});return n}catch(n){throw hn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):kn(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${Je/1e3}s on '${e}'.
96
- The helper may be waiting for authentication to an external vault.`):n}}};function Z(r){return r instanceof Error?r.message:String(r)}function hn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function kn(r){return r instanceof Error&&"killed"in r&&r.killed}var Re=Sn(wn(),".kanonak","config.json"),X=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=Rn(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!_(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=vn();return e.credentialHelper?new j(e.credentialHelper):process.platform==="darwin"?new C:process.platform==="win32"?new x:await be()?new K:new I}};function Rn(r){let t="KANONAK_TOKEN_"+c(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function vn(){if(!bn(Re))return{};try{return JSON.parse(Pn(Re,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${Re}: ${e}
97
- Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as En,createPrivateKey as Cn,generateKeyPairSync as xn,randomUUID as Kn,sign as $n}from"crypto";function Ye(){let{publicKey:r,privateKey:e}=xn("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function B(r,e,t,n,o,a){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Kn(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=En("sha256").update(o).digest("base64url")),a&&(s.nonce=a),In(i,s,r)}function Ze(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function In(r,e,t){let n=qe(JSON.stringify(r)),o=qe(JSON.stringify(e)),a=`${n}.${o}`,i=Cn({key:t,format:"jwk"}),l=$n("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${l}`}function qe(r){return Buffer.from(r,"utf-8").toString("base64url")}function Xe(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return fetch(t,{method:o});let a=await r.getCredential(n);if(!a?.accessToken)return fetch(t,{method:o});U(a)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let i={};if(a.dpopKeyPair){let l=e.get(n);try{let u=B(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,l);i.Authorization=`DPoP ${a.accessToken}`,i.DPoP=u}catch(u){let d=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${n}': ${d}
98
- The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),i.Authorization=`Bearer ${a.accessToken}`}}else i.Authorization=`Bearer ${a.accessToken}`;let s=await fetch(t,{method:o,headers:i});if(s.status===401&&a.dpopKeyPair){let l=s.headers.get("DPoP-Nonce");if(l){e.set(n,l);try{let u=B(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,l);i.DPoP=u,s=await fetch(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as jn,writeFileSync as Bn,existsSync as An}from"fs";import{createHash as Vn}from"crypto";import Qe from"js-yaml";var et="kanonak.lock",Dn=`# This file is generated by Kanonak CLI. Do not edit manually.
99
- `;function tt(r=et){if(!An(r))return null;let e=jn(r,"utf-8"),t=Qe.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function rt(r,e=et){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=Qe.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Bn(e,Dn+n,"utf-8")}function nt(r){return`sha256:${Vn("sha256").update(r).digest("hex")}`}import*as Ce from"js-yaml";import{createHash as Tn}from"crypto";function ve(r){let e=[];for(let n of r)n instanceof f&&e.push(Nn(n));return e.sort((n,o)=>n.uri<o.uri?-1:n.uri>o.uri?1:0),JSON.stringify({subjects:e})}function Q(r){let e=ve(r);return`sha256:${Tn("sha256").update(e,"utf8").digest("hex")}`}function Nn(r){let e=Mn(r),t=Ee(r.statement);return{uri:e,statements:t}}function Ee(r){let e=[];for(let t of r){let n=On(t);n&&e.push(n)}return e.sort((t,n)=>t.predicate<n.predicate?-1:t.predicate>n.predicate?1:0),e}function On(r){let e=Fn(r);if(!e)return;let t=Un(r);if(t)return Ln(e,t)}function Un(r){if(r instanceof ce)return{type:"string",value:r.object};if(r instanceof le)return{type:"number",value:st(r.object)};if(r instanceof ue)return{type:"boolean",value:r.object};if(r instanceof de)return{type:"ref",value:at(r.object)};if(r instanceof pe){let e=r.object;return ot(e)}if(r instanceof me)return{type:"list",items:r.object.map(_n)}}function ot(r){let e=Ee(r.statement);return r.name&&r.name.length>0?{type:"embedded",name:r.name,statements:e}:{type:"embedded",statements:e}}function _n(r){if(r instanceof k)return{type:"ref",value:at(r)};if(r instanceof y)return ot(r);if(r instanceof se){let e=r.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:st(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(r instanceof ie)return{type:"embedded",statements:Ee(r.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function Ln(r,e){switch(e.type){case"string":return{predicate:r,type:"string",value:e.value};case"number":return{predicate:r,type:"number",value:e.value};case"boolean":return{predicate:r,type:"boolean",value:e.value};case"ref":return{predicate:r,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:r,type:"embedded",name:e.name,statements:e.statements}:{predicate:r,type:"embedded",statements:e.statements};case"list":return{predicate:r,type:"list",items:e.items}}}function Fn(r){let e=r.predicate;if(e)return it(e.subject)}function Mn(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function at(r){return it(r.subject)}function it(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}function st(r){if(Number.isNaN(r))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(r))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(r,-0)?"0":String(r)}var P=class{constructor(e,t=new S,n){this.repository=e;this.parser=t;this.objectParser=n??new v(this.parser)}repository;parser;objectParser;imports(){return new A}serializeValue(e,t){return ut(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=xe(n),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=n),Object.assign(a,e.header??{});let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:lt(s),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{});let a={[e.name]:n,...e.body},i=this.dump(a),s={yaml:i,byteCount:lt(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ce.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[ct]:{type:"EphemeralPackage",publisher:e,imports:t},...n},a=this.parser.parse(Ce.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),l=(await this.objectParser.parseKanonaks(new De(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==ct);for(let u of l)u.namespace="ephemeral";return Q(l)}},ct="__pkgbuilder_probe__";function lt(r){return new TextEncoder().encode(r).length}function xe(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var A=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o){let a=`${e}/${t}@${n}`,i=this.byKey.get(a);if(i)return i.alias;let s=this.uniqueAlias(o);return this.byKey.set(a,{publisher:e,package_:t,version:n,alias:s}),s}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,h(e.version),e.package_)}.${e.name}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:"^",version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=V(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function ut(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof k)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>ut(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(Hn(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function V(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Hn(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ee=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let a=`${t}/${n}@${h(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,n,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},a=await n.resolveVersion(e,t.packageName,o);return a?this.produceCached(n,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=ye(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Ke={async authorize(){return{allowed:!0}}},$e={async record(){}},D=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},te=class{inner;ctx;policy;meter;constructor(e,t,n=Ke,o=$e){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let a=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new D(e,t.reason)}};var p="kanonak.org",m="view",dt="core-kanonak",zn={publisher:p,package_:m,name:"rootView"},Wn={publisher:p,package_:m,name:"bind"},Gn={publisher:p,package_:m,name:"produces"},Jn={publisher:p,package_:m,name:"projections"},qn={publisher:p,package_:m,name:"where"},Yn={publisher:p,package_:m,name:"value"},Zn={publisher:p,package_:m,name:"as"},re=class{constructor(e,t=new S){this.repository=e;this.parser=t;this.objectParser=new v(this.parser),this.builder=new P(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),a=E(o,Wn);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=E(o,Gn);if(!i)throw new Error(`View ${o.namespace}/${o.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=Xn(o),l=pt(n,p,dt),u=pt(n,p,m),d=this.builder.imports(),ne=d.ensure(p,dt,l,"ck"),ft=d.ensure(p,m,u,"v"),yt=d.ref(i),gt=new Oe(this.repository,this.parser,this.objectParser),Ie=new Te(gt,n),ht=this.readProjections(n,o),kt=to(o,qn),bt=this.findInstances(n,a,await this.reason(t)),je={},Pt=new Set;for(let T of bt){if(!await this.passesWhere(Ie,n,kt,T))continue;let ae={type:yt};for(let Ae of ht){let wt=await this.evaluateValue(Ie,n,Ae.value,T),Ve=this.builder.serializeValue(mt(wt),d);Ve!==void 0&&(ae[d.ref(Ae.as)]=Ve)}let Be=g(T);Be&&(ae[`${ft}.derivedFrom`]=d.ref(Be)),je[this.rowName(T,Pt)]=ae}let oe={};t.resolvedAt&&(oe[`${ne}.resolvedAt`]=t.resolvedAt),t.invocationId&&(oe[`${ne}.id`]=t.invocationId);let w=await this.builder.buildContentAddressed({publisher:s,book:d,body:je,contentHashProperty:`${ne}.contentHash`,header:oe});return{yaml:w.yaml,contentHash:w.contentHash,packageName:w.packageName,publisher:w.publisher,rowCount:w.resourceCount}}resolveView(e,t){let n=O(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=E(n,zn);if(o){let a=O(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return n}readProjections(e,t){let n=[];for(let o of he(t,Jn)){let a=o instanceof y?o:o instanceof k?O(e,o.subject):void 0;if(!a)continue;let i=ge(a,Yn),s=E(a,Zn);i&&s&&n.push({value:i,as:s})}return n}async reason(e){return new fe({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=eo(e),a=[],i=new Set;for(let s of n.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let l=o.get(s);l&&a.push(l)}return a.sort((s,l)=>{let u=R(g(s)),d=R(g(l));return u<d?-1:u>d?1:0}),a}async passesWhere(e,t,n,o){for(let a of n){let i=await this.evaluateValue(e,t,a,o);if(!ro(i))return!1}return!0}async evaluateValue(e,t,n,o){let a=Ne(n,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let n=V(e.name)||"row",o=n,a=2;for(;t.has(o);)o=`${n}-${a++}`;return t.add(o),o}};function mt(r){return ke(r)?r.value:Array.isArray(r)?r.map(mt):r}function Xn(r){let e=g(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function pt(r,e,t){let n=Qn(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function Qn(r,e,t){let n;for(let o of r){if(!(o instanceof f))continue;let a=g(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!n||N(a.version,n)>0)&&(n=a.version)}return n?h(n):void 0}function eo(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof f))continue;let o=g(n);if(!o||!o.version)continue;let a=R(o),i=t.get(a);(!i||N(o.version,i)>0)&&(t.set(a,o.version),e.set(a,n))}return e}function to(r,e){let t=ge(r,e);return t?[t]:he(r,e).filter(n=>n instanceof y)}function ro(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:ke(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{Mr as AmbiguousReferenceRule,ue as BooleanStatement,qr as ClassDefinitionRule,Vr as ClassHierarchyCycleRule,At as CompositeKanonakDocumentRepository,X as CredentialStore,ie as DefinedKanonak,Lr as DefinitionPropertyReferenceRule,Bt as DocumentLocation,or as EdgeType,y as EmbeddedKanonak,jr as EmbeddedKanonakTypeRule,pe as EmbeddedStatement,D as EntitlementDeniedError,te as EntitlementProducer,jt as FileSystemKanonakDocumentRepository,ur as GitIgnoreFilter,ar as GraphBuilder,Ut as HttpKanonakDocumentRepository,A as ImportBook,Br as ImportExistenceRule,It as InMemoryKanonakDocumentRepository,_r as InstancePropertyReferenceRule,Mt as Kanonak,pr as KanonakDocumentPositions,v as KanonakObjectParser,Zr as KanonakObjectValidator,S as KanonakParser,Ht as KanonakUri,yr as KanonakUriBuilder,hr as KanonakUrlResolver,Qt as KanonakVocabulary,me as ListStatement,se as LiteralKanonak,_t as LocalFirstRepository,en as LookRenderer,Yr as MarkdownLinkRule,Gt as MarkdownStatement,Ur as NamespaceImportCycleRule,xr as NamespacePrefixRule,nr as NodeType,le as NumberStatement,cr as OWL_RL_CLASSIFICATION_RULES,zr as ObjectPropertyImportRule,Wr as ObjectPropertyValueValidationRule,vr as OntologyValidationError,Sr as OntologyValidationResult,P as PackageBuilder,ee as ProducerRepository,Gr as PropertyDomainRule,Dr as PropertyHierarchyCycleRule,dr as PropertyMetadata,Hr as PropertyRangeReferenceRule,Tr as PropertyRangeRequiredRule,$r as PropertyTypeSpecificityRule,Jr as PropertyValueTypeRule,Tt as PublisherConfigResolver,Nt as PublisherIndex,sr as RDFS_RULES,fe as Reasoner,lr as ReasoningResult,k as ReferenceKanonak,de as ReferenceStatement,Dt as RepositoryFactory,Kr as ResourceNamingRule,Jt as ResourceResolver,rr as ResourceTypeClassifier,Wt as ScalarStatement,zt as Statement,ce as StringStatement,Nr as SubClassOfReferenceRule,Or as SubPropertyOfReferenceRule,f as SubjectKanonak,Ir as SubjectKanonakTypeRequiredRule,ir as TripleStore,qt as TypeResolver,Ar as UnresolvedReferenceRule,Cr as ValidationCache,Er as ValidationContext,Rr as ValidationSeverity,ni as VersionOperator,re as ViewMaterializer,Fr as XsdImportRule,Ke as allowAllPolicy,Ot as assertPackageIdentity,Ft as buildLocalFirstRepository,ve as canonicalForm,Q as canonicalHash,Lt as collectKanonakFiles,N as compareVersions,nt as computeIntegrity,xe as contentAddressedName,Pr as contextTypesOf,Xe as createAuthenticatedFetch,B as createDPoPProof,Et as createVersion,tr as extractMarkdownLinks,Xr as findDerivation,wr as findInstancesByType,er as findMalformedReferences,fr as findMarkdownLinkAt,gr as formatKanonakAddress,h as formatVersion,Ye as generateDPoPKeyPair,Vt as getGlobalCachePath,_ as hasValidToken,xt as isCompatibleVersion,U as isExpired,Kt as isMajorCompatible,tt as loadLockFile,Yt as makeUriKey,$e as noopMeter,c as normalizeHost,ye as parseKanonakAddress,Ct as parseVersionString,mr as parseWithPositions,$t as pickHighestDocument,kr as propertiesInScope,Qr as resolveDisplayValue,br as resolvePropertyStep,V as sanitizeName,rt as saveLockFile,Ze as serverSupportsDPoP,g as subjectUri,Zt as tripleKey,R as uriKey,Xt as uriTriple,St as versionOperatorFromChar,Rt as versionOperatorToChar,vt as versionsEqual};
93
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let r=u(e);try{await this.runHelper("store",{publisher:r,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${r}': ${le(o)}
94
+ Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=u(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${le(r)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${le(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await Kr(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:lt});return r}catch(r){throw xr(r)?new Error(`Credential helper not found at '${this.helperPath}'.
95
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Ir(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${lt/1e3}s on '${e}'.
96
+ The helper may be waiting for authentication to an external vault.`):r}}};function le(n){return n instanceof Error?n.message:String(n)}function xr(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"}function Ir(n){return n instanceof Error&&"killed"in n&&n.killed}var Ue=Dr(Br(),".kanonak","config.json"),ue=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=Ar(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!Z(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=Or();return e.credentialHelper?new F(e.credentialHelper):process.platform==="darwin"?new U:process.platform==="win32"?new N:await Ae()?new _:new M}};function Ar(n){let t="KANONAK_TOKEN_"+u(n).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Or(){if(!$r(Ue))return{};try{return JSON.parse(jr(Ue,"utf-8"))}catch(n){let e=n instanceof Error?n.message:String(n);return console.warn(` Warning: Failed to parse ${Ue}: ${e}
97
+ Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Tr,createPrivateKey as Vr,generateKeyPairSync as Ur,randomUUID as Nr,sign as _r}from"crypto";function pt(){let{publicKey:n,privateKey:e}=Ur("ec",{namedCurve:"P-256"});return{publicKey:n.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function H(n,e,t,r,o,a){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Nr(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Tr("sha256").update(o).digest("base64url")),a&&(s.nonce=a),Lr(i,s,n)}function dt(n){return!n||n.length===0?!1:n.some(e=>e.toUpperCase()==="ES256")}function Lr(n,e,t){let r=ut(JSON.stringify(n)),o=ut(JSON.stringify(e)),a=`${r}.${o}`,i=Vr({key:t,format:"jwk"}),c=_r("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${c}`}function ut(n){return Buffer.from(n,"utf-8").toString("base64url")}function mt(n){let e=new Map;return async(t,r,o="GET")=>{if(!n)return fetch(t,{method:o});let a=await n.getCredential(r);if(!a?.accessToken)return fetch(t,{method:o});Y(a)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let i={};if(a.dpopKeyPair){let c=e.get(r);try{let l=H(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.Authorization=`DPoP ${a.accessToken}`,i.DPoP=l}catch(l){let p=l instanceof Error?l.message:String(l);console.error(` Error: Failed to create DPoP proof for '${r}': ${p}
98
+ The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${a.accessToken}`}}else i.Authorization=`Bearer ${a.accessToken}`;let s=await fetch(t,{method:o,headers:i});if(s.status===401&&a.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(r,c);try{let l=H(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=l,s=await fetch(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as Mr,writeFileSync as Fr,existsSync as Hr}from"fs";import{createHash as zr}from"crypto";import ft from"js-yaml";var yt="kanonak.lock",Wr=`# This file is generated by Kanonak CLI. Do not edit manually.
99
+ `;function gt(n=yt){if(!Hr(n))return null;let e=Mr(n,"utf-8"),t=ft.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function kt(n,e=yt){n.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(n.packages).sort())t[o]=n.packages[o];n.packages=t;let r=ft.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Fr(e,Wr+r,"utf-8")}function ht(n){return`sha256:${zr("sha256").update(n).digest("hex")}`}import*as Le from"js-yaml";import{createHash as Gr}from"crypto";function Ne(n){let e=[];for(let r of n)r instanceof m&&e.push(Jr(r));return e.sort((r,o)=>r.uri<o.uri?-1:r.uri>o.uri?1:0),JSON.stringify({subjects:e})}function pe(n){let e=Ne(n);return`sha256:${Gr("sha256").update(e,"utf8").digest("hex")}`}function Jr(n){let e=eo(n),t=_e(n.statement);return{uri:e,statements:t}}function _e(n){let e=[];for(let t of n){let r=qr(t);r&&e.push(r)}return e.sort((t,r)=>t.predicate<r.predicate?-1:t.predicate>r.predicate?1:0),e}function qr(n){let e=Qr(n);if(!e)return;let t=Xr(n);if(t)return Zr(e,t)}function Xr(n){if(n instanceof Ce)return{type:"string",value:n.object};if(n instanceof Ee)return{type:"number",value:St(n.object)};if(n instanceof ve)return{type:"boolean",value:n.object};if(n instanceof Ke)return{type:"ref",value:Pt(n.object)};if(n instanceof xe){let e=n.object;return bt(e)}if(n instanceof Ie)return{type:"list",items:n.object.map(Yr)}}function bt(n){let e=_e(n.statement);return n.name&&n.name.length>0?{type:"embedded",name:n.name,statements:e}:{type:"embedded",statements:e}}function Yr(n){if(n instanceof y)return{type:"ref",value:Pt(n)};if(n instanceof b)return bt(n);if(n instanceof Re){let e=n.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:St(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(n instanceof we)return{type:"embedded",statements:_e(n.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${n.constructor?.name??typeof n}); add canonicalization support before hashing data that contains it`)}function Zr(n,e){switch(e.type){case"string":return{predicate:n,type:"string",value:e.value};case"number":return{predicate:n,type:"number",value:e.value};case"boolean":return{predicate:n,type:"boolean",value:e.value};case"ref":return{predicate:n,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:n,type:"embedded",name:e.name,statements:e.statements}:{predicate:n,type:"embedded",statements:e.statements};case"list":return{predicate:n,type:"list",items:e.items}}}function Qr(n){let e=n.predicate;if(e)return wt(e.subject)}function eo(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function Pt(n){return wt(n.subject)}function wt(n){let e=n.version;return e&&typeof e.major=="number"?`${n.publisher}/${n.package_}@${e.major}.${e.minor}.${e.patch}/${n.name}`:`${n.publisher}/${n.package_}/${n.name}`}function St(n){if(Number.isNaN(n))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(n))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(n,-0)?"0":String(n)}import{VersionOperator as Rt}from"@kanonak-protocol/types/document/models/enums";var to="0.0.0",$=class{constructor(e,t=new A,r){this.repository=e;this.parser=t;this.objectParser=r??new C(this.parser)}repository;parser;objectParser;imports(){return new z}serializeValue(e,t){return vt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Me(r),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=r),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:Et(s),contentHash:r,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=o),Object.assign(r,e.header??{}),r.imports=t;let a={[e.name]:r,...e.body},i=this.dump(a),s={yaml:i,byteCount:Et(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Le.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[Ct]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(Le.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Xe(a,this.repository))).filter(l=>l instanceof m&&l.namespace===i&&l.name!==Ct);for(let l of c)l.namespace="ephemeral";return pe(c)}},Ct="__pkgbuilder_probe__";function Et(n){return new TextEncoder().encode(n).length}function Me(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var z=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=Rt.Major){let i=`${e}/${t}@${r}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:a}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,R(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,o){return`${this.ensure(e,t,to,o??t,Rt.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let o=e.get(r.publisher)??[];o.push(r),e.set(r.publisher,o)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:be(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=W(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function vt(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof y)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>vt(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n instanceof b)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(no(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function W(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function no(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var de=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,o){let a=`${t}/${r}@${R(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,r,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let o={operator:t.versionOperator,version:t.version},a=await r.resolveVersion(e,t.packageName,o);return a?this.produceCached(r,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=je(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let o=r.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Fe={async authorize(){return{allowed:!0}}},He={async record(){}},G=class extends Error{constructor(t,r){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},me=class{inner;ctx;policy;meter;constructor(e,t,r=Fe,o=He){this.inner=e,this.ctx=t,this.policy=r,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let o={publisher:e,package_:t,version:r};await this.assertAllowed(o);let a=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new G(e,t.reason)}};var f="kanonak.org",g="view",Kt="core-kanonak",ro={publisher:f,package_:g,name:"rootView"},oo={publisher:f,package_:g,name:"bind"},ao={publisher:f,package_:g,name:"produces"},io={publisher:f,package_:g,name:"projections"},so={publisher:f,package_:g,name:"where"},co={publisher:f,package_:g,name:"value"},lo={publisher:f,package_:g,name:"as"},fe=class{constructor(e,t=new A){this.repository=e;this.parser=t;this.objectParser=new C(this.parser),this.builder=new $(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(r,e),a=w(o,oo);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=w(o,ao);if(!i)throw new Error(`View ${o.namespace}/${o.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=uo(o),c=xt(r,f,Kt),l=xt(r,f,g),p=this.builder.imports(),k=p.ensure(f,Kt,c,"ck"),h=p.ensure(f,g,l,"v"),S=p.ref(i),x=new Qe(this.repository,this.parser,this.objectParser),B=new Ye(x,r),J=this.readProjections(r,o),ge=fo(o,so),At=this.findInstances(r,a,await this.reason(t)),We={},Ot=new Set;for(let q of At){if(!await this.passesWhere(B,r,ge,q))continue;let he={type:S};for(let Je of J){let Tt=await this.evaluateValue(B,r,Je.value,q),qe=this.builder.serializeValue(It(Tt),p);qe!==void 0&&(he[p.ref(Je.as)]=qe)}let Ge=d(q);Ge&&(he[`${h}.derivedFrom`]=p.ref(Ge)),We[this.rowName(q,Ot)]=he}let ke={};t.resolvedAt&&(ke[`${k}.resolvedAt`]=t.resolvedAt),t.invocationId&&(ke[`${k}.id`]=t.invocationId);let D=await this.builder.buildContentAddressed({publisher:s,book:p,body:We,contentHashProperty:`${k}.contentHash`,header:ke});return{yaml:D.yaml,contentHash:D.contentHash,packageName:D.packageName,publisher:D.publisher,rowCount:D.resourceCount}}resolveView(e,t){let r=v(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=w(r,ro);if(o){let a=v(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return r}readProjections(e,t){let r=[];for(let o of V(t,io)){let a=o instanceof b?o:o instanceof y?v(e,o.subject):void 0;if(!a)continue;let i=Be(a,co),s=w(a,lo);i&&s&&r.push({value:i,as:s})}return r}async reason(e){return new $e({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let o=mo(e),a=[],i=new Set;for(let s of r.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let c=o.get(s);c&&a.push(c)}return a.sort((s,c)=>{let l=O(d(s)),p=O(d(c));return l<p?-1:l>p?1:0}),a}async passesWhere(e,t,r,o){for(let a of r){let i=await this.evaluateValue(e,t,a,o);if(!yo(i))return!1}return!0}async evaluateValue(e,t,r,o){let a=Ze(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let r=W(e.name)||"row",o=r,a=2;for(;t.has(o);)o=`${r}-${a++}`;return t.add(o),o}};function It(n){return De(n)?n.value:Array.isArray(n)?n.map(It):n}function uo(n){let e=d(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function xt(n,e,t){let r=po(n,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function po(n,e,t){let r;for(let o of n){if(!(o instanceof m))continue;let a=d(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!r||X(a.version,r)>0)&&(r=a.version)}return r?R(r):void 0}function mo(n){let e=new Map,t=new Map;for(let r of n){if(!(r instanceof m))continue;let o=d(r);if(!o||!o.version)continue;let a=O(o),i=t.get(a);(!i||X(o.version,i)>0)&&(t.set(a,o.version),e.set(a,r))}return e}function fo(n,e){let t=Be(n,e);return t?[t]:V(n,e).filter(r=>r instanceof b)}function yo(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:De(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}var K="kanonak.org",j="core-rdf",go="core-xsd",ko={publisher:K,package_:j,name:"domain"},ho={publisher:K,package_:j,name:"range"},$t={publisher:K,package_:j,name:"subClassOf"},jt={publisher:K,package_:j,name:"label"},Bt={publisher:K,package_:j,name:"comment"},bo=new Se(K,j,"Resource"),ye=n=>n;function ze(n,e){let t=w(n,e);if(t)return[t];let r=[];for(let o of V(n,e))o instanceof y&&r.push(o.subject);return r}function Po(n,e,t){let r=new Set([E(e)]);if(!t)return r;r.add(E(bo));let o=new Set,a=[e];for(;a.length>0;){let i=a.shift(),s=E(i);if(o.has(s))continue;o.add(s),r.add(s);let c=v(n,i);c&&a.push(...ze(c,$t))}return r}function wo(n,e,t){let r=v(n,e);if(r){let o=ye(r);if(P.isClassType(o))return{kind:"class",uri:d(r)??e,localName:r.name};if(P.isDatatypeType(o))return{kind:"datatype",uri:e}}return e.publisher===K&&e.package_===go?{kind:"datatype",uri:e}:t==="datatype"?{kind:"datatype",uri:e}:{kind:"class",uri:e,localName:e.name}}function So(n){let e=ye(n);return P.isObjectPropertyType(e)?"object":P.isDatatypePropertyType(e)?"datatype":"other"}function Ro(n,e,t){let r=Po(n,e,t),o=[],a=new Set;for(let i of n){if(!(i instanceof m))continue;let s=ye(i);if(!P.isAnyPropertyType(s)||!ze(i,ko).some(ge=>r.has(E(ge))))continue;let l=d(i);if(!l)continue;let p=E(l);if(a.has(p))continue;a.add(p);let k=w(i,ho);if(!k)throw new Error(`Property ${l.publisher}/${l.package_}/${l.name} has no rdfs.range; every property must declare a range. Validate the ontology before introspecting it.`);let h=So(i),S=wo(n,k,h),x=h==="object"?"object":h==="datatype"?"datatype":S.kind==="class"?"object":"datatype",B=T(i,jt),J=T(i,Bt);o.push({uri:l,localName:l.name,kind:x,range:S,...B!==void 0?{label:B}:{},...J!==void 0?{comment:J}:{}})}return o}async function Dt(n,e,t){let r=n.metadata?.namespace_;if(!r)throw new Error("buildOntologyModel: document has no namespace (publisher/package/version).");let o=t?.includeInherited??!1,a=await new C().parseKanonaks(e),i=[],s=new Set;for(let c of a){if(!(c instanceof m)||!P.isClassType(ye(c)))continue;let l=d(c);if(!l||l.publisher!==r.publisher||l.package_!==r.package_||l.version&&r.version&&!Pe(l.version,r.version))continue;let p=E(l);if(s.has(p))continue;s.add(p);let k=ze(c,$t).map(x=>({uri:x,localName:x.name})),h=T(c,jt),S=T(c,Bt);i.push({uri:l,localName:l.name,superClasses:k,properties:Ro(a,l,o),...h!==void 0?{label:h}:{},...S!==void 0?{comment:S}:{}})}return{classes:i}}export{tr as AmbiguousReferenceRule,ve as BooleanStatement,sr as ClassDefinitionRule,Wn as ClassHierarchyCycleRule,Wt as CompositeKanonakDocumentRepository,ue as CredentialStore,we as DefinedKanonak,Qn as DefinitionPropertyReferenceRule,zt as DocumentLocation,gn as EdgeType,b as EmbeddedKanonak,Fn as EmbeddedKanonakTypeRule,xe as EmbeddedStatement,G as EntitlementDeniedError,me as EntitlementProducer,Ht as FileSystemKanonakDocumentRepository,Sn as GitIgnoreFilter,kn as GraphBuilder,Zt as HttpKanonakDocumentRepository,z as ImportBook,Hn as ImportExistenceRule,Ft as InMemoryKanonakDocumentRepository,Zn as InstancePropertyReferenceRule,nn as Kanonak,Cn as KanonakDocumentPositions,C as KanonakObjectParser,lr as KanonakObjectValidator,A as KanonakParser,Se as KanonakUri,Kn as KanonakUriBuilder,In as KanonakUrlResolver,dn as KanonakVocabulary,Ie as ListStatement,Re as LiteralKanonak,Qt as LocalFirstRepository,dr as LookRenderer,cr as MarkdownLinkRule,an as MarkdownStatement,Yn as NamespaceImportCycleRule,Nn as NamespacePrefixRule,yn as NodeType,Ee as NumberStatement,Pn as OWL_RL_CLASSIFICATION_RULES,rr as ObjectPropertyImportRule,or as ObjectPropertyValueValidationRule,Tn as OntologyValidationError,An as OntologyValidationResult,$ as PackageBuilder,de as ProducerRepository,ar as PropertyDomainRule,Gn as PropertyHierarchyCycleRule,Rn as PropertyMetadata,nr as PropertyRangeReferenceRule,Jn as PropertyRangeRequiredRule,Ln as PropertyTypeSpecificityRule,ir as PropertyValueTypeRule,qt as PublisherConfigResolver,Xt as PublisherIndex,bn as RDFS_RULES,$e as Reasoner,wn as ReasoningResult,y as ReferenceKanonak,Ke as ReferenceStatement,Jt as RepositoryFactory,_n as ResourceNamingRule,sn as ResourceResolver,P as ResourceTypeClassifier,on as ScalarStatement,rn as Statement,Ce as StringStatement,qn as SubClassOfReferenceRule,Xn as SubPropertyOfReferenceRule,m as SubjectKanonak,Mn as SubjectKanonakTypeRequiredRule,hn as TripleStore,cn as TypeResolver,zn as UnresolvedReferenceRule,Un as ValidationCache,Vn as ValidationContext,On as ValidationSeverity,Oi as VersionOperator,fe as ViewMaterializer,er as XsdImportRule,Fe as allowAllPolicy,Yt as assertPackageIdentity,tn as buildLocalFirstRepository,Dt as buildOntologyModel,Ne as canonicalForm,pe as canonicalHash,en as collectKanonakFiles,X as compareVersions,ht as computeIntegrity,Me as contentAddressedName,Bn as contextTypesOf,mt as createAuthenticatedFetch,H as createDPoPProof,Ut as createVersion,fn as extractMarkdownLinks,ur as findDerivation,Dn as findInstancesByType,mn as findMalformedReferences,vn as findMarkdownLinkAt,xn as formatKanonakAddress,R as formatVersion,pt as generateDPoPKeyPair,Gt as getGlobalCachePath,Z as hasValidToken,_t as isCompatibleVersion,Y as isExpired,Lt as isMajorCompatible,gt as loadLockFile,ln as makeUriKey,He as noopMeter,u as normalizeHost,je as parseKanonakAddress,Nt as parseVersionString,En as parseWithPositions,Mt as pickHighestDocument,$n as propertiesInScope,pr as resolveDisplayValue,jn as resolvePropertyStep,W as sanitizeName,kt as saveLockFile,dt as serverSupportsDPoP,d as subjectUri,un as tripleKey,O as uriKey,pn as uriTriple,Vt as versionOperatorFromChar,be as versionOperatorToChar,Pe as versionsEqual};
@@ -0,0 +1,67 @@
1
+ import { KanonakUri } from '../resolution/KanonakUri.js';
2
+ import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
3
+ import type { KanonakDocument } from '@kanonak-protocol/types/document/models/types';
4
+ /** A reference to a class, by its durable canonical identity. */
5
+ export interface ClassRef {
6
+ uri: KanonakUri;
7
+ localName: string;
8
+ }
9
+ /**
10
+ * A property's range, discriminated into a datatype (an xsd datatype) or a
11
+ * class (a durable reference to the target class across imports).
12
+ */
13
+ export type TypeRef = {
14
+ kind: 'datatype';
15
+ uri: KanonakUri;
16
+ } | {
17
+ kind: 'class';
18
+ uri: KanonakUri;
19
+ localName: string;
20
+ };
21
+ export interface PropertyDef {
22
+ /** The property's durable canonical URI. */
23
+ uri: KanonakUri;
24
+ localName: string;
25
+ label?: string;
26
+ comment?: string;
27
+ /** Datatype vs object, by the property's resolved canonical type. */
28
+ kind: 'datatype' | 'object';
29
+ /** The range, resolved to a durable datatype or class reference. */
30
+ range: TypeRef;
31
+ /** Surfaced only when the ontology expresses it; otherwise unknown. */
32
+ cardinality?: 'single' | 'list';
33
+ /** Surfaced only when the ontology expresses it; otherwise unknown. */
34
+ required?: boolean;
35
+ }
36
+ export interface ClassDef {
37
+ /** The class's durable canonical URI (publisher/package@version/name). */
38
+ uri: KanonakUri;
39
+ localName: string;
40
+ label?: string;
41
+ comment?: string;
42
+ /** Direct `subClassOf` parents, resolved. */
43
+ superClasses: ClassRef[];
44
+ /**
45
+ * Properties scoped to this class. By default only those DECLARED on the
46
+ * class (their `domain` names it); with `includeInherited`, the flattened
47
+ * set inherited from ancestors and `rdfs.Resource` as well.
48
+ */
49
+ properties: PropertyDef[];
50
+ }
51
+ export interface OntologyModel {
52
+ classes: ClassDef[];
53
+ }
54
+ export interface BuildOntologyModelOptions {
55
+ /** Flatten inherited properties (from ancestors + rdfs.Resource) into each class. */
56
+ includeInherited?: boolean;
57
+ }
58
+ /**
59
+ * Build the resolved type-model of an ontology package.
60
+ *
61
+ * Enumerates the classes the package declares (matched by the document's own
62
+ * publisher/package/version, not by name shape), resolves each one's direct
63
+ * `subClassOf` parents and its property set, and resolves every property's
64
+ * range to a durable datatype or class reference. Built entirely on the parsed
65
+ * object model — no `rdf:type` string matching, no alias assumptions.
66
+ */
67
+ export declare function buildOntologyModel(doc: KanonakDocument, repo: IKanonakDocumentRepository, opts?: BuildOntologyModelOptions): Promise<OntologyModel>;
@@ -0,0 +1,2 @@
1
+ export { buildOntologyModel } from './OntologyModel.js';
2
+ export type { OntologyModel, ClassDef, PropertyDef, ClassRef, TypeRef, BuildOntologyModelOptions, } from './OntologyModel.js';
@@ -1,6 +1,7 @@
1
1
  import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
2
2
  import { KanonakParser } from '../parsing/KanonakParser.js';
3
3
  import { KanonakObjectParser } from '../parsing/KanonakObjectParser.js';
4
+ import { VersionOperator } from '@kanonak-protocol/types/document/models/enums';
4
5
  import type { KanonakUri } from '../resolution/KanonakUri.js';
5
6
  /**
6
7
  * The producer-side toolkit for constructing a valid, canonical Kanonak
@@ -112,18 +113,42 @@ export interface ImportEntry {
112
113
  package_: string;
113
114
  version: string;
114
115
  alias: string;
116
+ /** The version-match operator this import is emitted with. */
117
+ match: VersionOperator;
115
118
  }
116
119
  /**
117
120
  * Allocates import aliases and emits the package's `imports` block. Aliases
118
121
  * are unique within the package; the same `publisher/package@version` reuses
119
122
  * its alias. Holding this while building the body lets value serialization
120
123
  * mint `alias.name` references that the emitted `imports` exactly covers.
124
+ *
125
+ * Each import carries a version-match operator (default `^`). A producer that
126
+ * references another producer's snapshot-versioned entity uses {@link refLatest}
127
+ * (or `ensure` with {@link VersionOperator.Any}) to emit a `*` (latest) import:
128
+ * the reference is to the ENTITY, and which snapshot it resolves to is a
129
+ * consumer-time (lockfile) concern — pinning the other package's mutable
130
+ * version would make this package's own bytes non-deterministic. (See #50.)
121
131
  */
122
132
  export declare class ImportBook {
123
133
  private readonly byKey;
124
134
  private readonly aliases;
125
- ensure(publisher: string, package_: string, version: string, preferred: string): string;
135
+ /**
136
+ * Ensure an import for `publisher/package@version` (deduped per key) and
137
+ * return its alias. `match` selects the operator emitted for it — default
138
+ * `^` (Major), backward-compatible; pass {@link VersionOperator.Any} for a
139
+ * `*` (latest) cross-producer reference.
140
+ */
141
+ ensure(publisher: string, package_: string, version: string, preferred: string, match?: VersionOperator): string;
126
142
  ref(uri: KanonakUri): string;
143
+ /**
144
+ * Reference an entity in another package AT LATEST — ensures a `*` import
145
+ * and returns `alias.name`. The version is irrelevant under `*`, so a fixed
146
+ * placeholder is recorded; the consumer's lockfile pins the concrete
147
+ * snapshot at resolution time. This is the version-agnostic cross-producer
148
+ * reference: it keeps THIS package's output a pure function of its own
149
+ * address even as the referenced package's version moves (#50).
150
+ */
151
+ refLatest(publisher: string, package_: string, name: string, preferredAlias?: string): string;
127
152
  toImports(): unknown[];
128
153
  private uniqueAlias;
129
154
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "3.73.0",
3
+ "version": "3.75.0",
4
4
  "description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -122,7 +122,7 @@
122
122
  "yaml-parser"
123
123
  ],
124
124
  "dependencies": {
125
- "@kanonak-protocol/types": "^3.73.0",
125
+ "@kanonak-protocol/types": "^3.75.0",
126
126
  "ignore": "^7.0.5",
127
127
  "js-yaml": "^4.1.0",
128
128
  "yaml": "^2.7.0"