@kanonak-protocol/sdk 6.5.0 → 6.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/browser.d.ts +2 -2
  2. package/dist/browser.js +1 -1
  3. package/dist/{chunk-Q57XCPAQ.js → chunk-426MUUGB.js} +16 -16
  4. package/dist/chunk-6WOPXTIL.js +1 -0
  5. package/dist/{chunk-GXEKJFXG.js → chunk-CPENAANM.js} +27 -27
  6. package/dist/{chunk-AAYMTPG7.js → chunk-DQGXJDQU.js} +1 -1
  7. package/dist/{chunk-7TNZ7ICK.js → chunk-FS7UGDEX.js} +1 -1
  8. package/dist/{chunk-5AMN6MW7.js → chunk-IWPCPQQY.js} +1 -1
  9. package/dist/{chunk-X4V6DEZL.js → chunk-LIN5SG5I.js} +1 -1
  10. package/dist/chunk-LK5SHY4B.js +1 -0
  11. package/dist/{chunk-FB5QKDNM.js → chunk-OHF4RIKS.js} +1 -1
  12. package/dist/{chunk-LKJVNKCN.js → chunk-SBWD7EOG.js} +1 -1
  13. package/dist/{chunk-MSOUPUUB.js → chunk-TF23WBSZ.js} +1 -1
  14. package/dist/chunk-VJUZKHQU.js +1 -0
  15. package/dist/index.d.ts +3 -3
  16. package/dist/index.js +4 -2
  17. package/dist/look/LookRenderer.d.ts +10 -4
  18. package/dist/parsing/index.js +1 -1
  19. package/dist/producer/index.js +1 -1
  20. package/dist/reasoning/KanonakVocabulary.d.ts +9 -0
  21. package/dist/reasoning/Reasoner.d.ts +6 -0
  22. package/dist/reasoning/index.d.ts +1 -1
  23. package/dist/reasoning/index.js +1 -1
  24. package/dist/resolution/index.js +1 -1
  25. package/dist/resolution/linkTargets.d.ts +45 -0
  26. package/dist/search/index.js +1 -1
  27. package/dist/server/closure.d.ts +11 -6
  28. package/dist/server/index.js +5 -5
  29. package/dist/shacl/ConformanceEvaluator.d.ts +8 -3
  30. package/dist/shacl/ConformanceScope.d.ts +60 -4
  31. package/dist/shacl/ShapesModel.d.ts +23 -0
  32. package/dist/shacl/index.d.ts +5 -5
  33. package/dist/shacl/uris.d.ts +1 -0
  34. package/dist/transformations/index.js +2 -2
  35. package/dist/transformations/v3/ExpressionEngineV3.d.ts +15 -0
  36. package/dist/uri-helpers/UriHelpers.d.ts +8 -0
  37. package/dist/uri-helpers/index.d.ts +1 -1
  38. package/dist/uri-helpers/index.js +1 -1
  39. package/dist/validation/index.js +1 -1
  40. package/package.json +2 -2
  41. package/dist/chunk-A224OOBZ.js +0 -1
  42. package/dist/chunk-PC3MYDGL.js +0 -1
  43. package/dist/chunk-WXUMROTA.js +0 -1
@@ -35,15 +35,71 @@ export interface ConformanceScope {
35
35
  * payload gets no inference.
36
36
  */
37
37
  reasoning?: ReasoningResult | undefined;
38
+ /**
39
+ * The subjects the evaluation judges, by subject address, when the catalog
40
+ * holds more than the data being judged. A closure scope judges the
41
+ * documents it was built from, while the rest of their import closure only
42
+ * supplies the shapes, classes and referenced subjects (typescript#135).
43
+ * Embedded values are judged with the subject they sit under. Absent: every
44
+ * node in the catalog is judged.
45
+ */
46
+ focus?: ReadonlySet<string> | undefined;
47
+ /**
48
+ * What the judged documents' `mode: link` references point at, read one hop
49
+ * out (typescript#138). A link is data, not a dependency (#111): its target
50
+ * package is not in the catalog, so nothing in it is judged, its shapes and
51
+ * keys bind nothing, and its classes are not the scope's. A value that is a
52
+ * link is checked against the subject it names, as `LinkTargetRule`
53
+ * dereferences it. Absent: the scope reads no links.
54
+ */
55
+ links?: ScopeLinks | undefined;
56
+ }
57
+ /** The targets of a scope's link references; see {@link ConformanceScope.links}. */
58
+ export interface ScopeLinks {
59
+ /**
60
+ * The subjects of each linked package the judged documents reference, at
61
+ * the version its link import resolves to: the package's own statements,
62
+ * with its names resolved through the repository. A reference value the
63
+ * catalog does not resolve is looked up here, as `findSubjectByUri` matches.
64
+ */
65
+ subjects: Kanonak[];
66
+ /** Why a link reference does not dereference, by the referenced subject's key (`uriKey`). */
67
+ unresolved: ReadonlyMap<string, string>;
38
68
  }
39
69
  /**
40
70
  * Build a merged scope from a repository — the pinned load-set. One parse
41
- * (the same open-world merge every SDK consumer sees) + one reasoning pass
42
- * over the same repository, so targeting and class checks are
43
- * closure-aware. The caller owns WHAT is in the repository; that is the
44
- * authorization boundary.
71
+ * (the same open-world merge every SDK consumer sees), reasoned over, so
72
+ * targeting and class checks are closure-aware. The caller owns WHAT is in
73
+ * the repository; that is the authorization boundary. Every document the
74
+ * repository enumerates is in scope: a workspace repository backed by the
75
+ * global cache brings in every cached version of every package. To judge
76
+ * documents against what they import, use {@link scopeFromClosureAsync}.
45
77
  */
46
78
  export declare function scopeFromRepositoryAsync(repository: IKanonakDocumentRepository): Promise<ConformanceScope>;
79
+ /**
80
+ * Build a merged scope that judges `seeds` against their own import closure,
81
+ * at the exact versions it resolves to through `repository` (typescript#135).
82
+ *
83
+ * The catalog is the closure and nothing else: a version of a package that no
84
+ * import resolved to does not enter it, wherever it is stored (the workspace,
85
+ * the global cache), so its shapes cannot bind the seeds' nodes. Only the
86
+ * seeds' own nodes are judged ({@link ConformanceScope.focus}), including
87
+ * subjects of other packages that a seed augments; the rest of the closure
88
+ * supplies their contracts.
89
+ *
90
+ * A seed's `mode: link` references are read one hop out
91
+ * ({@link ConformanceScope.links}): each linked package a seed references is
92
+ * resolved by its link import and parsed on its own, without joining the
93
+ * catalog. A link that does not dereference is not an error here: a check on
94
+ * that value fails, and says why.
95
+ *
96
+ * Every seed must be a document of `repository`, and every import in the
97
+ * closure must resolve. A partial closure would judge the seeds against fewer
98
+ * contracts than they declare, so an unresolved import is an error. So is a
99
+ * package that two seeds link at different versions, since a link value
100
+ * names one subject: judge such seeds in separate scopes.
101
+ */
102
+ export declare function scopeFromClosureAsync(seeds: KanonakDocument[], repository: IKanonakDocumentRepository): Promise<ConformanceScope>;
47
103
  /**
48
104
  * Build a merged scope from an already-parsed catalog (e.g. a validation
49
105
  * pass's single-parse `ValidationCache.getKanonaks()`), optionally with an
@@ -85,3 +85,26 @@ export interface ShaclNodeShapeModel {
85
85
  * definition validator warns about it separately).
86
86
  */
87
87
  export declare function buildShapesModel(shapesCatalog: Kanonak[]): ShaclNodeShapeModel[];
88
+ /**
89
+ * A class's key, `owl:hasKey` (typescript#134): properties whose values
90
+ * jointly identify a named instance of the class or of its subclasses.
91
+ */
92
+ export interface ShaclClassKeyModel {
93
+ /** The keyed class. */
94
+ classUri: KanonakUri;
95
+ /** How messages name the class. */
96
+ className: string;
97
+ /** The key's properties, in authored order. */
98
+ properties: KanonakUri[];
99
+ }
100
+ /**
101
+ * The keys the classes in a catalog declare. A key is part of the contract
102
+ * the data is held to, like a shape, so conformance reads keys from the same
103
+ * catalog it reads shapes from. Each `owl:hasKey` statement on a class is a
104
+ * key of its own; two never merge into one composite key.
105
+ *
106
+ * A key that lists nothing, or lists anything but a property defined in the
107
+ * catalog, is an error: every instance would be unkeyed, and the uniqueness
108
+ * check would pass by construction.
109
+ */
110
+ export declare function buildKeysModel(catalog: Kanonak[]): ShaclClassKeyModel[];
@@ -1,10 +1,10 @@
1
- export { scopeFromRepositoryAsync, scopeFromCatalog, scopeFromDocumentAsync, } from './ConformanceScope.js';
2
- export type { ConformanceScope } from './ConformanceScope.js';
3
- export { buildShapesModel } from './ShapesModel.js';
4
- export type { ShaclNodeShapeModel, ShaclPropertyConstraint, ShaclNodeKind, ShaclSeverity, } from './ShapesModel.js';
1
+ export { scopeFromRepositoryAsync, scopeFromClosureAsync, scopeFromCatalog, scopeFromDocumentAsync, } from './ConformanceScope.js';
2
+ export type { ConformanceScope, ScopeLinks } from './ConformanceScope.js';
3
+ export { buildShapesModel, buildKeysModel } from './ShapesModel.js';
4
+ export type { ShaclNodeShapeModel, ShaclClassKeyModel, ShaclPropertyConstraint, ShaclNodeKind, ShaclSeverity, } from './ShapesModel.js';
5
5
  export { lowerConstraint, foldFlagsIntoPattern } from './lowering.js';
6
6
  export type { LoweredCheck, LoweredExprNode } from './lowering.js';
7
7
  export { evaluateConformance } from './ConformanceEvaluator.js';
8
8
  export type { ShaclConformanceResult, ShaclFinding } from './ConformanceEvaluator.js';
9
9
  export { buildReportPackageAsync } from './ReportBuilder.js';
