@kanonak-protocol/sdk 5.20.0 → 5.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +1 -1
- package/dist/chunk-6VIUXP4N.js +1 -0
- package/dist/{chunk-LYSCTQC2.js → chunk-APWYAZMI.js} +1 -1
- package/dist/chunk-BPIAKTAV.js +63 -0
- package/dist/{chunk-M443OYKT.js → chunk-BRCVOR7A.js} +1 -1
- package/dist/{chunk-6AIRUIV5.js → chunk-DUM5Q4MH.js} +1 -1
- package/dist/{chunk-YEGCG4MF.js → chunk-FNLI7URD.js} +1 -1
- package/dist/{chunk-V3IPBWWU.js → chunk-GFLQ5TPR.js} +1 -1
- package/dist/{chunk-YW6P24RF.js → chunk-H6UAD2LP.js} +1 -1
- package/dist/{chunk-NJ3AZYQD.js → chunk-KOWDHKBN.js} +1 -1
- package/dist/{chunk-V6KIDED2.js → chunk-LMD432SO.js} +1 -1
- package/dist/chunk-M7OWTFTC.js +2 -0
- package/dist/{chunk-SVUMCLK5.js → chunk-O6YV2SDB.js} +1 -1
- package/dist/chunk-PEB52US5.js +1 -0
- package/dist/chunk-QILEJIFU.js +1 -0
- package/dist/{chunk-5NH5XDGO.js → chunk-ULHACEE2.js} +1 -1
- package/dist/chunk-WKLSD5DQ.js +1 -0
- package/dist/chunk-YM2V52DK.js +152 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/look/LookRenderer.d.ts +162 -9
- package/dist/look/index.d.ts +1 -1
- package/dist/parsing/index.js +1 -1
- package/dist/reasoning/index.js +1 -1
- package/dist/repositories/browser.js +1 -1
- package/dist/repositories/index.js +1 -1
- package/dist/resolution/VersionUtils.d.ts +21 -1
- package/dist/resolution/index.d.ts +1 -3
- package/dist/resolution/index.js +1 -1
- package/dist/search/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/transformations/index.js +2 -2
- package/dist/uri-helpers/index.js +1 -1
- package/dist/validation/index.js +1 -1
- package/dist/validation/rules/repository/UnrenderableBandRule.d.ts +33 -0
- package/dist/validation/rules/repository/index.d.ts +1 -0
- package/package.json +2 -2
- package/dist/chunk-2ACBWC7K.js +0 -1
- package/dist/chunk-4NO7MHS7.js +0 -1
- package/dist/chunk-4YMGH5RR.js +0 -1
- package/dist/chunk-CCVH7TCQ.js +0 -2
- package/dist/chunk-P36E2UV6.js +0 -152
- package/dist/chunk-PEUTCG3B.js +0 -1
- package/dist/chunk-QHABFCRC.js +0 -0
- package/dist/chunk-UYSEO3OT.js +0 -63
- package/dist/resolution/InstanceSearch.d.ts +0 -32
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as X,c as Un,d as Vn,e as
|
|
1
|
+
import{a as pe}from"../chunk-APWYAZMI.js";import"../chunk-ULHACEE2.js";import{b as X,c as Un,d as Vn,e as le,f as ve,g as M,h as Rn,i as q,j as G}from"../chunk-YM2V52DK.js";import"../chunk-6VIUXP4N.js";import{a as ce,b as ue,c as de,e as $n,f as Tn,g as Bn,h as xn,m as fe}from"../chunk-LMD432SO.js";import{a as se}from"../chunk-KOWDHKBN.js";import"../chunk-PEJALHXK.js";import{e as U}from"../chunk-O6YV2SDB.js";import{b as Y,c as D,d as E,g as $,h as T,i as B,j as w,k as me,l as x,n as N,o as S,r as A}from"../chunk-H6UAD2LP.js";import"../chunk-FUUTGGJS.js";import{g as ie}from"../chunk-QILEJIFU.js";var Le="kanonak.org",Oe="document-ast",i=e=>({publisher:Le,package_:Oe,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ge(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var V=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=Ie(n.metadata,t),o=Ke(n.children),s=["---",...r,"---","",o].join(`
|
|
2
2
|
`);return t?.trailingNewline&&(s.endsWith(`
|
|
3
3
|
`)||(s+=`
|
|
4
4
|
`)),s}};function Ie(e,n){if(!e)return[];let t=new Map;for(let c of e.entries)t.set(P(c.key),c);let r=new Map;if(n?.metadataRenames)for(let[c,u]of n.metadataRenames)r.set(P(c),u);let a=(n?.metadataKeys??e.entries.map(c=>c.key)).map(P),s=[];for(let c of a){let u=t.get(c);if(!u)continue;let f=r.get(c),l=P(f??c),d=ye(u.value,u.escapeHint);d!==void 0&&s.push(`${l}: ${d}`)}return s}function P(e){let n=e.lastIndexOf(".");return n===-1?e:e.substring(n+1)||e}function ye(e,n){switch(e.kind){case"StringScalar":return _e(e.stringValue,n);case"IntegerScalar":return String(e.integerValue);case"StructuredList":{let t=[];for(let r of e.items){let o=ye(r,n);o!==void 0&&t.push(o)}return t.join(", ")}case"StructuredMap":return;default:return}}function _e(e,n){return!n||ge(n,m.ESC_RAW)?e:ge(n,m.ESC_YAML_SAFE)?Ce(e):e}function Ce(e){return e.includes(`
|
|
@@ -88,4 +88,4 @@ ${e.rawContent}
|
|
|
88
88
|
`)&&(o+=`
|
|
89
89
|
`),o}};function C(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var K=class{backendUri="kanonak.org/transformations/dynamodb-json";render(n,t){if(!n.metadata)throw new Error("dynamodb-json backend: Document has no `metadata` channel. This backend serializes Document.metadata into DynamoDB attribute-value JSON \u2014 the transformation must populate that channel. (No silent empty artifact.)");let r=Ae(n.metadata,t),o=JSON.stringify(r,null,2);return t?.trailingNewline&&!o.endsWith(`
|
|
90
90
|
`)&&(o+=`
|
|
91
|
-
`),o}};function Ae(e,n){let t=new Map;for(let a of e.entries)t.set(a.key,a);let r=n?.metadataKeys??e.entries.map(a=>a.key),o={};for(let a of r){let s=t.get(a);if(!s)continue;let c=n?.metadataRenames.get(a)??a;o[c]=je(s.value,s.escapeHint)}return{M:o}}function je(e,n){switch(e.kind){case"StructuredMap":return Ae(e);case"StructuredList":return{L:e.items.map(t=>je(t,void 0))};case"StringScalar":return dn(e.stringValue,n??e.escapeHint);case"IntegerScalar":return fn(e.integerValue,n??e.escapeHint)}}function dn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL)){if(e==="true")return{BOOL:!0};if(e==="false")return{BOOL:!1};throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-bool must have the value "true" or "false"; got ${JSON.stringify(e)}.`)}if(n&&C(n,m.ESC_DYNAMODB_NULL))return{NULL:!0};if(n&&C(n,m.ESC_DYNAMODB_NUMBER)){if(e.trim()===""||Number.isNaN(Number(e)))throw new Error(`dynamodb-json backend: a StringScalar hinted esc-dynamodb-number must hold a numeric literal; got ${JSON.stringify(e)}.`);return{N:e}}return{S:e}}function fn(e,n){if(n&&C(n,m.ESC_DYNAMODB_BOOL))throw new Error(`dynamodb-json backend: esc-dynamodb-bool cannot apply to an IntegerScalar (value ${e}). Use a StringScalar "true"/"false".`);if(n&&C(n,m.ESC_DYNAMODB_NULL))throw new Error(`dynamodb-json backend: esc-dynamodb-null cannot apply to an IntegerScalar (value ${e}). Use a StringScalar hinted esc-dynamodb-null.`);return{N:String(e)}}var ln={"markdown-with-frontmatter":{formatUri:"kanonak.org/transformations/markdown-with-frontmatter",extension:".md"},"plain-markdown":{formatUri:"kanonak.org/transformations/plain-markdown",extension:".md"},toml:{formatUri:"kanonak.org/transformations/toml",extension:".toml"},json:{formatUri:"kanonak.org/transformations/json",extension:".json"},html:{formatUri:"kanonak.org/transformations/html",extension:".html"},svg:{formatUri:"kanonak.org/transformations/svg",extension:".svg"},stylesheet:{formatUri:"kanonak.org/transformations/stylesheet",extension:".css"},yaml:{formatUri:"kanonak.org/transformations/yaml",extension:".yaml"},"dynamodb-json":{formatUri:"kanonak.org/transformations/dynamodb-json",extension:".json"}},h=class extends Error{},H=class{backends=new Map;constructor(){this.register(new V),this.register(new R),this.register(new v),this.register(new L),this.register(new O),this.register(new I),this.register(new _),this.register(new K)}register(n){this.backends.set(n.backendUri,n)}async run(n){let t=n.transformationKanonaks??n.allKanonaks,r=M(n.transformation,t);if(!r.outputs.has(n.outputFormat))throw new h(`Transformation "${r.name}" does not declare output format "${n.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let o=this.findBackend(n.outputFormat);if(!o)throw new h(`No backend registered for OutputFormat "${n.outputFormat}".`);let a=new q(n.repository,n.parser,n.objectParser),s=new pe(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)}`}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 le(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,pe as ExpressionEngineV3,Vn as ExpressionEvalErrorV3,L as HtmlBackend,v as JsonBackend,V as MarkdownFrontmatterBackend,q as ReferenceResolver,p as RenderError,ln as SUPPORTED_FORMATS_V3,O as SvgBackend,xn as TX_V3,Tn as TX_V3_PKG,$n as TX_V3_PUB,Bn as TX_V3_VERSION_MAJOR,R as TomlBackend,oe as TransformationEngine,ve as TransformationLoadErrorV3,h as TransformationRunnerErrorV3,H as TransformationRunnerV3,_ as YamlBackend,Rn as compileExpression,M as compileTransformationV3,Un 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)}`}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,V as MarkdownFrontmatterBackend,q as ReferenceResolver,p as RenderError,ln as SUPPORTED_FORMATS_V3,O as SvgBackend,xn as TX_V3,Tn as TX_V3_PKG,$n as TX_V3_PUB,Bn as TX_V3_VERSION_MAJOR,R as TomlBackend,oe as TransformationEngine,ve as TransformationLoadErrorV3,h as TransformationRunnerErrorV3,H as TransformationRunnerV3,_ as YamlBackend,Rn as compileExpression,M as compileTransformationV3,Un as isRawStringV3,X as renderMarkdownToHtml,ae as toExpressionRuntimeTree};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as a,n as b,o as c,p as d,q as e,r as f,s as g,t as h,u as i,v as j,w as k,x as l,y as m,z as n}from"../chunk-
|
|
1
|
+
import{m as a,n as b,o as c,p as d,q as e,r as f,s as g,t as h,u as i,v as j,w as k,x as l,y as m,z as n}from"../chunk-H6UAD2LP.js";import"../chunk-FUUTGGJS.js";import"../chunk-QILEJIFU.js";export{n as SingleDocumentRepository,g as findAllResourcesByCanonicalUri,f as findSubjectByUri,e as findSubjectsByType,i as getDatatypeValue,l as getEmbeddedValue,m as getListValues,k as getReferenceUri,j as getStringValue,h as hasProperty,d as hasType,c as toCanonicalUrl,a as uriKey,b as uriMatches};
|
package/dist/validation/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A,B,C,D,E,F,G,H,K as I,L as J,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-
|
|
1
|
+
import{A,B,C,D,E,F,G,H,K as I,L as J,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-BPIAKTAV.js";import"../chunk-BRCVOR7A.js";import"../chunk-YM2V52DK.js";import"../chunk-6VIUXP4N.js";import"../chunk-LMD432SO.js";import"../chunk-KOWDHKBN.js";import"../chunk-PEJALHXK.js";import"../chunk-O6YV2SDB.js";import"../chunk-H6UAD2LP.js";import"../chunk-FUUTGGJS.js";import"../chunk-QILEJIFU.js";export{u as AmbiguousReferenceRule,A as ClassDefinitionRule,n as ClassHierarchyCycleRule,I as DiamondNameClashRule,C as DisplayLensScopeRule,k as EmbeddedKanonakTypeRule,l as ImportExistenceRule,J as KanonakObjectValidator,E as LookBandPathRule,D as LookSemanticSvgPathRule,B as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,w as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,H as OwlOneOfRule,j as PackageHeaderRule,x as PropertyDomainRule,o as PropertyHierarchyCycleRule,y as PropertyKindRangeConsistencyRule,v as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,z as ReservedNameShadowRule,g as ResourceNamingRule,G as ShaclShapeRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,F as TxExpressionPathRule,t as UnresolvedPredicateRule,m as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
|
|
2
|
+
import type { KanonakDocument } from '@kanonak-protocol/types/document/models/types';
|
|
3
|
+
import { OntologyValidationError } from '../../OntologyValidationError.js';
|
|
4
|
+
import type { IRepositoryValidationRule } from './IRepositoryValidationRule.js';
|
|
5
|
+
import type { ValidationCache } from '../../ValidationCache.js';
|
|
6
|
+
/**
|
|
7
|
+
* Warn when a look declares a band the renderer cannot honour.
|
|
8
|
+
*
|
|
9
|
+
* The gap this closes (kanonak-protocol/typescript#100): a band valid against
|
|
10
|
+
* the look vocabulary but absent from the renderer's dispatch validates clean,
|
|
11
|
+
* then renders as an HTML comment — which a browser does not display. The page
|
|
12
|
+
* silently loses that region, and the only evidence is in the page source.
|
|
13
|
+
*
|
|
14
|
+
* The renderer's dispatch table is the source of truth, exported as
|
|
15
|
+
* `supportedBandKeys()`, so this rule cannot drift from what actually renders:
|
|
16
|
+
* implementing a band makes it acceptable here automatically, and removing one
|
|
17
|
+
* makes it warn.
|
|
18
|
+
*
|
|
19
|
+
* A WARNING rather than an error. The declaration is legitimate against the
|
|
20
|
+
* vocabulary, the ontology is not wrong, and a publisher may reasonably author
|
|
21
|
+
* ahead of the renderer — but they should be told, at author time, rather than
|
|
22
|
+
* discovering it by reading rendered HTML.
|
|
23
|
+
*/
|
|
24
|
+
export declare class UnrenderableBandRule implements IRepositoryValidationRule {
|
|
25
|
+
readonly ruleName = "UnrenderableBand";
|
|
26
|
+
validateAsync(document: KanonakDocument, repository: IKanonakDocumentRepository, cache?: ValidationCache): Promise<OntologyValidationError[]>;
|
|
27
|
+
/**
|
|
28
|
+
* The band's declared type URI, read through the object model's own
|
|
29
|
+
* reference reader rather than by walking statements here — one way to ask
|
|
30
|
+
* this question, and it already handles the shapes a `type` can take.
|
|
31
|
+
*/
|
|
32
|
+
private typeOf;
|
|
33
|
+
}
|
|
@@ -20,6 +20,7 @@ export { MarkdownLinkRule } from './MarkdownLinkRule.js';
|
|
|
20
20
|
export { DisplayLensScopeRule } from './DisplayLensScopeRule.js';
|
|
21
21
|
export { LookSemanticSvgPathRule } from './LookSemanticSvgPathRule.js';
|
|
22
22
|
export { LookBandPathRule } from './LookBandPathRule.js';
|
|
23
|
+
export { UnrenderableBandRule } from './UnrenderableBandRule.js';
|
|
23
24
|
export { TxExpressionPathRule } from './TxExpressionPathRule.js';
|
|
24
25
|
export { ShaclShapeRule } from './ShaclShapeRule.js';
|
|
25
26
|
export { OwlOneOfRule } from './OwlOneOfRule.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanonak-protocol/sdk",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.23.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",
|
|
@@ -126,7 +126,7 @@
|
|
|
126
126
|
],
|
|
127
127
|
"dependencies": {
|
|
128
128
|
"@kanonak-protocol/canonical": "^0.1.3",
|
|
129
|
-
"@kanonak-protocol/types": "^5.
|
|
129
|
+
"@kanonak-protocol/types": "^5.23.0",
|
|
130
130
|
"ignore": "^7.0.5",
|
|
131
131
|
"js-yaml": "^4.1.0",
|
|
132
132
|
"yaml": "^2.7.0",
|
package/dist/chunk-2ACBWC7K.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{VersionOperator as o}from"@kanonak-protocol/types/document/models/enums";function f(e){switch(e){case"=":return o.Exact;case"~":return o.Compatible;case"^":return o.Major;case"*":return o.Any;default:return o.Compatible}}function V(e){switch(e){case o.Exact:return"=";case o.Compatible:return"~";case o.Major:return"^";case o.Any:return"*";default:return"~"}}function u(e,n){return e.major!==n.major?e.major-n.major:e.minor!==n.minor?e.minor-n.minor:e.patch-n.patch}function x(e,n){return e.major===n.major&&e.minor===n.minor&&e.patch===n.patch}function l(e){return`${e.major}.${e.minor}.${e.patch}`}function c(e,n,t){let a=`${e}.${n}.${t}`;return{major:e,minor:n,patch:t,toString:()=>a,equals:r=>r?.major===e&&r?.minor===n&&r?.patch===t,getHashCode:()=>e<<20|n<<10|t,compareTo:r=>e!==r.major?e-r.major:n!==r.minor?n-r.minor:t-r.patch}}function g(e){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);return n?c(Number(n[1]),Number(n[2]),Number(n[3])):null}function h(e,n){return u(e,n)>=0&&e.major===n.major&&e.minor===n.minor}function v(e,n){return n.major===0?u(e,n)>=0&&e.major===0&&e.minor===n.minor:u(e,n)>=0&&e.major===n.major}function j(e,n={}){let{requestedVersion:t}=n;if(e.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!t};if(t){let r=e.find(i=>{let s=i.metadata.namespace_?.version;return!!s&&l(s)===t});return r?{chosen:r,alternatives:e.filter(i=>i!==r),multipleVersionsPresent:e.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:e,multipleVersionsPresent:e.length>1,exactRequestedVersionMissing:!0}}if(e.length===1)return{chosen:e[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let a=[...e].sort((r,i)=>{let s=r.metadata.namespace_?.version,m=i.metadata.namespace_?.version;return!s&&!m?0:s?m?u(m,s):-1:1});return{chosen:a[0],alternatives:a.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}export{f as a,V as b,u as c,x as d,l as e,c as f,g,h,v as i,j};
|
package/dist/chunk-4NO7MHS7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as i,d as u,h as d,i as p}from"./chunk-2ACBWC7K.js";import{VersionOperator as r}from"@kanonak-protocol/types/document/models/enums";var l=class{documents=new Map;documentContents=new Map;parser;constructor(e){this.parser=e}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,n){let t=[];for(let s of this.documents.values())s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===n&&t.push(s);return t}async getHighestCompatibleVersionAsync(e,n){let t=[];for(let a of this.documents.values())a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===n.packageName&&a.metadata?.namespace_?.version!==void 0&&t.push(a);if(t.length===0)return null;let s=t.filter(a=>{let o=a.metadata.namespace_.version;if(!o)return!1;switch(n.versionOperator){case r.Exact:return u(o,n.version);case r.Compatible:return d(o,n.version);case r.Major:return p(o,n.version);case r.Any:return i(o,n.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,o)=>{let c=a.metadata.namespace_.version,m=o.metadata.namespace_.version;return!c&&!m?0:c?m?i(m,c):-1:1}),s[0])}async saveDocumentAsync(e,n){this.documents.set(n,e);let t=this.parser.save(e);this.documentContents.set(n,t)}async deleteDocumentAsync(e){this.documents.delete(e),this.documentContents.delete(e)}async clearNamespaceAsync(e,n){let t=[];for(let[s,a]of this.documents.entries())a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===n&&t.push(s);for(let s of t)this.documents.delete(s),this.documentContents.delete(s)}async getAllDocumentReferencesAsync(){let e=[];for(let n of this.documents.values())n.metadata?.namespace_&&e.push({identifier:n.metadata.namespace_.toString(),uri:`kanonak://${n.metadata.namespace_}`,hasParseError:!1});return e}async getDocumentContentAsync(e){let n=this.documentContents.get(e);if(n!==void 0)return n;let t=this.documents.get(e);return t!==void 0?this.parser.save(t):null}async getDocumentUriAsync(e){let n=this.documents.get(e);return n?n.metadata?.namespace_?`kanonak://${n.metadata.namespace_}`:`kanonak://${e}`:null}};export{l as a};
|
package/dist/chunk-4YMGH5RR.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as v}from"./chunk-CCVH7TCQ.js";import{a as w}from"./chunk-4NO7MHS7.js";import{a as f}from"./chunk-NJ3AZYQD.js";import{c as A,d as R,g as b,h as F,i as S}from"./chunk-2ACBWC7K.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as x}from"url";import{VersionOperator as P}from"@kanonak-protocol/types/document/models/enums";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case P.Exact:return R(r,t.version);case P.Compatible:return F(r,t.version);case P.Major:return S(r,t.version);case P.Any:return A(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return A(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],h=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,h)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=x(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return x(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as g from"fs";var _=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(_||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as $}from"os";import{join as B}from"path";function d(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||B($(),".kanonak","packages")}var C=class u{static createComposite(e,t,n){let o=e??d(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{VersionOperator as H}from"@kanonak-protocol/types/document/models/enums";var K=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return this.lock.packages[`${e}/${t}`]?.version}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=b(n);if(o){let s={...t,versionOperator:H.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as V,readdirSync as j}from"fs";import{join as N}from"path";var E=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function I(u,e=[]){for(let t of j(u,{withFileTypes:!0}))t.isDirectory()?E.has(t.name)||I(N(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(N(u,t.name));return e}async function z(u,e=new f,t={}){let n=new w(e);for(let m of I(u))try{let l=e.parse(V(m,"utf-8")),p=l.metadata?.namespace_,h=p?.version;p&&h&&await n.saveDocumentAsync(l,`${p.publisher}/${p.package_}@${h.major}.${h.minor}.${h.patch}`)}catch{}let o=new y(d(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,p)=>s.get(`${m}|${l}|${p}`)??null,onFetch:(m,l,p,h)=>{s.set(`${m}|${l}|${p}`,h)}},r=new v({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,_ as b,k as c,d,C as e,D as f,K as g,I as h,z as i};
|
package/dist/chunk-CCVH7TCQ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{a as v}from"./chunk-SC5M74NM.js";import{a as R}from"./chunk-NJ3AZYQD.js";import{e as F,g as A}from"./chunk-2ACBWC7K.js";var b="@kanonak-protocol/sdk (+https://kanonak.org)",w=b;function q(o){w=o}function G(){return w}function m(o){let t;try{t=typeof o=="string"?new URL(o):o}catch{throw new Error(`Kanonak requires an absolute https:// URL \u2014 got an unparseable or relative URL: ${String(o)}`)}if(t.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${t.href} (only https:// is supported).`)}var D=new Set([429,502,503,504]),K=4,I=500,C=2e4;function u(o,t){m(o);let e=new Headers(t?.headers);return e.has("User-Agent")||e.set("User-Agent",w),T(o,{...t,headers:e})}var k=K;function V(o){k=Math.max(0,o)}async function T(o,t){let e;for(let n=0;n<=k;n++){let r;try{r=await fetch(o,t)}catch(s){if(e=s,n>=k)throw s;await E(x(n,null));continue}if(!D.has(r.status)||n>=k)return r;await E(x(n,r.headers.get("retry-after")))}throw e??new Error("kanonakFetch: exhausted retries")}function x(o,t){let e=j(t);if(e!=null)return Math.min(e,C);let n=Math.min(C,I*2**o);return Math.floor(n/2+Math.random()*(n/2))}function j(o){if(!o)return null;let t=Number(o);if(Number.isFinite(t))return Math.max(0,t*1e3);let e=Date.parse(o);return Number.isNaN(e)?null:Math.max(0,e-Date.now())}function E(o){return new Promise(t=>setTimeout(t,o))}var M="https://{publisher}/{package}/{version}.kan.yml",L={version:1};function X(){return{version:1}}var y=class{constructor(t){this.fetchFn=t}fetchFn;cache=new Map;getConfig(t){let e=this.cache.get(t);return e||(e=this.fetchConfig(t),this.cache.set(t,e),e.catch(()=>{this.cache.get(t)===e&&this.cache.delete(t)})),e}async fetchConfig(t){let e=`https://${t}/.well-known/kanonak.json`,n;try{n=await(this.fetchFn?this.fetchFn(e,t):u(e))}catch{return L}if(n.status===404)return L;if(!n.ok)throw new Error(`Failed to fetch publisher config: ${e} (${n.status} ${n.statusText})`);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let s={version:r.version};return typeof r.package_url_template=="string"&&(N(e,"package_url_template",r.package_url_template),s.package_url_template=r.package_url_template),Array.isArray(r.featured_packages)&&r.featured_packages.every(i=>typeof i=="string")&&(s.featured_packages=r.featured_packages),s}resolvePackageUrl(t,e,n,r){let s=r.package_url_template??M,i=S(s,{publisher:t,package:e,version:n});return m(i),i}};function N(o,t,e){if(!e.startsWith("https://"))throw new Error(`Invalid publisher config at ${o}: ${t} must be an absolute https:// URL template (got "${e}").`)}function S(o,t){let e=o;for(let[r,s]of Object.entries(t))e=e.replaceAll(`{${r}}`,s);let n=e.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${o}`);return e}import $ from"js-yaml";var H=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
2
|
-
`,O="sha256:";function _(o){let t=$.load(o);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??"",packages:t.packages??{}}}function Q(o){let t={};for(let n of Object.keys(o.packages).sort())t[n]=o.packages[n];let e=$.dump({...o,packages:t},{lineWidth:-1,sortKeys:!1,quotingType:'"'});return H+e}async function Z(o){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)),e=Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("");return`${O}${e}`}var d=class{configResolver;fetchFn;lockCache=new Map;constructor(t){this.configResolver=t?.configResolver??new y(t?.fetchFn),this.fetchFn=t?.fetchFn}getConfig(t){return this.configResolver.getConfig(t)}async getPackageUrl(t,e,n){let r=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,e,n,r)}getLock(t){let e=this.lockCache.get(t);return e||(e=this.fetchLock(t),this.lockCache.set(t,e),e.catch(()=>{this.lockCache.get(t)===e&&this.lockCache.delete(t)})),e}async fetchLock(t){let e=`https://${t}/kanonak.lock`,n;try{n=this.fetchFn?await this.fetchFn(e,t):await u(e)}catch{return null}if(n.status===404)return null;if(!n.ok)throw new Error(`Failed to fetch publisher lock: ${e} (${n.status} ${n.statusText})`);return _(await n.text())}};import{VersionOperator as g}from"@kanonak-protocol/types/document/models/enums";function B(o,t){let e=A(o);if(!e)return!1;let n=t.version;switch(t.versionOperator){case g.Any:return!0;case g.Exact:return e.major===n.major&&e.minor===n.minor&&e.patch===n.patch;case g.Compatible:return e.major===n.major&&e.minor===n.minor&&e.patch>=n.patch;case g.Major:return e.major!==n.major?!1:e.minor!==n.minor?e.minor>n.minor:e.patch>=n.patch;default:return!1}}var U=class{parser=new R;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new d({fetchFn:t.fetchFn}):new d}async getHighestCompatibleVersionAsync(t,e){let r=(await this.publisherIndex.getLock(t))?.packages[`${t}/${e.packageName}`];return r&&B(r.version,e)?this.fetchPinned(t,e.packageName,r):r&&e.versionOperator!==g.Exact?null:this.resolveByDirectFetch(t,e)}async fetchPinned(t,e,n){let r=n.version,s=`${t}/${e}@${r}`,i=this.documents.get(s);if(i)return i;let a=f=>{let p=this.parser.parse(f);return v(p,t,e,r),p};if(this.getFromCache){let f=this.getFromCache(t,e,r);if(f){let p=a(f);return this.documents.set(s,p),this.contentCache.set(s,f),p}}let l=n.resolved,c=this.fetchFn?await this.fetchFn(l,t):await u(l);if(!c.ok)throw new Error(`Failed to fetch Kanonak package: ${l} (${c.status} ${c.statusText})`);let h=await c.text(),P=a(h);return this.onFetch&&this.onFetch(t,e,r,h),this.documents.set(s,P),this.contentCache.set(s,h),P}async resolveByDirectFetch(t,e){let n=e.packageName,s=e.versionOperator===g.Exact?await this.publisherIndex.getPackageUrl(t,n,F(e.version)):`https://${t}/${n}.kan.yml`,i=await this.fetchFollowing(s,t);if(!i)return null;let a=this.parser.parse(i.content),l=a.metadata.namespace_;if(!l||!l.version)throw new Error(`Producer origin returned a package with no namespace/version for ${t}/${n}`);let c=F(l.version);v(a,t,n,c);let h=`${t}/${n}@${c}`;return this.onFetch&&this.onFetch(t,n,c,i.content),this.documents.set(h,a),this.contentCache.set(h,i.content),a}async fetchFollowing(t,e,n=4){let r=t;for(let s=0;s<n;s++){m(r);let i=this.fetchFn?await this.fetchFn(r,e):await u(r,{redirect:"manual"});if(i.status===301||i.status===302){let a=i.headers.get("location");if(!a)throw new Error(`Redirect with no Location header from ${r}`);r=new URL(a,r).toString();continue}if(i.status===404)return null;if(!i.ok)throw new Error(`Failed to fetch Kanonak package: ${r} (${i.status} ${i.statusText})`);return{url:r,content:await i.text()}}throw new Error(`Too many redirects resolving ${t}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===t&&r.package_===e})}async saveDocumentAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let e=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,n,r,s]=e;return this.publisherIndex.getPackageUrl(n,r,s)}};export{b as a,q as b,G as c,m as d,u as e,V as f,X as g,y as h,O as i,_ as j,Q as k,Z as l,d as m,U as n};
|