@kanonak-protocol/sdk 2.1.0 → 2.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,3 +1,19 @@
1
1
  import { DefinedKanonak } from './DefinedKanonak.js';
2
2
  export declare class EmbeddedKanonak extends DefinedKanonak {
3
+ /**
4
+ * Optional source label for this embedded kanonak. Populated when
5
+ * the embedded was authored as the value of a dict-keyed list entry
6
+ * — e.g. `hasConvention: { file-location: { ... } }` produces an
7
+ * EmbeddedKanonak with `name = "file-location"`. Empty for embeddeds
8
+ * authored as positional list items (`- ...`) or as the single
9
+ * value of a property (`hasConvention: { summary: ... }`).
10
+ *
11
+ * Carries no semantic identity — the dict key isn't a URI, isn't
12
+ * resolved against imports, and isn't part of any RDF triple. It's
13
+ * purely a presentation hint for human-facing tools (Outline, tree
14
+ * views, error messages) so the dict-keyed authoring form doesn't
15
+ * lose its author-given labels when the parser flattens the dict
16
+ * into a positional list of anonymous embeddeds.
17
+ */
18
+ name?: string;
3
19
  }
@@ -0,0 +1,14 @@
1
+ export interface LockEntry {
2
+ version: string;
3
+ resolved: string;
4
+ integrity: string;
5
+ dependencies: Record<string, string>;
6
+ }
7
+ export interface LockFile {
8
+ version: string;
9
+ lastUpdated: string;
10
+ packages: Record<string, LockEntry>;
11
+ }
12
+ export declare function loadLockFile(path?: string): LockFile | null;
13
+ export declare function saveLockFile(lock: LockFile, path?: string): void;
14
+ export declare function computeIntegrity(content: string): string;
@@ -0,0 +1,2 @@
1
+ export { loadLockFile, saveLockFile, computeIntegrity, } from './LockFile.js';
2
+ export type { LockFile, LockEntry } from './LockFile.js';
@@ -0,0 +1,244 @@
1
+ /**
2
+ * One entry in an entity's `imports:` block, paired with the source
3
+ * position of its `package:` value. Used by the VS Code extension's
4
+ * DocumentLinkProvider to make each import line a Ctrl-clickable
5
+ * link to the imported package's file.
6
+ */
7
+ export interface ImportPackageEntry {
8
+ /** `publisher` from the outer import block (`publisher: kanonak.org`). */
9
+ publisher: string;
10
+ /** `package: <name>` of this entry. */
11
+ package_: string;
12
+ /** `version: <x.y.z>` of this entry, if present (empty string otherwise). */
13
+ version: string;
14
+ /** `alias: <prefix>` of this entry, if present. */
15
+ alias?: string;
16
+ /**
17
+ * Source range of the `<name>` token after `package:` — i.e. just
18
+ * the scalar value, not including the `package:` key. Diagnostic
19
+ * and click-target friendly.
20
+ */
21
+ position: SourcePosition;
22
+ }
23
+ /**
24
+ * A source-position range within a `.kan.yml` document.
25
+ *
26
+ * All values are **0-indexed**, matching VS Code's `Position`/`Range`
27
+ * conventions. The yaml package's `LineCounter` is 1-indexed; the
28
+ * conversion happens inside `KanonakDocumentPositions` so callers
29
+ * never see the off-by-one.
30
+ *
31
+ * Range semantics: half-open. `endLine`/`endColumn` point one past
32
+ * the last character that belongs to the node. A single-line key
33
+ * `MyClass:` at line 5 col 0 of length 8 (excluding the colon) has
34
+ * `line=4, column=0, endLine=4, endColumn=7`.
35
+ */
36
+ export interface SourcePosition {
37
+ line: number;
38
+ column: number;
39
+ endLine: number;
40
+ endColumn: number;
41
+ }
42
+ /**
43
+ * Position lookup over a parsed Kanonak document. Built by walking
44
+ * the `yaml` package's CST in parallel with the SDK's existing
45
+ * js-yaml-based `KanonakParser`. The two parsers operate on the same
46
+ * source bytes and produce consistent positions for any well-formed
47
+ * Kanonak YAML — they're both YAML 1.1/1.2 compliant.
48
+ *
49
+ * Three lookup levels, mirroring the structure of a Kanonak document:
50
+ *
51
+ * 1. **Entity** — the top-level key in `body` (e.g. `MyClass:`).
52
+ * The position covers the key itself (where to underline a
53
+ * "this entity has issue X" diagnostic).
54
+ * 2. **Property** — a nested key under an entity (e.g.
55
+ * `subClassOf:`). Position covers the property's key.
56
+ * 3. **Value** — a specific value within a property. For scalar
57
+ * values, the value's range. For list values, the indexed
58
+ * list-item's range.
59
+ *
60
+ * Callers fall back from value → property → entity → undefined as
61
+ * specificity decreases. The diagnostic provider in the VS Code
62
+ * extension uses this fall-through to land at the most precise
63
+ * available position for each `OntologyValidationError`.
64
+ */
65
+ export declare class KanonakDocumentPositions {
66
+ private readonly entities;
67
+ /**
68
+ * entity name → range covering the entity's whole block (key plus
69
+ * value, including nested properties). Used by reverse-lookup
70
+ * helpers to answer "what entity is the cursor inside?" — the
71
+ * foundation for symbol-intelligence providers (DefinitionProvider,
72
+ * HoverProvider, etc.).
73
+ */
74
+ private readonly entityBlocks;
75
+ /** entity name → property name → position of property key. */
76
+ private readonly properties;
77
+ /** entity name → property name → position of property value (scalar or full sequence). */
78
+ private readonly propertyValues;
79
+ /** entity name → property name → array of per-list-item positions (for list-valued properties). */
80
+ private readonly valueListItems;
81
+ /** entity name → list of import-package entries with source positions. */
82
+ private readonly importPackages;
83
+ /**
84
+ * Path-keyed positions for ARBITRARILY nested keys/values. Built by
85
+ * a recursive YAML CST walk that records, at every depth, the
86
+ * position of each map key and the position of each map/sequence
87
+ * value. The path is a `(string | number)[]` — string segments for
88
+ * dict keys, number segments for sequence indices — serialized as
89
+ * JSON for use as a Map key.
90
+ *
91
+ * Example for `foo: { bar: { baz: x } }`:
92
+ * - nestedKeys[`["foo","bar","baz"]`] = position of `baz:` token
93
+ * - nestedValues[`["foo","bar","baz"]`] = position of `x`
94
+ *
95
+ * Example for `foo: [{a: 1}, {b: 2}]`:
96
+ * - nestedValues[`["foo",0]`] = position of `{a: 1}` block
97
+ * - nestedKeys[`["foo",0,"a"]`] = position of `a:` token
98
+ * - nestedValues[`["foo",0,"a"]`] = position of `1`
99
+ *
100
+ * Used by symbol-intelligence providers (Outline) that need to
101
+ * navigate to a precise location within a deeply-nested embedded
102
+ * value. The shallower entity-level / property-level / list-item
103
+ * maps above continue to back the existing single-level lookups
104
+ * for backward compatibility and call-site clarity.
105
+ */
106
+ private readonly nestedKeys;
107
+ private readonly nestedValues;
108
+ /**
109
+ * Parse `content` as YAML and build the position index.
110
+ *
111
+ * If the document fails to parse via the yaml package, returns an
112
+ * empty index. Callers fall through to file-scope ranges. This is
113
+ * not a fallback that masks failure — empty positions is the
114
+ * factual answer to "where is X in this document?" when the
115
+ * document isn't parseable. Diagnostics produced for the same
116
+ * document via the SDK's `KanonakParser` will surface the parse
117
+ * error itself; the position index doesn't need to duplicate that.
118
+ */
119
+ static fromContent(content: string): KanonakDocumentPositions;
120
+ /**
121
+ * Position of the entity's top-level key (e.g. the colon-key
122
+ * `MyClass:` at the start of its block).
123
+ */
124
+ getEntityPosition(entityName: string): SourcePosition | undefined;
125
+ /**
126
+ * Position spanning the entire entity block — its key plus all its
127
+ * property declarations and values, up to (but not including) the
128
+ * next top-level entity. Use for "is the cursor inside this entity?"
129
+ * style lookups.
130
+ */
131
+ getEntityBlockPosition(entityName: string): SourcePosition | undefined;
132
+ /**
133
+ * The entity name whose block range contains the given position,
134
+ * or `undefined` if the position falls outside every entity block
135
+ * (e.g. blank lines between entities).
136
+ */
137
+ findEntityAtPosition(line: number, column: number): string | undefined;
138
+ /**
139
+ * The (entityName, propertyName) pair whose property-value range
140
+ * (or, failing that, property-key range) contains the position.
141
+ * Returns `undefined` for either field that isn't matched, e.g.
142
+ * a position inside an entity but on a blank line returns the
143
+ * entity name only.
144
+ */
145
+ findPropertyAtPosition(line: number, column: number): {
146
+ entityName: string;
147
+ propertyName?: string;
148
+ } | undefined;
149
+ /**
150
+ * Position of a property's key within an entity (e.g. the
151
+ * `subClassOf:` token within `MyClass:`).
152
+ */
153
+ getPropertyPosition(entityName: string, propertyName: string): SourcePosition | undefined;
154
+ /**
155
+ * Position of a property's value (the scalar or the full
156
+ * sequence/map after the `propertyName:` token).
157
+ */
158
+ getPropertyValuePosition(entityName: string, propertyName: string): SourcePosition | undefined;
159
+ /**
160
+ * Imports declared by the entity's `imports:` block, each with the
161
+ * source position of its `package:` token. Empty array when the
162
+ * entity has no imports (e.g., it's not a Package). Used by the
163
+ * extension's DocumentLinkProvider to make import lines
164
+ * Ctrl-clickable links to the imported package's file.
165
+ */
166
+ getImportPackages(entityName: string): ImportPackageEntry[];
167
+ /**
168
+ * All import-package entries across every entity in the document.
169
+ * Convenience for callers that want to iterate every clickable
170
+ * import without first knowing which entity is the Package.
171
+ */
172
+ getAllImportPackages(): Array<{
173
+ entityName: string;
174
+ entry: ImportPackageEntry;
175
+ }>;
176
+ /**
177
+ * Resolve the source-name key for a property by its **bare** local
178
+ * name — i.e., the segment after the last dot in an aliased form.
179
+ * Returns the actual source key as authored (`subClassOf` or
180
+ * `rdfs.subClassOf`) so callers can use it for downstream
181
+ * `getPropertyValuePosition` / `getListItemPosition` lookups.
182
+ *
183
+ * `subClassOf:` source → `findPropertySourceName(entity, 'subClassOf')`
184
+ * returns `'subClassOf'`.
185
+ *
186
+ * `rdfs.subClassOf:` source → same call returns `'rdfs.subClassOf'`.
187
+ *
188
+ * Used by reference-style providers that work from resolved
189
+ * predicate URIs (which only carry the bare local name) and need
190
+ * to find the corresponding position-index entry regardless of
191
+ * whether the author wrote the property with or without an alias
192
+ * prefix.
193
+ */
194
+ findPropertySourceName(entityName: string, bareName: string): string | undefined;
195
+ /**
196
+ * Position of a specific list item within a list-valued property,
197
+ * or `undefined` if the property is not a sequence or the index
198
+ * is out of range. Use this for diagnostics that point at a
199
+ * particular bad entry inside a list (e.g. one bad URI in a
200
+ * `subClassOf: [GoodA, BadB, GoodC]` list).
201
+ */
202
+ getListItemPosition(entityName: string, propertyName: string, listIndex: number): SourcePosition | undefined;
203
+ /**
204
+ * Position of the KEY at an arbitrary nested path. The path is a
205
+ * `(string | number)[]` — string for dict keys, number for sequence
206
+ * indices. For path `[entity, property, key]`, returns the position
207
+ * of `key:` within `entity.property`. For path `[entity]`, returns
208
+ * the entity's key (same as `getEntityPosition`).
209
+ *
210
+ * Sequence items don't have a "key" — for path that ends in a
211
+ * number, returns `undefined` (use `getNodeValuePosition` instead).
212
+ *
213
+ * Returns `undefined` when the path doesn't resolve to a key in the
214
+ * source document (e.g. statement was synthesized by the SDK rather
215
+ * than authored, or the path is malformed).
216
+ */
217
+ getNodeKeyPosition(path: ReadonlyArray<string | number>): SourcePosition | undefined;
218
+ /**
219
+ * Position of the VALUE at an arbitrary nested path. For map values,
220
+ * the value's range (e.g. the inner block of an embedded object).
221
+ * For sequence items, the item's range (same as
222
+ * `getListItemPosition` for top-level list items, but works at any
223
+ * depth). For path `[entity]`, returns the entity's body range
224
+ * (the value after the entity's `:`); for path `[entity, prop]`,
225
+ * the property's value range (same as `getPropertyValuePosition`).
226
+ */
227
+ getNodeValuePosition(path: ReadonlyArray<string | number>): SourcePosition | undefined;
228
+ /**
229
+ * Internal: setters used by the recursive walker. Public-on-the-
230
+ * class but not part of the documented API — exposed only because
231
+ * the walker is a free function (operates on the yaml CST directly,
232
+ * which the class itself doesn't import beyond `fromContent`'s
233
+ * scope).
234
+ */
235
+ setNestedKeyPosition(pathKey: string, pos: SourcePosition): void;
236
+ setNestedValuePosition(pathKey: string, pos: SourcePosition): void;
237
+ /**
238
+ * Most-specific available position for a diagnostic, falling
239
+ * through from list-item → property-value → property-key → entity.
240
+ * Returns `undefined` only when none of those are available, in
241
+ * which case the caller should use a file-scope range.
242
+ */
243
+ getMostSpecificPosition(entityName?: string, propertyName?: string, listIndex?: number): SourcePosition | undefined;
244
+ }
@@ -2,5 +2,9 @@ export { KanonakParser } from './KanonakParser.js';
2
2
  export { KanonakObjectParser } from './KanonakObjectParser.js';