10
- export { SHACL_PUBLISHER, SHACL_PACKAGE, SH_SHAPE, SH_NODE_SHAPE, SH_PROPERTY_SHAPE, } from './uris.js';
10
+ export { SHACL_PUBLISHER, SHACL_PACKAGE, SH_SHAPE, SH_NODE_SHAPE, SH_PROPERTY_SHAPE, SH_COMP_MIN_COUNT, SH_COMP_MAX_COUNT, SH_COMP_DATATYPE, SH_COMP_CLASS, SH_COMP_IN, SH_COMP_PATTERN, SH_COMP_MIN_LENGTH, SH_COMP_MAX_LENGTH, SH_COMP_MIN_INCLUSIVE, SH_COMP_MAX_INCLUSIVE, SH_COMP_NODE_KIND, SH_COMP_CLOSED, SH_COMP_HAS_VALUE, SH_COMP_QUALIFIED_MIN_COUNT, SH_COMP_QUALIFIED_MAX_COUNT, SH_COMP_HAS_KEY, } from './uris.js';
@@ -70,3 +70,4 @@ export declare const SH_QUALIFIED_MAX_COUNT: EntityUri;
70
70
  export declare const SH_COMP_HAS_VALUE: EntityUri;
71
71
  export declare const SH_COMP_QUALIFIED_MIN_COUNT: EntityUri;
72
72
  export declare const SH_COMP_QUALIFIED_MAX_COUNT: EntityUri;
