@blue-labs/language 5.0.0-rc.2 → 5.0.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Blue-BwbQa9VQ.js → Blue-COev3Ekz.js} +6 -6
- package/dist/{Blue-Cnkas-g6.mjs → Blue-Cr47qYiN.mjs} +227 -198
- package/dist/conformance.js +1 -1
- package/dist/conformance.mjs +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +3 -3
- package/dist/lib/model/NodeDeserializer.d.ts +4 -1
- package/dist/lib/model/NodeDeserializer.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const fe=require("big.js"),u=require("@blue-labs/shared-utils"),m=require("zod"),$r=require("bs58"),ve=require("radash"),y=require("@blue-labs/repository-contract"),kr=require("js-sha256"),qr=require("crypto");require("base32.js");const Be=require("js-yaml"),Ht=n=>n&&n.__esModule?n:{default:n},De=Ht($r),pt=Ht(qr);class V extends fe{constructor(e){super(e)}}class R extends fe{constructor(e){super(e)}}const ae="name",le="description",U="type",me="itemType",ge="keyType",ye="valueType",X="value",Te="items",N="blueId",rt="blue",wt="constraints",St="properties",Kr="positional",Gr="append-only",ce="$previous",it="$pos",st="$replace",Ie="$empty",Ct=[ae,le,U,me,ge,ye,X,Te,N,rt,y.OBJECT_SCHEMA,y.OBJECT_MERGE_POLICY,y.OBJECT_CONTRACTS,wt,St,ce,it,st,Ie],Yt="Text",Wt="Double",Zt="Integer",Jt="Boolean",Xt="List",Qt="Dictionary",nt=[Yt,Wt,Zt,Jt],Rt=[...nt,Xt,Qt],z="GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC",_="9eWaHYz2vKrFofdHTHAizNNu8xP6QE3WQ5y7DGrGZvyJ",j="E2LM6qgzWG9ttagq2xTmiZkgYEAgkYedFCmU9v7NnVEq",K="AwvXD961fmnmqcSQhjMA7r15HpVh39cefb6ZTyUz2Fm2",ot="8DSFoWG9MqRSUhStqoPLrwVQiYByRh18NWbDEarN8MKF",at="Efkz9D1ARMM7rU43w3rDNVqat1naS6qXKCqP4eHin3yG",At=[z,_,j,K],ie=[...At,ot,at],lt=Object.fromEntries(Rt.map((n,e)=>[n,ie[e]])),ct=Object.fromEntries(ie.map((n,e)=>[n,Rt[e]])),Z={Contract:"6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF","Json Patch Entry":"61W96XosAp3DrEC7PuqLYtmF2A6ETpqH6qF2DgYwDq4c","Contract Execution Result":"AMtAXPmvumgz1GxKUU9uv3ncXiKMENvqq8AaLvD5LXhv",Channel:"4FAZ94JPExNM4pn2ZhtdHa4CVP7uASmLNVrBy7aCG1p5",Handler:"7X46P3Q6FJrogqKrBXTALpqzkieyyiQeatnqLvWzAPXE",Marker:"6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy","Process Embedded":"8FVc8MPz6DcTMgcY3RXU6EBpGa9arWPJ141K2H86yi8Q","Processing Initialized Marker":"6JjyUKoK7uJxA5NY9YhMaKJbXC6c9iHyx1khv4gaAq4Q","Processing Terminated Marker":"GBDBthfshBFr4GQKUU1fmy4GnPL7q2y3as4deUWpuBtu","Channel Event Checkpoint":"9GEC24YbFG9hj4banjYh2oEnDpAob1wAPmhjuykJp8T1","Type Generalization Policy":"Fbenow6tanFHkWzKiDD8fGxminQswQ1FecMRakaCx2WX","Type Generalization Rule":"7Vnmk8StjwY7e9mBNpACrn8oh3KZ7yQBjnXe5bLDWn4D","Document Update Channel":"Ac9LC5T7pHVa1TtkhMBjBRtxecShzvbe7ugUdXT1Mu2o","Triggered Event Channel":"5HwxfbwRBCxG8xYpowWkCPC9akqUSKV7So2M4QHEmLsZ","Lifecycle Event Channel":"2DXGQUiQBQ6CT89jwAsTAXaEPhLgiSXhKCGh9Q7Hv3MQ","Embedded Node Channel":"H6iUJp3GcLypsJDimMSVoxQQdxxuD8j6eqEUWWqCZ6i","Document Update":"7HEaG1SpBdsbVHsrwRTZSZGmpJUWHfFoEzecYWpjo1vm","Document Processing Initiated":"Ht1o66MTLKf7JmnEiR27rRLSwdz8FUTgf2mGPNuLSDUL","Document Processing Terminated":"4HWncQEQsdpk8zcXxYxgdtoXo5nKHxFPWeJfTscCbmeK","Document Processing Fatal Error":"AMZbj5tNGxjPrvaNyw56sfqcLSW2j1XmkncEYUVtgmVC"},Ot={...lt,...Z},er=Object.fromEntries(Object.entries(Z).map(([n,e])=>[e,n])),tr={...ct,...er},Hr=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:nt,BASIC_TYPE_BLUE_IDS:At,BLUE_CONTRACTS_RUNTIME_TYPE_BLUE_ID_TO_NAME_MAP:er,BLUE_CONTRACTS_RUNTIME_TYPE_NAME_TO_BLUE_ID_MAP:Z,BOOLEAN_TYPE:Jt,BOOLEAN_TYPE_BLUE_ID:K,CORE_TYPES:Rt,CORE_TYPE_BLUE_IDS:ie,CORE_TYPE_BLUE_ID_TO_NAME_MAP:ct,CORE_TYPE_NAME_TO_BLUE_ID_MAP:lt,DEFAULT_BLUE_TYPE_BLUE_ID_TO_NAME_MAP:tr,DEFAULT_BLUE_TYPE_NAME_TO_BLUE_ID_MAP:Ot,DICTIONARY_TYPE:Qt,DICTIONARY_TYPE_BLUE_ID:at,DOUBLE_TYPE:Wt,DOUBLE_TYPE_BLUE_ID:_,INTEGER_TYPE:Zt,INTEGER_TYPE_BLUE_ID:j,LIST_CONTROL_EMPTY:Ie,LIST_CONTROL_POS:it,LIST_CONTROL_PREVIOUS:ce,LIST_CONTROL_REPLACE:st,LIST_MERGE_POLICY_APPEND_ONLY:Gr,LIST_MERGE_POLICY_POSITIONAL:Kr,LIST_TYPE:Xt,LIST_TYPE_BLUE_ID:ot,OBJECT_BLUE:rt,OBJECT_BLUE_ID:N,OBJECT_CONSTRAINTS:wt,OBJECT_CONTRACTS:y.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:le,OBJECT_ITEMS:Te,OBJECT_ITEM_TYPE:me,OBJECT_KEY_TYPE:ge,OBJECT_MERGE_POLICY:y.OBJECT_MERGE_POLICY,OBJECT_NAME:ae,OBJECT_PROPERTIES:St,OBJECT_SCHEMA:y.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:Ct,OBJECT_TYPE:U,OBJECT_VALUE:X,OBJECT_VALUE_TYPE:ye,TEXT_TYPE:Yt,TEXT_TYPE_BLUE_ID:z},Symbol.toStringTag,{value:"Module"}));class Yr{static get(e,t,r,i=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return i&&o!==void 0?o:e}const s=t.substring(1).split("/");return this.getRecursive(e,s,0,r,i)}static getRecursive(e,t,r,i,s){if(r===t.length-1&&!s)return this.getNodeForSegment(e,t[r],i,!1);if(r===t.length){const l=e.getValue();return s&&l!==void 0?l:e}const o=t[r],a=this.getNodeForSegment(e,o,i,!0);if(a)return this.getRecursive(a,t,r+1,i,s)}static getNodeForSegment(e,t,r,i){let s;const o=e.getProperties();if(o&&t in o)s=o[t];else switch(t){case"name":{const a=e.getName();s=new h().setValue(a??null);break}case"description":{const a=e.getDescription();s=new h().setValue(a??null);break}case"type":s=e.getType();break;case"itemType":s=e.getItemType();break;case"keyType":s=e.getKeyType();break;case"valueType":s=e.getValueType();break;case"value":{const a=e.getValue();s=new h().setValue(a??null);break}case"blueId":{const a=e.getBlueId();s=new h().setValue(a??null);break}case"blue":s=e.getBlue();break;case"items":{const a=e.getItems();s=new h().setItems(a);break}case"properties":{const a=e.getProperties();s=new h().setProperties(a);break}case y.OBJECT_CONTRACTS:{const a=e.getContracts();s=new h().setContracts(a);break}default:{if(/^\d+$/.test(t)){const a=parseInt(t,10),l=e.getItems();l&&a>=0&&a<l.length?s=l[a]:s=void 0}else s=void 0;break}}if(s)return i&&r?this.link(s,r):s}static link(e,t){const r=t(e);return u.isNonNullable(r)?r:e}}class h{static INTEGER=new h("Integer");name;description;type;itemType;keyType;valueType;value;items;properties;contracts;blueId;schema;mergePolicy;previousBlueId;position;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 h().setValue(e).setInlineValue(!0):this.type=e,this}getItemType(){return this.itemType}setItemType(e){return typeof e=="string"?this.itemType=new h().setValue(e).setInlineValue(!0):this.itemType=e,this}getKeyType(){return this.keyType}setKeyType(e){return typeof e=="string"?this.keyType=new h().setValue(e).setInlineValue(!0):this.keyType=e,this}getValueType(){return this.valueType}setValueType(e){return typeof e=="string"?this.valueType=new h().setValue(e).setInlineValue(!0):this.valueType=e,this}getValue(){const e=this.type?.getBlueId();if(u.isNonNullable(e)&&u.isNonNullable(this.value)){if(e===j&&typeof this.value=="string")return new R(this.value);if(e===_&&typeof this.value=="string"){const t=new V(this.value),r=parseFloat(t.toString());return new V(r.toString())}else if(e===K&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}getRawValue(){return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new R(e.toString()):this.value=new V(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.contracts=e?.[y.OBJECT_CONTRACTS],this}addProperty(e,t){return this.properties||(this.properties={}),this.properties[e]=t,e===y.OBJECT_CONTRACTS&&(this.contracts=t),this}removeProperty(e){return this.properties&&delete this.properties[e],e===y.OBJECT_CONTRACTS&&(this.contracts=void 0),this}getContractsProperty(){return this.contracts??this.properties?.[y.OBJECT_CONTRACTS]}getContracts(){return this.getContractsProperty()?.getProperties()}getContractsNode(){return this.contracts??this.properties?.[y.OBJECT_CONTRACTS]}setContracts(e){return u.isNullable(e)?(this.contracts=void 0,this.removeProperty(y.OBJECT_CONTRACTS)):(this.contracts=new h().setProperties(e),this.addProperty(y.OBJECT_CONTRACTS,this.contracts)),this}setContractsNode(e){return this.contracts=e,e===void 0?this.removeProperty(y.OBJECT_CONTRACTS):this.addProperty(y.OBJECT_CONTRACTS,e),this}addContract(e,t){const r=this.getContractsProperty();return u.isNullable(r)?this.addProperty(y.OBJECT_CONTRACTS,new h().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(y.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)}getSchema(){return this.schema}setSchema(e){return this.schema=e,this}getMergePolicy(){return this.mergePolicy}setMergePolicy(e){return this.mergePolicy=e,this}getPreviousBlueId(){return this.previousBlueId}setPreviousBlueId(e){return this.previousBlueId=e,this}getPosition(){return this.position}setPosition(e){return this.position=e,this}getBlue(){return this.blue}setBlue(e){return this.blue=e,this}isInlineValue(){return this.inlineValue}setInlineValue(e){return this.inlineValue=e,this}isResolved(){return!1}get(e,t){return Yr.get(this,e,t)}getAsNode(e){const t=this.get(e);if(t instanceof h)return t;throw new Error(`Value at path ${e} is not a BlueNode: ${t}`)}getAsInteger(e){const t=this.get(e);if(t instanceof R||t instanceof V)return t.toNumber();throw new Error(`Value at path ${e} is not a BigInteger or BigDecimal: ${t}`)}clone(){const e=new h(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()]))),this.contracts&&(e.contracts=e.properties?.[y.OBJECT_CONTRACTS]??this.contracts.clone()),e.blueId=this.blueId,e.schema=this.schema?.clone(),e.mergePolicy=this.mergePolicy,e.previousBlueId=this.previousBlueId,e.position=this.position,e.blue=this.blue?.clone(),e.inlineValue=this.inlineValue,e}cloneShallow(){const e=new h(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.contracts=e.properties?.[y.OBJECT_CONTRACTS]??this.contracts,e.blueId=this.blueId,e.schema=this.schema,e.mergePolicy=this.mergePolicy,e.previousBlueId=this.previousBlueId,e.position=this.position,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 G{static MIN_BLUE_ID_LENGTH=41;static MAX_BLUE_ID_LENGTH=45;static ZERO_BLUE_ID="0".repeat(44);static PLAIN_BLUE_ID_PATTERN=/^[1-9A-HJ-NP-Za-km-z]+$/;static CYCLIC_MEMBER_PATTERN=/^([1-9A-HJ-NP-Za-km-z]+)#(0|[1-9]\d*)$/;static THIS_MEMBER_PATTERN=/^this#(0|[1-9]\d*)$/;static ZERO_PLACEHOLDER_PATTERN=/^0{44}$/;static isPotentialBlueId(e){try{return this.requireBlueIdOrCyclicMember(e,"blueId"),!0}catch{return!1}}static requirePlainBlueId(e,t){if(e===void 0||e.length===0||!this.PLAIN_BLUE_ID_PATTERN.test(e))throw new Error(`Expected canonical Base58 SHA-256 BlueId at ${t}.`);try{const r=De.default.decode(e);if(r.length!==32||De.default.encode(r)!==e)throw new Error}catch{throw new Error(`Expected canonical Base58 SHA-256 BlueId at ${t}.`)}return e}static requireBlueIdOrCyclicMember(e,t){if(e===void 0)throw new Error(`Expected BlueId at ${t}.`);const r=e.match(this.CYCLIC_MEMBER_PATTERN);if(r!==null)return this.requirePlainBlueId(r[1],t),e;if(e.includes("#"))throw new Error(`Invalid cyclic BlueId member syntax at ${t}.`);return this.requirePlainBlueId(e,t)}static requireNoThisPlaceholderOutsideCyclicApi(e,t){if(e!==void 0&&(e==="this"||this.THIS_MEMBER_PATTERN.test(e)))throw new Error(`"this" BlueId placeholders are valid only inside cyclic BlueId calculation APIs. Path: ${t}`);return e}static isCyclicCalculationPlaceholder(e){return e!==void 0&&(e==="this"||this.THIS_MEMBER_PATTERN.test(e)||this.ZERO_PLACEHOLDER_PATTERN.test(e))}}const Wr=m.z.string().max(G.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(G.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(n=>{try{return De.default.decode(n),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),Ze=m.z.lazy(()=>m.z.record(m.z.unknown()).and(m.z.object({blueId:m.z.string().optional(),name:m.z.string().optional(),description:m.z.string().optional(),type:Ze.optional(),value:m.z.union([m.z.string(),m.z.number(),m.z.boolean()]).optional().nullable(),items:m.z.array(Ze).optional()}))),ze=m.z.object({blueId:m.z.string().optional(),name:m.z.string().optional(),description:m.z.string().optional(),type:Ze.optional()}),Zr=ze.extend({value:m.z.string().optional()}),Jr=ze.extend({value:m.z.number().optional()}),Xr=ze.extend({value:m.z.boolean().optional()}),Qr=ze.extend({items:m.z.array(m.z.string()).optional()}),D=n=>n instanceof fe,Y=n=>D(n)&&n instanceof R,Je=n=>D(n)&&n instanceof V,ei=m.z.lazy(()=>m.z.record(Xe)),ti=m.z.lazy(()=>m.z.union([m.z.array(Xe),m.z.array(Xe).readonly()])),Xe=m.z.lazy(()=>m.z.union([u.jsonPrimitiveSchema,ei,ti,m.z.instanceof(fe)])),q=n=>ve.isObject(n)&&!ve.isArray(n)&&!u.isReadonlyArray(n)&&!D(n),Mt=n=>ve.isArray(n)||u.isReadonlyArray(n),ri=n=>Mt(n)||q(n)||D(n)||u.isJsonPrimitive(n),ut=["required","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minItems","maxItems","uniqueItems","minFields","maxFields"],ii=["required","uniqueItems"],si=["minLength","maxLength","minItems","maxItems","minFields","maxFields"],ni=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"],oi=new Set(ii),ai=new Set(si),li=new Set(ni);function rr(n){return oi.has(n)}function ir(n){return ai.has(n)}function ci(n){return li.has(n)}class je{fields={};enumValues;get(e){return this.fields[e]}set(e,t){return t===void 0?delete this.fields[e]:this.fields[e]=t,this}getEnum(){return this.enumValues}setEnum(e){return this.enumValues=e,this}entries(){return ut.flatMap(e=>{const t=this.fields[e];return t===void 0?[]:[[e,t]]})}clone(){const e=new je;for(const[t,r]of this.entries())e.set(t,r.clone());return e.setEnum(this.enumValues?.map(t=>t.clone())),e}}const ui=new R(Number.MIN_SAFE_INTEGER.toString()),di=new R(Number.MAX_SAFE_INTEGER.toString());class g{static deserialize(e){return g.handleNode(e,{root:!0,strictReferenceOnly:!0})}static deserializeUnchecked(e){return g.handleNode(e,{root:!1,strictReferenceOnly:!1})}static handleNode(e,t={root:!1,strictReferenceOnly:!0}){if(e===void 0)throw new Error("This is not a valid JSON-like value. Found 'undefined' as a value.");if(e===null&&t.root)throw new Error("Root null is not a valid Blue document.");if(q(e)){const r=new h,i={};return Object.entries(e).forEach(([s,o])=>{switch(s){case ae:if(o==null)r.setName(void 0);else{if(typeof o!="string")throw new Error(`The ${ae} field must be a string.`);r.setName(o)}break;case le:if(o==null)r.setDescription(void 0);else{if(typeof o!="string")throw new Error(`The ${le} field must be a string.`);r.setDescription(o)}break;case U:r.setType(g.handleNode(o,{...t,root:!1}));break;case me:r.setItemType(g.handleNode(o,{...t,root:!1}));break;case ge:r.setKeyType(g.handleNode(o,{...t,root:!1}));break;case ye:r.setValueType(g.handleNode(o,{...t,root:!1}));break;case y.OBJECT_MERGE_POLICY:if(o!=="positional"&&o!=="append-only"&&o!==void 0)throw new Error('The mergePolicy field must be "positional" or "append-only".');r.setMergePolicy(o);break;case X:r.setValue(g.handleValue(o));break;case N:if(t.strictReferenceOnly&&Object.keys(e).length!==1)throw new Error("blueId nodes must be reference-only and cannot contain sibling fields.");if(typeof o!="string")throw new Error(`The ${N} field must be a string.`);r.setBlueId(o);break;case Te:r.setItems(g.handleArray(o,t));break;case rt:r.setBlue(g.handleNode(o,{...t,root:!1}));break;case ce:if(Object.keys(e).length!==1)throw new Error("$previous list anchors must be single-key list items.");r.setPreviousBlueId(g.handlePreviousBlueId(o));break;case it:r.setPosition(g.handlePosition(o));break;case y.OBJECT_SCHEMA:r.setSchema(g.handleSchema(o,t));break;case y.OBJECT_CONTRACTS:i[s]=g.handleNode(o,{...t,root:!1});break;case wt:throw new Error("constraints is not part of the Blue Language 1.0 top-level vocabulary.");case St:throw new Error("properties is an internal field and must not appear in Blue documents.");default:i[s]=g.handleNode(o,{...t,root:!1});break}}),Object.keys(i).length>0&&r.setProperties(i),r}else{if(Mt(e))return new h().setItems(g.handleArray(e,t));{const r=e;return new h().setValue(g.handleValue(r)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||D(e)){if(typeof e=="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error("Unquoted integers outside [-9007199254740991, 9007199254740991] must be quoted and explicitly typed as Integer.");if(Y(e)||Number.isSafeInteger(e)){const t=new R(e.toString());if(t.lt(ui)||t.gt(di))throw new Error("Unquoted integers outside [-9007199254740991, 9007199254740991] must be quoted and explicitly typed as Integer.");return t}else{const t=parseFloat(e.toString());return new V(t.toString())}}else if(typeof e=="boolean")return e;throw new Error(`Can't handle node: ${JSON.stringify(e)}`)}static handleArray(e,t){if(e!=null){if(ve.isObject(e)&&!Array.isArray(e))return[g.handleNode(e,{...t,root:!1})];if(Array.isArray(e))return e.map(r=>g.handleNode(r,{...t,root:!1}));throw new Error("Expected an array node")}}static handlePreviousBlueId(e){if(!q(e)||Object.keys(e).length!==1)throw new Error("$previous must have shape { blueId: <PrevListBlueId> }.");const t=e[N];if(typeof t!="string")throw new Error("$previous.blueId must be a string.");return t}static handlePosition(e){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error("$pos must be a non-negative integer.");return e}static handleSchema(e,t){if(!q(e))throw new Error("schema must be an object.");const r=new je;for(const i of Object.keys(e)){if(i==="enum"){const s=e[i];if(!Array.isArray(s))throw new Error("schema.enum must be a list.");r.setEnum(s.map(o=>g.handleNode(o,{...t,root:!1})));continue}if(!ut.includes(i))throw new Error(`schema.${i} is not part of the Blue language core.`);g.validateSchemaKeywordShape(i,e[i],t),r.set(i,g.handleNode(e[i],{...t,root:!1}))}return r}static validateSchemaKeywordShape(e,t,r){if(rr(e)){if(typeof t!="boolean")throw new Error(`schema.${e} must be a boolean.`);return}if(ir(e)){if(typeof t!="number"||!Number.isInteger(t)||t<0||!Number.isSafeInteger(t))throw new Error(`schema.${e} must be a non-negative integer in the interoperable range.`);return}if(q(t)){const i=g.handleNode(t,{...r,root:!1});if(g.isExplicitNumericValue(i))return;throw new Error(`schema.${e} must be numeric or an explicit numeric scalar node.`)}if(typeof t!="number"&&!D(t))throw new Error(`schema.${e} must be numeric or an explicit numeric scalar node.`)}static isExplicitNumericValue(e){if(!g.isExplicitSchemaScalar(e,!0))return!1;const t=e.getValue(),r=e.getType();return D(t)||typeof t=="number"?r===void 0||g.isNumericType(r):!1}static isExplicitSchemaScalar(e,t){const r=e.getType();return e.getValue()!==void 0&&e.getValue()!==null&&(t||r===void 0)&&e.getName()===void 0&&e.getDescription()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0&&e.getContractsNode()===void 0&&e.getBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0&&(r===void 0||g.isScalarType(r))}static isScalarType(e){return g.isCoreType(e,z,"Text")||g.isCoreType(e,j,"Integer")||g.isCoreType(e,_,"Double")||g.isCoreType(e,K,"Boolean")}static isNumericType(e){return g.isCoreType(e,j,"Integer")||g.isCoreType(e,_,"Double")}static isCoreType(e,t,r){return e.getBlueId()===t||e.isInlineValue()&&e.getValue()===r}}function hi(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ft,Ut;function pi(){return Ut||(Ut=1,ft=function n(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?n(e.toJSON()):Array.isArray(e)?`[${e.reduce((i,s,o)=>`${i}${o===0?"":","}${n(s===void 0||typeof s=="symbol"?null:s)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,i)=>{if(e[i]===void 0||typeof e[i]=="symbol")return r;const s=r.length===0?"":",";return`${r}${s}${n(i)}:${n(e[i])}`},"")}}`}),ft}var fi=pi();const mi=hi(fi);class Qe{static canonicalize(e){return mi(e)}}const mt=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class Vt{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new Vt),this.instance}initBrowserCrypto(){return mt?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return mt&&!!pt.default&&typeof pt.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return mt?pt.default:null}}class sr{cryptoEnv=Vt.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return De.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return De.default.encode(r)}canonicalizeInput(e){const t=Qe.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(kr.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 i=new TextEncoder().encode(e),s=await t.subtle.digest("SHA-256",i);return new Uint8Array(s)}}class nr{static toCanonicalDoubleValue(e){const t=e instanceof V||e instanceof R?e.toNumber():typeof e=="number"?e:typeof e=="string"?Number(e):Number.NaN;if(!Number.isFinite(t))throw new Error("Double value must be finite.");return new V(t.toString())}static isExactBinary64Multiple(e,t){const r=be.fromNumber(this.toFiniteNumber(e)),i=be.fromNumber(this.toFiniteNumber(t));return r.dividedByIsInteger(i)}static toFiniteNumber(e){const t=e instanceof V||e instanceof R?e.toNumber():typeof e=="number"?e:Number.NaN;if(!Number.isFinite(t))throw new Error("Double value must be finite.");return t}}class be{constructor(e,t){if(this.numerator=e,this.denominator=t,t<=0n)throw new Error("denominator must be positive");const r=gi(zt(e),t);this.numerator=e/r,this.denominator=t/r}static fromNumber(e){if(!Number.isFinite(e))throw new Error("Double value must be finite.");if(Object.is(e,0)||Object.is(e,-0))return new be(0n,1n);const t=new ArrayBuffer(8),r=new DataView(t);r.setFloat64(0,e,!1);const i=r.getBigUint64(0,!1),s=(i&1n<<63n)!==0n,o=Number(i>>52n&0x7ffn),a=i&0x000fffffffffffffn;let l,c;return o===0?(l=a,c=-1074):(l=1n<<52n|a,c=o-1023-52),s&&(l=-l),c>=0?new be(l<<BigInt(c),1n):new be(l,1n<<BigInt(-c))}dividedByIsInteger(e){if(e.numerator===0n)throw new Error("Division by zero rational.");const t=this.numerator*e.denominator,r=this.denominator*zt(e.numerator);return t%r===0n}}function gi(n,e){let t=n,r=e;for(;r!==0n;){const i=t%r;t=r,r=i}return t===0n?1n:t}function zt(n){return n<0n?-n:n}const yi=new R(Number.MIN_SAFE_INTEGER.toString()),Ii=new R(Number.MAX_SAFE_INTEGER.toString());class ne{static get(e){return this.getNode(e,"/","root",-1,!1)}static getAllowingCyclicPlaceholders(e){return this.getNode(e,"/","root",-1,!0)}static getWithResolvedBlueIdMetadata(e){return this.getNode(this.stripResolvedBlueIdMetadata(e.clone()),"/","root",-1,!1)}static stripResolvedBlueIdMetadata(e){e.getReferenceBlueId()!==void 0&&!this.isReferenceOnly(e)&&e.setReferenceBlueId(void 0),this.stripResolvedBlueIdMetadataChild(e.getType()),this.stripResolvedBlueIdMetadataChild(e.getItemType()),this.stripResolvedBlueIdMetadataChild(e.getKeyType()),this.stripResolvedBlueIdMetadataChild(e.getValueType()),this.stripResolvedBlueIdMetadataChild(e.getBlue()),this.stripResolvedBlueIdMetadataChild(e.getContractsNode()),e.getItems()?.forEach(r=>this.stripResolvedBlueIdMetadata(r)),Object.values(e.getProperties()??{}).forEach(r=>this.stripResolvedBlueIdMetadata(r));const t=e.getSchema();return t?.entries().forEach(([,r])=>this.stripResolvedBlueIdMetadata(r)),t?.getEnum()?.forEach(r=>this.stripResolvedBlueIdMetadata(r)),e}static stripResolvedBlueIdMetadataChild(e){e!==void 0&&this.stripResolvedBlueIdMetadata(e)}static getListElement(e,t){return this.getNode(e,`/${t}`,"list-element",t,!1)}static getListElementAllowingCyclicPlaceholders(e,t){return this.getNode(e,`/${t}`,"list-element",t,!0)}static getNode(e,t,r,i,s){if(this.validateBlueIdInput(e,t,r,i),r==="list-element"&&this.isEmptyPlaceholder(e))return{[Ie]:!0};if(this.isReferenceOnly(e)){const f=this.validateReferenceBlueId(e.getReferenceBlueId(),this.appendPath(t,N),s);return{[N]:f}}if(e.getPreviousBlueId()!==void 0){const f=G.requirePlainBlueId(e.getPreviousBlueId(),this.appendPath(this.appendPath(t,ce),N));return{[ce]:{[N]:f}}}const o=e.getValue(),a=e.getItems(),l=a===void 0?void 0:a.map((f,I)=>this.getNode(f,this.appendPath(this.appendPath(t,Te),String(I)),"list-element",I,s));if(l!==void 0&&this.isPayloadOnlyList(e))return l;const c={};this.setString(c,ae,e.getName()),this.setString(c,le,e.getDescription());let d;o!=null&&e.getType()===void 0?(d=this.inferTypeBlueId(o),d!==void 0&&(c[U]={[N]:d})):e.getType()!==void 0&&(d=e.getType()?.getReferenceBlueId(),c[U]=this.getNode(e.getType(),this.appendPath(t,U),"metadata",-1,s)),this.setNode(c,me,e.getItemType(),t,s),this.setNode(c,ge,e.getKeyType(),t,s),this.setNode(c,ye,e.getValueType(),t,s),e.getMergePolicy()!==void 0&&(c[y.OBJECT_MERGE_POLICY]=e.getMergePolicy()),o!=null&&(c[X]=this.handleValue(o,d)),l!==void 0&&(c[Te]=l);const p=e.getSchema();p!==void 0&&(c[y.OBJECT_SCHEMA]=this.schemaToInput(p,this.appendPath(t,y.OBJECT_SCHEMA),s)),e.getContractsNode()!==void 0&&(c[y.OBJECT_CONTRACTS]=this.getNode(e.getContractsNode(),this.appendPath(t,y.OBJECT_CONTRACTS),"metadata",-1,s));for(const[f,I]of Object.entries(e.getProperties()??{}))f!==y.OBJECT_CONTRACTS&&(c[f]=this.getNode(I,this.appendPath(t,f),"object-field",-1,s));return c}static schemaToInput(e,t,r){const i={};for(const[o,a]of e.entries())i[o]=this.getNode(a,this.appendPath(t,o),"metadata",-1,r);const s=e.getEnum();return s!==void 0&&(i.enum=this.canonicalizeSchemaEnumValues(s,this.appendPath(t,"enum"),r).map((o,a)=>this.getNode(o,this.appendPath(this.appendPath(t,"enum"),String(a)),"metadata",-1,r))),i}static canonicalizeSchemaEnumValues(e,t,r){const i=new Map;for(const s of e){const o=s.clone();o.setSchema(void 0),i.set(JSON.stringify(this.getNode(o,t,"metadata",-1,r)),s)}return[...i.entries()].sort(([s],[o])=>s.localeCompare(o)).map(([,s])=>s)}static validateReferenceBlueId(e,t,r){return r&&G.isCyclicCalculationPlaceholder(e)?e:G.requireBlueIdOrCyclicMember(G.requireNoThisPlaceholderOutsideCyclicApi(e,t),t)}static validateBlueIdInput(e,t,r,i){if(e===void 0)throw new Error(`BlueId input must not contain null nodes. Path: ${t}`);if(r==="metadata"&&this.isTypePosition(t)&&e.isInlineValue())throw new Error(`Direct BlueId input must not contain unresolved type aliases. Path: ${t}`);if(e.getBlue()!==void 0)throw new Error(`"blue" is a preprocessing directive and must not be present in BlueId input. Call preprocess/canonicalize/calculateSemanticBlueId first. Path: ${t}`);if(e.getPosition()!==void 0)throw new Error(`"$pos" overlays are not valid direct BlueId input. Path: ${t}`);if(e.getProperties()?.[st]!==void 0)throw new Error(`"$replace" overlays are not valid direct BlueId input. Path: ${t}`);if(r==="list-element"){if(this.isEmptyNode(e))throw new Error(`Direct BlueId input must use { "$empty": true } for empty list placeholders. Path: ${t}`);if(e.getProperties()?.[Ie]!==void 0&&this.validateEmptyPlaceholder(e,t),e.getPreviousBlueId()!==void 0&&i!==0)throw new Error(`"$previous" must appear only as the first list item. Path: ${t}`)}else if(e.getPreviousBlueId()!==void 0)throw new Error(`"$previous" is valid only as the first list item in direct BlueId input. Path: ${t}`);this.validatePayloadKind(e,t)}static validatePayloadKind(e,t){const r=this.ordinaryPropertyKeys(e),i=[e.getValue()!==void 0&&e.getValue()!==null,e.getItems()!==void 0,r.length>0].filter(Boolean).length;if(i>1)throw new Error(`A Blue node may contain only one payload kind: value, items, or object fields. Path: ${t}`);if(e.getReferenceBlueId()!==void 0&&!this.isReferenceOnly(e))throw new Error(`"blueId" nodes must be reference-only and cannot contain sibling fields. Path: ${t}`);if(e.getPreviousBlueId()!==void 0&&(i>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.getSchema()!==void 0||e.getMergePolicy()!==void 0||e.getPosition()!==void 0||e.getContractsNode()!==void 0||e.getReferenceBlueId()!==void 0))throw new Error(`"$previous" list anchors must be single-key list items. Path: ${t}`)}static handleValue(e,t){if(t===_)return nr.toCanonicalDoubleValue(e).toNumber();if(e instanceof R||Y(e))return e.lt(yi)||e.gt(Ii)?e.toString():e.toNumber();const r=e;if(r instanceof V||D(r))return r.toNumber();if(typeof e=="string"||typeof e=="boolean")return e;throw new Error(`Unsupported Blue scalar value: ${String(e)}`)}static inferTypeBlueId(e){if(typeof e=="string")return z;if(e instanceof R||Y(e))return j;if(e instanceof V||D(e))return _;if(typeof e=="boolean")return K}static setString(e,t,r){r!==void 0&&(e[t]=r)}static setNode(e,t,r,i,s){r!==void 0&&(e[t]=this.getNode(r,this.appendPath(i,t),"metadata",-1,s))}static isReferenceOnly(e){return e.getReferenceBlueId()!==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.getValue()===void 0||e.getValue()===null)&&e.getItems()===void 0&&this.ordinaryPropertyKeys(e).length===0&&e.getContractsNode()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static isPayloadOnlyList(e){return e.getItems()!==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.getValue()===void 0||e.getValue()===null)&&this.ordinaryPropertyKeys(e).length===0&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static isEmptyNode(e){return 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.getValue()===void 0||e.getValue()===null)&&e.getItems()===void 0&&this.ordinaryPropertyKeys(e).length===0&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static isEmptyPlaceholder(e){const t=e.getProperties(),r=t?.[Ie];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&r.getValue()===!0&&r.getItems()===void 0&&Object.keys(r.getProperties()??{}).length===0}static validateEmptyPlaceholder(e,t){if(!this.isEmptyPlaceholder(e))throw new Error(`"$empty" list placeholder must have exact shape { "$empty": true }. Path: ${t}`)}static isTypePosition(e){return e.endsWith(`/${U}`)||e.endsWith(`/${me}`)||e.endsWith(`/${ge}`)||e.endsWith(`/${ye}`)}static appendPath(e,t){const r=t.replace(/~/g,"~0").replace(/\//g,"~1");return e==="/"?`/${r}`:`${e}/${r}`}static ordinaryPropertyKeys(e){return Object.keys(e.getProperties()??{}).filter(t=>t!==y.OBJECT_CONTRACTS)}}const vi=new Set([ae,le,X]);class b{constructor(e){this.hashProvider=e}static INSTANCE=new b(new sr);static calculateBlueId(e){return b.INSTANCE.calculate(e)}static calculateBlueIdSync(e){return b.INSTANCE.calculateSync(e)}static calculateBlueIdAllowingCyclicPlaceholdersSync(e){return b.INSTANCE.calculateAllowingCyclicPlaceholdersSync(e)}static calculateBlueIdWithResolvedBlueIdMetadataSync(e){return b.INSTANCE.calculateInput(ne.getWithResolvedBlueIdMetadata(e),!0)}static calculateBlueIdInputSync(e){return b.INSTANCE.calculateInput(e,!0)}calculate(e){return this.calculateInput(this.prepareInput(e),!1)}calculateSync(e){return this.calculateInput(this.prepareInput(e),!0)}calculateAllowingCyclicPlaceholdersSync(e){return this.calculateInput(this.prepareInputAllowingCyclicPlaceholders(e),!0)}prepareInput(e){return e instanceof h?ne.get(e):Array.isArray(e)&&e.every(t=>t instanceof h)?e.map((t,r)=>ne.getListElement(t,r)):ne.get(g.deserialize(e))}prepareInputAllowingCyclicPlaceholders(e){return e instanceof h?ne.getAllowingCyclicPlaceholders(e):Array.isArray(e)&&e.every(t=>t instanceof h)?e.map((t,r)=>ne.getListElementAllowingCyclicPlaceholders(t,r)):ne.getAllowingCyclicPlaceholders(g.deserialize(e))}calculateInput(e,t){return this.calculateCleaned(this.cleanRoot(e),t)}calculateCleaned(e,t){return this.isScalar(e)?this.applyHash(e,t):Array.isArray(e)?this.calculateList(e,t):this.calculateMap(e,t)}calculateMap(e,t){if(Object.keys(e).length===1&&typeof e[N]=="string")return e[N];const r=Object.keys(e).sort().map(i=>{const s=e[i];if(vi.has(i))return[i,s];const o=this.calculateCleaned(s,t);return t?[i,{[N]:o}]:Promise.resolve(o).then(a=>[i,{[N]:a}])});return t?this.applyHash(Object.fromEntries(r),!0):Promise.all(r).then(i=>this.applyHash(Object.fromEntries(i),!1))}calculateList(e,t){let r,i=0;e.length>0&&this.isPreviousControl(e[0])?(r=this.previousBlueId(e[0]),i=1):r=this.applyHash({$list:"empty"},t);for(let s=i;s<e.length;s+=1){const o=r,a=this.calculateCleaned(e[s],t);t?r=this.applyHash(this.listCons(o,a),!0):r=Promise.all([o,a]).then(([l,c])=>this.applyHash(this.listCons(l,c),!1))}return r}listCons(e,t){return{$listCons:{elem:{[N]:t},prev:{[N]:e}}}}cleanRoot(e){if(e==null)throw new Error("Root null is not valid BlueId input.");if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.cleanRoot(r));const t={};for(const[r,i]of Object.entries(e)){const s=this.cleanObjectField(i);s!==void 0&&(t[r]=s)}return t}cleanObjectField(e){if(e==null)return;if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.cleanRoot(r));const t={};for(const[r,i]of Object.entries(e)){const s=this.cleanObjectField(i);s!==void 0&&(t[r]=s)}return Object.keys(t).length===0?void 0:t}isPreviousControl(e){if(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length!==1)return!1;const t=e[ce];return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length===1&&typeof t[N]=="string"}previousBlueId(e){return e[ce][N]}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}isScalar(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}}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 C{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(),i=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(i)}static textNode(e){return new h().setType(new h().setBlueId(z)).setValue(e)}static integerNode(e){const t=e instanceof R?e:new R(e.toString());return new h().setType(new h().setBlueId(j)).setValue(t)}static doubleNode(e){const t=e instanceof V?e:new V(e.toString());return new h().setType(new h().setBlueId(_)).setValue(t)}static booleanNode(e){return new h().setType(new h().setBlueId(K)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const i of Object.values(S)){const s=u.isNonNullable(this.getFieldValue(e,i));if(t.has(i)){if(!s)return!1}else if(!r.has(i)){if(s)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 gt="$previous",Re="$pos",Et="$empty";class P{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.getMergePolicy();if(t==="append-only"||t==="positional")return t;const r=e.getProperties()?.[y.OBJECT_MERGE_POLICY]?.getValue();if(r==="append-only"||r==="positional")return r}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 e.getPreviousBlueId()!==void 0||Object.prototype.hasOwnProperty.call(e.getProperties()??{},gt)}static hasPositionProperty(e){return e.getPosition()!==void 0||Object.prototype.hasOwnProperty.call(e.getProperties()??{},Re)}static hasEmptyProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},Et)}static isEmptyItem(e){const t=e.getProperties(),r=t?.[Et];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&C.hasFieldsAndMayHaveFields(e,new Set([S.PROPERTIES]))&&C.hasFieldsAndMayHaveFields(r,new Set([S.VALUE]),new Set([S.TYPE]))&&r.getValue()===!0}static isPreviousItem(e){if(e.getPreviousBlueId()!==void 0)return 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.getValue()===void 0&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0;const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&C.hasFieldsAndMayHaveFields(e,new Set([S.PROPERTIES]))&&C.hasBlueIdOnly(t[gt])}static getPreviousBlueId(e){if(e.getPreviousBlueId()!==void 0)return e.getPreviousBlueId();if(this.isPreviousItem(e))return e.getProperties()?.[gt]?.getBlueId()}static createPreviousItem(e){return new h().setPreviousBlueId(e)}static readPosition(e){if(e.getPosition()!==void 0)return e.getPosition();const t=e.getProperties()?.[Re];if(t===void 0)return;if(!C.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(),i=r instanceof R?r.toNumber():typeof r=="number"?r:void 0;if(i===void 0||!Number.isInteger(i)||i<0)throw new Error("$pos must be a non-negative integer value.");return i}static createPositionedItem(e,t){return t.clone().setPosition(e)}static withoutPosition(e){const t=e.clone();t.setPosition(void 0);const r=t.getProperties();return r!==void 0&&(delete r[Re],Object.keys(r).length===0&&t.setProperties(void 0)),t}static hasPayloadAfterRemovingPosition(e){return!C.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)}}class k{constructor(e={emitListControls:!0}){this.options=e}reverse(e){const t=new h;return this.reverseNode(t,e,void 0,!0),t}reverseToCanonicalOverlay(e){const t=new h;return this.reverseCanonicalNode(t,e,e.getType()),t}static calculateHashMinimalBlueId(e){return b.calculateBlueIdSync(this.toHashMinimalNode(e))}static calculateHashMinimalListBlueId(e){return b.calculateBlueIdSync(e.map(t=>this.toHashMinimalNode(t)))}static toHashMinimalNode(e){return new k({emitListControls:!1}).reverse(e)}reverseCanonicalNode(e,t,r){if(t.getReferenceBlueId()!==void 0&&r?.getReferenceBlueId()===t.getReferenceBlueId())return;const i=t.getValue();i!=null&&(r===void 0||r.getValue()===void 0||r.getValue()===null||!this.sameScalarValue(i,r.getValue()))&&e.setValue(i),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getType(),(l,c)=>l.setType(c)),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getItemType(),(l,c)=>l.setItemType(c)),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getKeyType(),(l,c)=>l.setKeyType(c)),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getValueType(),(l,c)=>l.setValueType(c)),this.preserveCanonicalPayloadTypeForMetadataOverride(t,e),t.getName()!==void 0&&(r===void 0||t.getName()!==r.getName())&&e.setName(t.getName()),t.getDescription()!==void 0&&(r===void 0||t.getDescription()!==r.getDescription())&&e.setDescription(t.getDescription()),this.isReferenceOnly(t)&&(r===void 0||t.getReferenceBlueId()!==r.getReferenceBlueId())&&e.setReferenceBlueId(t.getReferenceBlueId()),t.getMergePolicy()!==void 0&&(r===void 0||t.getMergePolicy()!==r.getMergePolicy())&&e.setMergePolicy(t.getMergePolicy()),t.getSchema()!==void 0&&!this.sameSchema(t.getSchema(),r?.getSchema())&&e.setSchema(t.getSchema()?.clone());const s=t.getContractsNode();if(s!==void 0){const l=r?.getContractsNode();if(!this.sameNodeBlueId(s,l)){const c=new h;this.reverseCanonicalNode(c,s,l),this.isCanonicalEmptyNode(c)||e.setContractsNode(c)}}const o=t.getItems();o!==void 0&&e.setItems(o.map(l=>{const c=new h;return this.reverseCanonicalNode(c,l,void 0),this.isCanonicalEmptyNode(c)?this.emptyPlaceholder():c}));const a=t.getProperties();if(a!==void 0){const l={};for(const[c,d]of Object.entries(a)){if(c===y.OBJECT_CONTRACTS)continue;const p=r?.getProperties()?.[c];if(this.sameNodeBlueId(d,p))continue;const f=new h;this.reverseCanonicalNode(f,d,p),this.isCanonicalEmptyNode(f)||(l[c]=f)}Object.keys(l).length>0&&e.setProperties(l)}}setCanonicalTypeIfDifferent(e,t,r,i,s){const o=i(e),a=t===void 0?void 0:i(t);o!==void 0&&(a===void 0||a.getReferenceBlueId()!==o.getReferenceBlueId())&&s(r,new h().setReferenceBlueId(o.getReferenceBlueId()))}preserveCanonicalPayloadTypeForMetadataOverride(e,t){if(t.getType()!==void 0||e.getType()===void 0||t.getItemType()===void 0&&t.getKeyType()===void 0&&t.getValueType()===void 0)return;const r=e.getType(),i=r?.getReferenceBlueId();t.setType(i===void 0?r?.clone():new h().setReferenceBlueId(i))}sameSchema(e,t){return e===t?!0:e===void 0||t===void 0?!1:b.calculateBlueIdSync(new h().setSchema(e))===b.calculateBlueIdSync(new h().setSchema(t))}sameNodeBlueId(e,t){return e===t?!0:e===void 0||t===void 0?!1:b.calculateBlueIdWithResolvedBlueIdMetadataSync(e)===b.calculateBlueIdWithResolvedBlueIdMetadataSync(t)}sameScalarValue(e,t){return e!==null&&t!==null&&typeof e=="object"&&typeof t=="object"&&"eq"in e&&typeof e.eq=="function"?!!e.eq(t):e===t}emptyPlaceholder(){return new h().addProperty("$empty",new h().setValue(!0))}isReferenceOnly(e){return e.getReferenceBlueId()!==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.getValue()===void 0&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0&&e.getContractsNode()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}isCanonicalEmptyNode(e){return 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.getValue()===void 0||e.getValue()===null)&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}reverseNode(e,t,r,i){const s=this.getEffectiveFromType(r,t);!i&&this.isIdenticalToType(t,s)||(this.reverseBasicProperties(e,t,s,i),this.reverseTypeReferences(e,t,r,s),this.reverseItems(e,t,s),this.reverseProperties(e,t,s))}isIdenticalToType(e,t){return u.isNonNullable(e.getBlueId())&&u.isNonNullable(t?.getBlueId())&&e.getBlueId()===t.getBlueId()}reverseBasicProperties(e,t,r,i){const s=t.getValue();u.isNonNullable(s)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(s),u.isNonNullable(t.getName())&&(i||u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(i||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,i){const s=(o,a,l)=>{const c=o(t),d=l?o(l):void 0;u.isNonNullable(c)&&!this.areTypeReferencesEquivalent(c,d)&&a(e,this.toMinimalTypeReference(c))};s(o=>o.getType(),(o,a)=>o.setType(a),r),s(o=>o.getItemType(),(o,a)=>o.setItemType(a),i),s(o=>o.getKeyType(),(o,a)=>o.setKeyType(a),i),s(o=>o.getValueType(),(o,a)=>o.setValueType(a),i)}areTypeReferencesEquivalent(e,t){if(u.isNullable(t))return!1;const r=e.getBlueId(),i=t.getBlueId();return u.isNonNullable(r)||u.isNonNullable(i)?u.isNonNullable(r)&&u.isNonNullable(i)&&r===i:k.calculateHashMinimalBlueId(e)===k.calculateHashMinimalBlueId(t)}toMinimalTypeReference(e){const t=e.getBlueId();if(u.isNonNullable(t))return new h().setBlueId(t);const r=new h;return this.reverseNode(r,e,void 0,!0),C.isEmptyNode(r)?e.clone():r}reverseItems(e,t,r){const i=t.getItems();if(u.isNullable(i))return;const s=r?.getItems();if(i.length===0){(u.isNullable(s)||s.length>0)&&e.setItems([]);return}if(u.isNonNullable(s)&&i.length===s.length&&i.every((a,l)=>k.calculateHashMinimalBlueId(a)===k.calculateHashMinimalBlueId(s[l])))return;const o=this.options.emitListControls!==!1&&u.isNonNullable(s)&&s.length>0?this.reverseInheritedItems(t,r):this.reverseFullItems(i);o.length>0&&e.setItems(o)}reverseInheritedItems(e,t){const r=e.getItems()??[],i=t.getItems()??[];if(r.length<i.length)throw new Error(`Resolved list has fewer items (${r.length}) than inherited list (${i.length}).`);const s=P.getMergePolicy(e,t),o=[];for(let c=0;c<i.length;c++)k.calculateHashMinimalBlueId(r[c])!==k.calculateHashMinimalBlueId(i[c])&&o.push(c);if(o.length>0&&s==="append-only")throw new Error("append-only list cannot be minimized as a non-prefix mutation.");const a=k.calculateHashMinimalListBlueId(i),l=[P.createPreviousItem(a)];for(const c of o){const d=new h;this.reverseNode(d,r[c],i[c],!1);const p=C.isEmptyNode(d)?r[c].clone():d;l.push(P.createPositionedItem(c,p))}for(let c=i.length;c<r.length;c++){const d=new h;this.reverseNode(d,r[c],void 0,!1),l.push(d)}return l.length===1?[]:l}reverseFullItems(e){const t=[];for(let r=0;r<e.length;r++){const i=new h;this.reverseNode(i,e[r],void 0,!1),t.push(i)}return t}reverseProperties(e,t,r){const i=t.getProperties();if(u.isNullable(i))return;const s={};for(const[o,a]of Object.entries(i)){const l=this.getInheritedProperty(o,r),c=new h;this.reverseNode(c,a,l,!1),C.isEmptyNode(c)||(s[o]=c)}Object.keys(s).length>0&&e.setProperties(s)}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(!C.isEmptyNode(t))return t}mergeNodes(e,t){const r=e.clone(),i=t.getValue();u.isNonNullable(i)&&r.setValue(i);const s=t.getType();u.isNonNullable(s)&&r.setType(s.clone());const o=t.getItemType();u.isNonNullable(o)&&r.setItemType(o.clone());const a=t.getKeyType();u.isNonNullable(a)&&r.setKeyType(a.clone());const l=t.getValueType();u.isNonNullable(l)&&r.setValueType(l.clone());const c=t.getProperties();if(u.isNonNullable(c)){const p=r.getProperties()||{};for(const[f,I]of Object.entries(c)){const v=p[f];p[f]=v===void 0?I.clone():this.mergeNodes(v,I)}r.setProperties(p)}const d=t.getItems();return u.isNonNullable(d)&&r.setItems(d.map(p=>p.clone())),r}}class Pt{mergeReverser=new k;hashMergeReverser=new k({emitListControls:!1});minimize(e){return this.minimizeResolved(e)}minimizeResolved(e){return this.mergeReverser.reverse(e)}minimizeResolvedForHash(e){return this.hashMergeReverser.reverse(e)}}class Ne extends Error{code;category;details;constructor(e,t,r,i){super(t),this.code=e,this.category=i,this.details=r&&r.length>0?r:[],this.name="BlueError"}}function Ti(n){return Bi(n)?n.category:void 0}function Bi(n){return typeof n=="object"&&n!==null&&typeof n.category=="string"}const H={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 Ee{static RESERVED_PROPERTY_KEYS=new Set([y.OBJECT_SCHEMA,y.OBJECT_MERGE_POLICY,y.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((s,o)=>{this.validateListControlNode(s,[...t,"items",String(o)],o)});const i=e.getProperties();if(i!==void 0)for(const[s,o]of Object.entries(i))this.validateListControlNode(o,[...t,s])}static validateNode(e,t,r){r.insideItems&&this.validateListControlItem(e,t,r.itemIndex??0);const i=e.getReferenceBlueId();if(i!==void 0&&!C.hasBlueIdOnly(e))if(r.insideItems&&P.hasPositionProperty(e)&&C.hasBlueIdOnly(P.withoutPosition(e)))P.readPosition(e);else{const p=this.toPointer(t);throw new Ne(H.AMBIGUOUS_BLUE_ID_PAYLOAD,`Ambiguous blueId plus payload at ${p}. Use exact { blueId } for references or remove blueId from payload content.`,[{code:H.AMBIGUOUS_BLUE_ID_PAYLOAD,message:"A storage or authoring node cannot combine blueId with payload.",locationPath:t,context:{blueId:i}}])}const s=this.getChildProperties(e,t,r),o=e.getValue()!==void 0,a=e.getItems()!==void 0,l=Object.keys(s).length>0;o&&a&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value and items payloads."),o&&l&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value payload with object child fields."),a&&l&&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((d,p)=>{this.validateNode(d,[...t,"items",String(p)],{insideItems:!0,itemIndex:p})});const c=e.getProperties();if(c!==void 0)for(const[d,p]of Object.entries(c))this.validateNode(p,[...t,d],{insideItems:!1})}static validateListControlItem(e,t,r){if(P.hasEmptyProperty(e)&&(P.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $previous."),P.hasPositionProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $pos."),P.isEmptyItem(e)||this.throwInvalidStorageShape(t,"$empty list content must be exactly { $empty: true }.")),P.hasPreviousProperty(e)&&(r!==0&&this.throwInvalidStorageShape(t,"$previous list control is allowed only as the first item."),P.isPreviousItem(e)||this.throwInvalidStorageShape(t,"$previous list control must be exactly { $previous: { blueId: <id> } }.")),P.hasPositionProperty(e)){P.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$pos cannot be combined with $previous.");try{P.readPosition(e)}catch(i){this.throwInvalidStorageShape([...t,Re],i instanceof Error?i.message:"$pos must be a non-negative integer value.")}P.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 i=e.getProperties()??{};return Object.prototype.hasOwnProperty.call(i,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(i).filter(([s])=>!this.RESERVED_PROPERTY_KEYS.has(s)&&!(r.insideItems&&(s===Re||s===Et))))}static throwInvalidStorageShape(e,t){const r=this.toPointer(e);throw new Ne(H.INVALID_STORAGE_SHAPE,`${t} at ${r}`,[{code:H.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 Ei{static get(e,t,r){const i={};for(const[o,a]of e.entries())this.put(i,o,this.schemaFieldValue(o,a,t,r));const s=e.getEnum();return s!==void 0&&(i.enum=s.map(o=>this.scalarOrExplicitNode(o,t,r))),i}static schemaFieldValue(e,t,r,i){return rr(e)||ir(e)?i(t.getValue())??r(t):ci(e)?this.numericValue(t,r,i):r(t)}static numericValue(e,t,r){return this.isPlainScalar(e)?r(e.getValue())??t(e):t(e)}static scalarOrExplicitNode(e,t,r){return this.isPlainScalar(e)?r(e.getValue())??t(e):t(e)}static isPlainScalar(e){return e.getValue()!==void 0&&e.getValue()!==null&&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&&e.getContractsNode()===void 0&&e.getBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static put(e,t,r){r!=null&&(e[t]=r)}}class B{static get(e,t="official"){const{strategy:r}=this.normalizeOptions(t),i=e.getValue(),s=this.handleValue(i);if(s!==void 0&&r==="simple")return s;const o=e.getItems()?.map(T=>B.get(T,r));if(o!==void 0&&r==="simple")return o;const a=e.getName(),l=e.getDescription();if(r==="original"&&a===void 0&&l===void 0){if(s!==void 0)return s;if(o!==void 0)return o}const c={};a!==void 0&&(c[ae]=a),l!==void 0&&(c[le]=l);const d=e.getType();if(r==="official"&&i!==void 0&&d===void 0){const T=this.inferTypeBlueId(i);T!==null&&(c[U]={[N]:T})}else d!==void 0&&(c[U]=B.get(d,r));const p=e.getItemType();p!==void 0&&(c[me]=B.get(p,r));const f=e.getKeyType();f!==void 0&&(c[ge]=B.get(f,r));const I=e.getValueType();I!==void 0&&(c[ye]=B.get(I,r));const v=e.getMergePolicy();v!==void 0&&(c[y.OBJECT_MERGE_POLICY]=v),s!==void 0&&(c[X]=s),o!==void 0&&(c[Te]=o);const E=e.getBlueId();E!==void 0&&(c[N]=E);const L=e.getBlue();L!==void 0&&(c[rt]=B.get(L,r));const $=e.getPreviousBlueId();$!==void 0&&(c[ce]={[N]:$});const W=e.getPosition();W!==void 0&&(c[it]=W);const ee=e.getSchema();ee!==void 0&&(c[y.OBJECT_SCHEMA]=Ei.get(ee,T=>B.get(T,r),T=>B.handleValue(T)));const we=e.getContractsNode();we!==void 0&&(c[y.OBJECT_CONTRACTS]=B.get(we,r));const w=e.getProperties();return w!==void 0&&Object.entries(w).forEach(([T,te])=>{c[T]=B.get(te,r)}),c}static handleValue(e){if(D(e)){if(Y(e)){const t=new fe(Number.MIN_SAFE_INTEGER.toString()),r=new fe(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"?z:D(e)?Y(e)?j:_:typeof e=="boolean"?K:null}static normalizeOptions(e){return typeof e=="string"?{strategy:e}:{strategy:e.strategy??"official"}}}class M{static transform(e,t){const r=t(e.clone()),i=r.getType();i!==void 0&&r.setType(M.transform(i,t));const s=r.getItemType();s!==void 0&&r.setItemType(M.transform(s,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(M.transform(o,t));const a=r.getValueType();a!==void 0&&r.setValueType(M.transform(a,t));const l=r.getSchema();if(l!==void 0){const p=l.clone();for(const[I,v]of p.entries())p.set(I,M.transform(v,t));const f=p.getEnum();f!==void 0&&p.setEnum(f.map(I=>M.transform(I,t))),r.setSchema(p)}const c=r.getItems();if(c!==void 0){const p=c.map(f=>M.transform(f,t));r.setItems(p)}const d=r.getProperties();if(d!==void 0){const p=Object.keys(d).reduce((f,I)=>(f[I]=M.transform(d[I],t),f),{});r.setProperties(p)}return r}}const yt=Symbol.for("zod-schema-annotations");function Pi(){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 or(){const n=Pi();return yt in n||(n[yt]=new WeakMap),n[yt]}function $e(n,e){const t=or(),r=t.get(n)||{};return t.set(n,{...r,...e}),n}const se=n=>or().get(n),ar=n=>e=>{const t=se(e);return $e(e,{...t,blueDescription:n})},lr=n=>{const e=se(n);return u.isNonNullable(e)&&ve.isString(e.blueDescription)?e.blueDescription:null},bi=n=>ar(n)(m.z.string().optional()),Ni=m.z.union([m.z.string(),m.z.boolean()]),cr=n=>e=>{const t=se(e);return $e(e,{...t,blueId:n})},ur=n=>{const e=se(n),t=Ni.safeParse(e?.blueId);return t.success?t.data:null},wi=n=>cr(n??!0)(m.z.string()),dr=n=>e=>{const t=se(e);return $e(e,{...t,blueName:n})},hr=n=>{const e=se(n);return u.isNonNullable(e)&&ve.isString(e.blueName)?e.blueName:null},Si=n=>{const e=m.z.string().optional();return dr(n)(e)},pr=()=>n=>{const e=se(n);return $e(n,{...e,blueNode:!0})},fr=n=>{const e=se(n);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},Dt=n=>!!fr(n),Ci=()=>{const n=m.z.instanceof(h);return pr()(n)},Ri=m.z.object({value:m.z.array(m.z.string()).optional(),defaultValue:m.z.string().optional()}),mr=n=>{const e=se(n),t=Ri.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},Ai=n=>e=>{const t=se(e),r=typeof n=="string"?{value:[n]}:n;return $e(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class Le{static resolveBlueId(e){const t=mr(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const i=t.value?.[0];return u.isNonNullable(i)?i:Le.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}const gr=n=>{const e=String(n._def.typeName);return e==="ZodOptional"||e==="ZodNullable"||e==="ZodReadonly"||e==="ZodBranded"||e==="ZodEffects"||e==="ZodLazy"},Oi=n=>{const e=String(n._def.typeName);return e==="ZodString"||e==="ZodNumber"||e==="ZodBoolean"||e==="ZodBigInt"};class J{static isTypeOf(e,t,r){const i=Le.resolveBlueId(t),s=e.getType()?.getBlueId();if(u.isNullable(i)||u.isNullable(s))return!1;const o=r?.blueIdMapper?.toCurrentBlueId(i)??i,a=r?.blueIdMapper?.toCurrentBlueId(s)??s;if(o===a)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const l=r.typeSchemaResolver.resolveSchema(e);return J.checkSchemaExtension(l,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const i=J.unwrapSchema(e),s=J.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(i,s):!1}static unwrapSchema(e){if(Dt(e))return e;const t=String(e._def.typeName);return t==="ZodEffects"?J.unwrapSchema(e.innerType()):t==="ZodLazy"?J.unwrapSchema(e.schema):gr(e)?J.unwrapSchema(e.unwrap()):e}}const yr=Symbol("blue.subtypeCache");function Mi(n,e){return n[yr]=e,n}function jt(n,e){const t=n.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(ie.includes(r)){const s=ct[r];return new h().setBlueId(r).setName(s)}const i=e.fetchByBlueId(r);if(!i||i.length===0)return;if(i.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return i[0].cloneShallow().setBlueId(r)}return t}function A(n,e,t){const r=xe(n),i=xe(e),s=t[yr],o=`${r}|${i}`,a=s?.get(o);if(a!==void 0)return a;const l=Vi(n,e,t,r,i);return s?.set(o,l),l}function xe(n){const e=n.getReferenceBlueId();return e!==void 0?e:b.calculateBlueIdSync(de(n))}function de(n){if(!Ir(n))return n;const e=n.cloneShallow();e.getReferenceBlueId()!==void 0&&!C.hasBlueIdOnly(e)&&e.setReferenceBlueId(void 0);const t=e.getType();t!==void 0&&e.setType(de(t));const r=e.getItemType();r!==void 0&&e.setItemType(de(r));const i=e.getKeyType();i!==void 0&&e.setKeyType(de(i));const s=e.getValueType();s!==void 0&&e.setValueType(de(s));const o=e.getBlue();o!==void 0&&e.setBlue(de(o));const a=e.getItems();a!==void 0&&e.setItems(a.map(c=>de(c)));const l=e.getProperties();return l!==void 0&&e.setProperties(Object.fromEntries(Object.entries(l).map(([c,d])=>[c,de(d)]))),e}function Ir(n){return n.getReferenceBlueId()!==void 0&&!C.hasBlueIdOnly(n)?!0:[n.getType(),n.getItemType(),n.getKeyType(),n.getValueType(),n.getBlue(),...n.getItems()??[],...Object.values(n.getProperties()??{})].some(t=>t!==void 0&&Ir(t))}function Vi(n,e,t,r,i){if(r===i)return!0;if(Di(e,i)&&vr(n))return!1;if(r&&ie.includes(r)){let l=e;for(;l!==void 0;){if(xe(l)===r)return!0;l=jt(l,t)}return!1}let s=n;const o=n.getBlueId();if(o){const l=t.fetchByBlueId(o);l&&l.length===1&&(s=l[0].cloneShallow().setBlueId(o))}let a=s;for(;a!==void 0;){if(xe(a)===i)return!0;a=jt(a,t)}return!1}function Di(n,e){return ie.includes(e)||Li(n)}function vr(n){const e=n.getType();return n.getName()===void 0&&n.getDescription()===void 0&&n.getReferenceBlueId()===void 0&&e!==void 0&&n.getItemType()===void 0&&n.getKeyType()===void 0&&n.getValueType()===void 0&&n.getValue()===void 0&&n.getItems()===void 0&&n.getProperties()===void 0&&n.getContractsNode()===void 0&&n.getSchema()===void 0&&n.getMergePolicy()===void 0&&n.getPreviousBlueId()===void 0&&n.getPosition()===void 0&&n.getBlue()===void 0&&ie.includes(xe(e))}function Li(n){const e=n.getName();return e!==void 0&&Object.prototype.hasOwnProperty.call(lt,e)&&n.getDescription()===void 0&&n.getType()===void 0&&n.getItemType()===void 0&&n.getKeyType()===void 0&&n.getValueType()===void 0&&n.getValue()===void 0&&n.getItems()===void 0&&n.getProperties()===void 0&&n.getContractsNode()===void 0&&n.getReferenceBlueId()===void 0&&n.getSchema()===void 0&&n.getMergePolicy()===void 0&&n.getPreviousBlueId()===void 0&&n.getPosition()===void 0&&n.getBlue()===void 0}function xi(n,e){return At.some(t=>{const r=new h().setBlueId(t);return A(n,r,e)})}function _i(n,e){const t=new h().setBlueId(z);return A(n,t,e)}function Fi(n,e){const t=new h().setBlueId(j);return A(n,t,e)}function Ui(n,e){const t=new h().setBlueId(_);return A(n,t,e)}function zi(n,e){const t=new h().setBlueId(K);return A(n,t,e)}function Ge(n,e){const t=new h().setBlueId(ot);return A(n,t,e)}function He(n,e){const t=new h().setBlueId(at);return A(n,t,e)}function ji(n,e){return nt.some(t=>{const r=new h().setName(t);return A(n,r,e)})}function $i(n,e){for(const t of nt){const r=new h().setName(t);if(A(n,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${n.getName()||"unknown"}".`)}class Tr{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=Le.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),i=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(i))return!1;if(r===i)return!0;if(u.isNonNullable(this.nodeProvider))try{const s=new h().setBlueId(r),o=new h().setBlueId(i);if(A(s,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=Le.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,i]of this.blueIdMap)if(i===e||i._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)?b.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}class ue{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function Lt(n){return new class extends ue{fetchByBlueId(e){return n(e)}}}class Ce extends ue{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 It=Be.types.float.options,ki={...It,construct:n=>{const e=n.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new V(e);if(It.construct)return It.construct(n)}},qi=new Be.Type("tag:yaml.org,2002:float",ki),vt=Be.types.int.options,Ki={...vt,construct:n=>{let e=n;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new R(e);if(vt.construct)return vt.construct(n)}},Gi=new Be.Type("tag:yaml.org,2002:int",Ki),Br=Be.CORE_SCHEMA.extend({implicit:[qi,Gi]}),he=n=>{const e=Be.load(n,{schema:Br});return e===void 0?void 0:e},Er=n=>Be.dump(n,{schema:Br,replacer:(e,t)=>{if(D(t)){if(Y(t)){const r=new fe(Number.MIN_SAFE_INTEGER.toString()),i=new fe(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(i))return t.toString()}return t.toNumber()}return t}}),Pr=`- type:
|
|
1
|
+
"use strict";const fe=require("big.js"),u=require("@blue-labs/shared-utils"),m=require("zod"),$r=require("bs58"),ve=require("radash"),g=require("@blue-labs/repository-contract"),kr=require("js-sha256"),qr=require("crypto");require("base32.js");const Be=require("js-yaml"),Ht=n=>n&&n.__esModule?n:{default:n},De=Ht($r),pt=Ht(qr);class V extends fe{constructor(e){super(e)}}class S extends fe{constructor(e){super(e)}}const ae="name",le="description",U="type",me="itemType",ye="keyType",ge="valueType",X="value",Te="items",N="blueId",rt="blue",wt="constraints",St="properties",Kr="positional",Gr="append-only",ce="$previous",it="$pos",st="$replace",Ie="$empty",Ct=[ae,le,U,me,ye,ge,X,Te,N,rt,g.OBJECT_SCHEMA,g.OBJECT_MERGE_POLICY,g.OBJECT_CONTRACTS,wt,St,ce,it,st,Ie],Yt="Text",Wt="Double",Zt="Integer",Jt="Boolean",Xt="List",Qt="Dictionary",nt=[Yt,Wt,Zt,Jt],Rt=[...nt,Xt,Qt],z="GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC",_="9eWaHYz2vKrFofdHTHAizNNu8xP6QE3WQ5y7DGrGZvyJ",j="E2LM6qgzWG9ttagq2xTmiZkgYEAgkYedFCmU9v7NnVEq",K="AwvXD961fmnmqcSQhjMA7r15HpVh39cefb6ZTyUz2Fm2",ot="8DSFoWG9MqRSUhStqoPLrwVQiYByRh18NWbDEarN8MKF",at="Efkz9D1ARMM7rU43w3rDNVqat1naS6qXKCqP4eHin3yG",At=[z,_,j,K],ie=[...At,ot,at],lt=Object.fromEntries(Rt.map((n,e)=>[n,ie[e]])),ct=Object.fromEntries(ie.map((n,e)=>[n,Rt[e]])),Z={Contract:"6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF","Json Patch Entry":"61W96XosAp3DrEC7PuqLYtmF2A6ETpqH6qF2DgYwDq4c","Contract Execution Result":"AMtAXPmvumgz1GxKUU9uv3ncXiKMENvqq8AaLvD5LXhv",Channel:"4FAZ94JPExNM4pn2ZhtdHa4CVP7uASmLNVrBy7aCG1p5",Handler:"7X46P3Q6FJrogqKrBXTALpqzkieyyiQeatnqLvWzAPXE",Marker:"6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy","Process Embedded":"8FVc8MPz6DcTMgcY3RXU6EBpGa9arWPJ141K2H86yi8Q","Processing Initialized Marker":"6JjyUKoK7uJxA5NY9YhMaKJbXC6c9iHyx1khv4gaAq4Q","Processing Terminated Marker":"GBDBthfshBFr4GQKUU1fmy4GnPL7q2y3as4deUWpuBtu","Channel Event Checkpoint":"9GEC24YbFG9hj4banjYh2oEnDpAob1wAPmhjuykJp8T1","Type Generalization Policy":"Fbenow6tanFHkWzKiDD8fGxminQswQ1FecMRakaCx2WX","Type Generalization Rule":"7Vnmk8StjwY7e9mBNpACrn8oh3KZ7yQBjnXe5bLDWn4D","Document Update Channel":"Ac9LC5T7pHVa1TtkhMBjBRtxecShzvbe7ugUdXT1Mu2o","Triggered Event Channel":"5HwxfbwRBCxG8xYpowWkCPC9akqUSKV7So2M4QHEmLsZ","Lifecycle Event Channel":"2DXGQUiQBQ6CT89jwAsTAXaEPhLgiSXhKCGh9Q7Hv3MQ","Embedded Node Channel":"H6iUJp3GcLypsJDimMSVoxQQdxxuD8j6eqEUWWqCZ6i","Document Update":"7HEaG1SpBdsbVHsrwRTZSZGmpJUWHfFoEzecYWpjo1vm","Document Processing Initiated":"Ht1o66MTLKf7JmnEiR27rRLSwdz8FUTgf2mGPNuLSDUL","Document Processing Terminated":"4HWncQEQsdpk8zcXxYxgdtoXo5nKHxFPWeJfTscCbmeK","Document Processing Fatal Error":"AMZbj5tNGxjPrvaNyw56sfqcLSW2j1XmkncEYUVtgmVC"},Ot={...lt,...Z},er=Object.fromEntries(Object.entries(Z).map(([n,e])=>[e,n])),tr={...ct,...er},Hr=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:nt,BASIC_TYPE_BLUE_IDS:At,BLUE_CONTRACTS_RUNTIME_TYPE_BLUE_ID_TO_NAME_MAP:er,BLUE_CONTRACTS_RUNTIME_TYPE_NAME_TO_BLUE_ID_MAP:Z,BOOLEAN_TYPE:Jt,BOOLEAN_TYPE_BLUE_ID:K,CORE_TYPES:Rt,CORE_TYPE_BLUE_IDS:ie,CORE_TYPE_BLUE_ID_TO_NAME_MAP:ct,CORE_TYPE_NAME_TO_BLUE_ID_MAP:lt,DEFAULT_BLUE_TYPE_BLUE_ID_TO_NAME_MAP:tr,DEFAULT_BLUE_TYPE_NAME_TO_BLUE_ID_MAP:Ot,DICTIONARY_TYPE:Qt,DICTIONARY_TYPE_BLUE_ID:at,DOUBLE_TYPE:Wt,DOUBLE_TYPE_BLUE_ID:_,INTEGER_TYPE:Zt,INTEGER_TYPE_BLUE_ID:j,LIST_CONTROL_EMPTY:Ie,LIST_CONTROL_POS:it,LIST_CONTROL_PREVIOUS:ce,LIST_CONTROL_REPLACE:st,LIST_MERGE_POLICY_APPEND_ONLY:Gr,LIST_MERGE_POLICY_POSITIONAL:Kr,LIST_TYPE:Xt,LIST_TYPE_BLUE_ID:ot,OBJECT_BLUE:rt,OBJECT_BLUE_ID:N,OBJECT_CONSTRAINTS:wt,OBJECT_CONTRACTS:g.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:le,OBJECT_ITEMS:Te,OBJECT_ITEM_TYPE:me,OBJECT_KEY_TYPE:ye,OBJECT_MERGE_POLICY:g.OBJECT_MERGE_POLICY,OBJECT_NAME:ae,OBJECT_PROPERTIES:St,OBJECT_SCHEMA:g.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:Ct,OBJECT_TYPE:U,OBJECT_VALUE:X,OBJECT_VALUE_TYPE:ge,TEXT_TYPE:Yt,TEXT_TYPE_BLUE_ID:z},Symbol.toStringTag,{value:"Module"}));class Yr{static get(e,t,r,i=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return i&&o!==void 0?o:e}const s=t.substring(1).split("/");return this.getRecursive(e,s,0,r,i)}static getRecursive(e,t,r,i,s){if(r===t.length-1&&!s)return this.getNodeForSegment(e,t[r],i,!1);if(r===t.length){const l=e.getValue();return s&&l!==void 0?l:e}const o=t[r],a=this.getNodeForSegment(e,o,i,!0);if(a)return this.getRecursive(a,t,r+1,i,s)}static getNodeForSegment(e,t,r,i){let s;const o=e.getProperties();if(o&&t in o)s=o[t];else switch(t){case"name":{const a=e.getName();s=new h().setValue(a??null);break}case"description":{const a=e.getDescription();s=new h().setValue(a??null);break}case"type":s=e.getType();break;case"itemType":s=e.getItemType();break;case"keyType":s=e.getKeyType();break;case"valueType":s=e.getValueType();break;case"value":{const a=e.getValue();s=new h().setValue(a??null);break}case"blueId":{const a=e.getBlueId();s=new h().setValue(a??null);break}case"blue":s=e.getBlue();break;case"items":{const a=e.getItems();s=new h().setItems(a);break}case"properties":{const a=e.getProperties();s=new h().setProperties(a);break}case g.OBJECT_CONTRACTS:{const a=e.getContracts();s=new h().setContracts(a);break}default:{if(/^\d+$/.test(t)){const a=parseInt(t,10),l=e.getItems();l&&a>=0&&a<l.length?s=l[a]:s=void 0}else s=void 0;break}}if(s)return i&&r?this.link(s,r):s}static link(e,t){const r=t(e);return u.isNonNullable(r)?r:e}}class h{static INTEGER=new h("Integer");name;description;type;itemType;keyType;valueType;value;items;properties;contracts;blueId;schema;mergePolicy;previousBlueId;position;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 h().setValue(e).setInlineValue(!0):this.type=e,this}getItemType(){return this.itemType}setItemType(e){return typeof e=="string"?this.itemType=new h().setValue(e).setInlineValue(!0):this.itemType=e,this}getKeyType(){return this.keyType}setKeyType(e){return typeof e=="string"?this.keyType=new h().setValue(e).setInlineValue(!0):this.keyType=e,this}getValueType(){return this.valueType}setValueType(e){return typeof e=="string"?this.valueType=new h().setValue(e).setInlineValue(!0):this.valueType=e,this}getValue(){const e=this.type?.getBlueId();if(u.isNonNullable(e)&&u.isNonNullable(this.value)){if(e===j&&typeof this.value=="string")return new S(this.value);if(e===_&&typeof this.value=="string"){const t=new V(this.value),r=parseFloat(t.toString());return new V(r.toString())}else if(e===K&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}getRawValue(){return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new S(e.toString()):this.value=new V(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.contracts=e?.[g.OBJECT_CONTRACTS],this}addProperty(e,t){return this.properties||(this.properties={}),this.properties[e]=t,e===g.OBJECT_CONTRACTS&&(this.contracts=t),this}removeProperty(e){return this.properties&&delete this.properties[e],e===g.OBJECT_CONTRACTS&&(this.contracts=void 0),this}getContractsProperty(){return this.contracts??this.properties?.[g.OBJECT_CONTRACTS]}getContracts(){return this.getContractsProperty()?.getProperties()}getContractsNode(){return this.contracts??this.properties?.[g.OBJECT_CONTRACTS]}setContracts(e){return u.isNullable(e)?(this.contracts=void 0,this.removeProperty(g.OBJECT_CONTRACTS)):(this.contracts=new h().setProperties(e),this.addProperty(g.OBJECT_CONTRACTS,this.contracts)),this}setContractsNode(e){return this.contracts=e,e===void 0?this.removeProperty(g.OBJECT_CONTRACTS):this.addProperty(g.OBJECT_CONTRACTS,e),this}addContract(e,t){const r=this.getContractsProperty();return u.isNullable(r)?this.addProperty(g.OBJECT_CONTRACTS,new h().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(g.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)}getSchema(){return this.schema}setSchema(e){return this.schema=e,this}getMergePolicy(){return this.mergePolicy}setMergePolicy(e){return this.mergePolicy=e,this}getPreviousBlueId(){return this.previousBlueId}setPreviousBlueId(e){return this.previousBlueId=e,this}getPosition(){return this.position}setPosition(e){return this.position=e,this}getBlue(){return this.blue}setBlue(e){return this.blue=e,this}isInlineValue(){return this.inlineValue}setInlineValue(e){return this.inlineValue=e,this}isResolved(){return!1}get(e,t){return Yr.get(this,e,t)}getAsNode(e){const t=this.get(e);if(t instanceof h)return t;throw new Error(`Value at path ${e} is not a BlueNode: ${t}`)}getAsInteger(e){const t=this.get(e);if(t instanceof S||t instanceof V)return t.toNumber();throw new Error(`Value at path ${e} is not a BigInteger or BigDecimal: ${t}`)}clone(){const e=new h(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()]))),this.contracts&&(e.contracts=e.properties?.[g.OBJECT_CONTRACTS]??this.contracts.clone()),e.blueId=this.blueId,e.schema=this.schema?.clone(),e.mergePolicy=this.mergePolicy,e.previousBlueId=this.previousBlueId,e.position=this.position,e.blue=this.blue?.clone(),e.inlineValue=this.inlineValue,e}cloneShallow(){const e=new h(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.contracts=e.properties?.[g.OBJECT_CONTRACTS]??this.contracts,e.blueId=this.blueId,e.schema=this.schema,e.mergePolicy=this.mergePolicy,e.previousBlueId=this.previousBlueId,e.position=this.position,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 G{static MIN_BLUE_ID_LENGTH=41;static MAX_BLUE_ID_LENGTH=45;static ZERO_BLUE_ID="0".repeat(44);static PLAIN_BLUE_ID_PATTERN=/^[1-9A-HJ-NP-Za-km-z]+$/;static CYCLIC_MEMBER_PATTERN=/^([1-9A-HJ-NP-Za-km-z]+)#(0|[1-9]\d*)$/;static THIS_MEMBER_PATTERN=/^this#(0|[1-9]\d*)$/;static ZERO_PLACEHOLDER_PATTERN=/^0{44}$/;static isPotentialBlueId(e){try{return this.requireBlueIdOrCyclicMember(e,"blueId"),!0}catch{return!1}}static requirePlainBlueId(e,t){if(e===void 0||e.length===0||!this.PLAIN_BLUE_ID_PATTERN.test(e))throw new Error(`Expected canonical Base58 SHA-256 BlueId at ${t}.`);try{const r=De.default.decode(e);if(r.length!==32||De.default.encode(r)!==e)throw new Error}catch{throw new Error(`Expected canonical Base58 SHA-256 BlueId at ${t}.`)}return e}static requireBlueIdOrCyclicMember(e,t){if(e===void 0)throw new Error(`Expected BlueId at ${t}.`);const r=e.match(this.CYCLIC_MEMBER_PATTERN);if(r!==null)return this.requirePlainBlueId(r[1],t),e;if(e.includes("#"))throw new Error(`Invalid cyclic BlueId member syntax at ${t}.`);return this.requirePlainBlueId(e,t)}static requireNoThisPlaceholderOutsideCyclicApi(e,t){if(e!==void 0&&(e==="this"||this.THIS_MEMBER_PATTERN.test(e)))throw new Error(`"this" BlueId placeholders are valid only inside cyclic BlueId calculation APIs. Path: ${t}`);return e}static isCyclicCalculationPlaceholder(e){return e!==void 0&&(e==="this"||this.THIS_MEMBER_PATTERN.test(e)||this.ZERO_PLACEHOLDER_PATTERN.test(e))}}const Wr=m.z.string().max(G.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(G.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(n=>{try{return De.default.decode(n),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),Ze=m.z.lazy(()=>m.z.record(m.z.unknown()).and(m.z.object({blueId:m.z.string().optional(),name:m.z.string().optional(),description:m.z.string().optional(),type:Ze.optional(),value:m.z.union([m.z.string(),m.z.number(),m.z.boolean()]).optional().nullable(),items:m.z.array(Ze).optional()}))),ze=m.z.object({blueId:m.z.string().optional(),name:m.z.string().optional(),description:m.z.string().optional(),type:Ze.optional()}),Zr=ze.extend({value:m.z.string().optional()}),Jr=ze.extend({value:m.z.number().optional()}),Xr=ze.extend({value:m.z.boolean().optional()}),Qr=ze.extend({items:m.z.array(m.z.string()).optional()}),M=n=>n instanceof fe,Y=n=>M(n)&&n instanceof S,Je=n=>M(n)&&n instanceof V,ei=m.z.lazy(()=>m.z.record(Xe)),ti=m.z.lazy(()=>m.z.union([m.z.array(Xe),m.z.array(Xe).readonly()])),Xe=m.z.lazy(()=>m.z.union([u.jsonPrimitiveSchema,ei,ti,m.z.instanceof(fe)])),q=n=>ve.isObject(n)&&!ve.isArray(n)&&!u.isReadonlyArray(n)&&!M(n),Mt=n=>ve.isArray(n)||u.isReadonlyArray(n),ri=n=>Mt(n)||q(n)||M(n)||u.isJsonPrimitive(n),ut=["required","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minItems","maxItems","uniqueItems","minFields","maxFields"],ii=["required","uniqueItems"],si=["minLength","maxLength","minItems","maxItems","minFields","maxFields"],ni=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"],oi=new Set(ii),ai=new Set(si),li=new Set(ni);function rr(n){return oi.has(n)}function ir(n){return ai.has(n)}function ci(n){return li.has(n)}class je{fields={};enumValues;get(e){return this.fields[e]}set(e,t){return t===void 0?delete this.fields[e]:this.fields[e]=t,this}getEnum(){return this.enumValues}setEnum(e){return this.enumValues=e,this}entries(){return ut.flatMap(e=>{const t=this.fields[e];return t===void 0?[]:[[e,t]]})}clone(){const e=new je;for(const[t,r]of this.entries())e.set(t,r.clone());return e.setEnum(this.enumValues?.map(t=>t.clone())),e}}const ui=new S(Number.MIN_SAFE_INTEGER.toString()),di=new S(Number.MAX_SAFE_INTEGER.toString());class y{static deserialize(e){return y.handleNode(e,{root:!0,strictReferenceOnly:!0})}static deserializeUnchecked(e){return y.handleNode(e,{root:!1,strictReferenceOnly:!1})}static handleNode(e,t={root:!1,strictReferenceOnly:!0}){if(e===void 0)throw new Error("This is not a valid JSON-like value. Found 'undefined' as a value.");if(e===null&&t.root)throw new Error("Root null is not a valid Blue document.");if(q(e)){const r=new h,i={};return Object.entries(e).forEach(([s,o])=>{switch(s){case ae:if(o==null)r.setName(void 0);else{if(typeof o!="string")throw new Error(`The ${ae} field must be a string.`);r.setName(o)}break;case le:if(o==null)r.setDescription(void 0);else{if(typeof o!="string")throw new Error(`The ${le} field must be a string.`);r.setDescription(o)}break;case U:r.setType(y.handleNode(o,{...t,root:!1}));break;case me:r.setItemType(y.handleNode(o,{...t,root:!1}));break;case ye:r.setKeyType(y.handleNode(o,{...t,root:!1}));break;case ge:r.setValueType(y.handleNode(o,{...t,root:!1}));break;case g.OBJECT_MERGE_POLICY:if(o!=="positional"&&o!=="append-only"&&o!==void 0)throw new Error('The mergePolicy field must be "positional" or "append-only".');r.setMergePolicy(o);break;case X:r.setValue(y.handleValue(o));break;case N:if(t.strictReferenceOnly&&Object.keys(e).length!==1)throw new Error("blueId nodes must be reference-only and cannot contain sibling fields.");if(typeof o!="string")throw new Error(`The ${N} field must be a string.`);r.setBlueId(o);break;case Te:r.setItems(y.handleArray(o,t));break;case rt:r.setBlue(y.handleNode(o,{...t,root:!1}));break;case ce:if(Object.keys(e).length!==1)throw new Error("$previous list anchors must be single-key list items.");r.setPreviousBlueId(y.handlePreviousBlueId(o));break;case it:r.setPosition(y.handlePosition(o));break;case g.OBJECT_SCHEMA:r.setSchema(y.handleSchema(o,t));break;case g.OBJECT_CONTRACTS:i[s]=y.handleNode(o,{...t,root:!1});break;case wt:throw new Error("constraints is not part of the Blue Language 1.0 top-level vocabulary.");case St:throw new Error("properties is an internal field and must not appear in Blue documents.");default:i[s]=y.handleNode(o,{...t,root:!1});break}}),Object.keys(i).length>0&&r.setProperties(i),r}else{if(Mt(e))return new h().setItems(y.handleArray(e,t));{const r=e;return new h().setValue(y.handleValue(r)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||M(e)){if(typeof e=="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error("Unquoted integers outside [-9007199254740991, 9007199254740991] must be quoted and explicitly typed as Integer.");if(Y(e)||Number.isSafeInteger(e)){const t=new S(e.toString());if(t.lt(ui)||t.gt(di))throw new Error("Unquoted integers outside [-9007199254740991, 9007199254740991] must be quoted and explicitly typed as Integer.");return t}else{const t=parseFloat(e.toString());return new V(t.toString())}}else if(typeof e=="boolean")return e;throw new Error(`Can't handle node: ${JSON.stringify(e)}`)}static handleArray(e,t){if(e!=null){if(ve.isObject(e)&&!Array.isArray(e))return[y.handleNode(e,{...t,root:!1})];if(Array.isArray(e))return e.map(r=>y.handleNode(r,{...t,root:!1}));throw new Error("Expected an array node")}}static handlePreviousBlueId(e){if(!q(e)||Object.keys(e).length!==1)throw new Error("$previous must have shape { blueId: <PrevListBlueId> }.");const t=e[N];if(typeof t!="string")throw new Error("$previous.blueId must be a string.");return t}static handlePosition(e){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error("$pos must be a non-negative integer.");return e}static handleSchema(e,t){if(!q(e))throw new Error("schema must be an object.");const r=new je;for(const i of Object.keys(e)){if(i==="enum"){const s=e[i];if(!Array.isArray(s))throw new Error("schema.enum must be a list.");r.setEnum(s.map(o=>y.handleNode(o,{...t,root:!1})));continue}if(!ut.includes(i))throw new Error(`schema.${i} is not part of the Blue language core.`);y.validateSchemaKeywordShape(i,e[i],t),r.set(i,y.handleNode(e[i],{...t,root:!1}))}return r}static validateSchemaKeywordShape(e,t,r){if(rr(e)){if(typeof t!="boolean")throw new Error(`schema.${e} must be a boolean.`);return}if(ir(e)){if(typeof t!="number"||!Number.isInteger(t)||t<0||!Number.isSafeInteger(t))throw new Error(`schema.${e} must be a non-negative integer in the interoperable range.`);return}if(q(t)){const i=y.handleNode(t,{...r,root:!1});if(y.isExplicitNumericValue(i))return;throw new Error(`schema.${e} must be numeric or an explicit numeric scalar node.`)}if(typeof t!="number"&&!M(t))throw new Error(`schema.${e} must be numeric or an explicit numeric scalar node.`)}static isExplicitNumericValue(e){if(!y.isExplicitSchemaScalar(e,!0))return!1;const t=e.getRawValue(),r=e.getType();return r===void 0?M(t)||typeof t=="number":y.isIntegerType(r)?y.isIntegerSchemaValue(t):y.isDoubleType(r)?y.isDoubleSchemaValue(t):!1}static isIntegerSchemaValue(e){if(typeof e=="number")return Number.isInteger(e);if(M(e))return e.mod(1).eq(0);if(typeof e=="string")try{return new S(e).mod(1).eq(0)}catch{return!1}return!1}static isDoubleSchemaValue(e){if(typeof e=="number")return Number.isFinite(e);if(M(e))return!0;if(typeof e=="string")try{return new V(e),!0}catch{return!1}return!1}static isExplicitSchemaScalar(e,t){const r=e.getType();return e.getValue()!==void 0&&e.getValue()!==null&&(t||r===void 0)&&e.getName()===void 0&&e.getDescription()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0&&e.getContractsNode()===void 0&&e.getBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0&&(r===void 0||y.isScalarType(r))}static isScalarType(e){return y.isCoreType(e,z,"Text")||y.isCoreType(e,j,"Integer")||y.isCoreType(e,_,"Double")||y.isCoreType(e,K,"Boolean")}static isIntegerType(e){return y.isCoreType(e,j,"Integer")}static isDoubleType(e){return y.isCoreType(e,_,"Double")}static isCoreType(e,t,r){return e.getBlueId()===t||e.isInlineValue()&&e.getValue()===r}}function hi(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ft,Ut;function pi(){return Ut||(Ut=1,ft=function n(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?n(e.toJSON()):Array.isArray(e)?`[${e.reduce((i,s,o)=>`${i}${o===0?"":","}${n(s===void 0||typeof s=="symbol"?null:s)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,i)=>{if(e[i]===void 0||typeof e[i]=="symbol")return r;const s=r.length===0?"":",";return`${r}${s}${n(i)}:${n(e[i])}`},"")}}`}),ft}var fi=pi();const mi=hi(fi);class Qe{static canonicalize(e){return mi(e)}}const mt=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class Vt{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new Vt),this.instance}initBrowserCrypto(){return mt?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return mt&&!!pt.default&&typeof pt.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return mt?pt.default:null}}class sr{cryptoEnv=Vt.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return De.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return De.default.encode(r)}canonicalizeInput(e){const t=Qe.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(kr.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 i=new TextEncoder().encode(e),s=await t.subtle.digest("SHA-256",i);return new Uint8Array(s)}}class nr{static toCanonicalDoubleValue(e){const t=e instanceof V||e instanceof S?e.toNumber():typeof e=="number"?e:typeof e=="string"?Number(e):Number.NaN;if(!Number.isFinite(t))throw new Error("Double value must be finite.");return new V(t.toString())}static isExactBinary64Multiple(e,t){const r=be.fromNumber(this.toFiniteNumber(e)),i=be.fromNumber(this.toFiniteNumber(t));return r.dividedByIsInteger(i)}static toFiniteNumber(e){const t=e instanceof V||e instanceof S?e.toNumber():typeof e=="number"?e:Number.NaN;if(!Number.isFinite(t))throw new Error("Double value must be finite.");return t}}class be{constructor(e,t){if(this.numerator=e,this.denominator=t,t<=0n)throw new Error("denominator must be positive");const r=yi(zt(e),t);this.numerator=e/r,this.denominator=t/r}static fromNumber(e){if(!Number.isFinite(e))throw new Error("Double value must be finite.");if(Object.is(e,0)||Object.is(e,-0))return new be(0n,1n);const t=new ArrayBuffer(8),r=new DataView(t);r.setFloat64(0,e,!1);const i=r.getBigUint64(0,!1),s=(i&1n<<63n)!==0n,o=Number(i>>52n&0x7ffn),a=i&0x000fffffffffffffn;let l,c;return o===0?(l=a,c=-1074):(l=1n<<52n|a,c=o-1023-52),s&&(l=-l),c>=0?new be(l<<BigInt(c),1n):new be(l,1n<<BigInt(-c))}dividedByIsInteger(e){if(e.numerator===0n)throw new Error("Division by zero rational.");const t=this.numerator*e.denominator,r=this.denominator*zt(e.numerator);return t%r===0n}}function yi(n,e){let t=n,r=e;for(;r!==0n;){const i=t%r;t=r,r=i}return t===0n?1n:t}function zt(n){return n<0n?-n:n}const gi=new S(Number.MIN_SAFE_INTEGER.toString()),Ii=new S(Number.MAX_SAFE_INTEGER.toString());class ne{static get(e){return this.getNode(e,"/","root",-1,!1)}static getAllowingCyclicPlaceholders(e){return this.getNode(e,"/","root",-1,!0)}static getWithResolvedBlueIdMetadata(e){return this.getNode(this.stripResolvedBlueIdMetadata(e.clone()),"/","root",-1,!1)}static stripResolvedBlueIdMetadata(e){e.getReferenceBlueId()!==void 0&&!this.isReferenceOnly(e)&&e.setReferenceBlueId(void 0),this.stripResolvedBlueIdMetadataChild(e.getType()),this.stripResolvedBlueIdMetadataChild(e.getItemType()),this.stripResolvedBlueIdMetadataChild(e.getKeyType()),this.stripResolvedBlueIdMetadataChild(e.getValueType()),this.stripResolvedBlueIdMetadataChild(e.getBlue()),this.stripResolvedBlueIdMetadataChild(e.getContractsNode()),e.getItems()?.forEach(r=>this.stripResolvedBlueIdMetadata(r)),Object.values(e.getProperties()??{}).forEach(r=>this.stripResolvedBlueIdMetadata(r));const t=e.getSchema();return t?.entries().forEach(([,r])=>this.stripResolvedBlueIdMetadata(r)),t?.getEnum()?.forEach(r=>this.stripResolvedBlueIdMetadata(r)),e}static stripResolvedBlueIdMetadataChild(e){e!==void 0&&this.stripResolvedBlueIdMetadata(e)}static getListElement(e,t){return this.getNode(e,`/${t}`,"list-element",t,!1)}static getListElementAllowingCyclicPlaceholders(e,t){return this.getNode(e,`/${t}`,"list-element",t,!0)}static getNode(e,t,r,i,s){if(this.validateBlueIdInput(e,t,r,i),r==="list-element"&&this.isEmptyPlaceholder(e))return{[Ie]:!0};if(this.isReferenceOnly(e)){const f=this.validateReferenceBlueId(e.getReferenceBlueId(),this.appendPath(t,N),s);return{[N]:f}}if(e.getPreviousBlueId()!==void 0){const f=G.requirePlainBlueId(e.getPreviousBlueId(),this.appendPath(this.appendPath(t,ce),N));return{[ce]:{[N]:f}}}const o=e.getValue(),a=e.getItems(),l=a===void 0?void 0:a.map((f,I)=>this.getNode(f,this.appendPath(this.appendPath(t,Te),String(I)),"list-element",I,s));if(l!==void 0&&this.isPayloadOnlyList(e))return l;const c={};this.setString(c,ae,e.getName()),this.setString(c,le,e.getDescription());let d;o!=null&&e.getType()===void 0?(d=this.inferTypeBlueId(o),d!==void 0&&(c[U]={[N]:d})):e.getType()!==void 0&&(d=e.getType()?.getReferenceBlueId(),c[U]=this.getNode(e.getType(),this.appendPath(t,U),"metadata",-1,s)),this.setNode(c,me,e.getItemType(),t,s),this.setNode(c,ye,e.getKeyType(),t,s),this.setNode(c,ge,e.getValueType(),t,s),e.getMergePolicy()!==void 0&&(c[g.OBJECT_MERGE_POLICY]=e.getMergePolicy()),o!=null&&(c[X]=this.handleValue(o,d)),l!==void 0&&(c[Te]=l);const p=e.getSchema();p!==void 0&&(c[g.OBJECT_SCHEMA]=this.schemaToInput(p,this.appendPath(t,g.OBJECT_SCHEMA),s)),e.getContractsNode()!==void 0&&(c[g.OBJECT_CONTRACTS]=this.getNode(e.getContractsNode(),this.appendPath(t,g.OBJECT_CONTRACTS),"metadata",-1,s));for(const[f,I]of Object.entries(e.getProperties()??{}))f!==g.OBJECT_CONTRACTS&&(c[f]=this.getNode(I,this.appendPath(t,f),"object-field",-1,s));return c}static schemaToInput(e,t,r){const i={};for(const[o,a]of e.entries())i[o]=this.getNode(a,this.appendPath(t,o),"metadata",-1,r);const s=e.getEnum();return s!==void 0&&(i.enum=this.canonicalizeSchemaEnumValues(s,this.appendPath(t,"enum"),r).map((o,a)=>this.getNode(o,this.appendPath(this.appendPath(t,"enum"),String(a)),"metadata",-1,r))),i}static canonicalizeSchemaEnumValues(e,t,r){const i=new Map;for(const s of e){const o=s.clone();o.setSchema(void 0),i.set(JSON.stringify(this.getNode(o,t,"metadata",-1,r)),s)}return[...i.entries()].sort(([s],[o])=>s.localeCompare(o)).map(([,s])=>s)}static validateReferenceBlueId(e,t,r){return r&&G.isCyclicCalculationPlaceholder(e)?e:G.requireBlueIdOrCyclicMember(G.requireNoThisPlaceholderOutsideCyclicApi(e,t),t)}static validateBlueIdInput(e,t,r,i){if(e===void 0)throw new Error(`BlueId input must not contain null nodes. Path: ${t}`);if(r==="metadata"&&this.isTypePosition(t)&&e.isInlineValue())throw new Error(`Direct BlueId input must not contain unresolved type aliases. Path: ${t}`);if(e.getBlue()!==void 0)throw new Error(`"blue" is a preprocessing directive and must not be present in BlueId input. Call preprocess/canonicalize/calculateSemanticBlueId first. Path: ${t}`);if(e.getPosition()!==void 0)throw new Error(`"$pos" overlays are not valid direct BlueId input. Path: ${t}`);if(e.getProperties()?.[st]!==void 0)throw new Error(`"$replace" overlays are not valid direct BlueId input. Path: ${t}`);if(r==="list-element"){if(this.isEmptyNode(e))throw new Error(`Direct BlueId input must use { "$empty": true } for empty list placeholders. Path: ${t}`);if(e.getProperties()?.[Ie]!==void 0&&this.validateEmptyPlaceholder(e,t),e.getPreviousBlueId()!==void 0&&i!==0)throw new Error(`"$previous" must appear only as the first list item. Path: ${t}`)}else if(e.getPreviousBlueId()!==void 0)throw new Error(`"$previous" is valid only as the first list item in direct BlueId input. Path: ${t}`);this.validatePayloadKind(e,t)}static validatePayloadKind(e,t){const r=this.ordinaryPropertyKeys(e),i=[e.getValue()!==void 0&&e.getValue()!==null,e.getItems()!==void 0,r.length>0].filter(Boolean).length;if(i>1)throw new Error(`A Blue node may contain only one payload kind: value, items, or object fields. Path: ${t}`);if(e.getReferenceBlueId()!==void 0&&!this.isReferenceOnly(e))throw new Error(`"blueId" nodes must be reference-only and cannot contain sibling fields. Path: ${t}`);if(e.getPreviousBlueId()!==void 0&&(i>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.getSchema()!==void 0||e.getMergePolicy()!==void 0||e.getPosition()!==void 0||e.getContractsNode()!==void 0||e.getReferenceBlueId()!==void 0))throw new Error(`"$previous" list anchors must be single-key list items. Path: ${t}`)}static handleValue(e,t){if(t===_)return nr.toCanonicalDoubleValue(e).toNumber();if(e instanceof S||Y(e))return e.lt(gi)||e.gt(Ii)?e.toString():e.toNumber();const r=e;if(r instanceof V||M(r))return r.toNumber();if(typeof e=="string"||typeof e=="boolean")return e;throw new Error(`Unsupported Blue scalar value: ${String(e)}`)}static inferTypeBlueId(e){if(typeof e=="string")return z;if(e instanceof S||Y(e))return j;if(e instanceof V||M(e))return _;if(typeof e=="boolean")return K}static setString(e,t,r){r!==void 0&&(e[t]=r)}static setNode(e,t,r,i,s){r!==void 0&&(e[t]=this.getNode(r,this.appendPath(i,t),"metadata",-1,s))}static isReferenceOnly(e){return e.getReferenceBlueId()!==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.getValue()===void 0||e.getValue()===null)&&e.getItems()===void 0&&this.ordinaryPropertyKeys(e).length===0&&e.getContractsNode()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static isPayloadOnlyList(e){return e.getItems()!==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.getValue()===void 0||e.getValue()===null)&&this.ordinaryPropertyKeys(e).length===0&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static isEmptyNode(e){return 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.getValue()===void 0||e.getValue()===null)&&e.getItems()===void 0&&this.ordinaryPropertyKeys(e).length===0&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static isEmptyPlaceholder(e){const t=e.getProperties(),r=t?.[Ie];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&r.getValue()===!0&&r.getItems()===void 0&&Object.keys(r.getProperties()??{}).length===0}static validateEmptyPlaceholder(e,t){if(!this.isEmptyPlaceholder(e))throw new Error(`"$empty" list placeholder must have exact shape { "$empty": true }. Path: ${t}`)}static isTypePosition(e){return e.endsWith(`/${U}`)||e.endsWith(`/${me}`)||e.endsWith(`/${ye}`)||e.endsWith(`/${ge}`)}static appendPath(e,t){const r=t.replace(/~/g,"~0").replace(/\//g,"~1");return e==="/"?`/${r}`:`${e}/${r}`}static ordinaryPropertyKeys(e){return Object.keys(e.getProperties()??{}).filter(t=>t!==g.OBJECT_CONTRACTS)}}const vi=new Set([ae,le,X]);class b{constructor(e){this.hashProvider=e}static INSTANCE=new b(new sr);static calculateBlueId(e){return b.INSTANCE.calculate(e)}static calculateBlueIdSync(e){return b.INSTANCE.calculateSync(e)}static calculateBlueIdAllowingCyclicPlaceholdersSync(e){return b.INSTANCE.calculateAllowingCyclicPlaceholdersSync(e)}static calculateBlueIdWithResolvedBlueIdMetadataSync(e){return b.INSTANCE.calculateInput(ne.getWithResolvedBlueIdMetadata(e),!0)}static calculateBlueIdInputSync(e){return b.INSTANCE.calculateInput(e,!0)}calculate(e){return this.calculateInput(this.prepareInput(e),!1)}calculateSync(e){return this.calculateInput(this.prepareInput(e),!0)}calculateAllowingCyclicPlaceholdersSync(e){return this.calculateInput(this.prepareInputAllowingCyclicPlaceholders(e),!0)}prepareInput(e){return e instanceof h?ne.get(e):Array.isArray(e)&&e.every(t=>t instanceof h)?e.map((t,r)=>ne.getListElement(t,r)):ne.get(y.deserialize(e))}prepareInputAllowingCyclicPlaceholders(e){return e instanceof h?ne.getAllowingCyclicPlaceholders(e):Array.isArray(e)&&e.every(t=>t instanceof h)?e.map((t,r)=>ne.getListElementAllowingCyclicPlaceholders(t,r)):ne.getAllowingCyclicPlaceholders(y.deserialize(e))}calculateInput(e,t){return this.calculateCleaned(this.cleanRoot(e),t)}calculateCleaned(e,t){return this.isScalar(e)?this.applyHash(e,t):Array.isArray(e)?this.calculateList(e,t):this.calculateMap(e,t)}calculateMap(e,t){if(Object.keys(e).length===1&&typeof e[N]=="string")return e[N];const r=Object.keys(e).sort().map(i=>{const s=e[i];if(vi.has(i))return[i,s];const o=this.calculateCleaned(s,t);return t?[i,{[N]:o}]:Promise.resolve(o).then(a=>[i,{[N]:a}])});return t?this.applyHash(Object.fromEntries(r),!0):Promise.all(r).then(i=>this.applyHash(Object.fromEntries(i),!1))}calculateList(e,t){let r,i=0;e.length>0&&this.isPreviousControl(e[0])?(r=this.previousBlueId(e[0]),i=1):r=this.applyHash({$list:"empty"},t);for(let s=i;s<e.length;s+=1){const o=r,a=this.calculateCleaned(e[s],t);t?r=this.applyHash(this.listCons(o,a),!0):r=Promise.all([o,a]).then(([l,c])=>this.applyHash(this.listCons(l,c),!1))}return r}listCons(e,t){return{$listCons:{elem:{[N]:t},prev:{[N]:e}}}}cleanRoot(e){if(e==null)throw new Error("Root null is not valid BlueId input.");if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.cleanRoot(r));const t={};for(const[r,i]of Object.entries(e)){const s=this.cleanObjectField(i);s!==void 0&&(t[r]=s)}return t}cleanObjectField(e){if(e==null)return;if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.cleanRoot(r));const t={};for(const[r,i]of Object.entries(e)){const s=this.cleanObjectField(i);s!==void 0&&(t[r]=s)}return Object.keys(t).length===0?void 0:t}isPreviousControl(e){if(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length!==1)return!1;const t=e[ce];return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length===1&&typeof t[N]=="string"}previousBlueId(e){return e[ce][N]}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}isScalar(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}}const C={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 R{static isEmptyNode(e){return this.hasFieldsAndMayHaveFields(e)}static hasBlueIdOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([C.BLUE_ID]))}static hasItemsOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([C.ITEMS]))}static isValidValueNode(e){const t=e.getValue(),r=e.getProperties(),i=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(i)}static textNode(e){return new h().setType(new h().setBlueId(z)).setValue(e)}static integerNode(e){const t=e instanceof S?e:new S(e.toString());return new h().setType(new h().setBlueId(j)).setValue(t)}static doubleNode(e){const t=e instanceof V?e:new V(e.toString());return new h().setType(new h().setBlueId(_)).setValue(t)}static booleanNode(e){return new h().setType(new h().setBlueId(K)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const i of Object.values(C)){const s=u.isNonNullable(this.getFieldValue(e,i));if(t.has(i)){if(!s)return!1}else if(!r.has(i)){if(s)return!1}}return!0}static getFieldValue(e,t){switch(t){case C.NAME:return e.getName();case C.TYPE:return e.getType();case C.VALUE:return e.getValue();case C.DESCRIPTION:return e.getDescription();case C.PROPERTIES:return e.getProperties();case C.BLUE:return e.getBlue();case C.ITEMS:return e.getItems();case C.KEY_TYPE:return e.getKeyType();case C.VALUE_TYPE:return e.getValueType();case C.ITEM_TYPE:return e.getItemType();case C.BLUE_ID:return e.getBlueId();default:throw new Error(`Unknown field: ${t}`)}}}const yt="$previous",Re="$pos",Et="$empty";class P{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.getMergePolicy();if(t==="append-only"||t==="positional")return t;const r=e.getProperties()?.[g.OBJECT_MERGE_POLICY]?.getValue();if(r==="append-only"||r==="positional")return r}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 e.getPreviousBlueId()!==void 0||Object.prototype.hasOwnProperty.call(e.getProperties()??{},yt)}static hasPositionProperty(e){return e.getPosition()!==void 0||Object.prototype.hasOwnProperty.call(e.getProperties()??{},Re)}static hasEmptyProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},Et)}static isEmptyItem(e){const t=e.getProperties(),r=t?.[Et];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&R.hasFieldsAndMayHaveFields(e,new Set([C.PROPERTIES]))&&R.hasFieldsAndMayHaveFields(r,new Set([C.VALUE]),new Set([C.TYPE]))&&r.getValue()===!0}static isPreviousItem(e){if(e.getPreviousBlueId()!==void 0)return 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.getValue()===void 0&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0;const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&R.hasFieldsAndMayHaveFields(e,new Set([C.PROPERTIES]))&&R.hasBlueIdOnly(t[yt])}static getPreviousBlueId(e){if(e.getPreviousBlueId()!==void 0)return e.getPreviousBlueId();if(this.isPreviousItem(e))return e.getProperties()?.[yt]?.getBlueId()}static createPreviousItem(e){return new h().setPreviousBlueId(e)}static readPosition(e){if(e.getPosition()!==void 0)return e.getPosition();const t=e.getProperties()?.[Re];if(t===void 0)return;if(!R.hasFieldsAndMayHaveFields(t,new Set([C.VALUE]),new Set([C.TYPE])))throw new Error("$pos must be a non-negative integer value.");const r=t.getValue(),i=r instanceof S?r.toNumber():typeof r=="number"?r:void 0;if(i===void 0||!Number.isInteger(i)||i<0)throw new Error("$pos must be a non-negative integer value.");return i}static createPositionedItem(e,t){return t.clone().setPosition(e)}static withoutPosition(e){const t=e.clone();t.setPosition(void 0);const r=t.getProperties();return r!==void 0&&(delete r[Re],Object.keys(r).length===0&&t.setProperties(void 0)),t}static hasPayloadAfterRemovingPosition(e){return!R.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)}}class k{constructor(e={emitListControls:!0}){this.options=e}reverse(e){const t=new h;return this.reverseNode(t,e,void 0,!0),t}reverseToCanonicalOverlay(e){const t=new h;return this.reverseCanonicalNode(t,e,e.getType()),t}static calculateHashMinimalBlueId(e){return b.calculateBlueIdSync(this.toHashMinimalNode(e))}static calculateHashMinimalListBlueId(e){return b.calculateBlueIdSync(e.map(t=>this.toHashMinimalNode(t)))}static toHashMinimalNode(e){return new k({emitListControls:!1}).reverse(e)}reverseCanonicalNode(e,t,r){if(t.getReferenceBlueId()!==void 0&&r?.getReferenceBlueId()===t.getReferenceBlueId())return;const i=t.getValue();i!=null&&(r===void 0||r.getValue()===void 0||r.getValue()===null||!this.sameScalarValue(i,r.getValue()))&&e.setValue(i),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getType(),(l,c)=>l.setType(c)),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getItemType(),(l,c)=>l.setItemType(c)),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getKeyType(),(l,c)=>l.setKeyType(c)),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getValueType(),(l,c)=>l.setValueType(c)),this.preserveCanonicalPayloadTypeForMetadataOverride(t,e),t.getName()!==void 0&&(r===void 0||t.getName()!==r.getName())&&e.setName(t.getName()),t.getDescription()!==void 0&&(r===void 0||t.getDescription()!==r.getDescription())&&e.setDescription(t.getDescription()),this.isReferenceOnly(t)&&(r===void 0||t.getReferenceBlueId()!==r.getReferenceBlueId())&&e.setReferenceBlueId(t.getReferenceBlueId()),t.getMergePolicy()!==void 0&&(r===void 0||t.getMergePolicy()!==r.getMergePolicy())&&e.setMergePolicy(t.getMergePolicy()),t.getSchema()!==void 0&&!this.sameSchema(t.getSchema(),r?.getSchema())&&e.setSchema(t.getSchema()?.clone());const s=t.getContractsNode();if(s!==void 0){const l=r?.getContractsNode();if(!this.sameNodeBlueId(s,l)){const c=new h;this.reverseCanonicalNode(c,s,l),this.isCanonicalEmptyNode(c)||e.setContractsNode(c)}}const o=t.getItems();o!==void 0&&e.setItems(o.map(l=>{const c=new h;return this.reverseCanonicalNode(c,l,void 0),this.isCanonicalEmptyNode(c)?this.emptyPlaceholder():c}));const a=t.getProperties();if(a!==void 0){const l={};for(const[c,d]of Object.entries(a)){if(c===g.OBJECT_CONTRACTS)continue;const p=r?.getProperties()?.[c];if(this.sameNodeBlueId(d,p))continue;const f=new h;this.reverseCanonicalNode(f,d,p),this.isCanonicalEmptyNode(f)||(l[c]=f)}Object.keys(l).length>0&&e.setProperties(l)}}setCanonicalTypeIfDifferent(e,t,r,i,s){const o=i(e),a=t===void 0?void 0:i(t);o!==void 0&&(a===void 0||a.getReferenceBlueId()!==o.getReferenceBlueId())&&s(r,new h().setReferenceBlueId(o.getReferenceBlueId()))}preserveCanonicalPayloadTypeForMetadataOverride(e,t){if(t.getType()!==void 0||e.getType()===void 0||t.getItemType()===void 0&&t.getKeyType()===void 0&&t.getValueType()===void 0)return;const r=e.getType(),i=r?.getReferenceBlueId();t.setType(i===void 0?r?.clone():new h().setReferenceBlueId(i))}sameSchema(e,t){return e===t?!0:e===void 0||t===void 0?!1:b.calculateBlueIdSync(new h().setSchema(e))===b.calculateBlueIdSync(new h().setSchema(t))}sameNodeBlueId(e,t){return e===t?!0:e===void 0||t===void 0?!1:b.calculateBlueIdWithResolvedBlueIdMetadataSync(e)===b.calculateBlueIdWithResolvedBlueIdMetadataSync(t)}sameScalarValue(e,t){return e!==null&&t!==null&&typeof e=="object"&&typeof t=="object"&&"eq"in e&&typeof e.eq=="function"?!!e.eq(t):e===t}emptyPlaceholder(){return new h().addProperty("$empty",new h().setValue(!0))}isReferenceOnly(e){return e.getReferenceBlueId()!==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.getValue()===void 0&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0&&e.getContractsNode()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}isCanonicalEmptyNode(e){return 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.getValue()===void 0||e.getValue()===null)&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}reverseNode(e,t,r,i){const s=this.getEffectiveFromType(r,t);!i&&this.isIdenticalToType(t,s)||(this.reverseBasicProperties(e,t,s,i),this.reverseTypeReferences(e,t,r,s),this.reverseItems(e,t,s),this.reverseProperties(e,t,s))}isIdenticalToType(e,t){return u.isNonNullable(e.getBlueId())&&u.isNonNullable(t?.getBlueId())&&e.getBlueId()===t.getBlueId()}reverseBasicProperties(e,t,r,i){const s=t.getValue();u.isNonNullable(s)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(s),u.isNonNullable(t.getName())&&(i||u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(i||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,i){const s=(o,a,l)=>{const c=o(t),d=l?o(l):void 0;u.isNonNullable(c)&&!this.areTypeReferencesEquivalent(c,d)&&a(e,this.toMinimalTypeReference(c))};s(o=>o.getType(),(o,a)=>o.setType(a),r),s(o=>o.getItemType(),(o,a)=>o.setItemType(a),i),s(o=>o.getKeyType(),(o,a)=>o.setKeyType(a),i),s(o=>o.getValueType(),(o,a)=>o.setValueType(a),i)}areTypeReferencesEquivalent(e,t){if(u.isNullable(t))return!1;const r=e.getBlueId(),i=t.getBlueId();return u.isNonNullable(r)||u.isNonNullable(i)?u.isNonNullable(r)&&u.isNonNullable(i)&&r===i:k.calculateHashMinimalBlueId(e)===k.calculateHashMinimalBlueId(t)}toMinimalTypeReference(e){const t=e.getBlueId();if(u.isNonNullable(t))return new h().setBlueId(t);const r=new h;return this.reverseNode(r,e,void 0,!0),R.isEmptyNode(r)?e.clone():r}reverseItems(e,t,r){const i=t.getItems();if(u.isNullable(i))return;const s=r?.getItems();if(i.length===0){(u.isNullable(s)||s.length>0)&&e.setItems([]);return}if(u.isNonNullable(s)&&i.length===s.length&&i.every((a,l)=>k.calculateHashMinimalBlueId(a)===k.calculateHashMinimalBlueId(s[l])))return;const o=this.options.emitListControls!==!1&&u.isNonNullable(s)&&s.length>0?this.reverseInheritedItems(t,r):this.reverseFullItems(i);o.length>0&&e.setItems(o)}reverseInheritedItems(e,t){const r=e.getItems()??[],i=t.getItems()??[];if(r.length<i.length)throw new Error(`Resolved list has fewer items (${r.length}) than inherited list (${i.length}).`);const s=P.getMergePolicy(e,t),o=[];for(let c=0;c<i.length;c++)k.calculateHashMinimalBlueId(r[c])!==k.calculateHashMinimalBlueId(i[c])&&o.push(c);if(o.length>0&&s==="append-only")throw new Error("append-only list cannot be minimized as a non-prefix mutation.");const a=k.calculateHashMinimalListBlueId(i),l=[P.createPreviousItem(a)];for(const c of o){const d=new h;this.reverseNode(d,r[c],i[c],!1);const p=R.isEmptyNode(d)?r[c].clone():d;l.push(P.createPositionedItem(c,p))}for(let c=i.length;c<r.length;c++){const d=new h;this.reverseNode(d,r[c],void 0,!1),l.push(d)}return l.length===1?[]:l}reverseFullItems(e){const t=[];for(let r=0;r<e.length;r++){const i=new h;this.reverseNode(i,e[r],void 0,!1),t.push(i)}return t}reverseProperties(e,t,r){const i=t.getProperties();if(u.isNullable(i))return;const s={};for(const[o,a]of Object.entries(i)){const l=this.getInheritedProperty(o,r),c=new h;this.reverseNode(c,a,l,!1),R.isEmptyNode(c)||(s[o]=c)}Object.keys(s).length>0&&e.setProperties(s)}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(!R.isEmptyNode(t))return t}mergeNodes(e,t){const r=e.clone(),i=t.getValue();u.isNonNullable(i)&&r.setValue(i);const s=t.getType();u.isNonNullable(s)&&r.setType(s.clone());const o=t.getItemType();u.isNonNullable(o)&&r.setItemType(o.clone());const a=t.getKeyType();u.isNonNullable(a)&&r.setKeyType(a.clone());const l=t.getValueType();u.isNonNullable(l)&&r.setValueType(l.clone());const c=t.getProperties();if(u.isNonNullable(c)){const p=r.getProperties()||{};for(const[f,I]of Object.entries(c)){const v=p[f];p[f]=v===void 0?I.clone():this.mergeNodes(v,I)}r.setProperties(p)}const d=t.getItems();return u.isNonNullable(d)&&r.setItems(d.map(p=>p.clone())),r}}class Pt{mergeReverser=new k;hashMergeReverser=new k({emitListControls:!1});minimize(e){return this.minimizeResolved(e)}minimizeResolved(e){return this.mergeReverser.reverse(e)}minimizeResolvedForHash(e){return this.hashMergeReverser.reverse(e)}}class Ne extends Error{code;category;details;constructor(e,t,r,i){super(t),this.code=e,this.category=i,this.details=r&&r.length>0?r:[],this.name="BlueError"}}function Ti(n){return Bi(n)?n.category:void 0}function Bi(n){return typeof n=="object"&&n!==null&&typeof n.category=="string"}const H={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 Ee{static RESERVED_PROPERTY_KEYS=new Set([g.OBJECT_SCHEMA,g.OBJECT_MERGE_POLICY,g.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((s,o)=>{this.validateListControlNode(s,[...t,"items",String(o)],o)});const i=e.getProperties();if(i!==void 0)for(const[s,o]of Object.entries(i))this.validateListControlNode(o,[...t,s])}static validateNode(e,t,r){r.insideItems&&this.validateListControlItem(e,t,r.itemIndex??0);const i=e.getReferenceBlueId();if(i!==void 0&&!R.hasBlueIdOnly(e))if(r.insideItems&&P.hasPositionProperty(e)&&R.hasBlueIdOnly(P.withoutPosition(e)))P.readPosition(e);else{const p=this.toPointer(t);throw new Ne(H.AMBIGUOUS_BLUE_ID_PAYLOAD,`Ambiguous blueId plus payload at ${p}. Use exact { blueId } for references or remove blueId from payload content.`,[{code:H.AMBIGUOUS_BLUE_ID_PAYLOAD,message:"A storage or authoring node cannot combine blueId with payload.",locationPath:t,context:{blueId:i}}])}const s=this.getChildProperties(e,t,r),o=e.getValue()!==void 0,a=e.getItems()!==void 0,l=Object.keys(s).length>0;o&&a&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value and items payloads."),o&&l&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value payload with object child fields."),a&&l&&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((d,p)=>{this.validateNode(d,[...t,"items",String(p)],{insideItems:!0,itemIndex:p})});const c=e.getProperties();if(c!==void 0)for(const[d,p]of Object.entries(c))this.validateNode(p,[...t,d],{insideItems:!1})}static validateListControlItem(e,t,r){if(P.hasEmptyProperty(e)&&(P.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $previous."),P.hasPositionProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $pos."),P.isEmptyItem(e)||this.throwInvalidStorageShape(t,"$empty list content must be exactly { $empty: true }.")),P.hasPreviousProperty(e)&&(r!==0&&this.throwInvalidStorageShape(t,"$previous list control is allowed only as the first item."),P.isPreviousItem(e)||this.throwInvalidStorageShape(t,"$previous list control must be exactly { $previous: { blueId: <id> } }.")),P.hasPositionProperty(e)){P.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$pos cannot be combined with $previous.");try{P.readPosition(e)}catch(i){this.throwInvalidStorageShape([...t,Re],i instanceof Error?i.message:"$pos must be a non-negative integer value.")}P.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 i=e.getProperties()??{};return Object.prototype.hasOwnProperty.call(i,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(i).filter(([s])=>!this.RESERVED_PROPERTY_KEYS.has(s)&&!(r.insideItems&&(s===Re||s===Et))))}static throwInvalidStorageShape(e,t){const r=this.toPointer(e);throw new Ne(H.INVALID_STORAGE_SHAPE,`${t} at ${r}`,[{code:H.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 Ei{static get(e,t,r){const i={};for(const[o,a]of e.entries())this.put(i,o,this.schemaFieldValue(o,a,t,r));const s=e.getEnum();return s!==void 0&&(i.enum=s.map(o=>this.scalarOrExplicitNode(o,t,r))),i}static schemaFieldValue(e,t,r,i){return rr(e)||ir(e)?i(t.getValue())??r(t):ci(e)?this.numericValue(t,r,i):r(t)}static numericValue(e,t,r){return this.isPlainScalar(e)?r(e.getValue())??t(e):t(e)}static scalarOrExplicitNode(e,t,r){return this.isPlainScalar(e)?r(e.getValue())??t(e):t(e)}static isPlainScalar(e){return e.getValue()!==void 0&&e.getValue()!==null&&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&&e.getContractsNode()===void 0&&e.getBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static put(e,t,r){r!=null&&(e[t]=r)}}class B{static get(e,t="official"){const{strategy:r}=this.normalizeOptions(t),i=e.getValue(),s=this.handleValue(i);if(s!==void 0&&r==="simple")return s;const o=e.getItems()?.map(T=>B.get(T,r));if(o!==void 0&&r==="simple")return o;const a=e.getName(),l=e.getDescription();if(r==="original"&&a===void 0&&l===void 0){if(s!==void 0)return s;if(o!==void 0)return o}const c={};a!==void 0&&(c[ae]=a),l!==void 0&&(c[le]=l);const d=e.getType();if(r==="official"&&i!==void 0&&d===void 0){const T=this.inferTypeBlueId(i);T!==null&&(c[U]={[N]:T})}else d!==void 0&&(c[U]=B.get(d,r));const p=e.getItemType();p!==void 0&&(c[me]=B.get(p,r));const f=e.getKeyType();f!==void 0&&(c[ye]=B.get(f,r));const I=e.getValueType();I!==void 0&&(c[ge]=B.get(I,r));const v=e.getMergePolicy();v!==void 0&&(c[g.OBJECT_MERGE_POLICY]=v),s!==void 0&&(c[X]=s),o!==void 0&&(c[Te]=o);const E=e.getBlueId();E!==void 0&&(c[N]=E);const L=e.getBlue();L!==void 0&&(c[rt]=B.get(L,r));const $=e.getPreviousBlueId();$!==void 0&&(c[ce]={[N]:$});const W=e.getPosition();W!==void 0&&(c[it]=W);const ee=e.getSchema();ee!==void 0&&(c[g.OBJECT_SCHEMA]=Ei.get(ee,T=>B.get(T,r),T=>B.handleValue(T)));const we=e.getContractsNode();we!==void 0&&(c[g.OBJECT_CONTRACTS]=B.get(we,r));const w=e.getProperties();return w!==void 0&&Object.entries(w).forEach(([T,te])=>{c[T]=B.get(te,r)}),c}static handleValue(e){if(M(e)){if(Y(e)){const t=new fe(Number.MIN_SAFE_INTEGER.toString()),r=new fe(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"?z:M(e)?Y(e)?j:_:typeof e=="boolean"?K:null}static normalizeOptions(e){return typeof e=="string"?{strategy:e}:{strategy:e.strategy??"official"}}}class D{static transform(e,t){const r=t(e.clone()),i=r.getType();i!==void 0&&r.setType(D.transform(i,t));const s=r.getItemType();s!==void 0&&r.setItemType(D.transform(s,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(D.transform(o,t));const a=r.getValueType();a!==void 0&&r.setValueType(D.transform(a,t));const l=r.getSchema();if(l!==void 0){const p=l.clone();for(const[I,v]of p.entries())p.set(I,D.transform(v,t));const f=p.getEnum();f!==void 0&&p.setEnum(f.map(I=>D.transform(I,t))),r.setSchema(p)}const c=r.getItems();if(c!==void 0){const p=c.map(f=>D.transform(f,t));r.setItems(p)}const d=r.getProperties();if(d!==void 0){const p=Object.keys(d).reduce((f,I)=>(f[I]=D.transform(d[I],t),f),{});r.setProperties(p)}return r}}const gt=Symbol.for("zod-schema-annotations");function Pi(){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 or(){const n=Pi();return gt in n||(n[gt]=new WeakMap),n[gt]}function $e(n,e){const t=or(),r=t.get(n)||{};return t.set(n,{...r,...e}),n}const se=n=>or().get(n),ar=n=>e=>{const t=se(e);return $e(e,{...t,blueDescription:n})},lr=n=>{const e=se(n);return u.isNonNullable(e)&&ve.isString(e.blueDescription)?e.blueDescription:null},bi=n=>ar(n)(m.z.string().optional()),Ni=m.z.union([m.z.string(),m.z.boolean()]),cr=n=>e=>{const t=se(e);return $e(e,{...t,blueId:n})},ur=n=>{const e=se(n),t=Ni.safeParse(e?.blueId);return t.success?t.data:null},wi=n=>cr(n??!0)(m.z.string()),dr=n=>e=>{const t=se(e);return $e(e,{...t,blueName:n})},hr=n=>{const e=se(n);return u.isNonNullable(e)&&ve.isString(e.blueName)?e.blueName:null},Si=n=>{const e=m.z.string().optional();return dr(n)(e)},pr=()=>n=>{const e=se(n);return $e(n,{...e,blueNode:!0})},fr=n=>{const e=se(n);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},Dt=n=>!!fr(n),Ci=()=>{const n=m.z.instanceof(h);return pr()(n)},Ri=m.z.object({value:m.z.array(m.z.string()).optional(),defaultValue:m.z.string().optional()}),mr=n=>{const e=se(n),t=Ri.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},Ai=n=>e=>{const t=se(e),r=typeof n=="string"?{value:[n]}:n;return $e(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class Le{static resolveBlueId(e){const t=mr(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const i=t.value?.[0];return u.isNonNullable(i)?i:Le.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}const yr=n=>{const e=String(n._def.typeName);return e==="ZodOptional"||e==="ZodNullable"||e==="ZodReadonly"||e==="ZodBranded"||e==="ZodEffects"||e==="ZodLazy"},Oi=n=>{const e=String(n._def.typeName);return e==="ZodString"||e==="ZodNumber"||e==="ZodBoolean"||e==="ZodBigInt"};class J{static isTypeOf(e,t,r){const i=Le.resolveBlueId(t),s=e.getType()?.getBlueId();if(u.isNullable(i)||u.isNullable(s))return!1;const o=r?.blueIdMapper?.toCurrentBlueId(i)??i,a=r?.blueIdMapper?.toCurrentBlueId(s)??s;if(o===a)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const l=r.typeSchemaResolver.resolveSchema(e);return J.checkSchemaExtension(l,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const i=J.unwrapSchema(e),s=J.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(i,s):!1}static unwrapSchema(e){if(Dt(e))return e;const t=String(e._def.typeName);return t==="ZodEffects"?J.unwrapSchema(e.innerType()):t==="ZodLazy"?J.unwrapSchema(e.schema):yr(e)?J.unwrapSchema(e.unwrap()):e}}const gr=Symbol("blue.subtypeCache");function Mi(n,e){return n[gr]=e,n}function jt(n,e){const t=n.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(ie.includes(r)){const s=ct[r];return new h().setBlueId(r).setName(s)}const i=e.fetchByBlueId(r);if(!i||i.length===0)return;if(i.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return i[0].cloneShallow().setBlueId(r)}return t}function A(n,e,t){const r=xe(n),i=xe(e),s=t[gr],o=`${r}|${i}`,a=s?.get(o);if(a!==void 0)return a;const l=Vi(n,e,t,r,i);return s?.set(o,l),l}function xe(n){const e=n.getReferenceBlueId();return e!==void 0?e:b.calculateBlueIdSync(de(n))}function de(n){if(!Ir(n))return n;const e=n.cloneShallow();e.getReferenceBlueId()!==void 0&&!R.hasBlueIdOnly(e)&&e.setReferenceBlueId(void 0);const t=e.getType();t!==void 0&&e.setType(de(t));const r=e.getItemType();r!==void 0&&e.setItemType(de(r));const i=e.getKeyType();i!==void 0&&e.setKeyType(de(i));const s=e.getValueType();s!==void 0&&e.setValueType(de(s));const o=e.getBlue();o!==void 0&&e.setBlue(de(o));const a=e.getItems();a!==void 0&&e.setItems(a.map(c=>de(c)));const l=e.getProperties();return l!==void 0&&e.setProperties(Object.fromEntries(Object.entries(l).map(([c,d])=>[c,de(d)]))),e}function Ir(n){return n.getReferenceBlueId()!==void 0&&!R.hasBlueIdOnly(n)?!0:[n.getType(),n.getItemType(),n.getKeyType(),n.getValueType(),n.getBlue(),...n.getItems()??[],...Object.values(n.getProperties()??{})].some(t=>t!==void 0&&Ir(t))}function Vi(n,e,t,r,i){if(r===i)return!0;if(Di(e,i)&&vr(n))return!1;if(r&&ie.includes(r)){let l=e;for(;l!==void 0;){if(xe(l)===r)return!0;l=jt(l,t)}return!1}let s=n;const o=n.getBlueId();if(o){const l=t.fetchByBlueId(o);l&&l.length===1&&(s=l[0].cloneShallow().setBlueId(o))}let a=s;for(;a!==void 0;){if(xe(a)===i)return!0;a=jt(a,t)}return!1}function Di(n,e){return ie.includes(e)||Li(n)}function vr(n){const e=n.getType();return n.getName()===void 0&&n.getDescription()===void 0&&n.getReferenceBlueId()===void 0&&e!==void 0&&n.getItemType()===void 0&&n.getKeyType()===void 0&&n.getValueType()===void 0&&n.getValue()===void 0&&n.getItems()===void 0&&n.getProperties()===void 0&&n.getContractsNode()===void 0&&n.getSchema()===void 0&&n.getMergePolicy()===void 0&&n.getPreviousBlueId()===void 0&&n.getPosition()===void 0&&n.getBlue()===void 0&&ie.includes(xe(e))}function Li(n){const e=n.getName();return e!==void 0&&Object.prototype.hasOwnProperty.call(lt,e)&&n.getDescription()===void 0&&n.getType()===void 0&&n.getItemType()===void 0&&n.getKeyType()===void 0&&n.getValueType()===void 0&&n.getValue()===void 0&&n.getItems()===void 0&&n.getProperties()===void 0&&n.getContractsNode()===void 0&&n.getReferenceBlueId()===void 0&&n.getSchema()===void 0&&n.getMergePolicy()===void 0&&n.getPreviousBlueId()===void 0&&n.getPosition()===void 0&&n.getBlue()===void 0}function xi(n,e){return At.some(t=>{const r=new h().setBlueId(t);return A(n,r,e)})}function _i(n,e){const t=new h().setBlueId(z);return A(n,t,e)}function Fi(n,e){const t=new h().setBlueId(j);return A(n,t,e)}function Ui(n,e){const t=new h().setBlueId(_);return A(n,t,e)}function zi(n,e){const t=new h().setBlueId(K);return A(n,t,e)}function Ge(n,e){const t=new h().setBlueId(ot);return A(n,t,e)}function He(n,e){const t=new h().setBlueId(at);return A(n,t,e)}function ji(n,e){return nt.some(t=>{const r=new h().setName(t);return A(n,r,e)})}function $i(n,e){for(const t of nt){const r=new h().setName(t);if(A(n,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${n.getName()||"unknown"}".`)}class Tr{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=Le.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),i=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(i))return!1;if(r===i)return!0;if(u.isNonNullable(this.nodeProvider))try{const s=new h().setBlueId(r),o=new h().setBlueId(i);if(A(s,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=Le.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,i]of this.blueIdMap)if(i===e||i._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)?b.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}class ue{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function Lt(n){return new class extends ue{fetchByBlueId(e){return n(e)}}}class Ce extends ue{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 It=Be.types.float.options,ki={...It,construct:n=>{const e=n.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new V(e);if(It.construct)return It.construct(n)}},qi=new Be.Type("tag:yaml.org,2002:float",ki),vt=Be.types.int.options,Ki={...vt,construct:n=>{let e=n;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new S(e);if(vt.construct)return vt.construct(n)}},Gi=new Be.Type("tag:yaml.org,2002:int",Ki),Br=Be.CORE_SCHEMA.extend({implicit:[qi,Gi]}),he=n=>{const e=Be.load(n,{schema:Br});return e===void 0?void 0:e},Er=n=>Be.dump(n,{schema:Br,replacer:(e,t)=>{if(M(t)){if(Y(t)){const r=new fe(Number.MIN_SAFE_INTEGER.toString()),i=new fe(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(i))return t.toString()}return t.toNumber()}return t}}),Pr=`- type:
|
|
2
2
|
blueId: 27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo
|
|
3
3
|
mappings:
|
|
4
4
|
Text: GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC
|
|
@@ -36,15 +36,15 @@ type:
|
|
|
36
36
|
description: This transformation infers type details for Text, Integer, Number and Boolean.`,Wi=`name: Replace Inline Types with BlueIds
|
|
37
37
|
type:
|
|
38
38
|
blueId: Ct1SGRGw1i47qjzm1ruiUdSZofeV6WevPTGuieVvbRS4
|
|
39
|
-
description: This transformation replaces`,Zi=[Pr,Hi,Yi,Wi];class Ji extends ue{blueIdToNodesMap=new Map;constructor(){super(),this.load()}fetchByBlueId(e){return this.blueIdToNodesMap.get(e)||[]}load(){for(const e of Zi){const t=he(e);if(t===void 0){console.error(`This content file is not valid YAML: ${e}`);continue}if(Array.isArray(t)){const r=t.map(s=>g.deserialize(s)),i=b.calculateBlueIdSync(r);this.blueIdToNodesMap.set(i,r)}else{const r=g.deserialize(t),i=b.calculateBlueIdSync(r);this.blueIdToNodesMap.set(i,[r])}}}}class Ae extends ue{static INSTANCE=new Ae;nodeProvider;constructor(){super(),this.nodeProvider=new Ji}fetchByBlueId(e){return this.nodeProvider.fetchByBlueId(e)}}class $t extends ue{constructor(e){super(),this.delegate=e}fetchByBlueId(e){let t;try{t=G.requireBlueIdOrCyclicMember(e,"provider.fetchByBlueId")}catch{return this.delegate.fetchByBlueId(e)}const r=this.delegate.fetchByBlueId(e);if(r===null||r.length===0||t.includes("#"))return r;const i=r.length===1?b.calculateBlueIdSync(this.contentWithoutRootIdentity(r[0])):b.calculateBlueIdSync(r.map(s=>this.contentWithoutRootIdentity(s)));if(i!==t){if(this.verifyCyclicSetContent(t,r))return r;throw new Error(`Provider returned content with BlueId ${i} for requested BlueId ${t}.`)}return r}contentWithoutRootIdentity(e){const t=e.clone();return t.getReferenceBlueId()!==void 0&&!this.isReferenceOnly(t)&&t.setReferenceBlueId(void 0),t}isReferenceOnly(e){return e.getReferenceBlueId()!==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.getValue()===void 0&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0&&e.getContractsNode()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}verifyCyclicSetContent(e,t){if(t.length===0)return!1;const r=t.map(s=>{const o=s.clone();return this.rewriteCyclicMemberReferences(o,e),o});if(!r.some(s=>this.hasThisReference(s)))return!1;try{return b.calculateBlueIdAllowingCyclicPlaceholdersSync(r)===e}catch{return!1}}rewriteCyclicMemberReferences(e,t){const r=e.getReferenceBlueId();r?.startsWith(`${t}#`)&&e.setReferenceBlueId(`this#${r.slice(t.length+1)}`),this.childrenOf(e).forEach(i=>this.rewriteCyclicMemberReferences(i,t))}hasThisReference(e){return e.getReferenceBlueId()?.startsWith("this#")?!0:this.childrenOf(e).some(r=>this.hasThisReference(r))}childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),e.getContractsNode(),...e.getSchema()?.entries().map(([,t])=>t)??[],...e.getSchema()?.getEnum()??[],...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}const br=Symbol.for("blue.repositoryBasedNodeProvider");class oe{static wrap(e){if(this.isAlreadyWrapped(e))return e;if(this.isUnverified(e))return new Ce([Ae.INSTANCE,e]);const t=[Ae.INSTANCE,new $t(e)];return new Ce(t)}static unverified(e){return new Tt(e)}static isUnverified(e){return e instanceof Tt||e[br]===!0?!0:e instanceof Ce&&e.getNodeProviders().some(t=>this.isUnverified(t))}static isAlreadyWrapped(e){return e instanceof Ce?e.getNodeProviders().some(t=>t===Ae.INSTANCE||t instanceof $t||t instanceof Tt):!1}}class Tt extends ue{constructor(e){super(),this.delegate=e}fetchByBlueId(e){return this.delegate.fetchByBlueId(e)}}class dt{}class Oe{static convert(e){const t=new et;return Oe.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const i=e.getProperties(),s=e.getItems(),o=i!==void 0&&Object.keys(i).length>0,a=s!==void 0&&s.length>0;if(!o&&!a){r.addPath(t===""?"/":t);return}if(i)for(const[l,c]of Object.entries(i)){const d=`${t}/${l}`;Oe.traverseNode(c,d,r)}if(s)for(let l=0;l<s.length;l++){const c=`${t}/${l}`;Oe.traverseNode(s[l],c,r)}}}function kt(n,e){const t=n.split(e),r=[...t].reverse().findIndex(s=>s!==""),i=r===-1?0:t.length-r;return t.slice(0,i)}class ke extends dt{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=kt(e,"/"),i=kt(t,"/");if(i.length>r.length)return!1;for(let s=1;s<i.length;s++)if(r[s]!=="*"&&r[s]!==i[s])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 et().setMaxDepth(e);for(let r=1;r<=e;r++){const i="/"+Array(r).fill("*").join("/");t.addPath(i)}return t.build()}static withSinglePath(e){return new et().addPath(e).build()}static fromNode(e){return Oe.convert(e)}}class et{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 ke(this.allowedPaths,this.maxDepth)}}class re extends dt{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class _e extends dt{limits;constructor(e){super(),this.limits=e}shouldExtendPathSegment(e,t){return this.limits.every(r=>r.shouldExtendPathSegment(e,t))}shouldMergePathSegment(e,t){return this.limits.every(r=>r.shouldMergePathSegment(e,t))}enterPathSegment(e,t){this.limits.forEach(r=>{r.enterPathSegment(e,t)})}exitPathSegment(){this.limits.forEach(e=>{e.exitPathSegment()})}static of(...e){return new _e(e)}}const F=new re;class Q extends h{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 h().setReferenceBlueId(this.sourceSemanticBlueId);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return new Pt().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 Pt().minimizeResolvedForHash(this);return b.calculateBlueIdSync(t)}clone(){const e=super.clone();return new Q(e,this.getMetadata())}cloneShallow(){const e=super.cloneShallow();return new Q(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(!G.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()).setContractsNode(e.getContractsNode()).setBlueId(e.getBlueId()).setSchema(e.getSchema()).setMergePolicy(e.getMergePolicy()).setPreviousBlueId(e.getPreviousBlueId()).setPosition(e.getPosition()).setBlue(e.getBlue()).setInlineValue(e.isInlineValue());const t=e.getValue();t!==void 0&&this.setValue(t)}}class Xi{blue;constructor(e){this.blue=e}matchesType(e,t,r=F,i={}){if(this.isTypeOnlyMatcher(t)&&this.targetTypeReferenceHasNoDefinition(t)&&this.matchesUnresolvedExactTypeOnly(e,t))return!0;try{const s=ke.fromNode(t),o=i.limits===void 0?r:_e.of(r,i.limits),a=_e.of(o,s),l=this.extendAndResolve(e,a),c=this.blue.resolve(t,a),d=this.expandSchemaOwnedTypeReferences(t);return this.recursiveValueComparison(l,c,d,a,{},this.normalizeMatcherPointer(i.pointer),i.memo)?this.isTypeOnlyMatcher(t)?!0:this.verifyMatch(l,t,a)||t.getType()===void 0:!1}catch{return this.matchesUnresolvedExactTypeOnly(e,t)}}extendAndResolve(e,t){const r=e.clone(),i=r.clone();this.blue.extend(i,t);const s=this.blue.resolve(i,t);return this.restoreMissingStructure(s,r),s}restoreMissingStructure(e,t){const r=t.getItems(),i=e.getItems();if(r&&r.length>0)if(!i||i.length===0)e.setItems(r.map(l=>l.clone()));else for(let l=0;l<Math.min(i.length,r.length);l++)this.restoreMissingStructure(i[l],r[l]);const s=t.getProperties();if(s){let l=e.getProperties();l||(l={},e.setProperties(l));for(const[c,d]of Object.entries(s)){const p=l[c];p===void 0?l[c]=d.clone():this.restoreMissingStructure(p,d)}}const o=t.getBlueId();e.getBlueId()===void 0&&o!==void 0&&e.setBlueId(o);const a=t.getValue();e.getValue()===void 0&&a!==void 0&&e.setValue(a)}verifyMatch(e,t,r){const i=t.getType();if(this.matchesImplicitStructure(e,i))return!0;const s=e.clone().setType(t.clone());try{this.blue.resolve(s,r)}catch{return!1}return!0}recursiveValueComparison(e,t,r=t,i=F,s={},o,a){const l=this.expectedTypeBlueIdForMemo(t,r);if(a&&o&&l){const c=a.get(o,l);if(c!==void 0)return c;const d=this.recursiveValueComparisonUncached(e,t,r,i,s,o,a);return a.set(o,l,d),d}return this.recursiveValueComparisonUncached(e,t,r,i,s,o,a)}recursiveValueComparisonUncached(e,t,r=t,i=F,s={},o,a){const l=t.getType(),c=this.matchesImplicitStructure(e,l)||this.matchesImplicitCoreCollectionType(e,t);if(this.requiresSemanticPresence(t)&&!this.isRootMatcherPointer(o)&&this.isMetadataOnlyNode(e)||!this.matchesSchemaCardinality(e,t)||e.getType()===void 0&&this.isCoreCollectionType(t)&&!c)return!1;if(l&&!c){const w=e.getType();if(w){if(!A(w,l,this.blue.getNodeProvider())&&!this.matchesExactTypeReference(w,l))return!1}else if(!this.matchesImplicitPrimitiveType(e,l))return!1}const d=t.getBlueId();if(!c&&d!==void 0)if(this.isExplicitBlueIdMatcher(r)){if(s.bareBlueIdMatcherMode==="type-reference"){if(!this.matchesBareBlueIdTypeReference(e,t,d))return!1}else if(!this.matchesBareBlueIdIdentity(e,d))return!1}else{const w=e.getBlueId(),T=e.getType();if(T===void 0&&w!==void 0&&w!==d||T&&!A(T,t,this.blue.getNodeProvider())&&!this.matchesExactTypeReference(T,t))return!1}const p=e.getBlueId();if(!c&&d===void 0&&p!==void 0&&e.getType()===void 0&&t.getItems()===void 0&&this.hasMatcherShape(t)&&!this.matchesCalculatedBlueId(t,p))return!1;const f=t.getValue();if(f!==void 0){const w=e.getValue();if(w===void 0)return!1;if(D(w)&&D(f)){if(!w.eq(f))return!1}else if(w!==f)return!1}const I=t.getItems(),v=r.getItems();if(I!==void 0){const w=e.getItems()??[];for(let T=0;T<I.length;T++)if(T<w.length){if(!this.recursiveValueComparison(w[T],I[T],v?.[T]??I[T],i,{},this.childMatcherPointer(o,String(T)),a))return!1}else if(this.requiresSemanticPresence(I[T])||this.hasValueInNestedStructure(I[T]))return!1}const E=t.getItemType(),L=r.getItemType();if(E!==void 0){const w=e.getItems()??[];for(let T=0;T<w.length;T++){const te=w[T];if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(te,E,L??E,i,"type-reference"),E,L??E,i,{bareBlueIdMatcherMode:"type-reference"},this.childMatcherPointer(o,String(T)),a))return!1}}const $=t.getProperties(),W=r.getProperties();if($!==void 0){const w=e.getProperties()??{};for(const[T,te]of Object.entries($))if(T in w){if(!this.recursiveValueComparison(w[T],te,W?.[T]??te,i,{},this.childMatcherPointer(o,T),a))return!1}else if(this.requiresSemanticPresence(te)||this.hasValueInNestedStructure(te))return!1}const ee=t.getValueType(),we=r.getValueType();if(ee!==void 0){const w=Object.entries(e.getProperties()??{});for(const[T,te]of w)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(te,ee,we??ee,i,"type-reference"),ee,we??ee,i,{bareBlueIdMatcherMode:"type-reference"},this.childMatcherPointer(o,T),a))return!1}return!0}expectedTypeBlueIdForMemo(e,t){return this.blueIdOrReference(t)??this.blueIdOrReference(e)??this.blueIdOrReference(t.getType())??this.blueIdOrReference(e.getType())}blueIdOrReference(e){return e?.getBlueId()??e?.getReferenceBlueId()}normalizeMatcherPointer(e){if(e===void 0)return;const t=e.trim();return t.length===0||t==="/"?"/":t.startsWith("/")?t:`/${t}`}childMatcherPointer(e,t){if(e===void 0)return;const r=t.replace(/~/g,"~0").replace(/\//g,"~1");return e==="/"?`/${r}`:`${e}/${r}`}resolveUntypedNodeAgainstMatcherType(e,t,r,i,s="identity"){return e.getType()!==void 0||e.getBlueId()!==void 0||s==="identity"&&this.isExplicitBlueIdMatcher(r)?e:this.resolveAgainstTargetType(e,t,i)??e}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const i of t)if(this.hasValueInNestedStructure(i))return!0}const r=e.getProperties();if(r!==void 0){for(const i of Object.values(r))if(this.hasValueInNestedStructure(i))return!0}return!1}requiresSemanticPresence(e){return e.getSchema()?.get("required")?.getValue()===!0}matchesSchemaCardinality(e,t){const r=t.getSchema();if(!r)return!0;const i=this.schemaInteger(r,"minItems");if(i!==void 0&&(e.getItems()?.length??0)<i)return!1;const s=this.schemaInteger(r,"maxItems");if(s!==void 0&&(e.getItems()?.length??0)>s)return!1;const o=Object.keys(e.getProperties()??{}).length,a=this.schemaInteger(r,"minFields");if(a!==void 0&&o<a)return!1;const l=this.schemaInteger(r,"maxFields");return!(l!==void 0&&o>l)}schemaInteger(e,t){const r=e.get(t)?.getValue();if(typeof r=="number"&&Number.isInteger(r))return r;if(Y(r))return Number(r.toString())}isRootMatcherPointer(e){return e===void 0||e==="/"}isMetadataOnlyNode(e){return e.getValue()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0&&e.getBlueId()===void 0&&e.getReferenceBlueId()===void 0&&this.hasMetadata(e)}hasMetadata(e){return 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.getSchema()!==void 0||e.getMergePolicy()!==void 0||e.getBlue()!==void 0}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}isTypeOnlyMatcher(e){return e.getType()!==void 0&&e.getBlueId()===void 0&&e.getReferenceBlueId()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getProperties()===void 0&&e.getName()===void 0&&e.getDescription()===void 0}matchesUnresolvedExactTypeOnly(e,t){if(!this.isTypeOnlyMatcher(t))return!1;const r=e.getType(),i=t.getType();return r!==void 0&&i!==void 0&&this.matchesExactTypeReference(r,i)}targetTypeReferenceHasNoDefinition(e){const t=this.blueIdOrReference(e.getType());if(t===void 0)return!1;const r=this.blue.getNodeProvider().fetchByBlueId(t);return r==null||r.length===0}matchesImplicitPrimitiveType(e,t){const r=e.getValue();switch(this.blueIdOrReference(t)??this.primitiveAliasBlueId(t.getValue())){case z:return typeof r=="string";case j:return typeof r=="number"&&Number.isInteger(r)&&Number.isSafeInteger(r)||Y(r);case _:return typeof r=="number"||D(r);case K:return typeof r=="boolean";default:return!1}}primitiveAliasBlueId(e){switch(e){case"Text":return z;case"Integer":return j;case"Double":return _;case"Boolean":return K;default:return}}matchesCalculatedBlueId(e,t){if(e instanceof Q&&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 i=e.getType();return i?A(i,t,this.blue.getNodeProvider()):e.getBlueId()!==void 0?this.matchesBareBlueIdIdentity(e,r):!1}matchesExactTypeReference(e,t){const r=this.blueIdOrReference(e),i=this.blueIdOrReference(t);return r!==void 0&&i!==void 0&&r===i}toPlainBlueNode(e){const t=new h(e.getName());t.setDescription(e.getDescription()).setReferenceBlueId(e.getReferenceBlueId()).setInlineValue(e.isInlineValue());const r=e.getValue();r!==void 0&&t.setValue(r);const i=e.getType();i!==void 0&&t.setType(this.toPlainBlueNode(i));const s=e.getItemType();s!==void 0&&t.setItemType(this.toPlainBlueNode(s));const o=e.getKeyType();o!==void 0&&t.setKeyType(this.toPlainBlueNode(o));const a=e.getValueType();a!==void 0&&t.setValueType(this.toPlainBlueNode(a));const l=e.getItems();l!==void 0&&t.setItems(l.map(p=>this.toPlainBlueNode(p)));const c=e.getProperties();c!==void 0&&t.setProperties(Object.fromEntries(Object.entries(c).map(([p,f])=>[p,this.toPlainBlueNode(f)])));const d=e.getBlue();return d!==void 0&&t.setBlue(this.toPlainBlueNode(d)),t}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:Ge(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):He(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}matchesImplicitCoreCollectionType(e,t){return e.getType()!==void 0?!1:Ge(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):He(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isCoreCollectionType(e){return Ge(e,this.blue.getNodeProvider())||He(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.getName()===void 0&&e.getDescription()===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&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}isExplicitBlueIdMatcher(e){return this.isBareBlueIdReference(e)}resolveAgainstTargetType(e,t,r){try{const i=e.clone(),s=i.clone().setType(t.clone()),o=this.blue.resolve(s,r);return this.restoreMissingStructure(o,i),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()),i=e.getType();i&&e.setType(this.expandReferencedTypeNode(i,r));const s=e.getItemType();s&&e.setItemType(this.expandReferencedTypeNode(s,r));const o=e.getKeyType();o&&e.setKeyType(this.expandReferencedTypeNode(o,r));const a=e.getValueType();a&&e.setValueType(this.expandReferencedTypeNode(a,r));const l=e.getItems();l&&e.setItems(l.map(d=>this.expandSchemaTypeReferences(d,r)));const c=e.getProperties();return c&&e.setProperties(Object.fromEntries(Object.entries(c).map(([d,p])=>[d,this.expandSchemaTypeReferences(p,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 i=this.blue.getNodeProvider().fetchByBlueId(r);return!i||i.length!==1?e.clone():this.expandSchemaTypeReferences(i[0].clone(),t)}withVisitedBlueId(e,t){if(!t||e.has(t))return e;const r=new Set(e);return r.add(t),r}}class x{static ZERO_BLUE_ID="0".repeat(44);static THIS_INDEX_REFERENCE_PATTERN=/^this#(0|[1-9]\d*)$/;prepareDocument;calculateBlueId;constructor(e={}){this.prepareDocument=e.prepareDocument??(t=>t),this.calculateBlueId=e.calculateBlueId??b.calculateBlueIdAllowingCyclicPlaceholdersSync}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((a,l)=>{const c=this.prepareDocument(this.replaceIndexedThisReferences(a,()=>x.ZERO_BLUE_ID));return{originalIndex:l,preliminaryBlueId:this.calculateBlueId(c),node:a}});this.rejectDuplicatePreliminaryInputs(t);const r=[...t].sort(this.comparePreliminaryDocuments),i=[];r.forEach(({originalIndex:a},l)=>{i[a]=l});const s=r.map(({node:a})=>this.prepareDocument(this.replaceIndexedThisReferences(a,l=>`this#${i[l]}`))),o=this.calculateBlueId(s);return{blueId:o,nodes:s,documentBlueIds:e.map((a,l)=>`${o}#${i[l]}`),originalToSortedIndexes:i}}comparePreliminaryDocuments(e,t){return e.preliminaryBlueId<t.preliminaryBlueId?-1:e.preliminaryBlueId>t.preliminaryBlueId?1:e.originalIndex-t.originalIndex}rejectDuplicatePreliminaryInputs(e){const t=new Map;e.forEach(({preliminaryBlueId:r,originalIndex:i})=>{const s=t.get(r);if(s!==void 0)throw new Error(`Duplicate preliminary cyclic BlueId input for members ${s} and ${i}.`);t.set(r,i)})}validateCyclicSet(e){if(e.length===0)throw new Error("Cyclic document set cannot be empty.");let t=!1;if(this.visitReferences(e,(r,i)=>{if((i==="this"||i.startsWith("this#"))&&(t=!0),i==="this")throw new Error("Direct cyclic document sets must use indexed references such as 'this#0'; unindexed 'this' is not supported.");if(i.startsWith("this#")&&!x.THIS_INDEX_REFERENCE_PATTERN.test(i))throw new Error(`Malformed direct cyclic reference '${i}'. Expected 'this#<non-negative-integer>'.`);const s=this.readIndexedThisReference(i);if(s!==void 0&&s>=e.length)throw new Error(`Direct cyclic reference '${i}' points outside the ${e.length}-document set.`)}),!t)throw new Error("Circular BlueId calculation requires at least one internal this reference.")}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 i=this.readIndexedThisReference(r);i!==void 0&&e.setReferenceBlueId(t(i))}this.childrenOf(e).forEach(i=>this.rewriteIndexedThisReferences(i,t))}static nodeHasThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,i)=>{(i==="this"||i.startsWith("this#"))&&(t=!0)}),t}static nodeHasIndexedThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,i)=>{x.THIS_INDEX_REFERENCE_PATTERN.test(i)&&(t=!0)}),t}visitReferences(e,t){e.forEach(r=>x.visitNodeReferences(r,t))}static visitNodeReferences(e,t){const r=e.getReferenceBlueId();r!==void 0&&t(e,r),this.childrenOf(e).forEach(i=>this.visitNodeReferences(i,t))}readIndexedThisReference(e){const t=e.match(x.THIS_INDEX_REFERENCE_PATTERN);if(t!==null)return Number(t[1])}childrenOf(e){return x.childrenOf(e)}static childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),e.getContractsNode(),...e.getSchema()?.entries().map(([,t])=>t)??[],...e.getSchema()?.getEnum()??[],...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}class Nr{resolveWithoutLimits(e){return this.resolve(e,F)}}class xt{nodeProvider;strategy;constructor(e,t){this.nodeProvider=oe.wrap(e),this.strategy=t||"THROW_EXCEPTION"}extend(e,t){this.extendNode(e,t,"")}extendNode(e,t,r,i=!1){if(!i){if(!t.shouldExtendPathSegment(r,e))return;t.enterPathSegment(r,e)}try{const s=e.getBlueId();if(s&&C.hasBlueIdOnly(e)&&!ie.includes(s)){const f=this.fetchNode(e);if(f&&f.length>0){const I=this.shouldPreserveReferenceBlueId(r,i);if(f.length===1){const v=f[0];this.mergeNodes(e,v,I)}else{const v=f.map(L=>L.clone()),E=new h().setItems(v);this.mergeNodes(e,E,I)}}}const o=e.getType();o&&this.extendNode(o,t,"type",!0);const a=e.getItemType();a&&this.extendNode(a,t,"itemType",!0);const l=e.getKeyType();l&&this.extendNode(l,t,"keyType",!0);const c=e.getValueType();c&&this.extendNode(c,t,"valueType",!0);const d=e.getProperties();d&&Object.entries(d).forEach(([f,I])=>{this.extendNode(I,t,f,!1)});const p=e.getItems();if(p&&p.length>0)for(let f=0;f<p.length;f++)this.extendNode(p[f],t,String(f),!1)}finally{i||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 i=t.getValue();u.isNonNullable(i)&&e.setValue(i),e.setItems(t.getItems()?.map(o=>o.clone()));const s=t.getProperties();e.setProperties(s===void 0?void 0:Object.fromEntries(Object.entries(s).map(([o,a])=>[o,a.clone()]))),e.setBlue(t.getBlue()?.clone())}}class pe extends Nr{mergingProcessor;nodeProvider;nodeProviderIsUnverified;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProviderIsUnverified=oe.isUnverified(t),this.nodeProvider=oe.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 i=e;const s=t.getType();if(u.isNonNullable(s)){const o=this.resolveTypeNode(s,r),a=this.getTypeOverlay(s,o,r);i=this.mergeObject(i,a,r);const l=t.cloneShallow().setType(o.clone());return this.mergeObject(i,l,r)}return this.mergeObject(i,t,r)}mergeObject(e,t,r){const i=e.cloneShallow(),s=this.mergingProcessor.preserveSource?.(i,t,r.nodeProvider);if(s!==void 0)return this.mergingProcessor.postProcess?this.mergingProcessor.postProcess(s,t,r.nodeProvider):s;let o=this.mergingProcessor.process(i,t,r.nodeProvider);if(this.mergingProcessor.shouldPreserveSource?.(t,r.nodeProvider))return this.mergingProcessor.postProcess&&(o=this.mergingProcessor.postProcess(o,t,r.nodeProvider)),o;const a=t.getItems();u.isNonNullable(a)&&(o=this.mergeChildren(o,t,r));const l=t.getProperties();return u.isNonNullable(l)&&(o=this.mergeProperties(o,t,l,r)),u.isNonNullable(t.getBlueId())&&(o=o.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(o=this.mergingProcessor.postProcess(o,t,r.nodeProvider)),o}mergeChildren(e,t,r){const i=t.getItems()??[];for(let s=0;s<i.length;s+=1)if(s!==0&&P.hasPreviousProperty(i[s]))throw new Error("$previous list control is allowed only as the first item.");return P.hasListControlItems(i)?this.mergeChildrenWithListControls(e,t,r):this.mergeChildrenWithoutListControls(e,i,r)}mergeChildrenWithoutListControls(e,t,r){const i=e.getItems();if(u.isNullable(i)){const o=[];for(let a=0;a<t.length;a++){const l=t[a];if(r.limits.shouldMergePathSegment(String(a),l)){this.enterPathSegment(r,String(a),l);try{const c=this.materializeForCurrentContextWithItemType(l,r,e.getItemType());o.push(c)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(o)}if(t.length<i.length)throw new Error(`Subtype of element must not have more items (${i.length}) than the element itself (${t.length}).`);const s=[...i];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>=s.length){const d=this.materializeForCurrentContextWithItemType(t[o],r,e.getItemType());s.push(d);continue}const a=r.limits instanceof re?this.applyItemType(t[o],e.getItemType()):this.materializeForCurrentContextWithItemType(t[o],r,e.getItemType()),l=this.calculateNodeBlueId(a,r),c=this.calculateNodeBlueId(s[o],r);if(l!==c)throw new Error(`Mismatched items at index ${o}: source item has blueId '${l}', but target item has blueId '${c}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(s)}mergeChildrenWithListControls(e,t,r){const i=t.getItems()??[],s=e.getItems()!==void 0,o=e.getItems()??[],a=P.getMergePolicy(t,e),l=[...o];let c=0,d=!1;const p=i[0];if(p!==void 0&&P.hasPreviousProperty(p)){if(P.getPreviousBlueId(p)===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");d=!0,c=1}const f=d&&o.length===0&&!(r.limits instanceof re),I=new Set;for(;c<i.length;c++){const v=i[c];if(P.hasPreviousProperty(v))throw new Error("$previous list control is allowed only as the first item.");const E=P.readPosition(v);if(E!==void 0){if(a==="append-only")throw new Error("$pos is not allowed in append-only lists.");if(!s){if(E!==l.length)throw new Error("$pos is out of range for a list without inherited items.");const W=P.withoutPosition(v);if(!P.hasPayloadAfterRemovingPosition(v))throw new Error("$pos list control must include an item payload.");this.enterPathSegment(r,String(E),W);try{l.push(this.materializeForCurrentContextWithItemType(W,r,e.getItemType()))}finally{this.exitPathSegment(r)}continue}if(E>=o.length)throw new Error(`$pos ${E} is out of range for inherited list length ${o.length}.`);if(I.has(E))throw new Error(`Duplicate $pos list overlay for index ${E}.`);I.add(E);const $=P.withoutPosition(v);if(!P.hasPayloadAfterRemovingPosition(v))throw new Error("$pos list control must include an item payload.");if(!r.limits.shouldMergePathSegment(String(E),$))continue;this.enterPathSegment(r,String(E),$);try{const W=l[E],ee=W?.getType()??e.getItemType();l[E]=W===void 0||P.isReplacementPayload($)?this.materializeForCurrentContextWithItemType($,r,ee):this.mergeWithContext(W,$,r)}finally{this.exitPathSegment(r)}continue}const L=l.length;if(!(!f&&!r.limits.shouldMergePathSegment(String(L),v))){if(f){l.push(this.materializeWithoutLimits(this.applyItemType(v,e.getItemType()),r));continue}this.enterPathSegment(r,String(L),v);try{const $=this.materializeForCurrentContextWithItemType(v,r,e.getItemType());l.push($)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}materializeWithoutLimits(e,t){return new pe(this.mergingProcessor,t.nodeProvider).resolve(e,F)}mergeProperties(e,t,r,i){const s=e.getProperties()??{};let o=s,a=!1;for(const[l,c]of Object.entries(r))if(i.limits.shouldMergePathSegment(l,c)){this.enterPathSegment(i,l,c);try{const d=o[l],p=this.getPathLimitedListControlTarget(d,t,l,c,i),f=p??d,v=this.shouldMergePropertyWithoutPreResolve(f,c,i)?this.mergeExistingProperty(f,c,i):(()=>{const L=this.materializeForCurrentContext(c,i);return f===void 0?L:this.mergeObject(f,L,i)})(),E=p===void 0?v:this.projectListNodeToCurrentLimits(v,i);E!==d&&(a||(o={...s},a=!0),o[l]=E)}finally{this.exitPathSegment(i)}}return a?e.cloneShallow().setProperties(o):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof re?u.isNonNullable(e)&&P.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 h,s=this.mergeWithContext(r,e,t).cloneShallow().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new Q(s,{completeness:t.limits instanceof re?"full":"path-limited"})}createResolutionContext(e){const t=new Map,r=new Map,i=Mi(this.createResolutionNodeProvider(this.nodeProvider,t),r);return{limits:e,nodeProvider:i,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 i=this.createResolvedTypeCacheKey(r,t),s=t.resolvedTypeCache.get(i);if(u.isNonNullable(s)&&!t.resolvingTypeKeys.has(i))return s;if(t.resolvingTypeBlueIds.has(r))return s??this.createCyclicTypeReference(r,t);const o=this.createCyclicTypeReference(r,t);t.resolvedTypeCache.set(i,o),t.resolvingTypeKeys.add(i),t.resolvingTypeBlueIds.add(r);try{const a=this.resolveAndExtendTypeNode(e,t);return a.setReferenceBlueId(r),t.resolvedTypeCache.set(i,a),a}catch(a){throw t.resolvedTypeCache.delete(i),a}finally{t.resolvingTypeKeys.delete(i),t.resolvingTypeBlueIds.delete(r)}}return this.resolveAndExtendTypeNode(e,t)}createCyclicTypeReference(e,t){return new Q(new h().setReferenceBlueId(e),{completeness:t.limits instanceof re?"full":"path-limited"})}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new xt(t.nodeProvider).extend(r,ke.withSinglePath("/")),this.resolveWithContext(r,t)}getTypeOverlay(e,t,r){const i=e.getBlueId();if(u.isNullable(i))return this.createTypeOverlay(t);const s=this.createResolvedTypeCacheKey(i,r),o=r.typeOverlayCache.get(s);if(u.isNonNullable(o))return o;const a=this.createTypeOverlay(t);return r.resolvingTypeBlueIds.has(i)||r.typeOverlayCache.set(s,a),a}createTypeOverlay(e){return e.cloneShallow().setType(void 0).setBlueId(void 0)}createResolvedTypeCacheKey(e,t){return t.limits instanceof re?e:`${e}|${this.getCurrentPointer(t)}`}materializeForCurrentContext(e,t){return e.isResolved()&&this.canReuseResolvedSubtree(t)?e.clone():this.resolveWithContext(e,t)}materializeForCurrentContextWithItemType(e,t,r){return this.materializeForCurrentContext(this.applyItemType(e,r),t)}applyItemType(e,t){return e.getType()!==void 0||e.getReferenceBlueId()!==void 0||t===void 0?e:e.clone().setType(this.itemTypeReference(t))}itemTypeReference(e){const t=e.getReferenceBlueId();return t===void 0?e.clone():new h().setReferenceBlueId(t)}canReuseResolvedSubtree(e){return e.limits instanceof re}calculateNodeBlueId(e,t){const r=t.nodeHashCache.get(e);if(u.isNonNullable(r))return r;const i=k.calculateHashMinimalBlueId(e);return t.nodeHashCache.set(e,i),i}getPathLimitedListControlTarget(e,t,r,i,s){if(!(e===void 0||s.limits instanceof re||!P.hasListControlItems(i.getItems())))return this.resolveFullInheritedProperty(t,r,s)}resolveFullInheritedProperty(e,t,r){const i=e.getType();if(i===void 0)return;const s=i.getBlueId();if(u.isNonNullable(s)){const l=r.nodeProvider.fetchByBlueId(s)?.[0];return l===void 0?void 0:new pe(this.mergingProcessor,r.nodeProvider).resolve(l,F).getProperties()?.[t]?.clone()}return new pe(this.mergingProcessor,r.nodeProvider).resolve(i,F).getProperties()?.[t]?.clone()}projectListNodeToCurrentLimits(e,t){const r=e.getItems();return r===void 0?e:e.cloneShallow().setItems(r.filter((i,s)=>t.limits.shouldMergePathSegment(String(s),i)))}createResolutionNodeProvider(e,t){const r=new class extends ue{fetchByBlueId(i){if(t.has(i))return t.get(i)??null;const s=e.fetchByBlueId(i);return t.set(i,s),s}};return this.nodeProviderIsUnverified?oe.unverified(r):r}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 wr{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((i,s)=>s.process(i,t,r),e)}preserveSource(e,t,r){for(const i of this.mergingProcessors){const s=i.preserveSource?.(e,t,r);if(s!==void 0)return s}}shouldPreserveSource(e,t){return this.mergingProcessors.some(r=>r.shouldPreserveSource?.(e,t))}postProcess(e,t,r){return this.mergingProcessors.reduce((i,s)=>s.postProcess?s.postProcess(i,t,r):i,e)}}class Sr{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const i=e.getValue();if(u.isNullable(i))return e.cloneShallow().setValue(r);if(!Qi(r,i)){if(es(e))return e.cloneShallow().setValue(r);throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${i}`)}}return e}}const Qi=(n,e)=>Y(n)&&Y(e)||Je(n)&&Je(e)?n.eq(e):n===e,es=n=>u.isNonNullable(n.getType())||u.isNonNullable(n.getItemType())||u.isNonNullable(n.getKeyType())||u.isNonNullable(n.getValueType())||u.isNonNullable(n.getSchema())||u.isNonNullable(n.getDescription());class Cr{process(e,t,r){const i=e.getType(),s=t.getType();let o=e;if(i===void 0){if(s!==void 0&&t.getValue()!==void 0&&vr(s)){const a=B.get(s);throw new Error(`Anonymous core type alias '${JSON.stringify(a)}' is not interchangeable with its registry core type.`)}o=e.cloneShallow().setType(s)}else if(s!==void 0){if(!A(s,i,r)){const l=B.get(s),c=B.get(i);throw new Error(`The source type '${JSON.stringify(l)}' is not a subtype of the target type '${JSON.stringify(c)}'.`)}o=e.cloneShallow().setType(s)}return o}}class Rr{process(e,t,r){let i=this.processMergePolicy(e,t);const s=t.getItemType(),o=t.getType();if(s!==void 0&&o!==void 0&&!Ge(o,r))throw new Error("Source node with itemType must have a List type");const a=i.getItemType();if(a===void 0)s!==void 0&&(i=i.cloneShallow().setItemType(s));else if(s!==void 0){if(!A(s,a,r)){const p=B.get(s),f=B.get(a);throw new Error(`The source item type '${JSON.stringify(p)}' is not a subtype of the target item type '${JSON.stringify(f)}'.`)}i=i.cloneShallow().setItemType(s)}const l=i.getItemType(),c=t.getItems();if(l!==void 0&&c!==void 0)for(const d of c){const p=d.getType();if(p!==void 0&&!A(p,l,r)){const f=B.get(p),I=B.get(l);throw new Error(`Item of type '${JSON.stringify(f)}' is not a subtype of the list's item type '${JSON.stringify(I)}'.`)}}return i}processMergePolicy(e,t){const r=t.getMergePolicy(),i=e.getMergePolicy();if(this.validateMergePolicy(r),this.validateMergePolicy(i),i===void 0)return r===void 0?e:e.cloneShallow().setMergePolicy(r);if(r!==void 0&&r!==i)throw new Error(`Conflicting list mergePolicy values: target is "${i}" but source is "${r}".`);return e}validateMergePolicy(e){if(e!==void 0&&e!=="positional"&&e!=="append-only")throw new Error('mergePolicy must be either "positional" or "append-only".')}}class Ar{process(e,t,r){const i=t.getKeyType(),s=t.getValueType(),o=t.getType();if((i!==void 0||s!==void 0)&&o!==void 0&&!He(o,r))throw new Error("Source node with keyType or valueType must have a Dictionary type");let a=this.processKeyType(e,t,r);a=this.processValueType(a,t,r);const l=a.getKeyType(),c=a.getValueType(),d=t.getProperties();return(l!==void 0||c!==void 0)&&d!==void 0&&Object.entries(d).forEach(([p,f])=>{l!==void 0&&this.validateKeyType(p,l,r),c!==void 0&&this.validateValueType(f,c,r)}),a}processKeyType(e,t,r){const i=e.getKeyType(),s=t.getKeyType();if(i===void 0){if(s!==void 0)return this.validateBasicKeyType(s,r),e.cloneShallow().setKeyType(s)}else if(s!==void 0){if(this.validateBasicKeyType(s,r),!A(s,i,r)){const a=B.get(s),l=B.get(i);throw new Error(`The source key type '${JSON.stringify(a)}' is not a subtype of the target key type '${JSON.stringify(l)}'.`)}return e.cloneShallow().setKeyType(s)}return e}processValueType(e,t,r){const i=e.getValueType(),s=t.getValueType();if(i===void 0){if(s!==void 0)return e.cloneShallow().setValueType(s)}else if(s!==void 0){if(!A(s,i,r)){const a=B.get(s),l=B.get(i);throw new Error(`The source value type '${JSON.stringify(a)}' is not a subtype of the target value type '${JSON.stringify(l)}'.`)}return e.cloneShallow().setValueType(s)}return e}validateBasicKeyType(e,t){if(!xi(e,t))throw new Error(`Dictionary key type must be a basic type: ${JSON.stringify(B.get(e))}`)}validateKeyType(e,t,r){if(!_i(t,r))if(Fi(t,r)){const i=Number.parseInt(e,10);if(Number.isNaN(i)||i.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(Ui(t,r)){const i=Number.parseFloat(e);if(Number.isNaN(i))throw new Error(`Key '${e}' is not a valid Number.`)}else if(zi(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 i=e.getType();if(i!==void 0&&!A(i,t,r)){const s=B.get(i),o=B.get(t);throw new Error(`Value of type '${JSON.stringify(s)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}const ts=new Set(["minLength","minimum","exclusiveMinimum","minItems","minFields"]),rs=new Set(["maxLength","maximum","exclusiveMaximum","maxItems","maxFields"]),is=new Set(["required","uniqueItems"]);class Or{process(e,t){const r=t.getSchema();if(r===void 0)return e;const i=e.getSchema()?.clone()??new je;for(const s of ut){const o=r.get(s);if(o===void 0)continue;const a=i.get(s);i.set(s,this.propagateField(s,a,o))}return i.setEnum(this.propagateEnum(i.getEnum(),r.getEnum())),e.cloneShallow().setSchema(i)}propagateField(e,t,r){return t===void 0?r.clone():is.has(e)?r.getValue()===!0?r.clone():t.clone():e==="multipleOf"?this.multipleOf(t,r):ts.has(e)?this.numericValue(r)>this.numericValue(t)?r.clone():t.clone():rs.has(e)?this.numericValue(r)<this.numericValue(t)?r.clone():t.clone():r.clone()}multipleOf(e,t){const r=this.numericValue(e),i=this.numericValue(t);return Number.isInteger(r)&&Number.isInteger(i)?new h().setValue(Number(ns(BigInt(r),BigInt(i)))):i>r?t.clone():e.clone()}propagateEnum(e,t){if(t===void 0)return e?.map(i=>i.clone());if(e===void 0)return this.canonicalizeEnum(t);const r=new Map(e.map(i=>[this.enumComparableBlueId(i),i]));return this.canonicalizeEnum(t.flatMap(i=>{const s=r.get(this.enumComparableBlueId(i));return s===void 0?[]:[s]}))}canonicalizeEnum(e){const t=new Map;for(const r of e)t.set(this.enumComparableBlueId(r),r.clone());return[...t.values()].sort((r,i)=>this.enumCanonicalKey(r).localeCompare(this.enumCanonicalKey(i)))}enumComparableBlueId(e){const t=e.clone();return t.setSchema(void 0),b.calculateBlueIdSync(t)}enumCanonicalKey(e){const t=e.clone();return t.setSchema(void 0),JSON.stringify(ne.get(t))}numericValue(e){const t=e.getValue();if(typeof t=="number")return t;if(t!=null&&"toString"in Object(t))return Number(t.toString());throw new Error("Schema keyword value must be numeric.")}}function ss(n,e){let t=n<0n?-n:n,r=e<0n?-e:e;for(;r!==0n;){const i=t%r;t=r,r=i}return t}function ns(n,e){return n===0n||e===0n?0n:n/ss(n,e)*e}class Mr{process(e){return e}postProcess(e){const t=e.getSchema();return t===void 0||(this.verifyMultipleOfKeyword(t),this.verifyTextLength("minLength",t.get("minLength"),e),this.verifyTextLength("maxLength",t.get("maxLength"),e),this.verifyMultipleOf(t.get("multipleOf"),e),this.verifyEnum(t.getEnum(),e)),e}verifyMultipleOfKeyword(e){const t=e.get("multipleOf");if(t!==void 0&&this.numericValue(t)<=0)throw new Error('Schema keyword "multipleOf" must be greater than zero.')}verifyTextLength(e,t,r){if(t===void 0)return;const i=r.getValue();if(i==null){if(!this.hasPayload(r))return;throw this.wrongKind(e,"Text scalar")}if(typeof i!="string")throw this.wrongKind(e,"Text scalar");const s=Array.from(i).length,o=this.numericValue(t);if(e==="minLength"&&s<o)throw new Error(`Value "${i}" is shorter than the minimum length of ${o}.`);if(e==="maxLength"&&s>o)throw new Error(`Value "${i}" is longer than the maximum length of ${o}.`)}verifyMultipleOf(e,t){if(e===void 0)return;const r=t.getValue();if(r==null){if(!this.hasPayload(t))return;throw this.wrongKind("multipleOf","numeric scalar")}if(!this.isNumeric(r))throw this.wrongKind("multipleOf","numeric scalar");if(!nr.isExactBinary64Multiple(r,e.getValue()))throw new Error(`Value ${String(r)} is not a multiple of ${String(e.getValue())}.`)}verifyEnum(e,t){if(e===void 0||t.getValue()===void 0)return;const r=this.comparableBlueId(t);if(!e.some(i=>this.comparableBlueId(i)===r))throw new Error("Node value is not one of the allowed enum values.")}comparableBlueId(e){const t=e.clone();return t.setName(void 0),t.setDescription(void 0),t.setSchema(void 0),b.calculateBlueIdSync(t)}hasPayload(e){return e.getValue()!==void 0&&e.getValue()!==null||e.getItems()!==void 0||Object.keys(e.getProperties()??{}).length>0}isNumeric(e){return typeof e=="number"||e!=null&&"toString"in Object(e)}numericValue(e){const t=e.getValue();if(!this.isNumeric(t))throw this.wrongKind("schema","numeric scalar");return Number(t?.toString())}wrongKind(e,t){return new Error(`Schema keyword "${e}" applies to wrong kind; expected ${t}.`)}}class Vr{process(e){return e}postProcess(e,t,r){const i=e.getType();if(i!==void 0&&ji(i,r)){const s=e.getItems(),o=e.getProperties();if(s!==void 0&&s.length>0||o!==void 0&&Object.keys(o).length>0){const a=$i(i,r),l=i.getName()||"unknown";throw new Error(`Node of type "${l}" (which extends basic type "${a}") must not have items, properties or contracts.`)}}return e}}class Dr{process(e,t){let r=e;const i=t.getName();i!==void 0&&i!==e.getName()&&(r=r.cloneShallow().setName(i));const s=t.getDescription();return s!==void 0&&s!==r.getDescription()&&(r=r.cloneShallow().setDescription(s)),r}}function _t(){return new wr([new Sr,new Cr,new Rr,new Ar,new Or,new Mr,new Dr,new Vr])}class Ye{nodeProvider;mergingProcessor;minimizer=new Pt;cyclicSetIdentity;constructor(e={}){this.nodeProvider=e.nodeProvider??Lt(()=>[]),this.mergingProcessor=e.mergingProcessor??_t(),this.cyclicSetIdentity=this.createCyclicSetIdentityService()}createCyclicSetIdentityService(){return new x({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 Q&&e.getCompleteness()==="path-limited"){const t=e.getSourceSemanticBlueId();if(t!==void 0)return new h().setReferenceBlueId(t);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return C.hasBlueIdOnly(e)?e.clone():e.isResolved()?this.minimizeResolved(e):this.minimizeAuthoring(e)}minimizeResolved(e){if(e instanceof Q&&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 pe(this.mergingProcessor,t).resolve(e,F);return this.minimizeResolved(r)}hashMinimalTrusted(e){return this.hashMinimalTrustedWithProvider(e,this.nodeProvider)}hashMinimalTrustedWithProvider(e,t){return Array.isArray(e)?(Ee.validateStorageListShape(e),b.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t))):(Ee.validateStorageShape(e),b.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t)))}hashMinimalTrustedAsync(e){return Array.isArray(e)?(Ee.validateStorageListShape(e),b.calculateBlueId(this.toHashableMinimalTrusted(e))):(Ee.validateStorageShape(e),b.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(!P.hasPositionControl(e))return e;const r=new pe(this.mergingProcessor,t).resolve(e,F);return this.minimizer.minimizeResolvedForHash(r)}prepareCyclicDocument(e){return this.minimizeAuthoringWithProvider(e,this.createCyclicReferenceNodeProvider())}hashCyclicPrepared(e){return b.calculateBlueIdAllowingCyclicPlaceholdersSync(this.toHashableMinimalTrusted(e,this.createCyclicReferenceNodeProvider()))}createCyclicReferenceNodeProvider(){const e=this.nodeProvider;return oe.unverified(new class extends ue{fetchByBlueId(t){return t===x.ZERO_BLUE_ID||x.isIndexedThisReference(t)?[new h().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)&&x.hasThisReference([e]))throw new Error("Direct cyclic references using 'this#k' are supported only in a top-level document set.");return}if(x.hasThisReference(t))return this.cyclicSetIdentity.calculate(t).blueId}getTopLevelSetItems(e){if(Array.isArray(e))return e;if(C.hasItemsOnly(e))return e.getItems()??[]}toMinimalListIdentityInput(e){if(Ee.validateListControlShape(e),e[0]!==void 0&&P.isPreviousItem(e[0]))return e.map(i=>i.clone());const t=new h().setItems(e);return this.minimizeAuthoring(t).getItems()??[]}}class Lr{static convertValue(e,t){const r=e.getType()?.getBlueId(),i=e.getValue();return u.isNullable(i)?Oi(t)&&C.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):i:z===r?this.convertFromString(String(i),t):_===r||i instanceof V?this.convertFromBigDecimal(new V(i?.toString()),t):j===r||i instanceof R?this.convertFromBigInteger(new R(i?.toString()),t):K===r||typeof i=="boolean"?this.convertFromBoolean(!!i,t):this.convertFromString(String(i),t)}static convertFromString(e,t){if(!t)return e;const r=Se(t);if(r==="ZodString"||r==="ZodEnum"||r==="ZodNativeEnum")return e;if(r==="ZodNumber")return Number(e);if(r==="ZodBoolean")return e.toLowerCase()==="true";if(r==="ZodBigInt")return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){const r=Se(t);if(r==="ZodNumber")return e.toNumber();if(r==="ZodString")return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){const r=Se(t);if(r==="ZodNumber")return e.toNumber();if(r==="ZodBigInt")return BigInt(e.toString());if(r==="ZodString")return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t)return e;const r=Se(t);if(r==="ZodBoolean")return e;if(r==="ZodString")return e.toString();if(r==="ZodNumber")return Number(e);if(r==="ZodBigInt")return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;const t=Se(e);if(t==="ZodNumber")return 0;if(t==="ZodBoolean")return!1;if(t==="ZodString")return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}function Se(n){return String(n._def.typeName)}class os{convert(e,t){return Lr.convertValue(e,t)}}class as{constructor(e,t){this.nodeToObjectConverter=e,this.calculateBlueId=t}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(Bt(t)==="ZodIntersection"){const r=t,i=r._def.left,s=r._def.right,o=this.convert(e,i),a=this.convert(e,s);return{...o,...a}}if(Bt(t)==="ZodUnion")throw new Error("Union not supported");if(Bt(t)==="ZodObject"){const r=t;return Object.keys(r.shape).reduce((s,o)=>{const a=e.getProperties(),l=r.shape[o],c=ur(l);if(u.isNonNullable(c)){const v=ve.isString(c)?c:o,E=a?.[v],L=E?this.calculateBlueId(E):void 0;return s[o]=L,s}const d=hr(l);if(u.isNonNullable(d)){const v=a?.[d];return s[o]=v?.getName(),s}const p=lr(l);if(u.isNonNullable(p)){const v=a?.[p];return s[o]=v?.getDescription(),s}if(o==="name"){const v=e.getName();return s[o]=v,s}if(o==="description"){const v=e.getDescription();return s[o]=v,s}const f=a?.[o];if(u.isNullable(f))return s;const I=this.nodeToObjectConverter.convert(f,l);return s[o]=I,s},{})}throw new Error("Unknown schema type, "+t._def.typeName)}}function Bt(n){return String(n._def.typeName)}class ls{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const i=t.element??t._def.type;return r.map(o=>this.nodeToObjectConverter.convert(o,i))}}class cs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const i=t._def.valueType,s=r.map(o=>this.nodeToObjectConverter.convert(o,i));return new Set(s)}}class us{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,i=t.valueSchema,s=new Map,o=e.getName();u.isNonNullable(o)&&s.set(ae,o);const a=e.getDescription();u.isNonNullable(a)&&s.set(le,a);const l=e.getProperties();return u.isNonNullable(l)&&Object.entries(l).forEach(([c,d])=>{const p=new h().setValue(c);p.setType(new h().setBlueId(z));const f=Lr.convertValue(p,r),I=this.nodeToObjectConverter.convert(d,i);s.set(f,I)}),t instanceof m.ZodRecord?Object.fromEntries(s):s}}class ds{convert(e){return B.get(e)}}class hs{convert(e){return B.get(e)}}class ps{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const i=t.items;return r.map((o,a)=>this.nodeToObjectConverter.convert(o,i[a]))}}const fs=m.z.union([m.z.literal("ZodString"),m.z.literal("ZodNumber"),m.z.literal("ZodBoolean"),m.z.literal("ZodBigInt"),m.z.literal("ZodArray"),m.z.literal("ZodSet"),m.z.literal("ZodMap"),m.z.literal("ZodRecord"),m.z.literal("ZodObject"),m.z.literal("ZodEnum"),m.z.literal("ZodNativeEnum"),m.z.literal("ZodUnknown"),m.z.literal("ZodAny"),m.z.literal("ZodTuple")]);class ms{constructor(e,t){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new as(this.nodeToObjectConverter,t)}converters=new Map;complexObjectConverter;registerConverters(){const e=new os,t=new ls(this.nodeToObjectConverter),r=new ps(this.nodeToObjectConverter),i=new cs(this.nodeToObjectConverter),s=new us(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 ds),this.converters.set("ZodAny",new hs),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",i),this.converters.set("ZodMap",s),this.converters.set("ZodRecord",s),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){const t=String(e._def.typeName);if(t==="ZodEffects")return this.getSchemaTypeName(e.innerType());if(t==="ZodLazy")return this.getSchemaTypeName(e.schema);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodReadonly"||t==="ZodBranded"||gr(e))return this.getSchemaTypeName(e.unwrap());try{return fs.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class xr{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 ms(this,this.calculateBlueId)}converterFactory;calculateBlueId;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),i=J.unwrapSchema(t);if(Dt(i))return e;let s=i;return J.checkSchemaExtension(r,i,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(s=r),this.convertWithType(e,s)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class gs{static get(e,t={}){const{strategy:r="official"}=t,i=B.get(e,r);return Er(i)}}function Me(n){try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}class ys{process(e){return M.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 h().setBlueId(z)):typeof r=="bigint"||Y(r)?e.setType(new h().setBlueId(j)):Je(r)?e.setType(new h().setBlueId(_)):typeof r=="boolean"&&e.setType(new h().setBlueId(K))),e}}class Fe{static MAPPINGS="mappings";mappings=new Map;constructor(e){if(e instanceof h){const r=e.getProperties();if(r&&r[Fe.MAPPINGS]){const s=r[Fe.MAPPINGS].getProperties();s&&Object.entries(s).forEach(([o,a])=>{const l=a.getValue();typeof l=="string"&&this.mappings.set(o,l)})}}else this.mappings=e}process(e){return M.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 i=this.mappings.get(r);if(i){const s=new h().setBlueId(i);t===e.getType()?e.setType(s):t===e.getItemType()?e.setItemType(s):t===e.getKeyType()?e.setKeyType(s):t===e.getValueType()&&e.setValueType(s)}}}}}class Is{process(e){return M.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 i=String(t.getValue());throw new Error(`Unknown type "${i}" found in ${r} field. No BlueId mapping exists for this type.`)}}}class _r{blueIdsCollections=[];initialize(...e){this.blueIdsCollections=[...e]}registerBlueIds(...e){this.blueIdsCollections.push(...e)}generateMappingsYaml(e="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo"){const t={};for(const i of this.blueIdsCollections)Object.assign(t,i);const r=Object.entries(t).map(([i,s])=>` ${i}: ${s}`).join(`
|
|
39
|
+
description: This transformation replaces`,Zi=[Pr,Hi,Yi,Wi];class Ji extends ue{blueIdToNodesMap=new Map;constructor(){super(),this.load()}fetchByBlueId(e){return this.blueIdToNodesMap.get(e)||[]}load(){for(const e of Zi){const t=he(e);if(t===void 0){console.error(`This content file is not valid YAML: ${e}`);continue}if(Array.isArray(t)){const r=t.map(s=>y.deserialize(s)),i=b.calculateBlueIdSync(r);this.blueIdToNodesMap.set(i,r)}else{const r=y.deserialize(t),i=b.calculateBlueIdSync(r);this.blueIdToNodesMap.set(i,[r])}}}}class Ae extends ue{static INSTANCE=new Ae;nodeProvider;constructor(){super(),this.nodeProvider=new Ji}fetchByBlueId(e){return this.nodeProvider.fetchByBlueId(e)}}class $t extends ue{constructor(e){super(),this.delegate=e}fetchByBlueId(e){let t;try{t=G.requireBlueIdOrCyclicMember(e,"provider.fetchByBlueId")}catch{return this.delegate.fetchByBlueId(e)}const r=this.delegate.fetchByBlueId(e);if(r===null||r.length===0||t.includes("#"))return r;const i=r.length===1?b.calculateBlueIdSync(this.contentWithoutRootIdentity(r[0])):b.calculateBlueIdSync(r.map(s=>this.contentWithoutRootIdentity(s)));if(i!==t){if(this.verifyCyclicSetContent(t,r))return r;throw new Error(`Provider returned content with BlueId ${i} for requested BlueId ${t}.`)}return r}contentWithoutRootIdentity(e){const t=e.clone();return t.getReferenceBlueId()!==void 0&&!this.isReferenceOnly(t)&&t.setReferenceBlueId(void 0),t}isReferenceOnly(e){return e.getReferenceBlueId()!==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.getValue()===void 0&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0&&e.getContractsNode()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}verifyCyclicSetContent(e,t){if(t.length===0)return!1;const r=t.map(s=>{const o=s.clone();return this.rewriteCyclicMemberReferences(o,e),o});if(!r.some(s=>this.hasThisReference(s)))return!1;try{return b.calculateBlueIdAllowingCyclicPlaceholdersSync(r)===e}catch{return!1}}rewriteCyclicMemberReferences(e,t){const r=e.getReferenceBlueId();r?.startsWith(`${t}#`)&&e.setReferenceBlueId(`this#${r.slice(t.length+1)}`),this.childrenOf(e).forEach(i=>this.rewriteCyclicMemberReferences(i,t))}hasThisReference(e){return e.getReferenceBlueId()?.startsWith("this#")?!0:this.childrenOf(e).some(r=>this.hasThisReference(r))}childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),e.getContractsNode(),...e.getSchema()?.entries().map(([,t])=>t)??[],...e.getSchema()?.getEnum()??[],...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}const br=Symbol.for("blue.repositoryBasedNodeProvider");class oe{static wrap(e){if(this.isAlreadyWrapped(e))return e;if(this.isUnverified(e))return new Ce([Ae.INSTANCE,e]);const t=[Ae.INSTANCE,new $t(e)];return new Ce(t)}static unverified(e){return new Tt(e)}static isUnverified(e){return e instanceof Tt||e[br]===!0?!0:e instanceof Ce&&e.getNodeProviders().some(t=>this.isUnverified(t))}static isAlreadyWrapped(e){return e instanceof Ce?e.getNodeProviders().some(t=>t===Ae.INSTANCE||t instanceof $t||t instanceof Tt):!1}}class Tt extends ue{constructor(e){super(),this.delegate=e}fetchByBlueId(e){return this.delegate.fetchByBlueId(e)}}class dt{}class Oe{static convert(e){const t=new et;return Oe.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const i=e.getProperties(),s=e.getItems(),o=i!==void 0&&Object.keys(i).length>0,a=s!==void 0&&s.length>0;if(!o&&!a){r.addPath(t===""?"/":t);return}if(i)for(const[l,c]of Object.entries(i)){const d=`${t}/${l}`;Oe.traverseNode(c,d,r)}if(s)for(let l=0;l<s.length;l++){const c=`${t}/${l}`;Oe.traverseNode(s[l],c,r)}}}function kt(n,e){const t=n.split(e),r=[...t].reverse().findIndex(s=>s!==""),i=r===-1?0:t.length-r;return t.slice(0,i)}class ke extends dt{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=kt(e,"/"),i=kt(t,"/");if(i.length>r.length)return!1;for(let s=1;s<i.length;s++)if(r[s]!=="*"&&r[s]!==i[s])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 et().setMaxDepth(e);for(let r=1;r<=e;r++){const i="/"+Array(r).fill("*").join("/");t.addPath(i)}return t.build()}static withSinglePath(e){return new et().addPath(e).build()}static fromNode(e){return Oe.convert(e)}}class et{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 ke(this.allowedPaths,this.maxDepth)}}class re extends dt{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class _e extends dt{limits;constructor(e){super(),this.limits=e}shouldExtendPathSegment(e,t){return this.limits.every(r=>r.shouldExtendPathSegment(e,t))}shouldMergePathSegment(e,t){return this.limits.every(r=>r.shouldMergePathSegment(e,t))}enterPathSegment(e,t){this.limits.forEach(r=>{r.enterPathSegment(e,t)})}exitPathSegment(){this.limits.forEach(e=>{e.exitPathSegment()})}static of(...e){return new _e(e)}}const F=new re;class Q extends h{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 h().setReferenceBlueId(this.sourceSemanticBlueId);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return new Pt().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 Pt().minimizeResolvedForHash(this);return b.calculateBlueIdSync(t)}clone(){const e=super.clone();return new Q(e,this.getMetadata())}cloneShallow(){const e=super.cloneShallow();return new Q(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(!G.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()).setContractsNode(e.getContractsNode()).setBlueId(e.getBlueId()).setSchema(e.getSchema()).setMergePolicy(e.getMergePolicy()).setPreviousBlueId(e.getPreviousBlueId()).setPosition(e.getPosition()).setBlue(e.getBlue()).setInlineValue(e.isInlineValue());const t=e.getValue();t!==void 0&&this.setValue(t)}}class Xi{blue;constructor(e){this.blue=e}matchesType(e,t,r=F,i={}){if(this.isTypeOnlyMatcher(t)&&this.targetTypeReferenceHasNoDefinition(t)&&this.matchesUnresolvedExactTypeOnly(e,t))return!0;try{const s=ke.fromNode(t),o=i.limits===void 0?r:_e.of(r,i.limits),a=_e.of(o,s),l=this.extendAndResolve(e,a),c=this.blue.resolve(t,a),d=this.expandSchemaOwnedTypeReferences(t);return this.recursiveValueComparison(l,c,d,a,{},this.normalizeMatcherPointer(i.pointer),i.memo)?this.isTypeOnlyMatcher(t)?!0:this.verifyMatch(l,t,a)||t.getType()===void 0:!1}catch{return this.matchesUnresolvedExactTypeOnly(e,t)}}extendAndResolve(e,t){const r=e.clone(),i=r.clone();this.blue.extend(i,t);const s=this.blue.resolve(i,t);return this.restoreMissingStructure(s,r),s}restoreMissingStructure(e,t){const r=t.getItems(),i=e.getItems();if(r&&r.length>0)if(!i||i.length===0)e.setItems(r.map(l=>l.clone()));else for(let l=0;l<Math.min(i.length,r.length);l++)this.restoreMissingStructure(i[l],r[l]);const s=t.getProperties();if(s){let l=e.getProperties();l||(l={},e.setProperties(l));for(const[c,d]of Object.entries(s)){const p=l[c];p===void 0?l[c]=d.clone():this.restoreMissingStructure(p,d)}}const o=t.getBlueId();e.getBlueId()===void 0&&o!==void 0&&e.setBlueId(o);const a=t.getValue();e.getValue()===void 0&&a!==void 0&&e.setValue(a)}verifyMatch(e,t,r){const i=t.getType();if(this.matchesImplicitStructure(e,i))return!0;const s=e.clone().setType(t.clone());try{this.blue.resolve(s,r)}catch{return!1}return!0}recursiveValueComparison(e,t,r=t,i=F,s={},o,a){const l=this.expectedTypeBlueIdForMemo(t,r);if(a&&o&&l){const c=a.get(o,l);if(c!==void 0)return c;const d=this.recursiveValueComparisonUncached(e,t,r,i,s,o,a);return a.set(o,l,d),d}return this.recursiveValueComparisonUncached(e,t,r,i,s,o,a)}recursiveValueComparisonUncached(e,t,r=t,i=F,s={},o,a){const l=t.getType(),c=this.matchesImplicitStructure(e,l)||this.matchesImplicitCoreCollectionType(e,t);if(this.requiresSemanticPresence(t)&&!this.isRootMatcherPointer(o)&&this.isMetadataOnlyNode(e)||!this.matchesSchemaCardinality(e,t)||e.getType()===void 0&&this.isCoreCollectionType(t)&&!c)return!1;if(l&&!c){const w=e.getType();if(w){if(!A(w,l,this.blue.getNodeProvider())&&!this.matchesExactTypeReference(w,l))return!1}else if(!this.matchesImplicitPrimitiveType(e,l))return!1}const d=t.getBlueId();if(!c&&d!==void 0)if(this.isExplicitBlueIdMatcher(r)){if(s.bareBlueIdMatcherMode==="type-reference"){if(!this.matchesBareBlueIdTypeReference(e,t,d))return!1}else if(!this.matchesBareBlueIdIdentity(e,d))return!1}else{const w=e.getBlueId(),T=e.getType();if(T===void 0&&w!==void 0&&w!==d||T&&!A(T,t,this.blue.getNodeProvider())&&!this.matchesExactTypeReference(T,t))return!1}const p=e.getBlueId();if(!c&&d===void 0&&p!==void 0&&e.getType()===void 0&&t.getItems()===void 0&&this.hasMatcherShape(t)&&!this.matchesCalculatedBlueId(t,p))return!1;const f=t.getValue();if(f!==void 0){const w=e.getValue();if(w===void 0)return!1;if(M(w)&&M(f)){if(!w.eq(f))return!1}else if(w!==f)return!1}const I=t.getItems(),v=r.getItems();if(I!==void 0){const w=e.getItems()??[];for(let T=0;T<I.length;T++)if(T<w.length){if(!this.recursiveValueComparison(w[T],I[T],v?.[T]??I[T],i,{},this.childMatcherPointer(o,String(T)),a))return!1}else if(this.requiresSemanticPresence(I[T])||this.hasValueInNestedStructure(I[T]))return!1}const E=t.getItemType(),L=r.getItemType();if(E!==void 0){const w=e.getItems()??[];for(let T=0;T<w.length;T++){const te=w[T];if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(te,E,L??E,i,"type-reference"),E,L??E,i,{bareBlueIdMatcherMode:"type-reference"},this.childMatcherPointer(o,String(T)),a))return!1}}const $=t.getProperties(),W=r.getProperties();if($!==void 0){const w=e.getProperties()??{};for(const[T,te]of Object.entries($))if(T in w){if(!this.recursiveValueComparison(w[T],te,W?.[T]??te,i,{},this.childMatcherPointer(o,T),a))return!1}else if(this.requiresSemanticPresence(te)||this.hasValueInNestedStructure(te))return!1}const ee=t.getValueType(),we=r.getValueType();if(ee!==void 0){const w=Object.entries(e.getProperties()??{});for(const[T,te]of w)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(te,ee,we??ee,i,"type-reference"),ee,we??ee,i,{bareBlueIdMatcherMode:"type-reference"},this.childMatcherPointer(o,T),a))return!1}return!0}expectedTypeBlueIdForMemo(e,t){return this.blueIdOrReference(t)??this.blueIdOrReference(e)??this.blueIdOrReference(t.getType())??this.blueIdOrReference(e.getType())}blueIdOrReference(e){return e?.getBlueId()??e?.getReferenceBlueId()}normalizeMatcherPointer(e){if(e===void 0)return;const t=e.trim();return t.length===0||t==="/"?"/":t.startsWith("/")?t:`/${t}`}childMatcherPointer(e,t){if(e===void 0)return;const r=t.replace(/~/g,"~0").replace(/\//g,"~1");return e==="/"?`/${r}`:`${e}/${r}`}resolveUntypedNodeAgainstMatcherType(e,t,r,i,s="identity"){return e.getType()!==void 0||e.getBlueId()!==void 0||s==="identity"&&this.isExplicitBlueIdMatcher(r)?e:this.resolveAgainstTargetType(e,t,i)??e}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const i of t)if(this.hasValueInNestedStructure(i))return!0}const r=e.getProperties();if(r!==void 0){for(const i of Object.values(r))if(this.hasValueInNestedStructure(i))return!0}return!1}requiresSemanticPresence(e){return e.getSchema()?.get("required")?.getValue()===!0}matchesSchemaCardinality(e,t){const r=t.getSchema();if(!r)return!0;const i=this.schemaInteger(r,"minItems");if(i!==void 0&&(e.getItems()?.length??0)<i)return!1;const s=this.schemaInteger(r,"maxItems");if(s!==void 0&&(e.getItems()?.length??0)>s)return!1;const o=Object.keys(e.getProperties()??{}).length,a=this.schemaInteger(r,"minFields");if(a!==void 0&&o<a)return!1;const l=this.schemaInteger(r,"maxFields");return!(l!==void 0&&o>l)}schemaInteger(e,t){const r=e.get(t)?.getValue();if(typeof r=="number"&&Number.isInteger(r))return r;if(Y(r))return Number(r.toString())}isRootMatcherPointer(e){return e===void 0||e==="/"}isMetadataOnlyNode(e){return e.getValue()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0&&e.getBlueId()===void 0&&e.getReferenceBlueId()===void 0&&this.hasMetadata(e)}hasMetadata(e){return 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.getSchema()!==void 0||e.getMergePolicy()!==void 0||e.getBlue()!==void 0}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}isTypeOnlyMatcher(e){return e.getType()!==void 0&&e.getBlueId()===void 0&&e.getReferenceBlueId()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getProperties()===void 0&&e.getName()===void 0&&e.getDescription()===void 0}matchesUnresolvedExactTypeOnly(e,t){if(!this.isTypeOnlyMatcher(t))return!1;const r=e.getType(),i=t.getType();return r!==void 0&&i!==void 0&&this.matchesExactTypeReference(r,i)}targetTypeReferenceHasNoDefinition(e){const t=this.blueIdOrReference(e.getType());if(t===void 0)return!1;const r=this.blue.getNodeProvider().fetchByBlueId(t);return r==null||r.length===0}matchesImplicitPrimitiveType(e,t){const r=e.getValue();switch(this.blueIdOrReference(t)??this.primitiveAliasBlueId(t.getValue())){case z:return typeof r=="string";case j:return typeof r=="number"&&Number.isInteger(r)&&Number.isSafeInteger(r)||Y(r);case _:return typeof r=="number"||M(r);case K:return typeof r=="boolean";default:return!1}}primitiveAliasBlueId(e){switch(e){case"Text":return z;case"Integer":return j;case"Double":return _;case"Boolean":return K;default:return}}matchesCalculatedBlueId(e,t){if(e instanceof Q&&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 i=e.getType();return i?A(i,t,this.blue.getNodeProvider()):e.getBlueId()!==void 0?this.matchesBareBlueIdIdentity(e,r):!1}matchesExactTypeReference(e,t){const r=this.blueIdOrReference(e),i=this.blueIdOrReference(t);return r!==void 0&&i!==void 0&&r===i}toPlainBlueNode(e){const t=new h(e.getName());t.setDescription(e.getDescription()).setReferenceBlueId(e.getReferenceBlueId()).setInlineValue(e.isInlineValue());const r=e.getValue();r!==void 0&&t.setValue(r);const i=e.getType();i!==void 0&&t.setType(this.toPlainBlueNode(i));const s=e.getItemType();s!==void 0&&t.setItemType(this.toPlainBlueNode(s));const o=e.getKeyType();o!==void 0&&t.setKeyType(this.toPlainBlueNode(o));const a=e.getValueType();a!==void 0&&t.setValueType(this.toPlainBlueNode(a));const l=e.getItems();l!==void 0&&t.setItems(l.map(p=>this.toPlainBlueNode(p)));const c=e.getProperties();c!==void 0&&t.setProperties(Object.fromEntries(Object.entries(c).map(([p,f])=>[p,this.toPlainBlueNode(f)])));const d=e.getBlue();return d!==void 0&&t.setBlue(this.toPlainBlueNode(d)),t}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:Ge(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):He(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}matchesImplicitCoreCollectionType(e,t){return e.getType()!==void 0?!1:Ge(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):He(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isCoreCollectionType(e){return Ge(e,this.blue.getNodeProvider())||He(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.getName()===void 0&&e.getDescription()===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&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}isExplicitBlueIdMatcher(e){return this.isBareBlueIdReference(e)}resolveAgainstTargetType(e,t,r){try{const i=e.clone(),s=i.clone().setType(t.clone()),o=this.blue.resolve(s,r);return this.restoreMissingStructure(o,i),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()),i=e.getType();i&&e.setType(this.expandReferencedTypeNode(i,r));const s=e.getItemType();s&&e.setItemType(this.expandReferencedTypeNode(s,r));const o=e.getKeyType();o&&e.setKeyType(this.expandReferencedTypeNode(o,r));const a=e.getValueType();a&&e.setValueType(this.expandReferencedTypeNode(a,r));const l=e.getItems();l&&e.setItems(l.map(d=>this.expandSchemaTypeReferences(d,r)));const c=e.getProperties();return c&&e.setProperties(Object.fromEntries(Object.entries(c).map(([d,p])=>[d,this.expandSchemaTypeReferences(p,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 i=this.blue.getNodeProvider().fetchByBlueId(r);return!i||i.length!==1?e.clone():this.expandSchemaTypeReferences(i[0].clone(),t)}withVisitedBlueId(e,t){if(!t||e.has(t))return e;const r=new Set(e);return r.add(t),r}}class x{static ZERO_BLUE_ID="0".repeat(44);static THIS_INDEX_REFERENCE_PATTERN=/^this#(0|[1-9]\d*)$/;prepareDocument;calculateBlueId;constructor(e={}){this.prepareDocument=e.prepareDocument??(t=>t),this.calculateBlueId=e.calculateBlueId??b.calculateBlueIdAllowingCyclicPlaceholdersSync}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((a,l)=>{const c=this.prepareDocument(this.replaceIndexedThisReferences(a,()=>x.ZERO_BLUE_ID));return{originalIndex:l,preliminaryBlueId:this.calculateBlueId(c),node:a}});this.rejectDuplicatePreliminaryInputs(t);const r=[...t].sort(this.comparePreliminaryDocuments),i=[];r.forEach(({originalIndex:a},l)=>{i[a]=l});const s=r.map(({node:a})=>this.prepareDocument(this.replaceIndexedThisReferences(a,l=>`this#${i[l]}`))),o=this.calculateBlueId(s);return{blueId:o,nodes:s,documentBlueIds:e.map((a,l)=>`${o}#${i[l]}`),originalToSortedIndexes:i}}comparePreliminaryDocuments(e,t){return e.preliminaryBlueId<t.preliminaryBlueId?-1:e.preliminaryBlueId>t.preliminaryBlueId?1:e.originalIndex-t.originalIndex}rejectDuplicatePreliminaryInputs(e){const t=new Map;e.forEach(({preliminaryBlueId:r,originalIndex:i})=>{const s=t.get(r);if(s!==void 0)throw new Error(`Duplicate preliminary cyclic BlueId input for members ${s} and ${i}.`);t.set(r,i)})}validateCyclicSet(e){if(e.length===0)throw new Error("Cyclic document set cannot be empty.");let t=!1;if(this.visitReferences(e,(r,i)=>{if((i==="this"||i.startsWith("this#"))&&(t=!0),i==="this")throw new Error("Direct cyclic document sets must use indexed references such as 'this#0'; unindexed 'this' is not supported.");if(i.startsWith("this#")&&!x.THIS_INDEX_REFERENCE_PATTERN.test(i))throw new Error(`Malformed direct cyclic reference '${i}'. Expected 'this#<non-negative-integer>'.`);const s=this.readIndexedThisReference(i);if(s!==void 0&&s>=e.length)throw new Error(`Direct cyclic reference '${i}' points outside the ${e.length}-document set.`)}),!t)throw new Error("Circular BlueId calculation requires at least one internal this reference.")}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 i=this.readIndexedThisReference(r);i!==void 0&&e.setReferenceBlueId(t(i))}this.childrenOf(e).forEach(i=>this.rewriteIndexedThisReferences(i,t))}static nodeHasThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,i)=>{(i==="this"||i.startsWith("this#"))&&(t=!0)}),t}static nodeHasIndexedThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,i)=>{x.THIS_INDEX_REFERENCE_PATTERN.test(i)&&(t=!0)}),t}visitReferences(e,t){e.forEach(r=>x.visitNodeReferences(r,t))}static visitNodeReferences(e,t){const r=e.getReferenceBlueId();r!==void 0&&t(e,r),this.childrenOf(e).forEach(i=>this.visitNodeReferences(i,t))}readIndexedThisReference(e){const t=e.match(x.THIS_INDEX_REFERENCE_PATTERN);if(t!==null)return Number(t[1])}childrenOf(e){return x.childrenOf(e)}static childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),e.getContractsNode(),...e.getSchema()?.entries().map(([,t])=>t)??[],...e.getSchema()?.getEnum()??[],...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}class Nr{resolveWithoutLimits(e){return this.resolve(e,F)}}class xt{nodeProvider;strategy;constructor(e,t){this.nodeProvider=oe.wrap(e),this.strategy=t||"THROW_EXCEPTION"}extend(e,t){this.extendNode(e,t,"")}extendNode(e,t,r,i=!1){if(!i){if(!t.shouldExtendPathSegment(r,e))return;t.enterPathSegment(r,e)}try{const s=e.getBlueId();if(s&&R.hasBlueIdOnly(e)&&!ie.includes(s)){const f=this.fetchNode(e);if(f&&f.length>0){const I=this.shouldPreserveReferenceBlueId(r,i);if(f.length===1){const v=f[0];this.mergeNodes(e,v,I)}else{const v=f.map(L=>L.clone()),E=new h().setItems(v);this.mergeNodes(e,E,I)}}}const o=e.getType();o&&this.extendNode(o,t,"type",!0);const a=e.getItemType();a&&this.extendNode(a,t,"itemType",!0);const l=e.getKeyType();l&&this.extendNode(l,t,"keyType",!0);const c=e.getValueType();c&&this.extendNode(c,t,"valueType",!0);const d=e.getProperties();d&&Object.entries(d).forEach(([f,I])=>{this.extendNode(I,t,f,!1)});const p=e.getItems();if(p&&p.length>0)for(let f=0;f<p.length;f++)this.extendNode(p[f],t,String(f),!1)}finally{i||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 i=t.getValue();u.isNonNullable(i)&&e.setValue(i),e.setItems(t.getItems()?.map(o=>o.clone()));const s=t.getProperties();e.setProperties(s===void 0?void 0:Object.fromEntries(Object.entries(s).map(([o,a])=>[o,a.clone()]))),e.setBlue(t.getBlue()?.clone())}}class pe extends Nr{mergingProcessor;nodeProvider;nodeProviderIsUnverified;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProviderIsUnverified=oe.isUnverified(t),this.nodeProvider=oe.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 i=e;const s=t.getType();if(u.isNonNullable(s)){const o=this.resolveTypeNode(s,r),a=this.getTypeOverlay(s,o,r);i=this.mergeObject(i,a,r);const l=t.cloneShallow().setType(o.clone());return this.mergeObject(i,l,r)}return this.mergeObject(i,t,r)}mergeObject(e,t,r){const i=e.cloneShallow(),s=this.mergingProcessor.preserveSource?.(i,t,r.nodeProvider);if(s!==void 0)return this.mergingProcessor.postProcess?this.mergingProcessor.postProcess(s,t,r.nodeProvider):s;let o=this.mergingProcessor.process(i,t,r.nodeProvider);if(this.mergingProcessor.shouldPreserveSource?.(t,r.nodeProvider))return this.mergingProcessor.postProcess&&(o=this.mergingProcessor.postProcess(o,t,r.nodeProvider)),o;const a=t.getItems();u.isNonNullable(a)&&(o=this.mergeChildren(o,t,r));const l=t.getProperties();return u.isNonNullable(l)&&(o=this.mergeProperties(o,t,l,r)),u.isNonNullable(t.getBlueId())&&(o=o.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(o=this.mergingProcessor.postProcess(o,t,r.nodeProvider)),o}mergeChildren(e,t,r){const i=t.getItems()??[];for(let s=0;s<i.length;s+=1)if(s!==0&&P.hasPreviousProperty(i[s]))throw new Error("$previous list control is allowed only as the first item.");return P.hasListControlItems(i)?this.mergeChildrenWithListControls(e,t,r):this.mergeChildrenWithoutListControls(e,i,r)}mergeChildrenWithoutListControls(e,t,r){const i=e.getItems();if(u.isNullable(i)){const o=[];for(let a=0;a<t.length;a++){const l=t[a];if(r.limits.shouldMergePathSegment(String(a),l)){this.enterPathSegment(r,String(a),l);try{const c=this.materializeForCurrentContextWithItemType(l,r,e.getItemType());o.push(c)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(o)}if(t.length<i.length)throw new Error(`Subtype of element must not have more items (${i.length}) than the element itself (${t.length}).`);const s=[...i];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>=s.length){const d=this.materializeForCurrentContextWithItemType(t[o],r,e.getItemType());s.push(d);continue}const a=r.limits instanceof re?this.applyItemType(t[o],e.getItemType()):this.materializeForCurrentContextWithItemType(t[o],r,e.getItemType()),l=this.calculateNodeBlueId(a,r),c=this.calculateNodeBlueId(s[o],r);if(l!==c)throw new Error(`Mismatched items at index ${o}: source item has blueId '${l}', but target item has blueId '${c}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(s)}mergeChildrenWithListControls(e,t,r){const i=t.getItems()??[],s=e.getItems()!==void 0,o=e.getItems()??[],a=P.getMergePolicy(t,e),l=[...o];let c=0,d=!1;const p=i[0];if(p!==void 0&&P.hasPreviousProperty(p)){if(P.getPreviousBlueId(p)===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");d=!0,c=1}const f=d&&o.length===0&&!(r.limits instanceof re),I=new Set;for(;c<i.length;c++){const v=i[c];if(P.hasPreviousProperty(v))throw new Error("$previous list control is allowed only as the first item.");const E=P.readPosition(v);if(E!==void 0){if(a==="append-only")throw new Error("$pos is not allowed in append-only lists.");if(!s){if(E!==l.length)throw new Error("$pos is out of range for a list without inherited items.");const W=P.withoutPosition(v);if(!P.hasPayloadAfterRemovingPosition(v))throw new Error("$pos list control must include an item payload.");this.enterPathSegment(r,String(E),W);try{l.push(this.materializeForCurrentContextWithItemType(W,r,e.getItemType()))}finally{this.exitPathSegment(r)}continue}if(E>=o.length)throw new Error(`$pos ${E} is out of range for inherited list length ${o.length}.`);if(I.has(E))throw new Error(`Duplicate $pos list overlay for index ${E}.`);I.add(E);const $=P.withoutPosition(v);if(!P.hasPayloadAfterRemovingPosition(v))throw new Error("$pos list control must include an item payload.");if(!r.limits.shouldMergePathSegment(String(E),$))continue;this.enterPathSegment(r,String(E),$);try{const W=l[E],ee=W?.getType()??e.getItemType();l[E]=W===void 0||P.isReplacementPayload($)?this.materializeForCurrentContextWithItemType($,r,ee):this.mergeWithContext(W,$,r)}finally{this.exitPathSegment(r)}continue}const L=l.length;if(!(!f&&!r.limits.shouldMergePathSegment(String(L),v))){if(f){l.push(this.materializeWithoutLimits(this.applyItemType(v,e.getItemType()),r));continue}this.enterPathSegment(r,String(L),v);try{const $=this.materializeForCurrentContextWithItemType(v,r,e.getItemType());l.push($)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}materializeWithoutLimits(e,t){return new pe(this.mergingProcessor,t.nodeProvider).resolve(e,F)}mergeProperties(e,t,r,i){const s=e.getProperties()??{};let o=s,a=!1;for(const[l,c]of Object.entries(r))if(i.limits.shouldMergePathSegment(l,c)){this.enterPathSegment(i,l,c);try{const d=o[l],p=this.getPathLimitedListControlTarget(d,t,l,c,i),f=p??d,v=this.shouldMergePropertyWithoutPreResolve(f,c,i)?this.mergeExistingProperty(f,c,i):(()=>{const L=this.materializeForCurrentContext(c,i);return f===void 0?L:this.mergeObject(f,L,i)})(),E=p===void 0?v:this.projectListNodeToCurrentLimits(v,i);E!==d&&(a||(o={...s},a=!0),o[l]=E)}finally{this.exitPathSegment(i)}}return a?e.cloneShallow().setProperties(o):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof re?u.isNonNullable(e)&&P.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 h,s=this.mergeWithContext(r,e,t).cloneShallow().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new Q(s,{completeness:t.limits instanceof re?"full":"path-limited"})}createResolutionContext(e){const t=new Map,r=new Map,i=Mi(this.createResolutionNodeProvider(this.nodeProvider,t),r);return{limits:e,nodeProvider:i,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 i=this.createResolvedTypeCacheKey(r,t),s=t.resolvedTypeCache.get(i);if(u.isNonNullable(s)&&!t.resolvingTypeKeys.has(i))return s;if(t.resolvingTypeBlueIds.has(r))return s??this.createCyclicTypeReference(r,t);const o=this.createCyclicTypeReference(r,t);t.resolvedTypeCache.set(i,o),t.resolvingTypeKeys.add(i),t.resolvingTypeBlueIds.add(r);try{const a=this.resolveAndExtendTypeNode(e,t);return a.setReferenceBlueId(r),t.resolvedTypeCache.set(i,a),a}catch(a){throw t.resolvedTypeCache.delete(i),a}finally{t.resolvingTypeKeys.delete(i),t.resolvingTypeBlueIds.delete(r)}}return this.resolveAndExtendTypeNode(e,t)}createCyclicTypeReference(e,t){return new Q(new h().setReferenceBlueId(e),{completeness:t.limits instanceof re?"full":"path-limited"})}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new xt(t.nodeProvider).extend(r,ke.withSinglePath("/")),this.resolveWithContext(r,t)}getTypeOverlay(e,t,r){const i=e.getBlueId();if(u.isNullable(i))return this.createTypeOverlay(t);const s=this.createResolvedTypeCacheKey(i,r),o=r.typeOverlayCache.get(s);if(u.isNonNullable(o))return o;const a=this.createTypeOverlay(t);return r.resolvingTypeBlueIds.has(i)||r.typeOverlayCache.set(s,a),a}createTypeOverlay(e){return e.cloneShallow().setType(void 0).setBlueId(void 0)}createResolvedTypeCacheKey(e,t){return t.limits instanceof re?e:`${e}|${this.getCurrentPointer(t)}`}materializeForCurrentContext(e,t){return e.isResolved()&&this.canReuseResolvedSubtree(t)?e.clone():this.resolveWithContext(e,t)}materializeForCurrentContextWithItemType(e,t,r){return this.materializeForCurrentContext(this.applyItemType(e,r),t)}applyItemType(e,t){return e.getType()!==void 0||e.getReferenceBlueId()!==void 0||t===void 0?e:e.clone().setType(this.itemTypeReference(t))}itemTypeReference(e){const t=e.getReferenceBlueId();return t===void 0?e.clone():new h().setReferenceBlueId(t)}canReuseResolvedSubtree(e){return e.limits instanceof re}calculateNodeBlueId(e,t){const r=t.nodeHashCache.get(e);if(u.isNonNullable(r))return r;const i=k.calculateHashMinimalBlueId(e);return t.nodeHashCache.set(e,i),i}getPathLimitedListControlTarget(e,t,r,i,s){if(!(e===void 0||s.limits instanceof re||!P.hasListControlItems(i.getItems())))return this.resolveFullInheritedProperty(t,r,s)}resolveFullInheritedProperty(e,t,r){const i=e.getType();if(i===void 0)return;const s=i.getBlueId();if(u.isNonNullable(s)){const l=r.nodeProvider.fetchByBlueId(s)?.[0];return l===void 0?void 0:new pe(this.mergingProcessor,r.nodeProvider).resolve(l,F).getProperties()?.[t]?.clone()}return new pe(this.mergingProcessor,r.nodeProvider).resolve(i,F).getProperties()?.[t]?.clone()}projectListNodeToCurrentLimits(e,t){const r=e.getItems();return r===void 0?e:e.cloneShallow().setItems(r.filter((i,s)=>t.limits.shouldMergePathSegment(String(s),i)))}createResolutionNodeProvider(e,t){const r=new class extends ue{fetchByBlueId(i){if(t.has(i))return t.get(i)??null;const s=e.fetchByBlueId(i);return t.set(i,s),s}};return this.nodeProviderIsUnverified?oe.unverified(r):r}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 wr{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((i,s)=>s.process(i,t,r),e)}preserveSource(e,t,r){for(const i of this.mergingProcessors){const s=i.preserveSource?.(e,t,r);if(s!==void 0)return s}}shouldPreserveSource(e,t){return this.mergingProcessors.some(r=>r.shouldPreserveSource?.(e,t))}postProcess(e,t,r){return this.mergingProcessors.reduce((i,s)=>s.postProcess?s.postProcess(i,t,r):i,e)}}class Sr{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const i=e.getValue();if(u.isNullable(i))return e.cloneShallow().setValue(r);if(!Qi(r,i)){if(es(e))return e.cloneShallow().setValue(r);throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${i}`)}}return e}}const Qi=(n,e)=>Y(n)&&Y(e)||Je(n)&&Je(e)?n.eq(e):n===e,es=n=>u.isNonNullable(n.getType())||u.isNonNullable(n.getItemType())||u.isNonNullable(n.getKeyType())||u.isNonNullable(n.getValueType())||u.isNonNullable(n.getSchema())||u.isNonNullable(n.getDescription());class Cr{process(e,t,r){const i=e.getType(),s=t.getType();let o=e;if(i===void 0){if(s!==void 0&&t.getValue()!==void 0&&vr(s)){const a=B.get(s);throw new Error(`Anonymous core type alias '${JSON.stringify(a)}' is not interchangeable with its registry core type.`)}o=e.cloneShallow().setType(s)}else if(s!==void 0){if(!A(s,i,r)){const l=B.get(s),c=B.get(i);throw new Error(`The source type '${JSON.stringify(l)}' is not a subtype of the target type '${JSON.stringify(c)}'.`)}o=e.cloneShallow().setType(s)}return o}}class Rr{process(e,t,r){let i=this.processMergePolicy(e,t);const s=t.getItemType(),o=t.getType();if(s!==void 0&&o!==void 0&&!Ge(o,r))throw new Error("Source node with itemType must have a List type");const a=i.getItemType();if(a===void 0)s!==void 0&&(i=i.cloneShallow().setItemType(s));else if(s!==void 0){if(!A(s,a,r)){const p=B.get(s),f=B.get(a);throw new Error(`The source item type '${JSON.stringify(p)}' is not a subtype of the target item type '${JSON.stringify(f)}'.`)}i=i.cloneShallow().setItemType(s)}const l=i.getItemType(),c=t.getItems();if(l!==void 0&&c!==void 0)for(const d of c){const p=d.getType();if(p!==void 0&&!A(p,l,r)){const f=B.get(p),I=B.get(l);throw new Error(`Item of type '${JSON.stringify(f)}' is not a subtype of the list's item type '${JSON.stringify(I)}'.`)}}return i}processMergePolicy(e,t){const r=t.getMergePolicy(),i=e.getMergePolicy();if(this.validateMergePolicy(r),this.validateMergePolicy(i),i===void 0)return r===void 0?e:e.cloneShallow().setMergePolicy(r);if(r!==void 0&&r!==i)throw new Error(`Conflicting list mergePolicy values: target is "${i}" but source is "${r}".`);return e}validateMergePolicy(e){if(e!==void 0&&e!=="positional"&&e!=="append-only")throw new Error('mergePolicy must be either "positional" or "append-only".')}}class Ar{process(e,t,r){const i=t.getKeyType(),s=t.getValueType(),o=t.getType();if((i!==void 0||s!==void 0)&&o!==void 0&&!He(o,r))throw new Error("Source node with keyType or valueType must have a Dictionary type");let a=this.processKeyType(e,t,r);a=this.processValueType(a,t,r);const l=a.getKeyType(),c=a.getValueType(),d=t.getProperties();return(l!==void 0||c!==void 0)&&d!==void 0&&Object.entries(d).forEach(([p,f])=>{l!==void 0&&this.validateKeyType(p,l,r),c!==void 0&&this.validateValueType(f,c,r)}),a}processKeyType(e,t,r){const i=e.getKeyType(),s=t.getKeyType();if(i===void 0){if(s!==void 0)return this.validateBasicKeyType(s,r),e.cloneShallow().setKeyType(s)}else if(s!==void 0){if(this.validateBasicKeyType(s,r),!A(s,i,r)){const a=B.get(s),l=B.get(i);throw new Error(`The source key type '${JSON.stringify(a)}' is not a subtype of the target key type '${JSON.stringify(l)}'.`)}return e.cloneShallow().setKeyType(s)}return e}processValueType(e,t,r){const i=e.getValueType(),s=t.getValueType();if(i===void 0){if(s!==void 0)return e.cloneShallow().setValueType(s)}else if(s!==void 0){if(!A(s,i,r)){const a=B.get(s),l=B.get(i);throw new Error(`The source value type '${JSON.stringify(a)}' is not a subtype of the target value type '${JSON.stringify(l)}'.`)}return e.cloneShallow().setValueType(s)}return e}validateBasicKeyType(e,t){if(!xi(e,t))throw new Error(`Dictionary key type must be a basic type: ${JSON.stringify(B.get(e))}`)}validateKeyType(e,t,r){if(!_i(t,r))if(Fi(t,r)){const i=Number.parseInt(e,10);if(Number.isNaN(i)||i.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(Ui(t,r)){const i=Number.parseFloat(e);if(Number.isNaN(i))throw new Error(`Key '${e}' is not a valid Number.`)}else if(zi(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 i=e.getType();if(i!==void 0&&!A(i,t,r)){const s=B.get(i),o=B.get(t);throw new Error(`Value of type '${JSON.stringify(s)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}const ts=new Set(["minLength","minimum","exclusiveMinimum","minItems","minFields"]),rs=new Set(["maxLength","maximum","exclusiveMaximum","maxItems","maxFields"]),is=new Set(["required","uniqueItems"]);class Or{process(e,t){const r=t.getSchema();if(r===void 0)return e;const i=e.getSchema()?.clone()??new je;for(const s of ut){const o=r.get(s);if(o===void 0)continue;const a=i.get(s);i.set(s,this.propagateField(s,a,o))}return i.setEnum(this.propagateEnum(i.getEnum(),r.getEnum())),e.cloneShallow().setSchema(i)}propagateField(e,t,r){return t===void 0?r.clone():is.has(e)?r.getValue()===!0?r.clone():t.clone():e==="multipleOf"?this.multipleOf(t,r):ts.has(e)?this.numericValue(r)>this.numericValue(t)?r.clone():t.clone():rs.has(e)?this.numericValue(r)<this.numericValue(t)?r.clone():t.clone():r.clone()}multipleOf(e,t){const r=this.numericValue(e),i=this.numericValue(t);return Number.isInteger(r)&&Number.isInteger(i)?new h().setValue(Number(ns(BigInt(r),BigInt(i)))):i>r?t.clone():e.clone()}propagateEnum(e,t){if(t===void 0)return e?.map(i=>i.clone());if(e===void 0)return this.canonicalizeEnum(t);const r=new Map(e.map(i=>[this.enumComparableBlueId(i),i]));return this.canonicalizeEnum(t.flatMap(i=>{const s=r.get(this.enumComparableBlueId(i));return s===void 0?[]:[s]}))}canonicalizeEnum(e){const t=new Map;for(const r of e)t.set(this.enumComparableBlueId(r),r.clone());return[...t.values()].sort((r,i)=>this.enumCanonicalKey(r).localeCompare(this.enumCanonicalKey(i)))}enumComparableBlueId(e){const t=e.clone();return t.setSchema(void 0),b.calculateBlueIdSync(t)}enumCanonicalKey(e){const t=e.clone();return t.setSchema(void 0),JSON.stringify(ne.get(t))}numericValue(e){const t=e.getValue();if(typeof t=="number")return t;if(t!=null&&"toString"in Object(t))return Number(t.toString());throw new Error("Schema keyword value must be numeric.")}}function ss(n,e){let t=n<0n?-n:n,r=e<0n?-e:e;for(;r!==0n;){const i=t%r;t=r,r=i}return t}function ns(n,e){return n===0n||e===0n?0n:n/ss(n,e)*e}class Mr{process(e){return e}postProcess(e){const t=e.getSchema();return t===void 0||(this.verifyMultipleOfKeyword(t),this.verifyTextLength("minLength",t.get("minLength"),e),this.verifyTextLength("maxLength",t.get("maxLength"),e),this.verifyMultipleOf(t.get("multipleOf"),e),this.verifyEnum(t.getEnum(),e)),e}verifyMultipleOfKeyword(e){const t=e.get("multipleOf");if(t!==void 0&&this.numericValue(t)<=0)throw new Error('Schema keyword "multipleOf" must be greater than zero.')}verifyTextLength(e,t,r){if(t===void 0)return;const i=r.getValue();if(i==null){if(!this.hasPayload(r))return;throw this.wrongKind(e,"Text scalar")}if(typeof i!="string")throw this.wrongKind(e,"Text scalar");const s=Array.from(i).length,o=this.numericValue(t);if(e==="minLength"&&s<o)throw new Error(`Value "${i}" is shorter than the minimum length of ${o}.`);if(e==="maxLength"&&s>o)throw new Error(`Value "${i}" is longer than the maximum length of ${o}.`)}verifyMultipleOf(e,t){if(e===void 0)return;const r=t.getValue();if(r==null){if(!this.hasPayload(t))return;throw this.wrongKind("multipleOf","numeric scalar")}if(!this.isNumeric(r))throw this.wrongKind("multipleOf","numeric scalar");if(!nr.isExactBinary64Multiple(r,e.getValue()))throw new Error(`Value ${String(r)} is not a multiple of ${String(e.getValue())}.`)}verifyEnum(e,t){if(e===void 0||t.getValue()===void 0)return;const r=this.comparableBlueId(t);if(!e.some(i=>this.comparableBlueId(i)===r))throw new Error("Node value is not one of the allowed enum values.")}comparableBlueId(e){const t=e.clone();return t.setName(void 0),t.setDescription(void 0),t.setSchema(void 0),b.calculateBlueIdSync(t)}hasPayload(e){return e.getValue()!==void 0&&e.getValue()!==null||e.getItems()!==void 0||Object.keys(e.getProperties()??{}).length>0}isNumeric(e){return typeof e=="number"||e!=null&&"toString"in Object(e)}numericValue(e){const t=e.getValue();if(!this.isNumeric(t))throw this.wrongKind("schema","numeric scalar");return Number(t?.toString())}wrongKind(e,t){return new Error(`Schema keyword "${e}" applies to wrong kind; expected ${t}.`)}}class Vr{process(e){return e}postProcess(e,t,r){const i=e.getType();if(i!==void 0&&ji(i,r)){const s=e.getItems(),o=e.getProperties();if(s!==void 0&&s.length>0||o!==void 0&&Object.keys(o).length>0){const a=$i(i,r),l=i.getName()||"unknown";throw new Error(`Node of type "${l}" (which extends basic type "${a}") must not have items, properties or contracts.`)}}return e}}class Dr{process(e,t){let r=e;const i=t.getName();i!==void 0&&i!==e.getName()&&(r=r.cloneShallow().setName(i));const s=t.getDescription();return s!==void 0&&s!==r.getDescription()&&(r=r.cloneShallow().setDescription(s)),r}}function _t(){return new wr([new Sr,new Cr,new Rr,new Ar,new Or,new Mr,new Dr,new Vr])}class Ye{nodeProvider;mergingProcessor;minimizer=new Pt;cyclicSetIdentity;constructor(e={}){this.nodeProvider=e.nodeProvider??Lt(()=>[]),this.mergingProcessor=e.mergingProcessor??_t(),this.cyclicSetIdentity=this.createCyclicSetIdentityService()}createCyclicSetIdentityService(){return new x({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 Q&&e.getCompleteness()==="path-limited"){const t=e.getSourceSemanticBlueId();if(t!==void 0)return new h().setReferenceBlueId(t);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return R.hasBlueIdOnly(e)?e.clone():e.isResolved()?this.minimizeResolved(e):this.minimizeAuthoring(e)}minimizeResolved(e){if(e instanceof Q&&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 pe(this.mergingProcessor,t).resolve(e,F);return this.minimizeResolved(r)}hashMinimalTrusted(e){return this.hashMinimalTrustedWithProvider(e,this.nodeProvider)}hashMinimalTrustedWithProvider(e,t){return Array.isArray(e)?(Ee.validateStorageListShape(e),b.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t))):(Ee.validateStorageShape(e),b.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t)))}hashMinimalTrustedAsync(e){return Array.isArray(e)?(Ee.validateStorageListShape(e),b.calculateBlueId(this.toHashableMinimalTrusted(e))):(Ee.validateStorageShape(e),b.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(!P.hasPositionControl(e))return e;const r=new pe(this.mergingProcessor,t).resolve(e,F);return this.minimizer.minimizeResolvedForHash(r)}prepareCyclicDocument(e){return this.minimizeAuthoringWithProvider(e,this.createCyclicReferenceNodeProvider())}hashCyclicPrepared(e){return b.calculateBlueIdAllowingCyclicPlaceholdersSync(this.toHashableMinimalTrusted(e,this.createCyclicReferenceNodeProvider()))}createCyclicReferenceNodeProvider(){const e=this.nodeProvider;return oe.unverified(new class extends ue{fetchByBlueId(t){return t===x.ZERO_BLUE_ID||x.isIndexedThisReference(t)?[new h().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)&&x.hasThisReference([e]))throw new Error("Direct cyclic references using 'this#k' are supported only in a top-level document set.");return}if(x.hasThisReference(t))return this.cyclicSetIdentity.calculate(t).blueId}getTopLevelSetItems(e){if(Array.isArray(e))return e;if(R.hasItemsOnly(e))return e.getItems()??[]}toMinimalListIdentityInput(e){if(Ee.validateListControlShape(e),e[0]!==void 0&&P.isPreviousItem(e[0]))return e.map(i=>i.clone());const t=new h().setItems(e);return this.minimizeAuthoring(t).getItems()??[]}}class Lr{static convertValue(e,t){const r=e.getType()?.getBlueId(),i=e.getValue();return u.isNullable(i)?Oi(t)&&R.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):i:z===r?this.convertFromString(String(i),t):_===r||i instanceof V?this.convertFromBigDecimal(new V(i?.toString()),t):j===r||i instanceof S?this.convertFromBigInteger(new S(i?.toString()),t):K===r||typeof i=="boolean"?this.convertFromBoolean(!!i,t):this.convertFromString(String(i),t)}static convertFromString(e,t){if(!t)return e;const r=Se(t);if(r==="ZodString"||r==="ZodEnum"||r==="ZodNativeEnum")return e;if(r==="ZodNumber")return Number(e);if(r==="ZodBoolean")return e.toLowerCase()==="true";if(r==="ZodBigInt")return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){const r=Se(t);if(r==="ZodNumber")return e.toNumber();if(r==="ZodString")return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){const r=Se(t);if(r==="ZodNumber")return e.toNumber();if(r==="ZodBigInt")return BigInt(e.toString());if(r==="ZodString")return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t)return e;const r=Se(t);if(r==="ZodBoolean")return e;if(r==="ZodString")return e.toString();if(r==="ZodNumber")return Number(e);if(r==="ZodBigInt")return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;const t=Se(e);if(t==="ZodNumber")return 0;if(t==="ZodBoolean")return!1;if(t==="ZodString")return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}function Se(n){return String(n._def.typeName)}class os{convert(e,t){return Lr.convertValue(e,t)}}class as{constructor(e,t){this.nodeToObjectConverter=e,this.calculateBlueId=t}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(Bt(t)==="ZodIntersection"){const r=t,i=r._def.left,s=r._def.right,o=this.convert(e,i),a=this.convert(e,s);return{...o,...a}}if(Bt(t)==="ZodUnion")throw new Error("Union not supported");if(Bt(t)==="ZodObject"){const r=t;return Object.keys(r.shape).reduce((s,o)=>{const a=e.getProperties(),l=r.shape[o],c=ur(l);if(u.isNonNullable(c)){const v=ve.isString(c)?c:o,E=a?.[v],L=E?this.calculateBlueId(E):void 0;return s[o]=L,s}const d=hr(l);if(u.isNonNullable(d)){const v=a?.[d];return s[o]=v?.getName(),s}const p=lr(l);if(u.isNonNullable(p)){const v=a?.[p];return s[o]=v?.getDescription(),s}if(o==="name"){const v=e.getName();return s[o]=v,s}if(o==="description"){const v=e.getDescription();return s[o]=v,s}const f=a?.[o];if(u.isNullable(f))return s;const I=this.nodeToObjectConverter.convert(f,l);return s[o]=I,s},{})}throw new Error("Unknown schema type, "+t._def.typeName)}}function Bt(n){return String(n._def.typeName)}class ls{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const i=t.element??t._def.type;return r.map(o=>this.nodeToObjectConverter.convert(o,i))}}class cs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const i=t._def.valueType,s=r.map(o=>this.nodeToObjectConverter.convert(o,i));return new Set(s)}}class us{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,i=t.valueSchema,s=new Map,o=e.getName();u.isNonNullable(o)&&s.set(ae,o);const a=e.getDescription();u.isNonNullable(a)&&s.set(le,a);const l=e.getProperties();return u.isNonNullable(l)&&Object.entries(l).forEach(([c,d])=>{const p=new h().setValue(c);p.setType(new h().setBlueId(z));const f=Lr.convertValue(p,r),I=this.nodeToObjectConverter.convert(d,i);s.set(f,I)}),t instanceof m.ZodRecord?Object.fromEntries(s):s}}class ds{convert(e){return B.get(e)}}class hs{convert(e){return B.get(e)}}class ps{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const i=t.items;return r.map((o,a)=>this.nodeToObjectConverter.convert(o,i[a]))}}const fs=m.z.union([m.z.literal("ZodString"),m.z.literal("ZodNumber"),m.z.literal("ZodBoolean"),m.z.literal("ZodBigInt"),m.z.literal("ZodArray"),m.z.literal("ZodSet"),m.z.literal("ZodMap"),m.z.literal("ZodRecord"),m.z.literal("ZodObject"),m.z.literal("ZodEnum"),m.z.literal("ZodNativeEnum"),m.z.literal("ZodUnknown"),m.z.literal("ZodAny"),m.z.literal("ZodTuple")]);class ms{constructor(e,t){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new as(this.nodeToObjectConverter,t)}converters=new Map;complexObjectConverter;registerConverters(){const e=new os,t=new ls(this.nodeToObjectConverter),r=new ps(this.nodeToObjectConverter),i=new cs(this.nodeToObjectConverter),s=new us(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 ds),this.converters.set("ZodAny",new hs),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",i),this.converters.set("ZodMap",s),this.converters.set("ZodRecord",s),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){const t=String(e._def.typeName);if(t==="ZodEffects")return this.getSchemaTypeName(e.innerType());if(t==="ZodLazy")return this.getSchemaTypeName(e.schema);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodReadonly"||t==="ZodBranded"||yr(e))return this.getSchemaTypeName(e.unwrap());try{return fs.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class xr{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 ms(this,this.calculateBlueId)}converterFactory;calculateBlueId;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),i=J.unwrapSchema(t);if(Dt(i))return e;let s=i;return J.checkSchemaExtension(r,i,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(s=r),this.convertWithType(e,s)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class ys{static get(e,t={}){const{strategy:r="official"}=t,i=B.get(e,r);return Er(i)}}function Me(n){try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}class gs{process(e){return D.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 h().setBlueId(z)):typeof r=="bigint"||Y(r)?e.setType(new h().setBlueId(j)):Je(r)?e.setType(new h().setBlueId(_)):typeof r=="boolean"&&e.setType(new h().setBlueId(K))),e}}class Fe{static MAPPINGS="mappings";mappings=new Map;constructor(e){if(e instanceof h){const r=e.getProperties();if(r&&r[Fe.MAPPINGS]){const s=r[Fe.MAPPINGS].getProperties();s&&Object.entries(s).forEach(([o,a])=>{const l=a.getValue();typeof l=="string"&&this.mappings.set(o,l)})}}else this.mappings=e}process(e){return D.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 i=this.mappings.get(r);if(i){const s=new h().setBlueId(i);t===e.getType()?e.setType(s):t===e.getItemType()?e.setItemType(s):t===e.getKeyType()?e.setKeyType(s):t===e.getValueType()&&e.setValueType(s)}}}}}class Is{process(e){return D.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 i=String(t.getValue());throw new Error(`Unknown type "${i}" found in ${r} field. No BlueId mapping exists for this type.`)}}}class _r{blueIdsCollections=[];initialize(...e){this.blueIdsCollections=[...e]}registerBlueIds(...e){this.blueIdsCollections.push(...e)}generateMappingsYaml(e="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo"){const t={};for(const i of this.blueIdsCollections)Object.assign(t,i);const r=Object.entries(t).map(([i,s])=>` ${i}: ${s}`).join(`
|
|
40
40
|
`);return`- type:
|
|
41
41
|
blueId: ${e}
|
|
42
42
|
mappings:
|
|
43
|
-
${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 Ue{static DEFAULT_BLUE_BLUE_ID="EsyNgNY4ZZeCvWiGLQM52WPJ7HF5kz3DyCoxdDDaauc6";processorProvider;nodeProvider;defaultSimpleBlue=null;blueIdsMappingGenerator;constructor(e={}){const{nodeProvider:t,processorProvider:r,blueIdsMappingGenerator:i}=e;if(!t)throw new Error("NodeProvider is required");this.nodeProvider=oe.wrap(t),this.processorProvider=r||Ue.getStandardProvider(),this.blueIdsMappingGenerator=i||new _r,this.loadDefaultSimpleBlue()}preprocess(e){return this.preprocessWithOptions(e,null)}preprocessWithDefaultBlue(e){return this.preprocessWithOptions(e,this.defaultSimpleBlue)}preprocessWithOptions(e,t){let r=this.applyPortableImports(this.normalizeListPlaceholders(e.clone(),!1)),i=r.getBlue();if(!i&&t&&(i=t.clone()),i){new xt(this.nodeProvider).extend(i,ke.withSinglePath("/*"));const s=this.flattenTransformationItems(i.getItems());if(s&&s.length>0){for(const o of s){const a=this.processorProvider.getProcessor(o);if(a)r=a.process(r);else throw new Error(`No processor found for transformation: ${o}`)}r.setBlue(void 0)}r=new Is().process(r)}return r}applyPortableImports(e){const r=e.getBlue()?.getProperties()?.imports;if(r===void 0)return e;const i=r.getProperties();if(i===void 0||r.getValue()!==void 0||r.getItems()!==void 0||r.getReferenceBlueId()!==void 0)throw new Error("blue.imports must be an object mapping aliases to pure references.");const s=new Map;for(const[l,c]of Object.entries(i)){if(!this.isReferenceOnly(c))throw new Error(`blue.imports.${l} must be a pure reference.`);const d=G.requirePlainBlueId(c.getReferenceBlueId(),`blue.imports.${l}`),p=Ot[l];if(p!==void 0&&p!==d)throw new Error(`blue.imports cannot redefine default Blue alias "${l}".`);s.set(l,d)}const o=new Fe(s).process(e),a=o.getBlue();return a!==void 0&&(a.removeProperty("imports"),this.isEmptyNode(a)&&o.setBlue(void 0)),o}normalizeListPlaceholders(e,t){if(t&&this.isEmptyPlaceholder(e))return e.clone();if(t&&(this.isNullNode(e)||this.isEmptyNode(e)))return this.emptyPlaceholder();const r=e.clone(),i=r.getType();i!==void 0&&r.setType(this.normalizeListPlaceholders(i,!1));const s=r.getItemType();s!==void 0&&r.setItemType(this.normalizeListPlaceholders(s,!1));const o=r.getKeyType();o!==void 0&&r.setKeyType(this.normalizeListPlaceholders(o,!1));const a=r.getValueType();a!==void 0&&r.setValueType(this.normalizeListPlaceholders(a,!1));const l=r.getBlue();l!==void 0&&r.setBlue(this.normalizeListPlaceholders(l,!1));const c=r.getContractsNode();c!==void 0&&r.setContractsNode(this.normalizeListPlaceholders(c,!1));const d=r.getItems();d!==void 0&&r.setItems(d.map(f=>this.normalizeListPlaceholders(f,!0)));const p=r.getProperties();if(p!==void 0){const f=Object.fromEntries(Object.entries(p).flatMap(([I,v])=>{const E=this.normalizeListPlaceholders(v,!1);return this.isEmptyNode(E)||this.isNullNode(E)?[]:[[I,E]]}));r.setProperties(Object.keys(f).length===0?void 0:f)}return t&&this.isEmptyNode(r)?this.emptyPlaceholder():r}emptyPlaceholder(){return new h().addProperty(Ie,new h().setValue(!0))}isEmptyPlaceholder(e){const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&t[Ie]?.getValue()===!0}isNullNode(e){return e.getValue()===null&&e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0}isReferenceOnly(e){return e.getReferenceBlueId()!==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.getValue()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0}isEmptyNode(e){return 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.getValue()===void 0&&e.getItems()===void 0&&(e.getProperties()===void 0||Object.keys(e.getProperties()??{}).length===0)&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0}flattenTransformationItems(e){if(e!==void 0)return e.flatMap(t=>t.getItems()??[t])}static getStandardProvider(){return{getProcessor(e){const t="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo",r="FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4",i=e.getType()?.getBlueId();if(t===i)return new Fe(e);if(r===i)return new
|
|
43
|
+
${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 Ue{static DEFAULT_BLUE_BLUE_ID="EsyNgNY4ZZeCvWiGLQM52WPJ7HF5kz3DyCoxdDDaauc6";processorProvider;nodeProvider;defaultSimpleBlue=null;blueIdsMappingGenerator;constructor(e={}){const{nodeProvider:t,processorProvider:r,blueIdsMappingGenerator:i}=e;if(!t)throw new Error("NodeProvider is required");this.nodeProvider=oe.wrap(t),this.processorProvider=r||Ue.getStandardProvider(),this.blueIdsMappingGenerator=i||new _r,this.loadDefaultSimpleBlue()}preprocess(e){return this.preprocessWithOptions(e,null)}preprocessWithDefaultBlue(e){return this.preprocessWithOptions(e,this.defaultSimpleBlue)}preprocessWithOptions(e,t){let r=this.applyPortableImports(this.normalizeListPlaceholders(e.clone(),!1)),i=r.getBlue();if(!i&&t&&(i=t.clone()),i){new xt(this.nodeProvider).extend(i,ke.withSinglePath("/*"));const s=this.flattenTransformationItems(i.getItems());if(s&&s.length>0){for(const o of s){const a=this.processorProvider.getProcessor(o);if(a)r=a.process(r);else throw new Error(`No processor found for transformation: ${o}`)}r.setBlue(void 0)}r=new Is().process(r)}return r}applyPortableImports(e){const r=e.getBlue()?.getProperties()?.imports;if(r===void 0)return e;const i=r.getProperties();if(i===void 0||r.getValue()!==void 0||r.getItems()!==void 0||r.getReferenceBlueId()!==void 0)throw new Error("blue.imports must be an object mapping aliases to pure references.");const s=new Map;for(const[l,c]of Object.entries(i)){if(!this.isReferenceOnly(c))throw new Error(`blue.imports.${l} must be a pure reference.`);const d=G.requirePlainBlueId(c.getReferenceBlueId(),`blue.imports.${l}`),p=Ot[l];if(p!==void 0&&p!==d)throw new Error(`blue.imports cannot redefine default Blue alias "${l}".`);s.set(l,d)}const o=new Fe(s).process(e),a=o.getBlue();return a!==void 0&&(a.removeProperty("imports"),this.isEmptyNode(a)&&o.setBlue(void 0)),o}normalizeListPlaceholders(e,t){if(t&&this.isEmptyPlaceholder(e))return e.clone();if(t&&(this.isNullNode(e)||this.isEmptyNode(e)))return this.emptyPlaceholder();const r=e.clone(),i=r.getType();i!==void 0&&r.setType(this.normalizeListPlaceholders(i,!1));const s=r.getItemType();s!==void 0&&r.setItemType(this.normalizeListPlaceholders(s,!1));const o=r.getKeyType();o!==void 0&&r.setKeyType(this.normalizeListPlaceholders(o,!1));const a=r.getValueType();a!==void 0&&r.setValueType(this.normalizeListPlaceholders(a,!1));const l=r.getBlue();l!==void 0&&r.setBlue(this.normalizeListPlaceholders(l,!1));const c=r.getContractsNode();c!==void 0&&r.setContractsNode(this.normalizeListPlaceholders(c,!1));const d=r.getItems();d!==void 0&&r.setItems(d.map(f=>this.normalizeListPlaceholders(f,!0)));const p=r.getProperties();if(p!==void 0){const f=Object.fromEntries(Object.entries(p).flatMap(([I,v])=>{const E=this.normalizeListPlaceholders(v,!1);return this.isEmptyNode(E)||this.isNullNode(E)?[]:[[I,E]]}));r.setProperties(Object.keys(f).length===0?void 0:f)}return t&&this.isEmptyNode(r)?this.emptyPlaceholder():r}emptyPlaceholder(){return new h().addProperty(Ie,new h().setValue(!0))}isEmptyPlaceholder(e){const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&t[Ie]?.getValue()===!0}isNullNode(e){return e.getValue()===null&&e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0}isReferenceOnly(e){return e.getReferenceBlueId()!==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.getValue()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0}isEmptyNode(e){return 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.getValue()===void 0&&e.getItems()===void 0&&(e.getProperties()===void 0||Object.keys(e.getProperties()??{}).length===0)&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0}flattenTransformationItems(e){if(e!==void 0)return e.flatMap(t=>t.getItems()??[t])}static getStandardProvider(){return{getProcessor(e){const t="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo",r="FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4",i=e.getType()?.getBlueId();if(t===i)return new Fe(e);if(r===i)return new gs}}}enrichDefaultBlue(e){if(this.blueIdsMappingGenerator.getTotalBlueIdCount()===0)return e;const t=this.blueIdsMappingGenerator.generateMappingsYaml();return`
|
|
44
44
|
${e}
|
|
45
45
|
${t}
|
|
46
|
-
`}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(Pr),t=he(e);if(t)this.defaultSimpleBlue=
|
|
47
|
-
${i.message}`):i}else throw Me(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 h().setBlueId(this.preprocessingAliases.get(t))),e}handleBlueId(e,t){return e.setBlue(new h().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 Ts={fetchUrl:async n=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${n}`)}};class Bs{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||Ts}validateUrl(e){if(!Me(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(a){throw new Error(`Error fetching from URL: ${e}`,{cause:a})}const{data:r,contentType:i}=t;let s;if(i.includes("application/json")||i.includes("text/yaml")||i.includes("application/yaml")||i.includes("text/plain"))s=he(r);else throw new Error(`Unsupported content type from URL: ${i}`);if(s===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(s)?o=s.map(a=>g.deserialize(a)):o=[g.deserialize(s)],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 qe{constructor(e,t,r,i=[],s=!1){this.blueId=e,this.content=t,this.isMultipleDocuments=r,this.documentBlueIds=i,this.isCyclicSet=s}}class Ft{static THIS_REFERENCE_PATTERN=/^this(#\d+)?$/;static parseAndCalculateBlueId(e,t,r){let i;try{const l=he(e);if(l===void 0)throw new Error;i=l}catch{throw new Error("Failed to parse content as YAML or JSON")}let s,o;const a=Array.isArray(i);if(a){const l=i.map(d=>g.deserialize(d)),c=r.prepareStorageNodeList(l,t);return s=c.blueId,o=c.nodes.map(d=>B.get(d)),new qe(s,o,!0,c.documentBlueIds,c.isCyclicSet??!1)}else{const l=g.deserialize(i),c=r.prepareStorageNode(l,t);s=c.blueId,o=B.get(c.node)}return new qe(s,o,a)}static parseAndCalculateBlueIdForNode(e,t,r){const i=r.prepareStorageNode(e,t),s=B.get(i.node);return new qe(i.blueId,s,!1)}static parseAndCalculateBlueIdForNodeList(e,t,r){if(!e||e.length===0)throw new Error("List of nodes cannot be null or empty");const i=r.prepareStorageNodeList(e,t),s=i.nodes.map(a=>B.get(a)),o=!0;return new qe(i.blueId,s,o,i.documentBlueIds,i.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 i={};for(const[s,o]of Object.entries(e))typeof o=="string"?s===N&&this.THIS_REFERENCE_PATTERN.test(o)?i[s]=this.resolveThisReference(o,t,r):i[s]=o:o&&typeof o=="object"?i[s]=this.resolveThisReferencesRecursive(o,t,r):i[s]=o;return i}else if(Array.isArray(e))return e.map(i=>i&&typeof i=="object"?this.resolveThisReferencesRecursive(i,t,r):i);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 Es extends ue{fetchByBlueId(e){const t=e.split("#")[0],r=this.fetchContentByBlueId(t);if(r==null)return null;const i=Array.isArray(r),s=Ft.resolveThisReferences(r,t,i);if(e.includes("#")){const o=e.split("#");if(o.length>1){const a=parseInt(o[1]);if(Array.isArray(s)&&a<s.length){const l=s[a];return[g.deserialize(l)]}else return a===0?[g.deserialize(s)]:null}}return Array.isArray(s)?s.map(o=>g.deserialize(o)):[g.deserialize(s)]}}class Fr extends Es{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 i of t){const s=this.fetchByBlueId(i);s&&r.push(...s)}return r}addToNameMap(e,t){this.nameToBlueIdsMap.set(e,[...this.nameToBlueIdsMap.get(e)||[],t])}}const Ps=new Set(["required","uniqueItems"]),bs=new Set(["minLength","maxLength","minItems","maxItems","minFields","maxFields"]),Ns=[U,me,ge,ye],ws=new Map([["DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",z],["7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",_],["5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",j],["4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",K],["6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",ot],["G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",at]]),Ss=new Map([["AERp8BWnuUsjoPciAeNXuUWS9fmqPNMdWbxmKn3tcitx",Z.Contract],["Bz49DbfqKC1yJeCfv5RYPZUKTfb7rtZnmreCaz4RsXn5",Z["Json Patch Entry"]],["DcoJyCh7XXxy1nR5xjy7qfkUgQ1GiZnKKSxh8DJusBSr",Z.Channel],["9ZE5pGjtSGJgWJG7iAVz4iPEz5CatceX3yb3qp5MpAKJ",Z.Handler],["7QACj919YMRvFCTELCf6jfQTp41RVhtHdE6bPazLUZQ6",Z.Marker],["BrpmpNt5JkapeUvPqYcxgXZrHNZX3R757dRwuXXdfNM2",Z["Document Processing Initiated"]],["C77W4kVGcxL7Mkx9WL9QESPEFFL2GzWAe647s1Efprt",Z["Triggered Event Channel"]],["H2aCCTUcLMTJozWkn7HPUjyFBFxamraw1q8DyWk87zxr",Z["Lifecycle Event Channel"]]]),Ur=new Map([...ws,...Ss]);function bt(n){const e=tt(n);return Array.isArray(e)?Cs(e):e}function Cs(n){const e=n.map(t=>g.deserialize(t));return x.hasIndexedThisReference(e)?Rs(e):n}function Rs(n){return new x().calculate(n).nodes.map(t=>tt(B.get(t)))}function tt(n){if(Array.isArray(n))return n.map(s=>tt(s));if(!q(n))return n;const e=Object.fromEntries(Object.entries(n).map(([s,o])=>[s,tt(o)])),t=e[N];typeof t=="string"&&(e[N]=Ur.get(t)??t);for(const s of Ns){const o=e[s];o!==void 0&&(e[s]=Ls(o))}const r=As(e);if(r!==void 0)return r;const i=e[y.OBJECT_SCHEMA];return q(i)&&(e[y.OBJECT_SCHEMA]=Vs(i)),e}function As(n){if(!Os(n))return;const e=n[X];return typeof e=="string"?Ms(e):void 0}function Os(n){const e=n[U];return q(e)&&e[N]===z&&typeof n[X]=="string"}function Ms(n){const t=n.trim().match(/^\$\{\s*(.*)\s*\}$/u);if(!t)return;const r=t[1].trim(),i=r.match(/^document\(['"]([^'"]+)['"]\)$/u);if(i)return{$document:zr(i[1])};if(r==="event")return{$event:"/"};if(r.startsWith("event."))return{$event:qt(r.slice(6))};if(r==="currentContract")return{$currentContract:"/"};if(r.startsWith("currentContract."))return{$currentContract:qt(r.slice(16))};if(r.startsWith("steps."))return{$steps:r.slice(6)}}function zr(n){return n.startsWith("/")?n:`/${n}`}function qt(n){return zr(n.split(".").map(e=>e.replace(/~/gu,"~0").replace(/\//gu,"~1")).join("/"))}function Vs(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Ds(e,t)]))}function Ds(n,e){if(n==="enum"&&q(e)){const t=e[Te];if(Array.isArray(t))return t}return(Ps.has(n)||bs.has(n))&&q(e)&&Object.prototype.hasOwnProperty.call(e,X)?e[X]:e}function Ls(n){if(!q(n)||Object.keys(n).length!==1)return n;const t=n[U];if(!q(t))return n;const r=t[N];if(typeof r!="string")return n;const i=Ur.get(r)??r;return ie.includes(i)?{[N]:i}:n}class Ve extends Fr{[br]=!0;blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;aliasBlueIdMap=new Map;constructor(e,t={}){super();const r=Ve.collectAliasMappings(e);this.aliasBlueIdMap=new Map(Object.entries(r)),this.loadRepositories(e)}static collectAliasMappings(e){const t={};for(const r of e)for(const i of Object.values(r.packages))for(const[s,o]of Object.entries(i.aliases)){const a=t[s];if(a&&a!==o)throw new Error(`Conflicting alias mapping for ${s}`);t[s]=o}return t}loadRepositories(e){const t=[],r=new Map;for(const i of e)Object.values(i.packages).forEach(s=>{for(const[o,a]of Object.entries(s.contents)){const l=Ve.parseCyclicBlueId(o);if(!l){t.push({providedBlueId:o,content:a});continue}const c=r.get(l.baseBlueId)??[];c.push({index:l.index,content:a}),r.set(l.baseBlueId,c)}});t.forEach(({content:i,providedBlueId:s})=>{const o=bt(i);this.storeContent(s,o,Array.isArray(o)),this.addContentNames(s,o)});for(const[i,s]of r){const o=Ve.toDenseCyclicContent(i,s),a=bt(o);this.storeContent(i,a,!0),this.addContentNames(i,a)}}static parseCyclicBlueId(e){const t=/^(.*)#(\d+)$/.exec(e);return!t?.[1]||t[2]===void 0?null:{baseBlueId:t[1],index:Number.parseInt(t[2],10)}}static toDenseCyclicContent(e,t){return[...t].sort((i,s)=>i.index-s.index).map((i,s)=>{if(i.index!==s)throw new Error(`Cyclic repository content for ${e} is missing index ${s}.`);return i.content})}addContentNames(e,t){if(Array.isArray(t)){this.addListItemNames(e,t);return}const i=g.deserialize(t).getName();i&&this.addToNameMap(i,e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,i)=>{const o=g.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${i}`)})}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?Ft.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:i}=this.getBaseBlueIdAndSuffix(e);if(i===void 0)return e;const s=this.aliasBlueIdMap.get(r);if(s===void 0)return e;if(this.getBaseBlueIdAndSuffix(s).suffix===void 0)return`${s}${i}`}getBaseBlueIdAndSuffix(e){const t=e.indexOf("#");return t===-1?{baseBlueId:e}:{baseBlueId:e.slice(0,t),suffix:e.slice(t)}}}class xs{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(ct).forEach(([s,o])=>{this.blueIdToInlineValue.set(s,o)});const i=r.getAllBlueIds();Object.entries(i).forEach(([s,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,s)})}restore(e){return M.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 i=t();if(!i||i.isInlineValue()&&i.getValue()!==void 0)return;const s=i.getBlueId();if(!s)return;const o=this.resolveInlineValue(s,i);if(!o)return;const a=new h().setValue(o).setInlineValue(!0);r(a)}resolveInlineValue(e,t){const r=this.blueIdToInlineValue.get(e);if(r)return r;const i=t.getName();if(i)return this.blueIdToInlineValue.set(e,i),i;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class _s{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(Fs(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)Ws(this.contents,r.contents,r.name),Ys(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]??Ot[e]??e;for(const r of this.runtimes){const i=r.toCurrentBlueIdIndex[t];if(i)return i}return t}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=tr[t];if(r)return r;for(const i of this.runtimes){const s=i.typeAliasByCurrentBlueId[t];if(s)return s}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const i=r.types[t];if(i)return{runtime:r,currentBlueId:t,typeMeta:i,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function Fs(n){const e=Us(n);return Object.values(n.packages).forEach(t=>{zs(e,n,t)}),{name:n.name,repositoryVersions:n.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 Us(n){const e=Object.fromEntries(n.repositoryVersions.map((r,i)=>[r,i])),t=n.repositoryVersions[n.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function zs(n,e,t){if(n.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);n.packageNames.add(t.name),js(n,t),$s(n,e,t),ks(n,t),qs(n,t)}function js(n,e){Object.entries(e.aliases).forEach(([t,r])=>{if(n.aliases[t]&&n.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);n.aliases[t]=r})}function $s(n,e,t){Object.entries(t.typesMeta).forEach(([r,i])=>{if(n.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const s=Ks(i,e,r,t.name);if(n.types[r]=s,n.typePackageByCurrentBlueId[r]=t.name,n.typeAliasByCurrentBlueId[r]=`${t.name}/${i.name}`,s.status===y.BLUE_REPOSITORY_STATUS_STABLE&&!n.toCurrentBlueIdIndex[r]&&(n.toCurrentBlueIdIndex[r]=r),s.status===y.BLUE_REPOSITORY_STATUS_STABLE)for(const o of s.versions){const a=n.toCurrentBlueIdIndex[o.typeBlueId];if(a&&a!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);n.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function ks(n,e){Object.entries(e.contents).forEach(([t,r])=>{n.contents[t]=r})}function qs(n,e){n.schemas.push(...Object.values(e.schemas))}function Ks(n,e,t,r){if(n.status===y.BLUE_REPOSITORY_STATUS_DEV)return Gs(n,e,t,r),{...n,versions:n.versions?[...n.versions]:n.versions};const i=[...n.versions??[]].sort((o,a)=>o.repositoryVersionIndex-a.repositoryVersionIndex);if(i.length===0)throw new Error(`Stable type ${r}/${n.name} (${t}) must have at least one version entry`);const s=new Set;return i.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${n.name}`);if(s.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${n.name}`);s.add(o.repositoryVersionIndex);for(const a of o.attributesAdded??[])Hs(a,e.name,t,o.repositoryVersionIndex)}),{...n,versions:i}}function Gs(n,e,t,r){if(n.status===y.BLUE_REPOSITORY_STATUS_DEV){if(n.versions&&n.versions.length>1)throw new Error(`Dev type ${r}/${n.name} (${t}) must not declare multiple versions`);if(n.versions&&n.versions.length===1){const i=n.versions[0];if(i.repositoryVersionIndex<0||i.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${i.repositoryVersionIndex} for dev type ${r}/${n.name}`)}}}function Hs(n,e,t,r){try{y.validateAttributesAddedPointer(n)}catch(i){const s=i instanceof Error?i.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${n}' for type ${t} in repository ${e} at index ${r}: ${s}`)}}function Ys(n,e,t){for(const[r,i]of Object.entries(e)){const s=n[r];if(s&&s!==i)throw new Error(`Conflicting alias '${r}' across repositories: '${s}' vs '${i}' (from ${t})`);n[r]=i}}function Ws(n,e,t){for(const[r,i]of Object.entries(e)){if(r in n){const s=n[r];if(!Zs(s,i))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}n[r]=i}}function Zs(n,e){if(n===e)return!0;if(n===null||e===null||typeof n!="object"||typeof e!="object")return!1;const t=Qe.canonicalize(n),r=Qe.canonicalize(e);return t!==void 0&&t===r}const ht={"6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF":{name:"Contract",description:`Base Blue Contracts and Processor 1.0 runtime type for executable or processor-interpreted declarations under an active scope's contracts map. A Contract is scope-local, identity-bearing Blue content. The processor discovers materialized contract entries in the selected document, resolves each entry far enough to identify its effective runtime type BlueId, and either executes supported behavior or applies must-understand and fatal rules. Contract entries are sorted by effective order and contract-map key when ordering is required. A Contract by itself has no executable behavior; concrete subtypes define Channel, Handler, Marker, or extension semantics.
|
|
46
|
+
`}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(Pr),t=he(e);if(t)this.defaultSimpleBlue=y.deserialize(t);else throw new Error("Failed to parse default Blue content")}catch(e){throw new Error(`Error loading default Blue: ${e}`)}}}class vs{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(G.isPotentialBlueId(t))return this.handleBlueId(r,t);throw Me(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(G.isPotentialBlueId(t))return this.handleBlueId(r,t);if(Me(t)&&this.urlContentFetcher)try{const i=await this.fetchFromUrl(t);return i&&r.setBlue(new h().setItems(i)),r}catch(i){throw i instanceof Error?new Error(`Failed to fetch from URL '${t}'.
|
|
47
|
+
${i.message}`):i}else throw Me(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 h().setBlueId(this.preprocessingAliases.get(t))),e}handleBlueId(e,t){return e.setBlue(new h().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 Ts={fetchUrl:async n=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${n}`)}};class Bs{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||Ts}validateUrl(e){if(!Me(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(a){throw new Error(`Error fetching from URL: ${e}`,{cause:a})}const{data:r,contentType:i}=t;let s;if(i.includes("application/json")||i.includes("text/yaml")||i.includes("application/yaml")||i.includes("text/plain"))s=he(r);else throw new Error(`Unsupported content type from URL: ${i}`);if(s===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(s)?o=s.map(a=>y.deserialize(a)):o=[y.deserialize(s)],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 qe{constructor(e,t,r,i=[],s=!1){this.blueId=e,this.content=t,this.isMultipleDocuments=r,this.documentBlueIds=i,this.isCyclicSet=s}}class Ft{static THIS_REFERENCE_PATTERN=/^this(#\d+)?$/;static parseAndCalculateBlueId(e,t,r){let i;try{const l=he(e);if(l===void 0)throw new Error;i=l}catch{throw new Error("Failed to parse content as YAML or JSON")}let s,o;const a=Array.isArray(i);if(a){const l=i.map(d=>y.deserialize(d)),c=r.prepareStorageNodeList(l,t);return s=c.blueId,o=c.nodes.map(d=>B.get(d)),new qe(s,o,!0,c.documentBlueIds,c.isCyclicSet??!1)}else{const l=y.deserialize(i),c=r.prepareStorageNode(l,t);s=c.blueId,o=B.get(c.node)}return new qe(s,o,a)}static parseAndCalculateBlueIdForNode(e,t,r){const i=r.prepareStorageNode(e,t),s=B.get(i.node);return new qe(i.blueId,s,!1)}static parseAndCalculateBlueIdForNodeList(e,t,r){if(!e||e.length===0)throw new Error("List of nodes cannot be null or empty");const i=r.prepareStorageNodeList(e,t),s=i.nodes.map(a=>B.get(a)),o=!0;return new qe(i.blueId,s,o,i.documentBlueIds,i.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 i={};for(const[s,o]of Object.entries(e))typeof o=="string"?s===N&&this.THIS_REFERENCE_PATTERN.test(o)?i[s]=this.resolveThisReference(o,t,r):i[s]=o:o&&typeof o=="object"?i[s]=this.resolveThisReferencesRecursive(o,t,r):i[s]=o;return i}else if(Array.isArray(e))return e.map(i=>i&&typeof i=="object"?this.resolveThisReferencesRecursive(i,t,r):i);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 Es extends ue{fetchByBlueId(e){const t=e.split("#")[0],r=this.fetchContentByBlueId(t);if(r==null)return null;const i=Array.isArray(r),s=Ft.resolveThisReferences(r,t,i);if(e.includes("#")){const o=e.split("#");if(o.length>1){const a=parseInt(o[1]);if(Array.isArray(s)&&a<s.length){const l=s[a];return[y.deserialize(l)]}else return a===0?[y.deserialize(s)]:null}}return Array.isArray(s)?s.map(o=>y.deserialize(o)):[y.deserialize(s)]}}class Fr extends Es{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 i of t){const s=this.fetchByBlueId(i);s&&r.push(...s)}return r}addToNameMap(e,t){this.nameToBlueIdsMap.set(e,[...this.nameToBlueIdsMap.get(e)||[],t])}}const Ps=new Set(["required","uniqueItems"]),bs=new Set(["minLength","maxLength","minItems","maxItems","minFields","maxFields"]),Ns=[U,me,ye,ge],ws=new Map([["DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",z],["7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",_],["5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",j],["4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",K],["6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",ot],["G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",at]]),Ss=new Map([["AERp8BWnuUsjoPciAeNXuUWS9fmqPNMdWbxmKn3tcitx",Z.Contract],["Bz49DbfqKC1yJeCfv5RYPZUKTfb7rtZnmreCaz4RsXn5",Z["Json Patch Entry"]],["DcoJyCh7XXxy1nR5xjy7qfkUgQ1GiZnKKSxh8DJusBSr",Z.Channel],["9ZE5pGjtSGJgWJG7iAVz4iPEz5CatceX3yb3qp5MpAKJ",Z.Handler],["7QACj919YMRvFCTELCf6jfQTp41RVhtHdE6bPazLUZQ6",Z.Marker],["BrpmpNt5JkapeUvPqYcxgXZrHNZX3R757dRwuXXdfNM2",Z["Document Processing Initiated"]],["C77W4kVGcxL7Mkx9WL9QESPEFFL2GzWAe647s1Efprt",Z["Triggered Event Channel"]],["H2aCCTUcLMTJozWkn7HPUjyFBFxamraw1q8DyWk87zxr",Z["Lifecycle Event Channel"]]]),Ur=new Map([...ws,...Ss]);function bt(n){const e=tt(n);return Array.isArray(e)?Cs(e):e}function Cs(n){const e=n.map(t=>y.deserialize(t));return x.hasIndexedThisReference(e)?Rs(e):n}function Rs(n){return new x().calculate(n).nodes.map(t=>tt(B.get(t)))}function tt(n){if(Array.isArray(n))return n.map(s=>tt(s));if(!q(n))return n;const e=Object.fromEntries(Object.entries(n).map(([s,o])=>[s,tt(o)])),t=e[N];typeof t=="string"&&(e[N]=Ur.get(t)??t);for(const s of Ns){const o=e[s];o!==void 0&&(e[s]=Ls(o))}const r=As(e);if(r!==void 0)return r;const i=e[g.OBJECT_SCHEMA];return q(i)&&(e[g.OBJECT_SCHEMA]=Vs(i)),e}function As(n){if(!Os(n))return;const e=n[X];return typeof e=="string"?Ms(e):void 0}function Os(n){const e=n[U];return q(e)&&e[N]===z&&typeof n[X]=="string"}function Ms(n){const t=n.trim().match(/^\$\{\s*(.*)\s*\}$/u);if(!t)return;const r=t[1].trim(),i=r.match(/^document\(['"]([^'"]+)['"]\)$/u);if(i)return{$document:zr(i[1])};if(r==="event")return{$event:"/"};if(r.startsWith("event."))return{$event:qt(r.slice(6))};if(r==="currentContract")return{$currentContract:"/"};if(r.startsWith("currentContract."))return{$currentContract:qt(r.slice(16))};if(r.startsWith("steps."))return{$steps:r.slice(6)}}function zr(n){return n.startsWith("/")?n:`/${n}`}function qt(n){return zr(n.split(".").map(e=>e.replace(/~/gu,"~0").replace(/\//gu,"~1")).join("/"))}function Vs(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Ds(e,t)]))}function Ds(n,e){if(n==="enum"&&q(e)){const t=e[Te];if(Array.isArray(t))return t}return(Ps.has(n)||bs.has(n))&&q(e)&&Object.prototype.hasOwnProperty.call(e,X)?e[X]:e}function Ls(n){if(!q(n)||Object.keys(n).length!==1)return n;const t=n[U];if(!q(t))return n;const r=t[N];if(typeof r!="string")return n;const i=Ur.get(r)??r;return ie.includes(i)?{[N]:i}:n}class Ve extends Fr{[br]=!0;blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;aliasBlueIdMap=new Map;constructor(e,t={}){super();const r=Ve.collectAliasMappings(e);this.aliasBlueIdMap=new Map(Object.entries(r)),this.loadRepositories(e)}static collectAliasMappings(e){const t={};for(const r of e)for(const i of Object.values(r.packages))for(const[s,o]of Object.entries(i.aliases)){const a=t[s];if(a&&a!==o)throw new Error(`Conflicting alias mapping for ${s}`);t[s]=o}return t}loadRepositories(e){const t=[],r=new Map;for(const i of e)Object.values(i.packages).forEach(s=>{for(const[o,a]of Object.entries(s.contents)){const l=Ve.parseCyclicBlueId(o);if(!l){t.push({providedBlueId:o,content:a});continue}const c=r.get(l.baseBlueId)??[];c.push({index:l.index,content:a}),r.set(l.baseBlueId,c)}});t.forEach(({content:i,providedBlueId:s})=>{const o=bt(i);this.storeContent(s,o,Array.isArray(o)),this.addContentNames(s,o)});for(const[i,s]of r){const o=Ve.toDenseCyclicContent(i,s),a=bt(o);this.storeContent(i,a,!0),this.addContentNames(i,a)}}static parseCyclicBlueId(e){const t=/^(.*)#(\d+)$/.exec(e);return!t?.[1]||t[2]===void 0?null:{baseBlueId:t[1],index:Number.parseInt(t[2],10)}}static toDenseCyclicContent(e,t){return[...t].sort((i,s)=>i.index-s.index).map((i,s)=>{if(i.index!==s)throw new Error(`Cyclic repository content for ${e} is missing index ${s}.`);return i.content})}addContentNames(e,t){if(Array.isArray(t)){this.addListItemNames(e,t);return}const i=y.deserialize(t).getName();i&&this.addToNameMap(i,e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,i)=>{const o=y.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${i}`)})}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?Ft.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:i}=this.getBaseBlueIdAndSuffix(e);if(i===void 0)return e;const s=this.aliasBlueIdMap.get(r);if(s===void 0)return e;if(this.getBaseBlueIdAndSuffix(s).suffix===void 0)return`${s}${i}`}getBaseBlueIdAndSuffix(e){const t=e.indexOf("#");return t===-1?{baseBlueId:e}:{baseBlueId:e.slice(0,t),suffix:e.slice(t)}}}class xs{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(ct).forEach(([s,o])=>{this.blueIdToInlineValue.set(s,o)});const i=r.getAllBlueIds();Object.entries(i).forEach(([s,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,s)})}restore(e){return D.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 i=t();if(!i||i.isInlineValue()&&i.getValue()!==void 0)return;const s=i.getBlueId();if(!s)return;const o=this.resolveInlineValue(s,i);if(!o)return;const a=new h().setValue(o).setInlineValue(!0);r(a)}resolveInlineValue(e,t){const r=this.blueIdToInlineValue.get(e);if(r)return r;const i=t.getName();if(i)return this.blueIdToInlineValue.set(e,i),i;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class _s{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(Fs(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)Ws(this.contents,r.contents,r.name),Ys(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]??Ot[e]??e;for(const r of this.runtimes){const i=r.toCurrentBlueIdIndex[t];if(i)return i}return t}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=tr[t];if(r)return r;for(const i of this.runtimes){const s=i.typeAliasByCurrentBlueId[t];if(s)return s}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const i=r.types[t];if(i)return{runtime:r,currentBlueId:t,typeMeta:i,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function Fs(n){const e=Us(n);return Object.values(n.packages).forEach(t=>{zs(e,n,t)}),{name:n.name,repositoryVersions:n.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 Us(n){const e=Object.fromEntries(n.repositoryVersions.map((r,i)=>[r,i])),t=n.repositoryVersions[n.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function zs(n,e,t){if(n.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);n.packageNames.add(t.name),js(n,t),$s(n,e,t),ks(n,t),qs(n,t)}function js(n,e){Object.entries(e.aliases).forEach(([t,r])=>{if(n.aliases[t]&&n.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);n.aliases[t]=r})}function $s(n,e,t){Object.entries(t.typesMeta).forEach(([r,i])=>{if(n.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const s=Ks(i,e,r,t.name);if(n.types[r]=s,n.typePackageByCurrentBlueId[r]=t.name,n.typeAliasByCurrentBlueId[r]=`${t.name}/${i.name}`,s.status===g.BLUE_REPOSITORY_STATUS_STABLE&&!n.toCurrentBlueIdIndex[r]&&(n.toCurrentBlueIdIndex[r]=r),s.status===g.BLUE_REPOSITORY_STATUS_STABLE)for(const o of s.versions){const a=n.toCurrentBlueIdIndex[o.typeBlueId];if(a&&a!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);n.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function ks(n,e){Object.entries(e.contents).forEach(([t,r])=>{n.contents[t]=r})}function qs(n,e){n.schemas.push(...Object.values(e.schemas))}function Ks(n,e,t,r){if(n.status===g.BLUE_REPOSITORY_STATUS_DEV)return Gs(n,e,t,r),{...n,versions:n.versions?[...n.versions]:n.versions};const i=[...n.versions??[]].sort((o,a)=>o.repositoryVersionIndex-a.repositoryVersionIndex);if(i.length===0)throw new Error(`Stable type ${r}/${n.name} (${t}) must have at least one version entry`);const s=new Set;return i.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${n.name}`);if(s.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${n.name}`);s.add(o.repositoryVersionIndex);for(const a of o.attributesAdded??[])Hs(a,e.name,t,o.repositoryVersionIndex)}),{...n,versions:i}}function Gs(n,e,t,r){if(n.status===g.BLUE_REPOSITORY_STATUS_DEV){if(n.versions&&n.versions.length>1)throw new Error(`Dev type ${r}/${n.name} (${t}) must not declare multiple versions`);if(n.versions&&n.versions.length===1){const i=n.versions[0];if(i.repositoryVersionIndex<0||i.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${i.repositoryVersionIndex} for dev type ${r}/${n.name}`)}}}function Hs(n,e,t,r){try{g.validateAttributesAddedPointer(n)}catch(i){const s=i instanceof Error?i.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${n}' for type ${t} in repository ${e} at index ${r}: ${s}`)}}function Ys(n,e,t){for(const[r,i]of Object.entries(e)){const s=n[r];if(s&&s!==i)throw new Error(`Conflicting alias '${r}' across repositories: '${s}' vs '${i}' (from ${t})`);n[r]=i}}function Ws(n,e,t){for(const[r,i]of Object.entries(e)){if(r in n){const s=n[r];if(!Zs(s,i))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}n[r]=i}}function Zs(n,e){if(n===e)return!0;if(n===null||e===null||typeof n!="object"||typeof e!="object")return!1;const t=Qe.canonicalize(n),r=Qe.canonicalize(e);return t!==void 0&&t===r}const ht={"6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF":{name:"Contract",description:`Base Blue Contracts and Processor 1.0 runtime type for executable or processor-interpreted declarations under an active scope's contracts map. A Contract is scope-local, identity-bearing Blue content. The processor discovers materialized contract entries in the selected document, resolves each entry far enough to identify its effective runtime type BlueId, and either executes supported behavior or applies must-understand and fatal rules. Contract entries are sorted by effective order and contract-map key when ordering is required. A Contract by itself has no executable behavior; concrete subtypes define Channel, Handler, Marker, or extension semantics.
|
|
48
48
|
`,order:{type:{blueId:"E2LM6qgzWG9ttagq2xTmiZkgYEAgkYedFCmU9v7NnVEq"},description:`Optional deterministic sort key within a scope. Missing order is treated as 0. Ordering compares order first, ascending, then contract-map key in lexicographic Unicode code-point order.
|
|
49
49
|
`}},"61W96XosAp3DrEC7PuqLYtmF2A6ETpqH6qF2DgYwDq4c":{name:"Json Patch Entry",description:`Blue Contracts and Processor 1.0 runtime patch request produced by handlers. A Json Patch Entry describes one deterministic mutation request against the selected document. Only add, replace, and remove are supported. The path is a Blue Runtime Pointer and must not target the document root. Despite its historical name, Json Patch Entry is not full RFC 6902; it uses Blue-specific upsert, auto-materialization, runtime insertion normalization, and post-patch type-soundness rules. The val field is required for add and replace and must be absent for remove. Patches are applied in result order; each successful patch triggers its full Document Update cascade before the next patch is applied. Field is named val, not value, because value is Blue's scalar payload wrapper.
|
|
50
50
|
`,op:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required patch operation. Allowed values are add, replace, and remove.
|
|
@@ -95,4 +95,4 @@ ${i.message}`):i}else throw Me(t)?new Error(`UrlContentFetcher not provided for
|
|
|
95
95
|
`,schema:{required:!0,enum:["fatal","graceful"]}},reason:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Optional deterministic reason for termination.
|
|
96
96
|
`}},AMZbj5tNGxjPrvaNyw56sfqcLSW2j1XmkncEYUVtgmVC:{name:"Document Processing Fatal Error",description:`Processor-emitted root outbox event appended when root processing terminates fatally. It is appended after Document Processing Terminated for the same root termination sequence. It is outbox-only: it is not delivered to Lifecycle Event Channels, is not recorded as bridgeable, and is not placed in the Triggered FIFO.
|
|
97
97
|
`,reason:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Optional deterministic fatal error reason.
|
|
98
|
-
`}}},Js=Object.fromEntries(Object.entries(ht).map(([n,e])=>[e.name,n])),Xs=Object.fromEntries(Object.entries(ht).map(([n,e])=>[n,{status:"stable",name:e.name,versions:[{repositoryVersionIndex:0,typeBlueId:n,attributesAdded:[]}]}])),Nt={name:"blue.builtin-runtime-types",repositoryVersions:["blue.builtin-runtime-types/v1"],packages:{builtinRuntimeTypes:{name:"builtinRuntimeTypes",aliases:{},typesMeta:Xs,contents:ht,schemas:{}}}},Qs=new Set(["__proto__","constructor","prototype"]);function Kt(n){const e=n.at(0),t=n.at(-1);return!e||!t?n:e==="'"&&t==="'"||e==='"'&&t==='"'?n.slice(1,-1):n}function en(n,e){const t=n.indexOf("=");if(t===-1)throw Pe(e,`Missing '=' in segment '${n.trim()}'`);if(n.indexOf("=",t+1)!==-1)throw Pe(e,`Unexpected '=' in segment '${n.trim()}'`);const r=Kt(n.slice(0,t).trim()),i=Kt(n.slice(t+1).trim());if(!r)throw Pe(e,"Repository name is empty");if(!i)throw Pe(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:i}}function tn(n){if(n.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of n.split(",")){const r=t.trim();if(!r)throw Pe(n,"Empty repository segment");const{name:i,value:s}=en(r,n);sn(i,n),e[i]=s}return e}function rn(n){return typeof n=="string"?tn(n):n}function Pe(n,e){return new Ne(H.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:H.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:n,reason:e}}])}function sn(n,e){if(Qs.has(n))throw Pe(e,`Forbidden repository name '${n}'`)}function nn(n,e){const t=n.filter(i=>i.repositoryVersionIndex>e).sort((i,s)=>s.repositoryVersionIndex-i.repositoryVersionIndex),r=[];for(const i of t){const s=[...i.attributesAdded].sort((o,a)=>Gt(a)-Gt(o));r.push(...s)}return r}function Gt(n){return y.parsePointer(n).length}const on=new Set([...Ct]),O={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class an{registry;targetRepoVersionIndexes;fallbackToCurrentInlineDefinitions;inliningStack=new Set;constructor(e){this.registry=e.registry,this.targetRepoVersionIndexes=e.targetRepoVersionIndexes,this.fallbackToCurrentInlineDefinitions=e.fallbackToCurrentInlineDefinitions}transform(e){return M.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(),i=r?.getBlueId();if(!r||!i)return;const s=this.resolveType(i);switch(s.kind){case O.core:{r.setBlueId(s.blueId);return}case O.representable:{this.applyDropPointers([r],s.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,s.dropPointers),r.setBlueId(s.targetBlueId);return}case O.noRuntime:case O.noTargetContext:case O.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,i);return}throw s.kind===O.unrepresentable?s.error:this.unrepresentableError(i,s.kind===O.noTargetContext?`Repository '${s.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",s.kind===O.noTargetContext?s.runtime:void 0,s.kind===O.noTargetContext?s.meta:void 0,void 0,s.kind===O.noTargetContext?s.typeAlias:void 0)}}}resolveType(e){if(ie.includes(e))return{kind:O.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),i=this.registry.findRuntimeByBlueId(t);if(!i||!i.typeMeta)return{kind:O.noRuntime};const s=this.targetRepoVersionIndexes[i.runtime.name];if(s===void 0)return{kind:O.noTargetContext,currentBlueId:t,runtimeName:i.runtime.name,runtime:i.runtime,meta:i.typeMeta,typeAlias:r};const o=i.typeMeta;if(o.status===y.BLUE_REPOSITORY_STATUS_DEV){const p=i.runtime.repositoryVersions.length-1;if(s!==p)return{kind:O.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${s}.`,i.runtime,o,s,r)};const f=o.versions?.[0];return{kind:O.representable,currentBlueId:t,targetBlueId:f?.typeBlueId??t,dropPointers:[]}}const a=o.versions||[];if(a.length===0)return{kind:O.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,i.runtime,o,s,r)};const l=a[0].repositoryVersionIndex;if(s<l)return{kind:O.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${s}.`,i.runtime,o,s,r)};let c=a[0].typeBlueId;for(const p of a)p.repositoryVersionIndex<=s&&(c=p.typeBlueId);const d=o.status===y.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,s):[];return{kind:O.representable,currentBlueId:t,targetBlueId:c,dropPointers:d}}getDropPointers(e,t){return e.status!==y.BLUE_REPOSITORY_STATUS_STABLE?[]:nn(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const i=r.rootIsSchema??!1;for(const s of t)for(const o of e)this.deletePropertyAtPointer(o,s,i)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,i])=>i instanceof h&&!on.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let i;try{i=y.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,i,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[i,...s]=t;if(i===U){const l=e.getType();l&&this.applyPointerSegments(l,s,!0);return}if(i===me){const l=e.getItemType();l&&this.applyPointerSegments(l,s,!0);return}if(i===ge){const l=e.getKeyType();l&&this.applyPointerSegments(l,s,!0);return}if(i===ye){const l=e.getValueType();l&&this.applyPointerSegments(l,s,!0);return}const o=e.getProperties();if(!o)return;if(s.length===0){if(!r||!(i in o))return;const l={...o};delete l[i],e.setProperties(l);return}const a=o[i];a instanceof h&&this.applyPointerSegments(a,s,r)}inlineDefinition(e,t,r){const i=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(i))throw this.unrepresentableError(i,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(i)});const s=this.registry.getContents()[i];if(!s)throw this.unrepresentableError(i,`Missing definition to inline for BlueId ${i}.`);this.inliningStack.add(i);try{const o=g.deserialize(s);o.setBlueId(void 0);const a=M.transform(o,l=>this.transformNode(l));return t(a),e}finally{this.inliningStack.delete(i)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new Ne(H.INVALID_REPOSITORY_POINTER,t,[{code:H.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,i,s,o,a){const l={currentTypeBlueId:e,targetRepoVersionIndex:s,typeAlias:o,...a};if(r&&(s!==void 0&&(l.requestedRepoBlueId=r.repositoryVersions[s]),l.serverRepoBlueId=r.currentRepoBlueId),i&&i.status===y.BLUE_REPOSITORY_STATUS_STABLE){const d=i.versions?.[0]?.repositoryVersionIndex;d!==void 0&&(l.typeIntroducedInRepoBlueId=r?.repositoryVersions[d])}const c={code:H.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[U],context:l};return new Ne(H.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[c])}}function We(n,e){return e?M.transform(n,t=>(Ke(()=>t.getType(),r=>t.setType(r),e),Ke(()=>t.getItemType(),r=>t.setItemType(r),e),Ke(()=>t.getKeyType(),r=>t.setKeyType(r),e),Ke(()=>t.getValueType(),r=>t.setValueType(r),e),t)):n}function Ke(n,e,t){const r=n();if(!r||r.isInlineValue())return;const i=r.getBlueId();if(!i)return;const s=t.toCurrentBlueId(i);s!==i&&e(r.clone().setBlueId(s))}class ln{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 i=We(e,this.blueIdMapper);return new an({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(i)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?rn(e.repositories):e.repositories;for(const[i,s]of Object.entries(r)){const o=this.registry.findRuntimeByName(i);if(!o)continue;const a=o.repoVersionIndexById[s];if(a===void 0)throw this.unknownRepoBlueIdError(i,s,o.currentRepoBlueId);t[i]=a}return Object.keys(t).length>0&&this.addImplicitBuiltinRuntimeTypesRepository(t),t}addImplicitBuiltinRuntimeTypesRepository(e){const t=Nt.name;if(e[t]!==void 0)return;const r=this.registry.findRuntimeByName(t);if(!r)return;const i=r.repoVersionIndexById[r.currentRepoBlueId];i!==void 0&&(e[t]=i)}unknownRepoBlueIdError(e,t,r){const i=`Unknown RepoBlueId '${t}' for repository '${e}'.`,s={code:H.REPO_UNKNOWN_REPO_BLUE_ID,message:i,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new Ne(H.REPO_UNKNOWN_REPO_BLUE_ID,i,[s])}}class jr{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=F;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:i,repositories:s,mergingProcessor:o}=e,a=this.includeBuiltinRuntimeTypesRepository(s);this.repositories=a,this.repositoryRegistry=new _s(a),this.blueContextResolver=new ln({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry}),this.mergingProcessor=o??_t();const l=Lt(()=>[]);this.nodeProvider=this.wrapNodeProviderWithRepositories(t||l,a),this.typeSchemaResolver=r??new Tr([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.urlContentFetcher=new Bs(i),this.blueDirectivePreprocessor=new vs(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new _r,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const c=this.repositoryRegistry.getRuntimes().flatMap(d=>d.schemas);c.length>0&&this.typeSchemaResolver?.registerSchemas(c)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),i=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return B.get(i,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),i=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return gs.get(i,{strategy:r.format})}nodeToSchemaOutput(e,t){return new xr(this.typeSchemaResolver,{calculateBlueId:i=>this.calculateBlueIdSync(i)}).convert(e,t)}resolve(e,t=F){const r=this.combineWithGlobalLimits(t),s=new pe(this.mergingProcessor,this.nodeProvider).resolve(e,r);if(!(r instanceof re)){const o=this.getExactReferenceBlueId(e);o!==void 0&&s.setSourceSemanticBlueId(o)}return s}createResolvedNode(e){return e instanceof Q?e:new Q(e)}reverse(e){return this.minimize(e)}minimize(e){return new Ye({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).minimize(e)}restoreInlineTypes(e){return new xs({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new xt(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(g.deserialize(e));return We(t,this.repositoryRegistry)}jsonValueToNodeUnchecked(e){const t=this.preprocess(g.deserializeUnchecked(e));return We(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(g.deserialize(e));return We(t,this.repositoryRegistry)}yamlToNode(e){const t=he(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}yamlToNodeUnchecked(e){const t=he(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeUnchecked(t)}async yamlToNodeAsync(e){const t=he(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeAsync(t)}prepareForBlueIdCalculation=async e=>e instanceof h||Array.isArray(e)&&e.every(t=>t instanceof h)?e:this.jsonValueToNodeAsync(e);calculateBlueId=async e=>{const t=await this.prepareForBlueIdCalculation(e);return new Ye({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).calculateBlueId(t)};prepareForBlueIdCalculationSync=e=>e instanceof h||Array.isArray(e)&&e.every(t=>t instanceof h)?e:this.jsonValueToNode(e);calculateBlueIdSync(e){const t=this.prepareForBlueIdCalculationSync(e);return new Ye({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 Ue({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new Ue({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}transform(e,t){return M.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(!C.hasBlueIdOnly(e))return;const t=e.getReferenceBlueId();return t!==void 0&&G.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()}includeBuiltinRuntimeTypesRepository(e){const t=e??[];return t.some(r=>r.name===Nt.name)?t:[Nt,...t]}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 J.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 i=e.getType();if(!i)return!1;const s=new h().setReferenceBlueId(r);return A(i,s,this.nodeProvider)}isTypeOfNode(e,t,r={}){return new Xi(this).matchesType(e,t,this.globalLimits,r)}setGlobalLimits(e){return this.globalLimits=e??F,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?new Ce([new Ve(t,{mergingProcessor:this.mergingProcessor}),oe.wrap(e)]):oe.wrap(e)}combineWithGlobalLimits(e){return this.globalLimits==F?e:e==F?this.globalLimits:_e.of(this.globalLimits,e)}}const cn=Object.freeze(Object.defineProperty({__proto__:null,Blue:jr},Symbol.toStringTag,{value:"Module"}));exports.BUILTIN_RUNTIME_TYPE_CONTENT_BY_BLUE_ID=ht;exports.BUILTIN_RUNTIME_TYPE_NAME_TO_BLUE_ID_MAP=Js;exports.Base58Sha256Provider=sr;exports.BasicTypesVerifier=Vr;exports.BigDecimalNumber=V;exports.BigIntegerNumber=R;exports.Blue=jr;exports.Blue$1=cn;exports.BlueIdCalculator=b;exports.BlueNode=h;exports.BlueNodeTypeSchema=J;exports.CORE_TYPE_NAME_TO_BLUE_ID_MAP=lt;exports.CyclicSetIdentityService=x;exports.DictionaryProcessor=Ar;exports.JsonCanonicalizer=Qe;exports.LIST_CONTROL_PREVIOUS=ce;exports.LIST_CONTROL_REPLACE=st;exports.Limits=dt;exports.ListProcessor=Rr;exports.MergeReverser=k;exports.Merger=pe;exports.MetadataPropagator=Dr;exports.NodeContentHandler=Ft;exports.NodeDeserializer=g;exports.NodeProviderWrapper=oe;exports.NodeResolver=Nr;exports.NodeToBlueIdInput=ne;exports.NodeToMapListOrValue=B;exports.NodeToObjectConverter=xr;exports.Nodes=C;exports.OBJECT_BLUE_ID=N;exports.OBJECT_DESCRIPTION=le;exports.OBJECT_NAME=ae;exports.OBJECT_SPECIFIC_KEYS=Ct;exports.OBJECT_VALUE=X;exports.PathLimits=ke;exports.PathLimitsBuilder=et;exports.PreloadedNodeProvider=Fr;exports.Preprocessor=Ue;exports.Properties=Hr;exports.ResolvedBlueNode=Q;exports.SCHEMA_FIELDS=ut;exports.Schema=je;exports.SchemaPropagator=Or;exports.SchemaVerifier=Mr;exports.SemanticIdentityService=Ye;exports.SequentialMergingProcessor=wr;exports.StorageShapeValidator=Ee;exports.TypeAssigner=Cr;exports.TypeSchemaResolver=Tr;exports.ValuePropagator=Sr;exports.baseBlueObjectSchema=ze;exports.blueDescriptionField=bi;exports.blueIdField=wi;exports.blueIdSchema=Wr;exports.blueLanguageErrorCategory=Ti;exports.blueNameField=Si;exports.blueNodeField=Ci;exports.blueObjectBooleanValueSchema=Xr;exports.blueObjectNumberValueSchema=Jr;exports.blueObjectSchema=Ze;exports.blueObjectStringListItemsSchema=Qr;exports.blueObjectStringValueSchema=Zr;exports.canonicalizeRepositoryContent=bt;exports.createDefaultMergingProcessor=_t;exports.createNodeProvider=Lt;exports.getBlueDescriptionAnnotation=lr;exports.getBlueIdAnnotation=ur;exports.getBlueNameAnnotation=hr;exports.getBlueNodeAnnotation=fr;exports.getTypeBlueIdAnnotation=mr;exports.isBigDecimalNumber=Je;exports.isBigIntegerNumber=Y;exports.isBigNumber=D;exports.isBlueNodeSchema=Dt;exports.isJsonBlueArray=Mt;exports.isJsonBlueObject=q;exports.isJsonBlueValue=ri;exports.isUrl=Me;exports.jsonBlueValueSchema=Xe;exports.withBlueDescription=ar;exports.withBlueId=cr;exports.withBlueName=dr;exports.withBlueNode=pr;exports.withTypeBlueId=Ai;exports.yamlBlueDump=Er;exports.yamlBlueParse=he;
|
|
98
|
+
`}}},Js=Object.fromEntries(Object.entries(ht).map(([n,e])=>[e.name,n])),Xs=Object.fromEntries(Object.entries(ht).map(([n,e])=>[n,{status:"stable",name:e.name,versions:[{repositoryVersionIndex:0,typeBlueId:n,attributesAdded:[]}]}])),Nt={name:"blue.builtin-runtime-types",repositoryVersions:["blue.builtin-runtime-types/v1"],packages:{builtinRuntimeTypes:{name:"builtinRuntimeTypes",aliases:{},typesMeta:Xs,contents:ht,schemas:{}}}},Qs=new Set(["__proto__","constructor","prototype"]);function Kt(n){const e=n.at(0),t=n.at(-1);return!e||!t?n:e==="'"&&t==="'"||e==='"'&&t==='"'?n.slice(1,-1):n}function en(n,e){const t=n.indexOf("=");if(t===-1)throw Pe(e,`Missing '=' in segment '${n.trim()}'`);if(n.indexOf("=",t+1)!==-1)throw Pe(e,`Unexpected '=' in segment '${n.trim()}'`);const r=Kt(n.slice(0,t).trim()),i=Kt(n.slice(t+1).trim());if(!r)throw Pe(e,"Repository name is empty");if(!i)throw Pe(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:i}}function tn(n){if(n.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of n.split(",")){const r=t.trim();if(!r)throw Pe(n,"Empty repository segment");const{name:i,value:s}=en(r,n);sn(i,n),e[i]=s}return e}function rn(n){return typeof n=="string"?tn(n):n}function Pe(n,e){return new Ne(H.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:H.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:n,reason:e}}])}function sn(n,e){if(Qs.has(n))throw Pe(e,`Forbidden repository name '${n}'`)}function nn(n,e){const t=n.filter(i=>i.repositoryVersionIndex>e).sort((i,s)=>s.repositoryVersionIndex-i.repositoryVersionIndex),r=[];for(const i of t){const s=[...i.attributesAdded].sort((o,a)=>Gt(a)-Gt(o));r.push(...s)}return r}function Gt(n){return g.parsePointer(n).length}const on=new Set([...Ct]),O={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class an{registry;targetRepoVersionIndexes;fallbackToCurrentInlineDefinitions;inliningStack=new Set;constructor(e){this.registry=e.registry,this.targetRepoVersionIndexes=e.targetRepoVersionIndexes,this.fallbackToCurrentInlineDefinitions=e.fallbackToCurrentInlineDefinitions}transform(e){return D.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(),i=r?.getBlueId();if(!r||!i)return;const s=this.resolveType(i);switch(s.kind){case O.core:{r.setBlueId(s.blueId);return}case O.representable:{this.applyDropPointers([r],s.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,s.dropPointers),r.setBlueId(s.targetBlueId);return}case O.noRuntime:case O.noTargetContext:case O.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,i);return}throw s.kind===O.unrepresentable?s.error:this.unrepresentableError(i,s.kind===O.noTargetContext?`Repository '${s.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",s.kind===O.noTargetContext?s.runtime:void 0,s.kind===O.noTargetContext?s.meta:void 0,void 0,s.kind===O.noTargetContext?s.typeAlias:void 0)}}}resolveType(e){if(ie.includes(e))return{kind:O.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),i=this.registry.findRuntimeByBlueId(t);if(!i||!i.typeMeta)return{kind:O.noRuntime};const s=this.targetRepoVersionIndexes[i.runtime.name];if(s===void 0)return{kind:O.noTargetContext,currentBlueId:t,runtimeName:i.runtime.name,runtime:i.runtime,meta:i.typeMeta,typeAlias:r};const o=i.typeMeta;if(o.status===g.BLUE_REPOSITORY_STATUS_DEV){const p=i.runtime.repositoryVersions.length-1;if(s!==p)return{kind:O.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${s}.`,i.runtime,o,s,r)};const f=o.versions?.[0];return{kind:O.representable,currentBlueId:t,targetBlueId:f?.typeBlueId??t,dropPointers:[]}}const a=o.versions||[];if(a.length===0)return{kind:O.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,i.runtime,o,s,r)};const l=a[0].repositoryVersionIndex;if(s<l)return{kind:O.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${s}.`,i.runtime,o,s,r)};let c=a[0].typeBlueId;for(const p of a)p.repositoryVersionIndex<=s&&(c=p.typeBlueId);const d=o.status===g.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,s):[];return{kind:O.representable,currentBlueId:t,targetBlueId:c,dropPointers:d}}getDropPointers(e,t){return e.status!==g.BLUE_REPOSITORY_STATUS_STABLE?[]:nn(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const i=r.rootIsSchema??!1;for(const s of t)for(const o of e)this.deletePropertyAtPointer(o,s,i)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,i])=>i instanceof h&&!on.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let i;try{i=g.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,i,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[i,...s]=t;if(i===U){const l=e.getType();l&&this.applyPointerSegments(l,s,!0);return}if(i===me){const l=e.getItemType();l&&this.applyPointerSegments(l,s,!0);return}if(i===ye){const l=e.getKeyType();l&&this.applyPointerSegments(l,s,!0);return}if(i===ge){const l=e.getValueType();l&&this.applyPointerSegments(l,s,!0);return}const o=e.getProperties();if(!o)return;if(s.length===0){if(!r||!(i in o))return;const l={...o};delete l[i],e.setProperties(l);return}const a=o[i];a instanceof h&&this.applyPointerSegments(a,s,r)}inlineDefinition(e,t,r){const i=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(i))throw this.unrepresentableError(i,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(i)});const s=this.registry.getContents()[i];if(!s)throw this.unrepresentableError(i,`Missing definition to inline for BlueId ${i}.`);this.inliningStack.add(i);try{const o=y.deserialize(s);o.setBlueId(void 0);const a=D.transform(o,l=>this.transformNode(l));return t(a),e}finally{this.inliningStack.delete(i)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new Ne(H.INVALID_REPOSITORY_POINTER,t,[{code:H.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,i,s,o,a){const l={currentTypeBlueId:e,targetRepoVersionIndex:s,typeAlias:o,...a};if(r&&(s!==void 0&&(l.requestedRepoBlueId=r.repositoryVersions[s]),l.serverRepoBlueId=r.currentRepoBlueId),i&&i.status===g.BLUE_REPOSITORY_STATUS_STABLE){const d=i.versions?.[0]?.repositoryVersionIndex;d!==void 0&&(l.typeIntroducedInRepoBlueId=r?.repositoryVersions[d])}const c={code:H.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[U],context:l};return new Ne(H.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[c])}}function We(n,e){return e?D.transform(n,t=>(Ke(()=>t.getType(),r=>t.setType(r),e),Ke(()=>t.getItemType(),r=>t.setItemType(r),e),Ke(()=>t.getKeyType(),r=>t.setKeyType(r),e),Ke(()=>t.getValueType(),r=>t.setValueType(r),e),t)):n}function Ke(n,e,t){const r=n();if(!r||r.isInlineValue())return;const i=r.getBlueId();if(!i)return;const s=t.toCurrentBlueId(i);s!==i&&e(r.clone().setBlueId(s))}class ln{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 i=We(e,this.blueIdMapper);return new an({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(i)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?rn(e.repositories):e.repositories;for(const[i,s]of Object.entries(r)){const o=this.registry.findRuntimeByName(i);if(!o)continue;const a=o.repoVersionIndexById[s];if(a===void 0)throw this.unknownRepoBlueIdError(i,s,o.currentRepoBlueId);t[i]=a}return Object.keys(t).length>0&&this.addImplicitBuiltinRuntimeTypesRepository(t),t}addImplicitBuiltinRuntimeTypesRepository(e){const t=Nt.name;if(e[t]!==void 0)return;const r=this.registry.findRuntimeByName(t);if(!r)return;const i=r.repoVersionIndexById[r.currentRepoBlueId];i!==void 0&&(e[t]=i)}unknownRepoBlueIdError(e,t,r){const i=`Unknown RepoBlueId '${t}' for repository '${e}'.`,s={code:H.REPO_UNKNOWN_REPO_BLUE_ID,message:i,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new Ne(H.REPO_UNKNOWN_REPO_BLUE_ID,i,[s])}}class jr{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=F;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:i,repositories:s,mergingProcessor:o}=e,a=this.includeBuiltinRuntimeTypesRepository(s);this.repositories=a,this.repositoryRegistry=new _s(a),this.blueContextResolver=new ln({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry}),this.mergingProcessor=o??_t();const l=Lt(()=>[]);this.nodeProvider=this.wrapNodeProviderWithRepositories(t||l,a),this.typeSchemaResolver=r??new Tr([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.urlContentFetcher=new Bs(i),this.blueDirectivePreprocessor=new vs(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new _r,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const c=this.repositoryRegistry.getRuntimes().flatMap(d=>d.schemas);c.length>0&&this.typeSchemaResolver?.registerSchemas(c)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),i=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return B.get(i,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),i=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return ys.get(i,{strategy:r.format})}nodeToSchemaOutput(e,t){return new xr(this.typeSchemaResolver,{calculateBlueId:i=>this.calculateBlueIdSync(i)}).convert(e,t)}resolve(e,t=F){const r=this.combineWithGlobalLimits(t),s=new pe(this.mergingProcessor,this.nodeProvider).resolve(e,r);if(!(r instanceof re)){const o=this.getExactReferenceBlueId(e);o!==void 0&&s.setSourceSemanticBlueId(o)}return s}createResolvedNode(e){return e instanceof Q?e:new Q(e)}reverse(e){return this.minimize(e)}minimize(e){return new Ye({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).minimize(e)}restoreInlineTypes(e){return new xs({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new xt(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(y.deserialize(e));return We(t,this.repositoryRegistry)}jsonValueToNodeUnchecked(e){const t=this.preprocess(y.deserializeUnchecked(e));return We(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(y.deserialize(e));return We(t,this.repositoryRegistry)}yamlToNode(e){const t=he(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}yamlToNodeUnchecked(e){const t=he(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeUnchecked(t)}async yamlToNodeAsync(e){const t=he(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeAsync(t)}prepareForBlueIdCalculation=async e=>e instanceof h||Array.isArray(e)&&e.every(t=>t instanceof h)?e:this.jsonValueToNodeAsync(e);calculateBlueId=async e=>{const t=await this.prepareForBlueIdCalculation(e);return new Ye({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).calculateBlueId(t)};prepareForBlueIdCalculationSync=e=>e instanceof h||Array.isArray(e)&&e.every(t=>t instanceof h)?e:this.jsonValueToNode(e);calculateBlueIdSync(e){const t=this.prepareForBlueIdCalculationSync(e);return new Ye({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 Ue({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new Ue({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}transform(e,t){return D.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(!R.hasBlueIdOnly(e))return;const t=e.getReferenceBlueId();return t!==void 0&&G.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()}includeBuiltinRuntimeTypesRepository(e){const t=e??[];return t.some(r=>r.name===Nt.name)?t:[Nt,...t]}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 J.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 i=e.getType();if(!i)return!1;const s=new h().setReferenceBlueId(r);return A(i,s,this.nodeProvider)}isTypeOfNode(e,t,r={}){return new Xi(this).matchesType(e,t,this.globalLimits,r)}setGlobalLimits(e){return this.globalLimits=e??F,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?new Ce([new Ve(t,{mergingProcessor:this.mergingProcessor}),oe.wrap(e)]):oe.wrap(e)}combineWithGlobalLimits(e){return this.globalLimits==F?e:e==F?this.globalLimits:_e.of(this.globalLimits,e)}}const cn=Object.freeze(Object.defineProperty({__proto__:null,Blue:jr},Symbol.toStringTag,{value:"Module"}));exports.BUILTIN_RUNTIME_TYPE_CONTENT_BY_BLUE_ID=ht;exports.BUILTIN_RUNTIME_TYPE_NAME_TO_BLUE_ID_MAP=Js;exports.Base58Sha256Provider=sr;exports.BasicTypesVerifier=Vr;exports.BigDecimalNumber=V;exports.BigIntegerNumber=S;exports.Blue=jr;exports.Blue$1=cn;exports.BlueIdCalculator=b;exports.BlueNode=h;exports.BlueNodeTypeSchema=J;exports.CORE_TYPE_NAME_TO_BLUE_ID_MAP=lt;exports.CyclicSetIdentityService=x;exports.DictionaryProcessor=Ar;exports.JsonCanonicalizer=Qe;exports.LIST_CONTROL_PREVIOUS=ce;exports.LIST_CONTROL_REPLACE=st;exports.Limits=dt;exports.ListProcessor=Rr;exports.MergeReverser=k;exports.Merger=pe;exports.MetadataPropagator=Dr;exports.NodeContentHandler=Ft;exports.NodeDeserializer=y;exports.NodeProviderWrapper=oe;exports.NodeResolver=Nr;exports.NodeToBlueIdInput=ne;exports.NodeToMapListOrValue=B;exports.NodeToObjectConverter=xr;exports.Nodes=R;exports.OBJECT_BLUE_ID=N;exports.OBJECT_DESCRIPTION=le;exports.OBJECT_NAME=ae;exports.OBJECT_SPECIFIC_KEYS=Ct;exports.OBJECT_VALUE=X;exports.PathLimits=ke;exports.PathLimitsBuilder=et;exports.PreloadedNodeProvider=Fr;exports.Preprocessor=Ue;exports.Properties=Hr;exports.ResolvedBlueNode=Q;exports.SCHEMA_FIELDS=ut;exports.Schema=je;exports.SchemaPropagator=Or;exports.SchemaVerifier=Mr;exports.SemanticIdentityService=Ye;exports.SequentialMergingProcessor=wr;exports.StorageShapeValidator=Ee;exports.TypeAssigner=Cr;exports.TypeSchemaResolver=Tr;exports.ValuePropagator=Sr;exports.baseBlueObjectSchema=ze;exports.blueDescriptionField=bi;exports.blueIdField=wi;exports.blueIdSchema=Wr;exports.blueLanguageErrorCategory=Ti;exports.blueNameField=Si;exports.blueNodeField=Ci;exports.blueObjectBooleanValueSchema=Xr;exports.blueObjectNumberValueSchema=Jr;exports.blueObjectSchema=Ze;exports.blueObjectStringListItemsSchema=Qr;exports.blueObjectStringValueSchema=Zr;exports.canonicalizeRepositoryContent=bt;exports.createDefaultMergingProcessor=_t;exports.createNodeProvider=Lt;exports.getBlueDescriptionAnnotation=lr;exports.getBlueIdAnnotation=ur;exports.getBlueNameAnnotation=hr;exports.getBlueNodeAnnotation=fr;exports.getTypeBlueIdAnnotation=mr;exports.isBigDecimalNumber=Je;exports.isBigIntegerNumber=Y;exports.isBigNumber=M;exports.isBlueNodeSchema=Dt;exports.isJsonBlueArray=Mt;exports.isJsonBlueObject=q;exports.isJsonBlueValue=ri;exports.isUrl=Me;exports.jsonBlueValueSchema=Xe;exports.withBlueDescription=ar;exports.withBlueId=cr;exports.withBlueName=dr;exports.withBlueNode=pr;exports.withTypeBlueId=Ai;exports.yamlBlueDump=Er;exports.yamlBlueParse=he;
|