@blue-labs/language 4.0.0-rc.3 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -8
- package/dist/index.mjs +1130 -1362
- package/dist/lib/index.d.ts +0 -1
- package/dist/lib/index.d.ts.map +1 -1
- package/dist/lib/utils/NodeTypeMatcher.d.ts +2 -0
- package/dist/lib/utils/NodeTypeMatcher.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/lib/repository/SemanticRepositoryReindexer.d.ts +0 -15
- package/dist/lib/repository/SemanticRepositoryReindexer.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Z=require("big.js"),u=require("@blue-labs/shared-utils"),h=require("zod"),Lr=require("bs58"),H=require("radash"),B=require("@blue-labs/repository-contract"),jr=require("js-sha256"),xr=require("crypto"),$r=require("base32.js"),pe=require("js-yaml"),Ft=i=>i&&i.__esModule?i:{default:i},Oe=Ft(Lr),it=Ft(xr);class D extends Z{constructor(e){super(e)}}class O extends Z{constructor(e){super(e)}}const le="name",ae="description",K="type",be="itemType",Pe="keyType",Se="valueType",J="value",W="items",V="blueId",Le="blue",vt=[le,ae,K,be,Pe,Se,J,W,V,Le],zt="Text",Ut="Double",Kt="Integer",Ht="Boolean",kt="List",Yt="Dictionary",Ge=[zt,Ut,Kt,Ht],Bt=[...Ge,kt,Yt],te="DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",re="7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",se="5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",ie="4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",qe="6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",Nt="G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",bt=[te,re,se,ie],fe=[...bt,qe,Nt],Wt=Object.fromEntries(Bt.map((i,e)=>[i,fe[e]])),Xe=Object.fromEntries(fe.map((i,e)=>[i,Bt[e]])),Fr=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:Ge,BASIC_TYPE_BLUE_IDS:bt,BOOLEAN_TYPE:Ht,BOOLEAN_TYPE_BLUE_ID:ie,CORE_TYPES:Bt,CORE_TYPE_BLUE_IDS:fe,CORE_TYPE_BLUE_ID_TO_NAME_MAP:Xe,CORE_TYPE_NAME_TO_BLUE_ID_MAP:Wt,DICTIONARY_TYPE:Yt,DICTIONARY_TYPE_BLUE_ID:Nt,DOUBLE_TYPE:Ut,DOUBLE_TYPE_BLUE_ID:re,INTEGER_TYPE:Kt,INTEGER_TYPE_BLUE_ID:se,LIST_TYPE:kt,LIST_TYPE_BLUE_ID:qe,OBJECT_BLUE:Le,OBJECT_BLUE_ID:V,OBJECT_CONTRACTS:B.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:ae,OBJECT_ITEMS:W,OBJECT_ITEM_TYPE:be,OBJECT_KEY_TYPE:Pe,OBJECT_MERGE_POLICY:B.OBJECT_MERGE_POLICY,OBJECT_NAME:le,OBJECT_SCHEMA:B.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:vt,OBJECT_TYPE:K,OBJECT_VALUE:J,OBJECT_VALUE_TYPE:Se,TEXT_TYPE:zt,TEXT_TYPE_BLUE_ID:te},Symbol.toStringTag,{value:"Module"}));class zr{static get(e,t,r,s=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return s&&o!==void 0?o:e}const n=t.substring(1).split("/");return this.getRecursive(e,n,0,r,s)}static getRecursive(e,t,r,s,n){if(r===t.length-1&&!n)return this.getNodeForSegment(e,t[r],s,!1);if(r===t.length){const a=e.getValue();return n&&a!==void 0?a:e}const o=t[r],l=this.getNodeForSegment(e,o,s,!0);if(l)return this.getRecursive(l,t,r+1,s,n)}static getNodeForSegment(e,t,r,s){let n;const o=e.getProperties();if(o&&t in o)n=o[t];else switch(t){case"name":{const l=e.getName();n=new d().setValue(l??null);break}case"description":{const l=e.getDescription();n=new d().setValue(l??null);break}case"type":n=e.getType();break;case"itemType":n=e.getItemType();break;case"keyType":n=e.getKeyType();break;case"valueType":n=e.getValueType();break;case"value":{const l=e.getValue();n=new d().setValue(l??null);break}case"blueId":{const l=e.getBlueId();n=new d().setValue(l??null);break}case"blue":n=e.getBlue();break;case"items":{const l=e.getItems();n=new d().setItems(l);break}case"properties":{const l=e.getProperties();n=new d().setProperties(l);break}case B.OBJECT_CONTRACTS:{const l=e.getContracts();n=new d().setContracts(l);break}default:{if(/^\d+$/.test(t)){const l=parseInt(t,10),a=e.getItems();a&&l>=0&&l<a.length?n=a[l]:n=void 0}else n=void 0;break}}if(n)return s&&r?this.link(n,r):n}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===se&&typeof this.value=="string")return new O(this.value);if(e===re&&typeof this.value=="string"){const t=new D(this.value),r=parseFloat(t.toString());return new D(r.toString())}else if(e===ie&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new O(e.toString()):this.value=new D(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}getReferenceBlueId(){return this.blueId}setReferenceBlueId(e){return this.blueId=e,this}getBlueId(){return this.getReferenceBlueId()}setBlueId(e){return this.setReferenceBlueId(e)}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 zr.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 O||t instanceof D)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 Te{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],s=r.length;if(s<this.MIN_BLUE_ID_LENGTH||s>this.MAX_BLUE_ID_LENGTH)return!1;try{if(Oe.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 Ur=h.z.string().max(Te.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(Te.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(i=>{try{return Oe.default.decode(i),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),ve=h.z.lazy(()=>h.z.record(h.z.unknown()).and(h.z.object({blueId:h.z.string().optional(),name:h.z.string().optional(),description:h.z.string().optional(),type:ve.optional(),value:h.z.union([h.z.string(),h.z.number(),h.z.boolean()]).optional().nullable(),items:h.z.array(ve).optional()}))),je=h.z.object({blueId:h.z.string().optional(),name:h.z.string().optional(),description:h.z.string().optional(),type:ve.optional()}),Kr=je.extend({value:h.z.string().optional()}),Hr=je.extend({value:h.z.number().optional()}),kr=je.extend({value:h.z.boolean().optional()}),Yr=je.extend({items:h.z.array(h.z.string()).optional()}),Wr=i=>ve.safeParse(i).success,Jt=i=>u.isNonNullable(i)&&"blueId"in i&&u.isNonNullable(i.blueId),Jr=i=>u.isNonNullable(i)&&"name"in i&&u.isNonNullable(i.name),Zt=i=>u.isNonNullable(i)&&"items"in i&&u.isNonNullable(i.items),Gt=i=>u.isNonNullable(i)&&"type"in i&&u.isNonNullable(i.type),qt=i=>u.isNonNullable(i)&&"value"in i&&u.isNonNullable(i.value),Zr=(i,e)=>i.required({type:!0}).safeParse(e).success,E=i=>i instanceof Z,Q=i=>E(i)&&i instanceof O,He=i=>E(i)&&i instanceof D,Gr=h.z.lazy(()=>h.z.record(Ve)),qr=h.z.lazy(()=>h.z.union([h.z.array(Ve),h.z.array(Ve).readonly()])),Ve=h.z.lazy(()=>h.z.union([u.jsonPrimitiveSchema,Gr,qr,h.z.instanceof(Z)])),Pt=i=>H.isObject(i)&&!H.isArray(i)&&!u.isReadonlyArray(i)&&!E(i),St=i=>H.isArray(i)||u.isReadonlyArray(i),Xr=i=>St(i)||Pt(i)||E(i)||u.isJsonPrimitive(i);class m{static deserialize(e){return m.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(Pt(e)){const t=new d,r={};return Object.entries(e).forEach(([s,n])=>{switch(s){case le:if(n==null)t.setName(void 0);else{if(typeof n!="string")throw new Error(`The ${le} field must be a string.`);t.setName(n)}break;case ae:if(n==null)t.setDescription(void 0);else{if(typeof n!="string")throw new Error(`The ${ae} field must be a string.`);t.setDescription(n)}break;case K:t.setType(m.handleNode(n));break;case be:t.setItemType(m.handleNode(n));break;case Pe:t.setKeyType(m.handleNode(n));break;case Se:t.setValueType(m.handleNode(n));break;case J:t.setValue(m.handleValue(n));break;case V:if(typeof n!="string")throw new Error(`The ${V} field must be a string.`);t.setBlueId(n);break;case W:t.setItems(m.handleArray(n));break;case Le:t.setBlue(m.handleNode(n));break;default:r[s]=m.handleNode(n);break}}),Object.keys(r).length>0&&t.setProperties(r),t}else{if(St(e))return new d().setItems(m.handleArray(e));{const t=e;return new d().setValue(m.handleValue(t)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||E(e))if(Q(e)||Number.isSafeInteger(e)){const t=new O(e.toString()),r=Number.MIN_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER;return t.lt(r)?new O(r.toString()):t.gt(s)?new O(s.toString()):t}else{const t=parseFloat(e.toString());return new D(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(H.isObject(e)&&!Array.isArray(e))return[m.handleNode(e)];if(Array.isArray(e))return e.map(m.handleNode);throw new Error("Expected an array node")}}}function Qr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var nt,_t;function es(){return _t||(_t=1,nt=function i(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?i(e.toJSON()):Array.isArray(e)?`[${e.reduce((s,n,o)=>`${s}${o===0?"":","}${i(n===void 0||typeof n=="symbol"?null:n)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,s)=>{if(e[s]===void 0||typeof e[s]=="symbol")return r;const n=r.length===0?"":",";return`${r}${n}${i(s)}:${i(e[s])}`},"")}}`}),nt}var ts=es();const rs=Qr(ts);class ke{static canonicalize(e){return rs(e)}}const ot=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class wt{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new wt),this.instance}initBrowserCrypto(){return ot?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return ot&&!!it.default&&typeof it.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return ot?it.default:null}}class Xt{cryptoEnv=wt.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return Oe.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return Oe.default.encode(r)}canonicalizeInput(e){const t=ke.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(jr.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 s=new TextEncoder().encode(e),n=await t.subtle.digest("SHA-256",s);return new Uint8Array(n)}}const w={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 P{static isEmptyNode(e){return this.hasFieldsAndMayHaveFields(e)}static hasBlueIdOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([w.BLUE_ID]))}static hasItemsOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([w.ITEMS]))}static isValidValueNode(e){const t=e.getValue(),r=e.getProperties(),s=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(s)}static textNode(e){return new d().setType(new d().setBlueId(te)).setValue(e)}static integerNode(e){const t=e instanceof O?e:new O(e.toString());return new d().setType(new d().setBlueId(se)).setValue(t)}static doubleNode(e){const t=e instanceof D?e:new D(e.toString());return new d().setType(new d().setBlueId(re)).setValue(t)}static booleanNode(e){return new d().setType(new d().setBlueId(ie)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const s of Object.values(w)){const n=u.isNonNullable(this.getFieldValue(e,s));if(t.has(s)){if(!n)return!1}else if(!r.has(s)){if(n)return!1}}return!0}static getFieldValue(e,t){switch(t){case w.NAME:return e.getName();case w.TYPE:return e.getType();case w.VALUE:return e.getValue();case w.DESCRIPTION:return e.getDescription();case w.PROPERTIES:return e.getProperties();case w.BLUE:return e.getBlue();case w.ITEMS:return e.getItems();case w.KEY_TYPE:return e.getKeyType();case w.VALUE_TYPE:return e.getValueType();case w.ITEM_TYPE:return e.getItemType();case w.BLUE_ID:return e.getBlueId();default:throw new Error(`Unknown field: ${t}`)}}}const ge="$previous",ue="$pos",dt="$empty";class v{static getMergePolicy(e,t){const r=this.getMergePolicyValue(e);return r!==void 0?r:(t===void 0?void 0:this.getMergePolicyValue(t))??"positional"}static getMergePolicyValue(e){const t=e.getProperties()?.[B.OBJECT_MERGE_POLICY]?.getValue();if(t==="append-only"||t==="positional")return t}static hasListControlItems(e){return e?.some(t=>this.hasPreviousProperty(t)||this.hasPositionProperty(t))??!1}static hasAnyListControl(e){const t=e.getItems();return this.hasListControlItems(t)||t?.some(r=>this.hasAnyListControl(r))?!0:Object.values(e.getProperties()??{}).some(r=>this.hasAnyListControl(r))||this.hasAnyListControlChild(e.getType())||this.hasAnyListControlChild(e.getItemType())||this.hasAnyListControlChild(e.getKeyType())||this.hasAnyListControlChild(e.getValueType())||this.hasAnyListControlChild(e.getBlue())}static hasPositionControl(e){const t=e.getItems();return t?.some(r=>this.hasPositionProperty(r))||t?.some(r=>this.hasPositionControl(r))?!0:Object.values(e.getProperties()??{}).some(r=>this.hasPositionControl(r))||this.hasPositionControlChild(e.getType())||this.hasPositionControlChild(e.getItemType())||this.hasPositionControlChild(e.getKeyType())||this.hasPositionControlChild(e.getValueType())||this.hasPositionControlChild(e.getBlue())}static hasPreviousProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},ge)}static hasPositionProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},ue)}static hasEmptyProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},dt)}static isEmptyItem(e){const t=e.getProperties(),r=t?.[dt];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&P.hasFieldsAndMayHaveFields(e,new Set([w.PROPERTIES]))&&P.hasFieldsAndMayHaveFields(r,new Set([w.VALUE]),new Set([w.TYPE]))&&r.getValue()===!0}static isPreviousItem(e){const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&P.hasFieldsAndMayHaveFields(e,new Set([w.PROPERTIES]))&&P.hasBlueIdOnly(t[ge])}static getPreviousBlueId(e){if(this.isPreviousItem(e))return e.getProperties()?.[ge]?.getBlueId()}static createPreviousItem(e){return new d().setProperties({[ge]:new d().setBlueId(e)})}static readPosition(e){const t=e.getProperties()?.[ue];if(t===void 0)return;if(!P.hasFieldsAndMayHaveFields(t,new Set([w.VALUE]),new Set([w.TYPE])))throw new Error("$pos must be a non-negative integer value.");const r=t.getValue(),s=r instanceof O?r.toNumber():typeof r=="number"?r:void 0;if(s===void 0||!Number.isInteger(s)||s<0)throw new Error("$pos must be a non-negative integer value.");return s}static createPositionedItem(e,t){const r=t.clone();return r.addProperty(ue,new d().setValue(e)),r}static withoutPosition(e){const t=e.clone(),r=t.getProperties();return r!==void 0&&(delete r[ue],Object.keys(r).length===0&&t.setProperties(void 0)),t}static hasPayloadAfterRemovingPosition(e){return!P.isEmptyNode(this.withoutPosition(e))}static isReplacementPayload(e){return u.isNonNullable(e.getValue())||u.isNonNullable(e.getItems())||u.isNonNullable(e.getBlueId())}static hasAnyListControlChild(e){return e!==void 0&&this.hasAnyListControl(e)}static hasPositionControlChild(e){return e!==void 0&&this.hasPositionControl(e)}}const ss=new Set([le,ae,J]),is={$list:"empty"},ns="$listCons",os="prev",ls="elem";class as{constructor(e){this.hashProvider=e}calculate(e){const t=this.clean(this.toHashValue(e));if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.calculateInternal(t,!1)}calculateSync(e){const t=this.clean(this.toHashValue(e));if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.calculateInternal(t,!0)}calculateInternal(e,t){return this.isScalar(e)?this.applyHash(this.toJsonScalar(e),t):Array.isArray(e)?this.calculateList(e,t):this.isPureReference(e)?e[V]:this.isScalarWrapper(e)?this.calculateInternal(e[J],t):this.isBasicTypedScalarWrapper(e)?this.calculateInternal(e[J],t):this.isListWrapper(e)?this.calculateInternal(e[W],t):this.isBasicTypedListWrapper(e)?this.calculateInternal(e[W],t):this.calculateMap(e,t)}calculateMap(e,t){const s=Object.entries(e).sort(([o],[l])=>o.localeCompare(l)).map(([o,l])=>{if(ss.has(o))return t?[o,l]:Promise.resolve([o,l]);const a=this.calculateInternal(l,t);return t?[o,{[V]:a}]:Promise.resolve(a).then(c=>[o,{[V]:c}])}),n=o=>{const l={};for(const[a,c]of o)l[a]=c;return this.applyHash(l,t)};return t?n(s):Promise.all(s).then(n)}calculateList(e,t){let r=0,s;const n=e[0];if(n!==void 0&&this.hasPreviousControlKey(n)){const o=this.getPreviousControlBlueId(n);if(o===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");s=t?o:Promise.resolve(o),r=1}else s=this.applyHash(is,t);for(let o=r;o<e.length;o++){const l=e[o];if(this.hasPreviousControlKey(l))throw new Error("$previous list control is allowed only first.");if(this.hasPositionControlKey(l))throw new Error("$pos list controls must be consumed before raw BlueId hashing.");const a=s,c=this.calculateInternal(l,t);t?s=this.applyHash(this.createListFoldInput(a,c),!0):s=Promise.all([a,c]).then(([p,f])=>this.applyHash(this.createListFoldInput(p,f),!1))}return s}createListFoldInput(e,t){return{[ns]:{[os]:{[V]:e},[ls]:{[V]:t}}}}getPreviousControlBlueId(e){if(typeof e!="object"||e===null||Array.isArray(e)||E(e))return;const t=Object.entries(e);if(t.length!==1||t[0][0]!==ge)return;const r=t[0][1];if(!(typeof r!="object"||r===null||Array.isArray(r)||E(r)||!this.isPureReference(r)))return r[V]}hasPreviousControlKey(e){return this.hasControlKey(e,ge)}hasPositionControlKey(e){return this.hasControlKey(e,ue)}hasControlKey(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!E(e)&&Object.prototype.hasOwnProperty.call(e,t)}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}toHashValue(e){return e instanceof d?this.nodeToHashValue(e):Array.isArray(e)?e.map(t=>this.toHashValue(t)).filter(t=>t!==void 0):this.jsonToHashValue(e)}nodeToHashValue(e){const t={};this.setIfPresent(t,le,e.getName()),this.setIfPresent(t,ae,e.getDescription()),this.setIfPresent(t,K,e.getType()),this.setIfPresent(t,be,e.getItemType()),this.setIfPresent(t,Pe,e.getKeyType()),this.setIfPresent(t,Se,e.getValueType());const r=e.getValue();r!==void 0&&(t[J]=this.scalarToHashValue(r));const s=e.getItems();s!==void 0&&(t[W]=s.map(o=>this.nodeToHashValue(o))),this.setIfPresent(t,V,e.getReferenceBlueId()),this.setIfPresent(t,Le,e.getBlue());const n=e.getProperties();if(n!==void 0)for(const[o,l]of Object.entries(n))t[o]=this.nodeToHashValue(l);return t}jsonToHashValue(e){if(e!=null){if(this.isScalar(e)||E(e))return this.scalarToHashValue(e);if(Array.isArray(e))return e.map(t=>this.jsonToHashValue(t)).filter(t=>t!==void 0);if(typeof e=="object"){const t={};for(const[r,s]of Object.entries(e))t[r]=this.jsonToHashValue(s);return t}return e}}setIfPresent(e,t,r){r!==void 0&&(e[t]=r instanceof d?this.nodeToHashValue(r):r)}clean(e){if(e==null)return;if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.clean(r)).filter(r=>r!==void 0);const t={};for(const[r,s]of Object.entries(e)){const n=this.clean(s);n!==void 0&&(t[r]=n)}return Object.keys(t).length===0?void 0:t}isPureReference(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===V&&typeof t[0]?.[1]=="string"}isScalarWrapper(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===J}isBasicTypedScalarWrapper(e){return this.hasOnlyKeys(e,[K,J])&&this.isBasicScalarTypeReference(e[K])}isListWrapper(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===W&&Array.isArray(t[0]?.[1])}isBasicTypedListWrapper(e){return this.hasOnlyKeys(e,[K,W])&&this.isTypeReference(e[K],qe)&&Array.isArray(e[W])}hasOnlyKeys(e,t){return Object.keys(e).length===t.length&&t.every(s=>Object.prototype.hasOwnProperty.call(e,s))}isBasicScalarTypeReference(e){return this.isTypeReference(e,te)||this.isTypeReference(e,se)||this.isTypeReference(e,re)||this.isTypeReference(e,ie)}isTypeReference(e,t){return typeof e!="object"||e===null||Array.isArray(e)||E(e)?!1:this.isPureReference(e)&&e[V]===t}isScalar(e){return u.isJsonPrimitive(e)&&e!==null||E(e)}scalarToHashValue(e){if(e instanceof O||Q(e)){const t=new Z(Number.MIN_SAFE_INTEGER.toString()),r=new Z(Number.MAX_SAFE_INTEGER.toString());return e.lt(t)||e.gt(r)?e.toString():e.toNumber()}return e instanceof D||E(e)?e.toNumber():e}toJsonScalar(e){return E(e)?this.scalarToHashValue(e):e}}class A{static INSTANCE=new A(new Xt);hasher;constructor(e){this.hasher=new as(e)}static calculateBlueId(e){return A.INSTANCE.calculate(e)}static calculateBlueIdSync(e){return A.INSTANCE.calculateSync(e)}calculate(e){return this.hasher.calculate(e)}calculateSync(e){return this.hasher.calculateSync(e)}}class z{constructor(e={emitListControls:!0}){this.options=e}reverse(e){const t=new d;return this.reverseNode(t,e,void 0,!0),t}static calculateHashMinimalBlueId(e){return A.calculateBlueIdSync(this.toHashMinimalNode(e))}static calculateHashMinimalListBlueId(e){return A.calculateBlueIdSync(e.map(t=>this.toHashMinimalNode(t)))}static toHashMinimalNode(e){return new z({emitListControls:!1}).reverse(e)}reverseNode(e,t,r,s){const n=this.getEffectiveFromType(r,t);!s&&this.isIdenticalToType(t,n)||(this.reverseBasicProperties(e,t,n,s),this.reverseTypeReferences(e,t,r,n),this.reverseItems(e,t,n),this.reverseProperties(e,t,n))}isIdenticalToType(e,t){return u.isNonNullable(e.getBlueId())&&u.isNonNullable(t?.getBlueId())&&e.getBlueId()===t.getBlueId()}reverseBasicProperties(e,t,r,s){const n=t.getValue();u.isNonNullable(n)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(n),u.isNonNullable(t.getName())&&(s||u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(s||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,s){const n=(o,l,a)=>{const c=o(t),p=a?o(a):void 0;u.isNonNullable(c)&&!this.areTypeReferencesEquivalent(c,p)&&l(e,this.toMinimalTypeReference(c))};n(o=>o.getType(),(o,l)=>o.setType(l),r),n(o=>o.getItemType(),(o,l)=>o.setItemType(l),s),n(o=>o.getKeyType(),(o,l)=>o.setKeyType(l),s),n(o=>o.getValueType(),(o,l)=>o.setValueType(l),s)}areTypeReferencesEquivalent(e,t){if(u.isNullable(t))return!1;const r=e.getBlueId(),s=t.getBlueId();return u.isNonNullable(r)||u.isNonNullable(s)?u.isNonNullable(r)&&u.isNonNullable(s)&&r===s:z.calculateHashMinimalBlueId(e)===z.calculateHashMinimalBlueId(t)}toMinimalTypeReference(e){const t=e.getBlueId();if(u.isNonNullable(t))return new d().setBlueId(t);const r=new d;return this.reverseNode(r,e,void 0,!0),P.isEmptyNode(r)?e.clone():r}reverseItems(e,t,r){const s=t.getItems();if(u.isNullable(s))return;const n=r?.getItems();if(s.length===0){(u.isNullable(n)||n.length>0)&&e.setItems([]);return}if(u.isNonNullable(n)&&s.length===n.length&&s.every((l,a)=>z.calculateHashMinimalBlueId(l)===z.calculateHashMinimalBlueId(n[a])))return;const o=this.options.emitListControls!==!1&&u.isNonNullable(n)&&n.length>0?this.reverseInheritedItems(t,r):this.reverseFullItems(s);o.length>0&&e.setItems(o)}reverseInheritedItems(e,t){const r=e.getItems()??[],s=t.getItems()??[];if(r.length<s.length)throw new Error(`Resolved list has fewer items (${r.length}) than inherited list (${s.length}).`);const n=v.getMergePolicy(e,t),o=[];for(let c=0;c<s.length;c++)z.calculateHashMinimalBlueId(r[c])!==z.calculateHashMinimalBlueId(s[c])&&o.push(c);if(o.length>0&&n==="append-only")throw new Error("append-only list cannot be minimized as a non-prefix mutation.");const l=z.calculateHashMinimalListBlueId(s),a=[v.createPreviousItem(l)];for(const c of o){const p=new d;this.reverseNode(p,r[c],s[c],!1);const f=P.isEmptyNode(p)?r[c].clone():p;a.push(v.createPositionedItem(c,f))}for(let c=s.length;c<r.length;c++){const p=new d;this.reverseNode(p,r[c],void 0,!1),a.push(p)}return a.length===1?[]:a}reverseFullItems(e){const t=[];for(let r=0;r<e.length;r++){const s=new d;this.reverseNode(s,e[r],void 0,!1),t.push(s)}return t}reverseProperties(e,t,r){const s=t.getProperties();if(u.isNullable(s))return;const n={};for(const[o,l]of Object.entries(s)){const a=this.getInheritedProperty(o,r),c=new d;this.reverseNode(c,l,a,!1),P.isEmptyNode(c)||(n[o]=c)}Object.keys(n).length>0&&e.setProperties(n)}getInheritedProperty(e,t){return t?.getProperties()?.[e]}getEffectiveFromType(e,t){const r=this.createOwnTypeOverlay(t.getType());return u.isNullable(e)?r:u.isNullable(r)?e:this.mergeNodes(e,r)}createOwnTypeOverlay(e){if(u.isNullable(e))return;const t=e.cloneShallow().setName(void 0).setDescription(void 0).setType(void 0).setBlueId(void 0);if(!P.isEmptyNode(t))return t}mergeNodes(e,t){const r=e.clone(),s=t.getValue();u.isNonNullable(s)&&r.setValue(s);const n=t.getType();u.isNonNullable(n)&&r.setType(n.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 c=t.getProperties();if(u.isNonNullable(c)){const f=r.getProperties()||{};for(const[y,g]of Object.entries(c)){const I=f[y];f[y]=I===void 0?g.clone():this.mergeNodes(I,g)}r.setProperties(f)}const p=t.getItems();return u.isNonNullable(p)&&r.setItems(p.map(f=>f.clone())),r}}class ht{mergeReverser=new z;hashMergeReverser=new z({emitListControls:!1});minimize(e){return this.minimizeResolved(e)}minimizeResolved(e){return this.mergeReverser.reverse(e)}minimizeResolvedForHash(e){return this.hashMergeReverser.reverse(e)}}class he extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r&&r.length>0?r:[],this.name="BlueError"}}const x={AMBIGUOUS_BLUE_ID_PAYLOAD:"AMBIGUOUS_BLUE_ID_PAYLOAD",BLUE_ID_MISMATCH:"BLUE_ID_MISMATCH",INVALID_STORAGE_SHAPE:"INVALID_STORAGE_SHAPE",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"};class q{static RESERVED_PROPERTY_KEYS=new Set([B.OBJECT_SCHEMA,B.OBJECT_MERGE_POLICY,B.OBJECT_CONTRACTS]);static INTERNAL_PROPERTIES_KEY="properties";static validateStorageShape(e){this.validateNode(e,[],{insideItems:!1})}static validateStorageListShape(e){e.forEach((t,r)=>{this.validateNode(t,[String(r)],{insideItems:!0,itemIndex:r})})}static validateListControlShape(e){e.forEach((t,r)=>{this.validateListControlNode(t,[String(r)],r)})}static validateListControlNode(e,t,r){r!==void 0&&this.validateListControlItem(e,t,r),this.validateListControlChild(e.getType(),[...t,"type"]),this.validateListControlChild(e.getItemType(),[...t,"itemType"]),this.validateListControlChild(e.getKeyType(),[...t,"keyType"]),this.validateListControlChild(e.getValueType(),[...t,"valueType"]),this.validateListControlChild(e.getBlue(),[...t,"blue"]),e.getItems()?.forEach((n,o)=>{this.validateListControlNode(n,[...t,"items",String(o)],o)});const s=e.getProperties();if(s!==void 0)for(const[n,o]of Object.entries(s))this.validateListControlNode(o,[...t,n])}static validateNode(e,t,r){r.insideItems&&this.validateListControlItem(e,t,r.itemIndex??0);const s=e.getReferenceBlueId();if(s!==void 0&&!P.hasBlueIdOnly(e))if(r.insideItems&&v.hasPositionProperty(e)&&P.hasBlueIdOnly(v.withoutPosition(e)))v.readPosition(e);else{const f=this.toPointer(t);throw new he(x.AMBIGUOUS_BLUE_ID_PAYLOAD,`Ambiguous blueId plus payload at ${f}. Use exact { blueId } for references or remove blueId from payload content.`,[{code:x.AMBIGUOUS_BLUE_ID_PAYLOAD,message:"A storage or authoring node cannot combine blueId with payload.",locationPath:t,context:{blueId:s}}])}const n=this.getChildProperties(e,t,r),o=e.getValue()!==void 0,l=e.getItems()!==void 0,a=Object.keys(n).length>0;o&&l&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value and items payloads."),o&&a&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value payload with object child fields."),l&&a&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine items payload with object child fields."),this.validateChild(e.getType(),[...t,"type"]),this.validateChild(e.getItemType(),[...t,"itemType"]),this.validateChild(e.getKeyType(),[...t,"keyType"]),this.validateChild(e.getValueType(),[...t,"valueType"]),this.validateChild(e.getBlue(),[...t,"blue"]),e.getItems()?.forEach((p,f)=>{this.validateNode(p,[...t,"items",String(f)],{insideItems:!0,itemIndex:f})});const c=e.getProperties();if(c!==void 0)for(const[p,f]of Object.entries(c))this.validateNode(f,[...t,p],{insideItems:!1})}static validateListControlItem(e,t,r){if(v.hasEmptyProperty(e)&&(v.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $previous."),v.hasPositionProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $pos."),v.isEmptyItem(e)||this.throwInvalidStorageShape(t,"$empty list content must be exactly { $empty: true }.")),v.hasPreviousProperty(e)&&(r!==0&&this.throwInvalidStorageShape(t,"$previous list control is allowed only as the first item."),v.isPreviousItem(e)||this.throwInvalidStorageShape(t,"$previous list control must be exactly { $previous: { blueId: <id> } }.")),v.hasPositionProperty(e)){v.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$pos cannot be combined with $previous.");try{v.readPosition(e)}catch(s){this.throwInvalidStorageShape([...t,ue],s instanceof Error?s.message:"$pos must be a non-negative integer value.")}v.hasPayloadAfterRemovingPosition(e)||this.throwInvalidStorageShape(t,"$pos list control must include an item payload.")}}static validateChild(e,t){e!==void 0&&this.validateNode(e,t,{insideItems:!1})}static validateListControlChild(e,t){e!==void 0&&this.validateListControlNode(e,t)}static getChildProperties(e,t,r){const s=e.getProperties()??{};return Object.prototype.hasOwnProperty.call(s,this.INTERNAL_PROPERTIES_KEY)&&this.throwInvalidStorageShape([...t,this.INTERNAL_PROPERTIES_KEY],"The document-level properties key is not part of the Blue language."),Object.fromEntries(Object.entries(s).filter(([n])=>!this.RESERVED_PROPERTY_KEYS.has(n)&&!(r.insideItems&&(n===ue||n===dt))))}static throwInvalidStorageShape(e,t){const r=this.toPointer(e);throw new he(x.INVALID_STORAGE_SHAPE,`${t} at ${r}`,[{code:x.INVALID_STORAGE_SHAPE,message:t,locationPath:e}])}static toPointer(e){return e.length===0?"/":`/${e.map(t=>t.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}`}}class cs{static convert(e){const t=Oe.default.decode(e),r=new Uint8Array(2+t.length);r[0]=18,r[1]=32,r.set(t,2);const s=new Uint8Array(2+r.length);return s[0]=1,s[1]=85,s.set(r,2),"b"+new $r.Encoder({type:"rfc4648",lc:!0}).write(s).finalize().replace(/=/g,"")}}class T{static get(e,t="official"){const{strategy:r}=this.normalizeOptions(t),s=e.getValue(),n=this.handleValue(s);if(n!==void 0&&r==="simple")return n;const o=e.getItems()?.map(F=>T.get(F,r));if(o!==void 0&&r==="simple")return o;const l=e.getName(),a=e.getDescription();if(r==="original"&&l===void 0&&a===void 0){if(n!==void 0)return n;if(o!==void 0)return o}const c={};l!==void 0&&(c[le]=l),a!==void 0&&(c[ae]=a);const p=e.getType();if(r==="official"&&s!==void 0&&p===void 0){const F=this.inferTypeBlueId(s);F!==null&&(c[K]={[V]:F})}else p!==void 0&&(c[K]=T.get(p,r));const f=e.getItemType();f!==void 0&&(c[be]=T.get(f,r));const y=e.getKeyType();y!==void 0&&(c[Pe]=T.get(y,r));const g=e.getValueType();g!==void 0&&(c[Se]=T.get(g,r)),n!==void 0&&(c[J]=n),o!==void 0&&(c[W]=o);const I=e.getBlueId();I!==void 0&&(c[V]=I);const L=e.getBlue();L!==void 0&&(c[Le]=L);const b=e.getProperties();return b!==void 0&&Object.entries(b).forEach(([F,N])=>{c[F]=T.get(N,r)}),c}static handleValue(e){if(E(e)){if(Q(e)){const t=new Z(Number.MIN_SAFE_INTEGER.toString()),r=new Z(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"?te:E(e)?Q(e)?se:re:typeof e=="boolean"?ie:null}static normalizeOptions(e){return typeof e=="string"?{strategy:e}:{strategy:e.strategy??"official"}}}class _{static transform(e,t){const r=t(e.clone()),s=r.getType();s!==void 0&&r.setType(_.transform(s,t));const n=r.getItemType();n!==void 0&&r.setItemType(_.transform(n,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(_.transform(o,t));const l=r.getValueType();l!==void 0&&r.setValueType(_.transform(l,t));const a=r.getItems();if(a!==void 0){const p=a.map(f=>_.transform(f,t));r.setItems(p)}const c=r.getProperties();if(c!==void 0){const p=Object.keys(c).reduce((f,y)=>(f[y]=_.transform(c[y],t),f),{});r.setProperties(p)}return r}}const ce=i=>!!i&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof d),X=i=>i instanceof O||i instanceof D,us=i=>i.replace(/~1/g,"/").replace(/~0/g,"~");function we(i){if(i==="/")return[];if(!i.startsWith("/"))throw new Error(`Path must start with '/': ${i}`);return i.split("/").slice(1).map(us)}function Be(i){if(i==="-")return-1;const e=typeof i=="number"?i:parseInt(i,10);if(isNaN(e))throw new Error(`Invalid array index (NaN) from '${i}'`);if(!Number.isFinite(e))throw new Error(`Invalid array index '${i}' results in non-finite number ${e}`);return e}function Qt(i,e,t,r=!0){switch(e){case"name":return t?r?i.getName()??null:i:i.getName();case"description":return t?r?i.getDescription():i:i.getDescription();case"type":return i.getType();case"itemType":return i.getItemType();case"keyType":return i.getKeyType();case"valueType":return i.getValueType();case"value":return t?r?i.getValue()??null:i:i.getValue();case"blueId":return t?r?i.getBlueId()??null:i:i.getBlueId();case"blue":return i.getBlue();case"items":return i.getItems();case"properties":return i.getProperties();case B.OBJECT_CONTRACTS:return i.getContracts();default:return}}function Dt(i,e,t=!0){if(i instanceof d){const r=Qt(i,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 n=i.getItems(),o=parseInt(e,10);return n&&o>=0&&o<n.length?n[o]:void 0}const s=i.getProperties();return s&&e in s?s[e]:void 0}if(Array.isArray(i)){if(e==="-")return;const r=Be(e);return r>=0&&r<i.length?i[r]:void 0}if(ce(i))return i[e]}function Ee(i,e){if(e.length===0)return{parent:i,key:"value",actualTarget:i.getValue()??i};let t=i;for(let s=0;s<e.length-1;++s){const n=e[s],o=Dt(t,n);if(o===void 0)throw new Error(`Cannot resolve '/${e.slice(0,s+1).join("/")}'`);t=o}const r=e[e.length-1];if(t instanceof d){const s=Dt(t,r,!1);if((typeof s!="object"||s===null||X(s))&&!(s instanceof d)&&!Array.isArray(s)&&["name","description","value","blueId"].includes(r))return{parent:t,key:r,actualTarget:s}}return Array.isArray(t)&&r==="-"?{parent:t,key:"-"}:t instanceof d&&t.getItems()&&r==="-"?{parent:t,key:"-"}:{parent:t,key:Array.isArray(t)?Be(r):r}}function Et(i,e){if(i instanceof d){const t=e,r=Qt(i,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 s=i.getItems(),n=typeof e=="number"?e:parseInt(e,10);if(s&&n>=0&&n<s.length)return s[n]}return i.getProperties()?.[t]}return Array.isArray(i)||ce(i)?i[e]:i}function j(i){if(i instanceof d)return i;if(i===null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"||X(i))return m.deserialize(i);const e=pt(i);return m.deserialize(e)}function pt(i){if(i===void 0)return null;if(i===null||typeof i!="object")return i;if(Array.isArray(i))return i.map(pt);const e={};for(const[t,r]of Object.entries(i))e[t]=pt(r);return e}function Ct(i,e,t){if(i instanceof d){const r=e;switch(r){case"name":i.setName(t);return;case"description":i.setDescription(t);return;case"type":i.setType(t instanceof d||typeof t=="string"||t===void 0?t:j(t));return;case"itemType":i.setItemType(t instanceof d||typeof t=="string"||t===void 0?t:j(t));return;case"keyType":i.setKeyType(t instanceof d||typeof t=="string"||t===void 0?t:j(t));return;case"valueType":i.setValueType(t instanceof d||typeof t=="string"||t===void 0?t:j(t));return;case"value":{const s=t;i.setValue(s===void 0?null:s);return}case"blueId":i.setBlueId(t);return;case"blue":i.setBlue(t instanceof d||t===void 0?t:j(t));return;case"items":i.setItems(t);return;case"properties":i.setProperties(t);return;case B.OBJECT_CONTRACTS:i.setContracts(t);return;default:{if(t===void 0){const s=i.getProperties();s&&r in s&&delete s[r]}else i.getProperties()||i.setProperties({}),i.addProperty(r,t instanceof d?t:j(t));return}}}Array.isArray(i)?i.splice(Be(e),1):ce(i)&&(t===void 0?delete i[e]:i[e]=t)}function ds(i,e,t,r){let s=-1;if(e!=="-"&&(s=typeof e=="number"?e:parseInt(e,10),isNaN(s)))throw new Error(`Invalid numeric key for BlueNode item operation: ${e}`);if(s<-1)throw new Error(`Invalid array index for BlueNode items: ${s}`);let n=i.getItems();if(n||(n=[],i.setItems(n)),!r&&s!==-1&&s>n.length)throw new Error(`ADD operation failed: Target array index '${s}' is greater than array length ${n.length}.`);if(e==="-")n.push(t);else if(r){if(s>=0)if(s<n.length)n[s]=t;else{for(let o=n.length;o<s;o++)n.push(m.deserialize(null));n.push(t)}}else n.splice(s,0,t)}function Ye(i,e,t,r){if(Array.isArray(i)){const s=e==="-"?i.length:Be(e);if(!r&&s>i.length)throw new Error(`ADD operation failed: Target array index '${s}' is greater than array length ${i.length}. Path involving key '${e}'.`);if(s<0&&e!=="-")throw new Error(`Invalid negative array index: ${e}`);const n=j(t);if(r){if(s>=0&&s<i.length)i[s]=n;else if(s>=i.length){for(let o=i.length;o<s;o++)i.push(m.deserialize(null));i.push(n)}}else i.splice(s,0,n);return}if(i instanceof d){e==="-"||typeof e=="number"&&!isNaN(e)||typeof e=="string"&&/^\d+$/.test(e)?ds(i,e,j(t),r):Ct(i,e,t);return}if(ce(i)){i[e]=j(t);return}throw new Error(`Cannot insert into parent of type ${typeof i}`)}function hs(i,e){if(Array.isArray(i)){const t=Be(e);t===-1&&e==="-"?i.length>0&&i.pop():t>=0&&t<i.length&&i.splice(t,1);return}if(i instanceof d){if(typeof e=="number"||typeof e=="string"&&/^-?\d+$/.test(e)){const t=i.getItems();if(t){const r=Be(e);r===-1&&e==="-"?t.length>0&&t.pop():r>=0&&r<t.length&&t.splice(r,1),t.length===0&&i.setItems(void 0);return}}Ct(i,e,void 0)}else ce(i)&&delete i[e]}function ft(i){if(i instanceof d)return i.clone();if(Array.isArray(i))return i.map(t=>ft(t));if(ce(i)){const e={};return Object.keys(i).forEach(t=>{e[t]=ft(i[t])}),e}return i}function de(i,e){if(i===e||i instanceof d&&(i.isInlineValue()||i.getValue()!==void 0)&&de(i.getValue()??null,e)||e instanceof d&&(e.isInlineValue()||e.getValue()!==void 0)&&de(i,e.getValue()??null))return!0;if(i instanceof d&&e instanceof d||X(i)&&X(e)||X(i)&&typeof e=="number"||typeof i=="number"&&X(e))return i.toString()===e.toString();if(Array.isArray(i)&&Array.isArray(e))return i.length===e.length&&i.every((t,r)=>de(t,e[r]));if(ce(i)&&ce(e)){const t=Object.keys(i),r=Object.keys(e);return t.length===r.length&&t.every(s=>de(i[s],e[s]))}return!1}function er(i,e){const{parent:t,key:r}=Ee(i,we(e));return Et(t,r)}function tr(i,e,t){const r=we(e);if(r.length===0&&e==="/"){const o=j(t);i.setValue(o.getValue()??null),o.getItems()?i.setItems(o.getItems()):i.setItems(void 0);return}const{parent:s,key:n}=Ee(i,r);Ye(s,n,t,!0)}function ps(i,e,t){const r=we(e);if(r.length===0&&e==="/"){if(i.getItems()&&Array.isArray(t)){const o=j(t);o.getItems()?(i.setItems(o.getItems()),i.setValue(null)):(i.setValue(o.getValue()??null),i.setItems(void 0))}else{const o=j(t);i.setValue(o.getValue()??null),o.getItems()&&i.setItems(o.getItems())}return!0}const{parent:s,key:n}=Ee(i,r);return Ye(s,n,t,!1),!0}function fs(i,e,t){const r=we(e);if(r.length===0&&e==="/"){const l=j(t);return i.setValue(l.getValue()??null),l.getItems()?i.setItems(l.getItems()):i.setItems(void 0),!0}const{parent:s,key:n,actualTarget:o}=Ee(i,r);if(o!==void 0&&s instanceof d)Ct(s,n,t);else{const l=Et(s,n),a=Array.isArray(s)||s instanceof d&&s.getItems()&&(typeof n=="number"||typeof n=="string"&&/^\d+$/.test(n));if(l===void 0){if(a)throw new Error(`REPLACE failed: Target array index '${n.toString()}' is out of bounds or does not exist at path '${e}'.`);Ye(s,n,t,!0)}else Ye(s,n,t,!0)}return!0}function rr(i,e){const t=we(e);if(t.length===0&&e==="/")return i.setValue(null),i.setItems(void 0),i.setProperties(void 0),!0;const{parent:r,key:s}=Ee(i,t);return hs(r,s),!0}function ys(i,e,t){const r=ft(er(i,e));return tr(i,t,r),!0}function gs(i,e,t){const r=we(e),{parent:s,key:n}=Ee(i,r),o=Et(s,n);if(o===void 0)throw new Error(`MOVE failed: 'from' location '${e}' does not exist.`);return rr(i,e)?(tr(i,t,o),!0):!1}function ms(i,e,t){const r=er(i,e);let s=t;if(r instanceof d)if((t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||X(t))&&(r.isInlineValue()||r.getValue()!==void 0)){if(!de(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)&&(s=j(t));else if(X(r)&&typeof t=="number")r instanceof O?s=new O(t.toString()):r instanceof D&&(s=new D(t.toString()));else if((r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&X(t)){const n=t;!de(r,n.toString())&&(typeof r=="number"&&parseFloat(n.toString()))}if(!de(r,s)){const n=r instanceof d?r.toString():JSON.stringify(r),o=s instanceof d?s.toString():JSON.stringify(s);throw new Error(`TEST failed at '${e}': Expected ${o}, got ${n}`)}return!0}function Is(i,e){switch(e.op){case"add":return ps(i,e.path,e.val);case"replace":return fs(i,e.path,e.val);case"remove":return rr(i,e.path);case"copy":return ys(i,e.from,e.path);case"move":return gs(i,e.from,e.path);case"test":return ms(i,e.path,e.val)}}function Ts(i,e,t=!1){const r=t?i:i.clone();return Is(r,e),r}const lt=Symbol.for("zod-schema-annotations");function vs(){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 sr(){const i=vs();return lt in i||(i[lt]=new WeakMap),i[lt]}function xe(i,e){const t=sr(),r=t.get(i)||{};return t.set(i,{...r,...e}),i}const G=i=>sr().get(i),ir=i=>e=>{const t=G(e);return xe(e,{...t,blueDescription:i})},nr=i=>{const e=G(i);return u.isNonNullable(e)&&H.isString(e.blueDescription)?e.blueDescription:null},Bs=i=>ir(i)(h.z.string().optional()),Ns=h.z.union([h.z.string(),h.z.boolean()]),or=i=>e=>{const t=G(e);return xe(e,{...t,blueId:i})},lr=i=>{const e=G(i),t=Ns.safeParse(e?.blueId);return t.success?t.data:null},bs=i=>or(i??!0)(h.z.string()),ar=i=>e=>{const t=G(e);return xe(e,{...t,blueName:i})},cr=i=>{const e=G(i);return u.isNonNullable(e)&&H.isString(e.blueName)?e.blueName:null},Ps=i=>{const e=h.z.string().optional();return ar(i)(e)},ur=()=>i=>{const e=G(i);return xe(i,{...e,blueNode:!0})},dr=i=>{const e=G(i);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},Rt=i=>!!dr(i),Ss=()=>{const i=h.z.instanceof(d);return ur()(i)},ws=h.z.object({value:h.z.array(h.z.string()).optional(),defaultValue:h.z.string().optional()}),hr=i=>{const e=G(i),t=ws.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},pr=i=>e=>{const t=G(e),r=typeof i=="string"?{value:[i]}:i;return xe(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class Me{static resolveBlueId(e){const t=hr(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const s=t.value?.[0];return u.isNonNullable(s)?s:Me.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}class U{static isTypeOf(e,t,r){const s=Me.resolveBlueId(t),n=e.getType()?.getBlueId();if(u.isNullable(s)||u.isNullable(n))return!1;const o=r?.blueIdMapper?.toCurrentBlueId(s)??s,l=r?.blueIdMapper?.toCurrentBlueId(n)??n;if(o===l)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const a=r.typeSchemaResolver.resolveSchema(e);return U.checkSchemaExtension(a,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const s=U.unwrapSchema(e),n=U.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(s,n):!1}static isWrapperType(e){return e instanceof h.ZodOptional||e instanceof h.ZodNullable||e instanceof h.ZodReadonly||e instanceof h.ZodBranded||e instanceof h.ZodEffects||e instanceof h.ZodLazy}static unwrapSchema(e){return Rt(e)?e:U.isWrapperType(e)?e instanceof h.ZodEffects?U.unwrapSchema(e.innerType()):e instanceof h.ZodLazy?U.unwrapSchema(e.schema):U.unwrapSchema(e.unwrap()):e}}const fr=Symbol("blue.subtypeCache");function Es(i,e){return i[fr]=e,i}function Lt(i,e){const t=i.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(fe.includes(r)){const n=Xe[r];return new d().setBlueId(r).setName(n)}const s=e.fetchByBlueId(r);if(!s||s.length===0)return;if(s.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return s[0].cloneShallow().setBlueId(r)}return t}function C(i,e,t){const r=We(i),s=We(e),n=t[fr],o=`${r}|${s}`,l=n?.get(o);if(l!==void 0)return l;const a=Cs(i,e,t,r,s);return n?.set(o,a),a}function We(i){const e=i.getReferenceBlueId();return e!==void 0?e:A.calculateBlueIdSync(ne(i))}function ne(i){if(!yr(i))return i;const e=i.cloneShallow();e.getReferenceBlueId()!==void 0&&!P.hasBlueIdOnly(e)&&e.setReferenceBlueId(void 0);const t=e.getType();t!==void 0&&e.setType(ne(t));const r=e.getItemType();r!==void 0&&e.setItemType(ne(r));const s=e.getKeyType();s!==void 0&&e.setKeyType(ne(s));const n=e.getValueType();n!==void 0&&e.setValueType(ne(n));const o=e.getBlue();o!==void 0&&e.setBlue(ne(o));const l=e.getItems();l!==void 0&&e.setItems(l.map(c=>ne(c)));const a=e.getProperties();return a!==void 0&&e.setProperties(Object.fromEntries(Object.entries(a).map(([c,p])=>[c,ne(p)]))),e}function yr(i){return i.getReferenceBlueId()!==void 0&&!P.hasBlueIdOnly(i)?!0:[i.getType(),i.getItemType(),i.getKeyType(),i.getValueType(),i.getBlue(),...i.getItems()??[],...Object.values(i.getProperties()??{})].some(t=>t!==void 0&&yr(t))}function Cs(i,e,t,r,s){if(r===s)return!0;if(r&&fe.includes(r)){let a=e;for(;a!==void 0;){if(We(a)===r)return!0;a=Lt(a,t)}return!1}let n=i;const o=i.getBlueId();if(o){const a=t.fetchByBlueId(o);a&&a.length===1&&(n=a[0])}let l=n;for(;l!==void 0;){if(We(l)===s)return!0;l=Lt(l,t)}return!1}function Rs(i,e){return bt.some(t=>{const r=new d().setBlueId(t);return C(i,r,e)})}function As(i,e){const t=new d().setBlueId(te);return C(i,t,e)}function Os(i,e){const t=new d().setBlueId(se);return C(i,t,e)}function Vs(i,e){const t=new d().setBlueId(re);return C(i,t,e)}function Ms(i,e){const t=new d().setBlueId(ie);return C(i,t,e)}function Ue(i,e){const t=new d().setBlueId(qe);return C(i,t,e)}function Ke(i,e){const t=new d().setBlueId(Nt);return C(i,t,e)}function _s(i,e){return Ge.some(t=>{const r=new d().setName(t);return C(i,r,e)})}function Ds(i,e){for(const t of Ge){const r=new d().setName(t);if(C(i,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${i.getName()||"unknown"}".`)}class gr{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=Me.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),s=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(s))return!1;if(r===s)return!0;if(u.isNonNullable(this.nodeProvider))try{const n=new d().setBlueId(r),o=new d().setBlueId(s);if(C(n,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=Me.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,s]of this.blueIdMap)if(s===e||s._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)?A.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}class Qe{}class Ce{static convert(e){const t=new yt;return Ce.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const s=e.getProperties(),n=e.getItems(),o=s!==void 0&&Object.keys(s).length>0,l=n!==void 0&&n.length>0;if(!o&&!l){r.addPath(t===""?"/":t);return}if(s)for(const[a,c]of Object.entries(s)){const p=`${t}/${a}`;Ce.traverseNode(c,p,r)}if(n)for(let a=0;a<n.length;a++){const c=`${t}/${a}`;Ce.traverseNode(n[a],c,r)}}}function jt(i,e){const t=i.split(e),r=[...t].reverse().findIndex(n=>n!==""),s=r===-1?0:t.length-r;return t.slice(0,s)}class et extends Qe{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=jt(e,"/"),s=jt(t,"/");if(s.length>r.length)return!1;for(let n=1;n<s.length;n++)if(r[n]!=="*"&&r[n]!==s[n])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 yt().setMaxDepth(e);for(let r=1;r<=e;r++){const s="/"+Array(r).fill("*").join("/");t.addPath(s)}return t.build()}static withSinglePath(e){return new yt().addPath(e).build()}static fromNode(e){return Ce.convert(e)}}class yt{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 et(this.allowedPaths,this.maxDepth)}}class Y extends Qe{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class tt extends Qe{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 tt(e)}}const $=new Y;class k extends d{completeness;sourceSemanticBlueId;constructor(e,t={}){super(e.getName()),this.completeness=t.completeness??"full",this.sourceSemanticBlueId=this.validateSourceSemanticBlueId(t.sourceSemanticBlueId),this.createFrom(e)}isResolved(){return!0}getMinimalNode(){if(this.completeness==="path-limited"){if(this.sourceSemanticBlueId!==void 0)return new d().setReferenceBlueId(this.sourceSemanticBlueId);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return new ht().minimizeResolved(this)}getMinimalBlueId(){if(this.completeness==="path-limited"){if(this.sourceSemanticBlueId!==void 0)return this.sourceSemanticBlueId;throw new Error("Cannot calculate minimal BlueId for a path-limited resolved node without a source semantic BlueId.")}const t=new ht().minimizeResolvedForHash(this);return A.calculateBlueIdSync(t)}clone(){const e=super.clone();return new k(e,this.getMetadata())}cloneShallow(){const e=super.cloneShallow();return new k(e,this.getMetadata())}getCompleteness(){return this.completeness}getSourceSemanticBlueId(){return this.sourceSemanticBlueId}setSourceSemanticBlueId(e){return this.sourceSemanticBlueId=this.validateSourceSemanticBlueId(e),this}validateSourceSemanticBlueId(e){if(e!==void 0){if(!Te.isPotentialBlueId(e))throw new Error("sourceSemanticBlueId must be a valid BlueId.");return e}}getMetadata(){return{completeness:this.completeness,sourceSemanticBlueId:this.sourceSemanticBlueId}}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 Ls{blue;constructor(e){this.blue=e}matchesType(e,t,r=$){const s=et.fromNode(t),n=tt.of(r,s),o=this.extendAndResolve(e,n),l=this.blue.resolve(t,n),a=this.expandSchemaOwnedTypeReferences(t);return this.recursiveValueComparison(o,l,a,n)?this.verifyMatch(o,t,n)||t.getType()===void 0:!1}extendAndResolve(e,t){const r=e.clone(),s=r.clone();this.blue.extend(s,t);const n=this.blue.resolve(s,t);return this.restoreMissingStructure(n,r),n}restoreMissingStructure(e,t){const r=t.getItems(),s=e.getItems();if(r&&r.length>0)if(!s||s.length===0)e.setItems(r.map(a=>a.clone()));else for(let a=0;a<Math.min(s.length,r.length);a++)this.restoreMissingStructure(s[a],r[a]);const n=t.getProperties();if(n){let a=e.getProperties();a||(a={},e.setProperties(a));for(const[c,p]of Object.entries(n)){const f=a[c];f===void 0?a[c]=p.clone():this.restoreMissingStructure(f,p)}}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 s=t.getType();if(this.matchesImplicitStructure(e,s))return!0;const n=e.clone().setType(t.clone());try{this.blue.resolve(n,r)}catch{return!1}return!0}recursiveValueComparison(e,t,r=t,s=$){const n=t.getType(),o=this.matchesImplicitStructure(e,n)||this.matchesImplicitCoreCollectionType(e,t);if(e.getType()===void 0&&this.isCoreCollectionType(t)&&!o)return!1;if(n&&!o){const N=e.getType();if(!N||!C(N,n,this.blue.getNodeProvider()))return!1}const l=t.getBlueId();if(!o&&l!==void 0)if(this.isExplicitBlueIdMatcher(r)){if(e.getBlueId()!==l&&!this.matchesCalculatedBlueId(e,l))return!1}else{const N=e.getBlueId(),S=e.getType();if(S===void 0&&N!==void 0&&N!==l||S&&!C(S,t,this.blue.getNodeProvider()))return!1}const a=e.getBlueId();if(!o&&l===void 0&&a!==void 0&&e.getType()===void 0&&t.getItems()===void 0&&this.hasMatcherShape(t)&&!this.matchesCalculatedBlueId(t,a))return!1;const c=t.getValue();if(c!==void 0){const N=e.getValue();if(N===void 0)return!1;if(E(N)&&E(c)){if(!N.eq(c))return!1}else if(N!==c)return!1}const p=t.getItems(),f=r.getItems();if(p!==void 0){const N=e.getItems()??[];for(let S=0;S<p.length;S++)if(S<N.length){if(!this.recursiveValueComparison(N[S],p[S],f?.[S]??p[S],s))return!1}else if(this.hasValueInNestedStructure(p[S]))return!1}const y=t.getItemType(),g=r.getItemType();if(y!==void 0){const N=e.getItems()??[];for(const S of N)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(S,y,g??y,s),y,g??y,s))return!1}const I=t.getProperties(),L=r.getProperties();if(I!==void 0){const N=e.getProperties()??{};for(const[S,st]of Object.entries(I))if(S in N){if(!this.recursiveValueComparison(N[S],st,L?.[S]??st,s))return!1}else if(this.hasValueInNestedStructure(st))return!1}const b=t.getValueType(),F=r.getValueType();if(b!==void 0){const N=Object.values(e.getProperties()??{});for(const S of N)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(S,b,F??b,s),b,F??b,s))return!1}return!0}resolveUntypedNodeAgainstMatcherType(e,t,r,s){return e.getType()!==void 0||this.isExplicitBlueIdMatcher(r)?e:this.resolveAgainstTargetType(e,t,s)??e}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const s of t)if(this.hasValueInNestedStructure(s))return!0}const r=e.getProperties();if(r!==void 0){for(const s of Object.values(r))if(this.hasValueInNestedStructure(s))return!0}return!1}hasMatcherShape(e){return e.getValue()!==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}matchesCalculatedBlueId(e,t){if(e instanceof k&&e.getCompleteness()==="path-limited"&&e.getSourceSemanticBlueId()!==void 0)return e.getSourceSemanticBlueId()===t;try{return this.blue.calculateBlueIdSync(e)===t}catch{try{return this.blue.calculateBlueIdSync(this.toPlainBlueNode(e))===t}catch{return!1}}}toPlainBlueNode(e){const t=new d(e.getName());t.setDescription(e.getDescription()).setReferenceBlueId(e.getReferenceBlueId()).setInlineValue(e.isInlineValue());const r=e.getValue();r!==void 0&&t.setValue(r);const s=e.getType();s!==void 0&&t.setType(this.toPlainBlueNode(s));const n=e.getItemType();n!==void 0&&t.setItemType(this.toPlainBlueNode(n));const o=e.getKeyType();o!==void 0&&t.setKeyType(this.toPlainBlueNode(o));const l=e.getValueType();l!==void 0&&t.setValueType(this.toPlainBlueNode(l));const a=e.getItems();a!==void 0&&t.setItems(a.map(f=>this.toPlainBlueNode(f)));const c=e.getProperties();c!==void 0&&t.setProperties(Object.fromEntries(Object.entries(c).map(([f,y])=>[f,this.toPlainBlueNode(y)])));const p=e.getBlue();return p!==void 0&&t.setBlue(this.toPlainBlueNode(p)),t}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:Ue(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ke(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}matchesImplicitCoreCollectionType(e,t){return e.getType()!==void 0?!1:Ue(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ke(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isCoreCollectionType(e){return Ue(e,this.blue.getNodeProvider())||Ke(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 s=e.clone(),n=s.clone().setType(t.clone()),o=this.blue.resolve(n,r);return this.restoreMissingStructure(o,s),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()),s=e.getType();s&&e.setType(this.expandReferencedTypeNode(s,r));const n=e.getItemType();n&&e.setItemType(this.expandReferencedTypeNode(n,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(p=>this.expandSchemaTypeReferences(p,r)));const c=e.getProperties();return c&&e.setProperties(Object.fromEntries(Object.entries(c).map(([p,f])=>[p,this.expandSchemaTypeReferences(f,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 s=this.blue.getNodeProvider().fetchByBlueId(r);return!s||s.length!==1?e.clone():this.expandSchemaTypeReferences(s[0].clone(),t)}withVisitedBlueId(e,t){if(!t||e.has(t))return e;const r=new Set(e);return r.add(t),r}}class M{static ZERO_BLUE_ID="0".repeat(44);static THIS_INDEX_REFERENCE_PATTERN=/^this#(\d+)$/;prepareDocument;calculateBlueId;constructor(e={}){this.prepareDocument=e.prepareDocument??(t=>t),this.calculateBlueId=e.calculateBlueId??A.calculateBlueIdSync}static hasThisReference(e){return e.some(t=>this.nodeHasThisReference(t))}static hasIndexedThisReference(e){return e.some(t=>this.nodeHasIndexedThisReference(t))}static isIndexedThisReference(e){return this.THIS_INDEX_REFERENCE_PATTERN.test(e)}calculate(e){this.validateCyclicSet(e);const t=e.map((l,a)=>{const c=this.prepareDocument(this.replaceIndexedThisReferences(l,()=>M.ZERO_BLUE_ID));return{originalIndex:a,preliminaryBlueId:this.calculateBlueId(c),node:l}});this.validateUniquePreliminaryBlueIds(t);const r=[...t].sort(this.comparePreliminaryDocuments),s=[];r.forEach(({originalIndex:l},a)=>{s[l]=a});const n=r.map(({node:l})=>this.prepareDocument(this.replaceIndexedThisReferences(l,a=>`this#${s[a]}`))),o=this.calculateBlueId(n);return{blueId:o,nodes:n,documentBlueIds:n.map((l,a)=>`${o}#${a}`),originalToSortedIndexes:s}}comparePreliminaryDocuments(e,t){return e.preliminaryBlueId<t.preliminaryBlueId?-1:e.preliminaryBlueId>t.preliminaryBlueId?1:0}validateUniquePreliminaryBlueIds(e){const t=new Map;for(const r of e){const s=t.get(r.preliminaryBlueId);if(s!==void 0)throw new Error(`Direct cyclic document set has ambiguous canonical ordering: documents ${s} and ${r.originalIndex} share preliminary BlueId '${r.preliminaryBlueId}'.`);t.set(r.preliminaryBlueId,r.originalIndex)}}validateCyclicSet(e){if(e.length===0)throw new Error("Cyclic document set cannot be empty.");this.visitReferences(e,(t,r)=>{if(r==="this")throw new Error("Direct cyclic document sets must use indexed references such as 'this#0'; unindexed 'this' is not supported.");if(r.startsWith("this#")&&!M.THIS_INDEX_REFERENCE_PATTERN.test(r))throw new Error(`Malformed direct cyclic reference '${r}'. Expected 'this#<non-negative-integer>'.`);const s=this.readIndexedThisReference(r);if(s!==void 0&&s>=e.length)throw new Error(`Direct cyclic reference '${r}' points outside the ${e.length}-document set.`)})}replaceIndexedThisReferences(e,t){const r=e.clone();return this.rewriteIndexedThisReferences(r,t),r}rewriteIndexedThisReferences(e,t){const r=e.getReferenceBlueId();if(r!==void 0){const s=this.readIndexedThisReference(r);s!==void 0&&e.setReferenceBlueId(t(s))}this.childrenOf(e).forEach(s=>this.rewriteIndexedThisReferences(s,t))}static nodeHasThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,s)=>{(s==="this"||s.startsWith("this#"))&&(t=!0)}),t}static nodeHasIndexedThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,s)=>{M.THIS_INDEX_REFERENCE_PATTERN.test(s)&&(t=!0)}),t}visitReferences(e,t){e.forEach(r=>M.visitNodeReferences(r,t))}static visitNodeReferences(e,t){const r=e.getReferenceBlueId();r!==void 0&&t(e,r),this.childrenOf(e).forEach(s=>this.visitNodeReferences(s,t))}readIndexedThisReference(e){const t=e.match(M.THIS_INDEX_REFERENCE_PATTERN);if(t!==null)return Number(t[1])}childrenOf(e){return M.childrenOf(e)}static childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}class ye{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function rt(i){return new class extends ye{fetchByBlueId(e){return i(e)}}}class mr{resolveWithoutLimits(e){return this.resolve(e,$)}}class Ir extends ye{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 at=pe.types.float.options,js={...at,construct:i=>{const e=i.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new D(e);if(at.construct)return at.construct(i)}},xs=new pe.Type("tag:yaml.org,2002:float",js),ct=pe.types.int.options,$s={...ct,construct:i=>{let e=i;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new O(e);if(ct.construct)return ct.construct(i)}},Fs=new pe.Type("tag:yaml.org,2002:int",$s),Tr=pe.CORE_SCHEMA.extend({implicit:[xs,Fs]}),ee=i=>{const e=pe.load(i,{schema:Tr});return e===void 0?void 0:e},vr=i=>pe.dump(i,{schema:Tr,replacer:(e,t)=>{if(E(t)){if(Q(t)){const r=new Z(Number.MIN_SAFE_INTEGER.toString()),s=new Z(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(s))return t.toString()}return t.toNumber()}return t}}),Br=`- type:
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Z=require("big.js"),u=require("@blue-labs/shared-utils"),h=require("zod"),Rr=require("bs58"),H=require("radash"),B=require("@blue-labs/repository-contract"),Ar=require("js-sha256"),Or=require("crypto"),Vr=require("base32.js"),he=require("js-yaml"),Lt=i=>i&&i.__esModule?i:{default:i},Ae=Lt(Rr),rt=Lt(Or);class $ extends Z{constructor(e){super(e)}}class O extends Z{constructor(e){super(e)}}const le="name",ae="description",U="type",Be="itemType",Ne="keyType",be="valueType",W="value",J="items",V="blueId",_e="blue",gt=[le,ae,U,Be,Ne,be,W,J,V,_e],$t="Text",jt="Double",xt="Integer",Ft="Boolean",zt="List",Ut="Dictionary",We=[$t,jt,xt,Ft],mt=[...We,zt,Ut],te="DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",re="7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",se="5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",ie="4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",Ze="6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",It="G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",Tt=[te,re,se,ie],pe=[...Tt,Ze,It],Kt=Object.fromEntries(mt.map((i,e)=>[i,pe[e]])),Ge=Object.fromEntries(pe.map((i,e)=>[i,mt[e]])),Mr=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:We,BASIC_TYPE_BLUE_IDS:Tt,BOOLEAN_TYPE:Ft,BOOLEAN_TYPE_BLUE_ID:ie,CORE_TYPES:mt,CORE_TYPE_BLUE_IDS:pe,CORE_TYPE_BLUE_ID_TO_NAME_MAP:Ge,CORE_TYPE_NAME_TO_BLUE_ID_MAP:Kt,DICTIONARY_TYPE:Ut,DICTIONARY_TYPE_BLUE_ID:It,DOUBLE_TYPE:jt,DOUBLE_TYPE_BLUE_ID:re,INTEGER_TYPE:xt,INTEGER_TYPE_BLUE_ID:se,LIST_TYPE:zt,LIST_TYPE_BLUE_ID:Ze,OBJECT_BLUE:_e,OBJECT_BLUE_ID:V,OBJECT_CONTRACTS:B.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:ae,OBJECT_ITEMS:J,OBJECT_ITEM_TYPE:Be,OBJECT_KEY_TYPE:Ne,OBJECT_MERGE_POLICY:B.OBJECT_MERGE_POLICY,OBJECT_NAME:le,OBJECT_SCHEMA:B.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:gt,OBJECT_TYPE:U,OBJECT_VALUE:W,OBJECT_VALUE_TYPE:be,TEXT_TYPE:$t,TEXT_TYPE_BLUE_ID:te},Symbol.toStringTag,{value:"Module"}));class Dr{static get(e,t,r,s=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return s&&o!==void 0?o:e}const n=t.substring(1).split("/");return this.getRecursive(e,n,0,r,s)}static getRecursive(e,t,r,s,n){if(r===t.length-1&&!n)return this.getNodeForSegment(e,t[r],s,!1);if(r===t.length){const a=e.getValue();return n&&a!==void 0?a:e}const o=t[r],l=this.getNodeForSegment(e,o,s,!0);if(l)return this.getRecursive(l,t,r+1,s,n)}static getNodeForSegment(e,t,r,s){let n;const o=e.getProperties();if(o&&t in o)n=o[t];else switch(t){case"name":{const l=e.getName();n=new d().setValue(l??null);break}case"description":{const l=e.getDescription();n=new d().setValue(l??null);break}case"type":n=e.getType();break;case"itemType":n=e.getItemType();break;case"keyType":n=e.getKeyType();break;case"valueType":n=e.getValueType();break;case"value":{const l=e.getValue();n=new d().setValue(l??null);break}case"blueId":{const l=e.getBlueId();n=new d().setValue(l??null);break}case"blue":n=e.getBlue();break;case"items":{const l=e.getItems();n=new d().setItems(l);break}case"properties":{const l=e.getProperties();n=new d().setProperties(l);break}case B.OBJECT_CONTRACTS:{const l=e.getContracts();n=new d().setContracts(l);break}default:{if(/^\d+$/.test(t)){const l=parseInt(t,10),a=e.getItems();a&&l>=0&&l<a.length?n=a[l]:n=void 0}else n=void 0;break}}if(n)return s&&r?this.link(n,r):n}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===se&&typeof this.value=="string")return new O(this.value);if(e===re&&typeof this.value=="string"){const t=new $(this.value),r=parseFloat(t.toString());return new $(r.toString())}else if(e===ie&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new O(e.toString()):this.value=new $(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}getReferenceBlueId(){return this.blueId}setReferenceBlueId(e){return this.blueId=e,this}getBlueId(){return this.getReferenceBlueId()}setBlueId(e){return this.setReferenceBlueId(e)}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 Dr.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 O||t instanceof $)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 me{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],s=r.length;if(s<this.MIN_BLUE_ID_LENGTH||s>this.MAX_BLUE_ID_LENGTH)return!1;try{if(Ae.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 _r=h.z.string().max(me.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(me.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(i=>{try{return Ae.default.decode(i),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),Ie=h.z.lazy(()=>h.z.record(h.z.unknown()).and(h.z.object({blueId:h.z.string().optional(),name:h.z.string().optional(),description:h.z.string().optional(),type:Ie.optional(),value:h.z.union([h.z.string(),h.z.number(),h.z.boolean()]).optional().nullable(),items:h.z.array(Ie).optional()}))),Le=h.z.object({blueId:h.z.string().optional(),name:h.z.string().optional(),description:h.z.string().optional(),type:Ie.optional()}),Lr=Le.extend({value:h.z.string().optional()}),$r=Le.extend({value:h.z.number().optional()}),jr=Le.extend({value:h.z.boolean().optional()}),xr=Le.extend({items:h.z.array(h.z.string()).optional()}),Fr=i=>Ie.safeParse(i).success,Ht=i=>u.isNonNullable(i)&&"blueId"in i&&u.isNonNullable(i.blueId),zr=i=>u.isNonNullable(i)&&"name"in i&&u.isNonNullable(i.name),Yt=i=>u.isNonNullable(i)&&"items"in i&&u.isNonNullable(i.items),kt=i=>u.isNonNullable(i)&&"type"in i&&u.isNonNullable(i.type),Jt=i=>u.isNonNullable(i)&&"value"in i&&u.isNonNullable(i.value),Ur=(i,e)=>i.required({type:!0}).safeParse(e).success,E=i=>i instanceof Z,Q=i=>E(i)&&i instanceof O,Ke=i=>E(i)&&i instanceof $,Kr=h.z.lazy(()=>h.z.record(Oe)),Hr=h.z.lazy(()=>h.z.union([h.z.array(Oe),h.z.array(Oe).readonly()])),Oe=h.z.lazy(()=>h.z.union([u.jsonPrimitiveSchema,Kr,Hr,h.z.instanceof(Z)])),vt=i=>H.isObject(i)&&!H.isArray(i)&&!u.isReadonlyArray(i)&&!E(i),Bt=i=>H.isArray(i)||u.isReadonlyArray(i),Yr=i=>Bt(i)||vt(i)||E(i)||u.isJsonPrimitive(i);class m{static deserialize(e){return m.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(vt(e)){const t=new d,r={};return Object.entries(e).forEach(([s,n])=>{switch(s){case le:if(n==null)t.setName(void 0);else{if(typeof n!="string")throw new Error(`The ${le} field must be a string.`);t.setName(n)}break;case ae:if(n==null)t.setDescription(void 0);else{if(typeof n!="string")throw new Error(`The ${ae} field must be a string.`);t.setDescription(n)}break;case U:t.setType(m.handleNode(n));break;case Be:t.setItemType(m.handleNode(n));break;case Ne:t.setKeyType(m.handleNode(n));break;case be:t.setValueType(m.handleNode(n));break;case W:t.setValue(m.handleValue(n));break;case V:if(typeof n!="string")throw new Error(`The ${V} field must be a string.`);t.setBlueId(n);break;case J:t.setItems(m.handleArray(n));break;case _e:t.setBlue(m.handleNode(n));break;default:r[s]=m.handleNode(n);break}}),Object.keys(r).length>0&&t.setProperties(r),t}else{if(Bt(e))return new d().setItems(m.handleArray(e));{const t=e;return new d().setValue(m.handleValue(t)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||E(e))if(Q(e)||Number.isSafeInteger(e)){const t=new O(e.toString()),r=Number.MIN_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER;return t.lt(r)?new O(r.toString()):t.gt(s)?new O(s.toString()):t}else{const t=parseFloat(e.toString());return new $(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(H.isObject(e)&&!Array.isArray(e))return[m.handleNode(e)];if(Array.isArray(e))return e.map(m.handleNode);throw new Error("Expected an array node")}}}function kr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var st,At;function Jr(){return At||(At=1,st=function i(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?i(e.toJSON()):Array.isArray(e)?`[${e.reduce((s,n,o)=>`${s}${o===0?"":","}${i(n===void 0||typeof n=="symbol"?null:n)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,s)=>{if(e[s]===void 0||typeof e[s]=="symbol")return r;const n=r.length===0?"":",";return`${r}${n}${i(s)}:${i(e[s])}`},"")}}`}),st}var Wr=Jr();const Zr=kr(Wr);class He{static canonicalize(e){return Zr(e)}}const it=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class Nt{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new Nt),this.instance}initBrowserCrypto(){return it?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return it&&!!rt.default&&typeof rt.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return it?rt.default:null}}class Wt{cryptoEnv=Nt.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return Ae.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return Ae.default.encode(r)}canonicalizeInput(e){const t=He.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(Ar.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 s=new TextEncoder().encode(e),n=await t.subtle.digest("SHA-256",s);return new Uint8Array(n)}}const S={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 N{static isEmptyNode(e){return this.hasFieldsAndMayHaveFields(e)}static hasBlueIdOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([S.BLUE_ID]))}static hasItemsOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([S.ITEMS]))}static isValidValueNode(e){const t=e.getValue(),r=e.getProperties(),s=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(s)}static textNode(e){return new d().setType(new d().setBlueId(te)).setValue(e)}static integerNode(e){const t=e instanceof O?e:new O(e.toString());return new d().setType(new d().setBlueId(se)).setValue(t)}static doubleNode(e){const t=e instanceof $?e:new $(e.toString());return new d().setType(new d().setBlueId(re)).setValue(t)}static booleanNode(e){return new d().setType(new d().setBlueId(ie)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const s of Object.values(S)){const n=u.isNonNullable(this.getFieldValue(e,s));if(t.has(s)){if(!n)return!1}else if(!r.has(s)){if(n)return!1}}return!0}static getFieldValue(e,t){switch(t){case S.NAME:return e.getName();case S.TYPE:return e.getType();case S.VALUE:return e.getValue();case S.DESCRIPTION:return e.getDescription();case S.PROPERTIES:return e.getProperties();case S.BLUE:return e.getBlue();case S.ITEMS:return e.getItems();case S.KEY_TYPE:return e.getKeyType();case S.VALUE_TYPE:return e.getValueType();case S.ITEM_TYPE:return e.getItemType();case S.BLUE_ID:return e.getBlueId();default:throw new Error(`Unknown field: ${t}`)}}}const ye="$previous",ue="$pos",at="$empty";class v{static getMergePolicy(e,t){const r=this.getMergePolicyValue(e);return r!==void 0?r:(t===void 0?void 0:this.getMergePolicyValue(t))??"positional"}static getMergePolicyValue(e){const t=e.getProperties()?.[B.OBJECT_MERGE_POLICY]?.getValue();if(t==="append-only"||t==="positional")return t}static hasListControlItems(e){return e?.some(t=>this.hasPreviousProperty(t)||this.hasPositionProperty(t))??!1}static hasAnyListControl(e){const t=e.getItems();return this.hasListControlItems(t)||t?.some(r=>this.hasAnyListControl(r))?!0:Object.values(e.getProperties()??{}).some(r=>this.hasAnyListControl(r))||this.hasAnyListControlChild(e.getType())||this.hasAnyListControlChild(e.getItemType())||this.hasAnyListControlChild(e.getKeyType())||this.hasAnyListControlChild(e.getValueType())||this.hasAnyListControlChild(e.getBlue())}static hasPositionControl(e){const t=e.getItems();return t?.some(r=>this.hasPositionProperty(r))||t?.some(r=>this.hasPositionControl(r))?!0:Object.values(e.getProperties()??{}).some(r=>this.hasPositionControl(r))||this.hasPositionControlChild(e.getType())||this.hasPositionControlChild(e.getItemType())||this.hasPositionControlChild(e.getKeyType())||this.hasPositionControlChild(e.getValueType())||this.hasPositionControlChild(e.getBlue())}static hasPreviousProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},ye)}static hasPositionProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},ue)}static hasEmptyProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},at)}static isEmptyItem(e){const t=e.getProperties(),r=t?.[at];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&N.hasFieldsAndMayHaveFields(e,new Set([S.PROPERTIES]))&&N.hasFieldsAndMayHaveFields(r,new Set([S.VALUE]),new Set([S.TYPE]))&&r.getValue()===!0}static isPreviousItem(e){const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&N.hasFieldsAndMayHaveFields(e,new Set([S.PROPERTIES]))&&N.hasBlueIdOnly(t[ye])}static getPreviousBlueId(e){if(this.isPreviousItem(e))return e.getProperties()?.[ye]?.getBlueId()}static createPreviousItem(e){return new d().setProperties({[ye]:new d().setBlueId(e)})}static readPosition(e){const t=e.getProperties()?.[ue];if(t===void 0)return;if(!N.hasFieldsAndMayHaveFields(t,new Set([S.VALUE]),new Set([S.TYPE])))throw new Error("$pos must be a non-negative integer value.");const r=t.getValue(),s=r instanceof O?r.toNumber():typeof r=="number"?r:void 0;if(s===void 0||!Number.isInteger(s)||s<0)throw new Error("$pos must be a non-negative integer value.");return s}static createPositionedItem(e,t){const r=t.clone();return r.addProperty(ue,new d().setValue(e)),r}static withoutPosition(e){const t=e.clone(),r=t.getProperties();return r!==void 0&&(delete r[ue],Object.keys(r).length===0&&t.setProperties(void 0)),t}static hasPayloadAfterRemovingPosition(e){return!N.isEmptyNode(this.withoutPosition(e))}static isReplacementPayload(e){return u.isNonNullable(e.getValue())||u.isNonNullable(e.getItems())||u.isNonNullable(e.getBlueId())}static hasAnyListControlChild(e){return e!==void 0&&this.hasAnyListControl(e)}static hasPositionControlChild(e){return e!==void 0&&this.hasPositionControl(e)}}const Gr=new Set([le,ae,W]),qr={$list:"empty"},Xr="$listCons",Qr="prev",es="elem";class ts{constructor(e){this.hashProvider=e}calculate(e){const t=this.clean(this.toHashValue(e));if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.calculateInternal(t,!1)}calculateSync(e){const t=this.clean(this.toHashValue(e));if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.calculateInternal(t,!0)}calculateInternal(e,t){return this.isScalar(e)?this.applyHash(this.toJsonScalar(e),t):Array.isArray(e)?this.calculateList(e,t):this.isPureReference(e)?e[V]:this.isScalarWrapper(e)?this.calculateInternal(e[W],t):this.isBasicTypedScalarWrapper(e)?this.calculateInternal(e[W],t):this.isListWrapper(e)?this.calculateInternal(e[J],t):this.isBasicTypedListWrapper(e)?this.calculateInternal(e[J],t):this.calculateMap(e,t)}calculateMap(e,t){const s=Object.entries(e).sort(([o],[l])=>o.localeCompare(l)).map(([o,l])=>{if(Gr.has(o))return t?[o,l]:Promise.resolve([o,l]);const a=this.calculateInternal(l,t);return t?[o,{[V]:a}]:Promise.resolve(a).then(c=>[o,{[V]:c}])}),n=o=>{const l={};for(const[a,c]of o)l[a]=c;return this.applyHash(l,t)};return t?n(s):Promise.all(s).then(n)}calculateList(e,t){let r=0,s;const n=e[0];if(n!==void 0&&this.hasPreviousControlKey(n)){const o=this.getPreviousControlBlueId(n);if(o===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");s=t?o:Promise.resolve(o),r=1}else s=this.applyHash(qr,t);for(let o=r;o<e.length;o++){const l=e[o];if(this.hasPreviousControlKey(l))throw new Error("$previous list control is allowed only first.");if(this.hasPositionControlKey(l))throw new Error("$pos list controls must be consumed before raw BlueId hashing.");const a=s,c=this.calculateInternal(l,t);t?s=this.applyHash(this.createListFoldInput(a,c),!0):s=Promise.all([a,c]).then(([p,f])=>this.applyHash(this.createListFoldInput(p,f),!1))}return s}createListFoldInput(e,t){return{[Xr]:{[Qr]:{[V]:e},[es]:{[V]:t}}}}getPreviousControlBlueId(e){if(typeof e!="object"||e===null||Array.isArray(e)||E(e))return;const t=Object.entries(e);if(t.length!==1||t[0][0]!==ye)return;const r=t[0][1];if(!(typeof r!="object"||r===null||Array.isArray(r)||E(r)||!this.isPureReference(r)))return r[V]}hasPreviousControlKey(e){return this.hasControlKey(e,ye)}hasPositionControlKey(e){return this.hasControlKey(e,ue)}hasControlKey(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!E(e)&&Object.prototype.hasOwnProperty.call(e,t)}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}toHashValue(e){return e instanceof d?this.nodeToHashValue(e):Array.isArray(e)?e.map(t=>this.toHashValue(t)).filter(t=>t!==void 0):this.jsonToHashValue(e)}nodeToHashValue(e){const t={};this.setIfPresent(t,le,e.getName()),this.setIfPresent(t,ae,e.getDescription()),this.setIfPresent(t,U,e.getType()),this.setIfPresent(t,Be,e.getItemType()),this.setIfPresent(t,Ne,e.getKeyType()),this.setIfPresent(t,be,e.getValueType());const r=e.getValue();r!==void 0&&(t[W]=this.scalarToHashValue(r));const s=e.getItems();s!==void 0&&(t[J]=s.map(o=>this.nodeToHashValue(o))),this.setIfPresent(t,V,e.getReferenceBlueId()),this.setIfPresent(t,_e,e.getBlue());const n=e.getProperties();if(n!==void 0)for(const[o,l]of Object.entries(n))t[o]=this.nodeToHashValue(l);return t}jsonToHashValue(e){if(e!=null){if(this.isScalar(e)||E(e))return this.scalarToHashValue(e);if(Array.isArray(e))return e.map(t=>this.jsonToHashValue(t)).filter(t=>t!==void 0);if(typeof e=="object"){const t={};for(const[r,s]of Object.entries(e))t[r]=this.jsonToHashValue(s);return t}return e}}setIfPresent(e,t,r){r!==void 0&&(e[t]=r instanceof d?this.nodeToHashValue(r):r)}clean(e){if(e==null)return;if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.clean(r)).filter(r=>r!==void 0);const t={};for(const[r,s]of Object.entries(e)){const n=this.clean(s);n!==void 0&&(t[r]=n)}return Object.keys(t).length===0?void 0:t}isPureReference(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===V&&typeof t[0]?.[1]=="string"}isScalarWrapper(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===W}isBasicTypedScalarWrapper(e){return this.hasOnlyKeys(e,[U,W])&&this.isBasicScalarTypeReference(e[U])}isListWrapper(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===J&&Array.isArray(t[0]?.[1])}isBasicTypedListWrapper(e){return this.hasOnlyKeys(e,[U,J])&&this.isTypeReference(e[U],Ze)&&Array.isArray(e[J])}hasOnlyKeys(e,t){return Object.keys(e).length===t.length&&t.every(s=>Object.prototype.hasOwnProperty.call(e,s))}isBasicScalarTypeReference(e){return this.isTypeReference(e,te)||this.isTypeReference(e,se)||this.isTypeReference(e,re)||this.isTypeReference(e,ie)}isTypeReference(e,t){return typeof e!="object"||e===null||Array.isArray(e)||E(e)?!1:this.isPureReference(e)&&e[V]===t}isScalar(e){return u.isJsonPrimitive(e)&&e!==null||E(e)}scalarToHashValue(e){if(e instanceof O||Q(e)){const t=new Z(Number.MIN_SAFE_INTEGER.toString()),r=new Z(Number.MAX_SAFE_INTEGER.toString());return e.lt(t)||e.gt(r)?e.toString():e.toNumber()}return e instanceof $||E(e)?e.toNumber():e}toJsonScalar(e){return E(e)?this.scalarToHashValue(e):e}}class A{static INSTANCE=new A(new Wt);hasher;constructor(e){this.hasher=new ts(e)}static calculateBlueId(e){return A.INSTANCE.calculate(e)}static calculateBlueIdSync(e){return A.INSTANCE.calculateSync(e)}calculate(e){return this.hasher.calculate(e)}calculateSync(e){return this.hasher.calculateSync(e)}}class F{constructor(e={emitListControls:!0}){this.options=e}reverse(e){const t=new d;return this.reverseNode(t,e,void 0,!0),t}static calculateHashMinimalBlueId(e){return A.calculateBlueIdSync(this.toHashMinimalNode(e))}static calculateHashMinimalListBlueId(e){return A.calculateBlueIdSync(e.map(t=>this.toHashMinimalNode(t)))}static toHashMinimalNode(e){return new F({emitListControls:!1}).reverse(e)}reverseNode(e,t,r,s){const n=this.getEffectiveFromType(r,t);!s&&this.isIdenticalToType(t,n)||(this.reverseBasicProperties(e,t,n,s),this.reverseTypeReferences(e,t,r,n),this.reverseItems(e,t,n),this.reverseProperties(e,t,n))}isIdenticalToType(e,t){return u.isNonNullable(e.getBlueId())&&u.isNonNullable(t?.getBlueId())&&e.getBlueId()===t.getBlueId()}reverseBasicProperties(e,t,r,s){const n=t.getValue();u.isNonNullable(n)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(n),u.isNonNullable(t.getName())&&(s||u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(s||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,s){const n=(o,l,a)=>{const c=o(t),p=a?o(a):void 0;u.isNonNullable(c)&&!this.areTypeReferencesEquivalent(c,p)&&l(e,this.toMinimalTypeReference(c))};n(o=>o.getType(),(o,l)=>o.setType(l),r),n(o=>o.getItemType(),(o,l)=>o.setItemType(l),s),n(o=>o.getKeyType(),(o,l)=>o.setKeyType(l),s),n(o=>o.getValueType(),(o,l)=>o.setValueType(l),s)}areTypeReferencesEquivalent(e,t){if(u.isNullable(t))return!1;const r=e.getBlueId(),s=t.getBlueId();return u.isNonNullable(r)||u.isNonNullable(s)?u.isNonNullable(r)&&u.isNonNullable(s)&&r===s:F.calculateHashMinimalBlueId(e)===F.calculateHashMinimalBlueId(t)}toMinimalTypeReference(e){const t=e.getBlueId();if(u.isNonNullable(t))return new d().setBlueId(t);const r=new d;return this.reverseNode(r,e,void 0,!0),N.isEmptyNode(r)?e.clone():r}reverseItems(e,t,r){const s=t.getItems();if(u.isNullable(s))return;const n=r?.getItems();if(s.length===0){(u.isNullable(n)||n.length>0)&&e.setItems([]);return}if(u.isNonNullable(n)&&s.length===n.length&&s.every((l,a)=>F.calculateHashMinimalBlueId(l)===F.calculateHashMinimalBlueId(n[a])))return;const o=this.options.emitListControls!==!1&&u.isNonNullable(n)&&n.length>0?this.reverseInheritedItems(t,r):this.reverseFullItems(s);o.length>0&&e.setItems(o)}reverseInheritedItems(e,t){const r=e.getItems()??[],s=t.getItems()??[];if(r.length<s.length)throw new Error(`Resolved list has fewer items (${r.length}) than inherited list (${s.length}).`);const n=v.getMergePolicy(e,t),o=[];for(let c=0;c<s.length;c++)F.calculateHashMinimalBlueId(r[c])!==F.calculateHashMinimalBlueId(s[c])&&o.push(c);if(o.length>0&&n==="append-only")throw new Error("append-only list cannot be minimized as a non-prefix mutation.");const l=F.calculateHashMinimalListBlueId(s),a=[v.createPreviousItem(l)];for(const c of o){const p=new d;this.reverseNode(p,r[c],s[c],!1);const f=N.isEmptyNode(p)?r[c].clone():p;a.push(v.createPositionedItem(c,f))}for(let c=s.length;c<r.length;c++){const p=new d;this.reverseNode(p,r[c],void 0,!1),a.push(p)}return a.length===1?[]:a}reverseFullItems(e){const t=[];for(let r=0;r<e.length;r++){const s=new d;this.reverseNode(s,e[r],void 0,!1),t.push(s)}return t}reverseProperties(e,t,r){const s=t.getProperties();if(u.isNullable(s))return;const n={};for(const[o,l]of Object.entries(s)){const a=this.getInheritedProperty(o,r),c=new d;this.reverseNode(c,l,a,!1),N.isEmptyNode(c)||(n[o]=c)}Object.keys(n).length>0&&e.setProperties(n)}getInheritedProperty(e,t){return t?.getProperties()?.[e]}getEffectiveFromType(e,t){const r=this.createOwnTypeOverlay(t.getType());return u.isNullable(e)?r:u.isNullable(r)?e:this.mergeNodes(e,r)}createOwnTypeOverlay(e){if(u.isNullable(e))return;const t=e.cloneShallow().setName(void 0).setDescription(void 0).setType(void 0).setBlueId(void 0);if(!N.isEmptyNode(t))return t}mergeNodes(e,t){const r=e.clone(),s=t.getValue();u.isNonNullable(s)&&r.setValue(s);const n=t.getType();u.isNonNullable(n)&&r.setType(n.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 c=t.getProperties();if(u.isNonNullable(c)){const f=r.getProperties()||{};for(const[y,g]of Object.entries(c)){const I=f[y];f[y]=I===void 0?g.clone():this.mergeNodes(I,g)}r.setProperties(f)}const p=t.getItems();return u.isNonNullable(p)&&r.setItems(p.map(f=>f.clone())),r}}class ct{mergeReverser=new F;hashMergeReverser=new F({emitListControls:!1});minimize(e){return this.minimizeResolved(e)}minimizeResolved(e){return this.mergeReverser.reverse(e)}minimizeResolvedForHash(e){return this.hashMergeReverser.reverse(e)}}class Te extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r&&r.length>0?r:[],this.name="BlueError"}}const K={AMBIGUOUS_BLUE_ID_PAYLOAD:"AMBIGUOUS_BLUE_ID_PAYLOAD",INVALID_STORAGE_SHAPE:"INVALID_STORAGE_SHAPE",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"};class q{static RESERVED_PROPERTY_KEYS=new Set([B.OBJECT_SCHEMA,B.OBJECT_MERGE_POLICY,B.OBJECT_CONTRACTS]);static INTERNAL_PROPERTIES_KEY="properties";static validateStorageShape(e){this.validateNode(e,[],{insideItems:!1})}static validateStorageListShape(e){e.forEach((t,r)=>{this.validateNode(t,[String(r)],{insideItems:!0,itemIndex:r})})}static validateListControlShape(e){e.forEach((t,r)=>{this.validateListControlNode(t,[String(r)],r)})}static validateListControlNode(e,t,r){r!==void 0&&this.validateListControlItem(e,t,r),this.validateListControlChild(e.getType(),[...t,"type"]),this.validateListControlChild(e.getItemType(),[...t,"itemType"]),this.validateListControlChild(e.getKeyType(),[...t,"keyType"]),this.validateListControlChild(e.getValueType(),[...t,"valueType"]),this.validateListControlChild(e.getBlue(),[...t,"blue"]),e.getItems()?.forEach((n,o)=>{this.validateListControlNode(n,[...t,"items",String(o)],o)});const s=e.getProperties();if(s!==void 0)for(const[n,o]of Object.entries(s))this.validateListControlNode(o,[...t,n])}static validateNode(e,t,r){r.insideItems&&this.validateListControlItem(e,t,r.itemIndex??0);const s=e.getReferenceBlueId();if(s!==void 0&&!N.hasBlueIdOnly(e))if(r.insideItems&&v.hasPositionProperty(e)&&N.hasBlueIdOnly(v.withoutPosition(e)))v.readPosition(e);else{const f=this.toPointer(t);throw new Te(K.AMBIGUOUS_BLUE_ID_PAYLOAD,`Ambiguous blueId plus payload at ${f}. Use exact { blueId } for references or remove blueId from payload content.`,[{code:K.AMBIGUOUS_BLUE_ID_PAYLOAD,message:"A storage or authoring node cannot combine blueId with payload.",locationPath:t,context:{blueId:s}}])}const n=this.getChildProperties(e,t,r),o=e.getValue()!==void 0,l=e.getItems()!==void 0,a=Object.keys(n).length>0;o&&l&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value and items payloads."),o&&a&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value payload with object child fields."),l&&a&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine items payload with object child fields."),this.validateChild(e.getType(),[...t,"type"]),this.validateChild(e.getItemType(),[...t,"itemType"]),this.validateChild(e.getKeyType(),[...t,"keyType"]),this.validateChild(e.getValueType(),[...t,"valueType"]),this.validateChild(e.getBlue(),[...t,"blue"]),e.getItems()?.forEach((p,f)=>{this.validateNode(p,[...t,"items",String(f)],{insideItems:!0,itemIndex:f})});const c=e.getProperties();if(c!==void 0)for(const[p,f]of Object.entries(c))this.validateNode(f,[...t,p],{insideItems:!1})}static validateListControlItem(e,t,r){if(v.hasEmptyProperty(e)&&(v.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $previous."),v.hasPositionProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $pos."),v.isEmptyItem(e)||this.throwInvalidStorageShape(t,"$empty list content must be exactly { $empty: true }.")),v.hasPreviousProperty(e)&&(r!==0&&this.throwInvalidStorageShape(t,"$previous list control is allowed only as the first item."),v.isPreviousItem(e)||this.throwInvalidStorageShape(t,"$previous list control must be exactly { $previous: { blueId: <id> } }.")),v.hasPositionProperty(e)){v.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$pos cannot be combined with $previous.");try{v.readPosition(e)}catch(s){this.throwInvalidStorageShape([...t,ue],s instanceof Error?s.message:"$pos must be a non-negative integer value.")}v.hasPayloadAfterRemovingPosition(e)||this.throwInvalidStorageShape(t,"$pos list control must include an item payload.")}}static validateChild(e,t){e!==void 0&&this.validateNode(e,t,{insideItems:!1})}static validateListControlChild(e,t){e!==void 0&&this.validateListControlNode(e,t)}static getChildProperties(e,t,r){const s=e.getProperties()??{};return Object.prototype.hasOwnProperty.call(s,this.INTERNAL_PROPERTIES_KEY)&&this.throwInvalidStorageShape([...t,this.INTERNAL_PROPERTIES_KEY],"The document-level properties key is not part of the Blue language."),Object.fromEntries(Object.entries(s).filter(([n])=>!this.RESERVED_PROPERTY_KEYS.has(n)&&!(r.insideItems&&(n===ue||n===at))))}static throwInvalidStorageShape(e,t){const r=this.toPointer(e);throw new Te(K.INVALID_STORAGE_SHAPE,`${t} at ${r}`,[{code:K.INVALID_STORAGE_SHAPE,message:t,locationPath:e}])}static toPointer(e){return e.length===0?"/":`/${e.map(t=>t.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}`}}class rs{static convert(e){const t=Ae.default.decode(e),r=new Uint8Array(2+t.length);r[0]=18,r[1]=32,r.set(t,2);const s=new Uint8Array(2+r.length);return s[0]=1,s[1]=85,s.set(r,2),"b"+new Vr.Encoder({type:"rfc4648",lc:!0}).write(s).finalize().replace(/=/g,"")}}class T{static get(e,t="official"){const{strategy:r}=this.normalizeOptions(t),s=e.getValue(),n=this.handleValue(s);if(n!==void 0&&r==="simple")return n;const o=e.getItems()?.map(_=>T.get(_,r));if(o!==void 0&&r==="simple")return o;const l=e.getName(),a=e.getDescription();if(r==="original"&&l===void 0&&a===void 0){if(n!==void 0)return n;if(o!==void 0)return o}const c={};l!==void 0&&(c[le]=l),a!==void 0&&(c[ae]=a);const p=e.getType();if(r==="official"&&s!==void 0&&p===void 0){const _=this.inferTypeBlueId(s);_!==null&&(c[U]={[V]:_})}else p!==void 0&&(c[U]=T.get(p,r));const f=e.getItemType();f!==void 0&&(c[Be]=T.get(f,r));const y=e.getKeyType();y!==void 0&&(c[Ne]=T.get(y,r));const g=e.getValueType();g!==void 0&&(c[be]=T.get(g,r)),n!==void 0&&(c[W]=n),o!==void 0&&(c[J]=o);const I=e.getBlueId();I!==void 0&&(c[V]=I);const D=e.getBlue();D!==void 0&&(c[_e]=D);const R=e.getProperties();return R!==void 0&&Object.entries(R).forEach(([_,je])=>{c[_]=T.get(je,r)}),c}static handleValue(e){if(E(e)){if(Q(e)){const t=new Z(Number.MIN_SAFE_INTEGER.toString()),r=new Z(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"?te:E(e)?Q(e)?se:re:typeof e=="boolean"?ie:null}static normalizeOptions(e){return typeof e=="string"?{strategy:e}:{strategy:e.strategy??"official"}}}class L{static transform(e,t){const r=t(e.clone()),s=r.getType();s!==void 0&&r.setType(L.transform(s,t));const n=r.getItemType();n!==void 0&&r.setItemType(L.transform(n,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(L.transform(o,t));const l=r.getValueType();l!==void 0&&r.setValueType(L.transform(l,t));const a=r.getItems();if(a!==void 0){const p=a.map(f=>L.transform(f,t));r.setItems(p)}const c=r.getProperties();if(c!==void 0){const p=Object.keys(c).reduce((f,y)=>(f[y]=L.transform(c[y],t),f),{});r.setProperties(p)}return r}}const ce=i=>!!i&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof d),X=i=>i instanceof O||i instanceof $,ss=i=>i.replace(/~1/g,"/").replace(/~0/g,"~");function Pe(i){if(i==="/")return[];if(!i.startsWith("/"))throw new Error(`Path must start with '/': ${i}`);return i.split("/").slice(1).map(ss)}function ve(i){if(i==="-")return-1;const e=typeof i=="number"?i:parseInt(i,10);if(isNaN(e))throw new Error(`Invalid array index (NaN) from '${i}'`);if(!Number.isFinite(e))throw new Error(`Invalid array index '${i}' results in non-finite number ${e}`);return e}function Zt(i,e,t,r=!0){switch(e){case"name":return t?r?i.getName()??null:i:i.getName();case"description":return t?r?i.getDescription():i:i.getDescription();case"type":return i.getType();case"itemType":return i.getItemType();case"keyType":return i.getKeyType();case"valueType":return i.getValueType();case"value":return t?r?i.getValue()??null:i:i.getValue();case"blueId":return t?r?i.getBlueId()??null:i:i.getBlueId();case"blue":return i.getBlue();case"items":return i.getItems();case"properties":return i.getProperties();case B.OBJECT_CONTRACTS:return i.getContracts();default:return}}function Ot(i,e,t=!0){if(i instanceof d){const r=Zt(i,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 n=i.getItems(),o=parseInt(e,10);return n&&o>=0&&o<n.length?n[o]:void 0}const s=i.getProperties();return s&&e in s?s[e]:void 0}if(Array.isArray(i)){if(e==="-")return;const r=ve(e);return r>=0&&r<i.length?i[r]:void 0}if(ce(i))return i[e]}function Se(i,e){if(e.length===0)return{parent:i,key:"value",actualTarget:i.getValue()??i};let t=i;for(let s=0;s<e.length-1;++s){const n=e[s],o=Ot(t,n);if(o===void 0)throw new Error(`Cannot resolve '/${e.slice(0,s+1).join("/")}'`);t=o}const r=e[e.length-1];if(t instanceof d){const s=Ot(t,r,!1);if((typeof s!="object"||s===null||X(s))&&!(s instanceof d)&&!Array.isArray(s)&&["name","description","value","blueId"].includes(r))return{parent:t,key:r,actualTarget:s}}return Array.isArray(t)&&r==="-"?{parent:t,key:"-"}:t instanceof d&&t.getItems()&&r==="-"?{parent:t,key:"-"}:{parent:t,key:Array.isArray(t)?ve(r):r}}function bt(i,e){if(i instanceof d){const t=e,r=Zt(i,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 s=i.getItems(),n=typeof e=="number"?e:parseInt(e,10);if(s&&n>=0&&n<s.length)return s[n]}return i.getProperties()?.[t]}return Array.isArray(i)||ce(i)?i[e]:i}function j(i){if(i instanceof d)return i;if(i===null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"||X(i))return m.deserialize(i);const e=ut(i);return m.deserialize(e)}function ut(i){if(i===void 0)return null;if(i===null||typeof i!="object")return i;if(Array.isArray(i))return i.map(ut);const e={};for(const[t,r]of Object.entries(i))e[t]=ut(r);return e}function Pt(i,e,t){if(i instanceof d){const r=e;switch(r){case"name":i.setName(t);return;case"description":i.setDescription(t);return;case"type":i.setType(t instanceof d||typeof t=="string"||t===void 0?t:j(t));return;case"itemType":i.setItemType(t instanceof d||typeof t=="string"||t===void 0?t:j(t));return;case"keyType":i.setKeyType(t instanceof d||typeof t=="string"||t===void 0?t:j(t));return;case"valueType":i.setValueType(t instanceof d||typeof t=="string"||t===void 0?t:j(t));return;case"value":{const s=t;i.setValue(s===void 0?null:s);return}case"blueId":i.setBlueId(t);return;case"blue":i.setBlue(t instanceof d||t===void 0?t:j(t));return;case"items":i.setItems(t);return;case"properties":i.setProperties(t);return;case B.OBJECT_CONTRACTS:i.setContracts(t);return;default:{if(t===void 0){const s=i.getProperties();s&&r in s&&delete s[r]}else i.getProperties()||i.setProperties({}),i.addProperty(r,t instanceof d?t:j(t));return}}}Array.isArray(i)?i.splice(ve(e),1):ce(i)&&(t===void 0?delete i[e]:i[e]=t)}function is(i,e,t,r){let s=-1;if(e!=="-"&&(s=typeof e=="number"?e:parseInt(e,10),isNaN(s)))throw new Error(`Invalid numeric key for BlueNode item operation: ${e}`);if(s<-1)throw new Error(`Invalid array index for BlueNode items: ${s}`);let n=i.getItems();if(n||(n=[],i.setItems(n)),!r&&s!==-1&&s>n.length)throw new Error(`ADD operation failed: Target array index '${s}' is greater than array length ${n.length}.`);if(e==="-")n.push(t);else if(r){if(s>=0)if(s<n.length)n[s]=t;else{for(let o=n.length;o<s;o++)n.push(m.deserialize(null));n.push(t)}}else n.splice(s,0,t)}function Ye(i,e,t,r){if(Array.isArray(i)){const s=e==="-"?i.length:ve(e);if(!r&&s>i.length)throw new Error(`ADD operation failed: Target array index '${s}' is greater than array length ${i.length}. Path involving key '${e}'.`);if(s<0&&e!=="-")throw new Error(`Invalid negative array index: ${e}`);const n=j(t);if(r){if(s>=0&&s<i.length)i[s]=n;else if(s>=i.length){for(let o=i.length;o<s;o++)i.push(m.deserialize(null));i.push(n)}}else i.splice(s,0,n);return}if(i instanceof d){e==="-"||typeof e=="number"&&!isNaN(e)||typeof e=="string"&&/^\d+$/.test(e)?is(i,e,j(t),r):Pt(i,e,t);return}if(ce(i)){i[e]=j(t);return}throw new Error(`Cannot insert into parent of type ${typeof i}`)}function ns(i,e){if(Array.isArray(i)){const t=ve(e);t===-1&&e==="-"?i.length>0&&i.pop():t>=0&&t<i.length&&i.splice(t,1);return}if(i instanceof d){if(typeof e=="number"||typeof e=="string"&&/^-?\d+$/.test(e)){const t=i.getItems();if(t){const r=ve(e);r===-1&&e==="-"?t.length>0&&t.pop():r>=0&&r<t.length&&t.splice(r,1),t.length===0&&i.setItems(void 0);return}}Pt(i,e,void 0)}else ce(i)&&delete i[e]}function dt(i){if(i instanceof d)return i.clone();if(Array.isArray(i))return i.map(t=>dt(t));if(ce(i)){const e={};return Object.keys(i).forEach(t=>{e[t]=dt(i[t])}),e}return i}function de(i,e){if(i===e||i instanceof d&&(i.isInlineValue()||i.getValue()!==void 0)&&de(i.getValue()??null,e)||e instanceof d&&(e.isInlineValue()||e.getValue()!==void 0)&&de(i,e.getValue()??null))return!0;if(i instanceof d&&e instanceof d||X(i)&&X(e)||X(i)&&typeof e=="number"||typeof i=="number"&&X(e))return i.toString()===e.toString();if(Array.isArray(i)&&Array.isArray(e))return i.length===e.length&&i.every((t,r)=>de(t,e[r]));if(ce(i)&&ce(e)){const t=Object.keys(i),r=Object.keys(e);return t.length===r.length&&t.every(s=>de(i[s],e[s]))}return!1}function Gt(i,e){const{parent:t,key:r}=Se(i,Pe(e));return bt(t,r)}function qt(i,e,t){const r=Pe(e);if(r.length===0&&e==="/"){const o=j(t);i.setValue(o.getValue()??null),o.getItems()?i.setItems(o.getItems()):i.setItems(void 0);return}const{parent:s,key:n}=Se(i,r);Ye(s,n,t,!0)}function os(i,e,t){const r=Pe(e);if(r.length===0&&e==="/"){if(i.getItems()&&Array.isArray(t)){const o=j(t);o.getItems()?(i.setItems(o.getItems()),i.setValue(null)):(i.setValue(o.getValue()??null),i.setItems(void 0))}else{const o=j(t);i.setValue(o.getValue()??null),o.getItems()&&i.setItems(o.getItems())}return!0}const{parent:s,key:n}=Se(i,r);return Ye(s,n,t,!1),!0}function ls(i,e,t){const r=Pe(e);if(r.length===0&&e==="/"){const l=j(t);return i.setValue(l.getValue()??null),l.getItems()?i.setItems(l.getItems()):i.setItems(void 0),!0}const{parent:s,key:n,actualTarget:o}=Se(i,r);if(o!==void 0&&s instanceof d)Pt(s,n,t);else{const l=bt(s,n),a=Array.isArray(s)||s instanceof d&&s.getItems()&&(typeof n=="number"||typeof n=="string"&&/^\d+$/.test(n));if(l===void 0){if(a)throw new Error(`REPLACE failed: Target array index '${n.toString()}' is out of bounds or does not exist at path '${e}'.`);Ye(s,n,t,!0)}else Ye(s,n,t,!0)}return!0}function Xt(i,e){const t=Pe(e);if(t.length===0&&e==="/")return i.setValue(null),i.setItems(void 0),i.setProperties(void 0),!0;const{parent:r,key:s}=Se(i,t);return ns(r,s),!0}function as(i,e,t){const r=dt(Gt(i,e));return qt(i,t,r),!0}function cs(i,e,t){const r=Pe(e),{parent:s,key:n}=Se(i,r),o=bt(s,n);if(o===void 0)throw new Error(`MOVE failed: 'from' location '${e}' does not exist.`);return Xt(i,e)?(qt(i,t,o),!0):!1}function us(i,e,t){const r=Gt(i,e);let s=t;if(r instanceof d)if((t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||X(t))&&(r.isInlineValue()||r.getValue()!==void 0)){if(!de(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)&&(s=j(t));else if(X(r)&&typeof t=="number")r instanceof O?s=new O(t.toString()):r instanceof $&&(s=new $(t.toString()));else if((r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&X(t)){const n=t;!de(r,n.toString())&&(typeof r=="number"&&parseFloat(n.toString()))}if(!de(r,s)){const n=r instanceof d?r.toString():JSON.stringify(r),o=s instanceof d?s.toString():JSON.stringify(s);throw new Error(`TEST failed at '${e}': Expected ${o}, got ${n}`)}return!0}function ds(i,e){switch(e.op){case"add":return os(i,e.path,e.val);case"replace":return ls(i,e.path,e.val);case"remove":return Xt(i,e.path);case"copy":return as(i,e.from,e.path);case"move":return cs(i,e.from,e.path);case"test":return us(i,e.path,e.val)}}function hs(i,e,t=!1){const r=t?i:i.clone();return ds(r,e),r}const nt=Symbol.for("zod-schema-annotations");function ps(){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 Qt(){const i=ps();return nt in i||(i[nt]=new WeakMap),i[nt]}function $e(i,e){const t=Qt(),r=t.get(i)||{};return t.set(i,{...r,...e}),i}const G=i=>Qt().get(i),er=i=>e=>{const t=G(e);return $e(e,{...t,blueDescription:i})},tr=i=>{const e=G(i);return u.isNonNullable(e)&&H.isString(e.blueDescription)?e.blueDescription:null},fs=i=>er(i)(h.z.string().optional()),ys=h.z.union([h.z.string(),h.z.boolean()]),rr=i=>e=>{const t=G(e);return $e(e,{...t,blueId:i})},sr=i=>{const e=G(i),t=ys.safeParse(e?.blueId);return t.success?t.data:null},gs=i=>rr(i??!0)(h.z.string()),ir=i=>e=>{const t=G(e);return $e(e,{...t,blueName:i})},nr=i=>{const e=G(i);return u.isNonNullable(e)&&H.isString(e.blueName)?e.blueName:null},ms=i=>{const e=h.z.string().optional();return ir(i)(e)},or=()=>i=>{const e=G(i);return $e(i,{...e,blueNode:!0})},lr=i=>{const e=G(i);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},St=i=>!!lr(i),Is=()=>{const i=h.z.instanceof(d);return or()(i)},Ts=h.z.object({value:h.z.array(h.z.string()).optional(),defaultValue:h.z.string().optional()}),ar=i=>{const e=G(i),t=Ts.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},vs=i=>e=>{const t=G(e),r=typeof i=="string"?{value:[i]}:i;return $e(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class Ve{static resolveBlueId(e){const t=ar(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const s=t.value?.[0];return u.isNonNullable(s)?s:Ve.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}class z{static isTypeOf(e,t,r){const s=Ve.resolveBlueId(t),n=e.getType()?.getBlueId();if(u.isNullable(s)||u.isNullable(n))return!1;const o=r?.blueIdMapper?.toCurrentBlueId(s)??s,l=r?.blueIdMapper?.toCurrentBlueId(n)??n;if(o===l)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const a=r.typeSchemaResolver.resolveSchema(e);return z.checkSchemaExtension(a,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const s=z.unwrapSchema(e),n=z.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(s,n):!1}static isWrapperType(e){return e instanceof h.ZodOptional||e instanceof h.ZodNullable||e instanceof h.ZodReadonly||e instanceof h.ZodBranded||e instanceof h.ZodEffects||e instanceof h.ZodLazy}static unwrapSchema(e){return St(e)?e:z.isWrapperType(e)?e instanceof h.ZodEffects?z.unwrapSchema(e.innerType()):e instanceof h.ZodLazy?z.unwrapSchema(e.schema):z.unwrapSchema(e.unwrap()):e}}const cr=Symbol("blue.subtypeCache");function Bs(i,e){return i[cr]=e,i}function Vt(i,e){const t=i.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(pe.includes(r)){const n=Ge[r];return new d().setBlueId(r).setName(n)}const s=e.fetchByBlueId(r);if(!s||s.length===0)return;if(s.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return s[0].cloneShallow().setBlueId(r)}return t}function w(i,e,t){const r=ke(i),s=ke(e),n=t[cr],o=`${r}|${s}`,l=n?.get(o);if(l!==void 0)return l;const a=Ns(i,e,t,r,s);return n?.set(o,a),a}function ke(i){const e=i.getReferenceBlueId();return e!==void 0?e:A.calculateBlueIdSync(ne(i))}function ne(i){if(!ur(i))return i;const e=i.cloneShallow();e.getReferenceBlueId()!==void 0&&!N.hasBlueIdOnly(e)&&e.setReferenceBlueId(void 0);const t=e.getType();t!==void 0&&e.setType(ne(t));const r=e.getItemType();r!==void 0&&e.setItemType(ne(r));const s=e.getKeyType();s!==void 0&&e.setKeyType(ne(s));const n=e.getValueType();n!==void 0&&e.setValueType(ne(n));const o=e.getBlue();o!==void 0&&e.setBlue(ne(o));const l=e.getItems();l!==void 0&&e.setItems(l.map(c=>ne(c)));const a=e.getProperties();return a!==void 0&&e.setProperties(Object.fromEntries(Object.entries(a).map(([c,p])=>[c,ne(p)]))),e}function ur(i){return i.getReferenceBlueId()!==void 0&&!N.hasBlueIdOnly(i)?!0:[i.getType(),i.getItemType(),i.getKeyType(),i.getValueType(),i.getBlue(),...i.getItems()??[],...Object.values(i.getProperties()??{})].some(t=>t!==void 0&&ur(t))}function Ns(i,e,t,r,s){if(r===s)return!0;if(r&&pe.includes(r)){let a=e;for(;a!==void 0;){if(ke(a)===r)return!0;a=Vt(a,t)}return!1}let n=i;const o=i.getBlueId();if(o){const a=t.fetchByBlueId(o);a&&a.length===1&&(n=a[0])}let l=n;for(;l!==void 0;){if(ke(l)===s)return!0;l=Vt(l,t)}return!1}function bs(i,e){return Tt.some(t=>{const r=new d().setBlueId(t);return w(i,r,e)})}function Ps(i,e){const t=new d().setBlueId(te);return w(i,t,e)}function Ss(i,e){const t=new d().setBlueId(se);return w(i,t,e)}function ws(i,e){const t=new d().setBlueId(re);return w(i,t,e)}function Es(i,e){const t=new d().setBlueId(ie);return w(i,t,e)}function ze(i,e){const t=new d().setBlueId(Ze);return w(i,t,e)}function Ue(i,e){const t=new d().setBlueId(It);return w(i,t,e)}function Cs(i,e){return We.some(t=>{const r=new d().setName(t);return w(i,r,e)})}function Rs(i,e){for(const t of We){const r=new d().setName(t);if(w(i,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${i.getName()||"unknown"}".`)}class dr{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=Ve.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),s=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(s))return!1;if(r===s)return!0;if(u.isNonNullable(this.nodeProvider))try{const n=new d().setBlueId(r),o=new d().setBlueId(s);if(w(n,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=Ve.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,s]of this.blueIdMap)if(s===e||s._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)?A.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}class qe{}class we{static convert(e){const t=new ht;return we.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const s=e.getProperties(),n=e.getItems(),o=s!==void 0&&Object.keys(s).length>0,l=n!==void 0&&n.length>0;if(!o&&!l){r.addPath(t===""?"/":t);return}if(s)for(const[a,c]of Object.entries(s)){const p=`${t}/${a}`;we.traverseNode(c,p,r)}if(n)for(let a=0;a<n.length;a++){const c=`${t}/${a}`;we.traverseNode(n[a],c,r)}}}function Mt(i,e){const t=i.split(e),r=[...t].reverse().findIndex(n=>n!==""),s=r===-1?0:t.length-r;return t.slice(0,s)}class Xe extends qe{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=Mt(e,"/"),s=Mt(t,"/");if(s.length>r.length)return!1;for(let n=1;n<s.length;n++)if(r[n]!=="*"&&r[n]!==s[n])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 ht().setMaxDepth(e);for(let r=1;r<=e;r++){const s="/"+Array(r).fill("*").join("/");t.addPath(s)}return t.build()}static withSinglePath(e){return new ht().addPath(e).build()}static fromNode(e){return we.convert(e)}}class ht{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 Xe(this.allowedPaths,this.maxDepth)}}class k extends qe{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class Qe extends qe{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 Qe(e)}}const x=new k;class Y extends d{completeness;sourceSemanticBlueId;constructor(e,t={}){super(e.getName()),this.completeness=t.completeness??"full",this.sourceSemanticBlueId=this.validateSourceSemanticBlueId(t.sourceSemanticBlueId),this.createFrom(e)}isResolved(){return!0}getMinimalNode(){if(this.completeness==="path-limited"){if(this.sourceSemanticBlueId!==void 0)return new d().setReferenceBlueId(this.sourceSemanticBlueId);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return new ct().minimizeResolved(this)}getMinimalBlueId(){if(this.completeness==="path-limited"){if(this.sourceSemanticBlueId!==void 0)return this.sourceSemanticBlueId;throw new Error("Cannot calculate minimal BlueId for a path-limited resolved node without a source semantic BlueId.")}const t=new ct().minimizeResolvedForHash(this);return A.calculateBlueIdSync(t)}clone(){const e=super.clone();return new Y(e,this.getMetadata())}cloneShallow(){const e=super.cloneShallow();return new Y(e,this.getMetadata())}getCompleteness(){return this.completeness}getSourceSemanticBlueId(){return this.sourceSemanticBlueId}setSourceSemanticBlueId(e){return this.sourceSemanticBlueId=this.validateSourceSemanticBlueId(e),this}validateSourceSemanticBlueId(e){if(e!==void 0){if(!me.isPotentialBlueId(e))throw new Error("sourceSemanticBlueId must be a valid BlueId.");return e}}getMetadata(){return{completeness:this.completeness,sourceSemanticBlueId:this.sourceSemanticBlueId}}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 As{blue;constructor(e){this.blue=e}matchesType(e,t,r=x){const s=Xe.fromNode(t),n=Qe.of(r,s);let o,l;try{o=this.extendAndResolve(e,n),l=this.blue.resolve(t,n)}catch{return!1}const a=this.expandSchemaOwnedTypeReferences(t);return this.recursiveValueComparison(o,l,a,n)?this.verifyMatch(o,t,n)||t.getType()===void 0:!1}extendAndResolve(e,t){const r=e.clone(),s=r.clone();this.blue.extend(s,t);const n=this.blue.resolve(s,t);return this.restoreMissingStructure(n,r),n}restoreMissingStructure(e,t){const r=t.getItems(),s=e.getItems();if(r&&r.length>0)if(!s||s.length===0)e.setItems(r.map(a=>a.clone()));else for(let a=0;a<Math.min(s.length,r.length);a++)this.restoreMissingStructure(s[a],r[a]);const n=t.getProperties();if(n){let a=e.getProperties();a||(a={},e.setProperties(a));for(const[c,p]of Object.entries(n)){const f=a[c];f===void 0?a[c]=p.clone():this.restoreMissingStructure(f,p)}}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 s=t.getType();if(this.matchesImplicitStructure(e,s))return!0;const n=e.clone().setType(t.clone());try{this.blue.resolve(n,r)}catch{return!1}return!0}recursiveValueComparison(e,t,r=t,s=x,n={}){const o=t.getType(),l=this.matchesImplicitStructure(e,o)||this.matchesImplicitCoreCollectionType(e,t);if(e.getType()===void 0&&this.isCoreCollectionType(t)&&!l)return!1;if(o&&!l){const b=e.getType();if(!b||!w(b,o,this.blue.getNodeProvider()))return!1}const a=t.getBlueId();if(!l&&a!==void 0)if(this.isExplicitBlueIdMatcher(r)){if(n.bareBlueIdMatcherMode==="type-reference"){if(!this.matchesBareBlueIdTypeReference(e,t,a))return!1}else if(!this.matchesBareBlueIdIdentity(e,a))return!1}else{const b=e.getBlueId(),P=e.getType();if(P===void 0&&b!==void 0&&b!==a||P&&!w(P,t,this.blue.getNodeProvider()))return!1}const c=e.getBlueId();if(!l&&a===void 0&&c!==void 0&&e.getType()===void 0&&t.getItems()===void 0&&this.hasMatcherShape(t)&&!this.matchesCalculatedBlueId(t,c))return!1;const p=t.getValue();if(p!==void 0){const b=e.getValue();if(b===void 0)return!1;if(E(b)&&E(p)){if(!b.eq(p))return!1}else if(b!==p)return!1}const f=t.getItems(),y=r.getItems();if(f!==void 0){const b=e.getItems()??[];for(let P=0;P<f.length;P++)if(P<b.length){if(!this.recursiveValueComparison(b[P],f[P],y?.[P]??f[P],s))return!1}else if(this.hasValueInNestedStructure(f[P]))return!1}const g=t.getItemType(),I=r.getItemType();if(g!==void 0){const b=e.getItems()??[];for(const P of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(P,g,I??g,s,"type-reference"),g,I??g,s,{bareBlueIdMatcherMode:"type-reference"}))return!1}const D=t.getProperties(),R=r.getProperties();if(D!==void 0){const b=e.getProperties()??{};for(const[P,tt]of Object.entries(D))if(P in b){if(!this.recursiveValueComparison(b[P],tt,R?.[P]??tt,s))return!1}else if(this.hasValueInNestedStructure(tt))return!1}const _=t.getValueType(),je=r.getValueType();if(_!==void 0){const b=Object.values(e.getProperties()??{});for(const P of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(P,_,je??_,s,"type-reference"),_,je??_,s,{bareBlueIdMatcherMode:"type-reference"}))return!1}return!0}resolveUntypedNodeAgainstMatcherType(e,t,r,s,n="identity"){return e.getType()!==void 0||e.getBlueId()!==void 0||n==="identity"&&this.isExplicitBlueIdMatcher(r)?e:this.resolveAgainstTargetType(e,t,s)??e}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const s of t)if(this.hasValueInNestedStructure(s))return!0}const r=e.getProperties();if(r!==void 0){for(const s of Object.values(r))if(this.hasValueInNestedStructure(s))return!0}return!1}hasMatcherShape(e){return e.getValue()!==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}matchesCalculatedBlueId(e,t){if(e instanceof Y&&e.getCompleteness()==="path-limited"&&e.getSourceSemanticBlueId()!==void 0)return e.getSourceSemanticBlueId()===t;try{return this.blue.calculateBlueIdSync(e)===t}catch{try{return this.blue.calculateBlueIdSync(this.toPlainBlueNode(e))===t}catch{return!1}}}matchesBareBlueIdIdentity(e,t){return e.getBlueId()===t||this.matchesCalculatedBlueId(e,t)}matchesBareBlueIdTypeReference(e,t,r){const s=e.getType();return s?w(s,t,this.blue.getNodeProvider()):e.getBlueId()!==void 0?this.matchesBareBlueIdIdentity(e,r):!1}toPlainBlueNode(e){const t=new d(e.getName());t.setDescription(e.getDescription()).setReferenceBlueId(e.getReferenceBlueId()).setInlineValue(e.isInlineValue());const r=e.getValue();r!==void 0&&t.setValue(r);const s=e.getType();s!==void 0&&t.setType(this.toPlainBlueNode(s));const n=e.getItemType();n!==void 0&&t.setItemType(this.toPlainBlueNode(n));const o=e.getKeyType();o!==void 0&&t.setKeyType(this.toPlainBlueNode(o));const l=e.getValueType();l!==void 0&&t.setValueType(this.toPlainBlueNode(l));const a=e.getItems();a!==void 0&&t.setItems(a.map(f=>this.toPlainBlueNode(f)));const c=e.getProperties();c!==void 0&&t.setProperties(Object.fromEntries(Object.entries(c).map(([f,y])=>[f,this.toPlainBlueNode(y)])));const p=e.getBlue();return p!==void 0&&t.setBlue(this.toPlainBlueNode(p)),t}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:ze(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ue(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}matchesImplicitCoreCollectionType(e,t){return e.getType()!==void 0?!1:ze(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ue(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isCoreCollectionType(e){return ze(e,this.blue.getNodeProvider())||Ue(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 s=e.clone(),n=s.clone().setType(t.clone()),o=this.blue.resolve(n,r);return this.restoreMissingStructure(o,s),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()),s=e.getType();s&&e.setType(this.expandReferencedTypeNode(s,r));const n=e.getItemType();n&&e.setItemType(this.expandReferencedTypeNode(n,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(p=>this.expandSchemaTypeReferences(p,r)));const c=e.getProperties();return c&&e.setProperties(Object.fromEntries(Object.entries(c).map(([p,f])=>[p,this.expandSchemaTypeReferences(f,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 s=this.blue.getNodeProvider().fetchByBlueId(r);return!s||s.length!==1?e.clone():this.expandSchemaTypeReferences(s[0].clone(),t)}withVisitedBlueId(e,t){if(!t||e.has(t))return e;const r=new Set(e);return r.add(t),r}}class M{static ZERO_BLUE_ID="0".repeat(44);static THIS_INDEX_REFERENCE_PATTERN=/^this#(\d+)$/;prepareDocument;calculateBlueId;constructor(e={}){this.prepareDocument=e.prepareDocument??(t=>t),this.calculateBlueId=e.calculateBlueId??A.calculateBlueIdSync}static hasThisReference(e){return e.some(t=>this.nodeHasThisReference(t))}static hasIndexedThisReference(e){return e.some(t=>this.nodeHasIndexedThisReference(t))}static isIndexedThisReference(e){return this.THIS_INDEX_REFERENCE_PATTERN.test(e)}calculate(e){this.validateCyclicSet(e);const t=e.map((l,a)=>{const c=this.prepareDocument(this.replaceIndexedThisReferences(l,()=>M.ZERO_BLUE_ID));return{originalIndex:a,preliminaryBlueId:this.calculateBlueId(c),node:l}});this.validateUniquePreliminaryBlueIds(t);const r=[...t].sort(this.comparePreliminaryDocuments),s=[];r.forEach(({originalIndex:l},a)=>{s[l]=a});const n=r.map(({node:l})=>this.prepareDocument(this.replaceIndexedThisReferences(l,a=>`this#${s[a]}`))),o=this.calculateBlueId(n);return{blueId:o,nodes:n,documentBlueIds:n.map((l,a)=>`${o}#${a}`),originalToSortedIndexes:s}}comparePreliminaryDocuments(e,t){return e.preliminaryBlueId<t.preliminaryBlueId?-1:e.preliminaryBlueId>t.preliminaryBlueId?1:0}validateUniquePreliminaryBlueIds(e){const t=new Map;for(const r of e){const s=t.get(r.preliminaryBlueId);if(s!==void 0)throw new Error(`Direct cyclic document set has ambiguous canonical ordering: documents ${s} and ${r.originalIndex} share preliminary BlueId '${r.preliminaryBlueId}'.`);t.set(r.preliminaryBlueId,r.originalIndex)}}validateCyclicSet(e){if(e.length===0)throw new Error("Cyclic document set cannot be empty.");this.visitReferences(e,(t,r)=>{if(r==="this")throw new Error("Direct cyclic document sets must use indexed references such as 'this#0'; unindexed 'this' is not supported.");if(r.startsWith("this#")&&!M.THIS_INDEX_REFERENCE_PATTERN.test(r))throw new Error(`Malformed direct cyclic reference '${r}'. Expected 'this#<non-negative-integer>'.`);const s=this.readIndexedThisReference(r);if(s!==void 0&&s>=e.length)throw new Error(`Direct cyclic reference '${r}' points outside the ${e.length}-document set.`)})}replaceIndexedThisReferences(e,t){const r=e.clone();return this.rewriteIndexedThisReferences(r,t),r}rewriteIndexedThisReferences(e,t){const r=e.getReferenceBlueId();if(r!==void 0){const s=this.readIndexedThisReference(r);s!==void 0&&e.setReferenceBlueId(t(s))}this.childrenOf(e).forEach(s=>this.rewriteIndexedThisReferences(s,t))}static nodeHasThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,s)=>{(s==="this"||s.startsWith("this#"))&&(t=!0)}),t}static nodeHasIndexedThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,s)=>{M.THIS_INDEX_REFERENCE_PATTERN.test(s)&&(t=!0)}),t}visitReferences(e,t){e.forEach(r=>M.visitNodeReferences(r,t))}static visitNodeReferences(e,t){const r=e.getReferenceBlueId();r!==void 0&&t(e,r),this.childrenOf(e).forEach(s=>this.visitNodeReferences(s,t))}readIndexedThisReference(e){const t=e.match(M.THIS_INDEX_REFERENCE_PATTERN);if(t!==null)return Number(t[1])}childrenOf(e){return M.childrenOf(e)}static childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}class fe{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function et(i){return new class extends fe{fetchByBlueId(e){return i(e)}}}class hr{resolveWithoutLimits(e){return this.resolve(e,x)}}class pr extends fe{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 ot=he.types.float.options,Os={...ot,construct:i=>{const e=i.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new $(e);if(ot.construct)return ot.construct(i)}},Vs=new he.Type("tag:yaml.org,2002:float",Os),lt=he.types.int.options,Ms={...lt,construct:i=>{let e=i;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new O(e);if(lt.construct)return lt.construct(i)}},Ds=new he.Type("tag:yaml.org,2002:int",Ms),fr=he.CORE_SCHEMA.extend({implicit:[Vs,Ds]}),ee=i=>{const e=he.load(i,{schema:fr});return e===void 0?void 0:e},yr=i=>he.dump(i,{schema:fr,replacer:(e,t)=>{if(E(t)){if(Q(t)){const r=new Z(Number.MIN_SAFE_INTEGER.toString()),s=new Z(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(s))return t.toString()}return t.toNumber()}return t}}),gr=`- 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
|
+
`,_s=`name: Transformation
|
|
13
|
+
description: TODO`,Ls=`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.`,$s=`name: Replace Inline Types with BlueIds
|
|
17
17
|
type:
|
|
18
18
|
blueId: Ct1SGRGw1i47qjzm1ruiUdSZofeV6WevPTGuieVvbRS4
|
|
19
|
-
description: This transformation replaces`,Hs=[Br,zs,Us,Ks];class ks extends ye{blueIdToNodesMap=new Map;constructor(){super(),this.load()}fetchByBlueId(e){return this.blueIdToNodesMap.get(e)||[]}load(){for(const e of Hs){const t=ee(e);if(t===void 0){console.error(`This content file is not valid YAML: ${e}`);continue}if(Array.isArray(t)){const r=t.map(n=>m.deserialize(n)),s=A.calculateBlueIdSync(r);this.blueIdToNodesMap.set(s,r)}else{const r=m.deserialize(t),s=A.calculateBlueIdSync(r);this.blueIdToNodesMap.set(s,[r])}}}}class At extends ye{static INSTANCE=new At;nodeProvider;constructor(){super(),this.nodeProvider=new ks}fetchByBlueId(e){return this.nodeProvider.fetchByBlueId(e)}}class _e{static wrap(e){const t=[At.INSTANCE];return t.push(e),new Ir(t)}}class Ot{nodeProvider;strategy;constructor(e,t){this.nodeProvider=_e.wrap(e),this.strategy=t||"THROW_EXCEPTION"}extend(e,t){this.extendNode(e,t,"")}extendNode(e,t,r,s=!1){if(!s){if(!t.shouldExtendPathSegment(r,e))return;t.enterPathSegment(r,e)}try{const n=e.getBlueId();if(n&&P.hasBlueIdOnly(e)&&!fe.includes(n)){const y=this.fetchNode(e);if(y&&y.length>0){const g=this.shouldPreserveReferenceBlueId(r,s);if(y.length===1){const I=y[0];this.mergeNodes(e,I,g)}else{const I=y.map(b=>b.clone()),L=new d().setItems(I);this.mergeNodes(e,L,g)}}}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 c=e.getValueType();c&&this.extendNode(c,t,"valueType",!0);const p=e.getProperties();p&&Object.entries(p).forEach(([y,g])=>{this.extendNode(g,t,y,!1)});const f=e.getItems();if(f&&f.length>0)for(let y=0;y<f.length;y++)this.extendNode(f[y],t,String(y),!1)}finally{s||t.exitPathSegment()}}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}shouldPreserveReferenceBlueId(e,t){return t&&["type","itemType","keyType","valueType"].includes(e)}mergeNodes(e,t,r){r||e.setReferenceBlueId(void 0),e.setName(t.getName()),e.setDescription(t.getDescription()),e.setType(t.getType()?.clone()),e.setItemType(t.getItemType()?.clone()),e.setKeyType(t.getKeyType()?.clone()),e.setValueType(t.getValueType()?.clone());const s=t.getValue();u.isNonNullable(s)&&e.setValue(s),e.setItems(t.getItems()?.map(o=>o.clone()));const n=t.getProperties();e.setProperties(n===void 0?void 0:Object.fromEntries(Object.entries(n).map(([o,l])=>[o,l.clone()]))),e.setBlue(t.getBlue()?.clone())}}class oe extends mr{mergingProcessor;nodeProvider;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProvider=_e.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 s=e;const n=t.getType();if(u.isNonNullable(n)){const o=this.resolveTypeNode(n,r),l=this.getTypeOverlay(n,o,r);s=this.mergeObject(s,l,r);const a=t.cloneShallow().setType(o.clone());return this.mergeObject(s,a,r)}return this.mergeObject(s,t,r)}mergeObject(e,t,r){const s=e.cloneShallow();let n=this.mergingProcessor.process(s,t,r.nodeProvider);const o=t.getItems();u.isNonNullable(o)&&(n=this.mergeChildren(n,t,r));const l=t.getProperties();return u.isNonNullable(l)&&(n=this.mergeProperties(n,t,l,r)),u.isNonNullable(t.getBlueId())&&(n=n.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(n=this.mergingProcessor.postProcess(n,t,r.nodeProvider)),n}mergeChildren(e,t,r){const s=t.getItems()??[];return v.hasListControlItems(s)?this.mergeChildrenWithListControls(e,t,r):this.mergeChildrenWithoutListControls(e,s,r)}mergeChildrenWithoutListControls(e,t,r){const s=e.getItems();if(u.isNullable(s)){const o=[];for(let l=0;l<t.length;l++){const a=t[l];if(r.limits.shouldMergePathSegment(String(l),a)){this.enterPathSegment(r,String(l),a);try{const c=this.materializeForCurrentContext(a,r);o.push(c)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(o)}if(t.length<s.length)throw new Error(`Subtype of element must not have more items (${s.length}) than the element itself (${t.length}).`);const n=[...s];for(let o=0;o<t.length;o++)if(r.limits.shouldMergePathSegment(String(o),t[o])){this.enterPathSegment(r,String(o),t[o]);try{if(o>=n.length){const p=this.materializeForCurrentContext(t[o],r);n.push(p);continue}const l=r.limits instanceof Y?t[o]:this.materializeForCurrentContext(t[o],r),a=this.calculateNodeBlueId(l,r),c=this.calculateNodeBlueId(n[o],r);if(a!==c)throw new Error(`Mismatched items at index ${o}: source item has blueId '${a}', but target item has blueId '${c}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(n)}mergeChildrenWithListControls(e,t,r){const s=t.getItems()??[],n=e.getItems()??[],o=v.getMergePolicy(t,e),l=[...n];let a=0,c=!1;const p=s[0];if(p!==void 0&&v.hasPreviousProperty(p)){if(v.getPreviousBlueId(p)===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");c=!0,a=1}const f=c&&n.length===0&&!(r.limits instanceof Y),y=new Set;for(;a<s.length;a++){const g=s[a];if(v.hasPreviousProperty(g))throw new Error("$previous list control is allowed only as the first item.");const I=v.readPosition(g);if(I!==void 0){if(o==="append-only")throw new Error("$pos is not allowed in append-only lists.");if(I>=n.length)throw new Error(`$pos ${I} is out of range for inherited list length ${n.length}.`);if(y.has(I))throw new Error(`Duplicate $pos list overlay for index ${I}.`);y.add(I);const b=v.withoutPosition(g);if(!v.hasPayloadAfterRemovingPosition(g))throw new Error("$pos list control must include an item payload.");if(!r.limits.shouldMergePathSegment(String(I),b))continue;this.enterPathSegment(r,String(I),b);try{const F=l[I];l[I]=F===void 0||v.isReplacementPayload(b)?this.materializeForCurrentContext(b,r):this.mergeWithContext(F,b,r)}finally{this.exitPathSegment(r)}continue}const L=l.length;if(!(!f&&!r.limits.shouldMergePathSegment(String(L),g))){if(f){l.push(this.materializeWithoutLimits(g,r));continue}this.enterPathSegment(r,String(L),g);try{const b=this.materializeForCurrentContext(g,r);l.push(b)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}materializeWithoutLimits(e,t){return new oe(this.mergingProcessor,t.nodeProvider).resolve(e,$)}mergeProperties(e,t,r,s){const n=e.getProperties()??{};let o=n,l=!1;for(const[a,c]of Object.entries(r))if(s.limits.shouldMergePathSegment(a,c)){this.enterPathSegment(s,a,c);try{const p=o[a],f=this.getPathLimitedListControlTarget(p,t,a,c,s),y=f??p,I=this.shouldMergePropertyWithoutPreResolve(y,c,s)?this.mergeExistingProperty(y,c,s):(()=>{const b=this.materializeForCurrentContext(c,s);return y===void 0?b:this.mergeObject(y,b,s)})(),L=f===void 0?I:this.projectListNodeToCurrentLimits(I,s);L!==p&&(l||(o={...n},l=!0),o[a]=L)}finally{this.exitPathSegment(s)}}return l?e.cloneShallow().setProperties(o):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof Y?u.isNonNullable(e)&&v.hasListControlItems(t.getItems()):u.isNonNullable(t.getItems())||u.isNonNullable(e.getItems())}mergeExistingProperty(e,t,r){if(e===void 0)throw new Error("Cannot merge property without an existing target.");return this.mergeWithContext(e,t,r)}resolve(e,t){return this.resolveWithContext(e,this.createResolutionContext(t))}resolveWithContext(e,t){const r=new d,n=this.mergeWithContext(r,e,t).cloneShallow().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new k(n,{completeness:t.limits instanceof Y?"full":"path-limited"})}createResolutionContext(e){const t=new Map,r=new Map,s=Es(this.createResolutionNodeProvider(this.nodeProvider,t),r);return{limits:e,nodeProvider:s,resolvedTypeCache:new Map,resolvingTypeKeys:new Set,resolvingTypeBlueIds:new Set,typeOverlayCache:new Map,nodeHashCache:new WeakMap,providerFetchCache:t,subtypeCache:r,pathStack:[]}}resolveTypeNode(e,t){const r=e.getBlueId();if(u.isNonNullable(r)){const s=this.createResolvedTypeCacheKey(r,t),n=t.resolvedTypeCache.get(s);if(u.isNonNullable(n)&&!t.resolvingTypeKeys.has(s))return n;if(t.resolvingTypeBlueIds.has(r))return n??this.createCyclicTypeReference(r,t);const o=this.createCyclicTypeReference(r,t);t.resolvedTypeCache.set(s,o),t.resolvingTypeKeys.add(s),t.resolvingTypeBlueIds.add(r);try{const l=this.resolveAndExtendTypeNode(e,t);return l.setReferenceBlueId(r),t.resolvedTypeCache.set(s,l),l}catch(l){throw t.resolvedTypeCache.delete(s),l}finally{t.resolvingTypeKeys.delete(s),t.resolvingTypeBlueIds.delete(r)}}return this.resolveAndExtendTypeNode(e,t)}createCyclicTypeReference(e,t){return new k(new d().setReferenceBlueId(e),{completeness:t.limits instanceof Y?"full":"path-limited"})}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new Ot(t.nodeProvider).extend(r,et.withSinglePath("/")),this.resolveWithContext(r,t)}getTypeOverlay(e,t,r){const s=e.getBlueId();if(u.isNullable(s))return this.createTypeOverlay(t);const n=this.createResolvedTypeCacheKey(s,r),o=r.typeOverlayCache.get(n);if(u.isNonNullable(o))return o;const l=this.createTypeOverlay(t);return r.resolvingTypeBlueIds.has(s)||r.typeOverlayCache.set(n,l),l}createTypeOverlay(e){return e.cloneShallow().setType(void 0).setBlueId(void 0)}createResolvedTypeCacheKey(e,t){return t.limits instanceof Y?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 Y}calculateNodeBlueId(e,t){const r=t.nodeHashCache.get(e);if(u.isNonNullable(r))return r;const s=z.calculateHashMinimalBlueId(e);return t.nodeHashCache.set(e,s),s}getPathLimitedListControlTarget(e,t,r,s,n){if(!(e===void 0||n.limits instanceof Y||!v.hasListControlItems(s.getItems())))return this.resolveFullInheritedProperty(t,r,n)}resolveFullInheritedProperty(e,t,r){const s=e.getType();if(s===void 0)return;const n=s.getBlueId();if(u.isNonNullable(n)){const a=r.nodeProvider.fetchByBlueId(n)?.[0];return a===void 0?void 0:new oe(this.mergingProcessor,r.nodeProvider).resolve(a,$).getProperties()?.[t]?.clone()}return new oe(this.mergingProcessor,r.nodeProvider).resolve(s,$).getProperties()?.[t]?.clone()}projectListNodeToCurrentLimits(e,t){const r=e.getItems();return r===void 0?e:e.cloneShallow().setItems(r.filter((s,n)=>t.limits.shouldMergePathSegment(String(n),s)))}createResolutionNodeProvider(e,t){return new class extends ye{fetchByBlueId(r){if(t.has(r))return t.get(r)??null;const s=e.fetchByBlueId(r);return t.set(r,s),s}}}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 Nr{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((s,n)=>n.process(s,t,r),e)}postProcess(e,t,r){return this.mergingProcessors.reduce((s,n)=>n.postProcess?n.postProcess(s,t,r):s,e)}}class br{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const s=e.getValue();if(u.isNullable(s))return e.cloneShallow().setValue(r);if(!Ys(r,s))throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${s}`)}return e}}const Ys=(i,e)=>Q(i)&&Q(e)||He(i)&&He(e)?i.eq(e):i===e;class Pr{process(e,t,r){const s=e.getType(),n=t.getType();let o=e;if(s===void 0)o=e.cloneShallow().setType(n);else if(n!==void 0){if(!C(n,s,r)){const a=T.get(n),c=T.get(s);throw new Error(`The source type '${JSON.stringify(a)}' is not a subtype of the target type '${JSON.stringify(c)}'.`)}o=e.cloneShallow().setType(n)}return o}}class Sr{process(e,t,r){const s=t.getItemType(),n=t.getType();if(s!==void 0&&n!==void 0&&!Ue(n,r))throw new Error("Source node with itemType must have a List type");const o=e.getItemType();let l=e;if(o===void 0)s!==void 0&&(l=e.cloneShallow().setItemType(s));else if(s!==void 0){if(!C(s,o,r)){const f=T.get(s),y=T.get(o);throw new Error(`The source item type '${JSON.stringify(f)}' is not a subtype of the target item type '${JSON.stringify(y)}'.`)}l=e.cloneShallow().setItemType(s)}const a=l.getItemType(),c=t.getItems();if(a!==void 0&&c!==void 0)for(const p of c){const f=p.getType();if(f!==void 0&&!C(f,a,r)){const y=T.get(f),g=T.get(a);throw new Error(`Item of type '${JSON.stringify(y)}' is not a subtype of the list's item type '${JSON.stringify(g)}'.`)}}return l}}class wr{process(e,t,r){const s=t.getKeyType(),n=t.getValueType(),o=t.getType();if((s!==void 0||n!==void 0)&&o!==void 0&&!Ke(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(),c=l.getValueType(),p=t.getProperties();return(a!==void 0||c!==void 0)&&p!==void 0&&Object.entries(p).forEach(([f,y])=>{a!==void 0&&this.validateKeyType(f,a,r),c!==void 0&&this.validateValueType(y,c,r)}),l}processKeyType(e,t,r){const s=e.getKeyType(),n=t.getKeyType();if(s===void 0){if(n!==void 0)return this.validateBasicKeyType(n,r),e.cloneShallow().setKeyType(n)}else if(n!==void 0){if(this.validateBasicKeyType(n,r),!C(n,s,r)){const l=T.get(n),a=T.get(s);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(n)}return e}processValueType(e,t,r){const s=e.getValueType(),n=t.getValueType();if(s===void 0){if(n!==void 0)return e.cloneShallow().setValueType(n)}else if(n!==void 0){if(!C(n,s,r)){const l=T.get(n),a=T.get(s);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(n)}return e}validateBasicKeyType(e,t){if(!Rs(e,t))throw new Error("Dictionary key type must be a basic type")}validateKeyType(e,t,r){if(!As(t,r))if(Os(t,r)){const s=Number.parseInt(e,10);if(Number.isNaN(s)||s.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(Vs(t,r)){const s=Number.parseFloat(e);if(Number.isNaN(s))throw new Error(`Key '${e}' is not a valid Number.`)}else if(Ms(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 s=e.getType();if(s!==void 0&&!C(s,t,r)){const n=T.get(s),o=T.get(t);throw new Error(`Value of type '${JSON.stringify(n)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}class Er{process(e){return e}postProcess(e,t,r){const s=e.getType();if(s!==void 0&&_s(s,r)){const n=e.getItems(),o=e.getProperties();if(n!==void 0&&n.length>0||o!==void 0&&Object.keys(o).length>0){const l=Ds(s,r),a=s.getName()||"unknown";throw new Error(`Node of type "${a}" (which extends basic type "${l}") must not have items, properties or contracts.`)}}return e}}class Cr{process(e,t){let r=e;const s=t.getName();s!==void 0&&s!==e.getName()&&(r=r.cloneShallow().setName(s));const n=t.getDescription();return n!==void 0&&n!==r.getDescription()&&(r=r.cloneShallow().setDescription(n)),r}}const Ws=Object.freeze(Object.defineProperty({__proto__:null,BasicTypesVerifier:Er,DictionaryProcessor:wr,ListProcessor:Sr,MetadataPropagator:Cr,SequentialMergingProcessor:Nr,TypeAssigner:Pr,ValuePropagator:br},Symbol.toStringTag,{value:"Module"}));function $e(){return new Nr([new br,new Pr,new Sr,new wr,new Cr,new Er])}class Re{nodeProvider;mergingProcessor;minimizer=new ht;cyclicSetIdentity;constructor(e={}){this.nodeProvider=e.nodeProvider??rt(()=>[]),this.mergingProcessor=e.mergingProcessor??$e(),this.cyclicSetIdentity=this.createCyclicSetIdentityService()}createCyclicSetIdentityService(){return new M({prepareDocument:e=>this.prepareCyclicDocument(e),calculateBlueId:e=>this.hashCyclicPrepared(e)})}calculateBlueId(e){const t=this.tryCalculateCyclicSetBlueId(e);if(t!==void 0)return Promise.resolve(t);const r=this.toMinimalIdentityInput(e);return this.hashMinimalTrustedAsync(r)}calculateBlueIdSync(e){const t=this.tryCalculateCyclicSetBlueId(e);if(t!==void 0)return t;const r=this.toMinimalIdentityInput(e);return this.hashMinimalTrusted(r)}minimize(e){if(e instanceof k&&e.getCompleteness()==="path-limited"){const t=e.getSourceSemanticBlueId();if(t!==void 0)return new d().setReferenceBlueId(t);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return P.hasBlueIdOnly(e)?e.clone():e.isResolved()?this.minimizeResolved(e):this.minimizeAuthoring(e)}minimizeResolved(e){if(e instanceof k&&e.getCompleteness()==="path-limited")throw new Error("Cannot minimize a path-limited resolved node as a full resolved tree.");return this.minimizer.minimizeResolved(e)}minimizeAuthoring(e){return this.minimizeAuthoringWithProvider(e,this.nodeProvider)}minimizeAuthoringWithProvider(e,t){const r=new oe(this.mergingProcessor,t).resolve(e,$);return this.minimizeResolved(r)}hashMinimalTrusted(e){return this.hashMinimalTrustedWithProvider(e,this.nodeProvider)}hashMinimalTrustedWithProvider(e,t){return Array.isArray(e)?(q.validateStorageListShape(e),A.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t))):(q.validateStorageShape(e),A.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t)))}hashMinimalTrustedAsync(e){return Array.isArray(e)?(q.validateStorageListShape(e),A.calculateBlueId(this.toHashableMinimalTrusted(e))):(q.validateStorageShape(e),A.calculateBlueId(this.toHashableMinimalTrusted(e)))}toHashableMinimalTrusted(e,t=this.nodeProvider){return Array.isArray(e)?e.map(r=>this.toHashableMinimalTrustedNode(r,t)):this.toHashableMinimalTrustedNode(e,t)}toHashableMinimalTrustedNode(e,t=this.nodeProvider){if(!v.hasPositionControl(e))return e;const r=new oe(this.mergingProcessor,t).resolve(e,$);return this.minimizer.minimizeResolvedForHash(r)}prepareCyclicDocument(e){return this.minimizeAuthoringWithProvider(e,this.createCyclicReferenceNodeProvider())}hashCyclicPrepared(e){return this.hashMinimalTrustedWithProvider(e,this.createCyclicReferenceNodeProvider())}createCyclicReferenceNodeProvider(){const e=this.nodeProvider;return new class extends ye{fetchByBlueId(t){return t===M.ZERO_BLUE_ID||M.isIndexedThisReference(t)?[new d().setReferenceBlueId(t)]:e.fetchByBlueId(t)}}}toMinimalIdentityInput(e){return Array.isArray(e)?this.toMinimalListIdentityInput(e):this.minimize(e)}tryCalculateCyclicSetBlueId(e){const t=this.getTopLevelSetItems(e);if(t===void 0){if(!Array.isArray(e)&&M.hasThisReference([e]))throw new Error("Direct cyclic references using 'this#k' are supported only in a top-level document set.");return}if(M.hasThisReference(t))return this.cyclicSetIdentity.calculate(t).blueId}getTopLevelSetItems(e){if(Array.isArray(e))return e;if(P.hasItemsOnly(e))return e.getItems()??[]}toMinimalListIdentityInput(e){q.validateListControlShape(e);const t=new d().setItems(e);return this.minimizeAuthoring(t).getItems()??[]}}class Js{semanticIdentity;cyclicSetIdentity;constructor(e={}){const t=e.nodeProvider??rt(()=>[]),r=e.mergingProcessor??$e();this.semanticIdentity=new Re({nodeProvider:t,mergingProcessor:r}),this.cyclicSetIdentity=this.semanticIdentity.createCyclicSetIdentityService()}prepareStorageNode(e,t){const r=this.preprocessForStorage(e,t);if(this.hasThisReference(r))throw new Error("Self-references using this or this#k are not supported in single-document provider storage ingest.");return this.preparePreprocessedStorageNode(r)}prepareStorageNodeList(e,t){if(e.length===0)throw new Error("List of nodes cannot be null or empty");const r=e.map(o=>this.preprocessForStorage(o,t));if(M.hasThisReference(r)){const o=this.cyclicSetIdentity.calculate(r);return o.nodes.forEach(l=>q.validateStorageShape(l)),{blueId:o.blueId,nodes:o.nodes,documentBlueIds:o.documentBlueIds,isCyclicSet:!0}}const s=r.map(o=>this.preparePreprocessedStorageNode(o).node);return{blueId:this.semanticIdentity.hashMinimalTrusted(s),nodes:s}}preprocessForStorage(e,t){q.validateStorageShape(e);const r=t(e);return q.validateStorageShape(r),r}preparePreprocessedStorageNode(e){const t=this.prepareSemanticStorage(e);return q.validateStorageShape(t.node),t}prepareSemanticStorage(e){const t=this.semanticIdentity.minimizeAuthoring(e);return{blueId:this.semanticIdentity.hashMinimalTrusted(t),node:t}}hasThisReference(e){const t=e.getReferenceBlueId();return t!==void 0&&(t==="this"||t.startsWith("this#"))?!0:[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),...e.getItems()??[],...Object.values(e.getProperties()??{})].some(s=>s!==void 0&&this.hasThisReference(s))}}const Zs=i=>i instanceof h.ZodOptional||i instanceof h.ZodNullable||i instanceof h.ZodReadonly||i instanceof h.ZodBranded||i instanceof h.ZodEffects||i instanceof h.ZodLazy,Gs=i=>i instanceof h.ZodString||i instanceof h.ZodNumber||i instanceof h.ZodBoolean||i instanceof h.ZodBigInt;class Rr{static convertValue(e,t){const r=e.getType()?.getBlueId(),s=e.getValue();return u.isNullable(s)?Gs(t)&&P.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):s:te===r?this.convertFromString(String(s),t):re===r||s instanceof D?this.convertFromBigDecimal(new D(s?.toString()),t):se===r||s instanceof O?this.convertFromBigInteger(new O(s?.toString()),t):ie===r||typeof s=="boolean"?this.convertFromBoolean(!!s,t):this.convertFromString(String(s),t)}static convertFromString(e,t){if(!t||t instanceof h.ZodString||t instanceof h.ZodEnum||t instanceof h.ZodNativeEnum)return e;if(t instanceof h.ZodNumber)return Number(e);if(t instanceof h.ZodBoolean)return e.toLowerCase()==="true";if(t instanceof h.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){if(t instanceof h.ZodNumber)return e.toNumber();if(t instanceof h.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){if(t instanceof h.ZodNumber)return e.toNumber();if(t instanceof h.ZodBigInt)return BigInt(e.toString());if(t instanceof h.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t||t instanceof h.ZodBoolean)return e;if(t instanceof h.ZodString)return e.toString();if(t instanceof h.ZodNumber)return Number(e);if(t instanceof h.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;if(e instanceof h.ZodNumber)return 0;if(e instanceof h.ZodBoolean)return!1;if(e instanceof h.ZodString)return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}class qs{convert(e,t){return Rr.convertValue(e,t)}}class Xs{constructor(e,t){this.nodeToObjectConverter=e,this.calculateBlueId=t}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(t instanceof h.ZodIntersection){const r=t._def.left,s=t._def.right,n=this.convert(e,r),o=this.convert(e,s);return{...n,...o}}if(t instanceof h.ZodUnion)throw new Error("Union not supported");if(t instanceof h.ZodObject)return Object.keys(t.shape).reduce((s,n)=>{const o=e.getProperties(),l=t.shape[n],a=lr(l);if(u.isNonNullable(a)){const g=H.isString(a)?a:n,I=o?.[g],L=I?this.calculateBlueId(I):void 0;return s[n]=L,s}const c=cr(l);if(u.isNonNullable(c)){const g=o?.[c];return s[n]=g?.getName(),s}const p=nr(l);if(u.isNonNullable(p)){const g=o?.[p];return s[n]=g?.getDescription(),s}if(n==="name"){const g=e.getName();return s[n]=g,s}if(n==="description"){const g=e.getDescription();return s[n]=g,s}const f=o?.[n];if(u.isNullable(f))return s;const y=this.nodeToObjectConverter.convert(f,l);return s[n]=y,s},{});throw new Error("Unknown schema type, "+t._def.typeName)}}class Qs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t.element;return r.map(o=>this.nodeToObjectConverter.convert(o,s))}}class ei{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t._def.valueType,n=r.map(o=>this.nodeToObjectConverter.convert(o,s));return new Set(n)}}class ti{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,s=t.valueSchema,n=new Map,o=e.getName();u.isNonNullable(o)&&n.set(le,o);const l=e.getDescription();u.isNonNullable(l)&&n.set(ae,l);const a=e.getProperties();return u.isNonNullable(a)&&Object.entries(a).forEach(([c,p])=>{const f=new d().setValue(c);f.setType(new d().setBlueId(te));const y=Rr.convertValue(f,r),g=this.nodeToObjectConverter.convert(p,s);n.set(y,g)}),t instanceof h.ZodRecord?Object.fromEntries(n):n}}class ri{convert(e){return T.get(e)}}class si{convert(e){return T.get(e)}}class ii{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t.items;return r.map((o,l)=>this.nodeToObjectConverter.convert(o,s[l]))}}const ni=h.z.union([h.z.literal("ZodString"),h.z.literal("ZodNumber"),h.z.literal("ZodBoolean"),h.z.literal("ZodBigInt"),h.z.literal("ZodArray"),h.z.literal("ZodSet"),h.z.literal("ZodMap"),h.z.literal("ZodRecord"),h.z.literal("ZodObject"),h.z.literal("ZodEnum"),h.z.literal("ZodNativeEnum"),h.z.literal("ZodUnknown"),h.z.literal("ZodAny"),h.z.literal("ZodTuple")]);class oi{constructor(e,t){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new Xs(this.nodeToObjectConverter,t)}converters=new Map;complexObjectConverter;registerConverters(){const e=new qs,t=new Qs(this.nodeToObjectConverter),r=new ii(this.nodeToObjectConverter),s=new ei(this.nodeToObjectConverter),n=new ti(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 ri),this.converters.set("ZodAny",new si),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",s),this.converters.set("ZodMap",n),this.converters.set("ZodRecord",n),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){if(Zs(e))return e instanceof h.ZodEffects?this.getSchemaTypeName(e.innerType()):e instanceof h.ZodLazy?this.getSchemaTypeName(e.schema):this.getSchemaTypeName(e.unwrap());const t=e._def.typeName;try{return ni.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class li{constructor(e,t){if(this.typeSchemaResolver=e,!t?.calculateBlueId)throw new Error("NodeToObjectConverter requires a semantic calculateBlueId option.");this.calculateBlueId=t.calculateBlueId,this.converterFactory=new oi(this,this.calculateBlueId)}converterFactory;calculateBlueId;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),s=U.unwrapSchema(t);if(Rt(s))return e;let n=s;return U.checkSchemaExtension(r,s,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(n=r),this.convertWithType(e,n)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class ai{static get(e,t={}){const{strategy:r="official"}=t,s=T.get(e,r);return vr(s)}}const gt=async i=>{if(Jt(i))return i;try{const e=Ve.parse(i),{Blue:t}=await Promise.resolve().then(()=>Wi),r=await new t().calculateBlueId(e);return{...i,blueId:r}}catch(e){throw new Error(`Failed enriching object with Blue ID: ${e}`)}},ci=i=>i?.items,ui=i=>i?.value,di=i=>u.isNullable(i)?{}:H.omit(i,vt),hi=i=>Gt(i)?i.type.name??null:qt(i)?H.pascal(typeof i.value):Zt(i)?"List":null,Ar=i=>u.isNonNullable(i)&&Object.keys(H.omit(i,["blueId"])).length>0,pi=i=>{try{const e=m.deserialize(i),t=T.get(e);return ve.parse(t)}catch(e){throw new Error(`Failed transforming JSON-like value to BlueObject: ${e}`)}},mt=async i=>{const{resolveFunction:e,signal:t=new AbortController().signal,omitItems:r}=i,s=i.count??i.items.length;let n=await H.map(i.items,async l=>await gt(l));const o=Math.max(n?.length-s,0);for(let l=n.length-1;l>=o;l--)if(!Ar(n[l])){const a=await e(n[l],{signal:t});if(Array.isArray(a))return mt({...i,items:[...n.slice(0,l),...a,...n.slice(l+1)]});const c=await gt(a);if(r?.includes(c.blueId))return mt({...i,items:[...n.slice(0,l),...n.slice(l+1)]});n=[...n.slice(0,l),c,...n.slice(l+1)]}return n};function Ae(i){try{const e=new URL(i);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}class fi{process(e){return _.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(te)):typeof r=="bigint"||Q(r)?e.setType(new d().setBlueId(se)):He(r)?e.setType(new d().setBlueId(re)):typeof r=="boolean"&&e.setType(new d().setBlueId(ie))),e}}class Je{static MAPPINGS="mappings";mappings=new Map;constructor(e){if(e instanceof d){const r=e.getProperties();if(r&&r[Je.MAPPINGS]){const n=r[Je.MAPPINGS].getProperties();n&&Object.entries(n).forEach(([o,l])=>{const a=l.getValue();typeof a=="string"&&this.mappings.set(o,a)})}}else this.mappings=e}process(e){return _.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 s=this.mappings.get(r);if(s){const n=new d().setBlueId(s);t===e.getType()?e.setType(n):t===e.getItemType()?e.setItemType(n):t===e.getKeyType()?e.setKeyType(n):t===e.getValueType()&&e.setValueType(n)}}}}}class yi{process(e){return _.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 s=String(t.getValue());throw new Error(`Unknown type "${s}" found in ${r} field. No BlueId mapping exists for this type.`)}}}class Or{blueIdsCollections=[];initialize(...e){this.blueIdsCollections=[...e]}registerBlueIds(...e){this.blueIdsCollections.push(...e)}generateMappingsYaml(e="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo"){const t={};for(const s of this.blueIdsCollections)Object.assign(t,s);const r=Object.entries(t).map(([s,n])=>` ${s}: ${n}`).join(`
|
|
19
|
+
description: This transformation replaces`,js=[gr,_s,Ls,$s];class xs extends fe{blueIdToNodesMap=new Map;constructor(){super(),this.load()}fetchByBlueId(e){return this.blueIdToNodesMap.get(e)||[]}load(){for(const e of js){const t=ee(e);if(t===void 0){console.error(`This content file is not valid YAML: ${e}`);continue}if(Array.isArray(t)){const r=t.map(n=>m.deserialize(n)),s=A.calculateBlueIdSync(r);this.blueIdToNodesMap.set(s,r)}else{const r=m.deserialize(t),s=A.calculateBlueIdSync(r);this.blueIdToNodesMap.set(s,[r])}}}}class wt extends fe{static INSTANCE=new wt;nodeProvider;constructor(){super(),this.nodeProvider=new xs}fetchByBlueId(e){return this.nodeProvider.fetchByBlueId(e)}}class Me{static wrap(e){const t=[wt.INSTANCE];return t.push(e),new pr(t)}}class Et{nodeProvider;strategy;constructor(e,t){this.nodeProvider=Me.wrap(e),this.strategy=t||"THROW_EXCEPTION"}extend(e,t){this.extendNode(e,t,"")}extendNode(e,t,r,s=!1){if(!s){if(!t.shouldExtendPathSegment(r,e))return;t.enterPathSegment(r,e)}try{const n=e.getBlueId();if(n&&N.hasBlueIdOnly(e)&&!pe.includes(n)){const y=this.fetchNode(e);if(y&&y.length>0){const g=this.shouldPreserveReferenceBlueId(r,s);if(y.length===1){const I=y[0];this.mergeNodes(e,I,g)}else{const I=y.map(R=>R.clone()),D=new d().setItems(I);this.mergeNodes(e,D,g)}}}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 c=e.getValueType();c&&this.extendNode(c,t,"valueType",!0);const p=e.getProperties();p&&Object.entries(p).forEach(([y,g])=>{this.extendNode(g,t,y,!1)});const f=e.getItems();if(f&&f.length>0)for(let y=0;y<f.length;y++)this.extendNode(f[y],t,String(y),!1)}finally{s||t.exitPathSegment()}}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}shouldPreserveReferenceBlueId(e,t){return t&&["type","itemType","keyType","valueType"].includes(e)}mergeNodes(e,t,r){r||e.setReferenceBlueId(void 0),e.setName(t.getName()),e.setDescription(t.getDescription()),e.setType(t.getType()?.clone()),e.setItemType(t.getItemType()?.clone()),e.setKeyType(t.getKeyType()?.clone()),e.setValueType(t.getValueType()?.clone());const s=t.getValue();u.isNonNullable(s)&&e.setValue(s),e.setItems(t.getItems()?.map(o=>o.clone()));const n=t.getProperties();e.setProperties(n===void 0?void 0:Object.fromEntries(Object.entries(n).map(([o,l])=>[o,l.clone()]))),e.setBlue(t.getBlue()?.clone())}}class oe extends hr{mergingProcessor;nodeProvider;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProvider=Me.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 s=e;const n=t.getType();if(u.isNonNullable(n)){const o=this.resolveTypeNode(n,r),l=this.getTypeOverlay(n,o,r);s=this.mergeObject(s,l,r);const a=t.cloneShallow().setType(o.clone());return this.mergeObject(s,a,r)}return this.mergeObject(s,t,r)}mergeObject(e,t,r){const s=e.cloneShallow();let n=this.mergingProcessor.process(s,t,r.nodeProvider);const o=t.getItems();u.isNonNullable(o)&&(n=this.mergeChildren(n,t,r));const l=t.getProperties();return u.isNonNullable(l)&&(n=this.mergeProperties(n,t,l,r)),u.isNonNullable(t.getBlueId())&&(n=n.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(n=this.mergingProcessor.postProcess(n,t,r.nodeProvider)),n}mergeChildren(e,t,r){const s=t.getItems()??[];return v.hasListControlItems(s)?this.mergeChildrenWithListControls(e,t,r):this.mergeChildrenWithoutListControls(e,s,r)}mergeChildrenWithoutListControls(e,t,r){const s=e.getItems();if(u.isNullable(s)){const o=[];for(let l=0;l<t.length;l++){const a=t[l];if(r.limits.shouldMergePathSegment(String(l),a)){this.enterPathSegment(r,String(l),a);try{const c=this.materializeForCurrentContext(a,r);o.push(c)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(o)}if(t.length<s.length)throw new Error(`Subtype of element must not have more items (${s.length}) than the element itself (${t.length}).`);const n=[...s];for(let o=0;o<t.length;o++)if(r.limits.shouldMergePathSegment(String(o),t[o])){this.enterPathSegment(r,String(o),t[o]);try{if(o>=n.length){const p=this.materializeForCurrentContext(t[o],r);n.push(p);continue}const l=r.limits instanceof k?t[o]:this.materializeForCurrentContext(t[o],r),a=this.calculateNodeBlueId(l,r),c=this.calculateNodeBlueId(n[o],r);if(a!==c)throw new Error(`Mismatched items at index ${o}: source item has blueId '${a}', but target item has blueId '${c}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(n)}mergeChildrenWithListControls(e,t,r){const s=t.getItems()??[],n=e.getItems()??[],o=v.getMergePolicy(t,e),l=[...n];let a=0,c=!1;const p=s[0];if(p!==void 0&&v.hasPreviousProperty(p)){if(v.getPreviousBlueId(p)===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");c=!0,a=1}const f=c&&n.length===0&&!(r.limits instanceof k),y=new Set;for(;a<s.length;a++){const g=s[a];if(v.hasPreviousProperty(g))throw new Error("$previous list control is allowed only as the first item.");const I=v.readPosition(g);if(I!==void 0){if(o==="append-only")throw new Error("$pos is not allowed in append-only lists.");if(I>=n.length)throw new Error(`$pos ${I} is out of range for inherited list length ${n.length}.`);if(y.has(I))throw new Error(`Duplicate $pos list overlay for index ${I}.`);y.add(I);const R=v.withoutPosition(g);if(!v.hasPayloadAfterRemovingPosition(g))throw new Error("$pos list control must include an item payload.");if(!r.limits.shouldMergePathSegment(String(I),R))continue;this.enterPathSegment(r,String(I),R);try{const _=l[I];l[I]=_===void 0||v.isReplacementPayload(R)?this.materializeForCurrentContext(R,r):this.mergeWithContext(_,R,r)}finally{this.exitPathSegment(r)}continue}const D=l.length;if(!(!f&&!r.limits.shouldMergePathSegment(String(D),g))){if(f){l.push(this.materializeWithoutLimits(g,r));continue}this.enterPathSegment(r,String(D),g);try{const R=this.materializeForCurrentContext(g,r);l.push(R)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}materializeWithoutLimits(e,t){return new oe(this.mergingProcessor,t.nodeProvider).resolve(e,x)}mergeProperties(e,t,r,s){const n=e.getProperties()??{};let o=n,l=!1;for(const[a,c]of Object.entries(r))if(s.limits.shouldMergePathSegment(a,c)){this.enterPathSegment(s,a,c);try{const p=o[a],f=this.getPathLimitedListControlTarget(p,t,a,c,s),y=f??p,I=this.shouldMergePropertyWithoutPreResolve(y,c,s)?this.mergeExistingProperty(y,c,s):(()=>{const R=this.materializeForCurrentContext(c,s);return y===void 0?R:this.mergeObject(y,R,s)})(),D=f===void 0?I:this.projectListNodeToCurrentLimits(I,s);D!==p&&(l||(o={...n},l=!0),o[a]=D)}finally{this.exitPathSegment(s)}}return l?e.cloneShallow().setProperties(o):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof k?u.isNonNullable(e)&&v.hasListControlItems(t.getItems()):u.isNonNullable(t.getItems())||u.isNonNullable(e.getItems())}mergeExistingProperty(e,t,r){if(e===void 0)throw new Error("Cannot merge property without an existing target.");return this.mergeWithContext(e,t,r)}resolve(e,t){return this.resolveWithContext(e,this.createResolutionContext(t))}resolveWithContext(e,t){const r=new d,n=this.mergeWithContext(r,e,t).cloneShallow().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new Y(n,{completeness:t.limits instanceof k?"full":"path-limited"})}createResolutionContext(e){const t=new Map,r=new Map,s=Bs(this.createResolutionNodeProvider(this.nodeProvider,t),r);return{limits:e,nodeProvider:s,resolvedTypeCache:new Map,resolvingTypeKeys:new Set,resolvingTypeBlueIds:new Set,typeOverlayCache:new Map,nodeHashCache:new WeakMap,providerFetchCache:t,subtypeCache:r,pathStack:[]}}resolveTypeNode(e,t){const r=e.getBlueId();if(u.isNonNullable(r)){const s=this.createResolvedTypeCacheKey(r,t),n=t.resolvedTypeCache.get(s);if(u.isNonNullable(n)&&!t.resolvingTypeKeys.has(s))return n;if(t.resolvingTypeBlueIds.has(r))return n??this.createCyclicTypeReference(r,t);const o=this.createCyclicTypeReference(r,t);t.resolvedTypeCache.set(s,o),t.resolvingTypeKeys.add(s),t.resolvingTypeBlueIds.add(r);try{const l=this.resolveAndExtendTypeNode(e,t);return l.setReferenceBlueId(r),t.resolvedTypeCache.set(s,l),l}catch(l){throw t.resolvedTypeCache.delete(s),l}finally{t.resolvingTypeKeys.delete(s),t.resolvingTypeBlueIds.delete(r)}}return this.resolveAndExtendTypeNode(e,t)}createCyclicTypeReference(e,t){return new Y(new d().setReferenceBlueId(e),{completeness:t.limits instanceof k?"full":"path-limited"})}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new Et(t.nodeProvider).extend(r,Xe.withSinglePath("/")),this.resolveWithContext(r,t)}getTypeOverlay(e,t,r){const s=e.getBlueId();if(u.isNullable(s))return this.createTypeOverlay(t);const n=this.createResolvedTypeCacheKey(s,r),o=r.typeOverlayCache.get(n);if(u.isNonNullable(o))return o;const l=this.createTypeOverlay(t);return r.resolvingTypeBlueIds.has(s)||r.typeOverlayCache.set(n,l),l}createTypeOverlay(e){return e.cloneShallow().setType(void 0).setBlueId(void 0)}createResolvedTypeCacheKey(e,t){return t.limits instanceof k?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 k}calculateNodeBlueId(e,t){const r=t.nodeHashCache.get(e);if(u.isNonNullable(r))return r;const s=F.calculateHashMinimalBlueId(e);return t.nodeHashCache.set(e,s),s}getPathLimitedListControlTarget(e,t,r,s,n){if(!(e===void 0||n.limits instanceof k||!v.hasListControlItems(s.getItems())))return this.resolveFullInheritedProperty(t,r,n)}resolveFullInheritedProperty(e,t,r){const s=e.getType();if(s===void 0)return;const n=s.getBlueId();if(u.isNonNullable(n)){const a=r.nodeProvider.fetchByBlueId(n)?.[0];return a===void 0?void 0:new oe(this.mergingProcessor,r.nodeProvider).resolve(a,x).getProperties()?.[t]?.clone()}return new oe(this.mergingProcessor,r.nodeProvider).resolve(s,x).getProperties()?.[t]?.clone()}projectListNodeToCurrentLimits(e,t){const r=e.getItems();return r===void 0?e:e.cloneShallow().setItems(r.filter((s,n)=>t.limits.shouldMergePathSegment(String(n),s)))}createResolutionNodeProvider(e,t){return new class extends fe{fetchByBlueId(r){if(t.has(r))return t.get(r)??null;const s=e.fetchByBlueId(r);return t.set(r,s),s}}}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 mr{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((s,n)=>n.process(s,t,r),e)}postProcess(e,t,r){return this.mergingProcessors.reduce((s,n)=>n.postProcess?n.postProcess(s,t,r):s,e)}}class Ir{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const s=e.getValue();if(u.isNullable(s))return e.cloneShallow().setValue(r);if(!Fs(r,s))throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${s}`)}return e}}const Fs=(i,e)=>Q(i)&&Q(e)||Ke(i)&&Ke(e)?i.eq(e):i===e;class Tr{process(e,t,r){const s=e.getType(),n=t.getType();let o=e;if(s===void 0)o=e.cloneShallow().setType(n);else if(n!==void 0){if(!w(n,s,r)){const a=T.get(n),c=T.get(s);throw new Error(`The source type '${JSON.stringify(a)}' is not a subtype of the target type '${JSON.stringify(c)}'.`)}o=e.cloneShallow().setType(n)}return o}}class vr{process(e,t,r){const s=t.getItemType(),n=t.getType();if(s!==void 0&&n!==void 0&&!ze(n,r))throw new Error("Source node with itemType must have a List type");const o=e.getItemType();let l=e;if(o===void 0)s!==void 0&&(l=e.cloneShallow().setItemType(s));else if(s!==void 0){if(!w(s,o,r)){const f=T.get(s),y=T.get(o);throw new Error(`The source item type '${JSON.stringify(f)}' is not a subtype of the target item type '${JSON.stringify(y)}'.`)}l=e.cloneShallow().setItemType(s)}const a=l.getItemType(),c=t.getItems();if(a!==void 0&&c!==void 0)for(const p of c){const f=p.getType();if(f!==void 0&&!w(f,a,r)){const y=T.get(f),g=T.get(a);throw new Error(`Item of type '${JSON.stringify(y)}' is not a subtype of the list's item type '${JSON.stringify(g)}'.`)}}return l}}class Br{process(e,t,r){const s=t.getKeyType(),n=t.getValueType(),o=t.getType();if((s!==void 0||n!==void 0)&&o!==void 0&&!Ue(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(),c=l.getValueType(),p=t.getProperties();return(a!==void 0||c!==void 0)&&p!==void 0&&Object.entries(p).forEach(([f,y])=>{a!==void 0&&this.validateKeyType(f,a,r),c!==void 0&&this.validateValueType(y,c,r)}),l}processKeyType(e,t,r){const s=e.getKeyType(),n=t.getKeyType();if(s===void 0){if(n!==void 0)return this.validateBasicKeyType(n,r),e.cloneShallow().setKeyType(n)}else if(n!==void 0){if(this.validateBasicKeyType(n,r),!w(n,s,r)){const l=T.get(n),a=T.get(s);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(n)}return e}processValueType(e,t,r){const s=e.getValueType(),n=t.getValueType();if(s===void 0){if(n!==void 0)return e.cloneShallow().setValueType(n)}else if(n!==void 0){if(!w(n,s,r)){const l=T.get(n),a=T.get(s);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(n)}return e}validateBasicKeyType(e,t){if(!bs(e,t))throw new Error("Dictionary key type must be a basic type")}validateKeyType(e,t,r){if(!Ps(t,r))if(Ss(t,r)){const s=Number.parseInt(e,10);if(Number.isNaN(s)||s.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(ws(t,r)){const s=Number.parseFloat(e);if(Number.isNaN(s))throw new Error(`Key '${e}' is not a valid Number.`)}else if(Es(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 s=e.getType();if(s!==void 0&&!w(s,t,r)){const n=T.get(s),o=T.get(t);throw new Error(`Value of type '${JSON.stringify(n)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}class Nr{process(e){return e}postProcess(e,t,r){const s=e.getType();if(s!==void 0&&Cs(s,r)){const n=e.getItems(),o=e.getProperties();if(n!==void 0&&n.length>0||o!==void 0&&Object.keys(o).length>0){const l=Rs(s,r),a=s.getName()||"unknown";throw new Error(`Node of type "${a}" (which extends basic type "${l}") must not have items, properties or contracts.`)}}return e}}class br{process(e,t){let r=e;const s=t.getName();s!==void 0&&s!==e.getName()&&(r=r.cloneShallow().setName(s));const n=t.getDescription();return n!==void 0&&n!==r.getDescription()&&(r=r.cloneShallow().setDescription(n)),r}}const zs=Object.freeze(Object.defineProperty({__proto__:null,BasicTypesVerifier:Nr,DictionaryProcessor:Br,ListProcessor:vr,MetadataPropagator:br,SequentialMergingProcessor:mr,TypeAssigner:Tr,ValuePropagator:Ir},Symbol.toStringTag,{value:"Module"}));function Ct(){return new mr([new Ir,new Tr,new vr,new Br,new br,new Nr])}class Ee{nodeProvider;mergingProcessor;minimizer=new ct;cyclicSetIdentity;constructor(e={}){this.nodeProvider=e.nodeProvider??et(()=>[]),this.mergingProcessor=e.mergingProcessor??Ct(),this.cyclicSetIdentity=this.createCyclicSetIdentityService()}createCyclicSetIdentityService(){return new M({prepareDocument:e=>this.prepareCyclicDocument(e),calculateBlueId:e=>this.hashCyclicPrepared(e)})}calculateBlueId(e){const t=this.tryCalculateCyclicSetBlueId(e);if(t!==void 0)return Promise.resolve(t);const r=this.toMinimalIdentityInput(e);return this.hashMinimalTrustedAsync(r)}calculateBlueIdSync(e){const t=this.tryCalculateCyclicSetBlueId(e);if(t!==void 0)return t;const r=this.toMinimalIdentityInput(e);return this.hashMinimalTrusted(r)}minimize(e){if(e instanceof Y&&e.getCompleteness()==="path-limited"){const t=e.getSourceSemanticBlueId();if(t!==void 0)return new d().setReferenceBlueId(t);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return N.hasBlueIdOnly(e)?e.clone():e.isResolved()?this.minimizeResolved(e):this.minimizeAuthoring(e)}minimizeResolved(e){if(e instanceof Y&&e.getCompleteness()==="path-limited")throw new Error("Cannot minimize a path-limited resolved node as a full resolved tree.");return this.minimizer.minimizeResolved(e)}minimizeAuthoring(e){return this.minimizeAuthoringWithProvider(e,this.nodeProvider)}minimizeAuthoringWithProvider(e,t){const r=new oe(this.mergingProcessor,t).resolve(e,x);return this.minimizeResolved(r)}hashMinimalTrusted(e){return this.hashMinimalTrustedWithProvider(e,this.nodeProvider)}hashMinimalTrustedWithProvider(e,t){return Array.isArray(e)?(q.validateStorageListShape(e),A.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t))):(q.validateStorageShape(e),A.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t)))}hashMinimalTrustedAsync(e){return Array.isArray(e)?(q.validateStorageListShape(e),A.calculateBlueId(this.toHashableMinimalTrusted(e))):(q.validateStorageShape(e),A.calculateBlueId(this.toHashableMinimalTrusted(e)))}toHashableMinimalTrusted(e,t=this.nodeProvider){return Array.isArray(e)?e.map(r=>this.toHashableMinimalTrustedNode(r,t)):this.toHashableMinimalTrustedNode(e,t)}toHashableMinimalTrustedNode(e,t=this.nodeProvider){if(!v.hasPositionControl(e))return e;const r=new oe(this.mergingProcessor,t).resolve(e,x);return this.minimizer.minimizeResolvedForHash(r)}prepareCyclicDocument(e){return this.minimizeAuthoringWithProvider(e,this.createCyclicReferenceNodeProvider())}hashCyclicPrepared(e){return this.hashMinimalTrustedWithProvider(e,this.createCyclicReferenceNodeProvider())}createCyclicReferenceNodeProvider(){const e=this.nodeProvider;return new class extends fe{fetchByBlueId(t){return t===M.ZERO_BLUE_ID||M.isIndexedThisReference(t)?[new d().setReferenceBlueId(t)]:e.fetchByBlueId(t)}}}toMinimalIdentityInput(e){return Array.isArray(e)?this.toMinimalListIdentityInput(e):this.minimize(e)}tryCalculateCyclicSetBlueId(e){const t=this.getTopLevelSetItems(e);if(t===void 0){if(!Array.isArray(e)&&M.hasThisReference([e]))throw new Error("Direct cyclic references using 'this#k' are supported only in a top-level document set.");return}if(M.hasThisReference(t))return this.cyclicSetIdentity.calculate(t).blueId}getTopLevelSetItems(e){if(Array.isArray(e))return e;if(N.hasItemsOnly(e))return e.getItems()??[]}toMinimalListIdentityInput(e){q.validateListControlShape(e);const t=new d().setItems(e);return this.minimizeAuthoring(t).getItems()??[]}}class Us{semanticIdentity;cyclicSetIdentity;constructor(e={}){const t=e.nodeProvider??et(()=>[]),r=e.mergingProcessor??Ct();this.semanticIdentity=new Ee({nodeProvider:t,mergingProcessor:r}),this.cyclicSetIdentity=this.semanticIdentity.createCyclicSetIdentityService()}prepareStorageNode(e,t){const r=this.preprocessForStorage(e,t);if(this.hasThisReference(r))throw new Error("Self-references using this or this#k are not supported in single-document provider storage ingest.");return this.preparePreprocessedStorageNode(r)}prepareStorageNodeList(e,t){if(e.length===0)throw new Error("List of nodes cannot be null or empty");const r=e.map(o=>this.preprocessForStorage(o,t));if(M.hasThisReference(r)){const o=this.cyclicSetIdentity.calculate(r);return o.nodes.forEach(l=>q.validateStorageShape(l)),{blueId:o.blueId,nodes:o.nodes,documentBlueIds:o.documentBlueIds,isCyclicSet:!0}}const s=r.map(o=>this.preparePreprocessedStorageNode(o).node);return{blueId:this.semanticIdentity.hashMinimalTrusted(s),nodes:s}}preprocessForStorage(e,t){q.validateStorageShape(e);const r=t(e);return q.validateStorageShape(r),r}preparePreprocessedStorageNode(e){const t=this.prepareSemanticStorage(e);return q.validateStorageShape(t.node),t}prepareSemanticStorage(e){const t=this.semanticIdentity.minimizeAuthoring(e);return{blueId:this.semanticIdentity.hashMinimalTrusted(t),node:t}}hasThisReference(e){const t=e.getReferenceBlueId();return t!==void 0&&(t==="this"||t.startsWith("this#"))?!0:[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),...e.getItems()??[],...Object.values(e.getProperties()??{})].some(s=>s!==void 0&&this.hasThisReference(s))}}const Ks=i=>i instanceof h.ZodOptional||i instanceof h.ZodNullable||i instanceof h.ZodReadonly||i instanceof h.ZodBranded||i instanceof h.ZodEffects||i instanceof h.ZodLazy,Hs=i=>i instanceof h.ZodString||i instanceof h.ZodNumber||i instanceof h.ZodBoolean||i instanceof h.ZodBigInt;class Pr{static convertValue(e,t){const r=e.getType()?.getBlueId(),s=e.getValue();return u.isNullable(s)?Hs(t)&&N.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):s:te===r?this.convertFromString(String(s),t):re===r||s instanceof $?this.convertFromBigDecimal(new $(s?.toString()),t):se===r||s instanceof O?this.convertFromBigInteger(new O(s?.toString()),t):ie===r||typeof s=="boolean"?this.convertFromBoolean(!!s,t):this.convertFromString(String(s),t)}static convertFromString(e,t){if(!t||t instanceof h.ZodString||t instanceof h.ZodEnum||t instanceof h.ZodNativeEnum)return e;if(t instanceof h.ZodNumber)return Number(e);if(t instanceof h.ZodBoolean)return e.toLowerCase()==="true";if(t instanceof h.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){if(t instanceof h.ZodNumber)return e.toNumber();if(t instanceof h.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){if(t instanceof h.ZodNumber)return e.toNumber();if(t instanceof h.ZodBigInt)return BigInt(e.toString());if(t instanceof h.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t||t instanceof h.ZodBoolean)return e;if(t instanceof h.ZodString)return e.toString();if(t instanceof h.ZodNumber)return Number(e);if(t instanceof h.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;if(e instanceof h.ZodNumber)return 0;if(e instanceof h.ZodBoolean)return!1;if(e instanceof h.ZodString)return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}class Ys{convert(e,t){return Pr.convertValue(e,t)}}class ks{constructor(e,t){this.nodeToObjectConverter=e,this.calculateBlueId=t}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(t instanceof h.ZodIntersection){const r=t._def.left,s=t._def.right,n=this.convert(e,r),o=this.convert(e,s);return{...n,...o}}if(t instanceof h.ZodUnion)throw new Error("Union not supported");if(t instanceof h.ZodObject)return Object.keys(t.shape).reduce((s,n)=>{const o=e.getProperties(),l=t.shape[n],a=sr(l);if(u.isNonNullable(a)){const g=H.isString(a)?a:n,I=o?.[g],D=I?this.calculateBlueId(I):void 0;return s[n]=D,s}const c=nr(l);if(u.isNonNullable(c)){const g=o?.[c];return s[n]=g?.getName(),s}const p=tr(l);if(u.isNonNullable(p)){const g=o?.[p];return s[n]=g?.getDescription(),s}if(n==="name"){const g=e.getName();return s[n]=g,s}if(n==="description"){const g=e.getDescription();return s[n]=g,s}const f=o?.[n];if(u.isNullable(f))return s;const y=this.nodeToObjectConverter.convert(f,l);return s[n]=y,s},{});throw new Error("Unknown schema type, "+t._def.typeName)}}class Js{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t.element;return r.map(o=>this.nodeToObjectConverter.convert(o,s))}}class Ws{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t._def.valueType,n=r.map(o=>this.nodeToObjectConverter.convert(o,s));return new Set(n)}}class Zs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,s=t.valueSchema,n=new Map,o=e.getName();u.isNonNullable(o)&&n.set(le,o);const l=e.getDescription();u.isNonNullable(l)&&n.set(ae,l);const a=e.getProperties();return u.isNonNullable(a)&&Object.entries(a).forEach(([c,p])=>{const f=new d().setValue(c);f.setType(new d().setBlueId(te));const y=Pr.convertValue(f,r),g=this.nodeToObjectConverter.convert(p,s);n.set(y,g)}),t instanceof h.ZodRecord?Object.fromEntries(n):n}}class Gs{convert(e){return T.get(e)}}class qs{convert(e){return T.get(e)}}class Xs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t.items;return r.map((o,l)=>this.nodeToObjectConverter.convert(o,s[l]))}}const Qs=h.z.union([h.z.literal("ZodString"),h.z.literal("ZodNumber"),h.z.literal("ZodBoolean"),h.z.literal("ZodBigInt"),h.z.literal("ZodArray"),h.z.literal("ZodSet"),h.z.literal("ZodMap"),h.z.literal("ZodRecord"),h.z.literal("ZodObject"),h.z.literal("ZodEnum"),h.z.literal("ZodNativeEnum"),h.z.literal("ZodUnknown"),h.z.literal("ZodAny"),h.z.literal("ZodTuple")]);class ei{constructor(e,t){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new ks(this.nodeToObjectConverter,t)}converters=new Map;complexObjectConverter;registerConverters(){const e=new Ys,t=new Js(this.nodeToObjectConverter),r=new Xs(this.nodeToObjectConverter),s=new Ws(this.nodeToObjectConverter),n=new Zs(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 Gs),this.converters.set("ZodAny",new qs),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",s),this.converters.set("ZodMap",n),this.converters.set("ZodRecord",n),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){if(Ks(e))return e instanceof h.ZodEffects?this.getSchemaTypeName(e.innerType()):e instanceof h.ZodLazy?this.getSchemaTypeName(e.schema):this.getSchemaTypeName(e.unwrap());const t=e._def.typeName;try{return Qs.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class ti{constructor(e,t){if(this.typeSchemaResolver=e,!t?.calculateBlueId)throw new Error("NodeToObjectConverter requires a semantic calculateBlueId option.");this.calculateBlueId=t.calculateBlueId,this.converterFactory=new ei(this,this.calculateBlueId)}converterFactory;calculateBlueId;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),s=z.unwrapSchema(t);if(St(s))return e;let n=s;return z.checkSchemaExtension(r,s,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(n=r),this.convertWithType(e,n)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class ri{static get(e,t={}){const{strategy:r="official"}=t,s=T.get(e,r);return yr(s)}}const pt=async i=>{if(Ht(i))return i;try{const e=Oe.parse(i),{Blue:t}=await Promise.resolve().then(()=>zi),r=await new t().calculateBlueId(e);return{...i,blueId:r}}catch(e){throw new Error(`Failed enriching object with Blue ID: ${e}`)}},si=i=>i?.items,ii=i=>i?.value,ni=i=>u.isNullable(i)?{}:H.omit(i,gt),oi=i=>kt(i)?i.type.name??null:Jt(i)?H.pascal(typeof i.value):Yt(i)?"List":null,Sr=i=>u.isNonNullable(i)&&Object.keys(H.omit(i,["blueId"])).length>0,li=i=>{try{const e=m.deserialize(i),t=T.get(e);return Ie.parse(t)}catch(e){throw new Error(`Failed transforming JSON-like value to BlueObject: ${e}`)}},ft=async i=>{const{resolveFunction:e,signal:t=new AbortController().signal,omitItems:r}=i,s=i.count??i.items.length;let n=await H.map(i.items,async l=>await pt(l));const o=Math.max(n?.length-s,0);for(let l=n.length-1;l>=o;l--)if(!Sr(n[l])){const a=await e(n[l],{signal:t});if(Array.isArray(a))return ft({...i,items:[...n.slice(0,l),...a,...n.slice(l+1)]});const c=await pt(a);if(r?.includes(c.blueId))return ft({...i,items:[...n.slice(0,l),...n.slice(l+1)]});n=[...n.slice(0,l),c,...n.slice(l+1)]}return n};function Ce(i){try{const e=new URL(i);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}class ai{process(e){return L.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(te)):typeof r=="bigint"||Q(r)?e.setType(new d().setBlueId(se)):Ke(r)?e.setType(new d().setBlueId(re)):typeof r=="boolean"&&e.setType(new d().setBlueId(ie))),e}}class Je{static MAPPINGS="mappings";mappings=new Map;constructor(e){if(e instanceof d){const r=e.getProperties();if(r&&r[Je.MAPPINGS]){const n=r[Je.MAPPINGS].getProperties();n&&Object.entries(n).forEach(([o,l])=>{const a=l.getValue();typeof a=="string"&&this.mappings.set(o,a)})}}else this.mappings=e}process(e){return L.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 s=this.mappings.get(r);if(s){const n=new d().setBlueId(s);t===e.getType()?e.setType(n):t===e.getItemType()?e.setItemType(n):t===e.getKeyType()?e.setKeyType(n):t===e.getValueType()&&e.setValueType(n)}}}}}class ci{process(e){return L.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 s=String(t.getValue());throw new Error(`Unknown type "${s}" found in ${r} field. No BlueId mapping exists for this type.`)}}}class wr{blueIdsCollections=[];initialize(...e){this.blueIdsCollections=[...e]}registerBlueIds(...e){this.blueIdsCollections.push(...e)}generateMappingsYaml(e="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo"){const t={};for(const s of this.blueIdsCollections)Object.assign(t,s);const r=Object.entries(t).map(([s,n])=>` ${s}: ${n}`).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 De{static DEFAULT_BLUE_BLUE_ID="BF4xn5LN3HzQJSmqcXRyUq4tZEtkj2eBZ8UPCDJMnhG9";processorProvider;nodeProvider;defaultSimpleBlue=null;blueIdsMappingGenerator;constructor(e={}){const{nodeProvider:t,processorProvider:r,blueIdsMappingGenerator:s}=e;if(!t)throw new Error("NodeProvider is required");this.nodeProvider=
|
|
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 De{static DEFAULT_BLUE_BLUE_ID="BF4xn5LN3HzQJSmqcXRyUq4tZEtkj2eBZ8UPCDJMnhG9";processorProvider;nodeProvider;defaultSimpleBlue=null;blueIdsMappingGenerator;constructor(e={}){const{nodeProvider:t,processorProvider:r,blueIdsMappingGenerator:s}=e;if(!t)throw new Error("NodeProvider is required");this.nodeProvider=Me.wrap(t),this.processorProvider=r||De.getStandardProvider(),this.blueIdsMappingGenerator=s||new wr,this.loadDefaultSimpleBlue()}preprocess(e){return this.preprocessWithOptions(e,null)}preprocessWithDefaultBlue(e){return this.preprocessWithOptions(e,this.defaultSimpleBlue)}preprocessWithOptions(e,t){let r=e.clone(),s=r.getBlue();if(!s&&t&&(s=t.clone()),s){new Et(this.nodeProvider).extend(s,Xe.withSinglePath("/*"));const n=this.flattenTransformationItems(s.getItems());if(n&&n.length>0){for(const o of n){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 ci().process(r)}return r}flattenTransformationItems(e){if(e!==void 0)return e.flatMap(t=>t.getItems()??[t])}static getStandardProvider(){return{getProcessor(e){const t="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo",r="FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4",s=e.getType()?.getBlueId();if(t===s)return new Je(e);if(r===s)return new ai}}}enrichDefaultBlue(e){if(this.blueIdsMappingGenerator.getTotalBlueIdCount()===0)return e;const t=this.blueIdsMappingGenerator.generateMappingsYaml();return`
|
|
24
24
|
${e}
|
|
25
25
|
${t}
|
|
26
|
-
`}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(
|
|
27
|
-
${s.message}`):s}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 mi={fetchUrl:async i=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${i}`)}};class Ii{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||mi}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:s}=t;let n;if(s.includes("application/json")||s.includes("text/yaml")||s.includes("application/yaml")||s.includes("text/plain"))n=ee(r);else throw new Error(`Unsupported content type from URL: ${s}`);if(n===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(n)?o=n.map(l=>m.deserialize(l)):o=[m.deserialize(n)],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 Fe{constructor(e,t,r,s=[],n=!1){this.blueId=e,this.content=t,this.isMultipleDocuments=r,this.documentBlueIds=s,this.isCyclicSet=n}}class Ie{static THIS_REFERENCE_PATTERN=/^this(#\d+)?$/;static parseAndCalculateBlueId(e,t,r){let s;try{const a=ee(e);if(a===void 0)throw new Error;s=a}catch{throw new Error("Failed to parse content as YAML or JSON")}let n,o;const l=Array.isArray(s);if(l){const a=s.map(p=>m.deserialize(p)),c=r.prepareStorageNodeList(a,t);return n=c.blueId,o=c.nodes.map(p=>T.get(p)),new Fe(n,o,!0,c.documentBlueIds,c.isCyclicSet??!1)}else{const a=m.deserialize(s),c=r.prepareStorageNode(a,t);n=c.blueId,o=T.get(c.node)}return new Fe(n,o,l)}static parseAndCalculateBlueIdForNode(e,t,r){const s=r.prepareStorageNode(e,t),n=T.get(s.node);return new Fe(s.blueId,n,!1)}static parseAndCalculateBlueIdForNodeList(e,t,r){if(!e||e.length===0)throw new Error("List of nodes cannot be null or empty");const s=r.prepareStorageNodeList(e,t),n=s.nodes.map(l=>T.get(l)),o=!0;return new Fe(s.blueId,n,o,s.documentBlueIds,s.isCyclicSet??!1)}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 s={};for(const[n,o]of Object.entries(e))typeof o=="string"?n===V&&this.THIS_REFERENCE_PATTERN.test(o)?s[n]=this.resolveThisReference(o,t,r):s[n]=o:o&&typeof o=="object"?s[n]=this.resolveThisReferencesRecursive(o,t,r):s[n]=o;return s}else if(Array.isArray(e))return e.map(s=>s&&typeof s=="object"?this.resolveThisReferencesRecursive(s,t,r):s);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 Ti extends ye{fetchByBlueId(e){const t=e.split("#")[0],r=this.fetchContentByBlueId(t);if(r==null)return null;const s=Array.isArray(r),n=Ie.resolveThisReferences(r,t,s);if(e.includes("#")){const o=e.split("#");if(o.length>1){const l=parseInt(o[1]);if(Array.isArray(n)&&l<n.length){const a=n[l];return[m.deserialize(a)]}else return l===0?[m.deserialize(n)]:null}}return Array.isArray(n)?n.map(o=>m.deserialize(o)):[m.deserialize(n)]}}class Vr extends Ti{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 s of t){const n=this.fetchByBlueId(s);n&&r.push(...n)}return r}addToNameMap(e,t){this.nameToBlueIdsMap.set(e,[...this.nameToBlueIdsMap.get(e)||[],t])}}function vi(i){return Array.isArray(i)?Bi(i):i}function Bi(i){const e=i.map(t=>m.deserialize(t));return M.hasIndexedThisReference(e)?Ni(e):i}function Ni(i){return new M().calculate(i).nodes.map(t=>T.get(t))}class Vt extends Vr{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;aliasBlueIdMap=new Map;constructor(e,t={}){super();const r=Vt.collectAliasMappings(e);this.aliasBlueIdMap=new Map(Object.entries(r)),this.loadRepositories(e)}static collectAliasMappings(e){const t={};for(const r of e)for(const s of Object.values(r.packages))for(const[n,o]of Object.entries(s.aliases)){const l=t[n];if(l&&l!==o)throw new Error(`Conflicting alias mapping for ${n}`);t[n]=o}return t}loadRepositories(e){for(const t of e)Object.values(t.packages).forEach(r=>{for(const[s,n]of Object.entries(r.contents)){const o=vi(n);this.storeContent(s,o,Array.isArray(o)),this.addContentNames(s,o)}})}addContentNames(e,t){if(Array.isArray(t)){this.addListItemNames(e,t);return}const s=m.deserialize(t).getName();s&&this.addToNameMap(s,e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,s)=>{const o=m.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${s}`)})}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?Ie.resolveThisReferences(t,e,r):null}fetchByBlueId(e){const t=this.resolveAliasBlueId(e);return t===void 0?null:super.fetchByBlueId(t)}storeContent(e,t,r){this.blueIdToContentMap.set(e,t),this.blueIdToMultipleDocumentsMap.set(e,r)}getBlueIds(){return Array.from(this.blueIdToContentMap.keys())}hasBlueId(e){const t=this.resolveAliasBlueId(e);return t===void 0?!1:this.blueIdToContentMap.has(this.getBaseBlueIdAndSuffix(t).baseBlueId)}resolveAliasBlueId(e){const t=this.aliasBlueIdMap.get(e);if(t!==void 0)return t;const{baseBlueId:r,suffix:s}=this.getBaseBlueIdAndSuffix(e);if(s===void 0)return e;const n=this.aliasBlueIdMap.get(r);if(n===void 0)return e;if(this.getBaseBlueIdAndSuffix(n).suffix===void 0)return`${n}${s}`}getBaseBlueIdAndSuffix(e){const t=e.indexOf("#");return t===-1?{baseBlueId:e}:{baseBlueId:e.slice(0,t),suffix:e.slice(t)}}}class bi{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(Xe).forEach(([n,o])=>{this.blueIdToInlineValue.set(n,o)});const s=r.getAllBlueIds();Object.entries(s).forEach(([n,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,n)})}restore(e){return _.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 s=t();if(!s||s.isInlineValue()&&s.getValue()!==void 0)return;const n=s.getBlueId();if(!n)return;const o=this.resolveInlineValue(n,s);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 s=t.getName();if(s)return this.blueIdToInlineValue.set(e,s),s;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class Pi{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(Si(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)Li(this.contents,r.contents,r.name),Di(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){const t=this.aliases[e]??Wt[e]??e;for(const r of this.runtimes){const s=r.toCurrentBlueIdIndex[t];if(s)return s}return t}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=Xe[t];if(r)return r;for(const s of this.runtimes){const n=s.typeAliasByCurrentBlueId[t];if(n)return n}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const s=r.types[t];if(s)return{runtime:r,currentBlueId:t,typeMeta:s,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function Si(i){const e=wi(i);return Object.values(i.packages).forEach(t=>{Ei(e,i,t)}),{name:i.name,repositoryVersions:i.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 wi(i){const e=Object.fromEntries(i.repositoryVersions.map((r,s)=>[r,s])),t=i.repositoryVersions[i.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function Ei(i,e,t){if(i.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);i.packageNames.add(t.name),Ci(i,t),Ri(i,e,t),Ai(i,t),Oi(i,t)}function Ci(i,e){Object.entries(e.aliases).forEach(([t,r])=>{if(i.aliases[t]&&i.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);i.aliases[t]=r})}function Ri(i,e,t){Object.entries(t.typesMeta).forEach(([r,s])=>{if(i.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const n=Vi(s,e,r,t.name);if(i.types[r]=n,i.typePackageByCurrentBlueId[r]=t.name,i.typeAliasByCurrentBlueId[r]=`${t.name}/${s.name}`,n.status===B.BLUE_REPOSITORY_STATUS_STABLE&&!i.toCurrentBlueIdIndex[r]&&(i.toCurrentBlueIdIndex[r]=r),n.status===B.BLUE_REPOSITORY_STATUS_STABLE)for(const o of n.versions){const l=i.toCurrentBlueIdIndex[o.typeBlueId];if(l&&l!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);i.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function Ai(i,e){Object.entries(e.contents).forEach(([t,r])=>{i.contents[t]=r})}function Oi(i,e){i.schemas.push(...Object.values(e.schemas))}function Vi(i,e,t,r){if(i.status===B.BLUE_REPOSITORY_STATUS_DEV)return Mi(i,e,t,r),{...i,versions:i.versions?[...i.versions]:i.versions};const s=[...i.versions??[]].sort((o,l)=>o.repositoryVersionIndex-l.repositoryVersionIndex);if(s.length===0)throw new Error(`Stable type ${r}/${i.name} (${t}) must have at least one version entry`);const n=new Set;return s.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${i.name}`);if(n.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${i.name}`);n.add(o.repositoryVersionIndex);for(const l of o.attributesAdded??[])_i(l,e.name,t,o.repositoryVersionIndex)}),{...i,versions:s}}function Mi(i,e,t,r){if(i.status===B.BLUE_REPOSITORY_STATUS_DEV){if(i.versions&&i.versions.length>1)throw new Error(`Dev type ${r}/${i.name} (${t}) must not declare multiple versions`);if(i.versions&&i.versions.length===1){const s=i.versions[0];if(s.repositoryVersionIndex<0||s.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${s.repositoryVersionIndex} for dev type ${r}/${i.name}`)}}}function _i(i,e,t,r){try{B.validateAttributesAddedPointer(i)}catch(s){const n=s instanceof Error?s.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${i}' for type ${t} in repository ${e} at index ${r}: ${n}`)}}function Di(i,e,t){for(const[r,s]of Object.entries(e)){const n=i[r];if(n&&n!==s)throw new Error(`Conflicting alias '${r}' across repositories: '${n}' vs '${s}' (from ${t})`);i[r]=s}}function Li(i,e,t){for(const[r,s]of Object.entries(e)){if(r in i){const n=i[r];if(!ji(n,s))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}i[r]=s}}function ji(i,e){if(i===e)return!0;if(i===null||e===null||typeof i!="object"||typeof e!="object")return!1;const t=ke.canonicalize(i),r=ke.canonicalize(e);return t!==void 0&&t===r}const xi=new Set(["__proto__","constructor","prototype"]);function xt(i){const e=i.at(0),t=i.at(-1);return!e||!t?i:e==="'"&&t==="'"||e==='"'&&t==='"'?i.slice(1,-1):i}function $i(i,e){const t=i.indexOf("=");if(t===-1)throw me(e,`Missing '=' in segment '${i.trim()}'`);if(i.indexOf("=",t+1)!==-1)throw me(e,`Unexpected '=' in segment '${i.trim()}'`);const r=xt(i.slice(0,t).trim()),s=xt(i.slice(t+1).trim());if(!r)throw me(e,"Repository name is empty");if(!s)throw me(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:s}}function Fi(i){if(i.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of i.split(",")){const r=t.trim();if(!r)throw me(i,"Empty repository segment");const{name:s,value:n}=$i(r,i);Ui(s,i),e[s]=n}return e}function zi(i){return typeof i=="string"?Fi(i):i}function me(i,e){return new he(x.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:x.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:i,reason:e}}])}function Ui(i,e){if(xi.has(i))throw me(e,`Forbidden repository name '${i}'`)}function Ki(i,e){const t=i.filter(s=>s.repositoryVersionIndex>e).sort((s,n)=>n.repositoryVersionIndex-s.repositoryVersionIndex),r=[];for(const s of t){const n=[...s.attributesAdded].sort((o,l)=>$t(l)-$t(o));r.push(...n)}return r}function $t(i){return B.parsePointer(i).length}const Hi=new Set([...vt]),R={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class ki{registry;targetRepoVersionIndexes;fallbackToCurrentInlineDefinitions;inliningStack=new Set;constructor(e){this.registry=e.registry,this.targetRepoVersionIndexes=e.targetRepoVersionIndexes,this.fallbackToCurrentInlineDefinitions=e.fallbackToCurrentInlineDefinitions}transform(e){return _.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(),s=r?.getBlueId();if(!r||!s)return;const n=this.resolveType(s);switch(n.kind){case R.core:{r.setBlueId(n.blueId);return}case R.representable:{this.applyDropPointers([r],n.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,n.dropPointers),r.setBlueId(n.targetBlueId);return}case R.noRuntime:case R.noTargetContext:case R.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,s);return}throw n.kind===R.unrepresentable?n.error:this.unrepresentableError(s,n.kind===R.noTargetContext?`Repository '${n.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",n.kind===R.noTargetContext?n.runtime:void 0,n.kind===R.noTargetContext?n.meta:void 0,void 0,n.kind===R.noTargetContext?n.typeAlias:void 0)}}}resolveType(e){if(fe.includes(e))return{kind:R.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),s=this.registry.findRuntimeByBlueId(t);if(!s||!s.typeMeta)return{kind:R.noRuntime};const n=this.targetRepoVersionIndexes[s.runtime.name];if(n===void 0)return{kind:R.noTargetContext,currentBlueId:t,runtimeName:s.runtime.name,runtime:s.runtime,meta:s.typeMeta,typeAlias:r};const o=s.typeMeta;if(o.status===B.BLUE_REPOSITORY_STATUS_DEV){const f=s.runtime.repositoryVersions.length-1;if(n!==f)return{kind:R.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${n}.`,s.runtime,o,n,r)};const y=o.versions?.[0];return{kind:R.representable,currentBlueId:t,targetBlueId:y?.typeBlueId??t,dropPointers:[]}}const l=o.versions||[];if(l.length===0)return{kind:R.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,s.runtime,o,n,r)};const a=l[0].repositoryVersionIndex;if(n<a)return{kind:R.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${n}.`,s.runtime,o,n,r)};let c=l[0].typeBlueId;for(const f of l)f.repositoryVersionIndex<=n&&(c=f.typeBlueId);const p=o.status===B.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,n):[];return{kind:R.representable,currentBlueId:t,targetBlueId:c,dropPointers:p}}getDropPointers(e,t){return e.status!==B.BLUE_REPOSITORY_STATUS_STABLE?[]:Ki(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const s=r.rootIsSchema??!1;for(const n of t)for(const o of e)this.deletePropertyAtPointer(o,n,s)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,s])=>s instanceof d&&!Hi.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let s;try{s=B.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,s,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[s,...n]=t;if(s===K){const a=e.getType();a&&this.applyPointerSegments(a,n,!0);return}if(s===be){const a=e.getItemType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Pe){const a=e.getKeyType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Se){const a=e.getValueType();a&&this.applyPointerSegments(a,n,!0);return}const o=e.getProperties();if(!o)return;if(n.length===0){if(!r||!(s in o))return;const a={...o};delete a[s],e.setProperties(a);return}const l=o[s];l instanceof d&&this.applyPointerSegments(l,n,r)}inlineDefinition(e,t,r){const s=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(s))throw this.unrepresentableError(s,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(s)});const n=this.registry.getContents()[s];if(!n)throw this.unrepresentableError(s,`Missing definition to inline for BlueId ${s}.`);this.inliningStack.add(s);try{const o=m.deserialize(n);o.setBlueId(void 0);const l=_.transform(o,a=>this.transformNode(a));return t(l),e}finally{this.inliningStack.delete(s)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new he(x.INVALID_REPOSITORY_POINTER,t,[{code:x.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,s,n,o,l){const a={currentTypeBlueId:e,targetRepoVersionIndex:n,typeAlias:o,...l};if(r&&(n!==void 0&&(a.requestedRepoBlueId=r.repositoryVersions[n]),a.serverRepoBlueId=r.currentRepoBlueId),s&&s.status===B.BLUE_REPOSITORY_STATUS_STABLE){const p=s.versions?.[0]?.repositoryVersionIndex;p!==void 0&&(a.typeIntroducedInRepoBlueId=r?.repositoryVersions[p])}const c={code:x.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[K],context:a};return new he(x.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[c])}}function It(i,e){return e?_.transform(i,t=>(ze(()=>t.getType(),r=>t.setType(r),e),ze(()=>t.getItemType(),r=>t.setItemType(r),e),ze(()=>t.getKeyType(),r=>t.setKeyType(r),e),ze(()=>t.getValueType(),r=>t.setValueType(r),e),t)):i}function ze(i,e,t){const r=i();if(!r||r.isInlineValue())return;const s=r.getBlueId();if(!s)return;const n=t.toCurrentBlueId(s);n!==s&&e(r.clone().setBlueId(n))}class Yi{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 s=It(e,this.blueIdMapper);return new ki({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(s)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?zi(e.repositories):e.repositories;for(const[s,n]of Object.entries(r)){const o=this.registry.findRuntimeByName(s);if(!o)continue;const l=o.repoVersionIndexById[n];if(l===void 0)throw this.unknownRepoBlueIdError(s,n,o.currentRepoBlueId);t[s]=l}return t}unknownRepoBlueIdError(e,t,r){const s=`Unknown RepoBlueId '${t}' for repository '${e}'.`,n={code:x.REPO_UNKNOWN_REPO_BLUE_ID,message:s,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new he(x.REPO_UNKNOWN_REPO_BLUE_ID,s,[n])}}class Ne{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=$;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:s,repositories:n,mergingProcessor:o}=e;this.repositories=n,this.repositoryRegistry=new Pi(n??[]),this.blueContextResolver=new Yi({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry}),this.mergingProcessor=o??$e();const l=rt(()=>[]);this.nodeProvider=this.wrapNodeProviderWithRepositories(t||l,n),this.typeSchemaResolver=r??new gr([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.urlContentFetcher=new Ii(s),this.blueDirectivePreprocessor=new gi(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new Or,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const a=this.repositoryRegistry.getRuntimes().flatMap(c=>c.schemas);a.length>0&&this.typeSchemaResolver?.registerSchemas(a)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),s=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return T.get(s,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),s=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return ai.get(s,{strategy:r.format})}nodeToSchemaOutput(e,t){return new li(this.typeSchemaResolver,{calculateBlueId:s=>this.calculateBlueIdSync(s)}).convert(e,t)}resolve(e,t=$){const r=this.combineWithGlobalLimits(t),n=new oe(this.mergingProcessor,this.nodeProvider).resolve(e,r);if(!(r instanceof Y)){const o=this.getExactReferenceBlueId(e);o!==void 0&&n.setSourceSemanticBlueId(o)}return n}createResolvedNode(e){return e instanceof k?e:new k(e)}reverse(e){return this.minimize(e)}minimize(e){return new Re({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).minimize(e)}restoreInlineTypes(e){return new bi({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new Ot(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(m.deserialize(e));return It(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(m.deserialize(e));return It(t,this.repositoryRegistry)}yamlToNode(e){const t=ee(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}async yamlToNodeAsync(e){const t=ee(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 new Re({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).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 new Re({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).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 De({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new De({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}transform(e,t){return _.transform(e,t)}getNodeProvider(){return this.nodeProvider}setNodeProvider(e){return this.nodeProvider=this.wrapNodeProviderWithRepositories(e,this.repositories),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this}getExactReferenceBlueId(e){if(!P.hasBlueIdOnly(e))return;const t=e.getReferenceBlueId();return t!==void 0&&Te.isPotentialBlueId(t)?t:void 0}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 U.isTypeOf(e,t,{checkSchemaExtensions:r?.checkSchemaExtensions,typeSchemaResolver:this.typeSchemaResolver,blueIdMapper:this.repositoryRegistry})}isTypeOfBlueId(e,t){const r=this.repositoryRegistry.toCurrentBlueId(t.trim());if(r.length===0)return!1;const s=e.getType();if(!s)return!1;const n=new d().setReferenceBlueId(r);return C(s,n,this.nodeProvider)}isTypeOfNode(e,t){return new Ls(this).matchesType(e,t,this.globalLimits)}setGlobalLimits(e){return this.globalLimits=e??$,this}getGlobalLimits(){return this.globalLimits}normalizeNodeToJsonOptions(e){return typeof e=="string"?{format:e,blueContext:void 0}:{format:e?.format??"official",blueContext:e?.blueContext}}wrapNodeProviderWithRepositories(e,t){return t&&t.length>0?_e.wrap(new Ir([new Vt(t,{mergingProcessor:this.mergingProcessor}),e])):_e.wrap(e)}combineWithGlobalLimits(e){return this.globalLimits==$?e:e==$?this.globalLimits:tt.of(this.globalLimits,e)}}const Wi=Object.freeze(Object.defineProperty({__proto__:null,Blue:Ne},Symbol.toStringTag,{value:"Module"})),ut=new WeakMap,Ji=10;function Zi(i,e={}){const t=e.mergingProcessor===void 0;if(t){const a=ut.get(i);if(a)return a}const r=Mr(i);if(r.length===0)return t&&ut.set(i,i),i;const s=_r(i),n=e.mergingProcessor??$e();let o=Object.fromEntries(r.map(({oldBlueId:a})=>[a,a]));const l=qi(r.length);for(let a=0;a<l;a++){const c=en(r,s,o,n);if(nn(o,c)){const p=tn(i,o);return t&&ut.set(i,p),p}o=c}throw new Error(`Repository semantic reindexing did not converge after ${l} passes for ${r.length} entries.`)}function Gi(i,e={}){const t=Mr(i);if(t.length===0)return;const r=_r(i),s=e.mergingProcessor??$e(),n=new Ne({nodeProvider:Xi(t,r),mergingProcessor:s});n.registerBlueIds(r);for(const{packageName:o,oldBlueId:l,content:a}of t){const c=Array.isArray(a)?a.map(f=>n.jsonValueToNode(f)):n.jsonValueToNode(a),p=n.calculateBlueIdSync(c);if(p!==l)throw new he(x.BLUE_ID_MISMATCH,`Repository content key '${l}' does not match semantic BlueId '${p}'.`,[{code:x.BLUE_ID_MISMATCH,message:"Repository contents must be keyed by the semantic BlueId of their minimal storage form.",context:{packageName:o,providedBlueId:l,computedBlueId:p}}])}}function qi(i){return Math.max(Ji,i+1)}function Mr(i){const e=[];for(const[t,r]of Object.entries(i.packages))for(const[s,n]of Object.entries(r.contents))e.push({packageName:t,oldBlueId:s,content:n});return e}function _r(i){const e={};for(const t of Object.values(i.packages))for(const[r,s]of Object.entries(t.aliases))e[r]=s;return e}function Xi(i,e){const t=new Map(i.map(({oldBlueId:n,content:o})=>[n,o])),r=new Map(Object.entries(e)),s=new Ne;return{fetchByBlueId(n){const o=Qi(n,r);if(o===void 0)return[];const{baseBlueId:l,suffix:a}=Tt(o),c=t.get(l);if(c===void 0)return[];const p=Array.isArray(c),f=Ie.resolveThisReferences(c,l,p);if(a!==void 0){const y=Number(a.slice(1));if(Array.isArray(f)){const g=f[y];return g===void 0?[]:[s.jsonValueToNode(g)]}return y===0?[s.jsonValueToNode(f)]:[]}return Array.isArray(f)?f.map(y=>s.jsonValueToNode(y)):[s.jsonValueToNode(f)]},fetchFirstByBlueId(n){return this.fetchByBlueId(n)[0]??null}}}function Qi(i,e){const t=e.get(i);if(t!==void 0)return t;const{baseBlueId:r,suffix:s}=Tt(i);if(s===void 0)return i;const n=e.get(r);if(n===void 0)return i;if(Tt(n).suffix===void 0)return`${n}${s}`}function Tt(i){const e=i.indexOf("#");return e===-1?{baseBlueId:i}:{baseBlueId:i.slice(0,e),suffix:i.slice(e)}}function en(i,e,t,r){const s=new Map(i.map(({oldBlueId:c,content:p})=>[c,Ze(p,t)])),n=new Map;for(const{oldBlueId:c}of i)n.set(c,c),n.set(t[c],c);const o=new Ne,l={fetchByBlueId(c){const[p,f]=c.split("#"),y=n.get(p);if(!y)return[];const g=s.get(y);if(g===void 0)return[];if(Array.isArray(g)){if(f!==void 0){const I=g[Number(f)];return I===void 0?[]:[o.jsonValueToNode(I)]}return g.map(I=>o.jsonValueToNode(I))}return f!==void 0&&f!=="0"?[]:[o.jsonValueToNode(g)]},fetchFirstByBlueId(c){return this.fetchByBlueId(c)[0]??null}},a=new Ne({nodeProvider:l,mergingProcessor:r});return a.registerBlueIds(Dr(e,t)),Object.fromEntries(i.map(({packageName:c,oldBlueId:p})=>{const f=s.get(p);if(f===void 0)throw new Error(`Missing repository content for ${p}.`);try{const y=a.jsonValueToNode(f);return[p,a.calculateBlueIdSync(y)]}catch(y){const g=y instanceof Error?y.message:String(y);throw new Error(`Failed to calculate semantic BlueId for ${c}/${p}: ${g}`)}}))}function tn(i,e){return{name:i.name,repositoryVersions:i.repositoryVersions,packages:Object.fromEntries(Object.entries(i.packages).map(([t,r])=>[t,rn(r,e)]))}}function rn(i,e){return{name:i.name,aliases:Dr(i.aliases,e),typesMeta:Object.fromEntries(Object.entries(i.typesMeta).map(([t,r])=>[e[t]??t,sn(r,e)])),contents:Object.fromEntries(Object.entries(i.contents).map(([t,r])=>[e[t]??t,Ze(r,e)])),schemas:Object.fromEntries(Object.entries(i.schemas).map(([t,r])=>{const s=e[t]??t;return[s,pr(s)(r)]}))}}function sn(i,e){return{...i,versions:i.versions.map(t=>({...t,typeBlueId:Mt(t.typeBlueId,e)}))}}function nn(i,e){const t=Object.keys(i);return t.length!==Object.keys(e).length?!1:t.every(r=>i[r]===e[r])}function Dr(i,e){return Object.fromEntries(Object.entries(i).map(([t,r])=>[t,Mt(r,e)]))}function Ze(i,e){return Array.isArray(i)?i.map(t=>Ze(t,e)):i&&typeof i=="object"?Object.fromEntries(Object.entries(i).map(([t,r])=>[t,t==="blueId"&&typeof r=="string"?Mt(r,e):Ze(r,e)])):i}function Mt(i,e){const t=e[i];if(t!==void 0)return t;const r=/^(.*)(#\d+)$/.exec(i);if(!r)return i;const[,s,n]=r;return`${e[s]??s}${n}`}class on extends Vr{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;preprocessor;storageService;constructor(e=[]){super();const t=new De({nodeProvider:this});this.preprocessor=r=>t.preprocessWithDefaultBlue(r),this.storageService=new Js({nodeProvider:this}),e.forEach(r=>this.processNode(r))}processNode(e){P.hasItemsOnly(e)?this.processNodeWithItems(e):this.processSingleNode(e)}processSingleNode(e){const t=Ie.parseAndCalculateBlueIdForNode(e,this.preprocessor,this.storageService);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;const r=this.storeNodeList(t);this.addListItemNames(r.blueId,r.content)}processNodeList(e){this.storeNodeList(e)}storeNodeList(e){const t=Ie.parseAndCalculateBlueIdForNodeList(e,this.preprocessor,this.storageService);return this.blueIdToContentMap.set(t.blueId,t.content),this.blueIdToMultipleDocumentsMap.set(t.blueId,!0),t}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?Ie.resolveThisReferences(t,e,r):null}addSingleNodes(...e){e.forEach(t=>this.processNode(t))}addSingleDocs(...e){e.forEach(t=>{const r=ee(t);if(r!==void 0){const s=m.deserialize(r);this.processNode(s)}})}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){const t=this.storeNodeList(e);if(M.hasThisReference(e)){this.addListItemNames(t.blueId,t.content);return}e.forEach(r=>this.processNode(r))}addListAndItsItemsFromDoc(e){const t=ee(e);if(t!==void 0){const s=m.deserialize(t).getItems();s&&this.addListAndItsItems(s)}}addListAndItsItems(e){Array.isArray(e)?this.addListAndItsItemsFromNodes(e):this.addListAndItsItemsFromDoc(e)}addList(e){this.processNodeList(e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,s)=>{const o=m.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${s}`)})}}exports.Base58Sha256Provider=Xt;exports.BasicNodeProvider=on;exports.Blue=Ne;exports.BlueIdCalculator=A;exports.BlueIdToCid=cs;exports.BlueNode=d;exports.BlueNodeTypeSchema=U;exports.JsonCanonicalizer=ke;exports.Limits=Qe;exports.Merger=oe;exports.MergingProcessors=Ws;exports.NodeResolver=mr;exports.Nodes=P;exports.Properties=Fr;exports.ResolvedBlueNode=k;exports.SemanticIdentityService=Re;exports.TypeSchemaResolver=gr;exports.applyBlueNodePatch=Ts;exports.baseBlueObjectSchema=je;exports.blueDescriptionField=Bs;exports.blueIdField=bs;exports.blueIdSchema=Ur;exports.blueNameField=Ps;exports.blueNodeField=Ss;exports.blueObjectBooleanValueSchema=kr;exports.blueObjectNumberValueSchema=Hr;exports.blueObjectSchema=ve;exports.blueObjectStringListItemsSchema=Yr;exports.blueObjectStringValueSchema=Kr;exports.createNodeProvider=rt;exports.enrichWithBlueId=gt;exports.getBlueDescriptionAnnotation=nr;exports.getBlueIdAnnotation=lr;exports.getBlueNameAnnotation=cr;exports.getBlueNodeAnnotation=dr;exports.getBlueObjectItems=ci;exports.getBlueObjectProperties=di;exports.getBlueObjectTypeLabel=hi;exports.getBlueObjectValue=ui;exports.getTypeBlueIdAnnotation=hr;exports.hasBlueObjectBlueIdDefined=Jt;exports.hasBlueObjectItemsDefined=Zt;exports.hasBlueObjectNameDefined=Jr;exports.hasBlueObjectTypeDefined=Gt;exports.hasBlueObjectValueDefined=qt;exports.isBigDecimalNumber=He;exports.isBigIntegerNumber=Q;exports.isBigNumber=E;exports.isBlueNodeSchema=Rt;exports.isBlueObject=Wr;exports.isBlueObjectResolved=Ar;exports.isGivenBlueObjectTypeSchema=Zr;exports.isJsonBlueArray=St;exports.isJsonBlueObject=Pt;exports.isJsonBlueValue=Xr;exports.isUrl=Ae;exports.jsonBlueValueSchema=Ve;exports.normalizeToBlueObject=pi;exports.reindexRepositoryForSemanticStorage=Zi;exports.resolveBlueObjectItems=mt;exports.validateRepositorySemanticStorage=Gi;exports.withBlueDescription=ir;exports.withBlueId=or;exports.withBlueName=ar;exports.withBlueNode=ur;exports.withTypeBlueId=pr;exports.yamlBlueDump=vr;exports.yamlBlueParse=ee;
|
|
26
|
+
`}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(gr),t=ee(e);if(t)this.defaultSimpleBlue=m.deserialize(t);else throw new Error("Failed to parse default Blue content")}catch(e){throw new Error(`Error loading default Blue: ${e}`)}}}class ui{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(me.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(me.isPotentialBlueId(t))return this.handleBlueId(r,t);if(Ce(t)&&this.urlContentFetcher)try{const s=await this.fetchFromUrl(t);return s&&r.setBlue(new d().setItems(s)),r}catch(s){throw s instanceof Error?new Error(`Failed to fetch from URL '${t}'.
|
|
27
|
+
${s.message}`):s}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 di={fetchUrl:async i=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${i}`)}};class hi{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||di}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:s}=t;let n;if(s.includes("application/json")||s.includes("text/yaml")||s.includes("application/yaml")||s.includes("text/plain"))n=ee(r);else throw new Error(`Unsupported content type from URL: ${s}`);if(n===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(n)?o=n.map(l=>m.deserialize(l)):o=[m.deserialize(n)],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 xe{constructor(e,t,r,s=[],n=!1){this.blueId=e,this.content=t,this.isMultipleDocuments=r,this.documentBlueIds=s,this.isCyclicSet=n}}class Re{static THIS_REFERENCE_PATTERN=/^this(#\d+)?$/;static parseAndCalculateBlueId(e,t,r){let s;try{const a=ee(e);if(a===void 0)throw new Error;s=a}catch{throw new Error("Failed to parse content as YAML or JSON")}let n,o;const l=Array.isArray(s);if(l){const a=s.map(p=>m.deserialize(p)),c=r.prepareStorageNodeList(a,t);return n=c.blueId,o=c.nodes.map(p=>T.get(p)),new xe(n,o,!0,c.documentBlueIds,c.isCyclicSet??!1)}else{const a=m.deserialize(s),c=r.prepareStorageNode(a,t);n=c.blueId,o=T.get(c.node)}return new xe(n,o,l)}static parseAndCalculateBlueIdForNode(e,t,r){const s=r.prepareStorageNode(e,t),n=T.get(s.node);return new xe(s.blueId,n,!1)}static parseAndCalculateBlueIdForNodeList(e,t,r){if(!e||e.length===0)throw new Error("List of nodes cannot be null or empty");const s=r.prepareStorageNodeList(e,t),n=s.nodes.map(l=>T.get(l)),o=!0;return new xe(s.blueId,n,o,s.documentBlueIds,s.isCyclicSet??!1)}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 s={};for(const[n,o]of Object.entries(e))typeof o=="string"?n===V&&this.THIS_REFERENCE_PATTERN.test(o)?s[n]=this.resolveThisReference(o,t,r):s[n]=o:o&&typeof o=="object"?s[n]=this.resolveThisReferencesRecursive(o,t,r):s[n]=o;return s}else if(Array.isArray(e))return e.map(s=>s&&typeof s=="object"?this.resolveThisReferencesRecursive(s,t,r):s);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 pi extends fe{fetchByBlueId(e){const t=e.split("#")[0],r=this.fetchContentByBlueId(t);if(r==null)return null;const s=Array.isArray(r),n=Re.resolveThisReferences(r,t,s);if(e.includes("#")){const o=e.split("#");if(o.length>1){const l=parseInt(o[1]);if(Array.isArray(n)&&l<n.length){const a=n[l];return[m.deserialize(a)]}else return l===0?[m.deserialize(n)]:null}}return Array.isArray(n)?n.map(o=>m.deserialize(o)):[m.deserialize(n)]}}class Er extends pi{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 s of t){const n=this.fetchByBlueId(s);n&&r.push(...n)}return r}addToNameMap(e,t){this.nameToBlueIdsMap.set(e,[...this.nameToBlueIdsMap.get(e)||[],t])}}function fi(i){return Array.isArray(i)?yi(i):i}function yi(i){const e=i.map(t=>m.deserialize(t));return M.hasIndexedThisReference(e)?gi(e):i}function gi(i){return new M().calculate(i).nodes.map(t=>T.get(t))}class Rt extends Er{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;aliasBlueIdMap=new Map;constructor(e,t={}){super();const r=Rt.collectAliasMappings(e);this.aliasBlueIdMap=new Map(Object.entries(r)),this.loadRepositories(e)}static collectAliasMappings(e){const t={};for(const r of e)for(const s of Object.values(r.packages))for(const[n,o]of Object.entries(s.aliases)){const l=t[n];if(l&&l!==o)throw new Error(`Conflicting alias mapping for ${n}`);t[n]=o}return t}loadRepositories(e){for(const t of e)Object.values(t.packages).forEach(r=>{for(const[s,n]of Object.entries(r.contents)){const o=fi(n);this.storeContent(s,o,Array.isArray(o)),this.addContentNames(s,o)}})}addContentNames(e,t){if(Array.isArray(t)){this.addListItemNames(e,t);return}const s=m.deserialize(t).getName();s&&this.addToNameMap(s,e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,s)=>{const o=m.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${s}`)})}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?Re.resolveThisReferences(t,e,r):null}fetchByBlueId(e){const t=this.resolveAliasBlueId(e);return t===void 0?null:super.fetchByBlueId(t)}storeContent(e,t,r){this.blueIdToContentMap.set(e,t),this.blueIdToMultipleDocumentsMap.set(e,r)}getBlueIds(){return Array.from(this.blueIdToContentMap.keys())}hasBlueId(e){const t=this.resolveAliasBlueId(e);return t===void 0?!1:this.blueIdToContentMap.has(this.getBaseBlueIdAndSuffix(t).baseBlueId)}resolveAliasBlueId(e){const t=this.aliasBlueIdMap.get(e);if(t!==void 0)return t;const{baseBlueId:r,suffix:s}=this.getBaseBlueIdAndSuffix(e);if(s===void 0)return e;const n=this.aliasBlueIdMap.get(r);if(n===void 0)return e;if(this.getBaseBlueIdAndSuffix(n).suffix===void 0)return`${n}${s}`}getBaseBlueIdAndSuffix(e){const t=e.indexOf("#");return t===-1?{baseBlueId:e}:{baseBlueId:e.slice(0,t),suffix:e.slice(t)}}}class mi{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(Ge).forEach(([n,o])=>{this.blueIdToInlineValue.set(n,o)});const s=r.getAllBlueIds();Object.entries(s).forEach(([n,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,n)})}restore(e){return L.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 s=t();if(!s||s.isInlineValue()&&s.getValue()!==void 0)return;const n=s.getBlueId();if(!n)return;const o=this.resolveInlineValue(n,s);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 s=t.getName();if(s)return this.blueIdToInlineValue.set(e,s),s;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class Ii{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(Ti(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)Ai(this.contents,r.contents,r.name),Ri(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){const t=this.aliases[e]??Kt[e]??e;for(const r of this.runtimes){const s=r.toCurrentBlueIdIndex[t];if(s)return s}return t}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=Ge[t];if(r)return r;for(const s of this.runtimes){const n=s.typeAliasByCurrentBlueId[t];if(n)return n}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const s=r.types[t];if(s)return{runtime:r,currentBlueId:t,typeMeta:s,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function Ti(i){const e=vi(i);return Object.values(i.packages).forEach(t=>{Bi(e,i,t)}),{name:i.name,repositoryVersions:i.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 vi(i){const e=Object.fromEntries(i.repositoryVersions.map((r,s)=>[r,s])),t=i.repositoryVersions[i.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function Bi(i,e,t){if(i.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);i.packageNames.add(t.name),Ni(i,t),bi(i,e,t),Pi(i,t),Si(i,t)}function Ni(i,e){Object.entries(e.aliases).forEach(([t,r])=>{if(i.aliases[t]&&i.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);i.aliases[t]=r})}function bi(i,e,t){Object.entries(t.typesMeta).forEach(([r,s])=>{if(i.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const n=wi(s,e,r,t.name);if(i.types[r]=n,i.typePackageByCurrentBlueId[r]=t.name,i.typeAliasByCurrentBlueId[r]=`${t.name}/${s.name}`,n.status===B.BLUE_REPOSITORY_STATUS_STABLE&&!i.toCurrentBlueIdIndex[r]&&(i.toCurrentBlueIdIndex[r]=r),n.status===B.BLUE_REPOSITORY_STATUS_STABLE)for(const o of n.versions){const l=i.toCurrentBlueIdIndex[o.typeBlueId];if(l&&l!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);i.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function Pi(i,e){Object.entries(e.contents).forEach(([t,r])=>{i.contents[t]=r})}function Si(i,e){i.schemas.push(...Object.values(e.schemas))}function wi(i,e,t,r){if(i.status===B.BLUE_REPOSITORY_STATUS_DEV)return Ei(i,e,t,r),{...i,versions:i.versions?[...i.versions]:i.versions};const s=[...i.versions??[]].sort((o,l)=>o.repositoryVersionIndex-l.repositoryVersionIndex);if(s.length===0)throw new Error(`Stable type ${r}/${i.name} (${t}) must have at least one version entry`);const n=new Set;return s.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${i.name}`);if(n.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${i.name}`);n.add(o.repositoryVersionIndex);for(const l of o.attributesAdded??[])Ci(l,e.name,t,o.repositoryVersionIndex)}),{...i,versions:s}}function Ei(i,e,t,r){if(i.status===B.BLUE_REPOSITORY_STATUS_DEV){if(i.versions&&i.versions.length>1)throw new Error(`Dev type ${r}/${i.name} (${t}) must not declare multiple versions`);if(i.versions&&i.versions.length===1){const s=i.versions[0];if(s.repositoryVersionIndex<0||s.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${s.repositoryVersionIndex} for dev type ${r}/${i.name}`)}}}function Ci(i,e,t,r){try{B.validateAttributesAddedPointer(i)}catch(s){const n=s instanceof Error?s.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${i}' for type ${t} in repository ${e} at index ${r}: ${n}`)}}function Ri(i,e,t){for(const[r,s]of Object.entries(e)){const n=i[r];if(n&&n!==s)throw new Error(`Conflicting alias '${r}' across repositories: '${n}' vs '${s}' (from ${t})`);i[r]=s}}function Ai(i,e,t){for(const[r,s]of Object.entries(e)){if(r in i){const n=i[r];if(!Oi(n,s))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}i[r]=s}}function Oi(i,e){if(i===e)return!0;if(i===null||e===null||typeof i!="object"||typeof e!="object")return!1;const t=He.canonicalize(i),r=He.canonicalize(e);return t!==void 0&&t===r}const Vi=new Set(["__proto__","constructor","prototype"]);function Dt(i){const e=i.at(0),t=i.at(-1);return!e||!t?i:e==="'"&&t==="'"||e==='"'&&t==='"'?i.slice(1,-1):i}function Mi(i,e){const t=i.indexOf("=");if(t===-1)throw ge(e,`Missing '=' in segment '${i.trim()}'`);if(i.indexOf("=",t+1)!==-1)throw ge(e,`Unexpected '=' in segment '${i.trim()}'`);const r=Dt(i.slice(0,t).trim()),s=Dt(i.slice(t+1).trim());if(!r)throw ge(e,"Repository name is empty");if(!s)throw ge(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:s}}function Di(i){if(i.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of i.split(",")){const r=t.trim();if(!r)throw ge(i,"Empty repository segment");const{name:s,value:n}=Mi(r,i);Li(s,i),e[s]=n}return e}function _i(i){return typeof i=="string"?Di(i):i}function ge(i,e){return new Te(K.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:K.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:i,reason:e}}])}function Li(i,e){if(Vi.has(i))throw ge(e,`Forbidden repository name '${i}'`)}function $i(i,e){const t=i.filter(s=>s.repositoryVersionIndex>e).sort((s,n)=>n.repositoryVersionIndex-s.repositoryVersionIndex),r=[];for(const s of t){const n=[...s.attributesAdded].sort((o,l)=>_t(l)-_t(o));r.push(...n)}return r}function _t(i){return B.parsePointer(i).length}const ji=new Set([...gt]),C={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class xi{registry;targetRepoVersionIndexes;fallbackToCurrentInlineDefinitions;inliningStack=new Set;constructor(e){this.registry=e.registry,this.targetRepoVersionIndexes=e.targetRepoVersionIndexes,this.fallbackToCurrentInlineDefinitions=e.fallbackToCurrentInlineDefinitions}transform(e){return L.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(),s=r?.getBlueId();if(!r||!s)return;const n=this.resolveType(s);switch(n.kind){case C.core:{r.setBlueId(n.blueId);return}case C.representable:{this.applyDropPointers([r],n.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,n.dropPointers),r.setBlueId(n.targetBlueId);return}case C.noRuntime:case C.noTargetContext:case C.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,s);return}throw n.kind===C.unrepresentable?n.error:this.unrepresentableError(s,n.kind===C.noTargetContext?`Repository '${n.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",n.kind===C.noTargetContext?n.runtime:void 0,n.kind===C.noTargetContext?n.meta:void 0,void 0,n.kind===C.noTargetContext?n.typeAlias:void 0)}}}resolveType(e){if(pe.includes(e))return{kind:C.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),s=this.registry.findRuntimeByBlueId(t);if(!s||!s.typeMeta)return{kind:C.noRuntime};const n=this.targetRepoVersionIndexes[s.runtime.name];if(n===void 0)return{kind:C.noTargetContext,currentBlueId:t,runtimeName:s.runtime.name,runtime:s.runtime,meta:s.typeMeta,typeAlias:r};const o=s.typeMeta;if(o.status===B.BLUE_REPOSITORY_STATUS_DEV){const f=s.runtime.repositoryVersions.length-1;if(n!==f)return{kind:C.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${n}.`,s.runtime,o,n,r)};const y=o.versions?.[0];return{kind:C.representable,currentBlueId:t,targetBlueId:y?.typeBlueId??t,dropPointers:[]}}const l=o.versions||[];if(l.length===0)return{kind:C.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,s.runtime,o,n,r)};const a=l[0].repositoryVersionIndex;if(n<a)return{kind:C.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${n}.`,s.runtime,o,n,r)};let c=l[0].typeBlueId;for(const f of l)f.repositoryVersionIndex<=n&&(c=f.typeBlueId);const p=o.status===B.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,n):[];return{kind:C.representable,currentBlueId:t,targetBlueId:c,dropPointers:p}}getDropPointers(e,t){return e.status!==B.BLUE_REPOSITORY_STATUS_STABLE?[]:$i(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const s=r.rootIsSchema??!1;for(const n of t)for(const o of e)this.deletePropertyAtPointer(o,n,s)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,s])=>s instanceof d&&!ji.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let s;try{s=B.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,s,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[s,...n]=t;if(s===U){const a=e.getType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Be){const a=e.getItemType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Ne){const a=e.getKeyType();a&&this.applyPointerSegments(a,n,!0);return}if(s===be){const a=e.getValueType();a&&this.applyPointerSegments(a,n,!0);return}const o=e.getProperties();if(!o)return;if(n.length===0){if(!r||!(s in o))return;const a={...o};delete a[s],e.setProperties(a);return}const l=o[s];l instanceof d&&this.applyPointerSegments(l,n,r)}inlineDefinition(e,t,r){const s=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(s))throw this.unrepresentableError(s,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(s)});const n=this.registry.getContents()[s];if(!n)throw this.unrepresentableError(s,`Missing definition to inline for BlueId ${s}.`);this.inliningStack.add(s);try{const o=m.deserialize(n);o.setBlueId(void 0);const l=L.transform(o,a=>this.transformNode(a));return t(l),e}finally{this.inliningStack.delete(s)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new Te(K.INVALID_REPOSITORY_POINTER,t,[{code:K.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,s,n,o,l){const a={currentTypeBlueId:e,targetRepoVersionIndex:n,typeAlias:o,...l};if(r&&(n!==void 0&&(a.requestedRepoBlueId=r.repositoryVersions[n]),a.serverRepoBlueId=r.currentRepoBlueId),s&&s.status===B.BLUE_REPOSITORY_STATUS_STABLE){const p=s.versions?.[0]?.repositoryVersionIndex;p!==void 0&&(a.typeIntroducedInRepoBlueId=r?.repositoryVersions[p])}const c={code:K.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[U],context:a};return new Te(K.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[c])}}function yt(i,e){return e?L.transform(i,t=>(Fe(()=>t.getType(),r=>t.setType(r),e),Fe(()=>t.getItemType(),r=>t.setItemType(r),e),Fe(()=>t.getKeyType(),r=>t.setKeyType(r),e),Fe(()=>t.getValueType(),r=>t.setValueType(r),e),t)):i}function Fe(i,e,t){const r=i();if(!r||r.isInlineValue())return;const s=r.getBlueId();if(!s)return;const n=t.toCurrentBlueId(s);n!==s&&e(r.clone().setBlueId(n))}class Fi{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 s=yt(e,this.blueIdMapper);return new xi({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(s)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?_i(e.repositories):e.repositories;for(const[s,n]of Object.entries(r)){const o=this.registry.findRuntimeByName(s);if(!o)continue;const l=o.repoVersionIndexById[n];if(l===void 0)throw this.unknownRepoBlueIdError(s,n,o.currentRepoBlueId);t[s]=l}return t}unknownRepoBlueIdError(e,t,r){const s=`Unknown RepoBlueId '${t}' for repository '${e}'.`,n={code:K.REPO_UNKNOWN_REPO_BLUE_ID,message:s,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new Te(K.REPO_UNKNOWN_REPO_BLUE_ID,s,[n])}}class Cr{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=x;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:s,repositories:n,mergingProcessor:o}=e;this.repositories=n,this.repositoryRegistry=new Ii(n??[]),this.blueContextResolver=new Fi({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry}),this.mergingProcessor=o??Ct();const l=et(()=>[]);this.nodeProvider=this.wrapNodeProviderWithRepositories(t||l,n),this.typeSchemaResolver=r??new dr([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.urlContentFetcher=new hi(s),this.blueDirectivePreprocessor=new ui(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new wr,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const a=this.repositoryRegistry.getRuntimes().flatMap(c=>c.schemas);a.length>0&&this.typeSchemaResolver?.registerSchemas(a)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),s=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return T.get(s,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),s=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return ri.get(s,{strategy:r.format})}nodeToSchemaOutput(e,t){return new ti(this.typeSchemaResolver,{calculateBlueId:s=>this.calculateBlueIdSync(s)}).convert(e,t)}resolve(e,t=x){const r=this.combineWithGlobalLimits(t),n=new oe(this.mergingProcessor,this.nodeProvider).resolve(e,r);if(!(r instanceof k)){const o=this.getExactReferenceBlueId(e);o!==void 0&&n.setSourceSemanticBlueId(o)}return n}createResolvedNode(e){return e instanceof Y?e:new Y(e)}reverse(e){return this.minimize(e)}minimize(e){return new Ee({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).minimize(e)}restoreInlineTypes(e){return new mi({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new Et(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(m.deserialize(e));return yt(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(m.deserialize(e));return yt(t,this.repositoryRegistry)}yamlToNode(e){const t=ee(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}async yamlToNodeAsync(e){const t=ee(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 new Ee({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).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 new Ee({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).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 De({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new De({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}transform(e,t){return L.transform(e,t)}getNodeProvider(){return this.nodeProvider}setNodeProvider(e){return this.nodeProvider=this.wrapNodeProviderWithRepositories(e,this.repositories),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this}getExactReferenceBlueId(e){if(!N.hasBlueIdOnly(e))return;const t=e.getReferenceBlueId();return t!==void 0&&me.isPotentialBlueId(t)?t:void 0}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 z.isTypeOf(e,t,{checkSchemaExtensions:r?.checkSchemaExtensions,typeSchemaResolver:this.typeSchemaResolver,blueIdMapper:this.repositoryRegistry})}isTypeOfBlueId(e,t){const r=this.repositoryRegistry.toCurrentBlueId(t.trim());if(r.length===0)return!1;const s=e.getType();if(!s)return!1;const n=new d().setReferenceBlueId(r);return w(s,n,this.nodeProvider)}isTypeOfNode(e,t){return new As(this).matchesType(e,t,this.globalLimits)}setGlobalLimits(e){return this.globalLimits=e??x,this}getGlobalLimits(){return this.globalLimits}normalizeNodeToJsonOptions(e){return typeof e=="string"?{format:e,blueContext:void 0}:{format:e?.format??"official",blueContext:e?.blueContext}}wrapNodeProviderWithRepositories(e,t){return t&&t.length>0?Me.wrap(new pr([new Rt(t,{mergingProcessor:this.mergingProcessor}),e])):Me.wrap(e)}combineWithGlobalLimits(e){return this.globalLimits==x?e:e==x?this.globalLimits:Qe.of(this.globalLimits,e)}}const zi=Object.freeze(Object.defineProperty({__proto__:null,Blue:Cr},Symbol.toStringTag,{value:"Module"}));class Ui extends Er{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;preprocessor;storageService;constructor(e=[]){super();const t=new De({nodeProvider:this});this.preprocessor=r=>t.preprocessWithDefaultBlue(r),this.storageService=new Us({nodeProvider:this}),e.forEach(r=>this.processNode(r))}processNode(e){N.hasItemsOnly(e)?this.processNodeWithItems(e):this.processSingleNode(e)}processSingleNode(e){const t=Re.parseAndCalculateBlueIdForNode(e,this.preprocessor,this.storageService);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;const r=this.storeNodeList(t);this.addListItemNames(r.blueId,r.content)}processNodeList(e){this.storeNodeList(e)}storeNodeList(e){const t=Re.parseAndCalculateBlueIdForNodeList(e,this.preprocessor,this.storageService);return this.blueIdToContentMap.set(t.blueId,t.content),this.blueIdToMultipleDocumentsMap.set(t.blueId,!0),t}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?Re.resolveThisReferences(t,e,r):null}addSingleNodes(...e){e.forEach(t=>this.processNode(t))}addSingleDocs(...e){e.forEach(t=>{const r=ee(t);if(r!==void 0){const s=m.deserialize(r);this.processNode(s)}})}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){const t=this.storeNodeList(e);if(M.hasThisReference(e)){this.addListItemNames(t.blueId,t.content);return}e.forEach(r=>this.processNode(r))}addListAndItsItemsFromDoc(e){const t=ee(e);if(t!==void 0){const s=m.deserialize(t).getItems();s&&this.addListAndItsItems(s)}}addListAndItsItems(e){Array.isArray(e)?this.addListAndItsItemsFromNodes(e):this.addListAndItsItemsFromDoc(e)}addList(e){this.processNodeList(e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,s)=>{const o=m.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${s}`)})}}exports.Base58Sha256Provider=Wt;exports.BasicNodeProvider=Ui;exports.Blue=Cr;exports.BlueIdCalculator=A;exports.BlueIdToCid=rs;exports.BlueNode=d;exports.BlueNodeTypeSchema=z;exports.JsonCanonicalizer=He;exports.Limits=qe;exports.Merger=oe;exports.MergingProcessors=zs;exports.NodeResolver=hr;exports.Nodes=N;exports.Properties=Mr;exports.ResolvedBlueNode=Y;exports.SemanticIdentityService=Ee;exports.TypeSchemaResolver=dr;exports.applyBlueNodePatch=hs;exports.baseBlueObjectSchema=Le;exports.blueDescriptionField=fs;exports.blueIdField=gs;exports.blueIdSchema=_r;exports.blueNameField=ms;exports.blueNodeField=Is;exports.blueObjectBooleanValueSchema=jr;exports.blueObjectNumberValueSchema=$r;exports.blueObjectSchema=Ie;exports.blueObjectStringListItemsSchema=xr;exports.blueObjectStringValueSchema=Lr;exports.createNodeProvider=et;exports.enrichWithBlueId=pt;exports.getBlueDescriptionAnnotation=tr;exports.getBlueIdAnnotation=sr;exports.getBlueNameAnnotation=nr;exports.getBlueNodeAnnotation=lr;exports.getBlueObjectItems=si;exports.getBlueObjectProperties=ni;exports.getBlueObjectTypeLabel=oi;exports.getBlueObjectValue=ii;exports.getTypeBlueIdAnnotation=ar;exports.hasBlueObjectBlueIdDefined=Ht;exports.hasBlueObjectItemsDefined=Yt;exports.hasBlueObjectNameDefined=zr;exports.hasBlueObjectTypeDefined=kt;exports.hasBlueObjectValueDefined=Jt;exports.isBigDecimalNumber=Ke;exports.isBigIntegerNumber=Q;exports.isBigNumber=E;exports.isBlueNodeSchema=St;exports.isBlueObject=Fr;exports.isBlueObjectResolved=Sr;exports.isGivenBlueObjectTypeSchema=Ur;exports.isJsonBlueArray=Bt;exports.isJsonBlueObject=vt;exports.isJsonBlueValue=Yr;exports.isUrl=Ce;exports.jsonBlueValueSchema=Oe;exports.normalizeToBlueObject=li;exports.resolveBlueObjectItems=ft;exports.withBlueDescription=er;exports.withBlueId=rr;exports.withBlueName=ir;exports.withBlueNode=or;exports.withTypeBlueId=vs;exports.yamlBlueDump=yr;exports.yamlBlueParse=ee;
|