73
+ export declare const SH_COMP_HAS_KEY: EntityUri;
@@ -1,4 +1,4 @@
1
- import{a as pe}from"../chunk-5AMN6MW7.js";import"../chunk-FB5QKDNM.js";import{a as ve,b as M,c as Vn,n as X,o as Rn,p as vn,q as le,r as q,t as G}from"../chunk-GXEKJFXG.js";import"../chunk-QHABFCRC.js";import"../chunk-WXXZOJ4O.js";import{b as $n,c as Tn,d as Bn,e as xn,f as Un,k as fe}from"../chunk-LKJVNKCN.js";import{a as se}from"../chunk-5ZRVFYCP.js";import"../chunk-PEJALHXK.js";import{c as U}from"../chunk-WXUMROTA.js";import{b as Y,c as D,d as ce,e as E,f as ue,i as $,j as T,k as B,l as w,m as me,n as x,o as de,q as N,r as S,x as A}from"../chunk-PC3MYDGL.js";import"../chunk-F67UH4FD.js";import{g as ie}from"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.js";var Le="kanonak.org",Oe="document-ast",i=e=>({publisher:Le,package_:Oe,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ge(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var V=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=Ie(n.metadata,t),o=Ke(n.children),s=["---",...r,"---","",o].join(`
1
+ import{a as pe}from"../chunk-IWPCPQQY.js";import"../chunk-OHF4RIKS.js";import{a as ve,b as M,c as Vn,n as X,o as Rn,p as vn,q as le,r as Ln,s as q,u as G}from"../chunk-CPENAANM.js";import"../chunk-QHABFCRC.js";import"../chunk-WXXZOJ4O.js";import{b as $n,c as Tn,d as Bn,e as xn,f as Un,k as fe}from"../chunk-SBWD7EOG.js";import{a as se}from"../chunk-5ZRVFYCP.js";import"../chunk-PEJALHXK.js";import{c as U}from"../chunk-6WOPXTIL.js";import{b as Y,c as D,d as ce,e as E,f as ue,i as $,j as T,k as B,l as w,m as me,n as x,o as de,q as N,r as S,y as A}from"../chunk-LK5SHY4B.js";import"../chunk-F67UH4FD.js";import{g as ie}from"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.js";var Le="kanonak.org",Oe="document-ast",i=e=>({publisher:Le,package_:Oe,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ge(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var V=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=Ie(n.metadata,t),o=Ke(n.children),s=["---",...r,"---","",o].join(`
2
2
  `);return t?.trailingNewline&&(s.endsWith(`
3
3
  `)||(s+=`
4
4
  `)),s}};function Ie(e,n){if(!e)return[];let t=new Map;for(let c of e.entries)t.set(P(c.key),c);let r=new Map;if(n?.metadataRenames)for(let[c,u]of n.metadataRenames)r.set(P(c),u);let a=(n?.metadataKeys??e.entries.map(c=>c.key)).map(P),s=[];for(let c of a){let u=t.get(c);if(!u)continue;let f=r.get(c),l=P(f??c),d=ye(u.value,u.escapeHint);d!==void 0&&s.push(`${l}: ${d}`)}return s}function P(e){let n=e.lastIndexOf(".");return n===-1?e:e.substring(n+1)||e}function ye(e,n){switch(e.kind){case"StringScalar":return _e(e.stringValue,n);case"IntegerScalar":return String(e.integerValue);case"StructuredList":{let t=[];for(let r of e.items){let o=ye(r,n);o!==void 0&&t.push(o)}return t.join(", ")}case"StructuredMap":return;default:return}}function _e(e,n){return!n||ge(n,m.ESC_RAW)?e:ge(n,m.ESC_YAML_SAFE)?Ce(e):e}function Ce(e){return e.includes(`
@@ -88,4 +88,4 @@ ${e.rawContent}
88
88
  `)&&(o+=`
89
89
  `),o}};function C(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var K=class{backendUri="kanonak.org/transformations/dynamodb-json";render(n,t){if(!n.metadata)throw new Error("dynamodb-json backend: Document has no `metadata` channel. This backend serializes Document.metadata into DynamoDB attribute-value JSON \u2014 the transformation must populate that channel. (No silent empty artifact.)");let r=Ae(n.metadata,t),o=JSON.stringify(r,null,2);return t?.trailingNewline&&!o.endsWith(`
90
90
  `)&&(o+=`
91
- `),o}};function Ae(e,n){let t=new Map;for(let a of e.entries)t.set(a.key,a);let r=n?.metadataKeys??e.entries.map(a=>a.key),o={};for(let a of r){let s=t.get(a);if(!s)continue;let c=n?.metadataRenames.get(a)??a;o[c]=je(s.value,s.escapeHint)}return{M:o}}function je(e,n){switch(e.kind){case"StructuredMap":return Ae(e);case"StructuredList":return{L:e.items.map(t=>je(t,void 0))};case"StringScalar":return dn(e.stringValue,n??e.escapeHint);case"IntegerScalar":return fn(e.integerValue,n??e.escapeHint)}}function dn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL)){if(e==="true")return{BOOL:!0};if(e==="false")return{BOOL:!1};throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-bool must have the value "true" or "false"; got ${JSON.stringify(e)}.`)}if(n&&C(n,m.ESC_DYNAMODB_NULL))return{NULL:!0};if(n&&C(n,m.ESC_DYNAMODB_NUMBER)){if(e.trim()===""||Number.isNaN(Number(e)))throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-number must hold a numeric literal; got ${JSON.stringify(e)}.`);return{N:e}}return{S:e}}function fn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL))throw new Error(`dynamodb-json backend: esc-dynamodb-bool cannot apply to an IntegerScalar (value ${e}). Use a StringScalar "true"/"false".`);if(n&&C(n,m.ESC_DYNAMODB_NULL))throw new Error(`dynamodb-json backend: esc-dynamodb-null cannot apply to an IntegerScalar (value ${e}). Use a StringScalar hinted esc-dynamodb-null.`);return{N:String(e)}}var ln={"markdown-with-frontmatter":{formatUri:"kanonak.org/transformations/markdown-with-frontmatter",extension:".md"},"plain-markdown":{formatUri:"kanonak.org/transformations/plain-markdown",extension:".md"},toml:{formatUri:"kanonak.org/transformations/toml",extension:".toml"},json:{formatUri:"kanonak.org/transformations/json",extension:".json"},html:{formatUri:"kanonak.org/transformations/html",extension:".html"},svg:{formatUri:"kanonak.org/transformations/svg",extension:".svg"},stylesheet:{formatUri:"kanonak.org/transformations/stylesheet",extension:".css"},yaml:{formatUri:"kanonak.org/transformations/yaml",extension:".yaml"},"dynamodb-json":{formatUri:"kanonak.org/transformations/dynamodb-json",extension:".json"}},h=class extends Error{},H=class{backends=new Map;constructor(){this.register(new V),this.register(new R),this.register(new v),this.register(new L),this.register(new O),this.register(new I),this.register(new _),this.register(new K)}register(n){this.backends.set(n.backendUri,n)}async run(n){let t=n.transformationKanonaks??n.allKanonaks,r=M(n.transformation,t);if(!r.outputs.has(n.outputFormat))throw new h(`Transformation "${r.name}" does not declare output format "${n.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let o=this.findBackend(n.outputFormat);if(!o)throw new h(`No backend registered for OutputFormat "${n.outputFormat}".`);let a=new q(n.repository,n.parser,n.objectParser),s=new le(a,n.allKanonaks,r.fragments);return r.kind==="instance"?this.runInstance(r,n,o,s):this.runSet(r,n,o,s)}async runInstance(n,t,r,o){let a=Ee(t.instances,n.inputPattern.requires),s=$e(a,n.inputPattern.sortBy),c=[];for(let u of s){let f=new Map;f.set("input",u);let l=await o.evaluate(n.rule,f);ee(l,n.name,`input "${u.name}"`);let d=ne(await o.evaluate(n.artifactName,f),n.name,`input "${u.name}"`),g=te(n.overrides.get(t.outputFormat),t.runtimeOverride),k=r.render(l,g);c.push({fileName:d,format:t.outputFormat,content:k,source:{kind:"instance",sourceName:u.name}})}return c}async runSet(n,t,r,o){let a=Ee(t.instances,n.inputPattern.requires),s=$e(a,n.inputPattern.sortBy);return n.partitionBy?this.runSetWithPartition(n,s,t,r,o):this.runSetSingle(n,s,t,r,o)}async runSetSingle(n,t,r,o,a){let s=new Map;s.set("inputs",t);let c=await a.evaluate(n.rule,s);ee(c,n.name,"set");let u=ne(await a.evaluate(n.artifactName,s),n.name,"set"),f=te(n.overrides.get(r.outputFormat),r.runtimeOverride),l=o.render(c,f);return[{fileName:u,format:r.outputFormat,content:l,source:{kind:"set",memberCount:t.length}}]}async runSetWithPartition(n,t,r,o,a){let s=n.partitionBy,c=new Map,u=[];for(let l of t){let d=yn(l,s);if(d==null)continue;let g=kn(d),k=c.get(g);k||(k={keyValue:d,keyDisplay:bn(d),members:[]},c.set(g,k),u.push(g)),k.members.push(l)}let f=[];for(let l of u){let d=c.get(l),g=new Map;g.set("inputs",d.members),g.set("key",d.keyValue);let k=await a.evaluate(n.rule,g);ee(k,n.name,`partition "${d.keyDisplay}"`);let Ue=ne(await a.evaluate(n.artifactName,g),n.name,`partition "${d.keyDisplay}"`),Ve=te(n.overrides.get(r.outputFormat),r.runtimeOverride),Re=o.render(k,Ve);f.push({fileName:Ue,format:r.outputFormat,content:Re,source:{kind:"set",memberCount:d.members.length,partitionKey:d.keyDisplay}})}return f}findBackend(n){let t=ln[n];if(t)return this.backends.get(t.formatUri)}};function Ee(e,n){return n.length===0?e:e.filter(t=>{for(let r of n)if(!gn(t,r))return!1;return!0})}function $e(e,n){if(n.length===0)return e;let t=[...e];return t.sort((r,o)=>{for(let a of n){let s=Te(r,a.byProperty),c=Te(o,a.byProperty),u=pn(s,c,a.order);if(u!==0)return u}return 0}),t}function Te(e,n){for(let t of e.statement){let r=re(t);if(!(!r||!N(r,n))){if(t instanceof $||t instanceof T||t instanceof B)return t.object;if(t instanceof x)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(t instanceof w)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function pn(e,n,t){if(e===void 0&&n===void 0)return 0;if(e===void 0)return t==="ascending"?1:-1;if(n===void 0)return t==="ascending"?-1:1;let r;return typeof e=="number"&&typeof n=="number"?r=e-n:r=String(e).localeCompare(String(n)),t==="ascending"?r:-r}function gn(e,n){for(let t of e.statement){let r=re(t);if(!r||!N(r,n))continue;let o=t.object;if(o!=null&&!(typeof o=="string"&&o.length===0)&&!(Array.isArray(o)&&o.length===0))return!0}return!1}function yn(e,n){for(let t of e.statement){let r=re(t);if(!(!r||!N(r,n))&&(t instanceof $||t instanceof T||t instanceof B||t instanceof w||t instanceof x))return t.object}}function re(e){return e.predicate?.subject}function kn(e){if(e===void 0)return" undef";if(e===null)return" null";if(typeof e=="string")return`s:${e}`;if(typeof e=="number")return`n:${e}`;if(typeof e=="boolean")return`b:${e}`;if(e instanceof E){let n=e.subject;return`r:${n.publisher}/${n.package_}/${n.name}`}if(e instanceof Y){let n=e.name??"";return`k:${e.namespace??""}/${n}`}if(typeof e=="object"&&e!==null&&typeof e.name=="string"&&typeof e.publisher=="string"){let n=e;return`u:${n.publisher}/${n.package_}/${n.name}`}return`o:${JSON.stringify(e,(n,t)=>n==="sourceKey"?void 0:t)}`}function bn(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e instanceof E?e.subject.name:e instanceof Y?e.name??"":typeof e=="object"&&e!==null&&typeof e.name=="string"?e.name:""}function ee(e,n,t){if(typeof e!="object"||e===null||e.kind!=="Document")throw new h(`Transformation "${n}" rule did not yield a Document for ${t}. Got: ${Be(e)}`)}function ne(e,n,t){if(typeof e=="string")return e;if(Array.isArray(e)&&e.every(hn))return e.map(r=>String(r)).join("");throw new h(`Transformation "${n}" artifactName did not yield a string for ${t}. Got: ${Be(e)}`)}function hn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Be(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"){let n=e.kind;return n?`object(kind=${n})`:"object"}return typeof e}function te(e,n){if(!e&&!n)return;let t={metadataRenames:n?.metadataRenames??e?.metadataRenames??new Map},r=n?.metadataKeys??e?.metadataKeys;r!==void 0&&(t.metadataKeys=r);let o=n?.trailingNewline??e?.trailingNewline;o!==void 0&&(t.trailingNewline=o);let a=n?.omitWrapper??e?.omitWrapper;return a!==void 0&&(t.omitWrapper=a),t}var p=class extends Error{constructor(t,r){super(t);this.cause=r;this.name="RenderError"}cause},xe={publisher:"kanonak.org",package_:"derivation",name:"default"},oe=class{constructor(n,t=new se,r=new fe){this.repository=n;this.parser=t;this.objectParser=r}repository;parser;objectParser;runner=new H;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async renderViaLook(n){let t=await this.getCatalog(),r=A(t,n.resource);if(!(r instanceof D))throw new p(`Resource not found: ${b(n.resource)}`);let o=new G(t),a;if(n.format.name==="html")a=await o.renderHtml(r);else if(n.format.name==="stylesheet")a=o.renderStylesheet(r);else throw new p(`LookRenderer does not support format ${b(n.format)} \u2014 only formats.html and formats.stylesheet are implemented in v0.1.`);return{content:a,format:n.format,filename:r.name}}async findDerivation(n){let t=await this.getCatalog(),r=A(t,n.resource);if(!(r instanceof D))return;let o=n.variant??xe;return pe(r,n.format,o,t)}async render(n){if(n.format.name==="html"||n.format.name==="stylesheet"){let a=await this.getCatalog(),s=A(a,n.resource);if(s instanceof D){let u=new G(a).findCascadedLook(s);if(u&&!wn(u.sourceClass)){let f=await this.findDerivation(n);if(!f||Dn(f))return this.renderViaLook({resource:n.resource,format:n.format})}}}let t=await this.findDerivation(n);if(!t)throw new p(`No derivation found for ${b(n.resource)} \u2192 format ${b(n.format)}`+(n.variant?` variant ${b(n.variant)}`:""));let r=ie(t.transformation.version),o={transformation:{publisher:t.transformation.publisher,package_:t.transformation.package_,name:t.transformation.name,...r?{version:r}:{}},input:n.resource,format:n.format};return n.omitWrapper!==void 0&&(o.omitWrapper=n.omitWrapper),this.runTransformation(o)}async runTransformation(n){let t=await this.getCatalog(),r=A(t,n.transformation);if(!(r instanceof D))throw new p(`Transformation not found: ${b(n.transformation)}`);let o=A(t,n.input);if(!(o instanceof D))throw new p(`Input resource not found: ${b(n.input)}`);let a=M(r,t),s=Sn(a.outputs,n.format);if(!s)throw new p(`Transformation ${b(n.transformation)} declares outputs [${[...a.outputs].join(", ")}], none of which corresponds to format ${b(n.format)}`);let c;try{c=await this.runner.run({transformation:r,instances:[o],allKanonaks:t,repository:this.repository,parser:this.parser,objectParser:this.objectParser,outputFormat:s,...n.omitWrapper!==void 0?{runtimeOverride:{metadataRenames:new Map,omitWrapper:n.omitWrapper}}:{}})}catch(u){throw new p(`Transformation execution failed: ${u.message}`,u)}if(c.length===0)throw new p("Transformation produced no artifacts");return{content:c[0].content,format:n.format,filename:c[0].fileName}}async getCatalog(){return this.cachedCatalog||(this.cachedCatalog=await this.objectParser.parseKanonaks(this.repository)),this.cachedCatalog}};function b(e){return`${e.publisher}/${e.package_}/${e.name}`}function Dn(e){return typeof e.source=="string"?!1:e.source.publisher==="kanonak.org"&&e.source.package_==="core-rdf"&&e.source.name==="Resource"}function wn(e){return e.publisher==="kanonak.org"&&e.package_==="core-rdf"&&e.name==="Resource"}function Sn(e,n){let t=n.name;if(e.has(t))return t;for(let r of e)if(r.startsWith(t+"-")||r===t)return r}var An="kanonak.org/core-rdf/type";function ae(e){let n=En(e),t,r={type:""};for(let o of e.statement){let a=o.predicate?.subject;if(!a)throw new Error(`Expression node ${n} has a statement with no resolved predicate`);if(U(a)===An){if(!(o instanceof w))throw new Error(`Expression node ${n} has a non-reference 'type' statement`);if(t!==void 0)throw new Error(`Expression node ${n} declares more than one type \u2014 a runtime tree node is exactly one operator/literal/leaf class`);t=U(o.object.subject);continue}let s=a.name;if(s in r)throw new Error(`Expression node ${n} declares operand '${s}' more than once`);r[s]=jn(o,n,s)}if(t===void 0)throw new Error(`Expression node ${n} declares no type \u2014 the runtime dispatches on it`);return r.type=t,r}function jn(e,n,t){if(e instanceof $||e instanceof de||e instanceof T||e instanceof B)return e.object;if(e instanceof w)return U(e.object.subject);if(e instanceof me)return ae(e.object);if(e instanceof x)return(e.object??[]).map((r,o)=>{if(r instanceof E)return U(r.subject);if(r instanceof ce)return ae(r);if(r instanceof ue)return r.value;throw new Error(`Expression node ${n}: '${t}'[${o}] is not a serializable list item`)});throw new Error(`Expression node ${n}: operand '${t}' has an unserializable statement kind`)}function En(e){let n=e;return n.name?`'${n.name}'`:"(embedded)"}export{I as CssBackend,xe as DEFAULT_VARIANT,m as DOCAST,Oe as DOCAST_PKG,Le as DOCAST_PUB,K as DynamoDbBackend,le as ExpressionEngineV3,vn as ExpressionEvalErrorV3,L as HtmlBackend,v as JsonBackend,xn as MATH_V1,V as MarkdownFrontmatterBackend,q as ReferenceResolver,p as RenderError,ln as SUPPORTED_FORMATS_V3,O as SvgBackend,Un as TX_V3,Tn as TX_V3_PKG,$n as TX_V3_PUB,Bn as TX_V3_VERSION_MAJOR,R as TomlBackend,oe as TransformationEngine,ve as TransformationLoadErrorV3,h as TransformationRunnerErrorV3,H as TransformationRunnerV3,_ as YamlBackend,Vn as compileExpression,M as compileTransformationV3,Rn as isRawStringV3,X as renderMarkdownToHtml,ae as toExpressionRuntimeTree};
91
+ `),o}};function Ae(e,n){let t=new Map;for(let a of e.entries)t.set(a.key,a);let r=n?.metadataKeys??e.entries.map(a=>a.key),o={};for(let a of r){let s=t.get(a);if(!s)continue;let c=n?.metadataRenames.get(a)??a;o[c]=je(s.value,s.escapeHint)}return{M:o}}function je(e,n){switch(e.kind){case"StructuredMap":return Ae(e);case"StructuredList":return{L:e.items.map(t=>je(t,void 0))};case"StringScalar":return dn(e.stringValue,n??e.escapeHint);case"IntegerScalar":return fn(e.integerValue,n??e.escapeHint)}}function dn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL)){if(e==="true")return{BOOL:!0};if(e==="false")return{BOOL:!1};throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-bool must have the value "true" or "false"; got ${JSON.stringify(e)}.`)}if(n&&C(n,m.ESC_DYNAMODB_NULL))return{NULL:!0};if(n&&C(n,m.ESC_DYNAMODB_NUMBER)){if(e.trim()===""||Number.isNaN(Number(e)))throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-number must hold a numeric literal; got ${JSON.stringify(e)}.`);return{N:e}}return{S:e}}function fn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL))throw new Error(`dynamodb-json backend: esc-dynamodb-bool cannot apply to an IntegerScalar (value ${e}). Use a StringScalar "true"/"false".`);if(n&&C(n,m.ESC_DYNAMODB_NULL))throw new Error(`dynamodb-json backend: esc-dynamodb-null cannot apply to an IntegerScalar (value ${e}). Use a StringScalar hinted esc-dynamodb-null.`);return{N:String(e)}}var ln={"markdown-with-frontmatter":{formatUri:"kanonak.org/transformations/markdown-with-frontmatter",extension:".md"},"plain-markdown":{formatUri:"kanonak.org/transformations/plain-markdown",extension:".md"},toml:{formatUri:"kanonak.org/transformations/toml",extension:".toml"},json:{formatUri:"kanonak.org/transformations/json",extension:".json"},html:{formatUri:"kanonak.org/transformations/html",extension:".html"},svg:{formatUri:"kanonak.org/transformations/svg",extension:".svg"},stylesheet:{formatUri:"kanonak.org/transformations/stylesheet",extension:".css"},yaml:{formatUri:"kanonak.org/transformations/yaml",extension:".yaml"},"dynamodb-json":{formatUri:"kanonak.org/transformations/dynamodb-json",extension:".json"}},h=class extends Error{},H=class{backends=new Map;constructor(){this.register(new V),this.register(new R),this.register(new v),this.register(new L),this.register(new O),this.register(new I),this.register(new _),this.register(new K)}register(n){this.backends.set(n.backendUri,n)}async run(n){let t=n.transformationKanonaks??n.allKanonaks,r=M(n.transformation,t);if(!r.outputs.has(n.outputFormat))throw new h(`Transformation "${r.name}" does not declare output format "${n.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let o=this.findBackend(n.outputFormat);if(!o)throw new h(`No backend registered for OutputFormat "${n.outputFormat}".`);let a=new q(n.repository,n.parser,n.objectParser),s=new le(a,n.allKanonaks,r.fragments);return r.kind==="instance"?this.runInstance(r,n,o,s):this.runSet(r,n,o,s)}async runInstance(n,t,r,o){let a=Ee(t.instances,n.inputPattern.requires),s=$e(a,n.inputPattern.sortBy),c=[];for(let u of s){let f=new Map;f.set("input",u);let l=await o.evaluate(n.rule,f);ee(l,n.name,`input "${u.name}"`);let d=ne(await o.evaluate(n.artifactName,f),n.name,`input "${u.name}"`),g=te(n.overrides.get(t.outputFormat),t.runtimeOverride),k=r.render(l,g);c.push({fileName:d,format:t.outputFormat,content:k,source:{kind:"instance",sourceName:u.name}})}return c}async runSet(n,t,r,o){let a=Ee(t.instances,n.inputPattern.requires),s=$e(a,n.inputPattern.sortBy);return n.partitionBy?this.runSetWithPartition(n,s,t,r,o):this.runSetSingle(n,s,t,r,o)}async runSetSingle(n,t,r,o,a){let s=new Map;s.set("inputs",t);let c=await a.evaluate(n.rule,s);ee(c,n.name,"set");let u=ne(await a.evaluate(n.artifactName,s),n.name,"set"),f=te(n.overrides.get(r.outputFormat),r.runtimeOverride),l=o.render(c,f);return[{fileName:u,format:r.outputFormat,content:l,source:{kind:"set",memberCount:t.length}}]}async runSetWithPartition(n,t,r,o,a){let s=n.partitionBy,c=new Map,u=[];for(let l of t){let d=yn(l,s);if(d==null)continue;let g=kn(d),k=c.get(g);k||(k={keyValue:d,keyDisplay:bn(d),members:[]},c.set(g,k),u.push(g)),k.members.push(l)}let f=[];for(let l of u){let d=c.get(l),g=new Map;g.set("inputs",d.members),g.set("key",d.keyValue);let k=await a.evaluate(n.rule,g);ee(k,n.name,`partition "${d.keyDisplay}"`);let Ue=ne(await a.evaluate(n.artifactName,g),n.name,`partition "${d.keyDisplay}"`),Ve=te(n.overrides.get(r.outputFormat),r.runtimeOverride),Re=o.render(k,Ve);f.push({fileName:Ue,format:r.outputFormat,content:Re,source:{kind:"set",memberCount:d.members.length,partitionKey:d.keyDisplay}})}return f}findBackend(n){let t=ln[n];if(t)return this.backends.get(t.formatUri)}};function Ee(e,n){return n.length===0?e:e.filter(t=>{for(let r of n)if(!gn(t,r))return!1;return!0})}function $e(e,n){if(n.length===0)return e;let t=[...e];return t.sort((r,o)=>{for(let a of n){let s=Te(r,a.byProperty),c=Te(o,a.byProperty),u=pn(s,c,a.order);if(u!==0)return u}return 0}),t}function Te(e,n){for(let t of e.statement){let r=re(t);if(!(!r||!N(r,n))){if(t instanceof $||t instanceof T||t instanceof B)return t.object;if(t instanceof x)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(t instanceof w)throw new h(`Sort property "${n.name}" on instance "${e.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function pn(e,n,t){if(e===void 0&&n===void 0)return 0;if(e===void 0)return t==="ascending"?1:-1;if(n===void 0)return t==="ascending"?-1:1;let r;return typeof e=="number"&&typeof n=="number"?r=e-n:r=String(e).localeCompare(String(n)),t==="ascending"?r:-r}function gn(e,n){for(let t of e.statement){let r=re(t);if(!r||!N(r,n))continue;let o=t.object;if(o!=null&&!(typeof o=="string"&&o.length===0)&&!(Array.isArray(o)&&o.length===0))return!0}return!1}function yn(e,n){for(let t of e.statement){let r=re(t);if(!(!r||!N(r,n))&&(t instanceof $||t instanceof T||t instanceof B||t instanceof w||t instanceof x))return t.object}}function re(e){return e.predicate?.subject}function kn(e){if(e===void 0)return" undef";if(e===null)return" null";if(typeof e=="string")return`s:${e}`;if(typeof e=="number")return`n:${e}`;if(typeof e=="boolean")return`b:${e}`;if(e instanceof E){let n=e.subject;return`r:${n.publisher}/${n.package_}/${n.name}`}if(e instanceof Y){let n=e.name??"";return`k:${e.namespace??""}/${n}`}if(typeof e=="object"&&e!==null&&typeof e.name=="string"&&typeof e.publisher=="string"){let n=e;return`u:${n.publisher}/${n.package_}/${n.name}`}return`o:${JSON.stringify(e,(n,t)=>n==="sourceKey"?void 0:t)}`}function bn(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e instanceof E?e.subject.name:e instanceof Y?e.name??"":typeof e=="object"&&e!==null&&typeof e.name=="string"?e.name:""}function ee(e,n,t){if(typeof e!="object"||e===null||e.kind!=="Document")throw new h(`Transformation "${n}" rule did not yield a Document for ${t}. Got: ${Be(e)}`)}function ne(e,n,t){if(typeof e=="string")return e;if(Array.isArray(e)&&e.every(hn))return e.map(r=>String(r)).join("");throw new h(`Transformation "${n}" artifactName did not yield a string for ${t}. Got: ${Be(e)}`)}function hn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Be(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return`array(${e.length})`;if(typeof e=="object"){let n=e.kind;return n?`object(kind=${n})`:"object"}return typeof e}function te(e,n){if(!e&&!n)return;let t={metadataRenames:n?.metadataRenames??e?.metadataRenames??new Map},r=n?.metadataKeys??e?.metadataKeys;r!==void 0&&(t.metadataKeys=r);let o=n?.trailingNewline??e?.trailingNewline;o!==void 0&&(t.trailingNewline=o);let a=n?.omitWrapper??e?.omitWrapper;return a!==void 0&&(t.omitWrapper=a),t}var p=class extends Error{constructor(t,r){super(t);this.cause=r;this.name="RenderError"}cause},xe={publisher:"kanonak.org",package_:"derivation",name:"default"},oe=class{constructor(n,t=new se,r=new fe){this.repository=n;this.parser=t;this.objectParser=r}repository;parser;objectParser;runner=new H;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async renderViaLook(n){let t=await this.getCatalog(),r=A(t,n.resource);if(!(r instanceof D))throw new p(`Resource not found: ${b(n.resource)}`);let o=new G(t),a;if(n.format.name==="html")a=await o.renderHtml(r);else if(n.format.name==="stylesheet")a=o.renderStylesheet(r);else throw new p(`LookRenderer does not support format ${b(n.format)} \u2014 only formats.html and formats.stylesheet are implemented in v0.1.`);return{content:a,format:n.format,filename:r.name}}async findDerivation(n){let t=await this.getCatalog(),r=A(t,n.resource);if(!(r instanceof D))return;let o=n.variant??xe;return pe(r,n.format,o,t)}async render(n){if(n.format.name==="html"||n.format.name==="stylesheet"){let a=await this.getCatalog(),s=A(a,n.resource);if(s instanceof D){let u=new G(a).findCascadedLook(s);if(u&&!wn(u.sourceClass)){let f=await this.findDerivation(n);if(!f||Dn(f))return this.renderViaLook({resource:n.resource,format:n.format})}}}let t=await this.findDerivation(n);if(!t)throw new p(`No derivation found for ${b(n.resource)} \u2192 format ${b(n.format)}`+(n.variant?` variant ${b(n.variant)}`:""));let r=ie(t.transformation.version),o={transformation:{publisher:t.transformation.publisher,package_:t.transformation.package_,name:t.transformation.name,...r?{version:r}:{}},input:n.resource,format:n.format};return n.omitWrapper!==void 0&&(o.omitWrapper=n.omitWrapper),this.runTransformation(o)}async runTransformation(n){let t=await this.getCatalog(),r=A(t,n.transformation);if(!(r instanceof D))throw new p(`Transformation not found: ${b(n.transformation)}`);let o=A(t,n.input);if(!(o instanceof D))throw new p(`Input resource not found: ${b(n.input)}`);let a=M(r,t),s=Sn(a.outputs,n.format);if(!s)throw new p(`Transformation ${b(n.transformation)} declares outputs [${[...a.outputs].join(", ")}], none of which corresponds to format ${b(n.format)}`);let c;try{c=await this.runner.run({transformation:r,instances:[o],allKanonaks:t,repository:this.repository,parser:this.parser,objectParser:this.objectParser,outputFormat:s,...n.omitWrapper!==void 0?{runtimeOverride:{metadataRenames:new Map,omitWrapper:n.omitWrapper}}:{}})}catch(u){throw new p(`Transformation execution failed: ${u.message}`,u)}if(c.length===0)throw new p("Transformation produced no artifacts");return{content:c[0].content,format:n.format,filename:c[0].fileName}}async getCatalog(){return this.cachedCatalog||(this.cachedCatalog=await this.objectParser.parseKanonaks(this.repository)),this.cachedCatalog}};function b(e){return`${e.publisher}/${e.package_}/${e.name}`}function Dn(e){return typeof e.source=="string"?!1:e.source.publisher==="kanonak.org"&&e.source.package_==="core-rdf"&&e.source.name==="Resource"}function wn(e){return e.publisher==="kanonak.org"&&e.package_==="core-rdf"&&e.name==="Resource"}function Sn(e,n){let t=n.name;if(e.has(t))return t;for(let r of e)if(r.startsWith(t+"-")||r===t)return r}var An="kanonak.org/core-rdf/type";function ae(e){let n=En(e),t,r={type:""};for(let o of e.statement){let a=o.predicate?.subject;if(!a)throw new Error(`Expression node ${n} has a statement with no resolved predicate`);if(U(a)===An){if(!(o instanceof w))throw new Error(`Expression node ${n} has a non-reference 'type' statement`);if(t!==void 0)throw new Error(`Expression node ${n} declares more than one type \u2014 a runtime tree node is exactly one operator/literal/leaf class`);t=U(o.object.subject);continue}let s=a.name;if(s in r)throw new Error(`Expression node ${n} declares operand '${s}' more than once`);r[s]=jn(o,n,s)}if(t===void 0)throw new Error(`Expression node ${n} declares no type \u2014 the runtime dispatches on it`);return r.type=t,r}function jn(e,n,t){if(e instanceof $||e instanceof de||e instanceof T||e instanceof B)return e.object;if(e instanceof w)return U(e.object.subject);if(e instanceof me)return ae(e.object);if(e instanceof x)return(e.object??[]).map((r,o)=>{if(r instanceof E)return U(r.subject);if(r instanceof ce)return ae(r);if(r instanceof ue)return r.value;throw new Error(`Expression node ${n}: '${t}'[${o}] is not a serializable list item`)});throw new Error(`Expression node ${n}: operand '${t}' has an unserializable statement kind`)}function En(e){let n=e;return n.name?`'${n.name}'`:"(embedded)"}export{I as CssBackend,xe as DEFAULT_VARIANT,m as DOCAST,Oe as DOCAST_PKG,Le as DOCAST_PUB,K as DynamoDbBackend,le as ExpressionEngineV3,vn as ExpressionEvalErrorV3,L as HtmlBackend,v as JsonBackend,xn as MATH_V1,V as MarkdownFrontmatterBackend,q as ReferenceResolver,p as RenderError,ln as SUPPORTED_FORMATS_V3,O as SvgBackend,Un as TX_V3,Tn as TX_V3_PKG,$n as TX_V3_PUB,Bn as TX_V3_VERSION_MAJOR,R as TomlBackend,oe as TransformationEngine,ve as TransformationLoadErrorV3,h as TransformationRunnerErrorV3,H as TransformationRunnerV3,_ as YamlBackend,Vn as compileExpression,M as compileTransformationV3,Ln as concatPartWithoutValue,Rn as isRawStringV3,X as renderMarkdownToHtml,ae as toExpressionRuntimeTree};
@@ -81,6 +81,14 @@ export declare class ExpressionEngineV3 {
81
81
  * (e.g. an aggregation over a property that happens to be
82
82
  * single-valued for one instance and multi-valued for another).
83
83
  */
84
+ /**
85
+ * What a PropertyRead reads from. A reference is read through, to the
86
+ * subject it names, as one Traverse step does (typescript#133). A reference
87
+ * that does not resolve, or a source that is not a resource, is an error:
88
+ * reading from either used to yield nothing, which flowed silently into
89
+ * whatever consumed it.
90
+ */
91
+ private propertyReadSource;
84
92
  private evaluateList;
85
93
  /**
86
94
  * Re-run an iterator with reverse iteration order, preserving each
@@ -109,3 +117,10 @@ export declare class ExpressionEngineV3 {
109
117
  */
110
118
  private evaluateReverseIterator;
111
119
  }
120
+ /**
121
+ * The error for a Concat part with no value (typescript#133). Skipping it
122
+ * turned a misauthored expression into a plausible wrong string. A part that
123
+ * may be absent says so: a When with no else adds nothing when its condition
124
+ * is false, and a Fallback supplies a value.
125
+ */
126
+ export declare function concatPartWithoutValue(index: number, part: CompiledExpressionV3): ExpressionEvalErrorV3;
@@ -110,6 +110,14 @@ export interface RawLiteral {
110
110
  * A list item of any other kind is an object-model bug and throws.
111
111
  */
112
112
  export declare function rawValuesOf(kanonak: Kanonak, property: EntityUri): RawPropertyValue[];
113
+ /**
114
+ * The values of a property grouped by the statement that asserts them — the
115
+ * same walk as {@link rawValuesOf}, for a property whose statements are
116
+ * separate assertions rather than one set of values: each `owl:hasKey`
117
+ * statement on a class is its own key (typescript#134), so two keys must not
118
+ * merge into one composite.
119
+ */
120
+ export declare function rawValuesByStatementOf(kanonak: Kanonak, property: EntityUri): RawPropertyValue[][];
113
121
  export declare function hasType(kanonak: Kanonak, target: EntityUri): boolean;
114
122
  /**
115
123
  * Filter a list of parsed kanonaks down to `SubjectKanonak`s whose type
@@ -1,4 +1,4 @@
1
- export { typeReferenceUris, referenceUris, rawValuesOf, uriKey, uriMatches, toCanonicalUrl, hasType, hasProperty, findSubjectsByType, findSubjectByUri, findAllResourcesByCanonicalUri, getDatatypeValue, getStringValue, getReferenceUri, getEmbeddedValue, getListValues, findStatement, } from './UriHelpers.js';
1
+ export { typeReferenceUris, referenceUris, rawValuesOf, rawValuesByStatementOf, uriKey, uriMatches, toCanonicalUrl, hasType, hasProperty, findSubjectsByType, findSubjectByUri, findAllResourcesByCanonicalUri, getDatatypeValue, getStringValue, getReferenceUri, getEmbeddedValue, getListValues, findStatement, } from './UriHelpers.js';
2
2
  export type { EntityUri, CanonicalUriParts, RawPropertyValue, RawLiteral } from './UriHelpers.js';
3
3
  export { valuesOf, subjectAddress } from './PropertyValues.js';
4
4
  export type { PropertyValue } from './PropertyValues.js';
@@ -1 +1 @@
1
- import{A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,J as t,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"../chunk-PC3MYDGL.js";import"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.js";export{t as SingleDocumentRepository,j as findAllResourcesByCanonicalUri,k as findStatement,i as findSubjectByUri,h as findSubjectsByType,m as getDatatypeValue,p as getEmbeddedValue,q as getListValues,o as getReferenceUri,n as getStringValue,l as hasProperty,g as hasType,f as rawValuesOf,e as referenceUris,s as subjectAddress,c as toCanonicalUrl,d as typeReferenceUris,a as uriKey,b as uriMatches,r as valuesOf};
1
+ import{A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,I as t,K as u,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"../chunk-LK5SHY4B.js";import"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.js";export{u as SingleDocumentRepository,k as findAllResourcesByCanonicalUri,l as findStatement,j as findSubjectByUri,i as findSubjectsByType,n as getDatatypeValue,q as getEmbeddedValue,r as getListValues,p as getReferenceUri,o as getStringValue,m as hasProperty,h as hasType,g as rawValuesByStatementOf,f as rawValuesOf,e as referenceUris,t as subjectAddress,c as toCanonicalUrl,d as typeReferenceUris,a as uriKey,b as uriMatches,s as valuesOf};
@@ -1 +1 @@
1
- import{A,B,C,D,E,F,G,H,I,J,K,L,M,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-Q57XCPAQ.js";import"../chunk-A224OOBZ.js";import"../chunk-GXEKJFXG.js";import"../chunk-QHABFCRC.js";import"../chunk-5FVUBF7N.js";import"../chunk-WXXZOJ4O.js";import"../chunk-LKJVNKCN.js";import"../chunk-5ZRVFYCP.js";import"../chunk-PEJALHXK.js";import"../chunk-WXUMROTA.js";import"../chunk-PC3MYDGL.js";import"../chunk-F67UH4FD.js";import"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.js";export{v as AmbiguousReferenceRule,B as ClassDefinitionRule,o as ClassHierarchyCycleRule,L as DiamondNameClashRule,D as DisplayLensScopeRule,l as EmbeddedKanonakTypeRule,m as ImportExistenceRule,M as KanonakObjectValidator,f as LinkTargetRule,H as LookBandPathRule,E as LookSemanticSvgPathRule,C as MarkdownLinkRule,t as NamespaceImportCycleRule,g as NamespacePrefixRule,x as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,K as OwlOneOfRule,k as PackageHeaderRule,y as PropertyDomainRule,p as PropertyHierarchyCycleRule,z as PropertyKindRangeConsistencyRule,w as PropertyRangeReferenceRule,q as PropertyRangeRequiredRule,i as PropertyTypeSpecificityRule,A as ReservedNameShadowRule,h as ResourceNamingRule,G as SequenceNarrativeRule,J as ShaclShapeRule,r as SubClassOfReferenceRule,s as SubPropertyOfReferenceRule,j as SubjectKanonakTypeRequiredRule,F as TxExpressionCompilesRule,I as TxExpressionPathRule,u as UnresolvedPredicateRule,n as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity};
1
+ import{A as y,B as z,C as A,D as B,E as C,F as D,G as E,H as F,I as G,J as H,K as I,L as J,M as K,N as L,O as M,a,b,c,d,e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,r as p,s as q,t as r,u as s,v as t,w as u,x as v,y as w,z as x}from"../chunk-426MUUGB.js";import"../chunk-VJUZKHQU.js";import"../chunk-CPENAANM.js";import"../chunk-QHABFCRC.js";import"../chunk-5FVUBF7N.js";import"../chunk-WXXZOJ4O.js";import"../chunk-SBWD7EOG.js";import"../chunk-5ZRVFYCP.js";import"../chunk-PEJALHXK.js";import"../chunk-6WOPXTIL.js";import"../chunk-LK5SHY4B.js";import"../chunk-F67UH4FD.js";import"../chunk-GGK6A6QK.js";import"../chunk-FUUTGGJS.js";export{v as AmbiguousReferenceRule,B as ClassDefinitionRule,o as ClassHierarchyCycleRule,L as DiamondNameClashRule,D as DisplayLensScopeRule,l as EmbeddedKanonakTypeRule,m as ImportExistenceRule,M as KanonakObjectValidator,f as LinkTargetRule,H as LookBandPathRule,E as LookSemanticSvgPathRule,C as MarkdownLinkRule,t as NamespaceImportCycleRule,g as NamespacePrefixRule,x as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,K as OwlOneOfRule,k as PackageHeaderRule,y as PropertyDomainRule,p as PropertyHierarchyCycleRule,z as PropertyKindRangeConsistencyRule,w as PropertyRangeReferenceRule,q as PropertyRangeRequiredRule,i as PropertyTypeSpecificityRule,A as ReservedNameShadowRule,h as ResourceNamingRule,G as SequenceNarrativeRule,J as ShaclShapeRule,r as SubClassOfReferenceRule,s as SubPropertyOfReferenceRule,j as SubjectKanonakTypeRequiredRule,F as TxExpressionCompilesRule,I as TxExpressionPathRule,u as UnresolvedPredicateRule,n as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "6.5.0",
3
+ "version": "6.7.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",
@@ -135,7 +135,7 @@
135
135
  ],
136
136
  "dependencies": {
137
137
  "@kanonak-protocol/canonical": "^0.1.3",
138
- "@kanonak-protocol/types": "^6.5.0",
138
+ "@kanonak-protocol/types": "^6.7.0",
139
139
  "ignore": "^7.0.5",
140
140
  "js-yaml": "^4.1.0",
141
141
  "yaml": "^2.7.0",
@@ -1 +0,0 @@
1
- import{b as D}from"./chunk-F67UH4FD.js";import{b as y,e as m}from"./chunk-GGK6A6QK.js";function k(t){let e=t.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}function v(t){let e=t.metadata?.namespace_;if(e)return e.version?`${e.publisher}/${e.package_}@${m(e.version)}`:`${e.publisher}/${e.package_}`}async function I(t,e,n={}){let o=new Set,u=new Set,a=[...t];for(;a.length>0;){let s=a.shift(),l=k(s),i=v(s);if(!l||!i||u.has(i))continue;u.add(i),o.add(l),n.onDocument?.(s);let p=s.metadata?.imports;if(p)for(let[g,h]of Object.entries(p))for(let r of h){if(D(r))continue;let c=null,d="no-compatible-version";try{c=await e.getHighestCompatibleVersionAsync(g,r)}catch{d="resolution-error"}c?a.push(c):n.onUnresolvedEdge?.({fromNamespace:i,publisher:g,packageName:r.packageName,constraint:`${y(r.versionOperator)}${m(r.version)}`,reason:d})}}return o}var f=class{constructor(e,n){this.inner=e;this.scope=n}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(n=>{let o=k(n);return o!==void 0&&this.scope.has(o)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,n){return this.inner.getDocumentsByNamespaceAsync(e,n)}getHighestCompatibleVersionAsync(e,n){return this.inner.getHighestCompatibleVersionAsync(e,n)}saveDocumentAsync(e,n){return this.inner.saveDocumentAsync(e,n)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,n){return this.inner.clearNamespaceAsync(e,n)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};export{I as a,f as b};
@@ -1 +0,0 @@
1
- import{c as L,g as D,l as I}from"./chunk-GGK6A6QK.js";import{a as v}from"./chunk-FUUTGGJS.js";var u=class{};var f=class extends u{statement=[];unresolvedPredicates=[];sourceDoc="";sourceKey};var p=class extends f{namespace;name;icon};var k=class extends f{name;rangeType};var s=class e extends u{subject;sourceKey;static parse(n){let t=new e;return t.subject=v.parse(n),t}};var h=class extends u{value;carrier;lexical;links;sourceKey};var c=class{predicate;object;sourceKey};var l=class extends c{carrier;lexical};var y=class e extends l{static parse(n,t){let r=new e;return r.predicate=s.parse(n),r.object=t,r}};var K=class e extends l{static parse(n,t){let r=new e;return r.predicate=s.parse(n),r.object=t,r}};var x=class extends l{};var b=class e extends c{static parse(n,t){let r=new e;return r.predicate=s.parse(n),r.object=s.parse(t),r}};var j=class extends c{};var S=class extends c{};var U=class extends y{links=[]};function R(e){return`${e.publisher}/${e.package_}/${e.name}`}function $(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}function C(e){let n=e.version;return n&&typeof n.major=="number"?`https://${e.publisher}/${e.package_}/${n.major}.${n.minor}.${n.patch}/${e.name}`:`https://${e.publisher}/${e.package_}/${e.name}`}function T(e){return A(e,B)}var B={publisher:"kanonak.org",package_:"core-rdf",name:"type"};function A(e,n){let t=[];for(let r of w(e,n))r.item instanceof s&&t.push(r.item.subject);return t}function w(e,n){if(!(e instanceof f))return[];let t=[];for(let r of e.statement){let a=r.predicate;if(!(!a?.subject||!$(a.subject,n)))if(r instanceof b)t.push({item:r.object,fromList:!1});else if(r instanceof j)t.push({item:r.object,fromList:!1});else if(r instanceof U)t.push({item:{literal:!0,value:r.object,carrier:r.carrier,lexical:r.lexical,links:r.links},fromList:!1});else if(r instanceof y||r instanceof K||r instanceof x)t.push({item:{literal:!0,value:r.object,carrier:r.carrier,lexical:r.lexical},fromList:!1});else if(r instanceof S)for(let o of r.object??[])if(o instanceof s||o instanceof k)t.push({item:o,fromList:!0});else if(o instanceof h)t.push({item:{literal:!0,value:o.value,carrier:o.carrier,lexical:o.lexical,links:o.links},fromList:!0});else throw new Error(`rawValuesOf: a list value of '${n.name}' is a ${o?.constructor?.name??typeof o}; list items are references, embedded values or literals.`);else throw new Error(`rawValuesOf: '${n.name}' has a statement of unknown kind ${r?.constructor?.name??typeof r}.`)}return t}function M(e,n){if(!(e instanceof f))return!1;for(let t of e.statement)if(t.predicate?.subject?.name==="type"&&t instanceof b){let a=t.object;if($(a.subject,n))return!0}return!1}function N(e,n){let t=[];for(let r of e)r instanceof p&&M(r,n)&&t.push(r);return t}function H(e,n){let t=n.version,r=t&&typeof t.major=="number"?`${n.publisher}/${n.package_}@${t.major}.${t.minor}.${t.patch}`:void 0;for(let a of e){if(!(a instanceof p)||a.name!==n.name)continue;let o=a.namespace||"";if(r!==void 0){if(o===r)return a}else if(o.startsWith(`${n.publisher}/${n.package_}@`))return a}}function W(e,n){let t=[];for(let r of e){if(!(r instanceof p)||r.name!==n.name)continue;(r.namespace||"").startsWith(`${n.publisher}/${n.package_}@`)&&t.push(r)}return t.sort((r,a)=>{let o=D((r.namespace||"").split("@")[1]??""),i=D((a.namespace||"").split("@")[1]??"");return o?i?L(i,o):-1:i?1:0}),t}function g(e,n){for(let t of e.statement){let r=t.predicate;if(r?.subject&&$(r.subject,n))return t}}function F(e,n){return g(e,n)!==void 0}function O(e,n){let t=g(e,n);if(t&&(t instanceof y||t instanceof K||t instanceof x))return t.object}function Y(e,n){let t=O(e,n);return typeof t=="string"?t:void 0}function q(e,n){let t=g(e,n);if(t instanceof b)return t.object.subject}function z(e,n){let t=g(e,n);if(t instanceof j)return t.object}function G(e,n){let t=g(e,n);return t instanceof S?t.object??[]:[]}function J(e,n,t,r){let a=X(e,n,r);if(a.length===0)return[];let o=Z(t);return a.map(({value:i,address:m})=>{let d=i.fromList;if(i.item instanceof s){let V=o.resolve(i.item.subject);return V?{kind:"subject",node:V,uri:i.item.subject,address:m,fromList:d}:{kind:"unresolved",uri:i.item.subject,address:m,fromList:d}}if(i.item instanceof k)return{kind:"embedded",node:i.item,address:m,fromList:d};let P={kind:"literal",value:i.item.value,carrier:i.item.carrier,lexical:i.item.lexical,address:m,fromList:d};return i.item.links&&(P.links=i.item.links),P})}function Q(e){let n=I(`${e.namespace}/${e.name}`);if(n.kind!=="resource")throw new Error(`subjectAddress: '${e.namespace}/${e.name}' is not a resource address`);return R(n.uri)}function X(e,n,t){let r=w(e,n);if(r.length===0)return[];let a=t.includes("#")?`${t}.${n.name}`:`${t}#${n.name}`,o=r.length>1||r.some(i=>i.fromList);return r.map((i,m)=>({value:i,address:i.item instanceof k&&i.item.name?`${a}.${i.item.name}`:o?`${a}[${m}]`:a}))}var _=new WeakMap;function Z(e){let n=_.get(e);if(n)return n;let t=new Map,r=new Map;for(let a of e){if(!(a instanceof p))continue;let o=a.namespace||"",i=`${o}\0${a.name}`;t.has(i)||t.set(i,a);let m=o.indexOf("@");if(m>=0){let d=`${o.slice(0,m)}\0${a.name}`;r.has(d)||r.set(d,a)}}return n={resolve(a){let o=a.version;return o&&typeof o.major=="number"?t.get(`${a.publisher}/${a.package_}@${o.major}.${o.minor}.${o.patch}\0${a.name}`):r.get(`${a.publisher}/${a.package_}\0${a.name}`)}},_.set(e,n),n}var E=class{constructor(n,t){this.doc=n;this.broader=t}doc;broader;async getAllDocumentsAsync(){return[this.doc]}async getDocumentAsync(n){return this.broader.getDocumentAsync(n)}async getDocumentsByNamespaceAsync(n,t){return this.broader.getDocumentsByNamespaceAsync(n,t)}async getHighestCompatibleVersionAsync(n,t){return this.broader.getHighestCompatibleVersionAsync(n,t)}async saveDocumentAsync(){throw new Error("SingleDocumentRepository is read-only")}async deleteDocumentAsync(){throw new Error("SingleDocumentRepository is read-only")}async clearNamespaceAsync(){throw new Error("SingleDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(n){return this.broader.getDocumentContentAsync(n)}async getDocumentUriAsync(n){return this.broader.getDocumentUriAsync(n)}};export{u as a,f as b,p as c,k as d,s as e,h as f,c as g,l as h,y as i,K as j,x as k,b as l,j as m,S as n,U as o,R as p,$ as q,C as r,T as s,A as t,w as u,M as v,N as w,H as x,W as y,g as z,F as A,O as B,Y as C,q as D,z as E,G as F,J as G,Q as H,X as I,E as J};
@@ -1 +0,0 @@
1
- import{C as L,D as Q,c as G,d as X,p as S,q as Y,s as q,t as I,x as W,y as v}from"./chunk-PC3MYDGL.js";import{b as H}from"./chunk-F67UH4FD.js";import{l as B}from"./chunk-GGK6A6QK.js";import{a as x}from"./chunk-FUUTGGJS.js";var z=class{cache=new Map;repository;logger;constructor(e,n){this.repository=e,this.logger=n}async resolveEntityAsync(e,n){let o=n.metadata?.namespace_?.toString()??"unknown",s=this.cache.get(o);if(s){let i=s.get(e);if(i)return i}let a=await this.buildEntityIndexAsyncInternal(n,new Set,"",new Map);return this.cache.set(o,a),a.get(e)??null}async resolveAllEntitiesAsync(e,n){let o=await this.buildAllEntitiesIndexAsync(n,new Set,"");if(e.includes(".")){let s=e.split("."),a=s[0],i=s[1],y=await this.findDocumentForAlias(n,a);return y?await this.resolveAllEntitiesAsync(i,y):[]}return o.filter(s=>s.entityName===e)}async buildAllEntitiesIndexAsync(e,n,o){let s=[],a=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${a}`),n.has(a))return this.logger?.debug?.(`Skipping ${a} - already visited (circular import prevention)`),s;n.add(a);let i=o.length===0?a:`${o} \u2192 ${a}`;for(let[y,l]of Object.entries(e.body))if(!y.includes(".")&&l&&typeof l=="object"&&!Array.isArray(l)){if(!e.metadata.namespace_)continue;let g=e.metadata.namespace_.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};s.push({entityName:y,uri:new x(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,y,g),entity:l,definedInNamespace:a,isImported:o.length>0,importPath:i})}if(this.logger?.debug?.(`Collected ${s.length} entities from ${a}`),e.metadata?.imports){let y=Object.values(e.metadata.imports).reduce((l,g)=>l+g.length,0);this.logger?.debug?.(`Processing ${y} import(s) for ${a}`);for(let[l,g]of Object.entries(e.metadata.imports))for(let d of g)if(!H(d))try{this.logger?.debug?.(`Resolving import: ${l}/${d.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(l,d);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let k=await this.buildAllEntitiesIndexAsync(m,n,i);s.push(...k),this.logger?.debug?.(`Added ${k.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${l}/${d.packageName}`)}catch(m){let k=m;throw this.logger?.error?.(`Failed to process import ${l}/${d.packageName} for namespace ${a}. Error: ${k.message}`,k),new Error(`Failed to process import ${l}/${d.packageName} for namespace ${a}. See inner exception for details.`,{cause:m})}}return s}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"",new Map)}async buildEntityIndexAsyncInternal(e,n,o,s){let a=new Map,i=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${i}`),n.has(i))return this.logger?.debug?.(`Skipping ${i} - circular import in progress`),a;let y=s.get(i);if(y)return y;n.add(i);let l=o.length===0?i:`${o} \u2192 ${i}`,g=0;for(let[d,m]of Object.entries(e.body))if(!d.includes(".")&&m&&typeof m=="object"&&!Array.isArray(m)){if(!e.metadata.namespace_)continue;if(!a.has(d)){let k=e.metadata.namespace_.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.set(d,{entityName:d,uri:new x(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,d,k),entity:m,definedInNamespace:i,isImported:o.length>0,importPath:l}),g++}}if(this.logger?.debug?.(`Indexed ${g} entities from ${i}`),e.metadata?.imports){let d=Object.values(e.metadata.imports).reduce((m,k)=>m+k.length,0);this.logger?.debug?.(`Processing ${d} import(s) for ${i}`);for(let[m,k]of Object.entries(e.metadata.imports))for(let b of k)if(!H(b))try{this.logger?.debug?.(`Resolving import: ${m}/${b.packageName}`);let h=await this.repository.getHighestCompatibleVersionAsync(m,b);if(h){this.logger?.debug?.(`Successfully loaded import: ${h.metadata?.namespace_?.toString()}`);let U=await this.buildEntityIndexAsyncInternal(h,n,l,s),M=0;for(let[A,P]of U.entries()){let _=a.get(A);if(!_)a.set(A,P),M++;else if(_.isImported&&P.isImported&&(_.uri.publisher!==P.uri.publisher||_.uri.package_!==P.uri.package_)){let C=_.isAmbiguous?_:{..._,isAmbiguous:!0,ambiguousNamespaces:[_.definedInNamespace]};C.ambiguousNamespaces.includes(P.definedInNamespace)||C.ambiguousNamespaces.push(P.definedInNamespace),a.set(A,C),this.logger?.warn?.(`Ambiguous reference '${A}': defined in ${C.ambiguousNamespaces.join(", ")}`)}if(b.alias&&!A.includes(".")){let C=`${b.alias}.${A}`;a.has(C)||(a.set(C,P),M++)}}this.logger?.debug?.(`Merged ${M} entities from import ${h.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${m}/${b.packageName}`)}catch(h){let U=h;throw this.logger?.error?.(`Failed to process import ${m}/${b.packageName} for namespace ${i}. Error: ${U.message}`,U),new Error(`Failed to process import ${m}/${b.packageName} for namespace ${i}. See inner exception for details.`,{cause:h})}}return n.delete(i),s.set(i,a),a}async findDocumentForAlias(e,n){if(!e.metadata?.imports)return null;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s)if(!H(a)){if(a.alias===n)return await this.repository.getHighestCompatibleVersionAsync(o,a);if(!a.alias&&a.packageName===n)return await this.repository.getHighestCompatibleVersionAsync(o,a)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}};var J=class t{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-xsd"&&t.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-rdf"&&e.name==="Literal":!1}isMarkdownDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-prose"&&e.name==="Markdown":!1}isSubstitutableDatatype(e){return t.isSubstitutableDatatypeUri(e)}static isSubstitutableDatatypeUri(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-prose"&&(e.name==="SubstitutableString"||e.name==="Markdown"):!1}isKnownXsdDatatypeName(e){let n=e.includes(".")?e.split(".")[1]:e;return t.KNOWN_XSD_DATATYPES.has(n.toLowerCase())}async isClassTypeAsync(e,n){if(this.isKnownXsdDatatypeName(e))return!1;let o=await this.resourceResolver.resolveEntityAsync(e,n);if(o){let s=o.entity.type;if(s){let a=String(s);return a==="Class"||a==="rdfs.Class"||a.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,n){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(n)||e==="Property"&&this.isLiteralType(n))}isEffectiveObjectProperty(e,n){return!!(e==="ObjectProperty"||e==="Property"&&n&&!this.isXsdDatatype(n)&&!this.isLiteralType(n))}};function Ue(t){return`${t.publisher}/${t.package_}/${t.name}`}function u(t,e,n){return`${t}/${e}/${n}`}function He(t){return`${t.s}|${t.p}|${ae(t.o)}`}function ae(t){switch(t.kind){case"uri":return`u:${t.key}`;case"literal":return`l:${t.datatype}:${t.lexical}`;case"blank":return`b:${t.id}`}}function Ie(t,e,n){return{s:t,p:e,o:{kind:"uri",key:n}}}var se="kanonak.org",ie="core-shacl",r=t=>({publisher:se,package_:ie,name:t}),D=r("Shape"),N=r("NodeShape"),T=r("PropertyShape"),Ne=r("targetClass"),Te=r("property"),je=r("path"),$e=r("minCount"),Me=r("maxCount"),ve=r("datatype"),Le=r("class"),we=r("in"),Ve=r("pattern"),Fe=r("flags"),Be=r("minLength"),Ge=r("maxLength"),Xe=r("minInclusive"),Ye=r("maxInclusive"),qe=r("message"),We=r("targetNode"),Qe=r("targetSubjectsOf"),ze=r("targetObjectsOf"),Je=r("closed"),Ze=r("ignoredProperties"),et=r("nodeKind"),tt=r("IRI"),nt=r("BlankNode"),rt=r("Literal"),ot=r("severity"),at=r("Violation"),st=r("Warning"),it=r("Info"),pt=r("ValidationReport"),ct=r("conforms"),lt=r("result"),ut=r("ValidationResult"),yt=r("focusNode"),mt=r("resultPath"),dt=r("resultMessage"),gt=r("resultSeverity"),ft=r("sourceShape"),kt=r("value"),St=r("sourceConstraintComponent"),bt=r("MinCountConstraintComponent"),_t=r("MaxCountConstraintComponent"),ht=r("DatatypeConstraintComponent"),Pt=r("ClassConstraintComponent"),Ct=r("InConstraintComponent"),Kt=r("PatternConstraintComponent"),Et=r("MinLengthConstraintComponent"),At=r("MaxLengthConstraintComponent"),xt=r("MinInclusiveConstraintComponent"),Rt=r("MaxInclusiveConstraintComponent"),Ot=r("NodeKindConstraintComponent"),Ut=r("ClosedConstraintComponent"),Ht=r("hasValue"),It=r("qualifiedValueShape"),Dt=r("qualifiedMinCount"),Nt=r("qualifiedMaxCount"),Tt=r("HasValueConstraintComponent"),jt=r("QualifiedMinCountConstraintComponent"),$t=r("QualifiedMaxCountConstraintComponent");var p="kanonak.org",c="core-rdf",f="core-owl",ee="core-kanonak",j=new Map([["type",c],["subClassOf",c],["subPropertyOf",c],["domain",c],["range",c],["label",c],["comment",c],["seeAlso",c],["isDefinedBy",c],["member",c],["Resource",c],["Class",c],["Property",c],["Datatype",c],["Literal",c],["List",c],["ObjectProperty",f],["DatatypeProperty",f],["AnnotationProperty",f],["Thing",f],["Nothing",f],["Package",ee]]),pe=new Set(["type","subClassOf","subPropertyOf","domain","range"]);function wt(t){return j.has(t)}function ce(t){let e=j.get(t);return e?{publisher:p,package_:e}:void 0}function Vt(){return[...new Set(j.values())].map(t=>({publisher:p,package_:t}))}function Ft(t){let e=ce(t);if(!e)throw new Error(`builtinUri: '${t}' is not a reserved built-in term.`);return{...e,name:t}}function V(t,e,n){if(!t||!t.name)return;let o=j.get(t.name);if(!o)return;let s=()=>{t.publisher=p,t.package_=o,n&&(t.version=n.get(o))};if(pe.has(t.name)){let a=t.publisher===p&&t.package_===o;t.publisher=p,t.package_=o,!a&&n&&(t.version=n.get(o));return}t.publisher===p&&t.package_===o||t.publisher&&t.publisher.length>0&&(!e||e(t))||s()}var Z=class{type=u(p,c,"type");subClassOf=u(p,c,"subClassOf");subPropertyOf=u(p,c,"subPropertyOf");domain=u(p,c,"domain");range=u(p,c,"range");label=u(p,c,"label");comment=u(p,c,"comment");resource=u(p,c,"Resource");class_=u(p,c,"Class");datatype=u(p,c,"Datatype");literal=u(p,c,"Literal");equivalentClass=u(p,f,"equivalentClass");equivalentProperty=u(p,f,"equivalentProperty");inverseOf=u(p,f,"inverseOf");sameAs=u(p,f,"sameAs");transitiveProperty=u(p,f,"TransitiveProperty");symmetricProperty=u(p,f,"SymmetricProperty");objectProperty=u(p,f,"ObjectProperty");datatypeProperty=u(p,f,"DatatypeProperty");annotationProperty=u(p,f,"AnnotationProperty");package_=u(p,ee,"Package");shape=w(D);nodeShape=w(N);propertyShape=w(T)};function w(t){return u(t.publisher,t.package_,t.name)}var le=new Set(["kanonak.org/core-rdf","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]);function R(t){let e=t;if(e.entity&&typeof e.entity=="object"){let n=e.entity.type;if(typeof n=="string"){let s={publisher:"",package_:"",name:n.includes(".")?n.substring(n.lastIndexOf(".")+1):n};return V(s),{publisher:s.publisher,package_:s.package_,name:s.name}}}return ne(t)[0]??null}function ne(t){let e=t;if(e.entity&&typeof e.entity=="object"){let n=R(t);return n?[n]:[]}return Array.isArray(e.statement)?q(t).map(n=>{let o={publisher:n.publisher??"",package_:n.package_??"",name:n.name};return V(o),{publisher:o.publisher,package_:o.package_,name:o.name}}):[]}var ue=[D,N,T];function O(t,e){return le.has(`${t}/${e}`)}var ye=new Set(["Property","ObjectProperty","DatatypeProperty","AnnotationProperty"]);function F(t){if(O(t.publisher,t.package_))return ye.has(t.name)?t.name:void 0}var te=class t{static getTypeUri(e){return R(e)}static isCoreOntologyType(e){return O(e.publisher,e.package_)}static hasCoreType(e,n){return ne(e).some(o=>O(o.publisher,o.package_)&&o.name===n)}static isClassType(e){return t.hasCoreType(e,"Class")}static isDatatypeType(e){return t.hasCoreType(e,"Datatype")}static isDatatypePropertyType(e){return t.hasCoreType(e,"DatatypeProperty")}static isObjectPropertyType(e){return t.hasCoreType(e,"ObjectProperty")}static isAnnotationPropertyType(e){return t.hasCoreType(e,"AnnotationProperty")}static isGenericPropertyType(e){return t.hasCoreType(e,"Property")}static isAnyPropertyType(e){let n=R(e);return!n||!O(n.publisher,n.package_)?!1:n.name==="Property"||n.name==="DatatypeProperty"||n.name==="ObjectProperty"||n.name==="AnnotationProperty"}static isShapeType(e){let n=R(e);return n?ue.some(o=>Y(n,o)):!1}static isSchemaDefinitionType(e){if(t.isShapeType(e))return!0;let n=R(e);return!n||!O(n.publisher,n.package_)?!1:n.name==="Class"||n.name==="Property"||n.name==="DatatypeProperty"||n.name==="ObjectProperty"||n.name==="AnnotationProperty"||n.name==="Datatype"}static isInstanceOfKnownClass(e,n){if(t.isSchemaDefinitionType(e))return!1;let o=R(e);return o?n.has(o.name):!1}};var K="kanonak.org",E="core-rdf",me={publisher:K,package_:E,name:"domain"},de={publisher:K,package_:E,name:"range"},ge={publisher:K,package_:E,name:"subClassOf"},fe={publisher:K,package_:E,name:"type"},ke={publisher:K,package_:E,name:"label"},Se={publisher:K,package_:E,name:"comment"},be=new x(K,E,"Resource");function _e(t){try{let e=B(`${t.namespace}/${t.name}`);return e.kind==="resource"?e.uri:void 0}catch{return}}function oe(t,e){let n=[],o=new Set,s="version"in e?e.version:void 0,a=[new x(e.publisher,e.package_,e.name,s??void 0)];for(;a.length>0;){let i=a.shift(),y=S(i);if(o.has(y))continue;o.add(y),n.push(i);let l=he(t,i);l&&a.push(...I(l,ge))}return n}function he(t,e){return e.version&&typeof e.version.major=="number"?W(t,e)??v(t,e)[0]:v(t,e)[0]}function $(t,e){let n;for(let o of Ee(e)){let s=Pe(t,o);if(s){if(s!=="Property")return s;n??=s}}return n}function Pe(t,e){let n=F(e);if(n)return n;let o=re.get(t);o||(o=new Map,re.set(t,o));let s=e.version,a=s&&typeof s.major=="number"?`${S(e)}@${s.major}.${s.minor}.${s.patch}`:S(e),i=o.get(a);if(i!==void 0)return i??void 0;let y;for(let l of oe(t,e)){let g=F(l);if(g){if(g!=="Property"){y=g;break}y??="Property"}}return o.set(a,y??null),y}var re=new WeakMap;function nn(t,e){return $(t,e)!==void 0}function rn(t,e){return $(t,e)==="ObjectProperty"}function on(t,e){return $(t,e)==="DatatypeProperty"}function Ce(t,e){let n=new Set([S(be)]);for(let o of oe(t,e))n.add(S(o));return n}function Ke(t,e){let n=Ce(t,e),o=[],s=new Set;for(let a of t){if(!(a instanceof G))continue;let i=$(t,a);if(!i)continue;let y=I(a,me);if(!y.some(d=>n.has(S(d))))continue;let l=_e(a);if(!l)continue;let g=S(l);s.has(g)||(s.add(g),o.push({uri:l,label:L(a,ke),comment:L(a,Se),kind:i==="ObjectProperty"?"object":i==="DatatypeProperty"?"datatype":"other",range:Q(a,de),domains:y}))}return o}function an(t,e,n){let o=Ke(t,e).find(s=>S(s.uri)===S(n));return o?{ok:!0,descriptor:o}:{ok:!1,message:`Property ${n.publisher}/${n.package_}/${n.name} is not in scope for ${e.publisher}/${e.package_}/${e.name}.`}}function Ee(t){let e=I(t,fe);return e.length>0?e:t instanceof X&&t.rangeType?[t.rangeType]:[]}export{z as a,J as b,Ue as c,u as d,He as e,ae as f,Ie as g,se as h,ie as i,D as j,N as k,T as l,Ne as m,Te as n,je as o,$e as p,Me as q,ve as r,Le as s,we as t,Ve as u,Fe as v,Be as w,Ge as x,Xe as y,Ye as z,qe as A,We as B,Qe as C,ze as D,Je as E,Ze as F,et as G,tt as H,nt as I,rt as J,ot as K,at as L,st as M,it as N,bt as O,_t as P,ht as Q,Pt as R,Ct as S,Kt as T,Et as U,At as V,xt as W,Rt as X,Ot as Y,Ut as Z,Ht as _,It as $,Dt as aa,Nt as ba,Tt as ca,jt as da,$t as ea,wt as fa,ce as ga,Vt as ha,Ft as ia,V as ja,Z as ka,F as la,te as ma,_e as na,oe as oa,$ as pa,nn as qa,rn as ra,on as sa,Ke as ta,an as ua,Ee as va};