3
3
  export type { IKanonakObjectParser } from './IKanonakObjectParser.js';
4
4
  export { PropertyMetadata } from './PropertyMetadata.js';
5
+ export { KanonakDocumentPositions } from './KanonakDocumentPositions.js';
6
+ export type { SourcePosition, ImportPackageEntry } from './KanonakDocumentPositions.js';
7
+ export { parseWithPositions } from './parseWithPositions.js';
8
+ export type { ParsedDocumentWithPositions } from './parseWithPositions.js';
5
9
  export type { IKanonakParser } from '@kanonak-protocol/types/document/parsing';
6
10
  export type { KanonakDocument, KanonakMetadata, Namespace, Import, Version, ParseResult, ParseError } from '@kanonak-protocol/types/document/models/types';
@@ -1 +1 @@
1
- var q=Object.defineProperty;var H=(u,e)=>()=>(u&&(e=u(u=0)),e);var U=(u,e)=>{for(var t in e)q(u,t,{get:e[t],enumerable:!0})};var F={};U(F,{KanonakUri:()=>v});var v,x=H(()=>{"use strict";v=class u{constructor(e,t,n,a){this.publisher=e;this.package_=t;this.name=n;this.version=a}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let n=t[0],a=t[1],r=n.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${n}. Expected format: publisher/package/name`);let o=a.split(".").map(Number),i={major:o[0]||0,minor:o[1]||0,patch:o[2]||0,toString:()=>`${o[0]||0}.${o[1]||0}.${o[2]||0}`,equals:s=>!s||typeof s!="object"?!1:s.major===(o[0]||0)&&s.minor===(o[1]||0)&&s.patch===(o[2]||0),getHashCode:()=>(o[0]||0)<<20|(o[1]||0)<<10|(o[2]||0),compareTo:s=>(o[0]||0)!==s.major?(o[0]||0)-s.major:(o[1]||0)!==s.minor?(o[1]||0)-s.minor:(o[2]||0)-s.patch};return new u(r[0],r[1],r[2],i)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as D from"js-yaml";var j=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let n=t.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return t.document}parseWithErrors(e){let t=[],n;try{e=e.replace(/^\uFEFF/,"");let a=D.load(e);if(!a||typeof a!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let r=this.extractMetadata(a),o=this.extractBody(a,r);return n={metadata:r,body:o,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:t,isValid:!0}}catch(a){let r=a,o={message:r.message||"Unknown parse error",line:r.mark?.line??0,column:r.mark?.column??0,errorType:r.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${r.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${r.mark?.line??0}: ${r.message||"Unknown parse error"}`};return t.push(o),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let n=e.metadata.namespace_,a={type:"Package",publisher:n.publisher};n.version&&(a.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(a.imports=this.serializeImports(e.metadata.imports)),t[n.package_]=a}return Object.assign(t,e.body),D.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let n=[];for(let a of Object.values(t))n.push(...a);return n},enumerable:!0,configurable:!0}),e}createVersion(e,t,n){return{major:e,minor:t,patch:n,toString:()=>`${e}.${t}.${n}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===t&&r.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:r=>e!==r.major?e-r.major:t!==r.minor?t-r.minor:n-r.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){t.type_="Package";let r=n,o=a.publisher,i=a.version?this.parseVersion(a.version):void 0;return o&&r&&(t.namespace_={publisher:o,package_:r,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:s=>!s||typeof s!="object"?!1:s.publisher===o&&s.package_===r&&(!i||!s.version||i.equals(s.version)),getHashCode:()=>{let s=0;for(let c=0;c<o.length;c++)s=(s<<5)-s+o.charCodeAt(c);for(let c=0;c<r.length;c++)s=(s<<5)-s+r.charCodeAt(c);return s|0}}),a.imports&&Array.isArray(a.imports)&&(t.imports=this.parseImportsV3(a.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let n=e.kanonak;return(n.publisher||n.package||n.version)&&(t.namespace_=this.parseNamespace(n)),n.imports&&typeof n.imports=="object"&&(t.imports=this.parseImportsLegacy(n.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let n={},a;for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){a=r;break}for(let[r,o]of Object.entries(e))r!==a&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(n[r]=o);return n}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let o=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:o,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===r[1]&&i.package_===r[2]&&(!o||!i.version||o.equals(i.version)),getHashCode:()=>{let i=0;for(let s=0;s<r[1].length;s++)i=(i<<5)-i+r[1].charCodeAt(s);for(let s=0;s<r[2].length;s++)i=(i<<5)-i+r[2].charCodeAt(s);return i|0}}}}let t=e.publisher||"",n=e.package||"",a=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:n,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:r=>!r||typeof r!="object"?!1:r.publisher===t&&r.package_===n&&(!a||!r.version||a.equals(r.version)),getHashCode:()=>{let r=0;for(let o=0;o<t.length;o++)r=(r<<5)-r+t.charCodeAt(o);for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o);return r|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let a=n.publisher;if(!a)throw new Error("PublisherImport requires 'publisher' property");t[a]||(t[a]=[]);for(let r of n.packages){if(!r||typeof r!="object")continue;let o=this.parseImportFromEmbeddedObject(r,a);t[a].push(o)}}else{let a=this.parseImportFromEmbeddedObject(n,n.publisher),r=a.publisher||"";t[r]||(t[r]=[]),t[r].push(a)}return t}parseImportsLegacy(e){let t={};for(let[n,a]of Object.entries(e))Array.isArray(a)&&(t[n]=a.map(r=>this.parseImport(r,n)));return t}parseImportFromEmbeddedObject(e,t){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let a=e.match;if(!a)throw new Error("Import requires 'match' property");let r=e.version;if(!r)throw new Error("Import requires 'version' property");let o=this.parseVersion(r),i=this.parseVersionOperator(a),s=this.calculateMaxVersion(a,o),c=e.alias;return{package_:`${n} ${a} ${o.toString()}`,publisher:t,packageName:n,versionOperator:i,version:o,alias:c,minVersion:o,maxVersion:s,toEmbeddedObject:()=>{let p={package:n,match:a,version:o.toString()};return c&&(p.alias=c),p},toString:()=>c?`${n} ${a} ${o.toString()} as ${c}`:`${n} ${a} ${o.toString()}`}}parseImport(e,t){if(typeof e=="string"){let s=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(s){let p=s[1].trim(),m=s[2],l=this.parseVersion(s[3].trim()),d=s[4].trim(),y=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:y,version:l,alias:d,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let k={package:p,match:m,version:l.toString()};return d&&(k.alias=d),k},toString:()=>`${p} ${m} ${l.toString()} as ${d}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),d=this.parseVersionOperator(m),y=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:d,version:l,alias:void 0,minVersion:l,maxVersion:y,toEmbeddedObject:()=>({package:p,match:m,version:l.toString()}),toString:()=>`${p} ${m} ${l.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),a=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",o=["=","~","^","*"][n],i=this.calculateMaxVersion(e.operator||"~",a);return{package_:e.package||"",publisher:t,packageName:r,versionOperator:n,version:a,alias:e.alias,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let s={package:r,match:o,version:a.toString()};return e.alias&&(s.alias=e.alias),s},toString:()=>`${r} ${o} ${a.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[n,a]of Object.entries(e)){let r={publisher:n,packages:a.map(o=>{let i=["=","~","^","*"][o.versionOperator],s={package:o.packageName,match:i,version:`${o.version.major}.${o.version.minor}.${o.version.patch}`};return o.alias&&(s.alias=o.alias),s})};t.push(r)}return t}};var b=class{};var R=class extends b{statement=[]};var I=class extends R{namespace;name;icon};var S=class extends R{};x();var f=class u extends b{subject;static parse(e){let t=new u;return t.subject=v.parse(e),t}};var A=class extends b{value};var g=class{predicate;object};var K=class extends g{};var P=class u extends K{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=t,n}};var E=class u extends K{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=t,n}};var O=class extends K{};var V=class u extends g{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=f.parse(t),n}};var w=class extends g{};var $=class extends g{};x();function N(u){if(Array.isArray(u))return u.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=u?.toString();return e?[e]:[]}var _=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let n=t.metadata?.namespace_?.toString()??"unknown",a=this.cache.get(n);if(a){let o=a.get(e);if(o)return o}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(n,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let n=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let a=e.split("."),r=a[0],o=a[1],i=await this.findDocumentForAlias(t,r);return i?await this.resolveAllEntitiesAsync(o,i):[]}return n.filter(a=>a.entityName===e)}async buildAllEntitiesIndexAsync(e,t,n){let a=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`;for(let[i,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.push({entityName:i,uri:new v(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:s,definedInNamespace:r,isImported:n.length>0,importPath:o})}if(this.logger?.debug?.(`Collected ${a.length} entities from ${r}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${r}`);for(let[s,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${s}/${p.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(s,p);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,o);a.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${p.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${s}/${p.packageName} for namespace ${r}. Error: ${l.message}`,l),new Error(`Failed to process import ${s}/${p.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return a}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,n){let a=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`,i=0;for(let[s,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!a.has(s)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.set(s,{entityName:s,uri:new v(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,s,p),entity:c,definedInNamespace:r,isImported:n.length>0,importPath:o}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${r}`),e.metadata?.imports){let s=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${s} import(s) for ${r}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let m of p)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(c,m);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(l,t,o),y=0;for(let[h,k]of d.entries())if(a.has(h)||(a.set(h,k),y++),m.alias&&!h.includes(".")){let T=`${m.alias}.${h}`;a.has(T)||(a.set(T,k),y++)}this.logger?.debug?.(`Merged ${y} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let d=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${r}. Error: ${d.message}`,d),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${r}. See inner exception for details.`,{cause:l})}}return a}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[n,a]of Object.entries(e.metadata.imports))for(let r of a){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(n,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(n,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubclassOfRecursiveAsync(e,t,n,a)}async isSubclassOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subClassOf;if(o){let i=N(o);for(let s of i)if(s===t||await this.isSubclassOfRecursiveAsync(s,t,n,a))return!0}return!1}async isSubpropertyOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,n,a)}async isSubpropertyOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subPropertyOf;if(o){let i=N(o);for(let s of i)if(s===t||await this.isSubpropertyOfRecursiveAsync(s,t,n,a))return!0}return!1}};var M=class u{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","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"&&u.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return u.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,t);if(n){let a=n.entity.type;if(a){let r=String(a);return r==="Class"||r==="rdfs.Class"||r.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,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var C=class{constructor(e){}async parseKanonaks(e){let t=[],n=await e.getAllDocumentsAsync(),a=new _(e),r=new M(a);for(let o of n)for(let[i,s]of Object.entries(o.body)){let c=new I;c.namespace=o.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let p=await this.parseStatements(s,o,a,r,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,n,a,r){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[i,s]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,n,r,a);if(!c)continue;let p=await this.parsePropertyValue(i,s,c,t,n,a);p&&o.push(p)}catch(c){console.error(`Error parsing property ${i}:`,c)}return o}async getPropertyMetadata(e,t,n,a,r){let o=await n.resolveEntityAsync(e,t);if(!o)return;let i=o.entity,s=i.type?.toString()??"",c=s.includes(".")?s.substring(s.lastIndexOf(".")+1):s;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=r.getPropertyTypeClassification(s),l=i.range?.toString(),d;if(m==="ObjectProperty")d="ObjectProperty";else if(m==="DatatypeProperty")d="DatatypeProperty";else{let h=l&&l.includes(".")?l.substring(l.lastIndexOf(".")+1):l??"";(l?r.isKnownXsdDatatypeName(l):!1)||h==="Literal"?d="DatatypeProperty":d="ObjectProperty"}return{propertyUri:o.uri.toString(),propertyType:d,range:l,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,n,a,r,o){let i=n.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,n,a,r,o);if(n.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,n);if(n.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,n,a,r,o)}}parseDatatypeValue(e,t,n){if(t instanceof Date)return P.parse(e,t.toISOString());if(typeof t=="string")return P.parse(e,t);if(typeof t=="number")return E.parse(e,t);if(typeof t=="boolean"){let a=new O;return a.predicate=f.parse(e),a.object=t,a}}async parseObjectValue(e,t,n,a,r,o){if(typeof t=="string"){let i=await this.resolveReference(t,a,r);if(!i)return;let s=new V;return s.predicate=f.parse(e),s.object=i,s}if(typeof t=="object"&&!Array.isArray(t)){let i=new S;if(i.statement=await this.parseStatements(t,a,r,o,{}),i.statement.length>0){let p=new w;return p.predicate=f.parse(e),p.object=i,p}let s=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new S;m.statement=await this.parseStatements(p,a,r,o,{}),s.push(m)}else if(typeof p=="string"){let m=await this.resolveReference(p,a,r);m&&s.push(m)}if(s.length>0){let p=new $;return p.predicate=f.parse(e),p.object=s,p}let c=new w;return c.predicate=f.parse(e),c.object=i,c}}async parseListValue(e,t,n,a,r,o){let i=[],s=n.propertyType==="DatatypeProperty";for(let p of t){if(s&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean")){let m=new A;m.value=p,i.push(m);continue}if(s&&p instanceof Date){let m=new A;m.value=p.toISOString(),i.push(m);continue}if(typeof p=="string"){let m=await this.resolveReference(p,a,r);m&&i.push(m)}else if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new S;m.statement=await this.parseStatements(p,a,r,o,{}),i.push(m)}}let c=new $;return c.predicate=f.parse(e),c.object=i,c}async resolveReference(e,t,n){let a=await n.resolveEntityAsync(e,t);if(a){let o=new f;return o.subject=a.uri,o}let r=t.metadata?.namespace_;if(r){let{KanonakUri:o}=await Promise.resolve().then(()=>(x(),F)),i=r.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[l,d]of Object.entries(t.metadata.imports))for(let y of d)if((y.alias??y.packageName)===p){let k=new f;return k.subject=new o(l,y.packageName,m,y.version),k}}}let s=new f;return s.subject=new o(r.publisher,r.package_,e,i),s}return null}async saveKanonaks(e,t){let n=new Map;for(let a of e)a instanceof I&&a.namespace&&(n.has(a.namespace)||n.set(a.namespace,[]),n.get(a.namespace).push(a));for(let[a,r]of n){let o=await this.convertKanonaksToDocument(a,r),i=`${a.split("@")[0]}.yml`;await t.saveDocumentAsync(o,i)}}async serializeToYaml(e,t){let n=e.filter(o=>o instanceof I&&o.namespace===t);if(n.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let a=await this.convertKanonaksToDocument(t,n);return new j().save(a)}async convertKanonaksToDocument(e,t){let a={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let i of Object.values(this.imports))o.push(...i);return o}},body:{}},r=new Map;for(let o of t){let i={};for(let s of o.statement){let[c,p]=this.convertStatementToProperty(s);c&&p!==null&&p!==void 0&&(i[c]=p),this.collectImportsFromStatement(s,e,r)}a.body[o.name]=i}return a}convertStatementToProperty(e){if(e instanceof P)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object];if(e instanceof O)return[e.predicate.subject.name,e.object];if(e instanceof V)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof $){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof w){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let n of e)n instanceof f?t.push(n.subject.name):n instanceof S&&t.push(this.convertEmbeddedKanonakToValue(n));return t}convertEmbeddedKanonakToValue(e){let t={};for(let n of e.statement){let[a,r]=this.convertStatementToProperty(n);a&&r!==null&&r!==void 0&&(t[a]=r)}return t}collectImportsFromStatement(e,t,n){}};var L=class{propertyUri;propertyType;range;isImported;definedInNamespace};export{C as KanonakObjectParser,j as KanonakParser,L as PropertyMetadata};
1
+ var ee=Object.defineProperty;var te=(p,e)=>()=>(p&&(e=p(p=0)),e);var re=(p,e)=>{for(var t in e)ee(p,t,{get:e[t],enumerable:!0})};var J={};re(J,{KanonakUri:()=>R});function ne(p,e,t){return{major:p,minor:e,patch:t,toString:()=>`${p}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===p&&r.minor===e&&r.patch===t,getHashCode:()=>p<<20|e<<10|t,compareTo:r=>p!==r.major?p-r.major:e!==r.minor?e-r.minor:t-r.patch}}var R,q=te(()=>{"use strict";R=class p{constructor(e,t,r,n){this.publisher=e;this.package_=t;this.name=r;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("/");if(t.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[r,n,o]=t;if(!r||!n||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let s=n.indexOf("@");if(s===-1)return new p(r,n,o,void 0);let i=n.substring(0,s),a=n.substring(s+1);if(!i||!a)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let c=a.split(".").map(Number),u=ne(c[0]||0,c[1]||0,c[2]||0);return new p(r,i,o,u)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});import*as F from"js-yaml";var w=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=F.load(e);if(!n||typeof n!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let o=this.extractMetadata(n),s=this.extractBody(n,o);return r={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(n){let o=n,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,n={type:"Package",publisher:r.publisher};r.version&&(n.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=n}return Object.assign(t,e.body),F.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:r-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let o=r,s=n.publisher,i=n.version?this.parseVersion(n.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:a=>!a||typeof a!="object"?!1:a.publisher===s&&a.package_===o&&(!i||!a.version||i.equals(a.version)),getHashCode:()=>{let a=0;for(let c=0;c<s.length;c++)a=(a<<5)-a+s.charCodeAt(c);for(let c=0;c<o.length;c++)a=(a<<5)-a+o.charCodeAt(c);return a|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){n=o;break}for(let[o,s]of Object.entries(e))o!==n&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(r[o]=s);return r}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===o[1]&&i.package_===o[2]&&(!s||!i.version||s.equals(i.version)),getHashCode:()=>{let i=0;for(let a=0;a<o[1].length;a++)i=(i<<5)-i+o[1].charCodeAt(a);for(let a=0;a<o[2].length;a++)i=(i<<5)-i+o[2].charCodeAt(a);return i|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===r&&(!n||!o.version||n.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<r.length;s++)o=(o<<5)-o+r.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let o of r.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,n);t[n].push(s)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),o=n.publisher||"";t[o]||(t[o]=[]),t[o].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(o=>this.parseImport(o,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),i=this.parseVersionOperator(n),a=this.calculateMaxVersion(n,s),c=e.alias;return{package_:`${r} ${n} ${s.toString()}`,publisher:t,packageName:r,versionOperator:i,version:s,alias:c,minVersion:s,maxVersion:a,toEmbeddedObject:()=>{let u={package:r,match:n,version:s.toString()};return c&&(u.alias=c),u},toString:()=>c?`${r} ${n} ${s.toString()} as ${c}`:`${r} ${n} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let a=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(a){let u=a[1].trim(),m=a[2],l=this.parseVersion(a[3].trim()),f=a[4].trim(),d=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:u,versionOperator:d,version:l,alias:f,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let g={package:u,match:m,version:l.toString()};return f&&(g.alias=f),g},toString:()=>`${u} ${m} ${l.toString()} as ${f}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let u=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),f=this.parseVersionOperator(m),d=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:u,versionOperator:f,version:l,alias:void 0,minVersion:l,maxVersion:d,toEmbeddedObject:()=>({package:u,match:m,version:l.toString()}),toString:()=>`${u} ${m} ${l.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][r],i=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:i,toEmbeddedObject:()=>{let a={package:o,match:s,version:n.toString()};return e.alias&&(a.alias=e.alias),a},toString:()=>`${o} ${s} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let o={publisher:r,packages:n.map(s=>{let i=["=","~","^","*"][s.versionOperator],a={package:s.packageName,match:i,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(a.alias=s.alias),a})};t.push(o)}return t}};var K=class{};var E=class extends K{statement=[]};var A=class extends E{namespace;name;icon};var $=class extends E{name};q();var y=class p extends K{subject;static parse(e){let t=new p;return t.subject=R.parse(e),t}};var _=class extends K{value};var S=class{predicate;object};var I=class extends S{};var V=class p extends I{static parse(e,t){let r=new p;return r.predicate=y.parse(e),r.object=t,r}};var N=class p extends I{static parse(e,t){let r=new p;return r.predicate=y.parse(e),r.object=t,r}};var L=class extends I{};var T=class p extends S{static parse(e,t){let r=new p;return r.predicate=y.parse(e),r.object=y.parse(t),r}};var j=class extends S{};var D=class extends S{};q();function H(p){if(Array.isArray(p))return p.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=p?.toString();return e?[e]:[]}var W=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(r);if(n){let s=n.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),o=n[0],s=n[1],i=await this.findDocumentForAlias(t,o);return i?await this.resolveAllEntitiesAsync(s,i):[]}return r.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let n=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`;for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:i,uri:new R(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:a,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((a,c)=>a+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[a,c]of Object.entries(e.metadata.imports))for(let u of c)try{this.logger?.debug?.(`Resolving import: ${a}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(a,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,s);n.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${u.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${a}/${u.packageName} for namespace ${o}. Error: ${l.message}`,l),new Error(`Failed to process import ${a}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,i=0;for(let[a,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!n.has(a)){let u=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(a,{entityName:a,uri:new R(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,u),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((c,u)=>c+u.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[c,u]of Object.entries(e.metadata.imports))for(let m of u)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(c,m);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let f=await this.buildEntityIndexAsyncInternal(l,t,s),d=0;for(let[h,g]of f.entries())if(n.has(h)||(n.set(h,g),d++),m.alias&&!h.includes(".")){let P=`${m.alias}.${h}`;n.has(P)||(n.set(P,g),d++)}this.logger?.debug?.(`Merged ${d} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let f=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${o}. Error: ${f.message}`,f),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${o}. See inner exception for details.`,{cause:l})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubclassOfRecursiveAsync(a,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubpropertyOfRecursiveAsync(a,t,r,n))return!0}return!1}};var U=class p{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","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"&&p.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return p.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let n=r.entity.type;if(n){let o=String(n);return o==="Class"||o==="rdfs.Class"||o.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,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var Y=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new W(e),o=new U(n);for(let s of r)for(let[i,a]of Object.entries(s.body)){let c=new A;c.namespace=s.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let u=await this.parseStatements(a,s,n,o,e);c.statement.push(...u),t.push(c)}return t}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[i,a]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,r,o,n);if(!c)continue;let u=await this.parsePropertyValue(i,a,c,t,r,n);u&&s.push(u)}catch(c){console.error(`Error parsing property ${i}:`,c)}return s}async getPropertyMetadata(e,t,r,n,o){let s=await r.resolveEntityAsync(e,t);if(!s)return;let i=s.entity,a=i.type?.toString()??"",c=a.includes(".")?a.substring(a.lastIndexOf(".")+1):a;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=o.getPropertyTypeClassification(a),l=i.range?.toString(),f;if(m==="ObjectProperty")f="ObjectProperty";else if(m==="DatatypeProperty")f="DatatypeProperty";else{let h=l&&l.includes(".")?l.substring(l.lastIndexOf(".")+1):l??"";(l?o.isKnownXsdDatatypeName(l):!1)||h==="Literal"?f="DatatypeProperty":f="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:f,range:l,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let i=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return V.parse(e,t.toISOString());if(typeof t=="string")return V.parse(e,t);if(typeof t=="number")return N.parse(e,t);if(typeof t=="boolean"){let n=new L;return n.predicate=y.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let i=await this.resolveReference(t,n,o);if(!i)return;let a=new T;return a.predicate=y.parse(e),a.object=i,a}if(typeof t=="object"&&!Array.isArray(t)){let i=new $;if(i.statement=await this.parseStatements(t,n,o,s,{}),i.statement.length>0){let u=new j;return u.predicate=y.parse(e),u.object=i,u}let a=[];for(let[u,m]of Object.entries(t))if(typeof m=="object"&&m!==null&&!Array.isArray(m)){let l=new $;l.name=u,l.statement=await this.parseStatements(m,n,o,s,{}),a.push(l)}else if(typeof m=="string"){let l=await this.resolveReference(m,n,o);l&&a.push(l)}if(a.length>0){let u=new D;return u.predicate=y.parse(e),u.object=a,u}let c=new j;return c.predicate=y.parse(e),c.object=i,c}}async parseListValue(e,t,r,n,o,s){let i=[],a=r.propertyType==="DatatypeProperty";for(let u of t){if(a&&(typeof u=="string"||typeof u=="number"||typeof u=="boolean")){let m=new _;m.value=u,i.push(m);continue}if(a&&u instanceof Date){let m=new _;m.value=u.toISOString(),i.push(m);continue}if(typeof u=="string"){let m=await this.resolveReference(u,n,o);m&&i.push(m)}else if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let m=new $;m.statement=await this.parseStatements(u,n,o,s,{}),i.push(m)}}let c=new D;return c.predicate=y.parse(e),c.object=i,c}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new y;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(q(),J)),i=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),u=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[l,f]of Object.entries(t.metadata.imports))for(let d of f)if((d.alias??d.packageName)===u){let g=new y;return g.subject=new s(l,d.packageName,m,d.version),g}}}let a=new y;return a.subject=new s(o.publisher,o.package_,e,i),a}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof A&&n.namespace&&(r.has(n.namespace)||r.set(n.namespace,[]),r.get(n.namespace).push(n));for(let[n,o]of r){let s=await this.convertKanonaksToDocument(n,o),i=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(s,i)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof A&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new w().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let i of Object.values(this.imports))s.push(...i);return s}},body:{}},o=new Map;for(let s of t){let i={};for(let a of s.statement){let[c,u]=this.convertStatementToProperty(a);c&&u!==null&&u!==void 0&&(i[c]=u),this.collectImportsFromStatement(a,e,o)}n.body[s.name]=i}return n}convertStatementToProperty(e){if(e instanceof V)return[e.predicate.subject.name,e.object];if(e instanceof N)return[e.predicate.subject.name,e.object];if(e instanceof L)return[e.predicate.subject.name,e.object];if(e instanceof T)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof D){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof j){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof y?t.push(r.subject.name):r instanceof $&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var B=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as oe,LineCounter as se,isMap as x,isPair as k,isScalar as b,isSeq as X}from"yaml";var C=class p{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new p,r=new se,n=oe(e,{lineCounter:r});if(n.errors.length>0||!x(n.contents))return t;G(n.contents,[],r,t);for(let o of n.contents.items){if(!k(o)||!b(o.key))continue;let s=String(o.key.value),i=o.key.range;if(!i)continue;t.entities.set(s,v(i,r));let a=o.value,c=a&&typeof a=="object"&&"range"in a?a.range:void 0;if(c?t.entityBlocks.set(s,v([i[0],i[1],c[2]],r)):t.entityBlocks.set(s,v(i,r)),x(o.value)){let u=new Map,m=new Map,l=new Map;for(let d of o.value.items){if(!k(d)||!b(d.key))continue;let h=String(d.key.value),g=d.key.range;g&&u.set(h,v(g,r));let P=d.value;if(P&&typeof P=="object"&&"range"in P&&Array.isArray(P.range)){let O=P.range;m.set(h,v(O,r))}if(X(P)){let O=[];for(let M of P.items)M&&typeof M=="object"&&"range"in M&&Array.isArray(M.range)&&O.push(v(M.range,r));O.length>0&&l.set(h,O)}}u.size>0&&t.properties.set(s,u),m.size>0&&t.propertyValues.set(s,m),l.size>0&&t.valueListItems.set(s,l);let f=ae(o.value,r);f.length>0&&t.importPackages.set(s,f)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,n]of this.entityBlocks)if(z(n,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let n=this.properties.get(r),o=this.propertyValues.get(r);if(!n&&!o)return{entityName:r};let s,i;if(o)for(let[a,c]of o)z(c,e,t)&&(!i||Q(c,i))&&(s=a,i=c);if(n)for(let[a,c]of n)z(c,e,t)&&(!i||Q(c,i))&&(s=a,i=c);return s?{entityName:r,propertyName:s}:{entityName:r}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,r]of this.importPackages)for(let n of r)e.push({entityName:t,entry:n});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let n of r.keys()){let o=n.lastIndexOf(".");if((o===-1?n:n.substring(o+1))===t)return n}}}getListItemPosition(e,t,r){let n=this.valueListItems.get(e)?.get(t);if(!(!n||r<0||r>=n.length))return n[r]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let n=this.getPropertyValuePosition(e,t);if(n)return n;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function ae(p,e){let t=[];if(!x(p))return t;let r=p.items.find(n=>k(n)&&b(n.key)&&String(n.key.value)==="imports");if(!r||!k(r)||!X(r.value))return t;for(let n of r.value.items){if(!x(n))continue;let o=n.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="publisher");if(!o||!k(o)||!b(o.value))continue;let s=String(o.value.value),i=n.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="packages");if(!(!i||!k(i)||!X(i.value)))for(let a of i.value.items){if(!x(a))continue;let c=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="package");if(!c||!k(c)||!b(c.value)||!c.value.range)continue;let u=String(c.value.value),m=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="version"),l=m&&k(m)&&b(m.value)?String(m.value.value):"",f=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="alias"),d=f&&k(f)&&b(f.value)?String(f.value.value):void 0,h=d!==void 0?{publisher:s,package_:u,version:l,alias:d,position:v(c.value.range,e)}:{publisher:s,package_:u,version:l,position:v(c.value.range,e)};t.push(h)}}return t}function z(p,e,t){return!(e<p.line||e>p.endLine||e===p.line&&t<p.column||e===p.endLine&&t>p.endColumn)}function Q(p,e){let t=p.endLine-p.line,r=e.endLine-e.line;if(t!==r)return t<r;let n=p.endLine===p.line?p.endColumn-p.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return n<o}function G(p,e,t,r){if(x(p)){for(let n of p.items){if(!k(n)||!b(n.key))continue;let o=String(n.key.value),s=[...e,o],i=JSON.stringify(s);n.key.range&&r.setNestedKeyPosition(i,v(n.key.range,t));let a=n.value,c=Z(a);c&&r.setNestedValuePosition(i,v(c,t)),G(a,s,t,r)}return}if(X(p)){for(let n=0;n<p.items.length;n++){let o=p.items[n],s=[...e,n],i=JSON.stringify(s),a=Z(o);a&&r.setNestedValuePosition(i,v(a,t)),G(o,s,t,r)}return}}function Z(p){if(!p||typeof p!="object"||!("range"in p))return;let e=p.range;return Array.isArray(e)&&e.length>=3?e:void 0}function v(p,e){let t=e.linePos(p[0]),r=e.linePos(p[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function ie(p,e){let r=(e??new w).parse(p),n=C.fromContent(p);return{document:r,positions:n}}export{C as KanonakDocumentPositions,Y as KanonakObjectParser,w as KanonakParser,B as PropertyMetadata,ie as parseWithPositions};
@@ -0,0 +1,41 @@
1
+ import type { KanonakDocument } from '@kanonak-protocol/types/document/models/types';
2
+ import { KanonakParser } from './KanonakParser.js';
3
+ import { KanonakDocumentPositions } from './KanonakDocumentPositions.js';
4
+ /**
5
+ * Result of `parseWithPositions`: the parsed document object model
6
+ * (built by the SDK's existing `KanonakParser`) plus a parallel
7
+ * source-position index (built by walking the yaml package's CST
8
+ * over the same source bytes).
9
+ *
10
+ * Both halves come from the same input string. They are consistent
11
+ * for any well-formed Kanonak document. Edge cases where the two
12
+ * parsers might disagree (rare YAML features like custom tags or
13
+ * merge keys) cause the position index to be empty rather than
14
+ * incorrect — the document still parses cleanly into its object
15
+ * model; consumers fall back to file-scope ranges for that document.
16
+ */
17
+ export interface ParsedDocumentWithPositions {
18
+ document: KanonakDocument;
19
+ positions: KanonakDocumentPositions;
20
+ }
21
+ /**
22
+ * Parse a `.kan.yml` source string into the SDK object model and
23
+ * build a position index in parallel.
24
+ *
25
+ * Two parses run on the same content:
26
+ *
27
+ * 1. `KanonakParser.parse(content)` — produces the typed
28
+ * `KanonakDocument` consumers already know how to walk.
29
+ * 2. `KanonakDocumentPositions.fromContent(content)` — walks the
30
+ * yaml package's CST to produce per-entity / per-property /
31
+ * per-list-item source positions.
32
+ *
33
+ * The two passes are intentionally decoupled. The object-model parse
34
+ * remains the source of truth for document shape; the position index
35
+ * is purely informational, used for diagnostic ranges and
36
+ * symbol-intelligence providers (Definition, Hover, etc.).
37
+ *
38
+ * Pass an existing `KanonakParser` instance to share its caches with
39
+ * other call sites; otherwise a fresh one is constructed.
40
+ */
41
+ export declare function parseWithPositions(content: string, parser?: KanonakParser): ParsedDocumentWithPositions;