@blue-labs/language 3.8.0 → 3.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +8 -8
- package/dist/index.mjs +1176 -1061
- package/dist/lib/utils/NodeTypeMatcher.d.ts +11 -0
- package/dist/lib/utils/NodeTypeMatcher.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("big.js"),u=require("@blue-labs/shared-utils"),c=require("zod"),cr=require("bs58"),V=require("radash"),b=require("@blue-labs/repository-contract"),dr=require("js-sha256"),pr=require("crypto"),hr=require("base32.js"),q=require("js-yaml"),gt=s=>s&&s.__esModule?s:{default:s},ue=gt(cr),xe=gt(pr);class P extends _{constructor(e){super(e)}}class w extends _{constructor(e){super(e)}}const Z="name",G="description",W="type",he="itemType",fe="keyType",ye="valueType",ge="value",Ae="items",x="blueId",Ve="blue",We=[Z,G,W,he,fe,ye,ge,Ae,x,Ve],mt="Text",It="Double",Tt="Integer",bt="Boolean",Nt="List",vt="Dictionary",Re=[mt,It,Tt,bt],He=[...Re,Nt,vt],j="DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",L="7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",z="5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",U="4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",qe="6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",Xe="G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",Qe=[j,L,z,U],X=[...Qe,qe,Xe],fr=Object.fromEntries(He.map((s,e)=>[s,X[e]])),Oe=Object.fromEntries(X.map((s,e)=>[s,He[e]])),yr=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:Re,BASIC_TYPE_BLUE_IDS:Qe,BOOLEAN_TYPE:bt,BOOLEAN_TYPE_BLUE_ID:U,CORE_TYPES:He,CORE_TYPE_BLUE_IDS:X,CORE_TYPE_BLUE_ID_TO_NAME_MAP:Oe,CORE_TYPE_NAME_TO_BLUE_ID_MAP:fr,DICTIONARY_TYPE:vt,DICTIONARY_TYPE_BLUE_ID:Xe,DOUBLE_TYPE:It,DOUBLE_TYPE_BLUE_ID:L,INTEGER_TYPE:Tt,INTEGER_TYPE_BLUE_ID:z,LIST_TYPE:Nt,LIST_TYPE_BLUE_ID:qe,OBJECT_BLUE:Ve,OBJECT_BLUE_ID:x,OBJECT_CONTRACTS:b.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:G,OBJECT_ITEMS:Ae,OBJECT_ITEM_TYPE:he,OBJECT_KEY_TYPE:fe,OBJECT_MERGE_POLICY:b.OBJECT_MERGE_POLICY,OBJECT_NAME:Z,OBJECT_SCHEMA:b.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:We,OBJECT_TYPE:W,OBJECT_VALUE:ge,OBJECT_VALUE_TYPE:ye,TEXT_TYPE:mt,TEXT_TYPE_BLUE_ID:j},Symbol.toStringTag,{value:"Module"}));class gr{static get(e,t,r,n=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return n&&o!==void 0?o:e}const i=t.substring(1).split("/");return this.getRecursive(e,i,0,r,n)}static getRecursive(e,t,r,n,i){if(r===t.length-1&&!i)return this.getNodeForSegment(e,t[r],n,!1);if(r===t.length){const a=e.getValue();return i&&a!==void 0?a:e}const o=t[r],l=this.getNodeForSegment(e,o,n,!0);if(l)return this.getRecursive(l,t,r+1,n,i)}static getNodeForSegment(e,t,r,n){let i;const o=e.getProperties();if(o&&t in o)i=o[t];else switch(t){case"name":{const l=e.getName();i=new d().setValue(l??null);break}case"description":{const l=e.getDescription();i=new d().setValue(l??null);break}case"type":i=e.getType();break;case"itemType":i=e.getItemType();break;case"keyType":i=e.getKeyType();break;case"valueType":i=e.getValueType();break;case"value":{const l=e.getValue();i=new d().setValue(l??null);break}case"blueId":{const l=e.getBlueId();i=new d().setValue(l??null);break}case"blue":i=e.getBlue();break;case"items":{const l=e.getItems();i=new d().setItems(l);break}case"properties":{const l=e.getProperties();i=new d().setProperties(l);break}case b.OBJECT_CONTRACTS:{const l=e.getContracts();i=new d().setContracts(l);break}default:{if(/^\d+$/.test(t)){const l=parseInt(t,10),a=e.getItems();a&&l>=0&&l<a.length?i=a[l]:i=void 0}else i=void 0;break}}if(i)return n&&r?this.link(i,r):i}static link(e,t){const r=t(e);return u.isNonNullable(r)?r:e}}class d{static INTEGER=new d("Integer");name;description;type;itemType;keyType;valueType;value;items;properties;blueId;blue;inlineValue=!1;constructor(e){this.name=e}getName(){return this.name}setName(e){return this.name=e,this}getDescription(){return this.description}setDescription(e){return this.description=e,this}getType(){return this.type}setType(e){return typeof e=="string"?this.type=new d().setValue(e).setInlineValue(!0):this.type=e,this}getItemType(){return this.itemType}setItemType(e){return typeof e=="string"?this.itemType=new d().setValue(e).setInlineValue(!0):this.itemType=e,this}getKeyType(){return this.keyType}setKeyType(e){return typeof e=="string"?this.keyType=new d().setValue(e).setInlineValue(!0):this.keyType=e,this}getValueType(){return this.valueType}setValueType(e){return typeof e=="string"?this.valueType=new d().setValue(e).setInlineValue(!0):this.valueType=e,this}getValue(){const e=this.type?.getBlueId();if(u.isNonNullable(e)&&u.isNonNullable(this.value)){if(e===z&&typeof this.value=="string")return new w(this.value);if(e===L&&typeof this.value=="string"){const t=new P(this.value),r=parseFloat(t.toString());return new P(r.toString())}else if(e===U&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new w(e.toString()):this.value=new P(e.toString()):this.value=e,this}getItems(){return this.items}setItems(e){return this.items=e,this}addItems(...e){return this.items||(this.items=[]),this.items.push(...e),this}getProperties(){return this.properties}setProperties(e){return this.properties=e,this}addProperty(e,t){return this.properties||(this.properties={}),this.properties[e]=t,this}removeProperty(e){return this.properties&&delete this.properties[e],this}getContractsProperty(){return this.properties?.[b.OBJECT_CONTRACTS]}getContracts(){return this.getContractsProperty()?.getProperties()}setContracts(e){return u.isNullable(e)?this.removeProperty(b.OBJECT_CONTRACTS):this.addProperty(b.OBJECT_CONTRACTS,new d().setProperties(e)),this}addContract(e,t){const r=this.getContractsProperty();return u.isNullable(r)?this.addProperty(b.OBJECT_CONTRACTS,new d().addProperty(e,t)):r.addProperty(e,t),this}removeContract(e){const t=this.getContractsProperty();if(t){t.removeProperty(e);const r=t.getProperties();r&&Object.keys(r).length===0&&this.removeProperty(b.OBJECT_CONTRACTS)}return this}getBlueId(){return this.blueId}setBlueId(e){return this.blueId=e,this}getBlue(){return this.blue}setBlue(e){return this.blue=e,this}isInlineValue(){return this.inlineValue}setInlineValue(e){return this.inlineValue=e,this}isResolved(){return!1}get(e,t){return gr.get(this,e,t)}getAsNode(e){const t=this.get(e);if(t instanceof d)return t;throw new Error(`Value at path ${e} is not a BlueNode: ${t}`)}getAsInteger(e){const t=this.get(e);if(t instanceof w||t instanceof P)return t.toNumber();throw new Error(`Value at path ${e} is not a BigInteger or BigDecimal: ${t}`)}clone(){const e=new d(this.name);return e.description=this.description,e.type=this.type?.clone(),e.itemType=this.itemType?.clone(),e.keyType=this.keyType?.clone(),e.valueType=this.valueType?.clone(),e.value=this.value,e.items=this.items?.map(t=>t.clone()),this.properties&&(e.properties=Object.fromEntries(Object.entries(this.properties).map(([t,r])=>[t,r.clone()]))),e.blueId=this.blueId,e.blue=this.blue?.clone(),e.inlineValue=this.inlineValue,e}cloneShallow(){const e=new d(this.name);return e.description=this.description,e.type=this.type,e.itemType=this.itemType,e.keyType=this.keyType,e.valueType=this.valueType,e.value=this.value,e.items=this.items?[...this.items]:void 0,e.properties=this.properties?{...this.properties}:void 0,e.blueId=this.blueId,e.blue=this.blue,e.inlineValue=this.inlineValue,e}toString(){return`BlueNode{name='${this.name}', description='${this.description}', type=${this.type}, itemType=${this.itemType}, keyType=${this.keyType}, valueType=${this.valueType}, value=${this.value}, items=${this.items}, properties=${this.properties}, blueId='${this.blueId}', blue=${this.blue}, inlineValue=${this.inlineValue}}`}}class Be{static MIN_BLUE_ID_LENGTH=41;static MAX_BLUE_ID_LENGTH=45;static BLUE_ID_PATTERN=/^[1-9A-HJ-NP-Za-km-z]{41,45}(?:#\d+)?$/;static isPotentialBlueId(e){if(!e||e.length===0||!this.BLUE_ID_PATTERN.test(e))return!1;const t=e.split("#"),r=t[0],n=r.length;if(n<this.MIN_BLUE_ID_LENGTH||n>this.MAX_BLUE_ID_LENGTH)return!1;try{if(ue.default.decode(r).length!==32)return!1}catch{return!1}if(t.length>1)try{if(Number(t[1])<0)return!1}catch{return!1}return!0}}const mr=c.z.string().max(Be.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(Be.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(s=>{try{return ue.default.decode(s),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),re=c.z.lazy(()=>c.z.record(c.z.unknown()).and(c.z.object({blueId:c.z.string().optional(),name:c.z.string().optional(),description:c.z.string().optional(),type:re.optional(),value:c.z.union([c.z.string(),c.z.number(),c.z.boolean()]).optional().nullable(),items:c.z.array(re).optional()}))),me=c.z.object({blueId:c.z.string().optional(),name:c.z.string().optional(),description:c.z.string().optional(),type:re.optional()}),Ir=me.extend({value:c.z.string().optional()}),Tr=me.extend({value:c.z.number().optional()}),br=me.extend({value:c.z.boolean().optional()}),Nr=me.extend({items:c.z.array(c.z.string()).optional()}),vr=s=>re.safeParse(s).success,Bt=s=>u.isNonNullable(s)&&"blueId"in s&&u.isNonNullable(s.blueId),Br=s=>u.isNonNullable(s)&&"name"in s&&u.isNonNullable(s.name),wt=s=>u.isNonNullable(s)&&"items"in s&&u.isNonNullable(s.items),Et=s=>u.isNonNullable(s)&&"type"in s&&u.isNonNullable(s.type),St=s=>u.isNonNullable(s)&&"value"in s&&u.isNonNullable(s.value),wr=(s,e)=>s.required({type:!0}).safeParse(e).success,C=s=>s instanceof _,F=s=>C(s)&&s instanceof w,we=s=>C(s)&&s instanceof P,Er=c.z.lazy(()=>c.z.record(ce)),Sr=c.z.lazy(()=>c.z.union([c.z.array(ce),c.z.array(ce).readonly()])),ce=c.z.lazy(()=>c.z.union([u.jsonPrimitiveSchema,Er,Sr,c.z.instanceof(_)])),et=s=>V.isObject(s)&&!V.isArray(s)&&!u.isReadonlyArray(s)&&!C(s),tt=s=>V.isArray(s)||u.isReadonlyArray(s),Pr=s=>tt(s)||et(s)||C(s)||u.isJsonPrimitive(s);class g{static deserialize(e){return g.handleNode(e)}static handleNode(e){if(e===void 0)throw new Error("This is not a valid JSON-like value. Found 'undefined' as a value.");if(et(e)){const t=new d,r={};return Object.entries(e).forEach(([n,i])=>{switch(n){case Z:if(i==null)t.setName(void 0);else{if(typeof i!="string")throw new Error(`The ${Z} field must be a string.`);t.setName(i)}break;case G:if(i==null)t.setDescription(void 0);else{if(typeof i!="string")throw new Error(`The ${G} field must be a string.`);t.setDescription(i)}break;case W:t.setType(g.handleNode(i));break;case he:t.setItemType(g.handleNode(i));break;case fe:t.setKeyType(g.handleNode(i));break;case ye:t.setValueType(g.handleNode(i));break;case ge:t.setValue(g.handleValue(i));break;case x:if(typeof i!="string")throw new Error(`The ${x} field must be a string.`);t.setBlueId(i);break;case Ae:t.setItems(g.handleArray(i));break;case Ve:t.setBlue(g.handleNode(i));break;default:r[n]=g.handleNode(i);break}}),Object.keys(r).length>0&&t.setProperties(r),t}else{if(tt(e))return new d().setItems(g.handleArray(e));{const t=e;return new d().setValue(g.handleValue(t)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||C(e))if(F(e)||Number.isSafeInteger(e)){const t=new w(e.toString()),r=Number.MIN_SAFE_INTEGER,n=Number.MAX_SAFE_INTEGER;return t.lt(r)?new w(r.toString()):t.gt(n)?new w(n.toString()):t}else{const t=parseFloat(e.toString());return new P(t.toString())}else if(typeof e=="boolean")return e;throw new Error(`Can't handle node: ${JSON.stringify(e)}`)}static handleArray(e){if(e!=null){if(V.isObject(e)&&!Array.isArray(e))return[g.handleNode(e)];if(Array.isArray(e))return e.map(g.handleNode);throw new Error("Expected an array node")}}}function Cr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Fe,ct;function Ar(){return ct||(ct=1,Fe=function s(e){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");return e===null||typeof e!="object"?JSON.stringify(e):e.toJSON instanceof Function?s(e.toJSON()):Array.isArray(e)?`[${e.reduce((n,i,o)=>`${n}${o===0?"":","}${s(i===void 0||typeof i=="symbol"?null:i)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,n)=>{if(e[n]===void 0||typeof e[n]=="symbol")return r;const i=r.length===0?"":",";return`${r}${i}${s(n)}:${s(e[n])}`},"")}}`}),Fe}var Vr=Ar();const Rr=Cr(Vr);class Ee{static canonicalize(e){return Rr(e)}}const $e=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class rt{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new rt),this.instance}initBrowserCrypto(){return $e?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return $e&&!!xe.default&&typeof xe.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return $e?xe.default:null}}class Pt{cryptoEnv=rt.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return ue.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return ue.default.encode(r)}canonicalizeInput(e){const t=Ee.canonicalize(e);if(typeof t!="string")throw new Error("Canonized value must be a string");return t}sha256Sync(e){const t=this.cryptoEnv.getNodeCrypto();if(!t)throw new Error("Synchronous SHA-256 is not available in this environment");const r=t.createHash("sha256").update(e).digest();return new Uint8Array(r)}sha256SyncBrowser(e){return new Uint8Array(dr.sha256.arrayBuffer(e))}async sha256Async(e){if(this.cryptoEnv.hasNodeCrypto())return Promise.resolve(this.sha256Sync(e));const t=this.cryptoEnv.getBrowserCrypto();if(!t)throw new Error("crypto is not available in this environment");const n=new TextEncoder().encode(e),i=await t.subtle.digest("SHA-256",n);return new Uint8Array(i)}}class m{static get(e,t="official"){const r=e.getValue(),n=this.handleValue(r);if(n!==void 0&&t==="simple")return n;const i=e.getItems()?.map(ee=>m.get(ee,t));if(i!==void 0&&t==="simple")return i;const o=e.getName(),l=e.getDescription();if(t==="original"&&o===void 0&&l===void 0){if(n!==void 0)return n;if(i!==void 0)return i}const a={};o!==void 0&&(a[Z]=o),l!==void 0&&(a[G]=l);const p=e.getType();if(t==="official"&&r!==void 0&&p===void 0){const ee=this.inferTypeBlueId(r);ee!==null&&(a[W]={[x]:ee})}else p!==void 0&&(a[W]=m.get(p,t));const y=e.getItemType();y!==void 0&&(a[he]=m.get(y,t));const h=e.getKeyType();h!==void 0&&(a[fe]=m.get(h,t));const f=e.getValueType();f!==void 0&&(a[ye]=m.get(f,t)),n!==void 0&&(a[ge]=n),i!==void 0&&(a[Ae]=i);const T=e.getBlueId();T!==void 0&&(a[x]=T);const k=e.getBlue();k!==void 0&&(a[Ve]=k);const Q=e.getProperties();return Q!==void 0&&Object.entries(Q).forEach(([ee,ur])=>{a[ee]=m.get(ur,t)}),a}static handleValue(e){if(C(e)){if(F(e)){const t=new _(Number.MIN_SAFE_INTEGER.toString()),r=new _(Number.MAX_SAFE_INTEGER.toString());if(e.lt(t)||e.gt(r))return e.toString()}return e.toNumber()}return e}static inferTypeBlueId(e){return typeof e=="string"?j:C(e)?F(e)?z:L:typeof e=="boolean"?U:null}}const Or=s=>u.isJsonPrimitive(s)&&u.isNonNullable(s);class I{static INSTANCE=new I(new Pt);hashProvider;constructor(e){this.hashProvider=e}static calculateBlueId(e){if(Array.isArray(e)){const r=e.map(n=>m.get(n));return I.INSTANCE.calculate(r)}const t=m.get(e);return I.INSTANCE.calculate(t)}static calculateBlueIdSync(e){if(Array.isArray(e)){const r=e.map(n=>m.get(n));return I.INSTANCE.calculateSync(r)}const t=m.get(e);return I.INSTANCE.calculateSync(t)}calculate(e){const t=this.cleanStructure(e);if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.internalCalculate(t,!1)}calculateSync(e){const t=this.cleanStructure(e);if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.internalCalculate(t,!0)}internalCalculate(e,t){return Or(e)||C(e)?this.applyHash(e.toString(),t):Array.isArray(e)||u.isReadonlyArray(e)?this.calculateList(e,t):this.calculateMap(e,t)}calculateMap(e,t){if(e[x]!==void 0)return e[x];const n=Object.keys(e).map(o=>{const l=e[o];if([Z,ge,G].includes(o))return t?[o,l]:Promise.resolve([o,l]);{const a=this.internalCalculate(l,t);return t?[o,{blueId:a}]:Promise.resolve(a).then(p=>[o,{blueId:p}])}}),i=o=>{const l={};for(const[a,p]of o)l[a]=p;return this.applyHash(l,t)};return t?i(n):Promise.all(n).then(i)}calculateList(e,t){if(e.length===0)throw new Error("Cannot calculate BlueId for an empty list.");let r=this.internalCalculate(e[0],t);const n=(i,o)=>t?this.applyHash([{blueId:i},{blueId:o}],!0):Promise.all([i,o]).then(([l,a])=>this.applyHash([{blueId:l},{blueId:a}],!1));for(let i=1;i<e.length;i++){const o=this.internalCalculate(e[i],t);r=n(r,o)}return r}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}cleanStructure(e){if(e!=null){if(u.isJsonPrimitive(e)||C(e))return e;if(Array.isArray(e)||u.isReadonlyArray(e)){const t=e.map(r=>this.cleanStructure(r)).filter(u.isNonNullable);return t.length>0?t:void 0}else if(typeof e=="object"){const t={};for(const r in e){const n=this.cleanStructure(e[r]);n!=null&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}else return e}}}class Dr{static convert(e){const t=ue.default.decode(e),r=new Uint8Array(2+t.length);r[0]=18,r[1]=32,r.set(t,2);const n=new Uint8Array(2+r.length);return n[0]=1,n[1]=85,n.set(r,2),"b"+new hr.Encoder({type:"rfc4648",lc:!0}).write(n).finalize().replace(/=/g,"")}}class B{static transform(e,t){const r=t(e.clone()),n=r.getType();n!==void 0&&r.setType(B.transform(n,t));const i=r.getItemType();i!==void 0&&r.setItemType(B.transform(i,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(B.transform(o,t));const l=r.getValueType();l!==void 0&&r.setValueType(B.transform(l,t));const a=r.getItems();if(a!==void 0){const y=a.map(h=>B.transform(h,t));r.setItems(y)}const p=r.getProperties();if(p!==void 0){const y=Object.keys(p).reduce((h,f)=>(h[f]=B.transform(p[f],t),h),{});r.setProperties(y)}return r}}const $=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof d),O=s=>s instanceof w||s instanceof P,Mr=s=>s.replace(/~1/g,"/").replace(/~0/g,"~");function ie(s){if(s==="/")return[];if(!s.startsWith("/"))throw new Error(`Path must start with '/': ${s}`);return s.split("/").slice(1).map(Mr)}function se(s){if(s==="-")return-1;const e=typeof s=="number"?s:parseInt(s,10);if(isNaN(e))throw new Error(`Invalid array index (NaN) from '${s}'`);if(!Number.isFinite(e))throw new Error(`Invalid array index '${s}' results in non-finite number ${e}`);return e}function Ct(s,e,t,r=!0){switch(e){case"name":return t?r?s.getName()??null:s:s.getName();case"description":return t?r?s.getDescription():s:s.getDescription();case"type":return s.getType();case"itemType":return s.getItemType();case"keyType":return s.getKeyType();case"valueType":return s.getValueType();case"value":return t?r?s.getValue()??null:s:s.getValue();case"blueId":return t?r?s.getBlueId()??null:s:s.getBlueId();case"blue":return s.getBlue();case"items":return s.getItems();case"properties":return s.getProperties();case b.OBJECT_CONTRACTS:return s.getContracts();default:return}}function dt(s,e,t=!0){if(s instanceof d){const r=Ct(s,e,!0,t);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",b.OBJECT_CONTRACTS].includes(e))return r;if(/^-?\d+$/.test(e)&&e!=="-"){const i=s.getItems(),o=parseInt(e,10);return i&&o>=0&&o<i.length?i[o]:void 0}const n=s.getProperties();return n&&e in n?n[e]:void 0}if(Array.isArray(s)){if(e==="-")return;const r=se(e);return r>=0&&r<s.length?s[r]:void 0}if($(s))return s[e]}function oe(s,e){if(e.length===0)return{parent:s,key:"value",actualTarget:s.getValue()??s};let t=s;for(let n=0;n<e.length-1;++n){const i=e[n],o=dt(t,i);if(o===void 0)throw new Error(`Cannot resolve '/${e.slice(0,n+1).join("/")}'`);t=o}const r=e[e.length-1];if(t instanceof d){const n=dt(t,r,!1);if((typeof n!="object"||n===null||O(n))&&!(n instanceof d)&&!Array.isArray(n)&&["name","description","value","blueId"].includes(r))return{parent:t,key:r,actualTarget:n}}return Array.isArray(t)&&r==="-"?{parent:t,key:"-"}:t instanceof d&&t.getItems()&&r==="-"?{parent:t,key:"-"}:{parent:t,key:Array.isArray(t)?se(r):r}}function st(s,e){if(s instanceof d){const t=e,r=Ct(s,t,!1);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",b.OBJECT_CONTRACTS].includes(t))return r;if(typeof e=="number"||typeof e=="string"&&/^\d+$/.test(e)){const n=s.getItems(),i=typeof e=="number"?e:parseInt(e,10);if(n&&i>=0&&i<n.length)return n[i]}return s.getProperties()?.[t]}return Array.isArray(s)||$(s)?s[e]:s}function S(s){if(s instanceof d)return s;if(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"||O(s))return g.deserialize(s);const e=ke(s);return g.deserialize(e)}function ke(s){if(s===void 0)return null;if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(ke);const e={};for(const[t,r]of Object.entries(s))e[t]=ke(r);return e}function nt(s,e,t){if(s instanceof d){const r=e;switch(r){case"name":s.setName(t);return;case"description":s.setDescription(t);return;case"type":s.setType(t instanceof d||typeof t=="string"||t===void 0?t:S(t));return;case"itemType":s.setItemType(t instanceof d||typeof t=="string"||t===void 0?t:S(t));return;case"keyType":s.setKeyType(t instanceof d||typeof t=="string"||t===void 0?t:S(t));return;case"valueType":s.setValueType(t instanceof d||typeof t=="string"||t===void 0?t:S(t));return;case"value":{const n=t;s.setValue(n===void 0?null:n);return}case"blueId":s.setBlueId(t);return;case"blue":s.setBlue(t instanceof d||t===void 0?t:S(t));return;case"items":s.setItems(t);return;case"properties":s.setProperties(t);return;case b.OBJECT_CONTRACTS:s.setContracts(t);return;default:{if(t===void 0){const n=s.getProperties();n&&r in n&&delete n[r]}else s.getProperties()||s.setProperties({}),s.addProperty(r,t instanceof d?t:S(t));return}}}Array.isArray(s)?s.splice(se(e),1):$(s)&&(t===void 0?delete s[e]:s[e]=t)}function _r(s,e,t,r){let n=-1;if(e!=="-"&&(n=typeof e=="number"?e:parseInt(e,10),isNaN(n)))throw new Error(`Invalid numeric key for BlueNode item operation: ${e}`);if(n<-1)throw new Error(`Invalid array index for BlueNode items: ${n}`);let i=s.getItems();if(i||(i=[],s.setItems(i)),!r&&n!==-1&&n>i.length)throw new Error(`ADD operation failed: Target array index '${n}' is greater than array length ${i.length}.`);if(e==="-")i.push(t);else if(r){if(n>=0)if(n<i.length)i[n]=t;else{for(let o=i.length;o<n;o++)i.push(g.deserialize(null));i.push(t)}}else i.splice(n,0,t)}function Se(s,e,t,r){if(Array.isArray(s)){const n=e==="-"?s.length:se(e);if(!r&&n>s.length)throw new Error(`ADD operation failed: Target array index '${n}' is greater than array length ${s.length}. Path involving key '${e}'.`);if(n<0&&e!=="-")throw new Error(`Invalid negative array index: ${e}`);const i=S(t);if(r){if(n>=0&&n<s.length)s[n]=i;else if(n>=s.length){for(let o=s.length;o<n;o++)s.push(g.deserialize(null));s.push(i)}}else s.splice(n,0,i);return}if(s instanceof d){e==="-"||typeof e=="number"&&!isNaN(e)||typeof e=="string"&&/^\d+$/.test(e)?_r(s,e,S(t),r):nt(s,e,t);return}if($(s)){s[e]=S(t);return}throw new Error(`Cannot insert into parent of type ${typeof s}`)}function xr(s,e){if(Array.isArray(s)){const t=se(e);t===-1&&e==="-"?s.length>0&&s.pop():t>=0&&t<s.length&&s.splice(t,1);return}if(s instanceof d){if(typeof e=="number"||typeof e=="string"&&/^-?\d+$/.test(e)){const t=s.getItems();if(t){const r=se(e);r===-1&&e==="-"?t.length>0&&t.pop():r>=0&&r<t.length&&t.splice(r,1),t.length===0&&s.setItems(void 0);return}}nt(s,e,void 0)}else $(s)&&delete s[e]}function Ye(s){if(s instanceof d)return s.clone();if(Array.isArray(s))return s.map(t=>Ye(t));if($(s)){const e={};return Object.keys(s).forEach(t=>{e[t]=Ye(s[t])}),e}return s}function K(s,e){if(s===e||s instanceof d&&(s.isInlineValue()||s.getValue()!==void 0)&&K(s.getValue()??null,e)||e instanceof d&&(e.isInlineValue()||e.getValue()!==void 0)&&K(s,e.getValue()??null))return!0;if(s instanceof d&&e instanceof d||O(s)&&O(e)||O(s)&&typeof e=="number"||typeof s=="number"&&O(e))return s.toString()===e.toString();if(Array.isArray(s)&&Array.isArray(e))return s.length===e.length&&s.every((t,r)=>K(t,e[r]));if($(s)&&$(e)){const t=Object.keys(s),r=Object.keys(e);return t.length===r.length&&t.every(n=>K(s[n],e[n]))}return!1}function At(s,e){const{parent:t,key:r}=oe(s,ie(e));return st(t,r)}function Vt(s,e,t){const r=ie(e);if(r.length===0&&e==="/"){const o=S(t);s.setValue(o.getValue()??null),o.getItems()?s.setItems(o.getItems()):s.setItems(void 0);return}const{parent:n,key:i}=oe(s,r);Se(n,i,t,!0)}function Fr(s,e,t){const r=ie(e);if(r.length===0&&e==="/"){if(s.getItems()&&Array.isArray(t)){const o=S(t);o.getItems()?(s.setItems(o.getItems()),s.setValue(null)):(s.setValue(o.getValue()??null),s.setItems(void 0))}else{const o=S(t);s.setValue(o.getValue()??null),o.getItems()&&s.setItems(o.getItems())}return!0}const{parent:n,key:i}=oe(s,r);return Se(n,i,t,!1),!0}function $r(s,e,t){const r=ie(e);if(r.length===0&&e==="/"){const l=S(t);return s.setValue(l.getValue()??null),l.getItems()?s.setItems(l.getItems()):s.setItems(void 0),!0}const{parent:n,key:i,actualTarget:o}=oe(s,r);if(o!==void 0&&n instanceof d)nt(n,i,t);else{const l=st(n,i),a=Array.isArray(n)||n instanceof d&&n.getItems()&&(typeof i=="number"||typeof i=="string"&&/^\d+$/.test(i));if(l===void 0){if(a)throw new Error(`REPLACE failed: Target array index '${i.toString()}' is out of bounds or does not exist at path '${e}'.`);Se(n,i,t,!0)}else Se(n,i,t,!0)}return!0}function Rt(s,e){const t=ie(e);if(t.length===0&&e==="/")return s.setValue(null),s.setItems(void 0),s.setProperties(void 0),!0;const{parent:r,key:n}=oe(s,t);return xr(r,n),!0}function jr(s,e,t){const r=Ye(At(s,e));return Vt(s,t,r),!0}function Lr(s,e,t){const r=ie(e),{parent:n,key:i}=oe(s,r),o=st(n,i);if(o===void 0)throw new Error(`MOVE failed: 'from' location '${e}' does not exist.`);return Rt(s,e)?(Vt(s,t,o),!0):!1}function zr(s,e,t){const r=At(s,e);let n=t;if(r instanceof d)if((t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||O(t))&&(r.isInlineValue()||r.getValue()!==void 0)){if(!K(r.getValue()??null,t))throw new Error(`TEST failed at '${e}': Expected ${JSON.stringify(t)}, got ${JSON.stringify(r.getValue()??null)}`);return!0}else typeof t=="object"&&!(t instanceof d)&&(n=S(t));else if(O(r)&&typeof t=="number")r instanceof w?n=new w(t.toString()):r instanceof P&&(n=new P(t.toString()));else if((r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&O(t)){const i=t;!K(r,i.toString())&&(typeof r=="number"&&parseFloat(i.toString()))}if(!K(r,n)){const i=r instanceof d?r.toString():JSON.stringify(r),o=n instanceof d?n.toString():JSON.stringify(n);throw new Error(`TEST failed at '${e}': Expected ${o}, got ${i}`)}return!0}function Ur(s,e){switch(e.op){case"add":return Fr(s,e.path,e.val);case"replace":return $r(s,e.path,e.val);case"remove":return Rt(s,e.path);case"copy":return jr(s,e.from,e.path);case"move":return Lr(s,e.from,e.path);case"test":return zr(s,e.path,e.val)}}function kr(s,e,t=!1){const r=t?s:s.clone();return Ur(r,e),r}const je=Symbol.for("zod-schema-annotations");function Yr(){if(typeof globalThis<"u")return globalThis;if(typeof global<"u")return global;if(typeof window<"u")return window;if(typeof self<"u")return self;throw new Error("Unable to locate global object")}function Ot(){const s=Yr();return je in s||(s[je]=new WeakMap),s[je]}function Ie(s,e){const t=Ot(),r=t.get(s)||{};return t.set(s,{...r,...e}),s}const R=s=>Ot().get(s),Dt=s=>e=>{const t=R(e);return Ie(e,{...t,blueDescription:s})},Mt=s=>{const e=R(s);return u.isNonNullable(e)&&V.isString(e.blueDescription)?e.blueDescription:null},Kr=s=>Dt(s)(c.z.string().optional()),Jr=c.z.union([c.z.string(),c.z.boolean()]),_t=s=>e=>{const t=R(e);return Ie(e,{...t,blueId:s})},xt=s=>{const e=R(s),t=Jr.safeParse(e?.blueId);return t.success?t.data:null},Zr=s=>_t(s??!0)(c.z.string()),Ft=s=>e=>{const t=R(e);return Ie(e,{...t,blueName:s})},$t=s=>{const e=R(s);return u.isNonNullable(e)&&V.isString(e.blueName)?e.blueName:null},Gr=s=>{const e=c.z.string().optional();return Ft(s)(e)},jt=()=>s=>{const e=R(s);return Ie(s,{...e,blueNode:!0})},Lt=s=>{const e=R(s);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},it=s=>!!Lt(s),Wr=()=>{const s=c.z.instanceof(d);return jt()(s)},Hr=c.z.object({value:c.z.array(c.z.string()).optional(),defaultValue:c.z.string().optional()}),zt=s=>{const e=R(s),t=Hr.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},qr=s=>e=>{const t=R(e),r=typeof s=="string"?{value:[s]}:s;return Ie(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class de{static resolveBlueId(e){const t=zt(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const n=t.value?.[0];return u.isNonNullable(n)?n:de.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}class A{static isTypeOf(e,t,r){const n=de.resolveBlueId(t),i=e.getType()?.getBlueId();if(u.isNullable(n)||u.isNullable(i))return!1;if(n===i)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const o=r.typeSchemaResolver.resolveSchema(e);return A.checkSchemaExtension(o,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const n=A.unwrapSchema(e),i=A.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(n,i):!1}static isWrapperType(e){return e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodReadonly||e instanceof c.ZodBranded||e instanceof c.ZodEffects||e instanceof c.ZodLazy}static unwrapSchema(e){return it(e)?e:A.isWrapperType(e)?e instanceof c.ZodEffects?A.unwrapSchema(e.innerType()):e instanceof c.ZodLazy?A.unwrapSchema(e.schema):A.unwrapSchema(e.unwrap()):e}}function pt(s,e){const t=s.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(X.includes(r)){const i=Oe[r];return new d().setBlueId(r).setName(i)}const n=e.fetchByBlueId(r);if(!n||n.length===0)return;if(n.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return n[0]}return t}function v(s,e,t){const r=I.calculateBlueIdSync(s),n=I.calculateBlueIdSync(e);if(r===n)return!0;if(r&&X.includes(r)){let a=e;for(;a!==void 0;){if(I.calculateBlueIdSync(a)===r)return!0;a=pt(a,t)}return!1}let i=s;const o=s.getBlueId();if(o){const a=t.fetchByBlueId(o);a&&a.length===1&&(i=a[0])}let l=i;for(;l!==void 0;){if(I.calculateBlueIdSync(l)===n)return!0;l=pt(l,t)}return!1}function Xr(s,e){return Qe.some(t=>{const r=new d().setBlueId(t);return v(s,r,e)})}function Qr(s,e){const t=new d().setBlueId(j);return v(s,t,e)}function es(s,e){const t=new d().setBlueId(z);return v(s,t,e)}function ts(s,e){const t=new d().setBlueId(L);return v(s,t,e)}function rs(s,e){const t=new d().setBlueId(U);return v(s,t,e)}function Ut(s,e){const t=new d().setBlueId(qe);return v(s,t,e)}function kt(s,e){const t=new d().setBlueId(Xe);return v(s,t,e)}function ss(s,e){return Re.some(t=>{const r=new d().setName(t);return v(s,r,e)})}function ns(s,e){for(const t of Re){const r=new d().setName(t);if(v(s,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${s.getName()||"unknown"}".`)}class Yt{blueIdMap=new Map;nodeProvider;constructor(e=[],t){this.nodeProvider=t?.nodeProvider??null,this.registerSchemas(e)}registerSchemas(e){for(const t of e)this.registerSchema(t)}registerSchema(e){const t=de.resolveBlueId(e);if(u.isNonNullable(t)){if(this.blueIdMap.has(t))throw new Error(`Duplicate BlueId value: ${t}`);this.blueIdMap.set(t,e)}}setNodeProvider(e){this.nodeProvider=e}resolveSchema(e){const t=this.getEffectiveBlueId(e);return u.isNullable(t)?null:this.blueIdMap.get(t)}isSchemaExtendedFrom(e,t){if(u.isNullable(e))return!1;const r=this.getBlueIdForSchema(e),n=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(n))return!1;if(r===n)return!0;if(u.isNonNullable(this.nodeProvider))try{const i=new d().setBlueId(r),o=new d().setBlueId(n);if(v(i,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=de.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,n]of this.blueIdMap)if(n===e||n._def===e._def)return r;return null}getEffectiveBlueId(e){const t=e.getType();return u.isNonNullable(t)&&u.isNonNullable(t.getBlueId())?t.getBlueId():u.isNonNullable(t)?I.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}const E={NAME:"name",DESCRIPTION:"description",TYPE:"type",BLUE_ID:"blue_id",KEY_TYPE:"key_type",VALUE_TYPE:"value_type",ITEM_TYPE:"item_type",VALUE:"value",PROPERTIES:"properties",BLUE:"blue",ITEMS:"items"};class Te{static isEmptyNode(e){return this.hasFieldsAndMayHaveFields(e)}static hasBlueIdOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([E.BLUE_ID]))}static hasItemsOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([E.ITEMS]))}static isValidValueNode(e){const t=e.getValue(),r=e.getProperties(),n=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(n)}static textNode(e){return new d().setType(new d().setBlueId(j)).setValue(e)}static integerNode(e){const t=e instanceof w?e:new w(e.toString());return new d().setType(new d().setBlueId(z)).setValue(t)}static doubleNode(e){const t=e instanceof P?e:new P(e.toString());return new d().setType(new d().setBlueId(L)).setValue(t)}static booleanNode(e){return new d().setType(new d().setBlueId(U)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const n of Object.values(E)){const i=u.isNonNullable(this.getFieldValue(e,n));if(t.has(n)){if(!i)return!1}else if(!r.has(n)){if(i)return!1}}return!0}static getFieldValue(e,t){switch(t){case E.NAME:return e.getName();case E.TYPE:return e.getType();case E.VALUE:return e.getValue();case E.DESCRIPTION:return e.getDescription();case E.PROPERTIES:return e.getProperties();case E.BLUE:return e.getBlue();case E.ITEMS:return e.getItems();case E.KEY_TYPE:return e.getKeyType();case E.VALUE_TYPE:return e.getValueType();case E.ITEM_TYPE:return e.getItemType();case E.BLUE_ID:return e.getBlueId();default:throw new Error(`Unknown field: ${t}`)}}}class De{}class le{static convert(e){const t=new Ke;return le.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const n=e.getProperties(),i=e.getItems(),o=n!==void 0&&Object.keys(n).length>0,l=i!==void 0&&i.length>0;if(!o&&!l){r.addPath(t===""?"/":t);return}if(n)for(const[a,p]of Object.entries(n)){const y=`${t}/${a}`;le.traverseNode(p,y,r)}if(i)for(let a=0;a<i.length;a++){const p=`${t}/${a}`;le.traverseNode(i[a],p,r)}}}function ht(s,e){const t=s.split(e),r=[...t].reverse().findIndex(i=>i!==""),n=r===-1?0:t.length-r;return t.slice(0,n)}class Me extends De{allowedPaths;maxDepth;currentPath=[];constructor(e,t){super(),this.allowedPaths=e,this.maxDepth=t}shouldExtendPathSegment(e){if(this.currentPath.length>=this.maxDepth)return!1;const t=this.normalizePath(this.getCurrentFullPath()+"/"+e);return this.isAllowedPath(t)}shouldMergePathSegment(e){return this.shouldExtendPathSegment(e)}isAllowedPath(e){for(const t of this.allowedPaths)if(this.matchesAllowedPath(t,e))return!0;return!1}matchesAllowedPath(e,t){const r=ht(e,"/"),n=ht(t,"/");if(n.length>r.length)return!1;for(let i=1;i<n.length;i++)if(r[i]!=="*"&&r[i]!==n[i])return!1;return!0}enterPathSegment(e){this.currentPath.push(e)}exitPathSegment(){this.currentPath.length>0&&this.currentPath.pop()}getCurrentFullPath(){return"/"+this.currentPath.join("/")}normalizePath(e){return"/"+e.split("/").filter(t=>t!=="").join("/")}static withMaxDepth(e){const t=new Ke().setMaxDepth(e);for(let r=1;r<=e;r++){const n="/"+Array(r).fill("*").join("/");t.addPath(n)}return t.build()}static withSinglePath(e){return new Ke().addPath(e).build()}static fromNode(e){return le.convert(e)}}class Ke{allowedPaths=new Set;maxDepth=Number.MAX_SAFE_INTEGER;addPath(e){return this.allowedPaths.add(e),this}setMaxDepth(e){return this.maxDepth=e,this}build(){return new Me(this.allowedPaths,this.maxDepth)}}class ve extends De{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class _e extends De{limits;constructor(e){super(),this.limits=e}shouldExtendPathSegment(e,t){return this.limits.every(r=>r.shouldExtendPathSegment(e,t))}shouldMergePathSegment(e,t){return this.limits.every(r=>r.shouldMergePathSegment(e,t))}enterPathSegment(e,t){this.limits.forEach(r=>{r.enterPathSegment(e,t)})}exitPathSegment(){this.limits.forEach(e=>{e.exitPathSegment()})}static of(...e){return new _e(e)}}const Y=new ve;class is{blue;constructor(e){this.blue=e}matchesType(e,t,r=Y){const n=t.getType();if(this.matchesImplicitStructure(e,n))return!0;const i=Me.fromNode(t),o=_e.of(r,i),l=this.extendAndResolve(e,o),a=this.blue.resolve(t,o);return this.verifyMatch(l,t,o)&&this.recursiveValueComparison(l,a)}extendAndResolve(e,t){const r=e.clone(),n=r.clone();this.blue.extend(n,t);const i=this.blue.resolve(n,t);return this.restoreMissingStructure(i,r),i}restoreMissingStructure(e,t){const r=t.getItems(),n=e.getItems();if(r&&r.length>0)if(!n||n.length===0)e.setItems(r.map(a=>a.clone()));else for(let a=0;a<Math.min(n.length,r.length);a++)this.restoreMissingStructure(n[a],r[a]);const i=t.getProperties();if(i){let a=e.getProperties();a||(a={},e.setProperties(a));for(const[p,y]of Object.entries(i)){const h=a[p];h===void 0?a[p]=y.clone():this.restoreMissingStructure(h,y)}}const o=t.getBlueId();e.getBlueId()===void 0&&o!==void 0&&e.setBlueId(o);const l=t.getValue();e.getValue()===void 0&&l!==void 0&&e.setValue(l)}verifyMatch(e,t,r){const n=t.getType();if(this.matchesImplicitStructure(e,n))return!0;const i=e.clone().setType(t.clone());try{this.blue.resolve(i,r)}catch{return!1}return!0}recursiveValueComparison(e,t){const r=t.getType(),n=this.matchesImplicitStructure(e,r);if(r&&!n){const h=e.getType();if(!h||!v(h,r,this.blue.getNodeProvider()))return!1}const i=t.getBlueId();if(!n&&i!==void 0){const h=e.getBlueId(),f=e.getType()?.getBlueId();if(h!==void 0){if(i!==h)return!1}else if(f===void 0||i!==f)return!1}const o=t.getValue();if(o!==void 0){const h=e.getValue();if(h===void 0)return!1;if(C(h)&&C(o)){if(!h.eq(o))return!1}else if(h!==o)return!1}const l=t.getItems();if(l!==void 0){const h=e.getItems()??[];for(let f=0;f<l.length;f++)if(f<h.length){if(!this.recursiveValueComparison(h[f],l[f]))return!1}else if(this.hasValueInNestedStructure(l[f]))return!1}const a=t.getItemType();if(a!==void 0){const h=e.getItems()??[];for(const f of h)if(!this.recursiveValueComparison(f,a))return!1}const p=t.getProperties();if(p!==void 0){const h=e.getProperties()??{};for(const[f,T]of Object.entries(p))if(f in h){if(!this.recursiveValueComparison(h[f],T))return!1}else if(this.hasValueInNestedStructure(T))return!1}const y=t.getValueType();if(y!==void 0){const h=Object.values(e.getProperties()??{});for(const f of h)if(!this.recursiveValueComparison(f,y))return!1}return!0}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const n of t)if(this.hasValueInNestedStructure(n))return!0}const r=e.getProperties();if(r!==void 0){for(const n of Object.values(r))if(this.hasValueInNestedStructure(n))return!0}return!1}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:Ut(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):kt(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isImplicitListStructure(e){return e.getItems()!==void 0&&e.getValue()===void 0}isImplicitDictionaryStructure(e){return e.getProperties()!==void 0&&e.getValue()===void 0}}const os=s=>s instanceof c.ZodOptional||s instanceof c.ZodNullable||s instanceof c.ZodReadonly||s instanceof c.ZodBranded||s instanceof c.ZodEffects||s instanceof c.ZodLazy,ls=s=>s instanceof c.ZodString||s instanceof c.ZodNumber||s instanceof c.ZodBoolean||s instanceof c.ZodBigInt;class Kt{static convertValue(e,t){const r=e.getType()?.getBlueId(),n=e.getValue();return u.isNullable(n)?ls(t)&&Te.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):n:j===r?this.convertFromString(String(n),t):L===r||n instanceof P?this.convertFromBigDecimal(new P(n?.toString()),t):z===r||n instanceof w?this.convertFromBigInteger(new w(n?.toString()),t):U===r||typeof n=="boolean"?this.convertFromBoolean(!!n,t):this.convertFromString(String(n),t)}static convertFromString(e,t){if(!t||t instanceof c.ZodString||t instanceof c.ZodEnum||t instanceof c.ZodNativeEnum)return e;if(t instanceof c.ZodNumber)return Number(e);if(t instanceof c.ZodBoolean)return e.toLowerCase()==="true";if(t instanceof c.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){if(t instanceof c.ZodNumber)return e.toNumber();if(t instanceof c.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){if(t instanceof c.ZodNumber)return e.toNumber();if(t instanceof c.ZodBigInt)return BigInt(e.toString());if(t instanceof c.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t||t instanceof c.ZodBoolean)return e;if(t instanceof c.ZodString)return e.toString();if(t instanceof c.ZodNumber)return Number(e);if(t instanceof c.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;if(e instanceof c.ZodNumber)return 0;if(e instanceof c.ZodBoolean)return!1;if(e instanceof c.ZodString)return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}class as{convert(e,t){return Kt.convertValue(e,t)}}class us{constructor(e){this.nodeToObjectConverter=e}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(t instanceof c.ZodIntersection){const r=t._def.left,n=t._def.right,i=this.convert(e,r),o=this.convert(e,n);return{...i,...o}}if(t instanceof c.ZodUnion)throw new Error("Union not supported");if(t instanceof c.ZodObject)return Object.keys(t.shape).reduce((n,i)=>{const o=e.getProperties(),l=t.shape[i],a=xt(l);if(u.isNonNullable(a)){const T=V.isString(a)?a:i,k=o?.[T],Q=k?I.calculateBlueIdSync(k):void 0;return n[i]=Q,n}const p=$t(l);if(u.isNonNullable(p)){const T=o?.[p];return n[i]=T?.getName(),n}const y=Mt(l);if(u.isNonNullable(y)){const T=o?.[y];return n[i]=T?.getDescription(),n}if(i==="name"){const T=e.getName();return n[i]=T,n}if(i==="description"){const T=e.getDescription();return n[i]=T,n}const h=o?.[i];if(u.isNullable(h))return n;const f=this.nodeToObjectConverter.convert(h,l);return n[i]=f,n},{});throw new Error("Unknown schema type, "+t._def.typeName)}}class cs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const n=t.element;return r.map(o=>this.nodeToObjectConverter.convert(o,n))}}class ds{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const n=t._def.valueType,i=r.map(o=>this.nodeToObjectConverter.convert(o,n));return new Set(i)}}class ps{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,n=t.valueSchema,i=new Map,o=e.getName();u.isNonNullable(o)&&i.set(Z,o);const l=e.getDescription();u.isNonNullable(l)&&i.set(G,l);const a=e.getProperties();return u.isNonNullable(a)&&Object.entries(a).forEach(([p,y])=>{const h=new d().setValue(p);h.setType(new d().setBlueId(j));const f=Kt.convertValue(h,r),T=this.nodeToObjectConverter.convert(y,n);i.set(f,T)}),t instanceof c.ZodRecord?Object.fromEntries(i):i}}class hs{convert(e){return m.get(e)}}class fs{convert(e){return m.get(e)}}class ys{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const n=t.items;return r.map((o,l)=>this.nodeToObjectConverter.convert(o,n[l]))}}const gs=c.z.union([c.z.literal("ZodString"),c.z.literal("ZodNumber"),c.z.literal("ZodBoolean"),c.z.literal("ZodBigInt"),c.z.literal("ZodArray"),c.z.literal("ZodSet"),c.z.literal("ZodMap"),c.z.literal("ZodRecord"),c.z.literal("ZodObject"),c.z.literal("ZodEnum"),c.z.literal("ZodNativeEnum"),c.z.literal("ZodUnknown"),c.z.literal("ZodAny"),c.z.literal("ZodTuple")]);class ms{constructor(e){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new us(this.nodeToObjectConverter)}converters=new Map;complexObjectConverter;registerConverters(){const e=new as,t=new cs(this.nodeToObjectConverter),r=new ys(this.nodeToObjectConverter),n=new ds(this.nodeToObjectConverter),i=new ps(this.nodeToObjectConverter);this.converters.set("ZodString",e),this.converters.set("ZodNumber",e),this.converters.set("ZodBoolean",e),this.converters.set("ZodBigInt",e),this.converters.set("ZodEnum",e),this.converters.set("ZodNativeEnum",e),this.converters.set("ZodUnknown",new hs),this.converters.set("ZodAny",new fs),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",n),this.converters.set("ZodMap",i),this.converters.set("ZodRecord",i),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){if(os(e))return e instanceof c.ZodEffects?this.getSchemaTypeName(e.innerType()):e instanceof c.ZodLazy?this.getSchemaTypeName(e.schema):this.getSchemaTypeName(e.unwrap());const t=e._def.typeName;try{return gs.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class Is{constructor(e){this.typeSchemaResolver=e,this.converterFactory=new ms(this)}converterFactory;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),n=A.unwrapSchema(t);if(it(n))return e;let i=n;return A.checkSchemaExtension(r,n,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(i=r),this.convertWithType(e,i)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class Jt{reverse(e){const t=new d;return this.reverseNode(t,e,e.getType()),t}reverseNode(e,t,r){this.isIdenticalToType(t,r)||(this.reverseBasicProperties(e,t,r),this.reverseTypeReferences(e,t,r),this.reverseItems(e,t,r),this.reverseProperties(e,t,r))}isIdenticalToType(e,t){return u.isNonNullable(e.getBlueId())&&u.isNonNullable(t?.getBlueId())&&e.getBlueId()===t.getBlueId()}reverseBasicProperties(e,t,r){const n=t.getValue();u.isNonNullable(n)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(n),u.isNonNullable(t.getName())&&(u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(u.isNullable(r)||t.getDescription()!==r.getDescription())&&e.setDescription(t.getDescription()),u.isNonNullable(t.getBlueId())&&(u.isNullable(r)||t.getBlueId()!==r.getBlueId())&&e.setBlueId(t.getBlueId())}reverseTypeReferences(e,t,r){const n=(i,o)=>{const l=i(t),a=r?i(r):void 0,p=l?.getBlueId();u.isNonNullable(p)&&(u.isNullable(a?.getBlueId())||p!==a.getBlueId())&&o(e,new d().setBlueId(p))};n(i=>i.getType(),(i,o)=>i.setType(o)),n(i=>i.getItemType(),(i,o)=>i.setItemType(o)),n(i=>i.getKeyType(),(i,o)=>i.setKeyType(o)),n(i=>i.getValueType(),(i,o)=>i.setValueType(o))}reverseItems(e,t,r){const n=t.getItems();if(u.isNullable(n))return;const i=r?.getItems(),o=[];if(u.isNonNullable(i)&&n.length>i.length&&u.isNonNullable(i)&&i.length>0){const p=I.calculateBlueIdSync(i);o.push(new d().setBlueId(p))}const a=i?.length||0;for(let p=a;p<n.length;p++){const y=new d;this.reverseNode(y,n[p],void 0),o.push(y)}o.length>0&&e.setItems(o)}reverseProperties(e,t,r){const n=t.getProperties();if(u.isNullable(n))return;const i={};for(const[o,l]of Object.entries(n)){const a=this.getInheritedProperty(o,t,r),p=new d;this.reverseNode(p,l,a),Te.isEmptyNode(p)||(i[o]=p)}Object.keys(i).length>0&&e.setProperties(i)}getInheritedProperty(e,t,r){const n=r?.getProperties()?.[e],i=t.getType()?.getProperties()?.[e];if(!(u.isNullable(n)&&u.isNullable(i)))return u.isNullable(n)?i:u.isNullable(i)?n:this.mergeNodes(n,i)}mergeNodes(e,t){const r=e.clone(),n=t.getValue();u.isNonNullable(n)&&r.setValue(n);const i=t.getType();u.isNonNullable(i)&&r.setType(i.clone());const o=t.getItemType();u.isNonNullable(o)&&r.setItemType(o.clone());const l=t.getKeyType();u.isNonNullable(l)&&r.setKeyType(l.clone());const a=t.getValueType();u.isNonNullable(a)&&r.setValueType(a.clone());const p=t.getProperties();if(u.isNonNullable(p)){const h=r.getProperties()||{};for(const[f,T]of Object.entries(p))h[f]=T.clone();r.setProperties(h)}const y=t.getItems();return u.isNonNullable(y)&&r.setItems(y.map(h=>h.clone())),r}}class H extends d{constructor(e){super(e.getName()),this.createFrom(e)}isResolved(){return!0}getMinimalNode(){return new Jt().reverse(this)}getMinimalBlueId(){const e=this.getMinimalNode();return I.calculateBlueIdSync(e)}clone(){const e=super.clone();return new H(e)}cloneShallow(){const e=super.cloneShallow();return new H(e)}createFrom(e){e.getName()!==this.getName()&&this.setName(e.getName()),this.setDescription(e.getDescription()).setType(e.getType()).setItemType(e.getItemType()).setKeyType(e.getKeyType()).setValueType(e.getValueType()).setItems(e.getItems()).setProperties(e.getProperties()).setBlueId(e.getBlueId()).setBlue(e.getBlue()).setInlineValue(e.isInlineValue());const t=e.getValue();t!==void 0&&this.setValue(t)}}class be{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function Ts(s){return new class extends be{fetchByBlueId(e){return s(e)}}}const Le=q.types.float.options,bs={...Le,construct:s=>{const e=s.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new P(e);if(Le.construct)return Le.construct(s)}},Ns=new q.Type("tag:yaml.org,2002:float",bs),ze=q.types.int.options,vs={...ze,construct:s=>{let e=s;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new w(e);if(ze.construct)return ze.construct(s)}},Bs=new q.Type("tag:yaml.org,2002:int",vs),Zt=q.CORE_SCHEMA.extend({implicit:[Ns,Bs]}),D=s=>{const e=q.load(s,{schema:Zt});return e===void 0?void 0:e},Gt=s=>q.dump(s,{schema:Zt,replacer:(e,t)=>{if(C(t)){if(F(t)){const r=new _(Number.MIN_SAFE_INTEGER.toString()),n=new _(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(n))return t.toString()}return t.toNumber()}return t}});class ws{static get(e,t={}){const{strategy:r="official"}=t,n=m.get(e,r);return Gt(n)}}class Es extends be{nodeProviders;constructor(e){super(),this.nodeProviders=e}fetchByBlueId(e){for(const t of this.nodeProviders){const r=t.fetchByBlueId(e);if(r&&r.length>0)return r}return[]}fetchFirstByBlueId(e){for(const t of this.nodeProviders){const r=t.fetchFirstByBlueId(e);if(r)return r}return null}getNodeProviders(){return this.nodeProviders}}const Wt=`- type:
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("big.js"),u=require("@blue-labs/shared-utils"),c=require("zod"),pr=require("bs58"),M=require("radash"),v=require("@blue-labs/repository-contract"),hr=require("js-sha256"),fr=require("crypto"),yr=require("base32.js"),te=require("js-yaml"),vt=s=>s&&s.__esModule?s:{default:s},de=vt(pr),Ue=vt(fr);class A extends U{constructor(e){super(e)}}class S extends U{constructor(e){super(e)}}const q="name",X="description",Q="type",ye="itemType",ge="keyType",me="valueType",Ie="value",Me="items",z="blueId",De="blue",et=[q,X,Q,ye,ge,me,Ie,Me,z,De],Nt="Text",Bt="Double",wt="Integer",Et="Boolean",St="List",Pt="Dictionary",xe=[Nt,Bt,wt,Et],tt=[...xe,St,Pt],Y="DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",J="7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",Z="5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",G="4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",rt="6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",st="G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",nt=[Y,J,Z,G],re=[...nt,rt,st],gr=Object.fromEntries(tt.map((s,e)=>[s,re[e]])),_e=Object.fromEntries(re.map((s,e)=>[s,tt[e]])),mr=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:xe,BASIC_TYPE_BLUE_IDS:nt,BOOLEAN_TYPE:Et,BOOLEAN_TYPE_BLUE_ID:G,CORE_TYPES:tt,CORE_TYPE_BLUE_IDS:re,CORE_TYPE_BLUE_ID_TO_NAME_MAP:_e,CORE_TYPE_NAME_TO_BLUE_ID_MAP:gr,DICTIONARY_TYPE:Pt,DICTIONARY_TYPE_BLUE_ID:st,DOUBLE_TYPE:Bt,DOUBLE_TYPE_BLUE_ID:J,INTEGER_TYPE:wt,INTEGER_TYPE_BLUE_ID:Z,LIST_TYPE:St,LIST_TYPE_BLUE_ID:rt,OBJECT_BLUE:De,OBJECT_BLUE_ID:z,OBJECT_CONTRACTS:v.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:X,OBJECT_ITEMS:Me,OBJECT_ITEM_TYPE:ye,OBJECT_KEY_TYPE:ge,OBJECT_MERGE_POLICY:v.OBJECT_MERGE_POLICY,OBJECT_NAME:q,OBJECT_SCHEMA:v.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:et,OBJECT_TYPE:Q,OBJECT_VALUE:Ie,OBJECT_VALUE_TYPE:me,TEXT_TYPE:Nt,TEXT_TYPE_BLUE_ID:Y},Symbol.toStringTag,{value:"Module"}));class Ir{static get(e,t,r,n=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return n&&o!==void 0?o:e}const i=t.substring(1).split("/");return this.getRecursive(e,i,0,r,n)}static getRecursive(e,t,r,n,i){if(r===t.length-1&&!i)return this.getNodeForSegment(e,t[r],n,!1);if(r===t.length){const a=e.getValue();return i&&a!==void 0?a:e}const o=t[r],l=this.getNodeForSegment(e,o,n,!0);if(l)return this.getRecursive(l,t,r+1,n,i)}static getNodeForSegment(e,t,r,n){let i;const o=e.getProperties();if(o&&t in o)i=o[t];else switch(t){case"name":{const l=e.getName();i=new d().setValue(l??null);break}case"description":{const l=e.getDescription();i=new d().setValue(l??null);break}case"type":i=e.getType();break;case"itemType":i=e.getItemType();break;case"keyType":i=e.getKeyType();break;case"valueType":i=e.getValueType();break;case"value":{const l=e.getValue();i=new d().setValue(l??null);break}case"blueId":{const l=e.getBlueId();i=new d().setValue(l??null);break}case"blue":i=e.getBlue();break;case"items":{const l=e.getItems();i=new d().setItems(l);break}case"properties":{const l=e.getProperties();i=new d().setProperties(l);break}case v.OBJECT_CONTRACTS:{const l=e.getContracts();i=new d().setContracts(l);break}default:{if(/^\d+$/.test(t)){const l=parseInt(t,10),a=e.getItems();a&&l>=0&&l<a.length?i=a[l]:i=void 0}else i=void 0;break}}if(i)return n&&r?this.link(i,r):i}static link(e,t){const r=t(e);return u.isNonNullable(r)?r:e}}class d{static INTEGER=new d("Integer");name;description;type;itemType;keyType;valueType;value;items;properties;blueId;blue;inlineValue=!1;constructor(e){this.name=e}getName(){return this.name}setName(e){return this.name=e,this}getDescription(){return this.description}setDescription(e){return this.description=e,this}getType(){return this.type}setType(e){return typeof e=="string"?this.type=new d().setValue(e).setInlineValue(!0):this.type=e,this}getItemType(){return this.itemType}setItemType(e){return typeof e=="string"?this.itemType=new d().setValue(e).setInlineValue(!0):this.itemType=e,this}getKeyType(){return this.keyType}setKeyType(e){return typeof e=="string"?this.keyType=new d().setValue(e).setInlineValue(!0):this.keyType=e,this}getValueType(){return this.valueType}setValueType(e){return typeof e=="string"?this.valueType=new d().setValue(e).setInlineValue(!0):this.valueType=e,this}getValue(){const e=this.type?.getBlueId();if(u.isNonNullable(e)&&u.isNonNullable(this.value)){if(e===Z&&typeof this.value=="string")return new S(this.value);if(e===J&&typeof this.value=="string"){const t=new A(this.value),r=parseFloat(t.toString());return new A(r.toString())}else if(e===G&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new S(e.toString()):this.value=new A(e.toString()):this.value=e,this}getItems(){return this.items}setItems(e){return this.items=e,this}addItems(...e){return this.items||(this.items=[]),this.items.push(...e),this}getProperties(){return this.properties}setProperties(e){return this.properties=e,this}addProperty(e,t){return this.properties||(this.properties={}),this.properties[e]=t,this}removeProperty(e){return this.properties&&delete this.properties[e],this}getContractsProperty(){return this.properties?.[v.OBJECT_CONTRACTS]}getContracts(){return this.getContractsProperty()?.getProperties()}setContracts(e){return u.isNullable(e)?this.removeProperty(v.OBJECT_CONTRACTS):this.addProperty(v.OBJECT_CONTRACTS,new d().setProperties(e)),this}addContract(e,t){const r=this.getContractsProperty();return u.isNullable(r)?this.addProperty(v.OBJECT_CONTRACTS,new d().addProperty(e,t)):r.addProperty(e,t),this}removeContract(e){const t=this.getContractsProperty();if(t){t.removeProperty(e);const r=t.getProperties();r&&Object.keys(r).length===0&&this.removeProperty(v.OBJECT_CONTRACTS)}return this}getBlueId(){return this.blueId}setBlueId(e){return this.blueId=e,this}getBlue(){return this.blue}setBlue(e){return this.blue=e,this}isInlineValue(){return this.inlineValue}setInlineValue(e){return this.inlineValue=e,this}isResolved(){return!1}get(e,t){return Ir.get(this,e,t)}getAsNode(e){const t=this.get(e);if(t instanceof d)return t;throw new Error(`Value at path ${e} is not a BlueNode: ${t}`)}getAsInteger(e){const t=this.get(e);if(t instanceof S||t instanceof A)return t.toNumber();throw new Error(`Value at path ${e} is not a BigInteger or BigDecimal: ${t}`)}clone(){const e=new d(this.name);return e.description=this.description,e.type=this.type?.clone(),e.itemType=this.itemType?.clone(),e.keyType=this.keyType?.clone(),e.valueType=this.valueType?.clone(),e.value=this.value,e.items=this.items?.map(t=>t.clone()),this.properties&&(e.properties=Object.fromEntries(Object.entries(this.properties).map(([t,r])=>[t,r.clone()]))),e.blueId=this.blueId,e.blue=this.blue?.clone(),e.inlineValue=this.inlineValue,e}cloneShallow(){const e=new d(this.name);return e.description=this.description,e.type=this.type,e.itemType=this.itemType,e.keyType=this.keyType,e.valueType=this.valueType,e.value=this.value,e.items=this.items?[...this.items]:void 0,e.properties=this.properties?{...this.properties}:void 0,e.blueId=this.blueId,e.blue=this.blue,e.inlineValue=this.inlineValue,e}toString(){return`BlueNode{name='${this.name}', description='${this.description}', type=${this.type}, itemType=${this.itemType}, keyType=${this.keyType}, valueType=${this.valueType}, value=${this.value}, items=${this.items}, properties=${this.properties}, blueId='${this.blueId}', blue=${this.blue}, inlineValue=${this.inlineValue}}`}}class Pe{static MIN_BLUE_ID_LENGTH=41;static MAX_BLUE_ID_LENGTH=45;static BLUE_ID_PATTERN=/^[1-9A-HJ-NP-Za-km-z]{41,45}(?:#\d+)?$/;static isPotentialBlueId(e){if(!e||e.length===0||!this.BLUE_ID_PATTERN.test(e))return!1;const t=e.split("#"),r=t[0],n=r.length;if(n<this.MIN_BLUE_ID_LENGTH||n>this.MAX_BLUE_ID_LENGTH)return!1;try{if(de.default.decode(r).length!==32)return!1}catch{return!1}if(t.length>1)try{if(Number(t[1])<0)return!1}catch{return!1}return!0}}const Tr=c.z.string().max(Pe.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(Pe.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(s=>{try{return de.default.decode(s),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),ne=c.z.lazy(()=>c.z.record(c.z.unknown()).and(c.z.object({blueId:c.z.string().optional(),name:c.z.string().optional(),description:c.z.string().optional(),type:ne.optional(),value:c.z.union([c.z.string(),c.z.number(),c.z.boolean()]).optional().nullable(),items:c.z.array(ne).optional()}))),Te=c.z.object({blueId:c.z.string().optional(),name:c.z.string().optional(),description:c.z.string().optional(),type:ne.optional()}),br=Te.extend({value:c.z.string().optional()}),vr=Te.extend({value:c.z.number().optional()}),Nr=Te.extend({value:c.z.boolean().optional()}),Br=Te.extend({items:c.z.array(c.z.string()).optional()}),wr=s=>ne.safeParse(s).success,Ct=s=>u.isNonNullable(s)&&"blueId"in s&&u.isNonNullable(s.blueId),Er=s=>u.isNonNullable(s)&&"name"in s&&u.isNonNullable(s.name),At=s=>u.isNonNullable(s)&&"items"in s&&u.isNonNullable(s.items),Rt=s=>u.isNonNullable(s)&&"type"in s&&u.isNonNullable(s.type),Vt=s=>u.isNonNullable(s)&&"value"in s&&u.isNonNullable(s.value),Sr=(s,e)=>s.required({type:!0}).safeParse(e).success,R=s=>s instanceof U,k=s=>R(s)&&s instanceof S,Ce=s=>R(s)&&s instanceof A,Pr=c.z.lazy(()=>c.z.record(pe)),Cr=c.z.lazy(()=>c.z.union([c.z.array(pe),c.z.array(pe).readonly()])),pe=c.z.lazy(()=>c.z.union([u.jsonPrimitiveSchema,Pr,Cr,c.z.instanceof(U)])),it=s=>M.isObject(s)&&!M.isArray(s)&&!u.isReadonlyArray(s)&&!R(s),ot=s=>M.isArray(s)||u.isReadonlyArray(s),Ar=s=>ot(s)||it(s)||R(s)||u.isJsonPrimitive(s);class y{static deserialize(e){return y.handleNode(e)}static handleNode(e){if(e===void 0)throw new Error("This is not a valid JSON-like value. Found 'undefined' as a value.");if(it(e)){const t=new d,r={};return Object.entries(e).forEach(([n,i])=>{switch(n){case q:if(i==null)t.setName(void 0);else{if(typeof i!="string")throw new Error(`The ${q} field must be a string.`);t.setName(i)}break;case X:if(i==null)t.setDescription(void 0);else{if(typeof i!="string")throw new Error(`The ${X} field must be a string.`);t.setDescription(i)}break;case Q:t.setType(y.handleNode(i));break;case ye:t.setItemType(y.handleNode(i));break;case ge:t.setKeyType(y.handleNode(i));break;case me:t.setValueType(y.handleNode(i));break;case Ie:t.setValue(y.handleValue(i));break;case z:if(typeof i!="string")throw new Error(`The ${z} field must be a string.`);t.setBlueId(i);break;case Me:t.setItems(y.handleArray(i));break;case De:t.setBlue(y.handleNode(i));break;default:r[n]=y.handleNode(i);break}}),Object.keys(r).length>0&&t.setProperties(r),t}else{if(ot(e))return new d().setItems(y.handleArray(e));{const t=e;return new d().setValue(y.handleValue(t)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||R(e))if(k(e)||Number.isSafeInteger(e)){const t=new S(e.toString()),r=Number.MIN_SAFE_INTEGER,n=Number.MAX_SAFE_INTEGER;return t.lt(r)?new S(r.toString()):t.gt(n)?new S(n.toString()):t}else{const t=parseFloat(e.toString());return new A(t.toString())}else if(typeof e=="boolean")return e;throw new Error(`Can't handle node: ${JSON.stringify(e)}`)}static handleArray(e){if(e!=null){if(M.isObject(e)&&!Array.isArray(e))return[y.handleNode(e)];if(Array.isArray(e))return e.map(y.handleNode);throw new Error("Expected an array node")}}}function Rr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var ze,yt;function Vr(){return yt||(yt=1,ze=function s(e){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");return e===null||typeof e!="object"?JSON.stringify(e):e.toJSON instanceof Function?s(e.toJSON()):Array.isArray(e)?`[${e.reduce((n,i,o)=>`${n}${o===0?"":","}${s(i===void 0||typeof i=="symbol"?null:i)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,n)=>{if(e[n]===void 0||typeof e[n]=="symbol")return r;const i=r.length===0?"":",";return`${r}${i}${s(n)}:${s(e[n])}`},"")}}`}),ze}var Or=Vr();const Mr=Rr(Or);class Ae{static canonicalize(e){return Mr(e)}}const ke=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class lt{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new lt),this.instance}initBrowserCrypto(){return ke?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return ke&&!!Ue.default&&typeof Ue.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return ke?Ue.default:null}}class Ot{cryptoEnv=lt.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return de.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return de.default.encode(r)}canonicalizeInput(e){const t=Ae.canonicalize(e);if(typeof t!="string")throw new Error("Canonized value must be a string");return t}sha256Sync(e){const t=this.cryptoEnv.getNodeCrypto();if(!t)throw new Error("Synchronous SHA-256 is not available in this environment");const r=t.createHash("sha256").update(e).digest();return new Uint8Array(r)}sha256SyncBrowser(e){return new Uint8Array(hr.sha256.arrayBuffer(e))}async sha256Async(e){if(this.cryptoEnv.hasNodeCrypto())return Promise.resolve(this.sha256Sync(e));const t=this.cryptoEnv.getBrowserCrypto();if(!t)throw new Error("crypto is not available in this environment");const n=new TextEncoder().encode(e),i=await t.subtle.digest("SHA-256",n);return new Uint8Array(i)}}class m{static get(e,t="official"){const r=e.getValue(),n=this.handleValue(r);if(n!==void 0&&t==="simple")return n;const i=e.getItems()?.map(_=>m.get(_,t));if(i!==void 0&&t==="simple")return i;const o=e.getName(),l=e.getDescription();if(t==="original"&&o===void 0&&l===void 0){if(n!==void 0)return n;if(i!==void 0)return i}const a={};o!==void 0&&(a[q]=o),l!==void 0&&(a[X]=l);const p=e.getType();if(t==="official"&&r!==void 0&&p===void 0){const _=this.inferTypeBlueId(r);_!==null&&(a[Q]={[z]:_})}else p!==void 0&&(a[Q]=m.get(p,t));const f=e.getItemType();f!==void 0&&(a[ye]=m.get(f,t));const h=e.getKeyType();h!==void 0&&(a[ge]=m.get(h,t));const g=e.getValueType();g!==void 0&&(a[me]=m.get(g,t)),n!==void 0&&(a[Ie]=n),i!==void 0&&(a[Me]=i);const T=e.getBlueId();T!==void 0&&(a[z]=T);const x=e.getBlue();x!==void 0&&(a[De]=x);const V=e.getProperties();return V!==void 0&&Object.entries(V).forEach(([_,b])=>{a[_]=m.get(b,t)}),a}static handleValue(e){if(R(e)){if(k(e)){const t=new U(Number.MIN_SAFE_INTEGER.toString()),r=new U(Number.MAX_SAFE_INTEGER.toString());if(e.lt(t)||e.gt(r))return e.toString()}return e.toNumber()}return e}static inferTypeBlueId(e){return typeof e=="string"?Y:R(e)?k(e)?Z:J:typeof e=="boolean"?G:null}}const Dr=s=>u.isJsonPrimitive(s)&&u.isNonNullable(s);class I{static INSTANCE=new I(new Ot);hashProvider;constructor(e){this.hashProvider=e}static calculateBlueId(e){if(Array.isArray(e)){const r=e.map(n=>m.get(n));return I.INSTANCE.calculate(r)}const t=m.get(e);return I.INSTANCE.calculate(t)}static calculateBlueIdSync(e){if(Array.isArray(e)){const r=e.map(n=>m.get(n));return I.INSTANCE.calculateSync(r)}const t=m.get(e);return I.INSTANCE.calculateSync(t)}calculate(e){const t=this.cleanStructure(e);if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.internalCalculate(t,!1)}calculateSync(e){const t=this.cleanStructure(e);if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.internalCalculate(t,!0)}internalCalculate(e,t){return Dr(e)||R(e)?this.applyHash(e.toString(),t):Array.isArray(e)||u.isReadonlyArray(e)?this.calculateList(e,t):this.calculateMap(e,t)}calculateMap(e,t){if(e[z]!==void 0)return e[z];const n=Object.keys(e).map(o=>{const l=e[o];if([q,Ie,X].includes(o))return t?[o,l]:Promise.resolve([o,l]);{const a=this.internalCalculate(l,t);return t?[o,{blueId:a}]:Promise.resolve(a).then(p=>[o,{blueId:p}])}}),i=o=>{const l={};for(const[a,p]of o)l[a]=p;return this.applyHash(l,t)};return t?i(n):Promise.all(n).then(i)}calculateList(e,t){if(e.length===0)throw new Error("Cannot calculate BlueId for an empty list.");let r=this.internalCalculate(e[0],t);const n=(i,o)=>t?this.applyHash([{blueId:i},{blueId:o}],!0):Promise.all([i,o]).then(([l,a])=>this.applyHash([{blueId:l},{blueId:a}],!1));for(let i=1;i<e.length;i++){const o=this.internalCalculate(e[i],t);r=n(r,o)}return r}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}cleanStructure(e){if(e!=null){if(u.isJsonPrimitive(e)||R(e))return e;if(Array.isArray(e)||u.isReadonlyArray(e)){const t=e.map(r=>this.cleanStructure(r)).filter(u.isNonNullable);return t.length>0?t:void 0}else if(typeof e=="object"){const t={};for(const r in e){const n=this.cleanStructure(e[r]);n!=null&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}else return e}}}class xr{static convert(e){const t=de.default.decode(e),r=new Uint8Array(2+t.length);r[0]=18,r[1]=32,r.set(t,2);const n=new Uint8Array(2+r.length);return n[0]=1,n[1]=85,n.set(r,2),"b"+new yr.Encoder({type:"rfc4648",lc:!0}).write(n).finalize().replace(/=/g,"")}}class E{static transform(e,t){const r=t(e.clone()),n=r.getType();n!==void 0&&r.setType(E.transform(n,t));const i=r.getItemType();i!==void 0&&r.setItemType(E.transform(i,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(E.transform(o,t));const l=r.getValueType();l!==void 0&&r.setValueType(E.transform(l,t));const a=r.getItems();if(a!==void 0){const f=a.map(h=>E.transform(h,t));r.setItems(f)}const p=r.getProperties();if(p!==void 0){const f=Object.keys(p).reduce((h,g)=>(h[g]=E.transform(p[g],t),h),{});r.setProperties(f)}return r}}const K=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof d),F=s=>s instanceof S||s instanceof A,_r=s=>s.replace(/~1/g,"/").replace(/~0/g,"~");function le(s){if(s==="/")return[];if(!s.startsWith("/"))throw new Error(`Path must start with '/': ${s}`);return s.split("/").slice(1).map(_r)}function ie(s){if(s==="-")return-1;const e=typeof s=="number"?s:parseInt(s,10);if(isNaN(e))throw new Error(`Invalid array index (NaN) from '${s}'`);if(!Number.isFinite(e))throw new Error(`Invalid array index '${s}' results in non-finite number ${e}`);return e}function Mt(s,e,t,r=!0){switch(e){case"name":return t?r?s.getName()??null:s:s.getName();case"description":return t?r?s.getDescription():s:s.getDescription();case"type":return s.getType();case"itemType":return s.getItemType();case"keyType":return s.getKeyType();case"valueType":return s.getValueType();case"value":return t?r?s.getValue()??null:s:s.getValue();case"blueId":return t?r?s.getBlueId()??null:s:s.getBlueId();case"blue":return s.getBlue();case"items":return s.getItems();case"properties":return s.getProperties();case v.OBJECT_CONTRACTS:return s.getContracts();default:return}}function gt(s,e,t=!0){if(s instanceof d){const r=Mt(s,e,!0,t);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",v.OBJECT_CONTRACTS].includes(e))return r;if(/^-?\d+$/.test(e)&&e!=="-"){const i=s.getItems(),o=parseInt(e,10);return i&&o>=0&&o<i.length?i[o]:void 0}const n=s.getProperties();return n&&e in n?n[e]:void 0}if(Array.isArray(s)){if(e==="-")return;const r=ie(e);return r>=0&&r<s.length?s[r]:void 0}if(K(s))return s[e]}function ae(s,e){if(e.length===0)return{parent:s,key:"value",actualTarget:s.getValue()??s};let t=s;for(let n=0;n<e.length-1;++n){const i=e[n],o=gt(t,i);if(o===void 0)throw new Error(`Cannot resolve '/${e.slice(0,n+1).join("/")}'`);t=o}const r=e[e.length-1];if(t instanceof d){const n=gt(t,r,!1);if((typeof n!="object"||n===null||F(n))&&!(n instanceof d)&&!Array.isArray(n)&&["name","description","value","blueId"].includes(r))return{parent:t,key:r,actualTarget:n}}return Array.isArray(t)&&r==="-"?{parent:t,key:"-"}:t instanceof d&&t.getItems()&&r==="-"?{parent:t,key:"-"}:{parent:t,key:Array.isArray(t)?ie(r):r}}function at(s,e){if(s instanceof d){const t=e,r=Mt(s,t,!1);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",v.OBJECT_CONTRACTS].includes(t))return r;if(typeof e=="number"||typeof e=="string"&&/^\d+$/.test(e)){const n=s.getItems(),i=typeof e=="number"?e:parseInt(e,10);if(n&&i>=0&&i<n.length)return n[i]}return s.getProperties()?.[t]}return Array.isArray(s)||K(s)?s[e]:s}function C(s){if(s instanceof d)return s;if(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"||F(s))return y.deserialize(s);const e=Ge(s);return y.deserialize(e)}function Ge(s){if(s===void 0)return null;if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(Ge);const e={};for(const[t,r]of Object.entries(s))e[t]=Ge(r);return e}function ut(s,e,t){if(s instanceof d){const r=e;switch(r){case"name":s.setName(t);return;case"description":s.setDescription(t);return;case"type":s.setType(t instanceof d||typeof t=="string"||t===void 0?t:C(t));return;case"itemType":s.setItemType(t instanceof d||typeof t=="string"||t===void 0?t:C(t));return;case"keyType":s.setKeyType(t instanceof d||typeof t=="string"||t===void 0?t:C(t));return;case"valueType":s.setValueType(t instanceof d||typeof t=="string"||t===void 0?t:C(t));return;case"value":{const n=t;s.setValue(n===void 0?null:n);return}case"blueId":s.setBlueId(t);return;case"blue":s.setBlue(t instanceof d||t===void 0?t:C(t));return;case"items":s.setItems(t);return;case"properties":s.setProperties(t);return;case v.OBJECT_CONTRACTS:s.setContracts(t);return;default:{if(t===void 0){const n=s.getProperties();n&&r in n&&delete n[r]}else s.getProperties()||s.setProperties({}),s.addProperty(r,t instanceof d?t:C(t));return}}}Array.isArray(s)?s.splice(ie(e),1):K(s)&&(t===void 0?delete s[e]:s[e]=t)}function Fr(s,e,t,r){let n=-1;if(e!=="-"&&(n=typeof e=="number"?e:parseInt(e,10),isNaN(n)))throw new Error(`Invalid numeric key for BlueNode item operation: ${e}`);if(n<-1)throw new Error(`Invalid array index for BlueNode items: ${n}`);let i=s.getItems();if(i||(i=[],s.setItems(i)),!r&&n!==-1&&n>i.length)throw new Error(`ADD operation failed: Target array index '${n}' is greater than array length ${i.length}.`);if(e==="-")i.push(t);else if(r){if(n>=0)if(n<i.length)i[n]=t;else{for(let o=i.length;o<n;o++)i.push(y.deserialize(null));i.push(t)}}else i.splice(n,0,t)}function Re(s,e,t,r){if(Array.isArray(s)){const n=e==="-"?s.length:ie(e);if(!r&&n>s.length)throw new Error(`ADD operation failed: Target array index '${n}' is greater than array length ${s.length}. Path involving key '${e}'.`);if(n<0&&e!=="-")throw new Error(`Invalid negative array index: ${e}`);const i=C(t);if(r){if(n>=0&&n<s.length)s[n]=i;else if(n>=s.length){for(let o=s.length;o<n;o++)s.push(y.deserialize(null));s.push(i)}}else s.splice(n,0,i);return}if(s instanceof d){e==="-"||typeof e=="number"&&!isNaN(e)||typeof e=="string"&&/^\d+$/.test(e)?Fr(s,e,C(t),r):ut(s,e,t);return}if(K(s)){s[e]=C(t);return}throw new Error(`Cannot insert into parent of type ${typeof s}`)}function $r(s,e){if(Array.isArray(s)){const t=ie(e);t===-1&&e==="-"?s.length>0&&s.pop():t>=0&&t<s.length&&s.splice(t,1);return}if(s instanceof d){if(typeof e=="number"||typeof e=="string"&&/^-?\d+$/.test(e)){const t=s.getItems();if(t){const r=ie(e);r===-1&&e==="-"?t.length>0&&t.pop():r>=0&&r<t.length&&t.splice(r,1),t.length===0&&s.setItems(void 0);return}}ut(s,e,void 0)}else K(s)&&delete s[e]}function We(s){if(s instanceof d)return s.clone();if(Array.isArray(s))return s.map(t=>We(t));if(K(s)){const e={};return Object.keys(s).forEach(t=>{e[t]=We(s[t])}),e}return s}function W(s,e){if(s===e||s instanceof d&&(s.isInlineValue()||s.getValue()!==void 0)&&W(s.getValue()??null,e)||e instanceof d&&(e.isInlineValue()||e.getValue()!==void 0)&&W(s,e.getValue()??null))return!0;if(s instanceof d&&e instanceof d||F(s)&&F(e)||F(s)&&typeof e=="number"||typeof s=="number"&&F(e))return s.toString()===e.toString();if(Array.isArray(s)&&Array.isArray(e))return s.length===e.length&&s.every((t,r)=>W(t,e[r]));if(K(s)&&K(e)){const t=Object.keys(s),r=Object.keys(e);return t.length===r.length&&t.every(n=>W(s[n],e[n]))}return!1}function Dt(s,e){const{parent:t,key:r}=ae(s,le(e));return at(t,r)}function xt(s,e,t){const r=le(e);if(r.length===0&&e==="/"){const o=C(t);s.setValue(o.getValue()??null),o.getItems()?s.setItems(o.getItems()):s.setItems(void 0);return}const{parent:n,key:i}=ae(s,r);Re(n,i,t,!0)}function jr(s,e,t){const r=le(e);if(r.length===0&&e==="/"){if(s.getItems()&&Array.isArray(t)){const o=C(t);o.getItems()?(s.setItems(o.getItems()),s.setValue(null)):(s.setValue(o.getValue()??null),s.setItems(void 0))}else{const o=C(t);s.setValue(o.getValue()??null),o.getItems()&&s.setItems(o.getItems())}return!0}const{parent:n,key:i}=ae(s,r);return Re(n,i,t,!1),!0}function Lr(s,e,t){const r=le(e);if(r.length===0&&e==="/"){const l=C(t);return s.setValue(l.getValue()??null),l.getItems()?s.setItems(l.getItems()):s.setItems(void 0),!0}const{parent:n,key:i,actualTarget:o}=ae(s,r);if(o!==void 0&&n instanceof d)ut(n,i,t);else{const l=at(n,i),a=Array.isArray(n)||n instanceof d&&n.getItems()&&(typeof i=="number"||typeof i=="string"&&/^\d+$/.test(i));if(l===void 0){if(a)throw new Error(`REPLACE failed: Target array index '${i.toString()}' is out of bounds or does not exist at path '${e}'.`);Re(n,i,t,!0)}else Re(n,i,t,!0)}return!0}function _t(s,e){const t=le(e);if(t.length===0&&e==="/")return s.setValue(null),s.setItems(void 0),s.setProperties(void 0),!0;const{parent:r,key:n}=ae(s,t);return $r(r,n),!0}function Ur(s,e,t){const r=We(Dt(s,e));return xt(s,t,r),!0}function zr(s,e,t){const r=le(e),{parent:n,key:i}=ae(s,r),o=at(n,i);if(o===void 0)throw new Error(`MOVE failed: 'from' location '${e}' does not exist.`);return _t(s,e)?(xt(s,t,o),!0):!1}function kr(s,e,t){const r=Dt(s,e);let n=t;if(r instanceof d)if((t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||F(t))&&(r.isInlineValue()||r.getValue()!==void 0)){if(!W(r.getValue()??null,t))throw new Error(`TEST failed at '${e}': Expected ${JSON.stringify(t)}, got ${JSON.stringify(r.getValue()??null)}`);return!0}else typeof t=="object"&&!(t instanceof d)&&(n=C(t));else if(F(r)&&typeof t=="number")r instanceof S?n=new S(t.toString()):r instanceof A&&(n=new A(t.toString()));else if((r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&F(t)){const i=t;!W(r,i.toString())&&(typeof r=="number"&&parseFloat(i.toString()))}if(!W(r,n)){const i=r instanceof d?r.toString():JSON.stringify(r),o=n instanceof d?n.toString():JSON.stringify(n);throw new Error(`TEST failed at '${e}': Expected ${o}, got ${i}`)}return!0}function Kr(s,e){switch(e.op){case"add":return jr(s,e.path,e.val);case"replace":return Lr(s,e.path,e.val);case"remove":return _t(s,e.path);case"copy":return Ur(s,e.from,e.path);case"move":return zr(s,e.from,e.path);case"test":return kr(s,e.path,e.val)}}function Yr(s,e,t=!1){const r=t?s:s.clone();return Kr(r,e),r}const Ke=Symbol.for("zod-schema-annotations");function Jr(){if(typeof globalThis<"u")return globalThis;if(typeof global<"u")return global;if(typeof window<"u")return window;if(typeof self<"u")return self;throw new Error("Unable to locate global object")}function Ft(){const s=Jr();return Ke in s||(s[Ke]=new WeakMap),s[Ke]}function be(s,e){const t=Ft(),r=t.get(s)||{};return t.set(s,{...r,...e}),s}const D=s=>Ft().get(s),$t=s=>e=>{const t=D(e);return be(e,{...t,blueDescription:s})},jt=s=>{const e=D(s);return u.isNonNullable(e)&&M.isString(e.blueDescription)?e.blueDescription:null},Zr=s=>$t(s)(c.z.string().optional()),Gr=c.z.union([c.z.string(),c.z.boolean()]),Lt=s=>e=>{const t=D(e);return be(e,{...t,blueId:s})},Ut=s=>{const e=D(s),t=Gr.safeParse(e?.blueId);return t.success?t.data:null},Wr=s=>Lt(s??!0)(c.z.string()),zt=s=>e=>{const t=D(e);return be(e,{...t,blueName:s})},kt=s=>{const e=D(s);return u.isNonNullable(e)&&M.isString(e.blueName)?e.blueName:null},Hr=s=>{const e=c.z.string().optional();return zt(s)(e)},Kt=()=>s=>{const e=D(s);return be(s,{...e,blueNode:!0})},Yt=s=>{const e=D(s);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},ct=s=>!!Yt(s),qr=()=>{const s=c.z.instanceof(d);return Kt()(s)},Xr=c.z.object({value:c.z.array(c.z.string()).optional(),defaultValue:c.z.string().optional()}),Jt=s=>{const e=D(s),t=Xr.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},Qr=s=>e=>{const t=D(e),r=typeof s=="string"?{value:[s]}:s;return be(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class he{static resolveBlueId(e){const t=Jt(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const n=t.value?.[0];return u.isNonNullable(n)?n:he.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}class O{static isTypeOf(e,t,r){const n=he.resolveBlueId(t),i=e.getType()?.getBlueId();if(u.isNullable(n)||u.isNullable(i))return!1;if(n===i)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const o=r.typeSchemaResolver.resolveSchema(e);return O.checkSchemaExtension(o,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const n=O.unwrapSchema(e),i=O.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(n,i):!1}static isWrapperType(e){return e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodReadonly||e instanceof c.ZodBranded||e instanceof c.ZodEffects||e instanceof c.ZodLazy}static unwrapSchema(e){return ct(e)?e:O.isWrapperType(e)?e instanceof c.ZodEffects?O.unwrapSchema(e.innerType()):e instanceof c.ZodLazy?O.unwrapSchema(e.schema):O.unwrapSchema(e.unwrap()):e}}function mt(s,e){const t=s.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(re.includes(r)){const i=_e[r];return new d().setBlueId(r).setName(i)}const n=e.fetchByBlueId(r);if(!n||n.length===0)return;if(n.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return n[0]}return t}function B(s,e,t){const r=I.calculateBlueIdSync(s),n=I.calculateBlueIdSync(e);if(r===n)return!0;if(r&&re.includes(r)){let a=e;for(;a!==void 0;){if(I.calculateBlueIdSync(a)===r)return!0;a=mt(a,t)}return!1}let i=s;const o=s.getBlueId();if(o){const a=t.fetchByBlueId(o);a&&a.length===1&&(i=a[0])}let l=i;for(;l!==void 0;){if(I.calculateBlueIdSync(l)===n)return!0;l=mt(l,t)}return!1}function es(s,e){return nt.some(t=>{const r=new d().setBlueId(t);return B(s,r,e)})}function ts(s,e){const t=new d().setBlueId(Y);return B(s,t,e)}function rs(s,e){const t=new d().setBlueId(Z);return B(s,t,e)}function ss(s,e){const t=new d().setBlueId(J);return B(s,t,e)}function ns(s,e){const t=new d().setBlueId(G);return B(s,t,e)}function we(s,e){const t=new d().setBlueId(rt);return B(s,t,e)}function Ee(s,e){const t=new d().setBlueId(st);return B(s,t,e)}function is(s,e){return xe.some(t=>{const r=new d().setName(t);return B(s,r,e)})}function os(s,e){for(const t of xe){const r=new d().setName(t);if(B(s,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${s.getName()||"unknown"}".`)}class Zt{blueIdMap=new Map;nodeProvider;constructor(e=[],t){this.nodeProvider=t?.nodeProvider??null,this.registerSchemas(e)}registerSchemas(e){for(const t of e)this.registerSchema(t)}registerSchema(e){const t=he.resolveBlueId(e);if(u.isNonNullable(t)){if(this.blueIdMap.has(t))throw new Error(`Duplicate BlueId value: ${t}`);this.blueIdMap.set(t,e)}}setNodeProvider(e){this.nodeProvider=e}resolveSchema(e){const t=this.getEffectiveBlueId(e);return u.isNullable(t)?null:this.blueIdMap.get(t)}isSchemaExtendedFrom(e,t){if(u.isNullable(e))return!1;const r=this.getBlueIdForSchema(e),n=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(n))return!1;if(r===n)return!0;if(u.isNonNullable(this.nodeProvider))try{const i=new d().setBlueId(r),o=new d().setBlueId(n);if(B(i,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=he.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,n]of this.blueIdMap)if(n===e||n._def===e._def)return r;return null}getEffectiveBlueId(e){const t=e.getType();return u.isNonNullable(t)&&u.isNonNullable(t.getBlueId())?t.getBlueId():u.isNonNullable(t)?I.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}const P={NAME:"name",DESCRIPTION:"description",TYPE:"type",BLUE_ID:"blue_id",KEY_TYPE:"key_type",VALUE_TYPE:"value_type",ITEM_TYPE:"item_type",VALUE:"value",PROPERTIES:"properties",BLUE:"blue",ITEMS:"items"};class ve{static isEmptyNode(e){return this.hasFieldsAndMayHaveFields(e)}static hasBlueIdOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([P.BLUE_ID]))}static hasItemsOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([P.ITEMS]))}static isValidValueNode(e){const t=e.getValue(),r=e.getProperties(),n=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(n)}static textNode(e){return new d().setType(new d().setBlueId(Y)).setValue(e)}static integerNode(e){const t=e instanceof S?e:new S(e.toString());return new d().setType(new d().setBlueId(Z)).setValue(t)}static doubleNode(e){const t=e instanceof A?e:new A(e.toString());return new d().setType(new d().setBlueId(J)).setValue(t)}static booleanNode(e){return new d().setType(new d().setBlueId(G)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const n of Object.values(P)){const i=u.isNonNullable(this.getFieldValue(e,n));if(t.has(n)){if(!i)return!1}else if(!r.has(n)){if(i)return!1}}return!0}static getFieldValue(e,t){switch(t){case P.NAME:return e.getName();case P.TYPE:return e.getType();case P.VALUE:return e.getValue();case P.DESCRIPTION:return e.getDescription();case P.PROPERTIES:return e.getProperties();case P.BLUE:return e.getBlue();case P.ITEMS:return e.getItems();case P.KEY_TYPE:return e.getKeyType();case P.VALUE_TYPE:return e.getValueType();case P.ITEM_TYPE:return e.getItemType();case P.BLUE_ID:return e.getBlueId();default:throw new Error(`Unknown field: ${t}`)}}}class Fe{}class ue{static convert(e){const t=new He;return ue.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const n=e.getProperties(),i=e.getItems(),o=n!==void 0&&Object.keys(n).length>0,l=i!==void 0&&i.length>0;if(!o&&!l){r.addPath(t===""?"/":t);return}if(n)for(const[a,p]of Object.entries(n)){const f=`${t}/${a}`;ue.traverseNode(p,f,r)}if(i)for(let a=0;a<i.length;a++){const p=`${t}/${a}`;ue.traverseNode(i[a],p,r)}}}function It(s,e){const t=s.split(e),r=[...t].reverse().findIndex(i=>i!==""),n=r===-1?0:t.length-r;return t.slice(0,n)}class $e extends Fe{allowedPaths;maxDepth;currentPath=[];constructor(e,t){super(),this.allowedPaths=e,this.maxDepth=t}shouldExtendPathSegment(e){if(this.currentPath.length>=this.maxDepth)return!1;const t=this.normalizePath(this.getCurrentFullPath()+"/"+e);return this.isAllowedPath(t)}shouldMergePathSegment(e){return this.shouldExtendPathSegment(e)}isAllowedPath(e){for(const t of this.allowedPaths)if(this.matchesAllowedPath(t,e))return!0;return!1}matchesAllowedPath(e,t){const r=It(e,"/"),n=It(t,"/");if(n.length>r.length)return!1;for(let i=1;i<n.length;i++)if(r[i]!=="*"&&r[i]!==n[i])return!1;return!0}enterPathSegment(e){this.currentPath.push(e)}exitPathSegment(){this.currentPath.length>0&&this.currentPath.pop()}getCurrentFullPath(){return"/"+this.currentPath.join("/")}normalizePath(e){return"/"+e.split("/").filter(t=>t!=="").join("/")}static withMaxDepth(e){const t=new He().setMaxDepth(e);for(let r=1;r<=e;r++){const n="/"+Array(r).fill("*").join("/");t.addPath(n)}return t.build()}static withSinglePath(e){return new He().addPath(e).build()}static fromNode(e){return ue.convert(e)}}class He{allowedPaths=new Set;maxDepth=Number.MAX_SAFE_INTEGER;addPath(e){return this.allowedPaths.add(e),this}setMaxDepth(e){return this.maxDepth=e,this}build(){return new $e(this.allowedPaths,this.maxDepth)}}class Se extends Fe{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class je extends Fe{limits;constructor(e){super(),this.limits=e}shouldExtendPathSegment(e,t){return this.limits.every(r=>r.shouldExtendPathSegment(e,t))}shouldMergePathSegment(e,t){return this.limits.every(r=>r.shouldMergePathSegment(e,t))}enterPathSegment(e,t){this.limits.forEach(r=>{r.enterPathSegment(e,t)})}exitPathSegment(){this.limits.forEach(e=>{e.exitPathSegment()})}static of(...e){return new je(e)}}const j=new Se;class ls{blue;constructor(e){this.blue=e}matchesType(e,t,r=j){const n=$e.fromNode(t),i=je.of(r,n),o=this.extendAndResolve(e,i),l=this.blue.resolve(t,i),a=this.expandSchemaOwnedTypeReferences(t);return this.verifyMatch(o,t,i)&&this.recursiveValueComparison(o,l,a,i)}extendAndResolve(e,t){const r=e.clone(),n=r.clone();this.blue.extend(n,t);const i=this.blue.resolve(n,t);return this.restoreMissingStructure(i,r),i}restoreMissingStructure(e,t){const r=t.getItems(),n=e.getItems();if(r&&r.length>0)if(!n||n.length===0)e.setItems(r.map(a=>a.clone()));else for(let a=0;a<Math.min(n.length,r.length);a++)this.restoreMissingStructure(n[a],r[a]);const i=t.getProperties();if(i){let a=e.getProperties();a||(a={},e.setProperties(a));for(const[p,f]of Object.entries(i)){const h=a[p];h===void 0?a[p]=f.clone():this.restoreMissingStructure(h,f)}}const o=t.getBlueId();e.getBlueId()===void 0&&o!==void 0&&e.setBlueId(o);const l=t.getValue();e.getValue()===void 0&&l!==void 0&&e.setValue(l)}verifyMatch(e,t,r){const n=t.getType();if(this.matchesImplicitStructure(e,n))return!0;const i=e.clone().setType(t.clone());try{this.blue.resolve(i,r)}catch{return!1}return!0}recursiveValueComparison(e,t,r=t,n=j){const i=t.getType(),o=this.matchesImplicitStructure(e,i)||this.matchesImplicitCoreCollectionType(e,t);if(e.getType()===void 0&&this.isCoreCollectionType(t)&&!o)return!1;if(i&&!o){const b=e.getType();if(!b||!B(b,i,this.blue.getNodeProvider()))return!1}const l=t.getBlueId();if(!o&&l!==void 0)if(this.isExplicitBlueIdMatcher(r)){const b=e.getBlueId(),N=e.getType()?.getBlueId();if(b!==l&&N!==l)return!1}else{const b=e.getBlueId(),N=e.getType();if(N===void 0&&b!==void 0&&b!==l||N&&!B(N,t,this.blue.getNodeProvider()))return!1}const a=t.getValue();if(a!==void 0){const b=e.getValue();if(b===void 0)return!1;if(R(b)&&R(a)){if(!b.eq(a))return!1}else if(b!==a)return!1}const p=t.getItems(),f=r.getItems();if(p!==void 0){const b=e.getItems()??[];for(let N=0;N<p.length;N++)if(N<b.length){if(!this.recursiveValueComparison(b[N],p[N],f?.[N]??p[N],n))return!1}else if(this.hasValueInNestedStructure(p[N]))return!1}const h=t.getItemType(),g=r.getItemType();if(h!==void 0){const b=e.getItems()??[];for(const N of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(N,h,g??h,n),h,g??h,n))return!1}const T=t.getProperties(),x=r.getProperties();if(T!==void 0){const b=e.getProperties()??{};for(const[N,Le]of Object.entries(T))if(N in b){if(!this.recursiveValueComparison(b[N],Le,x?.[N]??Le,n))return!1}else if(this.hasValueInNestedStructure(Le))return!1}const V=t.getValueType(),_=r.getValueType();if(V!==void 0){const b=Object.values(e.getProperties()??{});for(const N of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(N,V,_??V,n),V,_??V,n))return!1}return!0}resolveUntypedNodeAgainstMatcherType(e,t,r,n){return e.getType()!==void 0||this.isExplicitBlueIdMatcher(r)?e:this.resolveAgainstTargetType(e,t,n)??e}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const n of t)if(this.hasValueInNestedStructure(n))return!0}const r=e.getProperties();if(r!==void 0){for(const n of Object.values(r))if(this.hasValueInNestedStructure(n))return!0}return!1}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:we(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ee(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}matchesImplicitCoreCollectionType(e,t){return e.getType()!==void 0?!1:we(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ee(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isCoreCollectionType(e){return we(e,this.blue.getNodeProvider())||Ee(e,this.blue.getNodeProvider())}isImplicitListStructure(e){return e.getItems()!==void 0&&e.getValue()===void 0}isImplicitDictionaryStructure(e){return e.getProperties()!==void 0&&e.getValue()===void 0}isBareBlueIdReference(e){return e.getBlueId()!==void 0&&e.getType()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getProperties()===void 0&&e.getValueType()===void 0}isExplicitBlueIdMatcher(e){return this.isBareBlueIdReference(e)}resolveAgainstTargetType(e,t,r){try{const n=e.clone(),i=n.clone().setType(t.clone()),o=this.blue.resolve(i,r);return this.restoreMissingStructure(o,n),o}catch{return null}}expandSchemaOwnedTypeReferences(e){return this.isSchemaDefinitionNode(e)?this.expandSchemaTypeReferences(e.clone()):e}isSchemaDefinitionNode(e){return e.getBlueId()!==void 0&&(e.getName()!==void 0||e.getDescription()!==void 0||e.getType()!==void 0||e.getItemType()!==void 0||e.getKeyType()!==void 0||e.getValueType()!==void 0||e.getItems()!==void 0||e.getProperties()!==void 0)}expandSchemaTypeReferences(e,t=new Set){const r=this.withVisitedBlueId(t,e.getBlueId()),n=e.getType();n&&e.setType(this.expandReferencedTypeNode(n,r));const i=e.getItemType();i&&e.setItemType(this.expandReferencedTypeNode(i,r));const o=e.getKeyType();o&&e.setKeyType(this.expandReferencedTypeNode(o,r));const l=e.getValueType();l&&e.setValueType(this.expandReferencedTypeNode(l,r));const a=e.getItems();a&&e.setItems(a.map(f=>this.expandSchemaTypeReferences(f,r)));const p=e.getProperties();return p&&e.setProperties(Object.fromEntries(Object.entries(p).map(([f,h])=>[f,this.expandSchemaTypeReferences(h,r)]))),e}expandReferencedTypeNode(e,t){if(!this.isBareBlueIdReference(e))return this.expandSchemaTypeReferences(e.clone(),t);const r=e.getBlueId();if(!r||t.has(r))return e.clone();const n=this.blue.getNodeProvider().fetchByBlueId(r);return!n||n.length!==1?e.clone():this.expandSchemaTypeReferences(n[0].clone(),t)}withVisitedBlueId(e,t){if(!t||e.has(t))return e;const r=new Set(e);return r.add(t),r}}const as=s=>s instanceof c.ZodOptional||s instanceof c.ZodNullable||s instanceof c.ZodReadonly||s instanceof c.ZodBranded||s instanceof c.ZodEffects||s instanceof c.ZodLazy,us=s=>s instanceof c.ZodString||s instanceof c.ZodNumber||s instanceof c.ZodBoolean||s instanceof c.ZodBigInt;class Gt{static convertValue(e,t){const r=e.getType()?.getBlueId(),n=e.getValue();return u.isNullable(n)?us(t)&&ve.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):n:Y===r?this.convertFromString(String(n),t):J===r||n instanceof A?this.convertFromBigDecimal(new A(n?.toString()),t):Z===r||n instanceof S?this.convertFromBigInteger(new S(n?.toString()),t):G===r||typeof n=="boolean"?this.convertFromBoolean(!!n,t):this.convertFromString(String(n),t)}static convertFromString(e,t){if(!t||t instanceof c.ZodString||t instanceof c.ZodEnum||t instanceof c.ZodNativeEnum)return e;if(t instanceof c.ZodNumber)return Number(e);if(t instanceof c.ZodBoolean)return e.toLowerCase()==="true";if(t instanceof c.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){if(t instanceof c.ZodNumber)return e.toNumber();if(t instanceof c.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){if(t instanceof c.ZodNumber)return e.toNumber();if(t instanceof c.ZodBigInt)return BigInt(e.toString());if(t instanceof c.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t||t instanceof c.ZodBoolean)return e;if(t instanceof c.ZodString)return e.toString();if(t instanceof c.ZodNumber)return Number(e);if(t instanceof c.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;if(e instanceof c.ZodNumber)return 0;if(e instanceof c.ZodBoolean)return!1;if(e instanceof c.ZodString)return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}class cs{convert(e,t){return Gt.convertValue(e,t)}}class ds{constructor(e){this.nodeToObjectConverter=e}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(t instanceof c.ZodIntersection){const r=t._def.left,n=t._def.right,i=this.convert(e,r),o=this.convert(e,n);return{...i,...o}}if(t instanceof c.ZodUnion)throw new Error("Union not supported");if(t instanceof c.ZodObject)return Object.keys(t.shape).reduce((n,i)=>{const o=e.getProperties(),l=t.shape[i],a=Ut(l);if(u.isNonNullable(a)){const T=M.isString(a)?a:i,x=o?.[T],V=x?I.calculateBlueIdSync(x):void 0;return n[i]=V,n}const p=kt(l);if(u.isNonNullable(p)){const T=o?.[p];return n[i]=T?.getName(),n}const f=jt(l);if(u.isNonNullable(f)){const T=o?.[f];return n[i]=T?.getDescription(),n}if(i==="name"){const T=e.getName();return n[i]=T,n}if(i==="description"){const T=e.getDescription();return n[i]=T,n}const h=o?.[i];if(u.isNullable(h))return n;const g=this.nodeToObjectConverter.convert(h,l);return n[i]=g,n},{});throw new Error("Unknown schema type, "+t._def.typeName)}}class ps{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const n=t.element;return r.map(o=>this.nodeToObjectConverter.convert(o,n))}}class hs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const n=t._def.valueType,i=r.map(o=>this.nodeToObjectConverter.convert(o,n));return new Set(i)}}class fs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,n=t.valueSchema,i=new Map,o=e.getName();u.isNonNullable(o)&&i.set(q,o);const l=e.getDescription();u.isNonNullable(l)&&i.set(X,l);const a=e.getProperties();return u.isNonNullable(a)&&Object.entries(a).forEach(([p,f])=>{const h=new d().setValue(p);h.setType(new d().setBlueId(Y));const g=Gt.convertValue(h,r),T=this.nodeToObjectConverter.convert(f,n);i.set(g,T)}),t instanceof c.ZodRecord?Object.fromEntries(i):i}}class ys{convert(e){return m.get(e)}}class gs{convert(e){return m.get(e)}}class ms{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const n=t.items;return r.map((o,l)=>this.nodeToObjectConverter.convert(o,n[l]))}}const Is=c.z.union([c.z.literal("ZodString"),c.z.literal("ZodNumber"),c.z.literal("ZodBoolean"),c.z.literal("ZodBigInt"),c.z.literal("ZodArray"),c.z.literal("ZodSet"),c.z.literal("ZodMap"),c.z.literal("ZodRecord"),c.z.literal("ZodObject"),c.z.literal("ZodEnum"),c.z.literal("ZodNativeEnum"),c.z.literal("ZodUnknown"),c.z.literal("ZodAny"),c.z.literal("ZodTuple")]);class Ts{constructor(e){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new ds(this.nodeToObjectConverter)}converters=new Map;complexObjectConverter;registerConverters(){const e=new cs,t=new ps(this.nodeToObjectConverter),r=new ms(this.nodeToObjectConverter),n=new hs(this.nodeToObjectConverter),i=new fs(this.nodeToObjectConverter);this.converters.set("ZodString",e),this.converters.set("ZodNumber",e),this.converters.set("ZodBoolean",e),this.converters.set("ZodBigInt",e),this.converters.set("ZodEnum",e),this.converters.set("ZodNativeEnum",e),this.converters.set("ZodUnknown",new ys),this.converters.set("ZodAny",new gs),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",n),this.converters.set("ZodMap",i),this.converters.set("ZodRecord",i),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){if(as(e))return e instanceof c.ZodEffects?this.getSchemaTypeName(e.innerType()):e instanceof c.ZodLazy?this.getSchemaTypeName(e.schema):this.getSchemaTypeName(e.unwrap());const t=e._def.typeName;try{return Is.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class bs{constructor(e){this.typeSchemaResolver=e,this.converterFactory=new Ts(this)}converterFactory;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),n=O.unwrapSchema(t);if(ct(n))return e;let i=n;return O.checkSchemaExtension(r,n,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(i=r),this.convertWithType(e,i)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class Wt{reverse(e){const t=new d;return this.reverseNode(t,e,e.getType()),t}reverseNode(e,t,r){this.isIdenticalToType(t,r)||(this.reverseBasicProperties(e,t,r),this.reverseTypeReferences(e,t,r),this.reverseItems(e,t,r),this.reverseProperties(e,t,r))}isIdenticalToType(e,t){return u.isNonNullable(e.getBlueId())&&u.isNonNullable(t?.getBlueId())&&e.getBlueId()===t.getBlueId()}reverseBasicProperties(e,t,r){const n=t.getValue();u.isNonNullable(n)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(n),u.isNonNullable(t.getName())&&(u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(u.isNullable(r)||t.getDescription()!==r.getDescription())&&e.setDescription(t.getDescription()),u.isNonNullable(t.getBlueId())&&(u.isNullable(r)||t.getBlueId()!==r.getBlueId())&&e.setBlueId(t.getBlueId())}reverseTypeReferences(e,t,r){const n=(i,o)=>{const l=i(t),a=r?i(r):void 0,p=l?.getBlueId();u.isNonNullable(p)&&(u.isNullable(a?.getBlueId())||p!==a.getBlueId())&&o(e,new d().setBlueId(p))};n(i=>i.getType(),(i,o)=>i.setType(o)),n(i=>i.getItemType(),(i,o)=>i.setItemType(o)),n(i=>i.getKeyType(),(i,o)=>i.setKeyType(o)),n(i=>i.getValueType(),(i,o)=>i.setValueType(o))}reverseItems(e,t,r){const n=t.getItems();if(u.isNullable(n))return;const i=r?.getItems(),o=[];if(u.isNonNullable(i)&&n.length>i.length&&u.isNonNullable(i)&&i.length>0){const p=I.calculateBlueIdSync(i);o.push(new d().setBlueId(p))}const a=i?.length||0;for(let p=a;p<n.length;p++){const f=new d;this.reverseNode(f,n[p],void 0),o.push(f)}o.length>0&&e.setItems(o)}reverseProperties(e,t,r){const n=t.getProperties();if(u.isNullable(n))return;const i={};for(const[o,l]of Object.entries(n)){const a=this.getInheritedProperty(o,t,r),p=new d;this.reverseNode(p,l,a),ve.isEmptyNode(p)||(i[o]=p)}Object.keys(i).length>0&&e.setProperties(i)}getInheritedProperty(e,t,r){const n=r?.getProperties()?.[e],i=t.getType()?.getProperties()?.[e];if(!(u.isNullable(n)&&u.isNullable(i)))return u.isNullable(n)?i:u.isNullable(i)?n:this.mergeNodes(n,i)}mergeNodes(e,t){const r=e.clone(),n=t.getValue();u.isNonNullable(n)&&r.setValue(n);const i=t.getType();u.isNonNullable(i)&&r.setType(i.clone());const o=t.getItemType();u.isNonNullable(o)&&r.setItemType(o.clone());const l=t.getKeyType();u.isNonNullable(l)&&r.setKeyType(l.clone());const a=t.getValueType();u.isNonNullable(a)&&r.setValueType(a.clone());const p=t.getProperties();if(u.isNonNullable(p)){const h=r.getProperties()||{};for(const[g,T]of Object.entries(p))h[g]=T.clone();r.setProperties(h)}const f=t.getItems();return u.isNonNullable(f)&&r.setItems(f.map(h=>h.clone())),r}}class ee extends d{constructor(e){super(e.getName()),this.createFrom(e)}isResolved(){return!0}getMinimalNode(){return new Wt().reverse(this)}getMinimalBlueId(){const e=this.getMinimalNode();return I.calculateBlueIdSync(e)}clone(){const e=super.clone();return new ee(e)}cloneShallow(){const e=super.cloneShallow();return new ee(e)}createFrom(e){e.getName()!==this.getName()&&this.setName(e.getName()),this.setDescription(e.getDescription()).setType(e.getType()).setItemType(e.getItemType()).setKeyType(e.getKeyType()).setValueType(e.getValueType()).setItems(e.getItems()).setProperties(e.getProperties()).setBlueId(e.getBlueId()).setBlue(e.getBlue()).setInlineValue(e.isInlineValue());const t=e.getValue();t!==void 0&&this.setValue(t)}}class Ne{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function vs(s){return new class extends Ne{fetchByBlueId(e){return s(e)}}}const Ye=te.types.float.options,Ns={...Ye,construct:s=>{const e=s.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new A(e);if(Ye.construct)return Ye.construct(s)}},Bs=new te.Type("tag:yaml.org,2002:float",Ns),Je=te.types.int.options,ws={...Je,construct:s=>{let e=s;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new S(e);if(Je.construct)return Je.construct(s)}},Es=new te.Type("tag:yaml.org,2002:int",ws),Ht=te.CORE_SCHEMA.extend({implicit:[Bs,Es]}),$=s=>{const e=te.load(s,{schema:Ht});return e===void 0?void 0:e},qt=s=>te.dump(s,{schema:Ht,replacer:(e,t)=>{if(R(t)){if(k(t)){const r=new U(Number.MIN_SAFE_INTEGER.toString()),n=new U(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(n))return t.toString()}return t.toNumber()}return t}});class Ss{static get(e,t={}){const{strategy:r="official"}=t,n=m.get(e,r);return qt(n)}}class Ps extends Ne{nodeProviders;constructor(e){super(),this.nodeProviders=e}fetchByBlueId(e){for(const t of this.nodeProviders){const r=t.fetchByBlueId(e);if(r&&r.length>0)return r}return[]}fetchFirstByBlueId(e){for(const t of this.nodeProviders){const r=t.fetchFirstByBlueId(e);if(r)return r}return null}getNodeProviders(){return this.nodeProviders}}const Xt=`- type:
|
|
2
2
|
blueId: 27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo
|
|
3
3
|
mappings:
|
|
4
4
|
Text: DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K
|
|
@@ -9,19 +9,19 @@
|
|
|
9
9
|
Dictionary: G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj
|
|
10
10
|
- type:
|
|
11
11
|
blueId: FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4
|
|
12
|
-
`,
|
|
13
|
-
description: TODO`,
|
|
12
|
+
`,Cs=`name: Transformation
|
|
13
|
+
description: TODO`,As=`name: Infer Basic Types For Untyped Values
|
|
14
14
|
type:
|
|
15
15
|
blueId: Ct1SGRGw1i47qjzm1ruiUdSZofeV6WevPTGuieVvbRS4
|
|
16
|
-
description: This transformation infers type details for Text, Integer, Number and Boolean.`,
|
|
16
|
+
description: This transformation infers type details for Text, Integer, Number and Boolean.`,Rs=`name: Replace Inline Types with BlueIds
|
|
17
17
|
type:
|
|
18
18
|
blueId: Ct1SGRGw1i47qjzm1ruiUdSZofeV6WevPTGuieVvbRS4
|
|
19
|
-
description: This transformation replaces`,
|
|
19
|
+
description: This transformation replaces`,Vs=[Xt,Cs,As,Rs];class Os extends Ne{blueIdToNodesMap=new Map;constructor(){super(),this.load()}fetchByBlueId(e){return this.blueIdToNodesMap.get(e)||[]}load(){for(const e of Vs){const t=$(e);if(t===void 0){console.error(`This content file is not valid YAML: ${e}`);continue}if(Array.isArray(t)){const r=t.map(i=>y.deserialize(i)),n=I.calculateBlueIdSync(r);this.blueIdToNodesMap.set(n,r)}else{const r=y.deserialize(t),n=I.calculateBlueIdSync(r);this.blueIdToNodesMap.set(n,[r])}}}}class dt extends Ne{static INSTANCE=new dt;nodeProvider;constructor(){super(),this.nodeProvider=new Os}fetchByBlueId(e){return this.nodeProvider.fetchByBlueId(e)}}class Ze{constructor(e,t,r){this.blueId=e,this.content=t,this.isMultipleDocuments=r}}class H{static THIS_REFERENCE_PATTERN=/^this(#\d+)?$/;static parseAndCalculateBlueId(e,t){let r;try{const l=$(e);if(l===void 0)throw new Error;r=l}catch{throw new Error("Failed to parse content as YAML or JSON")}let n,i;const o=Array.isArray(r)&&r.length>1;if(o){const l=r.map(a=>{const p=y.deserialize(a);return t(p)});n=I.calculateBlueIdSync(l),i=l.map(a=>m.get(a))}else{const l=y.deserialize(r),a=t(l);n=I.calculateBlueIdSync(a),i=m.get(a)}return new Ze(n,i,o)}static parseAndCalculateBlueIdForNode(e,t){const r=t(e),n=I.calculateBlueIdSync(r),i=m.get(r);return new Ze(n,i,!1)}static parseAndCalculateBlueIdForNodeList(e,t){if(!e||e.length===0)throw new Error("List of nodes cannot be null or empty");const r=e.map(t),n=I.calculateBlueIdSync(r),i=r.map(l=>m.get(l)),o=e.length>1;return new Ze(n,i,o)}static resolveThisReferences(e,t,r){return this.resolveThisReferencesRecursive(e,t,r)}static resolveThisReferencesRecursive(e,t,r){if(e&&typeof e=="object"&&!Array.isArray(e)){const n={};for(const[i,o]of Object.entries(e))typeof o=="string"?this.THIS_REFERENCE_PATTERN.test(o)?n[i]=this.resolveThisReference(o,t,r):n[i]=o:o&&typeof o=="object"?n[i]=this.resolveThisReferencesRecursive(o,t,r):n[i]=o;return n}else if(Array.isArray(e))return e.map(n=>typeof n=="string"?this.THIS_REFERENCE_PATTERN.test(n)?this.resolveThisReference(n,t,r):n:n&&typeof n=="object"?this.resolveThisReferencesRecursive(n,t,r):n);return e}static resolveThisReference(e,t,r){if(r){if(!e.startsWith("this#"))throw new Error("For multiple documents, 'this' references must include an index (e.g., 'this#0')");return t+e.substring(4)}else{if(e==="this")return t;throw new Error("For a single document, only 'this' is allowed as a reference, not 'this#<id>'")}}}class Ms extends Ne{fetchByBlueId(e){const t=e.split("#")[0],r=this.fetchContentByBlueId(t);if(r==null)return null;const n=Array.isArray(r)&&r.length>1,i=H.resolveThisReferences(r,t,n);if(e.includes("#")){const o=e.split("#");if(o.length>1){const l=parseInt(o[1]);if(Array.isArray(i)&&l<i.length){const a=i[l],p=y.deserialize(a);return p.setBlueId(e),[p]}else if(l===0){const a=y.deserialize(i);return a.setBlueId(e),[a]}else return null}}if(Array.isArray(i))return i.map(o=>y.deserialize(o));{const o=y.deserialize(i);return o.setBlueId(t),[o]}}}class Qt extends Ms{nameToBlueIdsMap=new Map;findNodeByName(e){const t=this.nameToBlueIdsMap.get(e);if(!t)return;if(t.length>1)throw new Error(`Multiple nodes found with name: ${e}`);const r=this.fetchByBlueId(t[0]);return r&&r.length>0?r[0]:void 0}findAllNodesByName(e){const t=this.nameToBlueIdsMap.get(e);if(!t)return[];const r=[];for(const n of t){const i=this.fetchByBlueId(n);i&&r.push(...i)}return r}addToNameMap(e,t){this.nameToBlueIdsMap.set(e,[...this.nameToBlueIdsMap.get(e)||[],t])}}const er=s=>s instanceof d||Array.isArray(s)&&s.every(e=>e instanceof d)?s:M.isArray(s)?s.map(e=>y.deserialize(e)):y.deserialize(s),tr=async s=>{const e=er(s);return I.calculateBlueId(e)},Ds=s=>{const e=er(s);return I.calculateBlueIdSync(e)},qe=async s=>{if(Ct(s))return s;try{const e=pe.parse(s),t=await tr(e);return{...s,blueId:t}}catch(e){throw new Error(`Failed enriching object with Blue ID: ${e}`)}},xs=s=>s?.items,_s=s=>s?.value,Fs=s=>u.isNullable(s)?{}:M.omit(s,et),$s=s=>Rt(s)?s.type.name??null:Vt(s)?M.pascal(typeof s.value):At(s)?"List":null,rr=s=>u.isNonNullable(s)&&Object.keys(M.omit(s,["blueId"])).length>0,js=s=>{try{const e=y.deserialize(s),t=m.get(e);return ne.parse(t)}catch(e){throw new Error(`Failed transforming JSON-like value to BlueObject: ${e}`)}},Xe=async s=>{const{resolveFunction:e,signal:t=new AbortController().signal,omitItems:r}=s,n=s.count??s.items.length;let i=await M.map(s.items,async l=>await qe(l));const o=Math.max(i?.length-n,0);for(let l=i.length-1;l>=o;l--)if(!rr(i[l])){const a=await e(i[l],{signal:t});if(Array.isArray(a))return Xe({...s,items:[...i.slice(0,l),...a,...i.slice(l+1)]});const p=await qe(a);if(r?.includes(p.blueId))return Xe({...s,items:[...i.slice(0,l),...i.slice(l+1)]});i=[...i.slice(0,l),p,...i.slice(l+1)]}return i};function ce(s){try{const e=new URL(s);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}class Ls{process(e){return E.transform(e,this.inferType.bind(this))}inferType(e){const t=e.getType(),r=e.getValue();return u.isNullable(t)&&u.isNonNullable(r)&&(typeof r=="string"?e.setType(new d().setBlueId(Y)):typeof r=="bigint"||k(r)?e.setType(new d().setBlueId(Z)):Ce(r)?e.setType(new d().setBlueId(J)):typeof r=="boolean"&&e.setType(new d().setBlueId(G))),e}}class Ve{static MAPPINGS="mappings";mappings=new Map;constructor(e){if(e instanceof d){const r=e.getProperties();if(r&&r[Ve.MAPPINGS]){const i=r[Ve.MAPPINGS].getProperties();i&&Object.entries(i).forEach(([o,l])=>{const a=l.getValue();typeof a=="string"&&this.mappings.set(o,a)})}}else this.mappings=e}process(e){return E.transform(e,this.transformNode.bind(this))}transformNode(e){const t=e.clone();return this.transformTypeField(t,t.getType()),this.transformTypeField(t,t.getItemType()),this.transformTypeField(t,t.getKeyType()),this.transformTypeField(t,t.getValueType()),t}transformTypeField(e,t){if(t&&t.isInlineValue()&&t.getValue()!==void 0){const r=String(t.getValue());if(this.mappings.has(r)){const n=this.mappings.get(r);if(n){const i=new d().setBlueId(n);t===e.getType()?e.setType(i):t===e.getItemType()?e.setItemType(i):t===e.getKeyType()?e.setKeyType(i):t===e.getValueType()&&e.setValueType(i)}}}}}class Us{process(e){return E.transform(e,this.validateNode.bind(this)),e}validateNode(e){return this.validateTypeField(e,e.getType(),"type"),this.validateTypeField(e,e.getItemType(),"itemType"),this.validateTypeField(e,e.getKeyType(),"keyType"),this.validateTypeField(e,e.getValueType(),"valueType"),e}validateTypeField(e,t,r){if(t&&t.isInlineValue()&&t.getValue()!==void 0){const n=String(t.getValue());throw new Error(`Unknown type "${n}" found in ${r} field. No BlueId mapping exists for this type.`)}}}class pt{nodeProvider;strategy;constructor(e,t){this.nodeProvider=fe.wrap(e),this.strategy=t||"THROW_EXCEPTION"}extend(e,t){this.extendNode(e,t,"")}extendNode(e,t,r,n=!1){if(!n){if(!t.shouldExtendPathSegment(r,e))return;t.enterPathSegment(r,e)}try{const i=e.getBlueId();if(i&&!re.includes(i)){const g=this.fetchNode(e);if(g&&g.length>0)if(g.length===1){const T=g[0];this.mergeNodes(e,T)}else{const T=g.map(V=>V.clone()),x=new d().setItems(T);this.mergeNodes(e,x)}}const o=e.getType();o&&this.extendNode(o,t,"type",!0);const l=e.getItemType();l&&this.extendNode(l,t,"itemType",!0);const a=e.getKeyType();a&&this.extendNode(a,t,"keyType",!0);const p=e.getValueType();p&&this.extendNode(p,t,"valueType",!0);const f=e.getProperties();f&&Object.entries(f).forEach(([g,T])=>{this.extendNode(T,t,g,!1)});const h=e.getItems();if(h&&h.length>0){this.reconstructList(h);for(let g=0;g<h.length;g++)this.extendNode(h[g],t,String(g),!1)}}finally{n||t.exitPathSegment()}}reconstructList(e){for(;e.length>0;){const r=e[0]?.getBlueId();if(!r)break;const n=this.nodeProvider.fetchByBlueId(r);if(!n||n.length===1)break;e.shift(),e.unshift(...n)}}fetchNode(e){const t=e.getBlueId();if(!t){if(this.strategy==="RETURN_EMPTY")return null;throw new Error(`No blueId found for node: ${e.getName()}`)}const r=this.nodeProvider.fetchByBlueId(t);if(!r||r.length===0){if(this.strategy==="RETURN_EMPTY")return null;throw new Error(`No content found for blueId: ${e.getBlueId()}`)}return r}mergeNodes(e,t){e.setName(t.getName()),e.setDescription(t.getDescription()),e.setType(t.getType()),e.setItemType(t.getItemType()),e.setKeyType(t.getKeyType()),e.setValueType(t.getValueType());const r=t.getValue();u.isNonNullable(r)&&e.setValue(r),e.setItems(t.getItems()),e.setProperties(t.getProperties())}}class ht{blueIdsCollections=[];initialize(...e){this.blueIdsCollections=[...e]}registerBlueIds(...e){this.blueIdsCollections.push(...e)}generateMappingsYaml(e="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo"){const t={};for(const n of this.blueIdsCollections)Object.assign(t,n);const r=Object.entries(t).map(([n,i])=>` ${n}: ${i}`).join(`
|
|
20
20
|
`);return`- type:
|
|
21
21
|
blueId: ${e}
|
|
22
22
|
mappings:
|
|
23
|
-
${r}`}getAllBlueIds(){const e={};for(const t of this.blueIdsCollections)Object.assign(e,t);return e}getAllBlueIdNames(){return Object.keys(this.getAllBlueIds())}clear(){this.blueIdsCollections=[]}getCollectionCount(){return this.blueIdsCollections.length}getTotalBlueIdCount(){return Object.keys(this.getAllBlueIds()).length}}class
|
|
23
|
+
${r}`}getAllBlueIds(){const e={};for(const t of this.blueIdsCollections)Object.assign(e,t);return e}getAllBlueIdNames(){return Object.keys(this.getAllBlueIds())}clear(){this.blueIdsCollections=[]}getCollectionCount(){return this.blueIdsCollections.length}getTotalBlueIdCount(){return Object.keys(this.getAllBlueIds()).length}}class oe{static DEFAULT_BLUE_BLUE_ID="6sqUywMoBRyj9hgQxSu2nDPnqcyiSM7xu9AB9sN98YJK";processorProvider;nodeProvider;defaultSimpleBlue=null;blueIdsMappingGenerator;constructor(e={}){const{nodeProvider:t,processorProvider:r,blueIdsMappingGenerator:n}=e;if(!t)throw new Error("NodeProvider is required");this.nodeProvider=fe.wrap(t),this.processorProvider=r||oe.getStandardProvider(),this.blueIdsMappingGenerator=n||new ht,this.loadDefaultSimpleBlue()}preprocess(e){return this.preprocessWithOptions(e,null)}preprocessWithDefaultBlue(e){return this.preprocessWithOptions(e,this.defaultSimpleBlue)}preprocessWithOptions(e,t){let r=e.clone(),n=r.getBlue();if(!n&&t&&(n=t.clone()),n){new pt(this.nodeProvider).extend(n,$e.withSinglePath("/*"));const i=n.getItems();if(i&&i.length>0){for(const o of i){const l=this.processorProvider.getProcessor(o);if(l)r=l.process(r);else throw new Error(`No processor found for transformation: ${o}`)}r.setBlue(void 0)}r=new Us().process(r)}return r}static getStandardProvider(){return{getProcessor(e){const t="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo",r="FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4",n=e.getType()?.getBlueId();if(t===n)return new Ve(e);if(r===n)return new Ls}}}enrichDefaultBlue(e){const t=this.blueIdsMappingGenerator.generateMappingsYaml();return`
|
|
24
24
|
${e}
|
|
25
25
|
${t}
|
|
26
|
-
`}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(
|
|
27
|
-
${n.message}`):n}else throw ae(t)?new Error(`UrlContentFetcher not provided for URL: ${t}`):new Error(`Invalid blue value: ${t}`)}return e}getBlueNodeValue(e){const r=e.getBlue()?.getValue();return r&&typeof r=="string"?r:null}handleAliasValue(e,t){return e.setBlue(new d().setBlueId(this.preprocessingAliases.get(t))),e}handleBlueId(e,t){return e.setBlue(new d().setBlueId(t)),e}async fetchFromUrl(e){if(!this.urlContentFetcher)throw new Error(`UrlContentFetcher not provided for URL: ${e}`);return await this.urlContentFetcher.fetchAndCache(e)}getPreprocessingAliases(){return new Map(this.preprocessingAliases)}setPreprocessingAliases(e){return this.preprocessingAliases=new Map(e),this}addPreprocessingAliases(e){return e.forEach((t,r)=>{this.preprocessingAliases.set(r,t)}),this}setUrlContentFetcher(e){return this.urlContentFetcher=e,this}getUrlContentFetcher(){return this.urlContentFetcher}}const zs={fetchUrl:async s=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${s}`)}};class Us{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||zs}validateUrl(e){if(!ae(e))throw new Error(`Invalid URL: ${e}`);return!0}isDomainAllowed(e){if(this.allowedDomains.length===0)return!0;try{const t=new URL(e);return this.allowedDomains.some(r=>t.hostname===r||t.hostname.endsWith(`.${r}`))}catch{return!1}}getFromCache(e){try{return this.validateUrl(e),this.cache.get(e)||[]}catch{return[]}}async fetchAndCache(e){if(this.validateUrl(e),!this.enabled)throw new Error("URL fetching is disabled. Enable it using the enableFetching method.");if(!this.isDomainAllowed(e))throw new Error(`Domain not allowed for URL: ${e}.`);let t;try{t=await this.fetchStrategy.fetchUrl(e)}catch(l){throw new Error(`Error fetching from URL: ${e}`,{cause:l})}const{data:r,contentType:n}=t;let i;if(n.includes("application/json")||n.includes("text/yaml")||n.includes("application/yaml")||n.includes("text/plain"))i=D(r);else throw new Error(`Unsupported content type from URL: ${n}`);if(i===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(i)?o=i.map(l=>g.deserialize(l)):o=[g.deserialize(i)],this.cache.set(e,o),o}prefetchUrl(e,t){try{this.validateUrl(e),this.cache.set(e,t)}catch{}}clearCache(){this.cache.clear()}setFetchStrategy(e){return this.fetchStrategy=e,this}getFetchStrategy(){return this.fetchStrategy}enableFetching(){return this.enabled=!0,this.allowedDomains=[],this}enableFetchingForDomains(e){return this.enabled=!0,this.allowedDomains=[...e],this}disableFetching(){return this.enabled=!1,this}isFetchingEnabled(){return this.enabled}getAllowedDomains(){return[...this.allowedDomains]}allowDomain(e){return this.allowedDomains.includes(e)||this.allowedDomains.push(e),this}disallowDomain(e){return this.allowedDomains=this.allowedDomains.filter(t=>t!==e),this}clearAllowedDomains(){return this.allowedDomains=[],this}}class er{resolveWithoutLimits(e){return this.resolve(e,Y)}}class tr extends er{mergingProcessor;nodeProvider;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProvider=pe.wrap(t)}merge(e,t,r){return this.mergeWithContext(e,t,this.createResolutionContext(r))}mergeWithContext(e,t,r){if(u.isNonNullable(t.getBlue()))throw new Error('Document contains "blue" attribute. Preprocess document before merging.');let n=e;const i=t.getType();if(u.isNonNullable(i)){const o=this.resolveTypeNode(i,r),l=o.clone().setType(void 0).setBlueId(void 0);n=this.mergeObject(n,l,r);const a=t.cloneShallow().setType(o.clone());return this.mergeObject(n,a,r)}return this.mergeObject(n,t,r)}mergeObject(e,t,r){const n=e.cloneShallow();let i=this.mergingProcessor.process(n,t,r.nodeProvider);const o=t.getItems();u.isNonNullable(o)&&(i=this.mergeChildren(i,o,r));const l=t.getProperties();return u.isNonNullable(l)&&(i=this.mergeProperties(i,l,r)),u.isNonNullable(t.getBlueId())&&(i=i.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(i=this.mergingProcessor.postProcess(i,t,r.nodeProvider)),i}mergeChildren(e,t,r){const n=e.getItems(),i=u.isNonNullable(n)||this.isInheritedListMarkerNode(t[0])?this.getInheritedItemsPrefixLength(t,n??[],r):void 0;if(this.rememberInheritedItemsPrefix(t,i,r),u.isNullable(n)){const l=[];for(let a=0;a<t.length;a++){const p=t[a];if(r.limits.shouldMergePathSegment(String(a),p)){this.enterPathSegment(r,String(a),p);try{const y=this.materializeForCurrentContext(p,r);l.push(y)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}if(u.isNonNullable(i)){const l=this.mergeChildrenWithInheritedItemsPrefix(t,n,i,r);return e.cloneShallow().setItems(l)}if(t.length<n.length)throw new Error(`Subtype of element must not have more items (${n.length}) than the element itself (${t.length}).`);const o=[...n];for(let l=0;l<t.length;l++)if(r.limits.shouldMergePathSegment(String(l),t[l])){this.enterPathSegment(r,String(l),t[l]);try{if(l>=o.length){const y=this.materializeForCurrentContext(t[l],r);o.push(y);continue}const a=I.calculateBlueIdSync(t[l]),p=I.calculateBlueIdSync(o[l]);if(a!==p)throw new Error(`Mismatched items at index ${l}: source item has blueId '${a}', but target item has blueId '${p}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(o)}getInheritedItemsPrefixLength(e,t,r){const n=e[0],i=n?.getBlueId();if(u.isNullable(i))return;let o;if(t.length>0){const l=I.calculateBlueIdSync(t);i===l&&(o=t.length)}if(u.isNullable(o)){const l=r.inheritedItemsPrefixByPath.get(this.getCurrentPointer(r));u.isNonNullable(l)&&l.blueId===i&&(o=l.length)}if(!u.isNullable(o)){if(!this.isInheritedListMarkerNode(n)){if(e.length>1)throw new Error("Invalid inherited-list marker: first list item must contain only blueId.");return}return o}}rememberInheritedItemsPrefix(e,t,r){const n=this.getCurrentPointer(r);if(e.length===0)return;const i=e[0],l=this.isInheritedListMarkerNode(i)?u.isNonNullable(t)?t+e.length-1:void 0:e.length;if(u.isNullable(l))return;const a={blueId:I.calculateBlueIdSync(e),length:l},p=r.inheritedItemsPrefixByPath.get(n);u.isNonNullable(p)&&p.length>=a.length||r.inheritedItemsPrefixByPath.set(n,a)}isInheritedListMarkerNode(e){return u.isNonNullable(e)&&u.isNonNullable(e.getBlueId())&&Te.hasBlueIdOnly(e)}mergeChildrenWithInheritedItemsPrefix(e,t,r,n){const i=[...t];for(let o=1;o<e.length;o++){const l=e[o],a=String(r+o-1);if(n.limits.shouldMergePathSegment(a,l)){this.enterPathSegment(n,a,l);try{const p=this.materializeForCurrentContext(l,n);i.push(p)}finally{this.exitPathSegment(n)}}}return i}mergeProperties(e,t,r){const n=e.getProperties()??{};let i=n,o=!1;for(const[l,a]of Object.entries(t))if(r.limits.shouldMergePathSegment(l,a)){this.enterPathSegment(r,l,a);try{const p=i[l],h=this.shouldMergePropertyWithoutPreResolve(p,a,r)?this.mergeWithContext(p,a,r):(()=>{const f=this.materializeForCurrentContext(a,r);return p===void 0?f:this.mergeObject(p,f,r)})();h!==p&&(o||(i={...n},o=!0),i[l]=h)}finally{this.exitPathSegment(r)}}return o?e.cloneShallow().setProperties(i):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof ve?!1:u.isNonNullable(t.getItems())||u.isNonNullable(e.getItems())}resolve(e,t){return this.resolveWithContext(e,this.createResolutionContext(t))}resolveWithContext(e,t){const r=new d,i=this.mergeWithContext(r,e,t).clone().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new H(i)}createResolutionContext(e){return{limits:e,nodeProvider:this.nodeProvider,resolvedTypeCache:new Map,inheritedItemsPrefixByPath:new Map,pathStack:[]}}resolveTypeNode(e,t){const r=e.getBlueId();if(u.isNonNullable(r)){const n=this.createResolvedTypeCacheKey(r,t),i=t.resolvedTypeCache.get(n);if(u.isNonNullable(i))return i;const o=this.resolveAndExtendTypeNode(e,t);return t.resolvedTypeCache.set(n,o),o}return this.resolveAndExtendTypeNode(e,t)}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new lt(t.nodeProvider).extend(r,Me.withSinglePath("/")),this.resolveWithContext(r,t)}createResolvedTypeCacheKey(e,t){return t.limits instanceof ve?e:`${e}|${this.getCurrentPointer(t)}`}materializeForCurrentContext(e,t){return e.isResolved()&&this.canReuseResolvedSubtree(t)?e.clone():this.resolveWithContext(e,t)}canReuseResolvedSubtree(e){return e.limits instanceof ve}getCurrentPointer(e){return e.pathStack.length===0?"/":`/${e.pathStack.join("/")}`}enterPathSegment(e,t,r){e.pathStack.push(t),e.limits.enterPathSegment(t,r)}exitPathSegment(e){e.pathStack.pop(),e.limits.exitPathSegment()}}class rr{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((n,i)=>i.process(n,t,r),e)}postProcess(e,t,r){return this.mergingProcessors.reduce((n,i)=>i.postProcess?i.postProcess(n,t,r):n,e)}}class sr{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const n=e.getValue();if(u.isNullable(n))return e.cloneShallow().setValue(r);if(!ks(r,n))throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${n}`)}return e}}const ks=(s,e)=>F(s)&&F(e)||we(s)&&we(e)?s.eq(e):s===e;class nr{process(e,t,r){const n=e.getType(),i=t.getType();let o=e;if(n===void 0)o=e.cloneShallow().setType(i);else if(i!==void 0){if(!v(i,n,r)){const a=m.get(i),p=m.get(n);throw new Error(`The source type '${JSON.stringify(a)}' is not a subtype of the target type '${JSON.stringify(p)}'.`)}o=e.cloneShallow().setType(i)}return o}}class ir{process(e,t,r){const n=t.getItemType(),i=t.getType();if(n!==void 0&&i!==void 0&&!Ut(i,r))throw new Error("Source node with itemType must have a List type");const o=e.getItemType();let l=e;if(o===void 0)n!==void 0&&(l=e.cloneShallow().setItemType(n));else if(n!==void 0){if(!v(n,o,r)){const h=m.get(n),f=m.get(o);throw new Error(`The source item type '${JSON.stringify(h)}' is not a subtype of the target item type '${JSON.stringify(f)}'.`)}l=e.cloneShallow().setItemType(n)}const a=l.getItemType(),p=t.getItems();if(a!==void 0&&p!==void 0)for(const y of p){const h=y.getType();if(h!==void 0&&!v(h,a,r)){const f=m.get(h),T=m.get(a);throw new Error(`Item of type '${JSON.stringify(f)}' is not a subtype of the list's item type '${JSON.stringify(T)}'.`)}}return l}}class or{process(e,t,r){const n=t.getKeyType(),i=t.getValueType(),o=t.getType();if((n!==void 0||i!==void 0)&&o!==void 0&&!kt(o,r))throw new Error("Source node with keyType or valueType must have a Dictionary type");let l=this.processKeyType(e,t,r);l=this.processValueType(l,t,r);const a=l.getKeyType(),p=l.getValueType(),y=t.getProperties();return(a!==void 0||p!==void 0)&&y!==void 0&&Object.entries(y).forEach(([h,f])=>{a!==void 0&&this.validateKeyType(h,a,r),p!==void 0&&this.validateValueType(f,p,r)}),l}processKeyType(e,t,r){const n=e.getKeyType(),i=t.getKeyType();if(n===void 0){if(i!==void 0)return this.validateBasicKeyType(i,r),e.cloneShallow().setKeyType(i)}else if(i!==void 0){if(this.validateBasicKeyType(i,r),!v(i,n,r)){const l=m.get(i),a=m.get(n);throw new Error(`The source key type '${JSON.stringify(l)}' is not a subtype of the target key type '${JSON.stringify(a)}'.`)}return e.cloneShallow().setKeyType(i)}return e}processValueType(e,t,r){const n=e.getValueType(),i=t.getValueType();if(n===void 0){if(i!==void 0)return e.cloneShallow().setValueType(i)}else if(i!==void 0){if(!v(i,n,r)){const l=m.get(i),a=m.get(n);throw new Error(`The source value type '${JSON.stringify(l)}' is not a subtype of the target value type '${JSON.stringify(a)}'.`)}return e.cloneShallow().setValueType(i)}return e}validateBasicKeyType(e,t){if(!Xr(e,t))throw new Error("Dictionary key type must be a basic type")}validateKeyType(e,t,r){if(!Qr(t,r))if(es(t,r)){const n=Number.parseInt(e,10);if(Number.isNaN(n)||n.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(ts(t,r)){const n=Number.parseFloat(e);if(Number.isNaN(n))throw new Error(`Key '${e}' is not a valid Number.`)}else if(rs(t,r)){if(e.toLowerCase()!=="true"&&e.toLowerCase()!=="false")throw new Error(`Key '${e}' is not a valid Boolean.`)}else throw new Error(`Unsupported key type: ${t.getName()||"unknown"}`)}validateValueType(e,t,r){const n=e.getType();if(n!==void 0&&!v(n,t,r)){const i=m.get(n),o=m.get(t);throw new Error(`Value of type '${JSON.stringify(i)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}class lr{process(e){return e}postProcess(e,t,r){const n=e.getType();if(n!==void 0&&ss(n,r)){const i=e.getItems(),o=e.getProperties();if(i!==void 0&&i.length>0||o!==void 0&&Object.keys(o).length>0){const l=ns(n,r),a=n.getName()||"unknown";throw new Error(`Node of type "${a}" (which extends basic type "${l}") must not have items, properties or contracts.`)}}return e}}class ar{process(e,t){let r=e;const n=t.getName();n!==void 0&&n!==e.getName()&&(r=r.cloneShallow().setName(n));const i=t.getDescription();return i!==void 0&&i!==r.getDescription()&&(r=r.cloneShallow().setDescription(i)),r}}const Ys=Object.freeze(Object.defineProperty({__proto__:null,BasicTypesVerifier:lr,DictionaryProcessor:or,ListProcessor:ir,MetadataPropagator:ar,SequentialMergingProcessor:rr,TypeAssigner:nr,ValuePropagator:sr},Symbol.toStringTag,{value:"Module"}));function Ks(){return new rr([new sr,new nr,new ir,new or,new ar,new lr])}class Js{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(Oe).forEach(([i,o])=>{this.blueIdToInlineValue.set(i,o)});const n=r.getAllBlueIds();Object.entries(n).forEach(([i,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,i)})}restore(e){return B.transform(e,t=>this.restoreNode(t))}restoreNode(e){return this.restoreTypeField(e,()=>e.getType(),t=>e.setType(t)),this.restoreTypeField(e,()=>e.getItemType(),t=>e.setItemType(t)),this.restoreTypeField(e,()=>e.getKeyType(),t=>e.setKeyType(t)),this.restoreTypeField(e,()=>e.getValueType(),t=>e.setValueType(t)),e}restoreTypeField(e,t,r){const n=t();if(!n||n.isInlineValue()&&n.getValue()!==void 0)return;const i=n.getBlueId();if(!i)return;const o=this.resolveInlineValue(i,n);if(!o)return;const l=new d().setValue(o).setInlineValue(!0);r(l)}resolveInlineValue(e,t){const r=this.blueIdToInlineValue.get(e);if(r)return r;const n=t.getName();if(n)return this.blueIdToInlineValue.set(e,n),n;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class Zs{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(Gs(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)on(this.contents,r.contents,r.name),nn(this.aliases,r.aliases,r.name)}getRuntimes(){return this.runtimes}getAliases(){return this.aliases}getContents(){return this.contents}findRuntimeByName(e){return this.runtimes.find(t=>t.name===e)}toCurrentBlueId(e){for(const t of this.runtimes){const r=t.toCurrentBlueIdIndex[e];if(r)return r}return e}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=Oe[t];if(r)return r;for(const n of this.runtimes){const i=n.typeAliasByCurrentBlueId[t];if(i)return i}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const n=r.types[t];if(n)return{runtime:r,currentBlueId:t,typeMeta:n,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function Gs(s){const e=Ws(s);return Object.values(s.packages).forEach(t=>{Hs(e,s,t)}),{name:s.name,repositoryVersions:s.repositoryVersions,repoVersionIndexById:e.repoVersionIndexById,aliases:e.aliases,types:e.types,toCurrentBlueIdIndex:e.toCurrentBlueIdIndex,contents:e.contents,schemas:e.schemas,currentRepoBlueId:e.currentRepoBlueId,typeAliasByCurrentBlueId:e.typeAliasByCurrentBlueId,typePackageByCurrentBlueId:e.typePackageByCurrentBlueId}}function Ws(s){const e=Object.fromEntries(s.repositoryVersions.map((r,n)=>[r,n])),t=s.repositoryVersions[s.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function Hs(s,e,t){if(s.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);s.packageNames.add(t.name),qs(s,t),Xs(s,e,t),Qs(s,t),en(s,t)}function qs(s,e){Object.entries(e.aliases).forEach(([t,r])=>{if(s.aliases[t]&&s.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);s.aliases[t]=r})}function Xs(s,e,t){Object.entries(t.typesMeta).forEach(([r,n])=>{if(s.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const i=tn(n,e,r,t.name);if(s.types[r]=i,s.typePackageByCurrentBlueId[r]=t.name,s.typeAliasByCurrentBlueId[r]=`${t.name}/${n.name}`,i.status===b.BLUE_REPOSITORY_STATUS_STABLE&&!s.toCurrentBlueIdIndex[r]&&(s.toCurrentBlueIdIndex[r]=r),i.status===b.BLUE_REPOSITORY_STATUS_STABLE)for(const o of i.versions){const l=s.toCurrentBlueIdIndex[o.typeBlueId];if(l&&l!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);s.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function Qs(s,e){Object.entries(e.contents).forEach(([t,r])=>{s.contents[t]=r})}function en(s,e){s.schemas.push(...Object.values(e.schemas))}function tn(s,e,t,r){if(s.status===b.BLUE_REPOSITORY_STATUS_DEV)return rn(s,e,t,r),{...s,versions:s.versions?[...s.versions]:s.versions};const n=[...s.versions??[]].sort((o,l)=>o.repositoryVersionIndex-l.repositoryVersionIndex);if(n.length===0)throw new Error(`Stable type ${r}/${s.name} (${t}) must have at least one version entry`);const i=new Set;return n.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${s.name}`);if(i.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${s.name}`);i.add(o.repositoryVersionIndex);for(const l of o.attributesAdded??[])sn(l,e.name,t,o.repositoryVersionIndex)}),{...s,versions:n}}function rn(s,e,t,r){if(s.status===b.BLUE_REPOSITORY_STATUS_DEV){if(s.versions&&s.versions.length>1)throw new Error(`Dev type ${r}/${s.name} (${t}) must not declare multiple versions`);if(s.versions&&s.versions.length===1){const n=s.versions[0];if(n.repositoryVersionIndex<0||n.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${n.repositoryVersionIndex} for dev type ${r}/${s.name}`)}}}function sn(s,e,t,r){try{b.validateAttributesAddedPointer(s)}catch(n){const i=n instanceof Error?n.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${s}' for type ${t} in repository ${e} at index ${r}: ${i}`)}}function nn(s,e,t){for(const[r,n]of Object.entries(e)){const i=s[r];if(i&&i!==n)throw new Error(`Conflicting alias '${r}' across repositories: '${i}' vs '${n}' (from ${t})`);s[r]=n}}function on(s,e,t){for(const[r,n]of Object.entries(e)){if(r in s){const i=s[r];if(!ln(i,n))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}s[r]=n}}function ln(s,e){if(s===e)return!0;if(s===null||e===null||typeof s!="object"||typeof e!="object")return!1;const t=Ee.canonicalize(s),r=Ee.canonicalize(e);return t!==void 0&&t===r}class Ce extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r&&r.length>0?r:[],this.name="BlueError"}}const M={REPO_UNKNOWN_REPO_BLUE_ID:"REPO_UNKNOWN_REPO_BLUE_ID",REPO_UNREPRESENTABLE_IN_TARGET_VERSION:"REPO_UNREPRESENTABLE_IN_TARGET_VERSION",INVALID_BLUE_CONTEXT_REPOSITORIES:"INVALID_BLUE_CONTEXT_REPOSITORIES",INVALID_REPOSITORY_POINTER:"INVALID_REPOSITORY_POINTER"},an=new Set(["__proto__","constructor","prototype"]);function ft(s){const e=s.at(0),t=s.at(-1);return!e||!t?s:e==="'"&&t==="'"||e==='"'&&t==='"'?s.slice(1,-1):s}function un(s,e){const t=s.indexOf("=");if(t===-1)throw te(e,`Missing '=' in segment '${s.trim()}'`);if(s.indexOf("=",t+1)!==-1)throw te(e,`Unexpected '=' in segment '${s.trim()}'`);const r=ft(s.slice(0,t).trim()),n=ft(s.slice(t+1).trim());if(!r)throw te(e,"Repository name is empty");if(!n)throw te(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:n}}function cn(s){if(s.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of s.split(",")){const r=t.trim();if(!r)throw te(s,"Empty repository segment");const{name:n,value:i}=un(r,s);pn(n,s),e[n]=i}return e}function dn(s){return typeof s=="string"?cn(s):s}function te(s,e){return new Ce(M.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:M.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:s,reason:e}}])}function pn(s,e){if(an.has(s))throw te(e,`Forbidden repository name '${s}'`)}function hn(s,e){const t=s.filter(n=>n.repositoryVersionIndex>e).sort((n,i)=>i.repositoryVersionIndex-n.repositoryVersionIndex),r=[];for(const n of t){const i=[...n.attributesAdded].sort((o,l)=>yt(l)-yt(o));r.push(...i)}return r}function yt(s){return b.parsePointer(s).length}const fn=new Set([...We]),N={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class yn{registry;targetRepoVersionIndexes;fallbackToCurrentInlineDefinitions;inliningStack=new Set;constructor(e){this.registry=e.registry,this.targetRepoVersionIndexes=e.targetRepoVersionIndexes,this.fallbackToCurrentInlineDefinitions=e.fallbackToCurrentInlineDefinitions}transform(e){return B.transform(e,t=>this.transformNode(t))}transformNode(e){return this.processTypeReference(e,{getter:()=>e.getType(),setter:t=>e.setType(t),schemaTraversalTargets:[e]}),this.processTypeReference(e,{getter:()=>e.getItemType(),setter:t=>e.setItemType(t),schemaTraversalTargets:e.getItems()??[]}),this.processTypeReference(e,{getter:()=>e.getKeyType(),setter:t=>e.setKeyType(t),schemaTraversalTargets:[]}),this.processTypeReference(e,{getter:()=>e.getValueType(),setter:t=>e.setValueType(t),schemaTraversalTargets:this.getDictionaryValueTargets(e)}),e}processTypeReference(e,t){const r=t.getter(),n=r?.getBlueId();if(!r||!n)return;const i=this.resolveType(n);switch(i.kind){case N.core:{r.setBlueId(i.blueId);return}case N.representable:{this.applyDropPointers([r],i.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,i.dropPointers),r.setBlueId(i.targetBlueId);return}case N.noRuntime:case N.noTargetContext:case N.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,n);return}throw i.kind===N.unrepresentable?i.error:this.unrepresentableError(n,i.kind===N.noTargetContext?`Repository '${i.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",i.kind===N.noTargetContext?i.runtime:void 0,i.kind===N.noTargetContext?i.meta:void 0,void 0,i.kind===N.noTargetContext?i.typeAlias:void 0)}}}resolveType(e){if(X.includes(e))return{kind:N.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),n=this.registry.findRuntimeByBlueId(t);if(!n||!n.typeMeta)return{kind:N.noRuntime};const i=this.targetRepoVersionIndexes[n.runtime.name];if(i===void 0)return{kind:N.noTargetContext,currentBlueId:t,runtimeName:n.runtime.name,runtime:n.runtime,meta:n.typeMeta,typeAlias:r};const o=n.typeMeta;if(o.status===b.BLUE_REPOSITORY_STATUS_DEV){const h=n.runtime.repositoryVersions.length-1;if(i!==h)return{kind:N.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${i}.`,n.runtime,o,i,r)};const f=o.versions?.[0];return{kind:N.representable,currentBlueId:t,targetBlueId:f?.typeBlueId??t,dropPointers:[]}}const l=o.versions||[];if(l.length===0)return{kind:N.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,n.runtime,o,i,r)};const a=l[0].repositoryVersionIndex;if(i<a)return{kind:N.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${i}.`,n.runtime,o,i,r)};let p=l[0].typeBlueId;for(const h of l)h.repositoryVersionIndex<=i&&(p=h.typeBlueId);const y=o.status===b.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,i):[];return{kind:N.representable,currentBlueId:t,targetBlueId:p,dropPointers:y}}getDropPointers(e,t){return e.status!==b.BLUE_REPOSITORY_STATUS_STABLE?[]:hn(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const n=r.rootIsSchema??!1;for(const i of t)for(const o of e)this.deletePropertyAtPointer(o,i,n)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,n])=>n instanceof d&&!fn.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let n;try{n=b.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,n,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[n,...i]=t;if(n===W){const a=e.getType();a&&this.applyPointerSegments(a,i,!0);return}if(n===he){const a=e.getItemType();a&&this.applyPointerSegments(a,i,!0);return}if(n===fe){const a=e.getKeyType();a&&this.applyPointerSegments(a,i,!0);return}if(n===ye){const a=e.getValueType();a&&this.applyPointerSegments(a,i,!0);return}const o=e.getProperties();if(!o)return;if(i.length===0){if(!r||!(n in o))return;const a={...o};delete a[n],e.setProperties(a);return}const l=o[n];l instanceof d&&this.applyPointerSegments(l,i,r)}inlineDefinition(e,t,r){const n=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(n))throw this.unrepresentableError(n,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(n)});const i=this.registry.getContents()[n];if(!i)throw this.unrepresentableError(n,`Missing definition to inline for BlueId ${n}.`);this.inliningStack.add(n);try{const o=g.deserialize(i);o.setBlueId(void 0);const l=B.transform(o,a=>this.transformNode(a));return t(l),e}finally{this.inliningStack.delete(n)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new Ce(M.INVALID_REPOSITORY_POINTER,t,[{code:M.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,n,i,o,l){const a={currentTypeBlueId:e,targetRepoVersionIndex:i,typeAlias:o,...l};if(r&&(i!==void 0&&(a.requestedRepoBlueId=r.repositoryVersions[i]),a.serverRepoBlueId=r.currentRepoBlueId),n&&n.status===b.BLUE_REPOSITORY_STATUS_STABLE){const y=n.versions?.[0]?.repositoryVersionIndex;y!==void 0&&(a.typeIntroducedInRepoBlueId=r?.repositoryVersions[y])}const p={code:M.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[W],context:a};return new Ce(M.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[p])}}function Ge(s,e){return e?B.transform(s,t=>(Ne(()=>t.getType(),r=>t.setType(r),e),Ne(()=>t.getItemType(),r=>t.setItemType(r),e),Ne(()=>t.getKeyType(),r=>t.setKeyType(r),e),Ne(()=>t.getValueType(),r=>t.setValueType(r),e),t)):s}function Ne(s,e,t){const r=s();if(!r||r.isInlineValue())return;const n=r.getBlueId();if(!n)return;const i=t.toCurrentBlueId(n);i!==n&&e(r.clone().setBlueId(i))}class gn{registry;blueIdMapper;constructor(e){this.registry=e.registry,this.blueIdMapper=e.blueIdMapper}transform(e,t){const r=this.computeTargetRepoVersionIndexes(t);if(Object.keys(r).length===0)return e;const n=Ge(e,this.blueIdMapper);return new yn({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(n)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?dn(e.repositories):e.repositories;for(const[n,i]of Object.entries(r)){const o=this.registry.findRuntimeByName(n);if(!o)continue;const l=o.repoVersionIndexById[i];if(l===void 0)throw this.unknownRepoBlueIdError(n,i,o.currentRepoBlueId);t[n]=l}return t}unknownRepoBlueIdError(e,t,r){const n=`Unknown RepoBlueId '${t}' for repository '${e}'.`,i={code:M.REPO_UNKNOWN_REPO_BLUE_ID,message:n,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new Ce(M.REPO_UNKNOWN_REPO_BLUE_ID,n,[i])}}class mn{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=Y;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:n,repositories:i,mergingProcessor:o}=e;this.repositories=i,this.repositoryRegistry=new Zs(i??[]),this.blueContextResolver=new gn({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry});const l=Ts(()=>[]);this.nodeProvider=pe.wrap(t||l,i),this.typeSchemaResolver=r??new Yt([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.mergingProcessor=o??Ks(),this.urlContentFetcher=new Us(n),this.blueDirectivePreprocessor=new Ls(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new at,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const a=this.repositoryRegistry.getRuntimes().flatMap(p=>p.schemas);a.length>0&&this.typeSchemaResolver?.registerSchemas(a)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),n=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return m.get(n,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),n=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return ws.get(n,{strategy:r.format})}nodeToSchemaOutput(e,t){return new Is(this.typeSchemaResolver).convert(e,t)}resolve(e,t=Y){const r=this.combineWithGlobalLimits(t);return new tr(this.mergingProcessor,this.nodeProvider).resolve(e,r)}createResolvedNode(e){return e instanceof H?e:new H(e)}reverse(e){return new Jt().reverse(e)}restoreInlineTypes(e){return new Js({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new lt(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(g.deserialize(e));return Ge(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(g.deserialize(e));return Ge(t,this.repositoryRegistry)}yamlToNode(e){const t=D(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}async yamlToNodeAsync(e){const t=D(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeAsync(t)}prepareForBlueIdCalculation=async e=>e instanceof d||Array.isArray(e)&&e.every(t=>t instanceof d)?e:Array.isArray(e)?await Promise.all(e.map(r=>this.jsonValueToNodeAsync(r))):this.jsonValueToNodeAsync(e);calculateBlueId=async e=>{const t=await this.prepareForBlueIdCalculation(e);return I.calculateBlueId(t)};prepareForBlueIdCalculationSync=e=>e instanceof d||Array.isArray(e)&&e.every(t=>t instanceof d)?e:Array.isArray(e)?e.map(t=>this.jsonValueToNode(t)):this.jsonValueToNode(e);calculateBlueIdSync(e){const t=this.prepareForBlueIdCalculationSync(e);return I.calculateBlueIdSync(t)}getTypeAliasByBlueId(e){const t=e?.trim();if(t)return this.repositoryRegistry.getTypeAlias(t)}addPreprocessingAliases(e){this.blueDirectivePreprocessor.addPreprocessingAliases(e)}preprocess(e){const t=this.blueDirectivePreprocessor.process(e);return new ne({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new ne({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}transform(e,t){return B.transform(e,t)}getNodeProvider(){return this.nodeProvider}setNodeProvider(e){return this.nodeProvider=pe.wrap(e,this.repositories),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this}getTypeSchemaResolver(){return this.typeSchemaResolver}setTypeSchemaResolver(e){return this.typeSchemaResolver=e,this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this}getUrlContentFetcher(){return this.urlContentFetcher}setUrlFetchStrategy(e){return this.urlContentFetcher.setFetchStrategy(e),this}enablePreprocessingDirectivesFetchForUrls(){return this.urlContentFetcher.enableFetching(),this}enablePreprocessingDirectivesFetchForDomains(e){return this.urlContentFetcher.enableFetchingForDomains(e),this}allowUrlFetchingForDomain(e){return this.urlContentFetcher.allowDomain(e),this}disallowUrlFetchingForDomain(e){return this.urlContentFetcher.disallowDomain(e),this}getAllowedUrlFetchingDomains(){return this.urlContentFetcher.getAllowedDomains()}disablePreprocessingDirectivesFetchForUrls(){return this.urlContentFetcher.disableFetching(),this}isPreprocessingDirectivesFetchForUrlsEnabled(){return this.urlContentFetcher.isFetchingEnabled()}getPreprocessingAliases(){return this.blueDirectivePreprocessor.getPreprocessingAliases()}setPreprocessingAliases(e){return this.blueDirectivePreprocessor.setPreprocessingAliases(e),this}registerBlueIds(...e){return this.blueIdsMappingGenerator.registerBlueIds(...e),this}getAllRegisteredBlueIds(){return this.blueIdsMappingGenerator.getAllBlueIds()}getAllBlueIdNames(){return this.blueIdsMappingGenerator.getAllBlueIdNames()}getBlueIdsMappingGenerator(){return this.blueIdsMappingGenerator}isTypeOf(e,t,r){return A.isTypeOf(e,t,{checkSchemaExtensions:r?.checkSchemaExtensions,typeSchemaResolver:this.typeSchemaResolver})}isTypeOfBlueId(e,t){const r=t.trim();if(r.length===0)return!1;const n=e.getType();if(!n)return!1;const i=new d().setBlueId(r);return v(n,i,this.nodeProvider)}isTypeOfNode(e,t){return new is(this).matchesType(e,t,this.globalLimits)}setGlobalLimits(e){return this.globalLimits=e??Y,this}getGlobalLimits(){return this.globalLimits}normalizeNodeToJsonOptions(e){return typeof e=="string"?{format:e,blueContext:void 0}:{format:e?.format??"official",blueContext:e?.blueContext}}combineWithGlobalLimits(e){return this.globalLimits==Y?e:e==Y?this.globalLimits:_e.of(this.globalLimits,e)}}class In extends Ht{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;preprocessor;constructor(e=[]){super();const t=new ne({nodeProvider:this});this.preprocessor=r=>t.preprocessWithDefaultBlue(r),e.forEach(r=>this.processNode(r))}processNode(e){Te.hasItemsOnly(e)?this.processNodeWithItems(e):this.processSingleNode(e)}processSingleNode(e){const t=J.parseAndCalculateBlueIdForNode(e,this.preprocessor);this.blueIdToContentMap.set(t.blueId,t.content),this.blueIdToMultipleDocumentsMap.set(t.blueId,t.isMultipleDocuments);const r=e.getName();r&&this.addToNameMap(r,t.blueId)}processNodeWithItems(e){const t=e.getItems();if(!t)return;this.processNodeList(t);const r=J.parseAndCalculateBlueIdForNodeList(t,this.preprocessor);this.blueIdToContentMap.set(r.blueId,r.content),this.blueIdToMultipleDocumentsMap.set(r.blueId,!0),t.forEach((n,i)=>{const o=n.getName();o&&this.addToNameMap(o,`${r.blueId}#${i}`)})}processNodeList(e){const t=I.calculateBlueIdSync(e),r=e.map(n=>m.get(n));this.blueIdToContentMap.set(t,r),this.blueIdToMultipleDocumentsMap.set(t,!0)}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?J.resolveThisReferences(t,e,r):null}addSingleNodes(...e){e.forEach(t=>this.processNode(t))}addSingleDocs(...e){e.forEach(t=>{const r=D(t);if(r!==void 0){const n=g.deserialize(r);this.processNode(n)}})}getBlueIdByName(e){const t=this.nameToBlueIdsMap.get(e);if(!t||t.length===0)throw new Error(`No node with name "${e}"`);return t[0]}getNodeByName(e){const t=this.findNodeByName(e);if(!t)throw new Error(`No node with name "${e}"`);return t}addListAndItsItemsFromNodes(e){this.processNodeList(e),e.forEach(t=>this.processNode(t))}addListAndItsItemsFromDoc(e){const t=D(e);if(t!==void 0){const n=g.deserialize(t).getItems();n&&this.addListAndItsItems(n)}}addListAndItsItems(e){Array.isArray(e)?this.addListAndItsItemsFromNodes(e):this.addListAndItsItemsFromDoc(e)}addList(e){this.processNodeList(e)}}exports.Base58Sha256Provider=Pt;exports.BasicNodeProvider=In;exports.Blue=mn;exports.BlueIdCalculator=I;exports.BlueIdToCid=Dr;exports.BlueNode=d;exports.BlueNodeTypeSchema=A;exports.JsonCanonicalizer=Ee;exports.Limits=De;exports.Merger=tr;exports.MergingProcessors=Ys;exports.NodeResolver=er;exports.Nodes=Te;exports.Properties=yr;exports.ResolvedBlueNode=H;exports.TypeSchemaResolver=Yt;exports.applyBlueNodePatch=kr;exports.baseBlueObjectSchema=me;exports.blueDescriptionField=Kr;exports.blueIdField=Zr;exports.blueIdSchema=mr;exports.blueNameField=Gr;exports.blueNodeField=Wr;exports.blueObjectBooleanValueSchema=br;exports.blueObjectNumberValueSchema=Tr;exports.blueObjectSchema=re;exports.blueObjectStringListItemsSchema=Nr;exports.blueObjectStringValueSchema=Ir;exports.calculateBlueId=Xt;exports.calculateBlueIdSync=Os;exports.enrichWithBlueId=Je;exports.getBlueDescriptionAnnotation=Mt;exports.getBlueIdAnnotation=xt;exports.getBlueNameAnnotation=$t;exports.getBlueNodeAnnotation=Lt;exports.getBlueObjectItems=Ds;exports.getBlueObjectProperties=_s;exports.getBlueObjectTypeLabel=xs;exports.getBlueObjectValue=Ms;exports.getTypeBlueIdAnnotation=zt;exports.hasBlueObjectBlueIdDefined=Bt;exports.hasBlueObjectItemsDefined=wt;exports.hasBlueObjectNameDefined=Br;exports.hasBlueObjectTypeDefined=Et;exports.hasBlueObjectValueDefined=St;exports.isBigDecimalNumber=we;exports.isBigIntegerNumber=F;exports.isBigNumber=C;exports.isBlueNodeSchema=it;exports.isBlueObject=vr;exports.isBlueObjectResolved=Qt;exports.isGivenBlueObjectTypeSchema=wr;exports.isJsonBlueArray=tt;exports.isJsonBlueObject=et;exports.isJsonBlueValue=Pr;exports.isUrl=ae;exports.jsonBlueValueSchema=ce;exports.normalizeToBlueObject=Fs;exports.resolveBlueObjectItems=Ze;exports.withBlueDescription=Dt;exports.withBlueId=_t;exports.withBlueName=Ft;exports.withBlueNode=jt;exports.withTypeBlueId=qr;exports.yamlBlueDump=Gt;exports.yamlBlueParse=D;
|
|
26
|
+
`}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(Xt),t=$(e);if(t)this.defaultSimpleBlue=y.deserialize(t);else throw new Error("Failed to parse default Blue content")}catch(e){throw new Error(`Error loading default Blue: ${e}`)}}}class ft extends Qt{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;preprocessor;constructor(e){super();const t=new ht,r=ft.collectAliasMappings(e);Object.keys(r).length>0&&t.registerBlueIds(r);const n=new oe({nodeProvider:this,blueIdsMappingGenerator:t});this.preprocessor=i=>n.preprocessWithDefaultBlue(i),this.loadRepositories(e)}static collectAliasMappings(e){const t={};for(const r of e)for(const n of Object.values(r.packages))for(const[i,o]of Object.entries(n.aliases)){const l=t[i];if(l&&l!==o)throw new Error(`Conflicting alias mapping for ${i}`);t[i]=o}return t}loadRepositories(e){for(const t of e)Object.values(t.packages).forEach(r=>{for(const[n,i]of Object.entries(r.contents))this.processContent(i,n)})}processContent(e,t){Array.isArray(e)?this.processMultipleDocuments(e,t):this.processSingleDocument(e,t)}processSingleDocument(e,t){const r=y.deserialize(e),n=H.parseAndCalculateBlueIdForNode(r,this.preprocessor),i=t||n.blueId;this.blueIdToContentMap.set(i,n.content),this.blueIdToMultipleDocumentsMap.set(i,!1);const o=r.getName();o&&this.addToNameMap(o,i)}processMultipleDocuments(e,t){const r=e.map(o=>{const l=y.deserialize(o);return this.preprocessor(l)}),n=H.parseAndCalculateBlueIdForNodeList(r,o=>o),i=t||n.blueId;this.blueIdToContentMap.set(i,n.content),this.blueIdToMultipleDocumentsMap.set(i,!0),r.forEach((o,l)=>{const a=`${i}#${l}`,p=m.get(o),f=I.calculateBlueIdSync(o);this.blueIdToContentMap.set(f,p),this.blueIdToMultipleDocumentsMap.set(f,!1);const h=o.getName();h&&this.addToNameMap(h,a)})}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?H.resolveThisReferences(t,e,r):null}getBlueIds(){return Array.from(this.blueIdToContentMap.keys())}hasBlueId(e){const t=e.split("#")[0];return this.blueIdToContentMap.has(t)}}class fe{static wrap(e,t){const r=[dt.INSTANCE];if(t&&t.length>0){const n=new ft(t);r.push(n)}return r.push(e),new Ps(r)}}class zs{preprocessingAliases=new Map;urlContentFetcher;constructor(e,t){e&&(this.preprocessingAliases=new Map(e)),this.urlContentFetcher=t}process(e){const t=this.getBlueNodeValue(e);if(t){const r=e.clone();if(this.preprocessingAliases.has(t))return this.handleAliasValue(r,t);if(Pe.isPotentialBlueId(t))return this.handleBlueId(r,t);throw ce(t)?new Error(`URL '${t}' detected. Use the async version of this method to fetch the content.`):new Error(`Invalid blue value: ${t}`)}return e}async processAsync(e){const t=this.getBlueNodeValue(e);if(t){const r=e.clone();if(this.preprocessingAliases.has(t))return this.handleAliasValue(r,t);if(Pe.isPotentialBlueId(t))return this.handleBlueId(r,t);if(ce(t)&&this.urlContentFetcher)try{const n=await this.fetchFromUrl(t);return n&&r.setBlue(new d().setItems(n)),r}catch(n){throw n instanceof Error?new Error(`Failed to fetch from URL '${t}'.
|
|
27
|
+
${n.message}`):n}else throw ce(t)?new Error(`UrlContentFetcher not provided for URL: ${t}`):new Error(`Invalid blue value: ${t}`)}return e}getBlueNodeValue(e){const r=e.getBlue()?.getValue();return r&&typeof r=="string"?r:null}handleAliasValue(e,t){return e.setBlue(new d().setBlueId(this.preprocessingAliases.get(t))),e}handleBlueId(e,t){return e.setBlue(new d().setBlueId(t)),e}async fetchFromUrl(e){if(!this.urlContentFetcher)throw new Error(`UrlContentFetcher not provided for URL: ${e}`);return await this.urlContentFetcher.fetchAndCache(e)}getPreprocessingAliases(){return new Map(this.preprocessingAliases)}setPreprocessingAliases(e){return this.preprocessingAliases=new Map(e),this}addPreprocessingAliases(e){return e.forEach((t,r)=>{this.preprocessingAliases.set(r,t)}),this}setUrlContentFetcher(e){return this.urlContentFetcher=e,this}getUrlContentFetcher(){return this.urlContentFetcher}}const ks={fetchUrl:async s=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${s}`)}};class Ks{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||ks}validateUrl(e){if(!ce(e))throw new Error(`Invalid URL: ${e}`);return!0}isDomainAllowed(e){if(this.allowedDomains.length===0)return!0;try{const t=new URL(e);return this.allowedDomains.some(r=>t.hostname===r||t.hostname.endsWith(`.${r}`))}catch{return!1}}getFromCache(e){try{return this.validateUrl(e),this.cache.get(e)||[]}catch{return[]}}async fetchAndCache(e){if(this.validateUrl(e),!this.enabled)throw new Error("URL fetching is disabled. Enable it using the enableFetching method.");if(!this.isDomainAllowed(e))throw new Error(`Domain not allowed for URL: ${e}.`);let t;try{t=await this.fetchStrategy.fetchUrl(e)}catch(l){throw new Error(`Error fetching from URL: ${e}`,{cause:l})}const{data:r,contentType:n}=t;let i;if(n.includes("application/json")||n.includes("text/yaml")||n.includes("application/yaml")||n.includes("text/plain"))i=$(r);else throw new Error(`Unsupported content type from URL: ${n}`);if(i===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(i)?o=i.map(l=>y.deserialize(l)):o=[y.deserialize(i)],this.cache.set(e,o),o}prefetchUrl(e,t){try{this.validateUrl(e),this.cache.set(e,t)}catch{}}clearCache(){this.cache.clear()}setFetchStrategy(e){return this.fetchStrategy=e,this}getFetchStrategy(){return this.fetchStrategy}enableFetching(){return this.enabled=!0,this.allowedDomains=[],this}enableFetchingForDomains(e){return this.enabled=!0,this.allowedDomains=[...e],this}disableFetching(){return this.enabled=!1,this}isFetchingEnabled(){return this.enabled}getAllowedDomains(){return[...this.allowedDomains]}allowDomain(e){return this.allowedDomains.includes(e)||this.allowedDomains.push(e),this}disallowDomain(e){return this.allowedDomains=this.allowedDomains.filter(t=>t!==e),this}clearAllowedDomains(){return this.allowedDomains=[],this}}class sr{resolveWithoutLimits(e){return this.resolve(e,j)}}class nr extends sr{mergingProcessor;nodeProvider;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProvider=fe.wrap(t)}merge(e,t,r){return this.mergeWithContext(e,t,this.createResolutionContext(r))}mergeWithContext(e,t,r){if(u.isNonNullable(t.getBlue()))throw new Error('Document contains "blue" attribute. Preprocess document before merging.');let n=e;const i=t.getType();if(u.isNonNullable(i)){const o=this.resolveTypeNode(i,r),l=o.clone().setType(void 0).setBlueId(void 0);n=this.mergeObject(n,l,r);const a=t.cloneShallow().setType(o.clone());return this.mergeObject(n,a,r)}return this.mergeObject(n,t,r)}mergeObject(e,t,r){const n=e.cloneShallow();let i=this.mergingProcessor.process(n,t,r.nodeProvider);const o=t.getItems();u.isNonNullable(o)&&(i=this.mergeChildren(i,o,r));const l=t.getProperties();return u.isNonNullable(l)&&(i=this.mergeProperties(i,l,r)),u.isNonNullable(t.getBlueId())&&(i=i.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(i=this.mergingProcessor.postProcess(i,t,r.nodeProvider)),i}mergeChildren(e,t,r){const n=e.getItems(),i=u.isNonNullable(n)||this.isInheritedListMarkerNode(t[0])?this.getInheritedItemsPrefixLength(t,n??[],r):void 0;if(this.rememberInheritedItemsPrefix(t,i,r),u.isNullable(n)){const l=[];for(let a=0;a<t.length;a++){const p=t[a];if(r.limits.shouldMergePathSegment(String(a),p)){this.enterPathSegment(r,String(a),p);try{const f=this.materializeForCurrentContext(p,r);l.push(f)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}if(u.isNonNullable(i)){const l=this.mergeChildrenWithInheritedItemsPrefix(t,n,i,r);return e.cloneShallow().setItems(l)}if(t.length<n.length)throw new Error(`Subtype of element must not have more items (${n.length}) than the element itself (${t.length}).`);const o=[...n];for(let l=0;l<t.length;l++)if(r.limits.shouldMergePathSegment(String(l),t[l])){this.enterPathSegment(r,String(l),t[l]);try{if(l>=o.length){const f=this.materializeForCurrentContext(t[l],r);o.push(f);continue}const a=I.calculateBlueIdSync(t[l]),p=I.calculateBlueIdSync(o[l]);if(a!==p)throw new Error(`Mismatched items at index ${l}: source item has blueId '${a}', but target item has blueId '${p}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(o)}getInheritedItemsPrefixLength(e,t,r){const n=e[0],i=n?.getBlueId();if(u.isNullable(i))return;let o;if(t.length>0){const l=I.calculateBlueIdSync(t);i===l&&(o=t.length)}if(u.isNullable(o)){const l=r.inheritedItemsPrefixByPath.get(this.getCurrentPointer(r));u.isNonNullable(l)&&l.blueId===i&&(o=l.length)}if(!u.isNullable(o)){if(!this.isInheritedListMarkerNode(n)){if(e.length>1)throw new Error("Invalid inherited-list marker: first list item must contain only blueId.");return}return o}}rememberInheritedItemsPrefix(e,t,r){const n=this.getCurrentPointer(r);if(e.length===0)return;const i=e[0],l=this.isInheritedListMarkerNode(i)?u.isNonNullable(t)?t+e.length-1:void 0:e.length;if(u.isNullable(l))return;const a={blueId:I.calculateBlueIdSync(e),length:l},p=r.inheritedItemsPrefixByPath.get(n);u.isNonNullable(p)&&p.length>=a.length||r.inheritedItemsPrefixByPath.set(n,a)}isInheritedListMarkerNode(e){return u.isNonNullable(e)&&u.isNonNullable(e.getBlueId())&&ve.hasBlueIdOnly(e)}mergeChildrenWithInheritedItemsPrefix(e,t,r,n){const i=[...t];for(let o=1;o<e.length;o++){const l=e[o],a=String(r+o-1);if(n.limits.shouldMergePathSegment(a,l)){this.enterPathSegment(n,a,l);try{const p=this.materializeForCurrentContext(l,n);i.push(p)}finally{this.exitPathSegment(n)}}}return i}mergeProperties(e,t,r){const n=e.getProperties()??{};let i=n,o=!1;for(const[l,a]of Object.entries(t))if(r.limits.shouldMergePathSegment(l,a)){this.enterPathSegment(r,l,a);try{const p=i[l],h=this.shouldMergePropertyWithoutPreResolve(p,a,r)?this.mergeWithContext(p,a,r):(()=>{const g=this.materializeForCurrentContext(a,r);return p===void 0?g:this.mergeObject(p,g,r)})();h!==p&&(o||(i={...n},o=!0),i[l]=h)}finally{this.exitPathSegment(r)}}return o?e.cloneShallow().setProperties(i):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof Se?!1:u.isNonNullable(t.getItems())||u.isNonNullable(e.getItems())}resolve(e,t){return this.resolveWithContext(e,this.createResolutionContext(t))}resolveWithContext(e,t){const r=new d,i=this.mergeWithContext(r,e,t).clone().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new ee(i)}createResolutionContext(e){return{limits:e,nodeProvider:this.nodeProvider,resolvedTypeCache:new Map,inheritedItemsPrefixByPath:new Map,pathStack:[]}}resolveTypeNode(e,t){const r=e.getBlueId();if(u.isNonNullable(r)){const n=this.createResolvedTypeCacheKey(r,t),i=t.resolvedTypeCache.get(n);if(u.isNonNullable(i))return i;const o=this.resolveAndExtendTypeNode(e,t);return t.resolvedTypeCache.set(n,o),o}return this.resolveAndExtendTypeNode(e,t)}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new pt(t.nodeProvider).extend(r,$e.withSinglePath("/")),this.resolveWithContext(r,t)}createResolvedTypeCacheKey(e,t){return t.limits instanceof Se?e:`${e}|${this.getCurrentPointer(t)}`}materializeForCurrentContext(e,t){return e.isResolved()&&this.canReuseResolvedSubtree(t)?e.clone():this.resolveWithContext(e,t)}canReuseResolvedSubtree(e){return e.limits instanceof Se}getCurrentPointer(e){return e.pathStack.length===0?"/":`/${e.pathStack.join("/")}`}enterPathSegment(e,t,r){e.pathStack.push(t),e.limits.enterPathSegment(t,r)}exitPathSegment(e){e.pathStack.pop(),e.limits.exitPathSegment()}}class ir{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((n,i)=>i.process(n,t,r),e)}postProcess(e,t,r){return this.mergingProcessors.reduce((n,i)=>i.postProcess?i.postProcess(n,t,r):n,e)}}class or{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const n=e.getValue();if(u.isNullable(n))return e.cloneShallow().setValue(r);if(!Ys(r,n))throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${n}`)}return e}}const Ys=(s,e)=>k(s)&&k(e)||Ce(s)&&Ce(e)?s.eq(e):s===e;class lr{process(e,t,r){const n=e.getType(),i=t.getType();let o=e;if(n===void 0)o=e.cloneShallow().setType(i);else if(i!==void 0){if(!B(i,n,r)){const a=m.get(i),p=m.get(n);throw new Error(`The source type '${JSON.stringify(a)}' is not a subtype of the target type '${JSON.stringify(p)}'.`)}o=e.cloneShallow().setType(i)}return o}}class ar{process(e,t,r){const n=t.getItemType(),i=t.getType();if(n!==void 0&&i!==void 0&&!we(i,r))throw new Error("Source node with itemType must have a List type");const o=e.getItemType();let l=e;if(o===void 0)n!==void 0&&(l=e.cloneShallow().setItemType(n));else if(n!==void 0){if(!B(n,o,r)){const h=m.get(n),g=m.get(o);throw new Error(`The source item type '${JSON.stringify(h)}' is not a subtype of the target item type '${JSON.stringify(g)}'.`)}l=e.cloneShallow().setItemType(n)}const a=l.getItemType(),p=t.getItems();if(a!==void 0&&p!==void 0)for(const f of p){const h=f.getType();if(h!==void 0&&!B(h,a,r)){const g=m.get(h),T=m.get(a);throw new Error(`Item of type '${JSON.stringify(g)}' is not a subtype of the list's item type '${JSON.stringify(T)}'.`)}}return l}}class ur{process(e,t,r){const n=t.getKeyType(),i=t.getValueType(),o=t.getType();if((n!==void 0||i!==void 0)&&o!==void 0&&!Ee(o,r))throw new Error("Source node with keyType or valueType must have a Dictionary type");let l=this.processKeyType(e,t,r);l=this.processValueType(l,t,r);const a=l.getKeyType(),p=l.getValueType(),f=t.getProperties();return(a!==void 0||p!==void 0)&&f!==void 0&&Object.entries(f).forEach(([h,g])=>{a!==void 0&&this.validateKeyType(h,a,r),p!==void 0&&this.validateValueType(g,p,r)}),l}processKeyType(e,t,r){const n=e.getKeyType(),i=t.getKeyType();if(n===void 0){if(i!==void 0)return this.validateBasicKeyType(i,r),e.cloneShallow().setKeyType(i)}else if(i!==void 0){if(this.validateBasicKeyType(i,r),!B(i,n,r)){const l=m.get(i),a=m.get(n);throw new Error(`The source key type '${JSON.stringify(l)}' is not a subtype of the target key type '${JSON.stringify(a)}'.`)}return e.cloneShallow().setKeyType(i)}return e}processValueType(e,t,r){const n=e.getValueType(),i=t.getValueType();if(n===void 0){if(i!==void 0)return e.cloneShallow().setValueType(i)}else if(i!==void 0){if(!B(i,n,r)){const l=m.get(i),a=m.get(n);throw new Error(`The source value type '${JSON.stringify(l)}' is not a subtype of the target value type '${JSON.stringify(a)}'.`)}return e.cloneShallow().setValueType(i)}return e}validateBasicKeyType(e,t){if(!es(e,t))throw new Error("Dictionary key type must be a basic type")}validateKeyType(e,t,r){if(!ts(t,r))if(rs(t,r)){const n=Number.parseInt(e,10);if(Number.isNaN(n)||n.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(ss(t,r)){const n=Number.parseFloat(e);if(Number.isNaN(n))throw new Error(`Key '${e}' is not a valid Number.`)}else if(ns(t,r)){if(e.toLowerCase()!=="true"&&e.toLowerCase()!=="false")throw new Error(`Key '${e}' is not a valid Boolean.`)}else throw new Error(`Unsupported key type: ${t.getName()||"unknown"}`)}validateValueType(e,t,r){const n=e.getType();if(n!==void 0&&!B(n,t,r)){const i=m.get(n),o=m.get(t);throw new Error(`Value of type '${JSON.stringify(i)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}class cr{process(e){return e}postProcess(e,t,r){const n=e.getType();if(n!==void 0&&is(n,r)){const i=e.getItems(),o=e.getProperties();if(i!==void 0&&i.length>0||o!==void 0&&Object.keys(o).length>0){const l=os(n,r),a=n.getName()||"unknown";throw new Error(`Node of type "${a}" (which extends basic type "${l}") must not have items, properties or contracts.`)}}return e}}class dr{process(e,t){let r=e;const n=t.getName();n!==void 0&&n!==e.getName()&&(r=r.cloneShallow().setName(n));const i=t.getDescription();return i!==void 0&&i!==r.getDescription()&&(r=r.cloneShallow().setDescription(i)),r}}const Js=Object.freeze(Object.defineProperty({__proto__:null,BasicTypesVerifier:cr,DictionaryProcessor:ur,ListProcessor:ar,MetadataPropagator:dr,SequentialMergingProcessor:ir,TypeAssigner:lr,ValuePropagator:or},Symbol.toStringTag,{value:"Module"}));function Zs(){return new ir([new or,new lr,new ar,new ur,new dr,new cr])}class Gs{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(_e).forEach(([i,o])=>{this.blueIdToInlineValue.set(i,o)});const n=r.getAllBlueIds();Object.entries(n).forEach(([i,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,i)})}restore(e){return E.transform(e,t=>this.restoreNode(t))}restoreNode(e){return this.restoreTypeField(e,()=>e.getType(),t=>e.setType(t)),this.restoreTypeField(e,()=>e.getItemType(),t=>e.setItemType(t)),this.restoreTypeField(e,()=>e.getKeyType(),t=>e.setKeyType(t)),this.restoreTypeField(e,()=>e.getValueType(),t=>e.setValueType(t)),e}restoreTypeField(e,t,r){const n=t();if(!n||n.isInlineValue()&&n.getValue()!==void 0)return;const i=n.getBlueId();if(!i)return;const o=this.resolveInlineValue(i,n);if(!o)return;const l=new d().setValue(o).setInlineValue(!0);r(l)}resolveInlineValue(e,t){const r=this.blueIdToInlineValue.get(e);if(r)return r;const n=t.getName();if(n)return this.blueIdToInlineValue.set(e,n),n;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class Ws{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(Hs(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)an(this.contents,r.contents,r.name),ln(this.aliases,r.aliases,r.name)}getRuntimes(){return this.runtimes}getAliases(){return this.aliases}getContents(){return this.contents}findRuntimeByName(e){return this.runtimes.find(t=>t.name===e)}toCurrentBlueId(e){for(const t of this.runtimes){const r=t.toCurrentBlueIdIndex[e];if(r)return r}return e}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=_e[t];if(r)return r;for(const n of this.runtimes){const i=n.typeAliasByCurrentBlueId[t];if(i)return i}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const n=r.types[t];if(n)return{runtime:r,currentBlueId:t,typeMeta:n,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function Hs(s){const e=qs(s);return Object.values(s.packages).forEach(t=>{Xs(e,s,t)}),{name:s.name,repositoryVersions:s.repositoryVersions,repoVersionIndexById:e.repoVersionIndexById,aliases:e.aliases,types:e.types,toCurrentBlueIdIndex:e.toCurrentBlueIdIndex,contents:e.contents,schemas:e.schemas,currentRepoBlueId:e.currentRepoBlueId,typeAliasByCurrentBlueId:e.typeAliasByCurrentBlueId,typePackageByCurrentBlueId:e.typePackageByCurrentBlueId}}function qs(s){const e=Object.fromEntries(s.repositoryVersions.map((r,n)=>[r,n])),t=s.repositoryVersions[s.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function Xs(s,e,t){if(s.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);s.packageNames.add(t.name),Qs(s,t),en(s,e,t),tn(s,t),rn(s,t)}function Qs(s,e){Object.entries(e.aliases).forEach(([t,r])=>{if(s.aliases[t]&&s.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);s.aliases[t]=r})}function en(s,e,t){Object.entries(t.typesMeta).forEach(([r,n])=>{if(s.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const i=sn(n,e,r,t.name);if(s.types[r]=i,s.typePackageByCurrentBlueId[r]=t.name,s.typeAliasByCurrentBlueId[r]=`${t.name}/${n.name}`,i.status===v.BLUE_REPOSITORY_STATUS_STABLE&&!s.toCurrentBlueIdIndex[r]&&(s.toCurrentBlueIdIndex[r]=r),i.status===v.BLUE_REPOSITORY_STATUS_STABLE)for(const o of i.versions){const l=s.toCurrentBlueIdIndex[o.typeBlueId];if(l&&l!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);s.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function tn(s,e){Object.entries(e.contents).forEach(([t,r])=>{s.contents[t]=r})}function rn(s,e){s.schemas.push(...Object.values(e.schemas))}function sn(s,e,t,r){if(s.status===v.BLUE_REPOSITORY_STATUS_DEV)return nn(s,e,t,r),{...s,versions:s.versions?[...s.versions]:s.versions};const n=[...s.versions??[]].sort((o,l)=>o.repositoryVersionIndex-l.repositoryVersionIndex);if(n.length===0)throw new Error(`Stable type ${r}/${s.name} (${t}) must have at least one version entry`);const i=new Set;return n.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${s.name}`);if(i.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${s.name}`);i.add(o.repositoryVersionIndex);for(const l of o.attributesAdded??[])on(l,e.name,t,o.repositoryVersionIndex)}),{...s,versions:n}}function nn(s,e,t,r){if(s.status===v.BLUE_REPOSITORY_STATUS_DEV){if(s.versions&&s.versions.length>1)throw new Error(`Dev type ${r}/${s.name} (${t}) must not declare multiple versions`);if(s.versions&&s.versions.length===1){const n=s.versions[0];if(n.repositoryVersionIndex<0||n.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${n.repositoryVersionIndex} for dev type ${r}/${s.name}`)}}}function on(s,e,t,r){try{v.validateAttributesAddedPointer(s)}catch(n){const i=n instanceof Error?n.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${s}' for type ${t} in repository ${e} at index ${r}: ${i}`)}}function ln(s,e,t){for(const[r,n]of Object.entries(e)){const i=s[r];if(i&&i!==n)throw new Error(`Conflicting alias '${r}' across repositories: '${i}' vs '${n}' (from ${t})`);s[r]=n}}function an(s,e,t){for(const[r,n]of Object.entries(e)){if(r in s){const i=s[r];if(!un(i,n))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}s[r]=n}}function un(s,e){if(s===e)return!0;if(s===null||e===null||typeof s!="object"||typeof e!="object")return!1;const t=Ae.canonicalize(s),r=Ae.canonicalize(e);return t!==void 0&&t===r}class Oe extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r&&r.length>0?r:[],this.name="BlueError"}}const L={REPO_UNKNOWN_REPO_BLUE_ID:"REPO_UNKNOWN_REPO_BLUE_ID",REPO_UNREPRESENTABLE_IN_TARGET_VERSION:"REPO_UNREPRESENTABLE_IN_TARGET_VERSION",INVALID_BLUE_CONTEXT_REPOSITORIES:"INVALID_BLUE_CONTEXT_REPOSITORIES",INVALID_REPOSITORY_POINTER:"INVALID_REPOSITORY_POINTER"},cn=new Set(["__proto__","constructor","prototype"]);function Tt(s){const e=s.at(0),t=s.at(-1);return!e||!t?s:e==="'"&&t==="'"||e==='"'&&t==='"'?s.slice(1,-1):s}function dn(s,e){const t=s.indexOf("=");if(t===-1)throw se(e,`Missing '=' in segment '${s.trim()}'`);if(s.indexOf("=",t+1)!==-1)throw se(e,`Unexpected '=' in segment '${s.trim()}'`);const r=Tt(s.slice(0,t).trim()),n=Tt(s.slice(t+1).trim());if(!r)throw se(e,"Repository name is empty");if(!n)throw se(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:n}}function pn(s){if(s.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of s.split(",")){const r=t.trim();if(!r)throw se(s,"Empty repository segment");const{name:n,value:i}=dn(r,s);fn(n,s),e[n]=i}return e}function hn(s){return typeof s=="string"?pn(s):s}function se(s,e){return new Oe(L.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:L.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:s,reason:e}}])}function fn(s,e){if(cn.has(s))throw se(e,`Forbidden repository name '${s}'`)}function yn(s,e){const t=s.filter(n=>n.repositoryVersionIndex>e).sort((n,i)=>i.repositoryVersionIndex-n.repositoryVersionIndex),r=[];for(const n of t){const i=[...n.attributesAdded].sort((o,l)=>bt(l)-bt(o));r.push(...i)}return r}function bt(s){return v.parsePointer(s).length}const gn=new Set([...et]),w={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class mn{registry;targetRepoVersionIndexes;fallbackToCurrentInlineDefinitions;inliningStack=new Set;constructor(e){this.registry=e.registry,this.targetRepoVersionIndexes=e.targetRepoVersionIndexes,this.fallbackToCurrentInlineDefinitions=e.fallbackToCurrentInlineDefinitions}transform(e){return E.transform(e,t=>this.transformNode(t))}transformNode(e){return this.processTypeReference(e,{getter:()=>e.getType(),setter:t=>e.setType(t),schemaTraversalTargets:[e]}),this.processTypeReference(e,{getter:()=>e.getItemType(),setter:t=>e.setItemType(t),schemaTraversalTargets:e.getItems()??[]}),this.processTypeReference(e,{getter:()=>e.getKeyType(),setter:t=>e.setKeyType(t),schemaTraversalTargets:[]}),this.processTypeReference(e,{getter:()=>e.getValueType(),setter:t=>e.setValueType(t),schemaTraversalTargets:this.getDictionaryValueTargets(e)}),e}processTypeReference(e,t){const r=t.getter(),n=r?.getBlueId();if(!r||!n)return;const i=this.resolveType(n);switch(i.kind){case w.core:{r.setBlueId(i.blueId);return}case w.representable:{this.applyDropPointers([r],i.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,i.dropPointers),r.setBlueId(i.targetBlueId);return}case w.noRuntime:case w.noTargetContext:case w.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,n);return}throw i.kind===w.unrepresentable?i.error:this.unrepresentableError(n,i.kind===w.noTargetContext?`Repository '${i.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",i.kind===w.noTargetContext?i.runtime:void 0,i.kind===w.noTargetContext?i.meta:void 0,void 0,i.kind===w.noTargetContext?i.typeAlias:void 0)}}}resolveType(e){if(re.includes(e))return{kind:w.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),n=this.registry.findRuntimeByBlueId(t);if(!n||!n.typeMeta)return{kind:w.noRuntime};const i=this.targetRepoVersionIndexes[n.runtime.name];if(i===void 0)return{kind:w.noTargetContext,currentBlueId:t,runtimeName:n.runtime.name,runtime:n.runtime,meta:n.typeMeta,typeAlias:r};const o=n.typeMeta;if(o.status===v.BLUE_REPOSITORY_STATUS_DEV){const h=n.runtime.repositoryVersions.length-1;if(i!==h)return{kind:w.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${i}.`,n.runtime,o,i,r)};const g=o.versions?.[0];return{kind:w.representable,currentBlueId:t,targetBlueId:g?.typeBlueId??t,dropPointers:[]}}const l=o.versions||[];if(l.length===0)return{kind:w.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,n.runtime,o,i,r)};const a=l[0].repositoryVersionIndex;if(i<a)return{kind:w.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${i}.`,n.runtime,o,i,r)};let p=l[0].typeBlueId;for(const h of l)h.repositoryVersionIndex<=i&&(p=h.typeBlueId);const f=o.status===v.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,i):[];return{kind:w.representable,currentBlueId:t,targetBlueId:p,dropPointers:f}}getDropPointers(e,t){return e.status!==v.BLUE_REPOSITORY_STATUS_STABLE?[]:yn(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const n=r.rootIsSchema??!1;for(const i of t)for(const o of e)this.deletePropertyAtPointer(o,i,n)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,n])=>n instanceof d&&!gn.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let n;try{n=v.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,n,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[n,...i]=t;if(n===Q){const a=e.getType();a&&this.applyPointerSegments(a,i,!0);return}if(n===ye){const a=e.getItemType();a&&this.applyPointerSegments(a,i,!0);return}if(n===ge){const a=e.getKeyType();a&&this.applyPointerSegments(a,i,!0);return}if(n===me){const a=e.getValueType();a&&this.applyPointerSegments(a,i,!0);return}const o=e.getProperties();if(!o)return;if(i.length===0){if(!r||!(n in o))return;const a={...o};delete a[n],e.setProperties(a);return}const l=o[n];l instanceof d&&this.applyPointerSegments(l,i,r)}inlineDefinition(e,t,r){const n=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(n))throw this.unrepresentableError(n,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(n)});const i=this.registry.getContents()[n];if(!i)throw this.unrepresentableError(n,`Missing definition to inline for BlueId ${n}.`);this.inliningStack.add(n);try{const o=y.deserialize(i);o.setBlueId(void 0);const l=E.transform(o,a=>this.transformNode(a));return t(l),e}finally{this.inliningStack.delete(n)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new Oe(L.INVALID_REPOSITORY_POINTER,t,[{code:L.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,n,i,o,l){const a={currentTypeBlueId:e,targetRepoVersionIndex:i,typeAlias:o,...l};if(r&&(i!==void 0&&(a.requestedRepoBlueId=r.repositoryVersions[i]),a.serverRepoBlueId=r.currentRepoBlueId),n&&n.status===v.BLUE_REPOSITORY_STATUS_STABLE){const f=n.versions?.[0]?.repositoryVersionIndex;f!==void 0&&(a.typeIntroducedInRepoBlueId=r?.repositoryVersions[f])}const p={code:L.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[Q],context:a};return new Oe(L.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[p])}}function Qe(s,e){return e?E.transform(s,t=>(Be(()=>t.getType(),r=>t.setType(r),e),Be(()=>t.getItemType(),r=>t.setItemType(r),e),Be(()=>t.getKeyType(),r=>t.setKeyType(r),e),Be(()=>t.getValueType(),r=>t.setValueType(r),e),t)):s}function Be(s,e,t){const r=s();if(!r||r.isInlineValue())return;const n=r.getBlueId();if(!n)return;const i=t.toCurrentBlueId(n);i!==n&&e(r.clone().setBlueId(i))}class In{registry;blueIdMapper;constructor(e){this.registry=e.registry,this.blueIdMapper=e.blueIdMapper}transform(e,t){const r=this.computeTargetRepoVersionIndexes(t);if(Object.keys(r).length===0)return e;const n=Qe(e,this.blueIdMapper);return new mn({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(n)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?hn(e.repositories):e.repositories;for(const[n,i]of Object.entries(r)){const o=this.registry.findRuntimeByName(n);if(!o)continue;const l=o.repoVersionIndexById[i];if(l===void 0)throw this.unknownRepoBlueIdError(n,i,o.currentRepoBlueId);t[n]=l}return t}unknownRepoBlueIdError(e,t,r){const n=`Unknown RepoBlueId '${t}' for repository '${e}'.`,i={code:L.REPO_UNKNOWN_REPO_BLUE_ID,message:n,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new Oe(L.REPO_UNKNOWN_REPO_BLUE_ID,n,[i])}}class Tn{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=j;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:n,repositories:i,mergingProcessor:o}=e;this.repositories=i,this.repositoryRegistry=new Ws(i??[]),this.blueContextResolver=new In({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry});const l=vs(()=>[]);this.nodeProvider=fe.wrap(t||l,i),this.typeSchemaResolver=r??new Zt([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.mergingProcessor=o??Zs(),this.urlContentFetcher=new Ks(n),this.blueDirectivePreprocessor=new zs(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new ht,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const a=this.repositoryRegistry.getRuntimes().flatMap(p=>p.schemas);a.length>0&&this.typeSchemaResolver?.registerSchemas(a)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),n=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return m.get(n,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),n=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return Ss.get(n,{strategy:r.format})}nodeToSchemaOutput(e,t){return new bs(this.typeSchemaResolver).convert(e,t)}resolve(e,t=j){const r=this.combineWithGlobalLimits(t);return new nr(this.mergingProcessor,this.nodeProvider).resolve(e,r)}createResolvedNode(e){return e instanceof ee?e:new ee(e)}reverse(e){return new Wt().reverse(e)}restoreInlineTypes(e){return new Gs({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new pt(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(y.deserialize(e));return Qe(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(y.deserialize(e));return Qe(t,this.repositoryRegistry)}yamlToNode(e){const t=$(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}async yamlToNodeAsync(e){const t=$(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeAsync(t)}prepareForBlueIdCalculation=async e=>e instanceof d||Array.isArray(e)&&e.every(t=>t instanceof d)?e:Array.isArray(e)?await Promise.all(e.map(r=>this.jsonValueToNodeAsync(r))):this.jsonValueToNodeAsync(e);calculateBlueId=async e=>{const t=await this.prepareForBlueIdCalculation(e);return I.calculateBlueId(t)};prepareForBlueIdCalculationSync=e=>e instanceof d||Array.isArray(e)&&e.every(t=>t instanceof d)?e:Array.isArray(e)?e.map(t=>this.jsonValueToNode(t)):this.jsonValueToNode(e);calculateBlueIdSync(e){const t=this.prepareForBlueIdCalculationSync(e);return I.calculateBlueIdSync(t)}getTypeAliasByBlueId(e){const t=e?.trim();if(t)return this.repositoryRegistry.getTypeAlias(t)}addPreprocessingAliases(e){this.blueDirectivePreprocessor.addPreprocessingAliases(e)}preprocess(e){const t=this.blueDirectivePreprocessor.process(e);return new oe({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new oe({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}transform(e,t){return E.transform(e,t)}getNodeProvider(){return this.nodeProvider}setNodeProvider(e){return this.nodeProvider=fe.wrap(e,this.repositories),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this}getTypeSchemaResolver(){return this.typeSchemaResolver}setTypeSchemaResolver(e){return this.typeSchemaResolver=e,this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this}getUrlContentFetcher(){return this.urlContentFetcher}setUrlFetchStrategy(e){return this.urlContentFetcher.setFetchStrategy(e),this}enablePreprocessingDirectivesFetchForUrls(){return this.urlContentFetcher.enableFetching(),this}enablePreprocessingDirectivesFetchForDomains(e){return this.urlContentFetcher.enableFetchingForDomains(e),this}allowUrlFetchingForDomain(e){return this.urlContentFetcher.allowDomain(e),this}disallowUrlFetchingForDomain(e){return this.urlContentFetcher.disallowDomain(e),this}getAllowedUrlFetchingDomains(){return this.urlContentFetcher.getAllowedDomains()}disablePreprocessingDirectivesFetchForUrls(){return this.urlContentFetcher.disableFetching(),this}isPreprocessingDirectivesFetchForUrlsEnabled(){return this.urlContentFetcher.isFetchingEnabled()}getPreprocessingAliases(){return this.blueDirectivePreprocessor.getPreprocessingAliases()}setPreprocessingAliases(e){return this.blueDirectivePreprocessor.setPreprocessingAliases(e),this}registerBlueIds(...e){return this.blueIdsMappingGenerator.registerBlueIds(...e),this}getAllRegisteredBlueIds(){return this.blueIdsMappingGenerator.getAllBlueIds()}getAllBlueIdNames(){return this.blueIdsMappingGenerator.getAllBlueIdNames()}getBlueIdsMappingGenerator(){return this.blueIdsMappingGenerator}isTypeOf(e,t,r){return O.isTypeOf(e,t,{checkSchemaExtensions:r?.checkSchemaExtensions,typeSchemaResolver:this.typeSchemaResolver})}isTypeOfBlueId(e,t){const r=t.trim();if(r.length===0)return!1;const n=e.getType();if(!n)return!1;const i=new d().setBlueId(r);return B(n,i,this.nodeProvider)}isTypeOfNode(e,t){return new ls(this).matchesType(e,t,this.globalLimits)}setGlobalLimits(e){return this.globalLimits=e??j,this}getGlobalLimits(){return this.globalLimits}normalizeNodeToJsonOptions(e){return typeof e=="string"?{format:e,blueContext:void 0}:{format:e?.format??"official",blueContext:e?.blueContext}}combineWithGlobalLimits(e){return this.globalLimits==j?e:e==j?this.globalLimits:je.of(this.globalLimits,e)}}class bn extends Qt{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;preprocessor;constructor(e=[]){super();const t=new oe({nodeProvider:this});this.preprocessor=r=>t.preprocessWithDefaultBlue(r),e.forEach(r=>this.processNode(r))}processNode(e){ve.hasItemsOnly(e)?this.processNodeWithItems(e):this.processSingleNode(e)}processSingleNode(e){const t=H.parseAndCalculateBlueIdForNode(e,this.preprocessor);this.blueIdToContentMap.set(t.blueId,t.content),this.blueIdToMultipleDocumentsMap.set(t.blueId,t.isMultipleDocuments);const r=e.getName();r&&this.addToNameMap(r,t.blueId)}processNodeWithItems(e){const t=e.getItems();if(!t)return;this.processNodeList(t);const r=H.parseAndCalculateBlueIdForNodeList(t,this.preprocessor);this.blueIdToContentMap.set(r.blueId,r.content),this.blueIdToMultipleDocumentsMap.set(r.blueId,!0),t.forEach((n,i)=>{const o=n.getName();o&&this.addToNameMap(o,`${r.blueId}#${i}`)})}processNodeList(e){const t=I.calculateBlueIdSync(e),r=e.map(n=>m.get(n));this.blueIdToContentMap.set(t,r),this.blueIdToMultipleDocumentsMap.set(t,!0)}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?H.resolveThisReferences(t,e,r):null}addSingleNodes(...e){e.forEach(t=>this.processNode(t))}addSingleDocs(...e){e.forEach(t=>{const r=$(t);if(r!==void 0){const n=y.deserialize(r);this.processNode(n)}})}getBlueIdByName(e){const t=this.nameToBlueIdsMap.get(e);if(!t||t.length===0)throw new Error(`No node with name "${e}"`);return t[0]}getNodeByName(e){const t=this.findNodeByName(e);if(!t)throw new Error(`No node with name "${e}"`);return t}addListAndItsItemsFromNodes(e){this.processNodeList(e),e.forEach(t=>this.processNode(t))}addListAndItsItemsFromDoc(e){const t=$(e);if(t!==void 0){const n=y.deserialize(t).getItems();n&&this.addListAndItsItems(n)}}addListAndItsItems(e){Array.isArray(e)?this.addListAndItsItemsFromNodes(e):this.addListAndItsItemsFromDoc(e)}addList(e){this.processNodeList(e)}}exports.Base58Sha256Provider=Ot;exports.BasicNodeProvider=bn;exports.Blue=Tn;exports.BlueIdCalculator=I;exports.BlueIdToCid=xr;exports.BlueNode=d;exports.BlueNodeTypeSchema=O;exports.JsonCanonicalizer=Ae;exports.Limits=Fe;exports.Merger=nr;exports.MergingProcessors=Js;exports.NodeResolver=sr;exports.Nodes=ve;exports.Properties=mr;exports.ResolvedBlueNode=ee;exports.TypeSchemaResolver=Zt;exports.applyBlueNodePatch=Yr;exports.baseBlueObjectSchema=Te;exports.blueDescriptionField=Zr;exports.blueIdField=Wr;exports.blueIdSchema=Tr;exports.blueNameField=Hr;exports.blueNodeField=qr;exports.blueObjectBooleanValueSchema=Nr;exports.blueObjectNumberValueSchema=vr;exports.blueObjectSchema=ne;exports.blueObjectStringListItemsSchema=Br;exports.blueObjectStringValueSchema=br;exports.calculateBlueId=tr;exports.calculateBlueIdSync=Ds;exports.enrichWithBlueId=qe;exports.getBlueDescriptionAnnotation=jt;exports.getBlueIdAnnotation=Ut;exports.getBlueNameAnnotation=kt;exports.getBlueNodeAnnotation=Yt;exports.getBlueObjectItems=xs;exports.getBlueObjectProperties=Fs;exports.getBlueObjectTypeLabel=$s;exports.getBlueObjectValue=_s;exports.getTypeBlueIdAnnotation=Jt;exports.hasBlueObjectBlueIdDefined=Ct;exports.hasBlueObjectItemsDefined=At;exports.hasBlueObjectNameDefined=Er;exports.hasBlueObjectTypeDefined=Rt;exports.hasBlueObjectValueDefined=Vt;exports.isBigDecimalNumber=Ce;exports.isBigIntegerNumber=k;exports.isBigNumber=R;exports.isBlueNodeSchema=ct;exports.isBlueObject=wr;exports.isBlueObjectResolved=rr;exports.isGivenBlueObjectTypeSchema=Sr;exports.isJsonBlueArray=ot;exports.isJsonBlueObject=it;exports.isJsonBlueValue=Ar;exports.isUrl=ce;exports.jsonBlueValueSchema=pe;exports.normalizeToBlueObject=js;exports.resolveBlueObjectItems=Xe;exports.withBlueDescription=$t;exports.withBlueId=Lt;exports.withBlueName=zt;exports.withBlueNode=Kt;exports.withTypeBlueId=Qr;exports.yamlBlueDump=qt;exports.yamlBlueParse=$;
|