@kanonak-protocol/sdk 4.2.0 → 4.3.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.
@@ -1,4 +1,5 @@
1
1
  import { type Kanonak } from '../kanonaks/index.js';
2
+ import { type CanonicalInput } from './InputModel.js';
2
3
  /**
3
4
  * The frozen canonical-form version. Content addresses are permanent, so the
4
5
  * rules in this module are pinned to this version and evolve only by minting a
@@ -20,9 +21,17 @@ export declare const CANONICAL_FORM_VERSION = "1";
20
21
  * always produce byte-identical output.
21
22
  */
22
23
  export declare function canonicalForm(kanonaks: Kanonak[]): string;
24
+ /**
25
+ * Canonicalize the language-neutral {@link CanonicalInput} model directly
26
+ * (issue #56) — the entry codecs and the cross-language ports share. Byte-
27
+ * identical to the `Kanonak[]` path for equivalent content.
28
+ */
29
+ export declare function canonicalForm(input: CanonicalInput): string;
23
30
  /**
24
31
  * SHA-256 of the canonical form, prefixed `sha256:`. The output is
25
32
  * 71 characters (`sha256:` + 64 hex digits) and matches the
26
33
  * convention used by `kanonak.lock` integrity entries.
27
34
  */
28
35
  export declare function canonicalHash(kanonaks: Kanonak[]): string;
36
+ /** SHA-256 of the canonical form of a {@link CanonicalInput} model (issue #56). */
37
+ export declare function canonicalHash(input: CanonicalInput): string;
@@ -0,0 +1,54 @@
1
+ import type { Kanonak } from '../kanonaks/Kanonak.js';
2
+ /**
3
+ * The language-neutral canonical INPUT model (issue #56) — the one
4
+ * cross-language contract a codec builds to content-address a typed object,
5
+ * carrying datatypes explicitly so canonicalization needs no parser. It is
6
+ * exactly the shape `full-form-vectors.json` is defined over and `kanonak hash
7
+ * -v` emits. The public `canonicalForm`/`canonicalHash` accept it directly (an
8
+ * overload of the `Kanonak[]` form), so all six `kanonak-canonical`
9
+ * implementations share one entry.
10
+ */
11
+ export interface CanonicalInput {
12
+ subjects: CanonicalInputSubject[];
13
+ }
14
+ export interface CanonicalInputSubject {
15
+ /** The subject's canonical URI, e.g. `publisher/package@1.0.0/Name`. */
16
+ uri: string;
17
+ statements: CanonicalInputStatement[];
18
+ }
19
+ export interface CanonicalInputStatement {
20
+ /** The predicate's canonical URI. */
21
+ predicate: string;
22
+ value: CanonicalInputValue;
23
+ }
24
+ /**
25
+ * A value: a typed scalar (`lit` + its `datatype` URI), an untyped/open-world
26
+ * scalar (`raw` token, no carrier), a reference, an embedded node, or a list.
27
+ */
28
+ export type CanonicalInputValue = {
29
+ lit: string;
30
+ datatype: string;
31
+ } | {
32
+ raw: string;
33
+ } | {
34
+ ref: string;
35
+ } | {
36
+ embed: {
37
+ name?: string;
38
+ statements: CanonicalInputStatement[];
39
+ };
40
+ } | {
41
+ list: CanonicalInputValue[];
42
+ };
43
+ /** Discriminate a `CanonicalInput` from a `Kanonak[]` (for the public overload). */
44
+ export declare function isCanonicalInput(arg: unknown): arg is CanonicalInput;
45
+ /**
46
+ * Build the SDK object model the canonical form consumes from a `CanonicalInput`.
47
+ * Datatypes are classified by their URI via {@link carrierOf} (the same routing
48
+ * the parser uses); predicate/reference URIs resolve through the canonical URI
49
+ * parser; a typed scalar carries `(carrier, lexical)`, an untyped one its raw
50
+ * token. The canonical form reads `(carrier, lexical)` off any scalar statement,
51
+ * so a single `StringStatement` faithfully represents every scalar carrier —
52
+ * producing bytes identical to the parsed-model path for equivalent content.
53
+ */
54
+ export declare function buildModelFromInput(input: CanonicalInput): Kanonak[];
@@ -1,2 +1,3 @@
1
1
  export { canonicalForm, canonicalHash, CANONICAL_FORM_VERSION } from './CanonicalHash.js';
2
2
  export { Carrier, carrierOf } from './Datatypes.js';
3
+ export type { CanonicalInput, CanonicalInputSubject, CanonicalInputStatement, CanonicalInputValue, } from './InputModel.js';
package/dist/index.d.ts CHANGED
@@ -34,5 +34,6 @@ 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, CANONICAL_FORM_VERSION, Carrier, carrierOf, } from './canonical/index.js';
37
+ export type { CanonicalInput, CanonicalInputSubject, CanonicalInputStatement, CanonicalInputValue, } from './canonical/index.js';
37
38
  export { buildOntologyModel } from './introspection/index.js';
38
39
  export type { OntologyModel, ClassDef, PropertyDef, ClassRef, TypeRef, EnumDef, EnumMember, BuildOntologyModelOptions, } from './introspection/index.js';
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import{a as mr,b as fr,c as yr,d as gr,e as he}from"./chunk-O27W3OKK.js";import{a as cn,c as we,e as Le,h as Fe,i as Me,j as ln}from"./chunk-JE4ZJ3OB.js";import{a as ur,b as dr,c as pr,d as U,e as _,f as l,g as un}from"./chunk-MJZSHLWI.js";import{a as sn}from"./chunk-HJQGBT7M.js";import"./chunk-QHABFCRC.js";import{a as Ut,b as _t,c as Lt,d as Ft,e as Mt,f as Jt,g as qt,h as Yt}from"./chunk-YWUKDEZA.js";import{b as Ht,c as zt,d as Gt}from"./chunk-YCV4H6H5.js";import{a as Tt}from"./chunk-4NO7MHS7.js";import{a as kr,b as br,c as Pr,d as wr}from"./chunk-JSHJ4ZDB.js";import{a as Sr,b as Ir}from"./chunk-PEUTCG3B.js";import{a as Cr}from"./chunk-PEJALHXK.js";import{a as Wt}from"./chunk-SC5M74NM.js";import{A as rn,B as nn,C as on,L as an,a as $r,b as jr,c as Br,d as Ar,e as Vr,f as Or,g as Dr,h as Nr,i as Tr,j as Ur,k as _r,l as Lr,m as Fr,n as Mr,o as Hr,p as zr,q as Wr,r as Gr,s as Jr,t as qr,u as Yr,v as Zr,w as Xr,x as Qr,y as en,z as tn}from"./chunk-5DXJ5B5T.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as ce,c as er,d as Te,e as Ue,f as ge,g as sr,h as cr,i as C}from"./chunk-CEFXZIHB.js";import{a as S}from"./chunk-ZYAABYDS.js";import{a as lr,b as ke,c as Rr,d as g,e as Er,f as vr,g as xr,h as Kr}from"./chunk-NC3FSY3R.js";import{f as T,k as E,l as be,m as Pe,n as _e}from"./chunk-PBNVHBS3.js";import{b as tr,c as rr,d as R,e as nr,f as or,h as ar,j as ir}from"./chunk-XYEY6HUC.js";import{a as Zt,b as se,c as f,d as k,e as Qt,f as le,g as ue,h as de,i as pe,j as me,k as fe,l as ye}from"./chunk-T3JR2SV6.js";import{a as Xt}from"./chunk-FUUTGGJS.js";import{a as jt,b as ie,c as N,d as Bt,e as h,f as At,g as Vt,h as Ot,i as Dt,j as Nt}from"./chunk-2ACBWC7K.js";import{a as hr}from"./chunk-ODIECDN7.js";import{VersionOperator as hi}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Kn,readFileSync as In}from"fs";import{homedir as $n}from"os";import{join as jn}from"path";import{execFile as dn}from"child_process";import{promisify as pn}from"util";var L=pn(dn),F="kanonak",M="/usr/bin/security",v=class{async get(e){let t=l(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(He(n,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${H(n)}
1
+ import{a as bn,b as Pn,c as wn,d as Sn,e as be}from"./chunk-O27W3OKK.js";import{a as mr,c as Ce,e as He,h as ze,i as We,j as fr}from"./chunk-JE4ZJ3OB.js";import{a as gn,b as hn,c as kn,d as W,e as G,f as l,g as yr}from"./chunk-MJZSHLWI.js";import{a as dr}from"./chunk-HJQGBT7M.js";import"./chunk-QHABFCRC.js";import{a as zt,b as Wt,c as Gt,d as Jt,e as qt,f as en,g as tn,h as nn}from"./chunk-YWUKDEZA.js";import{b as Yt,c as Zt,d as Qt}from"./chunk-YCV4H6H5.js";import{a as Ht}from"./chunk-4NO7MHS7.js";import{a as Rn,b as En,c as xn,d as In}from"./chunk-JSHJ4ZDB.js";import{a as vn,b as On}from"./chunk-PEUTCG3B.js";import{a as $n}from"./chunk-PEJALHXK.js";import{a as Xt}from"./chunk-SC5M74NM.js";import{A as cr,B as lr,C as ur,L as pr,a as Dn,b as Nn,c as Tn,d as _n,e as Ln,f as Un,g as Fn,h as Mn,i as Hn,j as zn,k as Wn,l as Gn,m as Jn,n as qn,o as Yn,p as Zn,q as Xn,r as Qn,s as er,t as tr,u as nr,v as rr,w as or,x as ar,y as ir,z as sr}from"./chunk-5DXJ5B5T.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as C,c as an,d as Fe,e as v,f as ke,g as mn,h as fn,i as $}from"./chunk-CEFXZIHB.js";import{a as S}from"./chunk-ZYAABYDS.js";import{a as yn,b as Pe,c as Kn,d as h,e as jn,f as Vn,g as An,h as Bn}from"./chunk-NC3FSY3R.js";import{f as z,k as j,l as we,m as Se,n as Me}from"./chunk-PBNVHBS3.js";import{b as sn,c as cn,d as K,e as ln,f as un,h as pn,j as dn}from"./chunk-XYEY6HUC.js";import{a as rn,b as fe,c as f,d as p,e as on,f as ye,g as R,h as ge,i as he,j as E,k as x,l as I}from"./chunk-T3JR2SV6.js";import{a as H}from"./chunk-FUUTGGJS.js";import{a as Nt,b as me,c as M,d as Tt,e as k,f as _t,g as Lt,h as Ut,i as Ft,j as Mt}from"./chunk-2ACBWC7K.js";import{a as Cn}from"./chunk-ODIECDN7.js";import{VersionOperator as Oi}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Ar,readFileSync as Br}from"fs";import{homedir as Or}from"os";import{join as Dr}from"path";import{execFile as gr}from"child_process";import{promisify as hr}from"util";var J=hr(gr),q="kanonak",Y="/usr/bin/security",V=class{async get(e){let t=l(e);try{let{stdout:r}=await J(Y,["find-generic-password","-s",q,"-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(Ge(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${Z(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=l(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=l(e),o=JSON.stringify(t);try{await J(Y,["add-generic-password","-s",q,"-a",r,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${r}': ${Z(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=l(e);try{await L(M,["delete-generic-password","-s",F,"-a",t],{timeout:1e4})}catch(n){if(He(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 He(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 mn}from"child_process";import{promisify as fn}from"util";var yn=fn(mn),z="kanonak:",x=class{async get(e){let t=z+l(e),n=`
9
- ${G}
6
+ On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await J(Y,["delete-generic-password","-s",q,"-a",t],{timeout:1e4})}catch(r){if(Ge(r,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${Z(r)}
7
+ The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await J(Y,["dump-keychain"],{timeout:1e4}),t=[],r=!1;for(let o of e.split(`
8
+ `))if(o.includes(`"svce"<blob>="${q}"`)&&(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: ${Z(e)}`),[]}}};function Ge(n,e){return typeof n=="object"&&n!==null&&"code"in n&&n.code===e}function Z(n){return n instanceof Error?n.message:String(n)}import{execFile as kr}from"child_process";import{promisify as br}from"util";var Pr=br(kr),X="kanonak:",A=class{async get(e){let t=X+l(e),r=`
9
+ ${ee}
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+l(e),o=JSON.stringify(t),a=`
22
- ${G}
21
+ }`;try{let{stdout:o}=await Q(r,t),a=o.trim();return a?JSON.parse(a):null}catch{return null}}async store(e,t){let r=X+l(e),o=JSON.stringify(t),a=`
22
+ ${ee}
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+l(e),n=`
40
- ${G}
38
+ }`;try{await Q(a,`${r}
39
+ ${o}`)}catch(i){throw new Error(`Windows Credential Manager write failed: ${String(i)}`)}}async remove(e){let t=X+l(e),r=`
40
+ ${ee}
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
- ${gn}
42
+ [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await Q(r,t)}catch{}}async list(){let e=`
43
+ ${ee}
44
+ ${wr}
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 yn(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 Q(e,X);return t.trim().split(`
59
+ `).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function Q(n,e){for(let t of["pwsh","powershell"])try{return await Pr(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 ee=`
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
- "@`,gn="";import{execFile as hn,spawn as kn}from"child_process";import{promisify as bn}from"util";var q=bn(hn),J="kanonak",K=class{async get(e){let t=l(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=l(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=kn("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",c=>{c===0?a():i(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",i)})}async remove(e){let t=l(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 Se(){try{return await q("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as ze,mkdirSync as We,readFileSync as Ge,writeFileSync as Je}from"fs";import{createCipheriv as Pn,createDecipheriv as wn,randomBytes as qe}from"crypto";import{homedir as Sn}from"os";import{join as Ee,dirname as Ye}from"path";var Xe=Ee(Sn(),".config","kanonak"),I=Ee(Xe,"keyring.key"),Y=Ee(Xe,"credentials.enc"),Ze="aes-256-gcm",Re=32,b=12,Ce=16,$=class{async get(e){let t=this.loadStore(),n=l(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=l(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=l(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!ze(Y))return{};try{let e=this.getOrCreateKey(),t=Ge(Y);if(t.length<b+Ce)return{};let n=t.subarray(0,b),o=t.subarray(b,b+Ce),a=t.subarray(b+Ce),i=wn(Ze,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=qe(b),o=Pn(Ze,t,n),a=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([o.update(a),o.final()]),s=o.getAuthTag(),c=Buffer.concat([n,s,i]);We(Ye(Y),{recursive:!0}),Je(Y,c,{mode:384})}getOrCreateKey(){if(ze(I)){let t=Ge(I);if(t.length!==Re)throw new Error(`Credential keyring key is corrupted (expected ${Re} bytes, got ${t.length}). Delete ${I} and re-authenticate.`);return t}let e=qe(Re);return We(Ye(I),{recursive:!0}),Je(I,e,{mode:384}),e}};import{execFile as Rn}from"child_process";import{promisify as Cn}from"util";var En=Cn(Rn),Qe=3e4,j=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(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
+ "@`,wr="";import{execFile as Sr,spawn as Cr}from"child_process";import{promisify as Rr}from"util";var ne=Rr(Sr),te="kanonak",B=class{async get(e){let t=l(e);try{let{stdout:r}=await ne("secret-tool",["lookup","service",te,"publisher",t],{timeout:1e4}),o=r.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let r=l(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=Cr("secret-tool",["store","--label",`Kanonak: ${r}`,"service",te,"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=l(e);try{await ne("secret-tool",["clear","service",te,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await ne("secret-tool",["search","service",te],{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 Re(){try{return await ne("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Je,mkdirSync as qe,readFileSync as Ye,writeFileSync as Ze}from"fs";import{createCipheriv as Er,createDecipheriv as xr,randomBytes as Xe}from"crypto";import{homedir as Ir}from"os";import{join as Ie,dirname as Qe}from"path";var tt=Ie(Ir(),".config","kanonak"),O=Ie(tt,"keyring.key"),re=Ie(tt,"credentials.enc"),et="aes-256-gcm",Ee=32,b=12,xe=16,D=class{async get(e){let t=this.loadStore(),r=l(e);return t[r]??null}async store(e,t){let r=this.loadStore(),o=l(e);r[o]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=l(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Je(re))return{};try{let e=this.getOrCreateKey(),t=Ye(re);if(t.length<b+xe)return{};let r=t.subarray(0,b),o=t.subarray(b,b+xe),a=t.subarray(b+xe),i=xr(et,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=Xe(b),o=Er(et,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]);qe(Qe(re),{recursive:!0}),Ze(re,c,{mode:384})}getOrCreateKey(){if(Je(O)){let t=Ye(O);if(t.length!==Ee)throw new Error(`Credential keyring key is corrupted (expected ${Ee} bytes, got ${t.length}). Delete ${O} and re-authenticate.`);return t}let e=Xe(Ee);return qe(Qe(O),{recursive:!0}),Ze(O,e,{mode:384}),e}};import{execFile as vr}from"child_process";import{promisify as Kr}from"util";var $r=Kr(vr),nt=3e4,N=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(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}': ${oe(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=l(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=l(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 En(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:Qe});return n}catch(n){throw vn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):xn(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${Qe/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 vn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function xn(r){return r instanceof Error&&"killed"in r&&r.killed}var ve=jn($n(),".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=Bn(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=An();return e.credentialHelper?new j(e.credentialHelper):process.platform==="darwin"?new v:process.platform==="win32"?new x:await Se()?new K:new $}};function Bn(r){let t="KANONAK_TOKEN_"+l(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function An(){if(!Kn(ve))return{};try{return JSON.parse(In(ve,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${ve}: ${e}
97
- Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Vn,createPrivateKey as On,generateKeyPairSync as Dn,randomUUID as Nn,sign as Tn}from"crypto";function tt(){let{publicKey:r,privateKey:e}=Dn("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:Nn(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Vn("sha256").update(o).digest("base64url")),a&&(s.nonce=a),Un(i,s,r)}function rt(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function Un(r,e,t){let n=et(JSON.stringify(r)),o=et(JSON.stringify(e)),a=`${n}.${o}`,i=On({key:t,format:"jwk"}),c=Tn("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${c}`}function et(r){return Buffer.from(r,"utf-8").toString("base64url")}function nt(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 c=e.get(n);try{let u=B(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);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 c=s.headers.get("DPoP-Nonce");if(c){e.set(n,c);try{let u=B(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=u,s=await fetch(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as _n,writeFileSync as Ln,existsSync as Fn}from"fs";import{createHash as Mn}from"crypto";import ot from"js-yaml";var at="kanonak.lock",Hn=`# This file is generated by Kanonak CLI. Do not edit manually.
99
- `;function it(r=at){if(!Fn(r))return null;let e=_n(r,"utf-8"),t=ot.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function st(r,e=at){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=ot.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Ln(e,Hn+n,"utf-8")}function ct(r){return`sha256:${Mn("sha256").update(r).digest("hex")}`}import*as Ie from"js-yaml";import{createHash as zn}from"crypto";var ut="1",lt=new TextEncoder;function dt(r,e){let t=lt.encode(r),n=lt.encode(e),o=Math.min(t.length,n.length);for(let a=0;a<o;a++)if(t[a]!==n[a])return t[a]-n[a];return t.length-n.length}function xe(r){let e=[];for(let n of r)n instanceof f&&e.push(Wn(n));return e.sort((n,o)=>dt(n.uri,o.uri)),JSON.stringify({subjects:e})}function Q(r){let e=xe(r);return`sha256:${zn("sha256").update(e,"utf8").digest("hex")}`}function Wn(r){let e=Xn(r),t=Ke(r.statement);return{uri:e,statements:t}}function Ke(r){let e=[];for(let t of r){let n=Gn(t);n&&e.push(n)}return e.sort((t,n)=>dt(t.predicate,n.predicate)),e}function Gn(r){let e=Zn(r);if(!e)return;let t=Jn(r);if(t)return Yn(e,t)}function Jn(r){if(r instanceof le&&r.carrier)return{type:"typed",carrier:r.carrier,value:ge(r.carrier,r.lexical??String(r.object))};if(r instanceof ue)return{type:"string",value:r.object};if(r instanceof de)return{type:"number",value:yt(r.object)};if(r instanceof pe)return{type:"boolean",value:r.object};if(r instanceof me)return{type:"ref",value:mt(r.object)};if(r instanceof fe){let e=r.object;return pt(e)}if(r instanceof ye)return{type:"list",items:r.object.map(qn)}}function pt(r){let e=Ke(r.statement);return r.name&&r.name.length>0?{type:"embedded",name:r.name,statements:e}:{type:"embedded",statements:e}}function qn(r){if(r instanceof k)return{type:"ref",value:mt(r)};if(r instanceof y)return pt(r);if(r instanceof ce){if(r.carrier)return{type:"typed",carrier:r.carrier,value:ge(r.carrier,r.lexical??String(r.value))};let e=r.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:yt(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(r instanceof se)return{type:"embedded",statements:Ke(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 Yn(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"typed":return{predicate:r,type:"typed",carrier:e.carrier,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 Zn(r){let e=r.predicate;if(e)return ft(e.subject)}function Xn(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function mt(r){return ft(r.subject)}function ft(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 yt(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)}import{VersionOperator as gt}from"@kanonak-protocol/types/document/models/enums";var Qn="0.0.0",P=class{constructor(e,t=new S,n){this.repository=e;this.parser=t;this.objectParser=n??new C(this.parser)}repository;parser;objectParser;imports(){return new A}serializeValue(e,t){return bt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=$e(n),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=n),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:kt(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??{}),n.imports=t;let a={[e.name]:n,...e.body},i=this.dump(a),s={yaml:i,byteCount:kt(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ie.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[ht]:{type:"EphemeralPackage",publisher:e,imports:t},...n},a=this.parser.parse(Ie.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new _e(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==ht);for(let u of c)u.namespace="ephemeral";return Q(c)}},ht="__pkgbuilder_probe__";function kt(r){return new TextEncoder().encode(r).length}function $e(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,a=gt.Major){let i=`${e}/${t}@${n}`,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:n,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_,h(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,Qn,o??t,gt.Any)}.${n}`}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:ie(o.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 bt(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=>bt(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(eo(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 eo(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=ke(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 je={async authorize(){return{allowed:!0}}},Be={async record(){}},O=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=je,o=Be){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 O(e,t.reason)}};var p="kanonak.org",m="view",Pt="core-kanonak",to={publisher:p,package_:m,name:"rootView"},ro={publisher:p,package_:m,name:"bind"},no={publisher:p,package_:m,name:"produces"},oo={publisher:p,package_:m,name:"projections"},ao={publisher:p,package_:m,name:"where"},io={publisher:p,package_:m,name:"value"},so={publisher:p,package_:m,name:"as"},re=class{constructor(e,t=new S){this.repository=e;this.parser=t;this.objectParser=new C(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,ro);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=E(o,no);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=co(o),c=wt(n,p,Pt),u=wt(n,p,m),d=this.builder.imports(),ne=d.ensure(p,Pt,c,"ck"),Rt=d.ensure(p,m,u,"v"),Ct=d.ref(i),Et=new Me(this.repository,this.parser,this.objectParser),Ae=new Le(Et,n),vt=this.readProjections(n,o),xt=po(o,ao),Kt=this.findInstances(n,a,await this.reason(t)),Ve={},It=new Set;for(let D of Kt){if(!await this.passesWhere(Ae,n,xt,D))continue;let ae={type:Ct};for(let De of vt){let $t=await this.evaluateValue(Ae,n,De.value,D),Ne=this.builder.serializeValue(St($t),d);Ne!==void 0&&(ae[d.ref(De.as)]=Ne)}let Oe=g(D);Oe&&(ae[`${Rt}.derivedFrom`]=d.ref(Oe)),Ve[this.rowName(D,It)]=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:Ve,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=T(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=E(n,to);if(o){let a=T(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 Pe(t,oo)){let a=o instanceof y?o:o instanceof k?T(e,o.subject):void 0;if(!a)continue;let i=be(a,io),s=E(a,so);i&&s&&n.push({value:i,as:s})}return n}async reason(e){return new he({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=uo(e),a=[],i=new Set;for(let s of n.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 u=R(g(s)),d=R(g(c));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(!mo(i))return!1}return!0}async evaluateValue(e,t,n,o){let a=Fe(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 St(r){return we(r)?r.value:Array.isArray(r)?r.map(St):r}function co(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 wt(r,e,t){let n=lo(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 lo(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 uo(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 po(r,e){let t=be(r,e);return t?[t]:Pe(r,e).filter(n=>n instanceof y)}function mo(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:we(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{Zr as AmbiguousReferenceRule,pe as BooleanStatement,ut as CANONICAL_FORM_VERSION,Te as Carrier,nn as ClassDefinitionRule,Fr as ClassHierarchyCycleRule,Lt as CompositeKanonakDocumentRepository,X as CredentialStore,se as DefinedKanonak,qr as DefinitionPropertyReferenceRule,_t as DocumentLocation,dr as EdgeType,y as EmbeddedKanonak,Ur as EmbeddedKanonakTypeRule,fe as EmbeddedStatement,O as EntitlementDeniedError,te as EntitlementProducer,Ut as FileSystemKanonakDocumentRepository,hr as GitIgnoreFilter,pr as GraphBuilder,Gt as HttpKanonakDocumentRepository,A as ImportBook,_r as ImportExistenceRule,Tt as InMemoryKanonakDocumentRepository,Jr as InstancePropertyReferenceRule,Zt as Kanonak,br as KanonakDocumentPositions,C as KanonakObjectParser,an as KanonakObjectValidator,S as KanonakParser,Xt as KanonakUri,Sr as KanonakUriBuilder,Cr as KanonakUrlResolver,ir as KanonakVocabulary,ye as ListStatement,ce as LiteralKanonak,Jt as LocalFirstRepository,ln as LookRenderer,on as MarkdownLinkRule,er as MarkdownStatement,Gr as NamespaceImportCycleRule,Or as NamespacePrefixRule,ur as NodeType,de as NumberStatement,yr as OWL_RL_CLASSIFICATION_RULES,Qr as ObjectPropertyImportRule,en as ObjectPropertyValueValidationRule,Br as OntologyValidationError,$r as OntologyValidationResult,P as PackageBuilder,ee as ProducerRepository,tn as PropertyDomainRule,Mr as PropertyHierarchyCycleRule,kr as PropertyMetadata,Xr as PropertyRangeReferenceRule,Hr as PropertyRangeRequiredRule,Nr as PropertyTypeSpecificityRule,rn as PropertyValueTypeRule,Ht as PublisherConfigResolver,zt as PublisherIndex,fr as RDFS_RULES,he as Reasoner,gr as ReasoningResult,k as ReferenceKanonak,me as ReferenceStatement,Mt as RepositoryFactory,Dr as ResourceNamingRule,tr as ResourceResolver,lr as ResourceTypeClassifier,le as ScalarStatement,Qt as Statement,ue as StringStatement,zr as SubClassOfReferenceRule,Wr as SubPropertyOfReferenceRule,f as SubjectKanonak,Tr as SubjectKanonakTypeRequiredRule,mr as TripleStore,rr as TypeResolver,Lr as UnresolvedReferenceRule,Vr as ValidationCache,Ar as ValidationContext,jr as ValidationSeverity,hi as VersionOperator,re as ViewMaterializer,Yr as XsdImportRule,je as allowAllPolicy,Wt as assertPackageIdentity,Yt as buildLocalFirstRepository,un as buildOntologyModel,xe as canonicalForm,Q as canonicalHash,Ue as carrierOf,qt as collectKanonakFiles,N as compareVersions,ct as computeIntegrity,$e as contentAddressedName,Kr as contextTypesOf,nt as createAuthenticatedFetch,B as createDPoPProof,At as createVersion,cr as extractMarkdownLinks,sn as findDerivation,Ir as findInstancesByType,sr as findMalformedReferences,wr as findMarkdownLinkAt,Rr as formatKanonakAddress,h as formatVersion,tt as generateDPoPKeyPair,Ft as getGlobalCachePath,_ as hasValidToken,Ot as isCompatibleVersion,U as isExpired,Dt as isMajorCompatible,it as loadLockFile,nr as makeUriKey,Be as noopMeter,l as normalizeHost,ke as parseKanonakAddress,Vt as parseVersionString,Pr as parseWithPositions,Nt as pickHighestDocument,vr as propertiesInScope,cn as resolveDisplayValue,xr as resolvePropertyStep,V as sanitizeName,st as saveLockFile,rt as serverSupportsDPoP,g as subjectUri,Er as superClassChain,or as tripleKey,R as uriKey,ar as uriTriple,jt as versionOperatorFromChar,ie as versionOperatorToChar,Bt as versionsEqual};
93
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let r=l(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}': ${oe(o)}
94
+ Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${oe(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: ${oe(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await $r(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:nt});return r}catch(r){throw jr(r)?new Error(`Credential helper not found at '${this.helperPath}'.
95
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Vr(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${nt/1e3}s on '${e}'.
96
+ The helper may be waiting for authentication to an external vault.`):r}}};function oe(n){return n instanceof Error?n.message:String(n)}function jr(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"}function Vr(n){return n instanceof Error&&"killed"in n&&n.killed}var ve=Dr(Or(),".kanonak","config.json"),ae=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=Nr(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!G(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=Tr();return e.credentialHelper?new N(e.credentialHelper):process.platform==="darwin"?new V:process.platform==="win32"?new A:await Re()?new B:new D}};function Nr(n){let t="KANONAK_TOKEN_"+l(n).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Tr(){if(!Ar(ve))return{};try{return JSON.parse(Br(ve,"utf-8"))}catch(n){let e=n instanceof Error?n.message:String(n);return console.warn(` Warning: Failed to parse ${ve}: ${e}
97
+ Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as _r,createPrivateKey as Lr,generateKeyPairSync as Ur,randomUUID as Fr,sign as Mr}from"crypto";function ot(){let{publicKey:n,privateKey:e}=Ur("ec",{namedCurve:"P-256"});return{publicKey:n.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function T(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:Fr(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=_r("sha256").update(o).digest("base64url")),a&&(s.nonce=a),Hr(i,s,n)}function at(n){return!n||n.length===0?!1:n.some(e=>e.toUpperCase()==="ES256")}function Hr(n,e,t){let r=rt(JSON.stringify(n)),o=rt(JSON.stringify(e)),a=`${r}.${o}`,i=Lr({key:t,format:"jwk"}),c=Mr("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${c}`}function rt(n){return Buffer.from(n,"utf-8").toString("base64url")}function it(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});W(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 u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);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 '${r}': ${d}
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 u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=u,s=await fetch(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as zr,writeFileSync as Wr,existsSync as Gr}from"fs";import{createHash as Jr}from"crypto";import st from"js-yaml";var ct="kanonak.lock",qr=`# This file is generated by Kanonak CLI. Do not edit manually.
99
+ `;function lt(n=ct){if(!Gr(n))return null;let e=zr(n,"utf-8"),t=st.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function ut(n,e=ct){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=st.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Wr(e,qr+r,"utf-8")}function pt(n){return`sha256:${Jr("sha256").update(n).digest("hex")}`}import*as Ae from"js-yaml";import{createHash as Zr}from"crypto";function Ke(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}function $e(n){return n.subjects.map(e=>{let t=new f,r=e.uri.lastIndexOf("/");return t.namespace=e.uri.slice(0,r),t.name=e.uri.slice(r+1),t.statement=(e.statements??[]).map(o=>mt(o.predicate,o.value)),t})}function dt(n,e,t){let r=new R;return r.predicate=p.parse(n),r.object=t,e&&(r.carrier=e,r.lexical=t),r}function mt(n,e){if("lit"in e)return dt(n,v(H.parse(e.datatype)),e.lit);if("raw"in e)return dt(n,void 0,e.raw);if("ref"in e){let t=new E;return t.predicate=p.parse(n),t.object=p.parse(e.ref),t}if("embed"in e){let t=new x;return t.predicate=p.parse(n),t.object=ft(e.embed),t}if("list"in e){let t=new I;return t.predicate=p.parse(n),t.object=e.list.map(Yr),t}throw new Error(`canonical input: unknown value shape ${JSON.stringify(e)}`)}function ft(n){let e=new y;return n.name&&(e.name=n.name),e.statement=(n.statements??[]).map(t=>mt(t.predicate,t.value)),e}function Yr(n){if("ref"in n)return p.parse(n.ref);if("embed"in n)return ft(n.embed);let e=new C;if("lit"in n){e.value=n.lit;let t=v(H.parse(n.datatype));t&&(e.carrier=t,e.lexical=n.lit)}else if("raw"in n)e.value=n.raw;else throw new Error(`canonical input: unknown list item shape ${JSON.stringify(n)}`);return e}var gt="1",yt=new TextEncoder;function ht(n,e){let t=yt.encode(n),r=yt.encode(e),o=Math.min(t.length,r.length);for(let a=0;a<o;a++)if(t[a]!==r[a])return t[a]-r[a];return t.length-r.length}function je(n){let e=Ke(n)?$e(n):n,t=[];for(let o of e)o instanceof f&&t.push(Xr(o));return t.sort((o,a)=>ht(o.uri,a.uri)),JSON.stringify({subjects:t})}function ie(n){let e=Ke(n)?$e(n):n,t=je(e);return`sha256:${Zr("sha256").update(t,"utf8").digest("hex")}`}function Xr(n){let e=oo(n),t=Ve(n.statement);return{uri:e,statements:t}}function Ve(n){let e=[];for(let t of n){let r=Qr(t);r&&e.push(r)}return e.sort((t,r)=>ht(t.predicate,r.predicate)),e}function Qr(n){let e=ro(n);if(!e)return;let t=eo(n);if(t)return no(e,t)}function eo(n){if(n instanceof ye&&n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.object))};if(n instanceof R)return{type:"string",value:n.object};if(n instanceof ge)return{type:"number",value:wt(n.object)};if(n instanceof he)return{type:"boolean",value:n.object};if(n instanceof E)return{type:"ref",value:bt(n.object)};if(n instanceof x){let e=n.object;return kt(e)}if(n instanceof I)return{type:"list",items:n.object.map(to)}}function kt(n){let e=Ve(n.statement);return n.name&&n.name.length>0?{type:"embedded",name:n.name,statements:e}:{type:"embedded",statements:e}}function to(n){if(n instanceof p)return{type:"ref",value:bt(n)};if(n instanceof y)return kt(n);if(n instanceof C){if(n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.value))};let e=n.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:wt(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(n instanceof fe)return{type:"embedded",statements:Ve(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 no(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"typed":return{predicate:n,type:"typed",carrier:e.carrier,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 ro(n){let e=n.predicate;if(e)return Pt(e.subject)}function oo(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function bt(n){return Pt(n.subject)}function Pt(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 wt(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 St}from"@kanonak-protocol/types/document/models/enums";var ao="0.0.0",P=class{constructor(e,t=new S,r){this.repository=e;this.parser=t;this.objectParser=r??new $(this.parser)}repository;parser;objectParser;imports(){return new _}serializeValue(e,t){return Et(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Be(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:Rt(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:Rt(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ae.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[Ct]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(Ae.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Me(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==Ct);for(let u of c)u.namespace="ephemeral";return ie(c)}},Ct="__pkgbuilder_probe__";function Rt(n){return new TextEncoder().encode(n).length}function Be(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var _=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=St.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_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,o){return`${this.ensure(e,t,ao,o??t,St.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:me(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=L(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function Et(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof p)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>Et(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n 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(io(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 L(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function io(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var se=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}@${k(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=Pe(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 Oe={async authorize(){return{allowed:!0}}},De={async record(){}},U=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},ce=class{inner;ctx;policy;meter;constructor(e,t,r=Oe,o=De){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 U(e,t.reason)}};var m="kanonak.org",g="view",xt="core-kanonak",so={publisher:m,package_:g,name:"rootView"},co={publisher:m,package_:g,name:"bind"},lo={publisher:m,package_:g,name:"produces"},uo={publisher:m,package_:g,name:"projections"},po={publisher:m,package_:g,name:"where"},mo={publisher:m,package_:g,name:"value"},fo={publisher:m,package_:g,name:"as"},le=class{constructor(e,t=new S){this.repository=e;this.parser=t;this.objectParser=new $(this.parser),this.builder=new P(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=j(o,co);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=j(o,lo);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=yo(o),c=It(r,m,xt),u=It(r,m,g),d=this.builder.imports(),ue=d.ensure(m,xt,c,"ck"),Kt=d.ensure(m,g,u,"v"),$t=d.ref(i),jt=new We(this.repository,this.parser,this.objectParser),Ne=new He(jt,r),Vt=this.readProjections(r,o),At=ko(o,po),Bt=this.findInstances(r,a,await this.reason(t)),Te={},Ot=new Set;for(let F of Bt){if(!await this.passesWhere(Ne,r,At,F))continue;let de={type:$t};for(let Le of Vt){let Dt=await this.evaluateValue(Ne,r,Le.value,F),Ue=this.builder.serializeValue(vt(Dt),d);Ue!==void 0&&(de[d.ref(Le.as)]=Ue)}let _e=h(F);_e&&(de[`${Kt}.derivedFrom`]=d.ref(_e)),Te[this.rowName(F,Ot)]=de}let pe={};t.resolvedAt&&(pe[`${ue}.resolvedAt`]=t.resolvedAt),t.invocationId&&(pe[`${ue}.id`]=t.invocationId);let w=await this.builder.buildContentAddressed({publisher:s,book:d,body:Te,contentHashProperty:`${ue}.contentHash`,header:pe});return{yaml:w.yaml,contentHash:w.contentHash,packageName:w.packageName,publisher:w.publisher,rowCount:w.resourceCount}}resolveView(e,t){let r=z(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=j(r,so);if(o){let a=z(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 Se(t,uo)){let a=o instanceof y?o:o instanceof p?z(e,o.subject):void 0;if(!a)continue;let i=we(a,mo),s=j(a,fo);i&&s&&r.push({value:i,as:s})}return r}async reason(e){return new be({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let o=ho(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 u=K(h(s)),d=K(h(c));return u<d?-1:u>d?1:0}),a}async passesWhere(e,t,r,o){for(let a of r){let i=await this.evaluateValue(e,t,a,o);if(!bo(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=L(e.name)||"row",o=r,a=2;for(;t.has(o);)o=`${r}-${a++}`;return t.add(o),o}};function vt(n){return Ce(n)?n.value:Array.isArray(n)?n.map(vt):n}function yo(n){let e=h(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function It(n,e,t){let r=go(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 go(n,e,t){let r;for(let o of n){if(!(o instanceof f))continue;let a=h(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!r||M(a.version,r)>0)&&(r=a.version)}return r?k(r):void 0}function ho(n){let e=new Map,t=new Map;for(let r of n){if(!(r instanceof f))continue;let o=h(r);if(!o||!o.version)continue;let a=K(o),i=t.get(a);(!i||M(o.version,i)>0)&&(t.set(a,o.version),e.set(a,r))}return e}function ko(n,e){let t=we(n,e);return t?[t]:Se(n,e).filter(r=>r instanceof y)}function bo(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Ce(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{rr as AmbiguousReferenceRule,he as BooleanStatement,gt as CANONICAL_FORM_VERSION,Fe as Carrier,lr as ClassDefinitionRule,Jn as ClassHierarchyCycleRule,Gt as CompositeKanonakDocumentRepository,ae as CredentialStore,fe as DefinedKanonak,tr as DefinitionPropertyReferenceRule,Wt as DocumentLocation,hn as EdgeType,y as EmbeddedKanonak,zn as EmbeddedKanonakTypeRule,x as EmbeddedStatement,U as EntitlementDeniedError,ce as EntitlementProducer,zt as FileSystemKanonakDocumentRepository,Cn as GitIgnoreFilter,kn as GraphBuilder,Qt as HttpKanonakDocumentRepository,_ as ImportBook,Wn as ImportExistenceRule,Ht as InMemoryKanonakDocumentRepository,er as InstancePropertyReferenceRule,rn as Kanonak,En as KanonakDocumentPositions,$ as KanonakObjectParser,pr as KanonakObjectValidator,S as KanonakParser,H as KanonakUri,vn as KanonakUriBuilder,$n as KanonakUrlResolver,dn as KanonakVocabulary,I as ListStatement,C as LiteralKanonak,en as LocalFirstRepository,fr as LookRenderer,ur as MarkdownLinkRule,an as MarkdownStatement,Qn as NamespaceImportCycleRule,Un as NamespacePrefixRule,gn as NodeType,ge as NumberStatement,wn as OWL_RL_CLASSIFICATION_RULES,ar as ObjectPropertyImportRule,ir as ObjectPropertyValueValidationRule,Tn as OntologyValidationError,Dn as OntologyValidationResult,P as PackageBuilder,se as ProducerRepository,sr as PropertyDomainRule,qn as PropertyHierarchyCycleRule,Rn as PropertyMetadata,or as PropertyRangeReferenceRule,Yn as PropertyRangeRequiredRule,Mn as PropertyTypeSpecificityRule,cr as PropertyValueTypeRule,Yt as PublisherConfigResolver,Zt as PublisherIndex,Pn as RDFS_RULES,be as Reasoner,Sn as ReasoningResult,p as ReferenceKanonak,E as ReferenceStatement,qt as RepositoryFactory,Fn as ResourceNamingRule,sn as ResourceResolver,yn as ResourceTypeClassifier,ye as ScalarStatement,on as Statement,R as StringStatement,Zn as SubClassOfReferenceRule,Xn as SubPropertyOfReferenceRule,f as SubjectKanonak,Hn as SubjectKanonakTypeRequiredRule,bn as TripleStore,cn as TypeResolver,Gn as UnresolvedReferenceRule,Ln as ValidationCache,_n as ValidationContext,Nn as ValidationSeverity,Oi as VersionOperator,le as ViewMaterializer,nr as XsdImportRule,Oe as allowAllPolicy,Xt as assertPackageIdentity,nn as buildLocalFirstRepository,yr as buildOntologyModel,je as canonicalForm,ie as canonicalHash,v as carrierOf,tn as collectKanonakFiles,M as compareVersions,pt as computeIntegrity,Be as contentAddressedName,Bn as contextTypesOf,it as createAuthenticatedFetch,T as createDPoPProof,_t as createVersion,fn as extractMarkdownLinks,dr as findDerivation,On as findInstancesByType,mn as findMalformedReferences,In as findMarkdownLinkAt,Kn as formatKanonakAddress,k as formatVersion,ot as generateDPoPKeyPair,Jt as getGlobalCachePath,G as hasValidToken,Ut as isCompatibleVersion,W as isExpired,Ft as isMajorCompatible,lt as loadLockFile,ln as makeUriKey,De as noopMeter,l as normalizeHost,Pe as parseKanonakAddress,Lt as parseVersionString,xn as parseWithPositions,Mt as pickHighestDocument,Vn as propertiesInScope,mr as resolveDisplayValue,An as resolvePropertyStep,L as sanitizeName,ut as saveLockFile,at as serverSupportsDPoP,h as subjectUri,jn as superClassChain,un as tripleKey,K as uriKey,pn as uriTriple,Nt as versionOperatorFromChar,me as versionOperatorToChar,Tt as versionsEqual};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "4.2.0",
3
+ "version": "4.3.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",
@@ -91,8 +91,7 @@
91
91
  "default": "./dist/browser.js"
92
92
  },
93
93
  "./vectors/lexical-vectors.json": "./vectors/lexical-vectors.json",
94
- "./vectors/full-form-vectors.json": "./vectors/full-form-vectors.json",
95
- "./vectors/decode.mjs": "./vectors/decode.mjs"
94
+ "./vectors/full-form-vectors.json": "./vectors/full-form-vectors.json"
96
95
  },
97
96
  "files": [
98
97
  "dist/**/*",
@@ -126,7 +125,7 @@
126
125
  "yaml-parser"
127
126
  ],
128
127
  "dependencies": {
129
- "@kanonak-protocol/types": "^4.2.0",
128
+ "@kanonak-protocol/types": "^4.3.0",
130
129
  "ignore": "^7.0.5",
131
130
  "js-yaml": "^4.1.0",
132
131
  "yaml": "^2.7.0"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "canonicalFormVersion": "1",
3
3
  "hashAlgorithm": "sha256",
4
- "description": "Golden conformance vectors for canonicalForm/canonicalHash over the typed-value input model (issue #55). input -> expectedCanonicalForm (exact UTF-8 JSON bytes) -> expectedHash. The same file drives every kanonak-canonical port. See decode.mjs for the input-model decoder. Expected values are authoritative.",
4
+ "description": "Golden conformance vectors for canonicalForm/canonicalHash over the language-neutral input model (issues #55, #56). input -> expectedCanonicalForm (exact UTF-8 JSON bytes) -> expectedHash. The public canonicalForm(input)/canonicalHash(input) entry accepts this model directly; the same file drives every kanonak-canonical port. Expected values are authoritative.",
5
5
  "vectors": [
6
6
  {
7
7
  "id": "typed-scalars-mixed",
@@ -1,115 +0,0 @@
1
- /**
2
- * Decoder for the canonical-form full-form vectors' typed-value INPUT model
3
- * (issue #55, option 1). The input is language-neutral and carries datatype
4
- * explicitly, so a port tests canonicalization in isolation (no parser needed):
5
- *
6
- * subject := { uri, statements: [ { predicate, value } ] }
7
- * value := { lit, datatype } typed scalar — raw lexical token + datatype URI
8
- * | { raw } untyped/open-world scalar (no carrier, raw token)
9
- * | { ref } reference to an entity (full canonical URI)
10
- * | { embed: { name?, statements } } embedded node
11
- * | { list: [ value ] } ordered list
12
- *
13
- * It builds the SDK object model the same way the parser's range-directed
14
- * typing does (carrier from the datatype URI via `carrierOf`), so
15
- * `canonicalForm`/`canonicalHash` over the result is the authoritative output.
16
- * This file is also the reference each `kanonak-canonical` port mirrors to map
17
- * the input model into its own representation.
18
- */
19
- import {
20
- SubjectKanonak,
21
- ReferenceKanonak,
22
- EmbeddedKanonak,
23
- LiteralKanonak,
24
- StringStatement,
25
- ReferenceStatement,
26
- EmbeddedStatement,
27
- ListStatement,
28
- carrierOf,
29
- } from '@kanonak-protocol/sdk';
30
-
31
- /** "publisher/package@ver/name" or "publisher/package/name" → { publisher, package_, name }. */
32
- function entityUri(uriStr) {
33
- const idx = uriStr.lastIndexOf('/');
34
- const name = uriStr.slice(idx + 1);
35
- const head = uriStr.slice(0, idx); // publisher/package@ver
36
- const publisher = head.slice(0, head.indexOf('/'));
37
- const pkg = head.slice(head.indexOf('/') + 1).split('@')[0];
38
- return { publisher, package_: pkg, name };
39
- }
40
-
41
- /**
42
- * A scalar statement. canonicalForm reads `(carrier, lexical)` off any
43
- * ScalarStatement, so a single StringStatement faithfully represents every
44
- * scalar carrier — the canonical output depends on the carrier+lexical, not the
45
- * statement class.
46
- */
47
- function scalar(predicateUri, carrier, lexical) {
48
- const s = new StringStatement();
49
- s.predicate = ReferenceKanonak.parse(predicateUri);
50
- s.object = lexical;
51
- if (carrier) {
52
- s.carrier = carrier;
53
- s.lexical = lexical;
54
- }
55
- return s;
56
- }
57
-
58
- function buildEmbedded(e) {
59
- const emb = new EmbeddedKanonak();
60
- if (e.name) emb.name = e.name;
61
- emb.statement = (e.statements ?? []).map((st) => buildStatement(st.predicate, st.value));
62
- return emb;
63
- }
64
-
65
- function buildItem(v) {
66
- if ('ref' in v) return ReferenceKanonak.parse(v.ref);
67
- if ('embed' in v) return buildEmbedded(v.embed);
68
- const lit = new LiteralKanonak();
69
- if ('lit' in v) {
70
- lit.value = v.lit;
71
- lit.carrier = carrierOf(entityUri(v.datatype));
72
- lit.lexical = v.lit;
73
- } else if ('raw' in v) {
74
- lit.value = v.raw;
75
- } else {
76
- throw new Error(`decode: unknown list item shape ${JSON.stringify(v)}`);
77
- }
78
- return lit;
79
- }
80
-
81
- export function buildStatement(predicateUri, v) {
82
- if ('lit' in v) return scalar(predicateUri, carrierOf(entityUri(v.datatype)), v.lit);
83
- if ('raw' in v) return scalar(predicateUri, undefined, v.raw);
84
- if ('ref' in v) {
85
- const s = new ReferenceStatement();
86
- s.predicate = ReferenceKanonak.parse(predicateUri);
87
- s.object = ReferenceKanonak.parse(v.ref);
88
- return s;
89
- }
90
- if ('embed' in v) {
91
- const s = new EmbeddedStatement();
92
- s.predicate = ReferenceKanonak.parse(predicateUri);
93
- s.object = buildEmbedded(v.embed);
94
- return s;
95
- }
96
- if ('list' in v) {
97
- const s = new ListStatement();
98
- s.predicate = ReferenceKanonak.parse(predicateUri);
99
- s.object = v.list.map(buildItem);
100
- return s;
101
- }
102
- throw new Error(`decode: unknown value shape ${JSON.stringify(v)}`);
103
- }
104
-
105
- /** Build the SubjectKanonak[] the canonical form consumes from a vector's `input`. */
106
- export function decodeSubjects(input) {
107
- return input.subjects.map((s) => {
108
- const subj = new SubjectKanonak();
109
- const idx = s.uri.lastIndexOf('/');
110
- subj.namespace = s.uri.slice(0, idx);
111
- subj.name = s.uri.slice(idx + 1);
112
- subj.statement = (s.statements ?? []).map((st) => buildStatement(st.predicate, st.value));
113
- return subj;
114
- });
115
- }