@modeldesk/cli 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/modeldesk.js CHANGED
@@ -1,292 +1,304 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
3
- var JS=Object.create;var uu=Object.defineProperty;var XS=Object.getOwnPropertyDescriptor;var QS=Object.getOwnPropertyNames;var ZS=Object.getPrototypeOf,ev=Object.prototype.hasOwnProperty;var Co=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var L=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}};var tv=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of QS(t))!ev.call(e,s)&&s!==n&&uu(e,s,{get:()=>t[s],enumerable:!(r=XS(t,s))||r.enumerable});return e};var kd=(e,t,n)=>(n=e!=null?JS(ZS(e)):{},tv(t||!e||!e.__esModule?uu(n,"default",{value:e,enumerable:!0}):n,e));var G=L(Ee=>{"use strict";var Rc=Symbol.for("yaml.alias"),Jw=Symbol.for("yaml.document"),Ii=Symbol.for("yaml.map"),Xw=Symbol.for("yaml.pair"),Sc=Symbol.for("yaml.scalar"),$i=Symbol.for("yaml.seq"),vt=Symbol.for("yaml.node.type"),EN=e=>!!e&&typeof e=="object"&&e[vt]===Rc,CN=e=>!!e&&typeof e=="object"&&e[vt]===Jw,RN=e=>!!e&&typeof e=="object"&&e[vt]===Ii,SN=e=>!!e&&typeof e=="object"&&e[vt]===Xw,Qw=e=>!!e&&typeof e=="object"&&e[vt]===Sc,vN=e=>!!e&&typeof e=="object"&&e[vt]===$i;function Zw(e){if(e&&typeof e=="object")switch(e[vt]){case Ii:case $i:return!0}return!1}function IN(e){if(e&&typeof e=="object")switch(e[vt]){case Rc:case Ii:case Sc:case $i:return!0}return!1}var $N=e=>(Qw(e)||Zw(e))&&!!e.anchor;Ee.ALIAS=Rc;Ee.DOC=Jw;Ee.MAP=Ii;Ee.NODE_TYPE=vt;Ee.PAIR=Xw;Ee.SCALAR=Sc;Ee.SEQ=$i;Ee.hasAnchor=$N;Ee.isAlias=EN;Ee.isCollection=Zw;Ee.isDocument=CN;Ee.isMap=RN;Ee.isNode=IN;Ee.isPair=SN;Ee.isScalar=Qw;Ee.isSeq=vN});var Ss=L(vc=>{"use strict";var we=G(),Te=Symbol("break visit"),eb=Symbol("skip children"),dt=Symbol("remove node");function xi(e,t){let n=tb(t);we.isDocument(e)?Sr(null,e.contents,n,Object.freeze([e]))===dt&&(e.contents=null):Sr(null,e,n,Object.freeze([]))}xi.BREAK=Te;xi.SKIP=eb;xi.REMOVE=dt;function Sr(e,t,n,r){let s=nb(e,t,n,r);if(we.isNode(s)||we.isPair(s))return rb(e,r,s),Sr(e,s,n,r);if(typeof s!="symbol"){if(we.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=Sr(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===Te)return Te;i===dt&&(t.items.splice(o,1),o-=1)}}}else if(we.isPair(t)){r=Object.freeze(r.concat(t));let o=Sr("key",t.key,n,r);if(o===Te)return Te;o===dt&&(t.key=null);let i=Sr("value",t.value,n,r);if(i===Te)return Te;i===dt&&(t.value=null)}}return s}async function Mi(e,t){let n=tb(t);we.isDocument(e)?await vr(null,e.contents,n,Object.freeze([e]))===dt&&(e.contents=null):await vr(null,e,n,Object.freeze([]))}Mi.BREAK=Te;Mi.SKIP=eb;Mi.REMOVE=dt;async function vr(e,t,n,r){let s=await nb(e,t,n,r);if(we.isNode(s)||we.isPair(s))return rb(e,r,s),vr(e,s,n,r);if(typeof s!="symbol"){if(we.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=await vr(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===Te)return Te;i===dt&&(t.items.splice(o,1),o-=1)}}}else if(we.isPair(t)){r=Object.freeze(r.concat(t));let o=await vr("key",t.key,n,r);if(o===Te)return Te;o===dt&&(t.key=null);let i=await vr("value",t.value,n,r);if(i===Te)return Te;i===dt&&(t.value=null)}}return s}function tb(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function nb(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(we.isMap(t))return n.Map?.(e,t,r);if(we.isSeq(t))return n.Seq?.(e,t,r);if(we.isPair(t))return n.Pair?.(e,t,r);if(we.isScalar(t))return n.Scalar?.(e,t,r);if(we.isAlias(t))return n.Alias?.(e,t,r)}function rb(e,t,n){let r=t[t.length-1];if(we.isCollection(r))r.items[e]=n;else if(we.isPair(r))e==="key"?r.key=n:r.value=n;else if(we.isDocument(r))r.contents=n;else{let s=we.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}vc.visit=xi;vc.visitAsync=Mi});var Ic=L(ob=>{"use strict";var sb=G(),xN=Ss(),MN={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},AN=e=>e.replace(/[!,[\]{}]/g,t=>MN[t]),vs=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),s=r.shift();switch(s){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[o,i]=r;return this.tags[o]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let i=/^\d+\.\d+$/.test(o);return n(6,`Unsupported YAML version ${o}`,i),!1}}default:return n(0,`Unknown directive ${s}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,s]=t.match(/^(.*!)([^!]*)$/s);s||n(`The ${t} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(s)}catch(i){return n(String(i)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+AN(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),s;if(t&&r.length>0&&sb.isNode(t.contents)){let o={};xN.visit(t.contents,(i,a)=>{sb.isNode(a)&&a.tag&&(o[a.tag]=!0)}),s=Object.keys(o)}else s=[];for(let[o,i]of r)o==="!!"&&i==="tag:yaml.org,2002:"||(!t||s.some(a=>a.startsWith(i)))&&n.push(`%TAG ${o} ${i}`);return n.join(`
4
- `)}};vs.defaultYaml={explicit:!1,version:"1.2"};vs.defaultTags={"!!":"tag:yaml.org,2002:"};ob.Directives=vs});var Ai=L(Is=>{"use strict";var ib=G(),TN=Ss();function ON(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function ab(e){let t=new Set;return TN.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function db(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function NN(e,t){let n=[],r=new Map,s=null;return{onAnchor:o=>{n.push(o),s??(s=ab(e));let i=db(t,s);return s.add(i),i},setAnchors:()=>{for(let o of n){let i=r.get(o);if(typeof i=="object"&&i.anchor&&(ib.isScalar(i.node)||ib.isCollection(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:r}}Is.anchorIsValid=ON;Is.anchorNames=ab;Is.createNodeAnchors=NN;Is.findNewAnchor=db});var $c=L(lb=>{"use strict";function $s(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let s=0,o=r.length;s<o;++s){let i=r[s],a=$s(e,r,String(s),i);a===void 0?delete r[s]:a!==i&&(r[s]=a)}else if(r instanceof Map)for(let s of Array.from(r.keys())){let o=r.get(s),i=$s(e,r,s,o);i===void 0?r.delete(s):i!==o&&r.set(s,i)}else if(r instanceof Set)for(let s of Array.from(r)){let o=$s(e,r,s,s);o===void 0?r.delete(s):o!==s&&(r.delete(s),r.add(o))}else for(let[s,o]of Object.entries(r)){let i=$s(e,r,s,o);i===void 0?delete r[s]:i!==o&&(r[s]=i)}return e.call(t,n,r)}lb.applyReviver=$s});var Jt=L(mb=>{"use strict";var LN=G();function cb(e,t,n){if(Array.isArray(e))return e.map((r,s)=>cb(r,String(s),n));if(e&&typeof e.toJSON=="function"){if(!n||!LN.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=o=>{r.res=o,delete n.onCreate};let s=e.toJSON(t,n);return n.onCreate&&n.onCreate(s),s}return typeof e=="bigint"&&!n?.keep?Number(e):e}mb.toJS=cb});var Ti=L(ub=>{"use strict";var PN=$c(),fb=G(),DN=Jt(),xc=class{constructor(t){Object.defineProperty(this,fb.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:s,reviver:o}={}){if(!fb.isDocument(t))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=DN.toJS(this,"",i);if(typeof s=="function")for(let{count:d,res:l}of i.anchors.values())s(l,d);return typeof o=="function"?PN.applyReviver(o,{"":a},"",a):a}};ub.NodeBase=xc});var xs=L(pb=>{"use strict";var _N=Ai(),jN=Ss(),Ir=G(),FN=Ti(),qN=Jt(),Mc=class extends FN.NodeBase{constructor(t){super(Ir.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],jN.visit(t,{Node:(o,i)=>{(Ir.isAlias(i)||Ir.hasAnchor(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let s;for(let o of r){if(o===this)break;o.anchor===this.source&&(s=o)}if(s&&n){let{anchors:o,doc:i,maxAliasCount:a}=n,d=o.get(s);if(d||(qN.toJS(s,null,n),d=o.get(s)),d?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(d.count+=1,d.aliasCount===0&&(d.aliasCount=Oi(i,s,o)),d.count*d.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return s}toJSON(t,n){if(!n)return{source:this.source};let r=this.resolve(n.doc,n);if(!r){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(s)}return n.anchors.get(r).res}toString(t,n,r){let s=`*${this.source}`;if(t){if(_N.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${s} `}return s}};function Oi(e,t,n){if(Ir.isAlias(t)){let r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}else if(Ir.isCollection(t)){let r=0;for(let s of t.items){let o=Oi(e,s,n);o>r&&(r=o)}return r}else if(Ir.isPair(t)){let r=Oi(e,t.key,n),s=Oi(e,t.value,n);return Math.max(r,s)}return 1}pb.Alias=Mc});var pe=L(Ac=>{"use strict";var BN=G(),WN=Ti(),UN=Jt(),HN=e=>!e||typeof e!="function"&&typeof e!="object",Xt=class extends WN.NodeBase{constructor(t){super(BN.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:UN.toJS(this.value,t,n)}toString(){return String(this.value)}};Xt.BLOCK_FOLDED="BLOCK_FOLDED";Xt.BLOCK_LITERAL="BLOCK_LITERAL";Xt.PLAIN="PLAIN";Xt.QUOTE_DOUBLE="QUOTE_DOUBLE";Xt.QUOTE_SINGLE="QUOTE_SINGLE";Ac.Scalar=Xt;Ac.isScalarValue=HN});var Ms=L(gb=>{"use strict";var GN=xs(),On=G(),hb=pe(),VN="tag:yaml.org,2002:";function KN(e,t,n){if(t){let r=n.filter(o=>o.tag===t),s=r.find(o=>!o.format)??r[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find(r=>r.identify?.(e)&&!r.format)}function YN(e,t,n){if(On.isDocument(e)&&(e=e.contents),On.isNode(e))return e;if(On.isPair(e)){let m=n.schema[On.MAP].createNode?.(n.schema,null,n);return m.items.push(e),m}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:s,onTagObj:o,schema:i,sourceObjects:a}=n,d;if(r&&e&&typeof e=="object"){if(d=a.get(e),d)return d.anchor??(d.anchor=s(e)),new GN.Alias(d.anchor);d={anchor:null,node:null},a.set(e,d)}t?.startsWith("!!")&&(t=VN+t.slice(2));let l=KN(e,t,i.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let m=new hb.Scalar(e);return d&&(d.node=m),m}l=e instanceof Map?i[On.MAP]:Symbol.iterator in Object(e)?i[On.SEQ]:i[On.MAP]}o&&(o(l),delete n.onTagObj);let c=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,e,n):new hb.Scalar(e);return t?c.tag=t:l.default||(c.tag=l.tag),d&&(d.node=c),c}gb.createNode=YN});var Li=L(Ni=>{"use strict";var zN=Ms(),lt=G(),JN=Ti();function Tc(e,t,n){let r=n;for(let s=t.length-1;s>=0;--s){let o=t[s];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let i=[];i[o]=r,r=i}else r=new Map([[o,r]])}return zN.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var yb=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Oc=class extends JN.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>lt.isNode(r)||lt.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(yb(t))this.add(n);else{let[r,...s]=t,o=this.get(r,!0);if(lt.isCollection(o))o.addIn(s,n);else if(o===void 0&&this.schema)this.set(r,Tc(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let s=this.get(n,!0);if(lt.isCollection(s))return s.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...s]=t,o=this.get(r,!0);return s.length===0?!n&&lt.isScalar(o)?o.value:o:lt.isCollection(o)?o.getIn(s,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!lt.isPair(n))return!1;let r=n.value;return r==null||t&&lt.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let s=this.get(n,!0);return lt.isCollection(s)?s.hasIn(r):!1}setIn(t,n){let[r,...s]=t;if(s.length===0)this.set(r,n);else{let o=this.get(r,!0);if(lt.isCollection(o))o.setIn(s,n);else if(o===void 0&&this.schema)this.set(r,Tc(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}};Ni.Collection=Oc;Ni.collectionFromPath=Tc;Ni.isEmptyPath=yb});var As=L(Pi=>{"use strict";var XN=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Nc(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var QN=(e,t,n)=>e.endsWith(`
5
- `)?Nc(n,t):n.includes(`
3
+ var gx=Object.create;var ju=Object.defineProperty;var yx=Object.getOwnPropertyDescriptor;var wx=Object.getOwnPropertyNames;var bx=Object.getPrototypeOf,Ex=Object.prototype.hasOwnProperty;var li=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var D=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}};var Cx=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of wx(t))!Ex.call(e,o)&&o!==n&&ju(e,o,{get:()=>t[o],enumerable:!(r=yx(t,o))||r.enumerable});return e};var bl=(e,t,n)=>(n=e!=null?gx(bx(e)):{},Cx(t||!e||!e.__esModule?ju(n,"default",{value:e,enumerable:!0}):n,e));var ee=D(Te=>{"use strict";var Wm=Symbol.for("yaml.alias"),tk=Symbol.for("yaml.document"),Aa=Symbol.for("yaml.map"),nk=Symbol.for("yaml.pair"),Hm=Symbol.for("yaml.scalar"),Oa=Symbol.for("yaml.seq"),Ht=Symbol.for("yaml.node.type"),Pj=e=>!!e&&typeof e=="object"&&e[Ht]===Wm,Dj=e=>!!e&&typeof e=="object"&&e[Ht]===tk,Lj=e=>!!e&&typeof e=="object"&&e[Ht]===Aa,_j=e=>!!e&&typeof e=="object"&&e[Ht]===nk,rk=e=>!!e&&typeof e=="object"&&e[Ht]===Hm,jj=e=>!!e&&typeof e=="object"&&e[Ht]===Oa;function ok(e){if(e&&typeof e=="object")switch(e[Ht]){case Aa:case Oa:return!0}return!1}function Fj(e){if(e&&typeof e=="object")switch(e[Ht]){case Wm:case Aa:case Hm:case Oa:return!0}return!1}var qj=e=>(rk(e)||ok(e))&&!!e.anchor;Te.ALIAS=Wm;Te.DOC=tk;Te.MAP=Aa;Te.NODE_TYPE=Ht;Te.PAIR=nk;Te.SCALAR=Hm;Te.SEQ=Oa;Te.hasAnchor=qj;Te.isAlias=Pj;Te.isCollection=ok;Te.isDocument=Dj;Te.isMap=Lj;Te.isNode=Fj;Te.isPair=_j;Te.isScalar=rk;Te.isSeq=jj});var ps=D(Bm=>{"use strict";var Se=ee(),We=Symbol("break visit"),sk=Symbol("skip children"),It=Symbol("remove node");function Ma(e,t){let n=ik(t);Se.isDocument(e)?so(null,e.contents,n,Object.freeze([e]))===It&&(e.contents=null):so(null,e,n,Object.freeze([]))}Ma.BREAK=We;Ma.SKIP=sk;Ma.REMOVE=It;function so(e,t,n,r){let o=ak(e,t,n,r);if(Se.isNode(o)||Se.isPair(o))return dk(e,r,o),so(e,o,n,r);if(typeof o!="symbol"){if(Se.isCollection(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=so(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===We)return We;i===It&&(t.items.splice(s,1),s-=1)}}}else if(Se.isPair(t)){r=Object.freeze(r.concat(t));let s=so("key",t.key,n,r);if(s===We)return We;s===It&&(t.key=null);let i=so("value",t.value,n,r);if(i===We)return We;i===It&&(t.value=null)}}return o}async function Na(e,t){let n=ik(t);Se.isDocument(e)?await io(null,e.contents,n,Object.freeze([e]))===It&&(e.contents=null):await io(null,e,n,Object.freeze([]))}Na.BREAK=We;Na.SKIP=sk;Na.REMOVE=It;async function io(e,t,n,r){let o=await ak(e,t,n,r);if(Se.isNode(o)||Se.isPair(o))return dk(e,r,o),io(e,o,n,r);if(typeof o!="symbol"){if(Se.isCollection(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=await io(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===We)return We;i===It&&(t.items.splice(s,1),s-=1)}}}else if(Se.isPair(t)){r=Object.freeze(r.concat(t));let s=await io("key",t.key,n,r);if(s===We)return We;s===It&&(t.key=null);let i=await io("value",t.value,n,r);if(i===We)return We;i===It&&(t.value=null)}}return o}function ik(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function ak(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(Se.isMap(t))return n.Map?.(e,t,r);if(Se.isSeq(t))return n.Seq?.(e,t,r);if(Se.isPair(t))return n.Pair?.(e,t,r);if(Se.isScalar(t))return n.Scalar?.(e,t,r);if(Se.isAlias(t))return n.Alias?.(e,t,r)}function dk(e,t,n){let r=t[t.length-1];if(Se.isCollection(r))r.items[e]=n;else if(Se.isPair(r))e==="key"?r.key=n:r.value=n;else if(Se.isDocument(r))r.contents=n;else{let o=Se.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}Bm.visit=Ma;Bm.visitAsync=Na});var Um=D(ck=>{"use strict";var lk=ee(),Wj=ps(),Hj={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Bj=e=>e.replace(/[!,[\]{}]/g,t=>Hj[t]),fs=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,i]=r;return this.tags[s]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let i=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,i),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=t.match(/^(.*!)([^!]*)$/s);o||n(`The ${t} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(o)}catch(i){return n(String(i)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+Bj(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(t&&r.length>0&&lk.isNode(t.contents)){let s={};Wj.visit(t.contents,(i,a)=>{lk.isNode(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!t||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`
4
+ `)}};fs.defaultYaml={explicit:!1,version:"1.2"};fs.defaultTags={"!!":"tag:yaml.org,2002:"};ck.Directives=fs});var Pa=D(us=>{"use strict";var mk=ee(),Uj=ps();function Gj(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function pk(e){let t=new Set;return Uj.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function fk(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function Vj(e,t){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=pk(e));let i=fk(t,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(mk.isScalar(i.node)||mk.isCollection(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}us.anchorIsValid=Gj;us.anchorNames=pk;us.createNodeAnchors=Vj;us.findNewAnchor=fk});var Gm=D(uk=>{"use strict";function hs(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],a=hs(e,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=hs(e,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=hs(e,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=hs(e,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return e.call(t,n,r)}uk.applyReviver=hs});var bn=D(gk=>{"use strict";var Yj=ee();function hk(e,t,n){if(Array.isArray(e))return e.map((r,o)=>hk(r,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!Yj.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=e.toJSON(t,n);return n.onCreate&&n.onCreate(o),o}return typeof e=="bigint"&&!n?.keep?Number(e):e}gk.toJS=hk});var Da=D(wk=>{"use strict";var Kj=Gm(),yk=ee(),zj=bn(),Vm=class{constructor(t){Object.defineProperty(this,yk.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!yk.isDocument(t))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=zj.toJS(this,"",i);if(typeof o=="function")for(let{count:d,res:l}of i.anchors.values())o(l,d);return typeof s=="function"?Kj.applyReviver(s,{"":a},"",a):a}};wk.NodeBase=Vm});var gs=D(bk=>{"use strict";var Jj=Pa(),Xj=ps(),ao=ee(),Qj=Da(),Zj=bn(),Ym=class extends Qj.NodeBase{constructor(t){super(ao.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Xj.visit(t,{Node:(s,i)=>{(ao.isAlias(i)||ao.hasAnchor(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let o;for(let s of r){if(s===this)break;s.anchor===this.source&&(o=s)}if(o&&n){let{anchors:s,doc:i,maxAliasCount:a}=n,d=s.get(o);if(d||(Zj.toJS(o,null,n),d=s.get(o)),d?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(d.count+=1,d.aliasCount===0&&(d.aliasCount=La(i,o,s)),d.count*d.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return o}toJSON(t,n){if(!n)return{source:this.source};let r=this.resolve(n.doc,n);if(!r){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(o)}return n.anchors.get(r).res}toString(t,n,r){let o=`*${this.source}`;if(t){if(Jj.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${o} `}return o}};function La(e,t,n){if(ao.isAlias(t)){let r=t.resolve(e),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(ao.isCollection(t)){let r=0;for(let o of t.items){let s=La(e,o,n);s>r&&(r=s)}return r}else if(ao.isPair(t)){let r=La(e,t.key,n),o=La(e,t.value,n);return Math.max(r,o)}return 1}bk.Alias=Ym});var Ce=D(Km=>{"use strict";var e1=ee(),t1=Da(),n1=bn(),r1=e=>!e||typeof e!="function"&&typeof e!="object",En=class extends t1.NodeBase{constructor(t){super(e1.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:n1.toJS(this.value,t,n)}toString(){return String(this.value)}};En.BLOCK_FOLDED="BLOCK_FOLDED";En.BLOCK_LITERAL="BLOCK_LITERAL";En.PLAIN="PLAIN";En.QUOTE_DOUBLE="QUOTE_DOUBLE";En.QUOTE_SINGLE="QUOTE_SINGLE";Km.Scalar=En;Km.isScalarValue=r1});var ys=D(Ck=>{"use strict";var o1=gs(),dr=ee(),Ek=Ce(),s1="tag:yaml.org,2002:";function i1(e,t,n){if(t){let r=n.filter(s=>s.tag===t),o=r.find(s=>!s.format)??r[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return n.find(r=>r.identify?.(e)&&!r.format)}function a1(e,t,n){if(dr.isDocument(e)&&(e=e.contents),dr.isNode(e))return e;if(dr.isPair(e)){let m=n.schema[dr.MAP].createNode?.(n.schema,null,n);return m.items.push(e),m}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,d;if(r&&e&&typeof e=="object"){if(d=a.get(e),d)return d.anchor??(d.anchor=o(e)),new o1.Alias(d.anchor);d={anchor:null,node:null},a.set(e,d)}t?.startsWith("!!")&&(t=s1+t.slice(2));let l=i1(e,t,i.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let m=new Ek.Scalar(e);return d&&(d.node=m),m}l=e instanceof Map?i[dr.MAP]:Symbol.iterator in Object(e)?i[dr.SEQ]:i[dr.MAP]}s&&(s(l),delete n.onTagObj);let c=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,e,n):new Ek.Scalar(e);return t?c.tag=t:l.default||(c.tag=l.tag),d&&(d.node=c),c}Ck.createNode=a1});var ja=D(_a=>{"use strict";var d1=ys(),St=ee(),l1=Da();function zm(e,t,n){let r=n;for(let o=t.length-1;o>=0;--o){let s=t[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let i=[];i[s]=r,r=i}else r=new Map([[s,r]])}return d1.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Rk=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Jm=class extends l1.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>St.isNode(r)||St.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(Rk(t))this.add(n);else{let[r,...o]=t,s=this.get(r,!0);if(St.isCollection(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,zm(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(St.isCollection(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...o]=t,s=this.get(r,!0);return o.length===0?!n&&St.isScalar(s)?s.value:s:St.isCollection(s)?s.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!St.isPair(n))return!1;let r=n.value;return r==null||t&&St.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let o=this.get(n,!0);return St.isCollection(o)?o.hasIn(r):!1}setIn(t,n){let[r,...o]=t;if(o.length===0)this.set(r,n);else{let s=this.get(r,!0);if(St.isCollection(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,zm(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};_a.Collection=Jm;_a.collectionFromPath=zm;_a.isEmptyPath=Rk});var ws=D(Fa=>{"use strict";var c1=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Xm(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var m1=(e,t,n)=>e.endsWith(`
5
+ `)?Xm(n,t):n.includes(`
6
6
  `)?`
7
- `+Nc(n,t):(e.endsWith(" ")?"":" ")+n;Pi.indentComment=Nc;Pi.lineComment=QN;Pi.stringifyComment=XN});var bb=L(Ts=>{"use strict";var ZN="flow",Lc="block",Di="quoted";function eL(e,t,n="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:o=20,onFold:i,onOverflow:a}={}){if(!s||s<0)return e;s<o&&(o=0);let d=Math.max(1+o,1+s-t.length);if(e.length<=d)return e;let l=[],c={},m=s-t.length;typeof r=="number"&&(r>s-Math.max(2,o)?l.push(0):m=s-r);let f,g,u=!1,h=-1,y=-1,k=-1;n===Lc&&(h=wb(e,h,t.length),h!==-1&&(m=h+d));for(let I;I=e[h+=1];){if(n===Di&&I==="\\"){switch(y=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}k=h}if(I===`
8
- `)n===Lc&&(h=wb(e,h,t.length)),m=h+t.length+d,f=void 0;else{if(I===" "&&g&&g!==" "&&g!==`
9
- `&&g!==" "){let x=e[h+1];x&&x!==" "&&x!==`
10
- `&&x!==" "&&(f=h)}if(h>=m)if(f)l.push(f),m=f+d,f=void 0;else if(n===Di){for(;g===" "||g===" ";)g=I,I=e[h+=1],u=!0;let x=h>k+1?h-2:y-1;if(c[x])return e;l.push(x),c[x]=!0,m=x+d,f=void 0}else u=!0}g=I}if(u&&a&&a(),l.length===0)return e;i&&i();let S=e.slice(0,l[0]);for(let I=0;I<l.length;++I){let x=l[I],E=l[I+1]||e.length;x===0?S=`
11
- ${t}${e.slice(0,E)}`:(n===Di&&c[x]&&(S+=`${e[x]}\\`),S+=`
12
- ${t}${e.slice(x+1,E)}`)}return S}function wb(e,t,n){let r=t,s=t+1,o=e[s];for(;o===" "||o===" ";)if(t<s+n)o=e[++t];else{do o=e[++t];while(o&&o!==`
13
- `);r=t,s=t+1,o=e[s]}return r}Ts.FOLD_BLOCK=Lc;Ts.FOLD_FLOW=ZN;Ts.FOLD_QUOTED=Di;Ts.foldFlowLines=eL});var Ns=L(kb=>{"use strict";var Je=pe(),Qt=bb(),ji=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Fi=e=>/^(%|---|\.\.\.)/m.test(e);function tL(e,t,n){if(!t||t<0)return!1;let r=t-n,s=e.length;if(s<=r)return!1;for(let o=0,i=0;o<s;++o)if(e[o]===`
14
- `){if(o-i>r)return!0;if(i=o+1,s-i<=r)return!1}return!0}function Os(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,s=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(Fi(e)?" ":""),i="",a=0;for(let d=0,l=n[d];l;l=n[++d])if(l===" "&&n[d+1]==="\\"&&n[d+2]==="n"&&(i+=n.slice(a,d)+"\\ ",d+=1,a=d,l="\\"),l==="\\")switch(n[d+1]){case"u":{i+=n.slice(a,d);let c=n.substr(d+2,4);switch(c){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:c.substr(0,2)==="00"?i+="\\x"+c.substr(2):i+=n.substr(d,6)}d+=5,a=d+1}break;case"n":if(r||n[d+2]==='"'||n.length<s)d+=1;else{for(i+=n.slice(a,d)+`
7
+ `+Xm(n,t):(e.endsWith(" ")?"":" ")+n;Fa.indentComment=Xm;Fa.lineComment=m1;Fa.stringifyComment=c1});var vk=D(bs=>{"use strict";var p1="flow",Qm="block",qa="quoted";function f1(e,t,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}={}){if(!o||o<0)return e;o<s&&(s=0);let d=Math.max(1+s,1+o-t.length);if(e.length<=d)return e;let l=[],c={},m=o-t.length;typeof r=="number"&&(r>o-Math.max(2,s)?l.push(0):m=o-r);let p,h,u=!1,y=-1,w=-1,E=-1;n===Qm&&(y=kk(e,y,t.length),y!==-1&&(m=y+d));for(let v;v=e[y+=1];){if(n===qa&&v==="\\"){switch(w=y,e[y+1]){case"x":y+=3;break;case"u":y+=5;break;case"U":y+=9;break;default:y+=1}E=y}if(v===`
8
+ `)n===Qm&&(y=kk(e,y,t.length)),m=y+t.length+d,p=void 0;else{if(v===" "&&h&&h!==" "&&h!==`
9
+ `&&h!==" "){let $=e[y+1];$&&$!==" "&&$!==`
10
+ `&&$!==" "&&(p=y)}if(y>=m)if(p)l.push(p),m=p+d,p=void 0;else if(n===qa){for(;h===" "||h===" ";)h=v,v=e[y+=1],u=!0;let $=y>E+1?y-2:w-1;if(c[$])return e;l.push($),c[$]=!0,m=$+d,p=void 0}else u=!0}h=v}if(u&&a&&a(),l.length===0)return e;i&&i();let I=e.slice(0,l[0]);for(let v=0;v<l.length;++v){let $=l[v],C=l[v+1]||e.length;$===0?I=`
11
+ ${t}${e.slice(0,C)}`:(n===qa&&c[$]&&(I+=`${e[$]}\\`),I+=`
12
+ ${t}${e.slice($+1,C)}`)}return I}function kk(e,t,n){let r=t,o=t+1,s=e[o];for(;s===" "||s===" ";)if(t<o+n)s=e[++t];else{do s=e[++t];while(s&&s!==`
13
+ `);r=t,o=t+1,s=e[o]}return r}bs.FOLD_BLOCK=Qm;bs.FOLD_FLOW=p1;bs.FOLD_QUOTED=qa;bs.foldFlowLines=f1});var Cs=D(Ik=>{"use strict";var ct=Ce(),Cn=vk(),Ha=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Ba=e=>/^(%|---|\.\.\.)/m.test(e);function u1(e,t,n){if(!t||t<0)return!1;let r=t-n,o=e.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(e[s]===`
14
+ `){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function Es(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,o=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(Ba(e)?" ":""),i="",a=0;for(let d=0,l=n[d];l;l=n[++d])if(l===" "&&n[d+1]==="\\"&&n[d+2]==="n"&&(i+=n.slice(a,d)+"\\ ",d+=1,a=d,l="\\"),l==="\\")switch(n[d+1]){case"u":{i+=n.slice(a,d);let c=n.substr(d+2,4);switch(c){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:c.substr(0,2)==="00"?i+="\\x"+c.substr(2):i+=n.substr(d,6)}d+=5,a=d+1}break;case"n":if(r||n[d+2]==='"'||n.length<o)d+=1;else{for(i+=n.slice(a,d)+`
15
15
 
16
16
  `;n[d+2]==="\\"&&n[d+3]==="n"&&n[d+4]!=='"';)i+=`
17
- `,d+=2;i+=o,n[d+2]===" "&&(i+="\\"),d+=1,a=d+1}break;default:d+=1}return i=a?i+n.slice(a):n,r?i:Qt.foldFlowLines(i,o,Qt.FOLD_QUOTED,ji(t,!1))}function Pc(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
18
- `)||/[ \t]\n|\n[ \t]/.test(e))return Os(e,t);let n=t.indent||(Fi(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
19
- ${n}`)+"'";return t.implicitKey?r:Qt.foldFlowLines(r,n,Qt.FOLD_FLOW,ji(t,!1))}function $r(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Os;else{let s=e.includes('"'),o=e.includes("'");s&&!o?r=Pc:o&&!s?r=Os:r=n?Pc:Os}return r(e,t)}var Dc;try{Dc=new RegExp(`(^|(?<!
17
+ `,d+=2;i+=s,n[d+2]===" "&&(i+="\\"),d+=1,a=d+1}break;default:d+=1}return i=a?i+n.slice(a):n,r?i:Cn.foldFlowLines(i,s,Cn.FOLD_QUOTED,Ha(t,!1))}function Zm(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
18
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Es(e,t);let n=t.indent||(Ba(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
19
+ ${n}`)+"'";return t.implicitKey?r:Cn.foldFlowLines(r,n,Cn.FOLD_FLOW,Ha(t,!1))}function lo(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Es;else{let o=e.includes('"'),s=e.includes("'");o&&!s?r=Zm:s&&!o?r=Es:r=n?Zm:Es}return r(e,t)}var ep;try{ep=new RegExp(`(^|(?<!
20
20
  ))
21
21
  +(?!
22
- |$)`,"g")}catch{Dc=/\n+(?!\n|$)/g}function _i({comment:e,type:t,value:n},r,s,o){let{blockQuote:i,commentString:a,lineWidth:d}=r.options;if(!i||/\n[\t ]+$/.test(n))return $r(n,r);let l=r.indent||(r.forceBlockIndent||Fi(n)?" ":""),c=i==="literal"?!0:i==="folded"||t===Je.Scalar.BLOCK_FOLDED?!1:t===Je.Scalar.BLOCK_LITERAL?!0:!tL(n,d,l.length);if(!n)return c?`|
22
+ |$)`,"g")}catch{ep=/\n+(?!\n|$)/g}function Wa({comment:e,type:t,value:n},r,o,s){let{blockQuote:i,commentString:a,lineWidth:d}=r.options;if(!i||/\n[\t ]+$/.test(n))return lo(n,r);let l=r.indent||(r.forceBlockIndent||Ba(n)?" ":""),c=i==="literal"?!0:i==="folded"||t===ct.Scalar.BLOCK_FOLDED?!1:t===ct.Scalar.BLOCK_LITERAL?!0:!u1(n,d,l.length);if(!n)return c?`|
23
23
  `:`>
24
- `;let m,f;for(f=n.length;f>0;--f){let E=n[f-1];if(E!==`
25
- `&&E!==" "&&E!==" ")break}let g=n.substring(f),u=g.indexOf(`
26
- `);u===-1?m="-":n===g||u!==g.length-1?(m="+",o&&o()):m="",g&&(n=n.slice(0,-g.length),g[g.length-1]===`
27
- `&&(g=g.slice(0,-1)),g=g.replace(Dc,`$&${l}`));let h=!1,y,k=-1;for(y=0;y<n.length;++y){let E=n[y];if(E===" ")h=!0;else if(E===`
28
- `)k=y;else break}let S=n.substring(0,k<y?k+1:y);S&&(n=n.substring(S.length),S=S.replace(/\n+/g,`$&${l}`));let x=(h?l?"2":"1":"")+m;if(e&&(x+=" "+a(e.replace(/ ?[\r\n]+/g," ")),s&&s()),!c){let E=n.replace(/\n+/g,`
29
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),M=!1,v=ji(r,!0);i!=="folded"&&t!==Je.Scalar.BLOCK_FOLDED&&(v.onOverflow=()=>{M=!0});let C=Qt.foldFlowLines(`${S}${E}${g}`,l,Qt.FOLD_BLOCK,v);if(!M)return`>${x}
30
- ${l}${C}`}return n=n.replace(/\n+/g,`$&${l}`),`|${x}
31
- ${l}${S}${n}${g}`}function nL(e,t,n,r){let{type:s,value:o}=e,{actualString:i,implicitKey:a,indent:d,indentStep:l,inFlow:c}=t;if(a&&o.includes(`
32
- `)||c&&/[[\]{},]/.test(o))return $r(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||c||!o.includes(`
33
- `)?$r(o,t):_i(e,t,n,r);if(!a&&!c&&s!==Je.Scalar.PLAIN&&o.includes(`
34
- `))return _i(e,t,n,r);if(Fi(o)){if(d==="")return t.forceBlockIndent=!0,_i(e,t,n,r);if(a&&d===l)return $r(o,t)}let m=o.replace(/\n+/g,`$&
35
- ${d}`);if(i){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(m),{compat:g,tags:u}=t.doc.schema;if(u.some(f)||g?.some(f))return $r(o,t)}return a?m:Qt.foldFlowLines(m,d,Qt.FOLD_FLOW,ji(t,!1))}function rL(e,t,n,r){let{implicitKey:s,inFlow:o}=t,i=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==Je.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=Je.Scalar.QUOTE_DOUBLE);let d=c=>{switch(c){case Je.Scalar.BLOCK_FOLDED:case Je.Scalar.BLOCK_LITERAL:return s||o?$r(i.value,t):_i(i,t,n,r);case Je.Scalar.QUOTE_DOUBLE:return Os(i.value,t);case Je.Scalar.QUOTE_SINGLE:return Pc(i.value,t);case Je.Scalar.PLAIN:return nL(i,t,n,r);default:return null}},l=d(a);if(l===null){let{defaultKeyType:c,defaultStringType:m}=t.options,f=s&&c||m;if(l=d(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}kb.stringifyString=rL});var Ls=L(_c=>{"use strict";var sL=Ai(),Zt=G(),oL=As(),iL=Ns();function aL(e,t){let n=Object.assign({blockQuote:!0,commentString:oL.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function dL(e,t){if(t.tag){let s=e.filter(o=>o.tag===t.tag);if(s.length>0)return s.find(o=>o.format===t.format)??s[0]}let n,r;if(Zt.isScalar(t)){r=t.value;let s=e.filter(o=>o.identify?.(r));if(s.length>1){let o=s.filter(i=>i.test);o.length>0&&(s=o)}n=s.find(o=>o.format===t.format)??s.find(o=>!o.format)}else r=t,n=e.find(s=>s.nodeClass&&r instanceof s.nodeClass);if(!n){let s=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${s} value`)}return n}function lL(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let s=[],o=(Zt.isScalar(e)||Zt.isCollection(e))&&e.anchor;o&&sL.anchorIsValid(o)&&(n.add(o),s.push(`&${o}`));let i=e.tag??(t.default?null:t.tag);return i&&s.push(r.directives.tagString(i)),s.join(" ")}function cL(e,t,n,r){if(Zt.isPair(e))return e.toString(t,n,r);if(Zt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let s,o=Zt.isNode(e)?e:t.doc.createNode(e,{onTagObj:d=>s=d});s??(s=dL(t.doc.schema.tags,o));let i=lL(o,s,t);i.length>0&&(t.indentAtStart=(t.indentAtStart??0)+i.length+1);let a=typeof s.stringify=="function"?s.stringify(o,t,n,r):Zt.isScalar(o)?iL.stringifyString(o,t,n,r):o.toString(t,n,r);return i?Zt.isScalar(o)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
36
- ${t.indent}${a}`:a}_c.createStringifyContext=aL;_c.stringify=cL});var Sb=L(Rb=>{"use strict";var It=G(),Eb=pe(),Cb=Ls(),Ps=As();function mL({key:e,value:t},n,r,s){let{allNullValues:o,doc:i,indent:a,indentStep:d,options:{commentString:l,indentSeq:c,simpleKeys:m}}=n,f=It.isNode(e)&&e.comment||null;if(m){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(It.isCollection(e)||!It.isNode(e)&&typeof e=="object"){let v="With simple keys, collection cannot be used as a key value";throw new Error(v)}}let g=!m&&(!e||f&&t==null&&!n.inFlow||It.isCollection(e)||(It.isScalar(e)?e.type===Eb.Scalar.BLOCK_FOLDED||e.type===Eb.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!g&&(m||!o),indent:a+d});let u=!1,h=!1,y=Cb.stringify(e,n,()=>u=!0,()=>h=!0);if(!g&&!n.inFlow&&y.length>1024){if(m)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(n.inFlow){if(o||t==null)return u&&r&&r(),y===""?"?":g?`? ${y}`:y}else if(o&&!m||t==null&&g)return y=`? ${y}`,f&&!u?y+=Ps.lineComment(y,n.indent,l(f)):h&&s&&s(),y;u&&(f=null),g?(f&&(y+=Ps.lineComment(y,n.indent,l(f))),y=`? ${y}
37
- ${a}:`):(y=`${y}:`,f&&(y+=Ps.lineComment(y,n.indent,l(f))));let k,S,I;It.isNode(t)?(k=!!t.spaceBefore,S=t.commentBefore,I=t.comment):(k=!1,S=null,I=null,t&&typeof t=="object"&&(t=i.createNode(t))),n.implicitKey=!1,!g&&!f&&It.isScalar(t)&&(n.indentAtStart=y.length+1),h=!1,!c&&d.length>=2&&!n.inFlow&&!g&&It.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let x=!1,E=Cb.stringify(t,n,()=>x=!0,()=>h=!0),M=" ";if(f||k||S){if(M=k?`
38
- `:"",S){let v=l(S);M+=`
39
- ${Ps.indentComment(v,n.indent)}`}E===""&&!n.inFlow?M===`
40
- `&&I&&(M=`
24
+ `;let m,p;for(p=n.length;p>0;--p){let C=n[p-1];if(C!==`
25
+ `&&C!==" "&&C!==" ")break}let h=n.substring(p),u=h.indexOf(`
26
+ `);u===-1?m="-":n===h||u!==h.length-1?(m="+",s&&s()):m="",h&&(n=n.slice(0,-h.length),h[h.length-1]===`
27
+ `&&(h=h.slice(0,-1)),h=h.replace(ep,`$&${l}`));let y=!1,w,E=-1;for(w=0;w<n.length;++w){let C=n[w];if(C===" ")y=!0;else if(C===`
28
+ `)E=w;else break}let I=n.substring(0,E<w?E+1:w);I&&(n=n.substring(I.length),I=I.replace(/\n+/g,`$&${l}`));let $=(y?l?"2":"1":"")+m;if(e&&($+=" "+a(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!c){let C=n.replace(/\n+/g,`
29
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),x=!1,L=Ha(r,!0);i!=="folded"&&t!==ct.Scalar.BLOCK_FOLDED&&(L.onOverflow=()=>{x=!0});let R=Cn.foldFlowLines(`${I}${C}${h}`,l,Cn.FOLD_BLOCK,L);if(!x)return`>${$}
30
+ ${l}${R}`}return n=n.replace(/\n+/g,`$&${l}`),`|${$}
31
+ ${l}${I}${n}${h}`}function h1(e,t,n,r){let{type:o,value:s}=e,{actualString:i,implicitKey:a,indent:d,indentStep:l,inFlow:c}=t;if(a&&s.includes(`
32
+ `)||c&&/[[\]{},]/.test(s))return lo(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||c||!s.includes(`
33
+ `)?lo(s,t):Wa(e,t,n,r);if(!a&&!c&&o!==ct.Scalar.PLAIN&&s.includes(`
34
+ `))return Wa(e,t,n,r);if(Ba(s)){if(d==="")return t.forceBlockIndent=!0,Wa(e,t,n,r);if(a&&d===l)return lo(s,t)}let m=s.replace(/\n+/g,`$&
35
+ ${d}`);if(i){let p=y=>y.default&&y.tag!=="tag:yaml.org,2002:str"&&y.test?.test(m),{compat:h,tags:u}=t.doc.schema;if(u.some(p)||h?.some(p))return lo(s,t)}return a?m:Cn.foldFlowLines(m,d,Cn.FOLD_FLOW,Ha(t,!1))}function g1(e,t,n,r){let{implicitKey:o,inFlow:s}=t,i=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==ct.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=ct.Scalar.QUOTE_DOUBLE);let d=c=>{switch(c){case ct.Scalar.BLOCK_FOLDED:case ct.Scalar.BLOCK_LITERAL:return o||s?lo(i.value,t):Wa(i,t,n,r);case ct.Scalar.QUOTE_DOUBLE:return Es(i.value,t);case ct.Scalar.QUOTE_SINGLE:return Zm(i.value,t);case ct.Scalar.PLAIN:return h1(i,t,n,r);default:return null}},l=d(a);if(l===null){let{defaultKeyType:c,defaultStringType:m}=t.options,p=o&&c||m;if(l=d(p),l===null)throw new Error(`Unsupported default string type ${p}`)}return l}Ik.stringifyString=g1});var Rs=D(tp=>{"use strict";var y1=Pa(),Rn=ee(),w1=ws(),b1=Cs();function E1(e,t){let n=Object.assign({blockQuote:!0,commentString:w1.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function C1(e,t){if(t.tag){let o=e.filter(s=>s.tag===t.tag);if(o.length>0)return o.find(s=>s.format===t.format)??o[0]}let n,r;if(Rn.isScalar(t)){r=t.value;let o=e.filter(s=>s.identify?.(r));if(o.length>1){let s=o.filter(i=>i.test);s.length>0&&(o=s)}n=o.find(s=>s.format===t.format)??o.find(s=>!s.format)}else r=t,n=e.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){let o=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${o} value`)}return n}function R1(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(Rn.isScalar(e)||Rn.isCollection(e))&&e.anchor;s&&y1.anchorIsValid(s)&&(n.add(s),o.push(`&${s}`));let i=e.tag??(t.default?null:t.tag);return i&&o.push(r.directives.tagString(i)),o.join(" ")}function k1(e,t,n,r){if(Rn.isPair(e))return e.toString(t,n,r);if(Rn.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let o,s=Rn.isNode(e)?e:t.doc.createNode(e,{onTagObj:d=>o=d});o??(o=C1(t.doc.schema.tags,s));let i=R1(s,o,t);i.length>0&&(t.indentAtStart=(t.indentAtStart??0)+i.length+1);let a=typeof o.stringify=="function"?o.stringify(s,t,n,r):Rn.isScalar(s)?b1.stringifyString(s,t,n,r):s.toString(t,n,r);return i?Rn.isScalar(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
36
+ ${t.indent}${a}`:a}tp.createStringifyContext=E1;tp.stringify=k1});var xk=D(Tk=>{"use strict";var Bt=ee(),Sk=Ce(),$k=Rs(),ks=ws();function v1({key:e,value:t},n,r,o){let{allNullValues:s,doc:i,indent:a,indentStep:d,options:{commentString:l,indentSeq:c,simpleKeys:m}}=n,p=Bt.isNode(e)&&e.comment||null;if(m){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Bt.isCollection(e)||!Bt.isNode(e)&&typeof e=="object"){let L="With simple keys, collection cannot be used as a key value";throw new Error(L)}}let h=!m&&(!e||p&&t==null&&!n.inFlow||Bt.isCollection(e)||(Bt.isScalar(e)?e.type===Sk.Scalar.BLOCK_FOLDED||e.type===Sk.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(m||!s),indent:a+d});let u=!1,y=!1,w=$k.stringify(e,n,()=>u=!0,()=>y=!0);if(!h&&!n.inFlow&&w.length>1024){if(m)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||t==null)return u&&r&&r(),w===""?"?":h?`? ${w}`:w}else if(s&&!m||t==null&&h)return w=`? ${w}`,p&&!u?w+=ks.lineComment(w,n.indent,l(p)):y&&o&&o(),w;u&&(p=null),h?(p&&(w+=ks.lineComment(w,n.indent,l(p))),w=`? ${w}
37
+ ${a}:`):(w=`${w}:`,p&&(w+=ks.lineComment(w,n.indent,l(p))));let E,I,v;Bt.isNode(t)?(E=!!t.spaceBefore,I=t.commentBefore,v=t.comment):(E=!1,I=null,v=null,t&&typeof t=="object"&&(t=i.createNode(t))),n.implicitKey=!1,!h&&!p&&Bt.isScalar(t)&&(n.indentAtStart=w.length+1),y=!1,!c&&d.length>=2&&!n.inFlow&&!h&&Bt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let $=!1,C=$k.stringify(t,n,()=>$=!0,()=>y=!0),x=" ";if(p||E||I){if(x=E?`
38
+ `:"",I){let L=l(I);x+=`
39
+ ${ks.indentComment(L,n.indent)}`}C===""&&!n.inFlow?x===`
40
+ `&&v&&(x=`
41
41
 
42
- `):M+=`
43
- ${n.indent}`}else if(!g&&It.isCollection(t)){let v=E[0],C=E.indexOf(`
44
- `),R=C!==-1,A=n.inFlow??t.flow??t.items.length===0;if(R||!A){let T=!1;if(R&&(v==="&"||v==="!")){let N=E.indexOf(" ");v==="&"&&N!==-1&&N<C&&E[N+1]==="!"&&(N=E.indexOf(" ",N+1)),(N===-1||C<N)&&(T=!0)}T||(M=`
45
- ${n.indent}`)}}else(E===""||E[0]===`
46
- `)&&(M="");return y+=M+E,n.inFlow?x&&r&&r():I&&!x?y+=Ps.lineComment(y,n.indent,l(I)):h&&s&&s(),y}Rb.stringifyPair=mL});var Fc=L(jc=>{"use strict";var vb=Co("process");function fL(e,...t){e==="debug"&&console.log(...t)}function uL(e,t){(e==="debug"||e==="warn")&&(typeof vb.emitWarning=="function"?vb.emitWarning(t):console.warn(t))}jc.debug=fL;jc.warn=uL});var Hi=L(Ui=>{"use strict";var Wi=G(),Ib=pe(),qi="<<",Bi={identify:e=>e===qi||typeof e=="symbol"&&e.description===qi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ib.Scalar(Symbol(qi)),{addToJSMap:$b}),stringify:()=>qi},pL=(e,t)=>(Bi.identify(t)||Wi.isScalar(t)&&(!t.type||t.type===Ib.Scalar.PLAIN)&&Bi.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Bi.tag&&n.default);function $b(e,t,n){let r=xb(e,n);if(Wi.isSeq(r))for(let s of r.items)qc(e,t,s);else if(Array.isArray(r))for(let s of r)qc(e,t,s);else qc(e,t,r)}function qc(e,t,n){let r=xb(e,n);if(!Wi.isMap(r))throw new Error("Merge sources must be maps or map aliases");let s=r.toJSON(null,e,Map);for(let[o,i]of s)t instanceof Map?t.has(o)||t.set(o,i):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0});return t}function xb(e,t){return e&&Wi.isAlias(t)?t.resolve(e.doc,e):t}Ui.addMergeToJSMap=$b;Ui.isMergeKey=pL;Ui.merge=Bi});var Wc=L(Tb=>{"use strict";var hL=Fc(),Mb=Hi(),gL=Ls(),Ab=G(),Bc=Jt();function yL(e,t,{key:n,value:r}){if(Ab.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Mb.isMergeKey(e,n))Mb.addMergeToJSMap(e,t,r);else{let s=Bc.toJS(n,"",e);if(t instanceof Map)t.set(s,Bc.toJS(r,s,e));else if(t instanceof Set)t.add(s);else{let o=wL(n,s,e),i=Bc.toJS(r,o,e);o in t?Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0}):t[o]=i}}return t}function wL(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Ab.isNode(e)&&n?.doc){let r=gL.createStringifyContext(n.doc,{});r.anchors=new Set;for(let o of n.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let s=e.toString(r);if(!n.mapKeyWarned){let o=JSON.stringify(s);o.length>40&&(o=o.substring(0,36)+'..."'),hL.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return s}return JSON.stringify(t)}Tb.addPairToJSMap=yL});var en=L(Uc=>{"use strict";var Ob=Ms(),bL=Sb(),kL=Wc(),Gi=G();function EL(e,t,n){let r=Ob.createNode(e,void 0,n),s=Ob.createNode(t,void 0,n);return new Vi(r,s)}var Vi=class e{constructor(t,n=null){Object.defineProperty(this,Gi.NODE_TYPE,{value:Gi.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return Gi.isNode(n)&&(n=n.clone(t)),Gi.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return kL.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?bL.stringifyPair(this,t,n,r):JSON.stringify(this)}};Uc.Pair=Vi;Uc.createPair=EL});var Hc=L(Lb=>{"use strict";var Nn=G(),Nb=Ls(),Ki=As();function CL(e,t,n){return(t.inFlow??e.flow?SL:RL)(e,t,n)}function RL({comment:e,items:t},n,{blockItemPrefix:r,flowChars:s,itemIndent:o,onChompKeep:i,onComment:a}){let{indent:d,options:{commentString:l}}=n,c=Object.assign({},n,{indent:o,type:null}),m=!1,f=[];for(let u=0;u<t.length;++u){let h=t[u],y=null;if(Nn.isNode(h))!m&&h.spaceBefore&&f.push(""),Yi(n,f,h.commentBefore,m),h.comment&&(y=h.comment);else if(Nn.isPair(h)){let S=Nn.isNode(h.key)?h.key:null;S&&(!m&&S.spaceBefore&&f.push(""),Yi(n,f,S.commentBefore,m))}m=!1;let k=Nb.stringify(h,c,()=>y=null,()=>m=!0);y&&(k+=Ki.lineComment(k,o,l(y))),m&&y&&(m=!1),f.push(r+k)}let g;if(f.length===0)g=s.start+s.end;else{g=f[0];for(let u=1;u<f.length;++u){let h=f[u];g+=h?`
47
- ${d}${h}`:`
48
- `}}return e?(g+=`
49
- `+Ki.indentComment(l(e),d),a&&a()):m&&i&&i(),g}function SL({items:e},t,{flowChars:n,itemIndent:r}){let{indent:s,indentStep:o,flowCollectionPadding:i,options:{commentString:a}}=t;r+=o;let d=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,c=0,m=[];for(let u=0;u<e.length;++u){let h=e[u],y=null;if(Nn.isNode(h))h.spaceBefore&&m.push(""),Yi(t,m,h.commentBefore,!1),h.comment&&(y=h.comment);else if(Nn.isPair(h)){let S=Nn.isNode(h.key)?h.key:null;S&&(S.spaceBefore&&m.push(""),Yi(t,m,S.commentBefore,!1),S.comment&&(l=!0));let I=Nn.isNode(h.value)?h.value:null;I?(I.comment&&(y=I.comment),I.commentBefore&&(l=!0)):h.value==null&&S?.comment&&(y=S.comment)}y&&(l=!0);let k=Nb.stringify(h,d,()=>y=null);l||(l=m.length>c||k.includes(`
50
- `)),u<e.length-1?k+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=m.reduce((S,I)=>S+I.length+2,2)+(k.length+2)>t.options.lineWidth)),l&&(k+=",")),y&&(k+=Ki.lineComment(k,r,a(y))),m.push(k),c=m.length}let{start:f,end:g}=n;if(m.length===0)return f+g;if(!l){let u=m.reduce((h,y)=>h+y.length+2,2);l=t.options.lineWidth>0&&u>t.options.lineWidth}if(l){let u=f;for(let h of m)u+=h?`
51
- ${o}${s}${h}`:`
42
+ `):x+=`
43
+ ${n.indent}`}else if(!h&&Bt.isCollection(t)){let L=C[0],R=C.indexOf(`
44
+ `),S=R!==-1,T=n.inFlow??t.flow??t.items.length===0;if(S||!T){let O=!1;if(S&&(L==="&"||L==="!")){let M=C.indexOf(" ");L==="&"&&M!==-1&&M<R&&C[M+1]==="!"&&(M=C.indexOf(" ",M+1)),(M===-1||R<M)&&(O=!0)}O||(x=`
45
+ ${n.indent}`)}}else(C===""||C[0]===`
46
+ `)&&(x="");return w+=x+C,n.inFlow?$&&r&&r():v&&!$?w+=ks.lineComment(w,n.indent,l(v)):y&&o&&o(),w}Tk.stringifyPair=v1});var rp=D(np=>{"use strict";var Ak=li("process");function I1(e,...t){e==="debug"&&console.log(...t)}function S1(e,t){(e==="debug"||e==="warn")&&(typeof Ak.emitWarning=="function"?Ak.emitWarning(t):console.warn(t))}np.debug=I1;np.warn=S1});var Ka=D(Ya=>{"use strict";var Va=ee(),Ok=Ce(),Ua="<<",Ga={identify:e=>e===Ua||typeof e=="symbol"&&e.description===Ua,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ok.Scalar(Symbol(Ua)),{addToJSMap:Mk}),stringify:()=>Ua},$1=(e,t)=>(Ga.identify(t)||Va.isScalar(t)&&(!t.type||t.type===Ok.Scalar.PLAIN)&&Ga.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Ga.tag&&n.default);function Mk(e,t,n){let r=Nk(e,n);if(Va.isSeq(r))for(let o of r.items)op(e,t,o);else if(Array.isArray(r))for(let o of r)op(e,t,o);else op(e,t,r)}function op(e,t,n){let r=Nk(e,n);if(!Va.isMap(r))throw new Error("Merge sources must be maps or map aliases");let o=r.toJSON(null,e,Map);for(let[s,i]of o)t instanceof Map?t.has(s)||t.set(s,i):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:i,writable:!0,enumerable:!0,configurable:!0});return t}function Nk(e,t){return e&&Va.isAlias(t)?t.resolve(e.doc,e):t}Ya.addMergeToJSMap=Mk;Ya.isMergeKey=$1;Ya.merge=Ga});var ip=D(Lk=>{"use strict";var T1=rp(),Pk=Ka(),x1=Rs(),Dk=ee(),sp=bn();function A1(e,t,{key:n,value:r}){if(Dk.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Pk.isMergeKey(e,n))Pk.addMergeToJSMap(e,t,r);else{let o=sp.toJS(n,"",e);if(t instanceof Map)t.set(o,sp.toJS(r,o,e));else if(t instanceof Set)t.add(o);else{let s=O1(n,o,e),i=sp.toJS(r,s,e);s in t?Object.defineProperty(t,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):t[s]=i}}return t}function O1(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Dk.isNode(e)&&n?.doc){let r=x1.createStringifyContext(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let o=e.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(o);s.length>40&&(s=s.substring(0,36)+'..."'),T1.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(t)}Lk.addPairToJSMap=A1});var kn=D(ap=>{"use strict";var _k=ys(),M1=xk(),N1=ip(),za=ee();function P1(e,t,n){let r=_k.createNode(e,void 0,n),o=_k.createNode(t,void 0,n);return new Ja(r,o)}var Ja=class e{constructor(t,n=null){Object.defineProperty(this,za.NODE_TYPE,{value:za.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return za.isNode(n)&&(n=n.clone(t)),za.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return N1.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?M1.stringifyPair(this,t,n,r):JSON.stringify(this)}};ap.Pair=Ja;ap.createPair=P1});var dp=D(Fk=>{"use strict";var lr=ee(),jk=Rs(),Xa=ws();function D1(e,t,n){return(t.inFlow??e.flow?_1:L1)(e,t,n)}function L1({comment:e,items:t},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:a}){let{indent:d,options:{commentString:l}}=n,c=Object.assign({},n,{indent:s,type:null}),m=!1,p=[];for(let u=0;u<t.length;++u){let y=t[u],w=null;if(lr.isNode(y))!m&&y.spaceBefore&&p.push(""),Qa(n,p,y.commentBefore,m),y.comment&&(w=y.comment);else if(lr.isPair(y)){let I=lr.isNode(y.key)?y.key:null;I&&(!m&&I.spaceBefore&&p.push(""),Qa(n,p,I.commentBefore,m))}m=!1;let E=jk.stringify(y,c,()=>w=null,()=>m=!0);w&&(E+=Xa.lineComment(E,s,l(w))),m&&w&&(m=!1),p.push(r+E)}let h;if(p.length===0)h=o.start+o.end;else{h=p[0];for(let u=1;u<p.length;++u){let y=p[u];h+=y?`
47
+ ${d}${y}`:`
48
+ `}}return e?(h+=`
49
+ `+Xa.indentComment(l(e),d),a&&a()):m&&i&&i(),h}function _1({items:e},t,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:a}}=t;r+=s;let d=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,c=0,m=[];for(let u=0;u<e.length;++u){let y=e[u],w=null;if(lr.isNode(y))y.spaceBefore&&m.push(""),Qa(t,m,y.commentBefore,!1),y.comment&&(w=y.comment);else if(lr.isPair(y)){let I=lr.isNode(y.key)?y.key:null;I&&(I.spaceBefore&&m.push(""),Qa(t,m,I.commentBefore,!1),I.comment&&(l=!0));let v=lr.isNode(y.value)?y.value:null;v?(v.comment&&(w=v.comment),v.commentBefore&&(l=!0)):y.value==null&&I?.comment&&(w=I.comment)}w&&(l=!0);let E=jk.stringify(y,d,()=>w=null);l||(l=m.length>c||E.includes(`
50
+ `)),u<e.length-1?E+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=m.reduce((I,v)=>I+v.length+2,2)+(E.length+2)>t.options.lineWidth)),l&&(E+=",")),w&&(E+=Xa.lineComment(E,r,a(w))),m.push(E),c=m.length}let{start:p,end:h}=n;if(m.length===0)return p+h;if(!l){let u=m.reduce((y,w)=>y+w.length+2,2);l=t.options.lineWidth>0&&u>t.options.lineWidth}if(l){let u=p;for(let y of m)u+=y?`
51
+ ${s}${o}${y}`:`
52
52
  `;return`${u}
53
- ${s}${g}`}else return`${f}${i}${m.join(" ")}${i}${g}`}function Yi({indent:e,options:{commentString:t}},n,r,s){if(r&&s&&(r=r.replace(/^\n+/,"")),r){let o=Ki.indentComment(t(r),e);n.push(o.trimStart())}}Lb.stringifyCollection=CL});var nn=L(Vc=>{"use strict";var vL=Hc(),IL=Wc(),$L=Li(),tn=G(),zi=en(),xL=pe();function Ds(e,t){let n=tn.isScalar(t)?t.value:t;for(let r of e)if(tn.isPair(r)&&(r.key===t||r.key===n||tn.isScalar(r.key)&&r.key.value===n))return r}var Gc=class extends $L.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(tn.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:s,replacer:o}=r,i=new this(t),a=(d,l)=>{if(typeof o=="function")l=o.call(n,d,l);else if(Array.isArray(o)&&!o.includes(d))return;(l!==void 0||s)&&i.items.push(zi.createPair(d,l,r))};if(n instanceof Map)for(let[d,l]of n)a(d,l);else if(n&&typeof n=="object")for(let d of Object.keys(n))a(d,n[d]);return typeof t.sortMapEntries=="function"&&i.items.sort(t.sortMapEntries),i}add(t,n){let r;tn.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new zi.Pair(t,t?.value):r=new zi.Pair(t.key,t.value);let s=Ds(this.items,r.key),o=this.schema?.sortMapEntries;if(s){if(!n)throw new Error(`Key ${r.key} already set`);tn.isScalar(s.value)&&xL.isScalarValue(r.value)?s.value.value=r.value:s.value=r.value}else if(o){let i=this.items.findIndex(a=>o(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(t){let n=Ds(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let s=Ds(this.items,t)?.value;return(!n&&tn.isScalar(s)?s.value:s)??void 0}has(t){return!!Ds(this.items,t)}set(t,n){this.add(new zi.Pair(t,n),!0)}toJSON(t,n,r){let s=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(s);for(let o of this.items)IL.addPairToJSMap(n,s,o);return s}toString(t,n,r){if(!t)return JSON.stringify(this);for(let s of this.items)if(!tn.isPair(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),vL.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};Vc.YAMLMap=Gc;Vc.findPair=Ds});var xr=L(Db=>{"use strict";var ML=G(),Pb=nn(),AL={collection:"map",default:!0,nodeClass:Pb.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ML.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>Pb.YAMLMap.from(e,t,n)};Db.map=AL});var rn=L(_b=>{"use strict";var TL=Ms(),OL=Hc(),NL=Li(),Xi=G(),LL=pe(),PL=Jt(),Kc=class extends NL.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Xi.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=Ji(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=Ji(t);if(typeof r!="number")return;let s=this.items[r];return!n&&Xi.isScalar(s)?s.value:s}has(t){let n=Ji(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=Ji(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let s=this.items[r];Xi.isScalar(s)&&LL.isScalarValue(n)?s.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let s=0;for(let o of this.items)r.push(PL.toJS(o,String(s++),n));return r}toString(t,n,r){return t?OL.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:s}=r,o=new this(t);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof s=="function"){let d=n instanceof Set?a:String(i++);a=s.call(n,d,a)}o.items.push(TL.createNode(a,void 0,r))}}return o}};function Ji(e){let t=Xi.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}_b.YAMLSeq=Kc});var Mr=L(Fb=>{"use strict";var DL=G(),jb=rn(),_L={collection:"seq",default:!0,nodeClass:jb.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return DL.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>jb.YAMLSeq.from(e,t,n)};Fb.seq=_L});var _s=L(qb=>{"use strict";var jL=Ns(),FL={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),jL.stringifyString(e,t,n,r)}};qb.string=FL});var Qi=L(Ub=>{"use strict";var Bb=pe(),Wb={identify:e=>e==null,createNode:()=>new Bb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Bb.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Wb.test.test(e)?e:t.options.nullStr};Ub.nullTag=Wb});var Yc=L(Gb=>{"use strict";var qL=pe(),Hb={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new qL.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&Hb.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};Gb.boolTag=Hb});var Ar=L(Vb=>{"use strict";function BL({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let s=typeof r=="number"?r:Number(r);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let i=o.indexOf(".");i<0&&(i=o.length,o+=".");let a=t-(o.length-i-1);for(;a-- >0;)o+="0"}return o}Vb.stringifyNumber=BL});var Jc=L(Zi=>{"use strict";var WL=pe(),zc=Ar(),UL={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:zc.stringifyNumber},HL={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():zc.stringifyNumber(e)}},GL={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new WL.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:zc.stringifyNumber};Zi.float=GL;Zi.floatExp=HL;Zi.floatNaN=UL});var Qc=L(ta=>{"use strict";var Kb=Ar(),ea=e=>typeof e=="bigint"||Number.isInteger(e),Xc=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function Yb(e,t,n){let{value:r}=e;return ea(r)&&r>=0?n+r.toString(t):Kb.stringifyNumber(e)}var VL={identify:e=>ea(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Xc(e,2,8,n),stringify:e=>Yb(e,8,"0o")},KL={identify:ea,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Xc(e,0,10,n),stringify:Kb.stringifyNumber},YL={identify:e=>ea(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Xc(e,2,16,n),stringify:e=>Yb(e,16,"0x")};ta.int=KL;ta.intHex=YL;ta.intOct=VL});var Jb=L(zb=>{"use strict";var zL=xr(),JL=Qi(),XL=Mr(),QL=_s(),ZL=Yc(),Zc=Jc(),em=Qc(),eP=[zL.map,XL.seq,QL.string,JL.nullTag,ZL.boolTag,em.intOct,em.int,em.intHex,Zc.floatNaN,Zc.floatExp,Zc.float];zb.schema=eP});var Zb=L(Qb=>{"use strict";var tP=pe(),nP=xr(),rP=Mr();function Xb(e){return typeof e=="bigint"||Number.isInteger(e)}var na=({value:e})=>JSON.stringify(e),sP=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:na},{identify:e=>e==null,createNode:()=>new tP.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:na},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:na},{identify:Xb,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>Xb(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:na}],oP={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},iP=[nP.map,rP.seq].concat(sP,oP);Qb.schema=iP});var nm=L(ek=>{"use strict";var js=Co("buffer"),tm=pe(),aP=Ns(),dP={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof js.Buffer=="function")return js.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let s=0;s<n.length;++s)r[s]=n.charCodeAt(s);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,s,o){if(!n)return"";let i=n,a;if(typeof js.Buffer=="function")a=i instanceof js.Buffer?i.toString("base64"):js.Buffer.from(i.buffer).toString("base64");else if(typeof btoa=="function"){let d="";for(let l=0;l<i.length;++l)d+=String.fromCharCode(i[l]);a=btoa(d)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=tm.Scalar.BLOCK_LITERAL),t!==tm.Scalar.QUOTE_DOUBLE){let d=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(a.length/d),c=new Array(l);for(let m=0,f=0;m<l;++m,f+=d)c[m]=a.substr(f,d);a=c.join(t===tm.Scalar.BLOCK_LITERAL?`
54
- `:" ")}return aP.stringifyString({comment:e,type:t,value:a},r,s,o)}};ek.binary=dP});var oa=L(sa=>{"use strict";var ra=G(),rm=en(),lP=pe(),cP=rn();function tk(e,t){if(ra.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!ra.isPair(r)){if(ra.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let s=r.items[0]||new rm.Pair(new lP.Scalar(null));if(r.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${r.commentBefore}
55
- ${s.key.commentBefore}`:r.commentBefore),r.comment){let o=s.value??s.key;o.comment=o.comment?`${r.comment}
56
- ${o.comment}`:r.comment}r=s}e.items[n]=ra.isPair(r)?r:new rm.Pair(r)}}else t("Expected a sequence for this tag");return e}function nk(e,t,n){let{replacer:r}=n,s=new cP.YAMLSeq(e);s.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let i of t){typeof r=="function"&&(i=r.call(t,String(o++),i));let a,d;if(Array.isArray(i))if(i.length===2)a=i[0],d=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let l=Object.keys(i);if(l.length===1)a=l[0],d=i[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=i;s.items.push(rm.createPair(a,d,n))}return s}var mP={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:tk,createNode:nk};sa.createPairs=nk;sa.pairs=mP;sa.resolvePairs=tk});var im=L(om=>{"use strict";var rk=G(),sm=Jt(),Fs=nn(),fP=rn(),sk=oa(),Ln=class e extends fP.YAMLSeq{constructor(){super(),this.add=Fs.YAMLMap.prototype.add.bind(this),this.delete=Fs.YAMLMap.prototype.delete.bind(this),this.get=Fs.YAMLMap.prototype.get.bind(this),this.has=Fs.YAMLMap.prototype.has.bind(this),this.set=Fs.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let s of this.items){let o,i;if(rk.isPair(s)?(o=sm.toJS(s.key,"",n),i=sm.toJS(s.value,o,n)):o=sm.toJS(s,"",n),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,i)}return r}static from(t,n,r){let s=sk.createPairs(t,n,r),o=new this;return o.items=s.items,o}};Ln.tag="tag:yaml.org,2002:omap";var uP={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ln,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=sk.resolvePairs(e,t),r=[];for(let{key:s}of n.items)rk.isScalar(s)&&(r.includes(s.value)?t(`Ordered maps must not include duplicate keys: ${s.value}`):r.push(s.value));return Object.assign(new Ln,n)},createNode:(e,t,n)=>Ln.from(e,t,n)};om.YAMLOMap=Ln;om.omap=uP});var lk=L(am=>{"use strict";var ok=pe();function ik({value:e,source:t},n){return t&&(e?ak:dk).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var ak={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new ok.Scalar(!0),stringify:ik},dk={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new ok.Scalar(!1),stringify:ik};am.falseTag=dk;am.trueTag=ak});var ck=L(ia=>{"use strict";var pP=pe(),dm=Ar(),hP={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:dm.stringifyNumber},gP={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():dm.stringifyNumber(e)}},yP={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new pP.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:dm.stringifyNumber};ia.float=yP;ia.floatExp=gP;ia.floatNaN=hP});var fk=L(Bs=>{"use strict";var mk=Ar(),qs=e=>typeof e=="bigint"||Number.isInteger(e);function aa(e,t,n,{intAsBigInt:r}){let s=e[0];if((s==="-"||s==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let i=BigInt(e);return s==="-"?BigInt(-1)*i:i}let o=parseInt(e,n);return s==="-"?-1*o:o}function lm(e,t,n){let{value:r}=e;if(qs(r)){let s=r.toString(t);return r<0?"-"+n+s.substr(1):n+s}return mk.stringifyNumber(e)}var wP={identify:qs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>aa(e,2,2,n),stringify:e=>lm(e,2,"0b")},bP={identify:qs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>aa(e,1,8,n),stringify:e=>lm(e,8,"0")},kP={identify:qs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>aa(e,0,10,n),stringify:mk.stringifyNumber},EP={identify:qs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>aa(e,2,16,n),stringify:e=>lm(e,16,"0x")};Bs.int=kP;Bs.intBin=wP;Bs.intHex=EP;Bs.intOct=bP});var mm=L(cm=>{"use strict";var ca=G(),da=en(),la=nn(),Pn=class e extends la.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;ca.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new da.Pair(t.key,null):n=new da.Pair(t,null),la.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=la.findPair(this.items,t);return!n&&ca.isPair(r)?ca.isScalar(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=la.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new da.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:s}=r,o=new this(t);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof s=="function"&&(i=s.call(n,i,i)),o.items.push(da.createPair(i,null,r));return o}};Pn.tag="tag:yaml.org,2002:set";var CP={collection:"map",identify:e=>e instanceof Set,nodeClass:Pn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Pn.from(e,t,n),resolve(e,t){if(ca.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Pn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};cm.YAMLSet=Pn;cm.set=CP});var um=L(ma=>{"use strict";var RP=Ar();function fm(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,s=i=>t?BigInt(i):Number(i),o=r.replace(/_/g,"").split(":").reduce((i,a)=>i*s(60)+s(a),s(0));return n==="-"?s(-1)*o:o}function uk(e){let{value:t}=e,n=i=>i;if(typeof t=="bigint")n=i=>BigInt(i);else if(isNaN(t)||!isFinite(t))return RP.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let s=n(60),o=[t%s];return t<60?o.unshift(0):(t=(t-o[0])/s,o.unshift(t%s),t>=60&&(t=(t-o[0])/s,o.unshift(t))),r+o.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var SP={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>fm(e,n),stringify:uk},vP={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>fm(e,!1),stringify:uk},pk={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(pk.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,s,o,i,a]=t.map(Number),d=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,s,o||0,i||0,a||0,d),c=t[8];if(c&&c!=="Z"){let m=fm(c,!1);Math.abs(m)<30&&(m*=60),l-=6e4*m}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ma.floatTime=vP;ma.intTime=SP;ma.timestamp=pk});var yk=L(gk=>{"use strict";var IP=xr(),$P=Qi(),xP=Mr(),MP=_s(),AP=nm(),hk=lk(),pm=ck(),fa=fk(),TP=Hi(),OP=im(),NP=oa(),LP=mm(),hm=um(),PP=[IP.map,xP.seq,MP.string,$P.nullTag,hk.trueTag,hk.falseTag,fa.intBin,fa.intOct,fa.int,fa.intHex,pm.floatNaN,pm.floatExp,pm.float,AP.binary,TP.merge,OP.omap,NP.pairs,LP.set,hm.intTime,hm.floatTime,hm.timestamp];gk.schema=PP});var $k=L(wm=>{"use strict";var Ek=xr(),DP=Qi(),Ck=Mr(),_P=_s(),jP=Yc(),gm=Jc(),ym=Qc(),FP=Jb(),qP=Zb(),Rk=nm(),Ws=Hi(),Sk=im(),vk=oa(),wk=yk(),Ik=mm(),ua=um(),bk=new Map([["core",FP.schema],["failsafe",[Ek.map,Ck.seq,_P.string]],["json",qP.schema],["yaml11",wk.schema],["yaml-1.1",wk.schema]]),kk={binary:Rk.binary,bool:jP.boolTag,float:gm.float,floatExp:gm.floatExp,floatNaN:gm.floatNaN,floatTime:ua.floatTime,int:ym.int,intHex:ym.intHex,intOct:ym.intOct,intTime:ua.intTime,map:Ek.map,merge:Ws.merge,null:DP.nullTag,omap:Sk.omap,pairs:vk.pairs,seq:Ck.seq,set:Ik.set,timestamp:ua.timestamp},BP={"tag:yaml.org,2002:binary":Rk.binary,"tag:yaml.org,2002:merge":Ws.merge,"tag:yaml.org,2002:omap":Sk.omap,"tag:yaml.org,2002:pairs":vk.pairs,"tag:yaml.org,2002:set":Ik.set,"tag:yaml.org,2002:timestamp":ua.timestamp};function WP(e,t,n){let r=bk.get(t);if(r&&!e)return n&&!r.includes(Ws.merge)?r.concat(Ws.merge):r.slice();let s=r;if(!s)if(Array.isArray(e))s=[];else{let o=Array.from(bk.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)s=s.concat(o);else typeof e=="function"&&(s=e(s.slice()));return n&&(s=s.concat(Ws.merge)),s.reduce((o,i)=>{let a=typeof i=="string"?kk[i]:i;if(!a){let d=JSON.stringify(i),l=Object.keys(kk).map(c=>JSON.stringify(c)).join(", ");throw new Error(`Unknown custom tag ${d}; use one of ${l}`)}return o.includes(a)||o.push(a),o},[])}wm.coreKnownTags=BP;wm.getTags=WP});var Em=L(xk=>{"use strict";var bm=G(),UP=xr(),HP=Mr(),GP=_s(),pa=$k(),VP=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,km=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:s,schema:o,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(t)?pa.getTags(t,"compat"):t?pa.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=s?pa.coreKnownTags:{},this.tags=pa.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,bm.MAP,{value:UP.map}),Object.defineProperty(this,bm.SCALAR,{value:GP.string}),Object.defineProperty(this,bm.SEQ,{value:HP.seq}),this.sortMapEntries=typeof i=="function"?i:i===!0?VP:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};xk.Schema=km});var Ak=L(Mk=>{"use strict";var KP=G(),Cm=Ls(),Us=As();function YP(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let d=e.directives.toString(e);d?(n.push(d),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let s=Cm.createStringifyContext(e,t),{commentString:o}=s.options;if(e.commentBefore){n.length!==1&&n.unshift("");let d=o(e.commentBefore);n.unshift(Us.indentComment(d,""))}let i=!1,a=null;if(e.contents){if(KP.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let c=o(e.contents.commentBefore);n.push(Us.indentComment(c,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}let d=a?void 0:()=>i=!0,l=Cm.stringify(e.contents,s,()=>a=null,d);a&&(l+=Us.lineComment(l,"",o(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(Cm.stringify(e.contents,s));if(e.directives?.docEnd)if(e.comment){let d=o(e.comment);d.includes(`
57
- `)?(n.push("..."),n.push(Us.indentComment(d,""))):n.push(`... ${d}`)}else n.push("...");else{let d=e.comment;d&&i&&(d=d.replace(/^\n+/,"")),d&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(Us.indentComment(o(d),"")))}return n.join(`
53
+ ${o}${h}`}else return`${p}${i}${m.join(" ")}${i}${h}`}function Qa({indent:e,options:{commentString:t}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=Xa.indentComment(t(r),e);n.push(s.trimStart())}}Fk.stringifyCollection=D1});var In=D(cp=>{"use strict";var j1=dp(),F1=ip(),q1=ja(),vn=ee(),Za=kn(),W1=Ce();function vs(e,t){let n=vn.isScalar(t)?t.value:t;for(let r of e)if(vn.isPair(r)&&(r.key===t||r.key===n||vn.isScalar(r.key)&&r.key.value===n))return r}var lp=class extends q1.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(vn.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:o,replacer:s}=r,i=new this(t),a=(d,l)=>{if(typeof s=="function")l=s.call(n,d,l);else if(Array.isArray(s)&&!s.includes(d))return;(l!==void 0||o)&&i.items.push(Za.createPair(d,l,r))};if(n instanceof Map)for(let[d,l]of n)a(d,l);else if(n&&typeof n=="object")for(let d of Object.keys(n))a(d,n[d]);return typeof t.sortMapEntries=="function"&&i.items.sort(t.sortMapEntries),i}add(t,n){let r;vn.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Za.Pair(t,t?.value):r=new Za.Pair(t.key,t.value);let o=vs(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);vn.isScalar(o.value)&&W1.isScalarValue(r.value)?o.value.value=r.value:o.value=r.value}else if(s){let i=this.items.findIndex(a=>s(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(t){let n=vs(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let o=vs(this.items,t)?.value;return(!n&&vn.isScalar(o)?o.value:o)??void 0}has(t){return!!vs(this.items,t)}set(t,n){this.add(new Za.Pair(t,n),!0)}toJSON(t,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)F1.addPairToJSMap(n,o,s);return o}toString(t,n,r){if(!t)return JSON.stringify(this);for(let o of this.items)if(!vn.isPair(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),j1.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};cp.YAMLMap=lp;cp.findPair=vs});var co=D(Wk=>{"use strict";var H1=ee(),qk=In(),B1={collection:"map",default:!0,nodeClass:qk.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return H1.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>qk.YAMLMap.from(e,t,n)};Wk.map=B1});var Sn=D(Hk=>{"use strict";var U1=ys(),G1=dp(),V1=ja(),td=ee(),Y1=Ce(),K1=bn(),mp=class extends V1.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(td.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=ed(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=ed(t);if(typeof r!="number")return;let o=this.items[r];return!n&&td.isScalar(o)?o.value:o}has(t){let n=ed(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=ed(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let o=this.items[r];td.isScalar(o)&&Y1.isScalarValue(n)?o.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let s of this.items)r.push(K1.toJS(s,String(o++),n));return r}toString(t,n,r){return t?G1.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:o}=r,s=new this(t);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof o=="function"){let d=n instanceof Set?a:String(i++);a=o.call(n,d,a)}s.items.push(U1.createNode(a,void 0,r))}}return s}};function ed(e){let t=td.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Hk.YAMLSeq=mp});var mo=D(Uk=>{"use strict";var z1=ee(),Bk=Sn(),J1={collection:"seq",default:!0,nodeClass:Bk.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return z1.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>Bk.YAMLSeq.from(e,t,n)};Uk.seq=J1});var Is=D(Gk=>{"use strict";var X1=Cs(),Q1={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),X1.stringifyString(e,t,n,r)}};Gk.string=Q1});var nd=D(Kk=>{"use strict";var Vk=Ce(),Yk={identify:e=>e==null,createNode:()=>new Vk.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Vk.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Yk.test.test(e)?e:t.options.nullStr};Kk.nullTag=Yk});var pp=D(Jk=>{"use strict";var Z1=Ce(),zk={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Z1.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&zk.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};Jk.boolTag=zk});var po=D(Xk=>{"use strict";function eF({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let o=typeof r=="number"?r:Number(r);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let a=t-(s.length-i-1);for(;a-- >0;)s+="0"}return s}Xk.stringifyNumber=eF});var up=D(rd=>{"use strict";var tF=Ce(),fp=po(),nF={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:fp.stringifyNumber},rF={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():fp.stringifyNumber(e)}},oF={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new tF.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:fp.stringifyNumber};rd.float=oF;rd.floatExp=rF;rd.floatNaN=nF});var gp=D(sd=>{"use strict";var Qk=po(),od=e=>typeof e=="bigint"||Number.isInteger(e),hp=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function Zk(e,t,n){let{value:r}=e;return od(r)&&r>=0?n+r.toString(t):Qk.stringifyNumber(e)}var sF={identify:e=>od(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>hp(e,2,8,n),stringify:e=>Zk(e,8,"0o")},iF={identify:od,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>hp(e,0,10,n),stringify:Qk.stringifyNumber},aF={identify:e=>od(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>hp(e,2,16,n),stringify:e=>Zk(e,16,"0x")};sd.int=iF;sd.intHex=aF;sd.intOct=sF});var tv=D(ev=>{"use strict";var dF=co(),lF=nd(),cF=mo(),mF=Is(),pF=pp(),yp=up(),wp=gp(),fF=[dF.map,cF.seq,mF.string,lF.nullTag,pF.boolTag,wp.intOct,wp.int,wp.intHex,yp.floatNaN,yp.floatExp,yp.float];ev.schema=fF});var ov=D(rv=>{"use strict";var uF=Ce(),hF=co(),gF=mo();function nv(e){return typeof e=="bigint"||Number.isInteger(e)}var id=({value:e})=>JSON.stringify(e),yF=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:id},{identify:e=>e==null,createNode:()=>new uF.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:id},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:id},{identify:nv,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>nv(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:id}],wF={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},bF=[hF.map,gF.seq].concat(yF,wF);rv.schema=bF});var Ep=D(sv=>{"use strict";var Ss=li("buffer"),bp=Ce(),EF=Cs(),CF={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ss.Buffer=="function")return Ss.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let o=0;o<n.length;++o)r[o]=n.charCodeAt(o);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,o,s){if(!n)return"";let i=n,a;if(typeof Ss.Buffer=="function")a=i instanceof Ss.Buffer?i.toString("base64"):Ss.Buffer.from(i.buffer).toString("base64");else if(typeof btoa=="function"){let d="";for(let l=0;l<i.length;++l)d+=String.fromCharCode(i[l]);a=btoa(d)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=bp.Scalar.BLOCK_LITERAL),t!==bp.Scalar.QUOTE_DOUBLE){let d=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(a.length/d),c=new Array(l);for(let m=0,p=0;m<l;++m,p+=d)c[m]=a.substr(p,d);a=c.join(t===bp.Scalar.BLOCK_LITERAL?`
54
+ `:" ")}return EF.stringifyString({comment:e,type:t,value:a},r,o,s)}};sv.binary=CF});var ld=D(dd=>{"use strict";var ad=ee(),Cp=kn(),RF=Ce(),kF=Sn();function iv(e,t){if(ad.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!ad.isPair(r)){if(ad.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let o=r.items[0]||new Cp.Pair(new RF.Scalar(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}
55
+ ${o.key.commentBefore}`:r.commentBefore),r.comment){let s=o.value??o.key;s.comment=s.comment?`${r.comment}
56
+ ${s.comment}`:r.comment}r=o}e.items[n]=ad.isPair(r)?r:new Cp.Pair(r)}}else t("Expected a sequence for this tag");return e}function av(e,t,n){let{replacer:r}=n,o=new kF.YAMLSeq(e);o.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let i of t){typeof r=="function"&&(i=r.call(t,String(s++),i));let a,d;if(Array.isArray(i))if(i.length===2)a=i[0],d=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let l=Object.keys(i);if(l.length===1)a=l[0],d=i[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=i;o.items.push(Cp.createPair(a,d,n))}return o}var vF={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:iv,createNode:av};dd.createPairs=av;dd.pairs=vF;dd.resolvePairs=iv});var vp=D(kp=>{"use strict";var dv=ee(),Rp=bn(),$s=In(),IF=Sn(),lv=ld(),cr=class e extends IF.YAMLSeq{constructor(){super(),this.add=$s.YAMLMap.prototype.add.bind(this),this.delete=$s.YAMLMap.prototype.delete.bind(this),this.get=$s.YAMLMap.prototype.get.bind(this),this.has=$s.YAMLMap.prototype.has.bind(this),this.set=$s.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let s,i;if(dv.isPair(o)?(s=Rp.toJS(o.key,"",n),i=Rp.toJS(o.value,s,n)):s=Rp.toJS(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}static from(t,n,r){let o=lv.createPairs(t,n,r),s=new this;return s.items=o.items,s}};cr.tag="tag:yaml.org,2002:omap";var SF={collection:"seq",identify:e=>e instanceof Map,nodeClass:cr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=lv.resolvePairs(e,t),r=[];for(let{key:o}of n.items)dv.isScalar(o)&&(r.includes(o.value)?t(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new cr,n)},createNode:(e,t,n)=>cr.from(e,t,n)};kp.YAMLOMap=cr;kp.omap=SF});var uv=D(Ip=>{"use strict";var cv=Ce();function mv({value:e,source:t},n){return t&&(e?pv:fv).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var pv={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new cv.Scalar(!0),stringify:mv},fv={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new cv.Scalar(!1),stringify:mv};Ip.falseTag=fv;Ip.trueTag=pv});var hv=D(cd=>{"use strict";var $F=Ce(),Sp=po(),TF={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Sp.stringifyNumber},xF={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Sp.stringifyNumber(e)}},AF={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new $F.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Sp.stringifyNumber};cd.float=AF;cd.floatExp=xF;cd.floatNaN=TF});var yv=D(xs=>{"use strict";var gv=po(),Ts=e=>typeof e=="bigint"||Number.isInteger(e);function md(e,t,n,{intAsBigInt:r}){let o=e[0];if((o==="-"||o==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let i=BigInt(e);return o==="-"?BigInt(-1)*i:i}let s=parseInt(e,n);return o==="-"?-1*s:s}function $p(e,t,n){let{value:r}=e;if(Ts(r)){let o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return gv.stringifyNumber(e)}var OF={identify:Ts,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>md(e,2,2,n),stringify:e=>$p(e,2,"0b")},MF={identify:Ts,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>md(e,1,8,n),stringify:e=>$p(e,8,"0")},NF={identify:Ts,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>md(e,0,10,n),stringify:gv.stringifyNumber},PF={identify:Ts,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>md(e,2,16,n),stringify:e=>$p(e,16,"0x")};xs.int=NF;xs.intBin=OF;xs.intHex=PF;xs.intOct=MF});var xp=D(Tp=>{"use strict";var ud=ee(),pd=kn(),fd=In(),mr=class e extends fd.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;ud.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new pd.Pair(t.key,null):n=new pd.Pair(t,null),fd.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=fd.findPair(this.items,t);return!n&&ud.isPair(r)?ud.isScalar(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=fd.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new pd.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:o}=r,s=new this(t);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(pd.createPair(i,null,r));return s}};mr.tag="tag:yaml.org,2002:set";var DF={collection:"map",identify:e=>e instanceof Set,nodeClass:mr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>mr.from(e,t,n),resolve(e,t){if(ud.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new mr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Tp.YAMLSet=mr;Tp.set=DF});var Op=D(hd=>{"use strict";var LF=po();function Ap(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,o=i=>t?BigInt(i):Number(i),s=r.replace(/_/g,"").split(":").reduce((i,a)=>i*o(60)+o(a),o(0));return n==="-"?o(-1)*s:s}function wv(e){let{value:t}=e,n=i=>i;if(typeof t=="bigint")n=i=>BigInt(i);else if(isNaN(t)||!isFinite(t))return LF.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let o=n(60),s=[t%o];return t<60?s.unshift(0):(t=(t-s[0])/o,s.unshift(t%o),t>=60&&(t=(t-s[0])/o,s.unshift(t))),r+s.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var _F={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>Ap(e,n),stringify:wv},jF={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Ap(e,!1),stringify:wv},bv={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(bv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,o,s,i,a]=t.map(Number),d=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,o,s||0,i||0,a||0,d),c=t[8];if(c&&c!=="Z"){let m=Ap(c,!1);Math.abs(m)<30&&(m*=60),l-=6e4*m}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};hd.floatTime=jF;hd.intTime=_F;hd.timestamp=bv});var Rv=D(Cv=>{"use strict";var FF=co(),qF=nd(),WF=mo(),HF=Is(),BF=Ep(),Ev=uv(),Mp=hv(),gd=yv(),UF=Ka(),GF=vp(),VF=ld(),YF=xp(),Np=Op(),KF=[FF.map,WF.seq,HF.string,qF.nullTag,Ev.trueTag,Ev.falseTag,gd.intBin,gd.intOct,gd.int,gd.intHex,Mp.floatNaN,Mp.floatExp,Mp.float,BF.binary,UF.merge,GF.omap,VF.pairs,YF.set,Np.intTime,Np.floatTime,Np.timestamp];Cv.schema=KF});var Mv=D(Lp=>{"use strict";var Sv=co(),zF=nd(),$v=mo(),JF=Is(),XF=pp(),Pp=up(),Dp=gp(),QF=tv(),ZF=ov(),Tv=Ep(),As=Ka(),xv=vp(),Av=ld(),kv=Rv(),Ov=xp(),yd=Op(),vv=new Map([["core",QF.schema],["failsafe",[Sv.map,$v.seq,JF.string]],["json",ZF.schema],["yaml11",kv.schema],["yaml-1.1",kv.schema]]),Iv={binary:Tv.binary,bool:XF.boolTag,float:Pp.float,floatExp:Pp.floatExp,floatNaN:Pp.floatNaN,floatTime:yd.floatTime,int:Dp.int,intHex:Dp.intHex,intOct:Dp.intOct,intTime:yd.intTime,map:Sv.map,merge:As.merge,null:zF.nullTag,omap:xv.omap,pairs:Av.pairs,seq:$v.seq,set:Ov.set,timestamp:yd.timestamp},eq={"tag:yaml.org,2002:binary":Tv.binary,"tag:yaml.org,2002:merge":As.merge,"tag:yaml.org,2002:omap":xv.omap,"tag:yaml.org,2002:pairs":Av.pairs,"tag:yaml.org,2002:set":Ov.set,"tag:yaml.org,2002:timestamp":yd.timestamp};function tq(e,t,n){let r=vv.get(t);if(r&&!e)return n&&!r.includes(As.merge)?r.concat(As.merge):r.slice();let o=r;if(!o)if(Array.isArray(e))o=[];else{let s=Array.from(vv.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)o=o.concat(s);else typeof e=="function"&&(o=e(o.slice()));return n&&(o=o.concat(As.merge)),o.reduce((s,i)=>{let a=typeof i=="string"?Iv[i]:i;if(!a){let d=JSON.stringify(i),l=Object.keys(Iv).map(c=>JSON.stringify(c)).join(", ");throw new Error(`Unknown custom tag ${d}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}Lp.coreKnownTags=eq;Lp.getTags=tq});var Fp=D(Nv=>{"use strict";var _p=ee(),nq=co(),rq=mo(),oq=Is(),wd=Mv(),sq=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,jp=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(t)?wd.getTags(t,"compat"):t?wd.getTags(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?wd.coreKnownTags:{},this.tags=wd.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,_p.MAP,{value:nq.map}),Object.defineProperty(this,_p.SCALAR,{value:oq.string}),Object.defineProperty(this,_p.SEQ,{value:rq.seq}),this.sortMapEntries=typeof i=="function"?i:i===!0?sq:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Nv.Schema=jp});var Dv=D(Pv=>{"use strict";var iq=ee(),qp=Rs(),Os=ws();function aq(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let d=e.directives.toString(e);d?(n.push(d),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let o=qp.createStringifyContext(e,t),{commentString:s}=o.options;if(e.commentBefore){n.length!==1&&n.unshift("");let d=s(e.commentBefore);n.unshift(Os.indentComment(d,""))}let i=!1,a=null;if(e.contents){if(iq.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let c=s(e.contents.commentBefore);n.push(Os.indentComment(c,""))}o.forceBlockIndent=!!e.comment,a=e.contents.comment}let d=a?void 0:()=>i=!0,l=qp.stringify(e.contents,o,()=>a=null,d);a&&(l+=Os.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(qp.stringify(e.contents,o));if(e.directives?.docEnd)if(e.comment){let d=s(e.comment);d.includes(`
57
+ `)?(n.push("..."),n.push(Os.indentComment(d,""))):n.push(`... ${d}`)}else n.push("...");else{let d=e.comment;d&&i&&(d=d.replace(/^\n+/,"")),d&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(Os.indentComment(s(d),"")))}return n.join(`
58
58
  `)+`
59
- `}Mk.stringifyDocument=YP});var Hs=L(Tk=>{"use strict";var zP=xs(),Tr=Li(),Ue=G(),JP=en(),XP=Jt(),QP=Em(),ZP=Ak(),Rm=Ai(),e0=$c(),t0=Ms(),Sm=Ic(),vm=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ue.NODE_TYPE,{value:Ue.DOC});let s=null;typeof n=="function"||Array.isArray(n)?s=n:r===void 0&&n&&(r=n,n=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:i}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Sm.Directives({version:i}),this.setSchema(i,r),this.contents=t===void 0?null:this.createNode(t,s,r)}clone(){let t=Object.create(e.prototype,{[Ue.NODE_TYPE]:{value:Ue.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Ue.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Or(this.contents)&&this.contents.add(t)}addIn(t,n){Or(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Rm.anchorNames(this);t.anchor=!n||r.has(n)?Rm.findNewAnchor(n||"a",r):n}return new zP.Alias(t.anchor)}createNode(t,n,r){let s;if(typeof n=="function")t=n.call({"":t},"",t),s=n;else if(Array.isArray(n)){let y=S=>typeof S=="number"||S instanceof String||S instanceof Number,k=n.filter(y).map(String);k.length>0&&(n=n.concat(k)),s=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:o,anchorPrefix:i,flow:a,keepUndefined:d,onTagObj:l,tag:c}=r??{},{onAnchor:m,setAnchors:f,sourceObjects:g}=Rm.createNodeAnchors(this,i||"a"),u={aliasDuplicateObjects:o??!0,keepUndefined:d??!1,onAnchor:m,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:g},h=t0.createNode(t,c,u);return a&&Ue.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,n,r={}){let s=this.createNode(t,null,r),o=this.createNode(n,null,r);return new JP.Pair(s,o)}delete(t){return Or(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Tr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Or(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return Ue.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return Tr.isEmptyPath(t)?!n&&Ue.isScalar(this.contents)?this.contents.value:this.contents:Ue.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return Ue.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Tr.isEmptyPath(t)?this.contents!==void 0:Ue.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=Tr.collectionFromPath(this.schema,[t],n):Or(this.contents)&&this.contents.set(t,n)}setIn(t,n){Tr.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=Tr.collectionFromPath(this.schema,Array.from(t),n):Or(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Sm.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Sm.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let s=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new QP.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:s,onAnchor:o,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},d=XP.toJS(this.contents,n??"",a);if(typeof o=="function")for(let{count:l,res:c}of a.anchors.values())o(c,l);return typeof i=="function"?e0.applyReviver(i,{"":d},"",d):d}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return ZP.stringifyDocument(this,t)}};function Or(e){if(Ue.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Tk.Document=vm});var Ks=L(Vs=>{"use strict";var Gs=class extends Error{constructor(t,n,r,s){super(),this.name=t,this.code=r,this.message=s,this.pos=n}},Im=class extends Gs{constructor(t,n,r){super("YAMLParseError",t,n,r)}},$m=class extends Gs{constructor(t,n,r){super("YAMLWarning",t,n,r)}},n0=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:r,col:s}=n.linePos[0];n.message+=` at line ${r}, column ${s}`;let o=s-1,i=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&i.length>80){let a=Math.min(o-39,i.length-79);i="\u2026"+i.substring(a),o-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,o))){let a=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
60
- `),i=a+i}if(/[^ ]/.test(i)){let a=1,d=n.linePos[1];d?.line===r&&d.col>s&&(a=Math.max(1,Math.min(d.col-s,80-o)));let l=" ".repeat(o)+"^".repeat(a);n.message+=`:
59
+ `}Pv.stringifyDocument=aq});var Ms=D(Lv=>{"use strict";var dq=gs(),fo=ja(),Ze=ee(),lq=kn(),cq=bn(),mq=Fp(),pq=Dv(),Wp=Pa(),fq=Gm(),uq=ys(),Hp=Um(),Bp=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ze.NODE_TYPE,{value:Ze.DOC});let o=null;typeof n=="function"||Array.isArray(n)?o=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:i}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Hp.Directives({version:i}),this.setSchema(i,r),this.contents=t===void 0?null:this.createNode(t,o,r)}clone(){let t=Object.create(e.prototype,{[Ze.NODE_TYPE]:{value:Ze.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Ze.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){uo(this.contents)&&this.contents.add(t)}addIn(t,n){uo(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Wp.anchorNames(this);t.anchor=!n||r.has(n)?Wp.findNewAnchor(n||"a",r):n}return new dq.Alias(t.anchor)}createNode(t,n,r){let o;if(typeof n=="function")t=n.call({"":t},"",t),o=n;else if(Array.isArray(n)){let w=I=>typeof I=="number"||I instanceof String||I instanceof Number,E=n.filter(w).map(String);E.length>0&&(n=n.concat(E)),o=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:i,flow:a,keepUndefined:d,onTagObj:l,tag:c}=r??{},{onAnchor:m,setAnchors:p,sourceObjects:h}=Wp.createNodeAnchors(this,i||"a"),u={aliasDuplicateObjects:s??!0,keepUndefined:d??!1,onAnchor:m,onTagObj:l,replacer:o,schema:this.schema,sourceObjects:h},y=uq.createNode(t,c,u);return a&&Ze.isCollection(y)&&(y.flow=!0),p(),y}createPair(t,n,r={}){let o=this.createNode(t,null,r),s=this.createNode(n,null,r);return new lq.Pair(o,s)}delete(t){return uo(this.contents)?this.contents.delete(t):!1}deleteIn(t){return fo.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):uo(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return Ze.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return fo.isEmptyPath(t)?!n&&Ze.isScalar(this.contents)?this.contents.value:this.contents:Ze.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return Ze.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return fo.isEmptyPath(t)?this.contents!==void 0:Ze.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=fo.collectionFromPath(this.schema,[t],n):uo(this.contents)&&this.contents.set(t,n)}setIn(t,n){fo.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=fo.collectionFromPath(this.schema,Array.from(t),n):uo(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Hp.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Hp.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${o}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new mq.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},d=cq.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:c}of a.anchors.values())s(c,l);return typeof i=="function"?fq.applyReviver(i,{"":d},"",d):d}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return pq.stringifyDocument(this,t)}};function uo(e){if(Ze.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Lv.Document=Bp});var Ds=D(Ps=>{"use strict";var Ns=class extends Error{constructor(t,n,r,o){super(),this.name=t,this.code=r,this.message=o,this.pos=n}},Up=class extends Ns{constructor(t,n,r){super("YAMLParseError",t,n,r)}},Gp=class extends Ns{constructor(t,n,r){super("YAMLWarning",t,n,r)}},hq=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:r,col:o}=n.linePos[0];n.message+=` at line ${r}, column ${o}`;let s=o-1,i=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&i.length>80){let a=Math.min(s-39,i.length-79);i="\u2026"+i.substring(a),s-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,s))){let a=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
60
+ `),i=a+i}if(/[^ ]/.test(i)){let a=1,d=n.linePos[1];d?.line===r&&d.col>o&&(a=Math.max(1,Math.min(d.col-o,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`:
61
61
 
62
62
  ${i}
63
63
  ${l}
64
- `}};Vs.YAMLError=Gs;Vs.YAMLParseError=Im;Vs.YAMLWarning=$m;Vs.prettifyError=n0});var Ys=L(Ok=>{"use strict";function r0(e,{flow:t,indicator:n,next:r,offset:s,onError:o,parentIndent:i,startOnNewline:a}){let d=!1,l=a,c=a,m="",f="",g=!1,u=!1,h=null,y=null,k=null,S=null,I=null,x=null,E=null;for(let C of e)switch(u&&(C.type!=="space"&&C.type!=="newline"&&C.type!=="comma"&&o(C.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),u=!1),h&&(l&&C.type!=="comment"&&C.type!=="newline"&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),C.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&C.source.includes(" ")&&(h=C),c=!0;break;case"comment":{c||o(C,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=C.source.substring(1)||" ";m?m+=f+R:m=R,f="",l=!1;break}case"newline":l?m?m+=C.source:(!x||n!=="seq-item-ind")&&(d=!0):f+=C.source,l=!0,g=!0,(y||k)&&(S=C),c=!0;break;case"anchor":y&&o(C,"MULTIPLE_ANCHORS","A node can have at most one anchor"),C.source.endsWith(":")&&o(C.offset+C.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=C,E??(E=C.offset),l=!1,c=!1,u=!0;break;case"tag":{k&&o(C,"MULTIPLE_TAGS","A node can have at most one tag"),k=C,E??(E=C.offset),l=!1,c=!1,u=!0;break}case n:(y||k)&&o(C,"BAD_PROP_ORDER",`Anchors and tags must be after the ${C.source} indicator`),x&&o(C,"UNEXPECTED_TOKEN",`Unexpected ${C.source} in ${t??"collection"}`),x=C,l=n==="seq-item-ind"||n==="explicit-key-ind",c=!1;break;case"comma":if(t){I&&o(C,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),I=C,l=!1,c=!1;break}default:o(C,"UNEXPECTED_TOKEN",`Unexpected ${C.type} token`),l=!1,c=!1}let M=e[e.length-1],v=M?M.offset+M.source.length:s;return u&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:I,found:x,spaceBefore:d,comment:m,hasNewline:g,anchor:y,tag:k,newlineAfterProp:S,end:v,start:E??v}}Ok.resolveProps=r0});var ha=L(Nk=>{"use strict";function xm(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
65
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(xm(t.key)||xm(t.value))return!0}return!1;default:return!0}}Nk.containsNewline=xm});var Mm=L(Lk=>{"use strict";var s0=ha();function o0(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&s0.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Lk.flowIndentCheck=o0});var Am=L(Dk=>{"use strict";var Pk=G();function i0(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let s=typeof r=="function"?r:(o,i)=>o===i||Pk.isScalar(o)&&Pk.isScalar(i)&&o.value===i.value;return t.some(o=>s(o.key,n))}Dk.mapIncludes=i0});var Wk=L(Bk=>{"use strict";var _k=en(),a0=nn(),jk=Ys(),d0=ha(),Fk=Mm(),l0=Am(),qk="All mapping items must start at the same column";function c0({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??a0.YAMLMap,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let d=r.offset,l=null;for(let c of r.items){let{start:m,key:f,sep:g,value:u}=c,h=jk.resolveProps(m,{indicator:"explicit-key-ind",next:f??g?.[0],offset:d,onError:s,parentIndent:r.indent,startOnNewline:!0}),y=!h.found;if(y){if(f&&(f.type==="block-seq"?s(d,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&s(d,"BAD_INDENT",qk)),!h.anchor&&!h.tag&&!g){l=h.end,h.comment&&(a.comment?a.comment+=`
66
- `+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||d0.containsNewline(f))&&s(f??m[m.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&s(d,"BAD_INDENT",qk);n.atKey=!0;let k=h.end,S=f?e(n,f,h,s):t(n,k,m,null,h,s);n.schema.compat&&Fk.flowIndentCheck(r.indent,f,s),n.atKey=!1,l0.mapIncludes(n,a.items,S)&&s(k,"DUPLICATE_KEY","Map keys must be unique");let I=jk.resolveProps(g??[],{indicator:"map-value-ind",next:u,offset:S.range[2],onError:s,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(d=I.end,I.found){y&&(u?.type==="block-map"&&!I.hasNewline&&s(d,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start<I.found.offset-1024&&s(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let x=u?e(n,u,I,s):t(n,d,g,null,I,s);n.schema.compat&&Fk.flowIndentCheck(r.indent,u,s),d=x.range[2];let E=new _k.Pair(S,x);n.options.keepSourceTokens&&(E.srcToken=c),a.items.push(E)}else{y&&s(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),I.comment&&(S.comment?S.comment+=`
67
- `+I.comment:S.comment=I.comment);let x=new _k.Pair(S);n.options.keepSourceTokens&&(x.srcToken=c),a.items.push(x)}}return l&&l<d&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,d,l??d],a}Bk.resolveBlockMap=c0});var Hk=L(Uk=>{"use strict";var m0=rn(),f0=Ys(),u0=Mm();function p0({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??m0.YAMLSeq,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset,l=null;for(let{start:c,value:m}of r.items){let f=f0.resolveProps(c,{indicator:"seq-item-ind",next:m,offset:d,onError:s,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||m)m?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(d,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let g=m?e(n,m,f,s):t(n,f.end,c,null,f,s);n.schema.compat&&u0.flowIndentCheck(r.indent,m,s),d=g.range[2],a.items.push(g)}return a.range=[r.offset,d,l??d],a}Uk.resolveBlockSeq=p0});var Nr=L(Gk=>{"use strict";function h0(e,t,n,r){let s="";if(e){let o=!1,i="";for(let a of e){let{source:d,type:l}=a;switch(l){case"space":o=!0;break;case"comment":{n&&!o&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let c=d.substring(1)||" ";s?s+=i+c:s=c,i="";break}case"newline":s&&(i+=d),o=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=d.length}}return{comment:s,offset:t}}Gk.resolveEnd=h0});var zk=L(Yk=>{"use strict";var g0=G(),y0=en(),Vk=nn(),w0=rn(),b0=Nr(),Kk=Ys(),k0=ha(),E0=Am(),Tm="Block collections are not allowed within flow collections",Om=e=>e&&(e.type==="block-map"||e.type==="block-seq");function C0({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=r.start.source==="{",a=i?"flow map":"flow sequence",d=o?.nodeClass??(i?Vk.YAMLMap:w0.YAMLSeq),l=new d(n.schema);l.flow=!0;let c=n.atRoot;c&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let m=r.offset+r.start.source.length;for(let y=0;y<r.items.length;++y){let k=r.items[y],{start:S,key:I,sep:x,value:E}=k,M=Kk.resolveProps(S,{flow:a,indicator:"explicit-key-ind",next:I??x?.[0],offset:m,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!M.found){if(!M.anchor&&!M.tag&&!x&&!E){y===0&&M.comma?s(M.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<r.items.length-1&&s(M.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),M.comment&&(l.comment?l.comment+=`
68
- `+M.comment:l.comment=M.comment),m=M.end;continue}!i&&n.options.strict&&k0.containsNewline(I)&&s(I,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)M.comma&&s(M.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(M.comma||s(M.start,"MISSING_CHAR",`Missing , between ${a} items`),M.comment){let v="";e:for(let C of S)switch(C.type){case"comma":case"space":break;case"comment":v=C.source.substring(1);break e;default:break e}if(v){let C=l.items[l.items.length-1];g0.isPair(C)&&(C=C.value??C.key),C.comment?C.comment+=`
69
- `+v:C.comment=v,M.comment=M.comment.substring(v.length+1)}}if(!i&&!x&&!M.found){let v=E?e(n,E,M,s):t(n,M.end,x,null,M,s);l.items.push(v),m=v.range[2],Om(E)&&s(v.range,"BLOCK_IN_FLOW",Tm)}else{n.atKey=!0;let v=M.end,C=I?e(n,I,M,s):t(n,v,S,null,M,s);Om(I)&&s(C.range,"BLOCK_IN_FLOW",Tm),n.atKey=!1;let R=Kk.resolveProps(x??[],{flow:a,indicator:"map-value-ind",next:E,offset:C.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(R.found){if(!i&&!M.found&&n.options.strict){if(x)for(let N of x){if(N===R.found)break;if(N.type==="newline"){s(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}M.start<R.found.offset-1024&&s(R.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?s(E,"MISSING_CHAR",`Missing space after : in ${a}`):s(R.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let A=E?e(n,E,R,s):R.found?t(n,R.end,x,null,R,s):null;A?Om(E)&&s(A.range,"BLOCK_IN_FLOW",Tm):R.comment&&(C.comment?C.comment+=`
70
- `+R.comment:C.comment=R.comment);let T=new y0.Pair(C,A);if(n.options.keepSourceTokens&&(T.srcToken=k),i){let N=l;E0.mapIncludes(n,N.items,C)&&s(v,"DUPLICATE_KEY","Map keys must be unique"),N.items.push(T)}else{let N=new Vk.YAMLMap(n.schema);N.flow=!0,N.items.push(T);let q=(A??C).range;N.range=[C.range[0],q[1],q[2]],l.items.push(N)}m=A?A.range[2]:R.end}}let f=i?"}":"]",[g,...u]=r.end,h=m;if(g?.source===f)h=g.offset+g.source.length;else{let y=a[0].toUpperCase()+a.substring(1),k=c?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;s(m,c?"MISSING_CHAR":"BAD_INDENT",k),g&&g.source.length!==1&&u.unshift(g)}if(u.length>0){let y=b0.resolveEnd(u,h,n.options.strict,s);y.comment&&(l.comment?l.comment+=`
71
- `+y.comment:l.comment=y.comment),l.range=[r.offset,h,y.offset]}else l.range=[r.offset,h,h];return l}Yk.resolveFlowCollection=C0});var Xk=L(Jk=>{"use strict";var R0=G(),S0=pe(),v0=nn(),I0=rn(),$0=Wk(),x0=Hk(),M0=zk();function Nm(e,t,n,r,s,o){let i=n.type==="block-map"?$0.resolveBlockMap(e,t,n,r,o):n.type==="block-seq"?x0.resolveBlockSeq(e,t,n,r,o):M0.resolveFlowCollection(e,t,n,r,o),a=i.constructor;return s==="!"||s===a.tagName?(i.tag=a.tagName,i):(s&&(i.tag=s),i)}function A0(e,t,n,r,s){let o=r.tag,i=o?t.directives.tagName(o.source,f=>s(o,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:g}=r,u=f&&o?f.offset>o.offset?f:o:f??o;u&&(!g||g.offset<u.offset)&&s(u,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!o||!i||i==="!"||i===v0.YAMLMap.tagName&&a==="map"||i===I0.YAMLSeq.tagName&&a==="seq")return Nm(e,t,n,s,i);let d=t.schema.tags.find(f=>f.tag===i&&f.collection===a);if(!d){let f=t.schema.knownTags[i];if(f?.collection===a)t.schema.tags.push(Object.assign({},f,{default:!1})),d=f;else return f?s(o,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Nm(e,t,n,s,i)}let l=Nm(e,t,n,s,i,d),c=d.resolve?.(l,f=>s(o,"TAG_RESOLVE_FAILED",f),t.options)??l,m=R0.isNode(c)?c:new S0.Scalar(c);return m.range=l.range,m.tag=i,d?.format&&(m.format=d.format),m}Jk.composeCollection=A0});var Pm=L(Qk=>{"use strict";var Lm=pe();function T0(e,t,n){let r=t.offset,s=O0(t,e.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};let o=s.mode===">"?Lm.Scalar.BLOCK_FOLDED:Lm.Scalar.BLOCK_LITERAL,i=t.source?N0(t.source):[],a=i.length;for(let h=i.length-1;h>=0;--h){let y=i[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=s.chomp==="+"&&i.length>0?`
72
- `.repeat(Math.max(1,i.length-1)):"",y=r+s.length;return t.source&&(y+=t.source.length),{value:h,type:o,comment:s.comment,range:[r,y,y]}}let d=t.indent+s.indent,l=t.offset+s.length,c=0;for(let h=0;h<a;++h){let[y,k]=i[h];if(k===""||k==="\r")s.indent===0&&y.length>d&&(d=y.length);else{y.length<d&&n(l+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(d=y.length),c=h,d===0&&!e.atRoot&&n(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=y.length+k.length+1}for(let h=i.length-1;h>=a;--h)i[h][0].length>d&&(a=h+1);let m="",f="",g=!1;for(let h=0;h<c;++h)m+=i[h][0].slice(d)+`
73
- `;for(let h=c;h<a;++h){let[y,k]=i[h];l+=y.length+k.length+1;let S=k[k.length-1]==="\r";if(S&&(k=k.slice(0,-1)),k&&y.length<d){let x=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;n(l-k.length-(S?2:1),"BAD_INDENT",x),y=""}o===Lm.Scalar.BLOCK_LITERAL?(m+=f+y.slice(d)+k,f=`
74
- `):y.length>d||k[0]===" "?(f===" "?f=`
75
- `:!g&&f===`
76
- `&&(f=`
64
+ `}};Ps.YAMLError=Ns;Ps.YAMLParseError=Up;Ps.YAMLWarning=Gp;Ps.prettifyError=hq});var Ls=D(_v=>{"use strict";function gq(e,{flow:t,indicator:n,next:r,offset:o,onError:s,parentIndent:i,startOnNewline:a}){let d=!1,l=a,c=a,m="",p="",h=!1,u=!1,y=null,w=null,E=null,I=null,v=null,$=null,C=null;for(let R of e)switch(u&&(R.type!=="space"&&R.type!=="newline"&&R.type!=="comma"&&s(R.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),u=!1),y&&(l&&R.type!=="comment"&&R.type!=="newline"&&s(y,"TAB_AS_INDENT","Tabs are not allowed as indentation"),y=null),R.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&R.source.includes(" ")&&(y=R),c=!0;break;case"comment":{c||s(R,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let S=R.source.substring(1)||" ";m?m+=p+S:m=S,p="",l=!1;break}case"newline":l?m?m+=R.source:(!$||n!=="seq-item-ind")&&(d=!0):p+=R.source,l=!0,h=!0,(w||E)&&(I=R),c=!0;break;case"anchor":w&&s(R,"MULTIPLE_ANCHORS","A node can have at most one anchor"),R.source.endsWith(":")&&s(R.offset+R.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=R,C??(C=R.offset),l=!1,c=!1,u=!0;break;case"tag":{E&&s(R,"MULTIPLE_TAGS","A node can have at most one tag"),E=R,C??(C=R.offset),l=!1,c=!1,u=!0;break}case n:(w||E)&&s(R,"BAD_PROP_ORDER",`Anchors and tags must be after the ${R.source} indicator`),$&&s(R,"UNEXPECTED_TOKEN",`Unexpected ${R.source} in ${t??"collection"}`),$=R,l=n==="seq-item-ind"||n==="explicit-key-ind",c=!1;break;case"comma":if(t){v&&s(R,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),v=R,l=!1,c=!1;break}default:s(R,"UNEXPECTED_TOKEN",`Unexpected ${R.type} token`),l=!1,c=!1}let x=e[e.length-1],L=x?x.offset+x.source.length:o;return u&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y&&(l&&y.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&s(y,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:$,spaceBefore:d,comment:m,hasNewline:h,anchor:w,tag:E,newlineAfterProp:I,end:L,start:C??L}}_v.resolveProps=gq});var bd=D(jv=>{"use strict";function Vp(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
65
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(Vp(t.key)||Vp(t.value))return!0}return!1;default:return!0}}jv.containsNewline=Vp});var Yp=D(Fv=>{"use strict";var yq=bd();function wq(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&yq.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Fv.flowIndentCheck=wq});var Kp=D(Wv=>{"use strict";var qv=ee();function bq(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||qv.isScalar(s)&&qv.isScalar(i)&&s.value===i.value;return t.some(s=>o(s.key,n))}Wv.mapIncludes=bq});var Yv=D(Vv=>{"use strict";var Hv=kn(),Eq=In(),Bv=Ls(),Cq=bd(),Uv=Yp(),Rq=Kp(),Gv="All mapping items must start at the same column";function kq({composeNode:e,composeEmptyNode:t},n,r,o,s){let i=s?.nodeClass??Eq.YAMLMap,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let d=r.offset,l=null;for(let c of r.items){let{start:m,key:p,sep:h,value:u}=c,y=Bv.resolveProps(m,{indicator:"explicit-key-ind",next:p??h?.[0],offset:d,onError:o,parentIndent:r.indent,startOnNewline:!0}),w=!y.found;if(w){if(p&&(p.type==="block-seq"?o(d,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==r.indent&&o(d,"BAD_INDENT",Gv)),!y.anchor&&!y.tag&&!h){l=y.end,y.comment&&(a.comment?a.comment+=`
66
+ `+y.comment:a.comment=y.comment);continue}(y.newlineAfterProp||Cq.containsNewline(p))&&o(p??m[m.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else y.found?.indent!==r.indent&&o(d,"BAD_INDENT",Gv);n.atKey=!0;let E=y.end,I=p?e(n,p,y,o):t(n,E,m,null,y,o);n.schema.compat&&Uv.flowIndentCheck(r.indent,p,o),n.atKey=!1,Rq.mapIncludes(n,a.items,I)&&o(E,"DUPLICATE_KEY","Map keys must be unique");let v=Bv.resolveProps(h??[],{indicator:"map-value-ind",next:u,offset:I.range[2],onError:o,parentIndent:r.indent,startOnNewline:!p||p.type==="block-scalar"});if(d=v.end,v.found){w&&(u?.type==="block-map"&&!v.hasNewline&&o(d,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&y.start<v.found.offset-1024&&o(I.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let $=u?e(n,u,v,o):t(n,d,h,null,v,o);n.schema.compat&&Uv.flowIndentCheck(r.indent,u,o),d=$.range[2];let C=new Hv.Pair(I,$);n.options.keepSourceTokens&&(C.srcToken=c),a.items.push(C)}else{w&&o(I.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),v.comment&&(I.comment?I.comment+=`
67
+ `+v.comment:I.comment=v.comment);let $=new Hv.Pair(I);n.options.keepSourceTokens&&($.srcToken=c),a.items.push($)}}return l&&l<d&&o(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,d,l??d],a}Vv.resolveBlockMap=kq});var zv=D(Kv=>{"use strict";var vq=Sn(),Iq=Ls(),Sq=Yp();function $q({composeNode:e,composeEmptyNode:t},n,r,o,s){let i=s?.nodeClass??vq.YAMLSeq,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset,l=null;for(let{start:c,value:m}of r.items){let p=Iq.resolveProps(c,{indicator:"seq-item-ind",next:m,offset:d,onError:o,parentIndent:r.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||m)m?.type==="block-seq"?o(p.end,"BAD_INDENT","All sequence items must start at the same column"):o(d,"MISSING_CHAR","Sequence item without - indicator");else{l=p.end,p.comment&&(a.comment=p.comment);continue}let h=m?e(n,m,p,o):t(n,p.end,c,null,p,o);n.schema.compat&&Sq.flowIndentCheck(r.indent,m,o),d=h.range[2],a.items.push(h)}return a.range=[r.offset,d,l??d],a}Kv.resolveBlockSeq=$q});var ho=D(Jv=>{"use strict";function Tq(e,t,n,r){let o="";if(e){let s=!1,i="";for(let a of e){let{source:d,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let c=d.substring(1)||" ";o?o+=i+c:o=c,i="";break}case"newline":o&&(i+=d),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=d.length}}return{comment:o,offset:t}}Jv.resolveEnd=Tq});var eI=D(Zv=>{"use strict";var xq=ee(),Aq=kn(),Xv=In(),Oq=Sn(),Mq=ho(),Qv=Ls(),Nq=bd(),Pq=Kp(),zp="Block collections are not allowed within flow collections",Jp=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Dq({composeNode:e,composeEmptyNode:t},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",d=s?.nodeClass??(i?Xv.YAMLMap:Oq.YAMLSeq),l=new d(n.schema);l.flow=!0;let c=n.atRoot;c&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let m=r.offset+r.start.source.length;for(let w=0;w<r.items.length;++w){let E=r.items[w],{start:I,key:v,sep:$,value:C}=E,x=Qv.resolveProps(I,{flow:a,indicator:"explicit-key-ind",next:v??$?.[0],offset:m,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!x.found){if(!x.anchor&&!x.tag&&!$&&!C){w===0&&x.comma?o(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<r.items.length-1&&o(x.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),x.comment&&(l.comment?l.comment+=`
68
+ `+x.comment:l.comment=x.comment),m=x.end;continue}!i&&n.options.strict&&Nq.containsNewline(v)&&o(v,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)x.comma&&o(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(x.comma||o(x.start,"MISSING_CHAR",`Missing , between ${a} items`),x.comment){let L="";e:for(let R of I)switch(R.type){case"comma":case"space":break;case"comment":L=R.source.substring(1);break e;default:break e}if(L){let R=l.items[l.items.length-1];xq.isPair(R)&&(R=R.value??R.key),R.comment?R.comment+=`
69
+ `+L:R.comment=L,x.comment=x.comment.substring(L.length+1)}}if(!i&&!$&&!x.found){let L=C?e(n,C,x,o):t(n,x.end,$,null,x,o);l.items.push(L),m=L.range[2],Jp(C)&&o(L.range,"BLOCK_IN_FLOW",zp)}else{n.atKey=!0;let L=x.end,R=v?e(n,v,x,o):t(n,L,I,null,x,o);Jp(v)&&o(R.range,"BLOCK_IN_FLOW",zp),n.atKey=!1;let S=Qv.resolveProps($??[],{flow:a,indicator:"map-value-ind",next:C,offset:R.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(S.found){if(!i&&!x.found&&n.options.strict){if($)for(let M of $){if(M===S.found)break;if(M.type==="newline"){o(M,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}x.start<S.found.offset-1024&&o(S.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else C&&("source"in C&&C.source?.[0]===":"?o(C,"MISSING_CHAR",`Missing space after : in ${a}`):o(S.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let T=C?e(n,C,S,o):S.found?t(n,S.end,$,null,S,o):null;T?Jp(C)&&o(T.range,"BLOCK_IN_FLOW",zp):S.comment&&(R.comment?R.comment+=`
70
+ `+S.comment:R.comment=S.comment);let O=new Aq.Pair(R,T);if(n.options.keepSourceTokens&&(O.srcToken=E),i){let M=l;Pq.mapIncludes(n,M.items,R)&&o(L,"DUPLICATE_KEY","Map keys must be unique"),M.items.push(O)}else{let M=new Xv.YAMLMap(n.schema);M.flow=!0,M.items.push(O);let _=(T??R).range;M.range=[R.range[0],_[1],_[2]],l.items.push(M)}m=T?T.range[2]:S.end}}let p=i?"}":"]",[h,...u]=r.end,y=m;if(h?.source===p)y=h.offset+h.source.length;else{let w=a[0].toUpperCase()+a.substring(1),E=c?`${w} must end with a ${p}`:`${w} in block collection must be sufficiently indented and end with a ${p}`;o(m,c?"MISSING_CHAR":"BAD_INDENT",E),h&&h.source.length!==1&&u.unshift(h)}if(u.length>0){let w=Mq.resolveEnd(u,y,n.options.strict,o);w.comment&&(l.comment?l.comment+=`
71
+ `+w.comment:l.comment=w.comment),l.range=[r.offset,y,w.offset]}else l.range=[r.offset,y,y];return l}Zv.resolveFlowCollection=Dq});var nI=D(tI=>{"use strict";var Lq=ee(),_q=Ce(),jq=In(),Fq=Sn(),qq=Yv(),Wq=zv(),Hq=eI();function Xp(e,t,n,r,o,s){let i=n.type==="block-map"?qq.resolveBlockMap(e,t,n,r,s):n.type==="block-seq"?Wq.resolveBlockSeq(e,t,n,r,s):Hq.resolveFlowCollection(e,t,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function Bq(e,t,n,r,o){let s=r.tag,i=s?t.directives.tagName(s.source,p=>o(s,"TAG_RESOLVE_FAILED",p)):null;if(n.type==="block-seq"){let{anchor:p,newlineAfterProp:h}=r,u=p&&s?p.offset>s.offset?p:s:p??s;u&&(!h||h.offset<u.offset)&&o(u,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!i||i==="!"||i===jq.YAMLMap.tagName&&a==="map"||i===Fq.YAMLSeq.tagName&&a==="seq")return Xp(e,t,n,o,i);let d=t.schema.tags.find(p=>p.tag===i&&p.collection===a);if(!d){let p=t.schema.knownTags[i];if(p?.collection===a)t.schema.tags.push(Object.assign({},p,{default:!1})),d=p;else return p?o(s,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${p.collection??"scalar"}`,!0):o(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Xp(e,t,n,o,i)}let l=Xp(e,t,n,o,i,d),c=d.resolve?.(l,p=>o(s,"TAG_RESOLVE_FAILED",p),t.options)??l,m=Lq.isNode(c)?c:new _q.Scalar(c);return m.range=l.range,m.tag=i,d?.format&&(m.format=d.format),m}tI.composeCollection=Bq});var Zp=D(rI=>{"use strict";var Qp=Ce();function Uq(e,t,n){let r=t.offset,o=Gq(t,e.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let s=o.mode===">"?Qp.Scalar.BLOCK_FOLDED:Qp.Scalar.BLOCK_LITERAL,i=t.source?Vq(t.source):[],a=i.length;for(let y=i.length-1;y>=0;--y){let w=i[y][1];if(w===""||w==="\r")a=y;else break}if(a===0){let y=o.chomp==="+"&&i.length>0?`
72
+ `.repeat(Math.max(1,i.length-1)):"",w=r+o.length;return t.source&&(w+=t.source.length),{value:y,type:s,comment:o.comment,range:[r,w,w]}}let d=t.indent+o.indent,l=t.offset+o.length,c=0;for(let y=0;y<a;++y){let[w,E]=i[y];if(E===""||E==="\r")o.indent===0&&w.length>d&&(d=w.length);else{w.length<d&&n(l+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(d=w.length),c=y,d===0&&!e.atRoot&&n(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=w.length+E.length+1}for(let y=i.length-1;y>=a;--y)i[y][0].length>d&&(a=y+1);let m="",p="",h=!1;for(let y=0;y<c;++y)m+=i[y][0].slice(d)+`
73
+ `;for(let y=c;y<a;++y){let[w,E]=i[y];l+=w.length+E.length+1;let I=E[E.length-1]==="\r";if(I&&(E=E.slice(0,-1)),E&&w.length<d){let $=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(l-E.length-(I?2:1),"BAD_INDENT",$),w=""}s===Qp.Scalar.BLOCK_LITERAL?(m+=p+w.slice(d)+E,p=`
74
+ `):w.length>d||E[0]===" "?(p===" "?p=`
75
+ `:!h&&p===`
76
+ `&&(p=`
77
77
 
78
- `),m+=f+y.slice(d)+k,f=`
79
- `,g=!0):k===""?f===`
78
+ `),m+=p+w.slice(d)+E,p=`
79
+ `,h=!0):E===""?p===`
80
80
  `?m+=`
81
- `:f=`
82
- `:(m+=f+k,f=" ",g=!1)}switch(s.chomp){case"-":break;case"+":for(let h=a;h<i.length;++h)m+=`
83
- `+i[h][0].slice(d);m[m.length-1]!==`
81
+ `:p=`
82
+ `:(m+=p+E,p=" ",h=!1)}switch(o.chomp){case"-":break;case"+":for(let y=a;y<i.length;++y)m+=`
83
+ `+i[y][0].slice(d);m[m.length-1]!==`
84
84
  `&&(m+=`
85
85
  `);break;default:m+=`
86
- `}let u=r+s.length+t.source.length;return{value:m,type:o,comment:s.comment,range:[r,u,u]}}function O0({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=t[0],o=s[0],i=0,a="",d=-1;for(let f=1;f<s.length;++f){let g=s[f];if(!a&&(g==="-"||g==="+"))a=g;else{let u=Number(g);!i&&u?i=u:d===-1&&(d=e+f)}}d!==-1&&r(d,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,c="",m=s.length;for(let f=1;f<t.length;++f){let g=t[f];switch(g.type){case"space":l=!0;case"newline":m+=g.source.length;break;case"comment":n&&!l&&r(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),m+=g.source.length,c=g.source.substring(1);break;case"error":r(g,"UNEXPECTED_TOKEN",g.message),m+=g.source.length;break;default:{let u=`Unexpected token in block scalar header: ${g.type}`;r(g,"UNEXPECTED_TOKEN",u);let h=g.source;h&&typeof h=="string"&&(m+=h.length)}}}return{mode:o,indent:i,chomp:a,comment:c,length:m}}function N0(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),o=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<t.length;i+=2)o.push([t[i],t[i+1]]);return o}Qk.resolveBlockScalar=T0});var _m=L(eE=>{"use strict";var Dm=pe(),L0=Nr();function P0(e,t,n){let{offset:r,type:s,source:o,end:i}=e,a,d,l=(f,g,u)=>n(r+f,g,u);switch(s){case"scalar":a=Dm.Scalar.PLAIN,d=D0(o,l);break;case"single-quoted-scalar":a=Dm.Scalar.QUOTE_SINGLE,d=_0(o,l);break;case"double-quoted-scalar":a=Dm.Scalar.QUOTE_DOUBLE,d=j0(o,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let c=r+o.length,m=L0.resolveEnd(i,c,t,n);return{value:d,type:a,comment:m.comment,range:[r,c,m.offset]}}function D0(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Zk(e)}function _0(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Zk(e.slice(1,-1)).replace(/''/g,"'")}function Zk(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,s;try{r=new RegExp("(?<![ ])[ ]+$"),s=new RegExp("^[ ]+|(?<![ ])[ ]+$","g")}catch{r=/[ \t]+$/,s=/^[ \t]+|[ \t]+$/g}let o=n[1].replace(r,""),i=" ",a=t.lastIndex;for(;n=t.exec(e);){let l=n[1].replace(s,"");l===""?i===`
87
- `?o+=i:i=`
88
- `:(o+=i+l,i=" "),a=t.lastIndex}let d=/[ \t]*(.*)/sy;return d.lastIndex=a,n=d.exec(e),o+i+(n?.[1]??"")}function j0(e,t){let n="";for(let r=1;r<e.length-1;++r){let s=e[r];if(!(s==="\r"&&e[r+1]===`
89
- `))if(s===`
90
- `){let{fold:o,offset:i}=F0(e,r);n+=o,r=i}else if(s==="\\"){let o=e[++r],i=q0[o];if(i)n+=i;else if(o===`
91
- `)for(o=e[r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="\r"&&e[r+1]===`
92
- `)for(o=e[++r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="x"||o==="u"||o==="U"){let a=o==="x"?2:o==="u"?4:8;n+=B0(e,r+1,a,t),r+=a}else{let a=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(s===" "||s===" "){let o=r,i=e[r+1];for(;i===" "||i===" ";)i=e[++r+1];i!==`
86
+ `}let u=r+o.length+t.source.length;return{value:m,type:s,comment:o.comment,range:[r,u,u]}}function Gq({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=t[0],s=o[0],i=0,a="",d=-1;for(let p=1;p<o.length;++p){let h=o[p];if(!a&&(h==="-"||h==="+"))a=h;else{let u=Number(h);!i&&u?i=u:d===-1&&(d=e+p)}}d!==-1&&r(d,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let l=!1,c="",m=o.length;for(let p=1;p<t.length;++p){let h=t[p];switch(h.type){case"space":l=!0;case"newline":m+=h.source.length;break;case"comment":n&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),m+=h.source.length,c=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),m+=h.source.length;break;default:{let u=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",u);let y=h.source;y&&typeof y=="string"&&(m+=y.length)}}}return{mode:s,indent:i,chomp:a,comment:c,length:m}}function Vq(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<t.length;i+=2)s.push([t[i],t[i+1]]);return s}rI.resolveBlockScalar=Uq});var tf=D(sI=>{"use strict";var ef=Ce(),Yq=ho();function Kq(e,t,n){let{offset:r,type:o,source:s,end:i}=e,a,d,l=(p,h,u)=>n(r+p,h,u);switch(o){case"scalar":a=ef.Scalar.PLAIN,d=zq(s,l);break;case"single-quoted-scalar":a=ef.Scalar.QUOTE_SINGLE,d=Jq(s,l);break;case"double-quoted-scalar":a=ef.Scalar.QUOTE_DOUBLE,d=Xq(s,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let c=r+s.length,m=Yq.resolveEnd(i,c,t,n);return{value:d,type:a,comment:m.comment,range:[r,c,m.offset]}}function zq(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),oI(e)}function Jq(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),oI(e.slice(1,-1)).replace(/''/g,"'")}function oI(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,o;try{r=new RegExp("(?<![ ])[ ]+$"),o=new RegExp("^[ ]+|(?<![ ])[ ]+$","g")}catch{r=/[ \t]+$/,o=/^[ \t]+|[ \t]+$/g}let s=n[1].replace(r,""),i=" ",a=t.lastIndex;for(;n=t.exec(e);){let l=n[1].replace(o,"");l===""?i===`
87
+ `?s+=i:i=`
88
+ `:(s+=i+l,i=" "),a=t.lastIndex}let d=/[ \t]*(.*)/sy;return d.lastIndex=a,n=d.exec(e),s+i+(n?.[1]??"")}function Xq(e,t){let n="";for(let r=1;r<e.length-1;++r){let o=e[r];if(!(o==="\r"&&e[r+1]===`
89
+ `))if(o===`
90
+ `){let{fold:s,offset:i}=Qq(e,r);n+=s,r=i}else if(o==="\\"){let s=e[++r],i=Zq[s];if(i)n+=i;else if(s===`
91
+ `)for(s=e[r+1];s===" "||s===" ";)s=e[++r+1];else if(s==="\r"&&e[r+1]===`
92
+ `)for(s=e[++r+1];s===" "||s===" ";)s=e[++r+1];else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;n+=eW(e,r+1,a,t),r+=a}else{let a=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(o===" "||o===" "){let s=r,i=e[r+1];for(;i===" "||i===" ";)i=e[++r+1];i!==`
93
93
  `&&!(i==="\r"&&e[r+2]===`
94
- `)&&(n+=r>o?e.slice(o,r+1):s)}else n+=s}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function F0(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
94
+ `)&&(n+=r>s?e.slice(s,r+1):o)}else n+=o}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function Qq(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
95
95
  `||r==="\r")&&!(r==="\r"&&e[t+2]!==`
96
96
  `);)r===`
97
97
  `&&(n+=`
98
- `),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var q0={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
99
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function B0(e,t,n,r){let s=e.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;try{return String.fromCodePoint(i)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}eE.resolveFlowScalar=P0});var rE=L(nE=>{"use strict";var Dn=G(),tE=pe(),W0=Pm(),U0=_m();function H0(e,t,n,r){let{value:s,type:o,comment:i,range:a}=t.type==="block-scalar"?W0.resolveBlockScalar(e,t,r):U0.resolveFlowScalar(t,e.options.strict,r),d=n?e.directives.tagName(n.source,m=>r(n,"TAG_RESOLVE_FAILED",m)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Dn.SCALAR]:d?l=G0(e.schema,s,d,n,r):t.type==="scalar"?l=V0(e,s,t,r):l=e.schema[Dn.SCALAR];let c;try{let m=l.resolve(s,f=>r(n??t,"TAG_RESOLVE_FAILED",f),e.options);c=Dn.isScalar(m)?m:new tE.Scalar(m)}catch(m){let f=m instanceof Error?m.message:String(m);r(n??t,"TAG_RESOLVE_FAILED",f),c=new tE.Scalar(s)}return c.range=a,c.source=s,o&&(c.type=o),d&&(c.tag=d),l.format&&(c.format=l.format),i&&(c.comment=i),c}function G0(e,t,n,r,s){if(n==="!")return e[Dn.SCALAR];let o=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(t))return a;let i=e.knownTags[n];return i&&!i.collection?(e.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[Dn.SCALAR])}function V0({atKey:e,directives:t,schema:n},r,s,o){let i=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[Dn.SCALAR];if(n.compat){let a=n.compat.find(d=>d.default&&d.test?.test(r))??n[Dn.SCALAR];if(i.tag!==a.tag){let d=t.tagString(i.tag),l=t.tagString(a.tag),c=`Value may be parsed as either ${d} or ${l}`;o(s,"TAG_RESOLVE_FAILED",c,!0)}}return i}nE.composeScalar=H0});var oE=L(sE=>{"use strict";function K0(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let s=t[r];switch(s.type){case"space":case"comment":case"newline":e-=s.source.length;continue}for(s=t[++r];s?.type==="space";)e+=s.source.length,s=t[++r];break}}return e}sE.emptyScalarPosition=K0});var dE=L(Fm=>{"use strict";var Y0=xs(),z0=G(),J0=Xk(),iE=rE(),X0=Nr(),Q0=oE(),Z0={composeNode:aE,composeEmptyNode:jm};function aE(e,t,n,r){let s=e.atKey,{spaceBefore:o,comment:i,anchor:a,tag:d}=n,l,c=!0;switch(t.type){case"alias":l=eD(e,t,r),(a||d)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=iE.composeScalar(e,t,d,r),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=J0.composeCollection(Z0,e,t,n,r),a&&(l.anchor=a.source.substring(1))}catch(m){let f=m instanceof Error?m.message:String(m);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let m=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",m),c=!1}}return l??(l=jm(e,t.offset,void 0,null,n,r)),a&&l.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&e.options.stringKeys&&(!z0.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(d??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(l.spaceBefore=!0),i&&(t.type==="scalar"&&t.source===""?l.comment=i:l.commentBefore=i),e.options.keepSourceTokens&&c&&(l.srcToken=t),l}function jm(e,t,n,r,{spaceBefore:s,comment:o,anchor:i,tag:a,end:d},l){let c={type:"scalar",offset:Q0.emptyScalarPosition(t,n,r),indent:-1,source:""},m=iE.composeScalar(e,c,a,l);return i&&(m.anchor=i.source.substring(1),m.anchor===""&&l(i,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(m.spaceBefore=!0),o&&(m.comment=o,m.range[2]=d),m}function eD({options:e},{offset:t,source:n,end:r},s){let o=new Y0.Alias(n.substring(1));o.source===""&&s(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&s(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=t+n.length,a=X0.resolveEnd(r,i,e.strict,s);return o.range=[t,i,a.offset],a.comment&&(o.comment=a.comment),o}Fm.composeEmptyNode=jm;Fm.composeNode=aE});var mE=L(cE=>{"use strict";var tD=Hs(),lE=dE(),nD=Nr(),rD=Ys();function sD(e,t,{offset:n,start:r,value:s,end:o},i){let a=Object.assign({_directives:t},e),d=new tD.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:d.directives,options:d.options,schema:d.schema},c=rD.resolveProps(r,{indicator:"doc-start",next:s??o?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});c.found&&(d.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!c.hasNewline&&i(c.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),d.contents=s?lE.composeNode(l,s,c,i):lE.composeEmptyNode(l,c.end,r,null,c,i);let m=d.contents.range[2],f=nD.resolveEnd(o,m,!1,i);return f.comment&&(d.comment=f.comment),d.range=[n,m,f.offset],d}cE.composeDoc=sD});var Bm=L(pE=>{"use strict";var oD=Co("process"),iD=Ic(),aD=Hs(),zs=Ks(),fE=G(),dD=mE(),lD=Nr();function Js(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function uE(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){let o=e[s];switch(o[0]){case"#":t+=(t===""?"":r?`
98
+ `),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var Zq={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
99
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function eW(e,t,n,r){let o=e.substr(t,n),i=o.length===n&&/^[0-9a-fA-F]+$/.test(o)?parseInt(o,16):NaN;try{return String.fromCodePoint(i)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}sI.resolveFlowScalar=Kq});var dI=D(aI=>{"use strict";var pr=ee(),iI=Ce(),tW=Zp(),nW=tf();function rW(e,t,n,r){let{value:o,type:s,comment:i,range:a}=t.type==="block-scalar"?tW.resolveBlockScalar(e,t,r):nW.resolveFlowScalar(t,e.options.strict,r),d=n?e.directives.tagName(n.source,m=>r(n,"TAG_RESOLVE_FAILED",m)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[pr.SCALAR]:d?l=oW(e.schema,o,d,n,r):t.type==="scalar"?l=sW(e,o,t,r):l=e.schema[pr.SCALAR];let c;try{let m=l.resolve(o,p=>r(n??t,"TAG_RESOLVE_FAILED",p),e.options);c=pr.isScalar(m)?m:new iI.Scalar(m)}catch(m){let p=m instanceof Error?m.message:String(m);r(n??t,"TAG_RESOLVE_FAILED",p),c=new iI.Scalar(o)}return c.range=a,c.source=o,s&&(c.type=s),d&&(c.tag=d),l.format&&(c.format=l.format),i&&(c.comment=i),c}function oW(e,t,n,r,o){if(n==="!")return e[pr.SCALAR];let s=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(t))return a;let i=e.knownTags[n];return i&&!i.collection?(e.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(o(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[pr.SCALAR])}function sW({atKey:e,directives:t,schema:n},r,o,s){let i=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[pr.SCALAR];if(n.compat){let a=n.compat.find(d=>d.default&&d.test?.test(r))??n[pr.SCALAR];if(i.tag!==a.tag){let d=t.tagString(i.tag),l=t.tagString(a.tag),c=`Value may be parsed as either ${d} or ${l}`;s(o,"TAG_RESOLVE_FAILED",c,!0)}}return i}aI.composeScalar=rW});var cI=D(lI=>{"use strict";function iW(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let o=t[r];switch(o.type){case"space":case"comment":case"newline":e-=o.source.length;continue}for(o=t[++r];o?.type==="space";)e+=o.source.length,o=t[++r];break}}return e}lI.emptyScalarPosition=iW});var fI=D(rf=>{"use strict";var aW=gs(),dW=ee(),lW=nI(),mI=dI(),cW=ho(),mW=cI(),pW={composeNode:pI,composeEmptyNode:nf};function pI(e,t,n,r){let o=e.atKey,{spaceBefore:s,comment:i,anchor:a,tag:d}=n,l,c=!0;switch(t.type){case"alias":l=fW(e,t,r),(a||d)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=mI.composeScalar(e,t,d,r),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=lW.composeCollection(pW,e,t,n,r),a&&(l.anchor=a.source.substring(1))}catch(m){let p=m instanceof Error?m.message:String(m);r(t,"RESOURCE_EXHAUSTION",p)}break;default:{let m=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",m),c=!1}}return l??(l=nf(e,t.offset,void 0,null,n,r)),a&&l.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&e.options.stringKeys&&(!dW.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(d??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),i&&(t.type==="scalar"&&t.source===""?l.comment=i:l.commentBefore=i),e.options.keepSourceTokens&&c&&(l.srcToken=t),l}function nf(e,t,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:d},l){let c={type:"scalar",offset:mW.emptyScalarPosition(t,n,r),indent:-1,source:""},m=mI.composeScalar(e,c,a,l);return i&&(m.anchor=i.source.substring(1),m.anchor===""&&l(i,"BAD_ALIAS","Anchor cannot be an empty string")),o&&(m.spaceBefore=!0),s&&(m.comment=s,m.range[2]=d),m}function fW({options:e},{offset:t,source:n,end:r},o){let s=new aW.Alias(n.substring(1));s.source===""&&o(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=t+n.length,a=cW.resolveEnd(r,i,e.strict,o);return s.range=[t,i,a.offset],a.comment&&(s.comment=a.comment),s}rf.composeEmptyNode=nf;rf.composeNode=pI});var gI=D(hI=>{"use strict";var uW=Ms(),uI=fI(),hW=ho(),gW=Ls();function yW(e,t,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:t},e),d=new uW.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:d.directives,options:d.options,schema:d.schema},c=gW.resolveProps(r,{indicator:"doc-start",next:o??s?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});c.found&&(d.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!c.hasNewline&&i(c.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),d.contents=o?uI.composeNode(l,o,c,i):uI.composeEmptyNode(l,c.end,r,null,c,i);let m=d.contents.range[2],p=hW.resolveEnd(s,m,!1,i);return p.comment&&(d.comment=p.comment),d.range=[n,m,p.offset],d}hI.composeDoc=yW});var sf=D(bI=>{"use strict";var wW=li("process"),bW=Um(),EW=Ms(),_s=Ds(),yI=ee(),CW=gI(),RW=ho();function js(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function wI(e){let t="",n=!1,r=!1;for(let o=0;o<e.length;++o){let s=e[o];switch(s[0]){case"#":t+=(t===""?"":r?`
100
100
 
101
101
  `:`
102
- `)+(o.substring(1)||" "),n=!0,r=!1;break;case"%":e[s+1]?.[0]!=="#"&&(s+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var qm=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,s,o)=>{let i=Js(n);o?this.warnings.push(new zs.YAMLWarning(i,r,s)):this.errors.push(new zs.YAMLParseError(i,r,s))},this.directives=new iD.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:s}=uE(this.prelude);if(r){let o=t.contents;if(n)t.comment=t.comment?`${t.comment}
103
- ${r}`:r;else if(s||t.directives.docStart||!o)t.commentBefore=r;else if(fE.isCollection(o)&&!o.flow&&o.items.length>0){let i=o.items[0];fE.isPair(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}
104
- ${a}`:r}else{let i=o.commentBefore;o.commentBefore=i?`${r}
105
- ${i}`:r}}if(n){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:uE(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let s of t)yield*this.next(s);yield*this.end(n,r)}*next(t){switch(oD.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,s)=>{let o=Js(t);o[0]+=n,this.onError(o,"BAD_DIRECTIVE",r,s)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=dD.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new zs.YAMLParseError(Js(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new zs.YAMLParseError(Js(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=lD.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
106
- ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new zs.YAMLParseError(Js(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),s=new aD.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,n,n],this.decorate(s,!1),yield s}}};pE.Composer=qm});var yE=L(ga=>{"use strict";var cD=Pm(),mD=_m(),fD=Ks(),hE=Ns();function uD(e,t=!0,n){if(e){let r=(s,o,i)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(n)n(a,o,i);else throw new fD.YAMLParseError([a,a+1],o,i)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return mD.resolveFlowScalar(e,t,r);case"block-scalar":return cD.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function pD(e,t){let{implicitKey:n=!1,indent:r,inFlow:s=!1,offset:o=-1,type:i="PLAIN"}=t,a=hE.stringifyString({type:i,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),d=t.end??[{type:"newline",offset:-1,indent:r,source:`
102
+ `)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":e[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var of=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=js(n);s?this.warnings.push(new _s.YAMLWarning(i,r,o)):this.errors.push(new _s.YAMLParseError(i,r,o))},this.directives=new bW.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:o}=wI(this.prelude);if(r){let s=t.contents;if(n)t.comment=t.comment?`${t.comment}
103
+ ${r}`:r;else if(o||t.directives.docStart||!s)t.commentBefore=r;else if(yI.isCollection(s)&&!s.flow&&s.items.length>0){let i=s.items[0];yI.isPair(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}
104
+ ${a}`:r}else{let i=s.commentBefore;s.commentBefore=i?`${r}
105
+ ${i}`:r}}if(n){for(let s=0;s<this.errors.length;++s)t.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)t.warnings.push(this.warnings[s])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:wI(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let o of t)yield*this.next(o);yield*this.end(n,r)}*next(t){switch(wW.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,o)=>{let s=js(t);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=CW.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new _s.YAMLParseError(js(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new _s.YAMLParseError(js(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=RW.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
106
+ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new _s.YAMLParseError(js(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),o=new EW.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),o.range=[0,n,n],this.decorate(o,!1),yield o}}};bI.Composer=of});var RI=D(Ed=>{"use strict";var kW=Zp(),vW=tf(),IW=Ds(),EI=Cs();function SW(e,t=!0,n){if(e){let r=(o,s,i)=>{let a=typeof o=="number"?o:Array.isArray(o)?o[0]:o.offset;if(n)n(a,s,i);else throw new IW.YAMLParseError([a,a+1],s,i)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return vW.resolveFlowScalar(e,t,r);case"block-scalar":return kW.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function $W(e,t){let{implicitKey:n=!1,indent:r,inFlow:o=!1,offset:s=-1,type:i="PLAIN"}=t,a=EI.stringifyString({type:i,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}}),d=t.end??[{type:"newline",offset:-1,indent:r,source:`
107
107
  `}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
108
108
  `),c=a.substring(0,l),m=a.substring(l+1)+`
109
- `,f=[{type:"block-scalar-header",offset:o,indent:r,source:c}];return gE(f,d)||f.push({type:"newline",offset:-1,indent:r,source:`
110
- `}),{type:"block-scalar",offset:o,indent:r,props:f,source:m}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:a,end:d};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:a,end:d};default:return{type:"scalar",offset:o,indent:r,source:a,end:d}}}function hD(e,t,n={}){let{afterKey:r=!1,implicitKey:s=!1,inFlow:o=!1,type:i}=n,a="indent"in e?e.indent:null;if(r&&typeof a=="number"&&(a+=2),!i)switch(e.type){case"single-quoted-scalar":i="QUOTE_SINGLE";break;case"double-quoted-scalar":i="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:i="PLAIN"}let d=hE.stringifyString({type:i,value:t},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(d[0]){case"|":case">":gD(e,d);break;case'"':Wm(e,d,"double-quoted-scalar");break;case"'":Wm(e,d,"single-quoted-scalar");break;default:Wm(e,d,"scalar")}}function gD(e,t){let n=t.indexOf(`
111
- `),r=t.substring(0,n),s=t.substring(n+1)+`
112
- `;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=r,e.source=s}else{let{offset:o}=e,i="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:i,source:r}];gE(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:i,source:`
113
- `});for(let d of Object.keys(e))d!=="type"&&d!=="offset"&&delete e[d];Object.assign(e,{type:"block-scalar",indent:i,props:a,source:s})}}function gE(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function Wm(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),s=t.length;e.props[0].type==="block-scalar-header"&&(s-=e.props[0].source.length);for(let o of r)o.offset+=s;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{let s={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
114
- `};delete e.items,Object.assign(e,{type:n,source:t,end:[s]});break}default:{let r="indent"in e?e.indent:-1,s="end"in e&&Array.isArray(e.end)?e.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:n,indent:r,source:t,end:s})}}}ga.createScalarToken=pD;ga.resolveAsScalar=uD;ga.setScalarValue=hD});var bE=L(wE=>{"use strict";var yD=e=>"type"in e?wa(e):ya(e);function wa(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=wa(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=ya(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=ya(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=ya(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function ya({start:e,key:t,sep:n,value:r}){let s="";for(let o of e)s+=o.source;if(t&&(s+=wa(t)),n)for(let o of n)s+=o.source;return r&&(s+=wa(r)),s}wE.stringify=yD});var RE=L(CE=>{"use strict";var Um=Symbol("break visit"),wD=Symbol("skip children"),kE=Symbol("remove item");function _n(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),EE(Object.freeze([]),e,t)}_n.BREAK=Um;_n.SKIP=wD;_n.REMOVE=kE;_n.itemAtPath=(e,t)=>{let n=e;for(let[r,s]of t){let o=n?.[r];if(o&&"items"in o)n=o.items[s];else return}return n};_n.parentCollection=(e,t)=>{let n=_n.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],s=n?.[r];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function EE(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let s of["key","value"]){let o=t[s];if(o&&"items"in o){for(let i=0;i<o.items.length;++i){let a=EE(Object.freeze(e.concat([[s,i]])),o.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Um)return Um;a===kE&&(o.items.splice(i,1),i-=1)}}typeof r=="function"&&s==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}CE.visit=_n});var ba=L(Oe=>{"use strict";var Hm=yE(),bD=bE(),kD=RE(),Gm="\uFEFF",Vm="",Km="",Ym="",ED=e=>!!e&&"items"in e,CD=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function RD(e){switch(e){case Gm:return"<BOM>";case Vm:return"<DOC>";case Km:return"<FLOW_END>";case Ym:return"<SCALAR>";default:return JSON.stringify(e)}}function SD(e){switch(e){case Gm:return"byte-order-mark";case Vm:return"doc-mode";case Km:return"flow-error-end";case Ym:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
109
+ `,p=[{type:"block-scalar-header",offset:s,indent:r,source:c}];return CI(p,d)||p.push({type:"newline",offset:-1,indent:r,source:`
110
+ `}),{type:"block-scalar",offset:s,indent:r,props:p,source:m}}case'"':return{type:"double-quoted-scalar",offset:s,indent:r,source:a,end:d};case"'":return{type:"single-quoted-scalar",offset:s,indent:r,source:a,end:d};default:return{type:"scalar",offset:s,indent:r,source:a,end:d}}}function TW(e,t,n={}){let{afterKey:r=!1,implicitKey:o=!1,inFlow:s=!1,type:i}=n,a="indent"in e?e.indent:null;if(r&&typeof a=="number"&&(a+=2),!i)switch(e.type){case"single-quoted-scalar":i="QUOTE_SINGLE";break;case"double-quoted-scalar":i="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:i="PLAIN"}let d=EI.stringifyString({type:i,value:t},{implicitKey:o||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(d[0]){case"|":case">":xW(e,d);break;case'"':af(e,d,"double-quoted-scalar");break;case"'":af(e,d,"single-quoted-scalar");break;default:af(e,d,"scalar")}}function xW(e,t){let n=t.indexOf(`
111
+ `),r=t.substring(0,n),o=t.substring(n+1)+`
112
+ `;if(e.type==="block-scalar"){let s=e.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=r,e.source=o}else{let{offset:s}=e,i="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:i,source:r}];CI(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:i,source:`
113
+ `});for(let d of Object.keys(e))d!=="type"&&d!=="offset"&&delete e[d];Object.assign(e,{type:"block-scalar",indent:i,props:a,source:o})}}function CI(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function af(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),o=t.length;e.props[0].type==="block-scalar-header"&&(o-=e.props[0].source.length);for(let s of r)s.offset+=o;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{let o={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
114
+ `};delete e.items,Object.assign(e,{type:n,source:t,end:[o]});break}default:{let r="indent"in e?e.indent:-1,o="end"in e&&Array.isArray(e.end)?e.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(e))s!=="type"&&s!=="offset"&&delete e[s];Object.assign(e,{type:n,indent:r,source:t,end:o})}}}Ed.createScalarToken=$W;Ed.resolveAsScalar=SW;Ed.setScalarValue=TW});var vI=D(kI=>{"use strict";var AW=e=>"type"in e?Rd(e):Cd(e);function Rd(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=Rd(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=Cd(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=Cd(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=Cd(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Cd({start:e,key:t,sep:n,value:r}){let o="";for(let s of e)o+=s.source;if(t&&(o+=Rd(t)),n)for(let s of n)o+=s.source;return r&&(o+=Rd(r)),o}kI.stringify=AW});var TI=D($I=>{"use strict";var df=Symbol("break visit"),OW=Symbol("skip children"),II=Symbol("remove item");function fr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),SI(Object.freeze([]),e,t)}fr.BREAK=df;fr.SKIP=OW;fr.REMOVE=II;fr.itemAtPath=(e,t)=>{let n=e;for(let[r,o]of t){let s=n?.[r];if(s&&"items"in s)n=s.items[o];else return}return n};fr.parentCollection=(e,t)=>{let n=fr.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],o=n?.[r];if(o&&"items"in o)return o;throw new Error("Parent collection not found")};function SI(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let o of["key","value"]){let s=t[o];if(s&&"items"in s){for(let i=0;i<s.items.length;++i){let a=SI(Object.freeze(e.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===df)return df;a===II&&(s.items.splice(i,1),i-=1)}}typeof r=="function"&&o==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}$I.visit=fr});var kd=D(He=>{"use strict";var lf=RI(),MW=vI(),NW=TI(),cf="\uFEFF",mf="",pf="",ff="",PW=e=>!!e&&"items"in e,DW=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function LW(e){switch(e){case cf:return"<BOM>";case mf:return"<DOC>";case pf:return"<FLOW_END>";case ff:return"<SCALAR>";default:return JSON.stringify(e)}}function _W(e){switch(e){case cf:return"byte-order-mark";case mf:return"doc-mode";case pf:return"flow-error-end";case ff:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
115
115
  `:case`\r
116
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Oe.createScalarToken=Hm.createScalarToken;Oe.resolveAsScalar=Hm.resolveAsScalar;Oe.setScalarValue=Hm.setScalarValue;Oe.stringify=bD.stringify;Oe.visit=kD.visit;Oe.BOM=Gm;Oe.DOCUMENT=Vm;Oe.FLOW_END=Km;Oe.SCALAR=Ym;Oe.isCollection=ED;Oe.isScalar=CD;Oe.prettyToken=RD;Oe.tokenType=SD});var Xm=L(vE=>{"use strict";var Xs=ba();function Xe(e){switch(e){case void 0:case" ":case`
117
- `:case"\r":case" ":return!0;default:return!1}}var SE=new Set("0123456789ABCDEFabcdef"),vD=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ka=new Set(",[]{}"),ID=new Set(` ,[]{}
118
- \r `),zm=e=>!e||ID.has(e),Jm=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
116
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}He.createScalarToken=lf.createScalarToken;He.resolveAsScalar=lf.resolveAsScalar;He.setScalarValue=lf.setScalarValue;He.stringify=MW.stringify;He.visit=NW.visit;He.BOM=cf;He.DOCUMENT=mf;He.FLOW_END=pf;He.SCALAR=ff;He.isCollection=PW;He.isScalar=DW;He.prettyToken=LW;He.tokenType=_W});var gf=D(AI=>{"use strict";var Fs=kd();function mt(e){switch(e){case void 0:case" ":case`
117
+ `:case"\r":case" ":return!0;default:return!1}}var xI=new Set("0123456789ABCDEFabcdef"),jW=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),vd=new Set(",[]{}"),FW=new Set(` ,[]{}
118
+ \r `),uf=e=>!e||FW.has(e),hf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
119
119
  `?!0:n==="\r"?this.buffer[t+1]===`
120
- `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+t];if(n==="\r"){let s=this.buffer[r+t+1];if(s===`
121
- `||!s&&!this.atEnd)return t+r+1}return n===`
122
- `||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Xe(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
123
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Xs.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let o=t[r-1];if(o===" "||o===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let o=t[n-1];if(o===" "||o===" ")n-=1;else break}let s=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield Xs.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&Xe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Xe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Xe(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(zm),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&s[0]!=="#"||r===0&&(s.startsWith("---")||s.startsWith("..."))&&Xe(s[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield Xs.FLOW_END,yield*this.parseLineStart();let o=0;for(;s[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),s[o]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(zm),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||Xe(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let o=0;for(;this.buffer[n-1-o]==="\\";)o+=1;if(o%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),s=r.indexOf(`
124
- `,this.pos);if(s!==-1){for(;s!==-1;){let o=this.continueScalar(s+1);if(o===-1)break;s=r.indexOf(`
125
- `,o)}s!==-1&&(n=s-(r[s-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>Xe(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let o=this.pos;r=this.buffer[o];++o)switch(r){case" ":n+=1;break;case`
126
- `:t=o,n=0;break;case"\r":{let i=this.buffer[o+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`
127
- `)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
128
- `,o)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let s=t+1;for(r=this.buffer[s];r===" ";)r=this.buffer[++s];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
129
- `;)r=this.buffer[++s];t=s-1}else if(!this.blockScalarKeep)do{let o=t-1,i=this.buffer[o];i==="\r"&&(i=this.buffer[--o]);let a=o;for(;i===" ";)i=this.buffer[--o];if(i===`
130
- `&&o>=this.pos&&o+1+n>a)t=o;else break}while(!0);return yield Xs.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,s;for(;s=this.buffer[++r];)if(s===":"){let o=this.buffer[r+1];if(Xe(o)||t&&ka.has(o))break;n=r}else if(Xe(s)){let o=this.buffer[r+1];if(s==="\r"&&(o===`
131
- `?(r+=1,s=`
132
- `,o=this.buffer[r+1]):n=r),o==="#"||t&&ka.has(o))break;if(s===`
133
- `){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(t&&ka.has(s))break;n=r}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Xs.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(zm),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Xe(r)||n&&ka.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!Xe(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(vD.has(n))n=this.buffer[++t];else if(n==="%"&&SE.has(this.buffer[t+1])&&SE.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
120
+ `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+t];if(n==="\r"){let o=this.buffer[r+t+1];if(o===`
121
+ `||!o&&!this.atEnd)return t+r+1}return n===`
122
+ `||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&mt(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
123
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Fs.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let s=t[r-1];if(s===" "||s===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let s=t[n-1];if(s===" "||s===" ")n-=1;else break}let o=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-o),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield Fs.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&mt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!mt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&mt(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(uf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let o=this.getLine();if(o===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&o[0]!=="#"||r===0&&(o.startsWith("---")||o.startsWith("..."))&&mt(o[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(o[0]==="]"||o[0]==="}")))return this.flowLevel=0,yield Fs.FLOW_END,yield*this.parseLineStart();let s=0;for(;o[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),o[s]){case void 0:return"flow";case"#":return yield*this.pushCount(o.length-s),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(uf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||mt(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let s=0;for(;this.buffer[n-1-s]==="\\";)s+=1;if(s%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),o=r.indexOf(`
124
+ `,this.pos);if(o!==-1){for(;o!==-1;){let s=this.continueScalar(o+1);if(s===-1)break;o=r.indexOf(`
125
+ `,s)}o!==-1&&(n=o-(r[o-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>mt(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let s=this.pos;r=this.buffer[s];++s)switch(r){case" ":n+=1;break;case`
126
+ `:t=s,n=0;break;case"\r":{let i=this.buffer[s+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`
127
+ `)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(t+1);if(s===-1)break;t=this.buffer.indexOf(`
128
+ `,s)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let o=t+1;for(r=this.buffer[o];r===" ";)r=this.buffer[++o];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
129
+ `;)r=this.buffer[++o];t=o-1}else if(!this.blockScalarKeep)do{let s=t-1,i=this.buffer[s];i==="\r"&&(i=this.buffer[--s]);let a=s;for(;i===" ";)i=this.buffer[--s];if(i===`
130
+ `&&s>=this.pos&&s+1+n>a)t=s;else break}while(!0);return yield Fs.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,o;for(;o=this.buffer[++r];)if(o===":"){let s=this.buffer[r+1];if(mt(s)||t&&vd.has(s))break;n=r}else if(mt(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===`
131
+ `?(r+=1,o=`
132
+ `,s=this.buffer[r+1]):n=r),s==="#"||t&&vd.has(s))break;if(o===`
133
+ `){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(t&&vd.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield Fs.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(uf),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(mt(r)||n&&vd.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!mt(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(jW.has(n))n=this.buffer[++t];else if(n==="%"&&xI.has(this.buffer[t+1])&&xI.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
134
134
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
135
- `?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let s=n-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=n),s}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};vE.Lexer=Jm});var Zm=L(IE=>{"use strict";var Qm=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let o=n+r>>1;this.lineStarts[o]<t?n=o+1:r=o}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let s=this.lineStarts[n-1];return{line:n,col:t-s+1}}}};IE.LineCounter=Qm});var tf=L(TE=>{"use strict";var $D=Co("process"),$E=ba(),xD=Xm();function sn(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function xE(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function AE(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Ea(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Lr(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Ca(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function ME(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!sn(t.start,"explicit-key-ind")&&!sn(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,AE(t.value)?t.value.end?Ca(t.value.end,t.sep):t.value.end=t.sep:Ca(t.start,t.sep),delete t.sep)}var ef=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new xD.Lexer,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,$D.env.LOG_TOKENS&&console.log("|",$E.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=$E.tokenType(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&ME(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let s=r.items[r.items.length-1];if(s.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=n;else{Object.assign(s,{key:n,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=r.items[r.items.length-1];s.value?r.items.push({start:[],value:n}):s.value=n;break}case"flow-collection":{let s=r.items[r.items.length-1];!s||s.value?r.items.push({start:[],key:n,sep:[]}):s.sep?s.value=n:Object.assign(s,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let s=n.items[n.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&xE(s.start)===-1&&(n.indent===0||s.start.every(o=>o.type!=="comment"||o.indent<n.indent))&&(r.type==="document"?r.end=s.start:r.items.push({start:s.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{xE(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=Ea(this.peek(2)),r=Lr(n),s;t.end?(s=t.end,s.push(this.sourceToken),delete t.end):s=[this.sourceToken];let o={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
135
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let o=n-this.pos;return o>0&&(yield this.buffer.substr(this.pos,o),this.pos=n),o}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};AI.Lexer=hf});var wf=D(OI=>{"use strict";var yf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<t?n=s+1:r=s}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let o=this.lineStarts[n-1];return{line:n,col:t-o+1}}}};OI.LineCounter=yf});var Ef=D(LI=>{"use strict";var qW=li("process"),MI=kd(),WW=gf();function $n(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function NI(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function DI(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Id(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function go(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Sd(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function PI(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!$n(t.start,"explicit-key-ind")&&!$n(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,DI(t.value)?t.value.end?Sd(t.value.end,t.sep):t.value.end=t.sep:Sd(t.start,t.sep),delete t.sep)}var bf=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new WW.Lexer,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,qW.env.LOG_TOKENS&&console.log("|",MI.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=MI.tokenType(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&PI(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let o=r.items[r.items.length-1];if(o.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(o.sep)o.value=n;else{Object.assign(o,{key:n,sep:[]}),this.onKeyLine=!o.explicitKey;return}break}case"block-seq":{let o=r.items[r.items.length-1];o.value?r.items.push({start:[],value:n}):o.value=n;break}case"flow-collection":{let o=r.items[r.items.length-1];!o||o.value?r.items.push({start:[],key:n,sep:[]}):o.sep?o.value=n:Object.assign(o,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let o=n.items[n.items.length-1];o&&!o.sep&&!o.value&&o.start.length>0&&NI(o.start)===-1&&(n.indent===0||o.start.every(s=>s.type!=="comment"||s.indent<n.indent))&&(r.type==="document"?r.end=o.start:r.items.push({start:o.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{NI(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=Id(this.peek(2)),r=go(n),o;t.end?(o=t.end,o.push(this.sourceToken),delete t.end):o=[this.sourceToken];let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
136
136
  `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
137
- `,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Ca(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,s=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let d=n.sep[a];switch(d.type){case"newline":i.push(a);break;case"space":break;case"comment":d.indent>t.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(o=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":s||n.value?(o.push(this.sourceToken),t.items.push({start:o}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):s||n.value?(o.push(this.sourceToken),t.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(sn(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(AE(n.key)&&!sn(n.sep,"newline")){let i=Lr(n.start),a=n.key,d=n.sep;d.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:d}]})}else o.length>0?n.sep=n.sep.concat(o,this.sourceToken):n.sep.push(this.sourceToken);else if(sn(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Lr(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||s?t.items.push({start:o,key:null,sep:[this.sourceToken]}):sn(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);s||n.value?(t.items.push({start:o,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(t);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!sn(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:o});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Ca(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||sn(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:s,sep:[]}):n.sep?this.stack.push(s):Object.assign(n,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let s=Ea(r),o=Lr(s);ME(t);let i=t.end.splice(1,t.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
137
+ `,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let o=t.items[t.items.length-2]?.value?.end;if(Array.isArray(o)){Sd(o,n.start),o.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let d=n.sep[a];switch(d.type){case"newline":i.push(a);break;case"space":break;case"comment":d.indent>t.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(s=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":o||n.value?(s.push(this.sourceToken),t.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):o||n.value?(s.push(this.sourceToken),t.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if($n(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(DI(n.key)&&!$n(n.sep,"newline")){let i=go(n.start),a=n.key,d=n.sep;d.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:d}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if($n(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=go(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||o?t.items.push({start:s,key:null,sep:[this.sourceToken]}):$n(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);o||n.value?(t.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(t);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!$n(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let o=t.items[t.items.length-2]?.value?.end;if(Array.isArray(o)){Sd(o,n.start),o.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||$n(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=Id(r),s=go(o);PI(t);let i=t.end.splice(1,t.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:s,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
138
138
  `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
139
- `,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ea(t),r=Lr(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ea(t),r=Lr(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};TE.Parser=ef});var DE=L(Zs=>{"use strict";var OE=Bm(),MD=Hs(),Qs=Ks(),AD=Fc(),TD=G(),OD=Zm(),NE=tf();function LE(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new OD.LineCounter||null,prettyErrors:t}}function ND(e,t={}){let{lineCounter:n,prettyErrors:r}=LE(t),s=new NE.Parser(n?.addNewLine),o=new OE.Composer(t),i=Array.from(o.compose(s.parse(e)));if(r&&n)for(let a of i)a.errors.forEach(Qs.prettifyError(e,n)),a.warnings.forEach(Qs.prettifyError(e,n));return i.length>0?i:Object.assign([],{empty:!0},o.streamInfo())}function PE(e,t={}){let{lineCounter:n,prettyErrors:r}=LE(t),s=new NE.Parser(n?.addNewLine),o=new OE.Composer(t),i=null;for(let a of o.compose(s.parse(e),!0,e.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Qs.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(Qs.prettifyError(e,n)),i.warnings.forEach(Qs.prettifyError(e,n))),i}function LD(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let s=PE(e,n);if(!s)return null;if(s.warnings.forEach(o=>AD.warn(s.options.logLevel,o)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function PD(e,t,n){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let s=Math.round(n);n=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=n??t??{};if(!s)return}return TD.isDocument(e)&&!r?e.toString(n):new MD.Document(e,r,n).toString(n)}Zs.parse=LD;Zs.parseAllDocuments=ND;Zs.parseDocument=PE;Zs.stringify=PD});var Sa=L(z=>{"use strict";var DD=Bm(),_D=Hs(),jD=Em(),nf=Ks(),FD=xs(),on=G(),qD=en(),BD=pe(),WD=nn(),UD=rn(),HD=ba(),GD=Xm(),VD=Zm(),KD=tf(),Ra=DE(),_E=Ss();z.Composer=DD.Composer;z.Document=_D.Document;z.Schema=jD.Schema;z.YAMLError=nf.YAMLError;z.YAMLParseError=nf.YAMLParseError;z.YAMLWarning=nf.YAMLWarning;z.Alias=FD.Alias;z.isAlias=on.isAlias;z.isCollection=on.isCollection;z.isDocument=on.isDocument;z.isMap=on.isMap;z.isNode=on.isNode;z.isPair=on.isPair;z.isScalar=on.isScalar;z.isSeq=on.isSeq;z.Pair=qD.Pair;z.Scalar=BD.Scalar;z.YAMLMap=WD.YAMLMap;z.YAMLSeq=UD.YAMLSeq;z.CST=HD;z.Lexer=GD.Lexer;z.LineCounter=VD.LineCounter;z.Parser=KD.Parser;z.parse=Ra.parse;z.parseAllDocuments=Ra.parseAllDocuments;z.parseDocument=Ra.parseDocument;z.stringify=Ra.stringify;z.visit=_E.visit;z.visitAsync=_E.visitAsync});var b={Success:0,Failure:1,Usage:2,NotFound:3,Validation:4,Conflict:5,NeedsHuman:6,Transient:7},et=e=>e instanceof Error?e.message:String(e),p=class extends Error{exitCode;reason;hint;type;requestId;details;constructor(t,n={}){let r=typeof n=="number"?{exitCode:n}:n;super(r.hint?`${t} ${r.hint}`:t),this.name="CliError",this.exitCode=r.exitCode??b.Failure,this.reason=t,this.hint=r.hint,this.type=r.type,this.requestId=r.requestId,this.details=r.details??{}}},$=(e,t="modeldesk --help")=>new p(e,{exitCode:b.Usage,hint:`Run '${t}'.`});var ke=(e,t)=>e.replace(/\{(\w+)\}/g,(n,r)=>{let s=t[r];if(s===""||s==="."||s==="..")throw $(`'${s}' is not a valid ${r}.`);return encodeURIComponent(s)}),D=(e,t,n,r)=>e.getJson(ke(t,n),r),pu=(e,t,n,r,s)=>e.getJsonIfChanged(ke(t,n),r,s),Q=(e,t,n,r,s)=>e.postJson(ke(t,n),r,s),Ro=e=>e&&e.length>0?e.join(","):void 0;var hu=e=>({list:t=>D(e,"/models/{modelId}/branches",{modelId:t}),create:(t,n)=>Q(e,"/models/{modelId}/branches",{modelId:t},n),delete:(t,n,r)=>e.delete(ke("/models/{modelId}/branches/{branchId}",{modelId:t,branchId:n}),{force:r?"true":void 0}),diff:(t,n,r)=>D(e,"/models/{modelId}/branches/{branchId}/diff",{modelId:t,branchId:n},{base:r}),mergePreview:(t,n,r)=>D(e,"/models/{modelId}/branches/{branchId}/merge-preview",{modelId:t,branchId:n},{source:r}),merge:(t,n,r)=>Q(e,"/models/{modelId}/branches/{branchId}/merge",{modelId:t,branchId:n},r)});var nv=/[ \t\n\r\f]+/g,rv=/^[ \t\n\r\f]+|[ \t\n\r\f]+$/g,sv=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Ur=e=>e.replace(sv,"");var ov=(e,t)=>{if(!Number.isFinite(e))throw new Error(`Cannot write ${e} as an SVG number`);let n=10**t,r=Math.sign(e)*Math.round(Math.abs(e)*n)/n;return String(r===0?0:r)},Ed=e=>ov(e,2);var iv=e=>e.replace(nv," ").replace(rv,""),Hr=e=>iv(Ur(e)).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;");var gu="index.json",So=e=>{let t=e.fragments?.find(r=>r.address==="")?.realization?.path;if(t===void 0)return;let n=t.lastIndexOf("/");return n===-1?gu:`${t.slice(0,n)}/${gu}`},Gr=e=>[...new Set(e)].sort(),av=(e,t,n)=>{let r=new Map((e.elements??[]).map(i=>[Hr(i.id),i.id])),s=(e.diagrams??[]).filter(i=>!n.has(i.id)).map(i=>({...i,elements:Gr([...t.get(i.id)??[]].flatMap(a=>r.get(a)??[]))})),o=new Map;for(let i of s)for(let a of i.elements??[])o.set(a,[...o.get(a)??[],i.id]);return{...e,elements:(e.elements??[]).map(i=>({...i,diagrams:Gr(o.get(i.id)??[])})),diagrams:s}},dv=e=>({id:e.id,anchor:e.anchor,path:e.path,title:e.title,kind:e.kind,...e.status===void 0?{}:{status:e.status},...e.uri===void 0?{}:{uri:e.uri},refs:Gr(e.refs??[]),diagrams:Gr(e.diagrams??[])}),lv=e=>({id:e.id,path:e.path,title:e.title,elements:Gr(e.elements??[])}),yu=e=>{let t={convention:e.convention,...e.generatedFrom===void 0?{}:{generatedFrom:e.generatedFrom},elements:(e.elements??[]).map(dv),diagrams:(e.diagrams??[]).map(lv).sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0)};return`${JSON.stringify(t,null,2)}
140
- `},vo=(e,t,n)=>e.index===void 0?e:{...e,index:av(e.index,t,n)};var hn=e=>{let t=e.payloads??{},n=[];for(let s of e.manifest.fragments??[]){let o=s.realization?.path;if(!o)continue;let i=t[s.address];i!==void 0&&n.push({path:o,content:i})}let r=e.index===void 0?void 0:So(e.manifest);return e.index!==void 0&&r!==void 0&&n.push({path:r,content:yu(e.index)}),n},wu="image/svg+xml, image/png",Hn=e=>{let t=[];for(let n of e.fragments??[])for(let r of n.realization?.media??[])t.push(r);return[...new Set(t)]},Gn=(e,t={})=>{let n=new Set,r=new Set;for(let s of e)Object.hasOwn(t,s)?n.add(t[s]):r.add(s);return n.size+r.size};var bu=e=>({get:(t,n)=>D(e,"/models/{modelId}/content-bundle",{modelId:t},n),renderDiagrams:(t,n)=>Q(e,"/models/{modelId}/content-bundle/diagrams",{modelId:t},void 0,n),media:(t,n)=>e.getBytes(ke("/models/{modelId}/content-bundle/media",{modelId:t}),wu,n)});var ku=e=>({get:t=>D(e,"/datasets/{datasetId}",{datasetId:t}),commits:(t,n={})=>D(e,"/datasets/{datasetId}/commits",{datasetId:t},{limit:n.limit===void 0?void 0:String(n.limit),cursor:n.cursor})});var Eu=e=>({list:t=>D(e,"/models/{modelId}/dependencies",{modelId:t}),update:async(t,n,r)=>{let o={...await Q(e,"/models/{modelId}/dependencies/{dependencyId}",{modelId:t,dependencyId:n},r)};return delete o.model,o}});var Cu=e=>({draftHeadId:e}),Ru=e=>({model:{stage:async(t,n)=>{let{body:r,headers:s}=await e.postJsonWithHeaders(ke("/models/{modelId}/draft/changes",{modelId:t}),n);return{envelope:r,draftId:s.get("draft-ref")??void 0}},undo:(t,n)=>Q(e,"/models/{modelId}/draft/undo",{modelId:t},{draftHeadId:n}),commit:(t,n)=>Q(e,"/models/{modelId}/draft/commit",{modelId:t},n),rebase:(t,n)=>Q(e,"/models/{modelId}/draft/rebase",{modelId:t},n),diff:t=>D(e,"/models/{modelId}/draft/diff",{modelId:t}),discard:(t,n)=>e.delete(ke("/models/{modelId}/draft",{modelId:t}),Cu(n)),open:(t,n)=>Q(e,"/models/{modelId}/draft",{modelId:t},{branchId:n})},dataset:{get:t=>D(e,"/datasets/{datasetId}/draft",{datasetId:t}),undo:(t,n)=>Q(e,"/datasets/{datasetId}/draft/undo",{datasetId:t},{draftHeadId:n}),commit:(t,n)=>Q(e,"/datasets/{datasetId}/draft/commit",{datasetId:t},n),rebase:(t,n)=>Q(e,"/datasets/{datasetId}/draft/rebase",{datasetId:t},n),diff:t=>D(e,"/datasets/{datasetId}/draft/diff",{datasetId:t}),discard:(t,n)=>e.delete(ke("/datasets/{datasetId}/draft",{datasetId:t}),Cu(n))}});var Su=e=>({encode:(t,n)=>D(e,"/models/{modelId}/encoding",{modelId:t},{format:n.format,mapping:n.mapping}),encodeCompressed:(t,n)=>e.getBytes(ke("/models/{modelId}/encoding",{modelId:t}),"application/octet-stream",{format:n.format,mapping:n.mapping,compressed:"true"})});var vu=e=>({list:t=>D(e,"/metamodels/{metamodelId}/encoding-formats",{metamodelId:t})});var Iu=e=>({get:(t,n)=>D(e,"/models/{modelId}/export-jobs/{jobId}",{modelId:t,jobId:n})});var $u=e=>({list:t=>D(e,"/imports",{},{ownerId:t}),create:t=>Q(e,"/imports",{},t),get:t=>D(e,"/imports/{importId}",{importId:t}),model:t=>D(e,"/imports/{importId}/model",{importId:t}),complete:(t,n)=>Q(e,"/imports/{importId}/complete",{importId:t},{name:n}),delete:t=>e.delete(ke("/imports/{importId}",{importId:t}))});var xu=e=>({list:t=>D(e,"/metamodel-extensions",{},{metamodelId:t})});var Mu=e=>({list:()=>D(e,"/metamodel-models",{}),create:t=>Q(e,"/metamodel-models",{},t),versions:t=>D(e,"/metamodel-models/{metamodelModelId}/versions",{metamodelModelId:t})});var Au=e=>({list:t=>D(e,"/metamodels/{metamodelId}/versions",{metamodelId:t})});var Tu=e=>({list:()=>D(e,"/metamodels",{}),templates:(t,n={})=>D(e,"/metamodels/{metamodelId}/templates",{metamodelId:t},{metamodelExtensions:Ro(n.metamodelExtensions)})});var Ou=e=>({catalog:()=>D(e,"/model-loaders",{}),forMetamodel:(t,n)=>D(e,"/metamodels/{metamodelId}/loaders",{metamodelId:t},{version:n})});var Nu=e=>({list:(t={})=>D(e,"/model-mappings",{},{sourceMetamodel:t.sourceMetamodel})});var Lu=e=>({limit:e.limit===void 0?void 0:String(e.limit),cursor:e.cursor}),Pu=e=>({create:t=>Q(e,"/models",{},t),delete:t=>e.delete(ke("/models/{modelId}",{modelId:t})),list:(t={})=>D(e,"/models",{},{ownerId:t.ownerId,metamodel:t.metamodel}),get:(t,n)=>D(e,"/models/{modelId}",{modelId:t},n&&{ref:n.ref,commit:n.commit,expand:Ro(n.expand)}),identity:(t,n={})=>D(e,"/models/{modelId}/identity",{modelId:t},n),identityIfChanged:(t,n)=>pu(e,"/models/{modelId}/identity",{modelId:t},n),overview:t=>D(e,"/models/{modelId}/overview",{modelId:t}),versions:(t,n={})=>D(e,"/models/{modelId}/versions",{modelId:t},Lu(n)),commits:(t,n={})=>D(e,"/models/{modelId}/commits",{modelId:t},{...Lu(n),ref:n.ref,includeSystem:n.includeSystem?"true":void 0}),commitHeader:(t,n,r={})=>D(e,"/models/{modelId}/commits/{commitId}/header",{modelId:t,commitId:n},{ref:r.ref}),draft:t=>D(e,"/models/{modelId}/draft",{modelId:t}),schema:(t,n)=>D(e,"/models/{modelId}/schema",{modelId:t},{type:n})});var Du=e=>({createVersion:(t,n)=>Q(e,"/models/{modelId}/versions",{modelId:t},n),createMetamodelRelease:(t,n)=>Q(e,"/metamodel-models/{metamodelModelId}/versions",{metamodelModelId:t},n===void 0?{}:{description:n}),refreshExtensionBase:t=>Q(e,"/metamodel-models/{extensionId}/refresh-base-dependency",{extensionId:t}),metamodelOverview:()=>D(e,"/metamodel-overview",{})});var _u=e=>({get:async(t,n={})=>{let r=await D(e,"/models/{modelId}/validation",{modelId:t},n);return{valid:r.valid,logEntries:r.logEntries??[]}}});var ju=e=>({models:Pu(e),branches:hu(e),metamodels:Tu(e),metamodelModels:Mu(e),metamodelExtensions:xu(e),drafts:Ru(e),datasets:ku(e),contentBundles:bu(e),exportJobs:Iu(e),validation:_u(e),imports:$u(e),modelLoaders:Ou(e),metamodelVersions:Au(e),encodingFormats:vu(e),encoding:Su(e),modelMappings:Nu(e),dependencies:Eu(e),releases:Du(e),accessTokenClaims:()=>e.accessTokenClaims()});var gt={host:{env:"MODELDESK_HOST"},model:{env:"MODELDESK_MODEL"},stack:{env:"MODELDESK_STACK"},template:{env:"MODELDESK_TEMPLATE"},version:{env:"MODELDESK_VERSION"}};var Vr="modeldesk.io",B={host:gt.host.env,model:gt.model.env,stack:gt.stack.env,template:gt.template.env,version:gt.version.env,clientId:"MODELDESK_CLIENT_ID",clientSecret:"MODELDESK_CLIENT_SECRET",apiKey:"MODELDESK_API_KEY",agentSession:"MODELDESK_AGENT_SESSION",allowCommit:"MODELDESK_ALLOW_COMMIT"},cv=(...e)=>e.find(t=>t!==void 0&&t!==""),Kr=(e,t,n)=>{let r={};for(let[s,{env:o}]of Object.entries(gt))r[s]=cv(e[s],t[o],n[s]);return{...r,host:r.host??Vr}};var Fu={requestUrl:"ACTIONS_ID_TOKEN_REQUEST_URL",requestToken:"ACTIONS_ID_TOKEN_REQUEST_TOKEN"},Lt=e=>e!==void 0&&e!=="",qu=e=>e==="true"||e==="1",mv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Cd="mdsk_",Bu=57,gn=(e,t)=>({mode:"error",reason:e,message:t}),Pt="org settings \u2192 Service accounts",Yr=e=>{if(Lt(e[B.apiKey]))return gn("legacy-api-key",`${B.apiKey} is no longer supported: the CI credential shipped as service accounts, not bearer keys. Use secret mode (set ${B.clientId} and ${B.clientSecret} from ${Pt}) or, on GitHub Actions, federated auth (grant 'permissions: id-token: write' and add a trust rule). Unset ${B.apiKey}.`);let t=e[B.clientId],n=e[B.clientSecret];if(Lt(t)!==Lt(n)){let[o,i]=Lt(t)?[B.clientId,B.clientSecret]:[B.clientSecret,B.clientId];return gn("partial-secret-config",`${o} is set but ${i} is not \u2014 both are required for secret-mode auth. Check the pipeline's secret configuration.`)}if(Lt(t)&&Lt(n))return mv.test(t)?n.startsWith(Cd)?n.length!==Bu?gn("invalid-client-secret",`${B.clientSecret} has the wrong length: expected ${Bu} characters, got ${n.length}. Check for truncation in the pipeline's secret store.`):{mode:"secret",clientId:t,clientSecret:n}:gn("invalid-client-secret",`${B.clientSecret} does not start with '${Cd}' (an issued secret always does). Check for quoting or truncation in the pipeline's secret store.`):gn("invalid-client-id",`${B.clientId} is not a service-account id: expected a UUID, got a ${t.length}-character value. Copy the account id from ${Pt}.`);let r=e[Fu.requestUrl],s=e[Fu.requestToken];return Lt(r)&&Lt(s)?{mode:"federated",oidcRequestUrl:r,oidcRequestToken:s}:qu(e.GITHUB_ACTIONS)?gn("headless-ci",`Running on GitHub Actions without machine credentials. Grant 'permissions: id-token: write' to use federated auth (with a trust rule in ${Pt}), or set ${B.clientId} and ${B.clientSecret}. The CLI never opens a browser login in CI.`):qu(e.CI)?gn("headless-ci",`Running in CI without machine credentials. Set ${B.clientId} and ${B.clientSecret} (${Pt}). The CLI never opens a browser login in CI.`):{mode:"interactive"}},Ie=e=>{let t=Yr(e);return t.mode==="secret"||t.mode==="federated"?t.mode:void 0},Wu=e=>`${e.slice(0,Cd.length+8)}\u2026`,Uu=`Check ${B.clientId} and ${B.clientSecret}; issue or rotate a secret in ${Pt}.`,Hu=`The service account may be disabled or deleted \u2014 check ${Pt}.`,Gu={issuer:"the auth server does not trust this token issuer \u2014 federated auth currently supports GitHub Actions only.",signature:"the OIDC token's signature could not be verified \u2014 re-run the job; if it persists, the issuer's keys and the auth server disagree.",audience:`the workflow's OIDC audience does not match this host \u2014 check that --host/${B.host} names the ModelDesk instance the trust rule lives on.`,expired:"the OIDC token expired before the exchange \u2014 re-run the job.",repository:"no active trust rule matches this repository. This is also the failure for a pull-request-triggered run unless the rule enables 'Allow pull requests', and for a revoked rule.",binding:"the trust rule pins a branch or environment that does not match this run."},Io={unauthorized:`The machine token was rejected. A disabled or deleted service account fails on the next request; a revoked secret within five minutes. Check ${Pt}.`,forbidden:`The service account's scopes do not permit this \u2014 pulling content needs the 'model:content' scope (${Pt}).`,notFound:"Check the model id. A machine credential reads SHARED models only (creator-private models are not visible), and the model's metamodel must be entitled under the organization's subscription."};var fv="http://localhost:8080",uv="http://localhost:8082",pv="http://localhost:3000",hv="localhost",gv=e=>{let t=e.trim(),n=/:\/\//.test(t)?t:`https://${t}`;try{return new URL(n).hostname}catch{return t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("/")[0].split(":")[0]}},yv=e=>e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]",zr=e=>{let t=gv(e);return yv(t)?{host:hv,apiBase:fv,issuer:uv,appBase:pv}:{host:t,apiBase:`https://api.${t}`,issuer:`https://auth.${t}`,appBase:`https://app.${t}`}};import{existsSync as bv,readFileSync as kv}from"node:fs";import{join as Ev}from"node:path";import{posix as wv}from"node:path";var Vn=e=>{if(e.trim()==="")return"is empty";if(e.includes("\\"))return'has a backslash; separate folders with "/"';if(/[\t\r\n]/.test(e))return"has a tab or a line break";if(e.startsWith("/")||/^[A-Za-z]:/.test(e))return"is absolute";if(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e))return"is a URL";if(e.includes("%"))return'has a "%", which the document reads as a percent-escape; name the file without one';if(e.includes("#"))return'has a "#", which the document reads as the start of a fragment; name the file without one';if(e.includes("?"))return'has a "?", which the document reads as the start of a query; name the file without one';if(e.split("/").some(t=>t!==t.trim()))return"has a folder or file name that starts or ends with a space";if(e.split("/").includes(".."))return'has a ".." segment'},ye=e=>wv.normalize(e).replace(/(.)\/+$/,"$1"),yn=(e,t)=>{let n=ye(e),r=ye(t);return r==="."||n===r||n.startsWith(`${r}/`)};var Kn=".modeldesk",Cv="config.json",$o="md-notes/",xo=e=>e.configPath!==void 0,Yn=e=>{let t=Ev(e,Kn,Cv);return bv(t)?{config:Rv(t),configPath:t,repoRoot:e}:{config:{},repoRoot:e}},Rv=e=>{let t;try{t=kv(e,"utf8")}catch(s){throw new p(`Could not read ${e}: ${s.message}`)}let n;try{n=JSON.parse(t)}catch(s){throw new p(`${e} is not valid JSON: ${s.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new p(`${e} must contain a JSON object.`);let r=n;return{...Object.fromEntries(Object.keys(gt).map(s=>[s,Vu(r,s,e)])),notesDir:Sv(r,"notesDir",e),publishDirs:vv(r,"publishDirs",e)}},Vu=(e,t,n)=>{let r=e[t];if(r!==void 0){if(typeof r!="string")throw new p(`${n}: "${t}" must be a string.`);return r}},Sv=(e,t,n)=>{let r=Vu(e,t,n);return r!==void 0&&Ku(r,`"${t}"`,n),r},vv=(e,t,n)=>{let r=e[t];if(r!==void 0){if(!Array.isArray(r)||!r.every(s=>typeof s=="string"))throw new p(`${n}: "${t}" must be an array of strings.`);return r.forEach((s,o)=>Ku(s,`"${t}"[${o}]`,n)),r}},Ku=(e,t,n)=>{let r=Vn(e);if(r!==void 0)throw new p(`${n}: ${t} ${JSON.stringify(e)} ${r}; give a folder relative to the repository root.`)};var Rd=(e,t,n)=>{let r=n[B.host];return!(t!==void 0&&t!==""||r!==void 0&&r!=="")&&xo(e)&&!!e.config.host},Iv=(e,t)=>{Rd(t,e.globals.host,e.env)&&t.config.host!==Vr&&e.io.err(`note: using host '${t.config.host}' from ${t.configPath} (it drives login and API calls).
141
- `)},$v=(e,t,n)=>{if(Ie(n)&&Rd(e,t,n))throw new p(`In a machine-auth run the host must be set explicitly: pass --host or set ${B.host}. The committed ${e.configPath??".modeldesk/config.json"} is not a trusted source for where machine credentials are sent.`)},Yu=e=>{let t=Yn(e.cwd);if(!e.interactive&&Rd(t,e.globals.host,e.env))throw new p(`A login without a terminal takes its host only from --host or ${B.host}, not from ${t.configPath??".modeldesk/config.json"}.`,{hint:`Pass --host ${t.config.host} if you trust it, or log in from a terminal.`})},zn=(e,t={})=>{let n=Yn(e.cwd),r=Kr({host:e.globals.host},e.env,n.config);return t.gateMachineHost&&$v(n,e.globals.host,e.env),Iv(e,n),zr(r.host)},Mo=(e,t)=>{let n=e.instance(),r=Yn(e.cwd),s=Kr({...t,host:e.globals.host},e.env,r.config);if(!s.model)throw new p(`No model specified. Pass --model, set ${B.model}, or add "model" to .modeldesk/config.json.`);return{instance:n,model:s.model,stack:s.stack,template:s.template,version:s.version,loaded:r}},Jr=(e,t,n,r)=>{let s=e?.trim();if(!s)throw new p(`No ${t} specified. Pass ${r}, set ${n}, or add "${t}" to .modeldesk/config.json. Run 'modeldesk bundle templates' to list a model's stacks and templates.`);return s};var xv=e=>{let t=[];for(let n of e)n.forEach((r,s)=>{t[s]=Math.max(t[s]??0,r.length)});return t},j=(e,{indent:t="",gap:n=2,widths:r}={})=>{let o=xv(e).map((a,d)=>r?.[d]??a),i=" ".repeat(n);return e.map(a=>(t+a.map((d,l)=>l===a.length-1?d:d.padEnd(o[l])).join(i)).trimEnd())};var Mv={draft:"@draft for your draft",head:"@head for your working branch without the draft",branch:"@main or @<branch> for a branch head",commit:"@<commit id> for a commit",release:"@<release> for a release"},Av={working:"your draft while it holds staged changes, else your working branch",head:"your working branch head",main:"main",draft:"your draft"},zu=e=>{if(e.kinds.length===0)return"It takes no @ref: this command reads main.";let t=e.kinds.map(r=>Mv[r]).join(", "),n="required"in e?"The ref is required.":`Without a ref: ${Av[e.default]}.`;return`Optionally at a ref: ${t}. ${n}`},Tv=e=>e.kinds.includes("release")?e.kinds.map(t=>t==="branch"?"main":t).join("|"):e.kinds.length===1?e.kinds[0]:"ref",Sd=e=>{if(e.kinds.length===0)return"";let t=Tv(e);return"required"in e?`@${t}`:`[@${t}]`},_=e=>({name:"model",type:{address:"model",slot:e},required:!0,description:`The model's id, from model list. ${zu(e)}`}),Ju=e=>({name:"resource",type:{address:"resource",slot:e},required:!0,description:`The model's id, from model list, or dataset/<id>. ${zu(e)}`}),Le=e=>({name:e,type:{address:"element"},required:!0,description:"The element's id, or its label path from the model root (SHACL/NodeShape/severity; write a '/' inside "+String.raw`a label as '\/').`});var Jn={json:{type:"boolean",description:"Print one JSON document on stdout instead of text."},"no-json":{type:"boolean",description:"Print text even where an agent host makes JSON the default."},host:{type:"string",placeholder:"host",description:"The ModelDesk instance to target (default: modeldesk.io, or MODELDESK_HOST or the repo config)."},"dry-run":{type:"boolean",description:"Report what would change and write nothing (commands that write)."},yes:{type:"boolean",description:"Answer yes to confirmations; required to confirm when not interactive."},help:{type:"boolean",short:"h",description:"Show help."},version:{type:"boolean",short:"v",description:"Show the CLI version."}},Xu=new Set(["json","no-json","host","dry-run","yes","help"]),vd=50,Xr={limit:{type:"number",placeholder:"n",default:vd,description:"Return at most this many rows."},cursor:{type:"string",placeholder:"cursor",description:"Continue a truncated listing from the nextCursor it returned."},all:{type:"boolean",description:"Return every row; with --json, one JSON object per line (NDJSON)."}},Qu=e=>e.defaultLimit===void 0?Xr:{...Xr,limit:{...Xr.limit,default:e.defaultLimit}};import{parseArgs as jv}from"node:util";var Ov=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,V=e=>Ov.test(e);var Nv={noun:"A model",listing:"modeldesk model list"},Ao="dataset/",Lv={draft:"@draft (your draft)",head:"@head (your working branch without the draft)",branch:"@main or @<branch>",commit:"@<commit id>",release:"@<release>"},Pv=(e,t)=>e==="branch"&&t.kinds.includes("release")?"@main":Lv[e],Zu=e=>{let t=e.kinds.map(n=>Pv(n,e));return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} or ${t.at(-1)}`},Id=e=>new p(e,{exitCode:b.Usage,type:"ref-unsupported"}),Dv=(e,t)=>e==="draft"||e==="head"?{kind:e}:V(e)?{kind:"commit",id:e}:e!=="main"&&t.kinds.includes("release")?{kind:"release",name:e}:{kind:"branch",name:e},_v=e=>{if(e.kind!=="working")return e.kind==="branch-id"?"branch":e.kind},ep=e=>e.slice(e.indexOf("@")),$d=(e,t)=>{let n=_v(e.ref);if(n===void 0){if("required"in t)throw Id(`'${e.text}' names no ref, and this argument needs one: ${Zu(t)}.`);return e}if(t.kinds.length===0)throw Id(`This command reads main only, so the model takes no ref; drop '${ep(e.text)}'.`);if(!t.kinds.includes(n))throw Id(`'${ep(e.text)}' is not accepted here; the ref can be ${Zu(t)}.`);return e},xd=(e,t)=>{if(e.startsWith(Ao)&&V(e.slice(Ao.length).split("@")[0]))throw new p(`'${e}' names a dataset, and this argument takes a model.`,{exitCode:b.Usage});let n=e.indexOf("@"),r=n===-1?e:e.slice(0,n),s=n===-1?void 0:e.slice(n+1);if(r==="")throw new p(`'${e}' names no model; write <model> or <model>@<ref>.`,{exitCode:b.Usage});if(s==="")throw new p(`'${e}' ends in '@' with no ref after it.`,{exitCode:b.Usage});if(!V(r)){let{noun:i,listing:a}=t.names??Nv;throw new p(`'${r}' is not an id. ${i} is addressed by its id: run '${a}' to find it.`,{exitCode:b.Usage,type:"id-required"})}let o=s===void 0?{kind:"working"}:Dv(s,t);return $d({model:r.toLowerCase(),ref:o,text:e},t)},Xn=e=>e.ref.kind==="release"?e.ref.name:void 0,tp=(e,t)=>{if(!e.startsWith(Ao))return{kind:"model",address:xd(e,t)};let n=e.slice(Ao.length);if(n.includes("@"))throw new p(`'${e}' names a ref on a dataset, which has drafts and no branches; drop the '@'.`,{exitCode:b.Usage});if(!V(n))throw new p(`'${e}' is not a dataset address; write dataset/<id>.`,{exitCode:b.Usage});return{kind:"dataset",id:n,text:e}};var Pe=e=>typeof e=="object"&&"list"in e,Oo=e=>typeof e=="object"&&"enum"in e,No=e=>typeof e=="object"&&"address"in e,Fv=(e,t,n)=>{try{switch(t.address){case"model":return xd(e,t.slot);case"resource":return tp(e,t.slot);case"element":return e}}catch(r){throw r instanceof p?new p(r.reason,{exitCode:b.Usage,type:r.type,hint:`Run '${n}'.`}):r}},yt=e=>({...e.flags,...e.listing?Qu(e.listing):{}}),sp=e=>({type:e.type==="boolean"?"boolean":"string",...Pe(e.type)?{multiple:!0}:{},...e.short?{short:e.short}:{}}),op=e=>Object.fromEntries(Object.entries(Jn).filter(([t])=>!(t in e)).map(([t,n])=>[t,sp(n)])),ip=(e,t,n)=>{try{return jv({args:e,options:t,allowPositionals:!0,strict:!0})}catch(r){throw $(r.message,n)}},ap=(e,t)=>({json:e.json===!0,noJson:e["no-json"]===!0,host:typeof e.host=="string"?e.host:void 0,dryRun:e["dry-run"]===!0,yes:e.yes===!0,help:e.help===!0,version:!("version"in t)&&e.version===!0}),Md=(e,t)=>{let{values:n,positionals:r}=ip(e,op({}),t);return{globals:ap(n,{}),positionals:r}},np=(e,t)=>Oo(t)?`${e} must be one of ${t.enum.join(", ")}`:`${e} expects a ${t==="number"?"number":"value"}`,To=(e,t,n,r)=>{let s=Pe(t)?t.list:t;if(No(s))return Fv(e,s,r);if(s==="number"){let o=Number(e);if(e.trim()===""||!Number.isFinite(o))throw $(`${np(n,s)}, got '${e}'.`,r);return o}if(s==="boolean"){if(e!=="true"&&e!=="false")throw $(`${n} expects true or false, got '${e}'.`,r);return e==="true"}if(Oo(s)&&!s.enum.includes(e))throw $(`${np(n,s)}, got '${e}'.`,r);return e},rp=(e,t,n)=>{let r=t.short?` (-${t.short})`:"",s=t.requiredReason?` ${t.requiredReason}`:"";return $(`Missing required flag --${e}${r}.${s}`,n)},qv=(e,t,n,r)=>{let s=`--${e}`;if(t.type==="boolean")return n===!0;if(Pe(t.type)){let o=n??[];if(o.length===0&&t.required)throw rp(e,t,r);return o.length===0&&t.default!==void 0?t.default:o.map(i=>To(i,t.type,s,r))}if(n===void 0){if(t.required)throw rp(e,t,r);return t.default}return To(n,t.type,s,r)},Bv=(e,t,n)=>{let r={};if(e.forEach((o,i)=>{let a=`<${o.name}>`;if(Pe(o.type)){let l=t.slice(i);if(l.length===0&&o.required)throw $(`Missing required argument ${a}.`,n);r[o.name]=l.map(c=>To(c,o.type,a,n));return}let d=t[i];if(d===void 0){if(o.required)throw $(`Missing required argument ${a}.`,n);r[o.name]=void 0;return}r[o.name]=To(d,o.type,a,n)}),!e.some(o=>Pe(o.type))&&t.length>e.length)throw $(`Unexpected argument '${t[e.length]}'.`,n);return r},dp=(e,t,n)=>{let r=yt(e),s={...op(r),...Object.fromEntries(Object.entries(r).map(([c,m])=>[c,sp(m)]))},{values:o,positionals:i}=ip(t,s,n),a=ap(o,r),d=Object.fromEntries(Object.entries(r).map(([c,m])=>[c,qv(c,m,o[c],n)]));if(e.listing){let c=d.limit;if(!Number.isInteger(c)||c<1)throw $(`--limit must be a positive whole number, got ${c}.`,n)}let l=Bv(e.positionals??[],i,n);return{flags:d,args:l,globals:a}};var lp=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/,Wv=new Set(Object.values(Jn).flatMap(e=>e.short?[e.short]:[])),Uv=(e,t)=>{for(let[n,r]of Object.entries(t.flags??{})){if(Xu.has(n))throw new Error(`'${e}' declares --${n}, which is a global flag every command already takes.`);if(t.listing&&n in Xr)throw new Error(`'${e}' declares --${n}, which its listing already provides.`);if(r.type==="boolean"&&r.default!==void 0)throw new Error(`'${e}' gives --${n} a default; a boolean flag is off unless passed.`)}},Hv=(e,t)=>{let n=Object.entries(t.flags??{}).flatMap(([r,s])=>s.short===void 0?[]:[[r,s.short]]);for(let[r,s]of n)if(!/^[a-z]$/.test(s)||Wv.has(s)||n.filter(([,o])=>o===s).length>1)throw new Error(`'${e}' gives --${r} the alias -${s}; an alias is one free lowercase letter.`)},Gv=(e,t)=>{let n=t.positionals??[];n.forEach((r,s)=>{let o=s===n.length-1;if(Pe(r.type)&&!o)throw new Error(`'${e}': only the last argument may take a list (<${r.name}>).`);let i=n[s-1];if(r.required&&i&&!i.required)throw new Error(`'${e}': required argument <${r.name}> follows an optional one.`)})},Vv=e=>{let t=e.path.join(" ");if(e.path.length===0||e.path.some(r=>!lp.test(r)))throw new Error(`Command path '${t}' must be one or more kebab-case words.`);Uv(t,e),Hv(t,e);let n=e.listing?.defaultLimit;if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`'${t}' gives its listing a default limit of ${n}; it must be a positive whole number.`);for(let r of Object.keys(yt(e)))if(!lp.test(r))throw new Error(`'${t}' declares --${r}; flag names are kebab-case.`);Gv(t,e)},Ad=e=>{let t={kind:"group",path:[],children:new Map};for(let n of e){Vv(n);let r=t;n.path.forEach((s,o)=>{let i=n.path.slice(0,o+1),a=r.children.get(s);if(o===n.path.length-1){if(a)throw new Error(`'${i.join(" ")}' is declared twice, or as both a command and a group.`);r.children.set(s,{kind:"command",path:i,spec:n});return}if(a?.kind==="command")throw new Error(`'${i.join(" ")}' is both a command and a group.`);let l=a??{kind:"group",path:i,children:new Map};r.children.set(s,l),r=l})}return t},Lo=e=>[...e.children.values()].flatMap(t=>t.kind==="group"?Lo(t):[t]);var Po="modeldesk",mp=[["0","success"],["1","failure (generic or server)"],["2","usage error"],["3","not found"],["4","validation or check failure (input refused, or an assertion the caller asked for failed)"],["5","conflict (stale base, lost compare-and-set)"],["6","needs a human (log in, confirm, commit in the app)"],["7","transient, safe to retry (network, 429, 5xx)"]],Kv=mp.map(([e,t])=>`${e} ${t.replace(/ \(.*\)$/,"")}`),Yv=`Exit codes: ${Kv.join(", ")}.`,zv=`With --json, a command's stdout is one JSON document led by schemaVersion (help and version stay text); on failure the last stderr line is {"error": {code, message, hint?, retryable, type?, requestId?, details}}.`,Jv=(e,t)=>{if(t)return`<${t}>`;let n=Pe(e)?e.list:e;return Oo(n)?`<${n.enum.join("|")}>`:No(n)?`<${n.address}${n.address==="element"?"":Sd(n.slot)}>`:n==="number"?"<n>":"<value>"},Od=(e,t)=>{let n=t.short?`, -${t.short}`:"";return t.type==="boolean"?`--${e}${n}`:`--${e}${n} ${Jv(t.type,t.placeholder)}`},Xv=e=>Array.isArray(e)?e.join(", "):String(e),cp=e=>{let t=[];return e.required&&t.push("required"),e.default!==void 0&&e.type!=="boolean"&&t.push(`default: ${Xv(e.default)}`),Pe(e.type)&&t.push("repeatable"),t.length>0?` (${t.join("; ")})`:""},Td=e=>{let t=Pe(e.type)?e.type.list:e.type,n=No(t)&&t.address!=="element"?Sd(t.slot):"";return`<${e.name}${n}>`},Qv=e=>{let t=Pe(e.type)?`${Td(e)}...`:Td(e);return e.required?t:`[${t}]`},fp=e=>{let t=yt(e),n=Object.entries(t).filter(([,s])=>s.required).map(([s,o])=>Od(s,o)),r=Object.values(t).some(s=>!s.required);return[Po,...e.path,...(e.positionals??[]).map(Qv),...n,...r?["[options]"]:["[global options]"]].join(" ")},wn=(e,t)=>t.length===0?[]:[`${e}:`,...j(t,{indent:" "}),""],up=e=>{let t=e?yt(e):{};return Object.entries(Jn).filter(([n])=>!(n in t)).filter(([n])=>n!=="dry-run"||e===void 0||e.dryRun===!0).map(([n,r])=>[Od(n,r),r.description])},Zv=e=>Lo(e).map(t=>[t.path.slice(e.path.length).join(" "),t.spec.summary]),pp=e=>["ModelDesk CLI","",`Usage: ${Po} <command> [options]`,"",...wn("Commands",Zv(e)),...wn("Global options",up()),...wn("Exit codes",mp),zv,`Run '${Po} <command> --help' for a command's arguments and flags.`,""].join(`
142
- `),hp=e=>{let t=[Po,...e.path].join(" "),n=Lo(e).flatMap(r=>[[r.path.slice(e.path.length).join(" "),r.spec.summary],["",fp(r.spec)]]);return[`Usage: ${t} <command> [options]`,"",...wn("Commands",n),`Run '${t} <command> --help' for a command's arguments and flags.`,""].join(`
143
- `)},gp=e=>{let t=(e.positionals??[]).map(s=>[Td(s),s.description+cp(s)]),n=Object.entries(yt(e)).map(([s,o])=>[Od(s,o),o.description+cp(o)]),r=(e.examples??[]).map(s=>` ${s}`);return[`Usage: ${fp(e)}`,"",e.summary,...e.description?["",e.description]:[],"",...wn("Arguments",t),...wn("Flags",n),...wn("Global options",up(e)),...r.length>0?["Examples:",...r,""]:[],Yv,...e.listing?[`Listings are truncated at --limit; ${eI(e)}`]:[],""].join(`
144
- `)},eI=e=>`a truncated one carries nextCursor and truncated: true.${e.listing?.narrowHint?` ${e.listing.narrowHint}`:""}`;var tI=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,ae=e=>e.replace(tI,""),w=e=>e.replace(/\s+/g," ").trim(),P=(e,t)=>`${e} ${t}${e===1?"":"s"}`;import{createHash as nI,randomUUID as rI}from"node:crypto";var Nd=200,sI=64,Ld=e=>e[B.agentSession]?.trim().replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,sI)||void 0,Qn=(e="cli",t=process.env)=>{let n=Ld(t);return[e,...n?[n]:[],rI()].join("-")},oI=e=>{let t=nI("sha256").update(e).digest("hex");return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-8${t.slice(17,20)}-${t.slice(20,32)}`},Do=(e,t,n)=>{let r=Ld(t);return[e,...r?[r]:[],oI(n)].join("-")},Qr=(e,t,n,r)=>r!==void 0&&r.total>1?Do(e,t,`${n}:${r.number}`):Dt(n)===e&&wp.test(n)&&Dd(n,t)?n:Do(e,t,n),iI=["web","cli","mcp"],Dt=e=>iI.find(t=>e?.startsWith(`${t}-`))??"api",yp=["cli","mcp"],aI=36,wp=/-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Pd=e=>{if(e===void 0||!wp.test(e))return;let t=e.slice(0,-aI-1),n=yp.find(r=>t.startsWith(`${r}-`));return n&&t.slice(n.length+1)||void 0},Dd=(e,t)=>{if(!yp.includes(Dt(e)))return!1;let n=Ld(t);return n===void 0||Pd(e)===n};var Zn={read:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},local:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},stage:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},create:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},unstage:{gate:"none",ownChangesOnly:!0,site:"dispatcher"},"land-draft":{gate:"allow-commit",ownChangesOnly:!0,site:"landing"},"land-direct":{gate:"allow-commit",ownChangesOnly:!1,site:"dispatcher"},destroy:{gate:"refuse",ownChangesOnly:!1,site:"dispatcher"}},bn="agent/",dI=e=>"name"in e&&e.name.toLowerCase().startsWith(bn),bp=(e,t,n,r)=>{if(r)return"read";if(t===void 0)return e;let s=n[t.flag];return s===!0||Array.isArray(s)&&s.length>0?t.to:e},lI={"land-direct":"changes committed state with no draft to review",destroy:"destroys content, other users' work included"},_d="agent-policy",kp=(e,t)=>{let{gate:n}=Zn[t];return e.agentHost===void 0||n==="none"||n==="allow-commit"&&e.env[B.allowCommit]==="1"},Ep="Ask them to run it from a plain shell, or to do it in the app.",jd=`${Ep} A person who trusts this agent to commit unattended sets ${B.allowCommit}=1.`,Fd=(e,t,n,r,s={})=>new p(`${n}, so it is left to a person while an agent (${e.agentHost}) runs the CLI; nothing was changed.`,{exitCode:b.NeedsHuman,type:_d,hint:r,details:{effect:t,gate:Zn[t].gate,...s}}),Cp=(e,t,n)=>{if(!(Zn[t].site==="landing"||kp(e,t)))throw Fd(e,t,`'${n}' ${lI[t]}`,Zn[t].gate==="allow-commit"?jd:Ep)},er=(e,t,n,r)=>{let{effect:s}=e;if(Zn[s].site!=="landing"||dI(r)||kp(e,s))return;let o=w(n.name);throw"name"in r?Fd(e,s,`'${t}' lands your draft of ${o} on ${w(r.name)}, which is not an agent's own branch (${bn}<topic>)`,`${jd} Or commit on a branch of your own: 'modeldesk branch create ${n.id} ${bn}<topic> --open', then stage and commit there; a person reviews and merges it in the app.`,{branch:{id:r.id,name:r.name}}):Fd(e,s,`'${t}' lands your draft of ${n.kind} ${o} on its one branch, which no agent owns`,jd,{branch:{id:r.id}})},cI=e=>({id:e.id,...e.requestId?{requestId:e.requestId}:{},surface:Dt(e.requestId),...e.message?{message:e.message}:{}}),De=async(e,t,n,r)=>{if(e.agentHost===void 0||!Zn[e.effect].ownChangesOnly||r.anySurface||n.changeCount===0)return;let o=`Ask the person you work for to review the draft ${t.url?`in the app at ${t.url}`:"in the app"}; ${r.override}`,i=t.url?{url:t.url}:{};if(t.changes===void 0)throw new p(`${r.action} is left to a person while an agent (${e.agentHost}) runs the CLI, since a dataset's staged changes cannot be listed to tell whose they are. Nothing was changed.`,{exitCode:b.NeedsHuman,type:_d,hint:o,details:i});let{scope:a}=r,d=await t.changes(n.id,a.kind==="last"?1:void 0),c=(a.kind==="ids"?d.filter(u=>a.ids.includes(u.id)):d).filter(u=>!Dd(u.requestId,e.env));if(c.length===0)return;let m="outside this agent session (in the app, by a script, or by another session)",f=c.length===1?"was":"were",g=a.kind==="last"?`the last staged change was made ${m}`:`${P(c.length,"staged change")} of the draft ${f} made ${m}`;throw new p(`${r.action} is left to a person while an agent (${e.agentHost}) runs the CLI: ${g}. Nothing was changed.`,{exitCode:b.NeedsHuman,type:_d,hint:o,details:{...i,changes:c.map(cI)}})},tr={"any-surface":{type:"boolean",description:"Under an agent host, also act on changes staged outside an agent session (in the app, or by a script), which the CLI otherwise leaves to a person."}};import{randomBytes as qd,randomInt as mI}from"node:crypto";import{chmodSync as Bd,closeSync as Hd,fsyncSync as Mp,linkSync as fI,mkdirSync as uI,openSync as Gd,readFileSync as _o,renameSync as Rp,rmSync as jo,statSync as Sp,utimesSync as pI,writeSync as vp}from"node:fs";import{homedir as hI,hostname as Ip}from"node:os";import{join as $p}from"node:path";var Wd=448,Ud=384,gI=5e3,yI=3e4,wI=9e4,xp=50,bI=e=>new Promise(t=>setTimeout(t,e)),nr=(e,t)=>e instanceof Error&&e.code===t,tt=class{dir;file;lockFile;lockTimeoutMs;staleLockMs;now;sleep;queue=Promise.resolve();constructor(t=$p(hI(),".modeldesk"),n={}){this.dir=t,this.file=$p(t,"credentials.json"),this.lockFile=`${this.file}.lock`,this.lockTimeoutMs=n.lockTimeoutMs??wI,this.staleLockMs=n.staleLockMs??yI,this.now=n.now??Date.now,this.sleep=n.sleep??bI}read(t){let n=this.readFile().hosts[t];return n&&typeof n.refreshToken=="string"?n:void 0}async save(t,n){await this.transact(async r=>r.write(t,n))}async clearHost(t){return this.transact(async n=>{let r=n.read(t)!==void 0;return r&&n.write(t,void 0),r})}async transact(t){let n=this.queue.then(async()=>{let r=await this.acquireLock(),s=setInterval(()=>this.touchLock(r),gI);s.unref();try{return await t({read:o=>this.read(o),write:(o,i)=>this.writeHost(o,i)})}finally{clearInterval(s),this.releaseLock(r)}});return this.queue=n.catch(()=>{}),n}readFile(){let t;try{t=_o(this.file,"utf8")}catch(n){if(nr(n,"ENOENT"))return{hosts:{}};throw new p(`Could not read ${this.file}: ${n.message}`)}try{let n=JSON.parse(t);if(n&&typeof n=="object"&&n.hosts&&typeof n.hosts=="object")return n}catch(n){if(!(n instanceof SyntaxError))throw n}return{hosts:{}}}writeHost(t,n){let r=this.readFile();n?r.hosts[t]=n:delete r.hosts[t],this.writeAtomically(`${JSON.stringify(r,null,2)}
145
- `)}writeAtomically(t){this.ensureDir();let n=`${this.file}.${process.pid}.${qd(6).toString("hex")}.tmp`;try{let r=Gd(n,"wx",Ud);try{vp(r,t),Mp(r)}finally{Hd(r)}Rp(n,this.file)}catch(r){throw jo(n,{force:!0}),r}EI(this.dir),Bd(this.dir,Wd),Bd(this.file,Ud)}ensureDir(){uI(this.dir,{recursive:!0,mode:Wd})!==void 0&&Bd(this.dir,Wd)}async acquireLock(){this.ensureDir();let t=`${Ip()} ${process.pid} ${qd(8).toString("hex")} ${new Date(this.now()).toISOString()}
146
- `,n=this.now()+this.lockTimeoutMs;for(;;){if(this.tryCreateLock(t))return t;if(!this.takeOverAbandonedLock()){if(this.now()>=n)throw new p(`Timed out waiting for another modeldesk process to release ${this.lockFile}.`,{exitCode:b.Transient,hint:"Retry; if no other modeldesk process is running, delete the lock file."});await this.sleep(xp+mI(xp))}}}tryCreateLock(t){let n;try{n=Gd(this.lockFile,"wx",Ud)}catch(r){if(nr(r,"EEXIST"))return!1;throw r}try{return vp(n,t),!0}catch(r){throw jo(this.lockFile,{force:!0}),r}finally{Hd(n)}}isAbandoned(t,n){if(this.now()-t>=this.staleLockMs)return!0;let[r,s]=n.split(" "),o=Number.parseInt(s??"",10);return r===Ip()&&Number.isInteger(o)&&o>0&&!kI(o)}takeOverAbandonedLock(){let t,n;try{t=Sp(this.lockFile),n=_o(this.lockFile,"utf8")}catch(o){if(nr(o,"ENOENT"))return!0;throw o}if(!this.isAbandoned(t.mtimeMs,n))return!1;let r=`${this.lockFile}.${process.pid}.${qd(6).toString("hex")}.stale`;try{Rp(this.lockFile,r)}catch(o){if(nr(o,"ENOENT"))return!0;throw o}let s=Sp(r);if(s.ino!==t.ino||s.mtimeMs!==t.mtimeMs)try{fI(r,this.lockFile)}catch{}return jo(r,{force:!0}),!0}touchLock(t){try{if(_o(this.lockFile,"utf8")===t){let n=new Date(this.now());pI(this.lockFile,n,n)}}catch{}}releaseLock(t){try{_o(this.lockFile,"utf8")===t&&jo(this.lockFile,{force:!0})}catch(n){if(!nr(n,"ENOENT"))throw n}}},kI=e=>{try{return process.kill(e,0),!0}catch(t){return!nr(t,"ESRCH")}},EI=e=>{let t;try{t=Gd(e,"r"),Mp(t)}catch{}finally{t!==void 0&&Hd(t)}},Vd=(e,t,n)=>e?.accessToken&&e.accessTokenExpiresAt!==void 0&&e.accessTokenExpiresAt-t>n?e.accessToken:void 0;var _t="modeldesk-cli",Ap="modeldesk-federation",Tp="openid",Kd="/callback";var jt=async e=>{let t=`${e.replace(/\/+$/,"")}/.well-known/openid-configuration`,n;try{n=await fetch(t,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(3e4)})}catch(s){throw new p(`Could not reach the auth server at ${e} (${s.message}).`,b.Transient)}if(!n.ok)throw new p(`OpenID discovery failed at ${t}: ${n.status} ${n.statusText}`,n.status===429||n.status>=500?b.Transient:b.Failure);let r=await n.json();if(!r.authorization_endpoint||!r.token_endpoint)throw new p(`OpenID discovery at ${t} did not return the authorization and token endpoints.`);for(let s of[r.authorization_endpoint,r.token_endpoint,r.device_authorization_endpoint])if(s!==void 0&&!CI(s,e))throw new p(`OpenID discovery at ${t} names an endpoint outside the issuer's origin: ${s}.`);return{authorizationEndpoint:r.authorization_endpoint,tokenEndpoint:r.token_endpoint,...r.device_authorization_endpoint?{deviceAuthorizationEndpoint:r.device_authorization_endpoint}:{}}},CI=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}};var Ft=class extends p{oauthError;errorDescription;constructor(t,n,r,s=b.Failure){super(t,s),this.name="TokenEndpointError",this.oauthError=n,this.errorDescription=r}},Op=e=>e instanceof Ft&&e.oauthError==="invalid_grant",Np=(e,t)=>Zr(e,new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:t.redirectUri,client_id:_t,code_verifier:t.codeVerifier})),RI="urn:ietf:params:oauth:grant-type:device_code",Lp=(e,t)=>Zr(e,new URLSearchParams({grant_type:RI,device_code:t,client_id:_t})),Pp=(e,t)=>Zr(e,new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:_t})),Dp=(e,t)=>Zr(e,new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_secret:t.clientSecret})),_p=(e,t)=>Zr(e,new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:t,subject_token_type:"urn:ietf:params:oauth:token-type:jwt",client_id:Ap})),SI=new Set(["server_error","temporarily_unavailable"]),Zr=async(e,t)=>{let n;try{n=await fetch(e,{method:"POST",redirect:"error",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString(),signal:AbortSignal.timeout(3e4)})}catch(s){throw new p(`Could not reach the token endpoint (${s.message}).`,b.Transient)}if(!n.ok){let{message:s,code:o,description:i}=await vI(n),a=SI.has(o??"")||n.status===429||n.status>=500;throw new Ft(`Token request failed: ${s}`,o,i,a?b.Transient:b.Failure)}let r=await n.json();if(!r.access_token)throw new p("The token response did not include an access token.");return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresInSeconds:r.expires_in??0}},vI=async e=>{try{if((e.headers.get("content-type")??"").includes("json")){let n=await e.json();if(n.error)return{message:n.error_description?`${n.error} (${n.error_description})`:n.error,code:n.error,description:n.error_description}}}catch{}return{message:`${e.status} ${e.statusText}`.trim()}};var II=5,$I=5,xI=1,MI=60,AI=600,TI=1800,qp=e=>Math.min(MI,Math.max(xI,e)),jp=(e,t)=>{let n;try{n=new URL(e)}catch{throw new p("The device authorization response carries an invalid verification URL.")}let r=new URL(t.issuer);if(!(n.protocol==="https:"||n.protocol==="http:"&&r.protocol==="http:")||n.hostname!==r.hostname)throw new p(`The device authorization response points to ${n.origin}, not to the auth server ${r.origin}; refusing to show its code.`);return n.toString()},Fp=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:t,Bp=new Set(["unauthorized_client","unsupported_grant_type","invalid_client"]),OI=e=>new Promise(t=>setTimeout(t,e)),Yd=e=>new p(`Device login is not enabled on ${e.host}.`,{hint:"Run 'modeldesk auth login' where a browser can reach this machine."}),NI=async(e,t)=>{let n;try{n=await fetch(e,{method:"POST",redirect:"error",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:_t}).toString(),signal:AbortSignal.timeout(3e4)})}catch(s){throw new p(`Could not reach the device authorization endpoint (${s.message}).`,{exitCode:b.Transient})}let r=await n.json().catch(()=>({}));if(!n.ok){if(r.error&&Bp.has(r.error))throw Yd(t);let s=r.error??`${n.status} ${n.statusText}`;throw new p(`Device authorization failed: ${s}`,{exitCode:n.status===429||n.status>=500?b.Transient:b.Failure})}return r},Wp=()=>new p("The code expired before it was approved.",{hint:"Run 'modeldesk auth login --device' again."}),LI=(e,t,n)=>{if(!(e instanceof Ft))throw e;switch(e.oauthError){case"authorization_pending":return t;case"slow_down":return qp(t+$I);case"access_denied":throw new p("The sign-in was declined, so nothing was stored.");case"expired_token":throw Wp();default:throw e.oauthError&&Bp.has(e.oauthError)?Yd(n):e}},PI=(e,t,n)=>{let{device_code:r,user_code:s,verification_uri:o}=e;if(!r||!s||!o)throw new p("The device authorization response is missing its code or verification URL.");let i=jp(o,t),a=e.verification_uri_complete?jp(e.verification_uri_complete,t):void 0;return n.info(`To sign in to ${t.host}, open ${i} and enter the code ${s}.`),a&&n.info(`Or open this link, which carries the code:
147
- ${a}`),r},Up=async(e,t,n={})=>{let r=n.sleep??OI,s=n.now??Date.now,{deviceAuthorizationEndpoint:o,tokenEndpoint:i}=await jt(e.issuer);if(!o)throw Yd(e);let a=await NI(o,e),d=PI(a,e,t),l=Math.min(TI,Fp(a.expires_in,AI)),c=s()+l*1e3,m=qp(Fp(a.interval,II));for(;;){await r(m*1e3);try{return await Lp(i,d)}catch(f){if(f instanceof p&&f.exitCode===b.Transient){if(s()>=c)throw f;continue}m=LI(f,m,e)}if(s()>=c)throw Wp()}};import{spawn as DI}from"node:child_process";import{platform as _I}from"node:process";var Hp=e=>{if(!jI(e))return;let{command:t,args:n,verbatim:r}=FI(e);try{let s=DI(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});s.on("error",()=>{}),s.unref()}catch{}},jI=e=>{try{let{protocol:t}=new URL(e);return t==="http:"||t==="https:"}catch{return!1}},FI=(e,t=_I)=>{switch(t){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start",'""',qI(e)],verbatim:!0};default:return{command:"xdg-open",args:[e]}}},qI=e=>e.replace(/[&|<>^()%"]/g,t=>`^${t}`);import{createServer as BI}from"node:http";var WI=3e5,Gp=(e,t=WI)=>new Promise((n,r)=>{let s,o=new Promise((c,m)=>{s={resolve:c,reject:m}}),i=BI((c,m)=>{let f=new URL(c.url??"/","http://127.0.0.1");if(f.pathname!==Kd){m.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}UI(f,m,e,s)}),a=setTimeout(()=>s.reject(new p("Timed out waiting for the browser login to complete.")),t);a.unref();let d=!1,l=()=>{d||(d=!0,clearTimeout(a),i.close())};o.then(l,l),i.once("error",c=>r(new p(`Could not start the loopback listener: ${c.message}`))),i.listen(0,"127.0.0.1",()=>{let{port:c}=i.address();n({redirectUri:`http://127.0.0.1:${c}${Kd}`,waitForCode:()=>o,close:l})})}),UI=(e,t,n,r)=>{if(e.searchParams.get("state")!==n){t.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Unexpected request");return}let s=e.searchParams.get("error");if(s){let i=e.searchParams.get("error_description");zd(t,"Sign-in failed","Sign-in failed. You can close this window and return to the terminal."),r.reject(new p(`Authorization failed: ${i?`${s} (${i})`:s}`));return}let o=e.searchParams.get("code");if(!o){zd(t,"Sign-in failed","No authorization code was returned. You can close this window."),r.reject(new p("Login failed: no authorization code was returned."));return}zd(t,"Signed in","You are signed in to the ModelDesk CLI. You can close this window and return to the terminal."),r.resolve(o)},zd=(e,t,n)=>{let r=`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${t}</title></head><body style="font-family: system-ui, sans-serif; text-align: center; padding: 3rem;"><h1>${t}</h1><p>${n}</p></body></html>`;e.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}).end(r)};import{createHash as HI,randomBytes as Vp}from"node:crypto";var Jd=e=>e.toString("base64url"),Kp=()=>{let e=Jd(Vp(32)),t=Jd(HI("sha256").update(e).digest());return{verifier:e,challenge:t,method:"S256"}},Yp=()=>Jd(Vp(16));var zp={info:e=>process.stderr.write(`${e}
148
- `)},Fo=async(e,t)=>{let{authorizationEndpoint:n,tokenEndpoint:r}=await jt(e.issuer),s=Kp(),o=Yp(),i=await Gp(o);try{let a=GI(n,i.redirectUri,s.challenge,o);t.info(`Opening your browser to sign in to ${e.host}...`),t.info(`If it does not open automatically, visit:
149
- ${a}`),Hp(a);let d=await i.waitForCode();return await Np(r,{code:d,redirectUri:i.redirectUri,codeVerifier:s.verifier})}finally{i.close()}},GI=(e,t,n,r)=>{let s=new URL(e);return s.searchParams.set("response_type","code"),s.searchParams.set("client_id",_t),s.searchParams.set("redirect_uri",t),s.searchParams.set("scope",Tp),s.searchParams.set("state",r),s.searchParams.set("code_challenge",n),s.searchParams.set("code_challenge_method","S256"),s.toString()};var es=6e4,qo=(e,t,n)=>{let r=e.refreshToken??t;if(r)return e.expiresInSeconds>0?{refreshToken:r,accessToken:e.accessToken,accessTokenExpiresAt:n+e.expiresInSeconds*1e3}:{refreshToken:r}},rr=class{constructor(t,n={}){this.instance=t;this.store=n.store??new tt,this.io=n.io??zp,this.now=n.now??Date.now,this.allowBrowserLogin=n.allowBrowserLogin??!0}instance;store;io;now;allowBrowserLogin;accessToken;accessTokenExpiresAt=0;endpoints;pendingLogin;async getAccessToken(){if(this.accessToken&&this.now()<this.accessTokenExpiresAt-es)return this.accessToken;let t=this.store.read(this.instance.host),n=Vd(t,this.now(),es);if(n)return this.remember({accessToken:n,expiresAt:t?.accessTokenExpiresAt??0});if(t){let r=await this.refresh({force:!1});if(r)return r}return this.login()}async refreshNow(){return this.refresh({force:!0})}async refresh({force:t}){let{tokenEndpoint:n}=await this.getEndpoints(),r=await this.store.transact(async s=>{let o=s.read(this.instance.host),i=t?void 0:Vd(o,this.now(),es);if(i)return{accessToken:i,expiresAt:o?.accessTokenExpiresAt??0};if(o)try{let a=await Pp(n,o.refreshToken);return s.write(this.instance.host,qo(a,o.refreshToken,this.now())),{accessToken:a.accessToken,expiresAt:this.now()+a.expiresInSeconds*1e3}}catch(a){if(Op(a)){s.write(this.instance.host,void 0);return}throw a}});return r?this.remember(r):void 0}login(){return this.pendingLogin??=this.browserLogin().finally(()=>{this.pendingLogin=void 0}),this.pendingLogin}async browserLogin(){if(!this.allowBrowserLogin)throw new p(`Not logged in to ${this.instance.host}, and this run cannot open a browser to log in.`,{exitCode:b.NeedsHuman,hint:"Run 'modeldesk auth login' in a terminal, or 'modeldesk auth login --device' where no browser can reach this machine, then retry."});let t=await Fo(this.instance,this.io),n=qo(t,void 0,this.now());return n&&await this.store.save(this.instance.host,n),this.remember({accessToken:t.accessToken,expiresAt:this.now()+t.expiresInSeconds*1e3})}remember({accessToken:t,expiresAt:n}){return this.accessToken=t,this.accessTokenExpiresAt=n,t}async getEndpoints(){return this.endpoints||(this.endpoints=await jt(this.instance.issuer)),this.endpoints}};var ts=e=>{let t=e.split(".");if(t.length===3)try{let n=Buffer.from(t[1],"base64url").toString("utf8"),r=JSON.parse(n);return r&&typeof r=="object"&&!Array.isArray(r)?r:void 0}catch{return}},Bo=e=>{let t=ts(e);if(t)return t.name&&t.email?`${t.name} <${t.email}>`:t.email??t.name??t.sub};import{createInterface as KI}from"node:readline";var Jp={name:"@modeldesk/cli",version:"0.7.0",description:"Command-line interface (CLI) for the ModelDesk platform",keywords:["modeldesk","cli","documentation","content-bundle","respec","mim","information-model"],homepage:"https://modeldesk.io",repository:{type:"git",url:"git+https://github.com/model-desk/modeldesk.git",directory:"packages/cli"},license:"MIT",type:"module",bin:{modeldesk:"dist/modeldesk.js"},files:["dist","THIRD-PARTY-NOTICES.txt"],publishConfig:{access:"public"},engines:{node:">=22"},scripts:{build:"node esbuild.config.mjs",prepublishOnly:"npm run build",typecheck:"node scripts/api-types.mjs --check && tsc --noEmit","generate:api":"node scripts/api-types.mjs",lint:"eslint","lint:fix":"eslint --fix",test:"vitest run","test:watch":"vitest"},devDependencies:{"@eslint/js":"^10.0.1","@modeldesk/content-bundle":"*","@types/node":"^24.19.2",esbuild:"^0.28.2",eslint:"^10.14.0","eslint-config-prettier":"^10.1.5","eslint-plugin-prettier":"^5.5.7",globals:"^17.14.0","openapi-typescript":"^6.7.6",prettier:"^3.9.10",typescript:"^6.0.3","typescript-eslint":"^8.72.1",vitest:"^5.1.0",yaml:"^2.9.1"}};var sr=Jp.version;var Xp={out:e=>{process.stdout.write(e)},err:e=>{process.stderr.write(e)}},YI=async e=>{let t=KI({input:process.stdin,output:process.stderr});try{return await new Promise(n=>{t.once("close",()=>n(void 0)),t.question(e,n)})}finally{t.close()}},zI=async()=>{process.stdin.setEncoding("utf8");let e="";for await(let t of process.stdin)e+=t;return e},Qp=()=>({env:process.env,cwd:process.cwd(),stdinIsTTY:!!process.stdin.isTTY,stdoutIsTTY:!!process.stdout.isTTY,ask:YI,readStdin:zI}),JI=[{variable:"CLAUDECODE",host:()=>"claude-code"},{variable:"CLAUDE_CODE_CHILD_SESSION",host:()=>"claude-code"},{variable:"CURSOR_AGENT",host:()=>"cursor"},{variable:"AI_AGENT",host:e=>XI(e)}],Xd=e=>e!==void 0&&e!==""&&e!=="0",XI=e=>{let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").slice(0,40);return t===""||t==="1"||t==="true"?"agent":t},Qd=e=>{let t=JI.find(({variable:n})=>Xd(e[n]));return t?t.host(e[t.variable]):void 0},Zd=e=>Xd(e.CI)&&e.CI?.toLowerCase()!=="false",Zp=e=>e.stdinIsTTY&&e.stdoutIsTTY&&!Zd(e.env)&&Qd(e.env)===void 0,eh=e=>e.stdoutIsTTY&&!Xd(e.env.NO_COLOR)&&e.env.TERM!=="dumb",th=e=>e?`modeldesk-cli/${sr} (${e})`:`modeldesk-cli/${sr}`;var O=e=>e;var nh=O({path:["auth","login"],effect:"local",summary:"Log in through the browser (OAuth authorization code + PKCE)",description:"Opens the browser to sign in to the host and stores the credential in ~/.modeldesk/credentials.json (mode 0600), so later commands run unattended. With --device, prints a code to approve in a browser on any device instead, for SSH sessions, containers and remote agents that cannot receive the browser redirect. Machine credentials in the environment take precedence for API commands; this login only affects interactive use.",flags:{device:{type:"boolean",description:"Log in by approving a code in a browser on another device (OAuth device authorization)."}},examples:["modeldesk auth login","modeldesk auth login --device --host modeldesk.io"],run:async e=>{let t=Ie(e.env);if(t&&e.warn(`machine auth (${t} mode) is active in this environment and takes precedence for API commands; this login only affects interactive use.`),Yu(e),!e.flags.device&&Zd(e.env))throw new p("A browser login cannot complete in CI.",{exitCode:b.NeedsHuman,hint:"Use a service account (MODELDESK_CLIENT_ID and MODELDESK_CLIENT_SECRET), or auth login --device."});let n=zn(e),r={info:a=>e.io.err(ae(`${a}
150
- `))},s=e.flags.device?await Up(n,r):await Fo(n,r),o=new tt,i=qo(s,void 0,Date.now());return i?await o.save(n.host,i):(await o.clearHost(n.host),e.warn("the server returned no refresh token, so later commands will re-open the browser each time instead of running unattended.")),{result:{host:n.host,identity:Bo(s.accessToken),refreshTokenStored:!!s.refreshToken}}},render:({host:e,identity:t})=>{let n=t?` as ${t}`:"";return`Logged in to ${e}${n}.`}});var rh=O({path:["auth","logout"],effect:"local",summary:"Remove the stored credential for the active host",examples:["modeldesk auth logout","modeldesk auth logout --host modeldesk.io"],description:"Removes the refresh token stored for the host. Machine credentials in the environment are untouched.",run:async e=>{let t=Ie(e.env);t&&e.warn(`machine auth (${t} mode) is active in this environment and takes precedence for API commands; this logout does not remove machine credentials.`);let n=zn(e);return{result:{host:n.host,removed:await new tt().clearHost(n.host)}}},render:({host:e,removed:t})=>t?`Logged out of ${e}.`:`No stored credential for ${e}.`});var el=class{constructor(t,n,r,s={}){this.instance=t;this.mode=n;this.mint=r;this.now=s.now??Date.now,this.discover=s.discover??jt}instance;mode;mint;now;discover;accessToken;accessTokenExpiresAt=0;endpoints;inflight;async getAccessToken(){return this.accessToken&&this.now()<this.accessTokenExpiresAt-es?this.accessToken:(this.inflight||(this.inflight=this.mintFresh().finally(()=>{this.inflight=void 0})),this.inflight)}async mintFresh(){let{tokenEndpoint:t}=await this.getEndpoints(),n;try{n=await this.mint(t)}catch(r){throw ZI(r,this.mode)}if(n.expiresInSeconds<=0)throw new p("The token response did not include a token lifetime (expires_in), so the machine token cannot be cached. This indicates a server problem.");return this.accessToken=n.accessToken,this.accessTokenExpiresAt=this.now()+n.expiresInSeconds*1e3,n.accessToken}async getEndpoints(){return this.endpoints||(this.endpoints=await this.discover(this.instance.issuer)),this.endpoints}},QI=async(e,t,n)=>{let r;try{r=await fetch(`${e}&audience=${encodeURIComponent(n)}`,{headers:{Authorization:`bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(3e4)})}catch(o){throw new p(`Could not reach the GitHub OIDC token endpoint (${o.message}).`,b.Transient)}if(!r.ok)throw new p(`The GitHub OIDC token request failed (${r.status} ${r.statusText}). Check that the workflow grants 'permissions: id-token: write'.`);let s=await r.json().catch(()=>{});if(!s?.value)throw new p("The GitHub OIDC token response did not include a token value. Check that the workflow grants 'permissions: id-token: write'.");return s.value},Wo=(e,t,n={})=>{let r=t.mode==="secret"?s=>Dp(s,{clientId:t.clientId,clientSecret:t.clientSecret}):async s=>_p(s,await QI(t.oidcRequestUrl,t.oidcRequestToken,e.issuer));return new el(e,t.mode,r,n)},ZI=(e,t)=>{if(!(e instanceof Ft)||!e.oauthError)return e;if(t==="secret")return e.oauthError==="invalid_client"?new p(`${e.message} ${Uu}`):e;if(e.errorDescription===void 0)return e.oauthError==="invalid_grant"?new p(`${e.message} ${Hu}`):e;let n=Gu[e.errorDescription];return n?new p(`${e.message} \u2014 ${n}`):e};var sh="Run 'modeldesk auth login'.",oh=O({path:["auth","status"],effect:"read",summary:"Show the active host, logged-in identity, and token validity",examples:["modeldesk auth status","modeldesk auth status --host modeldesk.io --json"],description:"Proves the credential the CLI would use: a machine mode (service-account secret or GitHub federation) mints a token, interactive mode silently refreshes the stored login. Exits 6 when not logged in or the stored login was rejected, and 7 when the auth server could not be reached.",run:async e=>{let t=Yr(e.env);if(t.mode==="error")throw new p(t.message);let n=e.instance();return e.print(`Host: ${n.host}
139
+ `,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Id(t),r=go(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Id(t),r=go(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};LI.Parser=bf});var WI=D(Ws=>{"use strict";var _I=sf(),HW=Ms(),qs=Ds(),BW=rp(),UW=ee(),GW=wf(),jI=Ef();function FI(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new GW.LineCounter||null,prettyErrors:t}}function VW(e,t={}){let{lineCounter:n,prettyErrors:r}=FI(t),o=new jI.Parser(n?.addNewLine),s=new _I.Composer(t),i=Array.from(s.compose(o.parse(e)));if(r&&n)for(let a of i)a.errors.forEach(qs.prettifyError(e,n)),a.warnings.forEach(qs.prettifyError(e,n));return i.length>0?i:Object.assign([],{empty:!0},s.streamInfo())}function qI(e,t={}){let{lineCounter:n,prettyErrors:r}=FI(t),o=new jI.Parser(n?.addNewLine),s=new _I.Composer(t),i=null;for(let a of s.compose(o.parse(e),!0,e.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new qs.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(qs.prettifyError(e,n)),i.warnings.forEach(qs.prettifyError(e,n))),i}function YW(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let o=qI(e,n);if(!o)return null;if(o.warnings.forEach(s=>BW.warn(o.options.logLevel,s)),o.errors.length>0){if(o.options.logLevel!=="silent")throw o.errors[0];o.errors=[]}return o.toJS(Object.assign({reviver:r},n))}function KW(e,t,n){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let o=Math.round(n);n=o<1?void 0:o>8?{indent:8}:{indent:o}}if(e===void 0){let{keepUndefined:o}=n??t??{};if(!o)return}return UW.isDocument(e)&&!r?e.toString(n):new HW.Document(e,r,n).toString(n)}Ws.parse=YW;Ws.parseAllDocuments=VW;Ws.parseDocument=qI;Ws.stringify=KW});var Td=D(se=>{"use strict";var zW=sf(),JW=Ms(),XW=Fp(),Cf=Ds(),QW=gs(),Tn=ee(),ZW=kn(),eH=Ce(),tH=In(),nH=Sn(),rH=kd(),oH=gf(),sH=wf(),iH=Ef(),$d=WI(),HI=ps();se.Composer=zW.Composer;se.Document=JW.Document;se.Schema=XW.Schema;se.YAMLError=Cf.YAMLError;se.YAMLParseError=Cf.YAMLParseError;se.YAMLWarning=Cf.YAMLWarning;se.Alias=QW.Alias;se.isAlias=Tn.isAlias;se.isCollection=Tn.isCollection;se.isDocument=Tn.isDocument;se.isMap=Tn.isMap;se.isNode=Tn.isNode;se.isPair=Tn.isPair;se.isScalar=Tn.isScalar;se.isSeq=Tn.isSeq;se.Pair=ZW.Pair;se.Scalar=eH.Scalar;se.YAMLMap=tH.YAMLMap;se.YAMLSeq=nH.YAMLSeq;se.CST=rH;se.Lexer=oH.Lexer;se.LineCounter=sH.LineCounter;se.Parser=iH.Parser;se.parse=$d.parse;se.parseAllDocuments=$d.parseAllDocuments;se.parseDocument=$d.parseDocument;se.stringify=$d.stringify;se.visit=HI.visit;se.visitAsync=HI.visitAsync});var b={Success:0,Failure:1,Usage:2,NotFound:3,Validation:4,Conflict:5,NeedsHuman:6,Transient:7},Fu="timed-out",Ge=e=>e instanceof Error?e.message:String(e),f=class extends Error{exitCode;reason;hint;type;requestId;details;hosted;report;constructor(t,n={}){let r=typeof n=="number"?{exitCode:n}:n;super(r.hint?`${t} ${r.hint}`:t),this.name="CliError",this.exitCode=r.exitCode??b.Failure,this.reason=t,this.hint=r.hint,this.type=r.type,this.requestId=r.requestId,this.details=r.details??{},this.hosted=r.hosted,this.report=r.report}},k=(e,t="modeldesk --help",n)=>new f(e,{exitCode:b.Usage,hint:`Run '${t}'.`,hosted:n});var Rx=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,ye=e=>e.replace(Rx,""),g=e=>e.replace(/\s+/g," ").trim(),P=(e,t)=>`${e} ${t}${e===1?"":"s"}`;import{createHash as kx,randomUUID as vx}from"node:crypto";var El=200,Ix=64,Ro=e=>e.session?.trim().replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,Ix)||void 0,Er=e=>{let t=Ro(e);return[e.surface,...t?[t]:[],vx()].join("-")},Sx=e=>{let t=kx("sha256").update(e).digest("hex");return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-8${t.slice(17,20)}-${t.slice(20,32)}`},ci=(e,t)=>{let n=Ro(e);return[e.surface,...n?[n]:[],Sx(t)].join("-")},_n=(e,t,n)=>n!==void 0&&n.total>1?ci(e,`${t}:${n.number}`):Xt(t)===e.surface&&Wu.test(t)&&ko(t,e)?t:ci(e,t),$x=["web","cli","mcp"],Xt=e=>$x.find(t=>e?.startsWith(`${t}-`))??"api",qu=["cli","mcp"],Tx=36,Wu=/-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Cl=e=>{if(e===void 0||!Wu.test(e))return;let t=e.slice(0,-Tx-1),n=qu.find(r=>t.startsWith(`${r}-`));return n&&t.slice(n.length+1)||void 0},ko=(e,t)=>{if(!qu.includes(Xt(e)))return!1;let n=Ro(t);return n===void 0||Cl(e)===n};var Cr={read:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},local:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},stage:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},create:{gate:"none",ownChangesOnly:!1,site:"dispatcher"},unstage:{gate:"none",ownChangesOnly:!0,site:"dispatcher"},"land-draft":{gate:"allow-commit",ownChangesOnly:!0,site:"landing"},"land-direct":{gate:"allow-commit",ownChangesOnly:!1,site:"dispatcher"},destroy:{gate:"refuse",ownChangesOnly:!1,site:"dispatcher"},publish:{gate:"allow-commit",ownChangesOnly:!1,site:"dispatcher"}},Qt="agent/",xx=e=>"name"in e&&e.name.toLowerCase().startsWith(Qt),Hu=(e,t,n,r)=>{if(r)return"read";if(t===void 0)return e;let o=n[t.flag];return o===!0||Array.isArray(o)&&o.length>0?t.to:e},Ax={"land-direct":"changes committed state with no draft to review",destroy:"destroys content, other users' work included",publish:"reaches people outside the organization and cannot be taken back"},Rl="agent-policy",Bu=(e,t)=>{let{gate:n}=Cr[t];return n==="refuse"?e.surface==="mcp"&&e.allowCommit:n==="none"||n==="allow-commit"&&e.allowCommit},kl=e=>`${e.wording.askAPerson} ${e.howToGrant}`,vl=(e,t,n,r,o={})=>new f(`${n}, so it is left to a person while an agent (${e.host}) ${e.wording.works}; nothing was changed.`,{exitCode:b.NeedsHuman,type:Rl,hint:r,details:{effect:t,gate:Cr[t].gate,...o}}),Uu=({agent:e},t,n)=>{if(!(e===void 0||Cr[t].site==="landing"||Bu(e,t)))throw vl(e,t,`'${n}' ${Ax[t]}`,Cr[t].gate==="allow-commit"?kl(e):e.wording.askAPerson)},Rr=(e,t,n,r)=>{let{agent:o,effect:s}=e;if(o===void 0||Cr[s].site!=="landing"||xx(r)||Bu(o,s))return;let i=g(n.name);throw"name"in r?vl(o,s,`'${t}' lands your draft of ${i} on ${g(r.name)}, which is not an agent's own branch (${Qt}<topic>)`,`${kl(o)} Or commit on a branch of your own: ${o.wording.branchLane(n.id)}, then stage and commit there; a person reviews and merges it in the app.`,{branch:{id:r.id,name:r.name}}):vl(o,s,`'${t}' lands your draft of ${n.kind} ${i} on its one branch, which no agent owns`,kl(o),{branch:{id:r.id}})},Ox=e=>({id:e.id,...e.requestId?{requestId:e.requestId}:{},surface:Xt(e.requestId),...e.message?{message:e.message}:{}}),Mx=e=>e.surface==="mcp"&&e.allowCommit,Be=async(e,t,n,r)=>{let{agent:o}=e;if(o===void 0||!Cr[e.effect].ownChangesOnly||r.anySurface||n.changeCount===0||Mx(o))return;let i=`Ask the person you work for to review the draft ${t.url?`in the app at ${t.url}`:"in the app"}; ${o.wording.noOverride??r.override}`,a=t.url?{url:t.url}:{};if(t.changes===void 0)throw new f(`${r.action} is left to a person while an agent (${o.host}) ${o.wording.works}, since a dataset's staged changes cannot be listed to tell whose they are. Nothing was changed.`,{exitCode:b.NeedsHuman,type:Rl,hint:i,details:a});let{scope:d}=r,l=await t.changes(n.id,d.kind==="last"?1:void 0),m=(d.kind==="ids"?l.filter(y=>d.ids.includes(y.id)):l).filter(y=>!ko(y.requestId,e.origin));if(m.length===0)return;let p="outside this agent session (in the app, by a script, or by another session)",h=m.length===1?"was":"were",u=d.kind==="last"?`the last staged change was made ${p}`:`${P(m.length,"staged change")} of the draft ${h} made ${p}`;throw new f(`${r.action} is left to a person while an agent (${o.host}) ${o.wording.works}: ${u}. Nothing was changed.`,{exitCode:b.NeedsHuman,type:Rl,hint:i,details:{...a,changes:m.map(Ox)}})},kr={"any-surface":{type:"boolean",description:"Under an agent host, also act on changes staged outside an agent session (in the app, or by a script), which the CLI otherwise leaves to a person."}};var Ot={host:{env:"MODELDESK_HOST"},model:{env:"MODELDESK_MODEL"},stack:{env:"MODELDESK_STACK"},template:{env:"MODELDESK_TEMPLATE"},version:{env:"MODELDESK_VERSION"}};var vo="modeldesk.io",G={host:Ot.host.env,model:Ot.model.env,stack:Ot.stack.env,template:Ot.template.env,version:Ot.version.env,clientId:"MODELDESK_CLIENT_ID",clientSecret:"MODELDESK_CLIENT_SECRET",apiKey:"MODELDESK_API_KEY",agentSession:"MODELDESK_AGENT_SESSION",allowCommit:"MODELDESK_ALLOW_COMMIT"},Io=e=>e!==void 0&&e!==""&&e!=="0",Nx=(...e)=>e.find(t=>t!==void 0&&t!==""),jn=(e,t,n)=>{let r={};for(let[o,{env:s}]of Object.entries(Ot))r[o]=Nx(e[o],t[s],n[o]);return{...r,host:r.host??vo}};var Px=`A person who trusts this agent to commit unattended sets ${G.allowCommit}=1.`,mi={works:"runs the CLI",askAPerson:"Ask them to run it from a plain shell, or to do it in the app.",grant:`${G.allowCommit}=1`,branchLane:e=>`'modeldesk branch create ${e} ${Qt}<topic> --open'`,afterLanding:e=>`Unaddressed invocations now default to main. Address ${e}, or run: modeldesk draft open ${e}`,allRows:e=>`pass --limit ${e} for all of them.`},vr=e=>e.agent?.wording??mi,Dx=[{variable:"CLAUDECODE",host:()=>"claude-code"},{variable:"CLAUDE_CODE_CHILD_SESSION",host:()=>"claude-code"},{variable:"CURSOR_AGENT",host:()=>"cursor"},{variable:"AI_AGENT",host:e=>Lx(e)}],Lx=e=>{let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").slice(0,40);return t===""||t==="1"||t==="true"?"agent":t},Il=e=>{let t=Dx.find(({variable:n})=>Io(e[n]));return t?t.host(e[t.variable]):void 0},Gu=e=>{let t=e[G.agentSession];return{surface:"cli",...t===void 0?{}:{session:t}}},Vu=(e,t)=>{let n=Il(e);return n===void 0?void 0:{...t,host:n,allowCommit:e[G.allowCommit]==="1",howToGrant:Px,wording:mi}};var ve=(e,t)=>e.replace(/\{(\w+)\}/g,(n,r)=>{let o=t[r];if(o===""||o==="."||o==="..")throw k(`'${o}' is not a valid ${r}.`);return encodeURIComponent(o)}),j=(e,t,n,r)=>e.getJson(ve(t,n),r),pi=(e,t,n,r,o)=>e.getJsonIfChanged(ve(t,n),r,o),ne=(e,t,n,r,o)=>e.postJson(ve(t,n),r,o),So=e=>e&&e.length>0?e.join(","):void 0;var Yu=e=>({list:t=>j(e,"/models/{modelId}/branches",{modelId:t}),create:(t,n)=>ne(e,"/models/{modelId}/branches",{modelId:t},n),delete:(t,n,r)=>e.delete(ve("/models/{modelId}/branches/{branchId}",{modelId:t,branchId:n}),{force:r?"true":void 0}),diff:(t,n,r)=>j(e,"/models/{modelId}/branches/{branchId}/diff",{modelId:t,branchId:n},{base:r}),mergePreview:(t,n,r)=>j(e,"/models/{modelId}/branches/{branchId}/merge-preview",{modelId:t,branchId:n},{source:r}),merge:(t,n,r)=>ne(e,"/models/{modelId}/branches/{branchId}/merge",{modelId:t,branchId:n},r)});var _x=/[ \t\n\r\f]+/g,jx=/^[ \t\n\r\f]+|[ \t\n\r\f]+$/g,Fx=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,$o=e=>e.replace(Fx,"");var qx=(e,t)=>{if(!Number.isFinite(e))throw new Error(`Cannot write ${e} as an SVG number`);let n=10**t,r=Math.sign(e)*Math.round(Math.abs(e)*n)/n;return String(r===0?0:r)},Sl=e=>qx(e,2);var Wx=e=>e.replace(_x," ").replace(jx,""),To=e=>Wx($o(e)).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;");var Ku="index.json",fi=e=>{let t=e.fragments?.find(r=>r.address==="")?.realization?.path;if(t===void 0)return;let n=t.lastIndexOf("/");return n===-1?Ku:`${t.slice(0,n)}/${Ku}`},xo=e=>[...new Set(e)].sort(),Hx=(e,t,n)=>{let r=new Map((e.elements??[]).map(i=>[To(i.id),i.id])),o=(e.diagrams??[]).filter(i=>!n.has(i.id)).map(i=>({...i,elements:xo([...t.get(i.id)??[]].flatMap(a=>r.get(a)??[]))})),s=new Map;for(let i of o)for(let a of i.elements??[])s.set(a,[...s.get(a)??[],i.id]);return{...e,elements:(e.elements??[]).map(i=>({...i,diagrams:xo(s.get(i.id)??[])})),diagrams:o}},Bx=e=>({id:e.id,anchor:e.anchor,path:e.path,title:e.title,kind:e.kind,...e.status===void 0?{}:{status:e.status},...e.uri===void 0?{}:{uri:e.uri},refs:xo(e.refs??[]),diagrams:xo(e.diagrams??[])}),Ux=e=>({id:e.id,path:e.path,title:e.title,elements:xo(e.elements??[])}),zu=e=>{let t={convention:e.convention,...e.generatedFrom===void 0?{}:{generatedFrom:e.generatedFrom},elements:(e.elements??[]).map(Bx),diagrams:(e.diagrams??[]).map(Ux).sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0)};return`${JSON.stringify(t,null,2)}
140
+ `},ui=(e,t,n)=>e.index===void 0?e:{...e,index:Hx(e.index,t,n)};var Fn=e=>{let t=e.payloads??{},n=[];for(let o of e.manifest.fragments??[]){let s=o.realization?.path;if(!s)continue;let i=t[o.address];i!==void 0&&n.push({path:s,content:i})}let r=e.index===void 0?void 0:fi(e.manifest);return e.index!==void 0&&r!==void 0&&n.push({path:r,content:zu(e.index)}),n},Ju="image/svg+xml, image/png",Ir=e=>{let t=[];for(let n of e.fragments??[])for(let r of n.realization?.media??[])t.push(r);return[...new Set(t)]},Sr=(e,t={})=>{let n=new Set,r=new Set;for(let o of e)Object.hasOwn(t,o)?n.add(t[o]):r.add(o);return n.size+r.size};var Xu=e=>({get:(t,n)=>j(e,"/models/{modelId}/content-bundle",{modelId:t},n),renderDiagrams:(t,n)=>ne(e,"/models/{modelId}/content-bundle/diagrams",{modelId:t},void 0,n),media:(t,n)=>e.getBytes(ve("/models/{modelId}/content-bundle/media",{modelId:t}),Ju,n)});var Qu=e=>({get:t=>j(e,"/datasets/{datasetId}",{datasetId:t}),commits:(t,n={})=>j(e,"/datasets/{datasetId}/commits",{datasetId:t},{limit:n.limit===void 0?void 0:String(n.limit),cursor:n.cursor})});var Zu=e=>({list:(t,n={})=>j(e,"/models/{modelId}/dependencies",{modelId:t},n),create:async(t,n)=>{let o={...await ne(e,"/models/{modelId}/dependencies",{modelId:t},n)};return delete o.model,o},connectionPreview:(t,n,r,o)=>ne(e,"/models/{modelId}/elements/{elementId}/connection-preview",{modelId:t,elementId:n},r,{ref:o}),disconnectPreview:(t,n,r)=>ne(e,"/models/{modelId}/elements/{elementId}/disconnect-preview",{modelId:t,elementId:n},void 0,{ref:r}),update:async(t,n,r)=>{let s={...await ne(e,"/models/{modelId}/dependencies/{dependencyId}",{modelId:t,dependencyId:n},r)};return delete s.model,s}});var eh=e=>({draftHeadId:e}),th=e=>({model:{stage:async(t,n)=>{let{body:r,headers:o}=await e.postJsonWithHeaders(ve("/models/{modelId}/draft/changes",{modelId:t}),n),s=o.get("disconnect-dropped-references");return{envelope:r,draftId:o.get("draft-ref")??void 0,...s===null?{}:{disconnectDroppedReferences:s}}},undo:(t,n)=>ne(e,"/models/{modelId}/draft/undo",{modelId:t},{draftHeadId:n}),commit:(t,n)=>ne(e,"/models/{modelId}/draft/commit",{modelId:t},n),rebase:(t,n)=>ne(e,"/models/{modelId}/draft/rebase",{modelId:t},n),diff:t=>j(e,"/models/{modelId}/draft/diff",{modelId:t}),discard:(t,n)=>e.delete(ve("/models/{modelId}/draft",{modelId:t}),eh(n)),handoff:(t,n)=>ne(e,"/models/{modelId}/draft/handoff",{modelId:t},n),open:(t,n)=>ne(e,"/models/{modelId}/draft",{modelId:t},{branchId:n})},dataset:{get:t=>j(e,"/datasets/{datasetId}/draft",{datasetId:t}),undo:(t,n)=>ne(e,"/datasets/{datasetId}/draft/undo",{datasetId:t},{draftHeadId:n}),commit:(t,n)=>ne(e,"/datasets/{datasetId}/draft/commit",{datasetId:t},n),rebase:(t,n)=>ne(e,"/datasets/{datasetId}/draft/rebase",{datasetId:t},n),diff:t=>j(e,"/datasets/{datasetId}/draft/diff",{datasetId:t}),discard:(t,n)=>e.delete(ve("/datasets/{datasetId}/draft",{datasetId:t}),eh(n))}});var nh=e=>({encode:(t,n)=>j(e,"/models/{modelId}/encoding",{modelId:t},{format:n.format,mapping:n.mapping}),encodeCompressed:(t,n)=>e.getBytes(ve("/models/{modelId}/encoding",{modelId:t}),"application/octet-stream",{format:n.format,mapping:n.mapping,compressed:"true"})});var rh=e=>({list:t=>j(e,"/metamodels/{metamodelId}/encoding-formats",{metamodelId:t})});var oh=e=>({get:(t,n)=>j(e,"/models/{modelId}/export-jobs/{jobId}",{modelId:t,jobId:n})});var sh=e=>({list:t=>j(e,"/imports",{},{ownerId:t}),create:t=>ne(e,"/imports",{},t),get:t=>j(e,"/imports/{importId}",{importId:t}),model:t=>j(e,"/imports/{importId}/model",{importId:t}),complete:(t,n)=>ne(e,"/imports/{importId}/complete",{importId:t},{name:n}),plan:t=>j(e,"/imports/{importId}/plan",{importId:t}),merge:(t,n)=>ne(e,"/imports/{importId}/merge",{importId:t},n),delete:t=>e.delete(ve("/imports/{importId}",{importId:t}))});var ih=e=>({list:t=>j(e,"/metamodel-extensions",{},{metamodelId:t})});var ah=e=>({list:()=>j(e,"/metamodel-models",{}),create:t=>ne(e,"/metamodel-models",{},t),versions:t=>j(e,"/metamodel-models/{metamodelModelId}/versions",{metamodelModelId:t}),dependents:t=>j(e,"/metamodel-models/{metamodelModelId}/dependents",{metamodelModelId:t})});var dh=e=>({list:t=>j(e,"/metamodels/{metamodelId}/versions",{metamodelId:t})});var lh=e=>({list:()=>j(e,"/metamodels",{}),templates:(t,n={})=>j(e,"/metamodels/{metamodelId}/templates",{metamodelId:t},{metamodelExtensions:So(n.metamodelExtensions)})});var ch=e=>({catalog:()=>j(e,"/model-loaders",{}),forMetamodel:(t,n)=>j(e,"/metamodels/{metamodelId}/loaders",{metamodelId:t},{version:n})});var mh=e=>({list:(t={})=>j(e,"/model-mappings",{},{sourceMetamodel:t.sourceMetamodel})});var ph=e=>({limit:e.limit===void 0?void 0:String(e.limit),cursor:e.cursor}),fh=e=>({create:t=>ne(e,"/models",{},t),update:(t,n)=>ne(e,"/models/{modelId}",{modelId:t},n),metamodelPin:t=>j(e,"/models/{modelId}/metamodel-pin",{modelId:t}),updateMetamodelPin:(t,n)=>ne(e,"/models/{modelId}/metamodel-pin",{modelId:t},n),metadata:t=>j(e,"/models/{modelId}/metadata",{modelId:t}),replaceMetadata:(t,n)=>e.putJson(ve("/models/{modelId}/metadata",{modelId:t}),n),delete:t=>e.delete(ve("/models/{modelId}",{modelId:t})),list:(t={})=>j(e,"/models",{},{ownerId:t.ownerId,metamodel:t.metamodel}),get:(t,n)=>j(e,"/models/{modelId}",{modelId:t},n&&{ref:n.ref,commit:n.commit,expand:So(n.expand)}),getIfChanged:(t,n,r)=>pi(e,"/models/{modelId}",{modelId:t},n,{ref:r.ref,expand:So(r.expand)}),identity:(t,n={})=>j(e,"/models/{modelId}/identity",{modelId:t},n),identityIfChanged:(t,n)=>pi(e,"/models/{modelId}/identity",{modelId:t},n),overview:t=>j(e,"/models/{modelId}/overview",{modelId:t}),versions:(t,n={})=>j(e,"/models/{modelId}/versions",{modelId:t},ph(n)),commits:(t,n={})=>j(e,"/models/{modelId}/commits",{modelId:t},{...ph(n),ref:n.ref,includeSystem:n.includeSystem?"true":void 0}),commitHeader:(t,n,r={})=>j(e,"/models/{modelId}/commits/{commitId}/header",{modelId:t,commitId:n},{ref:r.ref}),events:(t,n)=>e.openEventStream(ve("/models/{modelId}/events",{modelId:t}),n),draft:t=>j(e,"/models/{modelId}/draft",{modelId:t}),schema:(t,n={})=>j(e,"/models/{modelId}/schema",{modelId:t},{ref:n.ref,type:n.type}),schemaIfChanged:(t,n,r={})=>pi(e,"/models/{modelId}/schema",{modelId:t},n,{ref:r.ref,type:r.type})});var uh=e=>({createVersion:(t,n)=>ne(e,"/models/{modelId}/versions",{modelId:t},n),createMetamodelRelease:(t,n,r)=>ne(e,"/metamodel-models/{metamodelModelId}/versions",{metamodelModelId:t},{...n===void 0?{}:{description:n},...r===void 0?{}:{expectedHeadId:r}}),refreshExtensionBase:t=>ne(e,"/metamodel-models/{extensionId}/refresh-base-dependency",{extensionId:t}),metamodelOverview:()=>j(e,"/metamodel-overview",{})});var hh=e=>({get:async(t,n={})=>{let r=await j(e,"/models/{modelId}/validation",{modelId:t},n);return{valid:r.valid,logEntries:r.logEntries??[]}}});var gh=e=>({models:fh(e),branches:Yu(e),metamodels:lh(e),metamodelModels:ah(e),metamodelExtensions:ih(e),drafts:th(e),datasets:Qu(e),contentBundles:Xu(e),exportJobs:oh(e),validation:hh(e),imports:sh(e),modelLoaders:ch(e),metamodelVersions:dh(e),encodingFormats:rh(e),encoding:nh(e),modelMappings:mh(e),dependencies:Zu(e),releases:uh(e),accessTokenClaims:()=>e.accessTokenClaims()});import{randomBytes as $l,randomInt as Gx}from"node:crypto";import{chmodSync as Tl,closeSync as Ol,fsyncSync as kh,linkSync as Vx,mkdirSync as Yx,openSync as Ml,readFileSync as hi,renameSync as yh,rmSync as gi,statSync as wh,utimesSync as Kx,writeSync as bh}from"node:fs";import{homedir as zx,hostname as Eh}from"node:os";import{join as Ch}from"node:path";var xl=448,Al=384,Jx=5e3,Xx=3e4,Qx=9e4,Rh=50,Zx=e=>new Promise(t=>setTimeout(t,e)),$r=(e,t)=>e instanceof Error&&e.code===t,Ve=class{dir;file;lockFile;lockTimeoutMs;staleLockMs;now;sleep;queue=Promise.resolve();constructor(t=Ch(zx(),".modeldesk"),n={}){this.dir=t,this.file=Ch(t,"credentials.json"),this.lockFile=`${this.file}.lock`,this.lockTimeoutMs=n.lockTimeoutMs??Qx,this.staleLockMs=n.staleLockMs??Xx,this.now=n.now??Date.now,this.sleep=n.sleep??Zx}read(t){let n=this.readFile().hosts[t];return n&&typeof n.refreshToken=="string"?n:void 0}async save(t,n){await this.transact(async r=>r.write(t,n))}async clearHost(t){return this.transact(async n=>{let r=n.read(t)!==void 0;return r&&n.write(t,void 0),r})}async transact(t){let n=this.queue.then(async()=>{let r=await this.acquireLock(),o=setInterval(()=>this.touchLock(r),Jx);o.unref();try{return await t({read:s=>this.read(s),write:(s,i)=>this.writeHost(s,i)})}finally{clearInterval(o),this.releaseLock(r)}});return this.queue=n.catch(()=>{}),n}readFile(){let t;try{t=hi(this.file,"utf8")}catch(n){if($r(n,"ENOENT"))return{hosts:{}};throw new f(`Could not read ${this.file}: ${n.message}`)}try{let n=JSON.parse(t);if(n&&typeof n=="object"&&n.hosts&&typeof n.hosts=="object")return n}catch(n){if(!(n instanceof SyntaxError))throw n}return{hosts:{}}}writeHost(t,n){let r=this.readFile();n?r.hosts[t]=n:delete r.hosts[t],this.writeAtomically(`${JSON.stringify(r,null,2)}
141
+ `)}writeAtomically(t){this.ensureDir();let n=`${this.file}.${process.pid}.${$l(6).toString("hex")}.tmp`;try{let r=Ml(n,"wx",Al);try{bh(r,t),kh(r)}finally{Ol(r)}yh(n,this.file)}catch(r){throw gi(n,{force:!0}),r}tA(this.dir),Tl(this.dir,xl),Tl(this.file,Al)}ensureDir(){Yx(this.dir,{recursive:!0,mode:xl})!==void 0&&Tl(this.dir,xl)}async acquireLock(){this.ensureDir();let t=`${Eh()} ${process.pid} ${$l(8).toString("hex")} ${new Date(this.now()).toISOString()}
142
+ `,n=this.now()+this.lockTimeoutMs;for(;;){if(this.tryCreateLock(t))return t;if(!this.takeOverAbandonedLock()){if(this.now()>=n)throw new f(`Timed out waiting for another modeldesk process to release ${this.lockFile}.`,{exitCode:b.Transient,hint:"Retry; if no other modeldesk process is running, delete the lock file."});await this.sleep(Rh+Gx(Rh))}}}tryCreateLock(t){let n;try{n=Ml(this.lockFile,"wx",Al)}catch(r){if($r(r,"EEXIST"))return!1;throw r}try{return bh(n,t),!0}catch(r){throw gi(this.lockFile,{force:!0}),r}finally{Ol(n)}}isAbandoned(t,n){if(this.now()-t>=this.staleLockMs)return!0;let[r,o]=n.split(" "),s=Number.parseInt(o??"",10);return r===Eh()&&Number.isInteger(s)&&s>0&&!eA(s)}takeOverAbandonedLock(){let t,n;try{t=wh(this.lockFile),n=hi(this.lockFile,"utf8")}catch(s){if($r(s,"ENOENT"))return!0;throw s}if(!this.isAbandoned(t.mtimeMs,n))return!1;let r=`${this.lockFile}.${process.pid}.${$l(6).toString("hex")}.stale`;try{yh(this.lockFile,r)}catch(s){if($r(s,"ENOENT"))return!0;throw s}let o=wh(r);if(o.ino!==t.ino||o.mtimeMs!==t.mtimeMs)try{Vx(r,this.lockFile)}catch{}return gi(r,{force:!0}),!0}touchLock(t){try{if(hi(this.lockFile,"utf8")===t){let n=new Date(this.now());Kx(this.lockFile,n,n)}}catch{}}releaseLock(t){try{hi(this.lockFile,"utf8")===t&&gi(this.lockFile,{force:!0})}catch(n){if(!$r(n,"ENOENT"))throw n}}},eA=e=>{try{return process.kill(e,0),!0}catch(t){return!$r(t,"ESRCH")}},tA=e=>{let t;try{t=Ml(e,"r"),kh(t)}catch{}finally{t!==void 0&&Ol(t)}},Nl=(e,t,n)=>e?.accessToken&&e.accessTokenExpiresAt!==void 0&&e.accessTokenExpiresAt-t>n?e.accessToken:void 0;var Ao={superAdmin:!1},nA={"super-admin":e=>e.superAdmin},Zt=(e,t)=>e===void 0||nA[e](t),vh=(e,t)=>e.flatMap(n=>typeof n=="string"?[n]:Zt(n.audience,t)?[n.text]:[]),Ih=(e,t)=>{if(e===void 0||typeof e=="string")return e;let n=vh(e,t).join(" ");return n===""?void 0:n},Sh=(e,t)=>vh(e??[],t),yi=(e,t)=>e.enum.filter(n=>Zt(e.audience?.[n],t)),Pl=(e,t)=>Object.fromEntries(Object.entries(e).filter(([,n])=>Zt(n.audience,t)));var $h={requestUrl:"ACTIONS_ID_TOKEN_REQUEST_URL",requestToken:"ACTIONS_ID_TOKEN_REQUEST_TOKEN"},en=e=>e!==void 0&&e!=="",Th=e=>e==="true"||e==="1",rA=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Dl="mdsk_",xh=57,qn=(e,t)=>({mode:"error",reason:e,message:t}),tn="org settings \u2192 Service accounts",Wn=e=>{if(en(e[G.apiKey]))return qn("legacy-api-key",`${G.apiKey} is no longer supported: the CI credential shipped as service accounts, not bearer keys. Use secret mode (set ${G.clientId} and ${G.clientSecret} from ${tn}) or, on GitHub Actions, federated auth (grant 'permissions: id-token: write' and add a trust rule). Unset ${G.apiKey}.`);let t=e[G.clientId],n=e[G.clientSecret];if(en(t)!==en(n)){let[s,i]=en(t)?[G.clientId,G.clientSecret]:[G.clientSecret,G.clientId];return qn("partial-secret-config",`${s} is set but ${i} is not \u2014 both are required for secret-mode auth. Check the pipeline's secret configuration.`)}if(en(t)&&en(n))return rA.test(t)?n.startsWith(Dl)?n.length!==xh?qn("invalid-client-secret",`${G.clientSecret} has the wrong length: expected ${xh} characters, got ${n.length}. Check for truncation in the pipeline's secret store.`):{mode:"secret",clientId:t,clientSecret:n}:qn("invalid-client-secret",`${G.clientSecret} does not start with '${Dl}' (an issued secret always does). Check for quoting or truncation in the pipeline's secret store.`):qn("invalid-client-id",`${G.clientId} is not a service-account id: expected a UUID, got a ${t.length}-character value. Copy the account id from ${tn}.`);let r=e[$h.requestUrl],o=e[$h.requestToken];return en(r)&&en(o)?{mode:"federated",oidcRequestUrl:r,oidcRequestToken:o}:Th(e.GITHUB_ACTIONS)?qn("headless-ci",`Running on GitHub Actions without machine credentials. Grant 'permissions: id-token: write' to use federated auth (with a trust rule in ${tn}), or set ${G.clientId} and ${G.clientSecret}. The CLI never opens a browser login in CI.`):Th(e.CI)?qn("headless-ci",`Running in CI without machine credentials. Set ${G.clientId} and ${G.clientSecret} (${tn}). The CLI never opens a browser login in CI.`):{mode:"interactive"}},Ye=e=>{let t=Wn(e);return t.mode==="secret"||t.mode==="federated"?t.mode:void 0},Ah=e=>`${e.slice(0,Dl.length+8)}\u2026`,Oh=`Check ${G.clientId} and ${G.clientSecret}; issue or rotate a secret in ${tn}.`,Mh=`The service account may be disabled or deleted \u2014 check ${tn}.`,Nh={issuer:"the auth server does not trust this token issuer \u2014 federated auth currently supports GitHub Actions only.",signature:"the OIDC token's signature could not be verified \u2014 re-run the job; if it persists, the issuer's keys and the auth server disagree.",audience:`the workflow's OIDC audience does not match this host \u2014 check that --host/${G.host} names the ModelDesk instance the trust rule lives on.`,expired:"the OIDC token expired before the exchange \u2014 re-run the job.",repository:"no active trust rule matches this repository. This is also the failure for a pull-request-triggered run unless the rule enables 'Allow pull requests', and for a revoked rule.",binding:"the trust rule pins a branch or environment that does not match this run."},wi={unauthorized:`The machine token was rejected. A disabled or deleted service account fails on the next request; a revoked secret within five minutes. Check ${tn}.`,forbidden:`The service account's scopes do not permit this \u2014 pulling content needs the 'model:content' scope (${tn}).`,notFound:"Check the model id. A machine credential reads SHARED models only (creator-private models are not visible), and the model's metamodel must be entitled under the organization's subscription."};var oA="http://localhost:8080",sA="http://localhost:8082",iA="http://localhost:3000",aA="localhost",dA=e=>{let t=e.trim(),n=/:\/\//.test(t)?t:`https://${t}`;try{return new URL(n).hostname}catch{return t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("/")[0].split(":")[0]}},lA=e=>e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]",Hn=e=>{let t=dA(e);return lA(t)?{host:aA,apiBase:oA,issuer:sA,appBase:iA}:{host:t,apiBase:`https://api.${t}`,issuer:`https://auth.${t}`,appBase:`https://app.${t}`}};import{existsSync as mA,readFileSync as pA}from"node:fs";import{join as fA}from"node:path";import{posix as cA}from"node:path";var Tr=e=>{if(e.trim()==="")return"is empty";if(e.includes("\\"))return'has a backslash; separate folders with "/"';if(/[\t\r\n]/.test(e))return"has a tab or a line break";if(e.startsWith("/")||/^[A-Za-z]:/.test(e))return"is absolute";if(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e))return"is a URL";if(e.includes("%"))return'has a "%", which the document reads as a percent-escape; name the file without one';if(e.includes("#"))return'has a "#", which the document reads as the start of a fragment; name the file without one';if(e.includes("?"))return'has a "?", which the document reads as the start of a query; name the file without one';if(e.split("/").some(t=>t!==t.trim()))return"has a folder or file name that starts or ends with a space";if(e.split("/").includes(".."))return'has a ".." segment'},Ie=e=>cA.normalize(e).replace(/(.)\/+$/,"$1"),Bn=(e,t)=>{let n=Ie(e),r=Ie(t);return r==="."||n===r||n.startsWith(`${r}/`)};var xr=".modeldesk",uA="config.json",bi="md-notes/",Ei=e=>e.configPath!==void 0,nn=e=>{let t=fA(e,xr,uA);return mA(t)?{config:hA(t),configPath:t,repoRoot:e}:{config:{},repoRoot:e}},hA=e=>{let t;try{t=pA(e,"utf8")}catch(o){throw new f(`Could not read ${e}: ${o.message}`)}let n;try{n=JSON.parse(t)}catch(o){throw new f(`${e} is not valid JSON: ${o.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new f(`${e} must contain a JSON object.`);let r=n;return{...Object.fromEntries(Object.keys(Ot).map(o=>[o,Ph(r,o,e)])),notesDir:gA(r,"notesDir",e),publishDirs:yA(r,"publishDirs",e)}},Ph=(e,t,n)=>{let r=e[t];if(r!==void 0){if(typeof r!="string")throw new f(`${n}: "${t}" must be a string.`);return r}},gA=(e,t,n)=>{let r=Ph(e,t,n);return r!==void 0&&Dh(r,`"${t}"`,n),r},yA=(e,t,n)=>{let r=e[t];if(r!==void 0){if(!Array.isArray(r)||!r.every(o=>typeof o=="string"))throw new f(`${n}: "${t}" must be an array of strings.`);return r.forEach((o,s)=>Dh(o,`"${t}"[${s}]`,n)),r}},Dh=(e,t,n)=>{let r=Tr(e);if(r!==void 0)throw new f(`${n}: ${t} ${JSON.stringify(e)} ${r}; give a folder relative to the repository root.`)};var Ll=(e,t,n)=>{let r=n[G.host];return!(t!==void 0&&t!==""||r!==void 0&&r!=="")&&Ei(e)&&!!e.config.host},wA=(e,t)=>{Ll(t,e.globals.host,e.env)&&t.config.host!==vo&&e.io.err(`note: using host '${t.config.host}' from ${t.configPath} (it drives login and API calls).
143
+ `)},bA=(e,t,n)=>{if(Ye(n)&&Ll(e,t,n))throw new f(`In a machine-auth run the host must be set explicitly: pass --host or set ${G.host}. The committed ${e.configPath??".modeldesk/config.json"} is not a trusted source for where machine credentials are sent.`)},Lh=e=>{let t=nn(e.cwd);if(!e.interactive&&Ll(t,e.globals.host,e.env))throw new f(`A login without a terminal takes its host only from --host or ${G.host}, not from ${t.configPath??".modeldesk/config.json"}.`,{hint:`Pass --host ${t.config.host} if you trust it, or log in from a terminal.`})},Ar=(e,t={})=>{let n=nn(e.cwd),r=jn({host:e.globals.host},e.env,n.config);return t.gateMachineHost&&bA(n,e.globals.host,e.env),wA(e,n),Hn(r.host)},Ci=(e,t)=>{let n=e.instance(),r=nn(e.cwd),o=jn({...t,host:e.globals.host},e.env,r.config);if(!o.model)throw new f(`No model specified. Pass --model, set ${G.model}, or add "model" to .modeldesk/config.json.`);return{instance:n,model:o.model,stack:o.stack,template:o.template,version:o.version,loaded:r}},Oo=(e,t,n,r)=>{let o=e?.trim();if(!o)throw new f(`No ${t} specified. Pass ${r}, set ${n}, or add "${t}" to .modeldesk/config.json. Run 'modeldesk bundle templates' to list a model's stacks and templates.`);return o};var EA=e=>{let t=[];for(let n of e)n.forEach((r,o)=>{t[o]=Math.max(t[o]??0,r.length)});return t},W=(e,{indent:t="",gap:n=2,widths:r}={})=>{let s=EA(e).map((a,d)=>r?.[d]??a),i=" ".repeat(n);return e.map(a=>(t+a.map((d,l)=>l===a.length-1?d:d.padEnd(s[l])).join(i)).trimEnd())};var CA={draft:"@draft for your draft",head:"@head for your working branch without the draft",branch:"@main or @<branch> for a branch head",commit:"@<commit id> for a commit",release:"@<release> for a release"},RA={working:"your draft while it holds staged changes, else your working branch",head:"your working branch head",main:"main",draft:"your draft"},_h=e=>{if(e.kinds.length===0)return"It takes no @ref: this command reads main.";let t=e.kinds.includes("release"),n=e.kinds.map(r=>r==="branch"&&t?"@main for its head":CA[r]).join(", ");return"required"in e?`At a ref: ${n}. The ref is required.`:`Optionally at a ref: ${n}. Without a ref: ${RA[e.default]}.`},kA=e=>e.kinds.includes("release")?e.kinds.map(t=>t==="branch"?"main":t).join("|"):e.kinds.length===1?e.kinds[0]:"ref",_l=e=>{if(e.kinds.length===0)return"";let t=kA(e);return"required"in e?`@${t}`:`[@${t}]`},N=e=>({name:"model",type:{address:"model",slot:e},required:!0,description:`The model's id, from model list. ${_h(e)}`}),jh=e=>({name:"resource",type:{address:"resource",slot:e},required:!0,description:`The model's id, from model list, or dataset/<id>. ${_h(e)}`}),$e=e=>({name:e,type:{address:"element"},required:!0,description:"The element's id, or its label path from the model root (SHACL/NodeShape/severity; write a '/' inside "+String.raw`a label as '\/').`});var Or={json:{type:"boolean",description:"Print one JSON document on stdout instead of text."},"no-json":{type:"boolean",description:"Print text even where an agent host makes JSON the default."},host:{type:"string",placeholder:"host",description:"The ModelDesk instance to target (default: modeldesk.io, or MODELDESK_HOST or the repo config)."},"dry-run":{type:"boolean",description:"Report what would change and write nothing (commands that write)."},yes:{type:"boolean",description:"Answer yes to confirmations; required to confirm when not interactive."},help:{type:"boolean",short:"h",description:"Show help."},version:{type:"boolean",short:"v",description:"Show the CLI version."}},Fh=new Set(["json","no-json","host","dry-run","yes","help"]),jl=50,Mo={limit:{type:"number",placeholder:"n",default:jl,description:"Return at most this many rows."},cursor:{type:"string",placeholder:"cursor",description:"Continue a truncated listing from the nextCursor it returned."},all:{type:"boolean",description:"Return every row; with --json, one JSON object per line (NDJSON)."}},qh=e=>e.defaultLimit===void 0?Mo:{...Mo,limit:{...Mo.limit,default:e.defaultLimit}};import{parseArgs as AA}from"node:util";var vA=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,B=e=>vA.test(e);var IA={noun:"A model",listing:"modeldesk model list"},Ri="dataset/",SA={draft:"@draft (your draft)",head:"@head (your working branch without the draft)",branch:"@main or @<branch>",commit:"@<commit id>",release:"@<release>"},$A=(e,t)=>e==="branch"&&t.kinds.includes("release")?"@main":SA[e],Wh=e=>{let t=e.kinds.map(n=>$A(n,e));return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} or ${t.at(-1)}`},Fl=e=>new f(e,{exitCode:b.Usage,type:"ref-unsupported"}),TA=(e,t)=>e==="draft"||e==="head"?{kind:e}:B(e)?{kind:"commit",id:e}:e!=="main"&&t.kinds.includes("release")?{kind:"release",name:e}:{kind:"branch",name:e},xA=e=>{if(e.kind!=="working")return e.kind==="branch-id"?"branch":e.kind},Hh=e=>e.slice(e.indexOf("@")),ql=(e,t)=>{let n=xA(e.ref);if(n===void 0){if("required"in t)throw Fl(`'${e.text}' names no ref, and this argument needs one: ${Wh(t)}.`);return e}if(t.kinds.length===0)throw Fl(`This command reads main only, so the model takes no ref; drop '${Hh(e.text)}'.`);if(!t.kinds.includes(n))throw Fl(`'${Hh(e.text)}' is not accepted here; the ref can be ${Wh(t)}.`);return e},Wl=(e,t)=>{if(e.startsWith(Ri)&&B(e.slice(Ri.length).split("@")[0]))throw new f(`'${e}' names a dataset, and this argument takes a model.`,{exitCode:b.Usage});let n=e.indexOf("@"),r=n===-1?e:e.slice(0,n),o=n===-1?void 0:e.slice(n+1);if(r==="")throw new f(`'${e}' names no model; write <model> or <model>@<ref>.`,{exitCode:b.Usage});if(o==="")throw new f(`'${e}' ends in '@' with no ref after it.`,{exitCode:b.Usage});if(!B(r)){let{noun:i,listing:a}=t.names??IA;throw new f(`'${r}' is not an id. ${i} is addressed by its id: run '${a}' to find it.`,{exitCode:b.Usage,type:"id-required",...t.names===void 0?{hosted:{reason:d=>`'${r}' is not an id. ${i} is addressed by its id: call ${d("model list")} to find it.`}}:{}})}let s=o===void 0?{kind:"working"}:TA(o,t);return ql({model:r.toLowerCase(),ref:s,text:e},t)},Mr=e=>e.ref.kind==="release"?e.ref.name:void 0,Bh=(e,t)=>{if(!e.startsWith(Ri))return{kind:"model",address:Wl(e,t)};let n=e.slice(Ri.length);if(n.includes("@"))throw new f(`'${e}' names a ref on a dataset, which has drafts and no branches; drop the '@'.`,{exitCode:b.Usage});if(!B(n))throw new f(`'${e}' is not a dataset address; write dataset/<id>.`,{exitCode:b.Usage});return{kind:"dataset",id:n,text:e}};var Ke=e=>typeof e=="object"&&"list"in e,Ii=e=>typeof e=="object"&&"enum"in e,Si=e=>typeof e=="object"&&"address"in e,OA=(e,t,n)=>{try{switch(t.address){case"model":return Wl(e,t.slot);case"resource":return Bh(e,t.slot);case"element":return e}}catch(r){throw r instanceof f?new f(r.reason,{exitCode:b.Usage,type:r.type,hint:`Run '${n}'.`,hosted:r.hosted}):r}},Mt=e=>({...e.flags,...e.listing?qh(e.listing):{}}),Gh=e=>({type:e.type==="boolean"?"boolean":"string",...Ke(e.type)?{multiple:!0}:{},...e.short?{short:e.short}:{}}),Vh=e=>Object.fromEntries(Object.entries(Or).filter(([t])=>!(t in e)).map(([t,n])=>[t,Gh(n)])),Yh=(e,t,n)=>{try{return AA({args:e,options:t,allowPositionals:!0,strict:!0})}catch(r){throw k(r.message,n)}},Kh=(e,t)=>({json:e.json===!0,noJson:e["no-json"]===!0,host:typeof e.host=="string"?e.host:void 0,dryRun:e["dry-run"]===!0,yes:e.yes===!0,help:e.help===!0,version:!("version"in t)&&e.version===!0}),Hl=(e,t)=>{let{values:n,positionals:r}=Yh(e,Vh({}),t);return{globals:Kh(n,{}),positionals:r}},MA=(e,t,n)=>Ii(t)?`${e} must be one of ${yi(t,n).join(", ")}`:`${e} expects a ${t==="number"?"number":"value"}`,ki=(e,t,n,r,o)=>k(`${MA(e,t,o)}, got '${n}'.`,r),vi=(e,t,n,r,o)=>{let s=Ke(t)?t.list:t;if(Si(s))return OA(e,s,r);if(s==="number"){let i=Number(e);if(e.trim()===""||!Number.isFinite(i))throw ki(n,s,e,r,o);return i}if(s==="boolean"){if(e!=="true"&&e!=="false")throw k(`${n} expects true or false, got '${e}'.`,r);return e==="true"}if(Ii(s)&&!s.enum.includes(e))throw ki(n,s,e,r,o);return e},Uh=(e,t,n)=>{let r=t.short?` (-${t.short})`:"",o=t.requiredReason?` ${t.requiredReason}`:"";return k(`Missing required flag --${e}${r}.${o}`,n)},NA=(e,t,n,r,o)=>{let s=`--${e}`;if(t.type==="boolean")return n===!0;if(Ke(t.type)){let i=n??[];if(i.length===0&&t.required)throw Uh(e,t,r);return i.length===0&&t.default!==void 0?t.default:i.map(a=>vi(a,t.type,s,r,o))}if(n===void 0){if(t.required)throw Uh(e,t,r);return t.default}return vi(n,t.type,s,r,o)},PA=(e,t,n,r)=>{let o={};if(e.forEach((i,a)=>{let d=`<${i.name}>`;if(Ke(i.type)){let c=t.slice(a);if(c.length===0&&i.required)throw k(`Missing required argument ${d}.`,n);o[i.name]=c.map(m=>vi(m,i.type,d,n,r));return}let l=t[a];if(l===void 0){if(i.required)throw k(`Missing required argument ${d}.`,n);o[i.name]=void 0;return}o[i.name]=vi(l,i.type,d,n,r)}),!e.some(i=>Ke(i.type))&&t.length>e.length)throw k(`Unexpected argument '${t[e.length]}'.`,n);return o},zh=(e,t,n,r)=>{let o=Mt(e),s={...Vh(o),...Object.fromEntries(Object.entries(o).map(([m,p])=>[m,Gh(p)]))},{values:i,positionals:a}=Yh(t,s,n),d=Kh(i,o),l=Object.fromEntries(Object.entries(o).map(([m,p])=>[m,NA(m,p,i[m],n,r)]));if(e.listing){let m=l.limit;if(!Number.isInteger(m)||m<1)throw k(`--limit must be a positive whole number, got ${m}.`,n)}let c=PA(e.positionals??[],a,n,r);return{flags:l,args:c,globals:d}};var Jh=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/,DA=new Set(Object.values(Or).flatMap(e=>e.short?[e.short]:[])),LA=(e,t)=>{for(let[n,r]of Object.entries(t.flags??{})){if(Fh.has(n))throw new Error(`'${e}' declares --${n}, which is a global flag every command already takes.`);if(t.listing&&n in Mo)throw new Error(`'${e}' declares --${n}, which its listing already provides.`);if(r.type==="boolean"&&r.default!==void 0)throw new Error(`'${e}' gives --${n} a default; a boolean flag is off unless passed.`)}},_A=(e,t)=>{let n=Object.entries(t.flags??{}).flatMap(([r,o])=>o.short===void 0?[]:[[r,o.short]]);for(let[r,o]of n)if(!/^[a-z]$/.test(o)||DA.has(o)||n.filter(([,s])=>s===o).length>1)throw new Error(`'${e}' gives --${r} the alias -${o}; an alias is one free lowercase letter.`)},jA=(e,t)=>{let n=t.positionals??[];n.forEach((r,o)=>{let s=o===n.length-1;if(Ke(r.type)&&!s)throw new Error(`'${e}': only the last argument may take a list (<${r.name}>).`);let i=n[o-1];if(r.required&&i&&!i.required)throw new Error(`'${e}': required argument <${r.name}> follows an optional one.`)})},FA=e=>{let t=e.path.join(" ");if(e.path.length===0||e.path.some(r=>!Jh.test(r)))throw new Error(`Command path '${t}' must be one or more kebab-case words.`);LA(t,e),_A(t,e);let n=e.listing?.defaultLimit;if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`'${t}' gives its listing a default limit of ${n}; it must be a positive whole number.`);for(let r of Object.keys(Mt(e)))if(!Jh.test(r))throw new Error(`'${t}' declares --${r}; flag names are kebab-case.`);jA(t,e)},Bl=e=>{let t={kind:"group",path:[],children:new Map};for(let n of e){FA(n);let r=t;n.path.forEach((o,s)=>{let i=n.path.slice(0,s+1),a=r.children.get(o);if(s===n.path.length-1){if(a)throw new Error(`'${i.join(" ")}' is declared twice, or as both a command and a group.`);r.children.set(o,{kind:"command",path:i,spec:n});return}if(a?.kind==="command")throw new Error(`'${i.join(" ")}' is both a command and a group.`);let l=a??{kind:"group",path:i,children:new Map};r.children.set(o,l),r=l})}return t},Ul=e=>[...e.children.values()].flatMap(t=>t.kind==="group"?Ul(t):[t]);var $i="modeldesk",Qh=[["0","success"],["1","failure (generic or server)"],["2","usage error"],["3","not found"],["4","validation or check failure (input refused, or an assertion the caller asked for failed)"],["5","conflict (stale base, lost compare-and-set)"],["6","needs a human (log in, confirm, commit in the app)"],["7","transient, safe to retry (network, 429, 5xx)"]],qA=Qh.map(([e,t])=>`${e} ${t.replace(/ \(.*\)$/,"")}`),WA=`Exit codes: ${qA.join(", ")}.`,HA=`With --json, a command's stdout is one JSON document led by schemaVersion (help and version stay text); on failure the last stderr line is {"error": {code, message, hint?, retryable, type?, requestId?, details}}.`,BA=(e,t,n)=>{if(n)return`<${n}>`;let r=Ke(e)?e.list:e;return Ii(r)?`<${yi(r,t).join("|")}>`:Si(r)?`<${r.address}${r.address==="element"?"":_l(r.slot)}>`:r==="number"?"<n>":"<value>"},Vl=(e,t,n)=>{let r=t.short?`, -${t.short}`:"";return t.type==="boolean"?`--${e}${r}`:`--${e}${r} ${BA(t.type,n,t.placeholder)}`},UA=e=>Array.isArray(e)?e.join(", "):String(e),Xh=e=>{let t=[];return e.required&&t.push("required"),e.default!==void 0&&e.type!=="boolean"&&t.push(`default: ${UA(e.default)}`),Ke(e.type)&&t.push("repeatable"),t.length>0?` (${t.join("; ")})`:""},Gl=e=>{let t=Ke(e.type)?e.type.list:e.type,n=Si(t)&&t.address!=="element"?_l(t.slot):"";return`<${e.name}${n}>`},GA=e=>{let t=Ke(e.type)?`${Gl(e)}...`:Gl(e);return e.required?t:`[${t}]`},Zh=(e,t)=>{let n=Pl(Mt(e),t),r=Object.entries(n).filter(([,s])=>s.required).map(([s,i])=>Vl(s,i,t)),o=Object.values(n).some(s=>!s.required);return[$i,...e.path,...(e.positionals??[]).map(GA),...r,...o?["[options]"]:["[global options]"]].join(" ")},Un=(e,t)=>t.length===0?[]:[`${e}:`,...W(t,{indent:" "}),""],eg=(e,t)=>{let n=t?Mt(t):{};return Object.entries(Or).filter(([r])=>!(r in n)).filter(([r])=>r!=="dry-run"||t===void 0||t.dryRun===!0).map(([r,o])=>[Vl(r,o,e),o.description])},Ti=(e,t)=>Ul(e).filter(n=>Zt(n.spec.audience,t)),VA=(e,t)=>Ti(e,t).map(n=>[n.path.slice(e.path.length).join(" "),n.spec.summary]),tg=(e,t)=>["ModelDesk CLI","",`Usage: ${$i} <command> [options]`,"",...Un("Commands",VA(e,t)),...Un("Global options",eg(t)),...Un("Exit codes",Qh),HA,`Run '${$i} <command> --help' for a command's arguments and flags.`,""].join(`
144
+ `),ng=(e,t)=>{let n=[$i,...e.path].join(" "),r=Ti(e,t).flatMap(o=>[[o.path.slice(e.path.length).join(" "),o.spec.summary],["",Zh(o.spec,t)]]);return[`Usage: ${n} <command> [options]`,"",...Un("Commands",r),`Run '${n} <command> --help' for a command's arguments and flags.`,""].join(`
145
+ `)},rg=(e,t)=>{let n=(e.positionals??[]).map(i=>[Gl(i),i.description+Xh(i)]),r=Object.entries(Pl(Mt(e),t)).map(([i,a])=>[Vl(i,a,t),a.description+Xh(a)]),o=Sh(e.examples,t).map(i=>` ${i}`),s=Ih(e.description,t);return[`Usage: ${Zh(e,t)}`,"",e.summary,...s?["",s]:[],"",...Un("Arguments",n),...Un("Flags",r),...Un("Global options",eg(t,e)),...o.length>0?["Examples:",...o,""]:[],WA,...e.listing?[`Listings are truncated at --limit; ${YA(e)}`]:[],""].join(`
146
+ `)},YA=e=>`a truncated one carries nextCursor and truncated: true.${e.listing?.narrowHint?` ${e.listing.narrowHint}`:""}`;var og='# Working in a ModelDesk model from a shell\n\nYou have a shell, so drive the CLI. You pay for a command only when you run it and read help only when you need it (`modeldesk <command> --help`). Under an agent host the output is one JSON document; pass `--no-json` for text.\n\nA person owns the model and reviews your work. You stage proposals; they decide what lands.\n\n## On every invocation\n\n- **Always write the ref.** Address `<model>@<branch>` every time, for example `<model>@agent/<topic>`, and never leave it out. A commit from any surface, the app included, deletes the draft, and unaddressed invocations then read and write `main`.\n- **Read your own work at `@draft`.** A change addressed `<model>@<branch>` is staged in your draft, but a read addressed `<model>@<branch>`, such as `modeldesk search`, `modeldesk el show` or `modeldesk validate`, sees the branch head without it. Read back and validate what you staged with `<model>@draft`.\n- **Keep one session.** Set `MODELDESK_AGENT_SESSION` before the first change and keep the same value for every command up to the wait, in every shell you start: it groups your changes for the person, and the wait finds your changes by it.\n- **Stage small steps, each with a message** (`-m`). The message is what the person reads first, in the app and in `modeldesk model log <model> --changes`.\n- **Add a dependency before you refer to another model.** Check `modeldesk pin list <model>@<branch>`. When the model is missing, run `modeldesk dependency add <model>@<branch> <target>@<release|main>` first: it is a staged change of its own, which the person reviews with the rest. `modeldesk dependency rm` and `modeldesk dependency pin` remove one and move one to another release the same way.\n- **Connect an element to the model it represents only when the person asks.** An element such as a MIM Extern holds another model\'s elements as copies, or by reference once connected to a dependency the model has directly. `modeldesk dependency connect <model>@<branch> <element> <dependency> --dry-run` shows each copy with its counterpart or candidates; then `--use <copy>=<counterpart>`, or `--settled`, names the copies to replace, and the rest stay owned. `modeldesk dependency disconnect` turns them into owned copies again, and its `--dry-run` names each reference it would leave out. A dependency elements are connected to cannot be removed until they are disconnected.\n- **Never merge, and never delete.** `modeldesk branch merge` lands on a shared branch with no draft to review, so it is refused unless the person set `MODELDESK_ALLOW_COMMIT=1`, and even then the merge is theirs to make. `modeldesk model delete` and `modeldesk branch delete` are refused to an agent.\n- **Commits elsewhere need the person\'s grant.** Commit only on a branch named `agent/<topic>`. A commit on any other branch is left to the person, unless they set `MODELDESK_ALLOW_COMMIT=1` for you.\n\n## The loop\n\n1. **Discover the schema.** `modeldesk describe <model>` gives the overview, `modeldesk describe <model> <type>` one type.\n2. **Read before you write.** `modeldesk search <model>@<branch> <text>` finds elements and `modeldesk el show <model>@<branch> <element>` reads one.\n3. **Stage.** Use `modeldesk el create`, `modeldesk el set`, `modeldesk el relate` and their siblings for small edits and `modeldesk el bulk` for sweeps. For bulk authoring use the file workspace: `modeldesk model pull <model>@<branch>`, edit the files, check them with `modeldesk model diff`, then stage them with `modeldesk model push -m <message>`.\n - To create an element with what it owns as one change, use `el create --from <file>`. In the file, attribute values are arrays, `"name": ["Address"]`; a reference is `"relations": {"type": {"@@": [{"id": "<id>", "owned": false}]}}`; owned elements nest under `"children"`, keyed by the owning relation.\n4. **Verify.** `modeldesk draft diff <model>@<branch>` shows what your draft changes and `modeldesk validate <model>@draft` checks the model with it. Validate after the first change that sets a pattern, not only at the end, so a mistake is not repeated across the draft. To repair your last change, undo it with `modeldesk draft undo <model>@<branch>` and stage it again complete, rather than adding changes that patch it: the person reviews each change by itself.\n5. **Keep the proposal rebased.** When `modeldesk draft status <model>@<branch>` shows `behind: true`, run `modeldesk draft rebase <model>@<branch>`. A `rebase-conflict` names your own rejected changes: correct and stage them again, and drop only what you cannot repair.\n\nThen pick a lane.\n\n## The draft lane\n\nFor a proposal that fits one draft. You stage into the draft you share with the person, who reviews it in their open model and answers it there.\n\n1. **Stage on the branch your draft aims at.** One draft per user per model; `modeldesk draft status` names where it aims. While it holds changes on another branch, staging elsewhere is refused with `draft-target-taken`: ask the person to commit or discard those changes.\n2. **End with `modeldesk draft handoff <model>@<branch> -m <summary>`.** The summary is your own account of what the draft does. Do not commit on this lane: the commit is the person\'s answer.\n3. **Wait for the verdict.** Run `modeldesk draft status <model>@<branch> --wait` and act on its `verdict`:\n - `committed`: tell the person it landed, with `url` and how many of your changes (`landed`).\n - `discarded`: none of your changes landed. Ask the person what to change.\n - `changed`: the person removed or undid changes. Read `modeldesk draft diff <model>@<branch> --changes`, then hand off again or wait again.\n - `branch-moved`: run `modeldesk draft rebase <model>@<branch>`, resolve any conflict in your own changes, then wait again.\n\n When the wait exits 7 (`retryable: true`) run it again. When you cannot keep waiting, tell the person how to check: `modeldesk draft status <model>@<branch>`.\n - A wait that finds no draft is refused with `no-draft`: the person has already answered (committed or discarded the draft), or nothing was handed off. Run `modeldesk model log <model>@<branch> --changes` to see whether your changes landed.\n - A wait refused with `no-own-changes` found none of your changes in the draft: it runs under another `MODELDESK_AGENT_SESSION` than the one that staged them, or the person removed them first. Run `modeldesk draft diff <model>@<branch> --changes` to see where each change came from.\n\n## The branch lane\n\nFor work too large for one draft. You commit on a branch of your own, and the person reviews and merges the branch.\n\n1. **Start on a branch of your own.** `modeldesk branch create <model> agent/<topic> --open`. While your draft holds changes on another branch this is refused with `draft-target-taken`, as above.\n2. **Commit as you go.** `modeldesk draft commit <model>@agent/<topic>`, with `-m` or without it to compose the message from your staged messages. Commit before `changeCount` in `modeldesk draft status` nears `maxChanges`, since a draft holds at most 500 changes.\n3. **End with the commit.** The last commit on `agent/<topic>` is the handoff: its message is the summary and its record lists every change with its message. There is no draft to wait on. Name the branch in the chat and ask the person to review and merge it in the app; `modeldesk branch list <model>` shows it unmerged until then.\n';var A=e=>e,J=e=>e;var sg=J({path:["agent-guide"],effect:"local",summary:"Print the guide for an agent that uses the CLI",description:"Prints, as Markdown, how an agent with a shell works in a model: always write the ref, stage small steps with a message each, and choose the draft lane (hand off, then wait for the verdict) or the branch lane (commit on agent/<topic>, then ask the person to merge). Under an agent host the output is a JSON document with the guide as its `guide` member; pass --no-json to print the Markdown itself.",examples:["modeldesk agent-guide --no-json"],run:async()=>({result:{guide:og}}),render:({guide:e})=>e});var rn="modeldesk-cli",ig="modeldesk-federation",ag="openid",Yl="/callback";var on=async e=>{let t=`${e.replace(/\/+$/,"")}/.well-known/openid-configuration`,n;try{n=await fetch(t,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(3e4)})}catch(o){throw new f(`Could not reach the auth server at ${e} (${o.message}).`,b.Transient)}if(!n.ok)throw new f(`OpenID discovery failed at ${t}: ${n.status} ${n.statusText}`,n.status===429||n.status>=500?b.Transient:b.Failure);let r=await n.json();if(!r.authorization_endpoint||!r.token_endpoint)throw new f(`OpenID discovery at ${t} did not return the authorization and token endpoints.`);for(let o of[r.authorization_endpoint,r.token_endpoint,r.device_authorization_endpoint])if(o!==void 0&&!KA(o,e))throw new f(`OpenID discovery at ${t} names an endpoint outside the issuer's origin: ${o}.`);return{authorizationEndpoint:r.authorization_endpoint,tokenEndpoint:r.token_endpoint,...r.device_authorization_endpoint?{deviceAuthorizationEndpoint:r.device_authorization_endpoint}:{}}},KA=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}};var sn=class extends f{oauthError;errorDescription;constructor(t,n,r,o=b.Failure){super(t,o),this.name="TokenEndpointError",this.oauthError=n,this.errorDescription=r}},dg=e=>e instanceof sn&&e.oauthError==="invalid_grant",lg=(e,t)=>No(e,new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:t.redirectUri,client_id:rn,code_verifier:t.codeVerifier})),zA="urn:ietf:params:oauth:grant-type:device_code",cg=(e,t)=>No(e,new URLSearchParams({grant_type:zA,device_code:t,client_id:rn})),mg=(e,t)=>No(e,new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:rn})),pg=(e,t)=>No(e,new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_secret:t.clientSecret})),fg=(e,t)=>No(e,new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:t,subject_token_type:"urn:ietf:params:oauth:token-type:jwt",client_id:ig})),JA=new Set(["server_error","temporarily_unavailable"]),No=async(e,t)=>{let n;try{n=await fetch(e,{method:"POST",redirect:"error",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString(),signal:AbortSignal.timeout(3e4)})}catch(o){throw new f(`Could not reach the token endpoint (${o.message}).`,b.Transient)}if(!n.ok){let{message:o,code:s,description:i}=await XA(n),a=JA.has(s??"")||n.status===429||n.status>=500;throw new sn(`Token request failed: ${o}`,s,i,a?b.Transient:b.Failure)}let r=await n.json();if(!r.access_token)throw new f("The token response did not include an access token.");return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresInSeconds:r.expires_in??0}},XA=async e=>{try{if((e.headers.get("content-type")??"").includes("json")){let n=await e.json();if(n.error)return{message:n.error_description?`${n.error} (${n.error_description})`:n.error,code:n.error,description:n.error_description}}}catch{}return{message:`${e.status} ${e.statusText}`.trim()}};var QA=5,ZA=5,eO=1,tO=60,nO=600,rO=1800,gg=e=>Math.min(tO,Math.max(eO,e)),ug=(e,t)=>{let n;try{n=new URL(e)}catch{throw new f("The device authorization response carries an invalid verification URL.")}let r=new URL(t.issuer);if(!(n.protocol==="https:"||n.protocol==="http:"&&r.protocol==="http:")||n.hostname!==r.hostname)throw new f(`The device authorization response points to ${n.origin}, not to the auth server ${r.origin}; refusing to show its code.`);return n.toString()},hg=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:t,yg=new Set(["unauthorized_client","unsupported_grant_type","invalid_client"]),oO=e=>new Promise(t=>setTimeout(t,e)),Kl=e=>new f(`Device login is not enabled on ${e.host}.`,{hint:"Run 'modeldesk auth login' where a browser can reach this machine."}),sO=async(e,t)=>{let n;try{n=await fetch(e,{method:"POST",redirect:"error",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:rn}).toString(),signal:AbortSignal.timeout(3e4)})}catch(o){throw new f(`Could not reach the device authorization endpoint (${o.message}).`,{exitCode:b.Transient})}let r=await n.json().catch(()=>({}));if(!n.ok){if(r.error&&yg.has(r.error))throw Kl(t);let o=r.error??`${n.status} ${n.statusText}`;throw new f(`Device authorization failed: ${o}`,{exitCode:n.status===429||n.status>=500?b.Transient:b.Failure})}return r},wg=()=>new f("The code expired before it was approved.",{hint:"Run 'modeldesk auth login --device' again."}),iO=(e,t,n)=>{if(!(e instanceof sn))throw e;switch(e.oauthError){case"authorization_pending":return t;case"slow_down":return gg(t+ZA);case"access_denied":throw new f("The sign-in was declined, so nothing was stored.");case"expired_token":throw wg();default:throw e.oauthError&&yg.has(e.oauthError)?Kl(n):e}},aO=(e,t,n)=>{let{device_code:r,user_code:o,verification_uri:s}=e;if(!r||!o||!s)throw new f("The device authorization response is missing its code or verification URL.");let i=ug(s,t),a=e.verification_uri_complete?ug(e.verification_uri_complete,t):void 0;return n.info(`To sign in to ${t.host}, open ${i} and enter the code ${o}.`),a&&n.info(`Or open this link, which carries the code:
147
+ ${a}`),r},bg=async(e,t,n={})=>{let r=n.sleep??oO,o=n.now??Date.now,{deviceAuthorizationEndpoint:s,tokenEndpoint:i}=await on(e.issuer);if(!s)throw Kl(e);let a=await sO(s,e),d=aO(a,e,t),l=Math.min(rO,hg(a.expires_in,nO)),c=o()+l*1e3,m=gg(hg(a.interval,QA));for(;;){await r(m*1e3);try{return await cg(i,d)}catch(p){if(p instanceof f&&p.exitCode===b.Transient){if(o()>=c)throw p;continue}m=iO(p,m,e)}if(o()>=c)throw wg()}};import{spawn as dO}from"node:child_process";import{platform as lO}from"node:process";var Eg=e=>{if(!cO(e))return;let{command:t,args:n,verbatim:r}=mO(e);try{let o=dO(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});o.on("error",()=>{}),o.unref()}catch{}},cO=e=>{try{let{protocol:t}=new URL(e);return t==="http:"||t==="https:"}catch{return!1}},mO=(e,t=lO)=>{switch(t){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start",'""',pO(e)],verbatim:!0};default:return{command:"xdg-open",args:[e]}}},pO=e=>e.replace(/[&|<>^()%"]/g,t=>`^${t}`);import{createServer as fO}from"node:http";var uO=3e5,Cg=(e,t=uO)=>new Promise((n,r)=>{let o,s=new Promise((c,m)=>{o={resolve:c,reject:m}}),i=fO((c,m)=>{let p=new URL(c.url??"/","http://127.0.0.1");if(p.pathname!==Yl){m.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}hO(p,m,e,o)}),a=setTimeout(()=>o.reject(new f("Timed out waiting for the browser login to complete.")),t);a.unref();let d=!1,l=()=>{d||(d=!0,clearTimeout(a),i.close())};s.then(l,l),i.once("error",c=>r(new f(`Could not start the loopback listener: ${c.message}`))),i.listen(0,"127.0.0.1",()=>{let{port:c}=i.address();n({redirectUri:`http://127.0.0.1:${c}${Yl}`,waitForCode:()=>s,close:l})})}),hO=(e,t,n,r)=>{if(e.searchParams.get("state")!==n){t.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Unexpected request");return}let o=e.searchParams.get("error");if(o){let i=e.searchParams.get("error_description");zl(t,"Sign-in failed","Sign-in failed. You can close this window and return to the terminal."),r.reject(new f(`Authorization failed: ${i?`${o} (${i})`:o}`));return}let s=e.searchParams.get("code");if(!s){zl(t,"Sign-in failed","No authorization code was returned. You can close this window."),r.reject(new f("Login failed: no authorization code was returned."));return}zl(t,"Signed in","You are signed in to the ModelDesk CLI. You can close this window and return to the terminal."),r.resolve(s)},zl=(e,t,n)=>{let r=`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${t}</title></head><body style="font-family: system-ui, sans-serif; text-align: center; padding: 3rem;"><h1>${t}</h1><p>${n}</p></body></html>`;e.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}).end(r)};import{createHash as gO,randomBytes as Rg}from"node:crypto";var Jl=e=>e.toString("base64url"),kg=()=>{let e=Jl(Rg(32)),t=Jl(gO("sha256").update(e).digest());return{verifier:e,challenge:t,method:"S256"}},vg=()=>Jl(Rg(16));var Ig={info:e=>process.stderr.write(`${e}
148
+ `)},xi=async(e,t)=>{let{authorizationEndpoint:n,tokenEndpoint:r}=await on(e.issuer),o=kg(),s=vg(),i=await Cg(s);try{let a=yO(n,i.redirectUri,o.challenge,s);t.info(`Opening your browser to sign in to ${e.host}...`),t.info(`If it does not open automatically, visit:
149
+ ${a}`),Eg(a);let d=await i.waitForCode();return await lg(r,{code:d,redirectUri:i.redirectUri,codeVerifier:o.verifier})}finally{i.close()}},yO=(e,t,n,r)=>{let o=new URL(e);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",rn),o.searchParams.set("redirect_uri",t),o.searchParams.set("scope",ag),o.searchParams.set("state",r),o.searchParams.set("code_challenge",n),o.searchParams.set("code_challenge_method","S256"),o.toString()};var Po=6e4,Ai=(e,t,n)=>{let r=e.refreshToken??t;if(r)return e.expiresInSeconds>0?{refreshToken:r,accessToken:e.accessToken,accessTokenExpiresAt:n+e.expiresInSeconds*1e3}:{refreshToken:r}},Nr=class{constructor(t,n={}){this.instance=t;this.store=n.store??new Ve,this.io=n.io??Ig,this.now=n.now??Date.now,this.allowBrowserLogin=n.allowBrowserLogin??!0}instance;store;io;now;allowBrowserLogin;accessToken;accessTokenExpiresAt=0;endpoints;pendingLogin;async getAccessToken(){if(this.accessToken&&this.now()<this.accessTokenExpiresAt-Po)return this.accessToken;let t=this.store.read(this.instance.host),n=Nl(t,this.now(),Po);if(n)return this.remember({accessToken:n,expiresAt:t?.accessTokenExpiresAt??0});if(t){let r=await this.refresh({force:!1});if(r)return r}return this.login()}async refreshNow(){return this.refresh({force:!0})}async refresh({force:t}){let{tokenEndpoint:n}=await this.getEndpoints(),r=await this.store.transact(async o=>{let s=o.read(this.instance.host),i=t?void 0:Nl(s,this.now(),Po);if(i)return{accessToken:i,expiresAt:s?.accessTokenExpiresAt??0};if(s)try{let a=await mg(n,s.refreshToken);return o.write(this.instance.host,Ai(a,s.refreshToken,this.now())),{accessToken:a.accessToken,expiresAt:this.now()+a.expiresInSeconds*1e3}}catch(a){if(dg(a)){o.write(this.instance.host,void 0);return}throw a}});return r?this.remember(r):void 0}login(){return this.pendingLogin??=this.browserLogin().finally(()=>{this.pendingLogin=void 0}),this.pendingLogin}async browserLogin(){if(!this.allowBrowserLogin)throw new f(`Not logged in to ${this.instance.host}, and this run cannot open a browser to log in.`,{exitCode:b.NeedsHuman,hint:"Run 'modeldesk auth login' in a terminal, or 'modeldesk auth login --device' where no browser can reach this machine, then retry."});let t=await xi(this.instance,this.io),n=Ai(t,void 0,this.now());return n&&await this.store.save(this.instance.host,n),this.remember({accessToken:t.accessToken,expiresAt:this.now()+t.expiresInSeconds*1e3})}remember({accessToken:t,expiresAt:n}){return this.accessToken=t,this.accessTokenExpiresAt=n,t}async getEndpoints(){return this.endpoints||(this.endpoints=await on(this.instance.issuer)),this.endpoints}};var Gn=e=>{let t=e.split(".");if(t.length===3)try{let n=Buffer.from(t[1],"base64url").toString("utf8"),r=JSON.parse(n);return r&&typeof r=="object"&&!Array.isArray(r)?r:void 0}catch{return}},Oi=e=>{let t=Gn(e);if(t)return t.name&&t.email?`${t.name} <${t.email}>`:t.email??t.name??t.sub};import{createInterface as bO}from"node:readline";var Sg={name:"@modeldesk/cli",version:"0.9.0",description:"Command-line interface (CLI) for the ModelDesk platform",keywords:["modeldesk","cli","documentation","content-bundle","respec","mim","information-model"],homepage:"https://modeldesk.io",repository:{type:"git",url:"git+https://github.com/model-desk/modeldesk.git",directory:"packages/cli"},license:"MIT",type:"module",bin:{modeldesk:"dist/modeldesk.js"},"//":"The ./headless export is the hosted MCP server's entry within this workspace, as TypeScript source. The published package is the binary alone: files ships dist, so the bin runs as before, and an import of @modeldesk/cli/headless or of any other path from it fails, as none is an API.",exports:{"./headless":"./src/headless.ts"},files:["dist","THIRD-PARTY-NOTICES.txt"],publishConfig:{access:"public"},engines:{node:">=22"},scripts:{build:"node esbuild.config.mjs",prepublishOnly:"npm run build",typecheck:"node scripts/api-types.mjs --check && node scripts/result-schemas.mjs --check && node scripts/guides.mjs --check && tsc --noEmit","generate:api":"node scripts/api-types.mjs","generate:result-schemas":"node scripts/result-schemas.mjs","generate:guides":"node scripts/guides.mjs",lint:"eslint","lint:fix":"eslint --fix",test:"vitest run","test:watch":"vitest"},devDependencies:{"@eslint/js":"^10.0.1","@modelcontextprotocol/client":"^2.4.0","@modelcontextprotocol/server":"^2.4.0","@modeldesk/content-bundle":"*","@types/node":"^24.19.2",esbuild:"^0.28.2",eslint:"^10.15.0","eslint-config-prettier":"^10.1.5","eslint-plugin-prettier":"^5.5.7",globals:"^17.14.0","openapi-typescript":"^7.13.0",prettier:"^3.10.1",typescript:"^6.0.3","typescript-eslint":"^8.73.0",vitest:"^5.1.0",yaml:"^2.9.1"}};var Pr=Sg.version;var $g={out:e=>{process.stdout.write(e)},err:e=>{process.stderr.write(e)}},EO=async e=>{let t=bO({input:process.stdin,output:process.stderr});try{return await new Promise(n=>{t.once("close",()=>n(void 0)),t.question(e,n)})}finally{t.close()}},CO=async()=>{process.stdin.setEncoding("utf8");let e="";for await(let t of process.stdin)e+=t;return e},Tg=()=>({env:process.env,cwd:process.cwd(),stdinIsTTY:!!process.stdin.isTTY,stdoutIsTTY:!!process.stdout.isTTY,ask:EO,readStdin:CO}),Xl=e=>Io(e.CI)&&e.CI?.toLowerCase()!=="false",xg=e=>e.stdinIsTTY&&e.stdoutIsTTY&&!Xl(e.env)&&Il(e.env)===void 0,Ag=e=>e.stdoutIsTTY&&!Io(e.env.NO_COLOR)&&e.env.TERM!=="dumb",Og=e=>e?`modeldesk-cli/${Pr} (${e})`:`modeldesk-cli/${Pr}`;var Mg=J({path:["auth","login"],effect:"local",summary:"Log in through the browser, or with --device by approving a code on another device",description:"Opens the browser to sign in to the host and stores the credential in ~/.modeldesk/credentials.json (mode 0600), so later commands run unattended. With --device, prints a code to approve in a browser on any device instead, for SSH sessions, containers and remote agents that cannot receive the browser redirect. Machine credentials in the environment take precedence for API commands; this login only affects interactive use.",flags:{device:{type:"boolean",description:"Log in by approving a code in a browser on another device (OAuth device authorization)."}},examples:["modeldesk auth login","modeldesk auth login --device --host modeldesk.io"],run:async e=>{let t=Ye(e.env);if(t&&e.warn(`machine auth (${t} mode) is active in this environment and takes precedence for API commands; this login only affects interactive use.`),Lh(e),!e.flags.device&&Xl(e.env))throw new f("A browser login cannot complete in CI.",{exitCode:b.NeedsHuman,hint:"Use a service account (MODELDESK_CLIENT_ID and MODELDESK_CLIENT_SECRET), or auth login --device."});let n=Ar(e),r={info:a=>e.io.err(ye(`${a}
150
+ `))},o=e.flags.device?await bg(n,r):await xi(n,r),s=new Ve,i=Ai(o,void 0,Date.now());return i?await s.save(n.host,i):(await s.clearHost(n.host),e.warn("the server returned no refresh token, so later commands will re-open the browser each time instead of running unattended.")),{result:{host:n.host,identity:Oi(o.accessToken),refreshTokenStored:!!o.refreshToken}}},render:({host:e,identity:t})=>{let n=t?` as ${t}`:"";return`Logged in to ${e}${n}.`}});var Ng=J({path:["auth","logout"],effect:"local",summary:"Remove the stored credential for the active host",examples:["modeldesk auth logout","modeldesk auth logout --host modeldesk.io"],description:"Removes the refresh token stored for the host. Machine credentials in the environment are untouched.",run:async e=>{let t=Ye(e.env);t&&e.warn(`machine auth (${t} mode) is active in this environment and takes precedence for API commands; this logout does not remove machine credentials.`);let n=Ar(e);return{result:{host:n.host,removed:await new Ve().clearHost(n.host)}}},render:({host:e,removed:t})=>t?`Logged out of ${e}.`:`No stored credential for ${e}.`});var Ql=class{constructor(t,n,r,o={}){this.instance=t;this.mode=n;this.mint=r;this.now=o.now??Date.now,this.discover=o.discover??on}instance;mode;mint;now;discover;accessToken;accessTokenExpiresAt=0;endpoints;inflight;async getAccessToken(){return this.accessToken&&this.now()<this.accessTokenExpiresAt-Po?this.accessToken:(this.inflight||(this.inflight=this.mintFresh().finally(()=>{this.inflight=void 0})),this.inflight)}async mintFresh(){let{tokenEndpoint:t}=await this.getEndpoints(),n;try{n=await this.mint(t)}catch(r){throw kO(r,this.mode)}if(n.expiresInSeconds<=0)throw new f("The token response did not include a token lifetime (expires_in), so the machine token cannot be cached. This indicates a server problem.");return this.accessToken=n.accessToken,this.accessTokenExpiresAt=this.now()+n.expiresInSeconds*1e3,n.accessToken}async getEndpoints(){return this.endpoints||(this.endpoints=await this.discover(this.instance.issuer)),this.endpoints}},RO=async(e,t,n)=>{let r;try{r=await fetch(`${e}&audience=${encodeURIComponent(n)}`,{headers:{Authorization:`bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(3e4)})}catch(s){throw new f(`Could not reach the GitHub OIDC token endpoint (${s.message}).`,b.Transient)}if(!r.ok)throw new f(`The GitHub OIDC token request failed (${r.status} ${r.statusText}). Check that the workflow grants 'permissions: id-token: write'.`);let o=await r.json().catch(()=>{});if(!o?.value)throw new f("The GitHub OIDC token response did not include a token value. Check that the workflow grants 'permissions: id-token: write'.");return o.value},Mi=(e,t,n={})=>{let r=t.mode==="secret"?o=>pg(o,{clientId:t.clientId,clientSecret:t.clientSecret}):async o=>fg(o,await RO(t.oidcRequestUrl,t.oidcRequestToken,e.issuer));return new Ql(e,t.mode,r,n)},kO=(e,t)=>{if(!(e instanceof sn)||!e.oauthError)return e;if(t==="secret")return e.oauthError==="invalid_client"?new f(`${e.message} ${Oh}`):e;if(e.errorDescription===void 0)return e.oauthError==="invalid_grant"?new f(`${e.message} ${Mh}`):e;let n=Nh[e.errorDescription];return n?new f(`${e.message} \u2014 ${n}`):e};var Pg="Run 'modeldesk auth login'.",Dg=J({path:["auth","status"],effect:"read",summary:"Show the active host, logged-in identity, and token validity",examples:["modeldesk auth status","modeldesk auth status --host modeldesk.io --json"],description:"Proves the credential the CLI would use: a machine mode (service-account secret or GitHub federation) mints a token, interactive mode silently refreshes the stored login. Exits 6 when not logged in or the stored login was rejected, and 7 when the auth server could not be reached.",run:async e=>{let t=Wn(e.env);if(t.mode==="error")throw new f(t.message);let n=e.instance();return e.print(`Host: ${n.host}
151
151
  `),e.print(`API: ${n.apiBase}
152
- `),t.mode==="secret"||t.mode==="federated"?e$(e,n,t):t$(e,n)}}),e$=async(e,t,n)=>{let r={host:t.host,apiBase:t.apiBase,mode:n.mode},s=n.mode==="secret"?{clientId:n.clientId,secretFingerprint:Wu(n.clientSecret)}:{repository:e.env.GITHUB_REPOSITORY??"unknown",ref:e.env.GITHUB_REF??"unknown"};n.mode==="secret"?e.print(`Auth: service account (secret mode), client ${s.clientId}, secret ${s.secretFingerprint}
153
- `):e.print(`Auth: federated (GitHub Actions), repository ${s.repository}, ref ${s.ref}
154
- `);let o=await Wo(t,n).getAccessToken(),i=ts(o)??{},a=typeof i.sub=="string"?i.sub:"unknown",d=typeof i.mdsk_org=="string"?i.mdsk_org:"unknown",l=typeof i.scope=="string"?i.scope.trim():"";return e.print(`Status: credential valid. Account ${a}, organization ${d}.
152
+ `),t.mode==="secret"||t.mode==="federated"?vO(e,n,t):IO(e,n)}}),vO=async(e,t,n)=>{let r={host:t.host,apiBase:t.apiBase,mode:n.mode},o=n.mode==="secret"?{clientId:n.clientId,secretFingerprint:Ah(n.clientSecret)}:{repository:e.env.GITHUB_REPOSITORY??"unknown",ref:e.env.GITHUB_REF??"unknown"};n.mode==="secret"?e.print(`Auth: service account (secret mode), client ${o.clientId}, secret ${o.secretFingerprint}
153
+ `):e.print(`Auth: federated (GitHub Actions), repository ${o.repository}, ref ${o.ref}
154
+ `);let s=await Mi(t,n).getAccessToken(),i=Gn(s)??{},a=typeof i.sub=="string"?i.sub:"unknown",d=typeof i.mdsk_org=="string"?i.mdsk_org:"unknown",l=typeof i.scope=="string"?i.scope.trim():"";return e.print(`Status: credential valid. Account ${a}, organization ${d}.
155
155
  `),e.print(l?`Scopes: ${l}
156
156
  `:`Scopes: enforced server-side from the account's current scopes.
157
- `),{result:{...r,...s,credentialValid:!0,account:a,organization:d,scopes:l}}},t$=async(e,t)=>{let n={host:t.host,apiBase:t.apiBase,mode:"interactive"},r=new tt;if(!r.read(t.host)){let s=`not logged in. ${sh}`;return e.print(`Status: ${s}
158
- `),{result:{...n,credentialValid:!1,problem:s},exitCode:b.NeedsHuman}}try{let s=await new rr(t,{store:r,allowBrowserLogin:!1}).refreshNow();if(!s)throw new p("The stored credential was rejected.",b.NeedsHuman);let o=Bo(s),i=o?` as ${o}`:"";return e.print(`Status: logged in${i} (credential valid).
159
- `),{result:{...n,credentialValid:!0,identity:o}}}catch(s){let o=`the stored credential could not be verified (it may be expired or revoked, or the server is unreachable). ${sh}`;e.print(`Status: ${o}
160
- `);let i=s instanceof p&&s.exitCode===b.Transient;return{result:{...n,credentialValid:!1,problem:o},exitCode:i?b.Transient:b.NeedsHuman}}};var qt=e=>e.superAdmin===!0,dh=async(e,t)=>{let[n,r]=await Promise.all([t.models?e.models.list({ownerId:t.ownerId,metamodel:t.metamodel}):void 0,t.metamodels?e.metamodelModels.list():void 0]),s=new Set((r?.items??[]).map(o=>o.id));return[...(n?.items??[]).filter(o=>!s.has(o.id)).map(o=>({model:o,kind:"model"})),...(r?.items??[]).map(o=>({model:o,kind:"metamodel"}))]},ih=e=>{let t;return()=>t??=e()},ah=new WeakMap,oe=(e,t)=>{let n=ah.get(e)??new Map;ah.set(e,n);let r=n.get(t);if(r!==void 0)return r;let s=async()=>t,o=ih(async()=>e.api().models.identity(await s())),i=ih(async()=>e.api().branches.list(await s())),a={id:s,identity:o,branches:i};return n.set(t,a),a};var lh=(e,t,n={})=>{let r=Yr(t);switch(r.mode){case"error":throw new p(r.message);case"secret":case"federated":return Wo(e,r);case"interactive":return new rr(e,{allowBrowserLogin:n.interactive??!0})}};var n$=6e4,ch={unauthorized:"Run 'modeldesk auth login' and try again.",forbidden:"Your account may lack access to this model."},r$={unauthorized:Io.unauthorized,forbidden:Io.forbidden,notFound:Io.notFound},s$=new Set(["type","title","status","detail","instance"]),o$={"change-validation-failed":b.Validation,"draft-target-taken":b.Conflict,"invalid-branch-name":b.Validation,"branch-limit-reached":b.Validation,"ambiguous-merge-base":b.Failure,"invalid-resolution":b.Validation},H=class extends p{status;problem;constructor(t,n,r,s){super(t,s),this.name="ApiError",this.status=n,this.problem=r}},mh=(e,t)=>new tl(e.apiBase,lh(e,t.env,{interactive:t.interactive}),{hints:Ie(t.env)?r$:ch,userAgent:th(t.agentHost)}),tl=class{constructor(t,n,r={}){this.apiBase=t;this.tokens=n;this.hints=r.hints??ch,this.userAgent=r.userAgent}apiBase;tokens;hints;userAgent;async getJson(t,n){return or(await this.request("GET",t,{query:n}),t)}async getJsonIfChanged(t,n,r){let s=await this.request("GET",t,{query:r,ifNoneMatch:n});return s.status===304?{notModified:!0}:{notModified:!1,body:await or(s,t),etag:s.headers.get("etag")??void 0}}async postJson(t,n,r){return or(await this.request("POST",t,{query:r,body:n}),t)}async postJsonWithHeaders(t,n,r){let s=await this.request("POST",t,{query:r,body:n});return{body:await or(s,t),headers:s.headers}}async putJson(t,n,r){return or(await this.request("PUT",t,{query:r,body:n}),t)}async delete(t,n){return or(await this.request("DELETE",t,{query:n}),t)}async getBytes(t,n,r){let s=await this.request("GET",t,{query:r,accept:n});return fh(t,async()=>new Uint8Array(await s.arrayBuffer()))}async accessTokenClaims(){return ts(await this.tokens.getAccessToken())??{}}async request(t,n,r){let s=await this.tokens.getAccessToken(),o=i$(this.apiBase,n,r.query),i={Authorization:`Bearer ${s}`,Accept:r.accept??"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{},...r.body!==void 0?{"Content-Type":"application/json"}:{},...r.ifNoneMatch?{"If-None-Match":r.ifNoneMatch}:{}},a;try{a=await fetch(o,{method:t,headers:i,...r.body!==void 0?{body:JSON.stringify(r.body)}:{},signal:AbortSignal.timeout(n$)})}catch(d){throw new p(`Could not reach ${this.apiBase} (${d.message}).`,{exitCode:b.Transient,hint:"Check the host and that the ModelDesk server is reachable."})}if(a.status===304&&r.ifNoneMatch)return a;if(!a.ok)throw await u$(a,n,this.hints);return a}},fh=async(e,t)=>{try{return await t()}catch(n){throw n instanceof SyntaxError?new p(`The response from ${e} is not JSON (${n.message}).`):new p(`Reading the response from ${e} failed (${n.message}).`,{exitCode:b.Transient})}},or=(e,t)=>e.status===204||e.headers.get("content-length")==="0"?Promise.resolve(void 0):fh(t,()=>e.json()),i$=(e,t,n)=>{let r=new URL(t,e);if(n)for(let[s,o]of Object.entries(n))o!==void 0&&r.searchParams.set(s,o);return r.toString()},a$=(e,t)=>{let n=t===void 0?void 0:o$[t];return n!==void 0?n:e===401?b.NeedsHuman:e===404?b.NotFound:e===409?b.Conflict:e===429||e>=500?b.Transient:b.Failure},d$=e=>{if(!e||e==="about:blank")return;let t="/problems/",n=e.lastIndexOf(t);return n===-1?e:e.slice(n+t.length)},l$=async e=>{try{if((e.headers.get("content-type")??"").includes("json")){let n=await e.json();if(n!==null&&typeof n=="object"&&!Array.isArray(n))return n}}catch{}},c$=e=>Object.fromEntries(Object.entries(e??{}).filter(([t])=>!s$.has(t))),m$="Run 'modeldesk model list' to see the ids; 'modeldesk model list --kind metamodel' for a metamodel-model.",f$=(e,t)=>t?.startsWith("Model not found")?/^\/(?:metamodel-)?models\/([0-9a-f-]{36})(?:[/?]|$)/.exec(e)?.[1]:void 0,u$=async(e,t,n)=>{let r=await l$(e),s=r?.detail??r?.title,o=s?`${e.status} ${s}`:`${e.status} ${e.statusText}`.trim(),i=d$(r?.type),{requestId:a,...d}=c$(r),l={exitCode:a$(e.status,i),type:i,requestId:typeof a=="string"?a:e.headers.get("x-request-id")??void 0,details:typeof a=="string"||a===void 0?d:{requestId:a,...d}};if(e.status===401)return new H(`Authentication failed (${o}).`,401,r,{...l,hint:n.unauthorized});if(e.status===403)return new H(`Not authorized (${o}).`,403,r,{...l,hint:n.forbidden});let c=e.status===404?f$(t,s):void 0;return c!==void 0?new H(`No model has the id '${c}'.`,404,r,{...l,hint:n.notFound??m$}):e.status===404&&n.notFound?new H(`Not found (${o}).`,404,r,{...l,hint:n.notFound}):new H(`Request to ${t} failed: ${o}`,e.status,r,l)};var p$="@Root",h$=e=>{let t=new Map;for(let[n,r]of Object.entries(e?.relations??{}))for(let s of Object.values(r))for(let o of s){let i=`${n}\0${o.id}`;t.has(i)||t.set(i,t.size)}return t},Bt=e=>{let{elements:t}=e,n=a=>Object.hasOwn(t,a),r=e.rootElementId??Object.values(t).find(a=>a.type===p$)?.id;if(r===void 0||!n(r))throw new p("The model read carries no root element, so its tree cannot be built.");let s=new Map,o=new Map;for(let[a,d]of Object.entries(e.elementIndexEntries)){if(!n(a))continue;let l=(d.owners??[]).filter(c=>n(c.id));s.set(a,l);for(let c of l){let m=o.get(c.id)??[];m.push({id:a,relation:c.relation}),o.set(c.id,m)}}for(let[a,d]of o){let l=h$(t[a]),c=m=>l.get(`${m.relation}\0${m.id}`)??Number.MAX_SAFE_INTEGER;d.sort((m,f)=>c(m)-c(f))}let i=e.elementLabels??{};return{rootId:r,element:a=>n(a)?t[a]:void 0,label:a=>Object.hasOwn(i,a)?i[a]:void 0,owners:a=>s.get(a)??[],children:a=>o.get(a)??[]}},kn=e=>e.startsWith("@"),ir={internal:{type:"boolean",description:"Include the platform's internal `@` elements."}},nl=e=>e.replace(/[\\/]/g,t=>`\\${t}`),nt=(e,t={})=>{let n=c=>{let m=e.element(c);return m!==void 0&&(t.internal===!0||!kn(m.type))},r=c=>{let m=new Set;return e.children(c).filter(f=>m.has(f.id)?!1:(m.add(f.id),!0))},s=c=>{let m=e.label(c);return m===void 0||m.trim()===""?void 0:m},o=new Map,i=c=>{let m=o.get(c);if(m!==void 0)return m;let f=new Map;for(let{id:g}of r(c)){let u=s(g);u!==void 0&&n(g)&&f.set(u,(f.get(u)??0)+1)}return o.set(c,f),f},a=(c,m)=>{let f=s(m);return f===void 0||(i(c).get(f)??0)>1?m:nl(f)},d=new Map,l=(c,m,f,g)=>{let u=e.element(c.id);if(u===void 0||!n(c.id)||t.maxDepth!==void 0&&f>t.maxDepth)return[];let h=g===""?a(m,c.id):`${g}/${a(m,c.id)}`,y=d.get(c.id);y===void 0&&d.set(c.id,h);let k=y===void 0?r(c.id).flatMap(E=>l(E,c.id,f+1,h)):[],S=t.types===void 0||t.types.has(u.type);if(!S&&k.length===0)return[];let I=e.label(c.id);return[{id:c.id,...I===void 0?{}:{label:I},type:u.type,depth:f,parentId:m,relation:c.relation,path:h,...e.owners(c.id).length>1?{multiOwned:!0}:{},...y===void 0?{}:{subtreeAt:y},...S?{}:{context:!0}},...k]};return d.set(e.rootId,""),r(e.rootId).flatMap(c=>l(c,e.rootId,1,""))},Wt=e=>{let t=new Set;return e.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))};var wt={kinds:["draft","head","branch","commit"],default:"working"},ar={kinds:["draft","head","branch"],default:"working"},sl={kinds:["draft","head","branch"],default:"head"},be={kinds:["draft","head","branch"],default:"working"},Cn={kinds:["head","branch"],default:"head"},bt={kinds:["branch"],required:!0},ol={kinds:["branch"],default:"draft"},uh={kinds:["commit"],default:"main"},ph={kinds:["release","branch"],required:!0,names:{noun:"A dependency",listing:"modeldesk pin list <model>"}},hh={noun:"A metamodel",listing:"modeldesk metamodel list"},Uo={kinds:["release"],default:"main",names:hh},gh={kinds:[],default:"main",names:hh},Ho={kinds:["release"],default:"main",names:{noun:"An extension",listing:"modeldesk metamodel extensions <metamodel>"}},fe={kinds:[],default:"main"},yh="ref-not-found",g$=e=>e instanceof H&&(e.status===404||e.type===yh),Ut=async e=>{try{return await e()}catch(t){if(g$(t))return;throw t}},Go=e=>({id:e.branch.id,name:e.branch.name,main:!0,head:e.branch.head.id}),rt=e=>({id:e.id,name:e.name,main:e.main,head:e.head.id}),y$=(e,t)=>e!==void 0&&e.headCommitId!==e.baselineCommitId?{kind:"draft",draft:e}:{kind:"branch",branch:t},w$={working:{kind:"working"},head:{kind:"head"},main:{kind:"branch",name:"main"},draft:{kind:"draft"}},En=(e,t)=>e.localeCompare(t,void 0,{sensitivity:"accent"})===0,il="branch-gone",b$=(e,t,n)=>new p(`Branch ${w(t.name)} (${t.id}) of ${w(e)} is gone`+(n===void 0?".":`; the branch named ${w(n.name)} now is another one (${n.id}), and it is not taken for it.`),{exitCode:b.NotFound,type:il,details:{branch:{id:t.id,name:t.name},...n&&{namesake:{id:n.id,name:n.name}}}}),rl=(e,t={})=>new p(e,{exitCode:b.NotFound,type:yh,...t}),Z=async(e,t,n)=>{$d(t,n);let r=e.api(),s=oe(e,t.model),o=await s.id(),[i,a]=await Promise.all([s.identity(),Ut(()=>r.models.draft(o))]),d=Go(i),l=async y=>{if(y===d.id)return d;let k=(await s.branches()).find(S=>S.id===y);return k===void 0?void 0:rt(k)},c=async y=>{let k=await l(y);if(k===void 0)throw rl(`Your draft of ${w(i.name)} targets a branch that is gone (${y}).`,{hint:"Discard the draft with 'modeldesk draft discard', or address the model at a branch."});return k},m=async y=>{if(En(y,d.name))return d;let k=await s.branches(),S=k.find(I=>En(I.name,y));if(S===void 0)throw rl(`${w(i.name)} has no branch named '${w(y)}'.`,{details:{branches:k.map(I=>I.name)}});return rt(S)},f=a===void 0?void 0:{...a,target:await c(a.targetRefId)},g=f?.target??d,u=t.ref.kind==="working"&&"default"in n?w$[n.default]:t.ref,h=await(async()=>{switch(u.kind){case"working":return y$(f,g);case"head":return{kind:"branch",branch:g};case"draft":if(f===void 0)throw rl(`You hold no draft of ${w(i.name)}.`,{hint:"Leave the ref out to read the branch, or stage a change to open a draft."});return{kind:"draft",draft:f};case"branch":return{kind:"branch",branch:await m(u.name)};case"branch-id":{let y=await l(u.id);if(y===void 0){let k=(await s.branches()).find(S=>En(S.name,u.name));throw b$(i.name,u,k&&rt(k))}return{kind:"branch",branch:y}}case"commit":return{kind:"commit",id:u.id};case"release":throw new p(`A release ref is not readable here (${t.text}).`,{exitCode:b.Usage})}})();return{id:o,name:i.name,ref:h,main:d,working:g,draft:f,...n.kinds.length===0&&!g.main?{note:`reads main; your draft targets ${g.name}`}:{}}},Ve=({ref:e})=>{if(e.kind!=="branch")throw new Error(`A branch-only slot resolved to a ${e.kind}.`);return e.branch},st=e=>{switch(e.kind){case"branch":return{ref:e.branch.id};case"draft":return{ref:e.draft.id};case"commit":return{commit:e.id}}},k$=e=>{switch(e.kind){case"branch":return{kind:"branch",id:e.branch.id,name:e.branch.name};case"draft":return{kind:"draft",id:e.draft.id,branch:{id:e.draft.target.id,name:e.draft.target.name}};case"commit":return{kind:"commit",id:e.id}}},de=({ref:e,draft:t,note:n})=>{let r=k$(e),s=t!==void 0&&e.kind==="branch"&&e.branch.id!==t.target.id;return{...r,...s?{draftIgnored:!0}:{},...n===void 0?{}:{note:n}}},E$=(e,t)=>{switch(e.kind){case"draft":return`Reading your draft of ${t}, aimed at ${w(e.branch.name)}.`;case"branch":return`Reading branch ${w(e.name)} of ${t}.`;case"commit":return`Reading commit ${e.id} of ${t}.`}},$e=(e,t)=>{let n=w(t.name);return[E$(e,n),...e.draftIgnored?["Your draft aims at another branch and was not read."]:[],...e.note?[`${e.note[0].toUpperCase()}${e.note.slice(1)}.`]:[]].join(" ")},dr=async(e,t,n)=>{let r=await Z(e,t,n),s=await e.api().models.get(r.id,{...st(r.ref),expand:["labels"]});return{model:{id:r.id,name:r.name},ref:de(r),resolved:r,read:s,tree:Bt(s)}};var al="draft-target-taken",ns=(e,t,n,r)=>{let s=w(e.name),o=t.changeCount>0,i=w(t.target.name);return new p(`Your draft of ${s} aims at ${i}`+(o?` and holds ${P(t.changeCount,"staged change")}`:" and holds no staged change")+`, so ${r}.`,{exitCode:b.Conflict,type:al,hint:o?`Commit or discard your changes on ${i} first: 'modeldesk draft commit ${e.id}@${i}' or 'modeldesk draft discard ${e.id}@${i}'. Or address ${e.id}@${i} to work where your draft aims.`:`Run 'modeldesk draft open ${e.id}@${w(n.name)}', which loses nothing.`,details:{targetRefId:t.target.id,targetRefName:t.target.name,requestedRefId:n.id,requestedRefName:n.name,changeCount:t.changeCount}})},ot=async(e,t)=>{let n=await Z(e,t,be),{ref:r,draft:s}=n;if(r.kind==="commit")throw new p(`A change cannot be staged at a commit (${t.text}); address a branch.`,{exitCode:b.Usage,type:"ref-unsupported"});let o=r.kind==="branch"?r.branch:r.draft.target;if(s!==void 0&&s.target.id!==o.id)throw ns(n,s,o,`nothing was staged on ${w(o.name)}`);let i=await e.api().models.get(n.id,{...st(s?{kind:"draft",draft:s}:{kind:"branch",branch:o}),expand:["labels"]});return{address:t,model:{id:n.id,name:n.name},branch:o,draft:s,resolved:n,read:i,tree:Bt(i),head:i.branch.head.id}};var W=(e,t)=>{if(t.kind==="import")return`${e.appBase}/imports/${encodeURIComponent(t.importId)}`;let n=`${e.appBase}/models/${encodeURIComponent(t.modelId)}`;switch(t.kind){case"model":return n;case"element":return`${n}/editor?elementId=${encodeURIComponent(t.elementId)}`;case"commit":return`${n}/history/${encodeURIComponent(t.commitId)}`}};var C$=e=>({id:e.id,createdAt:e.createdAt,...e.message?{message:e.message}:{},...e.requestId?{requestId:e.requestId}:{},actionTypes:[...new Set(e.actions.map(t=>t.type))].sort(),elementIds:e.actions.reduce((t,n)=>({...t,[n.type]:[...t[n.type]??[],...n.elementIds??[]]}),{})}),Rn=async(e,t,n,r)=>{let s=[],o;for(;;){let i=r===void 0?rs:Math.min(rs,r-s.length),a=(await e.models.commits(t,{ref:n,limit:i,cursor:o})).items;if(s.push(...a.map(C$)),a.length<i||r!==void 0&&s.length>=r)return s;o=a.at(-1)?.id}},_e={...Ju(ol),description:"The model's id, from model list, or dataset/<id>. Your draft wherever it aims; a model's @<branch> asserts where it aims, and a draft aimed elsewhere is refused (exit 5) with nothing done."},R$=5,rs=100,bh=async(e,t,n)=>{let r;for(let s=0;s<R$;s++){let o=await e(r);for(let i of o){if(i.requestId===t)return i;if(i.id===n)return}if(o.length<rs)return;r=o.at(-1)?.id}},Vo=(e,t)=>({url:W(e.instance(),{kind:"model",modelId:t}),changes:(n,r)=>Rn(e.api(),t,n,r)}),ss=async(e,t)=>{let n=e.api(),r=oe(e,t),s=await r.identity(),o=s.id,i=n.drafts.model,a=async d=>{if(d===s.branch.id)return Go(s);let l=(await r.branches()).find(c=>c.id===d);if(l===void 0)throw new p(`Your draft of ${w(s.name)} targets a branch that is gone (${d}).`,{exitCode:b.NotFound,type:"ref-not-found",hint:"Discard the draft with 'modeldesk draft discard', or address the model at a branch."});return rt(l)};return{ref:{kind:"model",id:o,name:s.name},url:W(e.instance(),{kind:"model",modelId:o}),read:()=>Ut(()=>n.models.draft(o)),workingBranch:async d=>{let l=d===void 0?Go(s):await a(d.targetRefId);return{branch:l,head:l.head}},branch:a,undo:async d=>({headCommitId:(await i.undo(o,d)).commitId}),commit:async d=>{let l=await i.commit(o,d),{id:c,message:m,requestId:f,createdAt:g,actionTypes:u}=l.commit;return{branch:await a(l.refId),commit:{id:c,...m?{message:m}:{},...f?{requestId:f}:{},createdAt:g,actionTypes:u},draftHeadCommitId:l.draftHeadCommitId}},rebase:async d=>{let l=await i.rebase(o,d);return{draft:l.draft,dropped:l.dropped,closureChanged:l.closureChanged,schemaChanged:l.schemaChanged}},discard:d=>i.discard(o,d),changes:(d,l)=>Rn(n,o,d,l),findLanding:async(d,l)=>{let c=await bh(async m=>(await n.models.commits(o,{ref:l.targetRefId,limit:rs,cursor:m})).items,d,l.baselineCommitId);return c&&{id:c.id,message:c.message,requestId:c.requestId,createdAt:c.createdAt,actionTypes:[...new Set(c.actions.map(m=>m.type))].sort()}}}},S$=async(e,t)=>{let n=e.api(),r=await n.datasets.get(t),s=n.drafts.dataset,o=async(i,a)=>(await n.datasets.commits(r.id,{limit:i,cursor:a})).items??[];return{ref:{kind:"dataset",id:r.id,name:r.name},read:()=>Ut(()=>s.get(r.id)),branch:async i=>({id:i}),workingBranch:async i=>{let[a]=await o(1);if(a===void 0)throw new p(`Dataset ${r.name} has no commits, so its branch head is unknown.`);return{branch:i===void 0?void 0:{id:i.targetRefId},head:a.id}},undo:async i=>{let{draft:a}=await s.undo(r.id,i);return{headCommitId:a.headCommitId,changeCount:a.changeCount}},commit:async i=>{let{refId:a,commit:d}=await s.commit(r.id,i);return{branch:{id:a},commit:{id:d.id,...d.message?{message:d.message}:{},...d.requestId?{requestId:d.requestId}:{},...d.createdAt?{createdAt:d.createdAt}:{},...d.rowsChanged===void 0?{}:{rowsChanged:d.rowsChanged}}}},rebase:async i=>{let a=await s.rebase(r.id,i);return{draft:a.draft,dropped:a.dropped.map(d=>({commitId:d.id,...d.requestId?{requestId:d.requestId}:{},...d.message?{message:d.message}:{},...d.rowsChanged===void 0?{}:{rowsChanged:d.rowsChanged}}))}},discard:i=>s.discard(r.id,i),findLanding:async(i,a)=>{let d=await bh(l=>o(rs,l),i,a.baselineCommitId);return d&&{id:d.id,message:d.message,requestId:d.requestId,rowsChanged:d.rowsChanged}}}},v$=async(e,t,n)=>{let r=await Z(e,t,ol),{draft:s,ref:o}=r;if(s!==void 0&&o.kind==="branch"&&s.target.id!==o.branch.id)throw ns(r,s,o.branch,`'modeldesk ${n}' did nothing on ${w(o.branch.name)}`)},wh=new WeakMap,je=e=>{let t=wh.get(e);if(t!==void 0)return t;let{resource:n}=e.args,r=n.kind==="dataset"?S$(e,n.id):(async()=>(n.address.ref.kind==="branch"&&await v$(e,n.address,e.commandName),ss(e,n.address.model)))();return wh.set(e,r),r},I$=e=>{if(e instanceof p&&e.type==="feature-not-enabled"){let{feature:t,organizationId:n}=e.details,r=typeof t=="string"?`The '${t}' feature`:"A feature this change needs",s=typeof n=="string"?` (${n})`:"";return new p(`${r} is not enabled for this organization${s}.`,{type:e.type,details:e.details,requestId:e.requestId,hint:"Ask ModelDesk to enable the feature for your organization, or leave out the change that needs it."})}return e},ee=async e=>{try{return await e()}catch(t){throw I$(t)}},ue=e=>`${e.kind} ${w(e.name)}`,Ke=500;var Eh=({id:e,name:t})=>({id:e,name:t}),kh=({id:e,targetRefId:t,baselineCommitId:n,headCommitId:r,changeCount:s,createdAt:o,updatedAt:i},a)=>({id:e,targetRefId:t,baselineCommitId:n,headCommitId:r,changeCount:s,createdAt:o,updatedAt:i,target:Eh(a)}),dl=async(e,t,n)=>{let{draft:r}=t;if(r?.target.id===n.id)return{draft:kh(r,n),opened:!1};if(r!==void 0&&r.changeCount>0)throw ns(t,r,n,`no draft was opened on ${w(n.name)}`);let s=e.api().drafts.model;if(r!==void 0)try{await s.discard(t.id,r.headCommitId)}catch(i){if(!(i instanceof H&&i.status===404))throw i}let o=await s.open(t.id,n.id);return{draft:kh(o,n),opened:!0,...r===void 0?{}:{reopenedFrom:Eh(r.target)}}},ll=(e,t)=>{let n=w(e.name),r=w(t.draft.target.name);return t.opened?t.reopenedFrom===void 0?`Opened your draft of ${n} on ${r}.`:`Discarded your empty draft of ${n} on ${w(t.reopenedFrom.name)} and opened one on ${r}.`:`Your draft of ${n} already aims at ${r}; it was left as it was.`},Ch=O({path:["draft","open"],effect:"stage",summary:"Aim your draft of a model at a branch",description:"Opens your draft of the model on the branch, so the writes that name no branch stage there. A draft already on the branch is left as it is (opened: false). A draft on another branch that holds nothing is discarded and opened here, which loses nothing (reopenedFrom names where it was). A draft holding staged changes on another branch is refused (exit 5): commit or discard them first. Only this command and 'branch create --open' discard a draft on your behalf. A dataset has no branches, so it takes a model.",positionals:[_(bt)],examples:["modeldesk draft open <model>@feat/x","modeldesk draft open <model>@agent/tidy-names --json"],run:async e=>ee(async()=>{let t=await Z(e,e.args.model,bt),n=await dl(e,t,Ve(t));return{result:{model:{id:t.id,name:t.name},ref:{kind:"draft",id:n.draft.id,branch:n.draft.target},...n}}}),render:e=>ll(e.model,e)});var $$={draft:"'@draft' in an address means your draft",head:"'@head' in an address means your working branch head",main:"'@main' in an address means the main branch"},x$=`An agent commits without MODELDESK_ALLOW_COMMIT=1 only on a branch named ${bn}\u2026`,M$=e=>{let t=$$[e.toLowerCase()]??(V(e)?"a UUID in an address is a commit":void 0);if(t!==void 0)throw new p(`A branch cannot be named '${w(e)}': ${t}.`,{exitCode:b.Validation,type:"invalid-branch-name",hint:"Pick another name.",details:{rule:"reserved-name"}})},A$=(e,t,n,r)=>{let{branch:s}=e;return s===void 0?`Would create branch ${t} of ${n} from ${r}; nothing was created (dry run).`:e.dryRun?`Branch ${t} of ${n} exists (${s.id}); --exist-ok would use it; nothing was created (dry run).`:e.created?`Created branch ${t} of ${n} from ${r}: ${s.id}`:`Branch ${t} of ${n} already exists: ${s.id}`},Rh=O({path:["branch","create"],effect:"create",summary:"Create a branch of a model",description:`Creates a branch at the head of your working branch (the one your draft aims at, else main), or of the branch the address names. A name another branch already has (in any case) exits 5 unless --exist-ok, which answers that branch with created: false, so a retried script converges. A name the server refuses exits 4 naming the rule; so do 'draft', 'head', 'main' and a UUID, which an address cannot reach as a branch. --open then aims your draft at the branch as draft open does, discarding an empty draft elsewhere. An agent's own branch is named ${bn}<topic>: a draft landing there needs no MODELDESK_ALLOW_COMMIT=1, since a person reviews and merges the branch in the app.`,positionals:[_(Cn),{name:"name",type:"string",required:!0,description:"The new branch name."}],flags:{open:{type:"boolean",description:"Aim your draft at the branch, as draft open does."},"exist-ok":{type:"boolean",description:"Answer the branch that already has the name (created: false) instead of exiting 5."}},dryRun:!0,examples:["modeldesk branch create <model> feat/assoc-ends","modeldesk branch create <model> agent/tidy-names --open --json","modeldesk branch create <model>@feat/x feat/x-followup --exist-ok"],run:async e=>ee(async()=>{let t=e.args.name.trim();M$(t);let n=e.args.model,r=await Z(e,n,Cn),s=Ve(r),o={id:r.id,name:r.name},i=e.agentHost!==void 0&&!t.toLowerCase().startsWith(bn)?x$:void 0;i!==void 0&&!e.globals.json&&e.warn(i);let a={model:o,name:t,from:{id:s.id,name:s.name},...i?{note:i}:{}},d=async()=>{let f=(await oe(e,n.model).branches()).find(g=>En(g.name,t));return f===void 0?void 0:rt(f)};if(e.globals.dryRun){let f=await d();if(f!==void 0&&!e.flags["exist-ok"])throw new p(`${w(o.name)} already has a branch named '${w(f.name)}'.`,{exitCode:b.Conflict,type:"branch-name-taken",hint:"Pick another name, or pass --exist-ok to use that branch."});return{result:{...a,...f?{branch:f}:{},created:!1,dryRun:!0}}}let l=await(async()=>{try{let f=await e.api().branches.create(o.id,{name:t,from:s.id});return{branch:rt(f),created:!0}}catch(f){let g=f instanceof p&&f.type==="branch-name-taken"&&e.flags["exist-ok"]?await d():void 0;if(g===void 0)throw f;return{branch:g,created:!1}}})(),c=e.flags.open?await dl(e,r,l.branch):void 0;return{result:{...a,...l,...c?{open:c}:{}}}}),render:e=>{let t=w(e.model.name),n=w(e.name),r=w(e.from.name);return[A$(e,n,t,r),...e.open?[ll(e.model,e.open)]:[]].join(`
161
- `)}});var it=async(e,t,n)=>{if(!e.globals.yes){if(!e.interactive)throw new p(`${n} needs confirmation, and this run cannot ask for it. Nothing was changed.`,{exitCode:b.NeedsHuman,hint:"Re-run with --yes to confirm."});if(!await e.confirm(t))throw new p(`${n} was cancelled. Nothing was changed.`)}};var T$=(e,t,n)=>{let r=n?Math.max(t,1):t;return r===0?`Deleting ${e} deletes only the branch. No one has a draft on it.`:r===1?`Deleting ${e} also deletes ${n?"your draft":"the one draft"} on it. It cannot be recovered.`:`Deleting ${e} also deletes the ${r} drafts on it${n?", yours among them":""}. They cannot be recovered.`},O$=(e,t)=>t===0?`Everything committed on ${e} is on main.`:t===1?`1 commit on ${e} is not on main. It is lost with the branch.`:`${t} commits on ${e} are not on main. They are lost with the branch.`,N$="modeldesk branch delete --help",L$=(e,t)=>{if(!(e instanceof p))return e;let n={exitCode:e.exitCode,type:e.type,requestId:e.requestId,details:e.details};if(e.type==="branch-has-drafts"){let r=Number(e.details.draftCount),s=r===1?"a draft":`${r} drafts`;return new p(`Other users hold ${s} with staged changes on ${t}, so it was not deleted.`,{...n,hint:"Pass --force to delete the branch with their drafts, which cannot be recovered."})}if(e.type==="branch-unmerged"){let r=Number(e.details.unmergedCommitCount),s=r===1?"1 commit":`${r} commits`;return new p(`${s} on ${t} ${r===1?"is":"are"} not on main, so it was not deleted.`,{...n,hint:"Merge it into main first to keep them, or pass --force to lose them with the branch."})}return e instanceof H&&e.status===403?new p(e.message,{...n,hint:"Deleting a branch needs the model:delete scope, which model:write does not imply, since other users' drafts are lost with it. Ask an owner of the model to delete it, or sign in with a token that carries that scope."}):e},Sh=O({path:["branch","delete"],effect:"destroy",summary:"Delete a branch with every draft on it",description:"Deletes the branch together with every draft that aims at it, whoever owns it. It restates how many drafts go with it and how many of its commits main does not reach, and asks at a terminal; anywhere else it needs --yes. While other users' drafts on it hold staged changes, or it holds commits main does not reach, the delete exits 5 unless --force, which loses them. main cannot be deleted (exit 2). It needs the model:delete scope. --dry-run restates what would go and deletes nothing; the server then checks neither the refusals nor the scope. Under an agent host deleting a branch is left to a person (exit 6).",positionals:[_(bt)],dryRun:!0,flags:{force:{type:"boolean",description:"Delete even when other users' drafts on the branch hold staged changes, or main lacks its commits."}},examples:["modeldesk branch delete <model>@feat/x --dry-run","modeldesk branch delete <model>@feat/x --yes","modeldesk branch delete <model>@feat/x --force --yes"],run:async e=>{let t=e.args.model,n=await Z(e,t,bt),r=Ve(n),s=w(r.name);if(r.main)throw $(`${s} is the main branch of ${w(n.name)}, which cannot be deleted.`,N$);let o=(await oe(e,t.model).branches()).find(g=>g.id===r.id),i=o?.draftCount??0,a=o?.unmergedCommitCount??0,d=n.draft?.target.id===r.id;e.print(`${T$(s,i,d)}
162
- ${O$(s,a)}
163
- `);let{force:l}=e.flags,{dryRun:c}=e.globals,m={model:{id:n.id,name:n.name},branch:{id:r.id,name:r.name},deleted:!c,dryRun:c,forced:l,draftCount:i,unmergedCommitCount:a};if(c)return{result:m};let f=`branch ${s} of ${w(n.name)}`;await it(e,`Delete ${f}?`,`Deleting ${f}`);try{await e.api().branches.delete(n.id,r.id,l)}catch(g){throw L$(g,s)}return{result:m}},render:e=>{let t=`branch ${w(e.branch.name)} of ${w(e.model.name)}`;return e.dryRun?`Would delete ${t}. Dry run: nothing was deleted.`:`Deleted ${t}.`}});var P$={ADDED:"+",MODIFIED:"~",REMOVED:"-"},vh=e=>e===void 0||e.length===0?"(none)":e.map(t=>w(typeof t=="string"?t:JSON.stringify(t))).join(", "),Ih=(e,t)=>e[t]===void 0?t:`${w(e[t])} (${t})`,cl=(e,t)=>[` ${P$[e.diffType]} ${w(e.elementName??t[e.elementId]??"(no name)")} (${e.elementType}) ${e.elementId}`,...Object.entries(e.attributes??{}).map(([n,r])=>` ${n}: ${vh(r.before)} -> ${vh(r.after)}`),...Object.entries(e.relations??{}).map(([n,r])=>[` ${n}:`,...(r.addedTargets??[]).map(s=>`+ ${Ih(t,s)}`),...(r.removedTargets??[]).map(s=>`- ${Ih(t,s)}`)].join(" "))],D$=(e,t)=>{let n=e.requestId?` [${e.requestId}]`:"";return` ${t+1}. ${e.id} ${e.createdAt} ${e.surface.toUpperCase()} ${w(e.message??"(no message)")}${n} ${e.actionTypes.join(", ")}`},_$=e=>{let t=ue(e.resource);if(e.draft===null)return`You hold no draft of ${t}, so nothing is staged.`;if(e.changes)return[`The staged changes of your draft of ${t}, oldest first:`,...e.changes.length===0?[" none"]:e.changes.map((s,o)=>D$(s,o))].join(`
164
- `);if(e.rows){let{added:s,changed:o,removed:i}=e.rows;return[`Your draft of ${t} against its baseline:`,...s.map(a=>` + ${a}`),...o.map(a=>` ~ ${a}`),...i.map(a=>` - ${a}`),...s.length+o.length+i.length===0?[" no rows differ"]:[]].join(`
165
- `)}let n=e.names??{},r=e.elements??[];return[`Your draft of ${t} against its baseline:`,...r.length===0?[" no elements differ"]:r.flatMap(s=>cl(s,n))].join(`
166
- `)},$h=O({path:["draft","diff"],effect:"read",summary:"Show what your draft changes",description:"Shows your draft's net difference from its baseline: per element of a model (added, modified with each changed attribute and relation, removed), per row of a dataset. With --changes it lists the staged changes instead, oldest first, each with its message, request id and the surface it came from (WEB for the app, CLI, MCP, or API for anything else). A dataset serves no list of its staged changes, so --changes takes a model.",positionals:[_e],flags:{changes:{type:"boolean",description:"List the staged changes, oldest first, instead of the difference."}},examples:["modeldesk draft diff <model>","modeldesk draft diff <model> --changes --json"],run:async e=>ee(async()=>{if(e.flags.changes&&e.args.resource.kind==="dataset")throw $("A dataset's draft serves no list of its staged changes, so --changes takes a model.","modeldesk draft diff --help");let t=await je(e),n=await t.read(),r={resource:t.ref,draft:n??null};if(n===void 0)return{result:r};let s=e.api();if(e.flags.changes&&t.changes){let i=(await t.changes(n.id)).reverse().map(a=>({id:a.id,createdAt:a.createdAt,...a.message?{message:a.message}:{},...a.requestId?{requestId:a.requestId}:{},surface:Dt(a.requestId),actionTypes:a.actionTypes}));return{result:{...r,changes:i}}}if(t.ref.kind==="dataset"){let i=await s.drafts.dataset.diff(t.ref.id);return{result:{...r,rows:{added:i.added??[],changed:i.changed??[],removed:i.removed??[]}}}}let o=await s.drafts.model.diff(t.ref.id);return{result:{...r,elements:o.elements,names:o.resolvedNames??{}}}}),render:_$});var xh=O({path:["branch","diff"],effect:"read",summary:"Show what a branch changed since it diverged",description:"Shows the branch's net change since it diverged from the base branch (main unless --base), per element as draft diff shows a draft: what merging it into the base would bring before conflicts. The branch is your working branch unless the address names one. Two branches each merged into the other have no single point where they split and exit 1, naming the candidate commits.",positionals:[_(Cn)],flags:{base:{type:"string",placeholder:"branch",description:"The branch to compare with, by name; main by default."}},examples:["modeldesk branch diff <model>@feat/x","modeldesk branch diff <model>@feat/x --base feat/y --json"],run:async e=>{let t=e.args.model,n=await Z(e,t,Cn),r=Ve(n),s=e.flags.base===void 0?n.main:Ve(await Z(e,{model:t.model,ref:{kind:"branch",name:e.flags.base},text:`${t.model}@${e.flags.base}`},Cn)),o=await(async()=>{try{return await e.api().branches.diff(n.id,r.id,s.id)}catch(a){if(a instanceof p&&a.type==="ambiguous-merge-base"){let d=Array.isArray(a.details.candidateBaseIds)?a.details.candidateBaseIds:[];throw new p(`${w(r.name)} and ${w(s.name)} were each merged into the other, so they have ${d.length||"several"} equally close common commits and no single point where they split.`,{exitCode:a.exitCode,type:a.type,requestId:a.requestId,details:a.details,hint:"Delete whichever branch holds nothing of its own since the two merges and create it again from the other, or create a new branch from one of them and redo the other changes there."})}throw a}})();return{result:{model:{id:n.id,name:n.name},ref:de(n),branch:{id:r.id,name:r.name,head:o.commitId},base:{id:s.id,name:s.name},...o.parentCommitId?{mergeBaseId:o.parentCommitId}:{},elements:o.elements,names:o.resolvedNames??{}}}},render:e=>{let t=e.mergeBaseId?`, since ${e.mergeBaseId}`:"";return[`${w(e.branch.name)} of ${w(e.model.name)} against ${w(e.base.name)}${t}:`,...e.elements.length===0?[" no elements differ"]:e.elements.flatMap(r=>cl(r,e.names))].join(`
167
- `)}});var j$=["","NAME","HEAD","DRAFTS","UNMERGED","ID"],Mh=O({path:["branch","list"],effect:"read",summary:"List a model's branches",description:"Lists the model's branches, main first, each with its head, how many drafts aim at it (whoever owns them) and how many of its commits main does not reach. The branch your draft aims at is marked working (* in the table): an invocation that names no ref works there, and on main when you hold no draft.",positionals:[_(fe)],listing:{},examples:["modeldesk branch list <model>","modeldesk branch list <model> --json"],run:async e=>{let t=oe(e,e.args.model.model),n=await t.id(),[r,s,o]=await Promise.all([t.identity(),t.branches(),Ut(()=>e.api().models.draft(n))]),i=o?.targetRefId??r.branch.id,a=s.map(l=>({id:l.id,name:l.name,main:l.main,head:l.head.id,draftCount:l.draftCount,unmergedCommitCount:l.unmergedCommitCount,working:l.id===i}));return{result:{model:{id:n,name:r.name},...await e.list(a)}}},render:e=>{let t=e.items.map(n=>[n.working?"*":"",w(n.name),n.head,String(n.draftCount),String(n.unmergedCommitCount),n.id]);return[`Branches of ${w(e.model.name)}:`,...j([j$,...t])].join(`
168
- `)}});import{readFileSync as ix}from"node:fs";import{resolve as ax}from"node:path";var F$=e=>Object.fromEntries(e.map(({key:t,kind:n,base:r,target:s,source:o})=>[t,{kind:n,...r===void 0?{}:{base:r},...s===void 0?{}:{target:s},...o===void 0?{}:{source:o}}])),Th=e=>({elementId:e.elementId,reason:e.reason,target:e.target,source:e.source,fields:F$(e.fields),...e.managedDependencyChanges===void 0?{}:{managedDependencyChanges:e.managedDependencyChanges}}),q$=e=>({elementId:String(e.elementId),rule:e.code,message:e.message,...e.property===void 0?{}:{property:e.property}}),Oh=e=>({conflicts:e.conflicts.map(Th),mergeBaseId:e.mergeBaseId,targetHead:e.targetCommitId,sourceHead:e.sourceCommitId,names:e.resolvedNames,blockers:e.blockers,rejected:[]}),Ah=e=>Array.isArray(e)?e:[],Nh=e=>{let t=e;return{conflicts:Ah(t.conflicts).map(Th),mergeBaseId:String(t.mergeBaseId??""),targetHead:String(t.targetCommitId??""),sourceHead:String(t.sourceCommitId??""),names:t.resolvedNames??{},blockers:[],rejected:Ah(t.rejected).map(q$)}},os=(e,t)=>e[t]===void 0?t:w(e[t]),B$=(e,t)=>{let[n]=e.target.present?e.target.owners:e.source.owners,r=os(t,e.elementId);return n===void 0?r:`${os(t,n)}/${r}`},W$=(e,t)=>{let n=t.rejected.filter(r=>r.elementId===e.elementId).map(r=>({rule:r.rule,message:r.message,...r.property===void 0?{}:{property:r.property}}));return{elementId:e.elementId,label:B$(e,t.names),reason:e.reason,target:e.target,source:e.source,fields:Object.fromEntries(Object.entries(e.fields).map(([r,s])=>[r,{...s}])),...e.managedDependencyChanges===void 0?{}:{managedDependencyChanges:e.managedDependencyChanges},...n.length===0?{}:{rejected:n}}},Lh=e=>e.blockers.length>0?"blocked":e.conflicts.length>0?"conflicts":"clean",ml=(e,t,n,r)=>{let s=new Set(t.conflicts.map(i=>i.elementId)),o=t.rejected.filter(i=>!s.has(i.elementId));return{...e,target:{...e.target,head:t.targetHead},source:{...e.source,head:t.sourceHead},outcome:n,mergeBaseId:t.mergeBaseId,blockers:t.blockers,names:t.names,resolutions:t.conflicts.map(i=>W$(i,t)),...r===void 0?{}:{takeOthers:r},...o.length===0?{}:{rejected:o}}};var te="modeldesk branch merge --help",U$=new Set(["target","source"]),is=e=>U$.has(e),fl=e=>typeof e=="string"?e:JSON.stringify(e)??"undefined",lr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ko=(e,t,n)=>{let r=e[t];if(typeof r!="string"||r==="")throw $(`The resolution file has no '${t}' on ${n}.`,te);return r},Ph=(e,t)=>{let n=e[t];if(!lr(n))throw $(`The resolution file has no '${t}' branch.`,te);return{id:Ko(n,"id",t),head:Ko(n,"head",t)}},H$=(e,t)=>{let{take:n}=e;if(n!=null){if(is(n)||n==="fields")return n;throw $(`The entry for ${t} has take '${fl(n)}'; it takes 'target', 'source' or 'fields'.`,te)}},G$=(e,t)=>{let{fields:n}=e;if(n==null)return{};if(!lr(n))throw $(`The entry for ${t} has 'fields' that is not an object keyed by field.`,te);return Object.fromEntries(Object.entries(n).flatMap(([r,s])=>{let o=lr(s)?s.take:void 0;if(o==null)return[];if(!is(o))throw $(`The field '${r}' of ${t} has take '${fl(o)}'; a field takes 'target' or 'source'.`,te);return[[r,o]]}))},V$=(e,t)=>{if(!lr(e))throw $(`Entry ${t+1} of the resolution file is not an object.`,te);let n=Ko(e,"elementId",`entry ${t+1}`),r=H$(e,n),s=G$(e,n),o=Object.keys(s);if(r!==void 0&&r!=="fields"&&o.length>0)throw $(`The entry for ${n} takes '${r}' whole and also takes fields (${o.join(", ")}); pick one: a side for the element, or 'fields' with a side per field.`,te);return{elementId:n,take:r??(o.length>0?"fields":void 0),fields:s}},Dh=e=>{let t;try{t=JSON.parse(e)}catch(s){throw $(`The resolution file is not JSON (${s.message}).`,te)}if(!lr(t))throw $("The resolution file is not a JSON object.",te);if(!lr(t.model))throw $("The resolution file has no 'model'.",te);let{takeOthers:n}=t;if(n!=null&&!is(n))throw $(`The resolution file has takeOthers '${fl(n)}'; it takes 'target' or 'source'.`,te);let{resolutions:r}=t;if(r!==void 0&&!Array.isArray(r))throw $("The resolution file's 'resolutions' is not a list.",te);return{model:{id:Ko(t.model,"id","model")},target:Ph(t,"target"),source:Ph(t,"source"),...is(n)?{takeOthers:n}:{},entries:(r??[]).map((s,o)=>V$(s,o))}},_h=e=>{let t=e.lastIndexOf("="),n=t===-1?void 0:e.slice(t+1);if(t===-1||!is(n))throw $(`--take takes <element>[#<field>]=target|source, got '${e}'.`,te);let r=e.slice(0,t),s=r.lastIndexOf("#"),o=s===-1?r:r.slice(0,s),i=s===-1?void 0:r.slice(s+1);if(o===""||i==="")throw $(`--take takes <element>[#<field>]=target|source, got '${e}'.`,te);return{element:o,...i===void 0?{}:{field:i},side:n}},jh=(e,t)=>{let n=e.find(s=>s.elementId===t.elementId),r=t.field===void 0?{elementId:t.elementId,take:t.side,fields:{}}:{elementId:t.elementId,take:"fields",fields:{...n?.take==="fields"?n.fields:{},[t.field]:t.side}};return n===void 0?[...e,r]:e.map(s=>s.elementId===t.elementId?r:s)},K$=e=>e.takeOthers===void 0?e.entries.filter(t=>t.take===void 0).map(t=>t.elementId):[],Fh=e=>{let t=K$(e);if(t.length>0){let n=t.length===1?"One entry has":`${t.length} entries have`;throw $(`${n} no take: ${t.join(", ")}. Fill in 'take' on each, or pass --take-others target|source for every entry left open.`,te)}},qh=(e,t)=>{let n=e.entries.flatMap(r=>r.take===void 0?[]:r.take!=="fields"?[{elementId:r.elementId,take:r.take}]:Object.keys(r.fields).length===0?[{elementId:r.elementId,take:"target"}]:[{elementId:r.elementId,take:"fields",fields:r.fields}]);return{source:e.source.id,message:t,expectedHeadId:e.target.head,expectedSourceHeadId:e.source.head,...n.length===0?{}:{resolutions:n},...e.takeOthers===void 0?{}:{takeOthers:e.takeOthers}}};var Bh=String.raw`Separate labels with '/'; inside a label, write '/' as '\/' and '\' as '\\'.`,Y$=e=>{let t=[],n="";for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\"){let o=e[r+1];if(o!=="/"&&o!=="\\")throw new p(String.raw`'${e}' is not an element path: a '\' escapes only '/' or '\'.`,{exitCode:b.Usage,hint:Bh});n+=o,r++}else s==="/"?(t.push(n),n=""):n+=s}if(t.push(n),t[0]===""&&t.shift(),t.at(-1)===""&&t.pop(),t.length===0||t.includes(""))throw new p(`'${e}' is not an element path.`,{exitCode:b.Usage,hint:Bh});return t},Wh=e=>e.map(nl).join("/"),Uh=(e,t,n,r)=>{let s=[...new Set(e.children(t).map(d=>d.id))].filter(d=>r||!kn(e.element(d)?.type??"")),o=s.filter(d=>d.toLowerCase()===n.toLowerCase());if(o.length>0)return o;let i=s.filter(d=>e.label(d)===n);if(i.length>0)return i;let a=n.toLowerCase();return s.filter(d=>e.label(d)?.toLowerCase()===a)},z$=(e,t)=>{let n=e.element(t)?t:t.toLowerCase();if(e.element(n)===void 0)throw new p(`No element ${t} in this model.`,{exitCode:b.NotFound});return n},le=(e,t,n={})=>{let r=n.internal??!1;if(V(t))return z$(e,t);let s=[],o=e.rootId;for(let i of Y$(t)){let a=s.length===0?"at the top of the model":`under '${Wh(s)}'`,d=Uh(e,o,i,r);if(d.length===0){let l=!r&&Uh(e,o,i,!0).length>0;throw new p(`No element labelled '${i}' ${a}.`,{exitCode:b.NotFound,hint:l?"It names an internal element; pass --internal to address it.":"Run 'modeldesk model tree' or 'modeldesk search' to find it.",details:{resolvedPath:Wh(s),resolvedId:o}})}if(d.length>1)throw new p(`'${i}' ${a} names ${d.length} elements; address the one you mean by id.`,{exitCode:b.Usage,details:{candidates:d.map(l=>({id:l,type:e.element(l)?.type,label:e.label(l)}))}});o=d[0],s.push(i)}return o};var cr=(e,t,n,r)=>new p(t,{exitCode:n,hint:r,type:e.type,requestId:e.requestId,details:e.details}),J$=(e,t)=>cr(t,`You hold no draft of ${e} any more: it was committed or discarded since it was read. Nothing was committed.`,b.Failure,"Run 'modeldesk model log' to see what landed."),X$=(e,t,n)=>{switch((e instanceof H?e.status:void 0)===404?"no-draft":e.type){case"draft-head-conflict":return cr(e,`The branch of ${t} moved past the commit your draft is based on, so the draft cannot land as it stands.`,b.Conflict,"Run 'modeldesk draft rebase', review what it reports, then commit again.");case"draft-moved":return cr(e,`Your draft of ${t} is not at ${n} any more: a change was staged, undone or rebased since, so nothing landed.`,b.Conflict,"Review it with 'modeldesk draft diff --changes', then commit again.");case"branch-head-conflict":return cr(e,`Your draft of ${t} changed while it was being committed, so nothing landed.`,b.Conflict,"Run 'modeldesk draft status', then commit again.");case"nothing-to-commit":return cr(e,`Your draft of ${t} holds no staged change, so there is nothing to commit.`,b.Failure);case"no-draft":return J$(t,e);default:return e}},Q$=(e,t)=>{let r=(Array.isArray(e.details.commits)?e.details.commits:[]).find(s=>s.requestId===t);return r&&{id:r.id,message:r.message,requestId:r.requestId,actionTypes:r.actionTypes}},Z$=async(e,t)=>{let{holder:n,draft:r,commitRequestId:s,retried:o}=t,i=e.exitCode===b.Transient,a=e instanceof H&&e.status===404;if(i||o&&a)try{let l=await n.findLanding(s,r);return l===void 0?{kind:"none"}:{kind:"landed",commit:l}}catch{return{kind:"unknown"}}let d=e.type==="draft-head-conflict"?Q$(e,s):void 0;return d===void 0?{kind:"none"}:{kind:"landed",commit:d}},ex=(e,t)=>cr(e,`${e.reason} Whether your draft of ${t} landed is unknown: the branch could not be read to look for the commit.`,b.Transient,"Run 'modeldesk model log' to see whether it landed before you commit again."),mr=async(e,t,n,r)=>{let s=Qn("cli",e.env),o={message:r.message,commitRequestId:s,expectedDraftHeadId:r.expectedDraftHeadId},i=async d=>({landing:{branch:await t.branch(n.targetRefId),commit:d},commitRequestId:s,recovered:!0}),a=async(d,l)=>{if(!(d instanceof p))throw d;let c=await Z$(d,{holder:t,draft:n,commitRequestId:s,retried:l});if(c.kind==="landed")return c.commit;if(!l&&d.exitCode===b.Transient)return"retry";throw c.kind==="unknown"?ex(d,t.ref.name):X$(d,t.ref.name,r.expectedDraftHeadId)};for(let d=!1;;d=!0)try{return{landing:await t.commit(o),commitRequestId:s,recovered:!1}}catch(l){let c=await a(l,d);if(c!=="retry")return i(c)}},fr=({branch:e,commit:t})=>({branch:"name"in e?{id:e.id,name:e.name}:{id:e.id},commit:t}),ur=(e,t)=>{let{branch:n}=e;if(!("main"in n)||n.main)return;let r=`${t.id}@${w(n.name)}`;return`Unaddressed invocations now default to main. Address ${r}, or run: modeldesk draft open ${r}`};var tx=/ \((\d+)\/(\d+)\)$/,nx=e=>{let t=tx.exec(e);if(t===null)return e;let[,n,r]=t.map(Number);return r>1&&n>=1&&n<=r?e.slice(0,t.index):e},rx=e=>nx(e.trim().split(/\r?\n/)[0].trim()),sx=e=>{let t=e.join("; ");if(t.length<=72)return t;let[n]=e;return`${n.length<=72?n:`${n.slice(0,71)}\u2026`} (and ${e.length-1} more)`},Hh=e=>{let t=e.flatMap(o=>o.message===void 0?[]:[rx(o.message)]).filter(o=>o!=="").filter((o,i,a)=>o!==a[i-1]);if(t.length<=1)return t[0];let n=`${sx(t)}
157
+ `),{result:{...r,...o,credentialValid:!0,account:a,organization:d,scopes:l}}},IO=async(e,t)=>{let n={host:t.host,apiBase:t.apiBase,mode:"interactive"},r=new Ve;if(!r.read(t.host)){let o=`not logged in. ${Pg}`;return e.print(`Status: ${o}
158
+ `),{result:{...n,credentialValid:!1,problem:o},exitCode:b.NeedsHuman}}try{let o=await new Nr(t,{store:r,allowBrowserLogin:!1}).refreshNow();if(!o)throw new f("The stored credential was rejected.",b.NeedsHuman);let s=Oi(o),i=s?` as ${s}`:"";return e.print(`Status: logged in${i} (credential valid).
159
+ `),{result:{...n,credentialValid:!0,identity:s}}}catch(o){let s=`the stored credential could not be verified (it may be expired or revoked, or the server is unreachable). ${Pg}`;e.print(`Status: ${s}
160
+ `);let i=o instanceof f&&o.exitCode===b.Transient;return{result:{...n,credentialValid:!1,problem:s},exitCode:i?b.Transient:b.NeedsHuman}}};var an=e=>e.superAdmin===!0,jg=async(e,t)=>{let[n,r]=await Promise.all([t.models?e.models.list({ownerId:t.ownerId,metamodel:t.metamodel}):void 0,t.metamodels?e.metamodelModels.list():void 0]),o=new Set((r?.items??[]).map(s=>s.id));return[...(n?.items??[]).filter(s=>!o.has(s.id)).map(s=>({model:s,kind:"model"})),...(r?.items??[]).map(s=>({model:s,kind:"metamodel"}))]},Lg=e=>{let t;return()=>t??=e()},_g=new WeakMap,ie=(e,t)=>{let n=_g.get(e)??new Map;_g.set(e,n);let r=n.get(t);if(r!==void 0)return r;let o=async()=>t,s=Lg(async()=>e.api().models.identity(await o())),i=Lg(async()=>e.api().branches.list(await o())),a={id:o,identity:s,branches:i};return n.set(t,a),a};var Fg=(e,t,n={})=>{let r=Wn(t);switch(r.mode){case"error":throw new f(r.message);case"secret":case"federated":return Mi(e,r);case"interactive":return new Nr(e,{allowBrowserLogin:n.interactive??!0})}};var SO=6e4,qg={unauthorized:"Run 'modeldesk auth login' and try again.",forbidden:"Your account may lack access to this model."},$O={unauthorized:wi.unauthorized,forbidden:wi.forbidden,notFound:wi.notFound},TO=new Set(["type","title","status","detail","instance"]),xO={"change-validation-failed":b.Validation,"draft-target-taken":b.Conflict,"invalid-branch-name":b.Validation,"branch-limit-reached":b.Validation,"ambiguous-merge-base":b.Failure,"invalid-resolution":b.Validation,"agent-creation-rate-limited":b.NeedsHuman,"agent-fetch-rate-limited":b.NeedsHuman},V=class extends f{status;problem;constructor(t,n,r,o){super(t,o),this.name="ApiError",this.status=n,this.problem=r}},Wg=(e,t)=>new Zl(e.apiBase,Fg(e,t.env,{interactive:t.interactive}),{hints:Ye(t.env)?$O:qg,userAgent:Og(t.agentHost)}),Zl=class{constructor(t,n,r={}){this.apiBase=t;this.tokens=n;this.hints=r.hints??qg,this.userAgent=r.userAgent}apiBase;tokens;hints;userAgent;async getJson(t,n){return Do(await this.request("GET",t,{query:n}),t)}async getJsonIfChanged(t,n,r){let o=await this.request("GET",t,{query:r,ifNoneMatch:n});if(o.status===304)return{notModified:!0};let{body:s,bytes:i}=await AO(o,t);return{notModified:!1,body:s,etag:o.headers.get("etag")??void 0,bytes:i}}async postJson(t,n,r){return Do(await this.request("POST",t,{query:r,body:n}),t)}async postJsonWithHeaders(t,n,r){let o=await this.request("POST",t,{query:r,body:n});return{body:await Do(o,t),headers:o.headers}}async putJson(t,n,r){return Do(await this.request("PUT",t,{query:r,body:n}),t)}async delete(t,n){return Do(await this.request("DELETE",t,{query:n}),t)}async getBytes(t,n,r){let o=await this.request("GET",t,{query:r,accept:n});return Ni(t,async()=>new Uint8Array(await o.arrayBuffer()))}async openEventStream(t,n){let r=await this.request("GET",t,{accept:"text/event-stream",signal:n});if(r.body===null)throw new f(`The event stream at ${t} opened without a body.`,{exitCode:b.Transient});return r.body}async accessTokenClaims(){return Gn(await this.tokens.getAccessToken())??{}}async request(t,n,r){let o=await this.tokens.getAccessToken(),s=OO(this.apiBase,n,r.query),i={Authorization:`Bearer ${o}`,Accept:r.accept??"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{},...r.body!==void 0?{"Content-Type":"application/json"}:{},...r.ifNoneMatch?{"If-None-Match":r.ifNoneMatch}:{}},a;try{a=await fetch(s,{method:t,headers:i,...r.body!==void 0?{body:JSON.stringify(r.body)}:{},signal:r.signal??AbortSignal.timeout(SO)})}catch(d){throw new f(`Could not reach ${this.apiBase} (${d.message}).`,{exitCode:b.Transient,hint:"Check the host and that the ModelDesk server is reachable."})}if(a.status===304&&r.ifNoneMatch)return a;if(!a.ok)throw await jO(a,n,this.hints);return a}},Ni=async(e,t)=>{try{return await t()}catch(n){throw n instanceof SyntaxError?new f(`The response from ${e} is not JSON (${n.message}).`):new f(`Reading the response from ${e} failed (${n.message}).`,{exitCode:b.Transient})}},Do=(e,t)=>e.status===204||e.headers.get("content-length")==="0"?Promise.resolve(void 0):Ni(t,()=>e.json()),AO=async(e,t)=>{if(e.status===204||e.headers.get("content-length")==="0")return{body:void 0,bytes:0};let n=await Ni(t,()=>e.text());return{body:await Ni(t,async()=>JSON.parse(n)),bytes:Buffer.byteLength(n,"utf8")}},OO=(e,t,n)=>{let r=new URL(t,e);if(n)for(let[o,s]of Object.entries(n))s!==void 0&&r.searchParams.set(o,s);return r.toString()},MO=(e,t)=>{let n=t===void 0?void 0:xO[t];return n!==void 0?n:e===401?b.NeedsHuman:e===404?b.NotFound:e===409?b.Conflict:e===429||e>=500?b.Transient:b.Failure},NO=e=>{if(!e||e==="about:blank")return;let t="/problems/",n=e.lastIndexOf(t);return n===-1?e:e.slice(n+t.length)},PO=async e=>{try{if((e.headers.get("content-type")??"").includes("json")){let n=await e.json();if(n!==null&&typeof n=="object"&&!Array.isArray(n))return n}}catch{}},DO=e=>Object.fromEntries(Object.entries(e??{}).filter(([t])=>!TO.has(t))),LO="Run 'modeldesk model list' to see the ids.",_O=(e,t)=>t?.startsWith("Model not found")?/^\/(?:metamodel-)?models\/([0-9a-f-]{36})(?:[/?]|$)/.exec(e)?.[1]:void 0,jO=async(e,t,n)=>{let r=await PO(e),o=r?.detail??r?.title,s=o?`${e.status} ${o}`:`${e.status} ${e.statusText}`.trim(),i=NO(r?.type),{requestId:a,...d}=DO(r),l={exitCode:MO(e.status,i),type:i,requestId:typeof a=="string"?a:e.headers.get("x-request-id")??void 0,details:typeof a=="string"||a===void 0?d:{requestId:a,...d}};if(e.status===401)return new V(`Authentication failed (${s}).`,401,r,{...l,hint:n.unauthorized,hosted:{hint:"The person you work for connects ModelDesk again."}});if(e.status===403)return new V(`Not authorized (${s}).`,403,r,{...l,hint:n.forbidden});let c=e.status===404?_O(t,o):void 0;return c!==void 0?new V(`No model has the id '${c}'.`,404,r,{...l,hint:n.notFound??LO,hosted:{reason:`No model with the id '${c}' is reached through this connection: it does not exist, or this connection does not reach it.`,hint:m=>`Call ${m("model list")} to see the ids.`}}):e.status===404&&n.notFound?new V(`Not found (${s}).`,404,r,{...l,hint:n.notFound}):new V(`Request to ${t} failed: ${s}`,e.status,r,l)};var FO="@Root",qO=e=>{let t=new Map;for(let[n,r]of Object.entries(e?.relations??{}))for(let o of Object.values(r))for(let s of o){let i=`${n}\0${s.id}`;t.has(i)||t.set(i,t.size)}return t},dn=e=>{let{elements:t}=e,n=a=>Object.hasOwn(t,a),r=e.rootElementId??Object.values(t).find(a=>a.type===FO)?.id;if(r===void 0||!n(r))throw new f("The model read carries no root element, so its tree cannot be built.");let o=new Map,s=new Map;for(let[a,d]of Object.entries(e.elementIndexEntries)){if(!n(a))continue;let l=(d.owners??[]).filter(c=>n(c.id));o.set(a,l);for(let c of l){let m=s.get(c.id)??[];m.push({id:a,relation:c.relation}),s.set(c.id,m)}}for(let[a,d]of s){let l=qO(t[a]),c=m=>l.get(`${m.relation}\0${m.id}`)??Number.MAX_SAFE_INTEGER;d.sort((m,p)=>c(m)-c(p))}let i=e.elementLabels??{};return{rootId:r,element:a=>n(a)?t[a]:void 0,label:a=>Object.hasOwn(i,a)?i[a]:void 0,owners:a=>o.get(a)??[],children:a=>s.get(a)??[]}},Vn=e=>e.startsWith("@"),Dr={internal:{type:"boolean",description:"Include the platform's internal `@` elements."}},ec=e=>e.replace(/[\\/]/g,t=>`\\${t}`),ft=(e,t={})=>{let n=c=>{let m=e.element(c);return m!==void 0&&(t.internal===!0||!Vn(m.type))},r=c=>{let m=new Set;return e.children(c).filter(p=>m.has(p.id)?!1:(m.add(p.id),!0))},o=c=>{let m=e.label(c);return m===void 0||m.trim()===""?void 0:m},s=new Map,i=c=>{let m=s.get(c);if(m!==void 0)return m;let p=new Map;for(let{id:h}of r(c)){let u=o(h);u!==void 0&&n(h)&&p.set(u,(p.get(u)??0)+1)}return s.set(c,p),p},a=(c,m)=>{let p=o(m);return p===void 0||(i(c).get(p)??0)>1?m:ec(p)},d=new Map,l=(c,m,p,h)=>{let u=e.element(c.id);if(u===void 0||!n(c.id)||t.maxDepth!==void 0&&p>t.maxDepth)return[];let y=h===""?a(m,c.id):`${h}/${a(m,c.id)}`,w=d.get(c.id);w===void 0&&d.set(c.id,y);let E=w===void 0?r(c.id).flatMap(C=>l(C,c.id,p+1,y)):[],I=t.types===void 0||t.types.has(u.type);if(!I&&E.length===0)return[];let v=e.label(c.id);return[{id:c.id,...v===void 0?{}:{label:v},type:u.type,depth:p,parentId:m,relation:c.relation,path:y,...e.owners(c.id).length>1?{multiOwned:!0}:{},...w===void 0?{}:{subtreeAt:w},...I?{}:{context:!0}},...E]};return d.set(e.rootId,""),r(e.rootId).flatMap(c=>l(c,e.rootId,1,""))},ln=e=>{let t=new Set;return e.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))};var Nt={kinds:["draft","head","branch","commit"],default:"working"},_e={kinds:["draft","head","branch"],default:"working"},nc={kinds:["draft","head","branch"],default:"head"},F={kinds:["draft","head","branch"],default:"working"},Kn={kinds:["head","branch"],default:"head"},Pt={kinds:["branch"],required:!0},rc={kinds:["branch"],default:"draft"},Hg={kinds:["commit"],default:"main"},Pi={kinds:["release","branch"],required:!0,names:{noun:"A dependency",listing:"modeldesk pin list <model>"}},Bg={kinds:["release","branch"],required:!0},Ug={noun:"A metamodel",listing:"modeldesk metamodel list"},Di={kinds:["release"],default:"main",names:Ug},Gg={kinds:[],default:"main",names:Ug},Li={kinds:["release"],default:"main",names:{noun:"An extension",listing:"modeldesk metamodel extensions <metamodel>"}},de={kinds:[],default:"main"},Vg="ref-not-found",_i=e=>e instanceof V&&(e.status===404||e.type===Vg),ht=async e=>{try{return await e()}catch(t){if(_i(t))return;throw t}},ji=e=>({id:e.branch.id,name:e.branch.name,main:!0,head:e.branch.head.id}),ut=e=>({id:e.id,name:e.name,main:e.main,head:e.head.id}),WO=(e,t)=>e!==void 0&&e.headCommitId!==e.baselineCommitId?{kind:"draft",draft:e}:{kind:"branch",branch:t},HO={working:{kind:"working"},head:{kind:"head"},main:{kind:"branch",name:"main"},draft:{kind:"draft"}},Yn=(e,t)=>e.localeCompare(t,void 0,{sensitivity:"accent"})===0,oc="branch-gone",BO=(e,t,n)=>new f(`Branch ${g(t.name)} (${t.id}) of ${g(e)} is gone`+(n===void 0?".":`; the branch named ${g(n.name)} now is another one (${n.id}), and it is not taken for it.`),{exitCode:b.NotFound,type:oc,details:{branch:{id:t.id,name:t.name},...n&&{namesake:{id:n.id,name:n.name}}}}),sc="Ask the person you work for to discard the draft in the app, or address the model at a branch.",tc=(e,t={})=>new f(e,{exitCode:b.NotFound,type:Vg,...t}),ae=async(e,t,n)=>{ql(t,n);let r=e.api(),o=ie(e,t.model),s=await o.id(),[i,a]=await Promise.all([o.identity(),ht(()=>r.models.draft(s))]),d=ji(i),l=async w=>{if(w===d.id)return d;let E=(await o.branches()).find(I=>I.id===w);return E===void 0?void 0:ut(E)},c=async w=>{let E=await l(w);if(E===void 0)throw tc(`Your draft of ${g(i.name)} targets a branch that is gone (${w}).`,{hint:"Discard the draft with 'modeldesk draft discard', or address the model at a branch.",hosted:{hint:sc}});return E},m=async w=>{if(Yn(w,d.name))return d;let E=await o.branches(),I=E.find(v=>Yn(v.name,w));if(I===void 0)throw tc(`${g(i.name)} has no branch named '${g(w)}'.`,{details:{branches:E.map(v=>v.name)}});return ut(I)},p=a===void 0?void 0:{...a,target:await c(a.targetRefId)},h=p?.target??d,u=t.ref.kind==="working"&&"default"in n?HO[n.default]:t.ref,y=await(async()=>{switch(u.kind){case"working":return WO(p,h);case"head":return{kind:"branch",branch:h};case"draft":if(p===void 0)throw tc(`You hold no draft of ${g(i.name)}.`,{hint:"Leave the ref out to read the branch, or stage a change to open a draft."});return{kind:"draft",draft:p};case"branch":return{kind:"branch",branch:await m(u.name)};case"branch-id":{let w=await l(u.id);if(w===void 0){let E=(await o.branches()).find(I=>Yn(I.name,u.name));throw BO(i.name,u,E&&ut(E))}return{kind:"branch",branch:w}}case"commit":return{kind:"commit",id:u.id};case"release":throw new f(`A release ref is not readable here (${t.text}).`,{exitCode:b.Usage})}})();return{id:s,name:i.name,ref:y,main:d,working:h,draft:p,...n.kinds.length===0&&!h.main?{note:`reads main; your draft targets ${h.name}`}:{}}},nt=({ref:e})=>{if(e.kind!=="branch")throw new Error(`A branch-only slot resolved to a ${e.kind}.`);return e.branch},rt=e=>{switch(e.kind){case"branch":return{ref:e.branch.id};case"draft":return{ref:e.draft.id};case"commit":return{commit:e.id}}},UO=e=>{switch(e.kind){case"branch":return{kind:"branch",id:e.branch.id,name:e.branch.name};case"draft":return{kind:"draft",id:e.draft.id,branch:{id:e.draft.target.id,name:e.draft.target.name}};case"commit":return{kind:"commit",id:e.id}}},le=({ref:e,draft:t,note:n})=>{let r=UO(e),o=t!==void 0&&e.kind==="branch"&&e.branch.id!==t.target.id;return{...r,...o?{draftIgnored:!0}:{},...n===void 0?{}:{note:n}}},GO=(e,t)=>{switch(e.kind){case"draft":return`Reading your draft of ${t}, aimed at ${g(e.branch.name)}.`;case"branch":return`Reading branch ${g(e.name)} of ${t}.`;case"commit":return`Reading commit ${e.id} of ${t}.`}},Ae=(e,t)=>{let n=g(t.name);return[GO(e,n),...e.draftIgnored?["Your draft aims at another branch and was not read."]:[],...e.note?[`${e.note[0].toUpperCase()}${e.note.slice(1)}.`]:[]].join(" ")},Lr=async(e,t,n)=>{let r=await ae(e,t,n),o=await e.content.read(e.api(),r.id,r.ref);return{model:{id:r.id,name:r.name},ref:le(r),resolved:r,read:o,tree:dn(o)}};var Dt=e=>e.draft?.id??e.branch.id,ic="draft-target-taken",Lo=(e,t,n,r,o=r)=>{let s=g(e.name),i=t.changeCount>0,a=g(t.target.name),d=m=>`Your draft of ${s} aims at ${a}`+(i?` and holds ${P(t.changeCount,"staged change")}`:" and holds no staged change")+`, so ${m}.`,l=`${e.id}@${a}`,c=`${e.id}@${g(n.name)}`;return new f(d(r),{exitCode:b.Conflict,type:ic,hint:i?`Commit or discard your changes on ${a} first: 'modeldesk draft commit ${e.id}@${a}' or 'modeldesk draft discard ${e.id}@${a}'. Or address ${e.id}@${a} to work where your draft aims.`:`Run 'modeldesk draft open ${e.id}@${g(n.name)}', which loses nothing.`,details:{targetRefId:t.target.id,targetRefName:t.target.name,requestedRefId:n.id,requestedRefName:n.name,changeCount:t.changeCount},hosted:{reason:d(o),hint:m=>i?`Commit your changes on ${a} first with ${m("draft commit")} (model ${l}), or ask the person you work for to discard them in the app. Or address ${l} to work where your draft aims.`:`Call ${m("draft open")} with model ${c}, which loses nothing.`}})},gt=async(e,t)=>{let n=await ae(e,t,F),{ref:r,draft:o}=n;if(r.kind==="commit")throw new f(`A change cannot be staged at a commit (${t.text}); address a branch.`,{exitCode:b.Usage,type:"ref-unsupported"});let s=r.kind==="branch"?r.branch:r.draft.target;if(o!==void 0&&o.target.id!==s.id)throw Lo(n,o,s,`nothing was staged on ${g(s.name)}`);let i=await e.content.read(e.api(),n.id,o?{kind:"draft",draft:o}:{kind:"branch",branch:s});return{address:t,model:{id:n.id,name:n.name},branch:s,draft:o,resolved:n,read:i,tree:dn(i),head:i.branch.head.id}};var VO=e=>({id:e.id,createdAt:e.createdAt,...e.message?{message:e.message}:{},...e.requestId?{requestId:e.requestId}:{},actionTypes:[...new Set(e.actions.map(t=>t.type))].sort(),elementIds:e.actions.reduce((t,n)=>({...t,[n.type]:[...t[n.type]??[],...n.elementIds??[]]}),{})}),ze=async(e,t,n,r)=>{let o=[],s;for(;;){let i=r===void 0?_o:Math.min(_o,r-o.length),a=(await e.models.commits(t,{ref:n,limit:i,cursor:s})).items;if(o.push(...a.map(VO)),a.length<i||r!==void 0&&o.length>=r)return o;s=a.at(-1)?.id}},je={...jh(rc),description:"The model's id, from model list, or dataset/<id>. Your draft wherever it aims; a model's @<branch> asserts where it aims, and a draft aimed elsewhere is refused (exit 5) with nothing done."},YO=5,_o=100,Kg=async(e,t,n)=>{let r;for(let o=0;o<YO;o++){let s=await e(r);for(let i of s){if(i.requestId===t)return i;if(i.id===n)return}if(s.length<_o)return;r=s.at(-1)?.id}},Fi=(e,t)=>({url:e.webUrl({kind:"model",modelId:t}),changes:(n,r)=>ze(e.api(),t,n,r)}),jo=async(e,t)=>{let n=e.api(),r=ie(e,t),o=await r.identity(),s=o.id,i=n.drafts.model,a=async d=>{if(d===o.branch.id)return ji(o);let l=(await r.branches()).find(c=>c.id===d);if(l===void 0)throw new f(`Your draft of ${g(o.name)} targets a branch that is gone (${d}).`,{exitCode:b.NotFound,type:"ref-not-found",hint:"Discard the draft with 'modeldesk draft discard', or address the model at a branch.",hosted:{hint:sc}});return ut(l)};return{ref:{kind:"model",id:s,name:o.name},url:e.webUrl({kind:"model",modelId:s}),read:()=>ht(()=>n.models.draft(s)),workingBranch:async d=>{let l=d===void 0?ji(o):await a(d.targetRefId);return{branch:l,head:l.head}},branch:a,undo:async d=>({headCommitId:(await i.undo(s,d)).commitId}),commit:async d=>{let l=await i.commit(s,d),{id:c,message:m,requestId:p,createdAt:h,actionTypes:u}=l.commit;return{branch:await a(l.refId),commit:{id:c,...m?{message:m}:{},...p?{requestId:p}:{},createdAt:h,actionTypes:u},draftHeadCommitId:l.draftHeadCommitId}},rebase:async d=>{let l=await i.rebase(s,d);return{draft:l.draft,dropped:l.dropped,closureChanged:l.closureChanged,schemaChanged:l.schemaChanged}},discard:d=>i.discard(s,d),changes:(d,l)=>ze(n,s,d,l),findLanding:async(d,l)=>{let c=await Kg(async m=>(await n.models.commits(s,{ref:l.targetRefId,limit:_o,cursor:m})).items,d,l.baselineCommitId);return c&&{id:c.id,message:c.message,requestId:c.requestId,createdAt:c.createdAt,actionTypes:[...new Set(c.actions.map(m=>m.type))].sort()}}}},KO=async(e,t)=>{let n=e.api(),r=await n.datasets.get(t),o=n.drafts.dataset,s=async(i,a)=>(await n.datasets.commits(r.id,{limit:i,cursor:a})).items??[];return{ref:{kind:"dataset",id:r.id,name:r.name},read:()=>ht(()=>o.get(r.id)),branch:async i=>({id:i}),workingBranch:async i=>{let[a]=await s(1);if(a===void 0)throw new f(`Dataset ${r.name} has no commits, so its branch head is unknown.`);return{branch:i===void 0?void 0:{id:i.targetRefId},head:a.id}},undo:async i=>{let{draft:a}=await o.undo(r.id,i);return{headCommitId:a.headCommitId,changeCount:a.changeCount}},commit:async i=>{let{refId:a,commit:d}=await o.commit(r.id,i);return{branch:{id:a},commit:{id:d.id,...d.message?{message:d.message}:{},...d.requestId?{requestId:d.requestId}:{},...d.createdAt?{createdAt:d.createdAt}:{},...d.rowsChanged===void 0?{}:{rowsChanged:d.rowsChanged}}}},rebase:async i=>{let a=await o.rebase(r.id,i);return{draft:a.draft,dropped:a.dropped.map(d=>({commitId:d.id,...d.requestId?{requestId:d.requestId}:{},...d.message?{message:d.message}:{},...d.rowsChanged===void 0?{}:{rowsChanged:d.rowsChanged}}))}},discard:i=>o.discard(r.id,i),findLanding:async(i,a)=>{let d=await Kg(l=>s(_o,l),i,a.baselineCommitId);return d&&{id:d.id,message:d.message,requestId:d.requestId,rowsChanged:d.rowsChanged}}}},zO=async(e,t,n)=>{let r=await ae(e,t,rc),{draft:o,ref:s}=r;if(o!==void 0&&s.kind==="branch"&&o.target.id!==s.branch.id)throw Lo(r,o,s.branch,`'modeldesk ${n}' did nothing on ${g(s.branch.name)}`,`'${n}' did nothing on ${g(s.branch.name)}`)},Yg=new WeakMap,Le=e=>{let t=Yg.get(e);if(t!==void 0)return t;let{resource:n}=e.args,r=n.kind==="dataset"?KO(e,n.id):(async()=>(n.address.ref.kind==="branch"&&await zO(e,n.address,e.commandName),jo(e,n.address.model)))();return Yg.set(e,r),r},JO=e=>{if(e instanceof f&&e.type==="feature-not-enabled"){let{feature:t,organizationId:n}=e.details,r=typeof t=="string"?`The '${t}' feature`:"A feature this change needs",o=typeof n=="string"?` (${n})`:"";return new f(`${r} is not enabled for this organization${o}.`,{type:e.type,details:e.details,requestId:e.requestId,hint:"Ask ModelDesk to enable the feature for your organization, or leave out the change that needs it."})}return e},oe=async e=>{try{return await e()}catch(t){throw JO(t)}},ce=e=>`${e.kind} ${g(e.name)}`,_r=(e,t)=>"name"in t?`${e.id}@${g(t.name)}`:e.id,Ue=500;var zg={draftOpen:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}}},draft:{type:"object",properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}}},opened:{type:"boolean",description:"False when the draft already aimed at the branch and was left as it was. One of false, true."},reopenedFrom:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The branch an empty draft aimed at before it was discarded and opened on this one."}},required:["schemaVersion","model","ref","draft","opened"]}};var Xg=({id:e,name:t})=>({id:e,name:t}),Jg=({id:e,targetRefId:t,baselineCommitId:n,headCommitId:r,changeCount:o,createdAt:s,updatedAt:i},a)=>({id:e,targetRefId:t,baselineCommitId:n,headCommitId:r,changeCount:o,createdAt:s,updatedAt:i,target:Xg(a)}),ac=async(e,t,n)=>{let{draft:r}=t;if(r?.target.id===n.id)return{draft:Jg(r,n),opened:!1};if(r!==void 0&&r.changeCount>0)throw Lo(t,r,n,`no draft was opened on ${g(n.name)}`);let o=e.api().drafts.model;if(r!==void 0)try{await o.discard(t.id,r.headCommitId)}catch(i){if(!(i instanceof V&&i.status===404))throw i}let s=await o.open(t.id,n.id);return{draft:Jg(s,n),opened:!0,...r===void 0?{}:{reopenedFrom:Xg(r.target)}}},dc=(e,t)=>{let n=g(e.name),r=g(t.draft.target.name);return t.opened?t.reopenedFrom===void 0?`Opened your draft of ${n} on ${r}.`:`Discarded your empty draft of ${n} on ${g(t.reopenedFrom.name)} and opened one on ${r}.`:`Your draft of ${n} already aims at ${r}; it was left as it was.`},Qg=A({path:["draft","open"],effect:"stage",summary:"Aim your draft of a model at a branch",description:"Opens your draft of the model on the branch, so the writes that name no branch stage there. A draft already on the branch is left as it is (opened: false). A draft on another branch that holds nothing is discarded and opened here, which loses nothing (reopenedFrom names where it was). A draft holding staged changes on another branch is refused (exit 5): commit or discard them first. Only this command and 'branch create --open' discard a draft on your behalf. A dataset has no branches, so it takes a model.",positionals:[N(Pt)],examples:["modeldesk draft open <model>@feat/x","modeldesk draft open <model>@agent/tidy-names --json"],mcp:{name:"draft_open",description:"Aims your draft of the model at a branch (model@<branch>), so calls that name no ref stage there. A draft already there is kept; an empty draft elsewhere moves here; a draft holding changes elsewhere is refused. For new work, branch_create with open: true cuts a branch and opens it in one call."},resultSchema:zg.draftOpen,run:async e=>oe(async()=>{let t=await ae(e,e.args.model,Pt),n=await ac(e,t,nt(t));return{result:{model:{id:t.id,name:t.name},ref:{kind:"draft",id:n.draft.id,branch:n.draft.target},...n}}}),render:e=>dc(e.model,e)});var Zg={branchCreate:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},name:{type:"string",description:"The name asked for, trimmed as the server trims it."},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"},main:{type:"boolean",description:"One of false, true."},head:{type:"string"}},description:"The branch created, or the one that has the name when asked to take it; absent under a dry run that would create it."},from:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The branch it is created from: the working branch, or the one the address named."},created:{type:"boolean",description:"False when the name was taken and the branch that has it answered instead, and under a dry run. One of false, true."},dryRun:{type:"boolean",description:"Always true."},open:{type:"object",properties:{draft:{type:"object",properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}}},opened:{type:"boolean",description:"False when the draft already aimed at the branch and was left as it was. One of false, true."},reopenedFrom:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The branch an empty draft aimed at before it was discarded and opened on this one."}},description:"When asked to open the branch: where your draft now aims."},note:{type:"string",description:"Under an agent host, for a name outside `agent/`: where an agent may commit without a person's say-so."}},required:["schemaVersion","model","name","from","created"]}};var ZO={draft:"'@draft' in an address means your draft",head:"'@head' in an address means your working branch head",main:"'@main' in an address means the main branch"},eM=e=>{let t=ZO[e.toLowerCase()]??(B(e)?"a UUID in an address is a commit":void 0);if(t!==void 0)throw new f(`A branch cannot be named '${g(e)}': ${t}.`,{exitCode:b.Validation,type:"invalid-branch-name",hint:"Pick another name.",details:{rule:"reserved-name"}})},tM=(e,t,n,r)=>{let{branch:o}=e;return o===void 0?`Would create branch ${t} of ${n} from ${r}; nothing was created (dry run).`:e.dryRun?`Branch ${t} of ${n} exists (${o.id}); --exist-ok would use it; nothing was created (dry run).`:e.created?`Created branch ${t} of ${n} from ${r}: ${o.id}`:`Branch ${t} of ${n} already exists: ${o.id}`},ey=A({path:["branch","create"],effect:"create",summary:"Create a branch of a model",description:`Creates a branch at the head of your working branch (the one your draft aims at, else main), or of the branch the address names. A name another branch already has (in any case) exits 5 unless --exist-ok, which answers that branch with created: false, so a retried script converges. A name the server refuses exits 4 naming the rule; so do 'draft', 'head', 'main' and a UUID, which an address cannot reach as a branch. --open then aims your draft at the branch as draft open does, discarding an empty draft elsewhere. An agent's own branch is named ${Qt}<topic>: a draft landing there needs no MODELDESK_ALLOW_COMMIT=1, since a person reviews and merges the branch in the app.`,positionals:[N(Kn),{name:"name",type:"string",required:!0,description:"The new branch name."}],flags:{open:{type:"boolean",description:"Aim your draft at the branch, as draft open does."},"exist-ok":{type:"boolean",description:"Answer the branch that already has the name (created: false) instead of exiting 5.",toolDescription:"Answer the branch that already has the name (created: false) instead of refusing the name."}},dryRun:!0,examples:["modeldesk branch create <model> feat/assoc-ends","modeldesk branch create <model> agent/tidy-names --open --json","modeldesk branch create <model>@feat/x feat/x-followup --exist-ok"],mcp:{name:"branch_create",description:"Creates a branch of the model at your working branch head, or at the branch the address names. For larger work, name it agent/<topic> and pass open: true: your draft then aims at it, and draft_commit lands there without the person's 'Act without your review' permission; end by asking the person to review and merge it in the app, naming the branch. A name outside agent/ is created with notes saying an agent commits there only with that permission. existOk answers a branch that already has the name instead of failing."},resultSchema:Zg.branchCreate,run:async e=>oe(async()=>{let t=e.args.name.trim();eM(t);let n=e.args.model,r=await ae(e,n,Kn),o=nt(r),s={id:r.id,name:r.name},i=e.agent!==void 0&&!t.toLowerCase().startsWith(Qt)?`An agent commits without ${e.agent.wording.grant} only on a branch named ${Qt}\u2026`:void 0;i!==void 0&&e.note(i);let a={model:s,name:t,from:{id:o.id,name:o.name},...i?{note:i}:{}},d=async()=>{let p=(await ie(e,n.model).branches()).find(h=>Yn(h.name,t));return p===void 0?void 0:ut(p)};if(e.dryRun){let p=await d();if(p!==void 0&&!e.flags["exist-ok"])throw new f(`${g(s.name)} already has a branch named '${g(p.name)}'.`,{exitCode:b.Conflict,type:"branch-name-taken",hint:"Pick another name, or pass --exist-ok to use that branch.",hosted:{hint:"Pick another name, or set existOk to use that branch."}});return{result:{...a,...p?{branch:p}:{},created:!1,dryRun:!0}}}let l=await(async()=>{try{let p=await e.api().branches.create(s.id,{name:t,from:o.id});return{branch:ut(p),created:!0}}catch(p){let h=p instanceof f&&p.type==="branch-name-taken"&&e.flags["exist-ok"]?await d():void 0;if(h===void 0)throw p;return{branch:h,created:!1}}})(),c=e.flags.open?await ac(e,r,l.branch):void 0;return{result:{...a,...l,...c?{open:c}:{}}}}),render:e=>{let t=g(e.model.name),n=g(e.name),r=g(e.from.name);return[tM(e,n,t,r),...e.open?[dc(e.model,e.open)]:[]].join(`
161
+ `)}});var yt=async(e,t,n)=>{if(!e.globals.yes){if(!e.interactive)throw new f(`${n} needs confirmation, and this run cannot ask for it. Nothing was changed.`,{exitCode:b.NeedsHuman,hint:"Re-run with --yes to confirm."});if(!await e.confirm(t))throw new f(`${n} was cancelled. Nothing was changed.`)}};var ty={branchDelete:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},deleted:{type:"boolean",description:"False on a dry run. One of false, true."},dryRun:{type:"boolean",description:"One of false, true."},forced:{type:"boolean",description:"True when the delete was forced: other users' staged work and commits main does not reach went too. One of false, true."},draftCount:{type:"number",description:"How many drafts aimed at the branch when it was listed, yours included; every one went with it."},unmergedCommitCount:{type:"number",description:"How many commits on the branch main did not reach when it was listed; they are left to garbage collection."}},required:["schemaVersion","model","branch","deleted","dryRun","forced","draftCount","unmergedCommitCount"]}};var rM=(e,t,n)=>{let r=n?Math.max(t,1):t;return r===0?`Deleting ${e} deletes only the branch. No one has a draft on it.`:r===1?`Deleting ${e} also deletes ${n?"your draft":"the one draft"} on it. It cannot be recovered.`:`Deleting ${e} also deletes the ${r} drafts on it${n?", yours among them":""}. They cannot be recovered.`},oM=(e,t)=>t===0?`Everything committed on ${e} is on main.`:t===1?`1 commit on ${e} is not on main. It is lost with the branch.`:`${t} commits on ${e} are not on main. They are lost with the branch.`,sM="modeldesk branch delete --help",ny={hint:"Nothing was deleted. Tell the person you work for what the branch holds; they decide in the app whether to delete it."},iM=(e,t)=>{if(!(e instanceof f))return e;let n={exitCode:e.exitCode,type:e.type,requestId:e.requestId,details:e.details};if(e.type==="branch-has-drafts"){let r=Number(e.details.draftCount),o=r===1?"a draft":`${r} drafts`;return new f(`Other users hold ${o} with staged changes on ${t}, so it was not deleted.`,{...n,hint:"Pass --force to delete the branch with their drafts, which cannot be recovered.",hosted:ny})}if(e.type==="branch-unmerged"){let r=Number(e.details.unmergedCommitCount),o=r===1?"1 commit":`${r} commits`;return new f(`${o} on ${t} ${r===1?"is":"are"} not on main, so it was not deleted.`,{...n,hint:"Merge it into main first to keep them, or pass --force to lose them with the branch.",hosted:ny})}return e instanceof V&&e.status===403?new f(e.message,{...n,hint:"Deleting a branch needs the model:delete scope, which model:write does not imply, since other users' drafts are lost with it. Ask an owner of the model to delete it, or sign in with a token that carries that scope."}):e},lc={name:"delete",description:"Deletes a model with its history and releases, or one of its branches with every draft aimed at it. Neither can be restored. It needs the person's 'Act without your review' permission. Call it with dryRun: true first and show the person what it reports: for a model its releases, the models that depend on it and whether it is public; for a branch its drafts and the commits main lacks. Delete only on their word, naming what goes. A branch holding commits main lacks, or another person's staged work, is refused: leave it to the person. A public model needs their 'Publish' permission."},cc="what",ry=async e=>{let t=e.args.model,n=await ae(e,t,Pt),r=nt(n),o=g(r.name);if(r.main)throw k(`${o} is the main branch of ${g(n.name)}, which cannot be deleted.`,sM);let s=(await ie(e,t.model).branches()).find(i=>i.id===r.id);return{resolved:n,branch:r,name:o,draftCount:s?.draftCount??0,unmergedCommitCount:s?.unmergedCommitCount??0,yours:n.draft?.target.id===r.id}},oy=A({path:["branch","delete"],effect:"destroy",summary:"Delete a branch with every draft on it",description:"Deletes the branch together with every draft that aims at it, whoever owns it. It restates how many drafts go with it and how many of its commits main does not reach, and asks at a terminal; anywhere else it needs --yes. While other users' drafts on it hold staged changes, or it holds commits main does not reach, the delete exits 5 unless --force, which loses them. main cannot be deleted (exit 2). It needs the model:delete scope. --dry-run restates what would go and deletes nothing; the server then checks neither the refusals nor the scope. Under an agent host deleting a branch is left to a person (exit 6).",positionals:[N(Pt)],dryRun:!0,flags:{force:{type:"boolean",description:"Delete even when other users' drafts on the branch hold staged changes, or main lacks its commits."}},examples:["modeldesk branch delete <model>@feat/x --dry-run","modeldesk branch delete <model>@feat/x --yes","modeldesk branch delete <model>@feat/x --force --yes"],mcp:{...lc,pin:{force:void 0},choice:{member:cc,value:"branch",description:"Delete the branch the address names (model@<branch>), with every draft aimed at it."}},resultSchema:ty.branchDelete,prepare:async e=>{let{name:t,draftCount:n,unmergedCommitCount:r,yours:o,resolved:s}=await ry(e);if(e.print(`${rM(t,n,o)}
162
+ ${oM(t,r)}
163
+ `),!e.dryRun){let i=`branch ${t} of ${g(s.name)}`;await yt(e,`Delete ${i}?`,`Deleting ${i}`)}},run:async e=>{let{resolved:t,branch:n,name:r,draftCount:o,unmergedCommitCount:s}=await ry(e),{force:i}=e.flags,{dryRun:a}=e,d={model:{id:t.id,name:t.name},branch:{id:n.id,name:n.name},deleted:!a,dryRun:a,forced:i,draftCount:o,unmergedCommitCount:s};if(a)return{result:d};try{await e.api().branches.delete(t.id,n.id,i)}catch(l){throw iM(l,r)}return{result:d}},render:e=>{let t=`branch ${g(e.branch.name)} of ${g(e.model.name)}`;return e.dryRun?`Would delete ${t}. Dry run: nothing was deleted.`:`Deleted ${t}.`}});var sy={draftDiff:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},draft:{properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}}},description:"Your draft, or null when you hold none. May be null."},elements:{type:"array",items:{type:"object",properties:{elementId:{type:"string"},elementName:{type:"string"},elementType:{type:"string"},diffType:{type:"string",description:'One of "ADDED", "MODIFIED", "REMOVED".'},attributes:{type:"object",additionalProperties:{type:"object",properties:{before:{type:"array",items:{}},after:{type:"array",items:{}}}}},relations:{type:"object",additionalProperties:{type:"object",properties:{before:{type:"array",items:{type:"string"}},after:{type:"array",items:{type:"string"}},addedTargets:{type:"array",items:{type:"string"}},removedTargets:{type:"array",items:{type:"string"}}}}}}},description:"A model draft's net difference from its baseline, one entry per element, as the server renders a commit's."},names:{type:"object",additionalProperties:{type:"string"},description:"The name of every element the diff mentions, relation targets included, keyed by id."},rows:{type:"object",properties:{added:{type:"array",items:{type:"string"}},changed:{type:"array",items:{type:"string"}},removed:{type:"array",items:{type:"string"}}},description:"A dataset draft's difference from its baseline."},changes:{type:"array",items:{type:"object",properties:{id:{type:"string"},createdAt:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `changeRequestId` it was staged under."},surface:{type:"string",description:'Where it came from, read off the request id\'s prefix: the app (`web`), `cli`, `mcp`, or `api`. One of "api", "cli", "mcp", "web".'},actionTypes:{type:"array",items:{type:"string"},description:"The action types the change recorded."}}},description:"When changes are asked for: the staged changes, oldest first, instead of the difference."}},required:["schemaVersion","resource","draft"]}};var dM={ADDED:"+",MODIFIED:"~",REMOVED:"-"},iy=e=>e===void 0||e.length===0?"(none)":e.map(t=>g(typeof t=="string"?t:JSON.stringify(t))).join(", "),ay=(e,t)=>e[t]===void 0?t:`${g(e[t])} (${t})`,mc=(e,t)=>[` ${dM[e.diffType]} ${g(e.elementName??t[e.elementId]??"(no name)")} (${e.elementType}) ${e.elementId}`,...Object.entries(e.attributes??{}).map(([n,r])=>` ${n}: ${iy(r.before)} -> ${iy(r.after)}`),...Object.entries(e.relations??{}).map(([n,r])=>[` ${n}:`,...(r.addedTargets??[]).map(o=>`+ ${ay(t,o)}`),...(r.removedTargets??[]).map(o=>`- ${ay(t,o)}`)].join(" "))],lM=(e,t)=>{let n=e.requestId?` [${e.requestId}]`:"";return` ${t+1}. ${e.id} ${e.createdAt} ${e.surface.toUpperCase()} ${g(e.message??"(no message)")}${n} ${e.actionTypes.join(", ")}`},cM=e=>{let t=ce(e.resource);if(e.draft===null)return`You hold no draft of ${t}, so nothing is staged.`;if(e.changes)return[`The staged changes of your draft of ${t}, oldest first:`,...e.changes.length===0?[" none"]:e.changes.map((o,s)=>lM(o,s))].join(`
164
+ `);if(e.rows){let{added:o,changed:s,removed:i}=e.rows;return[`Your draft of ${t} against its baseline:`,...o.map(a=>` + ${a}`),...s.map(a=>` ~ ${a}`),...i.map(a=>` - ${a}`),...o.length+s.length+i.length===0?[" no rows differ"]:[]].join(`
165
+ `)}let n=e.names??{},r=e.elements??[];return[`Your draft of ${t} against its baseline:`,...r.length===0?[" no elements differ"]:r.flatMap(o=>mc(o,n))].join(`
166
+ `)},dy=A({path:["draft","diff"],effect:"read",summary:"Show what your draft changes",description:"Shows your draft's net difference from its baseline: per element of a model (added, modified with each changed attribute and relation, removed), per row of a dataset. With --changes it lists the staged changes instead, oldest first, each with its message, request id and the surface it came from (WEB for the app, CLI, MCP, or API for anything else). A dataset serves no list of its staged changes, so --changes takes a model.",positionals:[je],flags:{changes:{type:"boolean",description:"List the staged changes, oldest first, instead of the difference."}},examples:["modeldesk draft diff <model>","modeldesk draft diff <model> --changes --json"],mcp:{name:"draft_diff",description:"Shows what your draft changes against its baseline, per element: added, modified with each changed attribute and relation, removed. changes: true lists the staged changes instead, oldest first, each with its message, request id and the surface it came from. Call it to check your work before draft_handoff or draft_commit."},resultSchema:sy.draftDiff,run:async e=>oe(async()=>{if(e.flags.changes&&e.args.resource.kind==="dataset")throw k("A dataset's draft serves no list of its staged changes, so --changes takes a model.","modeldesk draft diff --help");let t=await Le(e),n=await t.read(),r={resource:t.ref,draft:n??null};if(n===void 0)return{result:r};let o=e.api();if(e.flags.changes&&t.changes){let i=(await t.changes(n.id)).reverse().map(a=>({id:a.id,createdAt:a.createdAt,...a.message?{message:a.message}:{},...a.requestId?{requestId:a.requestId}:{},surface:Xt(a.requestId),actionTypes:a.actionTypes}));return{result:{...r,changes:i}}}if(t.ref.kind==="dataset"){let i=await o.drafts.dataset.diff(t.ref.id);return{result:{...r,rows:{added:i.added??[],changed:i.changed??[],removed:i.removed??[]}}}}let s=await o.drafts.model.diff(t.ref.id);return{result:{...r,elements:s.elements,names:s.resolvedNames??{}}}}),render:cM});var ly={branchDiff:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"The branch whose changes are listed."},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"},head:{type:"string"}}},base:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The branch it is compared with, main by default."},mergeBaseId:{type:"string",description:"The commit the two diverged at: what the changes are counted from."},elements:{type:"array",items:{type:"object",properties:{elementId:{type:"string"},elementName:{type:"string"},elementType:{type:"string"},diffType:{type:"string",description:'One of "ADDED", "MODIFIED", "REMOVED".'},attributes:{type:"object",additionalProperties:{type:"object",properties:{before:{type:"array",items:{}},after:{type:"array",items:{}}}}},relations:{type:"object",additionalProperties:{type:"object",properties:{before:{type:"array",items:{type:"string"}},after:{type:"array",items:{type:"string"}},addedTargets:{type:"array",items:{type:"string"}},removedTargets:{type:"array",items:{type:"string"}}}}}}},description:"The branch's net change since `mergeBaseId`, one entry per element, as a draft's diff renders it."},names:{type:"object",additionalProperties:{type:"string"},description:"The name of every element the diff mentions, relation targets included, keyed by id."}},required:["schemaVersion","model","ref","branch","base","elements","names"]}};var cy=A({path:["branch","diff"],effect:"read",summary:"Show what a branch changed since it diverged",description:"Shows the branch's net change since it diverged from the base branch (main unless --base), per element as draft diff shows a draft: what merging it into the base would bring before conflicts. The branch is your working branch unless the address names one. Two branches each merged into the other have no single point where they split and exit 1, naming the candidate commits.",positionals:[N(Kn)],flags:{base:{type:"string",placeholder:"branch",description:"The branch to compare with, by name; main by default."}},examples:["modeldesk branch diff <model>@feat/x","modeldesk branch diff <model>@feat/x --base feat/y --json"],mcp:{name:"branch_diff",description:"Shows what a branch changed since it diverged from base (main unless given), per element as draft_diff shows a draft: what merging it would bring, before conflicts. Without a ref, your working branch."},resultSchema:ly.branchDiff,run:async e=>{let t=e.args.model,n=await ae(e,t,Kn),r=nt(n),o=e.flags.base===void 0?n.main:nt(await ae(e,{model:t.model,ref:{kind:"branch",name:e.flags.base},text:`${t.model}@${e.flags.base}`},Kn)),s=await(async()=>{try{return await e.api().branches.diff(n.id,r.id,o.id)}catch(a){if(a instanceof f&&a.type==="ambiguous-merge-base"){let d=Array.isArray(a.details.candidateBaseIds)?a.details.candidateBaseIds:[];throw new f(`${g(r.name)} and ${g(o.name)} were each merged into the other, so they have ${d.length||"several"} equally close common commits and no single point where they split.`,{exitCode:a.exitCode,type:a.type,requestId:a.requestId,details:a.details,hint:"Delete whichever branch holds nothing of its own since the two merges and create it again from the other, or create a new branch from one of them and redo the other changes there."})}throw a}})();return{result:{model:{id:n.id,name:n.name},ref:le(n),branch:{id:r.id,name:r.name,head:s.commitId},base:{id:o.id,name:o.name},...s.parentCommitId?{mergeBaseId:s.parentCommitId}:{},elements:s.elements,names:s.resolvedNames??{}}}},render:e=>{let t=e.mergeBaseId?`, since ${e.mergeBaseId}`:"";return[`${g(e.branch.name)} of ${g(e.model.name)} against ${g(e.base.name)}${t}:`,...e.elements.length===0?[" no elements differ"]:e.elements.flatMap(r=>mc(r,e.names))].join(`
167
+ `)}});var my={branchList:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},items:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},main:{type:"boolean",description:"One of false, true."},head:{type:"string",description:"The commit the branch points at."},draftCount:{type:"number",description:"How many drafts aim at the branch, whoever owns them; a delete takes every one."},unmergedCommitCount:{type:"number",description:"How many commits on the branch main does not reach; a delete loses them."},working:{type:"boolean",description:"True for the branch your draft aims at, which an invocation that names no ref works on. One of false, true."}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","model","items","truncated"]}};var fM=["","NAME","HEAD","DRAFTS","UNMERGED","ID"],py=A({path:["branch","list"],effect:"read",summary:"List a model's branches",description:"Lists the model's branches, main first, each with its head, how many drafts aim at it (whoever owns them) and how many of its commits main does not reach. The branch your draft aims at is marked working (* in the table): an invocation that names no ref works there, and on main when you hold no draft.",positionals:[N(de)],listing:{},examples:["modeldesk branch list <model>","modeldesk branch list <model> --json"],mcp:{name:"branch_list",description:"Lists the model's branches, main first, each with its head, how many drafts aim at it and how many of its commits main does not reach. The branch your draft aims at is marked working: a call that names no ref works there."},resultSchema:my.branchList,run:async e=>{let t=ie(e,e.args.model.model),n=await t.id(),[r,o,s]=await Promise.all([t.identity(),t.branches(),ht(()=>e.api().models.draft(n))]),i=s?.targetRefId??r.branch.id,a=o.map(l=>({id:l.id,name:l.name,main:l.main,head:l.head.id,draftCount:l.draftCount,unmergedCommitCount:l.unmergedCommitCount,working:l.id===i}));return{result:{model:{id:n,name:r.name},...await e.list(a)}}},render:e=>{let t=e.items.map(n=>[n.working?"*":"",g(n.name),n.head,String(n.draftCount),String(n.unmergedCommitCount),n.id]);return[`Branches of ${g(e.model.name)}:`,...W([fM,...t])].join(`
168
+ `)}});var uM=e=>Object.fromEntries(e.map(({key:t,kind:n,base:r,target:o,source:s})=>[t,{kind:n,...r===void 0?{}:{base:r},...o===void 0?{}:{target:o},...s===void 0?{}:{source:s}}])),uy=e=>({elementId:e.elementId,reason:e.reason,target:e.target,source:e.source,fields:uM(e.fields),...e.managedDependencyChanges===void 0?{}:{managedDependencyChanges:e.managedDependencyChanges}}),hM=e=>({elementId:String(e.elementId),rule:e.code,message:e.message,...e.property===void 0?{}:{property:e.property}}),hy=e=>({conflicts:e.conflicts.map(uy),mergeBaseId:e.mergeBaseId,targetHead:e.targetCommitId,sourceHead:e.sourceCommitId,names:e.resolvedNames,blockers:e.blockers,rejected:[]}),fy=e=>Array.isArray(e)?e:[],gy=e=>{let t=e;return{conflicts:fy(t.conflicts).map(uy),mergeBaseId:String(t.mergeBaseId??""),targetHead:String(t.targetCommitId??""),sourceHead:String(t.sourceCommitId??""),names:t.resolvedNames??{},blockers:[],rejected:fy(t.rejected).map(hM)}},Fo=(e,t)=>e[t]===void 0?t:g(e[t]),gM=(e,t)=>{let[n]=e.target.present?e.target.owners:e.source.owners,r=Fo(t,e.elementId);return n===void 0?r:`${Fo(t,n)}/${r}`},yM=(e,t)=>{let n=t.rejected.filter(r=>r.elementId===e.elementId).map(r=>({rule:r.rule,message:r.message,...r.property===void 0?{}:{property:r.property}}));return{elementId:e.elementId,label:gM(e,t.names),reason:e.reason,target:e.target,source:e.source,fields:Object.fromEntries(Object.entries(e.fields).map(([r,o])=>[r,{...o}])),...e.managedDependencyChanges===void 0?{}:{managedDependencyChanges:e.managedDependencyChanges},...n.length===0?{}:{rejected:n}}},yy=e=>e.blockers.length>0?"blocked":e.conflicts.length>0?"conflicts":"clean",pc=(e,t,n,r)=>{let o=new Set(t.conflicts.map(i=>i.elementId)),s=t.rejected.filter(i=>!o.has(i.elementId));return{...e,target:{...e.target,head:t.targetHead},source:{...e.source,head:t.sourceHead},outcome:n,mergeBaseId:t.mergeBaseId,blockers:t.blockers,names:t.names,resolutions:t.conflicts.map(i=>yM(i,t)),...r===void 0?{}:{takeOthers:r},...s.length===0?{}:{rejected:s}}};var pe="modeldesk branch merge --help",wM=new Set(["target","source"]),qo=e=>wM.has(e),fc=e=>typeof e=="string"?e:JSON.stringify(e)??"undefined",jr=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qi=(e,t,n)=>{let r=e[t];if(typeof r!="string"||r==="")throw k(`The resolution file has no '${t}' on ${n}.`,pe);return r},wy=(e,t)=>{let n=e[t];if(!jr(n))throw k(`The resolution file has no '${t}' branch.`,pe);return{id:qi(n,"id",t),head:qi(n,"head",t)}},bM=(e,t)=>{let{take:n}=e;if(n!=null){if(qo(n)||n==="fields")return n;throw k(`The entry for ${t} has take '${fc(n)}'; it takes 'target', 'source' or 'fields'.`,pe)}},EM=(e,t)=>{let{fields:n}=e;if(n==null)return{};if(!jr(n))throw k(`The entry for ${t} has 'fields' that is not an object keyed by field.`,pe);return Object.fromEntries(Object.entries(n).flatMap(([r,o])=>{let s=jr(o)?o.take:void 0;if(s==null)return[];if(!qo(s))throw k(`The field '${r}' of ${t} has take '${fc(s)}'; a field takes 'target' or 'source'.`,pe);return[[r,s]]}))},CM=(e,t)=>{if(!jr(e))throw k(`Entry ${t+1} of the resolution file is not an object.`,pe);let n=qi(e,"elementId",`entry ${t+1}`),r=bM(e,n),o=EM(e,n),s=Object.keys(o);if(r!==void 0&&r!=="fields"&&s.length>0)throw k(`The entry for ${n} takes '${r}' whole and also takes fields (${s.join(", ")}); pick one: a side for the element, or 'fields' with a side per field.`,pe);return{elementId:n,take:r??(s.length>0?"fields":void 0),fields:o}},by=e=>{let t;try{t=JSON.parse(e)}catch(o){throw k(`The resolution file is not JSON (${o.message}).`,pe)}if(!jr(t))throw k("The resolution file is not a JSON object.",pe);if(!jr(t.model))throw k("The resolution file has no 'model'.",pe);let{takeOthers:n}=t;if(n!=null&&!qo(n))throw k(`The resolution file has takeOthers '${fc(n)}'; it takes 'target' or 'source'.`,pe);let{resolutions:r}=t;if(r!==void 0&&!Array.isArray(r))throw k("The resolution file's 'resolutions' is not a list.",pe);return{model:{id:qi(t.model,"id","model")},target:wy(t,"target"),source:wy(t,"source"),...qo(n)?{takeOthers:n}:{},entries:(r??[]).map((o,s)=>CM(o,s))}},Ey=e=>{let t=e.lastIndexOf("="),n=t===-1?void 0:e.slice(t+1),r=()=>k(`--take takes <element>[#<field>]=target|source, got '${e}'.`,pe,{reason:`'take' takes <element>[#<field>]=target|source, got '${e}'.`});if(t===-1||!qo(n))throw r();let o=e.slice(0,t),s=o.lastIndexOf("#"),i=s===-1?o:o.slice(0,s),a=s===-1?void 0:o.slice(s+1);if(i===""||a==="")throw r();return{element:i,...a===void 0?{}:{field:a},side:n}},Cy=(e,t)=>{let n=e.find(o=>o.elementId===t.elementId),r=t.field===void 0?{elementId:t.elementId,take:t.side,fields:{}}:{elementId:t.elementId,take:"fields",fields:{...n?.take==="fields"?n.fields:{},[t.field]:t.side}};return n===void 0?[...e,r]:e.map(o=>o.elementId===t.elementId?r:o)},RM=e=>e.takeOthers===void 0?e.entries.filter(t=>t.take===void 0).map(t=>t.elementId):[],Ry=e=>{let t=RM(e);if(t.length>0){let n=t.length===1?"One entry has":`${t.length} entries have`;throw k(`${n} no take: ${t.join(", ")}. Fill in 'take' on each, or pass --take-others target|source for every entry left open.`,pe,{reason:`${n} no take: ${t.join(", ")}. Give a take for each, or takeOthers (target or source) for every entry left open.`})}},ky=(e,t)=>{let n=e.entries.flatMap(r=>r.take===void 0?[]:r.take!=="fields"?[{elementId:r.elementId,take:r.take}]:Object.keys(r.fields).length===0?[{elementId:r.elementId,take:"target"}]:[{elementId:r.elementId,take:"fields",fields:r.fields}]);return{source:e.source.id,message:t,expectedHeadId:e.target.head,expectedSourceHeadId:e.source.head,...n.length===0?{}:{resolutions:n},...e.takeOthers===void 0?{}:{takeOthers:e.takeOthers}}};var vy=String.raw`Separate labels with '/'; inside a label, write '/' as '\/' and '\' as '\\'.`,kM=e=>{let t=[],n="";for(let r=0;r<e.length;r++){let o=e[r];if(o==="\\"){let s=e[r+1];if(s!=="/"&&s!=="\\")throw new f(String.raw`'${e}' is not an element path: a '\' escapes only '/' or '\'.`,{exitCode:b.Usage,hint:vy});n+=s,r++}else o==="/"?(t.push(n),n=""):n+=o}if(t.push(n),t[0]===""&&t.shift(),t.at(-1)===""&&t.pop(),t.length===0||t.includes(""))throw new f(`'${e}' is not an element path.`,{exitCode:b.Usage,hint:vy});return t},Iy=e=>e.map(ec).join("/"),Sy=(e,t,n,r)=>{let o=[...new Set(e.children(t).map(d=>d.id))].filter(d=>r||!Vn(e.element(d)?.type??"")),s=o.filter(d=>d.toLowerCase()===n.toLowerCase());if(s.length>0)return s;let i=o.filter(d=>e.label(d)===n);if(i.length>0)return i;let a=n.toLowerCase();return o.filter(d=>e.label(d)?.toLowerCase()===a)},Fr="$",vM=(e,t,n)=>{let r=t.get(n.slice(Fr.length));if(r===void 0){let o=[...t.keys()].map(i=>`${Fr}${i}`).join(", "),s=o===""?"Give a create operation a key first.":`The keys so far: ${o}.`;throw new f(`No earlier operation of this batch created an element under '${n}'.`,{exitCode:b.Usage,hint:s,hosted:{hint:s}})}if(e.element(r)===void 0)throw new f(`The element created as ${n} was deleted by an earlier operation of this batch.`,{exitCode:b.Usage});return r},IM=(e,t)=>{let n=e.element(t)?t:t.toLowerCase();if(e.element(n)===void 0)throw new f(`No element ${t} in this model.`,{exitCode:b.NotFound});return n},SM=(e,t,n,r)=>new f(`No element labelled '${e}' ${t}.`,{exitCode:b.NotFound,hint:n?"It names an internal element; pass --internal to address it.":"Run 'modeldesk model tree' or 'modeldesk search' to find it.",details:r,hosted:{hint:n?"It names an internal element; address it by its id.":o=>`Call ${o("search")} or ${o("describe")} to find it.`}}),U=(e,t,n={})=>{if(e.keys!==void 0&&t.startsWith(Fr))return vM(e,e.keys,t);let r=n.internal??!1;if(B(t))return IM(e,t);let o=[],s=e.rootId;for(let i of kM(t)){let a=o.length===0?"at the top of the model":`under '${Iy(o)}'`,d=Sy(e,s,i,r);if(d.length===0){let l=!r&&Sy(e,s,i,!0).length>0;throw SM(i,a,l,{resolvedPath:Iy(o),resolvedId:s})}if(d.length>1)throw new f(`'${i}' ${a} names ${d.length} elements; address the one you mean by id.`,{exitCode:b.Usage,details:{candidates:d.map(l=>({id:l,type:e.element(l)?.type,label:e.label(l)}))}});s=d[0],o.push(i)}return s},$M="/",Wi=(e,t)=>t===$M?e.rootId:U(e,t);var qr=(e,t,n,r,o)=>new f(t,{exitCode:n,hint:r,type:e.type,requestId:e.requestId,details:e.details,hosted:o}),uc=e=>({hint:t=>`${e(t)}, then commit again.`}),TM=(e,t)=>qr(t,`You hold no draft of ${e} any more: it was committed or discarded since it was read. Nothing was committed.`,b.Failure,"Run 'modeldesk model log' to see what landed.",{hint:n=>`Call ${n("model log")} to see what landed.`}),xM=(e,t,n)=>{switch((e instanceof V?e.status:void 0)===404?"no-draft":e.type){case"draft-head-conflict":return qr(e,`The branch of ${t} moved past the commit your draft is based on, so the draft cannot land as it stands.`,b.Conflict,"Run 'modeldesk draft rebase', review what it reports, then commit again.",uc(o=>`Call ${o("draft rebase")} and review what it reports`));case"draft-moved":return qr(e,`Your draft of ${t} is not at ${n} any more: a change was staged, undone or rebased since, so nothing landed.`,b.Conflict,"Review it with 'modeldesk draft diff --changes', then commit again.",uc(o=>`Review it with ${o("draft diff")} and changes: true`));case"branch-head-conflict":return qr(e,`Your draft of ${t} changed while it was being committed, so nothing landed.`,b.Conflict,"Run 'modeldesk draft status', then commit again.",uc(o=>`Call ${o("draft status")}`));case"nothing-to-commit":return qr(e,`Your draft of ${t} holds no staged change, so there is nothing to commit.`,b.Failure);case"no-draft":return TM(t,e);default:return e}},AM=(e,t)=>{let r=(Array.isArray(e.details.commits)?e.details.commits:[]).find(o=>o.requestId===t);return r&&{id:r.id,message:r.message,requestId:r.requestId,actionTypes:r.actionTypes}},OM=async(e,t)=>{let{holder:n,draft:r,commitRequestId:o,retried:s}=t,i=e.exitCode===b.Transient,a=e instanceof V&&e.status===404;if(i||s&&a)try{let l=await n.findLanding(o,r);return l===void 0?{kind:"none"}:{kind:"landed",commit:l}}catch{return{kind:"unknown"}}let d=e.type==="draft-head-conflict"?AM(e,o):void 0;return d===void 0?{kind:"none"}:{kind:"landed",commit:d}},MM=(e,t)=>qr(e,`${e.reason} Whether your draft of ${t} landed is unknown: the branch could not be read to look for the commit.`,b.Transient,"Run 'modeldesk model log' to see whether it landed before you commit again.",{hint:n=>`Call ${n("model log")} to see whether it landed before you commit again.`}),Wr=async(e,t,n,r)=>{let o=await NM(e,t,n,r);return t.ref.kind==="model"&&e.content.drop(t.ref.id,n.id),o},NM=async(e,t,n,r)=>{let o=Er(e.origin),s={message:r.message,commitRequestId:o,expectedDraftHeadId:r.expectedDraftHeadId},i=async d=>({landing:{branch:await t.branch(n.targetRefId),commit:d},commitRequestId:o,recovered:!0}),a=async(d,l)=>{if(!(d instanceof f))throw d;let c=await OM(d,{holder:t,draft:n,commitRequestId:o,retried:l});if(c.kind==="landed")return c.commit;if(!l&&d.exitCode===b.Transient)return"retry";throw c.kind==="unknown"?MM(d,t.ref.name):xM(d,t.ref.name,r.expectedDraftHeadId)};for(let d=!1;;d=!0)try{return{landing:await t.commit(s),commitRequestId:o,recovered:!1}}catch(l){let c=await a(l,d);if(c!=="retry")return i(c)}},Hr=({branch:e,commit:t})=>({branch:"name"in e?{id:e.id,name:e.name}:{id:e.id},commit:t}),Br=(e,t,n=mi)=>{let{branch:r}=e;if(!(!("main"in r)||r.main))return n.afterLanding(`${t.id}@${g(r.name)}`)};var PM=/ \((\d+)\/(\d+)\)$/,DM=e=>{let t=PM.exec(e);if(t===null)return e;let[,n,r]=t.map(Number);return r>1&&n>=1&&n<=r?e.slice(0,t.index):e},LM=e=>DM(e.trim().split(/\r?\n/)[0].trim()),_M=e=>{let t=e.join("; ");if(t.length<=72)return t;let[n]=e;return`${n.length<=72?n:`${n.slice(0,71)}\u2026`} (and ${e.length-1} more)`},$y=e=>{let t=e.flatMap(s=>s.message===void 0?[]:[LM(s.message)]).filter(s=>s!=="").filter((s,i,a)=>s!==a[i-1]);if(t.length<=1)return t[0];let n=`${_M(t)}
169
169
 
170
- `,r=t.map(o=>`- ${o}`),s=n+r.join(`
171
- `);if(s.length<=2e3)return s;for(let o=r.length-1;;o--){let i=`${n}${r.slice(0,o).join(`
172
- `)}${o===0?"":`
173
- `}- and ${r.length-o} more`;if(i.length<=2e3)return i}};var zo={message:{type:"string",short:"m",required:!0,placeholder:"message",description:"Why, in your words: the line a person reviews the change by in the app and in history.",requiredReason:"Every change carries a message, the rationale a reviewer reads first; none is invented."}},Sn=(e,t)=>{if(e.trim()==="")throw $("The message (-m) is blank; say why, in your words.",t);if(e.length>2e3)throw $(`The message (-m) is ${e.length} characters long; it holds at most ${2e3}.`,t);return e},Yo="modeldesk draft commit --help",ox=async(e,t,n)=>{if(e.changes===void 0)throw new p(`The staged changes of ${n} cannot be listed, so committing it takes -m.`);let r=Hh((await e.changes(t)).reverse());if(r===void 0)throw $(`No change staged in your draft of ${n} carries a message, so committing it takes -m: a landing message is composed from what the author wrote, never invented.`,Yo);return r},Gh=O({path:["draft","commit"],effect:"land-draft",summary:"Commit your draft as one commit",description:"Lands everything your draft holds on its branch as one commit carrying the message: every staged change, whichever surface staged it, which is what a standalone commit means. Without -m, a model draft lands under a message composed from its staged changes' own messages, oldest first; a dataset draft takes -m. The landing names the draft head it read, or the one --expect gives, so a draft that moved since exits 5 with nothing written. Under an agent host (Claude Code, Cursor, AI_AGENT) committing is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1 or the draft aims at a branch named agent/<topic>, an agent's own, which a person reviews and merges in the app; a draft holding changes staged outside an agent session is left to them unless --any-surface. A draft based on a branch head that has moved on exits 5: run 'modeldesk draft rebase' first. After a landing off main you hold no draft, so unaddressed invocations default to main; the result says so.",positionals:[_e],flags:{message:{type:"string",short:"m",placeholder:"message",description:"Why, in your words: the line a person reviews the commit by. Without it a model draft lands under its staged changes' own messages, never an invented one."},expect:{type:"string",placeholder:"draft-head",description:"The draft head the landing must find: a draft at any other head is refused (exit 5)."},...tr},examples:['modeldesk draft commit <model> -m "Add the severity binding"',"modeldesk draft commit <model>"],run:async e=>ee(async()=>{let{message:t,expect:n}=e.flags;if(t!==void 0)Sn(t,Yo);else if(e.args.resource.kind==="dataset")throw $("Committing a dataset draft takes -m: its staged changes cannot be listed, so there is no message to compose from them.",Yo);if(n!==void 0&&!V(n))throw $("--expect takes the draft head id a read reported.",Yo);let r=await je(e),s=ue(r.ref),o=await r.read();if(o!==void 0&&er(e,e.commandName,r.ref,await r.branch(o.targetRefId)),o===void 0||o.changeCount===0)throw new p(`You hold no staged change on ${s}, so there is nothing to commit.`,{type:"nothing-to-commit"});await De(e,r,o,{scope:{kind:"all"},action:`Committing your draft of ${s}`,anySurface:e.flags["any-surface"],override:"pass --any-surface only when they asked for it."});let{landing:i,recovered:a}=await mr(e,r,o,{message:t??await ox(r,o.id,s),expectedDraftHeadId:n??o.headCommitId}),d=ur(i,r.ref);return{result:{resource:r.ref,landed:fr(i),...i.draftHeadCommitId?{draftHeadCommitId:i.draftHeadCommitId}:{},recovered:a,...d===void 0?{}:{next:d},...r.ref.kind==="model"?{url:W(e.instance(),{kind:"commit",modelId:r.ref.id,commitId:i.commit.id})}:{}}}}),render:e=>{let t=e.landed.branch.name===void 0?"":` on ${w(e.landed.branch.name)}`;return[`Committed your draft of ${ue(e.resource)} as ${e.landed.commit.id}${t}: ${w(e.landed.commit.message?.split(`
170
+ `,r=t.map(s=>`- ${s}`),o=n+r.join(`
171
+ `);if(o.length<=2e3)return o;for(let s=r.length-1;;s--){let i=`${n}${r.slice(0,s).join(`
172
+ `)}${s===0?"":`
173
+ `}- and ${r.length-s} more`;if(i.length<=2e3)return i}};var Ty={draftCommit:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},landed:{type:"object",properties:{branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}},description:"The branch the draft landed on and the commit it became."},draftHeadCommitId:{type:"string",description:"The draft head that landed, where the server reports it."},recovered:{type:"boolean",description:"True when the answer was lost and the landing was recognised on the branch by its request id. One of false, true."},next:{type:"string",description:"Present after a landing off main: where unaddressed invocations now go, and how to get back."},url:{type:"string",description:"The commit in the app; absent for a dataset."}},required:["schemaVersion","resource","landed","recovered"]}};var Bi={message:{type:"string",short:"m",required:!0,placeholder:"message",description:"Why, in your words: the line a person reviews the change by in the app and in history.",requiredReason:"Every change carries a message, the rationale a reviewer reads first; none is invented."}},Lt=(e,t)=>{if(e.trim()==="")throw k("The message (-m) is blank; say why, in your words.",t,{reason:"The message is blank; say why, in your words."});if(e.length>2e3)throw k(`The message (-m) is ${e.length} characters long; it holds at most ${2e3}.`,t,{reason:`The message is ${e.length} characters long; it holds at most ${2e3}.`});return e},Hi="modeldesk draft commit --help",FM=async(e,t,n)=>{if(e.changes===void 0)throw new f(`The staged changes of ${n} cannot be listed, so committing it takes -m.`);let r=$y((await e.changes(t)).reverse());if(r===void 0)throw k(`No change staged in your draft of ${n} carries a message, so committing it takes -m: a landing message is composed from what the author wrote, never invented.`,Hi);return r},xy=A({path:["draft","commit"],effect:"land-draft",summary:"Commit your draft as one commit",description:"Lands everything your draft holds on its branch as one commit carrying the message: every staged change, whichever surface staged it, which is what a standalone commit means. Without -m, a model draft lands under a message composed from its staged changes' own messages, oldest first; a dataset draft takes -m. The landing names the draft head it read, or the one --expect gives, so a draft that moved since exits 5 with nothing written. Under an agent host (Claude Code, Cursor, AI_AGENT) committing is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1 or the draft aims at a branch named agent/<topic>, an agent's own, which a person reviews and merges in the app; a draft holding changes staged outside an agent session is left to them unless --any-surface. A draft based on a branch head that has moved on exits 5: run 'modeldesk draft rebase' first. After a landing off main you hold no draft, so unaddressed invocations default to main; the result says so.",positionals:[je],flags:{message:{type:"string",short:"m",placeholder:"message",description:"Why, in your words: the line a person reviews the commit by. Without it a model draft lands under its staged changes' own messages, never an invented one."},expect:{type:"string",placeholder:"draft-head",description:"The draft head the landing must find: a draft at any other head is refused (exit 5).",toolDescription:"The draft head the landing must find: a draft at any other head is refused as a conflict."},...kr},examples:['modeldesk draft commit <model> -m "Add the severity binding"',"modeldesk draft commit <model>"],mcp:{name:"draft_commit",description:"Lands everything your draft holds on its branch as one commit. On a branch named agent/<topic> it needs no further permission; on any other branch only the person's 'Act without your review' permission lets it land, and without it the call is refused before anything is sent. A draft that also holds the person's or another session's changes is refused without that permission, and even with it, land those only when the person asks you to. Without message the commit is described by your staged changes' messages. A branch that moved past the baseline needs draft_rebase first. Commit before draft_status shows changeCount near maxChanges."},resultSchema:Ty.draftCommit,run:async e=>oe(async()=>{let{message:t,expect:n}=e.flags;if(t!==void 0)Lt(t,Hi);else if(e.args.resource.kind==="dataset")throw k("Committing a dataset draft takes -m: its staged changes cannot be listed, so there is no message to compose from them.",Hi);if(n!==void 0&&!B(n))throw k("--expect takes the draft head id a read reported.",Hi,{reason:"'expect' takes the draft head id a read reported."});let r=await Le(e),o=ce(r.ref),s=await r.read();if(s!==void 0&&Rr(e,e.commandName,r.ref,await r.branch(s.targetRefId)),s===void 0||s.changeCount===0)throw new f(`You hold no staged change on ${o}, so there is nothing to commit.`,{type:"nothing-to-commit"});await Be(e,r,s,{scope:{kind:"all"},action:`Committing your draft of ${o}`,anySurface:e.flags["any-surface"],override:"pass --any-surface only when they asked for it."});let{landing:i,recovered:a}=await Wr(e,r,s,{message:t??await FM(r,s.id,o),expectedDraftHeadId:n??s.headCommitId}),d=Br(i,r.ref,vr(e));return{result:{resource:r.ref,landed:Hr(i),...i.draftHeadCommitId?{draftHeadCommitId:i.draftHeadCommitId}:{},recovered:a,...d===void 0?{}:{next:d},...r.ref.kind==="model"?{url:e.webUrl({kind:"commit",modelId:r.ref.id,commitId:i.commit.id})}:{}}}}),render:e=>{let t=e.landed.branch.name===void 0?"":` on ${g(e.landed.branch.name)}`;return[`Committed your draft of ${ce(e.resource)} as ${e.landed.commit.id}${t}: ${g(e.landed.commit.message?.split(`
174
174
  `)[0]??"")}`,...e.recovered?["(The answer was lost; the commit was found on the branch by its request id.)"]:[],...e.next?[e.next]:[],...e.url?[`url: ${e.url}`]:[]].join(`
175
- `)}});var dx={clean:b.Success,conflicts:b.Conflict,blocked:b.Validation},lx=e=>{for(let[t,n]of[["--expect",e.expect],["--expect-source",e["expect-source"]]])if(n!==void 0&&!V(n))throw $(`${t} takes the commit id the preview reported as that branch's head.`,te);return{...e.expect?{target:e.expect}:{},...e["expect-source"]?{source:e["expect-source"]}:{}}},cx=(e,t,n)=>{let r=e.take.length>0||e["take-others"]!==void 0;if(n&&(r||e.resolve!==void 0||t.target!==void 0||t.source!==void 0))throw $("A dry run previews the merge and takes no --resolve, --take, --take-others, --expect or --expect-source.",te);if(e.resolve!==void 0&&(t.target!==void 0||t.source!==void 0))throw $("--resolve carries both heads in the file; --expect and --expect-source are not taken with it.",te);if(r&&e.resolve===void 0&&(t.target===void 0||t.source===void 0))throw $("--take and --take-others bind to the heads you reviewed: pass both --expect <target-head> and --expect-source <source-head> as the preview reported them, or --resolve <file>.",te)},mx=async(e,t)=>{if(t==="-")return e.readStdin();try{return ix(ax(e.cwd,t),"utf8")}catch(n){throw $(`Could not read the resolution file ${t} (${n.message}).`,te)}},fx=(e,t)=>{if(e.model.id!==t.model.id)throw $(`The resolution file is for model ${e.model.id}, not ${w(t.model.name)} (${t.model.id}).`,te);if(e.target.id!==t.target.id||e.source.id!==t.source.id)throw $(`The resolution file is for merging ${e.source.id} into ${e.target.id}, not ${w(t.source.name)} (${t.source.id}) into ${w(t.target.name)} (${t.target.id}).`,te)},ux=async(e,t,n,r,s)=>{let o=await oe(e,t).branches(),i=V(n),a=o.find(l=>i?l.id===n.toLowerCase():En(l.name,n));if(a===void 0){let l=i?n:`named '${w(n)}'`;throw new p(`${w(s)} has no branch ${l}.`,{exitCode:b.NotFound,type:"ref-not-found",details:{branches:o.map(c=>c.name)}})}let d=rt(a);if(d.id===r.id)throw $(`The source and the target are the same branch (${w(d.name)}); a merge takes two.`,te);return d},px=e=>({id:e.id,...e.message?{message:e.message}:{},...e.requestId?{requestId:e.requestId}:{},createdAt:e.createdAt,actionTypes:e.actionTypes}),hx=(e,t,n)=>{let r=n.conflicts.length,s=n.rejected.length,o=s===1?"was":"were",i=s===0?"":`, and ${P(s,"resolution")} it was given ${o} refused`;return new p(`Merging ${w(t.source.name)} into ${w(t.target.name)} of ${w(t.model.name)} conflicts on ${P(r,"element")}${i}; nothing was merged.`,{exitCode:b.Conflict,type:"merge-conflict",requestId:e.requestId,hint:"The report is on stdout (--json > merge.json captures it): fill in 'take' on each entry (target, source, or fields with a side per field) and run again with --resolve merge.json. An entry marked rejected needs another pick.",details:{conflicts:r,rejected:s}})},Yh=e=>`modeldesk branch merge ${e.model.id}@${w(e.target.name)} ${w(e.source.name)} --dry-run --json > merge.json`,gx=(e,t)=>{let n=e.details.conflict??{},r=n.branchId===t.source.id?t.source:t.target,s=typeof n.currentHeadCommitId=="string"?` (its head is now ${n.currentHeadCommitId})`:"";return new p(`${w(r.name)} moved since the heads this merge was bound to${s}, so nothing was merged.`,{exitCode:b.Conflict,type:"branch-head-conflict",requestId:e.requestId,hint:`Run the preview again, '${Yh(t)}', fill in the takes, and run again with --resolve merge.json.`,details:e.details})},yx=(e,t)=>{let n=typeof e.details.rule=="string"?e.details.rule:"unknown",r=typeof e.details.elementId=="string"?` on ${e.details.elementId}`:"";return new p(`The merge refused a resolution${r} (${n}); nothing was merged.`,{exitCode:e.exitCode,type:e.type,requestId:e.requestId,hint:`Run the preview again, '${Yh(t)}', and fill in the takes on its report.`,details:e.details})},wx=async(e,t)=>{let n;try{n=await e.branches.mergePreview(t.model.id,t.target.id,t.source.id)}catch(o){if(o instanceof p&&o.type==="nothing-to-merge")return{result:{...t,outcome:"already-merged"}};throw o}let r=Oh(n),s=Lh(r);return{result:ml(t,r,s),exitCode:dx[s]}},bx=(e,t,n,r,s)=>{let o=r===void 0?{}:{takeOthers:r};if(e!==void 0)return{...e,...o};if(!(n.target===void 0||n.source===void 0||t.length===0&&r===void 0))return{model:{id:s.model.id},target:{id:s.target.id,head:n.target},source:{id:s.source.id,head:n.source},...o,entries:[]}},kx=async(e,t,{bound:n,heads:r,takes:s,text:o})=>{if(n===void 0)return{source:t.source.id,message:o,...r.target===void 0?{}:{expectedHeadId:r.target},...r.source===void 0?{}:{expectedSourceHeadId:r.source}};let i=await Cx(e,t,s),a={...n,entries:i.reduce((d,l)=>jh(d,l),n.entries)};return Fh(a),qh(a,o)},Ex=(e,t,n)=>{if(!(e instanceof p))throw e;switch(e.type){case"nothing-to-merge":return{result:{...t,outcome:"already-merged"}};case"merge-conflict":{let r=Nh(e.details);return{result:ml(t,r,"conflicts",n.takeOthers),refusal:hx(e,t,r)}}case"branch-head-conflict":throw gx(e,t);case"invalid-resolution":throw yx(e,t);default:throw e}},zh=O({path:["branch","merge"],effect:"land-direct",summary:"Merge a branch into the addressed one",description:"Merges the source branch into the branch the address names, as one commit with both heads as parents. --dry-run is the preview: it exits 0 when the merge would land clean, 5 when the branches conflict, 4 when the merged model would break a rule no pick resolves, and the report it prints under --json is the resolution file: fill in 'take' on each entry (target, source, or fields with a side per field) and pass it back with --resolve <file> or - for standard input. The file carries both heads, so a branch that moved since the preview exits 5. A person picks inline with --take <element>[#<field>]=target|source, together with --expect and --expect-source as the preview reported the heads; --take-others takes every other conflict from one side. A merge refused with conflicts prints the same report on stdout and the error on stderr, exit 5; one with nothing to merge exits 0 as already-merged, so a re-run converges. Under an agent host a merge is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1, whatever the branches; the preview runs.",positionals:[_(bt),{name:"source",type:"string",required:!0,description:"The branch to merge from, by name (ignoring case) or id: another branch of the same model."}],flags:{message:{type:"string",short:"m",placeholder:"message",description:"What the merge commit is called in history; 'Merged <source> into <target>' unless given."},resolve:{type:"string",placeholder:"file",description:"The report printed by --dry-run --json or by a refused merge, with 'take' filled in; '-' reads standard input. Only ids, takes and both heads are read from it."},take:{type:{list:"string"},placeholder:"element[#field]=target|source",description:"Take one conflicting element, or one of its fields, from a side; the element by id, or by its label path on the target branch. Needs both --expect flags, or --resolve, so the pick binds to heads you reviewed."},"take-others":{type:{enum:["target","source"]},description:"The side every conflict no other pick names is taken from whole. Needs the heads as --take does."},expect:{type:"string",placeholder:"target-head",description:"The head the target branch must still be at, as the preview reported it (exit 5 otherwise)."},"expect-source":{type:"string",placeholder:"source-head",description:"The head the source branch must still be at, as the preview reported it (exit 5 otherwise)."}},dryRun:!0,examples:["modeldesk branch merge <model>@main feat/x --dry-run --json > merge.json","modeldesk branch merge <model>@main feat/x --resolve merge.json","modeldesk branch merge <model>@main feat/x --take SHACL/NodeShape#severity=source --take-others target --expect <target-head> --expect-source <source-head>"],run:async e=>{let{flags:t,globals:n}=e,r=t.take.map(_h),s=lx(t);cx(t,s,n.dryRun);let o=t.message===void 0?void 0:Sn(t.message,te),i=t.resolve===void 0?void 0:Dh(await mx(e,t.resolve)),a=e.args.model,d=await Z(e,a,bt),l=Ve(d),c=await ux(e,a.model,e.args.source,l,d.name),m={model:{id:d.id,name:d.name},ref:de(d),target:{id:l.id,name:l.name,head:l.head},source:{id:c.id,name:c.name,head:c.head}},f=e.api();if(n.dryRun)return wx(f,m);i!==void 0&&fx(i,m);let g=bx(i,r,s,t["take-others"]??i?.takeOthers,m),u=o??`Merged ${c.name} into ${l.name}`,h=await kx(e,m,{bound:g,heads:s,takes:r,text:u});try{let y=await f.branches.merge(m.model.id,l.id,h);return{result:{...m,target:{...m.target,head:y.targetCommitId},source:{...m.source,head:y.sourceCommitId},outcome:"merged",mergeBaseId:y.mergeBaseId,commit:px(y.commit),resolved:h.resolutions?.length??0,...h.takeOthers===void 0?{}:{takeOthers:h.takeOthers}}}}catch(y){return Ex(y,m,h)}},render:e=>{let t=w(e.model.name),n=w(e.target.name),r=w(e.source.name);switch(e.outcome){case"already-merged":return`${n} of ${t} already holds everything on ${r}; there is nothing to merge.`;case"merged":{let s=e.resolved>0?` (${P(e.resolved,"conflict")} resolved)`:"";return`Merged ${r} into ${n} of ${t} as ${e.commit.id}${s}: `+w(e.commit.message?.split(`
176
- `)[0]??"")}case"clean":return`Merging ${r} into ${n} of ${t} would land clean (merge base ${e.mergeBaseId}); nothing was merged (dry run).`;case"blocked":return[`Merging ${r} into ${n} of ${t} is blocked by ${P(e.blockers.length,"rule")} the merged model would break:`,...e.blockers.map(s=>` - ${w(s)}`),...e.resolutions.length===0?[]:[`It also conflicts on ${P(e.resolutions.length,"element")}:`,...e.resolutions.flatMap(s=>Kh(s,e.names,n,r))]].join(`
177
- `);case"conflicts":return[`Merging ${r} into ${n} of ${t} conflicts on ${P(e.resolutions.length,"element")} (merge base ${e.mergeBaseId}):`,...e.resolutions.flatMap(s=>Kh(s,e.names,n,r)),...(e.rejected??[]).map(s=>` rejected on ${s.elementId}: ${w(s.message)} (${s.rule})`),"Run with --json > merge.json, fill in 'take' on each entry, and pass it back with --resolve merge.json."].join(`
178
- `)}}}),Cx=async(e,t,n)=>{let s=n.filter(o=>!V(o.element)).length===0?void 0:Bt(await e.api().models.get(t.model.id,{ref:t.target.id,expand:["labels"]}));return n.map(o=>({elementId:s===void 0||V(o.element)?o.element.toLowerCase():le(s,o.element,{internal:!0}),...o.field===void 0?{}:{field:o.field},side:o.side}))},Rx=(e,t,n)=>typeof e=="string"?n?os(t,e):w(e):w(JSON.stringify(e)),ul=(e,t,n)=>e===void 0||e.length===0?"(none)":e.map(r=>Rx(r,t,n)).join(", "),Vh=(e,t)=>{if(!e.present)return"absent";let n=e.owners.length===0?"":` under ${e.owners.map(r=>os(t,r)).join(", ")}`;return`${e.type??"present"}${n}`},Sx=(e,t,n,r,s)=>{let o=t.kind==="relation",i=t.base===void 0?"":` | base ${ul(t.base,n,o)}`;return` ${e}: ${r} ${ul(t.target,n,o)} | ${s} ${ul(t.source,n,o)}${i}`},Kh=(e,t,n,r)=>{let s=[Vh(e.target,t),Vh(e.source,t)];return[` ${w(e.label)} ${e.reason} ${e.elementId}`,...s[0]===s[1]?[]:[` on ${n}: ${s[0]}; on ${r}: ${s[1]}`],...Object.entries(e.fields).map(([o,i])=>Sx(o,i,t,n,r)),...(e.rejected??[]).map(o=>` rejected: ${w(o.message)} (${o.rule})`)]};var Jo=(e,t)=>e.at(-1)===""&&t==="";var vx=/^<figure data-md-diagram="([^"]*)"[ >]/,Ix=e=>vx.exec(e)?.[1],$x="</figure>",Jh=(e,t)=>{if(t.size===0||e.payloads===void 0)return e;let n=Object.fromEntries(Object.entries(e.payloads).map(([r,s])=>[r,xx(s,t)]));return{...e,payloads:n}},xx=(e,t)=>{let n=e.split(`
179
- `),r=[];for(let s=0;s<n.length;s+=1){let o=Ix(n[s]),i=o!==void 0&&t.has(o)?n.indexOf($x,s):-1;if(i===-1){r.push(n[s]);continue}s=i,Jo(r,n[s+1])&&(s+=1)}return r.join(`
180
- `)};var pl=e=>`${JSON.stringify(e,null,2)}
181
- `;var xe=["intro","after"],at=e=>{let t=new Map;for(let n of e.fragments??[]){let r=t.get(n.elementId)??{};t.set(n.elementId,{title:r.title||n.title||void 0,kind:r.kind||n.kind||void 0,anchor:r.anchor||n.realization?.anchor||void 0})}return t},Mx=/^<!-- md-slot (?=intro [0-9a-f-]{36} -->$|after )(intro|after) ([0-9a-f-]{36})(?: heading=([1-6]))? -->$/,Ax="<!-- md-slot ",ds=class extends Error{constructor(n){super(`The bundle carries a note slot this version cannot read: ${n}. The client is older than the server.`);this.line=n;this.name="UnreadableSlotError"}line},Qh=e=>{if(!e.startsWith(Ax))return;let t=Mx.exec(e);if(t===null)throw new ds(e);let n={name:t[1],elementId:t[2]};return t[3]===void 0?n:{...n,heading:Number(t[3])}},Zh=e=>{let t=new Map;for(let[n,r]of Object.entries(e.payloads??{})){let s=r.split(`
182
- `).flatMap(o=>Qh(o)??[]);s.length>0&&t.set(n,s)}return t},hl=(e,t)=>{if(e.payloads===void 0)return{bundle:e,filled:[],dropped:[]};let n=at(e.manifest),r=a=>n.get(a)?.anchor,s=[],o=[],i=Object.fromEntries(Object.entries(e.payloads).map(([a,d])=>{let l=Tx(d,t,r);return s.push(...l.filled.map(c=>({...c,address:a}))),o.push(...l.dropped.map(c=>({...c,address:a}))),[a,l.text]}));return{bundle:{...e,payloads:i},filled:s,dropped:o}},Tx=(e,t,n)=>{let r=e.split(`
183
- `),s=[],o=new Set,i=[],a=[];for(let d=0;d<r.length;d+=1){let l=Qh(r[d]);if(l===void 0){s.push(r[d]);continue}let c=t.get(l.elementId)?.[l.name],m=`${l.name} ${l.elementId}`;if(c!==void 0&&!o.has(m)){o.add(m),i.push(l),s.push(...Ox(l,c,n));continue}c!==void 0&&a.push(l),Jo(s,r[d+1])&&(d+=1)}return{text:s.join(`
184
- `),filled:i,dropped:a}},Ox=(e,t,n)=>{if(e.heading===void 0){if(typeof t!="string")throw new Error(`The ${e.name} slot of ${e.elementId} takes a note path, not a heading.`);return[Xh(t)]}if(typeof t=="string")throw new Error(`The ${e.name} slot of ${e.elementId} takes a note with a heading.`);let r=n(e.elementId);if(r===void 0)throw new Error(`The bundle's manifest has no anchor for ${e.elementId}.`);let s=t.heading.replace(/\s+/g," ").trim();if(s==="")throw new Error(`The ${e.name} note of ${e.elementId} has an empty heading.`);let o=`${r}-${vn(s)||e.name}`;return[`${"#".repeat(e.heading)} ${Lx(s)} {#${o}}`,"",Xh(t.file)]},vn=e=>e.normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),Xh=e=>`<div data-include-format="markdown" data-include="${Nx(e)}"></div>`,Nx=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g,"&#10;").replace(/\r/g,"&#13;"),Lx=e=>e.replace(/[\\`*_[\]()!#|~]/g,"\\$&").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\{/g,"&#123;").replace(/\}/g,"&#125;");var ls="http://www.w3.org/2000/svg",ng="Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",gl="group",yl="spacingAndGlyphs",wl="italic",bl="underline",pr="none";var Xo="hidden",Qo="stroke",kl="auto";var Px="start",Zo="clip",Dx=/^[A-Za-z0-9_-]+$/,_x=/[^A-Za-z0-9_-]+/g,El=e=>Dx.test(e),rg=e=>e.replace(_x,"-");var Cl=(e,t)=>t?`${e}-${Px}`:e,eg=String.raw`-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?`,tg=String.raw`[a-zA-Z]+\(\s*(?:${eg}(?:[\s,]+${eg})*)?\s*\)`,jx=new RegExp(String.raw`^${tg}(?:\s+${tg})*$`),sg=e=>jx.test(e);var Fx=/[\u0000- \u007F]/g,qx=/^([a-zA-Z][a-zA-Z0-9+.-]*):/,Bx=new Set(["http","https","mailto"]),ei=e=>{let t=Ur(e).replace(Fx,"");if(t==="")return!1;let n=qx.exec(t);return n===null||Bx.has(n[1].toLowerCase())};var K="#4b5563";var Ye="white";var Rl="strokeWidth",ti=[{id:"triangle-filled",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"line",x1:16,y1:10,x2:20,y2:10,stroke:"white",strokeWidth:2},{element:"path",d:"M 6 4 L 19 10 L 6 16 L 10 10 Z",fill:K,stroke:K,strokeWidth:1}]},{id:"triangle-hollow",markerWidth:24,markerHeight:24,refX:24,refY:12,shapes:[{element:"line",x1:20,y1:12,x2:24,y2:12,stroke:"white",strokeWidth:2},{element:"path",d:"M 6 2 L 22 12 L 6 22 Z",fill:Ye,stroke:K,strokeWidth:2}]},{id:"diamond-filled",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 10 5 L 19 10 L 10 15 L 1 10 Z",fill:K,stroke:K,strokeWidth:1.5}]},{id:"diamond-hollow",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 10 5 L 19 10 L 10 15 L 1 10 Z",fill:Ye,stroke:K,strokeWidth:1.5}]},{id:"arrow-open",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 6 4 L 19 10 L 6 16",fill:"none",stroke:K,strokeWidth:2}]},{id:"bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:K,strokeWidth:1.5}]},{id:"circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"circle",cx:13.5,cy:6,r:2.75,fill:Ye,stroke:K,strokeWidth:1.5}]},{id:"crowsfoot",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:K,strokeWidth:1.5}]},{id:"crowsfoot-bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:K,strokeWidth:1.5},{element:"line",x1:4,y1:1,x2:4,y2:11,stroke:K,strokeWidth:1.5}]},{id:"crowsfoot-circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:K,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:Ye,stroke:K,strokeWidth:1.5}]},{id:"bar-circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:K,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:Ye,stroke:K,strokeWidth:1.5}]},{id:"crowsfoot-triangle-circle",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 24 3 L 19 3 M 24 6 L 19 6 M 24 9 L 19 9",fill:"none",stroke:K,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:Ye,stroke:K,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:Ye,stroke:K,strokeWidth:1.5}]},{id:"crowsfoot-triangle-bar",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 24 3 L 19 3 M 24 6 L 19 6 M 24 9 L 19 9",fill:"none",stroke:K,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:Ye,stroke:K,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:K,strokeWidth:1.5}]},{id:"triangle-circle",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:Ye,stroke:K,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:Ye,stroke:K,strokeWidth:1.5}]},{id:"triangle-bar",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:Ye,stroke:K,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:K,strokeWidth:1.5}]},{id:"cup",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 13 1 A 5 5 0 0 0 13 11",fill:"none",stroke:K,strokeWidth:1.5}]}],L2=new Map(ti.map(e=>[e.id,e]));var Vx=" ",Sl=["fill","fill-opacity","stroke","stroke-opacity","stroke-width","stroke-dasharray"],Kx={svg:["xmlns","viewBox","width","height","role","aria-label","font-family"],defs:[],marker:["id","markerWidth","markerHeight","refX","refY","orient","markerUnits"],clipPath:["id"],g:["data-md-element","clip-path","transform"],a:["href"],title:[],desc:[],rect:["x","y","width","height","rx",...Sl],path:["d",...Sl,"stroke-linejoin","marker-start","marker-end","visibility","pointer-events"],polygon:["points",...Sl],line:["x1","y1","x2","y2","fill","stroke","stroke-opacity","stroke-width","stroke-dasharray"],circle:["cx","cy","r","fill","stroke","stroke-width"],text:["x","y","font-size","font-weight","font-style","text-decoration","fill","fill-opacity","textLength","lengthAdjust"]},cg=new Map(Object.entries(Kx).map(([e,t])=>[e,new Set(t)])),Yx=new Set(["title","desc","text"]),og="svg",hr="g",kt="a",mg="title",cs="data-md-element",fg="path",ug=["visibility","pointer-events"],pg=new Set(["rect","text","polygon","line"]),zx={"clip-path":"clipPath","marker-start":"marker","marker-end":"marker"},hg=/&(amp|lt|gt|quot|apos);/g,Jx={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},Xx=/[<>"']/,Qx=/[\u0000-\u001F]/,Zx=/^<([^\s/>]+)/,eM=/^<\/([^\s/>]+)>/,vl=/ ([^\s=/>"'<]+)=/y,Il=/"([^"]*)"/y,tM=/^on/i,nM=/^ */,rM=64,ig=/[\p{Cc}\p{Cf}\u2028\u2029]/gu,Et=String.raw`-?\d+(?:\.\d+)?(?:e\+\d+)?`,sM=new RegExp(`^${Et}$`),oM=/^(?:[1-9]\d{0,2}|1000)$/,iM=new RegExp(`^0 0 ${Et} ${Et}$`),aM=new RegExp(`^${Et}(?:[ ,]${Et})*$`),dM=new RegExp(`^(?:${Et},${Et}(?: ${Et},${Et})*)?$`),lM=/^[MmZzLlHhVvCcSsQqTtAa0-9eE.,+\- ]*$/,gg=/^url\(#([A-Za-z0-9_-]+)\)$/,yg=/^#[0-9a-f]{6}$/,ag=Array.from(new Set([pr,...ti.flatMap(({shapes:e})=>e.flatMap(t=>["fill"in t?t.fill:pr,t.stroke])).filter(e=>!yg.test(e))])),wg=ti.flatMap(({id:e})=>[Cl(e,!1),Cl(e,!0)]),cM=new RegExp(`^${Zo}-[1-9]\\d*$`),mM=new RegExp(`-${Zo}-[1-9]\\d*$`),Ml=`${"md"}-`,Al=e=>`U+${e.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}`,Re=e=>{let t=[];for(let n of e){if(t.length===rM)return`${t.join("").replace(ig,Al)}\u2026`;t.push(n)}return e.replace(ig,Al)},bg=e=>{if(e.includes("&#"))return"a numeric character reference is not allowed";let t=e.replace(hg,"");if(t.includes("&"))return"& does not start one of the five XML entities";let n=Xx.exec(t);return n===null?void 0:`an unescaped ${n[0]} is not allowed`},kg=e=>e.replace(hg,(t,n)=>Jx[n]),In=(e,t)=>n=>e.test(n)?void 0:`"${Re(n)}" is not ${t}`,ze=(e,t)=>n=>e.includes(kg(n))?void 0:`"${Re(n)}" is not ${t}`,dg=()=>{},ce=In(sM,"a number as the serializer writes one"),lg=e=>yg.test(e)||ag.includes(e)?void 0:`"${Re(e)}" is not a paint the serializer writes (#rrggbb, ${ag.join(", ")})`,$l=In(gg,"a reference to a definition in the file, as url(#\u2026)"),fM=e=>cM.test(e)?"clipPath":wg.includes(e)?"marker":void 0,uM=(e,t)=>{if(!e.startsWith(Ml))return;let n=e.slice(Ml.length);if(t!==void 0)return n.startsWith(`${t}-`)?fM(n.slice(t.length+1)):void 0;if(El(n))return(mM.exec(n)?.index??0)>0?"clipPath":wg.some(r=>n.length>r.length+1&&n.endsWith(`-${r}`))?"marker":void 0},pM=(e,t,{idPrefix:n})=>{if(uM(e,n)===t)return;let r=n??"<prefix>",s=t==="marker"?"<marker>[-start]":`${Zo}-<n>`;return`"${Re(e)}" is not an id the serializer gives a <${t}> (${Ml}${r}-${s})`},hM=e=>{let t=kg(e);return t.startsWith("#")&&ei(t)?void 0:`"${Re(e)}" does not point at a section of the page (#\u2026)`},gM={xmlns:ze([ls],"the SVG namespace"),viewBox:In(iM,"a viewBox the serializer writes (0 0 width height)"),width:ce,height:ce,role:ze([gl],`the role the serializer writes (${gl})`),"aria-label":dg,"font-family":ze([ng],"the serializer's font stack"),id:pM,markerWidth:ce,markerHeight:ce,refX:ce,refY:ce,orient:ze([kl],`the marker orientation the serializer writes (${kl})`),markerUnits:ze([Rl],`the marker units the serializer writes (${Rl})`),"data-md-element":dg,"clip-path":$l,transform:e=>sg(e)?void 0:`"${Re(e)}" is not a transform of numbers the serializer writes`,href:hM,x:ce,y:ce,rx:ce,fill:lg,"fill-opacity":ce,stroke:lg,"stroke-opacity":ce,"stroke-width":ce,"stroke-dasharray":In(aM,"a dash pattern of numbers"),d:In(lM,"path data (commands and numbers only)"),"stroke-linejoin":ze(["round"],"the line join the serializer writes (round)"),"marker-start":$l,"marker-end":$l,points:In(dM,"polygon points as the serializer writes them (x,y x,y \u2026)"),x1:ce,y1:ce,x2:ce,y2:ce,cx:ce,cy:ce,r:ce,"font-size":ce,"font-weight":In(oM,"a numeric font weight (1 to 1000)"),"font-style":ze([wl],`the font style the serializer writes (${wl})`),"text-decoration":ze([bl],`the decoration the serializer writes (${bl})`),textLength:ce,lengthAdjust:ze([yl],`the length adjustment the serializer writes (${yl})`),visibility:ze([Xo],`the visibility of a hit area (${Xo})`),"pointer-events":ze([Qo],`the pointer events of a hit area (${Qo})`)},yM=(e,t)=>{if(tM.test(t))return`the event-handler attribute ${Re(t)} is not allowed`;if(t.toLowerCase()==="style")return"a style attribute is not allowed";if(t.toLowerCase()==="class")return"a class attribute is not allowed";if(t.includes(":"))return`the namespaced attribute ${Re(t)} is not allowed`;if(!cg.get(e).has(t))return`<${e}> does not take the attribute ${Re(t)}`},wM=(e,t,n,r)=>{let s=bg(n)??gM[t](n,e,r);return s===void 0?void 0:`${t}: ${s}`},bM=(e,t,n,r)=>{let s=new Map,o=n;for(;t[o]!==">"&&!t.startsWith("/>",o);){vl.lastIndex=o;let i=vl.exec(t)?.[1];if(i===void 0)return{problem:'a tag the serializer would not write: expected ` name="value"`, `>` or `/>`'};Il.lastIndex=vl.lastIndex;let a=Il.exec(t)?.[1];if(a===void 0)return{problem:`the value of ${Re(i)} is not double-quoted`};let d=yM(e,i)??wM(e,i,a,r);if(d!==void 0)return{problem:d};if(s.has(i))return{problem:`<${e}> repeats the attribute ${i}`};s.set(i,a),o=Il.lastIndex}return{attributes:s,end:o}},xl=e=>e.startsWith("<")?"more than one element on one line":"text outside <title> and <text>",kM=(e,t)=>{if(e.includes("<!"))return{problem:"a markup declaration (<!\u2026>: a DOCTYPE, an ENTITY, a comment or CDATA) is not allowed"};if(e.includes("<?"))return{problem:"a processing instruction (<?\u2026?>) is not allowed"};if(e.startsWith("</")){let m=eM.exec(e);if(m===null)return{problem:"a closing tag the serializer would not write"};let f=e.slice(m[0].length);return f!==""?{problem:xl(f)}:{line:{kind:"close",name:m[1]}}}let n=Zx.exec(e)?.[1];if(n===void 0)return{problem:"the line does not start with a tag"};if(!cg.has(n))return{problem:`<${Re(n)}> is not an element the diagram serializer writes`};let r=bM(n,e,n.length+1,t);if("problem"in r)return r;let{attributes:s,end:o}=r,i=e.startsWith("/>",o),a=e.slice(o+(i?2:1));if(!Yx.has(n))return a!==""?{problem:xl(a)}:{line:{kind:i?"empty":"open",name:n,attributes:s}};if(i||a==="")return{problem:`<${n}> has to hold its text on one line, as <${n}>\u2026</${n}>`};let d=`</${n}>`,l=a.indexOf(d);if(l===-1)return{problem:`<${n}> is not closed on its line`};if(l+d.length!==a.length)return{problem:xl(a.slice(l+d.length))};let c=bg(a.slice(0,l));return c===void 0?{line:{kind:"text",name:n,attributes:s}}:{problem:`text: ${c}`}},EM=(e,t)=>{if(e.name===og!=(t===0))return t===0?`the file opens with <${e.name}>, not the serializer's <svg xmlns="${ls}"> root`:"<svg> is only the root, never nested";if(e.name===og&&(e.kind!=="open"||e.attributes.get("xmlns")!==ls))return`the root is not the serializer's <svg xmlns="${ls}">`;if(e.name===kt&&!e.attributes.has("href"))return"<a> without an href"},CM=(e,t,n)=>{if(t.name===kt&&t.children===0&&e.name!==mg)return"<a> has to open with the <title> of the group it links";if(e.name===kt)return e.kind!=="open"?"<a> is only written open, around the title and body of the group it links":t.name!==hr||!t.stamped||t.children!==0?`<a> is only written as the first child of a <g ${cs}>`:n>0?"an <a> inside another <a>":void 0},Eg=e=>ug.some(t=>e.attributes.has(t)),RM=(e,t)=>e.size===t.size&&Array.from(t).every(([n,r])=>e.get(n)===r),Cg=e=>e.findLast(t=>t.stamped),Rg="a line's group draws no box: it holds no <rect>, <text>, <polygon> or <line>",Sg="a line's group holds no stamped group of its own",ni="desc",SM=e=>e!==void 0&&(e.hitArea||e.described),vM={d:()=>!0,fill:e=>e===pr,stroke:e=>e===K,"stroke-opacity":e=>e==="0","stroke-width":e=>e===Ed(1),"stroke-dasharray":e=>e==="6 4","marker-start":()=>!0,"marker-end":()=>!0},vg=e=>e.name===fg&&e.attributes.get("fill")===pr&&e.attributes.get("stroke")===K&&Array.from(e.attributes).every(([t,n])=>vM[t]?.(n)??!1),Ig=e=>{let t=e.at(-1),n=t?.name===kt?e.at(-2):t;return n?.name===hr&&n.stamped?n:void 0},IM=(e,t)=>{if(!Eg(e))return;let n=t.at(-1),r=n.name===kt?t.at(-2):n;if(r?.name!==hr||!r.stamped)return`a hit area (${ug.join(", ")}) is only written in a <g ${cs}>`;if(r.hitArea)return"a stamped group holds one hit area";if(r===n&&r.linked)return"in a linked group, the hit area is inside the link";if(r.drawsBox)return Rg;if(r.nestsStamp)return Sg;let s=n.previous;if(s===void 0||s!==n.firstPath||!vg(s))return"a hit area follows the line's route, the first path of its group";let o=new Map([["d",s.attributes.get("d")??""],["fill",pr],["stroke",K],["stroke-width",Ed(10)],["visibility",Xo],["pointer-events",Qo]]);return RM(e.attributes,o)?void 0:`a hit area is the route before it as <path ${Array.from(o.keys()).join(" ")}>, with the serializer's values`},$M=(e,t)=>{let n=Cg(t);if(SM(n))return pg.has(e.name)?Rg:e.name===hr&&e.attributes.has(cs)?Sg:void 0},xM=(e,t)=>{if(e.name!==ni)return;let n=t.at(-1);return Ig(t)===void 0||n.children!==1||n.previous?.name!==mg?`a <${ni}> is only written right after the <title> that opens a stamped group`:void 0},Tl=(e,t={})=>{if(t.idPrefix!==void 0&&!El(t.idPrefix))return`the id prefix "${Re(t.idPrefix)}" is not one the serializer accepts`;let n=e.split(`
185
- `);if(n.at(-1)===""&&n.pop(),n.length===0)return"the file is empty";let r=[],s=new Map,o=[],i=0,a=!1;for(let[c,m]of n.entries()){let f=c+1,g=A=>`line ${f}: ${A}`;if(m==="")return g("a blank line");let u=Qx.exec(m);if(u!==null)return g(`the control character ${Al(u[0])} is not allowed`);if(Ur(m)!==m)return g("a code point XML cannot carry is not allowed");if(a)return g("content after the root element");let h=m.replace(nM,""),y=kM(h,t);if("problem"in y)return g(y.problem);let{line:k}=y,S=k.kind==="close"?r.pop():void 0;if(k.kind==="close"&&S?.name!==k.name)return g(S===void 0?`</${Re(k.name)}> closes nothing`:`</${Re(k.name)}> closes <${S.name}>, opened on line ${S.lineNumber}`);let I=m.length-h.length,x=r.length*Vx.length;if(I!==x)return g(`indented ${I} spaces where the nesting calls for ${x}`);if(k.kind==="close"){if(S.name===kt){if(S.children===0)return g("<a> has to open with the <title> of the group it links");i-=1}if(S.described&&!S.drawsRoute)return g(`a <${ni}> belongs to a line's route group, and this group draws no route`);a=r.length===0;continue}let E=r.at(-1),M=EM(k,r.length)??(E&&(CM(k,E,i)??IM(k,r)??xM(k,r)??$M(k,r)));if(M!==void 0)return g(M);let v=k.attributes.get("id");if(v!==void 0){if(s.has(v))return g(`the id ${Re(v)} is declared twice`);s.set(v,k.name)}for(let[A,T]of k.attributes){let N=zx[A];N!==void 0&&o.push({attribute:A,id:gg.exec(T)[1],kind:N,lineNumber:f})}E!==void 0&&(E.children+=1,E.previous=k,E.firstPath??=k.name===fg?k:void 0,E.linked||=E.stamped&&k.name===kt),Eg(k)&&((E.name===kt?r.at(-2):E).hitArea=!0);let C=Ig(r);C!==void 0&&(C.described||=k.name===ni,C.drawsRoute||=E.firstPath===k&&vg(k));let R=Cg(r);R!==void 0&&pg.has(k.name)&&(R.drawsBox=!0),R!==void 0&&k.name===hr&&k.attributes.has(cs)&&(R.nestsStamp=!0),k.kind==="open"&&(r.push({name:k.name,lineNumber:f,stamped:k.name===hr&&k.attributes.has(cs),children:0,linked:!1,hitArea:!1,drawsBox:!1,described:!1,drawsRoute:!1,nestsStamp:!1}),i+=k.name===kt?1:0)}let d=r.at(-1);if(d!==void 0)return`<${d.name}> opened on line ${d.lineNumber} is never closed`;let l=o.find(({id:c,kind:m})=>s.get(c)!==m);return l===void 0?void 0:`line ${l.lineNumber}: ${l.attribute}: url(#${Re(l.id)}) names no <${l.kind}> the file declares`};var Ol=" ",Nl=/^( *)<g data-md-element="([^"]*)">$/,MM=/^<title>[^<]*<\/title>$/,ri=".svg",$g=".png",xg=[137,80,78,71,13,10,26,10],AM=e=>{let t=new Map,n=(r,s)=>{s&&!t.has(r)&&t.set(r,`#${s}`)};for(let r of e.fragments??[]){n(r.elementId,r.realization?.anchor);for(let s of r.anchors??[])n(s.elementId,s.anchor)}return t},TM=e=>{let t=new Map;for(let[n,r]of e){let s=Hr(n);!t.has(s)&&ei(r)&&t.set(s,r)}return t},OM=(e,t,n)=>{let r=n+Ol,s=`${n}</g>`,o=`${r}<g data-md-element="`;for(let i=t+1;i<e.length;i+=1){let a=e[i];if(a===s||a.startsWith(o))return i;if(!a.startsWith(r))return}},NM=(e,t)=>{if(t.size===0)return e;let n=e.split(`
186
- `),r=[],s=0;for(;s<n.length;){let o=n[s];r.push(o),s+=1;let i=Nl.exec(o),a=i?t.get(i[2]):void 0;if(!i||a===void 0)continue;let d=i[1],l=d+Ol,c=n[s];if(c===void 0||!c.startsWith(l)||!MM.test(c.slice(l.length)))continue;let m=OM(n,s-1,d);if(m!==void 0){for(r.push(`${l}<a href="${Hr(a)}">`);s<m;s+=1)r.push(Ol+n[s]);r.push(`${l}</a>`)}}return r.join(`
187
- `)},LM=e=>e.split(`
188
- `).some(t=>Nl.test(t)),PM=e=>new Set(e.split(`
189
- `).flatMap(t=>Nl.exec(t)?.[2]??[])),si=(e,t)=>e.toLowerCase().endsWith(ri)?PM(new TextDecoder().decode(t)):void 0,Mg=(e,t)=>e.toLowerCase().endsWith(ri)&&!LM(new TextDecoder().decode(t));var Ct=class extends Error{path;problem;constructor(t,n){super(`Refused the diagram file ${t}: ${n}`),this.name="RefusedMediaError",this.path=t,this.problem=n}},DM=e=>e.length>=xg.length&&xg.every((t,n)=>e[n]===t),_M=(e,t)=>{let n=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return typeof n=="string"?{idPrefix:rg(n)}:{}},Ag=({manifest:e,mediaIndex:t})=>{let n=TM(AM(e)),r=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),s=new TextEncoder,o=(i,a)=>{let d;try{d=r.decode(a)}catch{throw new Ct(i,"the bytes are not UTF-8 text")}let l=_M(t,i),c=Tl(d,l);if(c!==void 0)throw new Ct(i,c);let m=NM(d,n);if(m===d)return a;let f=Tl(m,l);if(f!==void 0)throw new Ct(i,`once linked, ${f}`);return s.encode(m)};return(i,a)=>{let d=i.toLowerCase();if(d.endsWith(ri))return o(i,a);if(!d.endsWith($g))throw new Ct(i,`a diagram file is an ${ri} or a ${$g}, and this is neither`);if(!DM(a))throw new Ct(i,"the bytes are not a PNG image");return a}};var Tg=(e,t)=>{let n=Ag(e),r=Og(e),s=new Map,o=[],i=[];for(let{path:f,bytes:g}of t){if(g===void 0){o.push(f);continue}try{s.set(f,n(f,g))}catch(u){if(!(u instanceof Ct))throw u;o.push(f),i.push({path:f,problem:u.problem})}}let a=new Set;for(let[f,g]of s){let u=r(f);u!==void 0&&Mg(f,g)&&a.add(u)}let d=f=>{let g=r(f);return g!==void 0&&a.has(g)},l=new Map([...s].filter(([f])=>!d(f))),c=o.filter(f=>!d(f)),m=new Map;for(let[f,g]of l){let u=r(f),h=si(f,g);u!==void 0&&h!==void 0&&m.set(u,h)}return{mediaBytesByPath:l,missingPaths:c,refusals:i.filter(({path:f})=>!d(f)),emptyDiagramIds:a,emptyDiagramPaths:t.map(({path:f})=>f).filter(d),stampsByDiagram:m,...jM(e,c,l)}},Og=e=>{let t=e.mediaIndex??{};return n=>Object.hasOwn(t,n)?t[n]:void 0},jM=(e,t,n)=>{let r=e.mediaIndex??{},s=Og(e),o=new Set([...n.keys()].map(s)),i=a=>{let d=s(a);return d!==void 0&&o.has(d)};return{missingDiagrams:Gn(t.filter(a=>!i(a)),r),partialDiagrams:Gn(t.filter(i),r)}},Ng=(e,{emptyDiagramIds:t,stampsByDiagram:n})=>vo(Jh(e,t),n,t);import{existsSync as Ll,lstatSync as Pg,realpathSync as FM,statSync as qM}from"node:fs";import{homedir as BM}from"node:os";import{basename as WM,dirname as UM,isAbsolute as Dg,join as _g,relative as HM,resolve as gr,sep as GM}from"node:path";var ms=(e,t,n)=>{if(Dg(n))throw new p(`Refusing an absolute path from the bundle manifest: ${n}`);let r=gr(e,t),s=gr(e,n);if(s===r||!Pl(r,s))throw new p(`Refusing a bundle path that escapes the content root: ${n}`);return s},Pl=(e,t)=>{let n=HM(e,t);return n===""||!Dg(n)&&n!==".."&&!n.startsWith(`..${GM}`)},fs=(e,t,{ignoreCase:n=!1}={})=>{let r=Lg(e),s=Lg(t);return n?Pl(r.toLowerCase(),s.toLowerCase()):Pl(r,s)},$n=e=>{try{return Pg(e)}catch{return}},xn=e=>{try{return qM(e)}catch{return}},Lg=e=>{let t=[],n=e;for(;!Ll(n);){let s=UM(n);if(s===n)return e;t.unshift(WM(n)),n=s}let r=FM(n);return t.length>0?_g(r,...t):r},Rt=e=>{if($n(e)?.isSymbolicLink())throw new p(`Refusing to write through an existing symlink at a managed path: ${e}`)},us=(e,t)=>{if(!fs(e,t))throw new p(`Refusing a path that escapes the content root through a symlink: ${t}`)},Dl=(e,t)=>{let n=gr(e,t);if(n===gr(e))throw new p(`The content root resolves to the repository root (${n}); refusing to sync it.`);if(n===gr(BM()))throw new p("The content root resolves to your home directory; refusing to sync it.");if(Ll(n)){if(Pg(n).isSymbolicLink())throw new p(`The content root ${n} is a symlink; refusing to sync it.`);if(Ll(_g(n,".git")))throw new p(`The content root ${n} contains a .git directory (it looks like a repo root); refusing.`)}if(!fs(gr(e),n))throw new p(`The content root ${n} resolves outside the repository via a symlinked ancestor; refusing.`);return n};var jg={respec:"data/model"},_l=e=>Object.hasOwn(jg,e)?jg[e]:void 0,oi=e=>{let t=_l(e);if(!t)throw new p(`The CLI does not know the content root for stack '${e}'.`);return t};var VM=1500,KM=6e5,YM=e=>new Promise(t=>setTimeout(t,e)),zM=e=>e==="COMPLETED"||e==="COMPLETED_WITH_ERRORS"||e==="FAILED",Fg=async(e,t,n)=>{let r=await e.contentBundles.renderDiagrams(t,{template:n.template,version:n.version});if(!r.commit)throw new p("The diagram render did not return a resolved commit; cannot pin the pull.");return r},qg=async(e,t,n,r,s,o={})=>{let i=o.sleep??YM,a=o.now??Date.now,d=a()+KM;for(r.update(0,s);;){let l=await e.exportJobs.get(t,n);if(l.progress&&r.update(l.progress.completed,l.progress.total,l.progress.currentItem),zM(l.status))return r.done(),l;if(a()>=d)throw new p("Timed out waiting for the diagram render to finish.");await i(VM)}},Bg=(e,t,n,r)=>e.contentBundles.media(t,{path:n,template:r.template,commit:r.commit});var Wg=e=>{let t=new Map;for(let n of e.fragments??[])n.realization?.path&&t.set(n.elementId,n.realization.path);return t},Ug=(e,t)=>{let n=Wg(e),r=[];for(let[s,o]of Wg(t)){let i=n.get(s);i&&i!==o&&r.push({elementId:s,oldPath:i,newPath:o})}return r};import{existsSync as JM,mkdirSync as XM,readFileSync as QM,writeFileSync as ZM}from"node:fs";import{join as Hg}from"node:path";var Gg=(e,t)=>Hg(e,Kn,`${t}.manifest.json`),ii=(e,t)=>{let n=Gg(e,t);if(!JM(n))return;let r;try{r=JSON.parse(QM(n,"utf8"))}catch{return}return eA(r)?r:void 0},eA=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let{fragments:t}=e;return t===void 0?!0:Array.isArray(t)&&t.every(n=>n!==null&&typeof n=="object")},Vg=(e,t,n)=>{XM(Hg(e,Kn),{recursive:!0}),ZM(Gg(e,t),pl(n))},Kg=e=>{let t=[];for(let r of e.fragments??[]){r.realization?.path&&t.push(r.realization.path);for(let s of r.realization?.media??[])t.push(s)}let n=So(e);return n!==void 0&&t.push(n),t};import{existsSync as jl,lstatSync as tA,mkdirSync as Yg,readdirSync as nA,readFileSync as rA,rmSync as sA,writeFileSync as zg}from"node:fs";import{dirname as Jg,join as yr,relative as oA,sep as iA}from"node:path";var Xg=(e,t)=>{let n=yr(e,t);if(!jl(n))return[];let r=[],s=o=>{for(let i of nA(o,{withFileTypes:!0})){let a=yr(o,i.name);i.isDirectory()?s(a):i.isFile()&&r.push(oA(e,a).split(iA).join("/"))}};return s(n),r},Fl=(e,t,n)=>{let r=yr(e,t);for(let s of n){let o=ms(e,t,s.path);Rt(o),us(r,o),Yg(Jg(o),{recursive:!0}),zg(o,s.content)}},aA=(e,t,n,r)=>{let s=yr(e,t),o=ms(e,t,n);Rt(o),us(s,o),Yg(Jg(o),{recursive:!0}),zg(o,r)},ql=(e,t,n,r)=>{let s=n.mediaIndex??{},o=yr(e,t),i=new Map;for(let a of r){let d=Object.hasOwn(s,a)?s[a]:void 0;if(d!==void 0)try{let l=ms(e,t,a);if(!jl(l)||tA(l).isSymbolicLink())continue;us(o,l);let c=si(a,rA(l));c!==void 0&&i.set(d,c)}catch{}}return i},Qg=(e,t,n,r,s=hn(n))=>{let o=[];for(let[l,c]of r.mediaBytesByPath)try{aA(e,t,l,c)}catch(m){o.push({path:l,error:m})}let i=new Map([...ql(e,t,n,Hn(n.manifest)),...r.stampsByDiagram]),a=new Map(s.map(l=>[l.path,l.content])),d=hn(Ng(n,{...r,stampsByDiagram:i})).filter(l=>a.get(l.path)!==l.content);return Fl(e,t,d),o},Bl=(e,t,n)=>{let r=ms(e,t,n);return us(yr(e,t),r),jl(r)?(sA(r),!0):!1},Zg=(e,t,n)=>{for(let r of n)Bl(e,t,r)};var dA=100,ty=e=>{if(e.newTextPaths.length===0&&!e.allowEmpty)throw new p("The content fetch returned no fragments (usually the wrong model or format, or a server error). Nothing was written or deleted. Re-run with --allow-empty only if the model is genuinely empty.");let t=ey([...e.newTextPaths,...e.newMediaPaths]).sort(),n=new Set(t),r=new Set(e.existingFiles),s=t.filter(c=>r.has(c)),o=e.priorManifestPaths!==void 0?"manifest-tracked":"full-sync",i=e.priorManifestPaths??e.existingFiles,a=ey(i).filter(c=>!n.has(c)).sort(),d=a.length>0&&!e.adopted,l=a.length>0&&(a.length>t.length||a.length>dA);return{writes:t,overwrites:s,orphanCandidates:a,mode:o,adoptionNeeded:d,outsized:l}},Wl=(e,t)=>{if(e.orphanCandidates.length===0)return{deletes:[],warnings:[]};if(e.adoptionNeeded&&!t.adopt)return{deletes:[],warnings:[`${e.orphanCandidates.length} file(s) under the content root are not tracked by the CLI and were left in place. Pass --adopt to let the CLI manage (and prune) this directory.`]};if(e.outsized&&!t.yes)throw new p(`This pull would remove ${e.orphanCandidates.length} file(s), more than the ${e.writes.length} it writes. That often signals a wrong model or format. Nothing was changed. Re-run with --yes if intended.`);return{deletes:e.orphanCandidates,warnings:[]}},ey=e=>[...new Set(e)];import{readdirSync as cA}from"node:fs";import{join as ps,posix as hs}from"node:path";var ry=e=>{let t=at(e),n=new Map;for(let r of e.fragments??[]){let s=n.get(r.elementId),o=r.realization?.path,i=o!==void 0&&(o===ny||o.endsWith(`/${ny}`));n.set(r.elementId,{elementId:r.elementId,title:t.get(r.elementId)?.title,kind:t.get(r.elementId)?.kind,path:s?.path??o,anchor:t.get(r.elementId)?.anchor,container:(s?.container??!1)||i})}return[...n.values()]},ny="index.md",Ul=e=>{let t=at(e);return(e.fragments??[]).flatMap(n=>(n.anchors??[]).map(r=>({elementId:r.elementId,kind:r.kind,slug:r.address.split("/").at(-1)??"",owner:t.get(n.elementId)?.title})))},sy=(e,t)=>{let n=vn(t);return n===""?[]:e.filter(r=>r.slug===n)},ai=e=>e.replace(/\s+/g," ").trim().toLowerCase(),Hl=(e,t)=>{let n=ai(t);return e.filter(r=>r.title!==void 0&&ai(r.title)===n)},lA=5,oy=(e,t)=>{let n=ai(t),r=n.length>=4?2:1,o=e.flatMap(i=>i.title===void 0?[]:[i.title]).filter(i=>{let a=ai(i);return n.length>=3&&a.includes(n)||Gl(a,n)<=r});return[...new Set(o)].slice(0,lA)},Gl=(e,t)=>{let n=Array.from({length:t.length+1},(r,s)=>s);for(let r=1;r<=e.length;r+=1){let s=[r];for(let o=1;o<=t.length;o+=1)s[o]=Math.min(n[o]+1,s[o-1]+1,n[o-1]+(e[r-1]===t[o-1]?0:1));n=s}return n[t.length]};var di=".after.md",Mn=".md",ay=e=>e.toLowerCase().endsWith(di),dy=e=>ay(e)?"after":"intro",li=(e,t)=>{let n=Vn(e);if(n!==void 0)return`the notes folder ${JSON.stringify(e)} ${n}; give a folder relative to the repository root`;if(ye(e)===".")return"the notes folder is the repository root, so every Markdown file in the repository would be read as a note; give a folder of its own, such as md-notes/";if(yn(e.toLowerCase(),t.toLowerCase())||yn(t.toLowerCase(),e.toLowerCase()))return`the notes folder ${e} overlaps the content root ${t}/, which every pull replaces; keep notes outside it`},ci=(e,t,n,r)=>{let s=`${ye(t)}/`,o=ye(n);if(!o.startsWith(s)||!o.endsWith(Mn))return;let i=o.slice(s.length,-Mn.length);return hs.join(ye(e),`${i}${r==="after"?di:Mn}`)},Vl=(e,t)=>$n(ps(e,ye(t)))?.isSymbolicLink()?`the notes folder ${ye(t)} is a symlink, which the pull does not follow; make it a folder of its own, or set "notesDir" in .modeldesk/config.json to the folder it points to`:void 0,ly=(e,t)=>{let n=ye(t),r=Vl(e,t);if(r!==void 0)throw new p(`${r[0].toUpperCase()}${r.slice(1)}.`);if($n(ps(e,n))?.isDirectory()!==!0)return[];let s=[],o=a=>{try{return cA(ps(e,a),{withFileTypes:!0})}catch(d){throw new p(`Could not read the notes folder ${a}: ${d.message}`)}},i=a=>{for(let d of o(a)){if(d.name.startsWith("."))continue;let l=hs.join(a,d.name);d.isDirectory()?i(l):d.name.toLowerCase().endsWith(Mn)&&!mA(e,l,d)&&s.push(l)}};return i(n),s.sort()},mA=(e,t,n)=>n.isSymbolicLink()?xn(ps(e,t))?.isDirectory()===!0:!1,fA=5,cy=({repoRoot:e,files:t,notesDir:n,contentRoot:r,manifest:s,entries:o})=>{let i=[...o.values()].flatMap(g=>xe.flatMap(u=>g[u]===void 0?[]:[ye(g[u])])),a=new Set(i),d=new Set(i.flatMap(g=>iy(e,g)??[])),l=g=>{if(a.has(ye(g)))return!0;let u=iy(e,g);return u!==void 0&&d.has(u)},c=new Map;for(let g of s.fragments??[]){let u=g.realization?.path;u!==void 0&&!c.has(ye(u))&&c.set(ye(u),{elementId:g.elementId,title:g.title||void 0})}let m=[],f=new Map;for(let g of t.filter(u=>!l(u))){let u=dy(g),h=uA(n,r,g),y=h===void 0?void 0:c.get(h);if(y===void 0){m.push(pA(g,h,n,r,[...c.keys()]));continue}let k=o.get(y.elementId)?.[u],S=y.title??y.elementId;if(k!==void 0){m.push(`the note ${g} would be the ${u} note of ${S}, which notes.json already gives as ${k}; keep one of the two files.`);continue}let I=`${u} ${y.elementId}`,x=f.get(I);if(x!==void 0){m.push(`the notes ${x.file} and ${g} would both be the ${u} note of ${S}, which appears at more than one place in the document; keep one of the two files.`);continue}f.set(I,{file:g,elementId:y.elementId,slot:u,title:y.title})}return{adoptions:[...f.values()],errors:m}},iy=(e,t)=>{let n=xn(ps(e,t));return n?.isFile()?`${n.dev}:${n.ino}`:void 0},uA=(e,t,n)=>{let r=`${ye(e)}/`,s=ye(n);if(!s.startsWith(r))return;let o=s.slice(r.length),i=ay(o)?o.slice(0,-di.length):o.toLowerCase().endsWith(Mn)?o.slice(0,-Mn.length):void 0;return i===void 0?void 0:hs.join(ye(t),`${i}${Mn}`)},pA=(e,t,n,r,s)=>{let o=`A note's path is its element's file under ${ye(r)}/ with ${ye(n)}/ in its place, ending in ${di} for the note after the element's content.`;if(t===void 0)return`the note ${e} matches no element: its name does not end in .md. ${o}`;let i=hs.basename(t),a=s.map(l=>({path:l,distance:Gl(l,t)})).filter(({path:l,distance:c})=>hs.basename(l)===i||c<=2).sort((l,c)=>l.distance-c.distance||l.path.localeCompare(c.path)).slice(0,fA).map(({path:l})=>ci(n,r,l,dy(e))).filter(l=>l!==void 0),d=a.length===0?"":` Did you mean ${a.join(", ")}?`;return`the note ${e} matches no element: this bundle has no ${t}.${d} ${o}`},Kl=(e,t)=>{let n=new Map(e);for(let{file:r,elementId:s,slot:o,title:i}of t){let a=n.get(s);n.set(s,a===void 0?{...i===void 0?{}:{name:i},[o]:r}:{...a,[o]:r})}return n};import{join as Yl}from"node:path";var zl=({repoRoot:e,contentRoot:t,entries:n})=>[...n].flatMap(([r,s])=>xe.flatMap(o=>{let i=s[o];return i===void 0?[]:hA(e,t,i).map(a=>`${wr(r,s.name)} ${o}: ${a}.`)})),my=({manifest:e,slots:t,entries:n,notesDir:r})=>{let s=yA(e,t),o=[],i=[],d=[...n].some(([l,c])=>s.has(l)&&xe.some(m=>c[m]!==void 0))&&t.size===0?`The server rendered stack ${e.stack} ${e.stackVersion}, which carries no note slots, so the notes cannot be placed. Either the server is older than note support, or this template has no slots: notes work with the MIM templates. Pull without notes by moving .modeldesk/notes.json and the notes folder ${r} aside, or pull again once the server is updated.`:void 0;for(let[l,c]of n){let m=s.get(l),f=wr(l,m?.title??c.name);if(m===void 0){i.push(`${f} is not in this bundle; its entry in notes.json is kept.`);continue}if(d===void 0)for(let g of xe)c[g]!==void 0&&o.push(...gA(m,g).map(u=>`${f} ${g}: ${u}.`))}return{errors:o,warnings:i,slotless:d}},Jl=e=>typeof e=="string"?e:e.file,Xl=(e,t,n)=>{let r=Vn(n);if(r!==void 0)return[`the note path ${JSON.stringify(n)} ${r}; note paths are relative to the repository root`];if(yn(n.toLowerCase(),t.toLowerCase()))return[`the note ${n} lies in the content root ${t}/, which every pull replaces, so the pull would remove it; keep notes outside it`];let s=Yl(e,n);return fs(Yl(e,t),s,{ignoreCase:!0})?[`the note ${n} lies in the content root ${t}/ through a symlink, and every pull replaces that folder, so the pull would remove it; keep notes outside it`]:fs(e,s)?[]:[`the note ${n} lies outside the repository through a symlink; keep notes inside it`]},hA=(e,t,n)=>{let r=Xl(e,t,n);if(r.length>0)return r;let s=xn(Yl(e,n));return s===void 0?[`the note ${n} does not exist`]:s.isFile()?[]:[`the note ${n} is not a file`]},gA=(e,t)=>{let n=e.slots.get(t);if(n===void 0){let r=[...e.slots.keys()],s=e.kind===void 0?"the element":`this ${e.kind}`;return[r.length===0?`${s} carries no slots`:`${s} carries no ${t} slot, only ${r.join(" and ")}`]}return n.headed&&e.anchor===void 0?["the bundle's manifest gives the element no anchor to build the heading's id from"]:[]},yA=(e,t)=>{let n=new Map;for(let[r,s]of at(e))n.set(r,{...s,slots:new Map});for(let r of(e.fragments??[]).flatMap(s=>s.anchors??[]))n.has(r.elementId)||n.set(r.elementId,{kind:r.kind,slots:new Map});for(let r of[...t.values()].flat()){let s=n.get(r.elementId)??{slots:new Map};n.set(r.elementId,s);let o=s.slots.get(r.name)?.headed??!1;s.slots.set(r.name,{headed:o||r.heading!==void 0})}return n},wr=(e,t)=>t===void 0?e:`${t} (${e})`;import{existsSync as wA,readFileSync as fy}from"node:fs";import{join as bA}from"node:path";var kA="notes.json",EA=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,CA=["name",...xe],RA=e=>bA(e,Kn,kA),mi=e=>{let t=RA(e);if(!wA(t))return{path:t,entries:new Map};let n;try{n=fy(t,"utf8")}catch(o){throw new p(`Could not read ${t}: ${o.message}`)}let r;try{r=JSON.parse(n)}catch(o){throw new p(`${t} is not valid JSON: ${o.message}`)}if(!Ql(r))throw new p(`${t} must contain a JSON object with a "notes" object.`);for(let o of Object.keys(r))if(o!=="notes")throw new p(`${t}: unknown key "${o}"; the file holds only "notes".`);if(!Ql(r.notes))throw new p(`${t}: "notes" must be an object of entries keyed by element id.`);let s=new Map;for(let[o,i]of Object.entries(r.notes))s.set(o,IA(t,o,i));return vA(t,n,s),{path:t,entries:s,raw:n}},SA=/"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"\s*:/g,vA=(e,t,n)=>{let r=new Map;for(let[,s]of t.matchAll(SA))r.set(s,(r.get(s)??0)+1);for(let s of n.keys())if((r.get(s)??0)>1)throw new p(`${e}: notes key "${s}" appears more than once, and JSON keeps only the last; merge the entries.`)},IA=(e,t,n)=>{if(!EA.test(t))throw new p(`${e}: notes key "${t}" is not an element id. Entries are keyed by the element's id, a lowercase UUID as the bundle's manifest gives it.`);let r=`notes.${t}`;if(!Ql(n))throw new p(`${e}: ${r} must be an object.`);for(let s of Object.keys(n))if(!CA.includes(s))throw new p(`${e}: ${r} has an unknown key "${s}"; an entry takes "name", "intro" and "after".`);if(n.name!==void 0&&typeof n.name!="string")throw new p(`${e}: ${r}.name must be a string.`);for(let s of xe)if(n[s]!==void 0&&typeof n[s]!="string")throw new p(`${e}: ${r}.${s} must be a note path. A note that comes under a heading names it on its own first line, <!-- heading: \u2026 -->.`);return n},Ql=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),uy=e=>{try{return fy(e,"utf8")}catch{return}};import{readFileSync as LA}from"node:fs";import{join as yy,posix as PA}from"node:path";var $A=/^ {0,3}(`{3,}|~{3,})/,Zl=/^(?: {4}|\t)/,xA=/^ {0,3}(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$)/,hy=e=>{let t=[],n,r=!1,s=!0,o=!1;for(let i of e.split(/\r?\n/)){let a=i.trim()==="",d=$A.exec(i)?.[1];if(n!==void 0){d!==void 0&&d[0]===n[0]&&d.length>=n.length&&i.trim()===d&&(n=void 0);continue}if(!(r&&(a||Zl.test(i)))){if(r=!1,d!==void 0){n=d,s=!1;continue}if(Zl.test(i)&&s&&!o){r=!0;continue}a||(o=xA.test(i)||o&&Zl.test(i)),s=a,t.push(i)}}return t},MA=/(?<!`)(`+)(?!`)(.*?[^`])\1(?!`)/g,AA=/!\[([^\]]*)\]\(\s*(?:<([^>]*)>|([^\s)]+))(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)/g,TA=/<img\b([^>]*)>/gi,OA=/([^\s=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g,gy=e=>{let t=hy(e).map(r=>r.replace(MA,s=>" ".repeat(s.length))).join(`
190
- `),n=[];for(let r of t.matchAll(AA))n.push({src:r[2]??r[3],alt:r[1],syntax:"markdown"});for(let r of t.matchAll(TA)){let s=new Map;for(let i of r[1].matchAll(OA))s.set(i[1].toLowerCase(),i[2]??i[3]??i[4]??"");let o=s.get("src");o!==void 0&&n.push({src:o,alt:s.get("alt"),syntax:"html"})}return n},NA=/^ {0,3}#{1,6}(?=[ \t]|$)(.*)$/,py=/\s*\{#[^\s}]+\}$/,ec=e=>hy(e).flatMap(t=>{let n=NA.exec(t);if(n===null)return[];let r=n[1].replace(/(?:^|[ \t]+)#+[ \t]*$/,"").trim(),s=py.test(r),o=s?r.replace(py,""):r;return o===""?[]:[{text:o,explicitId:s}]});var wy=e=>{let{repoRoot:t,manifest:n,slots:r,entries:s,notes:o,placed:i}=e,a=at(n),d=u=>a.get(u)?.title??s.get(u)?.name,l=new Map;for(let{name:u,elementId:h}of i.filled){let y=o.get(h)?.[u],k=`${u} ${h}`;y!==void 0&&!l.has(k)&&l.set(k,{elementId:h,title:d(h)??h,slot:u,target:y})}let c=[],m=[],f=new Map;for(let{target:u}of l.values())f.set(Jl(u),(f.get(Jl(u))??0)+1);for(let[u,h]of f)try{m.push({file:u,text:LA(yy(t,u),"utf8"),slots:h})}catch(y){c.push(`could not read the note ${u}, so its images and headings were not checked: ${et(y)}`)}for(let u of m)c.push(...jA(t,u.file,u.text,e.publishDirs));c.push(...FA(m),...qA(n,i.dropped,d));let g=[...r.values()].reduce((u,h)=>u+h.length,0);return{warnings:c,substitutions:[...l.values()],removedSlots:g-i.filled.length}},DA=/^(?:https?:|data:|\/\/)/i,_A=e=>{let t=e.replace(/[?#].*$/,""),n=t;try{n=decodeURIComponent(t)}catch{}return PA.normalize(n.replace(/^\/+/,""))},jA=(e,t,n,r)=>gy(n).flatMap(({src:s,alt:o,syntax:i})=>{let a=[];if((o===void 0||i==="markdown"&&o.trim()==="")&&a.push(`the note ${t} has an image without alt text, ${s}; describe it for readers who cannot see it.`),DA.test(s))return a;let d=_A(s);if(d==="."||d==="")return a;if(xn(yy(e,d))?.isFile()!==!0){let l=d===s?"":` (${d} in the repository)`;a.push(`the note ${t} links the image ${s}${l}, which does not exist; image paths resolve against the repository root.`)}return r!==void 0&&!r.some(l=>yn(d,l))&&a.push(`the note ${t} links the image ${s}, which lies outside the publishDirs (${r.join(", ")||"none"}), so the published copy will miss it.`),a}),FA=e=>{let t=new Map;for(let s of e)for(let o of ec(s.text)){if(o.explicitId)continue;let i=vn(o.text),a=t.get(i)??{text:o.text,files:[]};a.files.includes(s.file)||t.set(i,{...a,files:[...a.files,s.file]})}let n=[...t.values()].filter(({files:s})=>s.length>1).map(({text:s,files:o})=>`the notes ${o.join(" and ")} each have the heading "${s}" without an explicit {#id}. ReSpec numbers the later ids, so a link to one shifts when the notes change; give each heading its own {#id}.`),r=e.filter(s=>s.slots>1&&ec(s.text).length>0).map(s=>`the note ${s.file} fills ${s.slots} slots, so each of its headings appears ${s.slots} times and their ids repeat or get numbered; give each place its own note file.`);return[...n,...r]},qA=(e,t,n)=>{let r=new Map((e.fragments??[]).map(o=>[o.address,o.realization?.path])),s=new Map;for(let{name:o,elementId:i,address:a}of t){let d=`${o} ${i}`,l=s.get(d)??{slot:o,elementId:i,files:new Set};s.set(d,{...l,files:l.files.add(r.get(a)??a)})}return[...s.values()].map(({slot:o,elementId:i,files:a})=>`${wr(i,n(i))} appears more than once in ${[...a].join(", ")}; its ${o} note goes in at the first place only.`)};import{renameSync as BA,rmSync as by,writeFileSync as WA}from"node:fs";var ky=(e,t)=>{let n=at(t);return[...e].flatMap(([r,s])=>{let o=n.get(r)?.title;return o===void 0||o===s.name?[]:[{elementId:r,from:s.name,to:o}]})},Ey=(e,t)=>{let n=new Map(t.map(r=>[r.elementId,r.to]));return new Map([...e].map(([r,s])=>{let o=n.get(r);return o===void 0?[r,s]:[r,"name"in s?{...s,name:o}:{name:o,...s}]}))},br=e=>`${JSON.stringify({notes:Object.fromEntries(e)},null,2)}
191
- `,fi=(e,t)=>{Rt(e);let n=`${e}.tmp`;try{by(n,{force:!0}),WA(n,t,{flag:"wx"}),BA(n,e)}catch(r){throw by(n,{force:!0}),r}};import{readFileSync as HA}from"node:fs";import{join as GA}from"node:path";var UA=/^<!--\s*heading:(.*)-->$/i,Cy=e=>{let t=e.split(/\r?\n/).find(n=>n.trim()!=="");return t===void 0?void 0:UA.exec(t.trim())?.[1].trim()},ui=e=>`<!-- heading: ${e} -->`,gs=e=>{if(e.trim()==="")return"is blank";if(/[\r\n]/.test(e))return"has a line break";let t=["-->","--!>"].find(n=>e.includes(n));return t===void 0?void 0:`has "${t}", which would end the heading line early`};var Ry=({repoRoot:e,slots:t,entries:n})=>{let r=[...t.values()].flat(),s=new Set(r.flatMap(l=>l.heading===void 0?[]:[`${l.name} ${l.elementId}`])),o=new Set(r.map(l=>l.elementId)),i=new Map,a=[],d=[];for(let[l,c]of n){let m={};for(let f of xe){let g=c[f];if(g===void 0)continue;if(!o.has(l)){m[f]=g;continue}let u=VA(e,g),h=`${wr(l,c.name)} ${f}`;s.has(`${f} ${l}`)?u===void 0||u===""?a.push(`${h}: the note ${g} comes under a heading of its own, so its first line names it, such as ${ui("Afsluiting")}.`):gs(u)!==void 0?a.push(`${h}: the heading line of the note ${g} ${gs(u)}.`):m[f]={file:g,heading:u}:(u!==void 0&&d.push(`${h}: the note ${g} starts with a heading line, which only the closing note of a package or the model takes; the line is left as a comment.`),m[f]=g)}i.set(l,m)}return{notes:i,errors:a,warnings:d}},VA=(e,t)=>{try{return Cy(HA(GA(e,t),"utf8"))}catch{return}};var KA=(e,t)=>{let n=t>0?Math.min(1,e/t):0,r=Math.round(n*24);return`[${"#".repeat(r)}${"-".repeat(24-r)}]`},Sy=(e,t=n=>{process.stderr.write(n)})=>{let n=-1;return{update(r,s,o){if(e){let i=o?` ${o}`:"";t(`\r${KA(r,s)} ${r}/${s}${i}\x1B[K`)}else if(r!==n){let i=o?` (${o})`:"";t(`Rendering diagrams: ${r}/${s}${i}
175
+ `)}});import{readFileSync as qM}from"node:fs";import{resolve as WM}from"node:path";var Ay=async(e,t,n)=>{if(t==="-")return e.readStdin();try{return qM(WM(e.cwd,t),"utf8")}catch(r){throw k(`Could not read the resolution file ${t} (${r.message}).`,n)}};var Oy={branchMerge:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"},head:{type:"string",description:"The head the facts were computed at: what a resolution sends back as the expected head."}}},source:{type:"object",properties:{id:{type:"string"},name:{type:"string"},head:{type:"string",description:"The head the facts were computed at: what a resolution sends back as the expected head."}}},outcome:{type:"string",description:'One of "already-merged", "blocked", "clean", "conflicts", "merged".'},mergeBaseId:{type:"string"},blockers:{type:"array",items:{type:"string"}},names:{type:"object",additionalProperties:{type:"string"}},resolutions:{type:"array",items:{type:"object",properties:{elementId:{type:"string"},label:{type:"string",description:"Context for the reader: the element's name under its owner's, as the server names them."},reason:{type:"string",description:'One of "both-changed", "changed-and-deleted", "dependency-removed", "owner-deleted", "pinned-differently", "target-deleted".'},target:{type:"object",properties:{present:{type:"boolean",description:"One of false, true."},type:{type:"string"},owners:{type:"array",items:{type:"string"}}}},source:{type:"object",properties:{present:{type:"boolean",description:"One of false, true."},type:{type:"string"},owners:{type:"array",items:{type:"string"}}}},take:{type:"string",description:'One of "fields", "source", "target".'},fields:{type:"object",additionalProperties:{type:"object",properties:{take:{type:"string",description:'One of "source", "target".'},kind:{type:"string",description:'One of "attribute", "relation".'},base:{type:"array",items:{}},target:{type:"array",items:{}},source:{type:"array",items:{}}}}},managedDependencyChanges:{type:"object",properties:{target:{type:"number"},source:{type:"number"}}},rejected:{type:"array",items:{type:"object",properties:{message:{type:"string"},rule:{type:"string"},property:{type:"string"}}}}}}},takeOthers:{type:"string",description:'One of "source", "target".'},rejected:{type:"array",items:{type:"object",properties:{elementId:{type:"string"},rule:{type:"string"},message:{type:"string"},property:{type:"string"}}},description:"Refused picks that name an element no card covers: one the merge repaired, which then broke a rule."},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}},resolved:{type:"number",description:"How many resolutions the request carried."}},required:["schemaVersion","model","ref","target","source","outcome"]}};var BM={clean:b.Success,conflicts:b.Conflict,blocked:b.Validation},UM=e=>{for(let[t,n,r]of[["--expect","expect",e.expect],["--expect-source","expectSource",e["expect-source"]]])if(r!==void 0&&!B(r))throw k(`${t} takes the commit id the preview reported as that branch's head.`,pe,{reason:`'${n}' takes the commit id the preview reported as that branch's head.`});return{...e.expect?{target:e.expect}:{},...e["expect-source"]?{source:e["expect-source"]}:{}}},GM=(e,t,n,r)=>{let o=e.take.length>0||e["take-others"]!==void 0;if(n&&(o||r||t.target!==void 0||t.source!==void 0))throw k("A dry run previews the merge and takes no --resolve, --take, --take-others, --expect or --expect-source.",pe);if(r&&(t.target!==void 0||t.source!==void 0))throw k("--resolve carries both heads in the file; --expect and --expect-source are not taken with it.",pe);if(o&&!r&&(t.target===void 0||t.source===void 0))throw k("--take and --take-others bind to the heads you reviewed: pass both --expect <target-head> and --expect-source <source-head> as the preview reported them, or --resolve <file>.",pe,{reason:`take and takeOthers bind to the heads you reviewed: pass both expect and expectSource as ${gc} reported them.`})},My=(e,t,n)=>{let r=e.take.map(Ey),o=UM(e);GM(e,o,t,n);let s=e.message===void 0?void 0:Lt(e.message,pe);return{takes:r,heads:o,message:s}},VM=(e,t)=>{if(e.model.id!==t.model.id)throw k(`The resolution file is for model ${e.model.id}, not ${g(t.model.name)} (${t.model.id}).`,pe);if(e.target.id!==t.target.id||e.source.id!==t.source.id)throw k(`The resolution file is for merging ${e.source.id} into ${e.target.id}, not ${g(t.source.name)} (${t.source.id}) into ${g(t.target.name)} (${t.target.id}).`,pe)},YM=async(e,t,n,r,o)=>{let s=await ie(e,t).branches(),i=B(n),a=s.find(l=>i?l.id===n.toLowerCase():Yn(l.name,n));if(a===void 0){let l=i?n:`named '${g(n)}'`;throw new f(`${g(o)} has no branch ${l}.`,{exitCode:b.NotFound,type:"ref-not-found",details:{branches:s.map(c=>c.name)}})}let d=ut(a);if(d.id===r.id)throw k(`The source and the target are the same branch (${g(d.name)}); a merge takes two.`,pe);return d},KM=e=>({id:e.id,...e.message?{message:e.message}:{},...e.requestId?{requestId:e.requestId}:{},createdAt:e.createdAt,actionTypes:e.actionTypes}),zM=(e,t,n)=>{let r=n.conflicts.length,o=n.rejected.length,s=o===1?"was":"were",i=o===0?"":`, and ${P(o,"resolution")} it was given ${s} refused`;return new f(`Merging ${g(t.source.name)} into ${g(t.target.name)} of ${g(t.model.name)} conflicts on ${P(r,"element")}${i}; nothing was merged.`,{exitCode:b.Conflict,type:"merge-conflict",requestId:e.requestId,hint:"The report is on stdout (--json > merge.json captures it): fill in 'take' on each entry (target, source, or fields with a side per field) and run again with --resolve merge.json. An entry marked rejected needs another pick.",details:{conflicts:r,rejected:o},hosted:{hint:"The result carries the report. Pick a side for each conflict with 'take' (element[#field]=target|source) or 'takeOthers', pass the heads the report gives as 'expect' and 'expectSource', and call again. An entry marked rejected needs another pick."}})},gc="merge_preview",Dy=`Call ${gc} again and pick on its report.`,Ly=e=>`modeldesk branch merge ${e.model.id}@${g(e.target.name)} ${g(e.source.name)} --dry-run --json > merge.json`,JM=(e,t)=>{let n=e.details.conflict??{},r=n.branchId===t.source.id?t.source:t.target,o=typeof n.currentHeadCommitId=="string"?` (its head is now ${n.currentHeadCommitId})`:"";return new f(`${g(r.name)} moved since the heads this merge was bound to${o}, so nothing was merged.`,{exitCode:b.Conflict,type:"branch-head-conflict",requestId:e.requestId,hint:`Run the preview again, '${Ly(t)}', fill in the takes, and run again with --resolve merge.json.`,details:e.details,hosted:{hint:Dy}})},XM=(e,t)=>{let n=typeof e.details.rule=="string"?e.details.rule:"unknown",r=typeof e.details.elementId=="string"?` on ${e.details.elementId}`:"";return new f(`The merge refused a resolution${r} (${n}); nothing was merged.`,{exitCode:e.exitCode,type:e.type,requestId:e.requestId,hint:`Run the preview again, '${Ly(t)}', and fill in the takes on its report.`,details:e.details,hosted:{hint:Dy}})},QM=async(e,t)=>{let n;try{n=await e.branches.mergePreview(t.model.id,t.target.id,t.source.id)}catch(s){if(s instanceof f&&s.type==="nothing-to-merge")return{result:{...t,outcome:"already-merged"}};throw s}let r=hy(n),o=yy(r);return{result:pc(t,r,o),exitCode:BM[o]}},ZM=(e,t,n,r,o)=>{let s=r===void 0?{}:{takeOthers:r};if(e!==void 0)return{...e,...s};if(!(n.target===void 0||n.source===void 0||t.length===0&&r===void 0))return{model:{id:o.model.id},target:{id:o.target.id,head:n.target},source:{id:o.source.id,head:n.source},...s,entries:[]}},eN=async(e,t,{bound:n,heads:r,takes:o,text:s})=>{if(n===void 0)return{source:t.source.id,message:s,...r.target===void 0?{}:{expectedHeadId:r.target},...r.source===void 0?{}:{expectedSourceHeadId:r.source}};let i=await nN(e,t,o),a={...n,entries:i.reduce((d,l)=>Cy(d,l),n.entries)};return Ry(a),ky(a,s)},tN=(e,t,n)=>{if(!(e instanceof f))throw e;switch(e.type){case"nothing-to-merge":return{result:{...t,outcome:"already-merged"}};case"merge-conflict":{let r=gy(e.details);return{result:pc(t,r,"conflicts",n.takeOthers),refusal:zM(e,t,r)}}case"branch-head-conflict":throw JM(e,t);case"invalid-resolution":throw XM(e,t);default:throw e}},_y=A({path:["branch","merge"],effect:"land-direct",summary:"Merge a branch into the addressed one",description:"Merges the source branch into the branch the address names, as one commit with both heads as parents. --dry-run is the preview: it exits 0 when the merge would land clean, 5 when the branches conflict, 4 when the merged model would break a rule no pick resolves, and the report it prints under --json is the resolution file: fill in 'take' on each entry (target, source, or fields with a side per field) and pass it back with --resolve <file> or - for standard input. The file carries both heads, so a branch that moved since the preview exits 5. A person picks inline with --take <element>[#<field>]=target|source, together with --expect and --expect-source as the preview reported the heads; --take-others takes every other conflict from one side. A merge refused with conflicts prints the same report on stdout and the error on stderr, exit 5; one with nothing to merge exits 0 as already-merged, so a re-run converges. Under an agent host a merge is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1, whatever the branches; the preview runs.",positionals:[N(Pt),{name:"source",type:"string",required:!0,description:"The branch to merge from, by name (ignoring case) or id: another branch of the same model."}],flags:{message:{type:"string",short:"m",placeholder:"message",description:"What the merge commit is called in history; 'Merged <source> into <target>' unless given."},resolve:{type:"string",readsFile:!0,placeholder:"file",description:"The report printed by --dry-run --json or by a refused merge, with 'take' filled in; '-' reads standard input. Only ids, takes and both heads are read from it."},take:{type:{list:"string"},placeholder:"element[#field]=target|source",description:"Take one conflicting element, or one of its fields, from a side; the element by id, or by its label path on the target branch. Needs both --expect flags, or --resolve, so the pick binds to heads you reviewed.",toolDescription:"Take one conflicting element, or one of its fields, from a side; the element by id, or by its label path on the target branch. Needs expect and expectSource, so the pick binds to heads you reviewed."},"take-others":{type:{enum:["target","source"]},description:"The side every conflict no other pick names is taken from whole. Needs the heads as --take does.",toolDescription:"The side every conflict no other pick names is taken from whole. Needs the heads as take does."},expect:{type:"string",placeholder:"target-head",description:"The head the target branch must still be at, as the preview reported it (exit 5 otherwise).",toolDescription:"The head the target branch must still be at, as the preview reported it; a conflict otherwise."},"expect-source":{type:"string",placeholder:"source-head",description:"The head the source branch must still be at, as the preview reported it (exit 5 otherwise).",toolDescription:"The head the source branch must still be at, as the preview reported it; a conflict otherwise."}},dryRun:!0,examples:["modeldesk branch merge <model>@main feat/x --dry-run --json > merge.json","modeldesk branch merge <model>@main feat/x --resolve merge.json","modeldesk branch merge <model>@main feat/x --take SHACL/NodeShape#severity=source --take-others target --expect <target-head> --expect-source <source-head>"],mcp:[{name:gc,description:"Previews merging source into the branch the address names (model@<target>) and changes nothing: whether it lands clean, each conflict with both sides' values, and any rule the merged model would break. Show it to the person when you ask them to merge your branch in the app.",pin:{dryRun:!0,take:void 0,"take-others":void 0,expect:void 0,"expect-source":void 0,message:void 0}},{name:"branch_merge",description:"Merges source into the branch the address names (model@<target>) as one commit. It needs the person's 'Act without your review' permission, and the call is refused without it. Never merge unless the person asked you to; ask them to review and merge in the app instead. Resolve conflicts merge_preview reported with take (element[#field]=target|source) and takeOthers, passing expect and expectSource as the heads it reported.",pin:{dryRun:!1}}],resultSchema:Oy.branchMerge,prepare:async e=>{let{flags:t}=e;if(t.resolve!==void 0)return My(t,e.dryRun,!0),Ay(e,t.resolve,pe)},run:async(e,t)=>{let{flags:n,dryRun:r}=e;if(t===void 0&&n.resolve!==void 0)throw k(`--resolve ${n.resolve} was not read, so there is no resolution to merge with.`,pe);let{takes:o,heads:s,message:i}=My(n,r,t!==void 0),a=t===void 0?void 0:by(t),d=e.args.model,l=await ae(e,d,Pt),c=nt(l),m=await YM(e,d.model,e.args.source,c,l.name),p={model:{id:l.id,name:l.name},ref:le(l),target:{id:c.id,name:c.name,head:c.head},source:{id:m.id,name:m.name,head:m.head}},h=e.api();if(r)return QM(h,p);a!==void 0&&VM(a,p);let u=ZM(a,o,s,n["take-others"]??a?.takeOthers,p),y=i??`Merged ${m.name} into ${c.name}`,w=await eN(e,p,{bound:u,heads:s,takes:o,text:y});try{let E=await h.branches.merge(p.model.id,c.id,w);return{result:{...p,target:{...p.target,head:E.targetCommitId},source:{...p.source,head:E.sourceCommitId},outcome:"merged",mergeBaseId:E.mergeBaseId,commit:KM(E.commit),resolved:w.resolutions?.length??0,...w.takeOthers===void 0?{}:{takeOthers:w.takeOthers}}}}catch(E){return tN(E,p,w)}},render:e=>{let t=g(e.model.name),n=g(e.target.name),r=g(e.source.name);switch(e.outcome){case"already-merged":return`${n} of ${t} already holds everything on ${r}; there is nothing to merge.`;case"merged":{let o=e.resolved>0?` (${P(e.resolved,"conflict")} resolved)`:"";return`Merged ${r} into ${n} of ${t} as ${e.commit.id}${o}: `+g(e.commit.message?.split(`
176
+ `)[0]??"")}case"clean":return`Merging ${r} into ${n} of ${t} would land clean (merge base ${e.mergeBaseId}); nothing was merged (dry run).`;case"blocked":return[`Merging ${r} into ${n} of ${t} is blocked by ${P(e.blockers.length,"rule")} the merged model would break:`,...e.blockers.map(o=>` - ${g(o)}`),...e.resolutions.length===0?[]:[`It also conflicts on ${P(e.resolutions.length,"element")}:`,...e.resolutions.flatMap(o=>Py(o,e.names,n,r))]].join(`
177
+ `);case"conflicts":return[`Merging ${r} into ${n} of ${t} conflicts on ${P(e.resolutions.length,"element")} (merge base ${e.mergeBaseId}):`,...e.resolutions.flatMap(o=>Py(o,e.names,n,r)),...(e.rejected??[]).map(o=>` rejected on ${o.elementId}: ${g(o.message)} (${o.rule})`),"Run with --json > merge.json, fill in 'take' on each entry, and pass it back with --resolve merge.json."].join(`
178
+ `)}}}),nN=async(e,t,n)=>{let o=n.filter(s=>!B(s.element)).length===0?void 0:dn(await e.api().models.get(t.model.id,{ref:t.target.id,expand:["labels"]}));return n.map(s=>({elementId:o===void 0||B(s.element)?s.element.toLowerCase():U(o,s.element,{internal:!0}),...s.field===void 0?{}:{field:s.field},side:s.side}))},rN=(e,t,n)=>typeof e=="string"?n?Fo(t,e):g(e):g(JSON.stringify(e)),hc=(e,t,n)=>e===void 0||e.length===0?"(none)":e.map(r=>rN(r,t,n)).join(", "),Ny=(e,t)=>{if(!e.present)return"absent";let n=e.owners.length===0?"":` under ${e.owners.map(r=>Fo(t,r)).join(", ")}`;return`${e.type??"present"}${n}`},oN=(e,t,n,r,o)=>{let s=t.kind==="relation",i=t.base===void 0?"":` | base ${hc(t.base,n,s)}`;return` ${e}: ${r} ${hc(t.target,n,s)} | ${o} ${hc(t.source,n,s)}${i}`},Py=(e,t,n,r)=>{let o=[Ny(e.target,t),Ny(e.source,t)];return[` ${g(e.label)} ${e.reason} ${e.elementId}`,...o[0]===o[1]?[]:[` on ${n}: ${o[0]}; on ${r}: ${o[1]}`],...Object.entries(e.fields).map(([s,i])=>oN(s,i,t,n,r)),...(e.rejected??[]).map(s=>` rejected: ${g(s.message)} (${s.rule})`)]};var Ui=(e,t)=>e.at(-1)===""&&t==="";var sN=/^<figure data-md-diagram="([^"]*)"[ >]/,iN=e=>sN.exec(e)?.[1],aN="</figure>",jy=(e,t)=>{if(t.size===0||e.payloads===void 0)return e;let n=Object.fromEntries(Object.entries(e.payloads).map(([r,o])=>[r,dN(o,t)]));return{...e,payloads:n}},dN=(e,t)=>{let n=e.split(`
179
+ `),r=[];for(let o=0;o<n.length;o+=1){let s=iN(n[o]),i=s!==void 0&&t.has(s)?n.indexOf(aN,o):-1;if(i===-1){r.push(n[o]);continue}o=i,Ui(r,n[o+1])&&(o+=1)}return r.join(`
180
+ `)};var yc=e=>`${JSON.stringify(e,null,2)}
181
+ `;var Fe=["intro","after"],wt=e=>{let t=new Map;for(let n of e.fragments??[]){let r=t.get(n.elementId)??{};t.set(n.elementId,{title:r.title||n.title||void 0,kind:r.kind||n.kind||void 0,anchor:r.anchor||n.realization?.anchor||void 0})}return t},lN=/^<!-- md-slot (?=intro [0-9a-f-]{36} -->$|after )(intro|after) ([0-9a-f-]{36})(?: heading=([1-6]))? -->$/,cN="<!-- md-slot ",Wo=class extends Error{constructor(n){super(`The bundle carries a note slot this version cannot read: ${n}. The client is older than the server.`);this.line=n;this.name="UnreadableSlotError"}line},qy=e=>{if(!e.startsWith(cN))return;let t=lN.exec(e);if(t===null)throw new Wo(e);let n={name:t[1],elementId:t[2]};return t[3]===void 0?n:{...n,heading:Number(t[3])}},Wy=e=>{let t=new Map;for(let[n,r]of Object.entries(e.payloads??{})){let o=r.split(`
182
+ `).flatMap(s=>qy(s)??[]);o.length>0&&t.set(n,o)}return t},wc=(e,t)=>{if(e.payloads===void 0)return{bundle:e,filled:[],dropped:[]};let n=wt(e.manifest),r=a=>n.get(a)?.anchor,o=[],s=[],i=Object.fromEntries(Object.entries(e.payloads).map(([a,d])=>{let l=mN(d,t,r);return o.push(...l.filled.map(c=>({...c,address:a}))),s.push(...l.dropped.map(c=>({...c,address:a}))),[a,l.text]}));return{bundle:{...e,payloads:i},filled:o,dropped:s}},mN=(e,t,n)=>{let r=e.split(`
183
+ `),o=[],s=new Set,i=[],a=[];for(let d=0;d<r.length;d+=1){let l=qy(r[d]);if(l===void 0){o.push(r[d]);continue}let c=t.get(l.elementId)?.[l.name],m=`${l.name} ${l.elementId}`;if(c!==void 0&&!s.has(m)){s.add(m),i.push(l),o.push(...pN(l,c,n));continue}c!==void 0&&a.push(l),Ui(o,r[d+1])&&(d+=1)}return{text:o.join(`
184
+ `),filled:i,dropped:a}},pN=(e,t,n)=>{if(e.heading===void 0){if(typeof t!="string")throw new Error(`The ${e.name} slot of ${e.elementId} takes a note path, not a heading.`);return[Fy(t)]}if(typeof t=="string")throw new Error(`The ${e.name} slot of ${e.elementId} takes a note with a heading.`);let r=n(e.elementId);if(r===void 0)throw new Error(`The bundle's manifest has no anchor for ${e.elementId}.`);let o=t.heading.replace(/\s+/g," ").trim();if(o==="")throw new Error(`The ${e.name} note of ${e.elementId} has an empty heading.`);let s=`${r}-${zn(o)||e.name}`;return[`${"#".repeat(e.heading)} ${uN(o)} {#${s}}`,"",Fy(t.file)]},zn=e=>e.normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),Fy=e=>`<div data-include-format="markdown" data-include="${fN(e)}"></div>`,fN=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g,"&#10;").replace(/\r/g,"&#13;"),uN=e=>e.replace(/[\\`*_[\]()!#|~]/g,"\\$&").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\{/g,"&#123;").replace(/\}/g,"&#125;");var Ho="http://www.w3.org/2000/svg",Uy="Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",bc="group",Ec="spacingAndGlyphs",Cc="italic",Rc="underline",Gr="none";var Gi="hidden",Vi="stroke",kc="auto";var hN="start",Yi="clip",gN=/^[A-Za-z0-9_-]+$/,yN=/[^A-Za-z0-9_-]+/g,vc=e=>gN.test(e),Gy=e=>e.replace(yN,"-");var Ic=(e,t)=>t?`${e}-${hN}`:e,Hy=String.raw`-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?`,By=String.raw`[a-zA-Z]+\(\s*(?:${Hy}(?:[\s,]+${Hy})*)?\s*\)`,wN=new RegExp(String.raw`^${By}(?:\s+${By})*$`),Vy=e=>wN.test(e);var bN=/[\u0000- \u007F]/g,EN=/^([a-zA-Z][a-zA-Z0-9+.-]*):/,CN=new Set(["http","https","mailto"]),Ki=e=>{let t=$o(e).replace(bN,"");if(t==="")return!1;let n=EN.exec(t);return n===null||CN.has(n[1].toLowerCase())};var re="#4b5563";var ot="white";var Sc="strokeWidth",zi=[{id:"triangle-filled",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"line",x1:16,y1:10,x2:20,y2:10,stroke:"white",strokeWidth:2},{element:"path",d:"M 6 4 L 19 10 L 6 16 L 10 10 Z",fill:re,stroke:re,strokeWidth:1}]},{id:"triangle-hollow",markerWidth:24,markerHeight:24,refX:24,refY:12,shapes:[{element:"line",x1:20,y1:12,x2:24,y2:12,stroke:"white",strokeWidth:2},{element:"path",d:"M 6 2 L 22 12 L 6 22 Z",fill:ot,stroke:re,strokeWidth:2}]},{id:"diamond-filled",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 10 5 L 19 10 L 10 15 L 1 10 Z",fill:re,stroke:re,strokeWidth:1.5}]},{id:"diamond-hollow",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 10 5 L 19 10 L 10 15 L 1 10 Z",fill:ot,stroke:re,strokeWidth:1.5}]},{id:"arrow-open",markerWidth:20,markerHeight:20,refX:20,refY:10,shapes:[{element:"path",d:"M 6 4 L 19 10 L 6 16",fill:"none",stroke:re,strokeWidth:2}]},{id:"bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:re,strokeWidth:1.5}]},{id:"circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"circle",cx:13.5,cy:6,r:2.75,fill:ot,stroke:re,strokeWidth:1.5}]},{id:"crowsfoot",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:re,strokeWidth:1.5}]},{id:"crowsfoot-bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:re,strokeWidth:1.5},{element:"line",x1:4,y1:1,x2:4,y2:11,stroke:re,strokeWidth:1.5}]},{id:"crowsfoot-circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 18 1 L 8 6 L 18 11 M 8 6 L 18 6",fill:"none",stroke:re,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:ot,stroke:re,strokeWidth:1.5}]},{id:"bar-circle",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:re,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:ot,stroke:re,strokeWidth:1.5}]},{id:"crowsfoot-triangle-circle",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 24 3 L 19 3 M 24 6 L 19 6 M 24 9 L 19 9",fill:"none",stroke:re,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:ot,stroke:re,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:ot,stroke:re,strokeWidth:1.5}]},{id:"crowsfoot-triangle-bar",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 24 3 L 19 3 M 24 6 L 19 6 M 24 9 L 19 9",fill:"none",stroke:re,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:ot,stroke:re,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:re,strokeWidth:1.5}]},{id:"triangle-circle",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:ot,stroke:re,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:ot,stroke:re,strokeWidth:1.5}]},{id:"triangle-bar",markerWidth:24,markerHeight:12,refX:24,refY:6,shapes:[{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:ot,stroke:re,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:re,strokeWidth:1.5}]},{id:"cup",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"path",d:"M 13 1 A 5 5 0 0 0 13 11",fill:"none",stroke:re,strokeWidth:1.5}]}],J8=new Map(zi.map(e=>[e.id,e]));var SN=" ",$c=["fill","fill-opacity","stroke","stroke-opacity","stroke-width","stroke-dasharray"],$N={svg:["xmlns","viewBox","width","height","role","aria-label","font-family"],defs:[],marker:["id","markerWidth","markerHeight","refX","refY","orient","markerUnits"],clipPath:["id"],g:["data-md-element","clip-path","transform"],a:["href"],title:[],desc:[],rect:["x","y","width","height","rx",...$c],path:["d",...$c,"stroke-linejoin","marker-start","marker-end","visibility","pointer-events"],polygon:["points",...$c],line:["x1","y1","x2","y2","fill","stroke","stroke-opacity","stroke-width","stroke-dasharray"],circle:["cx","cy","r","fill","stroke","stroke-width"],text:["x","y","font-size","font-weight","font-style","text-decoration","fill","fill-opacity","textLength","lengthAdjust"]},Qy=new Map(Object.entries($N).map(([e,t])=>[e,new Set(t)])),TN=new Set(["title","desc","text"]),Yy="svg",Vr="g",_t="a",Zy="title",Bo="data-md-element",ew="path",tw=["visibility","pointer-events"],nw=new Set(["rect","text","polygon","line"]),xN={"clip-path":"clipPath","marker-start":"marker","marker-end":"marker"},rw=/&(amp|lt|gt|quot|apos);/g,AN={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},ON=/[<>"']/,MN=/[\u0000-\u001F]/,NN=/^<([^\s/>]+)/,PN=/^<\/([^\s/>]+)>/,Tc=/ ([^\s=/>"'<]+)=/y,xc=/"([^"]*)"/y,DN=/^on/i,LN=/^ */,_N=64,Ky=/[\p{Cc}\p{Cf}\u2028\u2029]/gu,jt=String.raw`-?\d+(?:\.\d+)?(?:e\+\d+)?`,jN=new RegExp(`^${jt}$`),FN=/^(?:[1-9]\d{0,2}|1000)$/,qN=new RegExp(`^0 0 ${jt} ${jt}$`),WN=new RegExp(`^${jt}(?:[ ,]${jt})*$`),HN=new RegExp(`^(?:${jt},${jt}(?: ${jt},${jt})*)?$`),BN=/^[MmZzLlHhVvCcSsQqTtAa0-9eE.,+\- ]*$/,ow=/^url\(#([A-Za-z0-9_-]+)\)$/,sw=/^#[0-9a-f]{6}$/,zy=Array.from(new Set([Gr,...zi.flatMap(({shapes:e})=>e.flatMap(t=>["fill"in t?t.fill:Gr,t.stroke])).filter(e=>!sw.test(e))])),iw=zi.flatMap(({id:e})=>[Ic(e,!1),Ic(e,!0)]),UN=new RegExp(`^${Yi}-[1-9]\\d*$`),GN=new RegExp(`-${Yi}-[1-9]\\d*$`),Mc=`${"md"}-`,Nc=e=>`U+${e.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}`,Oe=e=>{let t=[];for(let n of e){if(t.length===_N)return`${t.join("").replace(Ky,Nc)}\u2026`;t.push(n)}return e.replace(Ky,Nc)},aw=e=>{if(e.includes("&#"))return"a numeric character reference is not allowed";let t=e.replace(rw,"");if(t.includes("&"))return"& does not start one of the five XML entities";let n=ON.exec(t);return n===null?void 0:`an unescaped ${n[0]} is not allowed`},dw=e=>e.replace(rw,(t,n)=>AN[n]),Jn=(e,t)=>n=>e.test(n)?void 0:`"${Oe(n)}" is not ${t}`,st=(e,t)=>n=>e.includes(dw(n))?void 0:`"${Oe(n)}" is not ${t}`,Jy=()=>{},we=Jn(jN,"a number as the serializer writes one"),Xy=e=>sw.test(e)||zy.includes(e)?void 0:`"${Oe(e)}" is not a paint the serializer writes (#rrggbb, ${zy.join(", ")})`,Ac=Jn(ow,"a reference to a definition in the file, as url(#\u2026)"),VN=e=>UN.test(e)?"clipPath":iw.includes(e)?"marker":void 0,YN=(e,t)=>{if(!e.startsWith(Mc))return;let n=e.slice(Mc.length);if(t!==void 0)return n.startsWith(`${t}-`)?VN(n.slice(t.length+1)):void 0;if(vc(n))return(GN.exec(n)?.index??0)>0?"clipPath":iw.some(r=>n.length>r.length+1&&n.endsWith(`-${r}`))?"marker":void 0},KN=(e,t,{idPrefix:n})=>{if(YN(e,n)===t)return;let r=n??"<prefix>",o=t==="marker"?"<marker>[-start]":`${Yi}-<n>`;return`"${Oe(e)}" is not an id the serializer gives a <${t}> (${Mc}${r}-${o})`},zN=e=>{let t=dw(e);return t.startsWith("#")&&Ki(t)?void 0:`"${Oe(e)}" does not point at a section of the page (#\u2026)`},JN={xmlns:st([Ho],"the SVG namespace"),viewBox:Jn(qN,"a viewBox the serializer writes (0 0 width height)"),width:we,height:we,role:st([bc],`the role the serializer writes (${bc})`),"aria-label":Jy,"font-family":st([Uy],"the serializer's font stack"),id:KN,markerWidth:we,markerHeight:we,refX:we,refY:we,orient:st([kc],`the marker orientation the serializer writes (${kc})`),markerUnits:st([Sc],`the marker units the serializer writes (${Sc})`),"data-md-element":Jy,"clip-path":Ac,transform:e=>Vy(e)?void 0:`"${Oe(e)}" is not a transform of numbers the serializer writes`,href:zN,x:we,y:we,rx:we,fill:Xy,"fill-opacity":we,stroke:Xy,"stroke-opacity":we,"stroke-width":we,"stroke-dasharray":Jn(WN,"a dash pattern of numbers"),d:Jn(BN,"path data (commands and numbers only)"),"stroke-linejoin":st(["round"],"the line join the serializer writes (round)"),"marker-start":Ac,"marker-end":Ac,points:Jn(HN,"polygon points as the serializer writes them (x,y x,y \u2026)"),x1:we,y1:we,x2:we,y2:we,cx:we,cy:we,r:we,"font-size":we,"font-weight":Jn(FN,"a numeric font weight (1 to 1000)"),"font-style":st([Cc],`the font style the serializer writes (${Cc})`),"text-decoration":st([Rc],`the decoration the serializer writes (${Rc})`),textLength:we,lengthAdjust:st([Ec],`the length adjustment the serializer writes (${Ec})`),visibility:st([Gi],`the visibility of a hit area (${Gi})`),"pointer-events":st([Vi],`the pointer events of a hit area (${Vi})`)},XN=(e,t)=>{if(DN.test(t))return`the event-handler attribute ${Oe(t)} is not allowed`;if(t.toLowerCase()==="style")return"a style attribute is not allowed";if(t.toLowerCase()==="class")return"a class attribute is not allowed";if(t.includes(":"))return`the namespaced attribute ${Oe(t)} is not allowed`;if(!Qy.get(e).has(t))return`<${e}> does not take the attribute ${Oe(t)}`},QN=(e,t,n,r)=>{let o=aw(n)??JN[t](n,e,r);return o===void 0?void 0:`${t}: ${o}`},ZN=(e,t,n,r)=>{let o=new Map,s=n;for(;t[s]!==">"&&!t.startsWith("/>",s);){Tc.lastIndex=s;let i=Tc.exec(t)?.[1];if(i===void 0)return{problem:'a tag the serializer would not write: expected ` name="value"`, `>` or `/>`'};xc.lastIndex=Tc.lastIndex;let a=xc.exec(t)?.[1];if(a===void 0)return{problem:`the value of ${Oe(i)} is not double-quoted`};let d=XN(e,i)??QN(e,i,a,r);if(d!==void 0)return{problem:d};if(o.has(i))return{problem:`<${e}> repeats the attribute ${i}`};o.set(i,a),s=xc.lastIndex}return{attributes:o,end:s}},Oc=e=>e.startsWith("<")?"more than one element on one line":"text outside <title> and <text>",eP=(e,t)=>{if(e.includes("<!"))return{problem:"a markup declaration (<!\u2026>: a DOCTYPE, an ENTITY, a comment or CDATA) is not allowed"};if(e.includes("<?"))return{problem:"a processing instruction (<?\u2026?>) is not allowed"};if(e.startsWith("</")){let m=PN.exec(e);if(m===null)return{problem:"a closing tag the serializer would not write"};let p=e.slice(m[0].length);return p!==""?{problem:Oc(p)}:{line:{kind:"close",name:m[1]}}}let n=NN.exec(e)?.[1];if(n===void 0)return{problem:"the line does not start with a tag"};if(!Qy.has(n))return{problem:`<${Oe(n)}> is not an element the diagram serializer writes`};let r=ZN(n,e,n.length+1,t);if("problem"in r)return r;let{attributes:o,end:s}=r,i=e.startsWith("/>",s),a=e.slice(s+(i?2:1));if(!TN.has(n))return a!==""?{problem:Oc(a)}:{line:{kind:i?"empty":"open",name:n,attributes:o}};if(i||a==="")return{problem:`<${n}> has to hold its text on one line, as <${n}>\u2026</${n}>`};let d=`</${n}>`,l=a.indexOf(d);if(l===-1)return{problem:`<${n}> is not closed on its line`};if(l+d.length!==a.length)return{problem:Oc(a.slice(l+d.length))};let c=aw(a.slice(0,l));return c===void 0?{line:{kind:"text",name:n,attributes:o}}:{problem:`text: ${c}`}},tP=(e,t)=>{if(e.name===Yy!=(t===0))return t===0?`the file opens with <${e.name}>, not the serializer's <svg xmlns="${Ho}"> root`:"<svg> is only the root, never nested";if(e.name===Yy&&(e.kind!=="open"||e.attributes.get("xmlns")!==Ho))return`the root is not the serializer's <svg xmlns="${Ho}">`;if(e.name===_t&&!e.attributes.has("href"))return"<a> without an href"},nP=(e,t,n)=>{if(t.name===_t&&t.children===0&&e.name!==Zy)return"<a> has to open with the <title> of the group it links";if(e.name===_t)return e.kind!=="open"?"<a> is only written open, around the title and body of the group it links":t.name!==Vr||!t.stamped||t.children!==0?`<a> is only written as the first child of a <g ${Bo}>`:n>0?"an <a> inside another <a>":void 0},lw=e=>tw.some(t=>e.attributes.has(t)),rP=(e,t)=>e.size===t.size&&Array.from(t).every(([n,r])=>e.get(n)===r),cw=e=>e.findLast(t=>t.stamped),mw="a line's group draws no box: it holds no <rect>, <text>, <polygon> or <line>",pw="a line's group holds no stamped group of its own",Ji="desc",oP=e=>e!==void 0&&(e.hitArea||e.described),sP={d:()=>!0,fill:e=>e===Gr,stroke:e=>e===re,"stroke-opacity":e=>e==="0","stroke-width":e=>e===Sl(1),"stroke-dasharray":e=>e==="6 4","marker-start":()=>!0,"marker-end":()=>!0},fw=e=>e.name===ew&&e.attributes.get("fill")===Gr&&e.attributes.get("stroke")===re&&Array.from(e.attributes).every(([t,n])=>sP[t]?.(n)??!1),uw=e=>{let t=e.at(-1),n=t?.name===_t?e.at(-2):t;return n?.name===Vr&&n.stamped?n:void 0},iP=(e,t)=>{if(!lw(e))return;let n=t.at(-1),r=n.name===_t?t.at(-2):n;if(r?.name!==Vr||!r.stamped)return`a hit area (${tw.join(", ")}) is only written in a <g ${Bo}>`;if(r.hitArea)return"a stamped group holds one hit area";if(r===n&&r.linked)return"in a linked group, the hit area is inside the link";if(r.drawsBox)return mw;if(r.nestsStamp)return pw;let o=n.previous;if(o===void 0||o!==n.firstPath||!fw(o))return"a hit area follows the line's route, the first path of its group";let s=new Map([["d",o.attributes.get("d")??""],["fill",Gr],["stroke",re],["stroke-width",Sl(10)],["visibility",Gi],["pointer-events",Vi]]);return rP(e.attributes,s)?void 0:`a hit area is the route before it as <path ${Array.from(s.keys()).join(" ")}>, with the serializer's values`},aP=(e,t)=>{let n=cw(t);if(oP(n))return nw.has(e.name)?mw:e.name===Vr&&e.attributes.has(Bo)?pw:void 0},dP=(e,t)=>{if(e.name!==Ji)return;let n=t.at(-1);return uw(t)===void 0||n.children!==1||n.previous?.name!==Zy?`a <${Ji}> is only written right after the <title> that opens a stamped group`:void 0},Pc=(e,t={})=>{if(t.idPrefix!==void 0&&!vc(t.idPrefix))return`the id prefix "${Oe(t.idPrefix)}" is not one the serializer accepts`;let n=e.split(`
185
+ `);if(n.at(-1)===""&&n.pop(),n.length===0)return"the file is empty";let r=[],o=new Map,s=[],i=0,a=!1;for(let[c,m]of n.entries()){let p=c+1,h=T=>`line ${p}: ${T}`;if(m==="")return h("a blank line");let u=MN.exec(m);if(u!==null)return h(`the control character ${Nc(u[0])} is not allowed`);if($o(m)!==m)return h("a code point XML cannot carry is not allowed");if(a)return h("content after the root element");let y=m.replace(LN,""),w=eP(y,t);if("problem"in w)return h(w.problem);let{line:E}=w,I=E.kind==="close"?r.pop():void 0;if(E.kind==="close"&&I?.name!==E.name)return h(I===void 0?`</${Oe(E.name)}> closes nothing`:`</${Oe(E.name)}> closes <${I.name}>, opened on line ${I.lineNumber}`);let v=m.length-y.length,$=r.length*SN.length;if(v!==$)return h(`indented ${v} spaces where the nesting calls for ${$}`);if(E.kind==="close"){if(I.name===_t){if(I.children===0)return h("<a> has to open with the <title> of the group it links");i-=1}if(I.described&&!I.drawsRoute)return h(`a <${Ji}> belongs to a line's route group, and this group draws no route`);a=r.length===0;continue}let C=r.at(-1),x=tP(E,r.length)??(C&&(nP(E,C,i)??iP(E,r)??dP(E,r)??aP(E,r)));if(x!==void 0)return h(x);let L=E.attributes.get("id");if(L!==void 0){if(o.has(L))return h(`the id ${Oe(L)} is declared twice`);o.set(L,E.name)}for(let[T,O]of E.attributes){let M=xN[T];M!==void 0&&s.push({attribute:T,id:ow.exec(O)[1],kind:M,lineNumber:p})}C!==void 0&&(C.children+=1,C.previous=E,C.firstPath??=E.name===ew?E:void 0,C.linked||=C.stamped&&E.name===_t),lw(E)&&((C.name===_t?r.at(-2):C).hitArea=!0);let R=uw(r);R!==void 0&&(R.described||=E.name===Ji,R.drawsRoute||=C.firstPath===E&&fw(E));let S=cw(r);S!==void 0&&nw.has(E.name)&&(S.drawsBox=!0),S!==void 0&&E.name===Vr&&E.attributes.has(Bo)&&(S.nestsStamp=!0),E.kind==="open"&&(r.push({name:E.name,lineNumber:p,stamped:E.name===Vr&&E.attributes.has(Bo),children:0,linked:!1,hitArea:!1,drawsBox:!1,described:!1,drawsRoute:!1,nestsStamp:!1}),i+=E.name===_t?1:0)}let d=r.at(-1);if(d!==void 0)return`<${d.name}> opened on line ${d.lineNumber} is never closed`;let l=s.find(({id:c,kind:m})=>o.get(c)!==m);return l===void 0?void 0:`line ${l.lineNumber}: ${l.attribute}: url(#${Oe(l.id)}) names no <${l.kind}> the file declares`};var Dc=" ",Lc=/^( *)<g data-md-element="([^"]*)">$/,lP=/^<title>[^<]*<\/title>$/,Xi=".svg",hw=".png",gw=[137,80,78,71,13,10,26,10],cP=e=>{let t=new Map,n=(r,o)=>{o&&!t.has(r)&&t.set(r,`#${o}`)};for(let r of e.fragments??[]){n(r.elementId,r.realization?.anchor);for(let o of r.anchors??[])n(o.elementId,o.anchor)}return t},mP=e=>{let t=new Map;for(let[n,r]of e){let o=To(n);!t.has(o)&&Ki(r)&&t.set(o,r)}return t},pP=(e,t,n)=>{let r=n+Dc,o=`${n}</g>`,s=`${r}<g data-md-element="`;for(let i=t+1;i<e.length;i+=1){let a=e[i];if(a===o||a.startsWith(s))return i;if(!a.startsWith(r))return}},fP=(e,t)=>{if(t.size===0)return e;let n=e.split(`
186
+ `),r=[],o=0;for(;o<n.length;){let s=n[o];r.push(s),o+=1;let i=Lc.exec(s),a=i?t.get(i[2]):void 0;if(!i||a===void 0)continue;let d=i[1],l=d+Dc,c=n[o];if(c===void 0||!c.startsWith(l)||!lP.test(c.slice(l.length)))continue;let m=pP(n,o-1,d);if(m!==void 0){for(r.push(`${l}<a href="${To(a)}">`);o<m;o+=1)r.push(Dc+n[o]);r.push(`${l}</a>`)}}return r.join(`
187
+ `)},uP=e=>e.split(`
188
+ `).some(t=>Lc.test(t)),hP=e=>new Set(e.split(`
189
+ `).flatMap(t=>Lc.exec(t)?.[2]??[])),Qi=(e,t)=>e.toLowerCase().endsWith(Xi)?hP(new TextDecoder().decode(t)):void 0,yw=(e,t)=>e.toLowerCase().endsWith(Xi)&&!uP(new TextDecoder().decode(t));var Ft=class extends Error{path;problem;constructor(t,n){super(`Refused the diagram file ${t}: ${n}`),this.name="RefusedMediaError",this.path=t,this.problem=n}},gP=e=>e.length>=gw.length&&gw.every((t,n)=>e[n]===t),yP=(e,t)=>{let n=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return typeof n=="string"?{idPrefix:Gy(n)}:{}},ww=({manifest:e,mediaIndex:t})=>{let n=mP(cP(e)),r=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),o=new TextEncoder,s=(i,a)=>{let d;try{d=r.decode(a)}catch{throw new Ft(i,"the bytes are not UTF-8 text")}let l=yP(t,i),c=Pc(d,l);if(c!==void 0)throw new Ft(i,c);let m=fP(d,n);if(m===d)return a;let p=Pc(m,l);if(p!==void 0)throw new Ft(i,`once linked, ${p}`);return o.encode(m)};return(i,a)=>{let d=i.toLowerCase();if(d.endsWith(Xi))return s(i,a);if(!d.endsWith(hw))throw new Ft(i,`a diagram file is an ${Xi} or a ${hw}, and this is neither`);if(!gP(a))throw new Ft(i,"the bytes are not a PNG image");return a}};var bw=(e,t)=>{let n=ww(e),r=Ew(e),o=new Map,s=[],i=[];for(let{path:p,bytes:h}of t){if(h===void 0){s.push(p);continue}try{o.set(p,n(p,h))}catch(u){if(!(u instanceof Ft))throw u;s.push(p),i.push({path:p,problem:u.problem})}}let a=new Set;for(let[p,h]of o){let u=r(p);u!==void 0&&yw(p,h)&&a.add(u)}let d=p=>{let h=r(p);return h!==void 0&&a.has(h)},l=new Map([...o].filter(([p])=>!d(p))),c=s.filter(p=>!d(p)),m=new Map;for(let[p,h]of l){let u=r(p),y=Qi(p,h);u!==void 0&&y!==void 0&&m.set(u,y)}return{mediaBytesByPath:l,missingPaths:c,refusals:i.filter(({path:p})=>!d(p)),emptyDiagramIds:a,emptyDiagramPaths:t.map(({path:p})=>p).filter(d),stampsByDiagram:m,...wP(e,c,l)}},Ew=e=>{let t=e.mediaIndex??{};return n=>Object.hasOwn(t,n)?t[n]:void 0},wP=(e,t,n)=>{let r=e.mediaIndex??{},o=Ew(e),s=new Set([...n.keys()].map(o)),i=a=>{let d=o(a);return d!==void 0&&s.has(d)};return{missingDiagrams:Sr(t.filter(a=>!i(a)),r),partialDiagrams:Sr(t.filter(i),r)}},Cw=(e,{emptyDiagramIds:t,stampsByDiagram:n})=>ui(jy(e,t),n,t);import{existsSync as _c,lstatSync as kw,realpathSync as bP,statSync as EP}from"node:fs";import{homedir as CP}from"node:os";import{basename as RP,dirname as kP,isAbsolute as vw,join as Iw,relative as vP,resolve as Yr,sep as IP}from"node:path";var Uo=(e,t,n)=>{if(vw(n))throw new f(`Refusing an absolute path from the bundle manifest: ${n}`);let r=Yr(e,t),o=Yr(e,n);if(o===r||!jc(r,o))throw new f(`Refusing a bundle path that escapes the content root: ${n}`);return o},jc=(e,t)=>{let n=vP(e,t);return n===""||!vw(n)&&n!==".."&&!n.startsWith(`..${IP}`)},Go=(e,t,{ignoreCase:n=!1}={})=>{let r=Rw(e),o=Rw(t);return n?jc(r.toLowerCase(),o.toLowerCase()):jc(r,o)},Xn=e=>{try{return kw(e)}catch{return}},Qn=e=>{try{return EP(e)}catch{return}},Rw=e=>{let t=[],n=e;for(;!_c(n);){let o=kP(n);if(o===n)return e;t.unshift(RP(n)),n=o}let r=bP(n);return t.length>0?Iw(r,...t):r},qt=e=>{if(Xn(e)?.isSymbolicLink())throw new f(`Refusing to write through an existing symlink at a managed path: ${e}`)},Vo=(e,t)=>{if(!Go(e,t))throw new f(`Refusing a path that escapes the content root through a symlink: ${t}`)},Fc=(e,t)=>{let n=Yr(e,t);if(n===Yr(e))throw new f(`The content root resolves to the repository root (${n}); refusing to sync it.`);if(n===Yr(CP()))throw new f("The content root resolves to your home directory; refusing to sync it.");if(_c(n)){if(kw(n).isSymbolicLink())throw new f(`The content root ${n} is a symlink; refusing to sync it.`);if(_c(Iw(n,".git")))throw new f(`The content root ${n} contains a .git directory (it looks like a repo root); refusing.`)}if(!Go(Yr(e),n))throw new f(`The content root ${n} resolves outside the repository via a symlinked ancestor; refusing.`);return n};var Sw={respec:"data/model"},qc=e=>Object.hasOwn(Sw,e)?Sw[e]:void 0,Zi=e=>{let t=qc(e);if(!t)throw new f(`The CLI does not know the content root for stack '${e}'.`);return t};var SP=1500,$P=6e5,TP=e=>new Promise(t=>setTimeout(t,e)),xP=e=>e==="COMPLETED"||e==="COMPLETED_WITH_ERRORS"||e==="FAILED",$w=async(e,t,n)=>{let r=await e.contentBundles.renderDiagrams(t,{template:n.template,version:n.version});if(!r.commit)throw new f("The diagram render did not return a resolved commit; cannot pin the pull.");return r},Tw=async(e,t,n,r,o,s={})=>{let i=s.sleep??TP,a=s.now??Date.now,d=a()+$P;for(r.update(0,o);;){let l=await e.exportJobs.get(t,n);if(l.progress&&r.update(l.progress.completed,l.progress.total,l.progress.currentItem),xP(l.status))return r.done(),l;if(a()>=d)throw new f("Timed out waiting for the diagram render to finish.");await i(SP)}},xw=(e,t,n,r)=>e.contentBundles.media(t,{path:n,template:r.template,commit:r.commit});var Aw=e=>{let t=new Map;for(let n of e.fragments??[])n.realization?.path&&t.set(n.elementId,n.realization.path);return t},Ow=(e,t)=>{let n=Aw(e),r=[];for(let[o,s]of Aw(t)){let i=n.get(o);i&&i!==s&&r.push({elementId:o,oldPath:i,newPath:s})}return r};import{existsSync as AP,mkdirSync as OP,readFileSync as MP,writeFileSync as NP}from"node:fs";import{join as Mw}from"node:path";var Nw=(e,t)=>Mw(e,xr,`${t}.manifest.json`),ea=(e,t)=>{let n=Nw(e,t);if(!AP(n))return;let r;try{r=JSON.parse(MP(n,"utf8"))}catch{return}return PP(r)?r:void 0},PP=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let{fragments:t}=e;return t===void 0?!0:Array.isArray(t)&&t.every(n=>n!==null&&typeof n=="object")},Pw=(e,t,n)=>{OP(Mw(e,xr),{recursive:!0}),NP(Nw(e,t),yc(n))},Dw=e=>{let t=[];for(let r of e.fragments??[]){r.realization?.path&&t.push(r.realization.path);for(let o of r.realization?.media??[])t.push(o)}let n=fi(e);return n!==void 0&&t.push(n),t};import{existsSync as Wc,lstatSync as DP,mkdirSync as Lw,readdirSync as LP,readFileSync as _P,rmSync as jP,writeFileSync as _w}from"node:fs";import{dirname as jw,join as Kr,relative as FP,sep as qP}from"node:path";var Fw=(e,t)=>{let n=Kr(e,t);if(!Wc(n))return[];let r=[],o=s=>{for(let i of LP(s,{withFileTypes:!0})){let a=Kr(s,i.name);i.isDirectory()?o(a):i.isFile()&&r.push(FP(e,a).split(qP).join("/"))}};return o(n),r},Hc=(e,t,n)=>{let r=Kr(e,t);for(let o of n){let s=Uo(e,t,o.path);qt(s),Vo(r,s),Lw(jw(s),{recursive:!0}),_w(s,o.content)}},WP=(e,t,n,r)=>{let o=Kr(e,t),s=Uo(e,t,n);qt(s),Vo(o,s),Lw(jw(s),{recursive:!0}),_w(s,r)},Bc=(e,t,n,r)=>{let o=n.mediaIndex??{},s=Kr(e,t),i=new Map;for(let a of r){let d=Object.hasOwn(o,a)?o[a]:void 0;if(d!==void 0)try{let l=Uo(e,t,a);if(!Wc(l)||DP(l).isSymbolicLink())continue;Vo(s,l);let c=Qi(a,_P(l));c!==void 0&&i.set(d,c)}catch{}}return i},qw=(e,t,n,r,o=Fn(n))=>{let s=[];for(let[l,c]of r.mediaBytesByPath)try{WP(e,t,l,c)}catch(m){s.push({path:l,error:m})}let i=new Map([...Bc(e,t,n,Ir(n.manifest)),...r.stampsByDiagram]),a=new Map(o.map(l=>[l.path,l.content])),d=Fn(Cw(n,{...r,stampsByDiagram:i})).filter(l=>a.get(l.path)!==l.content);return Hc(e,t,d),s},Uc=(e,t,n)=>{let r=Uo(e,t,n);return Vo(Kr(e,t),r),Wc(r)?(jP(r),!0):!1},Ww=(e,t,n)=>{for(let r of n)Uc(e,t,r)};var HP=100,Bw=e=>{if(e.newTextPaths.length===0&&!e.allowEmpty)throw new f("The content fetch returned no fragments (usually the wrong model or format, or a server error). Nothing was written or deleted. Re-run with --allow-empty only if the model is genuinely empty.");let t=Hw([...e.newTextPaths,...e.newMediaPaths]).sort(),n=new Set(t),r=new Set(e.existingFiles),o=t.filter(c=>r.has(c)),s=e.priorManifestPaths!==void 0?"manifest-tracked":"full-sync",i=e.priorManifestPaths??e.existingFiles,a=Hw(i).filter(c=>!n.has(c)).sort(),d=a.length>0&&!e.adopted,l=a.length>0&&(a.length>t.length||a.length>HP);return{writes:t,overwrites:o,orphanCandidates:a,mode:s,adoptionNeeded:d,outsized:l}},Gc=(e,t)=>{if(e.orphanCandidates.length===0)return{deletes:[],warnings:[]};if(e.adoptionNeeded&&!t.adopt)return{deletes:[],warnings:[`${e.orphanCandidates.length} file(s) under the content root are not tracked by the CLI and were left in place. Pass --adopt to let the CLI manage (and prune) this directory.`]};if(e.outsized&&!t.yes)throw new f(`This pull would remove ${e.orphanCandidates.length} file(s), more than the ${e.writes.length} it writes. That often signals a wrong model or format. Nothing was changed. Re-run with --yes if intended.`);return{deletes:e.orphanCandidates,warnings:[]}},Hw=e=>[...new Set(e)];import{readdirSync as UP}from"node:fs";import{join as Yo,posix as Ko}from"node:path";var Gw=e=>{let t=wt(e),n=new Map;for(let r of e.fragments??[]){let o=n.get(r.elementId),s=r.realization?.path,i=s!==void 0&&(s===Uw||s.endsWith(`/${Uw}`));n.set(r.elementId,{elementId:r.elementId,title:t.get(r.elementId)?.title,kind:t.get(r.elementId)?.kind,path:o?.path??s,anchor:t.get(r.elementId)?.anchor,container:(o?.container??!1)||i})}return[...n.values()]},Uw="index.md",Vc=e=>{let t=wt(e);return(e.fragments??[]).flatMap(n=>(n.anchors??[]).map(r=>({elementId:r.elementId,kind:r.kind,slug:r.address.split("/").at(-1)??"",owner:t.get(n.elementId)?.title})))},Vw=(e,t)=>{let n=zn(t);return n===""?[]:e.filter(r=>r.slug===n)},ta=e=>e.replace(/\s+/g," ").trim().toLowerCase(),Yc=(e,t)=>{let n=ta(t);return e.filter(r=>r.title!==void 0&&ta(r.title)===n)},BP=5,Yw=(e,t)=>{let n=ta(t),r=n.length>=4?2:1,s=e.flatMap(i=>i.title===void 0?[]:[i.title]).filter(i=>{let a=ta(i);return n.length>=3&&a.includes(n)||Kc(a,n)<=r});return[...new Set(s)].slice(0,BP)},Kc=(e,t)=>{let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r];for(let s=1;s<=t.length;s+=1)o[s]=Math.min(n[s]+1,o[s-1]+1,n[s-1]+(e[r-1]===t[s-1]?0:1));n=o}return n[t.length]};var na=".after.md",Zn=".md",zw=e=>e.toLowerCase().endsWith(na),Jw=e=>zw(e)?"after":"intro",ra=(e,t)=>{let n=Tr(e);if(n!==void 0)return`the notes folder ${JSON.stringify(e)} ${n}; give a folder relative to the repository root`;if(Ie(e)===".")return"the notes folder is the repository root, so every Markdown file in the repository would be read as a note; give a folder of its own, such as md-notes/";if(Bn(e.toLowerCase(),t.toLowerCase())||Bn(t.toLowerCase(),e.toLowerCase()))return`the notes folder ${e} overlaps the content root ${t}/, which every pull replaces; keep notes outside it`},oa=(e,t,n,r)=>{let o=`${Ie(t)}/`,s=Ie(n);if(!s.startsWith(o)||!s.endsWith(Zn))return;let i=s.slice(o.length,-Zn.length);return Ko.join(Ie(e),`${i}${r==="after"?na:Zn}`)},zc=(e,t)=>Xn(Yo(e,Ie(t)))?.isSymbolicLink()?`the notes folder ${Ie(t)} is a symlink, which the pull does not follow; make it a folder of its own, or set "notesDir" in .modeldesk/config.json to the folder it points to`:void 0,Xw=(e,t)=>{let n=Ie(t),r=zc(e,t);if(r!==void 0)throw new f(`${r[0].toUpperCase()}${r.slice(1)}.`);if(Xn(Yo(e,n))?.isDirectory()!==!0)return[];let o=[],s=a=>{try{return UP(Yo(e,a),{withFileTypes:!0})}catch(d){throw new f(`Could not read the notes folder ${a}: ${d.message}`)}},i=a=>{for(let d of s(a)){if(d.name.startsWith("."))continue;let l=Ko.join(a,d.name);d.isDirectory()?i(l):d.name.toLowerCase().endsWith(Zn)&&!GP(e,l,d)&&o.push(l)}};return i(n),o.sort()},GP=(e,t,n)=>n.isSymbolicLink()?Qn(Yo(e,t))?.isDirectory()===!0:!1,VP=5,Qw=({repoRoot:e,files:t,notesDir:n,contentRoot:r,manifest:o,entries:s})=>{let i=[...s.values()].flatMap(h=>Fe.flatMap(u=>h[u]===void 0?[]:[Ie(h[u])])),a=new Set(i),d=new Set(i.flatMap(h=>Kw(e,h)??[])),l=h=>{if(a.has(Ie(h)))return!0;let u=Kw(e,h);return u!==void 0&&d.has(u)},c=new Map;for(let h of o.fragments??[]){let u=h.realization?.path;u!==void 0&&!c.has(Ie(u))&&c.set(Ie(u),{elementId:h.elementId,title:h.title||void 0})}let m=[],p=new Map;for(let h of t.filter(u=>!l(u))){let u=Jw(h),y=YP(n,r,h),w=y===void 0?void 0:c.get(y);if(w===void 0){m.push(KP(h,y,n,r,[...c.keys()]));continue}let E=s.get(w.elementId)?.[u],I=w.title??w.elementId;if(E!==void 0){m.push(`the note ${h} would be the ${u} note of ${I}, which notes.json already gives as ${E}; keep one of the two files.`);continue}let v=`${u} ${w.elementId}`,$=p.get(v);if($!==void 0){m.push(`the notes ${$.file} and ${h} would both be the ${u} note of ${I}, which appears at more than one place in the document; keep one of the two files.`);continue}p.set(v,{file:h,elementId:w.elementId,slot:u,title:w.title})}return{adoptions:[...p.values()],errors:m}},Kw=(e,t)=>{let n=Qn(Yo(e,t));return n?.isFile()?`${n.dev}:${n.ino}`:void 0},YP=(e,t,n)=>{let r=`${Ie(e)}/`,o=Ie(n);if(!o.startsWith(r))return;let s=o.slice(r.length),i=zw(s)?s.slice(0,-na.length):s.toLowerCase().endsWith(Zn)?s.slice(0,-Zn.length):void 0;return i===void 0?void 0:Ko.join(Ie(t),`${i}${Zn}`)},KP=(e,t,n,r,o)=>{let s=`A note's path is its element's file under ${Ie(r)}/ with ${Ie(n)}/ in its place, ending in ${na} for the note after the element's content.`;if(t===void 0)return`the note ${e} matches no element: its name does not end in .md. ${s}`;let i=Ko.basename(t),a=o.map(l=>({path:l,distance:Kc(l,t)})).filter(({path:l,distance:c})=>Ko.basename(l)===i||c<=2).sort((l,c)=>l.distance-c.distance||l.path.localeCompare(c.path)).slice(0,VP).map(({path:l})=>oa(n,r,l,Jw(e))).filter(l=>l!==void 0),d=a.length===0?"":` Did you mean ${a.join(", ")}?`;return`the note ${e} matches no element: this bundle has no ${t}.${d} ${s}`},Jc=(e,t)=>{let n=new Map(e);for(let{file:r,elementId:o,slot:s,title:i}of t){let a=n.get(o);n.set(o,a===void 0?{...i===void 0?{}:{name:i},[s]:r}:{...a,[s]:r})}return n};import{join as Xc}from"node:path";var Qc=({repoRoot:e,contentRoot:t,entries:n})=>[...n].flatMap(([r,o])=>Fe.flatMap(s=>{let i=o[s];return i===void 0?[]:zP(e,t,i).map(a=>`${zr(r,o.name)} ${s}: ${a}.`)})),Zw=({manifest:e,slots:t,entries:n,notesDir:r})=>{let o=XP(e,t),s=[],i=[],d=[...n].some(([l,c])=>o.has(l)&&Fe.some(m=>c[m]!==void 0))&&t.size===0?`The server rendered stack ${e.stack} ${e.stackVersion}, which carries no note slots, so the notes cannot be placed. Either the server is older than note support, or this template has no slots: notes work with the MIM templates. Pull without notes by moving .modeldesk/notes.json and the notes folder ${r} aside, or pull again once the server is updated.`:void 0;for(let[l,c]of n){let m=o.get(l),p=zr(l,m?.title??c.name);if(m===void 0){i.push(`${p} is not in this bundle; its entry in notes.json is kept.`);continue}if(d===void 0)for(let h of Fe)c[h]!==void 0&&s.push(...JP(m,h).map(u=>`${p} ${h}: ${u}.`))}return{errors:s,warnings:i,slotless:d}},Zc=e=>typeof e=="string"?e:e.file,em=(e,t,n)=>{let r=Tr(n);if(r!==void 0)return[`the note path ${JSON.stringify(n)} ${r}; note paths are relative to the repository root`];if(Bn(n.toLowerCase(),t.toLowerCase()))return[`the note ${n} lies in the content root ${t}/, which every pull replaces, so the pull would remove it; keep notes outside it`];let o=Xc(e,n);return Go(Xc(e,t),o,{ignoreCase:!0})?[`the note ${n} lies in the content root ${t}/ through a symlink, and every pull replaces that folder, so the pull would remove it; keep notes outside it`]:Go(e,o)?[]:[`the note ${n} lies outside the repository through a symlink; keep notes inside it`]},zP=(e,t,n)=>{let r=em(e,t,n);if(r.length>0)return r;let o=Qn(Xc(e,n));return o===void 0?[`the note ${n} does not exist`]:o.isFile()?[]:[`the note ${n} is not a file`]},JP=(e,t)=>{let n=e.slots.get(t);if(n===void 0){let r=[...e.slots.keys()],o=e.kind===void 0?"the element":`this ${e.kind}`;return[r.length===0?`${o} carries no slots`:`${o} carries no ${t} slot, only ${r.join(" and ")}`]}return n.headed&&e.anchor===void 0?["the bundle's manifest gives the element no anchor to build the heading's id from"]:[]},XP=(e,t)=>{let n=new Map;for(let[r,o]of wt(e))n.set(r,{...o,slots:new Map});for(let r of(e.fragments??[]).flatMap(o=>o.anchors??[]))n.has(r.elementId)||n.set(r.elementId,{kind:r.kind,slots:new Map});for(let r of[...t.values()].flat()){let o=n.get(r.elementId)??{slots:new Map};n.set(r.elementId,o);let s=o.slots.get(r.name)?.headed??!1;o.slots.set(r.name,{headed:s||r.heading!==void 0})}return n},zr=(e,t)=>t===void 0?e:`${t} (${e})`;import{existsSync as QP,readFileSync as eb}from"node:fs";import{join as ZP}from"node:path";var eD="notes.json",tD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,nD=["name",...Fe],rD=e=>ZP(e,xr,eD),sa=e=>{let t=rD(e);if(!QP(t))return{path:t,entries:new Map};let n;try{n=eb(t,"utf8")}catch(s){throw new f(`Could not read ${t}: ${s.message}`)}let r;try{r=JSON.parse(n)}catch(s){throw new f(`${t} is not valid JSON: ${s.message}`)}if(!tm(r))throw new f(`${t} must contain a JSON object with a "notes" object.`);for(let s of Object.keys(r))if(s!=="notes")throw new f(`${t}: unknown key "${s}"; the file holds only "notes".`);if(!tm(r.notes))throw new f(`${t}: "notes" must be an object of entries keyed by element id.`);let o=new Map;for(let[s,i]of Object.entries(r.notes))o.set(s,iD(t,s,i));return sD(t,n,o),{path:t,entries:o,raw:n}},oD=/"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"\s*:/g,sD=(e,t,n)=>{let r=new Map;for(let[,o]of t.matchAll(oD))r.set(o,(r.get(o)??0)+1);for(let o of n.keys())if((r.get(o)??0)>1)throw new f(`${e}: notes key "${o}" appears more than once, and JSON keeps only the last; merge the entries.`)},iD=(e,t,n)=>{if(!tD.test(t))throw new f(`${e}: notes key "${t}" is not an element id. Entries are keyed by the element's id, a lowercase UUID as the bundle's manifest gives it.`);let r=`notes.${t}`;if(!tm(n))throw new f(`${e}: ${r} must be an object.`);for(let o of Object.keys(n))if(!nD.includes(o))throw new f(`${e}: ${r} has an unknown key "${o}"; an entry takes "name", "intro" and "after".`);if(n.name!==void 0&&typeof n.name!="string")throw new f(`${e}: ${r}.name must be a string.`);for(let o of Fe)if(n[o]!==void 0&&typeof n[o]!="string")throw new f(`${e}: ${r}.${o} must be a note path. A note that comes under a heading names it on its own first line, <!-- heading: \u2026 -->.`);return n},tm=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),tb=e=>{try{return eb(e,"utf8")}catch{return}};import{readFileSync as uD}from"node:fs";import{join as sb,posix as hD}from"node:path";var aD=/^ {0,3}(`{3,}|~{3,})/,nm=/^(?: {4}|\t)/,dD=/^ {0,3}(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$)/,rb=e=>{let t=[],n,r=!1,o=!0,s=!1;for(let i of e.split(/\r?\n/)){let a=i.trim()==="",d=aD.exec(i)?.[1];if(n!==void 0){d!==void 0&&d[0]===n[0]&&d.length>=n.length&&i.trim()===d&&(n=void 0);continue}if(!(r&&(a||nm.test(i)))){if(r=!1,d!==void 0){n=d,o=!1;continue}if(nm.test(i)&&o&&!s){r=!0;continue}a||(s=dD.test(i)||s&&nm.test(i)),o=a,t.push(i)}}return t},lD=/(?<!`)(`+)(?!`)(.*?[^`])\1(?!`)/g,cD=/!\[([^\]]*)\]\(\s*(?:<([^>]*)>|([^\s)]+))(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)/g,mD=/<img\b([^>]*)>/gi,pD=/([^\s=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g,ob=e=>{let t=rb(e).map(r=>r.replace(lD,o=>" ".repeat(o.length))).join(`
190
+ `),n=[];for(let r of t.matchAll(cD))n.push({src:r[2]??r[3],alt:r[1],syntax:"markdown"});for(let r of t.matchAll(mD)){let o=new Map;for(let i of r[1].matchAll(pD))o.set(i[1].toLowerCase(),i[2]??i[3]??i[4]??"");let s=o.get("src");s!==void 0&&n.push({src:s,alt:o.get("alt"),syntax:"html"})}return n},fD=/^ {0,3}#{1,6}(?=[ \t]|$)(.*)$/,nb=/\s*\{#[^\s}]+\}$/,rm=e=>rb(e).flatMap(t=>{let n=fD.exec(t);if(n===null)return[];let r=n[1].replace(/(?:^|[ \t]+)#+[ \t]*$/,"").trim(),o=nb.test(r),s=o?r.replace(nb,""):r;return s===""?[]:[{text:s,explicitId:o}]});var ib=e=>{let{repoRoot:t,manifest:n,slots:r,entries:o,notes:s,placed:i}=e,a=wt(n),d=u=>a.get(u)?.title??o.get(u)?.name,l=new Map;for(let{name:u,elementId:y}of i.filled){let w=s.get(y)?.[u],E=`${u} ${y}`;w!==void 0&&!l.has(E)&&l.set(E,{elementId:y,title:d(y)??y,slot:u,target:w})}let c=[],m=[],p=new Map;for(let{target:u}of l.values())p.set(Zc(u),(p.get(Zc(u))??0)+1);for(let[u,y]of p)try{m.push({file:u,text:uD(sb(t,u),"utf8"),slots:y})}catch(w){c.push(`could not read the note ${u}, so its images and headings were not checked: ${Ge(w)}`)}for(let u of m)c.push(...wD(t,u.file,u.text,e.publishDirs));c.push(...bD(m),...ED(n,i.dropped,d));let h=[...r.values()].reduce((u,y)=>u+y.length,0);return{warnings:c,substitutions:[...l.values()],removedSlots:h-i.filled.length}},gD=/^(?:https?:|data:|\/\/)/i,yD=e=>{let t=e.replace(/[?#].*$/,""),n=t;try{n=decodeURIComponent(t)}catch{}return hD.normalize(n.replace(/^\/+/,""))},wD=(e,t,n,r)=>ob(n).flatMap(({src:o,alt:s,syntax:i})=>{let a=[];if((s===void 0||i==="markdown"&&s.trim()==="")&&a.push(`the note ${t} has an image without alt text, ${o}; describe it for readers who cannot see it.`),gD.test(o))return a;let d=yD(o);if(d==="."||d==="")return a;if(Qn(sb(e,d))?.isFile()!==!0){let l=d===o?"":` (${d} in the repository)`;a.push(`the note ${t} links the image ${o}${l}, which does not exist; image paths resolve against the repository root.`)}return r!==void 0&&!r.some(l=>Bn(d,l))&&a.push(`the note ${t} links the image ${o}, which lies outside the publishDirs (${r.join(", ")||"none"}), so the published copy will miss it.`),a}),bD=e=>{let t=new Map;for(let o of e)for(let s of rm(o.text)){if(s.explicitId)continue;let i=zn(s.text),a=t.get(i)??{text:s.text,files:[]};a.files.includes(o.file)||t.set(i,{...a,files:[...a.files,o.file]})}let n=[...t.values()].filter(({files:o})=>o.length>1).map(({text:o,files:s})=>`the notes ${s.join(" and ")} each have the heading "${o}" without an explicit {#id}. ReSpec numbers the later ids, so a link to one shifts when the notes change; give each heading its own {#id}.`),r=e.filter(o=>o.slots>1&&rm(o.text).length>0).map(o=>`the note ${o.file} fills ${o.slots} slots, so each of its headings appears ${o.slots} times and their ids repeat or get numbered; give each place its own note file.`);return[...n,...r]},ED=(e,t,n)=>{let r=new Map((e.fragments??[]).map(s=>[s.address,s.realization?.path])),o=new Map;for(let{name:s,elementId:i,address:a}of t){let d=`${s} ${i}`,l=o.get(d)??{slot:s,elementId:i,files:new Set};o.set(d,{...l,files:l.files.add(r.get(a)??a)})}return[...o.values()].map(({slot:s,elementId:i,files:a})=>`${zr(i,n(i))} appears more than once in ${[...a].join(", ")}; its ${s} note goes in at the first place only.`)};import{renameSync as CD,rmSync as ab,writeFileSync as RD}from"node:fs";var db=(e,t)=>{let n=wt(t);return[...e].flatMap(([r,o])=>{let s=n.get(r)?.title;return s===void 0||s===o.name?[]:[{elementId:r,from:o.name,to:s}]})},lb=(e,t)=>{let n=new Map(t.map(r=>[r.elementId,r.to]));return new Map([...e].map(([r,o])=>{let s=n.get(r);return s===void 0?[r,o]:[r,"name"in o?{...o,name:s}:{name:s,...o}]}))},Jr=e=>`${JSON.stringify({notes:Object.fromEntries(e)},null,2)}
191
+ `,ia=(e,t)=>{qt(e);let n=`${e}.tmp`;try{ab(n,{force:!0}),RD(n,t,{flag:"wx"}),CD(n,e)}catch(r){throw ab(n,{force:!0}),r}};import{readFileSync as vD}from"node:fs";import{join as ID}from"node:path";var kD=/^<!--\s*heading:(.*)-->$/i,cb=e=>{let t=e.split(/\r?\n/).find(n=>n.trim()!=="");return t===void 0?void 0:kD.exec(t.trim())?.[1].trim()},aa=e=>`<!-- heading: ${e} -->`,zo=e=>{if(e.trim()==="")return"is blank";if(/[\r\n]/.test(e))return"has a line break";let t=["-->","--!>"].find(n=>e.includes(n));return t===void 0?void 0:`has "${t}", which would end the heading line early`};var mb=({repoRoot:e,slots:t,entries:n})=>{let r=[...t.values()].flat(),o=new Set(r.flatMap(l=>l.heading===void 0?[]:[`${l.name} ${l.elementId}`])),s=new Set(r.map(l=>l.elementId)),i=new Map,a=[],d=[];for(let[l,c]of n){let m={};for(let p of Fe){let h=c[p];if(h===void 0)continue;if(!s.has(l)){m[p]=h;continue}let u=SD(e,h),y=`${zr(l,c.name)} ${p}`;o.has(`${p} ${l}`)?u===void 0||u===""?a.push(`${y}: the note ${h} comes under a heading of its own, so its first line names it, such as ${aa("Afsluiting")}.`):zo(u)!==void 0?a.push(`${y}: the heading line of the note ${h} ${zo(u)}.`):m[p]={file:h,heading:u}:(u!==void 0&&d.push(`${y}: the note ${h} starts with a heading line, which only the closing note of a package or the model takes; the line is left as a comment.`),m[p]=h)}i.set(l,m)}return{notes:i,errors:a,warnings:d}},SD=(e,t)=>{try{return cb(vD(ID(e,t),"utf8"))}catch{return}};var $D=(e,t)=>{let n=t>0?Math.min(1,e/t):0,r=Math.round(n*24);return`[${"#".repeat(r)}${"-".repeat(24-r)}]`},pb=(e,t=n=>{process.stderr.write(n)})=>{let n=-1;return{update(r,o,s){if(e){let i=s?` ${s}`:"";t(`\r${$D(r,o)} ${r}/${o}${i}\x1B[K`)}else if(r!==n){let i=s?` (${s})`:"";t(`Rendering diagrams: ${r}/${o}${i}
192
192
  `),n=r}},done(){e&&t(`
193
- `)}}};var xy=O({path:["bundle","pull"],effect:"local",summary:"Materialize a model's content bundle into a local folder",description:"A full sync of the content root (for ReSpec, data/model/): writes every generated fragment, removes files a previous pull left orphaned, then renders and fetches the diagrams, all pinned to one commit. Text lands first, so a diagram failure leaves valid text and exits 1. A removal larger than the write set needs --yes (exit 6 when not interactive), and a content root the CLI has not managed before is pruned only with --adopt. The repo's element notes (.modeldesk/notes.json and the notes folder) fill the slots the bundle carries; a problem in them stops the pull before anything is written.",flags:{model:{type:"string",placeholder:"id",description:"The model's UUID (default: MODELDESK_MODEL or the repo config)."},stack:{type:"string",placeholder:"id",description:"The content stack to render (required via flag, env or config; see bundle templates)."},template:{type:"string",placeholder:"slug",description:"The document shape within the stack (required via flag, env or config; see bundle templates)."},version:{type:"string",placeholder:"name",description:"Pin a released model version for a reproducible pull (default: live HEAD)."},"no-diagrams":{type:"boolean",description:"Write text fragments only; skip the diagram render and fetch."},adopt:{type:"boolean",description:"Allow the CLI to prune a content root it did not previously manage."},"allow-empty":{type:"boolean",description:"Permit a pull that returns no fragments (a genuinely emptied model)."}},dryRun:!0,examples:["modeldesk bundle pull","modeldesk bundle pull --model <model> --stack respec --template conceptueel-toc --dry-run"],run:async e=>{let{flags:t,globals:n}=e,r=Mo(e,{model:t.model,stack:t.stack,template:t.template,version:t.version}),s=e.api(),o=Jr(r.stack,"stack",B.stack,"--stack"),i=Jr(r.template,"template",B.template,"--template"),{repoRoot:a}=r.loaded,d=mi(a),l=r.loaded.config.notesDir??$o,c=_l(o);c!==void 0&&(zA(l,c),pi(zl({repoRoot:a,contentRoot:c,entries:d.entries})));let f=!t["no-diagrams"]&&!n.dryRun?await Fg(s,r.model,{template:i,version:r.version}):void 0,g=f?.commit,u=await s.contentBundles.get(r.model,{template:i,commit:g,version:g?void 0:r.version});if(u.manifest.stack!==o)throw new p(`Requested stack '${o}', but template '${i}' renders under stack '${u.manifest.stack}'. Run 'modeldesk bundle templates' to see valid stack/template pairs.`);let h=oi(o);Dl(a,h);let{adoptions:y,errors:k}=cy({repoRoot:a,files:ly(a,l),notesDir:l,contentRoot:h,manifest:u.manifest,entries:d.entries});pi([...k,...zl({repoRoot:a,contentRoot:h,entries:JA(y)})]);let S=Kl(d.entries,y),I=vy(()=>Zh(u)),x=my({manifest:u.manifest,slots:I,entries:S,notesDir:l});x.warnings.forEach(ve=>e.warn(ve)),YA(x);let E=Ry({repoRoot:a,slots:I,entries:S});E.warnings.forEach(ve=>e.warn(ve)),pi(E.errors);let M=vy(()=>hl(u,E.notes)),{bundle:v}=M,C=wy({repoRoot:a,manifest:u.manifest,slots:I,entries:S,notes:E.notes,placed:M,publishDirs:r.loaded.config.publishDirs});C.warnings.forEach(ve=>e.warn(ve));let R=[...x.warnings,...E.warnings,...C.warnings],A=ky(S,v.manifest),T=Ey(S,A),N=br(T)!==br(d.entries),q=Hn(v.manifest),X=ql(a,h,v,q),me=hn(vo(v,X,new Set)),Y=Gn(q,v.mediaIndex),U=ii(a,o),ge=ty({newTextPaths:me.map(ve=>ve.path),newMediaPaths:q,priorManifestPaths:U?Kg(U):void 0,existingFiles:Xg(a,h),adopted:U!==void 0||xo(r.loaded),allowEmpty:t["allow-empty"]}),Nt=U?Ug(U,v.manifest):[],se={stack:o,version:v.manifest.stackVersion},au=ve=>({host:r.instance.host,model:r.model,stack:o,stackVersion:se.version,template:i,...g?{commit:g}:{},...r.version?{version:r.version}:{},dryRun:n.dryRun,syncMode:ge.mode,written:ge.writes.length,overwritten:ge.overwrites.length,removed:ve?ve.deletes:ge.orphanCandidates,withheld:ve?.deletes.length===0?ge.orphanCandidates.length:0,moved:Nt.map(Eo=>({from:Eo.oldPath,to:Eo.newPath})),diagrams:{count:Y,status:"skipped",failed:[],leftOut:[]},notes:{adopted:y.map(Eo=>Eo.file),filled:C.substitutions.length,renamed:A.length,slotsRemoved:C.removedSlots},warnings:[...R,...ve?.warnings??[]]});if(n.dryRun)return $y(e,r,i,se,g,ge,void 0,Nt,Y,!0),rT(e,C,y,A),{result:au(void 0)};N&&Rt(d.path);let bd=await QA(e,ge,t.adopt);$y(e,r,i,se,g,ge,bd,Nt,Y,!1),Dl(a,h),Fl(a,h,me),Zg(a,h,bd.deletes),Vg(a,o,v.manifest);let du=[],lu={...e,warn:ve=>{du.push(ve),e.warn(ve)}};N&&XA(lu,d,T,y.length,A.length);let cu=au(bd),mu=()=>({...cu,warnings:[...cu.warnings,...du]});if(q.length===0||!f)return{result:mu()};let fu=await ZA(lu,s,r,{template:i,commit:g,job:f,bundle:v,media:q,written:me},{diagramCount:Y,contentRoot:h});return{result:{...mu(),diagrams:{count:Y,...fu}},exitCode:fu.status==="complete"?b.Success:b.Failure}}}),vy=e=>{try{return e()}catch(t){throw t instanceof ds?new p(`${t.message} Update @modeldesk/cli and pull again.`):t}},YA=e=>{if(e.slotless!==void 0)throw new p(e.slotless);pi(e.errors)},pi=e=>{if(e.length>0)throw new p(`The notes have ${e.length} problem(s), so the pull stopped before writing anything:
193
+ `)}}};var gb=J({path:["bundle","pull"],effect:"local",summary:"Materialize a model's content bundle into a local folder",description:"A full sync of the content root (for ReSpec, data/model/): writes every generated fragment, removes files a previous pull left orphaned, then renders and fetches the diagrams, all pinned to one commit. Text lands first, so a diagram failure leaves valid text and exits 1. A removal larger than the write set needs --yes (exit 6 when not interactive), and a content root the CLI has not managed before is pruned only with --adopt. The repo's element notes (.modeldesk/notes.json and the notes folder) fill the slots the bundle carries; a problem in them stops the pull before anything is written.",flags:{model:{type:"string",placeholder:"id",description:"The model's UUID (default: MODELDESK_MODEL or the repo config)."},stack:{type:"string",placeholder:"id",description:"The content stack to render (required via flag, env or config; see bundle templates)."},template:{type:"string",placeholder:"slug",description:"The document shape within the stack (required via flag, env or config; see bundle templates)."},version:{type:"string",placeholder:"name",description:"Pin a released model version for a reproducible pull (default: live HEAD)."},"no-diagrams":{type:"boolean",description:"Write text fragments only; skip the diagram render and fetch."},adopt:{type:"boolean",description:"Allow the CLI to prune a content root it did not previously manage."},"allow-empty":{type:"boolean",description:"Permit a pull that returns no fragments (a genuinely emptied model)."}},dryRun:!0,examples:["modeldesk bundle pull","modeldesk bundle pull --model <model> --stack respec --template conceptueel-toc --dry-run"],run:async e=>{let{flags:t,globals:n}=e,r=Ci(e,{model:t.model,stack:t.stack,template:t.template,version:t.version}),o=e.api(),s=Oo(r.stack,"stack",G.stack,"--stack"),i=Oo(r.template,"template",G.template,"--template"),{repoRoot:a}=r.loaded,d=sa(a),l=r.loaded.config.notesDir??bi,c=qc(s);c!==void 0&&(xD(l,c),da(Qc({repoRoot:a,contentRoot:c,entries:d.entries})));let p=!t["no-diagrams"]&&!n.dryRun?await $w(o,r.model,{template:i,version:r.version}):void 0,h=p?.commit,u=await o.contentBundles.get(r.model,{template:i,commit:h,version:h?void 0:r.version});if(u.manifest.stack!==s)throw new f(`Requested stack '${s}', but template '${i}' renders under stack '${u.manifest.stack}'. Run 'modeldesk bundle templates' to see valid stack/template pairs.`);let y=Zi(s);Fc(a,y);let{adoptions:w,errors:E}=Qw({repoRoot:a,files:Xw(a,l),notesDir:l,contentRoot:y,manifest:u.manifest,entries:d.entries});da([...E,...Qc({repoRoot:a,contentRoot:y,entries:AD(w)})]);let I=Jc(d.entries,w),v=fb(()=>Wy(u)),$=Zw({manifest:u.manifest,slots:v,entries:I,notesDir:l});$.warnings.forEach(De=>e.warn(De)),TD($);let C=mb({repoRoot:a,slots:v,entries:I});C.warnings.forEach(De=>e.warn(De)),da(C.errors);let x=fb(()=>wc(u,C.notes)),{bundle:L}=x,R=ib({repoRoot:a,manifest:u.manifest,slots:v,entries:I,notes:C.notes,placed:x,publishDirs:r.loaded.config.publishDirs});R.warnings.forEach(De=>e.warn(De));let S=[...$.warnings,...C.warnings,...R.warnings],T=db(I,L.manifest),O=lb(I,T),M=Jr(O)!==Jr(d.entries),_=Ir(L.manifest),z=Bc(a,y,L,_),me=Fn(ui(L,z,new Set)),te=Sr(_,L.mediaIndex),Y=ea(a,s),ke=Bw({newTextPaths:me.map(De=>De.path),newMediaPaths:_,priorManifestPaths:Y?Dw(Y):void 0,existingFiles:Fw(a,y),adopted:Y!==void 0||Ei(r.loaded),allowEmpty:t["allow-empty"]}),Jt=Y?Ow(Y,L.manifest):[],ge={stack:s,version:L.manifest.stackVersion},Mu=De=>({host:r.instance.host,model:r.model,stack:s,stackVersion:ge.version,template:i,...h?{commit:h}:{},...r.version?{version:r.version}:{},dryRun:n.dryRun,syncMode:ke.mode,written:ke.writes.length,overwritten:ke.overwrites.length,removed:De?De.deletes:ke.orphanCandidates,withheld:De?.deletes.length===0?ke.orphanCandidates.length:0,moved:Jt.map(di=>({from:di.oldPath,to:di.newPath})),diagrams:{count:te,status:"skipped",failed:[],leftOut:[]},notes:{adopted:w.map(di=>di.file),filled:R.substitutions.length,renamed:T.length,slotsRemoved:R.removedSlots},warnings:[...S,...De?.warnings??[]]});if(n.dryRun)return hb(e,r,i,ge,h,ke,void 0,Jt,te,!0),_D(e,R,w,T),{result:Mu(void 0)};M&&qt(d.path);let wl=await MD(e,ke,t.adopt);hb(e,r,i,ge,h,ke,wl,Jt,te,!1),Fc(a,y),Hc(a,y,me),Ww(a,y,wl.deletes),Pw(a,s,L.manifest);let Nu=[],Pu={...e,warn:De=>{Nu.push(De),e.warn(De)}};M&&OD(Pu,d,O,w.length,T.length);let Du=Mu(wl),Lu=()=>({...Du,warnings:[...Du.warnings,...Nu]});if(_.length===0||!p)return{result:Lu()};let _u=await ND(Pu,o,r,{template:i,commit:h,job:p,bundle:L,media:_,written:me},{diagramCount:te,contentRoot:y});return{result:{...Lu(),diagrams:{count:te,..._u}},exitCode:_u.status==="complete"?b.Success:b.Failure}}}),fb=e=>{try{return e()}catch(t){throw t instanceof Wo?new f(`${t.message} Update @modeldesk/cli and pull again.`):t}},TD=e=>{if(e.slotless!==void 0)throw new f(e.slotless);da(e.errors)},da=e=>{if(e.length>0)throw new f(`The notes have ${e.length} problem(s), so the pull stopped before writing anything:
194
194
  `+e.map(t=>` - ${t}`).join(`
195
- `))},zA=(e,t)=>{let n=li(e,t);if(n!==void 0)throw new p(`${n[0].toUpperCase()}${n.slice(1)}. Set "notesDir" in .modeldesk/config.json.`)},JA=e=>Kl(new Map,e),XA=(e,t,n,r,s)=>{if(uy(t.path)!==t.raw){e.warn(`${t.path} changed while the pull ran, so the pull left it as it is. Pull again to record the new notes and names in it.`);return}fi(t.path,br(n));let o=[...r>0?[`${r} note(s) added`]:[],...s>0?[`${s} name(s) updated`]:[]];e.print(` notes.json: ${o.join(", ")||"rewritten"}
196
- `)},QA=async(e,t,n)=>{let r=n,s=e.globals.yes;if(t.orphanCandidates.length===0)return Wl(t,{adopt:r,yes:s});if(t.adoptionNeeded&&!r&&(e.io.err(`The content root has ${t.orphanCandidates.length} file(s) the CLI does not track:
197
- `),Iy(e,t.orphanCandidates),r=await e.confirm("Adopt this directory and allow the CLI to remove these files?")),t.outsized&&!s&&(r||!t.adoptionNeeded)){if(e.io.err(`This pull would remove ${t.orphanCandidates.length} file(s), more than the ${t.writes.length} it writes:
198
- `),Iy(e,t.orphanCandidates),!e.interactive)throw new p(`This pull would remove ${t.orphanCandidates.length} file(s), more than the ${t.writes.length} it writes, and this run cannot ask for confirmation. Nothing was changed.`,{exitCode:b.NeedsHuman,hint:"Re-run with --yes if the removal is intended."});s=await e.confirm("Proceed with removing them?")}return Wl(t,{adopt:r,yes:s})},Iy=(e,t)=>{for(let n of t)e.io.err(` ${n}
199
- `)},ZA=async(e,t,n,{template:r,commit:s,job:o,bundle:i,media:a,written:d},{diagramCount:l,contentRoot:c})=>{let m=Sy(e.interactive,E=>{e.globals.json||e.io.err(E)}),f=await qg(t,n.model,o.id,m,l);if(f.status==="FAILED")return e.warn("the diagram render failed. Text fragments are written; media was not fetched. Re-run to retry."),{status:"failed",failed:a,leftOut:[]};let{repoRoot:g}=n.loaded,u=[],h=new Map;for(let E of a)try{u.push({path:E,bytes:await Bg(t,n.model,E,{template:r,commit:s})})}catch(M){u.push({path:E}),h.set(E,M)}let y=Tg(i,u),k=new Map(y.refusals.map(({path:E,problem:M})=>[E,M]));for(let E of y.missingPaths){let M=k.get(E),v=h.get(E);M!==void 0?e.warn(`refused the diagram file ${E} and did not write it: ${M}`):e.warn(`could not fetch media ${E}: ${et(v)}`),(M!==void 0||nT(v))&&Ay(e,g,c,E)}let S=Qg(g,c,i,y,d);for(let{path:E,error:M}of S)e.warn(`could not write media ${E}: ${et(M)}`);let I=y.emptyDiagramPaths.filter(My);y.emptyDiagramIds.size>0&&eT(e,g,c,y.emptyDiagramIds.size,y.emptyDiagramPaths);let x=[...y.missingPaths,...S.map(({path:E})=>E)];return f.status==="COMPLETED_WITH_ERRORS"||x.length>0?(e.warn(`${x.length} media file(s) could not be written; the pull is re-runnable.`),{status:"partial",failed:x,leftOut:I}):{status:"complete",failed:x,leftOut:I}},My=e=>e.toLowerCase().endsWith(".svg"),eT=(e,t,n,r,s)=>{e.print(` Left out ${r} empty diagram(s), which draw no model element:
200
- `);for(let o of s.filter(My))e.print(` - ${o}
201
- `);for(let o of s)Ay(e,t,n,o,i=>e.print(` ${i}
202
- `))},tT=404,nT=e=>e instanceof H&&e.status===tT,Ay=(e,t,n,r,s=e.warn)=>{try{Bl(t,n,r)&&s(`removed the copy of ${r} an earlier pull wrote.`)}catch(o){e.warn(`could not remove the copy of ${r} an earlier pull wrote: ${et(o)}`)}},$y=(e,t,n,r,s,o,i,a,d,l)=>{let c=e.print,m=s?`commit ${s}`:t.version?`version ${t.version}`:"HEAD",f=`${r.stack} ${r.version}`;c(`${l?"Dry run: ":""}Pulling ${t.model} (stack ${f}, template ${n}) at ${m} into ${t.instance.host}.
203
- `),c(` Write: ${o.writes.length} file(s)${o.overwrites.length?` (${o.overwrites.length} overwritten)`:""}
195
+ `))},xD=(e,t)=>{let n=ra(e,t);if(n!==void 0)throw new f(`${n[0].toUpperCase()}${n.slice(1)}. Set "notesDir" in .modeldesk/config.json.`)},AD=e=>Jc(new Map,e),OD=(e,t,n,r,o)=>{if(tb(t.path)!==t.raw){e.warn(`${t.path} changed while the pull ran, so the pull left it as it is. Pull again to record the new notes and names in it.`);return}ia(t.path,Jr(n));let s=[...r>0?[`${r} note(s) added`]:[],...o>0?[`${o} name(s) updated`]:[]];e.print(` notes.json: ${s.join(", ")||"rewritten"}
196
+ `)},MD=async(e,t,n)=>{let r=n,o=e.globals.yes;if(t.orphanCandidates.length===0)return Gc(t,{adopt:r,yes:o});if(t.adoptionNeeded&&!r&&(e.io.err(`The content root has ${t.orphanCandidates.length} file(s) the CLI does not track:
197
+ `),ub(e,t.orphanCandidates),r=await e.confirm("Adopt this directory and allow the CLI to remove these files?")),t.outsized&&!o&&(r||!t.adoptionNeeded)){if(e.io.err(`This pull would remove ${t.orphanCandidates.length} file(s), more than the ${t.writes.length} it writes:
198
+ `),ub(e,t.orphanCandidates),!e.interactive)throw new f(`This pull would remove ${t.orphanCandidates.length} file(s), more than the ${t.writes.length} it writes, and this run cannot ask for confirmation. Nothing was changed.`,{exitCode:b.NeedsHuman,hint:"Re-run with --yes if the removal is intended."});o=await e.confirm("Proceed with removing them?")}return Gc(t,{adopt:r,yes:o})},ub=(e,t)=>{for(let n of t)e.io.err(` ${n}
199
+ `)},ND=async(e,t,n,{template:r,commit:o,job:s,bundle:i,media:a,written:d},{diagramCount:l,contentRoot:c})=>{let m=pb(e.interactive,C=>{e.globals.json||e.io.err(C)}),p=await Tw(t,n.model,s.id,m,l);if(p.status==="FAILED")return e.warn("the diagram render failed. Text fragments are written; media was not fetched. Re-run to retry."),{status:"failed",failed:a,leftOut:[]};let{repoRoot:h}=n.loaded,u=[],y=new Map;for(let C of a)try{u.push({path:C,bytes:await xw(t,n.model,C,{template:r,commit:o})})}catch(x){u.push({path:C}),y.set(C,x)}let w=bw(i,u),E=new Map(w.refusals.map(({path:C,problem:x})=>[C,x]));for(let C of w.missingPaths){let x=E.get(C),L=y.get(C);x!==void 0?e.warn(`refused the diagram file ${C} and did not write it: ${x}`):e.warn(`could not fetch media ${C}: ${Ge(L)}`),(x!==void 0||LD(L))&&wb(e,h,c,C)}let I=qw(h,c,i,w,d);for(let{path:C,error:x}of I)e.warn(`could not write media ${C}: ${Ge(x)}`);let v=w.emptyDiagramPaths.filter(yb);w.emptyDiagramIds.size>0&&PD(e,h,c,w.emptyDiagramIds.size,w.emptyDiagramPaths);let $=[...w.missingPaths,...I.map(({path:C})=>C)];return p.status==="COMPLETED_WITH_ERRORS"||$.length>0?(e.warn(`${$.length} media file(s) could not be written; the pull is re-runnable.`),{status:"partial",failed:$,leftOut:v}):{status:"complete",failed:$,leftOut:v}},yb=e=>e.toLowerCase().endsWith(".svg"),PD=(e,t,n,r,o)=>{e.print(` Left out ${r} empty diagram(s), which draw no model element:
200
+ `);for(let s of o.filter(yb))e.print(` - ${s}
201
+ `);for(let s of o)wb(e,t,n,s,i=>e.print(` ${i}
202
+ `))},DD=404,LD=e=>e instanceof V&&e.status===DD,wb=(e,t,n,r,o=e.warn)=>{try{Uc(t,n,r)&&o(`removed the copy of ${r} an earlier pull wrote.`)}catch(s){e.warn(`could not remove the copy of ${r} an earlier pull wrote: ${Ge(s)}`)}},hb=(e,t,n,r,o,s,i,a,d,l)=>{let c=e.print,m=o?`commit ${o}`:t.version?`version ${t.version}`:"HEAD",p=`${r.stack} ${r.version}`;c(`${l?"Dry run: ":""}Pulling ${t.model} (stack ${p}, template ${n}) at ${m} into ${t.instance.host}.
203
+ `),c(` Write: ${s.writes.length} file(s)${s.overwrites.length?` (${s.overwrites.length} overwritten)`:""}
204
204
  `),c(` Diagrams: ${d}
205
- `);let g=l?o.orphanCandidates:i?.deletes??[];c(` Remove: ${g.length} file(s) [${o.mode}]
206
- `);for(let u of g)c(` - ${u}
207
- `);if(l)o.adoptionNeeded&&c(` note: removing these needs --adopt (the root is not CLI-managed yet).
208
- `),o.outsized&&c(` note: this removal is larger than the write set and needs --yes.
205
+ `);let h=l?s.orphanCandidates:i?.deletes??[];c(` Remove: ${h.length} file(s) [${s.mode}]
206
+ `);for(let u of h)c(` - ${u}
207
+ `);if(l)s.adoptionNeeded&&c(` note: removing these needs --adopt (the root is not CLI-managed yet).
208
+ `),s.outsized&&c(` note: this removal is larger than the write set and needs --yes.
209
209
  `);else for(let u of i?.warnings??[])e.warn(u);for(let u of a)c(` moved: ${u.oldPath} -> ${u.newPath}
210
- `);if(l)for(let u of o.writes)c(` write ${u}
211
- `)},rT=(e,t,n,r)=>{let s=e.print;for(let{file:o,elementId:i,slot:a,title:d}of n)s(` adopt ${o}: ${d??i} ${a}
212
- `);for(let{title:o,slot:i,target:a}of t.substitutions){let d=typeof a=="string"?a:`${a.file} under the heading "${a.heading}"`;s(` fill ${o} ${i}: ${d}
213
- `)}s(` slots removed: ${t.removedSlots}
214
- `);for(let{elementId:o,from:i,to:a}of r)s(` rename ${o} in notes.json: ${i===void 0?"(no name)":`"${i}"`} -> "${a}"
215
- `)};var sT=["STACK","TEMPLATE","NAME"],Ty=O({path:["bundle","templates"],effect:"read",summary:"List a model's document templates",description:"Lists the stack/template pairs a model can be pulled as, one per document shape. A template slug is unique only within its stack, so bundle pull takes both.",flags:{model:{type:"string",placeholder:"id",description:"The model's UUID (default: MODELDESK_MODEL or the repo config)."},stack:{type:"string",placeholder:"id",description:"List only the templates of this content stack."}},listing:{narrowHint:"Pass --stack to list one content stack."},examples:["modeldesk bundle templates --model <model>","modeldesk bundle templates --stack respec --json"],run:async e=>{let t=Mo(e,{model:e.flags.model}),n=e.api(),r=await n.models.get(t.model),s=(r.metamodelExtensions??[]).map(m=>m.id),{items:o}=await n.metamodels.templates(r.metamodel.id,{metamodelExtensions:s}),i=e.flags.stack,a=o??[],d=a.filter(m=>!i||m.stack===i).map(m=>({stack:m.stack??"",template:m.key??m.id,name:m.name,id:m.id})),l=await e.list(d);return{result:{model:t.model,...i?{stack:i}:{},modelTemplateCount:a.length,...l}}},render:({items:e,stack:t,modelTemplateCount:n})=>{if(n===0)return"This model has no document templates.";if(e.length===0)return`No document templates for stack '${t}'.`;let r=e.map(s=>[s.stack,s.template,s.name]);return j([sT,...r]).join(`
216
- `)}});var Oy="type-not-found",tc=({min:e,max:t})=>`${e??0}..${t===void 0||t<0?"*":t}`,oT=e=>{if(e===void 0)return"";switch(e.type){case"string":{let t=[e.format,e.lang?"language-tagged":void 0,e.enum?`one of ${e.enum.join(", ")}`:void 0].filter(n=>n!==void 0);return t.length===0?"string":`string (${t.join("; ")})`}case"integer":case"number":{let t=e.minimum!==void 0||e.maximum!==void 0?` ${e.minimum??""}..${e.maximum??""}`:"";return`${e.type}${t}`}default:return e.type}},Ny=e=>["abstract","package","trait","internal"].filter(t=>e[t]).join(", "),iT=e=>e.parentBound?"the owner's type ($parent)":e.unrestricted?"any type":(e.allowedTargetTypes??[]).map(t=>t.foreign?`${t.name} (foreign)`:t.name).join(", "),An=(e,t)=>[`${e}:`,...t.length===0?[" none"]:t],aT=(e,t)=>{let n=new Set((e.types??[]).filter(a=>a.internal).map(a=>a.name)),r=a=>t||!(n.has(a)||kn(a)),s=(e.root??[]).filter(a=>r(a.type)),o=(e.types??[]).filter(a=>r(a.name)),i=(e.types??[]).length-o.length;return[...An("Root",j(s.map(a=>[a.type,w(a.label),tc(a.multiplicity),a.instantiableTypes&&a.instantiableTypes.join()!==a.type?`creates ${a.instantiableTypes.join(", ")}`:""]),{indent:" "})),...An("Types",o.length===0?[]:j([["NAME","LABEL","KIND","SPECIALIZES"],...o.map(a=>[a.name,w(a.label),Ny(a),(a.specializes??[]).join(", ")])],{indent:" "})),...i>0?[`(${i} internal types not shown; pass --internal to list them.)`]:[]]},dT=e=>{let t=[["kind:",Ny(e)],["definition:",w(e.definition??"")],["supertypes:",(e.supertypes??[]).join(", ")],["traits:",(e.traits??[]).join(", ")],["instantiable as:",(e.instantiableTypes??[]).join(", ")],["keyed by:",(e.keyProperties??[]).join(", ")]],n=i=>[i.derived?"derived":"",i.abstract?"abstract":""].filter(a=>a!=="").join(", "),r=(e.attributes??[]).map(i=>[i.name,w(i.label),oT(i.schema),tc(i.multiplicity),i.definedBy?`from ${i.definedBy}`:"",n(i)]),s=(e.relations??[]).map(i=>[i.name,w(i.label),tc(i.multiplicity),i.ownership,iT(i),i.definedBy?`from ${i.definedBy}`:"",n(i)]),o=(e.kindGroups??[]).flatMap(i=>[` ${i.classifier}: ${i.kinds.join(", ")}`,...i.shared?.length?[` shared: ${i.shared.join(", ")}`]:[],...(i.distinguishing??[]).map(a=>` ${a.binding}: ${a.kinds.join(", ")}`)]);return[`${e.name} (${w(e.label)})`,...j(t.filter(([,i])=>i!==""),{indent:" "}),...An("Attributes",r.length===0?[]:j([["NAME","LABEL","SCHEMA","MULT","DEFINED",""],...r],{indent:" "})),...An("Relations",s.length===0?[]:j([["NAME","LABEL","MULT","OWNERSHIP","TARGETS","DEFINED",""],...s],{indent:" "})),...An("Home slots (where it can live)",(e.homeSlots??[]).map(i=>` ${i.ownerType}.${i.relation}`)),...An("Child slots (what can be created inside it)",(e.childSlots??[]).map(i=>` ${i.relation}: ${i.targetTypes.join(", ")}`)),...o.length===0?[]:An("Kind groups",o)]},lT=(e,t)=>{let{metamodel:n}=e;return[`Metamodel ${w(n.name)}`+(n.version?` ${n.version}`:"")+(n.prefix?` (prefix ${n.prefix})`:""),...e.type?dT(e.type):aT(e,t)].join(`
217
- `)},cT=(e,t)=>{let n=e.problem?.candidates,r=Array.isArray(n)?n.filter(s=>typeof s=="string"):[];return new p(e.problem?.detail??`The metamodel declares no type '${e.problem?.typeName}'.`,{exitCode:r.length>0?b.Usage:b.NotFound,type:Oy,requestId:e.requestId,details:e.details,hint:r.length>0?"Pass one of the candidates.":`Run 'modeldesk describe ${t}' to list the types of its metamodel.`})},Ly=O({path:["describe"],effect:"read",summary:"Describe the schema a model is written against",description:"Without a type: the types the model root admits and every classifier of its metamodel, with its label, kind and supertypes. With a type (canonical, such as sh:NodeShape, or any spelling naming one classifier): its supertypes and traits, its attributes with value schema and multiplicity, its relations with multiplicity, ownership and resolved allowed targets, where an element of it can live, what can be created inside one, and the kind groups of a discriminated branch. Always the committed metamodel of main, never your draft or a branch: a metamodel pin cannot be staged. --json prints the server document as schema.",positionals:[_(fe),{name:"type",type:"string",description:"The classifier to describe in full."}],flags:{internal:{type:"boolean",description:"List the internal types (`@` types and auxiliary ones) in the overview too; --json always carries them."}},examples:["modeldesk describe <model>","modeldesk describe <model> sh:NodeShape --json"],run:async e=>{let{model:t,type:n}=e.args,r=await Z(e,t,fe),s=de(r);s.note!==void 0&&e.warn(s.note);try{let o=await e.api().models.schema(r.id,n);return e.print(`${lT(o,e.flags.internal)}
218
- `),{result:{model:{id:r.id,name:r.name},ref:s,schema:o}}}catch(o){throw o instanceof H&&o.type===Oy?cT(o,t.text):o}}});var Py=O({path:["draft","discard"],effect:"unstage",summary:"Discard your draft and everything staged on it",description:"Discards your draft with every change staged on it, whichever surface staged them. It restates what it will discard and asks at a terminal; anywhere else it needs --yes. It sends the draft head it read, so a change staged after that is not destroyed unseen (exit 5). Holding no draft is reported, not refused. --dry-run restates what it would discard and discards nothing. Under an agent host a draft holding changes made outside an agent session (in the app) is left to a person (exit 6) unless --any-surface.",positionals:[_e],flags:tr,dryRun:!0,examples:["modeldesk draft discard <model> --dry-run","modeldesk draft discard <model> --yes"],run:async e=>ee(async()=>{let t=await je(e),n=ue(t.ref),r=await t.read(),{dryRun:s}=e.globals,o={resource:t.ref,discarded:!1,dryRun:s,draft:null};if(r===void 0)return{result:o};if(s)return{result:{resource:t.ref,discarded:!1,dryRun:s,draft:r}};let i=P(r.changeCount,"staged change");await De(e,t,r,{scope:{kind:"all"},action:`Discarding your draft of ${n}`,anySurface:e.flags["any-surface"],override:"pass --any-surface only when they asked for it."}),await it(e,`Discard your draft of ${n} with its ${i}?`,`Discarding your draft of ${n} (${i})`);try{await t.discard(r.headCommitId)}catch(a){if(a instanceof H&&a.status===404)return{result:o};throw a instanceof p&&a.type==="draft-moved"?new p(`Your draft of ${n} moved after this command read it, so nothing was discarded.`,{exitCode:b.Conflict,type:a.type,details:a.details,hint:"Run 'modeldesk draft status' to see what it now holds, then discard again if you still mean to."}):a}return{result:{resource:t.ref,discarded:!0,dryRun:s,draft:r}}}),render:e=>{let t=ue(e.resource);if(e.draft===null)return`You hold no draft of ${t}; nothing was discarded.`;let n=`${t} (${P(e.draft.changeCount,"staged change")})`;return e.dryRun?`Would discard your draft of ${n}. Dry run: nothing was discarded.`:`Discarded your draft of ${n}.`}});var mT=e=>{let t=[e.code,e.actionIndex===void 0?void 0:`action ${e.actionIndex}`,e.elementId===void 0?void 0:`element ${e.elementId}`,e.property===void 0?void 0:`property ${e.property}`].filter(n=>n!==void 0);return`${w(e.message)} (${t.join(", ")})`},Dy=e=>e?` (${e})`:"",fT=e=>e.flatMap(t=>[`Change ${t.sourceCommitId}${Dy(t.requestId)}: ${w(t.description)}`,...t.actionTypes?.length?[` actions: ${t.actionTypes.join(", ")}`]:[],...(t.errors??[]).map(n=>` - ${mT(n)}`),...t.rowIds?.length?[` rows: ${t.rowIds.join(", ")}`]:[]]).map(t=>`${t}
219
- `).join(""),uT=(e,t,n)=>{if(!(t instanceof p))return t;if(t.type==="rebase-conflict"){let r=Array.isArray(t.details.conflicts)?t.details.conflicts:[];return e.print(fT(r)),new p(`The branch head refuses ${P(r.length,"staged change")} of your draft of ${n}, so nothing was rebased.`,{exitCode:b.Conflict,type:t.type,requestId:t.requestId,details:e.globals.json?t.details:{},hint:"Correct those changes, or leave them out with --drop <change id> (a change id is its sourceCommitId)."})}return t.type==="draft-head-conflict"||t.type==="branch-head-conflict"?new p(`Your draft of ${n} moved while it was being rebased, so nothing was rebased.`,{exitCode:b.Conflict,type:t.type,requestId:t.requestId,details:t.details,hint:"Run 'modeldesk draft status', then rebase again."}):t},pT=e=>[`Rebased your draft of ${ue(e.resource)} onto ${e.draft.baselineCommitId}; it holds ${P(e.draft.changeCount,"change")}.`,...e.dropped.length>0?["Dropped:",...e.dropped.map(t=>` ${t.commitId}${Dy(t.requestId)} ${w(t.message??"")}`.trimEnd())]:[],...e.closureChanged?["The branch changed the model's dependencies meanwhile."]:[],...e.schemaChanged?["The branch changed the model's metamodel pin meanwhile; re-read its schema."]:[]].join(`
220
- `),_y=O({path:["draft","rebase"],effect:"stage",escalate:{flag:"drop",to:"unstage"},summary:"Move your draft onto the branch head",description:"Replays every staged change onto the current branch head and moves your draft there, as a commit needs once the branch has moved past its baseline. Nothing is left out unless --drop names it. A change the branch head refuses swaps nothing: the command prints each refused change (its id, request id, action types and errors) and exits 5; correct the change, or rebase again with --drop <id>. On success it reports the dropped changes and whether the branch changed the model's dependencies or metamodel pin meanwhile.",positionals:[_e],flags:{drop:{type:{list:"string"},placeholder:"change-id",description:"A staged change to leave out, by the id a conflict report gives it."}},examples:["modeldesk draft rebase <model>","modeldesk draft rebase <model> --drop <change-id> --json"],run:async e=>ee(async()=>{let t=await je(e),n=ue(t.ref),r=await t.read();if(r===void 0)throw new p(`You hold no draft of ${n}, so there is nothing to rebase.`);let{drop:s}=e.flags;s.length>0&&await De(e,t,r,{scope:{kind:"ids",ids:s},action:`Dropping ${P(s.length,"staged change")} from your draft of ${n}`,anySurface:!1,override:"ask them to run 'modeldesk draft rebase --drop' from a plain shell."});try{let o=await t.rebase({draftHeadId:r.headCommitId,...s.length>0?{drop:s}:{}});return{result:{resource:t.ref,...o}}}catch(o){throw uT(e,o,n)}}),render:pT});var jy=e=>"name"in e?w(e.name):e.id,hT=e=>{let{draft:t,reads:n}=e,r=()=>{let o=n.head===void 0?"the branch head":`the head of ${jy(n.head)}`;return`Unaddressed reads see ${n.default==="draft"?"your draft":o}.`};if(t===null)return[`You hold no draft of ${ue(e.resource)}.`,r(),...e.url?[`url: ${e.url}`]:[]].join(`
221
- `);let s=e.behind?`${t.baselineCommitId} (behind the branch head ${e.branchHeadCommitId}: rebase before committing)`:t.baselineCommitId;return[`Your draft of ${ue(e.resource)}, aimed at ${jy(t.target)}:`,...j([["draft:",t.id],["changes:",`${t.changeCount} of at most ${e.maxChanges}`],["baseline:",s],["head:",t.headCommitId],["created:",t.createdAt],["updated:",t.updatedAt],...e.url?[["url:",e.url]]:[]],{indent:" "}),r()].join(`
222
- `)},gT=e=>e.name===void 0?{id:e.id}:{id:e.id,name:e.name},Fy=O({path:["draft","status"],effect:"read",summary:"Show your draft of a model or dataset",description:`Shows your own draft: the branch it aims at, the head it is based on, its head, how many changes it holds against the ${Ke}-change cap, and whether that branch has moved past its baseline (a commit then needs a rebase first). reads says what an invocation that names no ref reads right now: your draft while it holds changes, else the head of the branch it aims at, main when you hold none. Holding no draft is reported, not refused. Drafts are private: you see only your own.`,positionals:[_e],examples:["modeldesk draft status <model>","modeldesk draft status dataset/<dataset-id> --json"],run:async e=>ee(async()=>{let t=await je(e),n=await t.read(),r=await t.workingBranch(n),s=r.branch===void 0?void 0:gT(r.branch),o=n!==void 0&&n.headCommitId!==n.baselineCommitId;return{result:{resource:t.ref,draft:n===void 0||s===void 0?null:{...n,target:s},maxChanges:Ke,branchHeadCommitId:r.head,...n?{behind:n.baselineCommitId!==r.head}:{},reads:{default:o?"draft":"head",...s===void 0?{}:{head:s}},...t.url?{url:t.url}:{}}}}),render:hT});var qy=O({path:["draft","undo"],effect:"unstage",summary:"Undo the last change staged in your draft",description:"Takes the last staged change back out of your draft, whichever surface staged it, guarded by the head this command read: a change staged in between is not undone in its place. Undo never goes below the branch commit the draft started from, and there is no redo: stage the change again instead. A draft with nothing staged, or no draft, exits 1. Under an agent host a last change made outside an agent session (in the app) is left to a person (exit 6) unless --any-surface.",positionals:[_e],flags:tr,examples:["modeldesk draft undo <model>"],run:async e=>ee(async()=>{let t=await je(e),n=await t.read();if(n===void 0)throw new p(`You hold no draft of ${ue(t.ref)}, so there is nothing to undo.`);await De(e,t,n,{scope:{kind:"last"},action:`Undoing the last change of your draft of ${ue(t.ref)}`,anySurface:e.flags["any-surface"],override:"pass --any-surface only when they asked for it."});try{let r=await t.undo(n.headCommitId);return{result:{resource:t.ref,undone:n.headCommitId,draft:{id:n.id,headCommitId:r.headCommitId,changeCount:r.changeCount??n.changeCount-1}}}}catch(r){throw r instanceof p&&r.type==="nothing-to-undo"?new p(`Your draft of ${ue(t.ref)} holds no staged change to undo.`,{type:r.type,details:r.details}):r instanceof p&&r.type==="draft-head-conflict"?new p(`Your draft of ${ue(t.ref)} moved after this command read it, so nothing was undone.`,{exitCode:b.Conflict,type:r.type,details:r.details,hint:"Run 'modeldesk draft status' and undo again if you still mean to."}):r}}),render:e=>`Undid the last staged change (${e.undone}) of your draft of ${ue(e.resource)}; ${P(e.draft.changeCount,"change")} remain${e.draft.changeCount===1?"s":""}.`});var yT={minimum:-2147483648,maximum:2147483647},wT={minimum:Number.MIN_SAFE_INTEGER,maximum:Number.MAX_SAFE_INTEGER},By=34028234663852886e22,bT={minimum:-By,maximum:By},Wy=new Set(["true","false"]),kT=/^-?\d+$/,ET=/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/,CT=/^-?\d+(\.\d+)?$/,RT=/^(\d{4})-(\d{2})-(\d{2})$/,ST=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/,vT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,IT=/^(?:[a-z][a-z0-9+.-]*:\/\/|urn:)[^\s<>"{}|\\^`]+$/i,kr=e=>({value:e}),Ht=(e,t,n={})=>({problem:{code:e,expected:t,...n}}),Hy=({minimum:e,maximum:t})=>e===void 0||t===void 0?{...e!==void 0&&{minimum:e},...t!==void 0&&{maximum:t}}:e===0&&t===0?{}:t<e?{minimum:e}:{minimum:e,maximum:t},$T=(e,{minimum:t,maximum:n})=>t!==void 0&&n!==void 0?`${e} from ${t} to ${n}`:t!==void 0?`${e} of at least ${t}`:`${e} of at most ${n}`,Gy=(e,t,...n)=>{for(let r of n)if(r.minimum!==void 0&&e<r.minimum||r.maximum!==void 0&&e>r.maximum)return Ht("out-of-range",$T(t,r),r);return kr(e)},xT=(e,t)=>kT.test(e)?Gy(Number(e),"a whole number",t.format==="INT64"?wT:yT,Hy(t)):Ht("invalid-value","a whole number"),MT=(e,t)=>{let n=Number(e);return!ET.test(e)||!Number.isFinite(n)?Ht("invalid-value","a number, such as 2.5 or 1e-3"):Gy(n,"a number",t.format==="FLOAT"?bT:{},Hy(t))},AT=e=>e%4===0&&(e%100!==0||e%400===0),TT=[31,28,31,30,31,30,31,31,30,31,30,31],Vy=(e,t,n)=>t>=1&&t<=12&&n>=1&&n<=(t===2&&AT(e)?29:TT[t-1]),OT=e=>{let t=RT.exec(e);return t!==null&&Vy(Number(t[1]),Number(t[2]),Number(t[3]))},NT=e=>{let t=ST.exec(e);if(t===null)return!1;let[n,r,s,o,i,a]=t.slice(1,7).map(Number),d=t[7]===void 0?0:Number(t[7]),l=t[8]===void 0?0:Number(t[8]);return Vy(n,r,s)&&o<=23&&i<=59&&a<=59&&d<=23&&l<=59},LT=e=>{if(!IT.test(e))return Ht("invalid-value","an absolute IRI, such as https://example.org/def#Term or urn:example:term");let t=Math.max(e.lastIndexOf("#"),e.lastIndexOf("/"),e.lastIndexOf(":"))+1,n=e.slice(0,t),r=e.slice(t);return kr(r===""?{namespace:n}:{namespace:n,localName:r})},Uy={expected:"a date-time written YYYY-MM-DDThh:mm:ss with a Z or \xB1hh:mm offset (RFC 3339)",test:NT},PT=new Map([["date",{expected:"a date written YYYY-MM-DD",test:OT}],["date-time",Uy],["datetime",Uy],["uuid",{expected:"a UUID",test:e=>vT.test(e)}]]),DT=(e,t)=>{if(t.format==="iri")return LT(e);if(t.enum&&t.enum.length>0&&!t.enum.includes(e))return Ht("not-in-enum",`one of ${t.enum.join(", ")}`,{validValues:[...t.enum]});let n=t.format===void 0?void 0:PT.get(t.format);return n&&!n.test(e)?Ht("invalid-value",n.expected):kr(e)},_T=e=>kr(e==="true"||e==="false"?e==="true":CT.test(e)&&String(Number(e))===e?Number(e):e),Ky=(e,t)=>{switch(t?.type){case void 0:case"any":return _T(e);case"boolean":return Wy.has(e)?kr(e==="true"):Ht("invalid-value","true or false",{validValues:[...Wy]});case"integer":return xT(e,t);case"number":return MT(e,t);case"string":return DT(e,t);case"object":return Ht("structured-value","a structured value, given as JSON with --json-value")}};var hi=class extends p{errors;constructor(t){let n=t.length>1?` (and ${t.length-1} more)`:"";super(`${t[0].message}${n}`,{exitCode:b.Validation,details:{errors:t}}),this.name="CoercionRefusedError",this.errors=t}},jT=/^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$/,Yy=-1,FT=e=>e.slice(e.lastIndexOf(":")+1),qT=(e,t)=>{let n=new Map,r=new Set;for(let s of[e,...t]){for(let o of s.attributes??[])!n.has(o.name)&&!r.has(o.name)&&n.set(o.name,o);for(let o of s.relations??[])n.has(o.name)||r.add(o.name)}return{typeName:e.name,attributes:n,relations:r}},BT=e=>[...e.attributes.values()].filter(t=>!t.derived).map(t=>t.name),zy=(e,t,n)=>e.flatMap(r=>{let s=r.indexOf("=");if(s<=0){let o=t==="json"?"<attribute>=<json>":"<attribute>=<value>";return n(s<0?r:"","malformed-assignment",`'${r}' is not an assignment; write ${o}.`,{value:r}),[]}return[{attribute:r.slice(0,s),text:r.slice(s+1),form:t}]}),WT=(e,t,n)=>{let{typeName:r,attributes:s,relations:o}=e,i=t.toLowerCase(),a=[...s.keys(),...o],d=a.includes(t)?[t]:a.filter(m=>m.toLowerCase()===i||FT(m).toLowerCase()===i);if(d.length===0){let m=BT(e);n(t,"unknown-attribute",m.length>0?`${r} has no attribute '${t}'. Its attributes: ${m.join(", ")}.`:`${r} has no attribute '${t}', nor any attribute to set.`,{validValues:m});return}if(d.length>1){n(t,"ambiguous-attribute",`'${t}' names ${d.length} properties of ${r} (${d.join(", ")}); pass the full name.`,{validValues:d});return}let[l]=d,c=s.get(l);if(c===void 0){n(t,"relation-not-attribute",`'${l}' is a relation of ${r}, not an attribute; relate its targets with 'el relate'.`,{property:l});return}if(c.derived){n(t,"derived-attribute",`'${l}' is derived: ${r} computes it on read, so it is never written.`,{property:l});return}return c},Jy=e=>typeof e=="object"&&e!==null&&"lang"in e&&typeof e.lang=="string"?e.lang:null,Xy=(e,t)=>(e??"").toLowerCase()===(t??"").toLowerCase(),UT=e=>e.map(Jy).filter((t,n,r)=>r.findIndex(s=>Xy(s,t))===n),HT=(e,t,n,r,s)=>{let o=e.attribute.name;if(r.lang!==void 0){if(jT.test(r.lang))return{lang:r.lang};s(e.given,"invalid-language",`--lang '${r.lang}' is not a language tag, such as nl or en-GB.`,{property:o,value:r.lang});return}let i=UT(n);if(i.length===1&&(i[0]!==null||t.optional))return{lang:i[0]};if(i.length===0&&t.optional)return{lang:null};let a=i.filter(l=>l!==null),d=i.length>1?`holds values in ${i.map(l=>l??"no language").join(", ")}`:"takes language-tagged strings";s(e.given,"language-required",`'${o}' ${d}; pass --lang to say which language to write.`,{property:o,...a.length>0&&{validValues:a}})},GT=(e,t,n,r)=>{let s=e.attribute.name,o=n.current?.[s]??[],i=HT(e,t,o,n,r);if(i===void 0)return e.assignments.map(({text:d})=>d);let a=e.assignments.map(({text:d})=>({lang:i.lang,value:d}));return t.uniqueLang&&i.lang!==null&&a.length>1&&r(e.given,"duplicate-language",`'${s}' takes one value per language, and ${a.length} are given in '${i.lang}'.`,{property:s}),[...o.filter(d=>!Xy(Jy(d),i.lang)),...a]},VT=(e,t)=>e.assignments.flatMap(({attribute:n,text:r})=>{try{return[JSON.parse(r)]}catch{return t(n,"invalid-json",`The --json-value of '${n}' is not valid JSON: '${r}'.`,{property:e.attribute.name,value:r}),[]}}),KT=(e,t,n)=>{let{attribute:r,assignments:s}=e,o=r.name,i=r.schema;if(s.some(({form:d})=>d==="json"))return VT(e,n);for(let{attribute:d}of s.filter(({text:l})=>l===""))n(d,"empty-value",`'${o}' is given an empty value; unset the attribute to remove its values.`,{property:o,value:""});let a=s.filter(({text:d})=>d!=="");return i?.type==="string"&&i.lang?GT({...e,assignments:a},i.lang,t,n):a.map(({attribute:d,text:l})=>{let c=Ky(l,i);if("problem"in c){let{code:m,expected:f,...g}=c.problem;n(d,m,`'${o}' takes ${f}, not '${l}'.`,{property:o,value:l,...g})}return"value"in c?c.value:l})},Tn=(e,t,n={})=>{let r=[],s=(c,m,f,g={})=>{r.push({attribute:c,code:m,message:f,...g})},o=qT(t,n.traits??[]),i=[...zy(e.values??[],"value",s),...zy(e.json??[],"json",s)],a=new Map,d=new Map;for(let c of i){a.has(c.attribute)||a.set(c.attribute,WT(o,c.attribute,s));let m=a.get(c.attribute);if(m!==void 0){let f=d.get(m.name)??{attribute:m,given:c.attribute,assignments:[]};f.assignments.push(c),d.set(m.name,f)}}let l={};for(let[c,m]of d){if(new Set(m.assignments.map(({form:u})=>u)).size>1){s(m.given,"mixed-forms",`'${c}' is given both as ${c}=<value> and with --json-value; give all of its values one way.`,{property:c});continue}let f=KT(m,n,s),g=m.attribute.multiplicity.max??Yy;g!==Yy&&f.length>g&&s(m.given,"too-many-values",`'${c}' takes at most ${P(g,"value")}, and this assignment leaves it with ${f.length}.`,{property:c,maximum:g}),l[c]=f}if(r.length>0)throw new hi(r);return l};var YT=e=>e instanceof p&&e.type==="draft-head-conflict"&&e.details.ancestor===!0,zT=(e,t)=>e.length===t.length&&e.every(n=>t.includes(n)),JT=e=>{switch(e.type){case"ELEMENT_UPDATE":case"ELEMENT_DELETE":return{all:[e.elementId]};case"ELEMENT_MOVE":return{all:e.move.elements.map(t=>t.id)};case"RELATION_MEMBERSHIP_UPDATE":return{among:[...e.update.addSourceElementIds??[],...e.update.removeSourceElementIds??[]]};case"ELEMENT_BULK_UPDATE":return{among:[...e.update.elementIds??[],...(e.update.updates??[]).map(t=>t.elementId)]};default:return{}}},Qy=e=>[...new Set(e.actions.map(t=>t.type))].sort(),XT=(e,t)=>{let n=Qy(t);if(!zT(e.actionTypes,n))return`it recorded ${e.actionTypes.join(", ")||"no action"}, and this one stages ${n.join(", ")}`;let{elementIds:r}=e;return r===void 0?void 0:t.actions.some(o=>{let i=r[o.type]??[],{all:a,among:d}=JT(o);return a?.some(l=>!i.includes(l))||d!==void 0&&i.some(l=>!d.includes(l))})?"it changed other elements than this one names":void 0},Zy=(e,t,n)=>{let r=XT(e,t);if(r!==void 0)throw new p(`Request id ${t.changeRequestId} was already used for a different change of your draft of ${n} (${e.id}): ${r}. Nothing was staged.`,{hint:"Leave --request-id out to stage this change under an id of its own.",details:{changeRequestId:t.changeRequestId,stagedCommitId:e.id,recordedActionTypes:e.actionTypes,actionTypes:Qy(t)}})},ew="Run 'modeldesk draft status', then stage the change again.",QT=(e,t,n,r)=>new p(e.details.ancestor===!0?`Your draft of ${t} moved again while ${n} was being sent a second time, so it was not staged.`:`Your draft of ${t} was undone, rebased or committed while ${n} was being staged, so it was not staged.`,{...r,exitCode:b.Conflict,hint:ew}),ZT=(e,t,n,r)=>{let s=e.details.targetRefName??e.details.targetRefId,o=typeof s=="string"?` (${s})`:"";return new p(`Your draft of ${t} aims at another branch${o} since it was read, so ${n} was not staged.`,{...r,exitCode:b.Conflict,hint:ew})},eO=e=>{let t=e.length;for(;t>0&&(e[t-1]==="."||e[t-1].trim()==="");)t--;return e.slice(0,t)},tO=(e,t,n,r,s)=>{let o=Array.isArray(e.details.errors)?e.details.errors:[];if(o.some(l=>l.code==="chain-too-long"))return new p(`Your draft of ${t} holds the most changes a draft can (${Ke}), so ${n} was not staged.`,{...r,exitCode:b.Validation,hint:"Commit the draft first ('modeldesk draft commit', or in the app); splitting the change does not help."});let[i]=o,a=s.chunks>1?`Change ${s.chunk} of ${s.chunks}`:"The change",d=o.length>1?` (and ${o.length-1} more)`:"";return new p(i?`${a} was refused: ${eO(i.message)}${d}.`:e.reason,{...r,exitCode:b.Validation})},tw=(e,t,n,r,s)=>{if(!(e instanceof p))return e;let o=r.chunks>1?`change ${r.chunk} of ${r.chunks}`:"this change",i={type:e.type,requestId:e.requestId,details:{...e.details,...r}};return e.exitCode===b.Transient?new p(`${e.reason} Whether ${o} was staged is unknown.`,{...i,exitCode:b.Transient,details:{...i.details,changeRequestId:n.changeRequestId},hint:s}):e.type==="draft-head-conflict"?QT(e,t,o,i):e.type===al?ZT(e,t,o,i):e.type==="change-validation-failed"?tO(e,t,o,i,r):new p(e.reason,{...i,exitCode:e.exitCode,hint:e.hint})},gi=async(e,t,n)=>{let r={context:e,api:e.api(),address:t.address,plan:n,name:w(t.model.name),current:t,chunks:[...n.chunks],head:t.head,draftId:t.draft?.id,replanned:!1,chain:void 0,staged:[]};for(let s=0;s<r.chunks.length;){let o=r.chunks[s];if(o.actions.length===0){s++;continue}let i=n.stableIds?await sO(r,o):void 0;if(i!==void 0){await nc(r,i,s),s++;continue}let a=await oO(r,s);if("resumeAt"in a){s=a.resumeAt;continue}r.head=a.sent.commitId,r.draftId=a.sent.draftId,r.chain=void 0,await nc(r,a.sent,s),s++}return{target:r.current,chunks:r.staged,head:r.head,draftId:r.draftId}},nO=e=>e.staged.map(t=>({number:e.chunks.indexOf(t.chunk)+1,changeRequestId:t.chunk.changeRequestId,commitId:t.commitId})),nw=(e,t)=>({chunk:t+1,chunks:e.chunks.length,landed:nO(e),baseCommitId:e.head}),rO=(e,t)=>t===void 0?Promise.resolve([]):(e.chain??=Rn(e.api,e.current.model.id,t),e.chain),nc=async(e,t,n)=>{e.staged.push(t),await e.plan.persisted?.(t,n)},sO=async(e,t)=>{let n=(await rO(e,e.draftId)).find(r=>r.requestId===t.changeRequestId);if(n!==void 0)return Zy(n,t,e.name),{chunk:t,commitId:n.id,draftId:e.draftId,alreadyStaged:!0,staged:!0}},oO=async(e,t)=>{let n=e.chunks[t];try{let r=await e.api.drafts.model.stage(e.current.model.id,{actions:[...n.actions],draftHeadId:e.head,changeRequestId:n.changeRequestId,message:n.message,...e.draftId===void 0?{branchId:e.current.branch.id}:{}});return{sent:{chunk:n,commitId:r.envelope.commitId,draftId:r.draftId??e.draftId,envelope:r.envelope,alreadyStaged:!1,staged:r.envelope.commitId!==e.head}}}catch(r){if(!(r instanceof p))throw r;return r.exitCode===b.Transient?{sent:await iO(e,r,t)}:{resumeAt:await aO(e,r,t)}}},iO=async(e,t,n)=>{let r=e.chunks[n],s=await dO(e.context,e.current.model.id,r.changeRequestId);if(s===void 0)throw tw(t,e.name,r,nw(e,n),e.plan.retryHint);return{chunk:r,commitId:s.commitId,draftId:s.draftId,alreadyStaged:!1,staged:!0}},aO=async(e,t,n)=>{let r=e.chunks[n];if(e.replanned||!YT(t)||e.plan.replan===void 0)throw tw(t,e.name,r,nw(e,n),e.plan.retryHint);let s=Array.isArray(t.details.commits)?t.details.commits:[];e.current=await ot(e.context,e.address),e.head=e.current.head,e.draftId=e.current.draft?.id,e.chain=void 0,e.replanned=!0;let o=n,i=s.find(a=>a.requestId===r.changeRequestId);return i!==void 0&&(Zy(i,r,e.name),await nc(e,{chunk:r,commitId:i.id,draftId:e.draftId,alreadyStaged:!0,staged:!0},n),o++),e.chunks=[...e.chunks.slice(0,o),...await e.plan.replan(e.current,e.chunks.slice(o))],o},dO=async(e,t,n)=>{let r=e.api();try{let s=await Ut(()=>r.models.draft(t));if(s===void 0)return;let i=(await Rn(r,t,s.id,lO)).find(a=>a.requestId===n);return i&&{commitId:i.id,draftId:s.id}}catch{return}},lO=10,ys=e=>e.chunks.some(t=>t.staged);var Gt="modeldesk el bulk --help",rw=["equalTo","empty","notEmpty","contains","greaterThan","lessThan"],cO={"=":"equalTo","~":"contains",">":"greaterThan","<":"lessThan"},mO={empty:"empty","not-empty":"notEmpty"},fO=/^([^=~<>]+)([=~<>])(.*)$/s,uO=/^(.+):(empty|not-empty)$/,pO="type=<T>[,<T>\u2026], <attr>=<value>, <attr>~<text>, <attr>><n>, <attr><<n>, <attr>:empty or <attr>:not-empty",hO=e=>{let t;try{t=JSON.parse(e)}catch(s){throw $(`--where is not valid JSON (${s.message}).`,Gt)}let{type:n,conditions:r}=t??{};if(n!==void 0&&!(Array.isArray(n)&&n.every(s=>typeof s=="string")))throw $('--where: "type" is a list of type names.',Gt);if(r!==void 0&&!Array.isArray(r))throw $('--where: "conditions" is a list of {attribute, operator, value}.',Gt);for(let s of r??[])if(typeof s?.attribute!="string"||!rw.includes(s.operator))throw $(`--where: every condition names an "attribute" and an "operator" (${rw.join(", ")}).`,Gt);return{...n===void 0?{}:{type:n},...r===void 0?{}:{conditions:r}}},gO=e=>{let t=fO.exec(e);if(t){let[,r,s,o]=t;if(r==="type"&&s==="="){let i=o.split(",").map(a=>a.trim()).filter(a=>a!=="");if(i.length===0)throw $(`'${e}' names no type.`,Gt);return{type:i}}return{condition:{attribute:r,operator:cO[s],value:o}}}let n=uO.exec(e);if(n)return{condition:{attribute:n[1],operator:mO[n[2]]}};throw $(`'${e}' is not a criterion; write one of ${pO}.`,Gt)},sw=e=>{if(e.some(r=>r.trimStart().startsWith("{"))){if(e.length>1)throw $("--where as JSON holds the whole selection; give it once, without other clauses.",Gt);return hO(e[0])}let t,n=[];for(let r of e){let s=gO(r);if("type"in s){if(t!==void 0)throw $("Name every type in one type= clause (type=A,B); two would both have to hold.",Gt);t=s.type}else n.push(s.condition)}return{...t?{type:t}:{},...n.length>0?{conditions:n}:{}}},yi=e=>{if(e!==null&&typeof e=="object"){if("value"in e)return String(e.value);if("namespace"in e||"localName"in e){let{namespace:t,localName:n}=e;return`${t??""}${n??""}`}return JSON.stringify(e)}return String(e)},yO=e=>e!=null&&e!=="",wO=(e,t)=>{let n=t.value===void 0?"":yi(t.value);switch(t.operator){case"empty":return e.length===0;case"notEmpty":return e.some(yO);case"equalTo":return e.some(r=>yi(r)===n);case"contains":return e.some(r=>yi(r).toLowerCase().includes(n.toLowerCase()));case"greaterThan":case"lessThan":{let r=Number(n);return n.trim()!==""&&!Number.isNaN(r)&&e.some(s=>{let o=Number(yi(s));return!Number.isNaN(o)&&(t.operator==="greaterThan"?o>r:o<r)})}}},ow=(e,t,n)=>n.types!==void 0&&!n.types.has(e.type)?!1:(t.conditions??[]).every(r=>{let s=n.attributeOf(e,r.attribute);return s!==void 0&&wO(e.attributes?.[s]??[],r)});var bO="@trait",iw="@Root",kO="@element",Vt=async(e,t,n)=>{let{type:r}=await e.models.schema(t,n);if(r===void 0)throw new p(`The schema of this model describes no type '${n}'.`,{exitCode:b.NotFound});return r},aw=async(e,t,n,r,s)=>{if((r.values?.length??0)+(r.json?.length??0)===0)return{};let o=(n.attributes?.[bO]??[]).filter(d=>typeof d=="string"),[i,...a]=await Promise.all([n.type,...o].map(d=>Vt(e,t,d)));return Tn(r,i,{lang:s,current:n.attributes,traits:a})},ws=async(e,t,n,r,s,o,i)=>{if(o!==void 0)return o;let a=n.element(r)?.type??iw;if(a===iw){let{root:m=[]}=await e.models.schema(t);if(m.some(f=>(f.instantiableTypes??[f.type]).includes(s)))return kO;throw new p(`The model root holds no ${s}.`,{exitCode:b.Validation,hint:`Types the root holds: ${m.flatMap(f=>f.instantiableTypes??[f.type]).join(", ")||"none"}.`})}let{childSlots:d=[]}=await Vt(e,t,a),l=d.filter(m=>m.targetTypes.includes(s));if(l.length===1)return l[0].relation;if(l.length>1)throw $(`A ${a} holds a ${s} through ${l.map(m=>m.relation).join(", ")}; pass --relation to pick one.`,i);let c=d.map(m=>`${m.relation} (${m.targetTypes.join(", ")})`).join("; ");throw new p(`A ${a} holds no ${s}.`,{exitCode:b.Validation,hint:d.length===0?`A ${a} holds no children at all.`:`What it holds: ${c}.`})},EO=e=>e.slice(e.lastIndexOf(":")+1),Fe=(e,t)=>{if(e.includes(t))return t;let n=t.toLowerCase(),r=e.filter(s=>s.toLowerCase()===n||EO(s).toLowerCase()===n);if(r.length>1)throw new p(`'${t}' names ${r.length} properties (${r.join(", ")}); pass the full name.`,{exitCode:b.Usage,details:{candidates:r}});return r[0]},wi=e=>e.ownership==="OWNED"||e.ownership==="MULTI_OWNED";import{randomUUID as FO}from"node:crypto";var rc=e=>{let t=new Map;for(let[n,r]of e)for(let s of r){let o=t.get(s.id);o===void 0?t.set(s.id,[n]):o.push(n)}return t};import{randomUUID as RO}from"node:crypto";var sc=(e,t)=>e.id===t.id&&e.relation===t.relation,bi=e=>Object.values(e??{}).flat(),dw=e=>Object.keys(e).some(t=>t!=="@@"),CO=(e,t)=>`${e}\0${t}`,lw=e=>{let t={...e.elements},n=new Map(Object.entries(e.elementIndexEntries).map(([v,C])=>[v,[...C.owners??[]]])),r=new Map;for(let[v,C]of n)for(let R of C)r.set(R.id,(r.get(R.id)??new Set).add(v));let s=new Set,o=v=>{let C=t[v];if(C===void 0||s.has(v))return C;let R={...C,...C.attributes&&{attributes:{...C.attributes}},...C.relations&&{relations:Object.fromEntries(Object.entries(C.relations).map(([A,T])=>[A,Object.fromEntries(Object.entries(T).map(([N,q])=>[N,[...q]]))]))}};return t[v]=R,s.add(v),R},i=(v,C)=>{let R=v.relations?.[C];if(!(R===void 0||v.relations===void 0)){for(let A of Object.keys(R))R[A].length===0&&delete R[A];Object.keys(R).length===0&&delete v.relations[C],Object.keys(v.relations).length===0&&delete v.relations}},a,d=(v,C,R)=>{a!==void 0&&a.set(v,(a.get(v)??new Set).add(CO(C,R)))},l=v=>{if(a===void 0){a=new Map;for(let[C,R]of Object.entries(t))for(let[A,T]of Object.entries(R.relations??{}))bi(T).forEach(N=>d(N.id,C,A))}return a.get(v)??new Set},c=(v,C)=>{let R=n.get(v)??[];R.some(A=>sc(A,C))||(n.set(v,[...R,C]),r.set(C.id,(r.get(C.id)??new Set).add(v)))},m=(v,C)=>{let R=(n.get(v)??[]).filter(A=>!sc(A,C));n.set(v,R),R.some(A=>A.id===C.id)||r.get(C.id)?.delete(v)},f=(v,C,R)=>{let A=o(v);if(A===void 0)return;bi(A.relations?.[C]).filter(N=>N.owned).forEach(N=>m(N.id,{id:v,relation:C}));let T=bi(R);T.filter(N=>N.owned).forEach(N=>c(N.id,{id:v,relation:C})),T.forEach(N=>d(N.id,v,C)),A.relations??={},A.relations[C]=Object.fromEntries(Object.entries(R).map(([N,q])=>[N,[...q]])),i(A,C)},g=(v,C,R)=>{let A=o(v),T=A?.relations?.[C];if(A===void 0||T===void 0)return;let N=Object.keys(T).find(q=>T[q].some(X=>X.id===R));if(N!==void 0)return T[N].splice(T[N].findIndex(q=>q.id===R),1),i(A,C),N},u=(v,C,R,A)=>{let T=o(v.id);if(T===void 0)return;T.relations??={};let N=T.relations[v.relation]??{},q=dw(N)?R:"@@";if(q===void 0||q==="@@"&&dw(N))return;T.relations[v.relation]=N;let X=N[q]??=[];X.splice(A??X.length,0,C),d(C.id,v.id,v.relation)},h=(v,C)=>{let R=v.id;t[R]={id:R,type:v.type,...v.attributes&&{attributes:v.attributes},...v.relations&&{relations:v.relations}},s.delete(R);for(let[A,T]of Object.entries(v.relations??{}))bi(T).forEach(N=>d(N.id,R,A));c(R,C),u(C,{id:R,owned:!0},void 0);for(let[A,T]of Object.entries(v.ownedElements??{}))T.forEach(N=>h(N,{id:R,relation:A}))},y=(v,C)=>{let R=o(v);if(R!==void 0){for(let[A,T]of Object.entries(C.attributes??{}))R.attributes??={},T.length===0?delete R.attributes[A]:R.attributes[A]=T;for(let[A,T]of Object.entries(C.relations??{}))f(v,A,T)}},k=({elements:v,targetParent:C,position:R})=>{for(let{id:A,parent:T}of v){let N=sc(T,C),q=(t[T.id]?.relations?.[T.relation]?.["@@"]??[]).findIndex(Y=>Y.id===A),X=g(T.id,T.relation,A);m(A,T),c(A,C);let me=N&&R!==void 0&&q!==-1&&R>q?R-1:R;u(C,{id:A,owned:!0},X,me)}},S=v=>{let C=new Set(v),R=[...C];for(let A=R.pop();A!==void 0;A=R.pop())for(let T of r.get(A)??[])!C.has(T)&&(n.get(T)??[]).every(N=>C.has(N.id))&&(C.add(T),R.push(T));return C},I=(v,C)=>{for(let R of l(v)){let[A,T]=R.split("\0"),N=C.has(A)?void 0:o(A),q=N?.relations?.[T];if(N!==void 0&&q!==void 0){for(let X of Object.keys(q))q[X]=q[X].filter(me=>me.modelId!==void 0||me.id!==v);i(N,T)}}},x=v=>{let C=S([v]);for(let R of C){for(let A of r.get(R)??[])(n.get(A)??[]).filter(T=>T.id===R).forEach(T=>m(A,T));I(R,C),a?.delete(R),delete t[R],s.delete(R),n.delete(R),r.delete(R)}},E=({relation:v,targetElementId:C,addSourceElementIds:R=[],removeSourceElementIds:A=[]})=>{for(let T of R)u({id:T,relation:v},{id:C,owned:!1},void 0);for(let T of A)g(T,v,C)};return{element:v=>t[v],owners:v=>n.get(v)??[],cascade:S,apply:v=>{switch(v.type){case"ELEMENT_CREATE":v.creation.owner&&h(v.creation,v.creation.owner);return;case"ELEMENT_UPDATE":y(v.elementId,v.update);return;case"ELEMENT_MOVE":k(v.move);return;case"ELEMENT_DELETE":x(v.elementId);return;case"RELATION_MEMBERSHIP_UPDATE":E(v.update);return;default:return}}}};var qe=["external","extensionLayer","lineage"],ki=class extends p{errors;constructor(t){let n=t.length>1?` (and ${t.length-1} more)`:"";super(`${t[0].message}${n}`,{exitCode:b.Validation,details:{errors:t}}),this.name="EditRefusedError",this.errors=t}},Ei=class extends Error{constructor(n,r,s={}){super(r);this.code=n;this.at=s}code;at},ie=(e,t,n)=>{throw new Ei(e,t,n)},St=(e,t=!0)=>({action:e,resendable:t}),Er=e=>Object.keys(e).length===0,SO=new Set(qe),bs=(e,t)=>{for(let n of e)SO.has(n)&&ie("read-only-field",`'${n}' is read-only: the server serves it on an element, but no staged write accepts it.`,{elementId:t,property:n})},mw=e=>ie("element-not-found",`Element '${e}' is not in the model.`,{elementId:e}),oc=({starting:e,working:t},n)=>t.element(n)??(e.elements[n]===void 0?mw(n):ie("element-not-found",`Element '${n}' is removed by an earlier delete of this change.`,{elementId:n})),fw=(e,t)=>e.get(t)??ie("unknown-key",`No new element of this change has the key '${t}'.`),ic=(e,t,n)=>{if(!("key"in e))return e.id;let r=fw(n.keys,e.key);return r.editIndex>=t&&ie("key-before-definition",`The key '${e.key}' is used before the create that makes it; create it first.`),r.id},ac=e=>({id:e.id,owned:e.owned,...e.modelId!==void 0&&{modelId:e.modelId}}),vO=(e,t)=>"key"in e?{id:fw(t.keys,e.key).id,owned:e.owned}:ac(e),uw=(e,t)=>Object.fromEntries(Object.entries(e).map(([n,r])=>[n,r.map(s=>vO(s,t))])),pw=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(ac)])),hw=e=>Object.values(e).every(t=>t.length===0),gw=(e,t)=>{for(let[n,r]of Object.entries(e)){let s=r.find(o=>o.id===t);if(s)return{group:n,ref:s}}},IO=(e,t)=>e.id===t.id&&e.owned===t.owned&&e.modelId===t.modelId,$O=(e,t)=>[t.owned?"owned":"unowned",...t.modelId!==void 0?[`in model '${t.modelId}'`]:[],...e!=="@@"?[`in group '${e}'`]:[]].join(", "),xO=(e,t,n)=>{let r=new Map,s=new Map;return e.forEach((o,i)=>{if(o.kind!=="create")return;let a=d=>{let l=t();r.set(d,l),d.key!==void 0&&(s.has(d.key)&&ie("duplicate-key",`The key '${d.key}' names two new elements; give each its own.`),s.set(d.key,{id:l,editIndex:i})),Object.values(d.children??{}).flat().forEach(a)};n(i,()=>a(o.element))}),{idOf:r,keys:s}},yw=(e,t)=>{let n=t.idOf.get(e);if(n===void 0)throw new Error("Every new element of an edit that was not refused has a minted id.");let r=e.attributes??{},s=e.relations??{},o=Object.entries(e.children??{}).filter(([,i])=>i.length>0);bs([...Object.keys(e),...Object.keys(r),...Object.keys(s),...o.map(([i])=>i)],n);for(let[i,a]of Object.entries(r))a.length===0&&ie("empty-value",`The attribute '${i}' of a new element has no value; leave it out.`,{elementId:n,property:i});for(let[i,a]of Object.entries(s))hw(a)&&ie("empty-value",`The relation '${i}' of a new element has no target; leave it out.`,{elementId:n,property:i}),Object.values(a).some(d=>d.some(l=>l.owned))&&ie("owned-on-create",`A new element cannot own through a reference in '${i}': nest what it owns under its children.`,{elementId:n,property:i});return{id:n,type:e.type,...!Er(r)&&{attributes:{...r}},...!Er(s)&&{relations:Object.fromEntries(Object.entries(s).map(([i,a])=>[i,uw(a,t)]))},...o.length>0&&{ownedElements:Object.fromEntries(o.map(([i,a])=>[i,a.map(d=>yw(d,t))]))}}},MO=(e,t,n)=>St({type:"ELEMENT_CREATE",creation:{...yw(e.element,n),owner:{id:ic(e.parent,t,n),relation:e.relation}}}),AO=(e,t)=>{let n=e.attributes??{},r=e.relations??{},s=o=>({elementId:e.element,property:o});bs([...Object.keys(e),...Object.keys(n),...Object.keys(r)],e.element),Er(n)&&Er(r)&&ie("empty-edit",`The set names no attribute or relation of '${e.element}'.`,{elementId:e.element});for(let[o,i]of Object.entries(n))i.length===0&&ie("empty-value",`The attribute '${o}' is set to no value; unset it instead.`,s(o));for(let[o,i]of Object.entries(r))hw(i)&&ie("empty-value",`The relation '${o}' is set to no target; unset it instead.`,s(o));return St({type:"ELEMENT_UPDATE",elementId:e.element,update:{...!Er(n)&&{attributes:{...n}},...!Er(r)&&{relations:Object.fromEntries(Object.entries(r).map(([o,i])=>[o,uw(i,t)]))}}})},TO=e=>{let t=e.attributes??[],n=e.relations??[];return t.length===0&&n.length===0&&ie("empty-edit",`The unset names no attribute or relation of '${e.element}'.`,{elementId:e.element}),bs([...t,...n],e.element),St({type:"ELEMENT_UPDATE",elementId:e.element,update:{...t.length>0&&{attributes:Object.fromEntries(t.map(r=>[r,[]]))},...n.length>0&&{relations:Object.fromEntries(n.map(r=>[r,{}]))}}})},OO=e=>{let t=e.filter(n=>n.kind==="delete");return{named:new Set(t.map(n=>n.element)),recursive:new Set(t.filter(n=>n.recursive).map(n=>n.element))}},NO=(e,t)=>{let{working:n,deletes:r}=t;if(n.element(e.element)===void 0)return t.starting.elements[e.element]===void 0?mw(e.element):void 0;let s=n.owners(e.element),o=n.cascade(r.named);if(s.length>0&&s.every(d=>o.has(d.id)))return;let i=n.cascade(r.recursive),a=[...n.cascade([e.element])].filter(d=>!r.named.has(d)&&!i.has(d));return a.length>0&&ie("owns-elements",`Element '${e.element}' owns ${P(a.length,"element")} that deleting it removes as well; delete it recursively to remove them with it.`,{elementId:e.element}),St({type:"ELEMENT_DELETE",elementId:e.element})},cw=e=>`'${e.id}' through '${e.relation}'`,LO=(e,t)=>{let n={elementId:e.element},{from:r}=e;return r?t.find(s=>s.id===r.id&&s.relation===r.relation)??ie("not-an-owner",`Element '${e.element}' is not owned by ${cw(r)}.`,n):(t.length===0&&ie("no-owner",`Element '${e.element}' has no owner to move it out of.`,n),t.length>1&&ie("ambiguous-owner",`Element '${e.element}' has ${t.length} owners (${t.map(cw).join("; ")}); name the one it leaves.`,n),t[0])},PO=(e,t,n)=>{oc(n,e.element),e.position!==void 0&&!(Number.isInteger(e.position)&&e.position>=0)&&ie("invalid-position",`The position ${e.position} is not a whole number from 0 up.`,{elementId:e.element});let r=LO(e,n.working.owners(e.element));return St({type:"ELEMENT_MOVE",move:{elements:[{id:e.element,parent:{id:r.id,relation:r.relation}}],targetParent:{id:ic(e.parent,t,n),relation:e.relation},...e.position!==void 0&&{position:e.position}}})},DO=(e,t,n)=>{let r=oc(n,e.element),s={elementId:e.element,property:e.relation};bs([e.relation],e.element);let o="key"in e.target?{id:ic({key:e.target.key},t,n),owned:e.target.owned}:ac(e.target),i=r.relations?.[e.relation]??{},a=Object.keys(i),d=a.some(f=>f!=="@@"),l=e.group??(d?ie("group-required",`The relation '${e.relation}' of '${e.element}' is grouped (${a.join(", ")}); name the group the target belongs in.`,s):"@@");a.length>0&&d!==(l!=="@@")&&ie("group-mismatch",d?`The relation '${e.relation}' of '${e.element}' is grouped (${a.join(", ")}); name the group the target belongs in rather than '${"@@"}'.`:`The relation '${e.relation}' of '${e.element}' is ungrouped; leave the group out.`,s);let c=gw(i,o.id);if(c&&!(c.group===l&&IO(c.ref,o))&&ie("already-related",`'${e.element}' already relates to '${o.id}' through '${e.relation}' (${$O(c.group,c.ref)}); unrelate it first.`,s),!o.owned&&o.modelId===void 0&&l==="@@")return St({type:"RELATION_MEMBERSHIP_UPDATE",update:{relation:e.relation,targetElementId:o.id,addSourceElementIds:[e.element]}});let m=pw(i);return c||(m[l]=[...m[l]??[],o]),St({type:"ELEMENT_UPDATE",elementId:e.element,update:{relations:{[e.relation]:m}}},!1)},_O=(e,t)=>{let n=oc(t,e.element);bs([e.relation],e.element);let r=n.relations?.[e.relation]??{};if((gw(r,e.target)??ie("not-related",`'${e.element}' does not relate to '${e.target}' through '${e.relation}'.`,{elementId:e.element,property:e.relation})).ref.modelId===void 0)return St({type:"RELATION_MEMBERSHIP_UPDATE",update:{relation:e.relation,targetElementId:e.target,removeSourceElementIds:[e.element]}});let o=Object.fromEntries(Object.entries(pw(r)).map(([i,a])=>[i,a.filter(d=>d.id!==e.target)]).filter(([,i])=>i.length>0));return St({type:"ELEMENT_UPDATE",elementId:e.element,update:{relations:{[e.relation]:o}}},!1)},jO=(e,t,n)=>{switch(e.kind){case"create":return MO(e,t,n);case"set":return AO(e,n);case"unset":return TO(e);case"delete":return NO(e,n);case"move":return PO(e,t,n);case"relate":return DO(e,t,n);case"unrelate":return _O(e,n)}},ks=(e,t,{mintId:n=RO}={})=>{let r=[],s=(d,l)=>{try{return l()}catch(c){if(!(c instanceof Ei))throw c;let{elementId:m,property:f}=c.at;r.push({editIndex:d,code:c.code,message:c.message,...m!==void 0&&{elementId:m},...f!==void 0&&{property:f}});return}},o=d=>r.some(l=>l.editIndex===d),i={starting:t,working:lw(t),...xO(e,n,s),deletes:OO(e)},a=[];if(e.forEach((d,l)=>{let c=o(l)?void 0:s(l,()=>jO(d,l,i));c!==void 0&&(a.push(c),i.working.apply(c.action))}),r.length>0)throw new ki(r.toSorted((d,l)=>d.editIndex-l.editIndex));return{actions:a.map(({action:d})=>d),ids:Object.fromEntries([...i.keys].map(([d,{id:l}])=>[d,l])),resendable:a.every(({resendable:d})=>d)}};var Me="The change is staged in your draft of the model, opened on the addressed branch by the first change, where the person you work for sees it in the app and commits it; -m says why, in your words. A lost race with another session is resent once; a refusal exits 4 with every reason in details.errors.",dc={"with-staged":{type:"boolean",description:"With --commit: also land the changes the draft held before this run, which the commit message then covers; required when there are any."}},Ae={...zo,"request-id":{type:"string",placeholder:"id",description:"The idempotency key to stage under, to retry a change whose outcome is unknown: a change already staged under it is not staged again. A cli-\u2026 id this session minted is sent as given, any other id seeds a cli-\u2026 id derived from it, the same one on every run. Minted (cli-\u2026) when left out."},commit:{type:"boolean",description:"Land the draft right after staging, with the same message. Under an agent host this is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1 or the draft aims at a branch named agent/<topic>."},...dc},qO=(e,t,n)=>{if(e!==void 0)return"id"in e?e.id:t===void 0?n[e.key]:void 0},BO=()=>{let e=[],t=0;return{mint:()=>(t===e.length&&e.push(FO()),e[t++]),rewind:()=>{t=0}}},lc=(e,t)=>{if(!/^[\x21-\x7e]+$/.test(e)||e.length>Nd)throw $(`--request-id takes 1 to ${Nd} printable characters without spaces, such as the changeRequestId a failed run reported.`,t);return e},WO=e=>`Retry with --request-id ${e}: a change already staged under it is found and not staged again.`,cc=async(e,t,n,r)=>{let s=r.requestId===void 0?Qn("cli",e.env):Qr("cli",e.env,r.requestId),o=await n(t),i=d=>({actions:d.actions,message:r.message,changeRequestId:s});return{staged:await gi(e,t,{chunks:[i(o)],stableIds:r.requestId!==void 0,replan:async(d,l)=>(e.flags.commit&&await bw(e,d,s),l.length===0?[]:(o=await n(d),[i(o)])),retryHint:WO(s)}),translation:o,changeRequestId:s}},ww=e=>e.staged.chunks[0],mc=e=>{let t=e.staged.target.draft,n=ww(e);if(n===void 0)return t?{id:t.id,headCommitId:t.headCommitId,changeCount:t.changeCount}:null;let r=ys(e.staged),s=e.staged.draftId;return s===void 0&&!r?null:{...s?{id:s}:{},headCommitId:e.staged.head,changeCount:(t?.changeCount??0)+(r&&!n.alreadyStaged?1:0)}},fc=e=>{let{target:t,draftId:n}=e.staged;return n===void 0?de({ref:{kind:"branch",branch:t.branch},draft:void 0}):{kind:"draft",id:n,branch:{id:t.branch.id,name:t.branch.name}}},uc=async(e,t)=>{let{target:n,head:r}=t.staged,s=await ss(e,n.model.id),o=w(n.model.name);if(t.staged.draftId===void 0)throw new p(`The change left ${o} as it was, so there is nothing to commit.`,{type:"nothing-to-commit"});let{landing:a,recovered:d}=await mr(e,s,{targetRefId:n.branch.id,baselineCommitId:n.draft?.baselineCommitId??n.head},{message:e.flags.message,expectedDraftHeadId:r}),l=ur(a,n.model);return{...fr(a),recovered:d,...l===void 0?{}:{next:l},url:W(e.instance(),{kind:"commit",modelId:n.model.id,commitId:a.commit.id})}},pc=(e,t)=>{if(e>0&&!t)throw new p(`Your draft already holds ${P(e,"staged change")}, and a commit lands every one of them under its message.`,{hint:"Review them with 'modeldesk draft diff --changes', then pass --with-staged to commit them too.",details:{changeCount:e}})},hc=e=>`land it from a plain shell with 'modeldesk draft commit ${e} --any-surface'.`,bw=async(e,t,n)=>{er(e,`${e.commandName} --commit`,{kind:"model",id:t.model.id,name:t.model.name},t.branch);let r=n!==void 0&&t.draft!==void 0?(await Rn(e.api(),t.model.id,t.draft.id)).filter(s=>s.requestId!==n).length:t.draft?.changeCount??0;if(pc(r,e.flags["with-staged"]),t.draft!==void 0){let s=w(t.model.name);await De(e,Vo(e,t.model.id),t.draft,{scope:{kind:"all"},action:`Committing your draft of ${s}`,anySurface:!1,override:hc(t.model.id)})}},gc=async e=>{let{commit:t}=e.flags,n=e.flags["with-staged"],r=`modeldesk ${e.commandName} --help`;Sn(e.flags.message,r);let s=e.flags["request-id"];if(s!==void 0&&lc(s,r),n&&!t)throw $("--with-staged goes with --commit.",r);let o=await ot(e,e.args.model);if(t){let i=s===void 0?void 0:Qr("cli",e.env,s);await bw(e,o,i)}return o},Be=(e,t)=>ee(async()=>{let n=await gc(e),r=BO(),s,o=await cc(e,n,async k=>{let S=await t(k);return s=S.subject,r.rewind(),ks(S.edits,k.read,{mintId:r.mint})},{message:e.flags.message,requestId:e.flags["request-id"]}),{translation:i}=o,a=ww(o),d=a?.alreadyStaged?a.commitId:void 0,l=a?.envelope,c=ys(o.staged),m=n.model.id,f=e.instance(),g=qO(s,d,i.ids),u=l?.removedElementIds??[],h=g===void 0||u.includes(g)?void 0:l?.revisions[g]?.element??o.staged.target.read.elements[g],y={model:n.model,ref:fc(o),draft:mc(o),message:e.flags.message,changeRequestId:o.changeRequestId,staged:c,...d?{alreadyStaged:!0,stagedCommitId:d}:{},...h?{element:h}:{},...u.length>0?{removedElementIds:u}:{},url:h?W(f,{kind:"element",modelId:m,elementId:h.id}):W(f,{kind:"model",modelId:m})};if(e.flags.commit){if(!c)throw new p(`The change left ${w(n.model.name)} as it was, so there is nothing to commit.`,{type:"nothing-to-commit"});y.commit=await uc(e,o)}return{result:y}}),UO=e=>w(typeof e=="string"?e:JSON.stringify(e)),HO=e=>e.kind==="draft"?e.branch.name:e.kind==="branch"?e.name:"",GO=e=>{let t=w(e.model.name);if(e.alreadyStaged)return`Already staged in your draft of ${t} under ${e.changeRequestId} (${e.stagedCommitId}); not staged again.`;let n=HO(e.ref);return e.staged?`Staged in your draft of ${t} on ${w(n)} (${P(e.draft?.changeCount??0,"change")}, at most ${Ke}): ${w(e.message)}`:`Nothing was staged: the change leaves ${t} as it is.`},Es=e=>[`Committed as ${e.commit.id} on ${e.branch.name===void 0?e.branch.id:w(e.branch.name)}${e.recovered?" (found on the branch by its request id)":""}.`,...e.next?[e.next]:[],`commit: ${e.url}`],VO=(e,t)=>[e.id,...e.owned?["(owned)"]:[],...t==="@@"?[]:[`[${t}]`]].join(" "),We=e=>{let{element:t}=e;return[GO(e),...t?[`${t.id} (${t.type})`,...Object.entries(t.attributes??{}).map(([n,r])=>` ${n}: ${r.map(UO).join(", ")}`),...Object.entries(t.relations??{}).map(([n,r])=>` ${n}: ${Object.entries(r).flatMap(([s,o])=>o.map(i=>VO(i,s))).join(", ")}`)]:[],...e.removedElementIds?[`Removed ${P(e.removedElementIds.length,"element")}.`]:[],`url: ${e.url}`,...e.commit?Es(e.commit):[]].join(`
223
- `)};var Ci="modeldesk el bulk --help",kw=100,KO="@trait",Ew=e=>(e.attributes?.[KO]??[]).filter(t=>typeof t=="string"),yc=(e,t)=>e===t?!0:e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t)?!1:[...new Set([...Object.keys(e),...Object.keys(t)])].every(r=>yc(e[r],t[r])),YO=(e,t)=>{let n=new Map;return r=>{let s=n.get(r);if(s!==void 0)return s;let o=Vt(e.api(),t,r);return n.set(r,o),o}},Cw=async(e,t,n,r)=>{let s=YO(e,t.model.id),o=n.type?new Set((await Promise.all(n.type.map(s))).flatMap(I=>I.instantiableTypes??[I.name])):void 0,i=Wt(nt(t.tree)).filter(I=>o===void 0||o.has(I.type)),a=i.map(I=>t.read.elements[I.id]),d=[...new Set(a.flatMap(I=>[I.type,...Ew(I)]))],l=new Map(await Promise.all(d.map(async I=>[I,await s(I)]))),c=I=>({type:l.get(I.type),traits:Ew(I).map(x=>l.get(x))}),m=I=>{let{type:x,traits:E}=c(I);return[x,...E].flatMap(M=>(M.attributes??[]).map(v=>v.name))},g=(n.conditions??[]).find(I=>!a.some(x=>Fe(m(x),I.attribute)!==void 0));if(g!==void 0&&a.length>0)throw new p(`No element type the selection reaches has an attribute '${g.attribute}'.`,{exitCode:b.Validation,hint:"Run 'modeldesk describe <model> <type>' to see a type's attributes."});let h=i.filter((I,x)=>ow(a[x],n,{attributeOf:(E,M)=>Fe(m(E),M)})).map(I=>{let x=t.read.elements[I.id],{type:E,traits:M}=c(x),v=Tn({values:r.set,json:r.json},E,{lang:r.lang,current:x.attributes,traits:M});for(let R of r.unset){let A=Fe(m(x),R);if(A===void 0)throw new p(`A ${x.type} has no attribute '${R}' to unset.`,{exitCode:b.Validation,details:{elementId:x.id}});if(A in v)throw $(`'${A}' is both set and unset.`,Ci);v[A]=[]}let C=Object.fromEntries(Object.keys(v).map(R=>[R,x.attributes?.[R]??[]]));return{id:I.id,type:I.type,...I.label===void 0?{}:{label:I.label},path:I.path,before:C,after:v,changes:Object.keys(v).some(R=>!yc(C[R],v[R]))}}),y=h.filter(I=>I.changes),S=y.every(I=>yc(I.after,y[0].after))&&y.length>0?{elementIds:y.map(I=>I.id),attributes:y[0].after}:{updates:y.map(I=>({elementId:I.id,attributes:I.after}))};return{rows:h,update:S}},zO=e=>w(typeof e=="string"?e:JSON.stringify(e)),Rw=e=>e.length===0?"(none)":e.map(zO).join(", "),JO=e=>e.dryRun?"Dry run: nothing was staged.":e.staged?`Staged as one change in your draft (${P(e.draft?.changeCount??0,"change")}): ${w(e.message)}`:"Nothing was staged: no selected element changes.",XO=e=>{let t=e.elements.filter(s=>s.changes).length,n=e.elements.slice(0,kw).flatMap(s=>[` ${w(s.path)} (${s.type}) ${s.id}${s.changes?"":" unchanged"}`,...Object.keys(s.after).map(o=>` ${o}: ${Rw(s.before[o])} -> ${Rw(s.after[o])}`)]),r=e.elements.length-kw;return[$e(e.ref,e.model),`Selected ${P(e.elements.length,"element")}, of which ${t} change:`,...n,...r>0?[` \u2026 and ${r} more (pass --json for every one).`]:[],JO(e),`url: ${e.url}`,...e.commit?Es(e.commit):[]].join(`
224
- `)},Sw=O({path:["el","bulk"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage one update of every element the criteria select",description:`Selects elements by --where and stages one bulk update writing the same attribute values to each, as the app's bulk update does. Each --where clause must hold: type=<T>[,<T>\u2026] (subtypes and trait appliers included), <attr>=<value>, <attr>~<text> (contains, ignoring case), <attr>><n>, <attr><<n>, <attr>:empty, <attr>:not-empty. A --where starting with { is the app's criteria as JSON, and stands alone. Conditions read stored values only, not defaults. --set values are typed by each element's schema as in 'el set'; --unset empties an attribute. --dry-run lists every selected element with its values before and after and stages nothing. ${Me}`,positionals:[_(be)],flags:{where:{type:{list:"string"},required:!0,placeholder:"criterion",description:"A criterion every selected element meets, or the app's criteria as JSON."},set:{type:{list:"string"},placeholder:"attr=value",description:"A value to write, typed by the schema."},"json-value":{type:{list:"string"},placeholder:"attr=json",description:"A value to write given as JSON, written as it is."},unset:{type:{list:"string"},placeholder:"attr",description:"An attribute to empty."},lang:{type:"string",placeholder:"tag",description:"The language of the language-tagged values given."},...Ae},dryRun:!0,examples:['modeldesk el bulk <model> --where type=ElementType --where notation:empty --set notation=uml -m "Default notation" --dry-run',`modeldesk el bulk <model> --where '{"type":["ElementType"],"conditions":[{"attribute":"notation","operator":"empty"}]}' --set notation=uml -m "Default notation"`],run:async e=>ee(async()=>{let{flags:t}=e,n=sw(t.where),r={set:t.set,json:t["json-value"],unset:t.unset,lang:t.lang};if(r.set.length+r.json.length+r.unset.length===0)throw $("Say what to write: --set attr=value, --json-value attr=json or --unset attr.",Ci);let s=e.globals.dryRun;if(s&&t.commit)throw $("--commit has nothing to commit under --dry-run, which stages nothing.",Ci);if(t["with-staged"]&&!t.commit)throw $("--with-staged goes with --commit.",Ci);let o=s?await ot(e,e.args.model):await gc(e),i=o.model.id,a=await Cw(e,o,n,r),d={model:o.model,ref:de(o.resolved),criteria:n,elements:a.rows,dryRun:s,staged:!1,message:t.message,url:W(e.instance(),{kind:"model",modelId:i})};if(s)return{result:d};if(a.rows.length===0)throw new p(`The criteria select no element of ${o.model.name}, so nothing was staged.`,{hint:"Preview a selection with --dry-run."});let l=()=>new p(`No selected element of ${o.model.name} changes, so nothing was staged or committed.`,{type:"nothing-to-commit"});if(!a.rows.some(g=>g.changes)){if(t.commit)throw l();return{result:d}}let c=await cc(e,o,async g=>(a=g===o?a:await Cw(e,g,n,r),{actions:a.rows.some(u=>u.changes)?[{type:"ELEMENT_BULK_UPDATE",update:a.update}]:[],ids:{},resendable:!1}),{message:t.message,requestId:t["request-id"]}),m=ys(c.staged);if(t.commit&&!m)throw l();let[f]=c.staged.chunks;return{result:{...d,ref:fc(c),elements:a.rows,staged:m,changeRequestId:c.changeRequestId,...f?.alreadyStaged?{alreadyStaged:!0,stagedCommitId:f.commitId}:{},draft:mc(c),...t.commit?{commit:await uc(e,c)}:{}}}}),render:XO});import{readFileSync as ZO}from"node:fs";import{resolve as eN}from"node:path";var Cr=e=>{let t=new Set(Object.keys(e.metamodel?.elementTypes??{}));for(let n of e.metamodelExtensions??[])Object.keys(n.elementTypes??{}).forEach(r=>t.add(r));return Object.values(e.elements).forEach(n=>t.add(n.type)),[...t].sort()},QO=e=>e.slice(e.lastIndexOf(":")+1),wc=(e,t)=>{if(e.includes(t))return t;let n=t.toLowerCase(),r=e.filter(s=>s.toLowerCase()===n||QO(s).toLowerCase()===n);if(r.length===0)throw new p(`No element type '${t}' in this model's metamodel.`,{exitCode:b.NotFound});if(r.length>1)throw new p(`'${t}' names ${r.length} element types; pass the full name.`,{exitCode:b.Usage,details:{candidates:r}});return r[0]},Ri=(e,t,n)=>{let r=wc(e,t);if(kn(r)&&!n)throw $(`'${r}' is an internal type; pass --internal to include internal elements.`);return r};var bc="new",tN="/",Rr="modeldesk el create --help",nN=e=>{let t=e.indexOf("=");if(t<=0||t===e.length-1)throw $(`'${e}' is not a relation to set; write --relate <relation>=<target>.`,Rr);return[e.slice(0,t),e.slice(t+1)]},vw=["key","type","attributes","relations","children"],Iw=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return[];let{children:n,...r}=e,s=Object.keys(r).filter(i=>!vw.includes(i)).map(i=>`${t}${i}`),o=n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).flatMap(([i,a])=>Array.isArray(a)?a.flatMap((d,l)=>Iw(d,`${t}children.${i}[${l}].`)):[]):[];return[...s,...o]},rN=(e,t)=>{let n;try{n=JSON.parse(ZO(eN(e,t),"utf8"))}catch(s){throw new p(`Could not read the element in ${t} (${s.message}).`,{exitCode:b.Usage})}if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.type!="string")throw new p(`${t} holds no element: write an object with its "type", and "attributes", "relations" and "children" as needed.`,{exitCode:b.Usage});let r=Iw(n,"");if(r.length>0){let s=vw.map(o=>`"${o}"`).join(", ");throw new p(`${t} names what an element does not have: ${r.join(", ")}. An element takes ${s}.`,{exitCode:b.Validation,details:{unknownKeys:r}})}return n},sN=(e,t)=>{let n=[...t.type===void 0?[]:["--type"],...t["json-value"].length===0?[]:["--json-value"],...t.lang===void 0?[]:["--lang"],...t.relate.length===0?[]:["--relate"]];if(e.length>0)throw $(`--from holds the whole element, so it takes no attr=value ('${e[0]}').`,Rr);if(n.length>0)throw $(`--from holds the whole element, so it takes no ${n.join(", ")}.`,Rr)},oN=(e,t,n,r)=>{let s=(n.relations??[]).map(i=>i.name),o={};for(let i of e){let[a,d]=nN(i),l=Fe(s,a);if(l===void 0)throw new p(`A ${t} has no relation '${a}'.`,{exitCode:b.Validation,hint:`Its relations: ${s.join(", ")||"none"}.`});let c=n.relations?.find(g=>g.name===l),m=c!==void 0&&wi(c),f=o[l]?.["@@"]??[];o[l]={"@@":[...f,{id:le(r,d),owned:m}]}}return o},$w=O({path:["el","create"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a new element under a parent",description:`Stages one new element under <parent> (an id, a label path, or / for the model root), owned through --relation, or through the one child relation of the parent's type that admits --type. Attribute values are checked and typed by the type's schema (see 'modeldesk describe'): attr=value as on 'el set' (repeat a name for several values), --json-value for a structured value, --lang for the language of a language-tagged one. --relate rel=target adds a reference. --from <file> stages a whole subtree in one change instead: a JSON element {"type", "attributes", "relations", "children": {relation: [elements]}}, written as it is. The element's id is minted by the CLI and reported. ${Me}`,positionals:[_(be),{name:"parent",type:"string",required:!0,description:"The parent's id, its label path from the model root, or / for the model root."},{name:"assignments",type:{list:"string"},description:"attr=value, once per value."}],flags:{type:{type:"string",placeholder:"type",description:"The new element's type (required unless --from)."},relation:{type:"string",placeholder:"relation",description:"The parent's relation that owns it; needed only where the parent's type has several for the type."},"json-value":{type:{list:"string"},placeholder:"attr=json",description:"An attribute value given as JSON and written as it is."},lang:{type:"string",placeholder:"tag",description:"The language of the language-tagged values given."},relate:{type:{list:"string"},placeholder:"relation=target",description:"A reference to an existing element (id or label path), not owned by the new one."},from:{type:"string",placeholder:"file",description:"A JSON file holding the element and the subtree it owns, staged as one change."},...Ae},examples:['modeldesk el create <model> SHACL name=Shape --type ElementType -m "Add the Shape type"','modeldesk el create <model> / sh:deactivated=false --type sh:NodeShape -m "Add a shape"'],run:async e=>Be(e,async t=>{let{flags:n}=e,r=e.api(),{tree:s}=t,o=e.args.parent===tN?s.rootId:le(s,e.args.parent);if(n.from!==void 0){sN(e.args.assignments,n);let m=rN(e.cwd,n.from),f=await ws(r,t.model.id,s,o,m.type,n.relation,Rr),g=m.key??bc;return{edits:[{kind:"create",parent:{id:o},relation:f,element:{...m,key:g}}],subject:{key:g}}}if(n.type===void 0)throw $("Pass the --type of the new element, or --from with a file describing it.",Rr);let i=wc(Cr(t.read),n.type),[a,d]=await Promise.all([Vt(r,t.model.id,i),ws(r,t.model.id,s,o,i,n.relation,Rr)]),l=Tn({values:e.args.assignments,json:n["json-value"]},a,{lang:n.lang}),c=oN(n.relate,i,a,s);return{edits:[{kind:"create",parent:{id:o},relation:d,element:{key:bc,type:i,...Object.keys(l).length>0?{attributes:l}:{},...Object.keys(c).length>0?{relations:c}:{}}}],subject:{key:bc}}}),render:We});var iN="/",xw=O({path:["el","mv"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage moving an element under another parent",description:`Moves the element, with everything it owns, under <new-parent> (an id, a label path, or / for the model root), through --relation or the one child relation of the new parent's type that admits it, at --position among the children there (from 0; last when left out). An element with several owners needs --from-owner to say which one it leaves. ${Me}`,positionals:[_(be),Le("element"),{name:"new-parent",type:"string",required:!0,description:"The new parent's id, its label path, or / for the model root."}],flags:{relation:{type:"string",placeholder:"relation",description:"The new parent's relation to own it through, where its type has several for the element."},position:{type:"number",placeholder:"n",description:"Its place among the children there, from 0."},"from-owner":{type:"string",placeholder:"element",description:"The owner it leaves (id or label path), for an element several elements own."},...Ae},examples:['modeldesk el mv <model> SHACL/NodeShape/severity SHACL/Shape -m "Severity applies to every shape"'],run:async e=>Be(e,async({model:t,read:n,tree:r})=>{let{flags:s}=e,o=le(r,e.args.element),i=e.args["new-parent"],a=i===iN?r.rootId:le(r,i),d=await ws(e.api(),t.id,r,a,n.elements[o].type,s.relation,"modeldesk el mv --help"),l;if(s["from-owner"]!==void 0){let c=le(r,s["from-owner"]),m=r.owners(o).filter(f=>f.id===c);if(m.length!==1)throw new p(m.length===0?`Element ${c} does not own element ${o}.`:`Element ${c} owns element ${o} through several relations.`,{exitCode:b.Validation});l={id:c,relation:m[0].relation}}return{edits:[{kind:"move",element:o,parent:{id:a},relation:d,...s.position===void 0?{}:{position:s.position},...l?{from:l}:{}}],subject:{id:o}}}),render:We});var Mw={name:"relation",type:"string",required:!0,description:"The relation's name (its canonical name, or a spelling differing in case or prefix)."},Aw={name:"target",type:"string",required:!0,description:"The target's id, or its label path from the model root."},aN=(e,t)=>{if(!wi(e))return e.ownership==="MIXED"&&!t;if(t)throw $(`The relation '${e.name}' owns every target it holds, so --unowned does not apply.`,"modeldesk el relate --help");return!0},Tw=O({path:["el","relate"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage adding a target to an element's relation",description:`Adds <target> to the element's <relation>, keeping the targets it already holds. Whether the target is owned follows the relation: a reference relation refers to it, an owning one adopts it, and one that holds both (MIXED) adopts it unless --unowned. A grouped relation needs --group. A target in another model is named by its id with --target-model. ${Me}`,positionals:[_(be),Le("element"),Mw,Aw],flags:{unowned:{type:"boolean",description:"Refer to the target rather than own it, on a relation that does both."},group:{type:"string",placeholder:"group",description:"The group of a grouped relation the target joins."},"target-model":{type:{address:"model",slot:fe},placeholder:"model",description:"The id of the model the target lives in, when it is not this one; the target is then an id."},...Ae},examples:['modeldesk el relate <model> SHACL/NodeShape extends SHACL/Shape -m "NodeShape is a Shape"'],run:async e=>Be(e,async({model:t,read:n,tree:r})=>{let{flags:s}=e,o=e.api(),i=le(r,e.args.element),a=n.elements[i],d=(a.attributes?.["@trait"]??[]).filter(y=>typeof y=="string"),c=(await Promise.all([a.type,...d].map(y=>Vt(o,t.id,y)))).flatMap(y=>y.relations??[]),m=Fe(c.map(y=>y.name),e.args.relation),f=c.find(y=>y.name===m);if(f===void 0)throw new p(`A ${a.type} has no relation '${e.args.relation}'.`,{exitCode:b.Validation,hint:`Its relations: ${[...new Set(c.map(y=>y.name))].join(", ")||"none"}.`});let g=aN(f,s.unowned),{target:u}=e.args,h;if(s["target-model"]!==void 0){if(!V(u))throw $("With --target-model, name the target by its id.","modeldesk el relate --help");let y=await oe(e,s["target-model"].model).id(),k=u.toLowerCase();h=y===t.id?{id:k,owned:g}:{id:k,owned:g,modelId:y}}else h={id:le(r,u),owned:g};return{edits:[{kind:"relate",element:i,relation:f.name,target:h,...s.group===void 0?{}:{group:s.group}}],subject:{id:i}}}),render:We}),Ow=O({path:["el","unrelate"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage removing a target from an element's relation",description:`Removes <target> from the element's <relation>, from whichever group holds it, keeping the other targets. A target in another model is named by its id. ${Me}`,positionals:[_(be),Le("element"),Mw,Aw],flags:Ae,examples:['modeldesk el unrelate <model> SHACL/NodeShape extends SHACL/Shape -m "NodeShape stands alone"'],run:async e=>Be(e,({read:t,tree:n})=>{let r=le(n,e.args.element),s=Object.keys(t.elements[r].relations??{}),o=Fe(s,e.args.relation)??e.args.relation,{target:i}=e.args,a=V(i)?i.toLowerCase():le(n,i);return{edits:[{kind:"unrelate",element:r,relation:o,target:a}],subject:{id:r}}}),render:We});var Nw=O({path:["el","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the deletion of an element",description:"Deletes the element, and with it everything it owns that no other element owns too. An element that owns anything is refused (exit 4) unless --recursive says to delete what it owns with it. "+Me,positionals:[_(be),Le("element")],flags:{recursive:{type:"boolean",description:"Delete what the element owns with it."},...Ae},examples:['modeldesk el rm <model> SHACL/NodeShape/severity -m "Severity moved to Shape"'],run:async e=>Be(e,({tree:t})=>{let n=le(t,e.args.element);return{edits:[{kind:"delete",element:n,recursive:e.flags.recursive}],subject:{id:n}}}),render:We});var Lw=O({path:["el","set"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage new values for an element's attributes",description:`Replaces each named attribute's values with the ones given, typed by the attribute's declaration in the schema (see 'modeldesk describe'): true or false for a boolean, a number for a number, one of the listed values for an enum. Name an attribute again for several values. A language-tagged attribute is written in the --lang given (or the one language it already holds) and keeps its other languages. --json-value attr=<json> writes a structured value as it is. An unknown attribute exits 4 listing the valid ones. Relations are changed with 'el relate' and 'el unrelate'. ${Me}`,positionals:[_(be),Le("element"),{name:"assignments",type:{list:"string"},description:"attr=value, once per value."}],flags:{"json-value":{type:{list:"string"},placeholder:"attr=json",description:"An attribute value given as JSON and written as it is."},lang:{type:"string",placeholder:"tag",description:"The language of the language-tagged values given."},...Ae},examples:['modeldesk el set <model> SHACL/NodeShape abstract=true -m "NodeShape is only ever specialized"','modeldesk el set <model> <element> rdfs:label=Persoon --lang nl -m "Dutch label"'],run:async e=>Be(e,async({model:t,read:n,tree:r})=>{let{assignments:s}=e.args,o=e.flags["json-value"];if(s.length===0&&o.length===0)throw $("Name at least one attr=value to set.","modeldesk el set --help");let i=le(r,e.args.element),a=await aw(e.api(),t.id,n.elements[i],{values:s,json:o},e.flags.lang);return{edits:[{kind:"set",element:i,attributes:a}],subject:{id:i}}}),render:We}),Pw=O({path:["el","unset"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of attribute or relation values",description:`Removes every value the element holds under each name given, an attribute or a relation (a relation with all of its targets; to remove one target use 'el unrelate'). A name the element holds nothing under exits 4 listing the names it does hold. ${Me}`,positionals:[_(be),Le("element"),{name:"names",type:{list:"string"},required:!0,description:"An attribute or relation to empty."}],flags:Ae,examples:['modeldesk el unset <model> SHACL/NodeShape alias -m "The alias was a typo"'],run:async e=>Be(e,({read:t,tree:n})=>{let r=le(n,e.args.element),s=t.elements[r],o={attributes:Object.keys(s.attributes??{}),relations:Object.keys(s.relations??{})},i=[],a=[];for(let d of e.args.names){let l=Fe(o.attributes,d),c=l===void 0?Fe(o.relations,d):void 0;if(l!==void 0)i.push(l);else if(c!==void 0)a.push(c);else throw new p(`Element ${r} holds nothing under '${d}'.`,{exitCode:b.Validation,hint:`It holds: ${[...o.attributes,...o.relations].join(", ")||"nothing"}.`})}return{edits:[{kind:"unset",element:r,attributes:i,relations:a}],subject:{id:r}}}),render:We});var jw=(e,t)=>{let n=e.label(t),r=e.element(t)?.type;return{id:t,...n===void 0?{}:{label:n},...r===void 0?{}:{type:r}}},Dw=(e,t)=>t.map(n=>({...jw(e,n.id),relation:n.relation})),dN=e=>w(e!==null&&typeof e=="object"?JSON.stringify(e):String(e)),_w=e=>{let t=e.label===void 0?"(no label)":w(e.label),n=e.type?` (${e.type})`:"";return`${t}${n}`},lN=e=>{let t=[["id:",e.id],["type:",e.type],...e.path===void 0?[]:[["path:",w(e.path)]],["url:",e.url]],n=Object.entries(e.attributes).map(([o,i])=>[`${o}:`,i.map(dN).join(", ")]),r=Object.entries(e.relations).flatMap(([o,i])=>[` ${o}:`,...j(i.map(a=>[_w(a),a.id,[a.owned?"owned":"",a.group?`group ${a.group}`:"",a.modelId?`model ${a.modelId}`:""].filter(d=>d!=="").join(", ")]),{indent:" "})]),s=o=>o.length===0?[" none"]:j(o.map(i=>[_w(i),i.id,`via ${i.relation}`]),{indent:" "});return[$e(e.ref,e.model),e.label===void 0?"(no label)":w(e.label),...j(t,{indent:" "}),"Attributes:",...n.length===0?[" none"]:j(n,{indent:" "}),"Relations:",...r.length===0?[" none"]:r,"Owners:",...s(e.owners),"Children:",...s(e.children)].join(`
225
- `)},Fw=O({path:["el","show"],effect:"read",summary:"Show one element of a model",description:"Shows an element's id, type, label, attribute values, relations (each target with its label), owners and children. Address the element by its id, or by its label path from the model root "+String.raw`(SHACL/NodeShape/severity; write a '/' inside a label as '\/'); a path must name exactly one element, `+"and passes through the platform's internal `@` elements only with --internal. Without a ref, reads your draft while it holds staged changes.",positionals:[_(wt),Le("element")],flags:{...ir},examples:["modeldesk el show <model> SHACL/NodeShape/severity","modeldesk el show <model>@head SHACL/NodeShape/severity","modeldesk el show <model> <element> --json"],run:async e=>{let{model:t,ref:n,tree:r}=await dr(e,e.args.model,wt),{internal:s}=e.flags,o=le(r,e.args.element,{internal:s}),i=r.element(o);if(i===void 0)throw new p(`No element ${o} in ${t.name}.`,{exitCode:b.NotFound});let a=Wt(nt(r,{internal:s})).find(m=>m.id===o)?.path,d=Object.fromEntries(Object.entries(i.relations??{}).map(([m,f])=>[m,Object.entries(f).flatMap(([g,u])=>u.map(h=>({...jw(r,h.id),owned:h.owned,...g==="@@"?{}:{group:g},...h.modelId?{modelId:h.modelId}:{}})))])),l=r.label(o);return{result:{model:t,ref:n,id:o,type:i.type,...l===void 0?{}:{label:l},...a===void 0?{}:{path:a},attributes:i.attributes??{},relations:d,owners:Dw(r,r.owners(o)),children:Dw(r,r.children(o)),url:W(e.instance(),{kind:"element",modelId:t.id,elementId:o})}}},render:lN});var Kt="modeldesk metamodel list",Si=e=>`modeldesk metamodel extensions ${e}`,Yt=(e,t,n,r)=>{let s=e.find(o=>o.id.toLowerCase()===t);if(s===void 0)throw new p(`No ${n} has the id '${t}'.`,{exitCode:b.NotFound,hint:`Run '${r}' to see the ids.`,details:{candidates:e.map(o=>({id:o.id,name:o.name}))}});return s};var cN=["ID","NAME","RELEASE","ABSTRACT"],mN=["ID","NAME","RELEASE","COMPLETES"],qw=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),Bw=e=>w(e??""),Ww=e=>e?"yes":"",Uw=O({path:["metamodel","list"],effect:"read",summary:"List the metamodels a model can be written in",description:"Lists each metamodel with the id --metamodel takes, its name, the release @<release> takes, and whether it is abstract. An abstract metamodel needs an extension that completes it: run metamodel extensions <id>. Names are not unique, so a metamodel is addressed by its id. To read a metamodel as a model, a super-admin uses model list --kind metamodel.",listing:{},examples:["modeldesk metamodel list","modeldesk metamodel list --json"],run:async e=>{let{items:t}=await e.api().metamodels.list(),n=t.filter(s=>s.kind!=="DATA_SCHEMA").map(({id:s,name:o,fullName:i,standardVersion:a,abstract:d})=>({id:s,name:o,...i?{fullName:i}:{},...a?{standardVersion:a}:{},abstract:d===!0})).sort(qw);return{result:await e.list(n)}},render:({items:e})=>e.length===0?"No metamodels.":j([cN,...e.map(t=>[t.id,w(t.name),Bw(t.standardVersion),Ww(t.abstract)])]).join(`
226
- `)}),Hw=O({path:["metamodel","extensions"],effect:"read",summary:"List the extensions of a metamodel",description:"Lists the extensions a model written in the metamodel can apply, each with the id --extension takes. COMPLETES marks an extension that completes an abstract metamodel; a new model on one needs such an extension. Names are not unique, so an extension is addressed by its id.",positionals:[{name:"metamodel",type:{address:"model",slot:gh},required:!0,description:"The metamodel's id, from metamodel list."}],listing:{},examples:["modeldesk metamodel extensions <metamodel>","modeldesk metamodel extensions <metamodel> --json"],run:async e=>{let t=e.api(),{id:n,name:r}=Yt((await t.metamodels.list()).items,e.args.metamodel.model,"metamodel",Kt),{items:s}=await t.metamodelExtensions.list(n),o=s.map(({id:a,name:d,fullName:l,standardVersion:c,concretizes:m,dependsOnExtensions:f})=>({id:a,name:d,...l?{fullName:l}:{},...c?{standardVersion:c}:{},completes:m===!0,dependsOn:f??[]})).sort(qw);return{result:{metamodel:{id:n,name:r},...await e.list(o)}}},render:({items:e})=>e.length===0?"No extensions.":j([mN,...e.map(t=>[t.id,w(t.name),Bw(t.standardVersion),Ww(t.completes)])]).join(`
227
- `)});var fN=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],zt=e=>{let t=e.orgs;return t!==null&&typeof t=="object"?Object.entries(t).map(([n,r])=>{let{name:s,seatAssignments:o}=r??{};return{id:n,...typeof s=="string"?{name:s}:{},seatAssignments:fN(o)}}):typeof e.mdsk_org=="string"?[{id:e.mdsk_org}]:[]},kc=e=>e.name?`${e.name} (${e.id})`:e.id,vi=e=>e.map(({id:t,name:n})=>({id:t,...n?{name:n}:{}})),uN=(e,t)=>e.seatAssignments===void 0||e.seatAssignments.some(n=>n.toLowerCase()===t.toLowerCase()),pN="me",Cs=(e,t)=>{let n=t.toLowerCase(),r=e.filter(s=>V(t)?s.id.toLowerCase()===n:s.name?.toLowerCase()===n);if(r.length===1)return r[0];throw r.length>1?new p(`${r.length} of your organizations are named '${t}'; pass --owner with an id.`,{exitCode:b.Usage,details:{candidates:vi(r)}}):new p(`You are not a member of an organization '${t}'.`,{exitCode:b.NotFound,hint:e.length===0?"Your credential names no organization.":`Your organizations: ${e.map(kc).join(", ")}.`,details:{candidates:vi(e)}})},Ec=(e,t)=>{if(t===pN)throw new p("An import is owned by an organization in which you hold a seat for its metamodel, so --owner me does not apply.",{exitCode:b.Usage,hint:"Pass --owner <organization> with one of your organizations."});return Cs(e,t)},Gw=(e,t,n)=>{if(n!==void 0){let{id:s,name:o}=Ec(e,n);return{id:s,...o?{name:o}:{},chosen:"owner-flag"}}let r=e.filter(s=>uN(s,t.id));if(r.length===1){let[{id:s,name:o}]=r;return{id:s,...o?{name:o}:{},chosen:"only-seated"}}throw r.length===0?new p(`None of your organizations gives you a seat for ${t.name}, and an import must be owned by one that does.`,{exitCode:b.Usage,hint:e.length===0?"Your credential names no organization.":`Pass --owner to choose one anyway (yours: ${e.map(kc).join(", ")}); the server checks the seat.`,details:{candidates:vi(e)}}):new p(`${r.length} of your organizations give you a seat for ${t.name}: ${r.map(kc).join(", ")}.`,{exitCode:b.Usage,hint:"Pass --owner <organization> to choose the owner.",details:{candidates:vi(r)}})};var Rs="modeldesk model create --help",hN=(e,t)=>{let n=zt(e);if(t==="me"){if(typeof e.sub!="string")throw $("This credential is no user, so --owner me names no one.",Rs);return{id:e.sub,type:"USER"}}if(t!==void 0){if(V(t))return{id:t.toLowerCase(),type:"ORGANIZATION"};let{id:r,name:s}=Cs(n,t);return{id:r,type:"ORGANIZATION",...s?{name:s}:{}}}if(n.length===1){let[r]=n;return{id:r.id,type:"ORGANIZATION",...r.name?{name:r.name}:{}}}throw $(n.length===0?"You belong to no organization: pass --owner <organization>, or --owner me for a model of your own.":`You belong to ${n.length} organizations (${n.map(r=>r.name??r.id).join(", ")}); pass --owner <organization> to say which owns the model.`,Rs)},gN=async(e,t,n)=>{let r=(await e.metamodels.list()).items.filter(a=>a.kind!=="DATA_SCHEMA"),s=Yt(r,t.model,"metamodel",Kt),o=n.length>0?(await e.metamodelExtensions.list(s.id)).items:[],i=(a,d)=>{let l=Xn(d);return{id:a.id,name:a.name,...l?{version:l}:{}}};return{metamodel:i(s,t),extensions:n.map(a=>i(Yt(o,a.model,`extension of ${s.name}`,Si(s.id)),a))}},yN=(e,t,n,r)=>{let s=r.filter(o=>o.version!==void 0);return{name:e,metamodelId:n.id,...n.version?{metamodelVersion:n.version}:{},...r.length>0?{metamodelExtensionIds:r.map(o=>o.id)}:{},...s.length>0?{metamodelExtensionVersions:Object.fromEntries(s.map(o=>[o.id,o.version]))}:{},owner:{id:t.id,type:t.type}}},Vw=async(e,t)=>{try{return await e()}catch(n){throw n instanceof p&&n.exitCode===b.Transient?new p(`${n.reason} The model may or may not have been created.`,{exitCode:b.Transient,type:n.type,requestId:n.requestId,details:n.details,hint:`Run 'modeldesk model list' and look for ${w(t)} before retrying: a creation carries no idempotency key, so a retry after one that landed creates a second model.`}):n}},Kw=e=>{let t=e.version?`@${e.version}`:"";return`${w(e.name)}${t}`},wN=e=>e?.length?` with ${e.map(Kw).join(", ")}`:"",bN=e=>e.metamodel?` on ${Kw(e.metamodel)}${wN(e.extensions)}`:" as a metamodel-model",kN=e=>{let{model:t}=e,n=bN(t),r=t.owner?`, owned by ${w(t.owner.name??t.owner.id)}`:"";return e.dryRun?`Would create ${w(t.name)}${n}${r}. Dry run: nothing was created.`:[`Created ${w(t.name)} (${t.id})${n}${r}.`,...e.url?[`url: ${e.url}`]:[]].join(`
228
- `)},Yw=O({path:["model","create"],effect:"create",summary:"Create a model",description:"Creates a model written in --metamodel (its id from metamodel list, with @<release> to pin one; the latest stable release otherwise), with the --extension(s) given the same way (ids from metamodel extensions <metamodel>), owned by --owner (an organization of yours by name or id, or me) or by your one organization. An abstract metamodel needs an extension that completes it. The creation is committed directly; no draft is involved. --kind metamodel creates a metamodel-model instead, which belongs to the platform and takes a super-admin. --dry-run checks the ids and shows what would be created.",flags:{name:{type:"string",required:!0,placeholder:"name",description:"The new model's name."},metamodel:{type:{address:"model",slot:Uo},placeholder:"metamodel[@release]",description:"The metamodel's id, from metamodel list, at @<release> or else its latest stable release (required for a model)."},extension:{type:{list:{address:"model",slot:Ho}},placeholder:"extension[@release]",description:"An extension's id, from metamodel extensions <metamodel>, at @<release> or else its latest stable release."},owner:{type:"string",placeholder:"organization|me",description:"Who owns it: an organization of yours, by name or id, or me; default your one organization."},kind:{type:{enum:["model","metamodel"]},default:"model",description:"model, or metamodel for a metamodel-model (super-admin)."},"standard-version":{type:"string",placeholder:"version",description:"A metamodel-model's standard version (such as 0.1.0)."}},dryRun:!0,examples:["modeldesk model create --name Shapes --metamodel <metamodel>","modeldesk model create --name Catalog --metamodel <metamodel>@1.2.0 --owner Acme --json"],run:async e=>{let{flags:t}=e,n=e.api(),{dryRun:r}=e.globals;if(t.kind==="metamodel"){if(t.metamodel!==void 0||t.owner!==void 0||t.extension.length>0)throw $("A metamodel-model is written in the meta-metamodel and owned by the platform: it takes no --metamodel, --extension or --owner.",Rs);if(!qt(await n.accessTokenClaims()))throw new p("Creating a metamodel-model takes a super-admin.");let c={name:t.name,...t["standard-version"]?{standardVersion:t["standard-version"]}:{}};if(r)return{result:{model:{name:t.name,kind:"metamodel"},dryRun:r}};let m=await Vw(()=>n.metamodelModels.create(c),t.name);return{result:{model:{id:m.id,name:m.name,kind:"metamodel",owner:m.owner},dryRun:r,url:W(e.instance(),{kind:"model",modelId:m.id})}}}if(t["standard-version"]!==void 0)throw $("--standard-version belongs to a metamodel-model (--kind metamodel).",Rs);if(t.metamodel===void 0)throw $("Pass the --metamodel the model is written in.",Rs);let[s,{metamodel:o,extensions:i}]=await Promise.all([n.accessTokenClaims().then(c=>hN(c,t.owner)),gN(n,t.metamodel,t.extension)]),a={name:t.name,kind:"model",metamodel:o,...i.length>0?{extensions:i}:{},owner:s};if(r)return{result:{model:a,dryRun:r}};let d=await Vw(()=>n.models.create(yN(t.name,s,o,i)),t.name);return{result:{model:{...a,id:d.id,name:d.name,owner:d.owner},dryRun:r,url:W(e.instance(),{kind:"model",modelId:d.id})}}},render:kN});var Cc=e=>{let t=e.owner?`, owned by ${w(e.owner.name??e.owner.id)}`:"";return`model ${w(e.name)} (${e.id})${t}`},zw=O({path:["model","delete"],effect:"destroy",summary:"Delete a model",description:"Deletes the model with its content, history and releases. It restates which model that is and asks at a terminal; anywhere else it needs --yes. A model other models still depend on is refused (exit 5). --dry-run restates which model it would delete and deletes nothing; the server then checks no dependents. Under an agent host deleting a model is left to a person (exit 6).",positionals:[_(fe)],dryRun:!0,examples:["modeldesk model delete <model> --dry-run","modeldesk model delete <model> --yes"],run:async e=>{let t=await oe(e,e.args.model.model).identity(),n={id:t.id,name:t.name,...t.owner?{owner:t.owner}:{},headCommitId:t.branch.head.id},r=Cc(n);if(e.globals.dryRun)return{result:{model:n,deleted:!1,dryRun:!0}};e.print(`This deletes ${r}: its content, its history and its releases.
229
- `),await it(e,`Delete ${r}?`,`Deleting ${r}`);try{await e.api().models.delete(n.id)}catch(o){throw o instanceof p&&o.exitCode===b.Conflict?new p(`Other models depend on ${r}, so it was not deleted.`,{exitCode:b.Conflict,type:o.type,details:o.details,hint:"Run 'modeldesk model show' to see what depends on it."}):o}return{result:{model:n,deleted:!0,dryRun:!1}}},render:e=>e.dryRun?`Would delete ${Cc(e.model)}. Dry run: nothing was deleted.`:`Deleted ${Cc(e.model)}.`});import{createHash as g_,randomUUID as y_}from"node:crypto";import{closeSync as w_,lstatSync as b_,mkdirSync as k_,openSync as E_,readdirSync as eC,readFileSync as C_,readSync as R_,renameSync as S_,rmdirSync as v_,rmSync as tC,writeFileSync as I_}from"node:fs";import{dirname as $_,join as Fn,posix as x_,resolve as hf}from"node:path";var he=kd(Sa(),1);var $t=2,va=".modeldesk",rf="workspace.json",xt="model.yaml",jE="_element.yaml",FE="_unowned",ct="model.json",YD="# modeldesk",qE=/^# modeldesk(?::|\s|$)/,Ia=8*1024*1024,sf=128*1024*1024,He=100,of=["id","type","attributes","relations","readOnly"],af=["ref","owned","model"],BE=[...qe,"relations"],zD="@element",Mt=e=>e.startsWith("@")&&e!==zD,WE={lineWidth:0,minContentWidth:0,doubleQuotedAsJSON:!0,indentSeq:!0},df={version:"1.2",schema:"core",uniqueKeys:!0,prettyErrors:!1},an=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,lf=e=>e in Object.prototype,F=e=>ae(w(e)),JD=/^[A-Za-z_][A-Za-z0-9_-]*$/,XD=/^(?:y|yes|n|no|true|false|on|off|null)$/i,UE=e=>{let t=new he.Scalar(e);return(!JD.test(e)||XD.test(e))&&(t.type=he.Scalar.QUOTE_DOUBLE),t},eo=(e,t=0)=>{if(t>He)throw new p(`A value nests more than ${He} deep, deeper than a workspace is written.`,{type:"model-too-deep"});if(Array.isArray(e)){let r=new he.YAMLSeq;return r.items=e.map(s=>eo(s,t+1)),r}if(e!==null&&typeof e=="object")return At(Object.keys(e).sort(ne).map(r=>[r,eo(e[r],t+1)]));let n=new he.Scalar(e);return typeof e=="string"&&(n.type=he.Scalar.QUOTE_DOUBLE),n},At=e=>{let t=new he.YAMLMap;return t.items=e.map(([n,r])=>new he.Pair(UE(n),r)),t},jn=(e,t)=>{let n=new he.Scalar(e);return n.type=he.Scalar.QUOTE_DOUBLE,t!==void 0&&t!==""&&(n.comment=` ${t}`),n},ne=(e,t)=>e<t?-1:e>t?1:0,$a=(e,t)=>{let n=new he.Document;return n.contents=e,n.commentBefore=`${YD.slice(1)}: ${t}`,n.toString(WE)},HE=(e,t)=>{let n=(0,he.parseDocument)(e,df),r=[];for(let{path:s,id:o}of t){let i=s.length===0?n.contents:n.getIn(s,!0);if(!(0,he.isMap)(i)||i.has("id")){r.push(s);continue}i.items.unshift(new he.Pair(UE("id"),jn(o)))}return{text:n.toString(WE),missed:r}},QD=/^(?:con|prn|aux|nul|com\d|lpt\d)$/,ZD=64,cf=e=>e.normalize("NFKD").replace(new RegExp("\\p{M}+","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,ZD).replace(/-$/g,""),mf=e=>e===""||QD.test(e),mt=e=>e.map(t=>`/${String(t).replaceAll("~","~0").replaceAll("/","~1")}`).join("");var Ma=kd(Sa(),1);var e_=100,uf=50,Ge=class extends p{constructor(n){let[r]=n,s=n.length>1?` (and ${n.length-1} more)`:"",o=r.at?` at ${r.at}`:"";super(F(`${r.file}${o}: ${r.message}${s}`),{exitCode:b.Validation,type:"workspace-invalid",hint:"The workspace format is described in the CLI's README; 'modeldesk model pull --force' rewrites the files.",details:{errors:n}});this.problems=n;this.name="WorkspaceInvalidError"}problems},Se=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ff=class{elements=new Map;fileLevel=new Set;problems=[];add(t,n){let r=this.elements.get(t.key);if(r!==void 0){n.problem([...t.location.path],"duplicate-id",`The id ${t.key} is also used at ${r.location.file}${mt(r.location.path)||" (its top)"}; every element is written once. Give a copy no id (a new element), or reference it by id.`);return}this.elements.set(t.key,t)}full(){return this.problems.length>=uf}},xa=(e,t,n)=>{if(typeof e!="string"||!an.test(e)){n.problem(t,"invalid-id",`An id is a UUID in quotes, not ${JSON.stringify(e)?.slice(0,60)}.`);return}return e.toLowerCase()},t_=(e,t,n)=>{let r=Object.keys(e).filter(i=>!af.includes(i));if(!("ref"in e)||r.length>0){n.problem(t,"invalid-reference",r.length>0?`A reference takes only ${af.join(", ")}; '${r[0]}' is not one of them. A nested element needs a type.`:"A reference mapping names its target with `ref: <id>`; a nested element needs a type.");return}let s=xa(e.ref,[...t,"ref"],n);if(e.owned!==void 0&&typeof e.owned!="boolean"){n.problem([...t,"owned"],"invalid-reference","`owned` is true or false.");return}let o=e.model===void 0?void 0:xa(e.model,[...t,"model"],n);if(!(s===void 0||e.model!==void 0&&o===void 0))return{key:s,owned:e.owned===!0,...o!==void 0&&{modelId:o}}},n_=(e,t,n,r,s)=>{if(typeof e=="string"){let o=xa(e,t,n);return o===void 0?void 0:{key:o,owned:!1}}if(!Se(e)){n.problem(t,"invalid-reference","A relation lists ids, `{ref: <id>, owned: true}` mappings or nested elements (a mapping with a type).");return}if("type"in e){let o=zE(e,t,n,r,!1,s+1);return o===void 0?void 0:{key:o.key,owned:!0}}return t_(e,t,n)},pf=(e,t,n,r)=>lf(e)?(n.problem(t,"reserved-name",`'${e}' cannot name ${r}: every JavaScript object already has a member of that name.`),!0):!1,GE=(e,t,n,r,s)=>{if(!Array.isArray(e)){n.problem(t,"invalid-relations","A relation's references are a list; write [] for none.");return}return e.flatMap((o,i)=>n_(o,[...t,i],n,r,s)??[])},r_=(e,t,n,r,s)=>{if(Array.isArray(e))return{"@@":GE(e,t,n,r,s)??[]};if(!Se(e)){n.problem(t,"invalid-relations",`The relation '${t.at(-1)}' is a list of references, or a mapping of groups to lists; write [] for none.`);return}return Object.fromEntries(Object.entries(e).filter(([o])=>!pf(o,[...t,o],n,"a group")).map(([o,i])=>[o,GE(i,[...t,o],n,r,s)??[]]))},YE=(e,t,n,r,s)=>{if(!Se(e))return n.problem(t,"invalid-relations","`relations:` maps each relation name to its references."),{};let o={};for(let[i,a]of Object.entries(e)){if(pf(i,[...t,i],n,"a relation"))continue;let d=r_(a,[...t,i],n,r,s);d!==void 0&&(o[i]=d)}return o},s_=(e,t,n)=>{let r=Object.keys(e).filter(s=>!of.includes(s));for(let s of r)n.problem([...t,s],"unknown-key",`An element block takes ${of.join(", ")}; '${s}' is none of them. An attribute goes under \`attributes:\`, a relation under \`relations:\`.`)},o_=(e,t,n)=>{let r={};if(e===void 0)return r;if(!Se(e))return n.problem([...t,"attributes"],"invalid-attributes","`attributes:` maps each name to a list of values."),r;for(let[s,o]of Object.entries(e))pf(s,[...t,"attributes",s],n,"an attribute")||(Array.isArray(o)?r[s]=o:n.problem([...t,"attributes",s],"invalid-attributes",`The attribute '${s}' holds a list of values: write - "value" on the line below it, or [] for none.`));return r},i_=(e,t)=>t?`\`readOnly:\` holds ${BE.join(", ")}; '${e}' is none of them.`:`\`readOnly:\` holds ${qe.join(", ")} here; '${e}' is none of them.`,a_=(e,t,n,r,s,o)=>{let i={},a={};if(e===void 0)return{readOnly:i,relations:a};if(!Se(e))return n.problem([...t,"readOnly"],"invalid-read-only","`readOnly:` is a mapping."),{readOnly:i,relations:a};for(let[d,l]of Object.entries(e))d==="relations"&&o?Object.assign(a,YE(l,[...t,"readOnly","relations"],n,r,s)):qe.includes(d)?i[d]=l:n.problem([...t,"readOnly",d],"unknown-key",i_(d,o));return{readOnly:i,relations:a}},zE=(e,t,n,r,s,o)=>{if(r.full())return;if(o>He){n.problem(t,"too-deep",`Elements nest more than ${He} deep here; write the rest in files of their own.`);return}if(!Se(e)){n.problem(t,"invalid-element","An element is a mapping with at least a `type`.");return}s_(e,t,n);let i={file:n.file,path:[...t]},a=e.id===void 0?void 0:xa(e.id,[...t,"id"],n);if(typeof e.type!="string"||e.type===""){n.problem([...t,"type"],"missing-type","Every element names its `type`.");return}let d=o_(e.attributes,t,n),l=e.relations===void 0?{}:YE(e.relations,[...t,"relations"],n,r,o),c=a_(e.readOnly,t,n,r,o,s);Object.assign(l,c.relations);let{readOnly:m}=c,f={key:a??`${n.file}#${mt(t)}`,...a!==void 0&&{id:a},type:e.type,attributes:d,relations:l,readOnly:m,location:i};return r.add(f,n),f},d_=(e,t)=>e?.range?t.linePos(e.range[0]).line:void 0,VE=(e,t)=>({file:e,code:"invalid-yaml",message:t instanceof RangeError?"The file nests too deeply to be read.":`The file cannot be read as YAML: ${t.message.split(`
230
- `)[0]}`}),l_=(e,t)=>{let n=new Ma.LineCounter,r;try{r=(0,Ma.parseDocument)(e.text,{...df,lineCounter:n})}catch(i){t.problems.push(VE(e.path,i));return}let s={file:e.path,problem:(i,a,d)=>{let l=i.length===0?r.contents:r.getIn(i,!0),c=d_(l,n);t.problems.push({file:e.path,...i.length>0&&{at:mt(i)},...c!==void 0&&{line:c},code:a,message:F(d)})}};if(r.errors.length>0){for(let i of r.errors.slice(0,3))t.problems.push({file:e.path,line:n.linePos(i.pos[0]).line,code:"invalid-yaml",message:i.message.split(`
231
- `)[0]});return}let o;try{o=r.toJS({maxAliasCount:e_})}catch(i){t.problems.push(VE(e.path,i));return}return zE(o,[],s,t,e.path===xt,0)},JE=e=>{let t=new ff,n;for(let r of[...e].sort((s,o)=>ne(s.path,o.path))){if(t.full())break;let s=l_(r,t);s!==void 0&&(t.fileLevel.add(s.key),r.path===xt&&(n=s.key))}if(n===void 0&&!t.problems.some(r=>r.file===xt)&&t.problems.push({file:xt,code:"missing-root",message:`The workspace has no ${xt}, which holds the model's root element.`}),t.problems.length>0)throw new Ge(t.problems.slice(0,uf));return{format:"yaml",rootKey:n,elements:t.elements,fileLevel:t.fileLevel}},c_=e=>[...Object.keys(Se(e.attributes)?e.attributes:{}),...Object.entries(Se(e.relations)?e.relations:{}).flatMap(([t,n])=>[t,...Object.keys(Se(n)?n:{})])].find(t=>lf(t)),KE=e=>typeof e=="string"&&an.test(e),m_=e=>Se(e)&&KE(e.id)&&(e.owned===void 0||typeof e.owned=="boolean")&&(e.modelId===void 0||KE(e.modelId)),f_=e=>Se(e)&&Object.values(e).every(t=>Array.isArray(t)&&t.every(m_)),u_=e=>e.relations!==void 0&&!(Se(e.relations)&&Object.values(e.relations).every(f_)),p_=e=>e.attributes!==void 0&&!(Se(e.attributes)&&Object.values(e.attributes).every(t=>Array.isArray(t))),h_=(e,t,n,r)=>{let s={},o=n.relations??{};for(let[l,c]of Object.entries(o))s[l]=Object.fromEntries(Object.entries(c).map(([m,f])=>[m,f.map(g=>({key:g.id.toLowerCase(),owned:g.owned===!0,...typeof g.modelId=="string"&&{modelId:g.modelId}}))]));let i=n.attributes??{},a=Object.fromEntries(qe.filter(l=>l in n).map(l=>[l,n[l]])),d=t.toLowerCase();return{key:d,id:d,type:r,attributes:i,relations:s,readOnly:a,location:{file:e,path:["elements",t]}}},XE=e=>{let t=[],n=(i,a,d)=>t.push({file:e.path,...i!==void 0&&{at:i},code:a,message:d}),r;try{r=JSON.parse(e.text)}catch(i){throw new Ge([{file:e.path,code:"invalid-json",message:i.message}])}if(!Se(r)||typeof r.rootElementId!="string"||!Se(r.elements))throw new Ge([{file:e.path,code:"invalid-json",message:`${ct} holds {"rootElementId": \u2026, "elements": {\u2026}}.`}]);let s=new Map;for(let[i,a]of Object.entries(r.elements)){let d=mt(["elements",i]);if(!an.test(i)||!Se(a)||a.id!==i||typeof a.type!="string"){n(d,"invalid-element","Each entry is an element keyed by its own id, with a type.");continue}let l=c_(a);if(l!==void 0){n(d,"reserved-name",`'${l}' cannot name an attribute, relation or group: every JavaScript object already has a member of that name.`);continue}if(u_(a)){n(d,"invalid-reference",'Relations map each name to its groups, and each group lists references: {"id": <uuid>, "owned": <boolean>}, with "modelId" for another model.');continue}if(p_(a)){n(d,"invalid-attributes","Attributes map each name to a list of values.");continue}s.set(i.toLowerCase(),h_(e.path,i,a,a.type))}let o=r.rootElementId.toLowerCase();if(s.has(o)||n("/rootElementId","missing-root","rootElementId names no element of the map."),t.length>0)throw new Ge(t.slice(0,uf));return{format:"json",rootKey:o,elements:s,fileLevel:new Set(s.keys())}};var nC=`${va}/${rf}`,M_=16*1024*1024,QE=Math.max(sf,Ia),A_=e=>e.startsWith(".")||e==="node_modules",T_=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/,O_=/^[0-9a-f]{64}$/,rC=(e,t)=>e<t?-1:e>t?1:0,sC=e=>g_("sha256").update(e,"utf8").digest("hex"),no=e=>Object.fromEntries(e.map(t=>[t.path,sC(t.text)])),ro=e=>Fn(e,va,rf),Aa=(e,t,n)=>new p(`${F(Fn(e,t))} ${n}, so the workspace does not touch it.`,{type:"workspace-path-refused",hint:"Replace it with a plain file or directory, or use another workspace directory.",details:{path:t}}),Ta=e=>{try{return b_(e)}catch(t){if(t.code==="ENOENT")return;throw t}},oC=e=>e===""||e.includes("\\")||e.includes("\0")||x_.isAbsolute(e)||e.split("/").some(n=>n===""||n==="."||n==="..")?void 0:e,dn=(e,t)=>{let n=oC(t);if(n===void 0)throw Aa(e,t,"is not a plain path inside the workspace");let r=n.split("/"),s=hf(e),o=s;for(let[i,a]of r.entries()){o=Fn(o,a);let d=Ta(o);if(d===void 0)return Fn(s,...r);if(d.isSymbolicLink())throw Aa(e,r.slice(0,i+1).join("/"),"is a symbolic link");if(i<r.length-1&&!d.isDirectory())throw Aa(e,r.slice(0,i+1).join("/"),"is not a directory")}return o},to=(e,t,n)=>{let r=dn(e,t),s=Ta(r);if(s!==void 0){if(!s.isFile())throw Aa(e,t,"is not a plain file");if(s.size>n)throw new p(`${F(Fn(e,t))} holds ${s.size} bytes, more than a workspace file may (${n}); it was not read.`,{type:"workspace-file-too-large",details:{path:t,bytes:s.size,limit:n}});return C_(r,"utf8")}},ft=(e,t)=>new p(`${F(ro(e))} ${t}.`,{hint:"Re-pull the workspace into an empty directory with 'modeldesk model pull'."}),N_=(e,t)=>{if(t.schemaVersion===1){let n=typeof t.modelId=="string"?F(t.modelId):"<model>";throw new p(`${F(ro(e))} is a workspace of format 1, which records no branch, and this CLI reads format ${$t} only.`,{hint:`Copy aside any edits you have not pushed, then pull the model again into an empty directory: 'modeldesk model pull ${n}@<branch> <dir>'.`})}if(t.schemaVersion!==$t)throw ft(e,`has workspace format ${F(String(t.schemaVersion))}, which this CLI does not read (it reads ${$t}); update the CLI`)},ZE=(e,t,n)=>{let r=t[n];if(typeof r!="object"||r===null||typeof r.id!="string"||!an.test(r.id)||typeof r.name!="string")throw ft(e,`lacks "${n}" with its id and name`);return{id:r.id.toLowerCase(),name:r.name}},L_=(e,t)=>{for(let[n,r]of Object.entries(t))if(oC(n)===void 0||n.split("/")[0]===va||typeof r!="string"||!O_.test(r))throw ft(e,`lists ${F(n)} among its files, which is not a workspace path with its SHA-256`)},iC=e=>{let t=to(e,nC,M_);if(t===void 0)return;let n;try{n=JSON.parse(t)}catch(a){throw ft(e,`is not valid JSON (${F(a.message)})`)}if(n===null||typeof n!="object"||Array.isArray(n))throw ft(e,"is not a JSON object");let r=n;if(N_(e,r),typeof r.host!="string"||!T_.test(r.host))throw ft(e,"names a host that is not a bare host name (such as modeldesk.io)");if(typeof r.baseCommitId!="string"||!an.test(r.baseCommitId))throw ft(e,'lacks "baseCommitId", the UUID of the commit its files reflect');let s=r.baseRootRevision;if(s!==void 0&&(typeof s!="string"||!an.test(s)))throw ft(e,'has a "baseRootRevision" that is not a UUID');let o=r.format??"yaml";if(o!=="yaml"&&o!=="json")throw ft(e,'has a format that is neither "yaml" nor "json"');let i=r.files??{};if(i===null||typeof i!="object"||Array.isArray(i))throw ft(e,'has a "files" member that is not an object');return L_(e,i),{schemaVersion:$t,host:r.host,model:ZE(e,r,"model"),branch:ZE(e,r,"branch"),baseCommitId:r.baseCommitId.toLowerCase(),...s!==void 0&&{baseRootRevision:s.toLowerCase()},format:o,files:Object.fromEntries(Object.entries(i))}},gf=(e,t)=>{k_($_(e),{recursive:!0});let n=`${e}.${y_()}.tmp`;try{I_(n,t),S_(n,e)}catch(r){throw tC(n,{force:!0}),r}},ln=(e,t)=>gf(dn(e,nC),`${JSON.stringify(t,null,2)}
232
- `),P_=e=>{let t=Buffer.alloc(64),n=E_(e,"r");try{let r=R_(n,t,0,t.length,0);return qE.test(t.subarray(0,r).toString("utf8").replace(/^\uFEFF/,""))}finally{w_(n)}},D_=e=>{try{return eC(e,{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}},aC=(e,t,n,r,s)=>{let o=Fn(e,t),i=D_(o);if(i!==void 0)for(let a of i){let d=t===""?a.name:`${t}/${a.name}`;if(a.isDirectory()){if(!A_(a.name)){let l=n||t===""&&r.has(a.name);aC(e,d,l,r,s)}}else a.isFile()&&a.name.endsWith(".yaml")&&!s.has(d)&&(n||P_(Fn(o,a.name)))&&s.add(d)}},__=(e,t)=>{let n=new Set,r=Object.keys(t.files);for(let o of[...r,...t.format==="json"?[ct]:[]])Ta(dn(e,o))!==void 0&&n.add(o);if(t.format==="json")return[...n].filter(o=>o===ct);let s=new Set(r.filter(o=>o.includes("/")).map(o=>o.split("/")[0]));return s.forEach(o=>dn(e,o)),aC(hf(e),"",!1,s,n),[...n].sort(rC)},yf=(e,t)=>__(e,t).flatMap(n=>{let r=to(e,n,n===ct?sf:Ia);return r===void 0?[]:[{path:n,text:r}]}),wf=(e,t)=>{if(t==="json"){let n=e.find(r=>r.path===ct);if(n===void 0)throw new Ge([{file:ct,code:"missing-root",message:"The workspace has no model.json."}]);return XE(n)}return JE(e)},cn=(e,t)=>wf(yf(e,t),t.format),Oa=(e,t,n)=>{let r={written:[],unchanged:[],removed:[],kept:[],collisions:[]},s=new Set(t.map(o=>o.path));for(let o of t){let i=to(e,o.path,QE);i===o.text?r.unchanged.push(o.path):i!==void 0&&!Object.hasOwn(n,o.path)?r.collisions.push(o.path):r.written.push(o.path)}for(let o of Object.keys(n).sort(rC)){if(s.has(o))continue;let i=to(e,o,QE);i!==void 0&&(sC(i)===n[o]?r.removed:r.kept).push(o)}return r},Na=(e,t,n)=>{if(n.collisions.length>0)throw new Error("A write plan with collisions is not applied.");let r=new Map(t.map(o=>[o.path,o.text]));for(let o of n.written)gf(dn(e,o),r.get(o));let s=new Set;for(let o of n.removed){tC(dn(e,o),{force:!0});let i=o.split("/");for(let a=i.length-1;a>0;a--)s.add(i.slice(0,a).join("/"))}for(let o of[...s].sort((i,a)=>a.length-i.length)){let i=dn(e,o);Ta(i)?.isDirectory()&&eC(i).length===0&&v_(i)}},dC=(e,t)=>{let n=[],r=new Map;for(let s of t)r.set(s.location.file,[...r.get(s.location.file)??[],s]);for(let[s,o]of r)try{let i=to(e,s,Ia);if(i===void 0){n.push(...o.map(l=>({...l,reason:"its file is gone"})));continue}let a=HE(i,o.map(({location:l,id:c})=>({path:l.path,id:c}))),d=new Set(a.missed.map(l=>JSON.stringify(l)));n.push(...o.filter(l=>d.has(JSON.stringify(l.location.path))).map(l=>({...l,reason:"its block is no longer where it was"}))),gf(dn(e,s),a.text)}catch(i){n.push(...o.map(a=>({...a,reason:F(i.message)})))}return n},lC=(e,t)=>hf(e,t??".");var La=e=>JSON.stringify(e,(t,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.keys(n).sort(ne).map(r=>[r,n[r]])):n),Pr=(e,t)=>La(e)===La(t),so=e=>Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t.length>0)),j_=e=>({key:e.id,owned:e.owned===!0,...e.modelId!==void 0&&{modelId:e.modelId}}),qn=(e,t)=>Object.fromEntries(Object.entries(e.relations?.[t]??{}).map(([n,r])=>[n,r.map(j_)])),Bn=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t.length>0)),bf=e=>Object.keys(e).some(t=>t!=="@@"),Ce=e=>Object.keys(e).sort(ne).flatMap(t=>e[t]),oo=e=>{let t=new Map;for(let n of Object.keys(e).sort(ne)){let r=e[n].relations??{};for(let s of Object.keys(r).sort(ne))for(let o of Ce(r[s])){if(o.owned!==!0)continue;let i=t.get(o.id)??[];i.some(a=>a.id===n&&a.relation===s)||i.push({id:n,relation:s}),t.set(o.id,i)}}return t},Pa=e=>{for(let t of e??[]){if(typeof t=="string"&&t.trim()!=="")return t;if(t!==null&&typeof t=="object"&&typeof t.value=="string")return t.value}};var ut=class extends p{constructor(n){let r=n.length>1?` (and ${n.length-1} more)`:"";super(F(`${n[0].message}${r}`),{exitCode:b.Validation,type:"workspace-refused",details:{errors:n}});this.problems=n;this.name="WorkspaceRefusedError"}problems},Da=e=>`${e.id}\0${e.relation}`,F_=e=>{let t=[],n=new Array(e.length).fill(-1);e.forEach((s,o)=>{let i=0,a=t.length;for(;i<a;){let d=i+a>>1;e[t[d]]<s?i=d+1:a=d}n[o]=i>0?t[i-1]:-1,t[i]=o});let r=new Set;for(let s=t.at(-1)??-1;s!==-1;s=n[s])r.add(s);return r},io=e=>"id"in e?e.id:e.new,q_=e=>{let t=new Map;for(let[n,r]of e)for(let[s,o]of Object.entries(r.relations))for(let i of Ce(o).filter(a=>a.owned)){let a=t.get(i.key)??[];a.some(d=>d.id===n&&d.relation===s)||a.push({id:n,relation:s}),t.set(i.key,a)}return t},B_=e=>Object.values(e.relations??{}).flatMap(t=>Ce(t)).filter(t=>t.owned===!0).map(t=>t.id),W_=(e,t)=>{let n=new Map,r=e[t]?.relations??{},s=Object.keys(r).filter(Mt).flatMap(o=>Ce(r[o]).filter(i=>i.owned===!0).map(i=>[i.id,o]));for(let o=s.shift();o!==void 0;o=s.shift()){let[i,a]=o;n.has(i)||!Object.hasOwn(e,i)||(n.set(i,a),B_(e[i]).forEach(d=>s.push([d,a])))}return n},U_=(e,t)=>{let n=e.elements,r=t.elements,s=e.rootId,o=[],i=c=>Object.hasOwn(n,c),a=c=>r.has(c)&&!i(c),d=oo(n),l=q_(r);return{C:n,W:r,rootId:s,problems:o,currentOwners:d,pinnedVia:W_(n,s),vanished:new Set(Object.keys(n).filter(c=>c!==s&&!r.has(c)).sort(ne)),has:i,isNew:a,nodeRef:c=>i(c)||r.get(c)?.id!==void 0?{id:c}:{new:c},opRef:c=>a(c.key)&&r.get(c.key)?.id===void 0?{new:c.key,owned:c.owned}:{id:c.key,owned:c.owned,...c.modelId!==void 0&&{modelId:c.modelId}},ownersNow:c=>d.get(c)??[],ownersThen:c=>l.get(c)??[],viaPin:c=>c.id===s&&Mt(c.relation),refuse:(c,m,f)=>{o.push({code:c,message:F(m),...f.elementId!==void 0&&{elementId:f.elementId},...f.element?.id!==void 0&&f.elementId===void 0&&{elementId:f.element.id},...f.property!==void 0&&{property:f.property},...f.element!==void 0&&{file:f.element.location.file},...f.element!==void 0&&f.element.location.path.length>0&&{at:mt(f.element.location.path)}})}}},fC=(e,t)=>({attributes:so(e),relations:Object.fromEntries(Object.entries(t).map(([n,r])=>[n,Bn(r)]).filter(([,n])=>Object.keys(n).length>0))}),H_=(e,t)=>fC(e[t].attributes??{},Object.fromEntries(Object.keys(e[t].relations??{}).map(n=>[n,qn(e[t],n)]))),G_=(e,t)=>{let{C:n,rootId:r,refuse:s}=e,o=n[r]?.relations??{},i=new Set([...Object.keys(o),...Object.keys(t.relations)]);for(let a of[...i].filter(Mt).sort(ne)){let d=Bn(qn(n[r],a)),l=Bn(t.relations[a]??{});Pr(d,l)||s("read-only-field",`The root's '${a}' is read-only: the model's pins and dependencies are not staged.`,{element:t,elementId:r,property:a})}},V_=(e,t)=>{let{W:n,has:r,pinnedVia:s,refuse:o}=e;for(let[i,a]of Object.entries(t.relations))for(let d of Ce(a))d.owned&&!n.has(d.key)&&r(d.key)&&!s.has(d.key)&&o("missing-block",`'${i}' owns ${d.key} (owned: true), but its block is gone from the workspace. Write its block here in place of the reference, or drop the reference to delete it.`,{element:t,property:i})},cC=e=>e.length===0?"no owner":e.map(t=>`${t.id} via ${t.relation}`).join(", "),K_=(e,t,n)=>n.length>0&&t.length===0?`Element ${e} is written on its own, and the element that owns it (${n[0].id}) is deleted. To delete it as well, remove its block. To keep it, reference it from its new owner as \`- ref: <id>\` with \`owned: true\`: the push moves it there before deleting the old owner.`:`Element ${e} is written on its own, but nothing in the workspace owns it any more: nest it where it belongs, or reference it from its owner with \`owned: true\`.`,Y_=(e,t,n,r)=>{let{ownersNow:s,ownersThen:o,vanished:i,viaPin:a,refuse:d}=e,l=s(t),c=o(t),m=l.filter(h=>!c.some(y=>Da(y)===Da(h))),f=c.filter(h=>!l.some(y=>Da(y)===Da(h))),g=m.filter(h=>!i.has(h.id)),u=m.filter(h=>i.has(h.id));if(f.some(a))d("read-only-field",`Element ${t} cannot be placed under the root's read-only relations.`,{element:n});else if(c.length===0&&l.length>0)d("unowned",K_(t,g,u),{element:n});else{if(f.length===0&&g.length===0)return;f.length===1&&g.length===1?r.set(t,{from:g[0],to:f[0]}):f.length===1&&g.length===0&&u.length>0?r.set(t,{from:u[0],to:f[0]}):d("ownership-change",`Element ${t} would go from ${cC(l)} to ${cC(c)}. A push moves an element from one owner to another; adding an owner, or dropping one that is not deleted, is done in the app. Keep its other owners as they are and change one at a time.`,{element:n})}},z_=(e,t,n,r)=>{let{C:s,rootId:o,pinnedVia:i,refuse:a}=e;n.type!==s[t].type&&a("type-changed",`Element ${t} is a ${s[t].type} and cannot become a ${n.type}: an element's type is fixed. Delete it and write a new element without an id.`,{element:n,property:"type"});for(let l of qe)Pr(s[t][l]??null,n.readOnly[l]??null)||a("read-only-field",`'${l}' of ${t} is read-only: the server serves it, no staged write accepts it.`,{element:n,property:l});let d=i.get(t);d!==void 0&&!Pr(H_(s,t),fC(n.attributes,n.relations))&&a("read-only-field",`Element ${t} belongs to the root's read-only '${d}' and cannot be changed.`,{element:n,property:d}),!(t===o||d!==void 0)&&Y_(e,t,n,r)},J_=(e,t,n)=>{let{rootId:r,ownersThen:s,viaPin:o,refuse:i}=e,a=s(t),d=n.id??`the new ${n.type} at ${F(n.location.file)}${F(mt(n.location.path))}`;Object.keys(n.readOnly).length>0&&i("read-only-field",`${d} carries read-only fields, which no staged write accepts.`,{element:n,property:Object.keys(n.readOnly)[0]}),a.length===0&&t!==r?i("unowned",`${d} is new and nothing owns it: nest it under its owner's relation, or give it an id and reference it from its owner as \`- ref: <id>\` with \`owned: true\`.`,{element:n}):a.length>1?i("multi-owned-create",`${d} is new and has ${a.length} owners; a new element starts with one.`,{element:n}):a.some(o)&&i("read-only-field",`${d} cannot be created under the root's read-only relations.`,{element:n})},X_=(e,t)=>{for(let[n,r]of e.W)V_(e,r),e.has(n)?z_(e,n,r,t):J_(e,n,r)},Q_=e=>{for(let t of e.vanished){let n=e.pinnedVia.get(t);n!==void 0&&e.refuse("read-only-field",`Element ${t} belongs to the root's read-only '${n}' and cannot be removed.`,{elementId:t,property:n})}},uC=e=>{let t=[],n=new Set;return{order:t,seen:n,visit:s=>{let o=[s];for(let i=o.pop();i!==void 0;i=o.pop()){if(n.has(i))continue;n.add(i),t.push(i);let a=e(i),d=Object.keys(a).sort(ne).flatMap(l=>Ce(a[l]).filter(c=>c.owned).map(c=>c.key));for(let l=d.length-1;l>=0;l--)o.push(d[l])}}}},Z_=(e,t)=>{let n=uC(r=>e.W.get(r)?.relations??{});return n.visit(e.rootId),[...t.fileLevel].sort(ne).forEach(n.visit),n.order.filter(r=>e.W.has(r))},kf=(e,t)=>e.ownersThen(t)[0],pC=(e,t,n,r)=>{let s=kf(e,r.key);return r.owned&&e.isNew(r.key)&&!t.has(r.key)&&s?.id===n.key&&s.relation===n.relation},e1=(e,t,n)=>{let r=[n];for(let s=r.pop();s!==void 0;s=r.pop()){t.add(s);for(let[o,i]of Object.entries(e.W.get(s)?.relations??{}))for(let a of Ce(i))pC(e,t,{key:s,relation:o},a)&&r.push(a.key)}},hC=(e,t,n,r=0)=>{t.add(n);let s=e.W.get(n);if(r>He)return e.refuse("too-deep",`New elements nest more than ${He} deep under ${F(s.location.file)}; push them in parts.`,{element:s}),e1(e,t,n),{element:e.nodeRef(n),type:s.type};let o={},i={};for(let d of Object.keys(s.relations).sort(ne)){let l=s.relations[d],c=Bn(Object.fromEntries(Object.entries(l).map(([f,g])=>[f,g.filter(u=>!u.owned).map(u=>e.opRef(u))])));Object.keys(c).length>0&&(o[d]=c);let m=Ce(l).filter(f=>pC(e,t,{key:n,relation:d},f));m.length>0&&(i[d]=m.map(f=>hC(e,t,f.key,r+1)))}let a=so(s.attributes);return{element:e.nodeRef(n),type:s.type,...Object.keys(a).length>0&&{attributes:a},...Object.keys(o).length>0&&{relations:o},...Object.keys(i).length>0&&{children:i}}},t1=(e,t)=>{let n=new Set,s=t.filter(o=>{let i=kf(e,o);return e.isNew(o)&&i!==void 0&&e.has(i.id)&&e.ownersThen(o).length===1}).map(o=>({key:o,home:kf(e,o),node:hC(e,n,o)}));for(let o of t)e.isNew(o)&&!n.has(o)&&e.ownersThen(o).length===1&&e.refuse("unowned",`The new ${e.W.get(o)?.type} at ${F(e.W.get(o)?.location.file??"")} hangs from no existing element.`,{element:e.W.get(o)});return s},gC=(e,t=[])=>(t.push(io(e.element)),Object.values(e.children??{}).flat().forEach(n=>gC(n,t)),t),yC=(e,t=new Set)=>{for(let n of Object.values(e.relations??{}))for(let r of Ce(n))t.add(io(r));return Object.values(e.children??{}).flat().forEach(n=>yC(n,t)),t},n1=e=>{let t=[],n=new Array(e.length).fill(-1),r=new Array(e.length).fill(0),s=new Array(e.length).fill(!1),o=[],i=0,a=c=>{n[c]=i,r[c]=i,i++,o.push(c),s[c]=!0},d=c=>{let m=[];for(let f=o.pop();f!==void 0&&(s[f]=!1,m.push(f),f!==c);f=o.pop());t.push(m.toSorted((f,g)=>f-g))},l=c=>{let m=[{node:c,edge:0}];a(c);for(let f=m.at(-1);f!==void 0;f=m.at(-1)){let{node:g}=f;if(f.edge<e[g].length){let h=e[g][f.edge++];n[h]===-1?(a(h),m.push({node:h,edge:0})):s[h]&&(r[g]=Math.min(r[g],n[h]));continue}m.pop();let u=m.at(-1);u!==void 0&&(r[u.node]=Math.min(r[u.node],r[g])),r[g]===n[g]&&d(g)}};return e.forEach((c,m)=>{n[m]===-1&&l(m)}),t},r1=e=>{let t=new Map;e.forEach((r,s)=>gC(r.node).forEach(o=>t.set(o,s)));let n=e.map((r,s)=>[...yC(r.node)].map(o=>t.get(o)).filter(o=>o!==void 0&&o!==s));return n1(n)},s1=e=>{let t=new Map;return(n,r)=>{let s=`${n}\0${r}`,o=t.get(s);return o===void 0&&(o=e.has(n)?Ce(qn(e.C[n],r)).map(i=>i.key):[],t.set(s,o)),o}},wC=(e,t)=>{let n=io(t.element);for(let[r,s]of Object.entries(t.relations??{}))e(n,r).push(...Ce(s).map(io));for(let[r,s]of Object.entries(t.children??{}))for(let o of s)e(n,r).push(io(o.element)),wC(e,o)},o1=(e,t,n,r,s)=>{for(let o of n){let i=s.ops.length;for(let a of o){let{key:d,home:l,node:c}=t[a];s.ops.push({op:"create",parent:e.nodeRef(l.id),relation:l.relation,element:c}),r(l.id,l.relation).push(d),wC(r,c)}o.length>1&&s.together.push(o.map((a,d)=>i+d))}},bC=({ctx:e},{parent:t,relation:n},r,s,o)=>({op:"move",element:e.nodeRef(r),from:{parent:e.nodeRef(s.id),relation:s.relation},parent:e.nodeRef(t),relation:n,...o!==void 0&&{position:o}}),kC=(e,t,n,r)=>{let{from:s}=e.moves.get(n);e.staged.ops.push(bC(e,t,n,s,r));let o=e.listOf(s.id,s.relation),i=o.indexOf(n);i!==-1&&o.splice(i,1)},i1=(e,t)=>Object.entries(t).some(([n,r])=>{let s=(e[n]??[]).map(l=>l.key),o=new Set(s),i=r.map(l=>l.key).filter(l=>o.has(l)),a=new Set(i),d=s.filter(l=>a.has(l));return i.some((l,c)=>l!==d[c])}),a1=(e,t,n)=>{let{ctx:r,staged:s,moved:o}=e,i=r.has(t.parent)?qn(r.C[t.parent],t.relation):{};i1(i,n)&&s.warnings.push(`The order of '${F(t.relation)}' of ${t.parent} changed in the files, and a grouped relation is not reordered by a push: its order stays as it is.`);for(let a of t.order.filter(d=>t.arriving.has(d)))kC(e,t,a,void 0),t.list.push(a),o.add(a)},EC=(e,t)=>t===void 0?0:e.indexOf(t)+1,d1=(e,t,n,r)=>{let s=EC(t.list,r);kC(e,t,n,s>=t.list.length?void 0:s),t.list.splice(s,0,n),t.inList.add(n),e.moved.add(n)},l1=(e,t,n,r)=>{let s=t.list.indexOf(n);t.list.splice(s,1);let o=EC(t.list,r);if(t.list.splice(o,0,n),o!==s){let i={id:t.parent,relation:t.relation};e.staged.ops.push(bC(e,t,n,i,s>=o?o:o+1))}},c1=(e,t,n,r)=>{if(t.inPlace.has(n)||!t.owned.has(n))return;let s=t.arriving.has(n);if(!s&&!t.inList.has(n))return;let o=t.order.slice(0,r).findLast(i=>t.inList.has(i)&&i!==n);s?d1(e,t,n,o):l1(e,t,n,o)},m1=(e,t)=>{let{order:n,list:r,arriving:s}=t,o=new Map;n.forEach((c,m)=>{o.has(c)||o.set(c,m)});let i=new Set(n),a=r.filter(c=>i.has(c)&&!s.has(c)),d=F_(a.map(c=>o.get(c))),l={...t,inPlace:new Set([...d].map(c=>a[c])),inList:new Set(r)};n.forEach((c,m)=>c1(e,l,c,m))},f1=(e,t,n,r)=>{let{ctx:s,moves:o,listOf:i}=e,a=Ce(r),d=a.map(m=>m.key),l={parent:t,relation:n,order:d,owned:new Set(a.filter(m=>m.owned).map(m=>m.key)),arriving:new Set(d.filter(m=>{let f=o.get(m);return f?.to.id===t&&f.to.relation===n})),list:i(t,n)};bf(r)||s.has(t)&&bf(s.C[t].relations?.[n]??{"@@":[]})?a1(e,l,r):m1(e,l)},u1=(e,t)=>{let{ctx:n,moves:r,moved:s}=e;for(let o of t){let i=n.W.get(o);for(let a of Object.keys(i.relations).sort(ne))o===n.rootId&&Mt(a)||f1(e,o,a,i.relations[a])}for(let o of r.keys())if(!s.has(o))throw new Error(`The move of ${o} found no place in the workspace walk.`)},mC=e=>Bn(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.filter(r=>!r.owned).map(r=>({key:r.key,modelId:r.modelId??null}))]))),p1=(e,t)=>{let n={},r=[];for(let s of[...new Set([...Object.keys(e),...Object.keys(t)])].sort(ne))t[s]===void 0?r.push(s):(e[s]===void 0||!Pr(e[s],t[s]))&&(n[s]=t[s]);return{set:n,unset:r}},h1=(e,t,n)=>{let r=new Set(Ce(n).map(o=>o.key)),s=Object.fromEntries(Object.entries(n).map(([o,i])=>[o,i.map(a=>e.opRef(a))]));for(let[o,i]of Object.entries(t))for(let a of i)a.owned&&e.vanished.has(a.key)&&!r.has(a.key)&&(s[o]=[...s[o]??[],e.opRef(a)]);return Bn(s)},g1=(e,t,n)=>{let r={},s=[],o=new Set([...Object.keys(e.C[t].relations??{}),...Object.keys(n.relations)]);for(let i of[...o].sort(ne)){if(t===e.rootId&&Mt(i))continue;let a=qn(e.C[t],i),d=n.relations[i]??{};if(Pr(mC(a),mC(d)))continue;let l=h1(e,a,d);Object.keys(l).length===0?s.push(i):r[i]=l}return{set:r,unset:s}},y1=(e,t)=>{let n=e.W.get(t),r=p1(so(e.C[t].attributes),so(n.attributes)),s=g1(e,t,n),o={...Object.keys(r.set).length>0&&{attributes:r.set},...Object.keys(s.set).length>0&&{relations:s.set}},i={...r.unset.length>0&&{attributes:r.unset},...s.unset.length>0&&{relations:s.unset}};if(!(Object.keys(o).length===0&&Object.keys(i).length===0))return{op:"update",element:t,...Object.keys(o).length>0&&{set:o},...Object.keys(i).length>0&&{unset:i}}},w1=(e,t,n)=>{for(let r of t){if(!e.has(r)||e.pinnedVia.has(r))continue;let s=y1(e,r);s!==void 0&&n.push(s)}},b1=(e,t,n)=>{let r=[],s=new Set([n]),o=[n];for(let i=o.shift();i!==void 0;i=o.shift())for(let a of t.get(i)??[])!s.has(a)&&e.vanished.has(a)&&e.ownersNow(a).every(d=>s.has(d.id))&&(s.add(a),r.push(a),o.push(a));return r},k1=(e,t)=>{let{C:n,vanished:r,rootId:s}=e,o=rc(e.currentOwners),i=uC(a=>Object.fromEntries(Object.keys(n[a]?.relations??{}).map(d=>[d,qn(n[a],d)])));i.visit(s),Object.keys(n).sort(ne).forEach(i.visit);for(let a of i.order){if(!r.has(a))continue;let d=e.ownersNow(a);d.length>0&&d.every(l=>r.has(l.id))||t.push({op:"delete",element:a,removes:b1(e,o,a)})}},Tt=(e,t,{createOrder:n="workspace"}={})=>{let r=e.rootId;if(t.rootKey!==r)throw new ut([{code:"root-changed",message:`The root element in model.yaml has to keep the model's root id ${r}.`,elementId:r}]);let s=U_(e,t);G_(s,s.W.get(r));let o=new Map;X_(s,o),Q_(s);let i=Z_(s,t),a=t1(s,i);if(s.problems.length>0)throw new ut(s.problems);let d={ops:[],together:[],warnings:[]},l=s1(s),c=n==="references"?r1(a):a.map((m,f)=>[f]);return o1(s,a,c,l,d),u1({ctx:s,moves:o,listOf:l,staged:d,moved:new Set},i),w1(s,i,d.ops),k1(s,d.ops),d};import{createHash as E1,randomUUID as C1}from"node:crypto";var Ef=1e3,R1=8*1024*1024,Cf=Math.floor(R1*.9),S1=(e,t,n)=>E1("sha256").update(La({format:$t,modelId:e,baseCommitId:t,ops:n})).digest("hex"),RC=e=>"id"in e?e.id:e.new,v1=(e,t)=>{let n=new Map,r=s=>{n.set(RC(s.element),"id"in s.element?s.element.id:t()),Object.values(s.children??{}).flat().forEach(r)};return e.forEach(s=>s.op==="create"&&r(s.element)),n},I1=(e,t)=>{let n=i=>"id"in i?i.id:t.get(i.new),r=i=>"new"in i?{id:t.get(i.new),owned:i.owned}:{id:i.id,owned:i.owned,...i.modelId!==void 0&&{modelId:i.modelId}},s=i=>Object.fromEntries(Object.entries(i).map(([a,d])=>[a,Object.fromEntries(Object.entries(d).map(([l,c])=>[l,c.map(r)]))])),o=i=>({key:RC(i.element),type:i.type,...i.attributes&&{attributes:i.attributes},...i.relations&&{relations:s(i.relations)},...i.children&&{children:Object.fromEntries(Object.entries(i.children).map(([a,d])=>[a,d.map(o)]))}});return e.map(i=>{switch(i.op){case"create":return[{kind:"create",parent:{id:n(i.parent)},relation:i.relation,element:o(i.element)}];case"move":return[{kind:"move",element:n(i.element),parent:{id:n(i.parent)},relation:i.relation,from:{id:n(i.from.parent),relation:i.from.relation},...i.position!==void 0&&{position:i.position}}];case"update":return[...i.set?[{kind:"set",element:i.element,...i.set.attributes&&{attributes:i.set.attributes},...i.set.relations&&{relations:s(i.set.relations)}}]:[],...i.unset?[{kind:"unset",element:i.element,...i.unset.attributes&&{attributes:i.unset.attributes},...i.unset.relations&&{relations:i.unset.relations}}]:[]];case"delete":return[{kind:"delete",element:i.element,recursive:!0}]}})},$1=(e,t,n)=>{let r={...e.elements},s=Object.fromEntries([...oo(e.elements)].map(([d,l])=>[d,{owners:l}])),o=d=>"id"in d?d.id:n.get(d.new),i=(d,l)=>{let c=o(d.element);r[c]={id:c,type:d.type},s[c]={owners:[l]};for(let[m,f]of Object.entries(d.children??{}))f.forEach(g=>i(g,{id:c,relation:m}))};for(let d of t)d.op==="create"&&i(d.element,{id:o(d.parent),relation:d.relation});return{elements:r,elementIndexEntries:s}},SC=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g,vC=e=>{let t=[],n=r=>{r.id!==void 0&&t.push(r.id),Object.values(r.ownedElements??{}).flat().forEach(n)};return e.forEach(r=>r.type==="ELEMENT_CREATE"&&n(r.creation)),t},x1=e=>e.flatMap(t=>{switch(t.type){case"ELEMENT_UPDATE":case"ELEMENT_DELETE":return[t.elementId];case"ELEMENT_MOVE":return t.move.elements.map(n=>n.id);default:return[]}}),M1=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),A1=(e,t)=>{let n=0;return t.map(r=>(n+=r,e.slice(n-r,n)))},T1=(e,t)=>{let n=new Map;t.forEach(s=>s.forEach(o=>n.set(o,s)));let r=[];for(let s=0;s<e;){let o=n.get(s)??[s];r.push([...o]),s=(o.at(-1)??s)+1}return r},CC=(e,t,n,{mintId:r=C1}={})=>{let{ops:s}=t,o=v1(s,r),i=I1(s,o),a=i.flat(),d=[],l=E=>{d.push(o.get(E.key)),Object.values(E.children??{}).flat().forEach(l)};a.forEach(E=>E.kind==="create"&&l(E.element));let c=ks(a,$1(e,s,o),{mintId:()=>{let E=d.shift();if(E===void 0)throw new Error("The translation asked for more element ids than the plan creates.");return E}});if(c.actions.length!==a.length||[...o].some(([E,M])=>c.ids[E]!==M))throw new Error("The translation did not map the plan one edit to one action.");let m=A1(c.actions,i.map(E=>E.length)),f=T1(s.length,t.together),g=[],u;for(let E of f){let M=E.flatMap(C=>m[C]),v=M.reduce((C,R)=>C+M1(R)+1,0);if(M.length>Ef||v>Cf){let C=E.length>1?`${E.length} new elements that reference each other`:"One operation";throw new p(`${C} would need ${M.length} actions of ${v} bytes in one change, more than a change carries (${Ef} actions, ${Cf} bytes).`,{exitCode:b.Validation,type:"change-too-large",hint:"Push the workspace in parts: leave part of the new content out, push, then add the rest.",details:{ops:E}})}(u===void 0||u.actions.length+M.length>Ef||u.bytes+v>Cf)&&(u={number:g.length+1,ops:[],actions:[],bytes:2,dependsOn:[]},g.push(u)),u.ops.push(...E),u.actions.push(...M),u.bytes+=v}let h=oo(e.elements),y=E=>`${E.id}\0${E.relation}`,k=E=>E.flatMap(M=>{switch(M.type){case"ELEMENT_CREATE":return M.creation.owner?[y(M.creation.owner)]:[];case"ELEMENT_MOVE":return[y(M.move.targetParent),...M.move.elements.map(v=>y(v.parent))];case"ELEMENT_DELETE":return(h.get(M.elementId)??[]).map(y);default:return[]}}),S=new Map,I=new Map,x=new Map;for(let E of g){let M=new Set(JSON.stringify(E.actions).match(SC)??[]),v=E.actions.flatMap(C=>C.type==="ELEMENT_MOVE"&&C.move.position!==void 0?[y(C.move.targetParent)]:[]);E.dependsOn=[...new Set([...[...M].flatMap(C=>S.has(C)?[S.get(C)]:[]),...[...M].flatMap(C=>I.get(C)??[]),...v.flatMap(C=>x.get(C)??[])])].sort((C,R)=>C-R),vC(E.actions).forEach(C=>S.set(C,E.number));for(let C of x1(E.actions))I.set(C,[...new Set([...I.get(C)??[],E.number])]);for(let C of k(E.actions))x.set(C,[...new Set([...x.get(C)??[],E.number])])}return{hash:S1(n.modelId,n.baseCommitId,s),ops:s,chunks:g,ids:o,warnings:t.warnings}},O1=e=>{let t=new Map;return e.chunks.forEach(n=>vC(n.actions).forEach(r=>t.set(r,n.number))),e.chunks.some(n=>n.actions.some(r=>r.type==="ELEMENT_CREATE"&&(JSON.stringify(r).match(SC)??[]).some(s=>(t.get(s)??0)>n.number)))},_a=(e,t,n,r={})=>{let s=CC(e,Tt(e,t),n,r);return s.chunks.length<2||!O1(s)?s:CC(e,Tt(e,t,{createOrder:"references"}),n,r)};var ja=e=>({create:e.filter(t=>t.op==="create").length,move:e.filter(t=>t.op==="move").length,update:e.filter(t=>t.op==="update").length,delete:e.filter(t=>t.op==="delete").length}),ao=e=>["create","move","update","delete"].filter(t=>e[t]>0).map(t=>P(e[t],t)).join(", "),Fa=(e,t={})=>{let n={};for(let r of JSON.stringify(e).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g)??[])Object.hasOwn(t,r)&&(n[r]=t[r]);return n},$C=e=>1+Object.values(e.children??{}).flat().reduce((t,n)=>t+$C(n),0),IC=e=>typeof e=="string"?e:"id"in e?e.id:e.new,qa=(e,t)=>{let n=new Map,r=o=>{let i=Pa(o.attributes?.name),a=i===void 0?"":` "${w(i)}"`;n.set(IC(o.element),`new ${o.type}${a}`),Object.values(o.children??{}).flat().forEach(r)};e.forEach(o=>o.op==="create"&&r(o.element));let s=o=>{let i=IC(o),a=n.get(i);return a!==void 0?a:Object.hasOwn(t,i)?`${w(t[i])} (${i.slice(0,8)})`:i};return e.map(o=>{switch(o.op){case"create":{let i=$C(o.element)-1;return`+ create ${s(o.element.element)} under ${s(o.parent)} via ${o.relation}`+(i>0?`, with ${P(i,"nested element")}`:"")}case"move":{let i=s(o.from.parent)===s(o.parent)&&o.from.relation===o.relation?"within its list":void 0,a=o.position===void 0?"at the end":`at position ${o.position}`;return i?`> move ${s(o.element)} ${i}, ${a}`:`> move ${s(o.element)} from ${s(o.from.parent)}.${o.from.relation} to ${s(o.parent)}.${o.relation}, ${a}`}case"update":{let i=[...Object.keys(o.set?.attributes??{}).map(a=>`set ${a}`),...Object.keys(o.set?.relations??{}).map(a=>`set ${a}`),...(o.unset?.attributes??[]).map(a=>`unset ${a}`),...(o.unset?.relations??[]).map(a=>`unset ${a}`)];return`~ update ${s(o.element)}: ${i.join(", ")}`}case"delete":return`- delete ${s(o.element)}`+(o.removes.length>0?`, and ${P(o.removes.length,"element")} it owns`:"")}})};var Dr={name:"dir",type:"string",description:"The workspace directory (default: the current directory)."},xC=new WeakMap,Rf=e=>{let t=lC(e.cwd,e.args.dir),n=iC(t);xC.set(e,{dir:t,...n&&{state:n}}),n!==void 0&&N1(e,t,n)},Ba=e=>{Rf(e),lo(e)},N1=(e,t,n)=>{let r=e.env[B.host],s=e.globals.host??(r!==void 0&&r!==""?r:void 0);if(s!==void 0){let o=zr(s).host;if(o!==n.host)throw new p(`The workspace in ${F(t)} was pulled from ${n.host}, and this run targets ${F(o)}.`,{exitCode:b.Usage,hint:`Run it against ${n.host}, or pull the model from the other instance into another directory.`});return}if(n.host===zr(Vr).host){e.globals.host=n.host;return}if(Ie(e.env))throw new p(`In a machine-auth run the host must be set explicitly: pass --host or set ${B.host}. The workspace's ${F(ro(t))} is not a trusted source for where machine credentials are sent.`);e.io.err(`note: using host '${F(n.host)}' from ${F(ro(t))}.
233
- `),e.globals.host=n.host},Sf=e=>{let t=xC.get(e);if(t===void 0)throw new Error("The workspace is loaded before the command runs.");return t},lo=e=>{let{dir:t,state:n}=Sf(e);if(n===void 0)throw new p(`${F(t)} is not a model workspace: it has no .modeldesk/workspace.json.`,{exitCode:b.Usage,hint:"Run 'modeldesk model pull <model> <dir>' to make one, or pass the workspace's directory."});return{dir:t,state:n}},co=async(e,t,n)=>{let r={model:n.model.id,ref:{kind:"branch-id",id:n.branch.id,name:n.branch.name},text:`${n.model.id}@${n.branch.name}`};try{return await ot(e,r)}catch(s){if(!(s instanceof p)||s.type!==il)throw s;let o=s.details.namesake,i=`modeldesk model pull ${n.model.id}@${w(o?.name??"<branch>")} ${F(t)} --force`;throw new p(`${s.reason} The workspace in ${F(t)} tracks it, so nothing was read or staged.`,{exitCode:s.exitCode,type:s.type,details:s.details,hint:`Copy aside any edits you have not pushed, then pull ${o?"that branch":"a branch that exists"} over the workspace: '${i}'.`})}},Wn=e=>e.read.branch.head.rootElement.revision,Wa=(e,t,n)=>{if(n.head===t.baseCommitId)return{kind:"fresh"};if(t.baseRootRevision===Wn(n))return{kind:"rebound",from:t.baseCommitId};try{return Tt(Ot(n.read),cn(e,t)).ops.length===0?{kind:"rebound",from:t.baseCommitId}:{kind:"stale"}}catch(r){if(r instanceof ut||r instanceof Ge)return{kind:"stale"};throw r}},_r=({draft:e,branch:t})=>de({ref:e!==void 0&&e.headCommitId!==t.head?{kind:"draft",draft:e}:{kind:"branch",branch:t},draft:e}),Ua=({draft:e,branch:t,model:n})=>e===void 0||e.baselineCommitId===t.head?void 0:`Your draft of ${w(n.name)} is based on ${e.baselineCommitId}, and ${w(t.name)} has moved on to ${t.head}.`,Ha=(e,t,n,r)=>`The workspace was rebound: ${Qe(e,t)} moved from ${n} to ${r} and holds exactly what the files hold, so its base is now ${r}.`,Ga=(e,t,n)=>{let r={...t,model:n.model,branch:{id:n.branch.id,name:n.branch.name},baseCommitId:n.head,baseRootRevision:Wn(n)};return ln(e,r),r},Ot=e=>{let t=e.rootElementId??Object.values(e.elements).find(n=>n.type==="@Root")?.id;if(t===void 0)throw new p(`The read of ${e.name} carries no root element.`);return{rootId:t,elements:e.elements,...e.elementLabels&&{labels:e.elementLabels}}},L1=e=>{let t=new Set,n=r=>{for(let[s,o]of Object.entries(r??{}))o?.package===!0&&t.add(s)};return n(e.metamodel?.elementTypes),e.metamodelExtensions?.forEach(r=>n(r.elementTypes)),t},Va=e=>{let t=Ot(e);return{modelName:e.name,rootId:t.rootId,elements:t.elements,...t.labels&&{labels:t.labels},indexOwners:n=>e.elementIndexEntries[n]?.owners,packageTypes:L1(e)}},Qe=(e,t)=>e.kind==="draft"?`your draft of ${t} (aimed at ${e.branch.name})`:e.kind==="branch"?`the head of branch ${e.name} of ${t}`:`commit ${e.id} of ${t}`;var MC=O({path:["model","diff"],effect:"read",summary:"Show what pushing a workspace would change",description:"Compares the workspace files with the branch the workspace was pulled from (your draft on it while you hold one, otherwise the branch head) and lists the operations a push stages, in order: creates, moves, updates and deletes. When that head moved since the workspace's base (an edit in the app, an 'el' command, an undo), the workspace is stale and the list is not pushable, since it would revert those changes; when it moved and holds exactly what the files hold (the draft they reflected was committed), the base moves to it and is reported as rebound. --exit-code exits 1 when there are differences, as git diff does.",positionals:[Dr],flags:{"exit-code":{type:"boolean",description:"Exit 1 when the workspace differs from its target, 0 when not."}},prepare:Ba,examples:["modeldesk model diff","modeldesk model diff shacl-workspace --exit-code"],run:e=>ee(async()=>{let t=lo(e),{dir:n}=t,{state:r}=t,s=await co(e,n,r),o=Wa(n,r,s),i=o.kind==="rebound"?{from:o.from}:void 0;i&&(r=Ga(n,r,s));let a=o.kind==="stale",d=cn(n,r),l=Ot(s.read),c,m;try{c=_a(l,d,{modelId:r.model.id,baseCommitId:s.head})}catch(h){if(!(a&&h instanceof ut))throw h;m={message:h.reason,errors:h.problems}}let f=c?.ops??[],g={model:s.model,ref:_r(s),dir:n,baseCommitId:r.baseCommitId,...i&&{rebound:i},headCommitId:s.head,stale:a,pushable:!a,ops:f,counts:ja(f),chunks:c?.chunks.length??0,...!a&&c!==void 0&&f.length>0&&{planHash:c.hash},labels:Fa(f,l.labels),warnings:c?.warnings??[],...m&&{refused:m},url:W(e.instance(),{kind:"model",modelId:r.model.id})},u=f.length>0||m!==void 0;return{result:g,...e.flags["exit-code"]&&u&&{exitCode:b.Failure}}}),render:e=>{let t=w(e.model.name),n=[];return e.rebound&&n.push(Ha(e.ref,t,e.rebound.from,e.headCommitId)),e.stale&&n.push(`The workspace is stale: ${Qe(e.ref,t)} moved from ${e.baseCommitId} to ${e.headCommitId} since it was pulled. The operations below are not pushable: they would revert what changed in between. Push nothing; re-pull with 'modeldesk model pull' (--force discards local edits).`),e.refused!==void 0?n.push(`Note: the files also change what a push cannot stage: ${e.refused.message}`):e.ops.length===0?n.push(`No differences with ${Qe(e.ref,t)}.`):(n.push(`${e.ops.length} operation(s) against ${Qe(e.ref,t)}: ${ao(e.counts)}`+(e.chunks>1?`, in ${e.chunks} changes`:"")+".",...qa(e.ops,e.labels).map(r=>` ${r}`)),e.counts.delete>0&&n.push("Deletes are pushed only with --allow-delete."),e.planHash!==void 0&&n.push(`plan: ${e.planHash}`)),n.push(...e.warnings.map(r=>`Note: ${r}`)),n.join(`
234
- `)}});import{basename as rj}from"node:path";import{randomUUID as j1}from"node:crypto";import{chmodSync as F1,closeSync as q1,fchmodSync as B1,fsyncSync as W1,openSync as U1,renameSync as PC,rmSync as vf,statSync as H1,writeSync as G1}from"node:fs";import{dirname as DC,join as If,resolve as TC}from"node:path";import{existsSync as P1,mkdirSync as D1}from"node:fs";import{dirname as AC,resolve as _1}from"node:path";var Ka=(e,t)=>{let n=[];for(let r=_1(e);!P1(r)&&AC(r)!==r;r=AC(r))n.unshift(r);return D1(e,{recursive:!0,mode:t})===void 0?[]:n};var Ya="modeldesk model export --help",OC=e=>{try{return H1(e)}catch{return}},_C=e=>{let{output:t,compressed:n,json:r,cwd:s}=e;if(n){if(t===void 0)throw $("--compressed writes a ZIP file and needs -o <file>; it never writes to stdout.",Ya);let a=TC(s,t);if(OC(a)?.isDirectory())throw $(`-o ${t} is a directory; --compressed writes one ZIP file, so name the file.`,Ya);return{kind:"zip",file:a}}if(t===void 0){if(r)throw $("--json needs -o <dir>: stdout carries the result document, so the exported documents cannot share it.",Ya);return{kind:"stdout"}}let o=TC(s,t),i=OC(o);if(i!==void 0&&!i.isDirectory())throw $(`-o ${t} is a file; without --compressed, -o names the directory to write into.`,Ya);return{kind:"directory",dir:o}},V1=/[\u0000-\u001f\u007f-\u009f<>:"|?*]/,K1=/^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i,Y1=e=>{if(e===""||e==="."||e==="..")return"it is not a file name";if(V1.test(e))return'it holds a control character or one of < > : " | ? *';if(e.includes("/")||e.includes("\\"))return"it names a path, not a file";if(K1.test(e))return"Windows reserves it for a device";if(/[. ]$/.test(e))return"it ends in a dot or a space, which Windows drops"},jC=e=>{for(let{filename:t}of e){let n=Y1(t);if(n!==void 0)throw new p(`Refusing to write the document named ${JSON.stringify(t)}: ${n}.`,{hint:"Nothing was written. Report the format to ModelDesk: its documents should carry portable file names.",details:{filename:t}})}},FC=e=>{let t=new Map;for(let{filename:n}of e){let r=n.normalize("NFC").toLowerCase(),s=t.get(r);if(s!==void 0)throw new p(`The export holds documents named ${JSON.stringify(s)} and ${JSON.stringify(n)}, which one directory cannot hold apart.`,{hint:"Nothing was written, since the second would overwrite the first.",details:{filenames:[s,n]}});t.set(r,n)}},qC=e=>new p(`The export produced ${e.length} documents, and stdout takes one.`,{exitCode:b.Usage,hint:"Pass -o <dir> to write each under its file name, or --compressed -o <file> for one ZIP.",details:{filenames:e.map(t=>t.filename)}}),z1=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g,BC=(e,t)=>t?e.replace(z1,""):e,za=e=>e.code??e.message,NC=420,LC=493,WC=e=>{Ka(e,LC).forEach(t=>F1(t,LC))},UC=e=>If(DC(e),`.modeldesk-${j1().slice(0,8)}.tmp`),HC=(e,t)=>{let n=U1(e,"wx",NC);try{B1(n,NC);let r=0;for(;r<t.length;)r+=G1(n,t,r,t.length-r);W1(n)}finally{q1(n)}},GC=(e,t)=>{WC(DC(e));let n=UC(e);try{HC(n,t),PC(n,e)}catch(r){throw vf(n,{force:!0}),new p(`Could not write ${e} (${za(r)}).`)}},VC=(e,t)=>{try{WC(e)}catch(o){throw new p(`Could not create ${e} (${za(o)}).`,{details:{renamed:[]}})}let n=[],r=()=>n.forEach(({temp:o})=>vf(o,{force:!0}));for(let{filename:o,contents:i}of t){let a=If(e,o),d=Buffer.from(i,"utf8"),l=UC(a);try{HC(l,d)}catch(c){throw vf(l,{force:!0}),r(),new p(`Could not write ${a} (${za(c)}); nothing was written.`,{details:{failed:o,renamed:[]}})}n.push({temp:l,written:{filename:o,path:a,bytes:d.length}})}let s=[];for(;n.length>0;){let{temp:o,written:i}=n[0];try{PC(o,i.path)}catch(a){throw r(),new p(`Could not move ${i.path} into place (${za(a)}); `+(s.length===0?"nothing was written.":`${s.length} document(s) before it were.`),{details:{failed:i.filename,renamed:s}})}s.push(i.filename),n.shift()}return t.map(({filename:o,contents:i})=>({filename:o,path:If(e,o),bytes:Buffer.byteLength(i,"utf8")}))};var KC=(e,t,n)=>{let r=t.toLowerCase(),s=e.filter(i=>V(t)?i.id.toLowerCase()===r:i.name.toLowerCase()===r);if(s.length===1)return s[0];let o=[...e].sort((i,a)=>(i.sortOrder??0)-(a.sortOrder??0)||i.name.localeCompare(a.name)).map(({id:i,name:a,mediaType:d,fileExtension:l})=>({id:i,name:a,...d?{mediaType:d}:{},...l?{fileExtension:l}:{}}));throw s.length>1?new p(`${s.length} ${n} formats are named '${t}'; pass --format with an id.`,{exitCode:b.Usage,details:{formats:o.filter(i=>i.name.toLowerCase()===r)}}):new p(`${n} has no encoding format '${t}'.`,{exitCode:b.NotFound,hint:o.length===0?`${n} offers no encoding formats.`:`Its formats: ${o.map(i=>i.name).join(", ")}.`,details:{formats:o}})};var YC=e=>{let t=String.raw`'\''`;return`'${e.replaceAll("'",t)}'`},J1=new Set(["sig","key","apikey","api_key","api-key"]),X1=["auth","token","secret","password","signature","credential"],jr="REDACTED",Q1="<unparseable URL redacted>",zC=e=>{let t=e.toLowerCase();return J1.has(t)||X1.some(n=>t.includes(n))},Z1=(e,t,n)=>t===-1||n!==-1&&n<t?"":e.slice(t+1,n===-1?void 0:n),mo=e=>{try{return decodeURIComponent(e.replaceAll("+"," "))}catch{return e}},fn=e=>{let t;try{t=new URL(e)}catch{return Q1}let n=!1;(t.username!==""||t.password!=="")&&(t.username=jr,t.password="",n=!0),t.hash!==""&&(t.hash="",n=!0);for(let r of new Set(t.searchParams.keys()))if(zC(r)){let s=t.searchParams.getAll(r).length;t.searchParams.delete(r);for(let o=0;o<s;o+=1)t.searchParams.append(r,jr);n=!0}return n?t.toString():e},ej=e=>{let t=[[e,fn(e)]],n=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)@/i.exec(e)?.[1];n&&t.push([`${n}@`,`${jr}@`],[`${mo(n)}@`,`${jr}@`]);let r=e.indexOf("#"),s=r===-1?"":e.slice(r+1);s!==""&&t.push([`#${s}`,""]);let o=e.indexOf("?"),i=Z1(e,o,r);for(let a of[...i.split("&"),...s.split("&")]){let d=a.indexOf("="),l=d===-1?a:a.slice(0,d),c=d===-1?"":a.slice(d+1);c!==""&&zC(mo(l))&&t.push([a,`${l}=${jr}`],[`${mo(l)}=${mo(c)}`,`${mo(l)}=${jr}`])}return t.filter(([a])=>a!=="").sort(([a],[d])=>d.length-a.length)},Ja=e=>{if(e===void 0)return n=>n;let t=ej(e);return n=>t.reduce((r,[s,o])=>r.split(s).join(o),n)},mn=(e,t)=>typeof e=="string"?t(e):Array.isArray(e)?e.map(n=>mn(n,t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,mn(r,t)])):e;var Xa=e=>({ERROR:e.filter(t=>t.logLevel==="ERROR").length,WARN:e.filter(t=>t.logLevel==="WARN").length,INFO:e.filter(t=>t.logLevel==="INFO").length}),$f=e=>{let t=[e.modelElementId?`element ${e.modelElementId}`:void 0,e.property?`property ${e.property}`:void 0].filter(Boolean),n=e.detailMessage&&e.detailMessage!==e.title?`: ${e.detailMessage}`:"",r=t.length>0?` (${t.join(", ")})`:"";return w(`${e.logLevel} [${e.code}] ${e.title}${n}${r}`)},fo=e=>e.map(t=>`${$f(t)}
235
- `).join("");var xf={initialMs:500,maxMs:5e3,factor:1.5},tj=(e,t)=>({settled:!1,...e===void 0?{}:{last:e},...t===void 0?{}:{lastError:t}}),uo=async({read:e,settled:t,deadline:n,clock:r,interval:s=xf,onRead:o,tolerate:i=()=>!1})=>{let a=s.initialMs,d,l;for(;;){try{let m=await e();if(d=m,l=void 0,o?.(m),t(m))return{settled:!0,value:m}}catch(m){if(!i(m))throw m;l=m}let c=n-r.now();if(c<=0)return tj(d,l);await r.sleep(Math.min(a,c)),a=Math.min(s.maxMs,a*s.factor)}};var nj=new Set(["INITIALIZED","PROCESSING"]),JC=e=>!nj.has(e.status),XC=e=>e.status==="COMPLETED"||e.status==="ERROR",po=e=>e instanceof p&&e.exitCode===b.Transient,Mf=(e,t)=>e.now()+t*1e3,ho=e=>`modeldesk model imports show ${e}`,Fr=(e,t)=>`modeldesk model imports complete ${e} --name ${t===void 0?"<name>":YC(t)}`,Af=(e,t)=>t?[...e]:e.map($f),Tf=e=>Ja(e.source.type==="remote"?e.source.location:void 0),go=e=>mn(e,Tf(e)),QC=(e,t,n)=>{let r=go(e);return new p(`Import ${r.id} failed ${t==="parse"?"while parsing":"while completing"}: ${r.errorMessage??"the server gave no reason"}`,{details:{importId:r.id,status:r.status,...r.errorMessage?{errorMessage:r.errorMessage}:{},logEntries:Af(r.logEntries??[],n)}})},ZC=(e,t,n,r,s,o)=>{let i=o instanceof p?` The last status check failed: ${o.reason}`:"";return new p(`Import ${e} is still ${t} after ${r} s; it continues on the server.${i}`,{exitCode:b.Transient,hint:n==="parse"?`Check it with '${ho(e)}' and, once it is READY, finish it with '${Fr(e,s)}'. Do not run the import again; that starts a second one.`:`Check it with '${ho(e)}'; it names the new model once the completion lands.`,details:{importId:e,status:t,phase:n}})},eR=(e,t,n,r={})=>new p(`${e.reason} (import ${t})`,{exitCode:b.Transient,hint:n,type:e.type,requestId:e.requestId,details:{...e.details,importId:t,...r}}),tR=(e,t)=>{let n;return r=>{r.status!==n&&(n=r.status,e.note(`Import ${t}: ${r.status}`))}},nR=async(e,t)=>{try{return await e.api.imports.create(t)}catch(n){throw po(n)?new p(n.reason,{exitCode:b.Transient,hint:"The import may exist anyway: run 'modeldesk model imports list' before retrying, then complete or delete the one that is there rather than starting another.",type:n.type,requestId:n.requestId,details:n.details}):n}},rR=async(e,t,n,r,s)=>{let o=tR(e,t.id);o(t);let i=t;if(!JC(t)){let a=await uo({read:()=>e.api.imports.get(t.id),settled:JC,deadline:n,clock:e.clock,onRead:o,tolerate:po});if(!a.settled){let d=(a.last??t).status;throw ZC(t.id,d,"parse",r,s,a.lastError)}i=a.value}if(i.status==="ERROR")throw QC(i,"parse",e.json);return i},Of=async(e,t,n,r,s)=>{e.note(`Completing import ${t} as '${n}'.`);let o;try{o=await e.api.imports.complete(t,n)}catch(a){throw po(a)?eR(a,t,`Check it with '${ho(t)}': once it is COMPLETED it names the model; while it is still READY, run '${Fr(t,n)}' again.`,{phase:"completion"}):a}let i=o;if(!XC(o)){let a=await uo({read:()=>e.api.imports.get(t),settled:XC,deadline:r,clock:e.clock,onRead:tR(e,t),tolerate:po});if(!a.settled){let d=(a.last??o).status;throw ZC(t,d,"completion",s,n,a.lastError)}i=a.value}if(i.status==="ERROR")throw QC(i,"completion",e.json);if(i.modelId===void 0)throw new p(`Import ${t} completed without naming the model it created.`,{hint:`Run '${ho(t)}'.`});return i},sR=async(e,t,n)=>{try{return await t()}catch(r){throw po(r)?eR(r,e,`The import is READY: review it with '${ho(e)}' and finish it with '${Fr(e,n)}'.`):r}},Nf=(e,t)=>e instanceof p?new p(t(e.reason),{exitCode:e.exitCode,...e.hint===void 0?{}:{hint:t(e.hint)},type:e.type,requestId:e.requestId,details:mn(e.details,t)}):e;var sj="modeldesk model export --help",oj=async(e,t,n)=>{if(V(t))return{id:t};if(Ie(e.env)!==void 0)throw $(`--mapping '${t}' is a name, and mappings can be looked up by name only in a user session.`,sj);let{items:r}=await e.api().modelMappings.list({sourceMetamodel:n}),s=r.filter(o=>o.name.toLowerCase()===t.toLowerCase());if(s.length===1)return{id:s[0].id,name:s[0].name};throw s.length>1?new p(`${s.length} mappings are named '${t}'; pass --mapping with an id.`,{exitCode:b.Usage,details:{candidates:s.map(({id:o,name:i})=>({id:o,name:i}))}}):new p(`No mapping named '${t}' applies to this model's metamodel.`,{exitCode:b.NotFound,hint:r.length===0?"None does.":`Mappings that do: ${r.map(o=>o.name).join(", ")}.`,details:{candidates:r.map(({id:o,name:i})=>({id:o,name:i}))}})},ij=e=>_C({output:e.flags.output,compressed:e.flags.compressed,json:e.globals.json,cwd:e.cwd}),aj=async(e,t)=>{let{metamodel:n}=await e.api().models.overview(t);if(n===void 0)throw new p("This is a metamodel-model; its encoding formats are not listed per metamodel.",{exitCode:b.NotFound});return{id:n.modelId,name:n.name}},oR=(e,t)=>{!e.globals.json&&t.length>0&&e.io.err(ae(fo(t)))},dj=async(e,t,n,r,s)=>{e.warn("a compressed export carries no log entries, so encode errors cannot fail this command; use -o <dir> without --compressed where errors must fail the run (CI).");let o=await e.api().encoding.encodeCompressed(n,r);return GC(t,o),{...s,compressed:!0,documents:[{filename:rj(t),path:t,bytes:o.length}],logEntries:[],logEntriesAvailable:!1,errorCount:0}},lj=(e,t,n,r)=>{if(!(t.length>0))throw new p(`The ${r.format} encoder produced no documents for ${r.model}.`,{hint:n.length>0?"Its log entries may say why.":"Check the model holds what the format encodes, or try another format.",details:{logEntries:Af(n,e.globals.json)}})},cj=(e,t,n)=>{let r=n[0]?` (${n[0].filename})`:"";e.io.err(ae(`Exported ${t.model} as ${t.format}${r}.
236
- `))},mj=(e,t,n)=>{let r=n===1?"y":"ies";e.io.err(ae(`error: the ${t} encoder reported ${n} ERROR log entr${r}; the documents were written anyway. Pass --lenient to exit 0 for a format that reports them routinely.
237
- `))},iR=O({path:["model","export"],effect:"read",summary:"Encode a model in a format of its metamodel",description:"Encodes a model in an encoding format of its metamodel (XSD, JSON Schema, Turtle, ...). One document goes to stdout, or to <dir>/<filename> with -o <dir>; several need -o <dir> or --compressed -o <file>. The encoder's log entries go to stderr (or the --json result, which needs -o). An ERROR entry exits 1, with the documents still written; --lenient exits 0 instead. --compressed returns no log entries, so it cannot fail on them. An export with no documents exits 1. Into a directory, a document whose server-supplied name is not a portable file name, or two names one directory cannot hold apart, exit 1 before anything is written. At a terminal, a document on stdout loses its control characters; piped or redirected it is byte-exact. Exports main only: a draft or a branch cannot be encoded yet.",positionals:[_(fe)],flags:{format:{type:"string",required:!0,placeholder:"name|id",description:"The encoding format, by name (ignoring case) or id, among the model's metamodel's formats."},mapping:{type:"string",placeholder:"id",description:"A model mapping to apply before encoding, by id (a name works in a user session only)."},output:{type:"string",short:"o",placeholder:"path",description:"The directory to write the documents into, or the ZIP file with --compressed."},compressed:{type:"boolean",description:"Fetch the documents as one ZIP (needs -o <file>); it carries no log entries."},lenient:{type:"boolean",description:"Exit 0 even when the encoder reports ERROR log entries."}},examples:['modeldesk model export <model> --format "MIM-LD - Turtle" > buildings.ttl',"modeldesk model export <model> --format XSD -o xsd/","modeldesk model export <model> --format XSD --compressed -o schemas.zip"],run:async e=>{let{flags:t,args:n}=e,r=ij(e),s=e.api(),o=await Z(e,n.model,fe),i=de(o);i.note!==void 0&&e.warn(i.note);let a=o.id,d=await aj(e,a),{items:l}=await s.encodingFormats.list(d.id),c=KC(l,t.format,d.name),m=t.mapping===void 0?void 0:await oj(e,t.mapping,d.id),f={format:c.id,mapping:m?.id},g={model:{id:a,name:o.name},ref:i,format:{id:c.id,name:c.name},...m?{mapping:m}:{}};if(r.kind==="zip")return{result:await dj(e,r.file,a,f,g)};let u=await s.encoding.encode(a,f),h=u.documents??[],y=u.logEntries??[],k={format:c.name,model:o.name};if(lj(e,h,y,k),r.kind==="stdout"&&h.length>1)throw oR(e,y),qC(h);let S;if(r.kind==="stdout"){let[{filename:M,contents:v}]=h;e.io.out(BC(v,e.stdoutIsTTY)),S=[{filename:M,path:"-",bytes:Buffer.byteLength(v,"utf8")}]}else jC(h),FC(h),S=VC(r.dir,h);oR(e,y);let I=Xa(y).ERROR,x=I>0&&!t.lenient;return e.globals.json||(r.kind==="stdout"&&cj(e,k,S),x&&mj(e,c.name,I)),{result:{...g,compressed:!1,documents:S,logEntries:y,logEntriesAvailable:!0,errorCount:I},exitCode:x?b.Failure:b.Success}},render:e=>e.documents.every(t=>t.path==="-")?"":[`Exported ${e.model.name} as ${e.format.name}:`,...e.documents.map(t=>` ${t.path} ${t.bytes} bytes`)].join(`
238
- `)});var Qa={now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))};import{readFileSync as fj,statSync as uj}from"node:fs";import{basename as pj,resolve as hj}from"node:path";var un=["mim-ld","nl-sbb","dsv","shacl-ap"],Lf=["rdf-file",...un],aR={".ttl":Lf,".trig":Lf,".nt":Lf,".n3":un,".nq":un,".rdf":un,".rdfs":un,".owl":un,".jsonld":un,".xml":[...un,"xmi-2.1-file"],".xmi":["xmi-2.1-file"],".eap":["eap-file"],".eapx":["eap-file"],".xsd":["xsd-file"],".zip":["shacl-ap"]};var dR={ADDRESS:"an address (--url)",FILE:"an uploaded file"},yo=e=>e.length===0?"none":e.join(", "),cR=e=>e.kind==="file"?"FILE":"ADDRESS",Pf=(e,t)=>e.sourceKinds.includes(cR(t)),Za=(e,t)=>new p(e,{exitCode:b.Usage,hint:"Pass --loader <name> to choose one.",details:{candidates:[...t]}}),Df=e=>{let t="";if(e.kind==="file")t=e.filename;else try{t=decodeURIComponent(new URL(e.location).pathname.split("/").at(-1)??"")}catch{}let n=t.lastIndexOf(".");return n>0?t.slice(n).toLowerCase():void 0},lR=(e,t)=>{let n=e.map(s=>`'${s.name}' reads ${s.sourceKinds.map(o=>dR[o]).join(" or ")} only`),r=e.every(s=>s.sourceKinds.includes("ADDRESS"));return new p(`${n.join("; ")}, and this import gives ${dR[cR(t)]}.`,{exitCode:b.Usage,hint:r?"Publish the file at an address and pass that with --url.":"Download the file and pass its path instead of --url.",details:{loaders:e.map(s=>({name:s.name,sourceKinds:[...s.sourceKinds]}))}})},mR=({source:e,metamodelLoaders:t,metamodelLabel:n,explicit:r})=>{let s=t.map(c=>c.name);if(r!==void 0){let c=t.find(m=>m.name===r);if(c===void 0)throw Za(`Loader '${r}' does not import into ${n}, which imports with ${yo(s)}.`,s);if(!Pf(c,e))throw lR([c],e);return{name:c.name,inferred:!1}}let o=Df(e),i=o===void 0?void 0:aR[o],a=t.filter(c=>Pf(c,e)).map(c=>c.name);if(i===void 0){let c=o===void 0?"a source without a file extension":`'${o}' files`;throw Za(`No loader is known for ${c}; ${n} imports with ${yo(s)}.`,a)}let d=t.filter(c=>i.includes(c.name));if(d.length===0)throw Za(`None of the loaders for '${o}' files (${yo(i)}) imports into ${n}, which imports with ${yo(s)}.`,a);let l=d.filter(c=>Pf(c,e));if(l.length===0)throw lR(d,e);if(l.length>1){let c=l.map(m=>m.name);throw Za(`Several loaders read '${o}' files into ${n}: ${yo(c)}.`,c)}return{name:l[0].name,inferred:!0}};var _f=70*1024*1024,fR=e=>`${(e/(1024*1024)).toFixed(1)} MB`,pR=(e,t,n)=>{let r="modeldesk model import --help";if(e!==void 0&&t!==void 0)throw $("Pass a file or --url, not both.",r);if(t!==void 0){let i;try{i=new URL(t)}catch{throw $("--url takes an absolute http or https address, and this one does not parse.",r)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw $(`--url takes an http or https address, got '${fn(t)}'.`,r);return{type:"remote",location:t}}if(e===void 0)throw $("Name the file to import, or pass --url.",r);let s=hj(n,e),o;try{let i=uj(s);if(!i.isFile())throw $(`'${e}' is not a file.`,r);if(i.size>_f)throw new p(`'${e}' is ${fR(i.size)}, and an upload is at most ${fR(_f)} (the server takes 100 MB of request, and base64 adds a third).`,{exitCode:b.Usage,hint:"Publish the file at an address the server can reach and import it with --url, or split the model.",details:{bytes:i.size,maxBytes:_f}});o=fj(s)}catch(i){throw i instanceof p?i:$(`Cannot read '${e}' (${i.code??i.message}).`,r)}return{type:"upload",filename:pj(s),path:s,bytes:o.length,binaryData:o.toString("base64")}},hR=e=>e.type==="upload"?{kind:"file",filename:e.filename}:{kind:"url",location:e.location},gj=e=>e.type==="upload"?e.filename:fn(e.location),gR=async(e,t)=>{let{items:n}=await e.metamodels.list(),{id:r,name:s}=Yt(n,t,"metamodel",Kt);return{id:r,name:s}},jf=e=>e.standardVersion??e.name,Ff=async(e,t,n)=>{let r=await e.metamodelVersions.list(t.id);if(n===void 0){if(r.length===0)throw new p(`${t.name} has no release to import into.`,{exitCode:b.NotFound});return{...t,version:jf(r[0]),chosen:"newest"}}let s=r.find(o=>o.standardVersion===n||o.name===n);if(s===void 0){let o=r.map(jf);throw new p(`${t.name} has no release '${n}'.`,{exitCode:b.NotFound,hint:`Its releases: ${o.join(", ")||"none"}.`,details:{candidates:o}})}return{...t,version:jf(s),chosen:"given"}},yR=async(e,t,n)=>{if(n.length===0)return[];let{items:r}=await e.metamodelExtensions.list(t.id),s=new Map(r.map(a=>[a.id,a])),o=new Map;for(let a of n){let d=Yt(r,a.model,`extension of ${t.name}`,Si(t.id));o.set(d.id,{version:Xn(a)})}let i=[...o.keys()];for(;i.length>0;){let a=s.get(i.shift());for(let d of a?.dependsOnExtensions??[])s.has(d)&&!o.has(d)&&(o.set(d,{requiredBy:a?.name}),i.push(d))}return Promise.all([...o].map(async([a,{version:d,requiredBy:l}])=>{let{name:c}=s.get(a);return{...await Ff(e,{id:a,name:c},d),...l?{requiredBy:l}:{}}}))},wR=async(e,t,n)=>Gw(zt(await e.accessTokenClaims()),t,n),bR=async(e,t,n,r)=>{let{items:s}=await e.modelLoaders.forMetamodel(t.id,t.version);return mR({source:hR(n),metamodelLoaders:s,metamodelLabel:`${t.name} ${t.version}`,explicit:r})},kR=e=>({metamodel:e.metamodel.id,metamodelVersion:e.metamodel.version,...e.extensions.length>0?{metamodelExtensions:e.extensions.map(t=>t.id)}:{},metamodelExtensionVersions:Object.fromEntries(e.extensions.map(t=>[t.id,t.version])),loader:e.loader.name,source:e.source.type==="upload"?{type:"upload",filename:e.source.filename,binaryData:e.source.binaryData}:{type:"remote",location:e.source.location},owner:{id:e.owner.id,type:"ORGANIZATION"}}),uR=e=>`${e.name} ${e.version}${e.chosen==="newest"?" (newest release)":""}`,ER=e=>{let t=Df(hR(e.source)),n=e.loader.inferred?`${e.loader.name} (inferred from ${t})`:e.loader.name,r=e.owner.name??e.owner.id,s=e.owner.chosen==="only-seated"?` (your one organization with a ${e.metamodel.name} seat)`:"",o=a=>{let d=a.requiredBy?` (required by ${a.requiredBy})`:"";return`${uR(a)}${d}`},i=e.extensions.length===0?"":`, with ${e.extensions.map(o).join(", ")}`;return`Importing ${gj(e.source)} into ${uR(e.metamodel)}${i} with loader ${n}, owned by ${r}${s}.`};var yj=e=>e.type==="remote"?{type:"remote",location:fn(e.location)}:{type:"upload",...e.filename?{filename:e.filename}:{}},qf=e=>({id:e.id,status:e.status,createdAt:e.createdAt,metamodel:{id:e.metamodelId,...e.metamodel?.name?{name:e.metamodel.name}:{},...e.metamodelVersion?{version:e.metamodelVersion}:{}},...e.loader?{loader:e.loader}:{},source:yj(e.source),owner:{id:e.owner.id,type:e.owner.type,...e.owner.name?{name:e.owner.name}:{}},...e.modelId?{modelId:e.modelId}:{}}),CR=(e,t)=>{let n=new Map((t.metamodelExtensions??[]).map(o=>[o.id,o.name])),r=t.metamodelExtensionVersions??{},s=t.metamodelExtensionIds??[...n.keys()];return{...qf(t),...t.createdBy?{createdBy:{id:t.createdBy.id,...t.createdBy.name?{name:t.createdBy.name}:{}}}:{},extensions:s.map(o=>({id:o,...n.get(o)?{name:n.get(o)}:{},...r[o]?{version:r[o]}:{}})),...t.errorMessage?{errorMessage:t.errorMessage}:{},logEntries:t.logEntries??[],url:W(e,{kind:"import",importId:t.id}),...t.modelId?{model:{id:t.modelId,url:W(e,{kind:"model",modelId:t.modelId})}}:{}}},RR=e=>{let t=new Map;for(let r of Object.values(e.elements??{}))r.type.startsWith("@")||t.set(r.type,(t.get(r.type)??0)+1);let n=[...t].map(([r,s])=>({type:r,count:s})).sort((r,s)=>s.count-r.count||r.type.localeCompare(s.type));return{...e.name?{name:e.name}:{},elementCount:n.reduce((r,{count:s})=>r+s,0),elementsByType:n}};var SR="modeldesk model import --help",wj=600,IR={type:"number",default:wj,placeholder:"seconds",description:"How long to wait for the server before exiting 7; the import carries on server-side and can be resumed."},Bf={name:"import-id",type:"string",required:!0,description:"The import's id, as 'model import' or 'model imports list' prints it."},$R=e=>t=>{e.globals.json||e.io.err(ae(`${t}
239
- `))},xR=e=>({api:e.api(),clock:Qa,json:e.globals.json,note:$R(e)}),MR=(e,t)=>{if(!Number.isFinite(e)||e<=0)throw $(`--timeout takes a positive number of seconds, got ${e}.`,t)},Wf=(e,t)=>{if(!V(e))throw $(`'${e}' is not an import id.`,`modeldesk model imports ${t} --help`)},bj=(e,t)=>{if(e.globals.json||t.length===0)return;let{ERROR:n,WARN:r,INFO:s}=Xa(t);e.io.err(ae(`Log: ${n} error(s), ${r} warning(s), ${s} info
240
- ${fo(t)}`))},AR=e=>e.type==="upload"?{type:"upload",filename:e.filename,bytes:e.bytes}:{type:"remote",location:fn(e.location)},TR=O({path:["model","import"],effect:"create",summary:"Import a file or an address as a new model",description:"Creates an import, waits for the parse, completes it as a model named --name, and prints the model id and link. The metamodel release is the one --metamodel names after @, or its newest; the loader is --loader or inferred from the file extension among the release's loaders; the owner is --owner or your one organization with a seat for the metamodel. Every choice is printed, and carried in --json. --review stops after the parse with a summary; finish with 'model imports complete'. Exits 1 when the server puts the import in ERROR, 2 for an ambiguous or mismatched loader or owner, and 7 when --timeout passes (the import then carries on server-side).",positionals:[{name:"file",type:"string",description:"The file to upload; its name travels with it, since some loaders read the format from it."}],flags:{url:{type:"string",placeholder:"uri",description:"Import from this address instead of a file; the server fetches it."},metamodel:{type:{address:"model",slot:Uo},required:!0,placeholder:"metamodel[@release]",description:"The metamodel's id, from metamodel list, at @<release> or else its newest release."},name:{type:"string",placeholder:"name",description:"The name of the model the import creates; required unless --review."},owner:{type:"string",placeholder:"organization",description:"The organization that owns the import and the model, by name or id; needed when several give you a seat."},extension:{type:{list:{address:"model",slot:Ho}},placeholder:"extension[@release]",description:"An extension's id, from metamodel extensions <metamodel>, at @<release> or else its newest release."},loader:{type:"string",placeholder:"name",description:"The loader to read the source with, instead of inferring it from the extension."},review:{type:"boolean",description:"Stop once the parse is READY and summarize it; complete with 'model imports complete'."},timeout:IR},dryRun:!0,examples:["modeldesk model import vocabulary.ttl --metamodel <metamodel> --name Vocabulary","modeldesk model import --url https://example.org/schema.xsd --metamodel <metamodel>@1.0 --name Schema","modeldesk model import model.eap --metamodel <metamodel> --owner Acme --review"],run:async e=>{let{flags:t}=e;if(MR(t.timeout,SR),!t.review&&t.name===void 0)throw $("Pass --name for the model the import creates, or --review to stop before completing.",SR);let n=e.api(),r=pR(e.args.file,t.url,e.cwd),s=await gR(n,t.metamodel.model),o=await wR(n,s,t.owner),i=await Ff(n,s,Xn(t.metamodel)),a=await yR(n,s,t.extension),d=await bR(n,i,r,t.loader),l={source:r,metamodel:i,extensions:a,loader:d,owner:o};$R(e)(ER(l));let m={source:AR(r),metamodel:i,extensions:a,loader:d,owner:o,...t.name!==void 0?{name:t.name}:{}};if(e.globals.dryRun)return{result:{dryRun:!0,...m,logEntries:[]}};let f=Ja(r.type==="remote"?r.location:void 0);try{return await kj(e,l,f)}catch(g){throw Nf(g,f)}},render:e=>{if(e.dryRun)return`Dry run: nothing was imported; ${vR(e.source)} would be read by ${e.loader.name}.`;if(e.status==="READY")return Ej(e);let t=e.model;return[`Imported ${vR(e.source)} as model '${w(t.name)}' (${t.id}).`,t.url].join(`
241
- `)}}),kj=async(e,t,n)=>{let{flags:r}=e,s=e.api(),o={source:AR(t.source),metamodel:t.metamodel,extensions:t.extensions,loader:t.loader,owner:t.owner,...r.name!==void 0?{name:r.name}:{}},i=xR(e),a=Mf(i.clock,r.timeout),d=await nR(i,kR(t)),l=await rR(i,d,a,r.timeout,r.name),c=mn(l.logEntries??[],n);if(bj(e,c),r.review||r.name===void 0){let h=mn(RR(await sR(l.id,()=>s.imports.model(l.id),r.name)),n);return{result:{dryRun:!1,importId:l.id,status:"READY",...o,logEntries:c,review:h,url:W(e.instance(),{kind:"import",importId:l.id}),next:Fr(l.id,r.name)}}}let m=await Of(i,l.id,r.name,a,r.timeout),f=m.modelId,g=W(e.instance(),{kind:"model",modelId:f});return{result:{dryRun:!1,importId:m.id,status:"COMPLETED",...o,logEntries:c,model:{id:f,name:r.name,url:g},url:g}}},vR=e=>e.type==="upload"?e.filename:e.location,Ej=e=>{let t=e.review,n=t.name?` '${w(t.name)}'`:"",r=t.elementsByType.length===0?[" (no elements)"]:j(t.elementsByType.map(({type:s,count:o})=>[String(o),s])).map(s=>` ${s}`);return[`Import ${e.importId} is READY for review.`,`Parsed model${n}: ${t.elementCount} element(s)`,...r,`Complete it with: ${e.next}`,e.url].join(`
242
- `)},ed=e=>e.api().imports.get(e.args["import-id"]),OR=O({path:["model","imports","complete"],effect:"create",summary:"Complete a READY import as a model",description:'Completes an import the parse left READY (after "model import --review", or one started in the app) as a model named --name, waits for the model, and prints its id and link. The name is the only completion input the server reads. An import that is not READY is refused (exit 1).',positionals:[Bf],flags:{name:{type:"string",required:!0,placeholder:"name",description:"The name of the model the import creates."},timeout:IR},dryRun:!0,examples:["modeldesk model imports complete f0909fb8-6867-42e0-a931-26d73185d949 --name Vocabulary"],run:async e=>{let{flags:t,args:n}=e;if(Wf(n["import-id"],"complete"),MR(t.timeout,"modeldesk model imports complete --help"),e.globals.dryRun){let d=await ed(e);if(d.status!=="READY")throw new p(`Import ${d.id} is ${d.status}; only a READY import can be completed.`);return{result:{dryRun:!0,importId:d.id,status:"READY",name:t.name,logEntries:go(d).logEntries??[],url:W(e.instance(),{kind:"import",importId:d.id})}}}let r=xR(e),s;try{s=await Of(r,n["import-id"],t.name,Mf(r.clock,t.timeout),t.timeout)}catch(d){let l=await ed(e).then(c=>c,()=>{});throw l===void 0?d:Nf(d,Tf(l))}let o=s.modelId,i=W(e.instance(),{kind:"model",modelId:o});return{result:{dryRun:!1,importId:s.id,status:"COMPLETED",name:t.name,logEntries:go(s).logEntries??[],model:{id:o,name:t.name,url:i},url:i}}},render:e=>e.dryRun?`Dry run: import ${e.importId} is READY and would be completed as '${w(e.name)}'.`:[`Completed import ${e.importId} as model '${w(e.name)}' (${e.model?.id}).`,e.url].join(`
243
- `)}),Cj=["ID","STATUS","DATE","METAMODEL","SOURCE","OWNER"],NR=e=>{let t=e.version?` ${e.version}`:"";return`${e.name??e.id}${t}`},LR=e=>e.source.type==="remote"?e.source.location:e.source.filename??"(upload)",PR=O({path:["model","imports","list"],effect:"read",summary:"List imports, pending and finished",description:"Lists the imports you can see, newest first: id, status, creation time, metamodel and release, source and owner. A READY import awaits completion; a COMPLETED one names the model it created.",flags:{owner:{type:"string",placeholder:"organization",description:"List only the imports this organization owns, by name or id."}},listing:{narrowHint:"Pass --owner to narrow the list."},examples:["modeldesk model imports list","modeldesk model imports list --owner Acme --json"],run:async e=>{let t=e.api(),n=e.flags.owner===void 0?void 0:Ec(zt(await t.accessTokenClaims()),e.flags.owner),{items:r}=await t.imports.list(n?.id),s=r.map(qf).sort((i,a)=>a.createdAt.localeCompare(i.createdAt)||i.id.localeCompare(a.id));return{result:{...n?{owner:{id:n.id,...n.name?{name:n.name}:{}}}:{},...await e.list(s)}}},render:({items:e})=>e.length===0?"No imports.":j([Cj,...e.map(t=>[t.id,t.status,t.createdAt,w(NR(t.metamodel)),w(LR(t)),w(t.owner.name??t.owner.id)])]).join(`
244
- `)}),DR=O({path:["model","imports","show"],effect:"read",summary:"Show one import",description:"Shows an import's status, metamodel release, extensions, loader, source, owner, error message and log entries, and the model it created once COMPLETED.",positionals:[Bf],examples:["modeldesk model imports show f0909fb8-6867-42e0-a931-26d73185d949"],run:async e=>(Wf(e.args["import-id"],"show"),{result:CR(e.instance(),go(await ed(e)))}),render:e=>{let t=NR(e.metamodel),n=e.createdBy?` by ${e.createdBy.name??e.createdBy.id}`:"";return[`Import ${e.id}`,` status ${e.status}`,` created ${e.createdAt}${n}`,` metamodel ${w(t)}`,...e.extensions.map(s=>{let o=s.version?` ${s.version}`:"";return` extension ${w(s.name??s.id)}${o}`}),...e.loader?[` loader ${e.loader}`]:[],` source ${w(LR(e))}`,` owner ${w(e.owner.name??e.owner.id)}`,...e.errorMessage?[` error ${w(e.errorMessage)}`]:[],...e.model?[` model ${e.model.id}`]:[],...e.logEntries.length>0?["","Log:",...fo(e.logEntries).trimEnd().split(`
245
- `)]:[],"",e.status==="READY"?`Complete it with: ${Fr(e.id)}`:void 0,e.model?.url??e.url].filter(s=>s!==void 0).join(`
246
- `)}}),_R=O({path:["model","imports","delete"],effect:"create",summary:"Discard an import",description:"Deletes an import and the parsed state it holds. A model an import already created is not affected. The server allows it to the import creator or an organization admin with a seat for the metamodel.",positionals:[Bf],dryRun:!0,examples:["modeldesk model imports delete f0909fb8-6867-42e0-a931-26d73185d949"],run:async e=>{let t=e.args["import-id"];Wf(t,"delete");let n=await ed(e);return e.globals.dryRun||await e.api().imports.delete(t),{result:{dryRun:e.globals.dryRun,importId:n.id,deleted:!e.globals.dryRun,status:n.status}}},render:e=>e.dryRun?`Dry run: import ${e.importId} (${e.status}) would be deleted.`:`Deleted import ${e.importId}.`});var Rj=["model","metamodel","all"],Sj=["ID","NAME","KIND","METAMODEL","OWNER"],vj=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),Ij=(e,t)=>t==="me"&&typeof e.sub=="string"?e.sub:t===void 0||V(t)?t:Cs(zt(e),t).id,$j=({model:e,kind:t})=>({id:e.id,name:e.name,kind:t,metamodel:{id:e.metamodel.id,name:e.metamodel.name},owner:{id:e.owner.id,type:e.owner.type,...e.owner.name?{name:e.owner.name}:{}}}),jR=O({path:["model","list"],effect:"read",summary:"List the models you can read",description:"Lists the models you can read with their id, name, kind, metamodel and owner. Metamodel-models (the metamodels themselves, as models) are listed only on --kind metamodel or --kind all, and for a super-admin only; --json reports the kinds listed as kinds. To choose a metamodel, run metamodel list.",flags:{metamodel:{type:"string",placeholder:"id",description:"List only models written in this metamodel, by its id from metamodel list."},owner:{type:"string",placeholder:"organization|me",description:"List only models this owner has: an organization of yours by name, any owner by id, or me."},kind:{type:{enum:Rj},default:"model",description:"List models, metamodel-models (super-admin), or both."}},listing:{narrowHint:"Pass --metamodel or --owner to narrow the list."},examples:["modeldesk model list","modeldesk model list --metamodel <metamodel> --json"],run:async e=>{let{metamodel:t,owner:n,kind:r}=e.flags;if(t!==void 0&&!V(t))throw $(`--metamodel takes a metamodel's id, got '${t}'; run '${Kt}' to find it.`,"modeldesk model list --help");let s=e.api(),o=await s.accessTokenClaims(),i=qt(o),a=Ij(o,n),d=(r==="all"?["model","metamodel"]:[r]).filter(f=>f==="model"||i),c=(await dh(s,{ownerId:a,metamodel:t,models:d.includes("model"),metamodels:d.includes("metamodel")})).map($j).filter(f=>t===void 0||f.metamodel.id.toLowerCase()===t.toLowerCase()).filter(f=>a===void 0||f.owner.id.toLowerCase()===a.toLowerCase()).sort(vj);return{result:{kind:r,kinds:d,...await e.list(c)}}},render:({items:e,kind:t,kinds:n})=>{let r=e.length===0?["No models."]:j([Sj,...e.map(o=>[o.id,w(o.name),o.kind,w(o.metamodel.name),w(o.owner.name??o.owner.id)])]),s=t!=="model"&&!n.includes("metamodel");return[...r,...s?["","Metamodel-models are not listed: only a super-admin can list them."]:[]].join(`
247
- `)}});var td=(e,t)=>async(n,r)=>{let s=Math.min(r,99),o=await e(s+1,n),i=o.slice(0,s);return o.length>s?{items:i,nextCursor:t(i.at(-1))}:{items:i}};var wo=async(e,t,n)=>{let r=0,s=!1,o=async()=>{for(;!s&&r<e.length;)try{await n(e[r++])}catch(i){throw s=!0,i}};await Promise.all(Array.from({length:Math.min(t,e.length)},o))};var xj=["ID","DATE","AUTHOR","CHANGES","MESSAGE","REQUEST"],Mj=8,Aj=" ",Tj=e=>({id:e.id,createdAt:e.createdAt,author:e.createdBy,...e.message?{message:e.message}:{},...e.requestId?{requestId:e.requestId}:{},...e.versions?.length?{versions:e.versions.map(t=>t.name)}:{},...e.stagedChangeCount===void 0?{}:{changes:e.stagedChangeCount}}),Oj=e=>{let t=w((e.message??"").split(/\r?\n/)[0]);return e.versions?`${t}${t?" ":""}[released ${e.versions.join(", ")}]`:t},Nj=e=>[Dt(e.requestId),w(Pd(e.requestId)??""),w(e.message??""),e.actionTypes.length?`[${e.actionTypes.join(", ")}]`:""],FR=O({path:["model","log"],effect:"read",summary:"List a model's commits",description:"Lists commits newest first with their id, time, author, message and request id. The platform hides the commits it makes itself (metamodel seeding, release re-pins) unless --include-system is passed. Without a ref it lists your working branch; @draft lists the staged chain of your draft instead. CHANGES counts the staged changes a landing landed; --changes lists them beneath it.",positionals:[_(sl)],flags:{"include-system":{type:"boolean",description:"Include the commits the platform made itself, such as the re-pins a metamodel release writes."},changes:{type:"boolean",description:"List what each landing held: every staged change with its surface, agent session, message and action types, in the order they were staged. Reads one request per listed landing."}},listing:{defaultLimit:20},examples:["modeldesk model log <model>","modeldesk model log <model>@draft","modeldesk model log <model>@agent/nightly-pass --changes","modeldesk model log <model>@feat/shapes --include-system --limit 100 --json"],run:async e=>{let t=e.api(),n=await Z(e,e.args.model,sl),{id:r}=n,s={...st(n.ref),includeSystem:e.flags["include-system"]},o=td(async(d,l)=>(await t.models.commits(r,{...s,limit:d,cursor:l})).items.map(Tj),d=>d.id),i=await e.list(o);if(e.flags.changes){let d=i.items.filter(l=>l.changes!==void 0);await wo(d,Mj,async l=>{l.stagedChanges=(await t.models.commitHeader(r,l.id,{ref:s.ref})).stagedChanges??[]})}return{result:{model:{id:r,name:n.name},ref:de(n),...i}}},render:e=>{let t=[$e(e.ref,e.model),...e.ref.kind==="draft"?["The log of a draft lists its staged commits only."]:[]];if(e.items.length===0)return[...t,"No commits."].join(`
248
- `);let[n,...r]=j([xj,...e.items.map(o=>[o.id,o.createdAt,w(o.author.name??o.author.id),o.changes===void 0?"":String(o.changes),Oj(o),o.requestId??""])]),s=e.items.flatMap((o,i)=>[r[i],...o.stagedChanges?.length?j(o.stagedChanges.map(Nj),{indent:Aj}):[]]);return[...t,n,...s].join(`
249
- `)}});var rd=kd(Sa(),1);import{posix as nd}from"node:path";var Lj=8,sd=e=>{let{elements:t,labels:n={},packageTypes:r=new Set}=e,s=[],o=new Set([e.rootId]),i=R=>Object.hasOwn(t,R)?t[R]:void 0,a=R=>{let A=Object.hasOwn(n,R)?n[R]:void 0,T=i(R);return A??(T&&(Pa(T.attributes?.name)??T.type))},d=R=>{let A=a(R);return A===void 0?void 0:ae(w(A))},l=(R,A,T)=>Ce(i(R)?.relations?.[A]??{}).some(N=>N.owned===!0&&N.id===T),c=R=>e.indexOwners?.(R)?.find(A=>l(A.id,A.relation,R)),m=(R,A,T)=>{if(i(T)===void 0||o.has(T))return!1;let N=c(T);return N===void 0||N.id===R&&N.relation===A},f=(R,A,T,N)=>{let q=T.owned===!0;if(q&&m(R,A,T.id)){if(o.add(T.id),N===void 0)return h(T.id);N(T.id)}let X=d(T.id);return!q&&T.modelId===void 0?jn(T.id,X):At([["ref",jn(T.id,T.modelId===void 0?X:void 0)],...q?[["owned",new rd.Scalar(!0)]]:[],...T.modelId!==void 0?[["model",jn(T.modelId)]]:[]])},g=(R,A,T)=>{let N=i(R)?.relations?.[A]??{},q=me=>{let Y=new rd.YAMLSeq;return Y.items=me.map(U=>f(R,A,U,T)),Y},X=Object.keys(N);return X.length===1&&X[0]==="@@"?q(N["@@"]):At(X.toSorted(ne).map(me=>[me,q(N[me])]))},u=0,h=(R,A)=>{if(++u>He)throw new p(`The model nests elements more than ${He} deep (at ${R}), deeper than a workspace is written.`,{type:"model-too-deep",details:{elementId:R,limit:He}});try{return y(R,A)}finally{u--}},y=(R,A)=>{let T=t[R],N=R===e.rootId,q=T.attributes??{},X=T.relations??{},me=Object.keys(X).sort(ne),Y=me.filter(se=>!(N&&Mt(se))),U=me.filter(se=>N&&Mt(se)),ge=qe.filter(se=>Object.hasOwn(T,se)&&T[se]!==void 0),Nt=[["id",jn(T.id)],["type",jn(T.type)]];return Object.keys(q).length>0&&Nt.push(["attributes",At(Object.keys(q).sort(ne).map(se=>[se,eo(q[se])]))]),Y.length>0&&Nt.push(["relations",At(Y.map(se=>[se,g(R,se,A)]))]),(ge.length>0||U.length>0)&&Nt.push(["readOnly",At([...ge.map(se=>[se,eo(T[se])]),...U.length>0?[["relations",At(U.map(se=>[se,g(R,se)]))]]:[]])]),At(Nt)},k=R=>Object.values(R.relations??{}).some(A=>Ce(A).some(T=>T.owned===!0&&r.has(i(T.id)?.type??""))),S=R=>{let A=t[R];return r.has(A.type)&&k(A)},I=(R,A)=>{let T=new Map(R.map(Y=>{let U=cf(a(Y)??"");return[Y,mf(U)?cf(t[Y].type):U]})),N=Y=>{let U=new Map;for(let ge of Y)U.set(ge,(U.get(ge)??0)+1);return U},q=N(T.values()),X=new Map(R.map(Y=>{let U=T.get(Y),ge=mf(U)||A.has(U)||(q.get(U)??0)>1;return[Y,ge?[U,Y.slice(0,Lj)].filter(Boolean).join("-"):U]})),me=N(X.values());return new Map(R.map(Y=>{let U=X.get(Y);return[Y,(me.get(U)??0)>1?[T.get(Y),Y].filter(Boolean).join("-"):U]}))},x=R=>{let A=d(R);return A===void 0?t[R].type:`${A} (${t[R].type})`},E=(R,A,T,N,q)=>{let X=[],me=h(R,U=>X.push(U));s.push({path:nd.join(A,T),text:$a(me,N)});let Y=I(X,q);u++;try{for(let U of X){let ge=Y.get(U);S(U)?E(U,nd.join(A,ge),jE,x(U),new Set):s.push({path:nd.join(A,`${ge}.yaml`),text:$a(h(U),x(U))})}}finally{u--}},M=`${e.modelName===void 0?"A ModelDesk model":ae(w(e.modelName))}. Edit these files, then run 'modeldesk model diff' and 'modeldesk model push'.`;E(e.rootId,"",xt,M,new Set([xt.replace(/\.yaml$/,"")]));let v=[];for(let R of Object.keys(t).sort(ne))o.has(R)||(o.add(R),v.push([R,h(R)]));let C=I(v.map(([R])=>R),new Set);for(let[R,A]of v)s.push({path:nd.join(FE,`${C.get(R)}.yaml`),text:$a(A,x(R))});return s.sort((R,A)=>ne(R.path,A.path))},od=e=>[{path:ct,text:`${JSON.stringify({rootElementId:e.rootId,elements:Object.fromEntries(Object.keys(e.elements).sort(ne).map(t=>[t,e.elements[t]]))},null,2)}
250
- `}];var Pj=async(e,t,n)=>{if(n.head===t.baseCommitId||t.baseRootRevision===Wn(n))return n.read;try{return await e.api().models.get(t.model.id,{commit:t.baseCommitId})}catch(r){if(r instanceof H&&(r.status===404||r.status===400))return;throw r}},qR=e=>`${e.slice(0,3).map(F).join(", ")}${e.length>3?", \u2026":""}`,Dj=(e,t)=>{if(t.collisions.length!==0)throw new p(`The pull would overwrite ${t.collisions.length} file(s) in ${F(e)} that the workspace did not write (${qR(t.collisions)}), so nothing was written.`,{type:"workspace-collision",hint:"Move those files away, or pull into another directory.",details:{collisions:t.collisions}})},_j=(e,t)=>{t.length!==0&&e.warn(`${t.length} file(s) the model no longer needs were edited since the workspace wrote them, so they were left in place (${qR(t)}). Remove them, or the next diff reads them.`)},jj=async(e,t,n,r)=>{let s;try{s=cn(t,n)}catch(i){if(i instanceof Ge)return{changed:!0,reason:`its files do not parse (${i.reason})`};throw i}let o=i=>Tt(Ot(i),s).ops.length;try{if(o(r.read)===0)return{changed:!1};let i=await Pj(e,n,r);if(i===void 0)return{changed:!0,reason:`its base commit ${n.baseCommitId} can no longer be read`};let a=o(i);return a>0?{changed:!0,reason:`it holds ${a} local change(s)`,ops:a}:{changed:!1}}catch(i){if(i instanceof ut)return{changed:!0,reason:`its files change what cannot be pushed (${i.reason})`};throw i}},BR=O({path:["model","pull"],effect:"local",summary:"Pull a model into a file workspace to edit",description:"Writes the model as a tree of YAML files, one element per file with what it owns inline (the format is described in the CLI's README), and records what it pulled in .modeldesk/workspace.json: the branch (@<branch>, or your working branch), which 'modeldesk model diff' and 'modeldesk model push' then address by its id, and the head the files reflect. It pulls what you write to: your draft on the branch, otherwise the branch head, so your edits build on what you staged. A draft the branch moved past is pulled as it stands, with a warning naming 'modeldesk draft rebase'. A commit is no ref to pull: a workspace tracks a branch to push to. Pulling again updates the files in place and moves the workspace's base to the current head, on the branch the address names; a workspace with local changes is refused unless --force, which discards them. --format json writes the element map exactly as the server serves it, in one model.json.",positionals:[_(be),Dr],flags:{force:{type:"boolean",description:"Pull over local changes in the workspace, discarding them."},format:{type:{enum:["yaml","json"]},description:"yaml (the default, or the workspace's format on a re-pull): the editable file tree; json: the lossless element map in one model.json."}},dryRun:!0,prepare:Rf,examples:["modeldesk model pull <model> shacl-workspace","modeldesk model pull <model>@agent/tidy-names . --format json"],run:e=>ee(async()=>{let{dir:t,state:n}=Sf(e),r=e.args.model,s=await oe(e,r.model).id();if(n!==void 0&&n.model.id!==s)throw new p(`${F(t)} is a workspace of another model (${F(n.model.name)}).`,{hint:"Pull into another directory."});let o=await ot(e,r),i=_r(o);if(n!==void 0&&!e.flags.force){let u=await jj(e,t,n,o);if(u.changed)throw new p(`The workspace in ${F(t)} is not pulled over: ${u.reason}.`,{exitCode:b.Failure,hint:"Push them with 'modeldesk model push', or pass --force to discard them. 'modeldesk model diff' shows them.",details:{...u.ops!==void 0&&{changes:u.ops}}})}let a=Va(o.read),d=e.flags.format??n?.format??"yaml",l=d==="json"?od(a):sd(a),c=Oa(t,l,n?.files??{});Dj(t,c);let m=e.instance().host;e.globals.dryRun||(Na(t,l,c),ln(t,{schemaVersion:$t,host:m,model:o.model,branch:{id:o.branch.id,name:o.branch.name},baseCommitId:o.head,baseRootRevision:Wn(o),format:d,files:no(l)}));let f=Ua(o);return f!==void 0&&e.warn(`${f} The files hold what the draft holds: run 'modeldesk draft rebase', then pull again.`),_j(e,c.kept),{result:{model:o.model,ref:i,dir:t,format:d,baseCommitId:o.head,...n!==void 0&&{previousBaseCommitId:n.baseCommitId},elements:Object.keys(o.read.elements).length,files:{written:c.written,removed:c.removed,kept:c.kept,unchanged:c.unchanged.length},...e.globals.dryRun&&{dryRun:!0},url:W(e.instance(),{kind:"model",modelId:s})}}}),render:e=>[`${e.dryRun?"Would pull":"Pulled"} ${Qe(e.ref,w(e.model.name))} into ${F(e.dir)}: ${e.elements} elements as ${e.format==="json"?"model.json":"YAML files"}.`,`${e.dryRun?"Would write":"Wrote"} ${e.files.written.length} file(s), ${e.dryRun?"would remove":"removed"} ${e.files.removed.length}, left ${e.files.unchanged} unchanged.`,...e.files.removed.map(t=>` removed ${F(t)}`),...e.files.kept.map(t=>` kept ${F(t)} (edited since it was written)`),`base: ${e.baseCommitId}`+(e.previousBaseCommitId!==void 0&&e.previousBaseCommitId!==e.baseCommitId?` (was ${e.previousBaseCommitId})`:""),`url: ${e.url}`].join(`
251
- `)});var UR=e=>({number:e.number,opCount:e.ops.length,firstOp:e.ops[0]??0,actions:e.actions.length,bytes:e.bytes,...e.dependsOn.length>0&&{dependsOn:e.dependsOn}}),HR=(e,t,n)=>n>1?`${e} (${t.number}/${n})`:e,Fj=(e,t,n)=>{let r=[],s=o=>{if("new"in o.element){let i=n.elements.get(o.element.new);i!==void 0&&r.push({location:i.location,id:t.ids.get(o.element.new)})}Object.values(o.children??{}).flat().forEach(s)};for(let o of e.ops){let i=t.ops[o];i.op==="create"&&s(i.element)}return r},Uf=e=>e.length===0?"Nothing was staged.":`${GR(e)}: 'modeldesk model diff' shows only what is left.`,GR=e=>{let t=e.length===1?"it":"them";return`${P(e.length,"earlier change")} landed and the workspace records ${t}`},qj=e=>Array.isArray(e.details.landed)?e.details.landed:[],VR=e=>Array.isArray(e.details.errors)?e.details.errors:[],Bj=(e,t,n,r)=>{let s=VR(e),o=s.some(a=>a.code==="invalid-position")?" A relation the metamodel orders alphabetically takes no position: list the element at its end.":"",i=s.some(a=>a.code==="chain-too-long");return new p(`${e.reason} ${Uf(n)}${o}`,{...t,hint:i?`Commit the draft first ('modeldesk draft commit ${r}', or in the app), then push again.`:void 0})},Wj=(e,t,n)=>{let r=n.length===0?"No earlier change of this push landed.":`${GR(n)}.`;return new p(`${e.reason} ${r}`,{...t,hint:e.hint})},Uj=(e,t)=>{if(!(e instanceof p)||e.type==="workspace-not-recorded")return e;let n=qj(e),r={type:e.type,requestId:e.requestId,details:e.details,exitCode:e.exitCode};return e.type==="draft-head-conflict"?new p(`${e.reason} ${Uf(n)}`,{...r,hint:"Re-pull the workspace with 'modeldesk model pull' and push what is left again."}):e.type==="change-validation-failed"&&e.exitCode===b.Validation?Bj(e,r,n,t):e.exitCode===b.Transient?Wj(e,r,n):new p(`${e.reason} ${Uf(n)}`,{...r,hint:e.hint})},WR=(e,t,n,r,s,o)=>{let[i]=n.slice(-1),a=t>1?`Change ${e.number} of ${t}`:"The change";return new p(`${a} landed as ${i.commitId}, but ${s}. The workspace's base stays at ${r}, so it reads as stale and nothing more was pushed.`,{type:"workspace-not-recorded",hint:"Copy aside any edits you have not pushed, then re-pull with 'modeldesk model pull --force' to bring the files to what landed.",details:{...o,chunk:e.number,chunks:t,landed:n,baseCommitId:r}})},Hj=(e,t,n,r)=>e===void 0?Do("cli",r,`${t}:${n.number}`):Qr("cli",r,e,n),Gj=(e,t)=>{let{dryRun:n}=e.globals,{message:r,plan:s,commit:o}=e.flags,i=e.flags["request-id"];if(n&&s!==void 0)throw $("--dry-run makes a plan and --plan pushes one; pass one of them.",t);if(n&&o)throw $("--commit has nothing to commit under --dry-run, which stages nothing.",t);if(e.flags["with-staged"]&&!o)throw $("--with-staged goes with --commit.",t);if(s!==void 0&&!/^[0-9a-f]{12,64}$/.test(s))throw $("--plan takes the hash a dry run printed (at least its first 12 characters).",t);Sn(r,t),i!==void 0&&lc(i,t)},Vj=(e,t,n)=>new p(`The workspace is stale: ${n} moved from ${e.baseCommitId} to ${t.head} since it was pulled. Nothing was staged.`,{exitCode:b.Conflict,type:"workspace-stale",hint:"Re-pull with 'modeldesk model pull' (--force discards local edits) and edit on top of what changed; a push now would revert it.",details:{baseCommitId:e.baseCommitId,headCommitId:t.head}}),Kj=(e,t)=>{let n=Ua(e);if(n===void 0)return[];if(t)throw new p(`${n} It cannot be committed as it stands, so nothing was staged.`,{exitCode:b.Conflict,type:"draft-baseline-stale",hint:"Run 'modeldesk draft rebase', re-pull the workspace, then push again.",details:{baselineCommitId:e.draft?.baselineCommitId,branchHeadCommitId:e.branch.head}});return[`${n} Committing it needs 'modeldesk draft rebase' first; re-pulling does not help.`]},Yj=async(e,t,n,r)=>{let{draft:s,branch:o}=t;er(e,`${e.commandName} --commit`,{kind:"model",id:n,name:r},o),pc(s?.changeCount??0,e.flags["with-staged"]),s!==void 0&&await De(e,Vo(e,n),s,{scope:{kind:"all"},action:`Committing your draft of ${r}`,anySurface:!1,override:hc(n)})},zj=(e,t)=>{if(t!==void 0&&!e.hash.startsWith(t))throw new p("The workspace no longer matches the plan: its operations or its base changed since.",{exitCode:b.Validation,type:"plan-mismatch",hint:"Run the dry run again and review the new plan.",details:{expected:t,planHash:e.hash}})},Jj=(e,t,n)=>{let r=t>1?` (${t}/${t})`.length:0;if(e.length+r>2e3)throw $(`The message (-m) is ${e.length} characters long; the push stages ${t} changes, each message suffixed (n/${t}), so it holds at most ${2e3-r}.`,n)},Xj=(e,t,n)=>{let r=e?.changeCount??0;if(r+t>Ke)throw new p(`The push needs ${P(t,"change")} and your draft of ${n} holds ${r} of the ${Ke} a draft can. Nothing was staged.`,{exitCode:b.Validation,type:"draft-change-cap",hint:"Commit the draft first ('modeldesk draft commit', or in the app).",details:{changes:t,changeCount:r,limit:Ke}})},Qj=async e=>{let t=lo(e),{dir:n}=t,{state:r}=t,{dryRun:s}=e.globals,{message:o,plan:i,commit:a}=e.flags,d=`modeldesk ${e.commandName} --help`;Gj(e,d);let l=r.model.id,c=W(e.instance(),{kind:"model",modelId:l}),m=await co(e,n,r),f=w(m.model.name),g=_r(m),u=Wa(n,r,m);if(u.kind==="stale")throw Vj(r,m,Qe(g,f));let h=u.kind==="rebound"?{from:u.from}:void 0;h&&!s&&(r=Ga(n,r,m));let y=Kj(m,a);a&&await Yj(e,m,l,f);let k=Ot(m.read),S=cn(n,r),I=_a(k,S,{modelId:l,baseCommitId:m.head});zj(I,i),y.push(...I.warnings),y.forEach(E=>e.warn(E));let x=I.chunks.length;return Jj(o,x,d),Xj(m.draft,x,f),{context:e,dir:n,modelId:l,state:r,target:m,name:f,workspace:S,plan:I,deletes:I.ops.flatMap(E=>E.op==="delete"?[E.element]:[]),base:{model:m.model,ref:g,dir:n,message:o,baseCommitId:m.head,...h&&{rebound:h},planHash:I.hash,ops:I.ops,counts:ja(I.ops),labels:Fa(I.ops,k.labels),warnings:y,url:c}}},KR=({context:e,deletes:t})=>t.length>0&&!e.flags["allow-delete"],Zj=async(e,t)=>{let{context:n,modelId:r,target:s,plan:o,base:i}=e,a=UR(t);if(t.number>1&&t.dependsOn.length>0)return{...a,validation:"client-checked"};let d={actions:t.actions,draftHeadId:s.head,changeRequestId:Qn("cli",n.env),message:HR(i.message,t,o.chunks.length),dryRun:!0,...s.draft===void 0?{branchId:s.branch.id}:{}};try{let{envelope:l}=await n.api().drafts.model.stage(r,d);return{...a,validation:"server",verdict:"valid",affected:{changed:Object.keys(l.revisions).sort(),removed:l.removedElementIds??[]}}}catch(l){if(l instanceof p&&l.type==="change-validation-failed")return{...a,validation:"server",verdict:"refused",errors:VR(l)};throw l}},eF=async e=>{let{target:t,plan:n,base:r}=e,s=[];for(let a of n.chunks)s.push(await Zj(e,a));let o=s.some(a=>a.verdict==="refused");return{result:{...r,dryRun:!0,headCommitId:t.head,chunks:s,staged:0},...(o||KR(e))&&{exitCode:b.Validation}}},tF=e=>new p(`The workspace deletes ${P(e.length,"element")} (${e.slice(0,5).join(", ")}${e.length>5?", \u2026":""}), and a push deletes only with --allow-delete. Nothing was staged.`,{exitCode:b.Validation,type:"deletes-not-allowed",hint:"Review them with 'modeldesk model diff'; restore a file removed by mistake, or pass --allow-delete.",details:{deletes:e}}),nF=({dir:e,plan:t,workspace:n},r)=>(s,o)=>{let{landed:i}=r,a=t.chunks.length,d=t.chunks[o];i.push({number:d.number,changeRequestId:s.chunk.changeRequestId,commitId:s.commitId});let l=dC(e,Fj(d,t,n));if(l.length>0)throw WR(d,a,i,r.recorded.baseCommitId,`the ids of ${P(l.length,"new element")} could not be written into the files (${F(l[0].location.file)}: ${l[0].reason})`,{missing:l.map(m=>({file:m.location.file,at:mt(m.location.path),id:m.id,reason:m.reason}))});let c={...r.recorded,baseCommitId:s.commitId,baseRootRevision:s.envelope?.rootElement.revisionId};try{ln(e,c)}catch(m){throw WR(d,a,i,r.recorded.baseCommitId,`workspace.json could not be written (${F(m.message)})`,{})}r.recorded=c},rF=async(e,t)=>{let{context:n,target:r,plan:s,base:o}=e,i=s.chunks.length,a=n.flags["request-id"],d=a===void 0?"":` with --request-id ${a}`;try{return await gi(n,r,{chunks:s.chunks.map(l=>({actions:l.actions,message:HR(o.message,l,i),changeRequestId:Hj(a,s.hash,{number:l.number,total:i},n.env)})),stableIds:!1,persisted:nF(e,t),retryHint:`Run 'modeldesk model diff': a stale workspace means it landed (re-pull, then push what is left); otherwise push again${d}.`})}catch(l){throw Uj(l,r.model.id)}},sF=async(e,t,n)=>{let{context:r,dir:s,modelId:o,target:i,name:a,base:d}=e;if(t.draftId===void 0)throw new p(`Your draft of ${a} holds no staged change, so there is nothing to commit.`,{type:"nothing-to-commit"});let l=await ss(r,o),{landing:c,recovered:m}=await mr(r,l,{targetRefId:i.branch.id,baselineCommitId:i.draft?.baselineCommitId??i.head},{message:d.message,expectedDraftHeadId:t.head}),f=c.commit.id;n.recorded={...n.recorded,baseCommitId:f},ln(s,n.recorded);let g=ur(c,i.model),u={...fr(c),recovered:m,...g===void 0?{}:{next:g},url:W(r.instance(),{kind:"commit",modelId:o,commitId:c.commit.id})};return{headNow:f,commit:u}},oF=(e,t,n)=>{try{return Tt(Ot(e.read),wf(t,n)).ops.length>0}catch{return!0}},iF=(e,t,n,r,s)=>{let o=Va(n.read),i=r.format==="json"?od(o):sd(o),a=Oa(t,i,s);return a.collisions.length===0?(Na(t,i,a),{manifest:no(i),refreshed:!0}):(e.warn(`The files stay as pushed: rewriting them from the server would overwrite files the workspace did not write (${a.collisions.slice(0,3).map(F).join(", ")}).`),{manifest:s,refreshed:!1})},aF=async(e,t,n)=>{let{context:r,dir:s}=e,{recorded:o}=t,i=await co(r,s,o);if(i.head!==n)return r.warn("The target moved right after the push, so the files stay as pushed; re-pull before editing on."),!1;let a=yf(s,o),d={manifest:no(a),refreshed:!1};return oF(i,a,o.format)&&(d=iF(r,s,i,o,d.manifest)),ln(s,{...o,files:d.manifest,baseRootRevision:Wn(i)}),d.refreshed},dF=async e=>{let{context:t,state:n,plan:r,base:s}=e;if(KR(e))throw tF(e.deletes);let o={recorded:n,landed:[]},i=await rF(e,o),a=i.head,d=i.chunks.map((u,h)=>({...UR(r.chunks[h]),changeRequestId:u.chunk.changeRequestId,commitId:u.commitId})),l;t.flags.commit&&({headNow:a,commit:l}=await sF(e,i,o));let m=(o.landed.length>0||l!==void 0)&&await aF(e,o,a),f=Object.fromEntries(r.ids);return{result:{...s,headCommitId:a,chunks:d,staged:o.landed.length,...Object.keys(f).length>0&&{createdIds:f},...l&&{commit:l},...m&&{refreshed:m}}}},lF=e=>ee(async()=>{let t=await Qj(e);return e.globals.dryRun?eF(t):dF(t)}),cF=e=>e.validation==="client-checked"?`client-checked: it stands on change ${(e.dependsOn??[]).join(", ")} (an element it creates, updates, moves or deletes, or a list it changes that this change places into), which a dry run does not keep, so the server validates it when it is staged`:e.verdict==="valid"?`validated by the server: ${e.affected?.changed.length??0} element(s) changed, ${e.affected?.removed.length??0} removed`:`REFUSED by the server: ${(e.errors??[]).map(t=>w(t.message)).join("; ")}`,mF=(e,t)=>{let n=[`Plan against ${Qe(e.ref,t)} at ${e.baseCommitId}: `+(e.ops.length===0?"nothing to push.":`${P(e.ops.length,"operation")} (${ao(e.counts)}) in ${P(e.chunks.length,"change")}.`)],r=qa(e.ops,e.labels);for(let s of e.chunks){let o=e.chunks.length>1?`Change ${s.number}/${e.chunks.length}`:"The change";n.push(`${o} (${P(s.actions,"action")}): ${cF(s)}.`,...r.slice(s.firstOp,s.firstOp+s.opCount).map(i=>` ${i}`))}return e.ops.length>0&&(n.push(`plan: ${e.planHash}`),e.counts.delete>0&&n.push("The plan deletes; push it with --allow-delete."),n.push(`Push exactly this plan: modeldesk model push ${F(e.dir)} -m <message> --plan ${e.planHash.slice(0,16)}`+(e.counts.delete>0?" --allow-delete":""))),n.join(`
252
- `)},fF=e=>{let t=w(e.model.name);if(e.dryRun)return mF(e,t);let n=[];return e.rebound&&n.push(Ha(e.ref,t,e.rebound.from,e.baseCommitId)),e.staged===0&&e.commit===void 0?n.push(`Nothing to push: the workspace matches ${Qe(e.ref,t)}.`):e.staged>0&&n.push(`Staged ${P(e.staged,"change")} (${ao(e.counts)}) in your draft of ${t}: ${w(e.message)}`,...e.chunks.map(r=>` change ${r.number}/${e.chunks.length}: ${r.commitId} (${P(r.actions,"action")})`)),e.commit?n.push(...Es(e.commit)):e.staged>0&&n.push("Review and commit it in the app, where the changes panel shows it."),(e.staged>0||e.commit)&&n.push(`Workspace base: ${e.headCommitId}${e.refreshed?" (files refreshed from the server)":""}.`),n.push(`url: ${e.url}`),n.join(`
253
- `)},YR=O({path:["model","push"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a workspace's changes on your draft",description:"Stages what 'modeldesk model diff' shows on your draft on the workspace's branch (opening the draft there when you hold none), as validated changes carrying the message, cut into as many changes as the server bounds need (1000 actions or 8 MiB each), each message suffixed (n/m). A workspace whose target moved since it was pulled is refused (exit 5) before anything is written. --dry-run has the server validate each change without keeping it and prints the plan with its hash; --plan <hash> then pushes only that exact plan. After each change lands the workspace records it (new ids written into the files, the base moved on), so a push stopped by a refusal leaves a workspace whose diff shows only what is left. Deletes need --allow-delete. --commit then lands the draft as one commit, under the same rules as draft commit.",positionals:[Dr],flags:{...zo,plan:{type:"string",placeholder:"hash",description:"Push only if the plan hash (or at least its first 12 characters) still matches."},"allow-delete":{type:"boolean",description:"Allow the push to delete the elements the workspace dropped."},"request-id":{type:"string",placeholder:"id",description:"The request id to stage under: a cli-\u2026 id this session minted is sent as given, any other id seeds a cli-\u2026 id derived from it (for each change of a push of several, from it and the change number). Derived from the plan hash when left out. Unlike on an el write it is not looked up: a change that landed leaves the workspace stale, which is what stops a push staging it twice."},commit:{type:"boolean",description:"Land the draft after staging, with the same message. Under an agent host this is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1 or the draft aims at a branch named agent/<topic>."},...dc},dryRun:!0,prepare:Ba,examples:['modeldesk model push -m "Add the severity binding" --dry-run','modeldesk model push -m "Add the severity binding" --plan 3f2a9c1e5b7d'],run:lF,render:fF});var Hf=10,uF=e=>({id:e.id,name:e.name,commitId:e.commitId,createdAt:e.createdAt,...e.description?{description:e.description}:{}}),zR=e=>e instanceof H&&(e.status===403||e.status===404),JR=e=>({items:e.slice(0,Hf).map(uF),truncated:e.length>Hf}),pF=async(e,t,n)=>{if(n)try{let r=await e.metamodelModels.versions(t);return JR([...r].sort((s,o)=>Date.parse(o.createdAt)-Date.parse(s.createdAt)))}catch(r){if(!zR(r))throw r}try{return JR((await e.models.versions(t,{limit:Hf+1})).items)}catch(r){if(zR(r))return;throw r}},hF=({name:e,pin:t})=>{let n=t?.versionName??t?.versionRef??(t?.commitId?`commit ${t.commitId}`:void 0);return n===void 0?w(e):`${w(e)} (pinned to ${w(n)})`},gF=e=>{if(e===void 0)return"unknown";let t=e.name?` ${e.id}`:"";return`${w(e.name??e.id)} (${e.type.toLowerCase()}${t})`},XR=(e,t)=>{let n=t.items.map(s=>{let o=s.pin?.versionRef??(s.pin?"@HEAD":void 0),i=s.pin?.versionName&&s.pin.versionName!==o?` (release ${s.pin.versionName})`:"";return[w(s.name),s.kind.toLowerCase(),o?w(`pinned ${o}${i}`):"",s.modelId??""]}),r=[...j(n,{indent:" "}),...t.hiddenCount>0?[` and ${t.hiddenCount} you cannot read`]:[]];return[`${e}:`,...r.length===0?[" none"]:r]},yF=e=>e.kind==="draft"?e.branch:e.kind==="branch"?e:void 0,wF=({latest:e,changesSinceRelease:t,changesCapped:n})=>{let r=`${t}${n?"+":""} change${t===1?"":"s"}`;return e?`${e.name} (${e.createdAt}), ${r} since`:`none yet, ${r} so far`},bF=(e,t)=>e===void 0?[" not readable with your access"]:t.length===0?[" none"]:j(t,{indent:" "}),kF=e=>{let{head:t}=e.branch,n=t.message?`: ${t.message}`:"",{overview:r}=e,s=[["id:",e.id],["kind:",e.kind],...e.metamodel===void 0?[]:[["metamodel:",hF(e.metamodel)]],["owner:",gF(e.owner)],["branch:",`${w(e.branch.name)} at ${t.id}`],["head:",w(`${t.createdAt} by ${t.author.name??t.author.id}${n}`)],["release:",wF(r.release)],...r.instanceModelCount===void 0?[]:[["instances:",`${r.instanceModelCount} models`]],["url:",e.url]],o=r.signals.map(a=>[a.tone,a.code,w(a.subject?.name??""),Object.entries(a.detail).map(([d,l])=>`${d} ${String(l)}`).join(", ")]),i=(e.versions?.items??[]).map(a=>[a.name,a.createdAt,a.commitId]);return[w(e.name),$e(e.ref,e),...j(s,{indent:" "}),"",`Overview of branch ${w(r.ref.name)}:`,...XR("Depends on",r.dependsOn),...XR("Depended on by",r.dependedOnBy),"Signals:",...o.length===0?[" none"]:j(o,{indent:" "}),"Versions:",...bF(e.versions,i),...e.versions?.truncated?[" (older versions not shown)"]:[]].join(`
254
- `)},QR=O({path:["model","show"],effect:"read",summary:"Show a model's identity, dependencies and releases",description:"Shows a model's metamodel and its pin, owner, branch head and latest release, the models it depends on and that depend on it (with their pins and staleness signals), and its newest releases. The identity and the head are read at the ref; the overview and the releases are always main's, and the result says so.",positionals:[_(ar)],examples:["modeldesk model show <model>","modeldesk model show <model>@feat/shapes","modeldesk model show <model> --json"],run:async e=>{let t=oe(e,e.args.model.model),n=e.api(),r=await Z(e,e.args.model,ar),{id:s}=r,[o,i,a]=await Promise.all([r.ref.kind==="branch"&&r.ref.branch.main?t.identity():n.models.identity(s,st(r.ref)),n.models.overview(s),n.accessTokenClaims()]),d=i.instanceModelCount===void 0?"model":"metamodel",l=await pF(n,s,d==="metamodel"&&qt(a)),{branch:c}=o,m=de(r),f=yF(m);return{result:{id:o.id,name:o.name,kind:d,...i.metamodel===void 0?{}:{metamodel:{id:i.metamodel.modelId,name:i.metamodel.name,...i.metamodel.pin?{pin:i.metamodel.pin}:{}}},...o.owner?{owner:o.owner}:{},createdAt:o.createdAt,updatedAt:o.updatedAt,ref:m,branch:{id:f?.id??c.id,name:f?.name??c.name,head:{id:c.head.id,createdAt:c.head.createdAt,author:c.head.createdBy,...c.head.message?{message:c.head.message}:{}}},overview:{ref:{kind:"branch",id:r.main.id,name:r.main.name},release:i.release,dependsOn:i.dependsOn,dependedOnBy:i.dependedOnBy,signals:i.signals,...i.instanceModelCount===void 0?{}:{instanceModelCount:i.instanceModelCount}},...l===void 0?{}:{versions:l},url:W(e.instance(),{kind:"model",modelId:o.id})}}},render:kF});var EF=e=>e.subtreeAt!==void 0?` [multi-owned, listed under ${w(e.subtreeAt)}]`:e.multiOwned?" [multi-owned]":"",CF=e=>e.map(t=>`${" ".repeat(t.depth-1)}${t.label===void 0?"(no label)":w(t.label)} (${t.type})`+EF(t)),ZR=O({path:["model","tree"],effect:"read",summary:"Show a model's element tree",description:"Shows the elements of a model as a tree, one line per element with its label and type. An element owned twice appears under each owner, marked. The platform's internal `@` elements are left out, as in the app, unless --internal is passed. Without a ref, reads your draft while it holds staged changes; --json carries every row's id, its label path (usable wherever an element is addressed) and what was read as ref.",positionals:[_(wt)],flags:{depth:{type:"number",placeholder:"n",description:"Show this many levels below the model root."},type:{type:"string",placeholder:"type",description:"Show only elements of this type, with their ancestors for context."},...ir},listing:{narrowHint:"Pass --depth or --type to narrow the tree."},examples:["modeldesk model tree <model> --depth 2","modeldesk model tree <model>@main --type NodeShape --json","modeldesk model tree <model>@feat/shapes"],run:async e=>{let{depth:t,type:n,internal:r}=e.flags;if(t!==void 0&&(!Number.isInteger(t)||t<1))throw $(`--depth must be a positive whole number, got ${t}.`,"modeldesk model tree --help");let{model:s,ref:o,read:i,tree:a}=await dr(e,e.args.model,wt),d=n===void 0?void 0:new Set([Ri(Cr(i),n,r)]),l=await e.list(nt(a,{maxDepth:t,types:d,internal:r}));return{result:{model:s,ref:o,rootElementId:a.rootId,...l}}},render:e=>[$e(e.ref,e.model),...e.items.length===0?["No elements."]:CF(e.items)].join(`
255
- `)});import{rmdirSync as RF,rmSync as SF,writeFileSync as vF}from"node:fs";import{dirname as IF,join as eS,posix as id}from"node:path";var tS=O({path:["note","add"],effect:"local",summary:"Create an empty note file for an element and add it to the repo's notes.json",description:"Finds the element by name in the last pull's manifest (or by --element), creates an empty note file at the path the next pull reads it from, and records it in .modeldesk/notes.json. A name several elements share is asked about at a terminal and refused elsewhere, listing their ids. The after note of the model or a package needs --heading. Nothing is overwritten, and nothing is written when the command refuses.",positionals:[{name:"name",type:{list:"string"},description:"The element's title; a name of several words may be passed unquoted."}],flags:{slot:{type:{enum:xe},default:"intro",description:"The slot the note fills: intro, after the element's heading, or after, after its content."},heading:{type:"string",placeholder:"text",description:"The heading the after note of the model or a package comes under (required there)."},dir:{type:"string",placeholder:"dir",description:"The folder to create the note in (default: notesDir in the repo config, or md-notes/)."},element:{type:"string",placeholder:"id",description:"The element's id, which decides when a name is given too."},stack:{type:"string",placeholder:"id",description:"The content stack whose last pull is searched (default: MODELDESK_STACK or the repo config)."}},examples:["modeldesk note add Pand","modeldesk note add Domein Fundering --slot after --heading Afsluiting"],run:async e=>{let{flags:t,args:n}=e,r=Yn(e.cwd),{repoRoot:s}=r,o=Jr(Kr({stack:t.stack},e.env,r.config).stack,"stack",B.stack,"--stack"),i=t.slot,a=ii(s,o);if(a===void 0)throw new p("Run 'modeldesk bundle pull' first: note add finds the element in the last pull's manifest.");let d=ry(a),l=await TF(e,a,d,n.name.join(" "),t.element),c=ad(l),m=NF(l,i,c,t.heading),f=oi(o),g=r.config.notesDir??$o,u=LF(s,f,t.dir??g,l,i),h=eS(s,u),y=mi(s),k=y.entries.get(l.elementId);if($F(s,y,k,{slot:i,label:c}),xF(y,u),$n(h)!==void 0){let M=l.path!==void 0&&ci(g,f,l.path,i)===u;throw new p(PF(u,c,i,M))}Rt(y.path);let S=AF(h,u,m),I=new Map(y.entries),x=k===void 0?{...l.title===void 0?{}:{name:l.title},[i]:u}:{...k,[i]:u};I.set(l.elementId,x);try{fi(y.path,br(I))}catch(M){throw SF(h,{force:!0}),S(),M instanceof p?M:new p(`Could not write ${y.path}, so ${u} was not kept: ${et(M)}`)}return{result:{file:u,slot:i,elementId:l.elementId,...l.title===void 0?{}:{name:l.title},label:c,...m===void 0?{}:{heading:m}}}},render:({file:e,slot:t,label:n,heading:r})=>{let s=r===void 0?"":`, under the heading "${r}"`;return`Created ${e}, the ${t} note of ${n}${s}.`}}),$F=(e,t,n,{slot:r,label:s})=>{let o=n?.[r];if(o===void 0)return;let i=$n(eS(e,o))===void 0?"That file does not exist yet: create it":"Write in that file";throw new p(`${s} already has an ${r} note, ${o}. ${i}, or take the entry out of ${t.path} first.`)},xF=(e,t)=>{let n=[...e.entries].find(([,r])=>xe.some(s=>r[s]!==void 0&&id.normalize(r[s])===id.normalize(t)));if(n!==void 0)throw new p(`${e.path} already names ${t} as a note of ${n[1].name??n[0]}; pick another folder with --dir.`)},MF=e=>{for(let t of e.toReversed())try{RF(t)}catch{return}},AF=(e,t,n)=>{let r;try{r=Ka(IF(e))}catch(o){throw new p(`Could not create ${id.dirname(t)}: ${et(o)}`)}let s=()=>MF(r);try{vF(e,n===void 0?"":`${ui(n)}
210
+ `);if(l)for(let u of s.writes)c(` write ${u}
211
+ `)},_D=(e,t,n,r)=>{let o=e.print;for(let{file:s,elementId:i,slot:a,title:d}of n)o(` adopt ${s}: ${d??i} ${a}
212
+ `);for(let{title:s,slot:i,target:a}of t.substitutions){let d=typeof a=="string"?a:`${a.file} under the heading "${a.heading}"`;o(` fill ${s} ${i}: ${d}
213
+ `)}o(` slots removed: ${t.removedSlots}
214
+ `);for(let{elementId:s,from:i,to:a}of r)o(` rename ${s} in notes.json: ${i===void 0?"(no name)":`"${i}"`} -> "${a}"
215
+ `)};var jD=["STACK","TEMPLATE","NAME"],bb=J({path:["bundle","templates"],effect:"read",summary:"List a model's document templates",description:"Lists the stack/template pairs a model can be pulled as, one per document shape. A template slug is unique only within its stack, so bundle pull takes both.",flags:{model:{type:"string",placeholder:"id",description:"The model's UUID (default: MODELDESK_MODEL or the repo config)."},stack:{type:"string",placeholder:"id",description:"List only the templates of this content stack."}},listing:{narrowHint:"Pass --stack to list one content stack."},examples:["modeldesk bundle templates --model <model>","modeldesk bundle templates --stack respec --json"],run:async e=>{let t=Ci(e,{model:e.flags.model}),n=e.api(),r=await n.models.get(t.model),o=(r.metamodelExtensions??[]).map(m=>m.id),{items:s}=await n.metamodels.templates(r.metamodel.id,{metamodelExtensions:o}),i=e.flags.stack,a=s??[],d=a.filter(m=>!i||m.stack===i).map(m=>({stack:m.stack??"",template:m.key??m.id,name:m.name,id:m.id})),l=await e.list(d);return{result:{model:t.model,...i?{stack:i}:{},modelTemplateCount:a.length,...l}}},render:({items:e,stack:t,modelTemplateCount:n})=>{if(n===0)return"This model has no document templates.";if(e.length===0)return`No document templates for stack '${t}'.`;let r=e.map(o=>[o.stack,o.template,o.name]);return W([jD,...r]).join(`
216
+ `)}});var Xr=e=>({id:e.id,name:e.name,commitId:e.commitId,createdAt:e.createdAt,...e.description?{description:e.description}:{}}),er=e=>{let t=e.compiledMetamodel?.standardVersion??e.compiledExtension?.standardVersion,n=e.builtInElementModelCommitId;return{...Xr(e),...t?{standardVersion:t}:{},...n?{builtInCommitId:n}:{}}},it=async(e,t)=>om((await e.metamodelModels.versions(t)).map(er));var Qr=async(e,t,n)=>{let r;for(;;){let{items:o}=await e.models.versions(t,{limit:100,cursor:r}),s=o.find(a=>a.name===n);if(s!==void 0)return s.commitId;let i=o.at(-1)?.id;if(o.length<100||i===void 0||i===r)return null;r=i}},om=e=>[...e].sort((t,n)=>Date.parse(n.createdAt)-Date.parse(t.createdAt)||n.name.localeCompare(t.name)),Jo=(e,t)=>e.find(n=>t===void 0?n.standardVersion===void 0:n.name===t);var Ee="@HEAD",FD=e=>e.kind==="pin"||e.kind==="base-pin",Eb=e=>e.models.flatMap(t=>t.steps),im=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),qD=e=>{let t=e.hiddenDependents.filter(({count:o})=>o>0);if(t.length===0)return;let n=t.reduce((o,{count:s})=>o+s,0),r=t.map(({modelId:o,count:s})=>`${s} of ${e.models[o]?.name??o}`);throw new f(`${P(n,"model")} depending on the cascade's metamodels ${n===1?"is":"are"} hidden from you (${r.join(", ")}), so the cascade cannot plan ${n===1?"its":"their"} pins. Nothing was changed.`,{hint:"Run the cascade as a super-admin, who can read every metamodel-model.",details:{hiddenDependents:t}})},WD=e=>{let t=new Map(Object.keys(e.models).map(n=>[n,new Set]));for(let{modelId:n,targetId:r}of[...e.edges,...e.basePins])n!==r&&e.models[r]!==void 0&&t.get(n)?.add(r);return t},HD=(e,t,n)=>{let r=a=>[...a].map(d=>e.models[d]).sort(im)[0].id,o=[],s=new Map,i=r(n);for(;!s.has(i);)s.set(i,o.length),o.push(i),i=r([...t.get(i)??[]].filter(a=>n.has(a)));return[...o.slice(s.get(i)),i].map(a=>e.models[a].name)},BD=e=>{let t=WD(e),n=new Map([...t].map(([s,i])=>[s,new Set(i)])),r=[],o=()=>[...n].filter(([,s])=>s.size===0).map(([s])=>e.models[s]).sort(im).map(s=>s.id);for(let s=o();s.length>0;s=o()){let[i]=s;r.push(i),n.delete(i),n.forEach(a=>a.delete(i))}if(n.size>0){let s=HD(e,t,new Set(n.keys()));throw new f(`The metamodels depend on each other in a cycle, so there is no order to release them in: ${s.join(" \u2192 ")} (each depends on the next). Nothing was changed.`,{hint:"Remove one of the dependencies in the app, then run the cascade again.",details:{cycle:s}})}return r},sm=(e,t,n,r)=>e?t:n!==r?"stale":void 0,Cb=e=>{qD(e);let t=BD(e),n=u=>e.models[u],r=new Set,o=new Map,s=[],i=0,a=(u,y,w)=>{if(w===Ee)return sm(r.has(y.id),"target-moves",u.commitId,y.headCommitId);if(o.has(y.id)&&o.get(y.id)===w)return r.has(y.id)||u.commitId!==y.headCommitId?"release-moves":void 0;let E=y.releases.find(I=>I.name===w);return E===void 0?"unresolved":u.commitId!==E.commitId?"stale":void 0},d=(u,y)=>{let w=n(u.targetId),E=u.versionRef??Ee,I=a(u,w,E);if(I==="unresolved"){s.push({modelId:y.id,modelName:y.name,dependencyId:u.dependencyId,name:u.name,targetId:w.id,targetName:w.name,versionRef:E});return}let v={dependencyId:u.dependencyId,targetId:w.id,targetName:w.name,...u.newerRelease?{newerRelease:u.newerRelease}:{}};return I===void 0?{kind:"pin",name:u.name,...u.versionRef===void 0?{}:{versionRef:u.versionRef},commitId:u.commitId,...v}:{kind:"refresh-pin",step:++i,modelId:y.id,modelName:y.name,dependencyName:u.name,versionRef:E,legacy:u.versionRef===void 0,fromCommitId:u.commitId,reason:I,...v}},l=(u,y)=>{let w=n(u.targetId),E=sm(r.has(w.id),"base-moves",u.commitId,w.headCommitId);return E===void 0?{kind:"base-pin",dependencyId:u.dependencyId,name:w.name,targetId:w.id,targetName:w.name,commitId:u.commitId}:{kind:"refresh-base-pin",step:++i,modelId:y.id,modelName:y.name,dependencyId:u.dependencyId,baseId:w.id,baseName:w.name,fromCommitId:u.commitId,reason:E}},c=u=>{let y=r.has(u.id);if(!u.released||!y&&u.outdated===void 0)return;let w=Jo(u.releases,u.standardVersion);return o.set(u.id,w?.name??u.standardVersion),{kind:"re-release",step:++i,modelId:u.id,modelName:u.name,...u.standardVersion?{release:u.standardVersion}:{},inPlace:w!==void 0,...w?{releaseId:w.id,releaseName:w.name,fromCommitId:w.commitId,...w.builtInCommitId?{fromBuiltInCommitId:w.builtInCommitId}:{},...w.description?{description:w.description}:{}}:{},reason:y?"pins-move":"outdated",...u.outdated?{outdated:u.outdated}:{},...u.outdated==="SOURCE"||u.outdated==="BOTH"?{unreleasedEdits:!0}:{},...u.instanceModelCount===void 0?{}:{instanceModelCount:u.instanceModelCount}}},m=t.map(u=>{let y=n(u),w=[],E=[],I=$=>{$!==void 0&&(FD($)?E.push($):(w.push($),r.add(u)))};e.edges.filter($=>$.modelId===u&&e.models[$.targetId]!==void 0).sort(($,C)=>im({name:$.name,id:$.dependencyId},{name:C.name,id:C.dependencyId})).forEach($=>I(d($,y))),e.basePins.filter($=>$.modelId===u&&e.models[$.targetId]!==void 0).forEach($=>I(l($,y)));let v=c(y);return v!==void 0&&w.push(v),{id:u,name:y.name,role:y.role,...y.baseId?{baseId:y.baseId}:{},released:y.released,steps:w,current:E,...y.outdated?{outdated:y.outdated}:{},...y.instanceModelCount===void 0?{}:{instanceModelCount:y.instanceModelCount}}}),p=e.siblingPins.flatMap(u=>{let y=e.models[u.targetId],w=e.models[u.modelId];if(y===void 0||w===void 0)return[];let E=sm(r.has(y.id),"target-moves",u.commitId,y.headCommitId);return E===void 0?[]:[{modelId:w.id,modelName:w.name,dependencyId:u.dependencyId,targetId:y.id,targetName:y.name,commitId:u.commitId,reason:E}]}),h=n(e.baseId);return{base:{id:h.id,name:h.name},models:m,stepCount:i,staleSiblingPins:p,unresolvedPins:s,outsideDependents:e.outsideDependents.map(u=>({...u,targetName:e.models[u.targetId]?.name??u.targetId}))}};import{randomUUID as SL}from"node:crypto";var am=e=>{let t=new Map;for(let[n,r]of e)for(let o of r){let s=t.get(o.id);s===void 0?t.set(o.id,[n]):s.push(n)}return t};import{randomUUID as GD}from"node:crypto";var dm=(e,t)=>e.id===t.id&&e.relation===t.relation,la=e=>Object.values(e??{}).flat(),Rb=e=>Object.keys(e).some(t=>t!=="@@"),UD=(e,t)=>`${e}\0${t}`,kb=e=>{let t={...e.elements},n=new Map(Object.entries(e.elementIndexEntries).map(([R,S])=>[R,[...S.owners??[]]])),r=new Map;for(let[R,S]of n)for(let T of S)r.set(T.id,(r.get(T.id)??new Set).add(R));let o=new Set,s=R=>{let S=t[R];if(S===void 0||o.has(R))return S;let T={...S,...S.attributes&&{attributes:{...S.attributes}},...S.relations&&{relations:Object.fromEntries(Object.entries(S.relations).map(([O,M])=>[O,Object.fromEntries(Object.entries(M).map(([_,z])=>[_,[...z]]))]))}};return t[R]=T,o.add(R),T},i=(R,S)=>{let T=R.relations?.[S];if(!(T===void 0||R.relations===void 0)){for(let O of Object.keys(T))T[O].length===0&&delete T[O];Object.keys(T).length===0&&delete R.relations[S],Object.keys(R.relations).length===0&&delete R.relations}},a,d=(R,S,T)=>{a!==void 0&&a.set(R,(a.get(R)??new Set).add(UD(S,T)))},l=R=>{if(a===void 0){a=new Map;for(let[S,T]of Object.entries(t))for(let[O,M]of Object.entries(T.relations??{}))la(M).forEach(_=>d(_.id,S,O))}return a.get(R)??new Set},c=(R,S)=>{let T=n.get(R)??[];T.some(O=>dm(O,S))||(n.set(R,[...T,S]),r.set(S.id,(r.get(S.id)??new Set).add(R)))},m=(R,S)=>{let T=(n.get(R)??[]).filter(O=>!dm(O,S));n.set(R,T),T.some(O=>O.id===S.id)||r.get(S.id)?.delete(R)},p=(R,S,T)=>{let O=s(R);if(O===void 0)return;la(O.relations?.[S]).filter(_=>_.owned).forEach(_=>m(_.id,{id:R,relation:S}));let M=la(T);M.filter(_=>_.owned).forEach(_=>c(_.id,{id:R,relation:S})),M.forEach(_=>d(_.id,R,S)),O.relations??={},O.relations[S]=Object.fromEntries(Object.entries(T).map(([_,z])=>[_,[...z]])),i(O,S)},h=(R,S,T)=>{let O=s(R),M=O?.relations?.[S];if(O===void 0||M===void 0)return;let _=Object.keys(M).find(z=>M[z].some(me=>me.id===T));if(_!==void 0)return M[_].splice(M[_].findIndex(z=>z.id===T),1),i(O,S),_},u=(R,S,T,O)=>{let M=s(R.id);if(M===void 0)return;M.relations??={};let _=M.relations[R.relation]??{},z=Rb(_)?T:"@@";if(z===void 0||z==="@@"&&Rb(_))return;M.relations[R.relation]=_;let me=_[z]??=[];me.splice(O??me.length,0,S),d(S.id,R.id,R.relation)},y=(R,S)=>{let T=R.id;t[T]={id:T,type:R.type,...R.attributes&&{attributes:R.attributes},...R.relations&&{relations:R.relations}},o.delete(T);for(let[O,M]of Object.entries(R.relations??{}))la(M).forEach(_=>d(_.id,T,O));c(T,S),u(S,{id:T,owned:!0},void 0);for(let[O,M]of Object.entries(R.ownedElements??{}))M.forEach(_=>y(_,{id:T,relation:O}))},w=(R,S)=>{let T=s(R);if(T!==void 0){for(let[O,M]of Object.entries(S.attributes??{}))T.attributes??={},M.length===0?delete T.attributes[O]:T.attributes[O]=M;for(let[O,M]of Object.entries(S.relations??{}))p(R,O,M)}},E=({elements:R,targetParent:S,position:T})=>{for(let{id:O,parent:M}of R){let _=dm(M,S),z=(t[M.id]?.relations?.[M.relation]?.["@@"]??[]).findIndex(Y=>Y.id===O),me=h(M.id,M.relation,O);m(O,M),c(O,S);let te=_&&T!==void 0&&z!==-1&&T>z?T-1:T;u(S,{id:O,owned:!0},me,te)}},I=R=>{let S=new Set(R),T=[...S];for(let O=T.pop();O!==void 0;O=T.pop())for(let M of r.get(O)??[])!S.has(M)&&(n.get(M)??[]).every(_=>S.has(_.id))&&(S.add(M),T.push(M));return S},v=(R,S)=>{for(let T of l(R)){let[O,M]=T.split("\0"),_=S.has(O)?void 0:s(O),z=_?.relations?.[M];if(_!==void 0&&z!==void 0){for(let me of Object.keys(z))z[me]=z[me].filter(te=>te.modelId!==void 0||te.id!==R);i(_,M)}}},$=R=>{let S=I([R]);for(let T of S){for(let O of r.get(T)??[])(n.get(O)??[]).filter(M=>M.id===T).forEach(M=>m(O,M));v(T,S),a?.delete(T),delete t[T],o.delete(T),n.delete(T),r.delete(T)}},C=({relation:R,targetElementId:S,addSourceElementIds:T=[],removeSourceElementIds:O=[]})=>{for(let M of T)u({id:M,relation:R},{id:S,owned:!1},void 0);for(let M of O)h(M,R,S)};return{element:R=>t[R],owners:R=>n.get(R)??[],cascade:I,apply:R=>{switch(R.type){case"ELEMENT_CREATE":R.creation.owner&&y(R.creation,R.creation.owner);return;case"ELEMENT_UPDATE":w(R.elementId,R.update);return;case"ELEMENT_MOVE":E(R.move);return;case"ELEMENT_DELETE":$(R.elementId);return;case"RELATION_MEMBERSHIP_UPDATE":C(R.update);return;default:return}},snapshot:()=>(o.clear(),{elements:{...t},elementIndexEntries:{...e.elementIndexEntries,...Object.fromEntries([...n].map(([R,S])=>[R,{...e.elementIndexEntries[R],owners:[...S]}]))}})}};var Je=["external","extensionLayer","lineage"],ca=class extends f{errors;constructor(t){let n=t.length>1?` (and ${t.length-1} more)`:"";super(`${t[0].message}${n}`,{exitCode:b.Validation,details:{errors:t}}),this.name="EditRefusedError",this.errors=t}},ma=class extends Error{constructor(n,r,o={}){super(r);this.code=n;this.at=o}code;at},he=(e,t,n)=>{throw new ma(e,t,n)},at=(e,t=!0)=>({action:e,resendable:t}),Zr=e=>Object.keys(e).length===0,VD=new Set(Je),Xo=(e,t)=>{for(let n of e)VD.has(n)&&he("read-only-field",`'${n}' is read-only: the server serves it on an element, but no staged write accepts it.`,{elementId:t,property:n})},Ib=e=>he("element-not-found",`Element '${e}' is not in the model.`,{elementId:e}),lm=({starting:e,working:t},n)=>t.element(n)??(e.elements[n]===void 0?Ib(n):he("element-not-found",`Element '${n}' is removed by an earlier delete of this change.`,{elementId:n})),Sb=(e,t)=>e.get(t)??he("unknown-key",`No new element of this change has the key '${t}'.`),cm=(e,t,n)=>{if(!("key"in e))return e.id;let r=Sb(n.keys,e.key);return r.editIndex>=t&&he("key-before-definition",`The key '${e.key}' is used before the create that makes it; create it first.`),r.id},mm=e=>({id:e.id,owned:e.owned,...e.modelId!==void 0&&{modelId:e.modelId}}),YD=(e,t)=>"key"in e?{id:Sb(t.keys,e.key).id,owned:e.owned}:mm(e),$b=(e,t)=>Object.fromEntries(Object.entries(e).map(([n,r])=>[n,r.map(o=>YD(o,t))])),Tb=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.map(mm)])),xb=e=>Object.values(e).every(t=>t.length===0),Ab=(e,t)=>{for(let[n,r]of Object.entries(e)){let o=r.find(s=>s.id===t);if(o)return{group:n,ref:o}}},KD=(e,t)=>e.id===t.id&&e.owned===t.owned&&e.modelId===t.modelId,zD=(e,t)=>[t.owned?"owned":"unowned",...t.modelId!==void 0?[`in model '${t.modelId}'`]:[],...e!=="@@"?[`in group '${e}'`]:[]].join(", "),JD=(e,t,n)=>{let r=new Map,o=new Map;return e.forEach((s,i)=>{if(s.kind==="action"&&s.key!==void 0){let d=s.key;n(i,()=>{o.has(d)&&he("duplicate-key",`The key '${d}' names two new elements; give each its own.`);let l=t(),{action:c}=s,m=c.type==="ELEMENT_PASTE"?c.paste.elementIds.slice(1).map(()=>t()):[];o.set(d,{id:l,editIndex:i,...m.length>0?{more:m}:{}})});return}if(s.kind!=="create")return;let a=d=>{let l=t();r.set(d,l),d.key!==void 0&&(o.has(d.key)&&he("duplicate-key",`The key '${d.key}' names two new elements; give each its own.`),o.set(d.key,{id:l,editIndex:i})),Object.values(d.children??{}).flat().forEach(a)};n(i,()=>a(s.element))}),{idOf:r,keys:o}},Ob=(e,t)=>{let n=t.idOf.get(e);if(n===void 0)throw new Error("Every new element of an edit that was not refused has a minted id.");let r=e.attributes??{},o=e.relations??{},s=Object.entries(e.children??{}).filter(([,i])=>i.length>0);Xo([...Object.keys(e),...Object.keys(r),...Object.keys(o),...s.map(([i])=>i)],n);for(let[i,a]of Object.entries(r))a.length===0&&he("empty-value",`The attribute '${i}' of a new element has no value; leave it out.`,{elementId:n,property:i});for(let[i,a]of Object.entries(o))xb(a)&&he("empty-value",`The relation '${i}' of a new element has no target; leave it out.`,{elementId:n,property:i}),Object.values(a).some(d=>d.some(l=>l.owned))&&he("owned-on-create",`A new element cannot own through a reference in '${i}': nest what it owns under its children.`,{elementId:n,property:i});return{id:n,type:e.type,...!Zr(r)&&{attributes:{...r}},...!Zr(o)&&{relations:Object.fromEntries(Object.entries(o).map(([i,a])=>[i,$b(a,t)]))},...s.length>0&&{ownedElements:Object.fromEntries(s.map(([i,a])=>[i,a.map(d=>Ob(d,t))]))}}},XD=(e,t,n)=>at({type:"ELEMENT_CREATE",creation:{...Ob(e.element,n),owner:{id:cm(e.parent,t,n),relation:e.relation}}}),QD=(e,t)=>{let n=e.attributes??{},r=e.relations??{},o=s=>({elementId:e.element,property:s});Xo([...Object.keys(e),...Object.keys(n),...Object.keys(r)],e.element),Zr(n)&&Zr(r)&&he("empty-edit",`The set names no attribute or relation of '${e.element}'.`,{elementId:e.element});for(let[s,i]of Object.entries(n))i.length===0&&he("empty-value",`The attribute '${s}' is set to no value; unset it instead.`,o(s));for(let[s,i]of Object.entries(r))xb(i)&&he("empty-value",`The relation '${s}' is set to no target; unset it instead.`,o(s));return at({type:"ELEMENT_UPDATE",elementId:e.element,update:{...!Zr(n)&&{attributes:{...n}},...!Zr(r)&&{relations:Object.fromEntries(Object.entries(r).map(([s,i])=>[s,$b(i,t)]))}}})},ZD=e=>{let t=e.attributes??[],n=e.relations??[];return t.length===0&&n.length===0&&he("empty-edit",`The unset names no attribute or relation of '${e.element}'.`,{elementId:e.element}),Xo([...t,...n],e.element),at({type:"ELEMENT_UPDATE",elementId:e.element,update:{...t.length>0&&{attributes:Object.fromEntries(t.map(r=>[r,[]]))},...n.length>0&&{relations:Object.fromEntries(n.map(r=>[r,{}]))}}})},eL=e=>{let t=e.filter(n=>n.kind==="delete");return{named:new Set(t.map(n=>n.element)),recursive:new Set(t.filter(n=>n.recursive).map(n=>n.element))}},tL=(e,t)=>{let{working:n,deletes:r}=t;if(n.element(e.element)===void 0)return t.starting.elements[e.element]===void 0?Ib(e.element):void 0;let o=n.owners(e.element),s=n.cascade(r.named);if(o.length>0&&o.every(d=>s.has(d.id)))return;let i=n.cascade(r.recursive),a=[...n.cascade([e.element])].filter(d=>!r.named.has(d)&&!i.has(d));return a.length>0&&he("owns-elements",`Element '${e.element}' owns ${P(a.length,"element")} that deleting it removes as well; delete it recursively to remove them with it.`,{elementId:e.element}),at({type:"ELEMENT_DELETE",elementId:e.element})},vb=e=>`'${e.id}' through '${e.relation}'`,nL=(e,t)=>{let n={elementId:e.element},{from:r}=e;return r?t.find(o=>o.id===r.id&&o.relation===r.relation)??he("not-an-owner",`Element '${e.element}' is not owned by ${vb(r)}.`,n):(t.length===0&&he("no-owner",`Element '${e.element}' has no owner to move it out of.`,n),t.length>1&&he("ambiguous-owner",`Element '${e.element}' has ${t.length} owners (${t.map(vb).join("; ")}); name the one it leaves.`,n),t[0])},rL=(e,t,n)=>{lm(n,e.element),e.position!==void 0&&!(Number.isInteger(e.position)&&e.position>=0)&&he("invalid-position",`The position ${e.position} is not a whole number from 0 up.`,{elementId:e.element});let r=nL(e,n.working.owners(e.element));return at({type:"ELEMENT_MOVE",move:{elements:[{id:e.element,parent:{id:r.id,relation:r.relation}}],targetParent:{id:cm(e.parent,t,n),relation:e.relation},...e.position!==void 0&&{position:e.position}}})},oL=(e,t,n)=>{let r=lm(n,e.element),o={elementId:e.element,property:e.relation};Xo([e.relation],e.element);let s="key"in e.target?{id:cm({key:e.target.key},t,n),owned:e.target.owned}:mm(e.target),i=r.relations?.[e.relation]??{},a=Object.keys(i),d=a.some(p=>p!=="@@"),l=e.group??(d?he("group-required",`The relation '${e.relation}' of '${e.element}' is grouped (${a.join(", ")}); name the group the target belongs in.`,o):"@@");a.length>0&&d!==(l!=="@@")&&he("group-mismatch",d?`The relation '${e.relation}' of '${e.element}' is grouped (${a.join(", ")}); name the group the target belongs in rather than '${"@@"}'.`:`The relation '${e.relation}' of '${e.element}' is ungrouped; leave the group out.`,o);let c=Ab(i,s.id);if(c&&!(c.group===l&&KD(c.ref,s))&&he("already-related",`'${e.element}' already relates to '${s.id}' through '${e.relation}' (${zD(c.group,c.ref)}); unrelate it first.`,o),!s.owned&&s.modelId===void 0&&l==="@@")return at({type:"RELATION_MEMBERSHIP_UPDATE",update:{relation:e.relation,targetElementId:s.id,addSourceElementIds:[e.element]}});let m=Tb(i);return c||(m[l]=[...m[l]??[],s]),at({type:"ELEMENT_UPDATE",elementId:e.element,update:{relations:{[e.relation]:m}}},!1)},sL=(e,t)=>{let n=lm(t,e.element);Xo([e.relation],e.element);let r=n.relations?.[e.relation]??{};if((Ab(r,e.target)??he("not-related",`'${e.element}' does not relate to '${e.target}' through '${e.relation}'.`,{elementId:e.element,property:e.relation})).ref.modelId===void 0)return at({type:"RELATION_MEMBERSHIP_UPDATE",update:{relation:e.relation,targetElementId:e.target,removeSourceElementIds:[e.element]}});let s=Object.fromEntries(Object.entries(Tb(r)).map(([i,a])=>[i,a.filter(d=>d.id!==e.target)]).filter(([,i])=>i.length>0));return at({type:"ELEMENT_UPDATE",elementId:e.element,update:{relations:{[e.relation]:s}}},!1)},iL=(e,{id:t,more:n=[]})=>{switch(e.type){case"ELEMENT_PASTE":return{...e,paste:{...e.paste,rootIds:[t,...n]}};case"DIAGRAM_MATERIALIZE":return{...e,diagramId:t};case"LAYOUT_RULE_CREATE":return{...e,creation:{...e.creation,id:t}};case"NAMESPACE_CREATE":return{...e,creation:{...e.creation,id:t}};case"TEMPLATE_ENTRY_CREATE":return{...e,creation:{...e.creation,id:t}};case"DIAGRAM_CREATE":return{...e,creation:{...e.creation,id:t}};case"HIERARCHY_GROUP_CREATE":return{...e,creation:{...e.creation,id:t}}}},aL=(e,t)=>{if(e.key===void 0)return at(e.action);let n=t.keys.get(e.key);if(n===void 0)throw new Error("Every key of an action edit that was not refused has a minted id.");return at(iL(e.action,n))},dL=(e,t,n)=>{switch(e.kind){case"action":return aL(e,n);case"create":return XD(e,t,n);case"set":return QD(e,n);case"unset":return ZD(e);case"delete":return tL(e,n);case"move":return rL(e,t,n);case"relate":return oL(e,t,n);case"unrelate":return sL(e,n)}},Qo=(e,t,{mintId:n=GD}={})=>{let r=[],o=(d,l)=>{try{return l()}catch(c){if(!(c instanceof ma))throw c;let{elementId:m,property:p}=c.at;r.push({editIndex:d,code:c.code,message:c.message,...m!==void 0&&{elementId:m},...p!==void 0&&{property:p}});return}},s=d=>r.some(l=>l.editIndex===d),i={starting:t,working:kb(t),...JD(e,n,o),deletes:eL(e)},a=[];if(e.forEach((d,l)=>{let c=s(l)?void 0:o(l,()=>dL(d,l,i));c!==void 0&&(a.push(c),i.working.apply(c.action))}),r.length>0)throw new ca(r.toSorted((d,l)=>d.editIndex-l.editIndex));return{actions:a.map(({action:d})=>d),ids:Object.fromEntries([...i.keys].map(([d,{id:l}])=>[d,l])),resendable:a.every(({resendable:d})=>d)}};var lL=e=>e instanceof f&&e.type==="draft-head-conflict"&&e.details.ancestor===!0,cL=(e,t)=>e.length===t.length&&e.every(n=>t.includes(n)),mL=e=>{switch(e.type){case"ELEMENT_UPDATE":case"ELEMENT_DELETE":return{all:[e.elementId]};case"ELEMENT_MOVE":return{all:e.move.elements.map(t=>t.id)};case"RELATION_MEMBERSHIP_UPDATE":return{among:[...e.update.addSourceElementIds??[],...e.update.removeSourceElementIds??[]]};case"ELEMENT_BULK_UPDATE":return{among:[...e.update.elementIds??[],...(e.update.updates??[]).map(t=>t.elementId)]};default:return{}}},Mb=e=>[...new Set(e.actions.map(t=>t.type))].sort(),pL=(e,t)=>{let n=Mb(t);if(!cL(e.actionTypes,n))return`it recorded ${e.actionTypes.join(", ")||"no action"}, and this one stages ${n.join(", ")}`;let{elementIds:r}=e;return r===void 0?void 0:t.actions.some(s=>{let i=r[s.type]??[],{all:a,among:d}=mL(s);return a?.some(l=>!i.includes(l))||d!==void 0&&i.some(l=>!d.includes(l))})?"it changed other elements than this one names":void 0},Nb=(e,t,n,r)=>{let o=(r.sameChange??pL)(e,t);if(o!==void 0)throw new f(`Request id ${t.changeRequestId} was already used for a different change of your draft of ${n} (${e.id}): ${o}. Nothing was staged.`,{hint:"Leave --request-id out to stage this change under an id of its own.",hosted:{hint:"Call again: the call stages the change under an id of its own."},details:{changeRequestId:t.changeRequestId,stagedCommitId:e.id,recordedActionTypes:e.actionTypes,actionTypes:Mb(t)}})},Pb="Run 'modeldesk draft status', then stage the change again.",Db={hint:e=>`Call ${e("draft status")}, then stage the change again.`},fL=(e,t,n,r)=>new f(e.details.ancestor===!0?`Your draft of ${t} moved again while ${n} was being sent a second time, so it was not staged.`:`Your draft of ${t} was undone, rebased or committed while ${n} was being staged, so it was not staged.`,{...r,exitCode:b.Conflict,hint:Pb,hosted:Db}),uL=(e,t,n,r)=>{let o=e.details.targetRefName??e.details.targetRefId,s=typeof o=="string"?` (${o})`:"";return new f(`Your draft of ${t} aims at another branch${s} since it was read, so ${n} was not staged.`,{...r,exitCode:b.Conflict,hint:Pb,hosted:Db})},hL=e=>{let t=e.length;for(;t>0&&(e[t-1]==="."||e[t-1].trim()==="");)t--;return e.slice(0,t)},gL=(e,t,n,r,o)=>{let s=Array.isArray(e.details.errors)?e.details.errors:[];if(s.some(l=>l.code==="chain-too-long"))return new f(`Your draft of ${t} holds the most changes a draft can (${Ue}), so ${n} was not staged.`,{...r,exitCode:b.Validation,hint:"Commit the draft first ('modeldesk draft commit', or in the app); splitting the change does not help.",hosted:{hint:l=>`Commit the draft first (${l("draft commit")}, or the person in the app); splitting the change does not help.`}});let[i]=s,a=o.chunks>1?`Change ${o.chunk} of ${o.chunks}`:"The change",d=s.length>1?` (and ${s.length-1} more)`:"";return new f(i?`${a} was refused: ${hL(i.message)}${d}.`:e.reason,{...r,exitCode:b.Validation})},yL=(e,t,n,r)=>({reason:r==="absent"?`${e.reason} Your draft holds no change under ${n} yet, but the server may still be staging ${t}.`:`${e.reason} Whether ${t} was staged is unknown: your draft could not be read to look for it.`,hint:o=>`Call ${o("draft diff")} with changes: true and look for request id ${n} before you call again: a change staged under it is in your draft.`,exitCode:b.Failure}),fm=(e,t,n,r,o,s="unknown")=>{if(!(e instanceof f))return e;let i=r.chunks>1?`change ${r.chunk} of ${r.chunks}`:"this change",a={type:e.type,requestId:e.requestId,details:{...e.details,...r}};return e.exitCode===b.Transient?new f(`${e.reason} Whether ${i} was staged is unknown.`,{...a,exitCode:b.Transient,details:{...a.details,changeRequestId:n.changeRequestId},hint:o,hosted:yL(e,i,n.changeRequestId,s)}):e.type==="draft-head-conflict"?fL(e,t,i,a):e.type===ic?uL(e,t,i,a):e.type==="change-validation-failed"?gL(e,t,i,a,r):new f(e.reason,{...a,exitCode:e.exitCode,hint:e.hint,hosted:e.hosted})},pa=async(e,t,n)=>{let r={context:e,api:e.api(),address:t.address,plan:n,name:g(t.model.name),current:t,chunks:[...n.chunks],head:t.head,draftId:t.draft?.id,replanned:!1,chain:t.draft===void 0?void 0:n.knownChain,staged:[]};for(let o=0;o<r.chunks.length;){let s=r.chunks[o];if(s.actions.length===0){o++;continue}let i=n.stableIds?await EL(r,s):void 0;if(i!==void 0){await pm(r,i,o),o++;continue}let a=await CL(r,o);if("resumeAt"in a){o=a.resumeAt;continue}r.head=a.sent.commitId,r.draftId=a.sent.draftId,r.chain=void 0;let{envelope:d,draftId:l}=a.sent;d!==void 0&&l!==void 0&&e.content.advance(r.current.model.id,l,d),await pm(r,a.sent,o),o++}return{target:r.current,chunks:r.staged,head:r.head,draftId:r.draftId}},wL=e=>e.staged.map(t=>({number:e.chunks.indexOf(t.chunk)+1,changeRequestId:t.chunk.changeRequestId,commitId:t.commitId})),um=(e,t)=>({chunk:t+1,chunks:e.chunks.length,landed:wL(e),baseCommitId:e.head}),bL=(e,t)=>t===void 0?Promise.resolve([]):(e.chain??=ze(e.api,e.current.model.id,t),e.chain),pm=async(e,t,n)=>{e.staged.push(t),await e.plan.persisted?.(t,n)},EL=async(e,t)=>{let n=(await bL(e,e.draftId)).find(r=>r.requestId===t.changeRequestId);if(n!==void 0)return Nb(n,t,e.name,e.plan),{chunk:t,commitId:n.id,draftId:e.draftId,alreadyStaged:!0,staged:!0}},CL=async(e,t)=>{let n=e.chunks[t];try{let r=await e.api.drafts.model.stage(e.current.model.id,{actions:[...n.actions],draftHeadId:e.head,changeRequestId:n.changeRequestId,message:n.message,...e.draftId===void 0?{branchId:e.current.branch.id}:{},...e.plan.dryRun?{dryRun:!0}:{}});return{sent:{chunk:n,commitId:r.envelope.commitId,draftId:r.draftId??e.draftId,envelope:r.envelope,...r.disconnectDroppedReferences===void 0?{}:{disconnectDroppedReferences:r.disconnectDroppedReferences},alreadyStaged:!1,staged:r.envelope.commitId!==e.head}}}catch(r){if(!(r instanceof f))throw r;if(e.plan.dryRun)throw r.exitCode===b.Transient?r:fm(r,e.name,n,um(e,t),e.plan.retryHint);return r.exitCode===b.Transient?{sent:await RL(e,r,t)}:{resumeAt:await kL(e,r,t)}}},RL=async(e,t,n)=>{let r=e.chunks[n],o=await vL(e.context,e.current.model.id,r.changeRequestId);if(typeof o=="string")throw fm(t,e.name,r,um(e,n),e.plan.retryHint,o);return{chunk:r,commitId:o.commitId,draftId:o.draftId,alreadyStaged:!1,staged:!0}},kL=async(e,t,n)=>{let r=e.chunks[n];if(e.replanned||!lL(t)||e.plan.replan===void 0)throw fm(t,e.name,r,um(e,n),e.plan.retryHint);let o=Array.isArray(t.details.commits)?t.details.commits:[];e.current=await gt(e.context,e.address),e.head=e.current.head,e.draftId=e.current.draft?.id,e.chain=void 0,e.replanned=!0;let s=n,i=o.find(a=>a.requestId===r.changeRequestId);return i!==void 0&&(Nb(i,r,e.name,e.plan),await pm(e,{chunk:r,commitId:i.id,draftId:e.draftId,alreadyStaged:!0,staged:!0},n),s++),e.chunks=[...e.chunks.slice(0,s),...await e.plan.replan(e.current,e.chunks.slice(s))],s},vL=async(e,t,n)=>{let r=e.api();try{let o=await ht(()=>r.models.draft(t));if(o===void 0)return"absent";let i=(await ze(r,t,o.id,IL)).find(a=>a.requestId===n);return i?{commitId:i.id,draftId:o.id}:"absent"}catch{return"unknown"}},IL=10,tr=e=>e.chunks.some(t=>t.staged);var K="The change is staged in your draft of the model, opened on the addressed branch by the first change, where the person you work for sees it in the app and commits it; -m says why, in your words. A lost race with another session is resent once; a refusal exits 4 with every reason in details.errors.",hm={"with-staged":{type:"boolean",description:"With --commit: also land the changes the draft held before this run, which the commit message then covers; required when there are any."}},$L={"request-id":{type:"string",placeholder:"id",description:"The idempotency key to stage under, to retry a change whose outcome is unknown: a change already staged under it is not staged again. A cli-\u2026 id this session minted is sent as given, any other id seeds a cli-\u2026 id derived from it, the same one on every run. Minted (cli-\u2026) when left out."}},TL={commit:{type:"boolean",description:"Land the draft right after staging, with the same message. Under an agent host this is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1 or the draft aims at a branch named agent/<topic>."}},q={...Bi,...$L,...TL,...hm},xL=(e,t,n)=>{if(e!==void 0)return"id"in e?e.id:t===void 0?n[e.key]:void 0},gm=()=>{let e=[],t=0;return{mint:()=>(t===e.length&&e.push(SL()),e[t++]),rewind:()=>{t=0}}},ym=(e,t)=>{if(!/^[\x21-\x7e]+$/.test(e)||e.length>El)throw k(`--request-id takes 1 to ${El} printable characters without spaces, such as the changeRequestId a failed run reported.`,t);return e},AL=e=>`Retry with --request-id ${e}: a change already staged under it is found and not staged again.`,Zo=async(e,t,n,r)=>{let o=r.requestId===void 0?Er(e.origin):_n(e.origin,r.requestId),s=await n(t),i=d=>({actions:d.actions,message:r.message,changeRequestId:o});return{staged:await pa(e,t,{chunks:[i(s)],stableIds:r.requestId!==void 0,replan:async(d,l)=>(e.flags.commit&&await _b(e,d,o),l.length===0?[]:(s=await n(d),[i(s)])),retryHint:AL(o),...r.dryRun?{dryRun:!0}:{},...r.sameChange?{sameChange:r.sameChange}:{},...r.knownChain?{knownChain:r.knownChain}:{}}),translation:s,changeRequestId:o}},Lb=e=>e.staged.chunks[0],es=e=>{let t=e.staged.target.draft,n=Lb(e);if(n===void 0)return t?{id:t.id,headCommitId:t.headCommitId,changeCount:t.changeCount}:null;let r=tr(e.staged),o=e.staged.draftId;return o===void 0&&!r?null:{...o?{id:o}:{},headCommitId:e.staged.head,changeCount:(t?.changeCount??0)+(r&&!n.alreadyStaged?1:0)}},ts=e=>{let{target:t,draftId:n}=e.staged;return n===void 0?le({ref:{kind:"branch",branch:t.branch},draft:void 0}):{kind:"draft",id:n,branch:{id:t.branch.id,name:t.branch.name}}},ns=async(e,t)=>{let{target:n,head:r}=t.staged,o=await jo(e,n.model.id),s=g(n.model.name),i=t.staged.draftId;if(i===void 0)throw new f(`The change left ${s} as it was, so there is nothing to commit.`,{type:"nothing-to-commit"});let{landing:a,recovered:d}=await Wr(e,o,{id:i,targetRefId:n.branch.id,baselineCommitId:n.draft?.baselineCommitId??n.head},{message:e.flags.message,expectedDraftHeadId:r}),l=Br(a,n.model,vr(e));return{...Hr(a),recovered:d,...l===void 0?{}:{next:l},url:e.webUrl({kind:"commit",modelId:n.model.id,commitId:a.commit.id})}},wm=(e,t)=>{if(e>0&&!t)throw new f(`Your draft already holds ${P(e,"staged change")}, and a commit lands every one of them under its message.`,{hint:"Review them with 'modeldesk draft diff --changes', then pass --with-staged to commit them too.",details:{changeCount:e}})},bm=e=>`land it from a plain shell with 'modeldesk draft commit ${e} --any-surface'.`,_b=async(e,t,n)=>{Rr(e,`${e.commandName} --commit`,{kind:"model",id:t.model.id,name:t.model.name},t.branch);let r=n!==void 0&&t.draft!==void 0?(await ze(e.api(),t.model.id,t.draft.id)).filter(o=>o.requestId!==n).length:t.draft?.changeCount??0;if(wm(r,e.flags["with-staged"]),t.draft!==void 0){let o=g(t.model.name);await Be(e,Fi(e,t.model.id),t.draft,{scope:{kind:"all"},action:`Committing your draft of ${o}`,anySurface:!1,override:bm(t.model.id)})}},fa=e=>{let{commit:t}=e.flags,n=`modeldesk ${e.commandName} --help`;Lt(e.flags.message,n);let r=e.flags["request-id"];if(r!==void 0&&ym(r,n),e.flags["with-staged"]&&!t)throw k("--with-staged goes with --commit.",n)},Wt=async e=>{let{commit:t}=e.flags;fa(e);let n=e.flags["request-id"],r=await gt(e,e.args.model);if(t){let o=n===void 0?void 0:_n(e.origin,n);await _b(e,r,o)}return r},X=(e,t)=>oe(async()=>{let n=await Wt(e),r=gm(),o,s=await Zo(e,n,async w=>{let E=await t(w);return o=E.subject,r.rewind(),Qo(E.edits,w.read,{mintId:r.mint})},{message:e.flags.message,requestId:e.flags["request-id"]}),{translation:i}=s,a=Lb(s),d=a?.alreadyStaged?a.commitId:void 0,l=a?.envelope,c=tr(s.staged),m=n.model.id,p=xL(o,d,i.ids),h=l?.removedElementIds??[],u=p===void 0||h.includes(p)?void 0:l?.revisions[p]?.element??s.staged.target.read.elements[p],y={model:n.model,ref:ts(s),draft:es(s),message:e.flags.message,changeRequestId:s.changeRequestId,staged:c,...d?{alreadyStaged:!0,stagedCommitId:d}:{},...u?{element:u}:{},...h.length>0?{removedElementIds:h}:{},url:u?e.webUrl({kind:"element",modelId:m,elementId:u.id}):e.webUrl({kind:"model",modelId:m})};if(e.flags.commit){if(!c)throw new f(`The change left ${g(n.model.name)} as it was, so there is nothing to commit.`,{type:"nothing-to-commit"});y.commit=await ns(e,s)}return{result:y}}),OL=e=>g(typeof e=="string"?e:JSON.stringify(e)),ML=e=>e.kind==="draft"?e.branch.name:e.kind==="branch"?e.name:"",NL=e=>{let t=g(e.model.name);if(e.alreadyStaged)return`Already staged in your draft of ${t} under ${e.changeRequestId} (${e.stagedCommitId}); not staged again.`;let n=ML(e.ref);return e.staged?`Staged in your draft of ${t} on ${g(n)} (${P(e.draft?.changeCount??0,"change")}, at most ${Ue}): ${g(e.message)}`:`Nothing was staged: the change leaves ${t} as it is.`},nr=e=>[`Committed as ${e.commit.id} on ${e.branch.name===void 0?e.branch.id:g(e.branch.name)}${e.recovered?" (found on the branch by its request id)":""}.`,...e.next?[e.next]:[],`commit: ${e.url}`],PL=(e,t)=>[e.id,...e.owned?["(owned)"]:[],...t==="@@"?[]:[`[${t}]`]].join(" "),Q=e=>{let{element:t}=e;return[NL(e),...t?[`${t.id} (${t.type})`,...Object.entries(t.attributes??{}).map(([n,r])=>` ${n}: ${r.map(OL).join(", ")}`),...Object.entries(t.relations??{}).map(([n,r])=>` ${n}: ${Object.entries(r).flatMap(([o,s])=>s.map(i=>PL(i,o))).join(", ")}`)]:[],...e.removedElementIds?[`Removed ${P(e.removedElementIds.length,"element")}.`]:[],`url: ${e.url}`,...e.commit?nr(e.commit):[]].join(`
217
+ `)};var be=(e,t)=>{if(t.kind==="import")return`${e.appBase}/imports/${encodeURIComponent(t.importId)}`;let n=`${e.appBase}/models/${encodeURIComponent(t.modelId)}`;switch(t.kind){case"model":return n;case"element":return`${n}/editor?elementId=${encodeURIComponent(t.elementId)}`;case"commit":return`${n}/history/${encodeURIComponent(t.commitId)}`}};var Z=e=>e?e.slice(0,8):"none",ua=(e,t)=>new f(e.reason,{exitCode:e.exitCode,hint:t,type:e.type,requestId:e.requestId,details:e.details});var jb="daaddd57-d61e-41e2-8751-19497881b8b2",DL="@element",LL=[["@metamodel","metamodel"],["@metamodelExtensions","extension"]],eo=(e,t)=>{let n=e?.attributes?.[t]?.[0];return typeof n=="string"&&n!==""?n:void 0},Fb=(e,t)=>Object.values(e?.relations?.[t]??{}).flatMap(n=>n.map(r=>r.id)),qb=e=>e.rootElementId===void 0?void 0:e.elements[e.rootElementId],ha=e=>{let t=qb(e);return LL.flatMap(([n,r])=>Fb(t,n).flatMap(o=>{let s=e.elements[o],i=eo(s,"@modelId");if(i===void 0)return[];let a=eo(s,"@commitId"),d=eo(s,"@version");return[{role:r,modelId:i,...a?{commitId:a}:{},...d?{version:d}:{}}]}))},rs=e=>{let[t]=Fb(qb(e),DL);return t===void 0?void 0:eo(e.elements[t],"standardVersion")},Wb=e=>Object.values(e.elements).flatMap(t=>{if(t.type!=="@ManagedDependency")return[];let n=eo(t,"@sourceMetamodelId"),r=eo(t,"@commitId");return n&&r?[{sourceMetamodelId:n,commitId:r}]:[]});var _L=e=>{let t;return()=>t??=e()},Hb=new WeakMap,dt=(e,t)=>{let n=Hb.get(e)??new Map;Hb.set(e,n);let r=n.get(t);if(r!==void 0)return r;let o=ie(e,t),s=_L(async()=>{try{return{overview:await e.api().models.overview(await o.id())}}catch(d){if(d instanceof V&&d.status===403)return{refusal:d};throw d}}),i=async()=>{let d=await s();if("refusal"in d)throw d.refusal;return d.overview},a={model:o,overview:i,overviewIfReadable:async()=>{let d=await s();return"overview"in d?d.overview:void 0},isMetamodelModel:async()=>(await i()).metamodel?.modelId===jb};return n.set(t,a),a};var lt=(e,t)=>e.filter(n=>n.id.toLowerCase()===t||"modelId"in n&&n.modelId?.toLowerCase()===t),cn=(e,t,n)=>{let r=`'${g(e.name)}'`,o=s=>s===void 0?{}:{hint:s};if(e.type==="MANAGED")throw new f(`${r} is a managed dependency of ${t}: built-in elements its metamodel supplies, ${n.managed.reason}`,o(n.managed.hint));if(e.type==="EXTERNAL")throw new f(`${r} is an external document, ${n.external.reason}`,o(n.external.hint));if(e.transitive){let s=(e.providedVia??[]).map(a=>`'${g(a.name)}'`),i=s.length?`, brought in by ${s.join(", ")}`:"";throw new f(`${r} is a transitive dependency of ${t}${i}: ${n.transitive.reason}`,{hint:n.transitive.hint})}return e},jL={managed:{reason:"pinned through the metamodel version, which pin set does not change.",hint:"Change the model's metamodel version in the app's model settings."},external:{reason:"not a model, so it has no version to pin."},transitive:{reason:"it follows the dependency that provides it.",hint:"Pin the direct dependency that provides it instead."}},mn=(e,t,n)=>{let r=lt(e,t);if(r.length===0)throw new f(`${n.name} has no dependency with the id '${t}'.`,{exitCode:b.NotFound,hint:`Run 'modeldesk pin list ${n.address}' to see its dependencies.`,hosted:{hint:o=>`Call ${o("pin list")} with model ${n.address} to see its dependencies.`}});if(r.length>1)throw new f(`${r.length} dependencies of ${n.name} match '${t}'; address the one you mean by id.`,{exitCode:b.Usage,details:{candidates:r.map(o=>({id:o.id,name:o.name,type:o.type,..."modelId"in o?{modelId:o.modelId}:{}}))}});return r[0]},FL=(e,t,n)=>cn(mn(e,t,n),n.name,jL),os=({ref:e})=>e.kind==="release"?e.name:Ee,Bb=J({path:["pin","set"],effect:"land-direct",summary:"Pin a dependency to a release or to the head",description:"Re-pins one of the model's direct dependencies on another model. <dependency>@<release> pins that release's commit; <dependency>@main pins the target's head as it is now, and moves again only when you re-pin. The server resolves the selector, and writes nothing when the pin already resolves there. Managed, external and transitive dependencies are refused, with the reason.",positionals:[N(de),{name:"dependency",type:{address:"model",slot:Pi},required:!0,description:"The dependency's id, or its target model's id, from pin list, at @<release> for that release of the target or @main for the target's head now."}],dryRun:!0,examples:["modeldesk pin set <model> <dependency>@1.2.0","modeldesk pin set <model> <dependency>@main --json"],run:async e=>{let t=dt(e,e.args.model.model),n=e.api(),r=await t.model.id(),[o,s]=await Promise.all([t.model.identity(),n.dependencies.list(r)]),i={id:o.id,name:o.name},a=FL(s.items,e.args.dependency.model,{name:g(o.name),address:e.args.model.model}),d=os(e.args.dependency),l=be(e.instance(),{kind:"model",modelId:o.id}),c={id:a.id,name:a.name,target:{id:a.modelId},versionRef:a.versionRef??null,commitId:a.commitId};if(e.globals.dryRun){if(d!==Ee&&await Qr(n,a.modelId,d)===null)throw new f(`The target of '${g(a.name)}' has no release named '${d}'.`,{exitCode:b.NotFound,hint:`Run 'modeldesk release list ${a.modelId}' to see the releases it can be pinned to.`});return{result:{dryRun:!0,model:i,dependency:c,versionRef:d,url:l}}}let m;try{m=await n.dependencies.update(r,a.id,{versionRef:d})}catch(w){throw w instanceof V&&w.status===400?ua(w,`Run 'modeldesk release list ${a.modelId}' to see the releases it can be pinned to.`):w}let p=m,h=p.versionRef??Ee,u=p.commitId!==c.commitId||h!==(c.versionRef??Ee),y=u&&await t.isMetamodelModel()?`${g(o.name)} is a metamodel-model and its head moved: run 'modeldesk release cascade ${o.id}' to re-release it and refresh the metamodels depending on it.`:void 0;return{result:{model:i,dependency:{id:p.id,name:p.name,target:{id:p.modelId},versionRef:h,commitId:p.commitId,...h===Ee?{}:{release:h}},previous:{versionRef:c.versionRef,commitId:c.commitId},changed:u,...y?{hint:y}:{},url:l}}},render:e=>{let t=`'${g(e.dependency.name)}' of ${g(e.model.name)}`;if("dryRun"in e)return`Dry run: would re-pin ${t} to ${g(e.versionRef)} (now ${g(e.dependency.versionRef??"@HEAD (legacy)")} at ${Z(e.dependency.commitId)}). Nothing was changed.`;let n=`${g(e.dependency.versionRef)} at ${Z(e.dependency.commitId)}`;return[e.changed?`Pinned ${t} to ${n} (was ${g(e.previous.versionRef??"@HEAD (legacy)")} at ${Z(e.previous.commitId)}).`:`${t} is already pinned to ${n}; nothing changed.`,...e.hint?[e.hint]:[],` url: ${e.url}`].join(`
218
+ `)}});var Ub={dependencyAdd:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The model depended on."},versionRef:{type:"string",description:"The selector that was sent: `@HEAD` for `@main`, else the release name."},promoted:{type:"boolean",description:"True when the model already reached the target through another dependency: that edge became a direct one in place and kept its id. Always true."},dependency:{type:"object",properties:{id:{type:"string"},name:{type:"string"},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},versionRef:{type:"string",description:"The selector: `@HEAD`, or the name of the release it is pinned to."},commitId:{type:"string"},release:{type:"string",description:"The release pinned, for a version selector."}},description:"The dependency as your draft holds it; absent on a dry run and when nothing was staged."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Where the change went: the draft it sits in, aimed at its branch; on a dry run, what was read."},draft:{properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft the change sits in; on a dry run, the draft as it was; null when you hold none. May be null."},message:{type:"string"},changeRequestId:{type:"string"},staged:{type:"boolean",description:"Whether the change is in your draft: staged now, or found staged under the request id. One of false, true."},dryRun:{type:"boolean",description:"Present on a dry run: the server tried the change and kept nothing. Always true."},alreadyStaged:{type:"boolean",description:"True when a change staged under the same request id was found in your draft and not staged again. One of false, true."},stagedCommitId:{type:"string"},commit:{type:"object",properties:{recovered:{type:"boolean",description:"One of false, true."},next:{type:"string",description:"What a landing off main leaves the caller with."},url:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}},description:"Present when the draft was landed right after the change was staged."},url:{type:"string"}},required:["schemaVersion","target","versionRef","model","ref","draft","message","changeRequestId","staged","url"]}};var bt={name:"dependency_change",description:"Stages one change to the model's dependencies on other models of the organization: change add depends on target, remove takes a direct dependency away, an external document's included, and pin moves one to another release of its target or to its head now. A relation to an element of another model needs that model as a dependency first: add it, then stage the elements with stage_changes on the same ref, where describe and allowed_types show the types it brings. list_dependencies shows what the model has and which release each pins. A dependency change is always a change of its own, which the server refuses beside any other action. It goes to your draft with message for the person to commit, and lands with the draft; draft_undo takes back your own. connect links an element that represents another model, such as a MIM Extern, to the dependency on that model; disconnect undoes it.",pin:{dryRun:!1}},Et="change",to="The change is staged in your draft of the model as a change of its own, where the person you work for sees it in the app and commits it; -m says why, in your words. --dry-run has the server try the change and keep nothing, so it answers the refusal the change would meet.",ga=(e,t)=>({model:t.model,ref:le(t.resolved),draft:t.draft?{id:t.draft.id,headCommitId:t.draft.headCommitId,changeCount:t.draft.changeCount}:null,message:e.flags.message,staged:!1,dryRun:!0,url:e.webUrl({kind:"model",modelId:t.model.id})}),WL=e=>(t,n)=>{let{types:r,ids:o,along:s=[],subject:i="dependency"}=e(),a=t.actionTypes.find(m=>r.includes(m)),d=n.actions.map(m=>m.type).join(", "),l=t.actionTypes.filter(m=>m!==a);if(a===void 0||l.some(m=>!s.includes(m)))return`it recorded ${t.actionTypes.join(", ")||"no action"}, and this one stages ${d}`;let c=t.elementIds?.[a];if(!(o===void 0||c===void 0))return c.some(m=>o.includes(m.toLowerCase()))?void 0:`it changed another ${i}`},HL=e=>{let t=(e??"").split(",").map(r=>r.trim().split("=")).find(([r])=>r==="0"),n=t===void 0?0:Number(t[1]);return Number.isInteger(n)&&n>=0?n:0},qe=(e,t)=>{let n=e.versionRef??Ee;return{id:e.id,name:e.name,target:{id:e.modelId,...t?{name:t}:{}},versionRef:n,commitId:e.commitId,...n===Ee?{}:{release:n}}},ss=e=>{if(e.dryRun&&e.flags.commit)throw k("--commit has nothing to commit under --dry-run, which stages nothing.",`modeldesk ${e.commandName} --help`)},BL=(e,t)=>{let[n]=e.staged.chunks,r=n?.alreadyStaged===!0,o=r||!t.dryRun&&tr(e.staged),s=t.dryRun&&!r,i=e.staged.target.draft,a=i?{id:i.id,headCommitId:i.headCommitId,changeCount:i.changeCount}:null;return{model:e.staged.target.model,ref:s?le(e.staged.target.resolved):ts(e),draft:s?a:es(e),message:t.message,changeRequestId:e.changeRequestId,staged:o,...t.dryRun?{dryRun:!0}:{},...r?{alreadyStaged:!0,stagedCommitId:n.commitId}:{},url:t.url}},Ct=(e,t)=>oe(async()=>{let{dryRun:n}=e,{message:r,commit:o}=e.flags,s=e.flags["request-id"];ss(e);let i=await Wt(e),a=e.api(),d=i.model.id,l=s===void 0?void 0:_n(e.origin,s),c=l===void 0||i.draft===void 0?void 0:ze(a,d,i.draft.id),m=c!==void 0&&(await c).some($=>$.requestId===l),p={types:[]},h=await Zo(e,i,async $=>{let C=(await a.dependencies.list(d,{ref:Dt($)})).items,x=await t({target:$,edges:C,retried:m});return p=x.recorded,{actions:[x.action],ids:{},resendable:!1}},{message:r,requestId:s,dryRun:n,sameChange:WL(()=>p),...c?{knownChain:c}:{}}),u=BL(h,{dryRun:n,message:r,url:e.webUrl({kind:"model",modelId:d})}),{staged:y}=u,w=h.staged.draftId,E=y&&w!==void 0?(await a.dependencies.list(d,{ref:w})).items:void 0;if(o){if(!y)throw new f(`The change left ${g(i.model.name)} as it was, so there is nothing to commit.`,{type:"nothing-to-commit"});u.commit=await ns(e,h)}let[I]=h.staged.chunks,v=!n&&I!==void 0&&!I.alreadyStaged&&I.envelope!==void 0;return{base:u,edgesAfter:E,droppedReferences:v?HL(I.disconnectDroppedReferences):void 0}}),UL=e=>e.kind==="draft"?e.branch.name:e.kind==="branch"?e.name:"",GL=e=>{let t=g(e.model.name);return e.alreadyStaged?`Already staged in your draft of ${t} under ${e.changeRequestId} (${e.stagedCommitId}); not staged again.`:e.dryRun?e.changeRequestId===void 0?`Dry run: the server's preview; nothing was staged in your draft of ${t}.`:`Dry run: the server accepted the change and kept nothing. Nothing was staged in your draft of ${t}.`:e.staged?`Staged in your draft of ${t} on ${g(UL(e.ref))} (${P(e.draft?.changeCount??0,"change")}, at most ${Ue}): ${g(e.message)}`:`Nothing was staged: the change leaves ${t} as it is.`},Rt=(e,t)=>{let n=[];return e.staged?n.push(t.done):e.dryRun&&n.push(t.would),[...n,GL(e),`url: ${e.url}`,...e.commit?nr(e.commit):[]].join(`
219
+ `)},is=e=>`${g(e.versionRef)} at ${Z(e.commitId)}`;var Yb="dependency-exists",Gb=(e,t)=>e.filter(n=>n.type==="INTERNAL"&&n.modelId.toLowerCase()===t),VL=(e,t)=>`Stage a move of its pin with 'modeldesk dependency pin ${e} ${t}@<release|main>'.`,YL="Stage against the release it pins (list_dependencies shows it), or stage a move of its pin with dependency_change and change pin when the person wants another release.",KL=(e,t)=>new f(`${g(e.name)} already depends on '${g(t.name)}' (${t.id}), pinned to ${is(qe(t))}. Nothing was staged.`,{exitCode:b.Validation,type:Yb,hint:VL(e.id,t.id),details:{dependency:qe(t)},hosted:{hint:YL}}),Vb=["DEPENDENCY_CREATE","DEPENDENCY_UPDATE"],zL=e=>e instanceof f&&Array.isArray(e.details.errors)&&e.details.errors.some(t=>t.code===Yb),Kb=A({path:["dependency","add"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a dependency on another model",description:"Adds a dependency on another model of the organization. <target>@<release> pins that release; <target>@main pins the target's head as it is now, which moves again only when you re-pin. A target the model already depends on is refused (exit 4), naming the dependency to re-pin with dependency pin; one it reaches only through another dependency becomes a direct one in place. Dependencies on an external document are added in the app. "+to,positionals:[N(F),{name:"target",type:{address:"model",slot:Bg},required:!0,description:"The id of the model to depend on, from model list, at @<release> for that release or @main for its head now.",toolDescription:"The model to depend on"}],flags:q,dryRun:!0,examples:['modeldesk dependency add <model> <target>@2.5.1 -m "Profile of UML 2.5.1"','modeldesk dependency add <model>@agent/profile <target>@main -m "Track the head" --dry-run'],mcp:{...bt,choice:{member:Et,value:"add",description:"Depend on target, a model's id from list_models at @<release> or @main."}},resultSchema:Ub.dependencyAdd,run:async e=>{let t=e.args.target.model,n=os(e.args.target),r=e.api(),o,s=async()=>{try{return o??=(await r.models.identity(t)).name,o}catch(c){throw c instanceof V&&(c.status===404||c.status===403)?new f(`No model '${t}' that you can read, so it cannot be depended on.`,{exitCode:b.NotFound,hint:"Run 'modeldesk model list' to find the model's id.",hosted:{hint:m=>`Call ${m("model list")} to find the model's id.`}}):c}},i=gm(),a=!1,d;try{d=await Ct(e,async({target:c,edges:m,retried:p})=>{if(await s(),c.model.id.toLowerCase()===t)throw new f(`${g(c.model.name)} cannot depend on itself.`,{exitCode:b.Validation});let h=Gb(m,t),u=h.find(w=>!w.transitive);i.rewind();let y={type:"DEPENDENCY_CREATE",id:i.mint(),modelId:t,versionRef:n};if(p)return{action:y,recorded:{types:Vb,ids:u?[u.id.toLowerCase()]:[]}};if(u!==void 0)throw KL(c.model,u);return a=h.length>0,{action:y,recorded:{types:Vb}}})}catch(c){if(zL(c)){let{model:m}=e.args.model;throw new f(c.reason,{exitCode:c.exitCode,hint:`Run 'modeldesk pin list ${m}' to see the dependency it has.`,type:c.type,requestId:c.requestId,details:c.details,hosted:{hint:p=>`Call ${p("pin list")} with model ${m} to see the dependency it has.`}})}throw c}let l=d.edgesAfter&&Gb(d.edgesAfter,t).find(c=>!c.transitive);return{result:{...d.base,target:{id:t,name:o??t},versionRef:n,...a?{promoted:!0}:{},...l?{dependency:qe(l,o??t)}:{}}}},render:e=>{let t=`'${g(e.target.name)}'`,n=e.versionRef===Ee?"its head":g(e.versionRef),r=e.dependency?`${is(e.dependency)} (${e.dependency.id})`:n,o=e.promoted?", until now reached through another dependency":"",s=g(e.model.name);return Rt(e,{done:`${s} depends on ${t}${o}, pinned to ${r}.`,would:`${s} would depend on ${t}${o}, pinned to ${n}.`})}});var zb={dependencyConnect:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},element:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The element connected."},dependency:{type:"object",properties:{id:{type:"string"},name:{type:"string"},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},versionRef:{type:"string",description:"The selector: `@HEAD`, or the name of the release it is pinned to."},commitId:{type:"string"},release:{type:"string",description:"The release pinned, for a version selector."}},description:"The dependency it is connected to; absent on a dry run against a model the model does not depend on yet."},replaces:{type:"array",items:{type:"object",properties:{copyId:{type:"string"},counterpartId:{type:"string"}}},description:"Each copy the connection replaces, by the counterpart that takes its place; every other copy stays owned."},copies:{type:"array",items:{type:"object",properties:{copyId:{type:"string"},name:{type:"string",description:"Its label in the model, where it has one."},group:{type:"string",description:'`SAME`, `DIFFERENT` (something differs, or a counterpart is still to be chosen) or `NOT_IN_MODEL`. One of "DIFFERENT", "NOT_IN_MODEL", "SAME".'},counterpartId:{type:"string",description:"The counterpart that takes its place: the one the preview settles, or the one `use` names."},candidates:{type:"array",items:{type:"object",properties:{id:{type:"string"},path:{type:"array",items:{type:"string"}}}},description:"Where several elements fit: each, with the labels of its owners from the model root down."},notReplaceable:{type:"string",description:"Why the copy stays owned whatever is chosen."},replaced:{type:"boolean",description:"Whether the connection, with the choices as given, puts the counterpart in its place. One of false, true."}}},description:"Present on a dry run: every copy the element owns, as it compares."},changeRequestId:{type:"string"},draft:{properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft the change sits in; on a dry run, the draft as it was; null when you hold none. May be null."},commit:{type:"object",properties:{recovered:{type:"boolean",description:"One of false, true."},next:{type:"string",description:"What a landing off main leaves the caller with."},url:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}},description:"Present when the draft was landed right after the change was staged."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},message:{type:"string"},url:{type:"string"},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Where the change went: the draft it sits in, aimed at its branch; on a dry run, what was read."},dryRun:{type:"boolean",description:"Present on a dry run: the server tried the change and kept nothing. Always true."},staged:{type:"boolean",description:"Whether the change is in your draft: staged now, or found staged under the request id. One of false, true."},alreadyStaged:{type:"boolean",description:"True when a change staged under the same request id was found in your draft and not staged again. One of false, true."},stagedCommitId:{type:"string"}},required:["schemaVersion","element","replaces","draft","model","message","url","ref","staged"]}};var Xb={managed:{reason:"which no element connects to."},external:{reason:"not a model, so no element connects to it."},transitive:{reason:"an element connects only to a model the model depends on itself.",hint:"Stage a dependency of its own on that model first."}},XL={types:["ELEMENT_UPDATE"],along:["ELEMENT_DELETE"],subject:"element"},Qb=e=>{let t=e.indexOf("@");return t<0?{id:e.toLowerCase()}:{id:e.slice(0,t).toLowerCase(),ref:e.slice(t+1)}},QL=(e,t)=>lt(e,t).find(n=>n.type==="INTERNAL"&&!n.transitive),ZL=e=>e.map(t=>{let[n,r,...o]=t.split("=").map(s=>s.trim().toLowerCase());if(n===""||r===""||o.length>0)throw k(`--use takes <copy id>=<counterpart id>, or <copy id> alone, got '${t}'.`,"modeldesk dependency connect --help",{reason:`use takes <copy id>=<counterpart id>, or <copy id> alone, got '${t}'.`});return r===void 0?{copyId:n}:{copyId:n,counterpartId:r}}),Jb=(e,t)=>e.find(n=>n.copyId.toLowerCase()===t),Zb=async(e,t)=>{let n=ZL(e.flags.use??[]),o=e.flags.settled||n.some(i=>i.counterpartId===void 0)?await t():[],s=new Map;if(e.flags.settled)for(let i of o)i.counterpartId!==void 0&&i.notReplaceable===void 0&&s.set(i.copyId.toLowerCase(),i.counterpartId);for(let i of n){let a=i.counterpartId??Jb(o,i.copyId)?.counterpartId;if(a===void 0){let d=Jb(o,i.copyId)?.candidateIds??[];throw new f(d.length>0?`No counterpart of copy ${i.copyId} is settled: ${d.length} elements fit. Name the one you mean as ${i.copyId}=<counterpart id>.`:`The element owns no copy ${i.copyId} that a counterpart fits.`,{exitCode:b.Usage,details:{copyId:i.copyId,candidateIds:d}})}s.set(i.copyId,a)}return[...s].map(([i,a])=>({copyId:i,counterpartId:a}))},eE=e=>Object.fromEntries(e.map(({copyId:t,counterpartId:n})=>[t,{decision:"USE_THEIRS",counterpartId:n}])),tE=(e,t)=>{let n=e.tree.label(t);return{id:t,...n===void 0?{}:{name:n}}},e0=(e,t,n)=>{let r=e.tree.label(t.copyId);return{copyId:t.copyId,...r===void 0?{}:{name:r},group:t.group,...t.counterpartId===void 0?{}:{counterpartId:t.counterpartId},...t.candidates===void 0?{}:{candidates:t.candidates},...t.notReplaceable===void 0?{}:{notReplaceable:t.notReplaceable.reason},replaced:n.has(t.copyId.toLowerCase())&&t.notReplaceable===void 0}},t0=async e=>{ss(e);let t=await Wt(e),n=e.api(),r=t.model.id,o=Dt(t),s=U(t.tree,e.args.element),i=(await n.dependencies.list(r,{ref:o})).items,{id:a,ref:d}=Qb(e.args.dependency),l=lt(i,a).length>0?mn(i,a,nE(e,t)):void 0;if(l!==void 0&&d!==void 0)throw k(`${g(t.model.name)} depends on ${a} already, which is compared at the release it pins: leave '@${d}' out.`,"modeldesk dependency connect --help");let c=l===void 0?void 0:cn(l,g(t.model.name),Xb),m=c===void 0?{modelId:a,...d===void 0||d==="main"?{}:{versionRef:d}}:{dependencyId:c.id},p=async w=>(await n.dependencies.connectionPreview(r,s,{...m,...w?{choices:w}:{}},o)).elements??[],h=await Zb(e,()=>p()),u=await p(h.length>0?eE(h):void 0),y=new Set(h.map(({copyId:w})=>w));return{...ga(e,t),element:tE(t,s),...c===void 0?{}:{dependency:qe(c)},replaces:h,copies:u.map(w=>e0(t,w,y))}},nE=(e,t)=>({name:g(t.model.name),address:e.args.model.model}),rE=A({path:["dependency","connect"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the connection of an element to the model it represents",description:"Connects an element whose type represents another model, such as a MIM Extern, to the dependency on that model, so it holds that model's elements by reference. Each copy --use names gives way to its counterpart, and what referred to the copy refers to the counterpart; every other copy stays owned. --settled replaces every copy whose counterpart the preview settles. The dependency has to be a direct one: stage it with dependency add first. The change is staged in your draft of the model as a change of its own, where the person you work for sees it in the app and commits it; -m says why, in your words. --dry-run reads the server's preview and stages nothing: each copy, its counterpart or its candidates, and whether it is replaced; it also compares with a model the model does not depend on yet, given as <model id>@<release|main>.",positionals:[N(F),{...$e("element"),toolDescription:"The element whose type represents another model, as its id or label path."},{name:"dependency",type:"string",required:!0,description:"The dependency's id, or its target model's id, from pin list; with --dry-run also a model the model does not depend on yet, as <model id>@<release|main>.",toolDescription:"The dependency's id, or its target model's id; with dryRun also a model not depended on yet, as <model id>@<release|main>."}],flags:{use:{type:{list:"string"},placeholder:"copy[=counterpart]",description:"A copy to replace, as <copy id>=<counterpart id> from --dry-run, or <copy id> alone for the counterpart the preview settles. Repeatable.",toolDescription:"Each copy to replace, as <copy id>=<counterpart id>, or <copy id> for the counterpart dryRun settles."},settled:{type:"boolean",description:"Replace every copy whose counterpart the preview settles and that can give way.",toolDescription:"Replace every copy whose counterpart dryRun settles and that can give way."},...q},dryRun:!0,examples:['modeldesk dependency connect <model> Extern/GML3 <dependency> -m "Use GML3 itself" --dry-run','modeldesk dependency connect <model> Extern/GML3 <dependency> --settled -m "Use GML3 itself"','modeldesk dependency connect <model> <element> <dependency> --use <copy>=<counterpart> -m "Use theirs"'],mcp:{...bt,pin:{},choice:{member:Et,value:"connect",description:"Connect element, whose type represents another model, to dependency: the counterparts use or settled name replace its copies. dryRun shows each copy and its candidates."}},resultSchema:zb.dependencyConnect,run:async e=>{if(e.dryRun)return{result:await t0(e)};if(Qb(e.args.dependency).ref!==void 0){let i="A connection is staged to a dependency the model has, named by its id or its target model's id; ",a="<model id>@<release|main> compares with a model it does not depend on yet, under ";throw k(`${i}${a}--dry-run only.`,"modeldesk dependency connect --help",{reason:`${i}${a}dryRun only.`})}let t=e.api(),n={id:""},r,o=[];return{result:{...(await Ct(e,async({target:i,edges:a,retried:d})=>{let l=U(i.tree,e.args.element);n=tE(i,l);let c=e.args.dependency.toLowerCase();r=d?QL(a,c):cn(mn(a,c,nE(e,i)),g(i.model.name),Xb);let m=r?.id??c,p=d?i.branch.id:Dt(i);return o=await Zb(e,async()=>(await t.dependencies.connectionPreview(i.model.id,l,{dependencyId:m},p)).elements??[]),{action:{type:"DEPENDENCY_CONNECT",elementId:l,dependencyId:m,...o.length>0?{choices:eE(o)}:{}},recorded:{...XL,ids:[l.toLowerCase()]}}})).base,element:n,...r===void 0?{}:{dependency:qe(r)},replaces:o}}},render:e=>{let t=e.element.name===void 0?e.element.id:`'${g(e.element.name)}'`,n=e.dependency===void 0?"the model compared with":`'${g(e.dependency.name)}'`,r=`${e.replaces.length} ${e.replaces.length===1?"copy":"copies"}`,o=(e.copies??[]).map(s=>{let i=s.name===void 0?s.copyId:`${g(s.name)} (${s.copyId})`,a=s.counterpartId??(s.candidates===void 0?"nothing fits":`one of ${s.candidates.map(({id:l})=>l).join(", ")}`),d=s.notReplaceable===void 0?"":`, stays owned: ${s.notReplaceable}`;return` ${s.replaced?"replaced":"kept"} ${i}: ${s.group}, ${a}${d}`});return Rt(e,{done:`${t} is connected to ${n}; ${r} gave way to their counterparts.`,would:[`Connecting ${t} to ${n} would replace ${r}:`,...o].join(`
220
+ `)})}});var oE={dependencyDisconnect:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},element:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},description:"The element disconnected."},dependency:{type:"object",properties:{id:{type:"string"},name:{type:"string"},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},versionRef:{type:"string",description:"The selector: `@HEAD`, or the name of the release it is pinned to."},commitId:{type:"string"},release:{type:"string",description:"The release pinned, for a version selector."}},description:"The dependency it was connected to, which stays."},droppedReferences:{type:"number",description:"How many references the disconnection left out; absent on a dry run and for a change found staged already."},members:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string"}}},description:"Present on a dry run: the members the element holds by reference, which become owned copies."},leftOut:{type:"array",items:{type:"object",properties:{elementId:{type:"string",description:"The element that loses the reference: a member a copy is made of, or an element of the model."},elementName:{type:"string"},relation:{type:"string"},targetId:{type:"string"},reason:{type:"string",description:"`TARGET_NOT_REACHABLE`, `OWNED_CHILD_MISSING` or `TERM_REFERENCE_NOT_A_CANDIDATE`."}}},description:"Present on a dry run: each reference the copies, or elements referring to a member, would leave out."},changeRequestId:{type:"string"},draft:{properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft the change sits in; on a dry run, the draft as it was; null when you hold none. May be null."},commit:{type:"object",properties:{recovered:{type:"boolean",description:"One of false, true."},next:{type:"string",description:"What a landing off main leaves the caller with."},url:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}},description:"Present when the draft was landed right after the change was staged."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},message:{type:"string"},url:{type:"string"},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Where the change went: the draft it sits in, aimed at its branch; on a dry run, what was read."},dryRun:{type:"boolean",description:"Present on a dry run: the server tried the change and kept nothing. Always true."},staged:{type:"boolean",description:"Whether the change is in your draft: staged now, or found staged under the request id. One of false, true."},alreadyStaged:{type:"boolean",description:"True when a change staged under the same request id was found in your draft and not staged again. One of false, true."},stagedCommitId:{type:"string"}},required:["schemaVersion","element","draft","model","message","url","ref","staged"]}};var r0={types:["ELEMENT_UPDATE"],along:["ELEMENT_CREATE"],subject:"element"},o0="@connectedDependency",s0=(e,t)=>{let n=e.tree.element(t)?.relations?.[o0]??{};return Object.values(n).flat()[0]?.id},sE=(e,t)=>{let n=t?.toLowerCase(),r=e.find(o=>o.type==="INTERNAL"&&o.id.toLowerCase()===n);return r===void 0?{}:{dependency:qe(r)}},iE=(e,t)=>{let n=e.tree.label(t);return{id:t,...n===void 0?{}:{name:n}}},i0=async e=>{ss(e);let t=await Wt(e),n=e.api(),r=Dt(t),o=U(t.tree,e.args.element),s=await n.dependencies.disconnectPreview(t.model.id,o,r),i=(await n.dependencies.list(t.model.id,{ref:r})).items;return{...ga(e,t),element:iE(t,o),...sE(i,s.dependencyId),members:s.members.map(({id:a,name:d,type:l})=>({id:a,name:d,type:l})),leftOut:s.droppedReferences.map(({elementId:a,elementName:d,relation:l,targetId:c,reason:m})=>({elementId:a,elementName:d,relation:l,targetId:c,reason:m}))}},aE=A({path:["dependency","disconnect"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the disconnection of an element from the model it represents",description:"Disconnects a connected element, such as a MIM Extern, from its dependency: each element it holds by reference becomes an owned copy of the version depended on, what referred to it refers to the copy, and the dependency stays. A reference a copy would make to a model this one does not depend on is left out, and the result counts them. A dependency elements are connected to cannot be removed until they are disconnected. The change is staged in your draft of the model as a change of its own, where the person you work for sees it in the app and commits it; -m says why, in your words. --dry-run reads the server's preview and stages nothing: the members that would become copies and each reference that would be left out, named.",positionals:[N(F),{...$e("element"),toolDescription:"The element whose type represents another model, as its id or label path."}],flags:q,dryRun:!0,examples:['modeldesk dependency disconnect <model> Extern/GML3 -m "Keep our own copies" --dry-run','modeldesk dependency disconnect <model> Extern/GML3 -m "Keep our own copies"'],mcp:{...bt,pin:{},choice:{member:Et,value:"disconnect",description:"Disconnect element: what it holds by reference becomes owned copies, and droppedReferences counts the references left out. dryRun names each."}},resultSchema:oE.dependencyDisconnect,run:async e=>{if(e.dryRun)return{result:await i0(e)};let t={id:""},n,r=[],o=await Ct(e,({target:s,edges:i})=>{let a=U(s.tree,e.args.element);return t=iE(s,a),n=s0(s,a),r=i,{action:{type:"DEPENDENCY_DISCONNECT",elementId:a},recorded:{...r0,ids:[a.toLowerCase()]}}});return{result:{...o.base,element:t,...sE(r,n),...o.droppedReferences===void 0?{}:{droppedReferences:o.droppedReferences}}}},render:e=>{let t=e.element.name===void 0?e.element.id:`'${g(e.element.name)}'`,n=e.dependency===void 0?"its dependency":`'${g(e.dependency.name)}'`,r=e.droppedReferences===void 0?"":` ${P(e.droppedReferences,"reference")} left out.`,o=(e.members??[]).map(i=>` copy ${g(i.name)} (${i.type})`),s=(e.leftOut??[]).map(i=>` left out ${g(i.elementName)} ${i.relation} -> ${i.targetId}: ${i.reason}`);return Rt(e,{done:`${t} is disconnected from ${n}; what it held by reference is owned as copies.${r}`,would:[`Disconnecting ${t} from ${n} would copy ${P(e.members?.length??0,"member")} and leave out ${P(e.leftOut?.length??0,"reference")}:`,...o,...s].join(`
221
+ `)})}});var dE={dependencyExternal:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},dryRun:{type:"boolean",description:"True for a dry run, which checks the request and sends nothing. One of false, true."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},source:{type:"object",properties:{type:{type:"string",description:'One of "content", "url".'},location:{type:"string"},filename:{type:"string"},bytes:{type:"number"}},description:"What the document is read from: the address the server fetches, or the content sent inline."},dependency:{type:"object",properties:{id:{type:"string"},name:{type:"string"},location:{type:"string"}},description:"The dependency as main now holds it; absent on a dry run."},url:{type:"string",description:"The model's app link."}},required:["schemaVersion","dryRun","model","source","url"]}};var d0=1024*1024,lE="modeldesk dependency external --help",cE=A({path:["dependency","external"],effect:"land-direct",summary:"Add a dependency on an external document",description:"Adds a dependency on a document outside ModelDesk, a vocabulary or schema the model refers to, committed to the model's main branch at once: the server reads the document at --url, or the content of --content under --filename (at most 1 MiB; give a larger document by address), through the metamodel --metamodel names or the model's own. A dependency on another model of the organization is staged with dependency add instead. Under an agent host it is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1.",positionals:[N(de)],flags:{url:{type:"string",placeholder:"address",description:"The public http or https address of the document, which the server fetches."},content:{type:"string",placeholder:"text",description:"The document's text, sent as it is, with --filename; at most 1 MiB.",toolDescription:"The document's text, as it is, with filename; at most 1 MiB. Give a larger one by url."},filename:{type:"string",placeholder:"name",description:"The name the content is known by, whose extension may tell the server its format."},metamodel:{type:"string",placeholder:"metamodel-id",description:"The metamodel the document is read through, when not the model's own."}},dryRun:!0,examples:["modeldesk dependency external <model> --url https://purl.org/dc/terms/",'modeldesk dependency external <model> --content "$(cat terms.ttl)" --filename terms.ttl'],mcp:{name:"dependency_external",description:"Adds a dependency on an external document, a vocabulary or schema at a public address (url) or its text (content with filename, at most 1 MiB), committed to the model's main branch at once: a draft cannot hold a fetched document. It needs the person's 'Act without your review' permission. Only fetch an address the person gave or confirmed; tell them what you will add first and add it on their word. A dependency_change remove stages taking it away again. A dependency on another model is dependency_change.",pin:{dryRun:!1}},resultSchema:dE.dependencyExternal,run:async e=>{let{url:t,content:n,filename:r,metamodel:o}=e.flags;if(t===void 0==(n===void 0))throw k("Name the document once: --url for an address, or --content with --filename.",lE);if(n!==void 0&&r===void 0)throw k("Content needs --filename, which names the document and may tell its format.",lE);let s=n===void 0?void 0:Buffer.from(n,"utf8");if(s!==void 0&&s.length>d0)throw new f(`The content is ${s.length} bytes, over the 1 MiB sent inline; give it by address.`,{exitCode:b.Usage,hosted:{hint:"Give the document by url instead."}});let i=s===void 0?{type:"url",location:t}:{type:"content",filename:r,bytes:s.length},a=e.args.model.model,d=e.api(),l=await d.models.identity(a),c={id:l.id,name:l.name},m=e.webUrl({kind:"model",modelId:c.id});if(e.dryRun)return{result:{dryRun:!0,model:c,source:i,url:m}};let p=await d.dependencies.create(c.id,{type:"EXTERNAL",...s===void 0?{location:t}:{filename:r,binaryData:s.toString("base64")},...o===void 0?{}:{metamodelId:o}});return{result:{dryRun:!1,model:c,source:i,dependency:{id:p.id,name:p.name,location:"location"in p&&typeof p.location=="string"?p.location:""},url:m}}},render:e=>{let t=e.source.type==="url"?e.source.location:e.source.filename,n=g(e.model.name);return e.dryRun?`Dry run: ${n} would depend on '${g(t)}'.
222
+ ${e.url}`:`${n} depends on '${g(e.dependency?.name??t)}', committed to main.
223
+ ${e.url}`}});var mE={dependencyPin:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},versionRef:{type:"string",description:"The selector that was sent: `@HEAD` for `@main`, else the release name."},previous:{type:"object",properties:{id:{type:"string"},name:{type:"string"},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},versionRef:{type:"string",description:"The selector: `@HEAD`, or the name of the release it is pinned to."},commitId:{type:"string"},release:{type:"string",description:"The release pinned, for a version selector."}},description:"The dependency as the model held it before the change."},dependency:{type:"object",properties:{id:{type:"string"},name:{type:"string"},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},versionRef:{type:"string",description:"The selector: `@HEAD`, or the name of the release it is pinned to."},commitId:{type:"string"},release:{type:"string",description:"The release pinned, for a version selector."}},description:"The dependency as your draft holds it; absent on a dry run and when nothing was staged."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Where the change went: the draft it sits in, aimed at its branch; on a dry run, what was read."},draft:{properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft the change sits in; on a dry run, the draft as it was; null when you hold none. May be null."},message:{type:"string"},changeRequestId:{type:"string"},staged:{type:"boolean",description:"Whether the change is in your draft: staged now, or found staged under the request id. One of false, true."},dryRun:{type:"boolean",description:"Present on a dry run: the server tried the change and kept nothing. Always true."},alreadyStaged:{type:"boolean",description:"True when a change staged under the same request id was found in your draft and not staged again. One of false, true."},stagedCommitId:{type:"string"},commit:{type:"object",properties:{recovered:{type:"boolean",description:"One of false, true."},next:{type:"string",description:"What a landing off main leaves the caller with."},url:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}},description:"Present when the draft was landed right after the change was staged."},url:{type:"string"}},required:["schemaVersion","versionRef","model","ref","draft","message","changeRequestId","staged","url"]}};var c0={managed:{reason:"pinned through the metamodel version, which dependency pin does not change.",hint:"Change the model's metamodel version in the app's model settings."},external:{reason:"not a model, so it has no release to pin."},transitive:{reason:"it follows the dependency that provides it.",hint:"Pin the direct dependency that provides it instead."}},m0=(e,t)=>e.find(n=>n.type==="INTERNAL"&&n.id.toLowerCase()===t),pE=A({path:["dependency","pin"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a move of a dependency to another release",description:`Re-pins one of the model's direct dependencies on another model. <dependency>@<release> pins that release of the target; <dependency>@main pins the target's head as it is now, and moves again only when you re-pin. Managed, external and transitive dependencies are refused, with the reason. pin set commits the same move to main directly. ${to}`,positionals:[N(F),{name:"dependency",type:{address:"model",slot:Pi},required:!0,description:"The dependency's id, or its target model's id, from pin list, at @<release> for that release of the target or @main for the target's head now.",toolDescription:"The dependency (its id or its target model's id, from list_dependencies)"}],flags:q,dryRun:!0,examples:['modeldesk dependency pin <model> <dependency>@2.0.0 -m "Follow UML 2.0"','modeldesk dependency pin <model>@agent/upgrade <dependency>@main -m "Track the head" --dry-run'],mcp:{...bt,choice:{member:Et,value:"pin",description:"Move dependency, at @<release> or @main, to that release of its target or to the target's head."}},resultSchema:mE.dependencyPin,run:async e=>{let t=e.args.dependency.model.toLowerCase(),n=os(e.args.dependency),r=e.api(),o,s=await Ct(e,async({target:a,edges:d,retried:l})=>{let c=g(a.model.name),m={name:c,address:e.args.model.model},p=l?(await r.dependencies.list(a.model.id,{ref:a.branch.id})).items.find(h=>lt([h],t).length>0):void 0;return o=cn(p??mn(d,t,m),c,c0),{action:{type:"DEPENDENCY_UPDATE",dependencyId:o.id,versionRef:n},recorded:{types:["DEPENDENCY_UPDATE"],ids:[o.id.toLowerCase()]}}}),i=o&&s.edgesAfter&&m0(s.edgesAfter,o.id.toLowerCase());return{result:{...s.base,versionRef:n,...o?{previous:qe(o)}:{},...i?{dependency:qe(i)}:{}}}},render:e=>{let t=e.previous?`'${g(e.previous.name)}'`:"The dependency",n=e.versionRef===Ee?"its target's head":g(e.versionRef),r=e.dependency?is(e.dependency):n,o=g(e.model.name);return Rt(e,{done:`${t} of ${o} is pinned to ${r}.`,would:`${t} of ${o} would be pinned to ${n}.`})}});var fE={dependencyRm:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},dependency:{type:"object",properties:{id:{type:"string"},name:{type:"string"},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},versionRef:{type:"string",description:"The selector: `@HEAD`, or the name of the release it is pinned to."},commitId:{type:"string"},release:{type:"string",description:"The release pinned, for a version selector."}},description:"The dependency as the model held it before the change. Absent when a change found staged under the same request id had already removed it."},external:{type:"object",properties:{id:{type:"string"},name:{type:"string"},location:{type:"string"}},description:"The external document removed, when the dependency was one; `dependency` names a model's."},outcome:{type:"string",description:'`removed`: the model no longer holds it. `kept-as-transitive`: another dependency still brings its target along, so it stays as one of theirs. Absent on a dry run and when nothing was staged. One of "kept-as-transitive", "removed".'},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Where the change went: the draft it sits in, aimed at its branch; on a dry run, what was read."},draft:{properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft the change sits in; on a dry run, the draft as it was; null when you hold none. May be null."},message:{type:"string"},changeRequestId:{type:"string"},staged:{type:"boolean",description:"Whether the change is in your draft: staged now, or found staged under the request id. One of false, true."},dryRun:{type:"boolean",description:"Present on a dry run: the server tried the change and kept nothing. Always true."},alreadyStaged:{type:"boolean",description:"True when a change staged under the same request id was found in your draft and not staged again. One of false, true."},stagedCommitId:{type:"string"},commit:{type:"object",properties:{recovered:{type:"boolean",description:"One of false, true."},next:{type:"string",description:"What a landing off main leaves the caller with."},url:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}},description:"Present when the draft was landed right after the change was staged."},url:{type:"string"}},required:["schemaVersion","model","ref","draft","message","changeRequestId","staged","url"]}};var f0={managed:{reason:"which stay while the model is written in that metamodel."},external:{reason:"which dependency rm removes only when the model depends on it directly."},transitive:{reason:"it stays as long as the dependency that provides it.",hint:"Remove the direct dependency that provides it instead."}},uE=["DEPENDENCY_DELETE","DEPENDENCY_UPDATE"],hE=(e,t)=>lt(e,t).find(n=>n.type==="INTERNAL"&&!n.transitive),gE=(e,t)=>lt(e,t).find(n=>n.type==="EXTERNAL"&&!n.transitive),u0="dependency-connected",h0=(e,t)=>{let n=e instanceof f&&Array.isArray(e.details.errors)?e.details.errors:[];return!(e instanceof f)||!n.some(r=>r.code===u0)?e:new f(e.reason,{exitCode:e.exitCode,type:e.type,requestId:e.requestId,details:e.details,hint:`Disconnect each element the errors name first, with 'modeldesk dependency disconnect ${t} <element>'.`,hosted:{...e.hosted,hint:r=>`Disconnect each element the errors name first, with ${r("dependency disconnect")} and change disconnect.`}})},yE=A({path:["dependency","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of a dependency",description:"Removes one of the model's direct dependencies, on another model or on an external document, with the dependencies it brought along that nothing else needs. One another dependency still brings along stays as a transitive one. A dependency whose content elements of the model still refer to is refused (exit 4), with the referring elements in details.errors, and so is one elements are connected to, until dependency disconnect disconnects them. Managed and transitive dependencies are refused, with the reason. "+to,positionals:[N(F),{name:"dependency",type:"string",required:!0,description:"The dependency's id, or its target model's id, from pin list.",toolDescription:"The dependency's id, or its target model's id, from list_dependencies."}],flags:q,dryRun:!0,examples:['modeldesk dependency rm <model> <dependency> -m "No longer a profile of UML"','modeldesk dependency rm <model> <dependency> -m "No longer a profile of UML" --dry-run'],mcp:{...bt,choice:{member:Et,value:"remove",description:"Remove dependency, a direct dependency's id or its target model's id; an external one by its id."}},resultSchema:fE.dependencyRm,run:async e=>{let t=e.args.dependency.toLowerCase(),n=e.api(),r,o,s=await Ct(e,async({target:c,edges:m,retried:p})=>{let h=g(c.model.name);if(p){let w=(await n.dependencies.list(c.model.id,{ref:c.branch.id})).items;r=hE(w,t)??hE(m,t),o=r?void 0:gE(w,t)??gE(m,t);let E=[...lt([...w,...m],t).map(I=>I.id.toLowerCase()),t];return{action:{type:"DEPENDENCY_DELETE",dependencyId:r?.id??o?.id??t},recorded:{types:uE,ids:E}}}let u=mn(m,t,{name:h,address:e.args.model.model});u.type==="EXTERNAL"&&!u.transitive?o=u:r=cn(u,h,f0);let y=o?.id??r?.id??u.id;return{action:{type:"DEPENDENCY_DELETE",dependencyId:y},recorded:{types:uE,ids:[y.toLowerCase()]}}}).catch(c=>{throw h0(c,e.args.model.model)}),{edgesAfter:i}=s,a=r?.modelId.toLowerCase(),d=i&&(a===void 0?lt(i,t):i.filter(c=>c.type==="INTERNAL"&&c.modelId.toLowerCase()===a)),l=d?.some(c=>c.transitive)?"kept-as-transitive":"removed";return{result:{...s.base,...r?{dependency:qe(r)}:{},...o?{external:{id:o.id,name:o.name,location:o.location}}:{},...d?{outcome:l}:{}}}},render:e=>{let t=e.dependency??e.external,n=t?`'${g(t.name)}'`:"The dependency",r=g(e.model.name);return Rt(e,{done:e.outcome==="kept-as-transitive"?`${n} is no longer a direct dependency of ${r}; another dependency still brings it along.`:`${n} is removed from the dependencies of ${r}.`,would:`${n} would be removed from the direct dependencies of ${r}.`})}});var wE={modelImportsMerge:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},dryRun:{type:"boolean",description:"True for a dry run: the plan, and nothing written. One of false, true."},importId:{type:"string"},model:{type:"object",properties:{id:{type:"string"}},description:"The model the import goes into, and the branch it merges into."},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},counts:{type:"object",properties:{added:{type:"number"},changed:{type:"number"},removed:{type:"number"},moved:{type:"number"},conflicts:{type:"number"}},description:"What the merge would change, by kind, and how many conflicts there are."},blockers:{type:"array",items:{type:"string"},description:"What would refuse the merge whatever side a conflict is taken from."},targetCommitId:{type:"string",description:"The branch head the plan read, which a merge sends back so it lands only there."},sourceCommitId:{type:"string",description:"The import's commit, the merge commit's second parent."},outcome:{type:"string",description:'After a merge: `merged`, or `nothing-to-merge` when the branch already held the import. One of "merged", "nothing-to-merge".'},commitId:{type:"string",description:"After a merge that landed: the merge commit."},url:{type:"string",description:"The model's app link."}},required:["schemaVersion","dryRun","importId","model","branch","counts","blockers","targetCommitId","sourceCommitId","url"]}};var bE="modeldesk model imports merge --help",EE=A({path:["model","imports","merge"],effect:"land-direct",summary:"Merge an import that waits in a model",description:"Merges a newer file imported into a model, which waits on the model's import line, into the branch it goes into, as one merge commit. --dry-run prints the plan and writes nothing: what the merge would change, its conflicts and what would refuse it, and the branch head it read. A merge takes that head as --expect, so it lands only on the branch the plan was read from (exit 5 otherwise); --take-others takes every conflict from one side. Under an agent host a merge is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1; the plan runs.",positionals:[{name:"import-id",type:"string",required:!0,description:"The import's id, as 'model import' or 'model imports list' prints it."}],flags:{expect:{type:"string",placeholder:"target-head",description:"The branch head the plan reported (targetCommitId); required for a merge.",toolDescription:"The branch head the plan reported (targetCommitId); required unless dryRun."},"take-others":{type:{enum:["target","source"]},description:"The side every conflict is taken from whole: the branch's (target) or the file's (source)."},message:{type:"string",short:"m",placeholder:"message",description:"What the merge commit is called in history; 'Imported' and the file's name unless given."}},dryRun:!0,examples:["modeldesk model imports merge <import-id> --dry-run --json","modeldesk model imports merge <import-id> --expect <target-head>"],mcp:{name:"import_merge",description:"Merges an import waiting in a model (model_import into a model) into the branch it goes into, as one merge commit. Call it with dryRun first: that is the plan, what the merge would add, change, remove and move, its conflicts and blockers, and writes nothing. Show the person the plan and merge only on their word, passing expect as the plan's targetCommitId; takeOthers takes every conflict from one side. A merge needs the person's 'Act without your review' permission."},resultSchema:wE.modelImportsMerge,run:async e=>{let t=e.args["import-id"];if(!B(t))throw k(`'${t}' is not an import id.`,bE);let{expect:n,message:r}=e.flags,o=e.flags["take-others"];if(!e.dryRun&&n===void 0)throw k("A merge takes --expect, the branch head the plan reported, so it lands on what was reviewed. Run it with --dry-run first.",bE);let s=e.api(),[i,a]=await Promise.all([s.imports.get(t),s.imports.plan(t)]),d=i.targetModelId??"",l={dryRun:e.dryRun,importId:t,model:{id:d},branch:{id:a.targetBranch.id,name:a.targetBranch.name},counts:a.counts,blockers:a.blockers,targetCommitId:a.targetCommitId,sourceCommitId:a.sourceCommitId,url:e.webUrl({kind:"model",modelId:d})};if(e.dryRun)return{result:l};let c=await s.imports.merge(t,{expectedHeadId:n,expectedSourceHeadId:a.sourceCommitId,...o===void 0?{}:{takeOthers:o},...r===void 0?{}:{message:r}});return{result:{...l,outcome:c.outcome,...c.commit?.id===void 0?{}:{commitId:c.commit.id}}}},render:e=>{let{added:t,changed:n,removed:r,moved:o,conflicts:s}=e.counts,i=`${t} added, ${n} changed, ${r} removed, ${o} moved, ${s} conflicts into ${g(e.branch.name)}`;return e.dryRun?`Plan of import ${e.importId}: ${i}.
224
+ Merge with --expect ${e.targetCommitId}.`:e.outcome==="nothing-to-merge"?`Import ${e.importId}: the branch already held it; completed without a commit.
225
+ ${e.url}`:`Merged import ${e.importId}: ${i}, as commit ${e.commitId??""}.
226
+ ${e.url}`}});var CE={describe:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What the schema was resolved at: your draft while it holds staged changes, else your working branch, or the ref named."},schema:{type:"object",properties:{modelId:{type:"string"},metamodel:{type:"object",properties:{id:{type:"string"},name:{type:"string"},version:{type:"string"},prefix:{type:"string"}}},root:{type:"array",items:{type:"object",properties:{type:{type:"string"},label:{type:"string"},multiplicity:{type:"object",properties:{min:{type:"number"},max:{type:"number"}}},instantiableTypes:{type:"array",items:{type:"string"}}}}},types:{type:"array",items:{type:"object",properties:{name:{type:"string"},label:{type:"string"},abstract:{type:"boolean",description:"One of false, true."},package:{type:"boolean",description:"One of false, true."},trait:{type:"boolean",description:"One of false, true."},internal:{type:"boolean",description:"One of false, true."},specializes:{type:"array",items:{type:"string"}},traits:{type:"array",items:{type:"string"}}}}},type:{type:"object",properties:{name:{type:"string"},label:{type:"string"},definition:{type:"string"},abstract:{type:"boolean",description:"One of false, true."},package:{type:"boolean",description:"One of false, true."},trait:{type:"boolean",description:"One of false, true."},internal:{type:"boolean",description:"One of false, true."},specializes:{type:"array",items:{type:"string"}},supertypes:{type:"array",items:{type:"string"}},traits:{type:"array",items:{type:"string"}},keyProperties:{type:"array",items:{type:"string"}},instantiableTypes:{type:"array",items:{type:"string"}},attributes:{type:"array",items:{type:"object",properties:{name:{type:"string"},label:{type:"string"},definedBy:{type:"string"},multiplicity:{type:"object",properties:{min:{type:"number"},max:{type:"number"}}},schema:{type:"object",properties:{type:{type:"string",description:'One of "any", "boolean", "integer", "number", "object", "string".'},properties:{type:"object",additionalProperties:{type:"object",properties:{type:{type:"string",description:'One of "any", "boolean", "integer", "number", "string".'},absentDiffers:{type:"boolean",description:"One of false, true."},trueLabel:{type:"object",additionalProperties:{type:"string"}},falseLabel:{type:"object",additionalProperties:{type:"string"}},format:{type:"string"},minimum:{type:"number"},maximum:{type:"number"},enum:{type:"array",items:{type:"string"}},multiline:{type:"boolean",description:"One of false, true."},tokenSet:{type:"boolean",description:"One of false, true."},exclusiveTokens:{type:"array",items:{type:"string"}},lang:{type:"object",properties:{optional:{type:"boolean",description:"One of false, true."},uniqueLang:{type:"boolean",description:"One of false, true."}}},enumLabels:{type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}}}}},required:{type:"array",items:{type:"string"}},absentDiffers:{type:"boolean",description:"One of false, true."},trueLabel:{type:"object",additionalProperties:{type:"string"}},falseLabel:{type:"object",additionalProperties:{type:"string"}},format:{type:"string"},minimum:{type:"number"},maximum:{type:"number"},enum:{type:"array",items:{type:"string"}},multiline:{type:"boolean",description:"One of false, true."},tokenSet:{type:"boolean",description:"One of false, true."},exclusiveTokens:{type:"array",items:{type:"string"}},lang:{type:"object",properties:{optional:{type:"boolean",description:"One of false, true."},uniqueLang:{type:"boolean",description:"One of false, true."}}},enumLabels:{type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}}}},derived:{type:"boolean",description:"One of false, true."}}}},relations:{type:"array",items:{type:"object",properties:{name:{type:"string"},label:{type:"string"},definedBy:{type:"string"},multiplicity:{type:"object",properties:{min:{type:"number"},max:{type:"number"}}},ownership:{type:"string",description:'One of "MIXED", "MULTI_OWNED", "OWNED", "UNOWNED".'},allowedTargetTypes:{type:"array",items:{type:"object",properties:{name:{type:"string"},label:{type:"string"},foreign:{type:"boolean",description:"One of false, true."},metamodelId:{type:"string"}}}},parentBound:{type:"boolean",description:"One of false, true."},unrestricted:{type:"boolean",description:"One of false, true."},derived:{type:"boolean",description:"One of false, true."},abstract:{type:"boolean",description:"One of false, true."}}}},homeSlots:{type:"array",items:{type:"object",properties:{ownerType:{type:"string"},relation:{type:"string"}}}},childSlots:{type:"array",items:{type:"object",properties:{relation:{type:"string"},targetTypes:{type:"array",items:{type:"string"}}}}},kindGroups:{type:"array",items:{type:"object",properties:{classifier:{type:"string"},kinds:{type:"array",items:{type:"string"}},shared:{type:"array",items:{type:"string"}},distinguishing:{type:"array",items:{type:"object",properties:{binding:{type:"string"},kinds:{type:"array",items:{type:"string"}}}}}}}}}}}}},required:["schemaVersion","model","ref","schema"]}};var RE="type-not-found",Em=({min:e,max:t})=>`${e??0}..${t===void 0||t<0?"*":t}`,w0=e=>{if(e===void 0)return"";switch(e.type){case"string":{let t=[e.format,e.lang?"language-tagged":void 0,e.enum?`one of ${e.enum.join(", ")}`:void 0].filter(n=>n!==void 0);return t.length===0?"string":`string (${t.join("; ")})`}case"integer":case"number":{let t=e.minimum!==void 0||e.maximum!==void 0?` ${e.minimum??""}..${e.maximum??""}`:"";return`${e.type}${t}`}default:return e.type}},kE=e=>["abstract","package","trait","internal"].filter(t=>e[t]).join(", "),b0=e=>e.parentBound?"the owner's type ($parent)":e.unrestricted?"any type":(e.allowedTargetTypes??[]).map(t=>t.foreign?`${t.name} (foreign)`:t.name).join(", "),rr=(e,t)=>[`${e}:`,...t.length===0?[" none"]:t],E0=(e,t)=>{let n=new Set((e.types??[]).filter(a=>a.internal).map(a=>a.name)),r=a=>t||!(n.has(a)||Vn(a)),o=(e.root??[]).filter(a=>r(a.type)),s=(e.types??[]).filter(a=>r(a.name)),i=(e.types??[]).length-s.length;return[...rr("Root",W(o.map(a=>[a.type,g(a.label),Em(a.multiplicity),a.instantiableTypes&&a.instantiableTypes.join()!==a.type?`creates ${a.instantiableTypes.join(", ")}`:""]),{indent:" "})),...rr("Types",s.length===0?[]:W([["NAME","LABEL","KIND","SPECIALIZES"],...s.map(a=>[a.name,g(a.label),kE(a),(a.specializes??[]).join(", ")])],{indent:" "})),...i>0?[`(${i} internal types not shown; pass --internal to list them.)`]:[]]},C0=e=>{let t=[["kind:",kE(e)],["definition:",g(e.definition??"")],["supertypes:",(e.supertypes??[]).join(", ")],["traits:",(e.traits??[]).join(", ")],["instantiable as:",(e.instantiableTypes??[]).join(", ")],["keyed by:",(e.keyProperties??[]).join(", ")]],n=i=>[i.derived?"derived":"",i.abstract?"abstract":""].filter(a=>a!=="").join(", "),r=(e.attributes??[]).map(i=>[i.name,g(i.label),w0(i.schema),Em(i.multiplicity),i.definedBy?`from ${i.definedBy}`:"",n(i)]),o=(e.relations??[]).map(i=>[i.name,g(i.label),Em(i.multiplicity),i.ownership,b0(i),i.definedBy?`from ${i.definedBy}`:"",n(i)]),s=(e.kindGroups??[]).flatMap(i=>[` ${i.classifier}: ${i.kinds.join(", ")}`,...i.shared?.length?[` shared: ${i.shared.join(", ")}`]:[],...(i.distinguishing??[]).map(a=>` ${a.binding}: ${a.kinds.join(", ")}`)]);return[`${e.name} (${g(e.label)})`,...W(t.filter(([,i])=>i!==""),{indent:" "}),...rr("Attributes",r.length===0?[]:W([["NAME","LABEL","SCHEMA","MULT","DEFINED",""],...r],{indent:" "})),...rr("Relations",o.length===0?[]:W([["NAME","LABEL","MULT","OWNERSHIP","TARGETS","DEFINED",""],...o],{indent:" "})),...rr("Home slots (where it can live)",(e.homeSlots??[]).map(i=>` ${i.ownerType}.${i.relation}`)),...rr("Child slots (what can be created inside it)",(e.childSlots??[]).map(i=>` ${i.relation}: ${i.targetTypes.join(", ")}`)),...s.length===0?[]:rr("Kind groups",s)]},R0=(e,t)=>{let{metamodel:n}=e;return[`Metamodel ${g(n.name)}`+(n.version?` ${n.version}`:"")+(n.prefix?` (prefix ${n.prefix})`:""),...e.type?C0(e.type):E0(e,t)].join(`
227
+ `)},k0=(e,t)=>{let n=e.problem?.candidates,r=Array.isArray(n)?n.filter(o=>typeof o=="string"):[];return new f(e.problem?.detail??`The metamodel declares no type '${e.problem?.typeName}'.`,{exitCode:r.length>0?b.Usage:b.NotFound,type:RE,requestId:e.requestId,details:e.details,hint:r.length>0?"Pass one of the candidates.":`Run 'modeldesk describe ${t}' to list the types of its metamodel.`,hosted:{hint:o=>r.length>0?"Pass one of the candidates.":`Call ${o("describe")} with model ${t} alone to list the types of its metamodel.`}})},vE=A({path:["describe"],effect:"read",summary:"Describe the schema a model is written against",description:"Without a type: the types the model root admits and every classifier of its metamodel, with its label, kind and supertypes. With a type (canonical, such as sh:NodeShape, or any spelling naming one classifier): its supertypes and traits, its attributes with value schema and multiplicity, its relations with multiplicity, ownership and resolved allowed targets, where an element of it can live, what can be created inside one, and the kind groups of a discriminated branch. Read at the ref the address names, else where you work, since a dependency staged in your draft brings its target's metamodel into the schema. --json prints the server document as schema.",positionals:[N(_e),{name:"type",type:"string",description:"The classifier to describe in full."}],flags:{internal:{type:"boolean",description:"List the internal types (`@` types and auxiliary ones) in the overview too; --json always carries them."}},examples:["modeldesk describe <model>","modeldesk describe <model>@agent/profile sh:NodeShape --json"],mcp:{name:"describe",description:"Describes the schema a model is written against at the ref you give. Without type it lists the types the model root admits and every classifier with its label, kind and supertypes. With type it gives that type's attributes with value schema and multiplicity, its relations with their allowed targets, where an element of it can live and what can be created inside one. Call it before staging, to learn the type, attribute and relation names that stage_changes takes. Write the ref you stage on: a dependency staged there adds its types.",pin:{internal:!1}},resultSchema:CE.describe,run:async e=>{let{model:t,type:n}=e.args,r=await ae(e,t,_e),o=le(r);o.note!==void 0&&e.note(o.note);try{let s=await e.api().models.schema(r.id,{ref:o.id,type:n});return{result:{model:{id:r.id,name:r.name},ref:o,schema:s}}}catch(s){throw s instanceof V&&s.type===RE?k0(s,t.text):s}},render:(e,t)=>R0(e.schema,t.internal)});var IE={draftDiscard:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},discarded:{type:"boolean",description:"False on a dry run, and when there was no draft to discard, which is not an error: a repeated discard is harmless. One of false, true."},dryRun:{type:"boolean",description:"One of false, true."},draft:{properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}}},description:"The draft as it stood when it was discarded, or null when there was none. May be null."}},required:["schemaVersion","resource","discarded","dryRun","draft"]}};var Cm=e=>`Discarding your draft of ${e}`,SE="pass --any-surface only when they asked for it.",$E=A({path:["draft","discard"],effect:"unstage",summary:"Discard your draft and everything staged on it",description:"Discards your draft with every change staged on it, whichever surface staged them. It restates what it will discard and asks at a terminal; anywhere else it needs --yes. It sends the draft head it read, so a change staged after that is not destroyed unseen (exit 5). Holding no draft is reported, not refused. --dry-run restates what it would discard and discards nothing; --expect holds the discard to the head it reported. Under an agent host a draft holding changes made outside an agent session (in the app) is left to a person (exit 6) unless --any-surface.",positionals:[je],flags:{expect:{type:"string",placeholder:"draft-head",description:"The draft head the discard must find: a draft at any other head is kept (exit 5).",toolDescription:"The draft head the discard must find, as the dry run reported it: a draft at any other head is kept."},...kr},dryRun:!0,examples:["modeldesk draft discard <model> --dry-run","modeldesk draft discard <model> --yes"],mcp:{name:"draft_discard",irreversible:!0,description:"Throws your draft away with every change staged on it, which nobody can restore. A draft holding only changes your own session staged is discarded with your grant to stage; one holding the person's or another session's changes needs their 'Act without your review' permission. Call it with dryRun: true first, show the person what it would discard, and discard only on their word, with expect set to the draft's headCommitId the dry run reported, so a change made since is not thrown away unseen. To take back one change, call draft_undo instead."},resultSchema:IE.draftDiscard,prepare:async e=>oe(async()=>{if(e.dryRun)return;let t=await Le(e),n=await t.read();if(n===void 0)return;let r=ce(t.ref),o=P(n.changeCount,"staged change");return await Be(e,t,n,{scope:{kind:"all"},action:Cm(r),anySurface:e.flags["any-surface"],override:SE}),await yt(e,`Discard your draft of ${r} with its ${o}?`,`${Cm(r)} (${o})`),{headCommitId:n.headCommitId}}),run:async(e,t)=>oe(async()=>{let n=await Le(e),r=ce(n.ref),o=await n.read(),{dryRun:s}=e,i={resource:n.ref,discarded:!1,dryRun:s,draft:null};if(o===void 0)return{result:i};if(s)return{result:{resource:n.ref,discarded:!1,dryRun:s,draft:o}};let{expect:a}=e.flags;if(e.agent?.surface==="mcp"&&a===void 0)throw k("A hosted discard takes --expect, the draft head its dry run reported. Run it with --dry-run first.",`modeldesk ${e.commandName} --help`,{reason:"A discard takes 'expect', the headCommitId of the dry run you showed the person, so it throws away only what they saw. Nothing was discarded."});if(a!==void 0&&!B(a))throw k("--expect takes the draft head id a read reported.",`modeldesk ${e.commandName} --help`,{reason:"'expect' takes the draft head id a read reported."});t===void 0&&await Be(e,n,o,{scope:{kind:"all"},action:Cm(r),anySurface:e.flags["any-surface"],override:SE});try{await n.discard(a??t?.headCommitId??o.headCommitId)}catch(d){if(d instanceof V&&d.status===404)return{result:i};throw d instanceof f&&d.type==="draft-moved"?new f(`Your draft of ${r} moved after this command read it, so nothing was discarded.`,{exitCode:b.Conflict,type:d.type,details:d.details,hint:"Run 'modeldesk draft status' to see what it now holds, then discard again if you still mean to.",hosted:{hint:l=>`Call ${l("draft status")} to see what it now holds, and ask the person again.`}}):d}return{result:{resource:n.ref,discarded:!0,dryRun:s,draft:o}}}),render:e=>{let t=ce(e.resource);if(e.draft===null)return`You hold no draft of ${t}; nothing was discarded.`;let n=`${t} (${P(e.draft.changeCount,"staged change")})`;return e.dryRun?`Would discard your draft of ${n}. Dry run: nothing was discarded.`:`Discarded your draft of ${n}.`}});var or=async(e,t,n)=>{let r=0,o=!1,s=async()=>{for(;!o&&r<e.length;)try{await n(e[r++])}catch(i){throw o=!0,i}};await Promise.all(Array.from({length:Math.min(t,e.length)},s))};var km=600,wa=86400,vm=90,ba=120,as={kind:"keep-waiting"},xE={kind:"draft-reset"},I0=(e,t)=>{let n=e.find(s=>s.refId===t.draftId);if(n===void 0)return{reading:{kind:"draft-missing"},held:t};if(t.draftResets!==void 0&&n.resets!==t.draftResets)return{reading:xE,held:t};let r=e.find(s=>s.refId===t.targetRefId);if(r!==void 0&&r.headCommitId!==t.targetHead)return{reading:{kind:"branch-moved",branchHeadId:r.headCommitId},held:t};let o={...t,draftHead:n.headCommitId,draftResets:n.resets};return t.draftResets===void 0&&n.headCommitId!==t.draftHead?{reading:{kind:"draft-moved",from:t.draftHead},held:o}:{reading:as,held:o}},S0=(e,t)=>{switch(e.event){case"heads":return I0(e.heads,t);case"ref-deleted":return{reading:e.refId===t.draftId?{kind:"draft-deleted"}:as,held:t};case"head-advanced":return e.refId===t.draftId?e.reset?{reading:xE,held:t}:{reading:as,held:{...t,draftHead:e.headCommitId}}:e.refId===t.targetRefId&&e.headCommitId!==t.targetHead?{reading:{kind:"branch-moved",branchHeadId:e.headCommitId},held:t}:{reading:as,held:t};default:return{reading:as,held:t}}},$0=8,T0=5,AE=100,x0=async(e,t,n,r)=>{try{return(await e.api().models.commits(t,{ref:n,limit:AE,cursor:r})).items}catch(o){if(o instanceof V&&o.status===404)return;throw o}},A0=async(e,t,n)=>{let r=[],o;for(let s=0;s<T0;s++){let i=await x0(e,t,n.targetRefId,o);if(i===void 0)return;for(let a of i){if(a.id===n.baselineCommitId)return r;a.stagedChangeCount!==void 0&&r.push(a)}if(i.length<AE)return r;o=i.at(-1)?.id}return r},O0=async(e,t,n,r)=>{let o=await A0(e,t,n);if(o===void 0)return{verdict:"discarded"};let s=new Map;await or(o,$0,async a=>{let d=await e.api().models.commitHeader(t,a.id,{ref:n.targetRefId});s.set(a.id,(d.stagedChanges??[]).filter(l=>r.has(l.requestId??"")).length)});let i=o.find(a=>(s.get(a.id)??0)>0);return i===void 0?{verdict:"discarded"}:{verdict:"committed",commitId:i.id,url:e.webUrl({kind:"commit",modelId:t,commitId:i.id}),landed:s.get(i.id)??0}},M0=[500,1500],OE=e=>e instanceof f&&e.exitCode===b.Transient,no=class extends Error{},N0=e=>new Promise(t=>setTimeout(t,e)),ME=async e=>{for(let t of M0)try{return await e()}catch(n){if(!OE(n))throw n;await N0(t)}return e()},NE=(e,t)=>new Promise((n,r)=>{let o=()=>r(new no);if(e.aborted){o();return}e.addEventListener("abort",o,{once:!0}),t().then(n,r).finally(()=>e.removeEventListener("abort",o))}),P0=async(e,t,n)=>{let r=await ht(()=>e.api().models.draft(t));return r?.id===n?r:void 0},Rm={kind:"gone"},ya={kind:"keep-waiting"},TE=e=>({kind:"verdict",verdict:{verdict:"changed",changeCount:e.changeCount}}),D0=async(e,t,n,r,o)=>{if(r.baselineCommitId!==n.baselineCommitId)return!1;if(o===n.baselineCommitId)return!0;try{return(await ze(e.api(),t,n.id)).some(i=>i.id===o)}catch(s){if(_i(s))return;throw s}},L0=async(e,t,n,r)=>{if(e.kind==="keep-waiting")return ya;if(e.kind==="draft-deleted")return Rm;let o=await P0(t,n,r.id);if(o===void 0)return Rm;switch(e.kind){case"draft-missing":return ya;case"draft-reset":return TE(o);case"branch-moved":return{kind:"verdict",verdict:{verdict:"branch-moved",branchHeadId:e.branchHeadId}};case"draft-moved":{let s=await D0(t,n,r,o,e.from);return s===void 0?Rm:s?ya:TE(o)}}},Im=(e,t)=>new f(`You hold no draft of ${e}, so there is nothing to wait on.`,{type:"no-draft",hint:`It was committed or discarded before the wait began, or never opened. Run 'modeldesk model log ${t} --changes' to see whether your changes landed.`,hosted:{hint:n=>`The person has already answered (committed or discarded the draft), or nothing was handed off. Call ${n("model log")} with model ${t} and changes true to see whether your changes landed.`}}),_0=async(e,t,n,r)=>{let o;try{o=await ze(e.api(),t,n)}catch(s){throw _i(s)?Im(r.subject,r.address):s}return new Set(o.map(s=>s.requestId).filter(s=>s!==void 0&&ko(s,e.origin)))},j0=(e,t,n)=>{let r=`'modeldesk draft diff ${t} --changes' to see where each change came from.`,o=s=>`Call ${s("draft diff")} with model ${t} and changes true to see where each change came from.`;return Ro(n)===void 0?new f(`None of the staged changes in your draft of ${e} was made by the CLI or an agent, so there is nothing of yours to wait on.`,{type:"no-own-changes",hint:`Run ${r}`,hosted:{hint:o}}):new f(`None of the staged changes in your draft of ${e} was made by this agent session, so there is nothing of its own to wait on.`,{type:"no-own-changes",hint:`Wait from the session that staged them, under the same MODELDESK_AGENT_SESSION, or run ${r}`,hosted:{hint:s=>`The person may have removed them first, or another connection staged them. ${o(s)}`}})},PE=(e,t,n,r)=>new f(`No verdict on your draft of ${e} within ${t} seconds; the draft is as it was.`,{exitCode:b.Transient,type:Fu,hint:`Run '${n}' again to keep waiting.`,hosted:{reason:`No verdict on your draft of ${e} yet; the draft is as it was.`,hint:o=>`Call ${o("draft status")} again with wait: true to keep waiting.`},report:r}),F0=(e,t,n)=>new f(`Your draft of ${e} is gone, and the commits that say whether it landed could not be read (${n.reason}).`,{exitCode:b.Transient,type:"verdict-unread",hint:`Run 'modeldesk model log ${t} --changes' to see whether your changes landed.`,hosted:{hint:r=>`Call ${r("model log")} with model ${t} and changes true to see whether your changes landed.`}}),q0=async(e,t,n,r,o)=>{let{modelId:s,draft:i}=o,{held:a}=o;try{for await(let d of e.events(s,AbortSignal.any([r,n]))){let l=S0(d,a);a=l.held;let c=await NE(n,()=>ME(()=>L0(l.reading,t,s,i)));if(c.kind!=="keep-waiting")return c}}catch(d){if(!(d instanceof no))throw d}return ya},DE=async(e,t,n,r)=>{let o=await _0(e,t,n.id,r);if(o.size===0)throw j0(r.subject,r.address,e.origin);if(r.branchHeadId!==n.baselineCommitId)return{verdict:"branch-moved",branchHeadId:r.branchHeadId};let s={draftId:n.id,targetRefId:n.targetRefId,draftHead:n.headCommitId,targetHead:r.branchHeadId},i=new AbortController,a=setTimeout(()=>i.abort(),Math.max(0,r.deadline()-Date.now())),d=new AbortController,l=e.deadline===void 0?void 0:setTimeout(()=>d.abort(),Math.max(0,e.deadline-Date.now())),c=e.signal===void 0?d.signal:AbortSignal.any([d.signal,e.signal]),m={...e,api:()=>{if(c.aborted)throw new no;return e.api()}};try{let p;try{p=await q0(e,m,c,i.signal,{modelId:t,draft:n,held:s})}finally{clearTimeout(a),i.abort()}switch(p.kind){case"keep-waiting":return{verdict:"timed-out"};case"verdict":return p.verdict;case"gone":try{return await NE(c,()=>ME(()=>O0(m,t,n,o)))}catch(h){if(h instanceof no)return{verdict:"timed-out"};throw OE(h)?F0(r.subject,r.address,h):h}}}finally{clearTimeout(l)}};var LE={draftStatus:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},draft:{properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Your draft and the branch it targets, or null when you hold none. May be null."},maxChanges:{type:"number",description:"The most changes a draft holds; staging past it is refused until the draft is committed."},branchHeadCommitId:{type:"string",description:"The head of the branch the draft lands on, main's (the dataset's) without a draft."},behind:{type:"boolean",description:"Whether the branch moved past the draft's baseline, so a commit needs a rebase first. Absent without a draft. One of false, true."},reads:{type:"object",properties:{default:{type:"string",description:'One of "draft", "head".'},head:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What an invocation that names no ref reads right now: your draft while it holds staged changes, else the head of the branch it targets, main when you hold none. A dataset's branch is named only by a draft that targets it."},url:{type:"string",description:"The app page where the draft is reviewed and committed; absent for a dataset."},verdict:{type:"string",description:'One of "branch-moved", "changed", "committed", "discarded".'},branchHeadId:{type:"string",description:"The head the branch moved to."},changeCount:{type:"number",description:"How many changes the draft holds now."},commitId:{type:"string",description:"The landing that holds this session's changes."},landed:{type:"number",description:"How many of this session's changes it landed."}},required:["schemaVersion","resource","draft","maxChanges","branchHeadCommitId","reads"]}};var _E=e=>"name"in e?g(e.name):e.id,H0=e=>{let{draft:t,reads:n}=e,r=()=>{let s=n.head===void 0?"the branch head":`the head of ${_E(n.head)}`;return`Unaddressed reads see ${n.default==="draft"?"your draft":s}.`};if(t===null)return[`You hold no draft of ${ce(e.resource)}.`,r(),...e.url?[`url: ${e.url}`]:[]].join(`
228
+ `);let o=e.behind?`${t.baselineCommitId} (behind the branch head ${e.branchHeadCommitId}: rebase before committing)`:t.baselineCommitId;return[`Your draft of ${ce(e.resource)}, aimed at ${_E(t.target)}:`,...W([["draft:",t.id],["changes:",`${t.changeCount} of at most ${e.maxChanges}`],["baseline:",o],["head:",t.headCommitId],["created:",t.createdAt],["updated:",t.updatedAt],...e.url?[["url:",e.url]]:[]],{indent:" "}),r()].join(`
229
+ `)},B0=e=>{let t=ce(e.resource);switch(e.verdict){case"committed":return[`Your draft of ${t} was committed as ${e.commitId}, with ${e.landed} of your changes.`,`url: ${e.url}`].join(`
230
+ `);case"discarded":return`None of your changes to ${t} landed: the draft was discarded, or they were removed before it was committed.`;case"changed":return`Your draft of ${t} was changed in review; it now holds ${P(e.changeCount,"change")}.`;case"branch-moved":{let n=e.draft===null?e.resource.id:_r(e.resource,e.draft.target);return`The branch your draft of ${t} aims at moved to ${e.branchHeadId}. Run 'modeldesk draft rebase ${n}', resolve any conflict in your own changes, then wait again.`}}},Sm=e=>e.name===void 0?{id:e.id}:{id:e.id,name:e.name},Ea="modeldesk draft status --help",U0=(e,t,n)=>{if(t!==void 0&&!e)throw k("--timeout bounds --wait; pass both, or neither.",Ea,{reason:"timeout bounds wait; pass both, or neither."});if(t!==void 0&&t<=0)throw k(`--timeout takes a positive number of seconds, got ${t}.`,Ea,{reason:`timeout takes a positive number of seconds, got ${t}.`});if(t!==void 0&&t>wa)throw k(`--timeout takes at most ${wa} seconds (a day), got ${t}.`,Ea);if(e&&n.kind==="dataset")throw k("--wait takes a model: a dataset's changes are announced on no event stream.",Ea,{reason:"wait takes a model: a dataset's changes are announced on no event stream."})},G0=e=>e.kind==="model"&&e.address.ref.kind==="branch"?g(e.address.text):void 0,jE=A({path:["draft","status"],effect:"read",summary:"Show your draft of a model or dataset",description:`Shows your own draft: the branch it aims at, the head it is based on, its head, how many changes it holds against the ${Ue}-change cap, and whether that branch has moved past its baseline (a commit then needs a rebase first). reads says what an invocation that names no ref reads right now: your draft while it holds changes, else the head of the branch it aims at, main when you hold none. Holding no draft is reported, not refused. Drafts are private: you see only your own. With --wait it then waits on the model's change stream for what a person does with the draft, typically after 'draft handoff', and reports the verdict beside the status: committed, discarded, changed or branch-moved, each exit 0. A forward move of the draft (the person staging edits of their own) is no verdict. When --timeout elapses or the stream cannot be re-established it exits 7, retryable: run it again. A draft the branch already left behind answers branch-moved at once.`,positionals:[je],flags:{wait:{type:"boolean",description:"Wait for what a person does with your draft of a model and report it as verdict: committed (with the commit and how many of your changes landed), discarded, changed, or branch-moved (rebase, then wait again). Exits 7, retryable, when --timeout elapses.",toolDescription:"Wait for what a person does with your draft and answer it as verdict: committed (with the commit, its url and how many of your changes landed), discarded, changed, or branch-moved (call draft_rebase, then wait again). A wait that ends with no answer returns verdict timed-out; call again to keep waiting."},timeout:{type:"number",placeholder:"seconds",description:`How long --wait waits for a verdict before exiting 7; ${km} when not given, ${wa} (a day) at most.`,toolDescription:`How long wait waits for a verdict, in seconds; ${vm} when not given, ${ba} at most (a larger value waits ${ba}).`}},examples:["modeldesk draft status <model>","modeldesk draft status dataset/<dataset-id> --json","modeldesk draft status <model> --wait --timeout 300"],mcp:{name:"draft_status",description:"Shows your draft of the model: the branch it aims at, its baseline and head, how many changes it holds against the cap, and whether the branch has moved past its baseline (call draft_rebase before committing then). reads says what a call that names no ref reads right now. After draft_handoff, call it with wait: true to hear the person's answer as verdict (committed, discarded, changed, branch-moved); a wait that ends with no answer returns verdict timed-out and the draft as it was, so call again.",wait:{defaultSeconds:vm,maxSeconds:ba}},resultSchema:LE.draftStatus,run:async e=>oe(async()=>{let{wait:t,timeout:n}=e.flags;U0(t===!0,n,e.args.resource);let r=await Le(e),o=await r.read(),s=await r.workingBranch(o),i=s.branch===void 0?void 0:Sm(s.branch),a=o!==void 0&&o.headCommitId!==o.baselineCommitId,d={resource:r.ref,draft:o===void 0||i===void 0?null:{...o,target:i},maxChanges:Ue,branchHeadCommitId:s.head,...o?{behind:o.baselineCommitId!==s.head}:{},reads:{default:a?"draft":"head",...i===void 0?{}:{head:i}},...r.url?{url:r.url}:{}};if(!t)return{result:d};let l=ce(r.ref),c=i===void 0?r.ref.id:_r(r.ref,i);if(o===void 0)throw Im(l,G0(e.args.resource)??c);let m=n??km,p=await DE(e,r.ref.id,o,{subject:l,address:c,deadline:()=>Math.min(Date.now()+m*1e3,e.deadline??Number.POSITIVE_INFINITY),branchHeadId:s.head});if(p.verdict==="timed-out"){let u=n===void 0?"":` --timeout ${n}`;throw PE(l,m,`modeldesk draft status ${c} --wait${u}`,{...d})}return{result:{...d,...p}}}),render:e=>"verdict"in e?B0(e):H0(e)});var FE={draftHandoff:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},draft:{type:"object",properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"Your draft as the server answered the handoff, carrying it as `handoff`, and the branch it targets."},url:{type:"string",description:"The model in the app, where the person reviews and commits the draft."}},required:["schemaVersion","resource","draft"]}};var qE="modeldesk draft handoff --help",Y0=async e=>{try{let t=await e.read();return t===void 0?e.ref.id:_r(e.ref,await e.branch(t.targetRefId))}catch{return e.ref.id}},K0=async(e,t)=>{let n=ce(t.ref);if(!(e instanceof f))return e;let r={type:e.type,requestId:e.requestId,details:e.details};switch(e.type){case"nothing-to-hand-off":return new f(`Your draft of ${n} holds no staged change, so there is nothing to hand off.`,{...r,exitCode:b.Failure});case"draft-moved":{let o=await Y0(t);return new f(`Your draft of ${n} moved while it was being handed off (a change was staged, undone or rebased), so no handoff was stored.`,{...r,exitCode:b.Conflict,hint:`Review it with 'modeldesk draft diff ${o} --changes', then hand it off again.`,hosted:{hint:s=>`Review it with ${s("draft diff")} (model ${o}, changes: true), then hand it off again.`}})}default:return e}},WE=A({path:["draft","handoff"],effect:"stage",summary:"Hand your draft off to a person for review, with a summary",description:"Stores the summary on your draft and marks it ready for review: the open model shows a notice with it, the panel header carries it, the commit dialog starts from it, and the model list reads Ready for review. Nothing is staged or committed, and a second handoff replaces the first. The person answers by committing, removing changes or discarding in the app; 'draft status --wait' reports which. A draft holding no staged change exits 1, and one that moved while it was handed off exits 5 with nothing stored. Models only: a dataset draft has no handoff (exit 2).",positionals:[je],flags:{message:{type:"string",short:"m",required:!0,placeholder:"summary",description:"What the draft does, in your words: the summary the person reviews it by. Plain text.",requiredReason:"The summary is your own account of the draft; none is composed."}},examples:['modeldesk draft handoff <model> -m "Tidy the shape names and add the severity binding"','modeldesk draft handoff <model>@feat/x -m "Ready: the new bindings on feat/x" --json'],mcp:{name:"draft_handoff",description:"Hands your draft to the person for review, with message as the summary they review it by; nothing is staged or committed, and a second handoff replaces the first. Then call draft_status with wait: true to hear the person's answer. This is the lane for a small change; for larger work, commit on a branch of your own (branch_create with an agent/<topic> name and open: true)."},resultSchema:FE.draftHandoff,run:async e=>oe(async()=>{if(e.args.resource.kind==="dataset")throw k("A dataset draft has no handoff; draft handoff takes a model.",qE);let t=Lt(e.flags.message,qE),n=await Le(e),r;try{r=await e.api().drafts.model.handoff(n.ref.id,{summary:t})}catch(s){throw await K0(s,n)}return{result:{resource:n.ref,draft:{...r,target:Sm(await n.branch(r.targetRefId))},...n.url?{url:n.url}:{}}}}),render:e=>[`Handed off your draft of ${ce(e.resource)} for review (${P(e.draft.changeCount,"staged change")}): ${g(e.draft.handoff?.summary.split(`
231
+ `)[0]??"")}`,...e.url?[`url: ${e.url}`]:[],`Wait for the verdict: modeldesk draft status ${_r(e.resource,e.draft.target)} --wait`].join(`
232
+ `)});var HE={draftRebase:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},draft:{type:"object",properties:{id:{type:"string"},targetRefId:{type:"string"},baselineCommitId:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"},createdAt:{type:"string"},updatedAt:{type:"string"},movesBaseTo:{type:"string"},handoff:{type:"object",properties:{summary:{type:"string"},headCommitId:{type:"string"},at:{type:"string"}}}},description:"The draft as it now stands: based on the branch head, holding the chain less what was dropped."},dropped:{type:"array",items:{type:"object",properties:{commitId:{type:"string"},requestId:{type:"string"},message:{type:"string"},actionTypes:{type:"array",items:{type:"string"}},rowsChanged:{type:"number"}}},description:"The changes left out as asked, in chain order."},closureChanged:{type:"boolean",description:"Whether the branch changed the model's dependencies while the draft was open (models only). One of false, true."},schemaChanged:{type:"boolean",description:"Whether the branch changed the model's metamodel pin while the draft was open (models only). One of false, true."}},required:["schemaVersion","resource","draft","dropped"]}};var J0=e=>{let t=[e.code,e.actionIndex===void 0?void 0:`action ${e.actionIndex}`,e.elementId===void 0?void 0:`element ${e.elementId}`,e.property===void 0?void 0:`property ${e.property}`].filter(n=>n!==void 0);return`${g(e.message)} (${t.join(", ")})`},BE=e=>e?` (${e})`:"",X0=e=>e.flatMap(t=>[`Change ${t.sourceCommitId}${BE(t.requestId)}: ${g(t.description)}`,...t.actionTypes?.length?[` actions: ${t.actionTypes.join(", ")}`]:[],...(t.errors??[]).map(n=>` - ${J0(n)}`),...t.rowIds?.length?[` rows: ${t.rowIds.join(", ")}`]:[]]).map(t=>`${t}
233
+ `).join(""),UE=e=>Array.isArray(e.details.conflicts)?e.details.conflicts:[],Q0=(e,t)=>{if(!(e instanceof f))return e;if(e.type==="rebase-conflict"){let n=UE(e);return new f(`The branch head refuses ${P(n.length,"staged change")} of your draft of ${t}, so nothing was rebased.`,{exitCode:b.Conflict,type:e.type,requestId:e.requestId,details:e.details,hint:"Correct those changes, or leave them out with --drop <change id> (a change id is its sourceCommitId).",hosted:{hint:"Correct those changes, or leave them out by listing their ids in 'drop' (a change id is its sourceCommitId)."}})}return e.type==="draft-head-conflict"||e.type==="branch-head-conflict"?new f(`Your draft of ${t} moved while it was being rebased, so nothing was rebased.`,{exitCode:b.Conflict,type:e.type,requestId:e.requestId,details:e.details,hint:"Run 'modeldesk draft status', then rebase again.",hosted:{hint:n=>`Call ${n("draft status")}, then rebase again.`}}):e},Z0=e=>[`Rebased your draft of ${ce(e.resource)} onto ${e.draft.baselineCommitId}; it holds ${P(e.draft.changeCount,"change")}.`,...e.dropped.length>0?["Dropped:",...e.dropped.map(t=>` ${t.commitId}${BE(t.requestId)} ${g(t.message??"")}`.trimEnd())]:[],...e.closureChanged?["The branch changed the model's dependencies meanwhile."]:[],...e.schemaChanged?["The branch changed the model's metamodel pin meanwhile; re-read its schema."]:[]].join(`
234
+ `),GE=A({path:["draft","rebase"],effect:"stage",escalate:{flag:"drop",to:"unstage"},summary:"Move your draft onto the branch head",description:"Replays every staged change onto the current branch head and moves your draft there, as a commit needs once the branch has moved past its baseline. Nothing is left out unless --drop names it. A change the branch head refuses swaps nothing: the command prints each refused change (its id, request id, action types and errors) and exits 5; correct the change, or rebase again with --drop <id>. On success it reports the dropped changes and whether the branch changed the model's dependencies or metamodel pin meanwhile.",positionals:[je],flags:{drop:{type:{list:"string"},placeholder:"change-id",description:"A staged change to leave out, by the id a conflict report gives it."}},examples:["modeldesk draft rebase <model>","modeldesk draft rebase <model> --drop <change-id> --json"],mcp:{name:"draft_rebase",description:"Replays your draft's staged changes onto the branch's current head and moves the draft there, which a commit needs once draft_status reports the branch moved past the baseline. A change the new head refuses moves nothing: the error lists each refused change with its errors. Correct and re-stage your change, or rebase again with drop naming the change ids to leave out (your own only)."},resultSchema:HE.draftRebase,run:async e=>oe(async()=>{let t=await Le(e),n=ce(t.ref),r=await t.read();if(r===void 0)throw new f(`You hold no draft of ${n}, so there is nothing to rebase.`);let{drop:o}=e.flags;o.length>0&&await Be(e,t,r,{scope:{kind:"ids",ids:o},action:`Dropping ${P(o.length,"staged change")} from your draft of ${n}`,anySurface:!1,override:"ask them to run 'modeldesk draft rebase --drop' from a plain shell."});let s=i=>{i===!0&&t.ref.kind==="model"&&e.content.schemaChanged(t.ref.id)};try{let i=await t.rebase({draftHeadId:r.headCommitId,...o.length>0?{drop:o}:{}});return s(i.schemaChanged),{result:{resource:t.ref,...i}}}catch(i){throw i instanceof f&&s(i.details.schemaChanged),Q0(i,n)}}),render:Z0,renderRefusal:e=>e.type==="rebase-conflict"?X0(UE(e)):void 0});var VE={draftUndo:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},resource:{type:"object",properties:{kind:{type:"string",description:'One of "dataset", "model".'},id:{type:"string"},name:{type:"string"}}},undone:{type:"string",description:"The staged change that was undone: the draft head before the undo."},draft:{type:"object",properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft after the undo: its head, and how many changes it still holds."}},required:["schemaVersion","resource","undone","draft"]}};var YE=A({path:["draft","undo"],effect:"unstage",summary:"Undo the last change staged in your draft",description:"Takes the last staged change back out of your draft, whichever surface staged it, guarded by the head this command read: a change staged in between is not undone in its place. Undo never goes below the branch commit the draft started from, and there is no redo: stage the change again instead. A draft with nothing staged, or no draft, exits 1. Under an agent host a last change made outside an agent session (in the app) is left to a person (exit 6) unless --any-surface.",positionals:[je],flags:kr,examples:["modeldesk draft undo <model>"],mcp:{name:"draft_undo",description:"Takes the last staged change back out of your draft. A change the person or another session staged is refused unless the person granted 'Act without your review', and even then undo one only when the person asks you to. There is no redo: stage the change again instead."},resultSchema:VE.draftUndo,run:async e=>oe(async()=>{let t=await Le(e),n=await t.read();if(n===void 0)throw new f(`You hold no draft of ${ce(t.ref)}, so there is nothing to undo.`);await Be(e,t,n,{scope:{kind:"last"},action:`Undoing the last change of your draft of ${ce(t.ref)}`,anySurface:e.flags["any-surface"],override:"pass --any-surface only when they asked for it."});try{let r=await t.undo(n.headCommitId);return{result:{resource:t.ref,undone:n.headCommitId,draft:{id:n.id,headCommitId:r.headCommitId,changeCount:r.changeCount??n.changeCount-1}}}}catch(r){throw r instanceof f&&r.type==="nothing-to-undo"?new f(`Your draft of ${ce(t.ref)} holds no staged change to undo.`,{type:r.type,details:r.details}):r instanceof f&&r.type==="draft-head-conflict"?new f(`Your draft of ${ce(t.ref)} moved after this command read it, so nothing was undone.`,{exitCode:b.Conflict,type:r.type,details:r.details,hint:"Run 'modeldesk draft status' and undo again if you still mean to.",hosted:{hint:o=>`Call ${o("draft status")} and undo again if you still mean to.`}}):r}}),render:e=>`Undid the last staged change (${e.undone}) of your draft of ${ce(e.resource)}; ${P(e.draft.changeCount,"change")} remain${e.draft.changeCount===1?"s":""}.`});var t_={minimum:-2147483648,maximum:2147483647},n_={minimum:Number.MIN_SAFE_INTEGER,maximum:Number.MAX_SAFE_INTEGER},KE=34028234663852886e22,r_={minimum:-KE,maximum:KE},zE=new Set(["true","false"]),o_=/^-?\d+$/,s_=/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/,i_=/^-?\d+(\.\d+)?$/,a_=/^(\d{4})-(\d{2})-(\d{2})$/,d_=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/,l_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,c_=/^(?:[a-z][a-z0-9+.-]*:\/\/|urn:)[^\s<>"{}|\\^`]+$/i,ro=e=>({value:e}),pn=(e,t,n={})=>({problem:{code:e,expected:t,...n}}),XE=({minimum:e,maximum:t})=>e===void 0||t===void 0?{...e!==void 0&&{minimum:e},...t!==void 0&&{maximum:t}}:e===0&&t===0?{}:t<e?{minimum:e}:{minimum:e,maximum:t},m_=(e,{minimum:t,maximum:n})=>t!==void 0&&n!==void 0?`${e} from ${t} to ${n}`:t!==void 0?`${e} of at least ${t}`:`${e} of at most ${n}`,QE=(e,t,...n)=>{for(let r of n)if(r.minimum!==void 0&&e<r.minimum||r.maximum!==void 0&&e>r.maximum)return pn("out-of-range",m_(t,r),r);return ro(e)},p_=(e,t)=>o_.test(e)?QE(Number(e),"a whole number",t.format==="INT64"?n_:t_,XE(t)):pn("invalid-value","a whole number"),f_=(e,t)=>{let n=Number(e);return!s_.test(e)||!Number.isFinite(n)?pn("invalid-value","a number, such as 2.5 or 1e-3"):QE(n,"a number",t.format==="FLOAT"?r_:{},XE(t))},u_=e=>e%4===0&&(e%100!==0||e%400===0),h_=[31,28,31,30,31,30,31,31,30,31,30,31],ZE=(e,t,n)=>t>=1&&t<=12&&n>=1&&n<=(t===2&&u_(e)?29:h_[t-1]),g_=e=>{let t=a_.exec(e);return t!==null&&ZE(Number(t[1]),Number(t[2]),Number(t[3]))},y_=e=>{let t=d_.exec(e);if(t===null)return!1;let[n,r,o,s,i,a]=t.slice(1,7).map(Number),d=t[7]===void 0?0:Number(t[7]),l=t[8]===void 0?0:Number(t[8]);return ZE(n,r,o)&&s<=23&&i<=59&&a<=59&&d<=23&&l<=59},w_=e=>{if(!c_.test(e))return pn("invalid-value","an absolute IRI, such as https://example.org/def#Term or urn:example:term");let t=Math.max(e.lastIndexOf("#"),e.lastIndexOf("/"),e.lastIndexOf(":"))+1,n=e.slice(0,t),r=e.slice(t);return ro(r===""?{namespace:n}:{namespace:n,localName:r})},JE={expected:"a date-time written YYYY-MM-DDThh:mm:ss with a Z or \xB1hh:mm offset (RFC 3339)",test:y_},b_=new Map([["date",{expected:"a date written YYYY-MM-DD",test:g_}],["date-time",JE],["datetime",JE],["uuid",{expected:"a UUID",test:e=>l_.test(e)}]]),E_=(e,t)=>{if(t.format==="iri")return w_(e);if(t.enum&&t.enum.length>0&&!t.enum.includes(e))return pn("not-in-enum",`one of ${t.enum.join(", ")}`,{validValues:[...t.enum]});let n=t.format===void 0?void 0:b_.get(t.format);return n&&!n.test(e)?pn("invalid-value",n.expected):ro(e)},C_=e=>ro(e==="true"||e==="false"?e==="true":i_.test(e)&&String(Number(e))===e?Number(e):e),eC=(e,t)=>{switch(t?.type){case void 0:case"any":return C_(e);case"boolean":return zE.has(e)?ro(e==="true"):pn("invalid-value","true or false",{validValues:[...zE]});case"integer":return p_(e,t);case"number":return f_(e,t);case"string":return E_(e,t);case"object":return pn("structured-value","a structured value, given as JSON with --json-value")}};var Ca=class extends f{errors;constructor(t,n=[]){let r=t.length>1?` (and ${t.length-1} more)`:"",o=t.map((s,i)=>({...s,message:n[i]??s.message}));super(`${t[0].message}${r}`,{exitCode:b.Validation,details:{errors:t},...n.some(s=>s!==void 0)?{hosted:{reason:`${o[0].message}${r}`,details:{errors:o}}}:{}}),this.name="CoercionRefusedError",this.errors=t}},R_={"structured-value":"a structured value, given as JSON in jsonValue"},k_=/^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$/,tC=-1,v_=e=>e.slice(e.lastIndexOf(":")+1),I_=(e,t)=>{let n=new Map,r=new Set;for(let o of[e,...t]){for(let s of o.attributes??[])!n.has(s.name)&&!r.has(s.name)&&n.set(s.name,s);for(let s of o.relations??[])n.has(s.name)||r.add(s.name)}return{typeName:e.name,attributes:n,relations:r}},S_=e=>[...e.attributes.values()].filter(t=>!t.derived).map(t=>t.name),nC=(e,t,n)=>e.flatMap(r=>{let o=r.indexOf("=");if(o<=0){let s=t==="json"?"<attribute>=<json>":"<attribute>=<value>";return n(o<0?r:"","malformed-assignment",`'${r}' is not an assignment; write ${s}.`,{value:r}),[]}return[{attribute:r.slice(0,o),text:r.slice(o+1),form:t}]}),$_=(e,t,n)=>{let{typeName:r,attributes:o,relations:s}=e,i=t.toLowerCase(),a=[...o.keys(),...s],d=a.includes(t)?[t]:a.filter(m=>m.toLowerCase()===i||v_(m).toLowerCase()===i);if(d.length===0){let m=S_(e);n(t,"unknown-attribute",m.length>0?`${r} has no attribute '${t}'. Its attributes: ${m.join(", ")}.`:`${r} has no attribute '${t}', nor any attribute to set.`,{validValues:m});return}if(d.length>1){n(t,"ambiguous-attribute",`'${t}' names ${d.length} properties of ${r} (${d.join(", ")}); pass the full name.`,{validValues:d});return}let[l]=d,c=o.get(l);if(c===void 0){n(t,"relation-not-attribute",`'${l}' is a relation of ${r}, not an attribute; relate its targets with 'el relate'.`,{property:l});return}if(c.derived){n(t,"derived-attribute",`'${l}' is derived: ${r} computes it on read, so it is never written.`,{property:l});return}return c},rC=e=>typeof e=="object"&&e!==null&&"lang"in e&&typeof e.lang=="string"?e.lang:null,oC=(e,t)=>(e??"").toLowerCase()===(t??"").toLowerCase(),T_=e=>e.map(rC).filter((t,n,r)=>r.findIndex(o=>oC(o,t))===n),x_=(e,t,n,r,o)=>{let s=e.attribute.name;if(r.lang!==void 0){if(k_.test(r.lang))return{lang:r.lang};o(e.given,"invalid-language",`--lang '${r.lang}' is not a language tag, such as nl or en-GB.`,{property:s,value:r.lang},`'lang' '${r.lang}' is not a language tag, such as nl or en-GB.`);return}let i=T_(n);if(i.length===1&&(i[0]!==null||t.optional))return{lang:i[0]};if(i.length===0&&t.optional)return{lang:null};let a=i.filter(l=>l!==null),d=i.length>1?`holds values in ${i.map(l=>l??"no language").join(", ")}`:"takes language-tagged strings";o(e.given,"language-required",`'${s}' ${d}; pass --lang to say which language to write.`,{property:s,...a.length>0&&{validValues:a}},`'${s}' ${d}; give lang to say which language to write.`)},A_=(e,t,n,r)=>{let o=e.attribute.name,s=n.current?.[o]??[],i=x_(e,t,s,n,r);if(i===void 0)return e.assignments.map(({text:d})=>d);let a=e.assignments.map(({text:d})=>({lang:i.lang,value:d}));return t.uniqueLang&&i.lang!==null&&a.length>1&&r(e.given,"duplicate-language",`'${o}' takes one value per language, and ${a.length} are given in '${i.lang}'.`,{property:o}),[...s.filter(d=>!oC(rC(d),i.lang)),...a]},O_=(e,t)=>e.assignments.flatMap(({attribute:n,text:r})=>{try{return[JSON.parse(r)]}catch{return t(n,"invalid-json",`The --json-value of '${n}' is not valid JSON: '${r}'.`,{property:e.attribute.name,value:r},`The jsonValue of '${n}' is not valid JSON: '${r}'.`),[]}}),M_=(e,t,n)=>{let{attribute:r,assignments:o}=e,s=r.name,i=r.schema;if(o.some(({form:d})=>d==="json"))return O_(e,n);for(let{attribute:d}of o.filter(({text:l})=>l===""))n(d,"empty-value",`'${s}' is given an empty value; unset the attribute to remove its values.`,{property:s,value:""});let a=o.filter(({text:d})=>d!=="");return i?.type==="string"&&i.lang?A_({...e,assignments:a},i.lang,t,n):a.map(({attribute:d,text:l})=>{let c=eC(l,i);if("problem"in c){let{code:m,expected:p,...h}=c.problem,u=R_[m];n(d,m,`'${s}' takes ${p}, not '${l}'.`,{property:s,value:l,...h},u===void 0?void 0:`'${s}' takes ${u}, not '${l}'.`)}return"value"in c?c.value:l})},sr=(e,t,n={})=>{let r=[],o=[],s=(m,p,h,u={},y=void 0)=>{r.push({attribute:m,code:p,message:h,...u}),o.push(y)},i=I_(t,n.traits??[]),a=[...nC(e.values??[],"value",s),...nC(e.json??[],"json",s)],d=new Map,l=new Map;for(let m of a){d.has(m.attribute)||d.set(m.attribute,$_(i,m.attribute,s));let p=d.get(m.attribute);if(p!==void 0){let h=l.get(p.name)??{attribute:p,given:m.attribute,assignments:[]};h.assignments.push(m),l.set(p.name,h)}}let c={};for(let[m,p]of l){if(new Set(p.assignments.map(({form:y})=>y)).size>1){s(p.given,"mixed-forms",`'${m}' is given both as ${m}=<value> and with --json-value; give all of its values one way.`,{property:m},`'${m}' is given both as ${m}=<value> and in jsonValue; give all of its values one way.`);continue}let h=M_(p,n,s),u=p.attribute.multiplicity.max??tC;u!==tC&&h.length>u&&s(p.given,"too-many-values",`'${m}' takes at most ${P(u,"value")}, and this assignment leaves it with ${h.length}.`,{property:m,maximum:u}),c[m]=h}if(r.length>0)throw new Ca(r,o);return c};var fn="modeldesk el bulk --help",$m=["equalTo","empty","notEmpty","contains","greaterThan","lessThan"],N_={"=":"equalTo","~":"contains",">":"greaterThan","<":"lessThan"},P_={empty:"empty","not-empty":"notEmpty"},D_=/^([^=~<>]+)([=~<>])(.*)$/s,L_=/^(.+):(empty|not-empty)$/,__="type=<T>[,<T>\u2026], <attr>=<value>, <attr>~<text>, <attr>><n>, <attr><<n>, <attr>:empty or <attr>:not-empty",j_=e=>{let t;try{t=JSON.parse(e)}catch(o){throw k(`--where is not valid JSON (${o.message}).`,fn,{reason:`'where' is not valid JSON (${o.message}).`})}let{type:n,conditions:r}=t??{};if(n!==void 0&&!(Array.isArray(n)&&n.every(o=>typeof o=="string")))throw k('--where: "type" is a list of type names.',fn,{reason:`'where': "type" is a list of type names.`});if(r!==void 0&&!Array.isArray(r))throw k('--where: "conditions" is a list of {attribute, operator, value}.',fn,{reason:`'where': "conditions" is a list of {attribute, operator, value}.`});for(let o of r??[])if(typeof o?.attribute!="string"||!$m.includes(o.operator))throw k(`--where: every condition names an "attribute" and an "operator" (${$m.join(", ")}).`,fn,{reason:`'where': every condition names an "attribute" and an "operator" (${$m.join(", ")}).`});return{...n===void 0?{}:{type:n},...r===void 0?{}:{conditions:r}}},F_=e=>{let t=D_.exec(e);if(t){let[,r,o,s]=t;if(r==="type"&&o==="="){let i=s.split(",").map(a=>a.trim()).filter(a=>a!=="");if(i.length===0)throw k(`'${e}' names no type.`,fn);return{type:i}}return{condition:{attribute:r,operator:N_[o],value:s}}}let n=L_.exec(e);if(n)return{condition:{attribute:n[1],operator:P_[n[2]]}};throw k(`'${e}' is not a criterion; write one of ${__}.`,fn)},sC=e=>{if(e.some(r=>r.trimStart().startsWith("{"))){if(e.length>1)throw k("--where as JSON holds the whole selection; give it once, without other clauses.",fn,{reason:"'where' as JSON holds the whole selection; give it once, without other clauses."});return j_(e[0])}let t,n=[];for(let r of e){let o=F_(r);if("type"in o){if(t!==void 0)throw k("Name every type in one type= clause (type=A,B); two would both have to hold.",fn);t=o.type}else n.push(o.condition)}return{...t?{type:t}:{},...n.length>0?{conditions:n}:{}}},Ra=e=>{if(e!==null&&typeof e=="object"){if("value"in e)return String(e.value);if("namespace"in e||"localName"in e){let{namespace:t,localName:n}=e;return`${t??""}${n??""}`}return JSON.stringify(e)}return String(e)},q_=e=>e!=null&&e!=="",W_=(e,t)=>{let n=t.value===void 0?"":Ra(t.value);switch(t.operator){case"empty":return e.length===0;case"notEmpty":return e.some(q_);case"equalTo":return e.some(r=>Ra(r)===n);case"contains":return e.some(r=>Ra(r).toLowerCase().includes(n.toLowerCase()));case"greaterThan":case"lessThan":{let r=Number(n);return n.trim()!==""&&!Number.isNaN(r)&&e.some(o=>{let s=Number(Ra(o));return!Number.isNaN(s)&&(t.operator==="greaterThan"?s>r:s<r)})}}},iC=(e,t,n)=>n.types!==void 0&&!n.types.has(e.type)?!1:(t.conditions??[]).every(r=>{let o=n.attributeOf(e,r.attribute);return o!==void 0&&W_(e.attributes?.[o]??[],r)});var H_="@trait",aC="@Root",B_="@element",kt=e=>({modelId:e.model.id,refId:Dt(e)}),un=async(e,t,n)=>{let{type:r}=await e.models.schema(t.modelId,{ref:t.refId,type:n});if(r===void 0)throw new f(`The schema of this model describes no type '${n}'.`,{exitCode:b.NotFound});return r},dC=async(e,t,n,r,o)=>{if((r.values?.length??0)+(r.json?.length??0)===0)return{};let s=(n.attributes?.[H_]??[]).filter(d=>typeof d=="string"),[i,...a]=await Promise.all([n.type,...s].map(d=>un(e,t,d)));return sr(r,i,{lang:o,current:n.attributes,traits:a})},ds=async(e,t,n,r,o,s,i)=>{if(s!==void 0)return s;let a=n.element(r)?.type??aC;if(a===aC){let{root:m=[]}=await e.models.schema(t.modelId,{ref:t.refId});if(m.some(p=>(p.instantiableTypes??[p.type]).includes(o)))return B_;throw new f(`The model root holds no ${o}.`,{exitCode:b.Validation,hint:`Types the root holds: ${m.flatMap(p=>p.instantiableTypes??[p.type]).join(", ")||"none"}.`})}let{childSlots:d=[]}=await un(e,t,a),l=d.filter(m=>m.targetTypes.includes(o));if(l.length===1)return l[0].relation;if(l.length>1)throw k(`A ${a} holds a ${o} through ${l.map(m=>m.relation).join(", ")}; pass --relation to pick one.`,i,{reason:`A ${a} holds a ${o} through ${l.map(m=>m.relation).join(", ")}; give relation to pick one.`});let c=d.map(m=>`${m.relation} (${m.targetTypes.join(", ")})`).join("; ");throw new f(`A ${a} holds no ${o}.`,{exitCode:b.Validation,hint:d.length===0?`A ${a} holds no children at all.`:`What it holds: ${c}.`})},U_=e=>e.slice(e.lastIndexOf(":")+1),Xe=(e,t)=>{if(e.includes(t))return t;let n=t.toLowerCase(),r=e.filter(o=>o.toLowerCase()===n||U_(o).toLowerCase()===n);if(r.length>1)throw new f(`'${t}' names ${r.length} properties (${r.join(", ")}); pass the full name.`,{exitCode:b.Usage,details:{candidates:r}});return r[0]},ka=e=>e.ownership==="OWNED"||e.ownership==="MULTI_OWNED";var lC={elBulk:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What the selection read: your draft while it holds staged changes, else your working branch head."},criteria:{type:"object",properties:{type:{type:"array",items:{type:"string"}},conditions:{type:"array",items:{type:"object",properties:{attribute:{type:"string"},operator:{type:"string",description:'One of "contains", "empty", "equalTo", "greaterThan", "lessThan", "notEmpty".'},value:{description:"The value compared against; none for `empty` and `notEmpty`."}}}}}},elements:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},label:{type:"string"},path:{type:"string"},before:{type:"object",additionalProperties:{type:"array",items:{}},description:"The values of each written attribute before the update."},after:{type:"object",additionalProperties:{type:"array",items:{}},description:"The values of each written attribute after it."},changes:{type:"boolean",description:"False when the element already holds these values, so the update leaves it out. One of false, true."}}},description:"Every selected element in tree order, with what the update writes to it."},dryRun:{type:"boolean",description:"True for a dry run: the preview alone, nothing staged. One of false, true."},staged:{type:"boolean",description:"Whether a change was staged; false on a dry run and when no selected element would change. One of false, true."},message:{type:"string"},changeRequestId:{type:"string",description:"The staged change's request id, when one was sent."},alreadyStaged:{type:"boolean",description:"True when a change staged under the same request id was found in your draft and not staged again. One of false, true."},stagedCommitId:{type:"string"},draft:{properties:{id:{type:"string"},headCommitId:{type:"string"},changeCount:{type:"number"}},description:"The draft the change sits in, when one was staged. May be null."},commit:{type:"object",properties:{recovered:{type:"boolean",description:"One of false, true."},next:{type:"string",description:"What a landing off main leaves the caller with."},url:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},commit:{type:"object",properties:{id:{type:"string"},message:{type:"string"},requestId:{type:"string",description:"The `commitRequestId` the landing was sent with."},createdAt:{type:"string"},actionTypes:{type:"array",items:{type:"string"},description:"A model commit's action types: the whole chain's."},rowsChanged:{type:"number",description:"A dataset commit's count of the rows it wrote or removed."}}}}},url:{type:"string"}},required:["schemaVersion","model","ref","criteria","elements","dryRun","staged","message","url"]}};var va="modeldesk el bulk --help",cC=100,V_="@trait",mC=e=>(e.attributes?.[V_]??[]).filter(t=>typeof t=="string"),Tm=(e,t)=>e===t?!0:e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t)?!1:[...new Set([...Object.keys(e),...Object.keys(t)])].every(r=>Tm(e[r],t[r])),Y_=(e,t)=>{let n=new Map;return r=>{let o=n.get(r);if(o!==void 0)return o;let s=un(e.api(),t,r);return n.set(r,s),s}},pC=async(e,t,n,r)=>{let o=Y_(e,kt(t)),s=n.type?new Set((await Promise.all(n.type.map(o))).flatMap(v=>v.instantiableTypes??[v.name])):void 0,i=ln(ft(t.tree)).filter(v=>s===void 0||s.has(v.type)),a=i.map(v=>t.read.elements[v.id]),d=[...new Set(a.flatMap(v=>[v.type,...mC(v)]))],l=new Map(await Promise.all(d.map(async v=>[v,await o(v)]))),c=v=>({type:l.get(v.type),traits:mC(v).map($=>l.get($))}),m=v=>{let{type:$,traits:C}=c(v);return[$,...C].flatMap(x=>(x.attributes??[]).map(L=>L.name))},h=(n.conditions??[]).find(v=>!a.some($=>Xe(m($),v.attribute)!==void 0));if(h!==void 0&&a.length>0)throw new f(`No element type the selection reaches has an attribute '${h.attribute}'.`,{exitCode:b.Validation,hint:"Run 'modeldesk describe <model> <type>' to see a type's attributes.",hosted:{hint:v=>`Call ${v("describe")} with the model and a type to see its attributes.`}});let y=i.filter((v,$)=>iC(a[$],n,{attributeOf:(C,x)=>Xe(m(C),x)})).map(v=>{let $=t.read.elements[v.id],{type:C,traits:x}=c($),L=sr({values:r.set,json:r.json},C,{lang:r.lang,current:$.attributes,traits:x});for(let S of r.unset){let T=Xe(m($),S);if(T===void 0)throw new f(`A ${$.type} has no attribute '${S}' to unset.`,{exitCode:b.Validation,details:{elementId:$.id}});if(T in L)throw k(`'${T}' is both set and unset.`,va);L[T]=[]}let R=Object.fromEntries(Object.keys(L).map(S=>[S,$.attributes?.[S]??[]]));return{id:v.id,type:v.type,...v.label===void 0?{}:{label:v.label},path:v.path,before:R,after:L,changes:Object.keys(L).some(S=>!Tm(R[S],L[S]))}}),w=y.filter(v=>v.changes),I=w.every(v=>Tm(v.after,w[0].after))&&w.length>0?{elementIds:w.map(v=>v.id),attributes:w[0].after}:{updates:w.map(v=>({elementId:v.id,attributes:v.after}))};return{rows:y,update:I}},K_=e=>g(typeof e=="string"?e:JSON.stringify(e)),fC=e=>e.length===0?"(none)":e.map(K_).join(", "),z_=e=>e.dryRun?"Dry run: nothing was staged.":e.staged?`Staged as one change in your draft (${P(e.draft?.changeCount??0,"change")}): ${g(e.message)}`:"Nothing was staged: no selected element changes.",J_=e=>{let t=e.elements.filter(o=>o.changes).length,n=e.elements.slice(0,cC).flatMap(o=>[` ${g(o.path)} (${o.type}) ${o.id}${o.changes?"":" unchanged"}`,...Object.keys(o.after).map(s=>` ${s}: ${fC(o.before[s])} -> ${fC(o.after[s])}`)]),r=e.elements.length-cC;return[Ae(e.ref,e.model),`Selected ${P(e.elements.length,"element")}, of which ${t} change:`,...n,...r>0?[` \u2026 and ${r} more (pass --json for every one).`]:[],z_(e),`url: ${e.url}`,...e.commit?nr(e.commit):[]].join(`
235
+ `)},uC=A({path:["el","bulk"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage one update of every element the criteria select",description:`Selects elements by --where and stages one bulk update writing the same attribute values to each, as the app's bulk update does. Each --where clause must hold: type=<T>[,<T>\u2026] (subtypes and trait appliers included), <attr>=<value>, <attr>~<text> (contains, ignoring case), <attr>><n>, <attr><<n>, <attr>:empty, <attr>:not-empty. A --where starting with { is the app's criteria as JSON, and stands alone. Conditions read stored values only, not defaults. --set values are typed by each element's schema as in 'el set'; --unset empties an attribute. --dry-run lists every selected element with its values before and after and stages nothing. ${K}`,positionals:[N(F)],flags:{where:{type:{list:"string"},required:!0,placeholder:"criterion",description:"A criterion every selected element meets, or the app's criteria as JSON."},set:{type:{list:"string"},placeholder:"attr=value",description:"A value to write, typed by the schema."},"json-value":{type:{list:"string"},placeholder:"attr=json",description:"A value to write given as JSON, written as it is."},unset:{type:{list:"string"},placeholder:"attr",description:"An attribute to empty."},lang:{type:"string",placeholder:"tag",description:"The language of the language-tagged values given."},...q},dryRun:!0,examples:['modeldesk el bulk <model> --where type=ElementType --where notation:empty --set notation=uml -m "Default notation" --dry-run',`modeldesk el bulk <model> --where '{"type":["ElementType"],"conditions":[{"attribute":"notation","operator":"empty"}]}' --set notation=uml -m "Default notation"`],mcp:{name:"bulk_update",description:"Stages one bulk update that writes the same attribute values to every element the criteria select, as one change with message. Each where clause must hold: type=<T>[,<T>...] (subtypes included), <attr>=<value>, <attr>~<text> (contains, ignoring case), <attr>><n>, <attr><<n>, <attr>:empty, <attr>:not-empty; or the app's criteria as one JSON object. set writes attr=value typed by each element's schema, jsonValue attr=<json> a structured value, unset empties an attribute. Run it with dryRun: true first: that lists every selected element before and after and stages nothing. For edits to a few named elements use stage_changes."},resultSchema:lC.elBulk,run:async e=>oe(async()=>{let{flags:t}=e,n=sC(t.where),r={set:t.set,json:t["json-value"],unset:t.unset,lang:t.lang};if(r.set.length+r.json.length+r.unset.length===0)throw k("Say what to write: --set attr=value, --json-value attr=json or --unset attr.",va,{reason:"Say what to write: set attr=value, jsonValue attr=json or unset attr."});let o=e.dryRun;if(o&&t.commit)throw k("--commit has nothing to commit under --dry-run, which stages nothing.",va);if(t["with-staged"]&&!t.commit)throw k("--with-staged goes with --commit.",va);let s=o?await gt(e,e.args.model):await Wt(e),i=s.model.id,a=await pC(e,s,n,r),d={model:s.model,ref:le(s.resolved),criteria:n,elements:a.rows,dryRun:o,staged:!1,message:t.message,url:e.webUrl({kind:"model",modelId:i})};if(o)return{result:d};if(a.rows.length===0)throw new f(`The criteria select no element of ${s.model.name}, so nothing was staged.`,{hint:"Preview a selection with --dry-run.",hosted:{hint:"Preview a selection with dryRun: true."}});let l=()=>new f(`No selected element of ${s.model.name} changes, so nothing was staged or committed.`,{type:"nothing-to-commit"});if(!a.rows.some(h=>h.changes)){if(t.commit)throw l();return{result:d}}let c=await Zo(e,s,async h=>(a=h===s?a:await pC(e,h,n,r),{actions:a.rows.some(u=>u.changes)?[{type:"ELEMENT_BULK_UPDATE",update:a.update}]:[],ids:{},resendable:!1}),{message:t.message,requestId:t["request-id"]}),m=tr(c.staged);if(t.commit&&!m)throw l();let[p]=c.staged.chunks;return{result:{...d,ref:ts(c),elements:a.rows,staged:m,changeRequestId:c.changeRequestId,...p?.alreadyStaged?{alreadyStaged:!0,stagedCommitId:p.commitId}:{},draft:es(c),...t.commit?{commit:await ns(e,c)}:{}}}}),render:J_});var oo=e=>{let t=new Set(Object.keys(e.metamodel?.elementTypes??{}));for(let n of e.metamodelExtensions??[])Object.keys(n.elementTypes??{}).forEach(r=>t.add(r));return Object.values(e.elements).forEach(n=>t.add(n.type)),[...t].sort()},X_=e=>e.slice(e.lastIndexOf(":")+1),xm=(e,t)=>{if(e.includes(t))return t;let n=t.toLowerCase(),r=e.filter(o=>o.toLowerCase()===n||X_(o).toLowerCase()===n);if(r.length===0)throw new f(`No element type '${t}' in this model's metamodel.`,{exitCode:b.NotFound});if(r.length>1)throw new f(`'${t}' names ${r.length} element types; pass the full name.`,{exitCode:b.Usage,details:{candidates:r}});return r[0]},Ia=(e,t,n)=>{let r=xm(e,t);if(Vn(r)&&!n)throw k(`'${r}' is an internal type; pass --internal to include internal elements.`,void 0,{reason:`'${r}' is an internal type; set internal to include internal elements.`});return r};import{readFileSync as Q_}from"node:fs";import{resolve as Z_}from"node:path";var hC=(e,t)=>{try{return JSON.parse(Q_(Z_(e,t),"utf8"))}catch(n){throw new f(`Could not read the element in ${t} (${n.message}).`,{exitCode:b.Usage})}};var Am="new",ir="modeldesk el create --help",ej=e=>{let t=e.indexOf("=");if(t<=0||t===e.length-1)throw k(`'${e}' is not a relation to set; write --relate <relation>=<target>.`,ir,{reason:`'${e}' is not a relation to set; write <relation>=<target>.`});return[e.slice(0,t),e.slice(t+1)]},wC=["key","type","attributes","relations","children"],bC=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return[];let{children:n,...r}=e,o=Object.keys(r).filter(i=>!wC.includes(i)).map(i=>`${t}${i}`),s=n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).flatMap(([i,a])=>Array.isArray(a)?a.flatMap((d,l)=>bC(d,`${t}children.${i}[${l}].`)):[]):[];return[...o,...s]},tj=(e,t)=>{let n=e;if(n===null||typeof n!="object"||Array.isArray(n)||typeof n.type!="string")throw new f(`${t} holds no element: write an object with its "type", and "attributes", "relations" and "children" as needed.`,{exitCode:b.Usage});let r=bC(n,"");if(r.length>0){let o=wC.map(s=>`"${s}"`).join(", ");throw new f(`${t} names what an element does not have: ${r.join(", ")}. An element takes ${o}.`,{exitCode:b.Validation,details:{unknownKeys:r}})}return n},gC=(e,t)=>{let n=[...t.type===void 0?[]:["--type"],...t["json-value"].length===0?[]:["--json-value"],...t.lang===void 0?[]:["--lang"],...t.relate.length===0?[]:["--relate"]];if(e.length>0)throw k(`--from holds the whole element, so it takes no attr=value ('${e[0]}').`,ir);if(n.length>0)throw k(`--from holds the whole element, so it takes no ${n.join(", ")}.`,ir)},nj=(e,t,n,r)=>{let o=(n.relations??[]).map(i=>i.name),s={};for(let i of e){let[a,d]=ej(i),l=Xe(o,a);if(l===void 0)throw new f(`A ${t} has no relation '${a}'.`,{exitCode:b.Validation,hint:`Its relations: ${o.join(", ")||"none"}.`});let c=n.relations?.find(h=>h.name===l),m=c!==void 0&&ka(c),p=s[l]?.["@@"]??[];s[l]={"@@":[...p,{id:U(r,d),owned:m}]}}return s},yC=async(e,t,n)=>{let{flags:r}=e,o=e.api(),{tree:s}=t,i=Wi(s,e.args.parent),a=kt(t);if(n!==void 0){let h=await ds(o,a,s,i,n.type,r.relation,ir),u=n.key??Am;return{edits:[{kind:"create",parent:{id:i},relation:h,element:{...n,key:u}}],subject:{key:u}}}if(r.type===void 0)throw k("Pass the --type of the new element, or --from with a file describing it.",ir,{reason:"Give the new element's type."});let d=xm(oo(t.read),r.type),[l,c]=await Promise.all([un(o,a,d),ds(o,a,s,i,d,r.relation,ir)]),m=sr({values:e.args.values,json:r["json-value"]},l,{lang:r.lang}),p=nj(r.relate,d,l,s);return{edits:[{kind:"create",parent:{id:i},relation:c,element:{key:Am,type:d,...Object.keys(m).length>0?{attributes:m}:{},...Object.keys(p).length>0?{relations:p}:{}}}],subject:{key:Am}}},EC=A({path:["el","create"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a new element under a parent",description:`Stages one new element under <parent> (an id, a label path, or / for the model root), owned through --relation, or through the one child relation of the parent's type that admits --type. Attribute values are checked and typed by the type's schema (see 'modeldesk describe'): attr=value as on 'el set' (repeat a name for several values), --json-value for a structured value, --lang for the language of a language-tagged one. --relate rel=target adds a reference. --from <file> stages a whole subtree in one change instead: a JSON element {"type", "attributes", "relations", "children": {relation: [elements]}}, written as it is. The element's id is minted by the CLI and reported. ${K}`,positionals:[N(F),{name:"parent",type:{address:"element"},required:!0,description:"The parent's id, its label path from the model root, or / for the model root."},{name:"values",type:{list:"string"},description:"attr=value, once per value."}],flags:{type:{type:"string",placeholder:"type",description:"The new element's type (required unless --from).",toolDescription:"The new element's type; required."},relation:{type:"string",placeholder:"relation",description:"The parent's relation that owns it; needed only where the parent's type has several for the type."},"json-value":{type:{list:"string"},placeholder:"attr=json",description:"An attribute value given as JSON and written as it is."},lang:{type:"string",placeholder:"tag",description:"The language of the language-tagged values given."},relate:{type:{list:"string"},placeholder:"relation=target",description:"A reference to an existing element (id or label path), not owned by the new one.",elementEntries:!0},from:{type:"string",readsFile:!0,placeholder:"file",description:"A JSON file holding the element and the subtree it owns, staged as one change."},...q},examples:['modeldesk el create <model> SHACL name=Shape --type ElementType -m "Add the Shape type"','modeldesk el create <model> / sh:deactivated=false --type sh:NodeShape -m "Add a shape"'],mcp:{name:"create",operationOf:"stage_changes",creates:!0,description:"Create an element of type under parent (an id, a label path, or / for the model root), with values as attr=value."},plan:(e,t)=>yC(e,t,void 0),prepare:async e=>{let{flags:t}=e;if(t.from!==void 0)return fa(e),gC(e.args.values,t),hC(e.cwd,t.from)},run:async(e,t)=>{let{flags:n}=e;if(t===void 0&&n.from!==void 0)throw k(`--from ${n.from} was not read, so there is no element to stage.`,ir);let r;return t!==void 0&&(fa(e),gC(e.args.values,n),r=tj(t,n.from??"The element given")),X(e,o=>yC(e,o,r))},render:Q});var CC=async(e,t)=>{let{read:n,tree:r}=t,{flags:o}=e,s=U(r,e.args.element),i=Wi(r,e.args["new-parent"]),a=await ds(e.api(),kt(t),r,i,n.elements[s].type,o.relation,"modeldesk el mv --help"),d;if(o["from-owner"]!==void 0){let l=U(r,o["from-owner"]),c=r.owners(s).filter(m=>m.id===l);if(c.length!==1)throw new f(c.length===0?`Element ${l} does not own element ${s}.`:`Element ${l} owns element ${s} through several relations.`,{exitCode:b.Validation});d={id:l,relation:c[0].relation}}return{edits:[{kind:"move",element:s,parent:{id:i},relation:a,...o.position===void 0?{}:{position:o.position},...d?{from:d}:{}}],subject:{id:s}}},RC=A({path:["el","mv"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage moving an element under another parent",description:`Moves the element, with everything it owns, under <new-parent> (an id, a label path, or / for the model root), through --relation or the one child relation of the new parent's type that admits it, at --position among the children there (from 0; last when left out). An element with several owners needs --from-owner to say which one it leaves. ${K}`,positionals:[N(F),$e("element"),{name:"new-parent",type:{address:"element"},required:!0,description:"The new parent's id, its label path, or / for the model root."}],flags:{relation:{type:"string",placeholder:"relation",description:"The new parent's relation to own it through, where its type has several for the element."},position:{type:"number",placeholder:"n",description:"Its place among the children there, from 0."},"from-owner":{type:{address:"element"},placeholder:"element",description:"The owner it leaves (id or label path), for an element several elements own."},...q},examples:['modeldesk el mv <model> SHACL/NodeShape/severity SHACL/Shape -m "Severity applies to every shape"'],mcp:{name:"mv",operationOf:"stage_changes",description:"Move element, with what it owns, under newParent, at position among its children."},plan:CC,run:async e=>X(e,t=>CC(e,t)),render:Q});var IC={name:"relation",type:"string",required:!0,description:"The relation's name (its canonical name, or a spelling differing in case or prefix)."},SC={name:"target",type:{address:"element"},required:!0,description:"The target's id, or its label path from the model root."},rj=(e,t)=>{if(!ka(e))return e.ownership==="MIXED"&&!t;if(t)throw k(`The relation '${e.name}' owns every target it holds, so --unowned does not apply.`,"modeldesk el relate --help",{reason:`The relation '${e.name}' owns every target it holds, so unowned does not apply.`});return!0},kC=async(e,t)=>{let{model:n,read:r,tree:o}=t,{flags:s}=e,i=e.api(),a=U(o,e.args.element),d=r.elements[a],l=(d.attributes?.["@trait"]??[]).filter(I=>typeof I=="string"),c=kt(t),p=(await Promise.all([d.type,...l].map(I=>un(i,c,I)))).flatMap(I=>I.relations??[]),h=Xe(p.map(I=>I.name),e.args.relation),u=p.find(I=>I.name===h);if(u===void 0)throw new f(`A ${d.type} has no relation '${e.args.relation}'.`,{exitCode:b.Validation,hint:`Its relations: ${[...new Set(p.map(I=>I.name))].join(", ")||"none"}.`});let y=rj(u,s.unowned),{target:w}=e.args,E;if(s["target-model"]!==void 0){if(!B(w))throw k("With --target-model, name the target by its id.","modeldesk el relate --help",{reason:"With targetModel, name the target by its id."});let I=await ie(e,s["target-model"].model).id(),v=w.toLowerCase();E=I===n.id?{id:v,owned:y}:{id:v,owned:y,modelId:I}}else E={id:U(o,w),owned:y};return{edits:[{kind:"relate",element:a,relation:u.name,target:E,...s.group===void 0?{}:{group:s.group}}],subject:{id:a}}},$C=A({path:["el","relate"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage adding a target to an element's relation",description:`Adds <target> to the element's <relation>, keeping the targets it already holds. Whether the target is owned follows the relation: a reference relation refers to it, an owning one adopts it, and one that holds both (MIXED) adopts it unless --unowned. A grouped relation needs --group. A target in another model is named by its id with --target-model. ${K}`,positionals:[N(F),$e("element"),IC,SC],flags:{unowned:{type:"boolean",description:"Refer to the target rather than own it, on a relation that does both."},group:{type:"string",placeholder:"group",description:"The group of a grouped relation the target joins."},"target-model":{type:{address:"model",slot:de},placeholder:"model",description:"The id of the model the target lives in, when it is not this one; the target is then an id."},...q},examples:['modeldesk el relate <model> SHACL/NodeShape extends SHACL/Shape -m "NodeShape is a Shape"'],mcp:{name:"relate",operationOf:"stage_changes",description:"Add target to the relation of element."},plan:kC,run:async e=>X(e,t=>kC(e,t)),render:Q}),vC=(e,{read:t,tree:n})=>{let r=U(n,e.args.element),o=Object.keys(t.elements[r].relations??{}),s=Xe(o,e.args.relation)??e.args.relation,{target:i}=e.args,a=B(i)?i.toLowerCase():U(n,i);return{edits:[{kind:"unrelate",element:r,relation:s,target:a}],subject:{id:r}}},TC=A({path:["el","unrelate"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage removing a target from an element's relation",description:`Removes <target> from the element's <relation>, from whichever group holds it, keeping the other targets. A target in another model is named by its id. ${K}`,positionals:[N(F),$e("element"),IC,SC],flags:q,examples:['modeldesk el unrelate <model> SHACL/NodeShape extends SHACL/Shape -m "NodeShape stands alone"'],mcp:{name:"unrelate",operationOf:"stage_changes",description:"Remove target from the relation of element."},plan:vC,run:async e=>X(e,t=>vC(e,t)),render:Q});var xC=(e,{tree:t})=>{let n=U(t,e.args.element);return{edits:[{kind:"delete",element:n,recursive:e.flags.recursive}],subject:{id:n}}},AC=A({path:["el","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the deletion of an element",description:"Deletes the element, and with it everything it owns that no other element owns too. An element that owns anything is refused (exit 4) unless --recursive says to delete what it owns with it. "+K,positionals:[N(F),$e("element")],flags:{recursive:{type:"boolean",description:"Delete what the element owns with it."},...q},examples:['modeldesk el rm <model> SHACL/NodeShape/severity -m "Severity moved to Shape"'],mcp:{name:"rm",operationOf:"stage_changes",description:"Delete element, and what it owns with recursive: true."},plan:xC,run:async e=>X(e,t=>xC(e,t)),render:Q});var OC=async(e,t)=>{let{read:n,tree:r}=t,{values:o}=e.args,s=e.flags["json-value"];if(o.length===0&&s.length===0)throw k("Name at least one attr=value to set.","modeldesk el set --help");let i=U(r,e.args.element),a=await dC(e.api(),kt(t),n.elements[i],{values:o,json:s},e.flags.lang);return{edits:[{kind:"set",element:i,attributes:a}],subject:{id:i}}},NC=A({path:["el","set"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage new values for an element's attributes",description:`Replaces each named attribute's values with the ones given, typed by the attribute's declaration in the schema (see 'modeldesk describe'): true or false for a boolean, a number for a number, one of the listed values for an enum. Name an attribute again for several values. A language-tagged attribute is written in the --lang given (or the one language it already holds) and keeps its other languages. --json-value attr=<json> writes a structured value as it is. An unknown attribute exits 4 listing the valid ones. Relations are changed with 'el relate' and 'el unrelate'. ${K}`,positionals:[N(F),$e("element"),{name:"values",type:{list:"string"},description:"attr=value, once per value."}],flags:{"json-value":{type:{list:"string"},placeholder:"attr=json",description:"An attribute value given as JSON and written as it is."},lang:{type:"string",placeholder:"tag",description:"The language of the language-tagged values given."},...q},examples:['modeldesk el set <model> SHACL/NodeShape abstract=true -m "NodeShape is only ever specialized"','modeldesk el set <model> <element> rdfs:label=Persoon --lang nl -m "Dutch label"'],mcp:{name:"set",operationOf:"stage_changes",description:"Replace the values of attributes of element, given in values as attr=value."},plan:OC,run:async e=>X(e,t=>OC(e,t)),render:Q}),MC=(e,{read:t,tree:n})=>{let r=U(n,e.args.element),o=t.elements[r],s={attributes:Object.keys(o.attributes??{}),relations:Object.keys(o.relations??{})},i=[],a=[];for(let d of e.args.names){let l=Xe(s.attributes,d),c=l===void 0?Xe(s.relations,d):void 0;if(l!==void 0)i.push(l);else if(c!==void 0)a.push(c);else throw new f(`Element ${r} holds nothing under '${d}'.`,{exitCode:b.Validation,hint:`It holds: ${[...s.attributes,...s.relations].join(", ")||"nothing"}.`})}return{edits:[{kind:"unset",element:r,attributes:i,relations:a}],subject:{id:r}}},PC=A({path:["el","unset"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of attribute or relation values",description:`Removes every value the element holds under each name given, an attribute or a relation (a relation with all of its targets; to remove one target use 'el unrelate'). A name the element holds nothing under exits 4 listing the names it does hold. ${K}`,positionals:[N(F),$e("element"),{name:"names",type:{list:"string"},required:!0,description:"An attribute or relation to empty."}],flags:q,examples:['modeldesk el unset <model> SHACL/NodeShape alias -m "The alias was a typo"'],mcp:{name:"unset",operationOf:"stage_changes",description:"Remove every value element holds under each of names."},plan:MC,run:async e=>X(e,t=>MC(e,t)),render:Q});var _C=(e,t)=>{let n=e.label(t),r=e.element(t)?.type;return{id:t,...n===void 0?{}:{label:n},...r===void 0?{}:{type:r}}},DC=(e,t)=>t.map(n=>({..._C(e,n.id),relation:n.relation})),oj=(e,t,n)=>{let{id:r}=t,o=Object.fromEntries(Object.entries(t.relations??{}).map(([i,a])=>[i,Object.entries(a).flatMap(([d,l])=>l.map(c=>({..._C(e,c.id),owned:c.owned,...d==="@@"?{}:{group:d},...c.modelId?{modelId:c.modelId}:{}})))])),s=e.label(r);return{id:r,type:t.type,...s===void 0?{}:{label:s},...n.path===void 0?{}:{path:n.path},attributes:t.attributes??{},relations:o,owners:DC(e,e.owners(r)),children:DC(e,e.children(r)),url:n.url}},sj=e=>g(e!==null&&typeof e=="object"?JSON.stringify(e):String(e)),LC=e=>{let t=e.label===void 0?"(no label)":g(e.label),n=e.type?` (${e.type})`:"";return`${t}${n}`},ij=e=>{let t=[["id:",e.id],["type:",e.type],...e.path===void 0?[]:[["path:",g(e.path)]],["url:",e.url]],n=Object.entries(e.attributes).map(([s,i])=>[`${s}:`,i.map(sj).join(", ")]),r=Object.entries(e.relations).flatMap(([s,i])=>[` ${s}:`,...W(i.map(a=>[LC(a),a.id,[a.owned?"owned":"",a.group?`group ${a.group}`:"",a.modelId?`model ${a.modelId}`:""].filter(d=>d!=="").join(", ")]),{indent:" "})]),o=s=>s.length===0?[" none"]:W(s.map(i=>[LC(i),i.id,`via ${i.relation}`]),{indent:" "});return[Ae(e.ref,e.model),e.label===void 0?"(no label)":g(e.label),...W(t,{indent:" "}),"Attributes:",...n.length===0?[" none"]:W(n,{indent:" "}),"Relations:",...r.length===0?[" none"]:r,"Owners:",...o(e.owners),"Children:",...o(e.children)].join(`
236
+ `)},jC=A({path:["el","show"],effect:"read",summary:"Show one element of a model",description:"Shows an element's id, type, label, attribute values, relations (each target with its label), owners and children. Address the element by its id, or by its label path from the model root "+String.raw`(SHACL/NodeShape/severity; write a '/' inside a label as '\/'); a path must name exactly one element, `+"and passes through the platform's internal `@` elements only with --internal. Without a ref, reads your draft while it holds staged changes.",positionals:[N(Nt),$e("element")],flags:{...Dr},examples:["modeldesk el show <model> SHACL/NodeShape/severity","modeldesk el show <model>@head SHACL/NodeShape/severity","modeldesk el show <model> <element> --json"],run:async e=>{let{model:t,ref:n,tree:r}=await Lr(e,e.args.model,Nt),{internal:o}=e.flags,s=U(r,e.args.element,{internal:o}),i=r.element(s);if(i===void 0)throw new f(`No element ${s} in ${t.name}.`,{exitCode:b.NotFound});let a=ln(ft(r,{internal:o})).find(c=>c.id===s)?.path,d=e.webUrl({kind:"element",modelId:t.id,elementId:s});return{result:{model:t,ref:n,...oj(r,i,{path:a,url:d})}}},render:ij});var hn="modeldesk metamodel list",Sa=e=>`modeldesk metamodel extensions ${e}`,gn=(e,t,n,r)=>{let o=e.find(s=>s.id.toLowerCase()===t);if(o===void 0)throw new f(`No ${n} has the id '${t}'.`,{exitCode:b.NotFound,hint:`Run '${r}' to see the ids.`,details:{candidates:e.map(s=>({id:s.id,name:s.name}))}});return o};var aj=["ID","NAME","RELEASE","ABSTRACT"],dj=["ID","NAME","RELEASE","COMPLETES"],FC=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),qC=e=>g(e??""),WC=e=>e?"yes":"",lj=async e=>{let{items:t}=await e.metamodels.list();return t.filter(n=>n.kind!=="DATA_SCHEMA").map(({id:n,name:r,fullName:o,standardVersion:s,abstract:i})=>({id:n,name:r,...o?{fullName:o}:{},...s?{standardVersion:s}:{},abstract:i===!0})).sort(FC)},cj=async(e,t)=>{let{id:n,name:r}=gn((await e.metamodels.list()).items,t,"metamodel",hn),{items:o}=await e.metamodelExtensions.list(n),s=o.map(({id:i,name:a,fullName:d,standardVersion:l,concretizes:c,dependsOnExtensions:m})=>({id:i,name:a,...d?{fullName:d}:{},...l?{standardVersion:l}:{},completes:c===!0,dependsOn:m??[]})).sort(FC);return{metamodel:{id:n,name:r},rows:s}},HC=A({path:["metamodel","list"],effect:"read",summary:"List the metamodels a model can be written in",description:["Lists each metamodel with the id --metamodel takes, its name, the release @<release> takes, and whether it is abstract. An abstract metamodel needs an extension that completes it: run metamodel extensions <id>. Names are not unique, so a metamodel is addressed by its id.",{audience:"super-admin",text:"To read a metamodel as a model, a super-admin uses model list --kind metamodel."}],listing:{},examples:["modeldesk metamodel list","modeldesk metamodel list --json"],run:async e=>({result:await e.list(await lj(e.api()))}),render:({items:e})=>e.length===0?"No metamodels.":W([aj,...e.map(t=>[t.id,g(t.name),qC(t.standardVersion),WC(t.abstract)])]).join(`
237
+ `)}),BC=A({path:["metamodel","extensions"],effect:"read",summary:"List the extensions of a metamodel",description:"Lists the extensions a model written in the metamodel can apply, each with the id --extension takes. COMPLETES marks an extension that completes an abstract metamodel; a new model on one needs such an extension. Names are not unique, so an extension is addressed by its id.",positionals:[{name:"metamodel",type:{address:"model",slot:Gg},required:!0,description:"The metamodel's id, from metamodel list."}],listing:{},examples:["modeldesk metamodel extensions <metamodel>","modeldesk metamodel extensions <metamodel> --json"],run:async e=>{let{metamodel:t,rows:n}=await cj(e.api(),e.args.metamodel.model);return{result:{metamodel:t,...await e.list(n)}}},render:({items:e})=>e.length===0?"No extensions.":W([dj,...e.map(t=>[t.id,g(t.name),qC(t.standardVersion),WC(t.completes)])]).join(`
238
+ `)});var Om={type:"@Namespace",noun:"namespace",label:"@prefix"},yn={type:"@Diagram",noun:"diagram",label:"@name"},Mm={type:"@AttributeTemplate",noun:"attribute template",label:"@attribute"},GC={type:"@LayoutRule",noun:"layout rule"},VC={type:"@HierarchyGroup",noun:"hierarchy group"},UC="created",Qe=e=>({edits:[{kind:"action",key:UC,action:e}],subject:{key:UC}}),Me=(e,t)=>({edits:[{kind:"action",action:e}],subject:{id:t}}),mj=(e,t)=>e.attributes?.[t]?.[0],pj=(e,t)=>{let n=e.label===void 0?e.type.slice(1):"<text>",r=e.label===void 0?n:`<part of its ${e.label.slice(1)}>`;return{hint:`Run 'modeldesk search ${t} ${n} --internal --type ${e.type}' to find its id.`,hosted:{hint:o=>`Call ${o("search")} with text ${r}, internal: true and type ${e.type} to find its id.`}}},Ne=({tree:e,read:t,model:n},r,o)=>{if(r.startsWith(Fr))return e.keys?.get(r.slice(Fr.length))??U(e,r);let s=Object.values(t.elements).filter(i=>i.type===o.type);if(B(r)){let i=s.find(a=>a.id.toLowerCase()===r.toLowerCase());if(i!==void 0)return i.id}else if(o.label!==void 0){let i=o.label,a=s.filter(d=>mj(d,i)===r);if(a.length===1)return a[0].id;if(a.length>1)throw new f(`${a.length} ${o.noun}s of ${g(n.name)} are named '${r}'; address the one you mean by id.`,{exitCode:b.Usage,details:{candidates:a.map(({id:d})=>d)}})}throw new f(`No ${o.noun} '${r}' in ${g(n.name)}.`,{exitCode:b.NotFound,...pj(o,n.id)})},ls=(e,t,n)=>{if(e!==void 0&&!(Number.isInteger(e)&&e>=0)){let r=`takes a whole number from 0, got ${e}.`;throw k(`--${t} ${r}`,`modeldesk ${n} --help`,{reason:`${YC(t)} ${r}`})}},Nm=(e,t,n)=>{if(e!==void 0&&!B(e)){let r=`takes an id, got '${g(e)}'.`;throw k(`--${t} ${r}`,`modeldesk ${n} --help`,{reason:`${YC(t)} ${r}`})}},YC=e=>e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase()),$a={enum:["yes","no"]},cs=e=>e===void 0?void 0:e==="yes",Pm={enum:["TOP_TO_BOTTOM","BOTTOM_TO_TOP"]},Dm={position:{type:"number",required:!0,placeholder:"n",description:"Its place among the ones the diagram holds, from 0."}};var Lm="An attribute template derives an attribute's value, such as an element's IRI, from the model's base IRI.",QC={name:"entry",type:{address:"element"},required:!0,description:"The attribute template's id, or the attribute it fills in where one template does."},ZC={attribute:{type:"string",required:!0,placeholder:"attribute",description:"The attribute the template fills in."},flavor:{type:{enum:["BaseIriPlusValue","BaseIriPlusUuid"]},required:!0,placeholder:"flavor",description:"How the value is made: the base IRI and the value of the source attribute, or the base IRI and a UUID."},"element-type":{type:"string",placeholder:"type",description:"The element type it applies to; without it, every type."},source:{type:"string",placeholder:"attribute",description:"The attribute whose value is appended."},segment:{type:"string",placeholder:"text",description:"A literal path segment between the base and the value."},lang:{type:"string",placeholder:"tag",description:"The language of the source value to take."},casing:{type:{enum:["as-is","slug","camelCase","PascalCase","kebab-case","snake_case"]},placeholder:"casing",description:"How the source value is cased."},"short-form":{type:"boolean",description:"Write the value in its short, prefixed form."}},eR=e=>({attribute:e.attribute,flavor:e.flavor,...e["element-type"]===void 0?{}:{elementType:e["element-type"]},...e.source===void 0?{}:{source:e.source},...e.segment===void 0?{}:{segment:e.segment},...e.lang===void 0?{}:{lang:e.lang},...e.casing===void 0?{}:{casing:e.casing},...e["short-form"]?{shortForm:!0}:{}}),KC=({flags:e},{read:t,tree:n})=>{let r=Object.values(t.elements).find(o=>o.type==="@TemplateConfig");return Me({type:"TEMPLATE_CONFIG_UPDATE",update:{baseIri:e["base-iri"]}},r?.id??n.rootId)},tR=A({path:["attr-template","base"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the base IRI attribute templates share",description:`Sets the base IRI every attribute template of the model builds on. ${Lm} ${K}`,positionals:[N(F)],flags:{"base-iri":{type:"string",required:!0,placeholder:"iri",description:"The base IRI."},...q},examples:['modeldesk attr-template base <model> --base-iri https://example.org/id/ -m "IRIs under our domain"'],mcp:{name:"template_base",operationOf:"stage_changes",description:"Set baseIri, the base IRI the model's attribute templates build on."},plan:KC,run:async e=>X(e,t=>KC(e,t)),render:Q}),zC=({flags:e})=>Qe({type:"TEMPLATE_ENTRY_CREATE",creation:eR(e)}),nR=A({path:["attr-template","create"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage an attribute template",description:`Creates an attribute template. ${Lm} ${K}`,positionals:[N(F)],flags:{...ZC,...q},examples:['modeldesk attr-template create <model> --attribute uri --flavor BaseIriPlusValue --source name -m "IRIs from names"'],mcp:{name:"template_create",operationOf:"stage_changes",creates:!0,description:"Create an attribute template that fills in attribute by flavor."},plan:zC,run:async e=>X(e,()=>zC(e)),render:Q}),JC=({flags:e,args:t},n)=>{let r=Ne(n,t.entry,Mm);return Me({type:"TEMPLATE_ENTRY_UPDATE",entryId:r,update:eR(e)},r)},rR=A({path:["attr-template","set"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a change to an attribute template",description:`Replaces an attribute template as a whole: what is not given is cleared, so give every part it is to keep. ${Lm} ${K}`,positionals:[N(F),QC],flags:{...ZC,...q},examples:['modeldesk attr-template set <model> uri --attribute uri --flavor BaseIriPlusUuid -m "UUIDs, not names"'],mcp:{name:"template_set",operationOf:"stage_changes",description:"Replace attribute template entry whole: what is left out is cleared."},plan:JC,run:async e=>X(e,t=>JC(e,t)),render:Q}),XC=({args:e},t)=>{let n=Ne(t,e.entry,Mm);return Me({type:"TEMPLATE_ENTRY_DELETE",entryId:n},n)},oR=A({path:["attr-template","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of an attribute template",description:`Removes an attribute template. ${K}`,positionals:[N(F),QC],flags:q,examples:['modeldesk attr-template rm <model> uri -m "Enter IRIs by hand"'],mcp:{name:"template_rm",operationOf:"stage_changes",description:"Remove attribute template entry."},plan:XC,run:async e=>X(e,t=>XC(e,t)),render:Q});var vt={name:"diagram",type:{address:"element"},required:!0,description:"The diagram's name or its id."},lR={description:{type:"string",placeholder:"text",description:"What the diagram shows."},lang:{type:"string",placeholder:"tag",description:"The language of the description."},context:{type:{address:"element"},placeholder:"element",description:"The element the diagram is about (id or label path)."}},cR={orientation:{type:Pm,placeholder:"orientation",description:"Which way the layout runs."},"hierarchy-orientation":{type:Pm,placeholder:"orientation",description:"Which way the hierarchy runs."}},mR={published:{type:$a,placeholder:"yes|no",description:"Whether the diagram is published with the model; no holds it back."}},pR=(e,t,n)=>{if(e===void 0){if(t!==void 0)throw k("--lang names the language of --description, which was not given.",`modeldesk ${n} --help`,{reason:"lang names the language of description, which was not given."});return{}}return{description:[{value:e,...t===void 0?{}:{lang:t}}]}},sR=({flags:e,commandName:t},{tree:n})=>(Nm(e["diagram-type"],"diagram-type",t),Qe({type:"DIAGRAM_CREATE",creation:{name:e.name,...pR(e.description,e.lang,t),...e.context===void 0?{}:{contextElementId:U(n,e.context)},...e["diagram-type"]===void 0?{}:{diagramTypeId:e["diagram-type"]}}})),fR=A({path:["diagram","create"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a diagram",description:"Creates a custom diagram under the model root, with no elements on it yet: diagram set adds them. "+K,positionals:[N(F)],flags:{name:{type:"string",required:!0,placeholder:"name",description:"The diagram's name."},...lR,"diagram-type":{type:"string",placeholder:"id",description:"The id of the metamodel's diagram type it follows, where it follows one."},...q},examples:['modeldesk diagram create <model> --name Overview -m "A diagram of the main classes"'],mcp:{name:"diagram_create",operationOf:"stage_changes",creates:!0,description:"Create a custom diagram called name, empty until diagram_set adds elements."},plan:sR,run:async e=>X(e,t=>sR(e,t)),render:Q}),iR=({flags:e,args:t,commandName:n},r)=>{let{tree:o}=r,s=Ne(r,t.diagram,yn),i=cs(e.published),a={...e.name===void 0?{}:{name:e.name},...pR(e.description,e.lang,n),...e.context===void 0?{}:{contextElementId:U(o,e.context)},...e.add.length===0?{}:{addElementIds:e.add.map(d=>U(o,d))},...e.remove.length===0?{}:{removeElementIds:e.remove.map(d=>U(o,d))},...e.orientation===void 0?{}:{orientation:e.orientation},...e["hierarchy-orientation"]===void 0?{}:{hierarchyOrientation:e["hierarchy-orientation"]},...i===void 0?{}:{published:i}};if(Object.keys(a).length===0)throw k("Pass what to change: there is nothing to change.",`modeldesk ${n} --help`,{reason:"Give what to change: there is nothing to change."});return Me({type:"DIAGRAM_UPDATE",diagramId:s,update:a},s)},uR=A({path:["diagram","set"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a change to a diagram",description:`Changes a diagram: its name, description or context element, the elements on it, its orientation, and whether it is published; what is not given is kept. A template-backed diagram takes its name, description and elements from its template, so those are refused on one. ${K}`,positionals:[N(F),vt],flags:{name:{type:"string",placeholder:"name",description:"The new name."},...lR,add:{type:{list:{address:"element"}},placeholder:"element",description:"An element to put on the diagram (id or label path), once per element."},remove:{type:{list:{address:"element"}},placeholder:"element",description:"An element to take off the diagram (id or label path), once per element."},...cR,...mR,...q},examples:['modeldesk diagram set <model> Overview --add Model/Customer --add Model/Order -m "Customers and orders"','modeldesk diagram set <model> Overview --published no -m "Not ready to publish"'],mcp:{name:"diagram_set",operationOf:"stage_changes",description:"Change the name, description, context, elements (add, remove), orientation, hierarchyOrientation or published of diagram; what is left out is kept."},plan:iR,run:async e=>X(e,t=>iR(e,t)),render:Q}),aR=({args:e},t)=>{let n=Ne(t,e.diagram,yn);return Me({type:"DIAGRAM_DELETE",diagramId:n},n)},hR=A({path:["diagram","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of a diagram",description:"Removes a diagram with its layout rules and hierarchy groups; the elements it shows stay in the model. "+K,positionals:[N(F),vt],flags:q,examples:['modeldesk diagram rm <model> Overview -m "Replaced by the context diagram"'],mcp:{name:"diagram_rm",operationOf:"stage_changes",description:"Remove diagram, with its layout rules and hierarchy groups."},plan:aR,run:async e=>X(e,t=>aR(e,t)),render:Q}),dR=({flags:e,args:t,commandName:n},{tree:r})=>{Nm(e.template,"template",n);let o=cs(e.published);return Qe({type:"DIAGRAM_MATERIALIZE",templateId:e.template,rootElementId:U(r,t.root),materialization:{...e.orientation===void 0?{}:{orientation:e.orientation},...e["hierarchy-orientation"]===void 0?{}:{hierarchyOrientation:e["hierarchy-orientation"]},...o===void 0?{}:{published:o}}})},gR=A({path:["diagram","materialize"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a stored diagram of a template instance",description:"Stores the diagram one of the metamodel's diagram templates shows for a root element, so it can take an orientation, layout rules and hierarchy groups of its own. An instance is stored once. "+K,positionals:[N(F),{...$e("root"),description:"The root element of the instance."}],flags:{template:{type:"string",required:!0,placeholder:"id",description:"The id of the diagram template."},...cR,...mR,...q},examples:['modeldesk diagram materialize <model> Model/Customer --template <id> -m "Lay out the customer view"'],mcp:{name:"diagram_materialize",operationOf:"stage_changes",creates:!0,description:"Store the diagram template's instance for root as a diagram of its own."},plan:dR,run:async e=>X(e,t=>dR(e,t)),render:Q});var vR=["ABOVE","BELOW","SAME_LEVEL"],fj=["BEFORE","AFTER"],uj=e=>vR.includes(e),IR={name:"rule",type:{address:"element"},required:!0,description:"The layout rule's id."},_m={name:"group",type:{address:"element"},required:!0,description:"The hierarchy group's id."},hj=(e,t,n)=>uj(e)?{"@type":"LevelRule",element:t,refElement:n,type:e}:{"@type":"OrderRule",element:t,refElement:n,type:e},yR=({flags:e,args:t},n)=>Qe({type:"LAYOUT_RULE_CREATE",diagramId:Ne(n,t.diagram,yn),creation:hj(e.type,U(n.tree,e.element),U(n.tree,e["ref-element"]))}),SR=A({path:["diagram","rule","create"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a layout rule on a diagram",description:`Adds a layout rule at the end of the diagram's: an element placed above, below or level with another, or before or after it. ${K}`,positionals:[N(F),vt],flags:{element:{type:{address:"element"},required:!0,placeholder:"element",description:"The element the rule places (id or label path)."},type:{type:{enum:[...vR,...fj]},required:!0,placeholder:"type",description:"Where it goes relative to the other element."},"ref-element":{type:{address:"element"},required:!0,placeholder:"element",description:"The element it is placed relative to (id or label path)."},...q},examples:['modeldesk diagram rule create <model> Overview --element Model/Order --type BELOW --ref-element Model/Customer -m "Orders below customers"'],mcp:{name:"rule_create",operationOf:"stage_changes",creates:!0,description:"Add a layout rule to diagram placing element by type relative to refElement."},plan:yR,run:async e=>X(e,t=>yR(e,t)),render:Q}),$R=({args:e},t)=>({diagramId:Ne(t,e.diagram,yn),layoutRuleId:Ne(t,e.rule,GC)}),wR=(e,t)=>{let n=$R(e,t);return Me({type:"LAYOUT_RULE_DELETE",...n},n.diagramId)},TR=A({path:["diagram","rule","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of a layout rule",description:`Removes a layout rule from the diagram that holds it. ${K}`,positionals:[N(F),vt,IR],flags:q,examples:['modeldesk diagram rule rm <model> Overview <rule> -m "Let the layout decide"'],mcp:{name:"rule_rm",operationOf:"stage_changes",description:"Remove layout rule from diagram."},plan:wR,run:async e=>X(e,t=>wR(e,t)),render:Q}),bR=(e,t)=>{ls(e.flags.position,"position",e.commandName);let n=$R(e,t);return Me({type:"LAYOUT_RULE_MOVE",...n,move:{position:e.flags.position}},n.diagramId)},xR=A({path:["diagram","rule","mv"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a move of a layout rule",description:`Moves a layout rule to another place among the diagram's, which apply in order. ${K}`,positionals:[N(F),vt,IR],flags:{...Dm,...q},examples:['modeldesk diagram rule mv <model> Overview <rule> --position 0 -m "Apply it first"'],mcp:{name:"rule_mv",operationOf:"stage_changes",description:"Move layout rule to position among diagram's rules."},plan:bR,run:async e=>X(e,t=>bR(e,t)),render:Q}),AR={root:{type:{address:"element"},required:!0,placeholder:"element",description:"The element whose children the group spreads (id or label path)."},"max-left":{type:"number",placeholder:"n",description:"How many children spread to its left; 0 without it."},"max-right":{type:"number",placeholder:"n",description:"How many children spread to its right; 0 without it."}},OR=(e,{tree:t},n)=>(ls(e["max-left"],"max-left",n),ls(e["max-right"],"max-right",n),{root:U(t,e.root),...e["max-left"]===void 0?{}:{maxLeft:e["max-left"]},...e["max-right"]===void 0?{}:{maxRight:e["max-right"]}}),ER=({flags:e,args:t,commandName:n},r)=>Qe({type:"HIERARCHY_GROUP_CREATE",diagramId:Ne(r,t.diagram,yn),creation:OR(e,r,n)}),MR=A({path:["diagram","group","create"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a hierarchy group on a diagram",description:`Adds a hierarchy group at the end of the diagram's: how the children of a root element spread to its left and right. A root carries one group. ${K}`,positionals:[N(F),vt],flags:{...AR,...q},examples:['modeldesk diagram group create <model> Overview --root Model/Customer --max-left 2 -m "Spread its parts"'],mcp:{name:"group_create",operationOf:"stage_changes",creates:!0,description:"Add a hierarchy group to diagram spreading root's children by maxLeft and maxRight."},plan:ER,run:async e=>X(e,t=>ER(e,t)),render:Q}),jm=({args:e},t)=>({diagramId:Ne(t,e.diagram,yn),hierarchyGroupId:Ne(t,e.group,VC)}),CR=(e,t)=>{let n=jm(e,t);return Me({type:"HIERARCHY_GROUP_UPDATE",...n,update:OR(e.flags,t,e.commandName)},n.diagramId)},NR=A({path:["diagram","group","set"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a change to a hierarchy group",description:"Replaces a hierarchy group as a whole, keeping its place: a spread not given is 0 again. "+K,positionals:[N(F),vt,_m],flags:{...AR,...q},examples:['modeldesk diagram group set <model> Overview <group> --root Model/Customer --max-right 3 -m "Wider"'],mcp:{name:"group_set",operationOf:"stage_changes",description:"Replace hierarchy group of diagram whole, from root, maxLeft and maxRight."},plan:CR,run:async e=>X(e,t=>CR(e,t)),render:Q}),RR=(e,t)=>{let n=jm(e,t);return Me({type:"HIERARCHY_GROUP_DELETE",...n},n.diagramId)},PR=A({path:["diagram","group","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of a hierarchy group",description:`Removes a hierarchy group from the diagram that holds it. ${K}`,positionals:[N(F),vt,_m],flags:q,examples:['modeldesk diagram group rm <model> Overview <group> -m "Let the layout decide"'],mcp:{name:"group_rm",operationOf:"stage_changes",description:"Remove hierarchy group from diagram."},plan:RR,run:async e=>X(e,t=>RR(e,t)),render:Q}),kR=(e,t)=>{ls(e.flags.position,"position",e.commandName);let n=jm(e,t);return Me({type:"HIERARCHY_GROUP_MOVE",...n,move:{position:e.flags.position}},n.diagramId)},DR=A({path:["diagram","group","mv"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a move of a hierarchy group",description:`Moves a hierarchy group to another place among the diagram's. ${K}`,positionals:[N(F),vt,_m],flags:{...Dm,...q},examples:['modeldesk diagram group mv <model> Overview <group> --position 0 -m "First"'],mcp:{name:"group_mv",operationOf:"stage_changes",description:"Move hierarchy group to position among diagram's groups."},plan:kR,run:async e=>X(e,t=>kR(e,t)),render:Q});var gj=(e,t,n)=>e.map(r=>{if(!t)return U(n.tree,r);if(!B(r))throw new f(`'${r}' is not an id: an element of another model is copied by its id, which search finds there.`,{exitCode:b.Usage});return r.toLowerCase()}),LR=({flags:e,args:t,commandName:n},r)=>{if(t.elements.length===0)throw k("Name at least one element to copy.",`modeldesk ${n} --help`,{reason:"Give at least one element to copy."});if(e.parent===void 0!=(e.relation===void 0))throw k("--parent and --relation go together: the relation of the parent that owns the copies.",`modeldesk ${n} --help`,{reason:"parent and relation go together: the relation of the parent that owns the copies."});let o=e["from-model"]?.model??r.model.id,s=o.toLowerCase()!==r.model.id.toLowerCase(),i=e.parent===void 0||e.relation===void 0?void 0:{id:U(r.tree,e.parent),relation:e.relation};return Qe({type:"ELEMENT_PASTE",paste:{sourceModelId:o,elementIds:gj(t.elements,s,r),...i===void 0?{}:{targetOwner:i},mode:"COPY"}})},_R=A({path:["el","paste"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a copy of elements, each with what it owns",description:"Copies elements, each with the subtree it owns, into the model: from the model itself, or from another model of the same organization written in a compatible metamodel. The copies land at the model root, or under --parent through --relation. References the copies cannot carry over are dropped. "+K,positionals:[N(F),{name:"elements",type:{list:{address:"element"}},required:!0,description:"The elements to copy: ids, or label paths within the model itself."}],flags:{"from-model":{type:{address:"model",slot:de},placeholder:"model",description:"The id of the model to copy from; without it, the model itself."},parent:{type:{address:"element"},placeholder:"element",description:"The element that owns the copies (id or label path); without it, the model root."},relation:{type:"string",placeholder:"relation",description:"The relation of --parent that owns the copies.",toolDescription:"The relation of parent that owns the copies."},...q},examples:['modeldesk el paste <model> Model/Customer -m "A second customer to start from"','modeldesk el paste <model> <element> --from-model <model> --parent Model --relation packagedElement -m "Reuse"'],mcp:{name:"paste",operationOf:"stage_changes",description:"Copy elements, each with what it owns, from fromModel (an id; without it, the model itself), to the model root or under parent through relation."},plan:LR,run:async e=>X(e,t=>LR(e,t)),render:Q});var WR={name:"namespace",type:{address:"element"},required:!0,description:"The namespace's prefix or its id."},HR={type:$a,placeholder:"yes|no",description:"Whether it is the model's default namespace."},jR=({flags:e})=>Qe({type:"NAMESPACE_CREATE",creation:{prefix:e.prefix,uri:e.uri,...e.default==="yes"?{isDefault:!0}:{}}}),BR=A({path:["namespace","create"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a namespace",description:`Creates a namespace of the model: a prefix and the IRI it stands for. ${K}`,positionals:[N(F)],flags:{prefix:{type:"string",required:!0,placeholder:"prefix",description:"The prefix, such as ex."},uri:{type:"string",required:!0,placeholder:"iri",description:"The IRI the prefix stands for."},default:HR,...q},examples:['modeldesk namespace create <model> --prefix ex --uri https://example.org/def# -m "Our namespace"'],mcp:{name:"namespace_create",operationOf:"stage_changes",creates:!0,description:'Create a namespace with prefix and uri; default: "yes" makes it the default.'},plan:jR,run:async e=>X(e,()=>jR(e)),render:Q}),FR=({flags:e,args:t,commandName:n},r)=>{let o=Ne(r,t.namespace,Om),s=cs(e.default);if(e.prefix===void 0&&e.uri===void 0&&s===void 0)throw k("Pass --prefix, --uri or --default: there is nothing to change.",`modeldesk ${n} --help`,{reason:"Give prefix, uri or default: there is nothing to change."});return Me({type:"NAMESPACE_UPDATE",namespaceId:o,update:{...e.prefix===void 0?{}:{prefix:e.prefix},...e.uri===void 0?{}:{uri:e.uri},...s===void 0?{}:{isDefault:s}}},o)},UR=A({path:["namespace","set"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a change to a namespace",description:`Changes a namespace's prefix, IRI or whether it is the default; what is not given is kept. ${K}`,positionals:[N(F),WR],flags:{prefix:{type:"string",placeholder:"prefix",description:"The new prefix."},uri:{type:"string",placeholder:"iri",description:"The new IRI."},default:HR,...q},examples:['modeldesk namespace set <model> ex --uri https://example.org/ns# -m "Move the namespace"'],mcp:{name:"namespace_set",operationOf:"stage_changes",description:"Change the prefix, uri or default of namespace; what is left out is kept."},plan:FR,run:async e=>X(e,t=>FR(e,t)),render:Q}),qR=({args:e},t)=>{let n=Ne(t,e.namespace,Om);return Me({type:"NAMESPACE_DELETE",namespaceId:n},n)},GR=A({path:["namespace","rm"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage the removal of a namespace",description:`Removes a namespace of the model. ${K}`,positionals:[N(F),WR],flags:q,examples:['modeldesk namespace rm <model> ex -m "No longer used"'],mcp:{name:"namespace_rm",operationOf:"stage_changes",description:"Remove namespace."},plan:qR,run:async e=>X(e,t=>qR(e,t)),render:Q});var yj=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],wj="7fa3158b-e053-47e1-8e05-638157c335b6",bj="agent",wn=e=>{let t=e.orgs;if(t!==null&&typeof t=="object"){let n=e.mdsk_actor===bj;return Object.entries(t).filter(([r])=>!n||r.toLowerCase()!==wj).map(([r,o])=>{let{name:s,seatAssignments:i}=o??{};return{id:r,...typeof s=="string"?{name:s}:{},seatAssignments:yj(i)}})}return typeof e.mdsk_org=="string"?[{id:e.mdsk_org}]:[]},Fm=e=>e.name?`${e.name} (${e.id})`:e.id,Ta=e=>e.map(({id:t,name:n})=>({id:t,...n?{name:n}:{}})),Ej=(e,t)=>e.seatAssignments===void 0||e.seatAssignments.some(n=>n.toLowerCase()===t.toLowerCase()),Cj="me",ms=(e,t)=>{let n=t.toLowerCase(),r=e.filter(o=>B(t)?o.id.toLowerCase()===n:o.name?.toLowerCase()===n);if(r.length===1)return r[0];throw r.length>1?new f(`${r.length} of your organizations are named '${t}'; pass --owner with an id.`,{exitCode:b.Usage,details:{candidates:Ta(r)},hosted:{reason:`${r.length} of your organizations are named '${t}'; give the owner by its id.`}}):new f(`You are not a member of an organization '${t}'.`,{exitCode:b.NotFound,hint:e.length===0?"Your credential names no organization.":`Your organizations: ${e.map(Fm).join(", ")}.`,details:{candidates:Ta(e)}})},qm=(e,t)=>{if(t===Cj)throw new f("An import is owned by an organization in which you hold a seat for its metamodel, so --owner me does not apply.",{exitCode:b.Usage,hint:"Pass --owner <organization> with one of your organizations."});return ms(e,t)},VR=(e,t,n)=>{if(n!==void 0){let{id:o,name:s}=qm(e,n);return{id:o,...s?{name:s}:{},chosen:"owner-flag"}}let r=e.filter(o=>Ej(o,t.id));if(r.length===1){let[{id:o,name:s}]=r;return{id:o,...s?{name:s}:{},chosen:"only-seated"}}throw r.length===0?new f(`None of your organizations gives you a seat for ${t.name}, and an import must be owned by one that does.`,{exitCode:b.Usage,hint:e.length===0?"Your credential names no organization.":`Pass --owner to choose one anyway (yours: ${e.map(Fm).join(", ")}); the server checks the seat.`,details:{candidates:Ta(e)}}):new f(`${r.length} of your organizations give you a seat for ${t.name}: ${r.map(Fm).join(", ")}.`,{exitCode:b.Usage,hint:"Pass --owner <organization> to choose the owner.",details:{candidates:Ta(r)}})};var YR={modelCreate:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"},kind:{type:"string",description:'One of "metamodel", "model".'},metamodel:{type:"object",properties:{id:{type:"string"},name:{type:"string"},version:{type:"string",description:"The release pinned; absent means the latest stable release, resolved by the server."}}},extensions:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},version:{type:"string",description:"The release pinned; absent means the latest stable release, resolved by the server."}}}},owner:{type:"object",properties:{id:{type:"string"},type:{type:"string",description:'One of "MACHINE", "ORGANIZATION", "SYSTEM", "USER".'},name:{type:"string"}}}},description:"The model created; on a dry run, the one that would be, without an id."},dryRun:{type:"boolean",description:"One of false, true."},url:{type:"string",description:"The new model in the app."}},required:["schemaVersion","model","dryRun"]}};var ar="modeldesk model create --help",KR={enum:["model","metamodel"],audience:{metamodel:"super-admin"}},kj=e=>e.name?`${e.name} (${e.id})`:e.id,vj=e=>{let t=e.length===0?"This connection reaches no organization of the person, so no model can be created through it.":`This connection reaches ${e.length} of the person's organizations (${e.map(kj).join(", ")}); ask the person which owns the model and give it as owner.`;return new f(t,{exitCode:b.Usage,details:{candidates:e.map(({id:n,name:r})=>({id:n,...r?{name:r}:{}}))}})},Ij=(e,t,n)=>{let r=wn(e);if(t==="me"&&n)throw k("A model you create through this connection belongs to one of the person's organizations: give owner as the organization's name or id.",ar);if(t==="me"){if(typeof e.sub!="string")throw k("This credential is no user, so --owner me names no one.",ar);return{id:e.sub,type:"USER"}}if(t!==void 0){if(B(t))return{id:t.toLowerCase(),type:"ORGANIZATION"};let{id:o,name:s}=ms(r,t);return{id:o,type:"ORGANIZATION",...s?{name:s}:{}}}if(r.length===1){let[o]=r;return{id:o.id,type:"ORGANIZATION",...o.name?{name:o.name}:{}}}throw n?vj(r):k(r.length===0?"You belong to no organization: pass --owner <organization>, or --owner me for a model of your own.":`You belong to ${r.length} organizations (${r.map(o=>o.name??o.id).join(", ")}); pass --owner <organization> to say which owns the model.`,ar)},Sj=async(e,t,n)=>{let r=(await e.metamodels.list()).items.filter(a=>a.kind!=="DATA_SCHEMA"),o=gn(r,t.model,"metamodel",hn),s=n.length>0?(await e.metamodelExtensions.list(o.id)).items:[],i=(a,d)=>{let l=Mr(d);return{id:a.id,name:a.name,...l?{version:l}:{}}};return{metamodel:i(o,t),extensions:n.map(a=>i(gn(s,a.model,`extension of ${o.name}`,Sa(o.id)),a))}},$j=(e,t,n,r)=>{let o=r.filter(s=>s.version!==void 0);return{name:e,metamodelId:n.id,...n.version?{metamodelVersion:n.version}:{},...r.length>0?{metamodelExtensionIds:r.map(s=>s.id)}:{},...o.length>0?{metamodelExtensionVersions:Object.fromEntries(o.map(s=>[s.id,s.version]))}:{},owner:{id:t.id,type:t.type}}},zR=async(e,t)=>{try{return await e()}catch(n){throw n instanceof f&&n.exitCode===b.Transient?new f(`${n.reason} The model may or may not have been created.`,{exitCode:b.Transient,type:n.type,requestId:n.requestId,details:n.details,hint:`Run 'modeldesk model list' and look for ${g(t)} before retrying: a creation carries no idempotency key, so a retry after one that landed creates a second model.`}):n}},JR=e=>{let t=e.version?`@${e.version}`:"";return`${g(e.name)}${t}`},Tj=e=>e?.length?` with ${e.map(JR).join(", ")}`:"",xj=e=>e.metamodel?` on ${JR(e.metamodel)}${Tj(e.extensions)}`:" as a metamodel-model",Aj=e=>{let{model:t}=e,n=xj(t),r=t.owner?`, owned by ${g(t.owner.name??t.owner.id)}`:"";return e.dryRun?`Would create ${g(t.name)}${n}${r}. Dry run: nothing was created.`:[`Created ${g(t.name)} (${t.id})${n}${r}.`,...e.url?[`url: ${e.url}`]:[]].join(`
239
+ `)},XR=A({path:["model","create"],effect:"create",summary:"Create a model",description:["Creates a model written in --metamodel (its id from metamodel list, with @<release> to pin one; the latest stable release otherwise), with the --extension(s) given the same way (ids from metamodel extensions <metamodel>), owned by --owner (an organization of yours by name or id, or me) or by your one organization. An abstract metamodel needs an extension that completes it. The creation is committed directly; no draft is involved.",{audience:"super-admin",text:"--kind metamodel creates a metamodel-model instead, which belongs to the platform and takes a super-admin."},"--dry-run checks the ids and shows what would be created."],flags:{name:{type:"string",required:!0,placeholder:"name",description:"The new model's name."},metamodel:{type:{address:"model",slot:Di},placeholder:"metamodel[@release]",description:"The metamodel's id, from metamodel list, at @<release> or else its latest stable release (required for a model)."},extension:{type:{list:{address:"model",slot:Li}},placeholder:"extension[@release]",description:"An extension's id, from metamodel extensions <metamodel>, at @<release> or else its latest stable release."},owner:{type:"string",placeholder:"organization|me",description:"Who owns it: an organization of yours, by name or id, or me; default your one organization.",toolDescription:"The organization that owns it, by name or id; required when the connection reaches more than one of the person's."},kind:{type:KR,default:"model",description:"model, or metamodel for a metamodel-model (super-admin).",audience:"super-admin"},"standard-version":{type:"string",placeholder:"version",description:"A metamodel-model's standard version (such as 0.1.0).",audience:"super-admin"}},dryRun:!0,examples:["modeldesk model create --name Shapes --metamodel <metamodel>","modeldesk model create --name Catalog --metamodel <metamodel>@1.2.0 --owner Acme --json"],mcp:{name:"model_create",description:"Creates a new, empty model written in metamodel (an id from list_metamodels, with @<release> to pin one), with the extensions given the same way, owned by owner. Only the person sees the model until they share it in the app. Call it only when the person asked for a new model; when the connection reaches several of their organizations, ask which one owns it. Returns the model id every other tool takes and the url the person opens it at; then stage its content with stage_changes and hand the draft off.",pin:{dryRun:!1}},resultSchema:YR.modelCreate,run:async e=>{let{flags:t,dryRun:n}=e,r=e.api(),o=e.agent?.surface==="mcp";if(t.kind==="metamodel"){if(!an(await r.accessTokenClaims()))throw ki("--kind",KR,t.kind,ar,Ao);if(t.metamodel!==void 0||t.owner!==void 0||t.extension.length>0)throw k("A metamodel-model is written in the meta-metamodel and owned by the platform: it takes no --metamodel, --extension or --owner.",ar);let m={name:t.name,...t["standard-version"]?{standardVersion:t["standard-version"]}:{}};if(n)return{result:{model:{name:t.name,kind:"metamodel"},dryRun:n}};let p=await zR(()=>r.metamodelModels.create(m),t.name);return{result:{model:{id:p.id,name:p.name,kind:"metamodel",owner:p.owner},dryRun:n,url:e.webUrl({kind:"model",modelId:p.id})}}}if(t["standard-version"]!==void 0)throw k("--standard-version does not apply to a model.",ar);if(t.metamodel===void 0)throw k("Pass the --metamodel the model is written in.",ar);let[s,{metamodel:i,extensions:a}]=await Promise.all([r.accessTokenClaims().then(m=>Ij(m,t.owner,o)),Sj(r,t.metamodel,t.extension)]),d={name:t.name,kind:"model",metamodel:i,...a.length>0?{extensions:a}:{},owner:s};if(n)return{result:{model:d,dryRun:n}};let l=await zR(()=>r.models.create($j(t.name,s,i,a)),t.name);return{result:{model:{...d,id:l.id,name:l.name,owner:l.owner},dryRun:n,url:e.webUrl({kind:"model",modelId:l.id})}}},render:Aj});var QR={modelDelete:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"},owner:{type:"object",properties:{id:{type:"string"},type:{type:"string",description:'One of "MACHINE", "ORGANIZATION", "SYSTEM", "USER".'},name:{type:"string"}}},headCommitId:{type:"string"}},description:"The model that was deleted, as it stood."},deleted:{type:"boolean",description:"False on a dry run. One of false, true."},dryRun:{type:"boolean",description:"One of false, true."},impact:{type:"object",properties:{releases:{type:"array",items:{type:"string"},description:"The names of the model's releases, newest first."},dependents:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},description:"The models that depend on the model and the caller may read, which refuse the delete while they do."},hiddenDependentCount:{type:"number",description:"How many models depend on it that the caller may not read; they refuse the delete as well."},public:{type:"boolean",description:"Whether its catalog record makes it public while it is shared: deleting it takes its published addresses away. One of false, true."}},description:"On a dry run, what the delete would take away besides the model's content."}},required:["schemaVersion","model","deleted","dryRun"]}};var xa=e=>{let t=e.owner?`, owned by ${g(e.owner.name??e.owner.id)}`:"";return`model ${g(e.name)} (${e.id})${t}`},ZR=async(e,t)=>{let n=await ie(e,t).identity();return{id:n.id,name:n.name,...n.owner?{owner:n.owner}:{},headCommitId:n.branch.head.id}},Mj=async(e,t,n)=>{if(!n)return!1;try{return(await e.models.metadata(t)).public}catch(r){if(r instanceof V&&(r.status===403||r.status===404))return!1;throw r}},Nj=async(e,t)=>{let n=e.api(),r=await ie(e,t).identity(),[o,s,i]=await Promise.all([n.models.versions(t),n.models.overview(t),Mj(n,t,(r.accessMode??"SHARED")==="SHARED")]);return{releases:o.items.map(a=>a.name),dependents:s.dependedOnBy.items.flatMap(a=>a.modelId===void 0?[]:[{id:a.modelId,name:a.name}]),hiddenDependentCount:s.dependedOnBy.hiddenCount??0,public:i}},ek=A({path:["model","delete"],effect:"destroy",summary:"Delete a model",description:"Deletes the model with its content, history and releases. It restates which model that is and asks at a terminal; anywhere else it needs --yes. A model other models still depend on is refused (exit 5). --dry-run restates which model it would delete, its releases, the models that depend on it and whether it is public, and deletes nothing. Under an agent host deleting a model is left to a person (exit 6).",positionals:[N(de)],dryRun:!0,examples:["modeldesk model delete <model> --dry-run","modeldesk model delete <model> --yes"],mcp:{...lc,choice:{member:cc,value:"model",description:"Delete the model, with its history and releases."}},resultSchema:QR.modelDelete,prepare:async e=>{if(!e.dryRun){let t=xa(await ZR(e,e.args.model.model));e.print(`This deletes ${t}: its content, its history and its releases.
240
+ `),await yt(e,`Delete ${t}?`,`Deleting ${t}`)}},run:async e=>{let t=await ZR(e,e.args.model.model);if(e.dryRun){let r=await Nj(e,t.id);return{result:{model:t,deleted:!1,dryRun:!0,impact:r}}}try{await e.api().models.delete(t.id)}catch(r){throw r instanceof f&&r.exitCode===b.Conflict?new f(`Other models depend on ${xa(t)}, so it was not deleted.`,{exitCode:b.Conflict,type:r.type,details:r.details,hint:"Run 'modeldesk model show' to see what depends on it.",hosted:{hint:o=>`Call ${o("model delete")} with dryRun: true to see what depends on it.`}}):r}return{result:{model:t,deleted:!0,dryRun:!1}}},render:e=>{if(!e.dryRun)return`Deleted ${xa(e.model)}.`;let t=[`Would delete ${xa(e.model)}. Dry run: nothing was deleted.`],{impact:n}=e;if(n!==void 0){n.releases.length>0&&t.push(`Its releases go with it: ${n.releases.map(g).join(", ")}.`);let r=n.dependents.length+n.hiddenDependentCount;r>0&&t.push(`${r} model${r===1?"":"s"} depend on it, which refuses the delete.`),n.public&&t.push("It is public: deleting it takes its published addresses away.")}return t.join(`
241
+ `)}});import{createHash as xH,randomUUID as AH}from"node:crypto";import{closeSync as OH,lstatSync as MH,mkdirSync as NH,openSync as PH,readdirSync as sS,readFileSync as DH,readSync as LH,renameSync as _H,rmdirSync as jH,rmSync as iS,writeFileSync as FH}from"node:fs";import{dirname as qH,join as hr,posix as WH,resolve as Nf}from"node:path";var Re=bl(Td(),1);var Ut=2,xd=".modeldesk",Rf="workspace.json",Gt="model.yaml",BI="_element.yaml",UI="_unowned",$t="model.json",aH="# modeldesk",GI=/^# modeldesk(?::|\s|$)/,Ad=8*1024*1024,kf=128*1024*1024,et=100,vf=["id","type","attributes","relations","readOnly"],If=["ref","owned","model"],VI=[...Je,"relations"],dH="@element",Vt=e=>e.startsWith("@")&&e!==dH,YI={lineWidth:0,minContentWidth:0,doubleQuotedAsJSON:!0,indentSeq:!0},Sf={version:"1.2",schema:"core",uniqueKeys:!0,prettyErrors:!1},xn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$f=e=>e in Object.prototype,H=e=>ye(g(e)),lH=/^[A-Za-z_][A-Za-z0-9_-]*$/,cH=/^(?:y|yes|n|no|true|false|on|off|null)$/i,KI=e=>{let t=new Re.Scalar(e);return(!lH.test(e)||cH.test(e))&&(t.type=Re.Scalar.QUOTE_DOUBLE),t},Hs=(e,t=0)=>{if(t>et)throw new f(`A value nests more than ${et} deep, deeper than a workspace is written.`,{type:"model-too-deep"});if(Array.isArray(e)){let r=new Re.YAMLSeq;return r.items=e.map(o=>Hs(o,t+1)),r}if(e!==null&&typeof e=="object")return Yt(Object.keys(e).sort(fe).map(r=>[r,Hs(e[r],t+1)]));let n=new Re.Scalar(e);return typeof e=="string"&&(n.type=Re.Scalar.QUOTE_DOUBLE),n},Yt=e=>{let t=new Re.YAMLMap;return t.items=e.map(([n,r])=>new Re.Pair(KI(n),r)),t},ur=(e,t)=>{let n=new Re.Scalar(e);return n.type=Re.Scalar.QUOTE_DOUBLE,t!==void 0&&t!==""&&(n.comment=` ${t}`),n},fe=(e,t)=>e<t?-1:e>t?1:0,Od=(e,t)=>{let n=new Re.Document;return n.contents=e,n.commentBefore=`${aH.slice(1)}: ${t}`,n.toString(YI)},zI=(e,t)=>{let n=(0,Re.parseDocument)(e,Sf),r=[];for(let{path:o,id:s}of t){let i=o.length===0?n.contents:n.getIn(o,!0);if(!(0,Re.isMap)(i)||i.has("id")){r.push(o);continue}i.items.unshift(new Re.Pair(KI("id"),ur(s)))}return{text:n.toString(YI),missed:r}},mH=/^(?:con|prn|aux|nul|com\d|lpt\d)$/,pH=64,Tf=e=>e.normalize("NFKD").replace(new RegExp("\\p{M}+","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,pH).replace(/-$/g,""),xf=e=>e===""||mH.test(e),Tt=e=>e.map(t=>`/${String(t).replaceAll("~","~0").replaceAll("/","~1")}`).join("");var Nd=bl(Td(),1);var fH=100,Of=50,tt=class extends f{constructor(n){let[r]=n,o=n.length>1?` (and ${n.length-1} more)`:"",s=r.at?` at ${r.at}`:"";super(H(`${r.file}${s}: ${r.message}${o}`),{exitCode:b.Validation,type:"workspace-invalid",hint:"The workspace format is described in the CLI's README; 'modeldesk model pull --force' rewrites the files.",details:{errors:n}});this.problems=n;this.name="WorkspaceInvalidError"}problems},Pe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Af=class{elements=new Map;fileLevel=new Set;problems=[];add(t,n){let r=this.elements.get(t.key);if(r!==void 0){n.problem([...t.location.path],"duplicate-id",`The id ${t.key} is also used at ${r.location.file}${Tt(r.location.path)||" (its top)"}; every element is written once. Give a copy no id (a new element), or reference it by id.`);return}this.elements.set(t.key,t)}full(){return this.problems.length>=Of}},Md=(e,t,n)=>{if(typeof e!="string"||!xn.test(e)){n.problem(t,"invalid-id",`An id is a UUID in quotes, not ${JSON.stringify(e)?.slice(0,60)}.`);return}return e.toLowerCase()},uH=(e,t,n)=>{let r=Object.keys(e).filter(i=>!If.includes(i));if(!("ref"in e)||r.length>0){n.problem(t,"invalid-reference",r.length>0?`A reference takes only ${If.join(", ")}; '${r[0]}' is not one of them. A nested element needs a type.`:"A reference mapping names its target with `ref: <id>`; a nested element needs a type.");return}let o=Md(e.ref,[...t,"ref"],n);if(e.owned!==void 0&&typeof e.owned!="boolean"){n.problem([...t,"owned"],"invalid-reference","`owned` is true or false.");return}let s=e.model===void 0?void 0:Md(e.model,[...t,"model"],n);if(!(o===void 0||e.model!==void 0&&s===void 0))return{key:o,owned:e.owned===!0,...s!==void 0&&{modelId:s}}},hH=(e,t,n,r,o)=>{if(typeof e=="string"){let s=Md(e,t,n);return s===void 0?void 0:{key:s,owned:!1}}if(!Pe(e)){n.problem(t,"invalid-reference","A relation lists ids, `{ref: <id>, owned: true}` mappings or nested elements (a mapping with a type).");return}if("type"in e){let s=eS(e,t,n,r,!1,o+1);return s===void 0?void 0:{key:s.key,owned:!0}}return uH(e,t,n)},Mf=(e,t,n,r)=>$f(e)?(n.problem(t,"reserved-name",`'${e}' cannot name ${r}: every JavaScript object already has a member of that name.`),!0):!1,JI=(e,t,n,r,o)=>{if(!Array.isArray(e)){n.problem(t,"invalid-relations","A relation's references are a list; write [] for none.");return}return e.flatMap((s,i)=>hH(s,[...t,i],n,r,o)??[])},gH=(e,t,n,r,o)=>{if(Array.isArray(e))return{"@@":JI(e,t,n,r,o)??[]};if(!Pe(e)){n.problem(t,"invalid-relations",`The relation '${t.at(-1)}' is a list of references, or a mapping of groups to lists; write [] for none.`);return}return Object.fromEntries(Object.entries(e).filter(([s])=>!Mf(s,[...t,s],n,"a group")).map(([s,i])=>[s,JI(i,[...t,s],n,r,o)??[]]))},ZI=(e,t,n,r,o)=>{if(!Pe(e))return n.problem(t,"invalid-relations","`relations:` maps each relation name to its references."),{};let s={};for(let[i,a]of Object.entries(e)){if(Mf(i,[...t,i],n,"a relation"))continue;let d=gH(a,[...t,i],n,r,o);d!==void 0&&(s[i]=d)}return s},yH=(e,t,n)=>{let r=Object.keys(e).filter(o=>!vf.includes(o));for(let o of r)n.problem([...t,o],"unknown-key",`An element block takes ${vf.join(", ")}; '${o}' is none of them. An attribute goes under \`attributes:\`, a relation under \`relations:\`.`)},wH=(e,t,n)=>{let r={};if(e===void 0)return r;if(!Pe(e))return n.problem([...t,"attributes"],"invalid-attributes","`attributes:` maps each name to a list of values."),r;for(let[o,s]of Object.entries(e))Mf(o,[...t,"attributes",o],n,"an attribute")||(Array.isArray(s)?r[o]=s:n.problem([...t,"attributes",o],"invalid-attributes",`The attribute '${o}' holds a list of values: write - "value" on the line below it, or [] for none.`));return r},bH=(e,t)=>t?`\`readOnly:\` holds ${VI.join(", ")}; '${e}' is none of them.`:`\`readOnly:\` holds ${Je.join(", ")} here; '${e}' is none of them.`,EH=(e,t,n,r,o,s)=>{let i={},a={};if(e===void 0)return{readOnly:i,relations:a};if(!Pe(e))return n.problem([...t,"readOnly"],"invalid-read-only","`readOnly:` is a mapping."),{readOnly:i,relations:a};for(let[d,l]of Object.entries(e))d==="relations"&&s?Object.assign(a,ZI(l,[...t,"readOnly","relations"],n,r,o)):Je.includes(d)?i[d]=l:n.problem([...t,"readOnly",d],"unknown-key",bH(d,s));return{readOnly:i,relations:a}},eS=(e,t,n,r,o,s)=>{if(r.full())return;if(s>et){n.problem(t,"too-deep",`Elements nest more than ${et} deep here; write the rest in files of their own.`);return}if(!Pe(e)){n.problem(t,"invalid-element","An element is a mapping with at least a `type`.");return}yH(e,t,n);let i={file:n.file,path:[...t]},a=e.id===void 0?void 0:Md(e.id,[...t,"id"],n);if(typeof e.type!="string"||e.type===""){n.problem([...t,"type"],"missing-type","Every element names its `type`.");return}let d=wH(e.attributes,t,n),l=e.relations===void 0?{}:ZI(e.relations,[...t,"relations"],n,r,s),c=EH(e.readOnly,t,n,r,s,o);Object.assign(l,c.relations);let{readOnly:m}=c,p={key:a??`${n.file}#${Tt(t)}`,...a!==void 0&&{id:a},type:e.type,attributes:d,relations:l,readOnly:m,location:i};return r.add(p,n),p},CH=(e,t)=>e?.range?t.linePos(e.range[0]).line:void 0,XI=(e,t)=>({file:e,code:"invalid-yaml",message:t instanceof RangeError?"The file nests too deeply to be read.":`The file cannot be read as YAML: ${t.message.split(`
242
+ `)[0]}`}),RH=(e,t)=>{let n=new Nd.LineCounter,r;try{r=(0,Nd.parseDocument)(e.text,{...Sf,lineCounter:n})}catch(i){t.problems.push(XI(e.path,i));return}let o={file:e.path,problem:(i,a,d)=>{let l=i.length===0?r.contents:r.getIn(i,!0),c=CH(l,n);t.problems.push({file:e.path,...i.length>0&&{at:Tt(i)},...c!==void 0&&{line:c},code:a,message:H(d)})}};if(r.errors.length>0){for(let i of r.errors.slice(0,3))t.problems.push({file:e.path,line:n.linePos(i.pos[0]).line,code:"invalid-yaml",message:i.message.split(`
243
+ `)[0]});return}let s;try{s=r.toJS({maxAliasCount:fH})}catch(i){t.problems.push(XI(e.path,i));return}return eS(s,[],o,t,e.path===Gt,0)},tS=e=>{let t=new Af,n;for(let r of[...e].sort((o,s)=>fe(o.path,s.path))){if(t.full())break;let o=RH(r,t);o!==void 0&&(t.fileLevel.add(o.key),r.path===Gt&&(n=o.key))}if(n===void 0&&!t.problems.some(r=>r.file===Gt)&&t.problems.push({file:Gt,code:"missing-root",message:`The workspace has no ${Gt}, which holds the model's root element.`}),t.problems.length>0)throw new tt(t.problems.slice(0,Of));return{format:"yaml",rootKey:n,elements:t.elements,fileLevel:t.fileLevel}},kH=e=>[...Object.keys(Pe(e.attributes)?e.attributes:{}),...Object.entries(Pe(e.relations)?e.relations:{}).flatMap(([t,n])=>[t,...Object.keys(Pe(n)?n:{})])].find(t=>$f(t)),QI=e=>typeof e=="string"&&xn.test(e),vH=e=>Pe(e)&&QI(e.id)&&(e.owned===void 0||typeof e.owned=="boolean")&&(e.modelId===void 0||QI(e.modelId)),IH=e=>Pe(e)&&Object.values(e).every(t=>Array.isArray(t)&&t.every(vH)),SH=e=>e.relations!==void 0&&!(Pe(e.relations)&&Object.values(e.relations).every(IH)),$H=e=>e.attributes!==void 0&&!(Pe(e.attributes)&&Object.values(e.attributes).every(t=>Array.isArray(t))),TH=(e,t,n,r)=>{let o={},s=n.relations??{};for(let[l,c]of Object.entries(s))o[l]=Object.fromEntries(Object.entries(c).map(([m,p])=>[m,p.map(h=>({key:h.id.toLowerCase(),owned:h.owned===!0,...typeof h.modelId=="string"&&{modelId:h.modelId}}))]));let i=n.attributes??{},a=Object.fromEntries(Je.filter(l=>l in n).map(l=>[l,n[l]])),d=t.toLowerCase();return{key:d,id:d,type:r,attributes:i,relations:o,readOnly:a,location:{file:e,path:["elements",t]}}},nS=e=>{let t=[],n=(i,a,d)=>t.push({file:e.path,...i!==void 0&&{at:i},code:a,message:d}),r;try{r=JSON.parse(e.text)}catch(i){throw new tt([{file:e.path,code:"invalid-json",message:i.message}])}if(!Pe(r)||typeof r.rootElementId!="string"||!Pe(r.elements))throw new tt([{file:e.path,code:"invalid-json",message:`${$t} holds {"rootElementId": \u2026, "elements": {\u2026}}.`}]);let o=new Map;for(let[i,a]of Object.entries(r.elements)){let d=Tt(["elements",i]);if(!xn.test(i)||!Pe(a)||a.id!==i||typeof a.type!="string"){n(d,"invalid-element","Each entry is an element keyed by its own id, with a type.");continue}let l=kH(a);if(l!==void 0){n(d,"reserved-name",`'${l}' cannot name an attribute, relation or group: every JavaScript object already has a member of that name.`);continue}if(SH(a)){n(d,"invalid-reference",'Relations map each name to its groups, and each group lists references: {"id": <uuid>, "owned": <boolean>}, with "modelId" for another model.');continue}if($H(a)){n(d,"invalid-attributes","Attributes map each name to a list of values.");continue}o.set(i.toLowerCase(),TH(e.path,i,a,a.type))}let s=r.rootElementId.toLowerCase();if(o.has(s)||n("/rootElementId","missing-root","rootElementId names no element of the map."),t.length>0)throw new tt(t.slice(0,Of));return{format:"json",rootKey:s,elements:o,fileLevel:new Set(o.keys())}};var aS=`${xd}/${Rf}`,HH=16*1024*1024,rS=Math.max(kf,Ad),BH=e=>e.startsWith(".")||e==="node_modules",UH=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/,GH=/^[0-9a-f]{64}$/,dS=(e,t)=>e<t?-1:e>t?1:0,lS=e=>xH("sha256").update(e,"utf8").digest("hex"),Us=e=>Object.fromEntries(e.map(t=>[t.path,lS(t.text)])),Gs=e=>hr(e,xd,Rf),Pd=(e,t,n)=>new f(`${H(hr(e,t))} ${n}, so the workspace does not touch it.`,{type:"workspace-path-refused",hint:"Replace it with a plain file or directory, or use another workspace directory.",details:{path:t}}),Dd=e=>{try{return MH(e)}catch(t){if(t.code==="ENOENT")return;throw t}},cS=e=>e===""||e.includes("\\")||e.includes("\0")||WH.isAbsolute(e)||e.split("/").some(n=>n===""||n==="."||n==="..")?void 0:e,An=(e,t)=>{let n=cS(t);if(n===void 0)throw Pd(e,t,"is not a plain path inside the workspace");let r=n.split("/"),o=Nf(e),s=o;for(let[i,a]of r.entries()){s=hr(s,a);let d=Dd(s);if(d===void 0)return hr(o,...r);if(d.isSymbolicLink())throw Pd(e,r.slice(0,i+1).join("/"),"is a symbolic link");if(i<r.length-1&&!d.isDirectory())throw Pd(e,r.slice(0,i+1).join("/"),"is not a directory")}return s},Bs=(e,t,n)=>{let r=An(e,t),o=Dd(r);if(o!==void 0){if(!o.isFile())throw Pd(e,t,"is not a plain file");if(o.size>n)throw new f(`${H(hr(e,t))} holds ${o.size} bytes, more than a workspace file may (${n}); it was not read.`,{type:"workspace-file-too-large",details:{path:t,bytes:o.size,limit:n}});return DH(r,"utf8")}},xt=(e,t)=>new f(`${H(Gs(e))} ${t}.`,{hint:"Re-pull the workspace into an empty directory with 'modeldesk model pull'."}),VH=(e,t)=>{if(t.schemaVersion===1){let n=typeof t.modelId=="string"?H(t.modelId):"<model>";throw new f(`${H(Gs(e))} is a workspace of format 1, which records no branch, and this CLI reads format ${Ut} only.`,{hint:`Copy aside any edits you have not pushed, then pull the model again into an empty directory: 'modeldesk model pull ${n}@<branch> <dir>'.`})}if(t.schemaVersion!==Ut)throw xt(e,`has workspace format ${H(String(t.schemaVersion))}, which this CLI does not read (it reads ${Ut}); update the CLI`)},oS=(e,t,n)=>{let r=t[n];if(typeof r!="object"||r===null||typeof r.id!="string"||!xn.test(r.id)||typeof r.name!="string")throw xt(e,`lacks "${n}" with its id and name`);return{id:r.id.toLowerCase(),name:r.name}},YH=(e,t)=>{for(let[n,r]of Object.entries(t))if(cS(n)===void 0||n.split("/")[0]===xd||typeof r!="string"||!GH.test(r))throw xt(e,`lists ${H(n)} among its files, which is not a workspace path with its SHA-256`)},mS=e=>{let t=Bs(e,aS,HH);if(t===void 0)return;let n;try{n=JSON.parse(t)}catch(a){throw xt(e,`is not valid JSON (${H(a.message)})`)}if(n===null||typeof n!="object"||Array.isArray(n))throw xt(e,"is not a JSON object");let r=n;if(VH(e,r),typeof r.host!="string"||!UH.test(r.host))throw xt(e,"names a host that is not a bare host name (such as modeldesk.io)");if(typeof r.baseCommitId!="string"||!xn.test(r.baseCommitId))throw xt(e,'lacks "baseCommitId", the UUID of the commit its files reflect');let o=r.baseRootRevision;if(o!==void 0&&(typeof o!="string"||!xn.test(o)))throw xt(e,'has a "baseRootRevision" that is not a UUID');let s=r.format??"yaml";if(s!=="yaml"&&s!=="json")throw xt(e,'has a format that is neither "yaml" nor "json"');let i=r.files??{};if(i===null||typeof i!="object"||Array.isArray(i))throw xt(e,'has a "files" member that is not an object');return YH(e,i),{schemaVersion:Ut,host:r.host,model:oS(e,r,"model"),branch:oS(e,r,"branch"),baseCommitId:r.baseCommitId.toLowerCase(),...o!==void 0&&{baseRootRevision:o.toLowerCase()},format:s,files:Object.fromEntries(Object.entries(i))}},Pf=(e,t)=>{NH(qH(e),{recursive:!0});let n=`${e}.${AH()}.tmp`;try{FH(n,t),_H(n,e)}catch(r){throw iS(n,{force:!0}),r}},On=(e,t)=>Pf(An(e,aS),`${JSON.stringify(t,null,2)}
244
+ `),KH=e=>{let t=Buffer.alloc(64),n=PH(e,"r");try{let r=LH(n,t,0,t.length,0);return GI.test(t.subarray(0,r).toString("utf8").replace(/^\uFEFF/,""))}finally{OH(n)}},zH=e=>{try{return sS(e,{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}},pS=(e,t,n,r,o)=>{let s=hr(e,t),i=zH(s);if(i!==void 0)for(let a of i){let d=t===""?a.name:`${t}/${a.name}`;if(a.isDirectory()){if(!BH(a.name)){let l=n||t===""&&r.has(a.name);pS(e,d,l,r,o)}}else a.isFile()&&a.name.endsWith(".yaml")&&!o.has(d)&&(n||KH(hr(s,a.name)))&&o.add(d)}},JH=(e,t)=>{let n=new Set,r=Object.keys(t.files);for(let s of[...r,...t.format==="json"?[$t]:[]])Dd(An(e,s))!==void 0&&n.add(s);if(t.format==="json")return[...n].filter(s=>s===$t);let o=new Set(r.filter(s=>s.includes("/")).map(s=>s.split("/")[0]));return o.forEach(s=>An(e,s)),pS(Nf(e),"",!1,o,n),[...n].sort(dS)},Df=(e,t)=>JH(e,t).flatMap(n=>{let r=Bs(e,n,n===$t?kf:Ad);return r===void 0?[]:[{path:n,text:r}]}),Lf=(e,t)=>{if(t==="json"){let n=e.find(r=>r.path===$t);if(n===void 0)throw new tt([{file:$t,code:"missing-root",message:"The workspace has no model.json."}]);return nS(n)}return tS(e)},Mn=(e,t)=>Lf(Df(e,t),t.format),Ld=(e,t,n)=>{let r={written:[],unchanged:[],removed:[],kept:[],collisions:[]},o=new Set(t.map(s=>s.path));for(let s of t){let i=Bs(e,s.path,rS);i===s.text?r.unchanged.push(s.path):i!==void 0&&!Object.hasOwn(n,s.path)?r.collisions.push(s.path):r.written.push(s.path)}for(let s of Object.keys(n).sort(dS)){if(o.has(s))continue;let i=Bs(e,s,rS);i!==void 0&&(lS(i)===n[s]?r.removed:r.kept).push(s)}return r},_d=(e,t,n)=>{if(n.collisions.length>0)throw new Error("A write plan with collisions is not applied.");let r=new Map(t.map(s=>[s.path,s.text]));for(let s of n.written)Pf(An(e,s),r.get(s));let o=new Set;for(let s of n.removed){iS(An(e,s),{force:!0});let i=s.split("/");for(let a=i.length-1;a>0;a--)o.add(i.slice(0,a).join("/"))}for(let s of[...o].sort((i,a)=>a.length-i.length)){let i=An(e,s);Dd(i)?.isDirectory()&&sS(i).length===0&&jH(i)}},fS=(e,t)=>{let n=[],r=new Map;for(let o of t)r.set(o.location.file,[...r.get(o.location.file)??[],o]);for(let[o,s]of r)try{let i=Bs(e,o,Ad);if(i===void 0){n.push(...s.map(l=>({...l,reason:"its file is gone"})));continue}let a=zI(i,s.map(({location:l,id:c})=>({path:l.path,id:c}))),d=new Set(a.missed.map(l=>JSON.stringify(l)));n.push(...s.filter(l=>d.has(JSON.stringify(l.location.path))).map(l=>({...l,reason:"its block is no longer where it was"}))),Pf(An(e,o),a.text)}catch(i){n.push(...s.map(a=>({...a,reason:H(i.message)})))}return n},uS=(e,t)=>Nf(e,t??".");var jd=e=>JSON.stringify(e,(t,n)=>n!==null&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.keys(n).sort(fe).map(r=>[r,n[r]])):n),yo=(e,t)=>jd(e)===jd(t),Vs=e=>Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t.length>0)),XH=e=>({key:e.id,owned:e.owned===!0,...e.modelId!==void 0&&{modelId:e.modelId}}),gr=(e,t)=>Object.fromEntries(Object.entries(e.relations?.[t]??{}).map(([n,r])=>[n,r.map(XH)])),yr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t.length>0)),_f=e=>Object.keys(e).some(t=>t!=="@@"),xe=e=>Object.keys(e).sort(fe).flatMap(t=>e[t]),Ys=e=>{let t=new Map;for(let n of Object.keys(e).sort(fe)){let r=e[n].relations??{};for(let o of Object.keys(r).sort(fe))for(let s of xe(r[o])){if(s.owned!==!0)continue;let i=t.get(s.id)??[];i.some(a=>a.id===n&&a.relation===o)||i.push({id:n,relation:o}),t.set(s.id,i)}}return t},Fd=e=>{for(let t of e??[]){if(typeof t=="string"&&t.trim()!=="")return t;if(t!==null&&typeof t=="object"&&typeof t.value=="string")return t.value}};var At=class extends f{constructor(n){let r=n.length>1?` (and ${n.length-1} more)`:"";super(H(`${n[0].message}${r}`),{exitCode:b.Validation,type:"workspace-refused",details:{errors:n}});this.problems=n;this.name="WorkspaceRefusedError"}problems},qd=e=>`${e.id}\0${e.relation}`,QH=e=>{let t=[],n=new Array(e.length).fill(-1);e.forEach((o,s)=>{let i=0,a=t.length;for(;i<a;){let d=i+a>>1;e[t[d]]<o?i=d+1:a=d}n[s]=i>0?t[i-1]:-1,t[i]=s});let r=new Set;for(let o=t.at(-1)??-1;o!==-1;o=n[o])r.add(o);return r},Ks=e=>"id"in e?e.id:e.new,ZH=e=>{let t=new Map;for(let[n,r]of e)for(let[o,s]of Object.entries(r.relations))for(let i of xe(s).filter(a=>a.owned)){let a=t.get(i.key)??[];a.some(d=>d.id===n&&d.relation===o)||a.push({id:n,relation:o}),t.set(i.key,a)}return t},eB=e=>Object.values(e.relations??{}).flatMap(t=>xe(t)).filter(t=>t.owned===!0).map(t=>t.id),tB=(e,t)=>{let n=new Map,r=e[t]?.relations??{},o=Object.keys(r).filter(Vt).flatMap(s=>xe(r[s]).filter(i=>i.owned===!0).map(i=>[i.id,s]));for(let s=o.shift();s!==void 0;s=o.shift()){let[i,a]=s;n.has(i)||!Object.hasOwn(e,i)||(n.set(i,a),eB(e[i]).forEach(d=>o.push([d,a])))}return n},nB=(e,t)=>{let n=e.elements,r=t.elements,o=e.rootId,s=[],i=c=>Object.hasOwn(n,c),a=c=>r.has(c)&&!i(c),d=Ys(n),l=ZH(r);return{C:n,W:r,rootId:o,problems:s,currentOwners:d,pinnedVia:tB(n,o),vanished:new Set(Object.keys(n).filter(c=>c!==o&&!r.has(c)).sort(fe)),has:i,isNew:a,nodeRef:c=>i(c)||r.get(c)?.id!==void 0?{id:c}:{new:c},opRef:c=>a(c.key)&&r.get(c.key)?.id===void 0?{new:c.key,owned:c.owned}:{id:c.key,owned:c.owned,...c.modelId!==void 0&&{modelId:c.modelId}},ownersNow:c=>d.get(c)??[],ownersThen:c=>l.get(c)??[],viaPin:c=>c.id===o&&Vt(c.relation),refuse:(c,m,p)=>{s.push({code:c,message:H(m),...p.elementId!==void 0&&{elementId:p.elementId},...p.element?.id!==void 0&&p.elementId===void 0&&{elementId:p.element.id},...p.property!==void 0&&{property:p.property},...p.element!==void 0&&{file:p.element.location.file},...p.element!==void 0&&p.element.location.path.length>0&&{at:Tt(p.element.location.path)}})}}},yS=(e,t)=>({attributes:Vs(e),relations:Object.fromEntries(Object.entries(t).map(([n,r])=>[n,yr(r)]).filter(([,n])=>Object.keys(n).length>0))}),rB=(e,t)=>yS(e[t].attributes??{},Object.fromEntries(Object.keys(e[t].relations??{}).map(n=>[n,gr(e[t],n)]))),oB=(e,t)=>{let{C:n,rootId:r,refuse:o}=e,s=n[r]?.relations??{},i=new Set([...Object.keys(s),...Object.keys(t.relations)]);for(let a of[...i].filter(Vt).sort(fe)){let d=yr(gr(n[r],a)),l=yr(t.relations[a]??{});yo(d,l)||o("read-only-field",`The root's '${a}' is read-only in a workspace: add or remove a dependency with 'modeldesk dependency add' or 'dependency rm', and move a pin with 'modeldesk pin set'.`,{element:t,elementId:r,property:a})}},sB=(e,t)=>{let{W:n,has:r,pinnedVia:o,refuse:s}=e;for(let[i,a]of Object.entries(t.relations))for(let d of xe(a))d.owned&&!n.has(d.key)&&r(d.key)&&!o.has(d.key)&&s("missing-block",`'${i}' owns ${d.key} (owned: true), but its block is gone from the workspace. Write its block here in place of the reference, or drop the reference to delete it.`,{element:t,property:i})},hS=e=>e.length===0?"no owner":e.map(t=>`${t.id} via ${t.relation}`).join(", "),iB=(e,t,n)=>n.length>0&&t.length===0?`Element ${e} is written on its own, and the element that owns it (${n[0].id}) is deleted. To delete it as well, remove its block. To keep it, reference it from its new owner as \`- ref: <id>\` with \`owned: true\`: the push moves it there before deleting the old owner.`:`Element ${e} is written on its own, but nothing in the workspace owns it any more: nest it where it belongs, or reference it from its owner with \`owned: true\`.`,aB=(e,t,n,r)=>{let{ownersNow:o,ownersThen:s,vanished:i,viaPin:a,refuse:d}=e,l=o(t),c=s(t),m=l.filter(y=>!c.some(w=>qd(w)===qd(y))),p=c.filter(y=>!l.some(w=>qd(w)===qd(y))),h=m.filter(y=>!i.has(y.id)),u=m.filter(y=>i.has(y.id));if(p.some(a))d("read-only-field",`Element ${t} cannot be placed under the root's read-only relations.`,{element:n});else if(c.length===0&&l.length>0)d("unowned",iB(t,h,u),{element:n});else{if(p.length===0&&h.length===0)return;p.length===1&&h.length===1?r.set(t,{from:h[0],to:p[0]}):p.length===1&&h.length===0&&u.length>0?r.set(t,{from:u[0],to:p[0]}):d("ownership-change",`Element ${t} would go from ${hS(l)} to ${hS(c)}. A push moves an element from one owner to another; adding an owner, or dropping one that is not deleted, is done in the app. Keep its other owners as they are and change one at a time.`,{element:n})}},dB=(e,t,n,r)=>{let{C:o,rootId:s,pinnedVia:i,refuse:a}=e;n.type!==o[t].type&&a("type-changed",`Element ${t} is a ${o[t].type} and cannot become a ${n.type}: an element's type is fixed. Delete it and write a new element without an id.`,{element:n,property:"type"});for(let l of Je)yo(o[t][l]??null,n.readOnly[l]??null)||a("read-only-field",`'${l}' of ${t} is read-only: the server serves it, no staged write accepts it.`,{element:n,property:l});let d=i.get(t);d!==void 0&&!yo(rB(o,t),yS(n.attributes,n.relations))&&a("read-only-field",`Element ${t} belongs to the root's read-only '${d}' and cannot be changed.`,{element:n,property:d}),!(t===s||d!==void 0)&&aB(e,t,n,r)},lB=(e,t,n)=>{let{rootId:r,ownersThen:o,viaPin:s,refuse:i}=e,a=o(t),d=n.id??`the new ${n.type} at ${H(n.location.file)}${H(Tt(n.location.path))}`;Object.keys(n.readOnly).length>0&&i("read-only-field",`${d} carries read-only fields, which no staged write accepts.`,{element:n,property:Object.keys(n.readOnly)[0]}),a.length===0&&t!==r?i("unowned",`${d} is new and nothing owns it: nest it under its owner's relation, or give it an id and reference it from its owner as \`- ref: <id>\` with \`owned: true\`.`,{element:n}):a.length>1?i("multi-owned-create",`${d} is new and has ${a.length} owners; a new element starts with one.`,{element:n}):a.some(s)&&i("read-only-field",`${d} cannot be created under the root's read-only relations.`,{element:n})},cB=(e,t)=>{for(let[n,r]of e.W)sB(e,r),e.has(n)?dB(e,n,r,t):lB(e,n,r)},mB=e=>{for(let t of e.vanished){let n=e.pinnedVia.get(t);n!==void 0&&e.refuse("read-only-field",`Element ${t} belongs to the root's read-only '${n}' and cannot be removed.`,{elementId:t,property:n})}},wS=e=>{let t=[],n=new Set;return{order:t,seen:n,visit:o=>{let s=[o];for(let i=s.pop();i!==void 0;i=s.pop()){if(n.has(i))continue;n.add(i),t.push(i);let a=e(i),d=Object.keys(a).sort(fe).flatMap(l=>xe(a[l]).filter(c=>c.owned).map(c=>c.key));for(let l=d.length-1;l>=0;l--)s.push(d[l])}}}},pB=(e,t)=>{let n=wS(r=>e.W.get(r)?.relations??{});return n.visit(e.rootId),[...t.fileLevel].sort(fe).forEach(n.visit),n.order.filter(r=>e.W.has(r))},jf=(e,t)=>e.ownersThen(t)[0],bS=(e,t,n,r)=>{let o=jf(e,r.key);return r.owned&&e.isNew(r.key)&&!t.has(r.key)&&o?.id===n.key&&o.relation===n.relation},fB=(e,t,n)=>{let r=[n];for(let o=r.pop();o!==void 0;o=r.pop()){t.add(o);for(let[s,i]of Object.entries(e.W.get(o)?.relations??{}))for(let a of xe(i))bS(e,t,{key:o,relation:s},a)&&r.push(a.key)}},ES=(e,t,n,r=0)=>{t.add(n);let o=e.W.get(n);if(r>et)return e.refuse("too-deep",`New elements nest more than ${et} deep under ${H(o.location.file)}; push them in parts.`,{element:o}),fB(e,t,n),{element:e.nodeRef(n),type:o.type};let s={},i={};for(let d of Object.keys(o.relations).sort(fe)){let l=o.relations[d],c=yr(Object.fromEntries(Object.entries(l).map(([p,h])=>[p,h.filter(u=>!u.owned).map(u=>e.opRef(u))])));Object.keys(c).length>0&&(s[d]=c);let m=xe(l).filter(p=>bS(e,t,{key:n,relation:d},p));m.length>0&&(i[d]=m.map(p=>ES(e,t,p.key,r+1)))}let a=Vs(o.attributes);return{element:e.nodeRef(n),type:o.type,...Object.keys(a).length>0&&{attributes:a},...Object.keys(s).length>0&&{relations:s},...Object.keys(i).length>0&&{children:i}}},uB=(e,t)=>{let n=new Set,o=t.filter(s=>{let i=jf(e,s);return e.isNew(s)&&i!==void 0&&e.has(i.id)&&e.ownersThen(s).length===1}).map(s=>({key:s,home:jf(e,s),node:ES(e,n,s)}));for(let s of t)e.isNew(s)&&!n.has(s)&&e.ownersThen(s).length===1&&e.refuse("unowned",`The new ${e.W.get(s)?.type} at ${H(e.W.get(s)?.location.file??"")} hangs from no existing element.`,{element:e.W.get(s)});return o},CS=(e,t=[])=>(t.push(Ks(e.element)),Object.values(e.children??{}).flat().forEach(n=>CS(n,t)),t),RS=(e,t=new Set)=>{for(let n of Object.values(e.relations??{}))for(let r of xe(n))t.add(Ks(r));return Object.values(e.children??{}).flat().forEach(n=>RS(n,t)),t},hB=e=>{let t=[],n=new Array(e.length).fill(-1),r=new Array(e.length).fill(0),o=new Array(e.length).fill(!1),s=[],i=0,a=c=>{n[c]=i,r[c]=i,i++,s.push(c),o[c]=!0},d=c=>{let m=[];for(let p=s.pop();p!==void 0&&(o[p]=!1,m.push(p),p!==c);p=s.pop());t.push(m.toSorted((p,h)=>p-h))},l=c=>{let m=[{node:c,edge:0}];a(c);for(let p=m.at(-1);p!==void 0;p=m.at(-1)){let{node:h}=p;if(p.edge<e[h].length){let y=e[h][p.edge++];n[y]===-1?(a(y),m.push({node:y,edge:0})):o[y]&&(r[h]=Math.min(r[h],n[y]));continue}m.pop();let u=m.at(-1);u!==void 0&&(r[u.node]=Math.min(r[u.node],r[h])),r[h]===n[h]&&d(h)}};return e.forEach((c,m)=>{n[m]===-1&&l(m)}),t},gB=e=>{let t=new Map;e.forEach((r,o)=>CS(r.node).forEach(s=>t.set(s,o)));let n=e.map((r,o)=>[...RS(r.node)].map(s=>t.get(s)).filter(s=>s!==void 0&&s!==o));return hB(n)},yB=e=>{let t=new Map;return(n,r)=>{let o=`${n}\0${r}`,s=t.get(o);return s===void 0&&(s=e.has(n)?xe(gr(e.C[n],r)).map(i=>i.key):[],t.set(o,s)),s}},kS=(e,t)=>{let n=Ks(t.element);for(let[r,o]of Object.entries(t.relations??{}))e(n,r).push(...xe(o).map(Ks));for(let[r,o]of Object.entries(t.children??{}))for(let s of o)e(n,r).push(Ks(s.element)),kS(e,s)},wB=(e,t,n,r,o)=>{for(let s of n){let i=o.ops.length;for(let a of s){let{key:d,home:l,node:c}=t[a];o.ops.push({op:"create",parent:e.nodeRef(l.id),relation:l.relation,element:c}),r(l.id,l.relation).push(d),kS(r,c)}s.length>1&&o.together.push(s.map((a,d)=>i+d))}},vS=({ctx:e},{parent:t,relation:n},r,o,s)=>({op:"move",element:e.nodeRef(r),from:{parent:e.nodeRef(o.id),relation:o.relation},parent:e.nodeRef(t),relation:n,...s!==void 0&&{position:s}}),IS=(e,t,n,r)=>{let{from:o}=e.moves.get(n);e.staged.ops.push(vS(e,t,n,o,r));let s=e.listOf(o.id,o.relation),i=s.indexOf(n);i!==-1&&s.splice(i,1)},bB=(e,t)=>Object.entries(t).some(([n,r])=>{let o=(e[n]??[]).map(l=>l.key),s=new Set(o),i=r.map(l=>l.key).filter(l=>s.has(l)),a=new Set(i),d=o.filter(l=>a.has(l));return i.some((l,c)=>l!==d[c])}),EB=(e,t,n)=>{let{ctx:r,staged:o,moved:s}=e,i=r.has(t.parent)?gr(r.C[t.parent],t.relation):{};bB(i,n)&&o.warnings.push(`The order of '${H(t.relation)}' of ${t.parent} changed in the files, and a grouped relation is not reordered by a push: its order stays as it is.`);for(let a of t.order.filter(d=>t.arriving.has(d)))IS(e,t,a,void 0),t.list.push(a),s.add(a)},SS=(e,t)=>t===void 0?0:e.indexOf(t)+1,CB=(e,t,n,r)=>{let o=SS(t.list,r);IS(e,t,n,o>=t.list.length?void 0:o),t.list.splice(o,0,n),t.inList.add(n),e.moved.add(n)},RB=(e,t,n,r)=>{let o=t.list.indexOf(n);t.list.splice(o,1);let s=SS(t.list,r);if(t.list.splice(s,0,n),s!==o){let i={id:t.parent,relation:t.relation};e.staged.ops.push(vS(e,t,n,i,o>=s?s:s+1))}},kB=(e,t,n,r)=>{if(t.inPlace.has(n)||!t.owned.has(n))return;let o=t.arriving.has(n);if(!o&&!t.inList.has(n))return;let s=t.order.slice(0,r).findLast(i=>t.inList.has(i)&&i!==n);o?CB(e,t,n,s):RB(e,t,n,s)},vB=(e,t)=>{let{order:n,list:r,arriving:o}=t,s=new Map;n.forEach((c,m)=>{s.has(c)||s.set(c,m)});let i=new Set(n),a=r.filter(c=>i.has(c)&&!o.has(c)),d=QH(a.map(c=>s.get(c))),l={...t,inPlace:new Set([...d].map(c=>a[c])),inList:new Set(r)};n.forEach((c,m)=>kB(e,l,c,m))},IB=(e,t,n,r)=>{let{ctx:o,moves:s,listOf:i}=e,a=xe(r),d=a.map(m=>m.key),l={parent:t,relation:n,order:d,owned:new Set(a.filter(m=>m.owned).map(m=>m.key)),arriving:new Set(d.filter(m=>{let p=s.get(m);return p?.to.id===t&&p.to.relation===n})),list:i(t,n)};_f(r)||o.has(t)&&_f(o.C[t].relations?.[n]??{"@@":[]})?EB(e,l,r):vB(e,l)},SB=(e,t)=>{let{ctx:n,moves:r,moved:o}=e;for(let s of t){let i=n.W.get(s);for(let a of Object.keys(i.relations).sort(fe))s===n.rootId&&Vt(a)||IB(e,s,a,i.relations[a])}for(let s of r.keys())if(!o.has(s))throw new Error(`The move of ${s} found no place in the workspace walk.`)},gS=e=>yr(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.filter(r=>!r.owned).map(r=>({key:r.key,modelId:r.modelId??null}))]))),$B=(e,t)=>{let n={},r=[];for(let o of[...new Set([...Object.keys(e),...Object.keys(t)])].sort(fe))t[o]===void 0?r.push(o):(e[o]===void 0||!yo(e[o],t[o]))&&(n[o]=t[o]);return{set:n,unset:r}},TB=(e,t,n)=>{let r=new Set(xe(n).map(s=>s.key)),o=Object.fromEntries(Object.entries(n).map(([s,i])=>[s,i.map(a=>e.opRef(a))]));for(let[s,i]of Object.entries(t))for(let a of i)a.owned&&e.vanished.has(a.key)&&!r.has(a.key)&&(o[s]=[...o[s]??[],e.opRef(a)]);return yr(o)},xB=(e,t,n)=>{let r={},o=[],s=new Set([...Object.keys(e.C[t].relations??{}),...Object.keys(n.relations)]);for(let i of[...s].sort(fe)){if(t===e.rootId&&Vt(i))continue;let a=gr(e.C[t],i),d=n.relations[i]??{};if(yo(gS(a),gS(d)))continue;let l=TB(e,a,d);Object.keys(l).length===0?o.push(i):r[i]=l}return{set:r,unset:o}},AB=(e,t)=>{let n=e.W.get(t),r=$B(Vs(e.C[t].attributes),Vs(n.attributes)),o=xB(e,t,n),s={...Object.keys(r.set).length>0&&{attributes:r.set},...Object.keys(o.set).length>0&&{relations:o.set}},i={...r.unset.length>0&&{attributes:r.unset},...o.unset.length>0&&{relations:o.unset}};if(!(Object.keys(s).length===0&&Object.keys(i).length===0))return{op:"update",element:t,...Object.keys(s).length>0&&{set:s},...Object.keys(i).length>0&&{unset:i}}},OB=(e,t,n)=>{for(let r of t){if(!e.has(r)||e.pinnedVia.has(r))continue;let o=AB(e,r);o!==void 0&&n.push(o)}},MB=(e,t,n)=>{let r=[],o=new Set([n]),s=[n];for(let i=s.shift();i!==void 0;i=s.shift())for(let a of t.get(i)??[])!o.has(a)&&e.vanished.has(a)&&e.ownersNow(a).every(d=>o.has(d.id))&&(o.add(a),r.push(a),s.push(a));return r},NB=(e,t)=>{let{C:n,vanished:r,rootId:o}=e,s=am(e.currentOwners),i=wS(a=>Object.fromEntries(Object.keys(n[a]?.relations??{}).map(d=>[d,gr(n[a],d)])));i.visit(o),Object.keys(n).sort(fe).forEach(i.visit);for(let a of i.order){if(!r.has(a))continue;let d=e.ownersNow(a);d.length>0&&d.every(l=>r.has(l.id))||t.push({op:"delete",element:a,removes:MB(e,s,a)})}},Kt=(e,t,{createOrder:n="workspace"}={})=>{let r=e.rootId;if(t.rootKey!==r)throw new At([{code:"root-changed",message:`The root element in model.yaml has to keep the model's root id ${r}.`,elementId:r}]);let o=nB(e,t);oB(o,o.W.get(r));let s=new Map;cB(o,s),mB(o);let i=pB(o,t),a=uB(o,i);if(o.problems.length>0)throw new At(o.problems);let d={ops:[],together:[],warnings:[]},l=yB(o),c=n==="references"?gB(a):a.map((m,p)=>[p]);return wB(o,a,c,l,d),SB({ctx:o,moves:s,listOf:l,staged:d,moved:new Set},i),OB(o,i,d.ops),NB(o,d.ops),d};import{createHash as PB,randomUUID as DB}from"node:crypto";var Ff=1e3,LB=8*1024*1024,qf=Math.floor(LB*.9),_B=(e,t,n)=>PB("sha256").update(jd({format:Ut,modelId:e,baseCommitId:t,ops:n})).digest("hex"),TS=e=>"id"in e?e.id:e.new,jB=(e,t)=>{let n=new Map,r=o=>{n.set(TS(o.element),"id"in o.element?o.element.id:t()),Object.values(o.children??{}).flat().forEach(r)};return e.forEach(o=>o.op==="create"&&r(o.element)),n},FB=(e,t)=>{let n=i=>"id"in i?i.id:t.get(i.new),r=i=>"new"in i?{id:t.get(i.new),owned:i.owned}:{id:i.id,owned:i.owned,...i.modelId!==void 0&&{modelId:i.modelId}},o=i=>Object.fromEntries(Object.entries(i).map(([a,d])=>[a,Object.fromEntries(Object.entries(d).map(([l,c])=>[l,c.map(r)]))])),s=i=>({key:TS(i.element),type:i.type,...i.attributes&&{attributes:i.attributes},...i.relations&&{relations:o(i.relations)},...i.children&&{children:Object.fromEntries(Object.entries(i.children).map(([a,d])=>[a,d.map(s)]))}});return e.map(i=>{switch(i.op){case"create":return[{kind:"create",parent:{id:n(i.parent)},relation:i.relation,element:s(i.element)}];case"move":return[{kind:"move",element:n(i.element),parent:{id:n(i.parent)},relation:i.relation,from:{id:n(i.from.parent),relation:i.from.relation},...i.position!==void 0&&{position:i.position}}];case"update":return[...i.set?[{kind:"set",element:i.element,...i.set.attributes&&{attributes:i.set.attributes},...i.set.relations&&{relations:o(i.set.relations)}}]:[],...i.unset?[{kind:"unset",element:i.element,...i.unset.attributes&&{attributes:i.unset.attributes},...i.unset.relations&&{relations:i.unset.relations}}]:[]];case"delete":return[{kind:"delete",element:i.element,recursive:!0}]}})},qB=(e,t,n)=>{let r={...e.elements},o=Object.fromEntries([...Ys(e.elements)].map(([d,l])=>[d,{owners:l}])),s=d=>"id"in d?d.id:n.get(d.new),i=(d,l)=>{let c=s(d.element);r[c]={id:c,type:d.type},o[c]={owners:[l]};for(let[m,p]of Object.entries(d.children??{}))p.forEach(h=>i(h,{id:c,relation:m}))};for(let d of t)d.op==="create"&&i(d.element,{id:s(d.parent),relation:d.relation});return{elements:r,elementIndexEntries:o}},xS=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g,AS=e=>{let t=[],n=r=>{r.id!==void 0&&t.push(r.id),Object.values(r.ownedElements??{}).flat().forEach(n)};return e.forEach(r=>r.type==="ELEMENT_CREATE"&&n(r.creation)),t},WB=e=>e.flatMap(t=>{switch(t.type){case"ELEMENT_UPDATE":case"ELEMENT_DELETE":return[t.elementId];case"ELEMENT_MOVE":return t.move.elements.map(n=>n.id);default:return[]}}),HB=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),BB=(e,t)=>{let n=0;return t.map(r=>(n+=r,e.slice(n-r,n)))},UB=(e,t)=>{let n=new Map;t.forEach(o=>o.forEach(s=>n.set(s,o)));let r=[];for(let o=0;o<e;){let s=n.get(o)??[o];r.push([...s]),o=(s.at(-1)??o)+1}return r},$S=(e,t,n,{mintId:r=DB}={})=>{let{ops:o}=t,s=jB(o,r),i=FB(o,s),a=i.flat(),d=[],l=C=>{d.push(s.get(C.key)),Object.values(C.children??{}).flat().forEach(l)};a.forEach(C=>C.kind==="create"&&l(C.element));let c=Qo(a,qB(e,o,s),{mintId:()=>{let C=d.shift();if(C===void 0)throw new Error("The translation asked for more element ids than the plan creates.");return C}});if(c.actions.length!==a.length||[...s].some(([C,x])=>c.ids[C]!==x))throw new Error("The translation did not map the plan one edit to one action.");let m=BB(c.actions,i.map(C=>C.length)),p=UB(o.length,t.together),h=[],u;for(let C of p){let x=C.flatMap(R=>m[R]),L=x.reduce((R,S)=>R+HB(S)+1,0);if(x.length>Ff||L>qf){let R=C.length>1?`${C.length} new elements that reference each other`:"One operation";throw new f(`${R} would need ${x.length} actions of ${L} bytes in one change, more than a change carries (${Ff} actions, ${qf} bytes).`,{exitCode:b.Validation,type:"change-too-large",hint:"Push the workspace in parts: leave part of the new content out, push, then add the rest.",details:{ops:C}})}(u===void 0||u.actions.length+x.length>Ff||u.bytes+L>qf)&&(u={number:h.length+1,ops:[],actions:[],bytes:2,dependsOn:[]},h.push(u)),u.ops.push(...C),u.actions.push(...x),u.bytes+=L}let y=Ys(e.elements),w=C=>`${C.id}\0${C.relation}`,E=C=>C.flatMap(x=>{switch(x.type){case"ELEMENT_CREATE":return x.creation.owner?[w(x.creation.owner)]:[];case"ELEMENT_MOVE":return[w(x.move.targetParent),...x.move.elements.map(L=>w(L.parent))];case"ELEMENT_DELETE":return(y.get(x.elementId)??[]).map(w);default:return[]}}),I=new Map,v=new Map,$=new Map;for(let C of h){let x=new Set(JSON.stringify(C.actions).match(xS)??[]),L=C.actions.flatMap(R=>R.type==="ELEMENT_MOVE"&&R.move.position!==void 0?[w(R.move.targetParent)]:[]);C.dependsOn=[...new Set([...[...x].flatMap(R=>I.has(R)?[I.get(R)]:[]),...[...x].flatMap(R=>v.get(R)??[]),...L.flatMap(R=>$.get(R)??[])])].sort((R,S)=>R-S),AS(C.actions).forEach(R=>I.set(R,C.number));for(let R of WB(C.actions))v.set(R,[...new Set([...v.get(R)??[],C.number])]);for(let R of E(C.actions))$.set(R,[...new Set([...$.get(R)??[],C.number])])}return{hash:_B(n.modelId,n.baseCommitId,o),ops:o,chunks:h,ids:s,warnings:t.warnings}},GB=e=>{let t=new Map;return e.chunks.forEach(n=>AS(n.actions).forEach(r=>t.set(r,n.number))),e.chunks.some(n=>n.actions.some(r=>r.type==="ELEMENT_CREATE"&&(JSON.stringify(r).match(xS)??[]).some(o=>(t.get(o)??0)>n.number)))},Wd=(e,t,n,r={})=>{let o=$S(e,Kt(e,t),n,r);return o.chunks.length<2||!GB(o)?o:$S(e,Kt(e,t,{createOrder:"references"}),n,r)};var Hd=e=>({create:e.filter(t=>t.op==="create").length,move:e.filter(t=>t.op==="move").length,update:e.filter(t=>t.op==="update").length,delete:e.filter(t=>t.op==="delete").length}),zs=e=>["create","move","update","delete"].filter(t=>e[t]>0).map(t=>P(e[t],t)).join(", "),Bd=(e,t={})=>{let n={};for(let r of JSON.stringify(e).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g)??[])Object.hasOwn(t,r)&&(n[r]=t[r]);return n},MS=e=>1+Object.values(e.children??{}).flat().reduce((t,n)=>t+MS(n),0),OS=e=>typeof e=="string"?e:"id"in e?e.id:e.new,Ud=(e,t)=>{let n=new Map,r=s=>{let i=Fd(s.attributes?.name),a=i===void 0?"":` "${g(i)}"`;n.set(OS(s.element),`new ${s.type}${a}`),Object.values(s.children??{}).flat().forEach(r)};e.forEach(s=>s.op==="create"&&r(s.element));let o=s=>{let i=OS(s),a=n.get(i);return a!==void 0?a:Object.hasOwn(t,i)?`${g(t[i])} (${i.slice(0,8)})`:i};return e.map(s=>{switch(s.op){case"create":{let i=MS(s.element)-1;return`+ create ${o(s.element.element)} under ${o(s.parent)} via ${s.relation}`+(i>0?`, with ${P(i,"nested element")}`:"")}case"move":{let i=o(s.from.parent)===o(s.parent)&&s.from.relation===s.relation?"within its list":void 0,a=s.position===void 0?"at the end":`at position ${s.position}`;return i?`> move ${o(s.element)} ${i}, ${a}`:`> move ${o(s.element)} from ${o(s.from.parent)}.${s.from.relation} to ${o(s.parent)}.${s.relation}, ${a}`}case"update":{let i=[...Object.keys(s.set?.attributes??{}).map(a=>`set ${a}`),...Object.keys(s.set?.relations??{}).map(a=>`set ${a}`),...(s.unset?.attributes??[]).map(a=>`unset ${a}`),...(s.unset?.relations??[]).map(a=>`unset ${a}`)];return`~ update ${o(s.element)}: ${i.join(", ")}`}case"delete":return`- delete ${o(s.element)}`+(s.removes.length>0?`, and ${P(s.removes.length,"element")} it owns`:"")}})};var wo={name:"dir",type:"string",description:"The workspace directory (default: the current directory)."},NS=new WeakMap,Wf=e=>{let t=uS(e.cwd,e.args.dir),n=mS(t);NS.set(e,{dir:t,...n&&{state:n}}),n!==void 0&&VB(e,t,n)},Gd=e=>{Wf(e),Js(e)},VB=(e,t,n)=>{let r=e.env[G.host],o=e.globals.host??(r!==void 0&&r!==""?r:void 0);if(o!==void 0){let s=Hn(o).host;if(s!==n.host)throw new f(`The workspace in ${H(t)} was pulled from ${n.host}, and this run targets ${H(s)}.`,{exitCode:b.Usage,hint:`Run it against ${n.host}, or pull the model from the other instance into another directory.`});return}if(n.host===Hn(vo).host){e.globals.host=n.host;return}if(Ye(e.env))throw new f(`In a machine-auth run the host must be set explicitly: pass --host or set ${G.host}. The workspace's ${H(Gs(t))} is not a trusted source for where machine credentials are sent.`);e.io.err(`note: using host '${H(n.host)}' from ${H(Gs(t))}.
245
+ `),e.globals.host=n.host},Hf=e=>{let t=NS.get(e);if(t===void 0)throw new Error("The workspace is loaded before the command runs.");return t},Js=e=>{let{dir:t,state:n}=Hf(e);if(n===void 0)throw new f(`${H(t)} is not a model workspace: it has no .modeldesk/workspace.json.`,{exitCode:b.Usage,hint:"Run 'modeldesk model pull <model> <dir>' to make one, or pass the workspace's directory."});return{dir:t,state:n}},Xs=async(e,t,n)=>{let r={model:n.model.id,ref:{kind:"branch-id",id:n.branch.id,name:n.branch.name},text:`${n.model.id}@${n.branch.name}`};try{return await gt(e,r)}catch(o){if(!(o instanceof f)||o.type!==oc)throw o;let s=o.details.namesake,i=`modeldesk model pull ${n.model.id}@${g(s?.name??"<branch>")} ${H(t)} --force`;throw new f(`${o.reason} The workspace in ${H(t)} tracks it, so nothing was read or staged.`,{exitCode:o.exitCode,type:o.type,details:o.details,hint:`Copy aside any edits you have not pushed, then pull ${s?"that branch":"a branch that exists"} over the workspace: '${i}'.`})}},wr=e=>e.read.branch.head.rootElement.revision,Vd=(e,t,n)=>{if(n.head===t.baseCommitId)return{kind:"fresh"};if(t.baseRootRevision===wr(n))return{kind:"rebound",from:t.baseCommitId};try{return Kt(zt(n.read),Mn(e,t)).ops.length===0?{kind:"rebound",from:t.baseCommitId}:{kind:"stale"}}catch(r){if(r instanceof At||r instanceof tt)return{kind:"stale"};throw r}},bo=({draft:e,branch:t})=>le({ref:e!==void 0&&e.headCommitId!==t.head?{kind:"draft",draft:e}:{kind:"branch",branch:t},draft:e}),Yd=({draft:e,branch:t,model:n})=>e===void 0||e.baselineCommitId===t.head?void 0:`Your draft of ${g(n.name)} is based on ${e.baselineCommitId}, and ${g(t.name)} has moved on to ${t.head}.`,Kd=(e,t,n,r)=>`The workspace was rebound: ${pt(e,t)} moved from ${n} to ${r} and holds exactly what the files hold, so its base is now ${r}.`,zd=(e,t,n)=>{let r={...t,model:n.model,branch:{id:n.branch.id,name:n.branch.name},baseCommitId:n.head,baseRootRevision:wr(n)};return On(e,r),r},zt=e=>{let t=e.rootElementId??Object.values(e.elements).find(n=>n.type==="@Root")?.id;if(t===void 0)throw new f(`The read of ${e.name} carries no root element.`);return{rootId:t,elements:e.elements,...e.elementLabels&&{labels:e.elementLabels}}},YB=e=>{let t=new Set,n=r=>{for(let[o,s]of Object.entries(r??{}))s?.package===!0&&t.add(o)};return n(e.metamodel?.elementTypes),e.metamodelExtensions?.forEach(r=>n(r.elementTypes)),t},Jd=e=>{let t=zt(e);return{modelName:e.name,rootId:t.rootId,elements:t.elements,...t.labels&&{labels:t.labels},indexOwners:n=>e.elementIndexEntries[n]?.owners,packageTypes:YB(e)}},pt=(e,t)=>e.kind==="draft"?`your draft of ${t} (aimed at ${e.branch.name})`:e.kind==="branch"?`the head of branch ${e.name} of ${t}`:`commit ${e.id} of ${t}`;var PS=J({path:["model","diff"],effect:"read",summary:"Show what pushing a workspace would change",description:"Compares the workspace files with the branch the workspace was pulled from (your draft on it while you hold one, otherwise the branch head) and lists the operations a push stages, in order: creates, moves, updates and deletes. When that head moved since the workspace's base (an edit in the app, an 'el' command, an undo), the workspace is stale and the list is not pushable, since it would revert those changes; when it moved and holds exactly what the files hold (the draft they reflected was committed), the base moves to it and is reported as rebound. --exit-code exits 1 when there are differences, as git diff does.",positionals:[wo],flags:{"exit-code":{type:"boolean",description:"Exit 1 when the workspace differs from its target, 0 when not."}},prepare:Gd,examples:["modeldesk model diff","modeldesk model diff shacl-workspace --exit-code"],run:e=>oe(async()=>{let t=Js(e),{dir:n}=t,{state:r}=t,o=await Xs(e,n,r),s=Vd(n,r,o),i=s.kind==="rebound"?{from:s.from}:void 0;i&&(r=zd(n,r,o));let a=s.kind==="stale",d=Mn(n,r),l=zt(o.read),c,m;try{c=Wd(l,d,{modelId:r.model.id,baseCommitId:o.head})}catch(y){if(!(a&&y instanceof At))throw y;m={message:y.reason,errors:y.problems}}let p=c?.ops??[],h={model:o.model,ref:bo(o),dir:n,baseCommitId:r.baseCommitId,...i&&{rebound:i},headCommitId:o.head,stale:a,pushable:!a,ops:p,counts:Hd(p),chunks:c?.chunks.length??0,...!a&&c!==void 0&&p.length>0&&{planHash:c.hash},labels:Bd(p,l.labels),warnings:c?.warnings??[],...m&&{refused:m},url:be(e.instance(),{kind:"model",modelId:r.model.id})},u=p.length>0||m!==void 0;return{result:h,...e.flags["exit-code"]&&u&&{exitCode:b.Failure}}}),render:e=>{let t=g(e.model.name),n=[];return e.rebound&&n.push(Kd(e.ref,t,e.rebound.from,e.headCommitId)),e.stale&&n.push(`The workspace is stale: ${pt(e.ref,t)} moved from ${e.baseCommitId} to ${e.headCommitId} since it was pulled. The operations below are not pushable: they would revert what changed in between. Push nothing; re-pull with 'modeldesk model pull' (--force discards local edits).`),e.refused!==void 0?n.push(`Note: the files also change what a push cannot stage: ${e.refused.message}`):e.ops.length===0?n.push(`No differences with ${pt(e.ref,t)}.`):(n.push(`${e.ops.length} operation(s) against ${pt(e.ref,t)}: ${zs(e.counts)}`+(e.chunks>1?`, in ${e.chunks} changes`:"")+".",...Ud(e.ops,e.labels).map(r=>` ${r}`)),e.counts.delete>0&&n.push("Deletes are pushed only with --allow-delete."),e.planHash!==void 0&&n.push(`plan: ${e.planHash}`)),n.push(...e.warnings.map(r=>`Note: ${r}`)),n.join(`
246
+ `)}});import{basename as IU}from"node:path";import{randomUUID as XB}from"node:crypto";import{chmodSync as QB,closeSync as ZB,fchmodSync as eU,fsyncSync as tU,lstatSync as nU,openSync as rU,renameSync as qS,rmdirSync as oU,rmSync as sU,statSync as iU,writeSync as aU}from"node:fs";import{dirname as Vf,isAbsolute as dU,join as Bf,relative as lU,resolve as LS,sep as cU}from"node:path";import{existsSync as KB,mkdirSync as zB}from"node:fs";import{dirname as DS,resolve as JB}from"node:path";var Xd=(e,t)=>{let n=[];for(let r=JB(e);!KB(r)&&DS(r)!==r;r=DS(r))n.unshift(r);return zB(e,{recursive:!0,mode:t})===void 0?[]:n};var Qd="modeldesk model export --help",_S=e=>{try{return iU(e)}catch{return}},WS=e=>{let{output:t,compressed:n,json:r,cwd:o}=e;if(n){if(t===void 0)throw k("--compressed writes a ZIP file and needs -o <file>; it never writes to stdout.",Qd);let a=LS(o,t);if(_S(a)?.isDirectory())throw k(`-o ${t} is a directory; --compressed writes one ZIP file, so name the file.`,Qd);return{kind:"zip",file:a}}if(t===void 0){if(r)throw k("--json needs -o <dir>: stdout carries the result document, so the exported documents cannot share it.",Qd);return{kind:"stdout"}}let s=LS(o,t),i=_S(s);if(i!==void 0&&!i.isDirectory())throw k(`-o ${t} is a file; without --compressed, -o names the directory to write into.`,Qd);return{kind:"directory",dir:s}},mU=/[\u0000-\u001f\u007f-\u009f<>:"|?*]/,pU=/^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i,fU=e=>{if(e===""||e==="."||e==="..")return'it holds an empty, "." or ".." path segment';if(mU.test(e))return'it holds a control character or one of < > : " | ? *';if(pU.test(e))return"Windows reserves it for a device";if(/[. ]$/.test(e))return"it ends in a dot or a space, which Windows drops"},uU=e=>{if(e.includes("\\"))return"it holds a backslash, and paths are separated by /";for(let t of e.split("/")){let n=fU(t);if(n!==void 0)return n}},HS=e=>{for(let{filename:t}of e){let n=uU(t);if(n!==void 0)throw new f(`Refusing to write the document named ${JSON.stringify(t)}: ${n}.`,{hint:"Nothing was written. Report the format to ModelDesk: its documents should carry portable file names.",details:{filename:t}})}},hU=e=>e.normalize("NFC").toLowerCase(),BS=e=>{let t=new Map;for(let{filename:n}of e){let r=hU(n),o=t.get(r);if(o!==void 0)throw new f(`The export holds documents named ${JSON.stringify(o)} and ${JSON.stringify(n)}, which one directory cannot hold apart.`,{hint:"Nothing was written, since the second would overwrite the first.",details:{filenames:[o,n]}});t.set(r,n)}for(let[n,r]of t){let o=n.split("/");for(let s=1;s<o.length;s++){let i=t.get(o.slice(0,s).join("/"));if(i!==void 0)throw new f(`The export holds the document ${JSON.stringify(i)} and also ${JSON.stringify(r)} inside it as a folder, which one path cannot be both.`,{hint:"Nothing was written, since one path cannot be both a file and a directory.",details:{filenames:[i,r]}})}}},US=e=>new f(`The export produced ${e.length} documents, and stdout takes one.`,{exitCode:b.Usage,hint:"Pass -o <dir> to write each under its file name, or --compressed -o <file> for one ZIP.",details:{filenames:e.map(t=>t.filename)}}),gU=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g,GS=(e,t)=>t?e.replace(gU,""):e,Zd=e=>e.code??e.message,jS=420,FS=493,Uf=e=>{let t=Xd(e,FS);return t.forEach(n=>QB(n,FS)),t},VS=e=>Bf(Vf(e),`.modeldesk-${XB().slice(0,8)}.tmp`),YS=(e,t)=>{let n=rU(e,"wx",jS);try{eU(n,jS);let r=0;for(;r<t.length;)r+=aU(n,t,r,t.length-r);tU(n)}finally{ZB(n)}},Gf=e=>{try{sU(e,{force:!0})}catch{}},KS=(e,t)=>{Uf(Vf(e));let n=VS(e);try{YS(n,t),qS(n,e)}catch(r){throw Gf(n),new f(`Could not write ${e} (${Zd(r)}).`)}},yU=(e,t)=>{let n=Bf(e,...t.split("/")),r=lU(e,n);if(r===""||r===".."||r.startsWith(`..${cU}`)||dU(r))throw new f(`Refusing to write ${JSON.stringify(t)}: it would land outside ${e}.`,{details:{filename:t}});let o=e;for(let s of t.split("/").slice(0,-1)){o=Bf(o,s);let i;try{i=nU(o).isSymbolicLink()}catch{break}if(i)throw new f(`Refusing to write ${JSON.stringify(t)}: ${o} is a symbolic link.`,{hint:"Nothing was written. Remove the link or export into another directory.",details:{filename:t}})}return n},zS=(e,t)=>{let n=t.map(({filename:a})=>yU(e,a)),r=[],o=[],s=()=>{o.forEach(({temp:a})=>Gf(a));for(let a of r.toReversed())try{oU(a)}catch{}};try{r.push(...Uf(e))}catch(a){throw new f(`Could not create ${e} (${Zd(a)}).`,{details:{renamed:[]}})}for(let[a,{filename:d,contents:l}]of t.entries()){let c=n[a],m=Buffer.from(l,"utf8"),p=VS(c);try{r.push(...Uf(Vf(c))),YS(p,m)}catch(h){throw Gf(p),s(),new f(`Could not write ${c} (${Zd(h)}); nothing was written.`,{details:{failed:d,renamed:[]}})}o.push({temp:p,written:{filename:d,path:c,bytes:m.length}})}let i=[];for(;o.length>0;){let{temp:a,written:d}=o[0];try{qS(a,d.path)}catch(l){throw s(),new f(`Could not move ${d.path} into place (${Zd(l)}); `+(i.length===0?"nothing was written.":`${i.length} document(s) before it were.`),{details:{failed:d.filename,renamed:i}})}i.push(d.filename),o.shift()}return t.map(({filename:a,contents:d},l)=>({filename:a,path:n[l],bytes:Buffer.byteLength(d,"utf8")}))};var JS=(e,t,n)=>{let r=t.toLowerCase(),o=e.filter(i=>B(t)?i.id.toLowerCase()===r:i.name.toLowerCase()===r);if(o.length===1)return o[0];let s=[...e].sort((i,a)=>(i.sortOrder??0)-(a.sortOrder??0)||i.name.localeCompare(a.name)).map(({id:i,name:a,mediaType:d,fileExtension:l})=>({id:i,name:a,...d?{mediaType:d}:{},...l?{fileExtension:l}:{}}));throw o.length>1?new f(`${o.length} ${n} formats are named '${t}'; pass --format with an id.`,{exitCode:b.Usage,details:{formats:s.filter(i=>i.name.toLowerCase()===r)}}):new f(`${n} has no encoding format '${t}'.`,{exitCode:b.NotFound,hint:s.length===0?`${n} offers no encoding formats.`:`Its formats: ${s.map(i=>i.name).join(", ")}.`,details:{formats:s}})};var XS=e=>{let t=String.raw`'\''`;return`'${e.replaceAll("'",t)}'`},wU=new Set(["sig","key","apikey","api_key","api-key"]),bU=["auth","token","secret","password","signature","credential"],Eo="REDACTED",EU="<unparseable URL redacted>",QS=e=>{let t=e.toLowerCase();return wU.has(t)||bU.some(n=>t.includes(n))},CU=(e,t,n)=>t===-1||n!==-1&&n<t?"":e.slice(t+1,n===-1?void 0:n),Qs=e=>{try{return decodeURIComponent(e.replaceAll("+"," "))}catch{return e}},Pn=e=>{let t;try{t=new URL(e)}catch{return EU}let n=!1;(t.username!==""||t.password!=="")&&(t.username=Eo,t.password="",n=!0),t.hash!==""&&(t.hash="",n=!0);for(let r of new Set(t.searchParams.keys()))if(QS(r)){let o=t.searchParams.getAll(r).length;t.searchParams.delete(r);for(let s=0;s<o;s+=1)t.searchParams.append(r,Eo);n=!0}return n?t.toString():e},RU=e=>{let t=[[e,Pn(e)]],n=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)@/i.exec(e)?.[1];n&&t.push([`${n}@`,`${Eo}@`],[`${Qs(n)}@`,`${Eo}@`]);let r=e.indexOf("#"),o=r===-1?"":e.slice(r+1);o!==""&&t.push([`#${o}`,""]);let s=e.indexOf("?"),i=CU(e,s,r);for(let a of[...i.split("&"),...o.split("&")]){let d=a.indexOf("="),l=d===-1?a:a.slice(0,d),c=d===-1?"":a.slice(d+1);c!==""&&QS(Qs(l))&&t.push([a,`${l}=${Eo}`],[`${Qs(l)}=${Qs(c)}`,`${Qs(l)}=${Eo}`])}return t.filter(([a])=>a!=="").sort(([a],[d])=>d.length-a.length)},el=e=>{if(e===void 0)return n=>n;let t=RU(e);return n=>t.reduce((r,[o,s])=>r.split(o).join(s),n)},Nn=(e,t)=>typeof e=="string"?t(e):Array.isArray(e)?e.map(n=>Nn(n,t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Nn(r,t)])):e;var tl=e=>({ERROR:e.filter(t=>t.logLevel==="ERROR").length,WARN:e.filter(t=>t.logLevel==="WARN").length,INFO:e.filter(t=>t.logLevel==="INFO").length}),Yf=e=>{let t=[e.modelElementId?`element ${e.modelElementId}`:void 0,e.property?`property ${e.property}`:void 0].filter(Boolean),n=e.detailMessage&&e.detailMessage!==e.title?`: ${e.detailMessage}`:"",r=t.length>0?` (${t.join(", ")})`:"";return g(`${e.logLevel} [${e.code}] ${e.title}${n}${r}`)},Zs=e=>e.map(t=>`${Yf(t)}
247
+ `).join("");var Kf={initialMs:500,maxMs:5e3,factor:1.5},kU=(e,t)=>({settled:!1,...e===void 0?{}:{last:e},...t===void 0?{}:{lastError:t}}),ei=async({read:e,settled:t,deadline:n,clock:r,interval:o=Kf,onRead:s,tolerate:i=()=>!1})=>{let a=o.initialMs,d,l;for(;;){try{let m=await e();if(d=m,l=void 0,s?.(m),t(m))return{settled:!0,value:m}}catch(m){if(!i(m))throw m;l=m}let c=n-r.now();if(c<=0)return kU(d,l);await r.sleep(Math.min(a,c)),a=Math.min(o.maxMs,a*o.factor)}};var vU=new Set(["INITIALIZED","PROCESSING"]),ZS=e=>!vU.has(e.status),e$=e=>e.status==="COMPLETED"||e.status==="ERROR",ti=e=>e instanceof f&&e.exitCode===b.Transient,zf=(e,t)=>e.now()+t*1e3,ni=e=>`modeldesk model imports show ${e}`,Co=(e,t)=>`modeldesk model imports complete ${e} --name ${t===void 0?"<name>":XS(t)}`,Jf=(e,t)=>t?[...e]:e.map(Yf),Xf=e=>el(e.source.type==="remote"?e.source.location:void 0),ri=e=>Nn(e,Xf(e)),t$=(e,t,n)=>{let r=ri(e);return new f(`Import ${r.id} failed ${t==="parse"?"while parsing":"while completing"}: ${r.errorMessage??"the server gave no reason"}`,{details:{importId:r.id,status:r.status,...r.errorMessage?{errorMessage:r.errorMessage}:{},logEntries:Jf(r.logEntries??[],n)}})},n$=(e,t,n,r,o,s)=>{let i=s instanceof f?` The last status check failed: ${s.reason}`:"";return new f(`Import ${e} is still ${t} after ${r} s; it continues on the server.${i}`,{exitCode:b.Transient,hint:n==="parse"?`Check it with '${ni(e)}' and, once it is READY, finish it with '${Co(e,o)}'. Do not run the import again; that starts a second one.`:`Check it with '${ni(e)}'; it names the new model once the completion lands.`,details:{importId:e,status:t,phase:n}})},r$=(e,t,n,r={})=>new f(`${e.reason} (import ${t})`,{exitCode:b.Transient,hint:n,type:e.type,requestId:e.requestId,details:{...e.details,importId:t,...r}}),o$=(e,t)=>{let n;return r=>{r.status!==n&&(n=r.status,e.note(`Import ${t}: ${r.status}`))}},s$=async(e,t)=>{try{return await e.api.imports.create(t)}catch(n){throw ti(n)?new f(n.reason,{exitCode:b.Transient,hint:"The import may exist anyway: run 'modeldesk model imports list' before retrying, then complete or delete the one that is there rather than starting another.",type:n.type,requestId:n.requestId,details:n.details}):n}},i$=async(e,t,n,r,o)=>{let s=o$(e,t.id);s(t);let i=t;if(!ZS(t)){let a=await ei({read:()=>e.api.imports.get(t.id),settled:ZS,deadline:n,clock:e.clock,onRead:s,tolerate:ti});if(!a.settled){let d=(a.last??t).status;throw n$(t.id,d,"parse",r,o,a.lastError)}i=a.value}if(i.status==="ERROR")throw t$(i,"parse",e.json);return i},Qf=async(e,t,n,r,o)=>{e.note(`Completing import ${t} as '${n}'.`);let s;try{s=await e.api.imports.complete(t,n)}catch(a){throw ti(a)?r$(a,t,`Check it with '${ni(t)}': once it is COMPLETED it names the model; while it is still READY, run '${Co(t,n)}' again.`,{phase:"completion"}):a}let i=s;if(!e$(s)){let a=await ei({read:()=>e.api.imports.get(t),settled:e$,deadline:r,clock:e.clock,onRead:o$(e,t),tolerate:ti});if(!a.settled){let d=(a.last??s).status;throw n$(t,d,"completion",o,n,a.lastError)}i=a.value}if(i.status==="ERROR")throw t$(i,"completion",e.json);if(i.modelId===void 0)throw new f(`Import ${t} completed without naming the model it created.`,{hint:`Run '${ni(t)}'.`});return i},a$=async(e,t,n)=>{try{return await t()}catch(r){throw ti(r)?r$(r,e,`The import is READY: review it with '${ni(e)}' and finish it with '${Co(e,n)}'.`):r}},Zf=(e,t)=>e instanceof f?new f(t(e.reason),{exitCode:e.exitCode,...e.hint===void 0?{}:{hint:t(e.hint)},type:e.type,requestId:e.requestId,details:Nn(e.details,t)}):e;var SU="modeldesk model export --help",$U=async(e,t,n)=>{if(B(t))return{id:t};if(Ye(e.env)!==void 0)throw k(`--mapping '${t}' is a name, and mappings can be looked up by name only in a user session.`,SU);let{items:r}=await e.api().modelMappings.list({sourceMetamodel:n}),o=r.filter(s=>s.name.toLowerCase()===t.toLowerCase());if(o.length===1)return{id:o[0].id,name:o[0].name};throw o.length>1?new f(`${o.length} mappings are named '${t}'; pass --mapping with an id.`,{exitCode:b.Usage,details:{candidates:o.map(({id:s,name:i})=>({id:s,name:i}))}}):new f(`No mapping named '${t}' applies to this model's metamodel.`,{exitCode:b.NotFound,hint:r.length===0?"None does.":`Mappings that do: ${r.map(s=>s.name).join(", ")}.`,details:{candidates:r.map(({id:s,name:i})=>({id:s,name:i}))}})},TU=e=>WS({output:e.flags.output,compressed:e.flags.compressed,json:e.globals.json,cwd:e.cwd}),xU=async(e,t)=>{let{metamodel:n}=await e.api().models.overview(t);if(n===void 0)throw new f("This is a metamodel-model; its encoding formats are not listed per metamodel.",{exitCode:b.NotFound});return{id:n.modelId,name:n.name}},d$=(e,t)=>{!e.globals.json&&t.length>0&&e.io.err(ye(Zs(t)))},AU=async(e,t,n,r,o)=>{e.warn("a compressed export carries no log entries, so encode errors cannot fail this command; use -o <dir> without --compressed where errors must fail the run (CI).");let s=await e.api().encoding.encodeCompressed(n,r);return KS(t,s),{...o,compressed:!0,documents:[{filename:IU(t),path:t,bytes:s.length}],logEntries:[],logEntriesAvailable:!1,errorCount:0}},OU=(e,t,n,r)=>{if(!(t.length>0))throw new f(`The ${r.format} encoder produced no documents for ${r.model}.`,{hint:n.length>0?"Its log entries may say why.":"Check the model holds what the format encodes, or try another format.",details:{logEntries:Jf(n,e.globals.json)}})},MU=(e,t,n)=>{let r=n[0]?` (${n[0].filename})`:"";e.io.err(ye(`Exported ${t.model} as ${t.format}${r}.
248
+ `))},NU=(e,t,n)=>{let r=n===1?"y":"ies";e.io.err(ye(`error: the ${t} encoder reported ${n} ERROR log entr${r}; the documents were written anyway. Pass --lenient to exit 0 for a format that reports them routinely.
249
+ `))},l$=J({path:["model","export"],effect:"read",summary:"Encode a model in a format of its metamodel",description:"Encodes a model in an encoding format of its metamodel (XSD, JSON Schema, Turtle, ...). One document goes to stdout, or to <dir>/<filename> with -o <dir>; several need -o <dir> or --compressed -o <file>. The encoder's log entries go to stderr (or the --json result, which needs -o). An ERROR entry exits 1, with the documents still written; --lenient exits 0 instead. --compressed returns no log entries, so it cannot fail on them. An export with no documents exits 1. Into a directory, a document whose server-supplied name is not a portable relative path (`/`-separated, as `schemas/common/b.xsd`, written into subdirectories of <dir>), or two names one directory cannot hold apart, exit 1 before anything is written. At a terminal, a document on stdout loses its control characters; piped or redirected it is byte-exact. Exports main only: a draft or a branch cannot be encoded yet.",positionals:[N(de)],flags:{format:{type:"string",required:!0,placeholder:"name|id",description:"The encoding format, by name (ignoring case) or id, among the model's metamodel's formats."},mapping:{type:"string",placeholder:"id",description:"A model mapping to apply before encoding, by id (a name works in a user session only)."},output:{type:"string",short:"o",placeholder:"path",description:"The directory to write the documents into, or the ZIP file with --compressed."},compressed:{type:"boolean",description:"Fetch the documents as one ZIP (needs -o <file>); it carries no log entries."},lenient:{type:"boolean",description:"Exit 0 even when the encoder reports ERROR log entries."}},examples:['modeldesk model export <model> --format "MIM-LD - Turtle" > buildings.ttl',"modeldesk model export <model> --format XSD -o xsd/","modeldesk model export <model> --format XSD --compressed -o schemas.zip"],run:async e=>{let{flags:t,args:n}=e,r=TU(e),o=e.api(),s=await ae(e,n.model,de),i=le(s);i.note!==void 0&&e.warn(i.note);let a=s.id,d=await xU(e,a),{items:l}=await o.encodingFormats.list(d.id),c=JS(l,t.format,d.name),m=t.mapping===void 0?void 0:await $U(e,t.mapping,d.id),p={format:c.id,mapping:m?.id},h={model:{id:a,name:s.name},ref:i,format:{id:c.id,name:c.name},...m?{mapping:m}:{}};if(r.kind==="zip")return{result:await AU(e,r.file,a,p,h)};let u=await o.encoding.encode(a,p),y=u.documents??[],w=u.logEntries??[],E={format:c.name,model:s.name};if(OU(e,y,w,E),r.kind==="stdout"&&y.length>1)throw d$(e,w),US(y);let I;if(r.kind==="stdout"){let[{filename:x,contents:L}]=y;e.io.out(GS(L,e.stdoutIsTTY)),I=[{filename:x,path:"-",bytes:Buffer.byteLength(L,"utf8")}]}else HS(y),BS(y),I=zS(r.dir,y);d$(e,w);let v=tl(w).ERROR,$=v>0&&!t.lenient;return e.globals.json||(r.kind==="stdout"&&MU(e,E,I),$&&NU(e,c.name,v)),{result:{...h,compressed:!1,documents:I,logEntries:w,logEntriesAvailable:!0,errorCount:v},exitCode:$?b.Failure:b.Success}},render:e=>e.documents.every(t=>t.path==="-")?"":[`Exported ${e.model.name} as ${e.format.name}:`,...e.documents.map(t=>` ${t.path} ${t.bytes} bytes`)].join(`
250
+ `)});var nl={now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))};import{readFileSync as PU,statSync as DU}from"node:fs";import{basename as LU,resolve as _U}from"node:path";var Dn=["mim-ld","nl-sbb","dsv","shacl-ap"],eu=["rdf-file",...Dn],c$={".ttl":eu,".trig":eu,".nt":eu,".n3":Dn,".nq":Dn,".rdf":Dn,".rdfs":Dn,".owl":Dn,".jsonld":Dn,".xml":[...Dn,"xmi-2.1-file","mim-xml"],".xmi":["xmi-2.1-file"],".eap":["eap-file"],".eapx":["eap-file"],".xsd":["xsd-file"],".zip":["shacl-ap"],".json":["json-schema-file"],".yaml":["json-schema-file"],".yml":["json-schema-file"]};var m$={ADDRESS:"an address (--url)",FILE:"an uploaded file"},oi=e=>e.length===0?"none":e.join(", "),f$=e=>e.kind==="file"?"FILE":"ADDRESS",tu=(e,t)=>e.sourceKinds.includes(f$(t)),rl=(e,t)=>new f(e,{exitCode:b.Usage,hint:"Pass --loader <name> to choose one.",details:{candidates:[...t]}}),nu=e=>{let t="";if(e.kind==="file")t=e.filename;else try{t=decodeURIComponent(new URL(e.location).pathname.split("/").at(-1)??"")}catch{}let n=t.lastIndexOf(".");return n>0?t.slice(n).toLowerCase():void 0},p$=(e,t)=>{let n=e.map(o=>`'${o.name}' reads ${o.sourceKinds.map(s=>m$[s]).join(" or ")} only`),r=e.every(o=>o.sourceKinds.includes("ADDRESS"));return new f(`${n.join("; ")}, and this import gives ${m$[f$(t)]}.`,{exitCode:b.Usage,hint:r?"Publish the file at an address and pass that with --url.":"Download the file and pass its path instead of --url.",details:{loaders:e.map(o=>({name:o.name,sourceKinds:[...o.sourceKinds]}))}})},u$=({source:e,metamodelLoaders:t,metamodelLabel:n,explicit:r})=>{let o=t.map(c=>c.name);if(r!==void 0){let c=t.find(m=>m.name===r);if(c===void 0)throw rl(`Loader '${r}' does not import into ${n}, which imports with ${oi(o)}.`,o);if(!tu(c,e))throw p$([c],e);return{name:c.name,inferred:!1}}let s=nu(e),i=s===void 0?void 0:c$[s],a=t.filter(c=>tu(c,e)).map(c=>c.name);if(i===void 0){let c=s===void 0?"a source without a file extension":`'${s}' files`;throw rl(`No loader is known for ${c}; ${n} imports with ${oi(o)}.`,a)}let d=t.filter(c=>i.includes(c.name));if(d.length===0)throw rl(`None of the loaders for '${s}' files (${oi(i)}) imports into ${n}, which imports with ${oi(o)}.`,a);let l=d.filter(c=>tu(c,e));if(l.length===0)throw p$(d,e);if(l.length>1){let c=l.map(m=>m.name);throw rl(`Several loaders read '${s}' files into ${n}: ${oi(c)}.`,c)}return{name:l[0].name,inferred:!0}};var ru=70*1024*1024,h$=e=>`${(e/(1024*1024)).toFixed(1)} MB`,y$=(e,t,n)=>{let r="modeldesk model import --help";if(e!==void 0&&t!==void 0)throw k("Pass a file or --url, not both.",r);if(t!==void 0){let i;try{i=new URL(t)}catch{throw k("--url takes an absolute http or https address, and this one does not parse.",r)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw k(`--url takes an http or https address, got '${Pn(t)}'.`,r);return{type:"remote",location:t}}if(e===void 0)throw k("Name the file to import, or pass --url.",r);let o=_U(n,e),s;try{let i=DU(o);if(!i.isFile())throw k(`'${e}' is not a file.`,r);if(i.size>ru)throw new f(`'${e}' is ${h$(i.size)}, and an upload is at most ${h$(ru)} (the server takes 100 MB of request, and base64 adds a third).`,{exitCode:b.Usage,hint:"Publish the file at an address the server can reach and import it with --url, or split the model.",details:{bytes:i.size,maxBytes:ru}});s=PU(o)}catch(i){throw i instanceof f?i:k(`Cannot read '${e}' (${i.code??i.message}).`,r)}return{type:"upload",filename:LU(o),path:o,bytes:s.length,binaryData:s.toString("base64")}},w$=e=>e.type==="upload"?{kind:"file",filename:e.filename}:{kind:"url",location:e.location},jU=e=>e.type==="upload"?e.filename:Pn(e.location),b$=async(e,t)=>{let{items:n}=await e.metamodels.list(),{id:r,name:o}=gn(n,t,"metamodel",hn);return{id:r,name:o}},ou=e=>e.standardVersion??e.name,su=async(e,t,n)=>{let r=await e.metamodelVersions.list(t.id);if(n===void 0){if(r.length===0)throw new f(`${t.name} has no release to import into.`,{exitCode:b.NotFound});return{...t,version:ou(r[0]),chosen:"newest"}}let o=r.find(s=>s.standardVersion===n||s.name===n);if(o===void 0){let s=r.map(ou);throw new f(`${t.name} has no release '${n}'.`,{exitCode:b.NotFound,hint:`Its releases: ${s.join(", ")||"none"}.`,details:{candidates:s}})}return{...t,version:ou(o),chosen:"given"}},E$=async(e,t,n)=>{if(n.length===0)return[];let{items:r}=await e.metamodelExtensions.list(t.id),o=new Map(r.map(a=>[a.id,a])),s=new Map;for(let a of n){let d=gn(r,a.model,`extension of ${t.name}`,Sa(t.id));s.set(d.id,{version:Mr(a)})}let i=[...s.keys()];for(;i.length>0;){let a=o.get(i.shift());for(let d of a?.dependsOnExtensions??[])o.has(d)&&!s.has(d)&&(s.set(d,{requiredBy:a?.name}),i.push(d))}return Promise.all([...s].map(async([a,{version:d,requiredBy:l}])=>{let{name:c}=o.get(a);return{...await su(e,{id:a,name:c},d),...l?{requiredBy:l}:{}}}))},C$=async(e,t,n)=>VR(wn(await e.accessTokenClaims()),t,n),R$=async(e,t,n,r)=>{let{items:o}=await e.modelLoaders.forMetamodel(t.id,t.version);return u$({source:w$(n),metamodelLoaders:o,metamodelLabel:`${t.name} ${t.version}`,explicit:r})},k$=e=>({metamodel:e.metamodel.id,metamodelVersion:e.metamodel.version,...e.extensions.length>0?{metamodelExtensions:e.extensions.map(t=>t.id)}:{},metamodelExtensionVersions:Object.fromEntries(e.extensions.map(t=>[t.id,t.version])),loader:e.loader.name,source:e.source.type==="upload"?{type:"upload",filename:e.source.filename,binaryData:e.source.binaryData}:{type:"remote",location:e.source.location},owner:{id:e.owner.id,type:"ORGANIZATION"}}),g$=e=>`${e.name} ${e.version}${e.chosen==="newest"?" (newest release)":""}`,v$=e=>{let t=nu(w$(e.source)),n=e.loader.inferred?`${e.loader.name} (inferred from ${t})`:e.loader.name,r=e.owner.name??e.owner.id,o=e.owner.chosen==="only-seated"?` (your one organization with a ${e.metamodel.name} seat)`:"",s=a=>{let d=a.requiredBy?` (required by ${a.requiredBy})`:"";return`${g$(a)}${d}`},i=e.extensions.length===0?"":`, with ${e.extensions.map(s).join(", ")}`;return`Importing ${jU(e.source)} into ${g$(e.metamodel)}${i} with loader ${n}, owned by ${r}${o}.`};var FU=e=>e.type==="remote"?{type:"remote",location:Pn(e.location)}:{type:"upload",...e.filename?{filename:e.filename}:{}},iu=e=>({id:e.id,status:e.status,createdAt:e.createdAt,metamodel:{id:e.metamodelId,...e.metamodel?.name?{name:e.metamodel.name}:{},...e.metamodelVersion?{version:e.metamodelVersion}:{}},...e.loader?{loader:e.loader}:{},source:FU(e.source),owner:{id:e.owner.id,type:e.owner.type,...e.owner.name?{name:e.owner.name}:{}},...e.modelId?{modelId:e.modelId}:{}}),I$=(e,t)=>{let n=new Map((t.metamodelExtensions??[]).map(s=>[s.id,s.name])),r=t.metamodelExtensionVersions??{},o=t.metamodelExtensionIds??[...n.keys()];return{...iu(t),...t.createdBy?{createdBy:{id:t.createdBy.id,...t.createdBy.name?{name:t.createdBy.name}:{}}}:{},extensions:o.map(s=>({id:s,...n.get(s)?{name:n.get(s)}:{},...r[s]?{version:r[s]}:{}})),...t.errorMessage?{errorMessage:t.errorMessage}:{},logEntries:t.logEntries??[],url:be(e,{kind:"import",importId:t.id}),...t.modelId?{model:{id:t.modelId,url:be(e,{kind:"model",modelId:t.modelId})}}:{}}},S$=e=>{let t=new Map;for(let r of Object.values(e.elements??{}))r.type.startsWith("@")||t.set(r.type,(t.get(r.type)??0)+1);let n=[...t].map(([r,o])=>({type:r,count:o})).sort((r,o)=>o.count-r.count||r.type.localeCompare(o.type));return{...e.name?{name:e.name}:{},elementCount:n.reduce((r,{count:o})=>r+o,0),elementsByType:n}};var $$="modeldesk model import --help",qU=600,x$={type:"number",default:qU,placeholder:"seconds",description:"How long to wait for the server before exiting 7; the import carries on server-side and can be resumed."},au={name:"import-id",type:"string",required:!0,description:"The import's id, as 'model import' or 'model imports list' prints it."},A$=e=>t=>{e.globals.json||e.io.err(ye(`${t}
251
+ `))},O$=e=>({api:e.api(),clock:nl,json:e.globals.json,note:A$(e)}),M$=(e,t)=>{if(!Number.isFinite(e)||e<=0)throw k(`--timeout takes a positive number of seconds, got ${e}.`,t)},du=(e,t)=>{if(!B(e))throw k(`'${e}' is not an import id.`,`modeldesk model imports ${t} --help`)},WU=(e,t)=>{if(e.globals.json||t.length===0)return;let{ERROR:n,WARN:r,INFO:o}=tl(t);e.io.err(ye(`Log: ${n} error(s), ${r} warning(s), ${o} info
252
+ ${Zs(t)}`))},N$=e=>e.type==="upload"?{type:"upload",filename:e.filename,bytes:e.bytes}:{type:"remote",location:Pn(e.location)},P$=J({path:["model","import"],effect:"create",summary:"Import a file or an address as a new model",description:"Creates an import, waits for the parse, completes it as a model named --name, and prints the model id and link. The metamodel release is the one --metamodel names after @, or its newest; the loader is --loader or inferred from the file extension among the release's loaders; the owner is --owner or your one organization with a seat for the metamodel. Every choice is printed, and carried in --json. --review stops after the parse with a summary; finish with 'model imports complete'. Exits 1 when the server puts the import in ERROR, 2 for an ambiguous or mismatched loader or owner, and 7 when --timeout passes (the import then carries on server-side).",positionals:[{name:"file",type:"string",description:"The file to upload; its name travels with it, since some loaders read the format from it."}],flags:{url:{type:"string",placeholder:"uri",description:"Import from this address instead of a file; the server fetches it."},metamodel:{type:{address:"model",slot:Di},required:!0,placeholder:"metamodel[@release]",description:"The metamodel's id, from metamodel list, at @<release> or else its newest release."},name:{type:"string",placeholder:"name",description:"The name of the model the import creates; required unless --review."},owner:{type:"string",placeholder:"organization",description:"The organization that owns the import and the model, by name or id; needed when several give you a seat."},extension:{type:{list:{address:"model",slot:Li}},placeholder:"extension[@release]",description:"An extension's id, from metamodel extensions <metamodel>, at @<release> or else its newest release."},loader:{type:"string",placeholder:"name",description:"The loader to read the source with, instead of inferring it from the extension."},review:{type:"boolean",description:"Stop once the parse is READY and summarize it; complete with 'model imports complete'."},timeout:x$},dryRun:!0,examples:["modeldesk model import vocabulary.ttl --metamodel <metamodel> --name Vocabulary","modeldesk model import --url https://example.org/schema.xsd --metamodel <metamodel>@1.0 --name Schema","modeldesk model import model.eap --metamodel <metamodel> --owner Acme --review"],run:async e=>{let{flags:t}=e;if(M$(t.timeout,$$),!t.review&&t.name===void 0)throw k("Pass --name for the model the import creates, or --review to stop before completing.",$$);let n=e.api(),r=y$(e.args.file,t.url,e.cwd),o=await b$(n,t.metamodel.model),s=await C$(n,o,t.owner),i=await su(n,o,Mr(t.metamodel)),a=await E$(n,o,t.extension),d=await R$(n,i,r,t.loader),l={source:r,metamodel:i,extensions:a,loader:d,owner:s};A$(e)(v$(l));let m={source:N$(r),metamodel:i,extensions:a,loader:d,owner:s,...t.name!==void 0?{name:t.name}:{}};if(e.globals.dryRun)return{result:{dryRun:!0,...m,logEntries:[]}};let p=el(r.type==="remote"?r.location:void 0);try{return await HU(e,l,p)}catch(h){throw Zf(h,p)}},render:e=>{if(e.dryRun)return`Dry run: nothing was imported; ${T$(e.source)} would be read by ${e.loader.name}.`;if(e.status==="READY")return BU(e);let t=e.model;return[`Imported ${T$(e.source)} as model '${g(t.name)}' (${t.id}).`,t.url].join(`
253
+ `)}}),HU=async(e,t,n)=>{let{flags:r}=e,o=e.api(),s={source:N$(t.source),metamodel:t.metamodel,extensions:t.extensions,loader:t.loader,owner:t.owner,...r.name!==void 0?{name:r.name}:{}},i=O$(e),a=zf(i.clock,r.timeout),d=await s$(i,k$(t)),l=await i$(i,d,a,r.timeout,r.name),c=Nn(l.logEntries??[],n);if(WU(e,c),r.review||r.name===void 0){let y=Nn(S$(await a$(l.id,()=>o.imports.model(l.id),r.name)),n);return{result:{dryRun:!1,importId:l.id,status:"READY",...s,logEntries:c,review:y,url:be(e.instance(),{kind:"import",importId:l.id}),next:Co(l.id,r.name)}}}let m=await Qf(i,l.id,r.name,a,r.timeout),p=m.modelId,h=be(e.instance(),{kind:"model",modelId:p});return{result:{dryRun:!1,importId:m.id,status:"COMPLETED",...s,logEntries:c,model:{id:p,name:r.name,url:h},url:h}}},T$=e=>e.type==="upload"?e.filename:e.location,BU=e=>{let t=e.review,n=t.name?` '${g(t.name)}'`:"",r=t.elementsByType.length===0?[" (no elements)"]:W(t.elementsByType.map(({type:o,count:s})=>[String(s),o])).map(o=>` ${o}`);return[`Import ${e.importId} is READY for review.`,`Parsed model${n}: ${t.elementCount} element(s)`,...r,`Complete it with: ${e.next}`,e.url].join(`
254
+ `)},ol=e=>e.api().imports.get(e.args["import-id"]),D$=J({path:["model","imports","complete"],effect:"create",summary:"Complete a READY import as a model",description:'Completes an import the parse left READY (after "model import --review", or one started in the app) as a model named --name, waits for the model, and prints its id and link. The name is the only completion input the server reads. An import that is not READY is refused (exit 1).',positionals:[au],flags:{name:{type:"string",required:!0,placeholder:"name",description:"The name of the model the import creates."},timeout:x$},dryRun:!0,examples:["modeldesk model imports complete f0909fb8-6867-42e0-a931-26d73185d949 --name Vocabulary"],run:async e=>{let{flags:t,args:n}=e;if(du(n["import-id"],"complete"),M$(t.timeout,"modeldesk model imports complete --help"),e.globals.dryRun){let d=await ol(e);if(d.status!=="READY")throw new f(`Import ${d.id} is ${d.status}; only a READY import can be completed.`);return{result:{dryRun:!0,importId:d.id,status:"READY",name:t.name,logEntries:ri(d).logEntries??[],url:be(e.instance(),{kind:"import",importId:d.id})}}}let r=O$(e),o;try{o=await Qf(r,n["import-id"],t.name,zf(r.clock,t.timeout),t.timeout)}catch(d){let l=await ol(e).then(c=>c,()=>{});throw l===void 0?d:Zf(d,Xf(l))}let s=o.modelId,i=be(e.instance(),{kind:"model",modelId:s});return{result:{dryRun:!1,importId:o.id,status:"COMPLETED",name:t.name,logEntries:ri(o).logEntries??[],model:{id:s,name:t.name,url:i},url:i}}},render:e=>e.dryRun?`Dry run: import ${e.importId} is READY and would be completed as '${g(e.name)}'.`:[`Completed import ${e.importId} as model '${g(e.name)}' (${e.model?.id}).`,e.url].join(`
255
+ `)}),UU=["ID","STATUS","DATE","METAMODEL","SOURCE","OWNER"],L$=e=>{let t=e.version?` ${e.version}`:"";return`${e.name??e.id}${t}`},_$=e=>e.source.type==="remote"?e.source.location:e.source.filename??"(upload)",j$=J({path:["model","imports","list"],effect:"read",summary:"List imports, pending and finished",description:"Lists the imports you can see, newest first: id, status, creation time, metamodel and release, source and owner. A READY import awaits completion; a COMPLETED one names the model it created.",flags:{owner:{type:"string",placeholder:"organization",description:"List only the imports this organization owns, by name or id."}},listing:{narrowHint:"Pass --owner to narrow the list."},examples:["modeldesk model imports list","modeldesk model imports list --owner Acme --json"],run:async e=>{let t=e.api(),n=e.flags.owner===void 0?void 0:qm(wn(await t.accessTokenClaims()),e.flags.owner),{items:r}=await t.imports.list(n?.id),o=r.map(iu).sort((i,a)=>a.createdAt.localeCompare(i.createdAt)||i.id.localeCompare(a.id));return{result:{...n?{owner:{id:n.id,...n.name?{name:n.name}:{}}}:{},...await e.list(o)}}},render:({items:e})=>e.length===0?"No imports.":W([UU,...e.map(t=>[t.id,t.status,t.createdAt,g(L$(t.metamodel)),g(_$(t)),g(t.owner.name??t.owner.id)])]).join(`
256
+ `)}),F$=J({path:["model","imports","show"],effect:"read",summary:"Show one import",description:"Shows an import's status, metamodel release, extensions, loader, source, owner, error message and log entries, and the model it created once COMPLETED.",positionals:[au],examples:["modeldesk model imports show f0909fb8-6867-42e0-a931-26d73185d949"],run:async e=>(du(e.args["import-id"],"show"),{result:I$(e.instance(),ri(await ol(e)))}),render:e=>{let t=L$(e.metamodel),n=e.createdBy?` by ${e.createdBy.name??e.createdBy.id}`:"";return[`Import ${e.id}`,` status ${e.status}`,` created ${e.createdAt}${n}`,` metamodel ${g(t)}`,...e.extensions.map(o=>{let s=o.version?` ${o.version}`:"";return` extension ${g(o.name??o.id)}${s}`}),...e.loader?[` loader ${e.loader}`]:[],` source ${g(_$(e))}`,` owner ${g(e.owner.name??e.owner.id)}`,...e.errorMessage?[` error ${g(e.errorMessage)}`]:[],...e.model?[` model ${e.model.id}`]:[],...e.logEntries.length>0?["","Log:",...Zs(e.logEntries).trimEnd().split(`
257
+ `)]:[],"",e.status==="READY"?`Complete it with: ${Co(e.id)}`:void 0,e.model?.url??e.url].filter(o=>o!==void 0).join(`
258
+ `)}}),q$=J({path:["model","imports","delete"],effect:"create",summary:"Discard an import",description:"Deletes an import and the parsed state it holds. A model an import already created is not affected. The server allows it to the import creator or an organization admin with a seat for the metamodel.",positionals:[au],dryRun:!0,examples:["modeldesk model imports delete f0909fb8-6867-42e0-a931-26d73185d949"],run:async e=>{let t=e.args["import-id"];du(t,"delete");let n=await ol(e);return e.globals.dryRun||await e.api().imports.delete(t),{result:{dryRun:e.globals.dryRun,importId:n.id,deleted:!e.globals.dryRun,status:n.status}}},render:e=>e.dryRun?`Dry run: import ${e.importId} (${e.status}) would be deleted.`:`Deleted import ${e.importId}.`});var W$={modelList:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},kind:{type:"string",description:'The kind of model asked for. One of "all", "metamodel", "model".'},kinds:{type:"array",items:{type:"string",description:'One of "metamodel", "model".'}},items:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},kind:{type:"string",description:'One of "metamodel", "model".'},metamodel:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},owner:{type:"object",properties:{id:{type:"string"},type:{type:"string"},name:{type:"string"}}}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","kind","kinds","items","truncated"]}};var VU=["model","metamodel","all"],YU=["ID","NAME","KIND","METAMODEL","OWNER"],KU=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),zU=(e,t)=>t==="me"&&typeof e.sub=="string"?e.sub:t===void 0||B(t)?t:ms(wn(e),t).id,JU=({model:e,kind:t})=>({id:e.id,name:e.name,kind:t,metamodel:{id:e.metamodel.id,name:e.metamodel.name},owner:{id:e.owner.id,type:e.owner.type,...e.owner.name?{name:e.owner.name}:{}}}),H$=A({path:["model","list"],effect:"read",summary:"List the models you can read",description:["Lists the models you can read with their id, name, kind, metamodel and owner.",{audience:"super-admin",text:"Metamodel-models (the metamodels themselves, as models) are listed only on --kind metamodel or --kind all, and for a super-admin only; --json reports the kinds listed as kinds."},"To choose a metamodel, run metamodel list."],flags:{metamodel:{type:"string",placeholder:"id",description:"List only models written in this metamodel, by its id from metamodel list.",toolDescription:"List only models written in this metamodel, by its id."},owner:{type:"string",placeholder:"organization|me",description:"List only models this owner has: an organization of yours by name, any owner by id, or me."},kind:{type:{enum:VU,audience:{metamodel:"super-admin",all:"super-admin"}},default:"model",description:"List models, metamodel-models (super-admin), or both.",audience:"super-admin"}},listing:{narrowHint:"Pass --metamodel or --owner to narrow the list.",toolNarrowHint:"Give a metamodel or an owner to narrow the list."},examples:["modeldesk model list","modeldesk model list --metamodel <metamodel> --json"],mcp:{name:"list_models",description:"Lists the models the person can read, with id, name, metamodel and owner. Call it first: every other tool takes a model id from here. Narrow with metamodel (an id) or owner (an organization name, an id, or me). A long list comes back truncated with nextCursor; pass it as cursor for the next page.",pin:{kind:"model"}},resultSchema:W$.modelList,run:async e=>{let{metamodel:t,owner:n,kind:r}=e.flags;if(t!==void 0&&!B(t))throw k(`--metamodel takes a metamodel's id, got '${t}'; run '${hn}' to find it.`,"modeldesk model list --help",{reason:`'metamodel' takes a metamodel's id, got '${t}'.`});let o=e.api(),s=await o.accessTokenClaims(),i=an(s),a=zU(s,n),d=(r==="all"?["model","metamodel"]:[r]).filter(p=>p==="model"||i),c=(await jg(o,{ownerId:a,metamodel:t,models:d.includes("model"),metamodels:d.includes("metamodel")})).map(JU).filter(p=>t===void 0||p.metamodel.id.toLowerCase()===t.toLowerCase()).filter(p=>a===void 0||p.owner.id.toLowerCase()===a.toLowerCase()).sort(KU);return{result:{kind:r,kinds:d,...await e.list(c)}}},render:({items:e})=>e.length===0?"No models.":W([YU,...e.map(t=>[t.id,g(t.name),t.kind,g(t.metamodel.name),g(t.owner.name??t.owner.id)])]).join(`
259
+ `)});var sl=(e,t)=>async(n,r)=>{let o=Math.min(r,99),s=await e(o+1,n),i=s.slice(0,o);return s.length>o?{items:i,nextCursor:t(i.at(-1))}:{items:i}};var B$={modelLog:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What was read: a branch, or your draft (its staged commits) when addressed as"},items:{type:"array",items:{type:"object",properties:{id:{type:"string"},createdAt:{type:"string"},author:{type:"object",properties:{id:{type:"string"},type:{type:"string",description:'One of "MACHINE", "ORGANIZATION", "SYSTEM", "USER".'},name:{type:"string"}}},message:{type:"string"},requestId:{type:"string",description:"The idempotency key of the request that made the commit, as its client sent it."},versions:{type:"array",items:{type:"string"},description:"The names of the releases cut at this commit."},changes:{type:"number",description:"How many staged changes a landing landed; absent on any other commit and on a landing older than the record."},stagedChanges:{type:"array",items:{type:"object",properties:{requestId:{type:"string"},message:{type:"string"},actionTypes:{type:"array",items:{type:"string"}}}},description:"When changes are asked for, what the landing recorded of each staged change, in the order they were staged."}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","model","ref","items","truncated"]}};var QU=["ID","DATE","AUTHOR","CHANGES","MESSAGE","REQUEST"],ZU=8,eG=" ",tG=e=>({id:e.id,createdAt:e.createdAt,author:e.createdBy,...e.message?{message:e.message}:{},...e.requestId?{requestId:e.requestId}:{},...e.versions?.length?{versions:e.versions.map(t=>t.name)}:{},...e.stagedChangeCount===void 0?{}:{changes:e.stagedChangeCount}}),nG=e=>{let t=g((e.message??"").split(/\r?\n/)[0]);return e.versions?`${t}${t?" ":""}[released ${e.versions.join(", ")}]`:t},rG=e=>[Xt(e.requestId),g(Cl(e.requestId)??""),g(e.message??""),e.actionTypes.length?`[${e.actionTypes.join(", ")}]`:""],U$=A({path:["model","log"],effect:"read",summary:"List a model's commits",description:"Lists commits newest first with their id, time, author, message and request id. The platform hides the commits it makes itself (metamodel seeding, release re-pins) unless --include-system is passed. Without a ref it lists your working branch; @draft lists the staged chain of your draft instead. CHANGES counts the staged changes a landing landed; --changes lists them beneath it.",positionals:[N(nc)],flags:{"include-system":{type:"boolean",description:"Include the commits the platform made itself, such as the re-pins a metamodel release writes."},changes:{type:"boolean",description:"List what each landing held: every staged change with its surface, agent session, message and action types, in the order they were staged. Reads one request per listed landing."}},listing:{defaultLimit:20},examples:["modeldesk model log <model>","modeldesk model log <model>@draft","modeldesk model log <model>@agent/nightly-pass --changes","modeldesk model log <model>@feat/shapes --include-system --limit 100 --json"],mcp:{name:"model_log",description:"Lists a model's commits newest first, with id, time, author, message and request id. Without a ref it lists your working branch; @draft lists the staged chain of your draft. changes: true lists what each landing held: every staged change with its surface, agent session and message. includeSystem adds the commits the platform made itself."},resultSchema:B$.modelLog,run:async e=>{let t=e.api(),n=await ae(e,e.args.model,nc),{id:r}=n,o={...rt(n.ref),includeSystem:e.flags["include-system"]},s=sl(async(d,l)=>(await t.models.commits(r,{...o,limit:d,cursor:l})).items.map(tG),d=>d.id),i=await e.list(s);if(e.flags.changes){let d=i.items.filter(l=>l.changes!==void 0);await or(d,ZU,async l=>{l.stagedChanges=(await t.models.commitHeader(r,l.id,{ref:o.ref})).stagedChanges??[]})}return{result:{model:{id:r,name:n.name},ref:le(n),...i}}},render:e=>{let t=[Ae(e.ref,e.model),...e.ref.kind==="draft"?["The log of a draft lists its staged commits only."]:[]];if(e.items.length===0)return[...t,"No commits."].join(`
260
+ `);let[n,...r]=W([QU,...e.items.map(s=>[s.id,s.createdAt,g(s.author.name??s.author.id),s.changes===void 0?"":String(s.changes),nG(s),s.requestId??""])]),o=e.items.flatMap((s,i)=>[r[i],...s.stagedChanges?.length?W(s.stagedChanges.map(rG),{indent:eG}):[]]);return[...t,n,...o].join(`
261
+ `)}});var lu={modelMetadata:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},metadata:{type:"object",additionalProperties:{},description:"The record at the head of main, as the catalog serves it."}},required:["schemaVersion","model","metadata"]},modelMetadataSet:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},before:{type:"object",additionalProperties:{},description:"The record before the write."},metadata:{type:"object",additionalProperties:{},description:"The record the write leaves, or would leave on a dry run."},replaced:{type:"boolean",description:"False on a dry run. One of false, true."},dryRun:{type:"boolean",description:"One of false, true."}},required:["schemaVersion","model","before","metadata","replaced","dryRun"]}};var G$="action",V$={name:"model_metadata",description:"Reads or replaces the model's catalog record: descriptions, keywords, themes, status, license, publisher, maintainers, contact points and distributions, and the public and publicWorkingVersion flags. It needs the organization's catalog feature. Replacing commits to main at once and needs the person's 'Act without your review' permission: read the record, change what the person asked for, call replace with dryRun: true and show them the result, then replace on their word. Setting or clearing a public flag, or changing the record of a public model, needs their 'Publish' permission."},Y$=A({path:["model","metadata","show"],effect:"read",summary:"Show a model's catalog record",description:"Prints the model's catalog record at the head of main: its descriptions, keywords and themes, status, license, publisher, maintainers, contact points, distributions, and whether it is public. It needs the organization's catalog feature.",positionals:[N(de)],examples:["modeldesk model metadata show <model> --json"],mcp:{...V$,choice:{member:G$,value:"read",description:"Read the record."}},resultSchema:lu.modelMetadata,run:async e=>{let t=await ie(e,e.args.model.model).identity(),n=await e.api().models.metadata(t.id);return{result:{model:{id:t.id,name:t.name},metadata:n}}},render:e=>`${JSON.stringify(e.metadata,null,2)}`}),sG=(e,t)=>{let n=()=>k("--record takes the catalog record as a JSON object.",`modeldesk ${t} --help`,{reason:"record takes the catalog record as a JSON object."}),r;try{r=JSON.parse(e)}catch{throw n()}if(typeof r!="object"||r===null||Array.isArray(r))throw n();return r},K$=A({path:["model","metadata","set"],effect:"land-direct",summary:"Replace a model's catalog record",description:"Replaces the model's catalog record whole with the JSON object given, as one commit on main: what it leaves out is cleared, so start from what model metadata show prints. It needs the organization's catalog feature. --dry-run reports the record before and after and writes nothing. Under an agent host it is left to a person (exit 6) unless they let the agent commit (MODELDESK_ALLOW_COMMIT=1).",positionals:[N(de)],flags:{record:{type:"string",required:!0,placeholder:"json",description:"The whole record, as a JSON object."}},dryRun:!0,examples:[`modeldesk model metadata set <model> --record '{"descriptions":[{"lang":"en","value":"Shapes"}]}'`],mcp:{...V$,choice:{member:G$,value:"replace",description:"Replace the record whole with record, a JSON object; what it leaves out is cleared."}},resultSchema:lu.modelMetadataSet,run:async e=>{let t=sG(e.flags.record,e.commandName),n=await ie(e,e.args.model.model).identity(),r=e.api(),o=await r.models.metadata(n.id),s=e.dryRun?t:await r.models.replaceMetadata(n.id,t);return{result:{model:{id:n.id,name:n.name},before:o,metadata:s,replaced:!e.dryRun,dryRun:e.dryRun}}},render:e=>e.dryRun?`Would replace the catalog record of model ${g(e.model.name)}. Dry run: nothing was changed.`:`Replaced the catalog record of model ${g(e.model.name)}.`});var al=bl(Td(),1);import{posix as il}from"node:path";var iG=8,dl=e=>{let{elements:t,labels:n={},packageTypes:r=new Set}=e,o=[],s=new Set([e.rootId]),i=S=>Object.hasOwn(t,S)?t[S]:void 0,a=S=>{let T=Object.hasOwn(n,S)?n[S]:void 0,O=i(S);return T??(O&&(Fd(O.attributes?.name)??O.type))},d=S=>{let T=a(S);return T===void 0?void 0:ye(g(T))},l=(S,T,O)=>xe(i(S)?.relations?.[T]??{}).some(M=>M.owned===!0&&M.id===O),c=S=>e.indexOwners?.(S)?.find(T=>l(T.id,T.relation,S)),m=(S,T,O)=>{if(i(O)===void 0||s.has(O))return!1;let M=c(O);return M===void 0||M.id===S&&M.relation===T},p=(S,T,O,M)=>{let _=O.owned===!0;if(_&&m(S,T,O.id)){if(s.add(O.id),M===void 0)return y(O.id);M(O.id)}let z=d(O.id);return!_&&O.modelId===void 0?ur(O.id,z):Yt([["ref",ur(O.id,O.modelId===void 0?z:void 0)],..._?[["owned",new al.Scalar(!0)]]:[],...O.modelId!==void 0?[["model",ur(O.modelId)]]:[]])},h=(S,T,O)=>{let M=i(S)?.relations?.[T]??{},_=me=>{let te=new al.YAMLSeq;return te.items=me.map(Y=>p(S,T,Y,O)),te},z=Object.keys(M);return z.length===1&&z[0]==="@@"?_(M["@@"]):Yt(z.toSorted(fe).map(me=>[me,_(M[me])]))},u=0,y=(S,T)=>{if(++u>et)throw new f(`The model nests elements more than ${et} deep (at ${S}), deeper than a workspace is written.`,{type:"model-too-deep",details:{elementId:S,limit:et}});try{return w(S,T)}finally{u--}},w=(S,T)=>{let O=t[S],M=S===e.rootId,_=O.attributes??{},z=O.relations??{},me=Object.keys(z).sort(fe),te=me.filter(ge=>!(M&&Vt(ge))),Y=me.filter(ge=>M&&Vt(ge)),ke=Je.filter(ge=>Object.hasOwn(O,ge)&&O[ge]!==void 0),Jt=[["id",ur(O.id)],["type",ur(O.type)]];return Object.keys(_).length>0&&Jt.push(["attributes",Yt(Object.keys(_).sort(fe).map(ge=>[ge,Hs(_[ge])]))]),te.length>0&&Jt.push(["relations",Yt(te.map(ge=>[ge,h(S,ge,T)]))]),(ke.length>0||Y.length>0)&&Jt.push(["readOnly",Yt([...ke.map(ge=>[ge,Hs(O[ge])]),...Y.length>0?[["relations",Yt(Y.map(ge=>[ge,h(S,ge)]))]]:[]])]),Yt(Jt)},E=S=>Object.values(S.relations??{}).some(T=>xe(T).some(O=>O.owned===!0&&r.has(i(O.id)?.type??""))),I=S=>{let T=t[S];return r.has(T.type)&&E(T)},v=(S,T)=>{let O=new Map(S.map(te=>{let Y=Tf(a(te)??"");return[te,xf(Y)?Tf(t[te].type):Y]})),M=te=>{let Y=new Map;for(let ke of te)Y.set(ke,(Y.get(ke)??0)+1);return Y},_=M(O.values()),z=new Map(S.map(te=>{let Y=O.get(te),ke=xf(Y)||T.has(Y)||(_.get(Y)??0)>1;return[te,ke?[Y,te.slice(0,iG)].filter(Boolean).join("-"):Y]})),me=M(z.values());return new Map(S.map(te=>{let Y=z.get(te);return[te,(me.get(Y)??0)>1?[O.get(te),te].filter(Boolean).join("-"):Y]}))},$=S=>{let T=d(S);return T===void 0?t[S].type:`${T} (${t[S].type})`},C=(S,T,O,M,_)=>{let z=[],me=y(S,Y=>z.push(Y));o.push({path:il.join(T,O),text:Od(me,M)});let te=v(z,_);u++;try{for(let Y of z){let ke=te.get(Y);I(Y)?C(Y,il.join(T,ke),BI,$(Y),new Set):o.push({path:il.join(T,`${ke}.yaml`),text:Od(y(Y),$(Y))})}}finally{u--}},x=`${e.modelName===void 0?"A ModelDesk model":ye(g(e.modelName))}. Edit these files, then run 'modeldesk model diff' and 'modeldesk model push'.`;C(e.rootId,"",Gt,x,new Set([Gt.replace(/\.yaml$/,"")]));let L=[];for(let S of Object.keys(t).sort(fe))s.has(S)||(s.add(S),L.push([S,y(S)]));let R=v(L.map(([S])=>S),new Set);for(let[S,T]of L)o.push({path:il.join(UI,`${R.get(S)}.yaml`),text:Od(T,$(S))});return o.sort((S,T)=>fe(S.path,T.path))},ll=e=>[{path:$t,text:`${JSON.stringify({rootElementId:e.rootId,elements:Object.fromEntries(Object.keys(e.elements).sort(fe).map(t=>[t,e.elements[t]]))},null,2)}
262
+ `}];var aG=async(e,t,n)=>{if(n.head===t.baseCommitId||t.baseRootRevision===wr(n))return n.read;try{return await e.api().models.get(t.model.id,{commit:t.baseCommitId})}catch(r){if(r instanceof V&&(r.status===404||r.status===400))return;throw r}},z$=e=>`${e.slice(0,3).map(H).join(", ")}${e.length>3?", \u2026":""}`,dG=(e,t)=>{if(t.collisions.length!==0)throw new f(`The pull would overwrite ${t.collisions.length} file(s) in ${H(e)} that the workspace did not write (${z$(t.collisions)}), so nothing was written.`,{type:"workspace-collision",hint:"Move those files away, or pull into another directory.",details:{collisions:t.collisions}})},lG=(e,t)=>{t.length!==0&&e.warn(`${t.length} file(s) the model no longer needs were edited since the workspace wrote them, so they were left in place (${z$(t)}). Remove them, or the next diff reads them.`)},cG=async(e,t,n,r)=>{let o;try{o=Mn(t,n)}catch(i){if(i instanceof tt)return{changed:!0,reason:`its files do not parse (${i.reason})`};throw i}let s=i=>Kt(zt(i),o).ops.length;try{if(s(r.read)===0)return{changed:!1};let i=await aG(e,n,r);if(i===void 0)return{changed:!0,reason:`its base commit ${n.baseCommitId} can no longer be read`};let a=s(i);return a>0?{changed:!0,reason:`it holds ${a} local change(s)`,ops:a}:{changed:!1}}catch(i){if(i instanceof At)return{changed:!0,reason:`its files change what cannot be pushed (${i.reason})`};throw i}},J$=J({path:["model","pull"],effect:"local",summary:"Pull a model into a file workspace to edit",description:"Writes the model as a tree of YAML files, one element per file with what it owns inline (the format is described in the CLI's README), and records what it pulled in .modeldesk/workspace.json: the branch (@<branch>, or your working branch), which 'modeldesk model diff' and 'modeldesk model push' then address by its id, and the head the files reflect. It pulls what you write to: your draft on the branch, otherwise the branch head, so your edits build on what you staged. A draft the branch moved past is pulled as it stands, with a warning naming 'modeldesk draft rebase'. A commit is no ref to pull: a workspace tracks a branch to push to. Pulling again updates the files in place and moves the workspace's base to the current head, on the branch the address names; a workspace with local changes is refused unless --force, which discards them. --format json writes the element map exactly as the server serves it, in one model.json.",positionals:[N(F),wo],flags:{force:{type:"boolean",description:"Pull over local changes in the workspace, discarding them."},format:{type:{enum:["yaml","json"]},description:"yaml (the default, or the workspace's format on a re-pull): the editable file tree; json: the lossless element map in one model.json."}},dryRun:!0,prepare:Wf,examples:["modeldesk model pull <model> shacl-workspace","modeldesk model pull <model>@agent/tidy-names . --format json"],run:e=>oe(async()=>{let{dir:t,state:n}=Hf(e),r=e.args.model,o=await ie(e,r.model).id();if(n!==void 0&&n.model.id!==o)throw new f(`${H(t)} is a workspace of another model (${H(n.model.name)}).`,{hint:"Pull into another directory."});let s=await gt(e,r),i=bo(s);if(n!==void 0&&!e.flags.force){let u=await cG(e,t,n,s);if(u.changed)throw new f(`The workspace in ${H(t)} is not pulled over: ${u.reason}.`,{exitCode:b.Failure,hint:"Push them with 'modeldesk model push', or pass --force to discard them. 'modeldesk model diff' shows them.",details:{...u.ops!==void 0&&{changes:u.ops}}})}let a=Jd(s.read),d=e.flags.format??n?.format??"yaml",l=d==="json"?ll(a):dl(a),c=Ld(t,l,n?.files??{});dG(t,c);let m=e.instance().host;e.globals.dryRun||(_d(t,l,c),On(t,{schemaVersion:Ut,host:m,model:s.model,branch:{id:s.branch.id,name:s.branch.name},baseCommitId:s.head,baseRootRevision:wr(s),format:d,files:Us(l)}));let p=Yd(s);return p!==void 0&&e.warn(`${p} The files hold what the draft holds: run 'modeldesk draft rebase', then pull again.`),lG(e,c.kept),{result:{model:s.model,ref:i,dir:t,format:d,baseCommitId:s.head,...n!==void 0&&{previousBaseCommitId:n.baseCommitId},elements:Object.keys(s.read.elements).length,files:{written:c.written,removed:c.removed,kept:c.kept,unchanged:c.unchanged.length},...e.globals.dryRun&&{dryRun:!0},url:be(e.instance(),{kind:"model",modelId:o})}}}),render:e=>[`${e.dryRun?"Would pull":"Pulled"} ${pt(e.ref,g(e.model.name))} into ${H(e.dir)}: ${e.elements} elements as ${e.format==="json"?"model.json":"YAML files"}.`,`${e.dryRun?"Would write":"Wrote"} ${e.files.written.length} file(s), ${e.dryRun?"would remove":"removed"} ${e.files.removed.length}, left ${e.files.unchanged} unchanged.`,...e.files.removed.map(t=>` removed ${H(t)}`),...e.files.kept.map(t=>` kept ${H(t)} (edited since it was written)`),`base: ${e.baseCommitId}`+(e.previousBaseCommitId!==void 0&&e.previousBaseCommitId!==e.baseCommitId?` (was ${e.previousBaseCommitId})`:""),`url: ${e.url}`].join(`
263
+ `)});var Q$=e=>({number:e.number,opCount:e.ops.length,firstOp:e.ops[0]??0,actions:e.actions.length,bytes:e.bytes,...e.dependsOn.length>0&&{dependsOn:e.dependsOn}}),Z$=(e,t,n)=>n>1?`${e} (${t.number}/${n})`:e,mG=(e,t,n)=>{let r=[],o=s=>{if("new"in s.element){let i=n.elements.get(s.element.new);i!==void 0&&r.push({location:i.location,id:t.ids.get(s.element.new)})}Object.values(s.children??{}).flat().forEach(o)};for(let s of e.ops){let i=t.ops[s];i.op==="create"&&o(i.element)}return r},cu=e=>e.length===0?"Nothing was staged.":`${eT(e)}: 'modeldesk model diff' shows only what is left.`,eT=e=>{let t=e.length===1?"it":"them";return`${P(e.length,"earlier change")} landed and the workspace records ${t}`},pG=e=>Array.isArray(e.details.landed)?e.details.landed:[],tT=e=>Array.isArray(e.details.errors)?e.details.errors:[],fG=(e,t,n,r)=>{let o=tT(e),s=o.some(a=>a.code==="invalid-position")?" A relation the metamodel orders alphabetically takes no position: list the element at its end.":"",i=o.some(a=>a.code==="chain-too-long");return new f(`${e.reason} ${cu(n)}${s}`,{...t,hint:i?`Commit the draft first ('modeldesk draft commit ${r}', or in the app), then push again.`:void 0})},uG=(e,t,n)=>{let r=n.length===0?"No earlier change of this push landed.":`${eT(n)}.`;return new f(`${e.reason} ${r}`,{...t,hint:e.hint})},hG=(e,t)=>{if(!(e instanceof f)||e.type==="workspace-not-recorded")return e;let n=pG(e),r={type:e.type,requestId:e.requestId,details:e.details,exitCode:e.exitCode};return e.type==="draft-head-conflict"?new f(`${e.reason} ${cu(n)}`,{...r,hint:"Re-pull the workspace with 'modeldesk model pull' and push what is left again."}):e.type==="change-validation-failed"&&e.exitCode===b.Validation?fG(e,r,n,t):e.exitCode===b.Transient?uG(e,r,n):new f(`${e.reason} ${cu(n)}`,{...r,hint:e.hint})},X$=(e,t,n,r,o,s)=>{let[i]=n.slice(-1),a=t>1?`Change ${e.number} of ${t}`:"The change";return new f(`${a} landed as ${i.commitId}, but ${o}. The workspace's base stays at ${r}, so it reads as stale and nothing more was pushed.`,{type:"workspace-not-recorded",hint:"Copy aside any edits you have not pushed, then re-pull with 'modeldesk model pull --force' to bring the files to what landed.",details:{...s,chunk:e.number,chunks:t,landed:n,baseCommitId:r}})},gG=(e,t,n,r)=>e===void 0?ci(r,`${t}:${n.number}`):_n(r,e,n),yG=(e,t)=>{let{dryRun:n}=e.globals,{message:r,plan:o,commit:s}=e.flags,i=e.flags["request-id"];if(n&&o!==void 0)throw k("--dry-run makes a plan and --plan pushes one; pass one of them.",t);if(n&&s)throw k("--commit has nothing to commit under --dry-run, which stages nothing.",t);if(e.flags["with-staged"]&&!s)throw k("--with-staged goes with --commit.",t);if(o!==void 0&&!/^[0-9a-f]{12,64}$/.test(o))throw k("--plan takes the hash a dry run printed (at least its first 12 characters).",t);Lt(r,t),i!==void 0&&ym(i,t)},wG=(e,t,n)=>new f(`The workspace is stale: ${n} moved from ${e.baseCommitId} to ${t.head} since it was pulled. Nothing was staged.`,{exitCode:b.Conflict,type:"workspace-stale",hint:"Re-pull with 'modeldesk model pull' (--force discards local edits) and edit on top of what changed; a push now would revert it.",details:{baseCommitId:e.baseCommitId,headCommitId:t.head}}),bG=(e,t)=>{let n=Yd(e);if(n===void 0)return[];if(t)throw new f(`${n} It cannot be committed as it stands, so nothing was staged.`,{exitCode:b.Conflict,type:"draft-baseline-stale",hint:"Run 'modeldesk draft rebase', re-pull the workspace, then push again.",details:{baselineCommitId:e.draft?.baselineCommitId,branchHeadCommitId:e.branch.head}});return[`${n} Committing it needs 'modeldesk draft rebase' first; re-pulling does not help.`]},EG=async(e,t,n,r)=>{let{draft:o,branch:s}=t;Rr(e,`${e.commandName} --commit`,{kind:"model",id:n,name:r},s),wm(o?.changeCount??0,e.flags["with-staged"]),o!==void 0&&await Be(e,Fi(e,n),o,{scope:{kind:"all"},action:`Committing your draft of ${r}`,anySurface:!1,override:bm(n)})},CG=(e,t)=>{if(t!==void 0&&!e.hash.startsWith(t))throw new f("The workspace no longer matches the plan: its operations or its base changed since.",{exitCode:b.Validation,type:"plan-mismatch",hint:"Run the dry run again and review the new plan.",details:{expected:t,planHash:e.hash}})},RG=(e,t,n)=>{let r=t>1?` (${t}/${t})`.length:0;if(e.length+r>2e3)throw k(`The message (-m) is ${e.length} characters long; the push stages ${t} changes, each message suffixed (n/${t}), so it holds at most ${2e3-r}.`,n)},kG=(e,t,n)=>{let r=e?.changeCount??0;if(r+t>Ue)throw new f(`The push needs ${P(t,"change")} and your draft of ${n} holds ${r} of the ${Ue} a draft can. Nothing was staged.`,{exitCode:b.Validation,type:"draft-change-cap",hint:"Commit the draft first ('modeldesk draft commit', or in the app).",details:{changes:t,changeCount:r,limit:Ue}})},vG=async e=>{let t=Js(e),{dir:n}=t,{state:r}=t,{dryRun:o}=e.globals,{message:s,plan:i,commit:a}=e.flags,d=`modeldesk ${e.commandName} --help`;yG(e,d);let l=r.model.id,c=be(e.instance(),{kind:"model",modelId:l}),m=await Xs(e,n,r),p=g(m.model.name),h=bo(m),u=Vd(n,r,m);if(u.kind==="stale")throw wG(r,m,pt(h,p));let y=u.kind==="rebound"?{from:u.from}:void 0;y&&!o&&(r=zd(n,r,m));let w=bG(m,a);a&&await EG(e,m,l,p);let E=zt(m.read),I=Mn(n,r),v=Wd(E,I,{modelId:l,baseCommitId:m.head});CG(v,i),w.push(...v.warnings),w.forEach(C=>e.warn(C));let $=v.chunks.length;return RG(s,$,d),kG(m.draft,$,p),{context:e,dir:n,modelId:l,state:r,target:m,name:p,workspace:I,plan:v,deletes:v.ops.flatMap(C=>C.op==="delete"?[C.element]:[]),base:{model:m.model,ref:h,dir:n,message:s,baseCommitId:m.head,...y&&{rebound:y},planHash:v.hash,ops:v.ops,counts:Hd(v.ops),labels:Bd(v.ops,E.labels),warnings:w,url:c}}},nT=({context:e,deletes:t})=>t.length>0&&!e.flags["allow-delete"],IG=async(e,t)=>{let{context:n,modelId:r,target:o,plan:s,base:i}=e,a=Q$(t);if(t.number>1&&t.dependsOn.length>0)return{...a,validation:"client-checked"};let d={actions:t.actions,draftHeadId:o.head,changeRequestId:Er(n.origin),message:Z$(i.message,t,s.chunks.length),dryRun:!0,...o.draft===void 0?{branchId:o.branch.id}:{}};try{let{envelope:l}=await n.api().drafts.model.stage(r,d);return{...a,validation:"server",verdict:"valid",affected:{changed:Object.keys(l.revisions).sort(),removed:l.removedElementIds??[]}}}catch(l){if(l instanceof f&&l.type==="change-validation-failed")return{...a,validation:"server",verdict:"refused",errors:tT(l)};throw l}},SG=async e=>{let{target:t,plan:n,base:r}=e,o=[];for(let a of n.chunks)o.push(await IG(e,a));let s=o.some(a=>a.verdict==="refused");return{result:{...r,dryRun:!0,headCommitId:t.head,chunks:o,staged:0},...(s||nT(e))&&{exitCode:b.Validation}}},$G=e=>new f(`The workspace deletes ${P(e.length,"element")} (${e.slice(0,5).join(", ")}${e.length>5?", \u2026":""}), and a push deletes only with --allow-delete. Nothing was staged.`,{exitCode:b.Validation,type:"deletes-not-allowed",hint:"Review them with 'modeldesk model diff'; restore a file removed by mistake, or pass --allow-delete.",details:{deletes:e}}),TG=({dir:e,plan:t,workspace:n},r)=>(o,s)=>{let{landed:i}=r,a=t.chunks.length,d=t.chunks[s];i.push({number:d.number,changeRequestId:o.chunk.changeRequestId,commitId:o.commitId});let l=fS(e,mG(d,t,n));if(l.length>0)throw X$(d,a,i,r.recorded.baseCommitId,`the ids of ${P(l.length,"new element")} could not be written into the files (${H(l[0].location.file)}: ${l[0].reason})`,{missing:l.map(m=>({file:m.location.file,at:Tt(m.location.path),id:m.id,reason:m.reason}))});let c={...r.recorded,baseCommitId:o.commitId,baseRootRevision:o.envelope?.rootElement.revisionId};try{On(e,c)}catch(m){throw X$(d,a,i,r.recorded.baseCommitId,`workspace.json could not be written (${H(m.message)})`,{})}r.recorded=c},xG=async(e,t)=>{let{context:n,target:r,plan:o,base:s}=e,i=o.chunks.length,a=n.flags["request-id"],d=a===void 0?"":` with --request-id ${a}`;try{return await pa(n,r,{chunks:o.chunks.map(l=>({actions:l.actions,message:Z$(s.message,l,i),changeRequestId:gG(a,o.hash,{number:l.number,total:i},n.origin)})),stableIds:!1,persisted:TG(e,t),retryHint:`Run 'modeldesk model diff': a stale workspace means it landed (re-pull, then push what is left); otherwise push again${d}.`})}catch(l){throw hG(l,r.model.id)}},AG=async(e,t,n)=>{let{context:r,dir:o,modelId:s,target:i,name:a,base:d}=e;if(t.draftId===void 0)throw new f(`Your draft of ${a} holds no staged change, so there is nothing to commit.`,{type:"nothing-to-commit"});let l=await jo(r,s),{landing:c,recovered:m}=await Wr(r,l,{id:t.draftId,targetRefId:i.branch.id,baselineCommitId:i.draft?.baselineCommitId??i.head},{message:d.message,expectedDraftHeadId:t.head}),p=c.commit.id;n.recorded={...n.recorded,baseCommitId:p},On(o,n.recorded);let h=Br(c,i.model),u={...Hr(c),recovered:m,...h===void 0?{}:{next:h},url:be(r.instance(),{kind:"commit",modelId:s,commitId:c.commit.id})};return{headNow:p,commit:u}},OG=(e,t,n)=>{try{return Kt(zt(e.read),Lf(t,n)).ops.length>0}catch{return!0}},MG=(e,t,n,r,o)=>{let s=Jd(n.read),i=r.format==="json"?ll(s):dl(s),a=Ld(t,i,o);return a.collisions.length===0?(_d(t,i,a),{manifest:Us(i),refreshed:!0}):(e.warn(`The files stay as pushed: rewriting them from the server would overwrite files the workspace did not write (${a.collisions.slice(0,3).map(H).join(", ")}).`),{manifest:o,refreshed:!1})},NG=async(e,t,n)=>{let{context:r,dir:o}=e,{recorded:s}=t,i=await Xs(r,o,s);if(i.head!==n)return r.warn("The target moved right after the push, so the files stay as pushed; re-pull before editing on."),!1;let a=Df(o,s),d={manifest:Us(a),refreshed:!1};return OG(i,a,s.format)&&(d=MG(r,o,i,s,d.manifest)),On(o,{...s,files:d.manifest,baseRootRevision:wr(i)}),d.refreshed},PG=async e=>{let{context:t,state:n,plan:r,base:o}=e;if(nT(e))throw $G(e.deletes);let s={recorded:n,landed:[]},i=await xG(e,s),a=i.head,d=i.chunks.map((u,y)=>({...Q$(r.chunks[y]),changeRequestId:u.chunk.changeRequestId,commitId:u.commitId})),l;t.flags.commit&&({headNow:a,commit:l}=await AG(e,i,s));let m=(s.landed.length>0||l!==void 0)&&await NG(e,s,a),p=Object.fromEntries(r.ids);return{result:{...o,headCommitId:a,chunks:d,staged:s.landed.length,...Object.keys(p).length>0&&{createdIds:p},...l&&{commit:l},...m&&{refreshed:m}}}},DG=e=>oe(async()=>{let t=await vG(e);return e.globals.dryRun?SG(t):PG(t)}),LG=e=>e.validation==="client-checked"?`client-checked: it stands on change ${(e.dependsOn??[]).join(", ")} (an element it creates, updates, moves or deletes, or a list it changes that this change places into), which a dry run does not keep, so the server validates it when it is staged`:e.verdict==="valid"?`validated by the server: ${e.affected?.changed.length??0} element(s) changed, ${e.affected?.removed.length??0} removed`:`REFUSED by the server: ${(e.errors??[]).map(t=>g(t.message)).join("; ")}`,_G=(e,t)=>{let n=[`Plan against ${pt(e.ref,t)} at ${e.baseCommitId}: `+(e.ops.length===0?"nothing to push.":`${P(e.ops.length,"operation")} (${zs(e.counts)}) in ${P(e.chunks.length,"change")}.`)],r=Ud(e.ops,e.labels);for(let o of e.chunks){let s=e.chunks.length>1?`Change ${o.number}/${e.chunks.length}`:"The change";n.push(`${s} (${P(o.actions,"action")}): ${LG(o)}.`,...r.slice(o.firstOp,o.firstOp+o.opCount).map(i=>` ${i}`))}return e.ops.length>0&&(n.push(`plan: ${e.planHash}`),e.counts.delete>0&&n.push("The plan deletes; push it with --allow-delete."),n.push(`Push exactly this plan: modeldesk model push ${H(e.dir)} -m <message> --plan ${e.planHash.slice(0,16)}`+(e.counts.delete>0?" --allow-delete":""))),n.join(`
264
+ `)},jG=e=>{let t=g(e.model.name);if(e.dryRun)return _G(e,t);let n=[];return e.rebound&&n.push(Kd(e.ref,t,e.rebound.from,e.baseCommitId)),e.staged===0&&e.commit===void 0?n.push(`Nothing to push: the workspace matches ${pt(e.ref,t)}.`):e.staged>0&&n.push(`Staged ${P(e.staged,"change")} (${zs(e.counts)}) in your draft of ${t}: ${g(e.message)}`,...e.chunks.map(r=>` change ${r.number}/${e.chunks.length}: ${r.commitId} (${P(r.actions,"action")})`)),e.commit?n.push(...nr(e.commit)):e.staged>0&&n.push("Review and commit it in the app, where the changes panel shows it."),(e.staged>0||e.commit)&&n.push(`Workspace base: ${e.headCommitId}${e.refreshed?" (files refreshed from the server)":""}.`),n.push(`url: ${e.url}`),n.join(`
265
+ `)},rT=J({path:["model","push"],effect:"stage",escalate:{flag:"commit",to:"land-draft"},summary:"Stage a workspace's changes on your draft",description:"Stages what 'modeldesk model diff' shows on your draft on the workspace's branch (opening the draft there when you hold none), as validated changes carrying the message, cut into as many changes as the server bounds need (1000 actions or 8 MiB each), each message suffixed (n/m). A workspace whose target moved since it was pulled is refused (exit 5) before anything is written. --dry-run has the server validate each change without keeping it and prints the plan with its hash; --plan <hash> then pushes only that exact plan. After each change lands the workspace records it (new ids written into the files, the base moved on), so a push stopped by a refusal leaves a workspace whose diff shows only what is left. Deletes need --allow-delete. --commit then lands the draft as one commit, under the same rules as draft commit.",positionals:[wo],flags:{...Bi,plan:{type:"string",placeholder:"hash",description:"Push only if the plan hash (or at least its first 12 characters) still matches."},"allow-delete":{type:"boolean",description:"Allow the push to delete the elements the workspace dropped."},"request-id":{type:"string",placeholder:"id",description:"The request id to stage under: a cli-\u2026 id this session minted is sent as given, any other id seeds a cli-\u2026 id derived from it (for each change of a push of several, from it and the change number). Derived from the plan hash when left out. Unlike on an el write it is not looked up: a change that landed leaves the workspace stale, which is what stops a push staging it twice."},commit:{type:"boolean",description:"Land the draft after staging, with the same message. Under an agent host this is left to a person (exit 6) unless MODELDESK_ALLOW_COMMIT=1 or the draft aims at a branch named agent/<topic>."},...hm},dryRun:!0,prepare:Gd,examples:['modeldesk model push -m "Add the severity binding" --dry-run','modeldesk model push -m "Add the severity binding" --plan 3f2a9c1e5b7d'],run:DG,render:jG});var mu=10,FG=e=>({id:e.id,name:e.name,commitId:e.commitId,createdAt:e.createdAt,...e.description?{description:e.description}:{}}),oT=e=>e instanceof V&&(e.status===403||e.status===404),sT=e=>({items:e.slice(0,mu).map(FG),truncated:e.length>mu}),qG=async(e,t,n)=>{if(n)try{let r=await e.metamodelModels.versions(t);return sT([...r].sort((o,s)=>Date.parse(s.createdAt)-Date.parse(o.createdAt)))}catch(r){if(!oT(r))throw r}try{return sT((await e.models.versions(t,{limit:mu+1})).items)}catch(r){if(oT(r))return;throw r}},WG=({name:e,pin:t})=>{let n=t?.versionName??t?.versionRef??(t?.commitId?`commit ${t.commitId}`:void 0);return n===void 0?g(e):`${g(e)} (pinned to ${g(n)})`},HG=e=>{if(e===void 0)return"unknown";let t=e.name?` ${e.id}`:"";return`${g(e.name??e.id)} (${e.type.toLowerCase()}${t})`},iT=(e,t)=>{let n=t.items.map(o=>{let s=o.pin?.versionRef??(o.pin?"@HEAD":void 0),i=o.pin?.versionName&&o.pin.versionName!==s?` (release ${o.pin.versionName})`:"";return[g(o.name),o.kind.toLowerCase(),s?g(`pinned ${s}${i}`):"",o.modelId??""]}),r=[...W(n,{indent:" "}),...t.hiddenCount>0?[` and ${t.hiddenCount} you cannot read`]:[]];return[`${e}:`,...r.length===0?[" none"]:r]},BG=e=>e.kind==="draft"?e.branch:e.kind==="branch"?e:void 0,UG=({latest:e,changesSinceRelease:t,changesCapped:n})=>{let r=`${t}${n?"+":""} change${t===1?"":"s"}`;return e?`${e.name} (${e.createdAt}), ${r} since`:`none yet, ${r} so far`},GG=(e,t)=>e===void 0?[" not readable with your access"]:t.length===0?[" none"]:W(t,{indent:" "}),VG=e=>{let{head:t}=e.branch,n=t.message?`: ${t.message}`:"",{overview:r}=e,o=[["id:",e.id],["kind:",e.kind],...e.metamodel===void 0?[]:[["metamodel:",WG(e.metamodel)]],["owner:",HG(e.owner)],["branch:",`${g(e.branch.name)} at ${t.id}`],["head:",g(`${t.createdAt} by ${t.author.name??t.author.id}${n}`)],["release:",UG(r.release)],...r.instanceModelCount===void 0?[]:[["instances:",`${r.instanceModelCount} models`]],["url:",e.url]],s=r.signals.map(a=>[a.tone,a.code,g(a.subject?.name??""),Object.entries(a.detail).map(([d,l])=>`${d} ${String(l)}`).join(", ")]),i=(e.versions?.items??[]).map(a=>[a.name,a.createdAt,a.commitId]);return[g(e.name),Ae(e.ref,e),...W(o,{indent:" "}),"",`Overview of branch ${g(r.ref.name)}:`,...iT("Depends on",r.dependsOn),...iT("Depended on by",r.dependedOnBy),"Signals:",...s.length===0?[" none"]:W(s,{indent:" "}),"Versions:",...GG(e.versions,i),...e.versions?.truncated?[" (older versions not shown)"]:[]].join(`
266
+ `)},aT=A({path:["model","show"],effect:"read",summary:"Show a model's identity, dependencies and releases",description:"Shows a model's metamodel and its pin, owner, branch head and latest release, the models it depends on and that depend on it (with their pins and staleness signals), and its newest releases. The identity and the head are read at the ref; the overview and the releases are always main's, and the result says so.",positionals:[N(_e)],examples:["modeldesk model show <model>","modeldesk model show <model>@feat/shapes","modeldesk model show <model> --json"],run:async e=>{let t=ie(e,e.args.model.model),n=e.api(),r=await ae(e,e.args.model,_e),{id:o}=r,[s,i,a]=await Promise.all([r.ref.kind==="branch"&&r.ref.branch.main?t.identity():n.models.identity(o,rt(r.ref)),n.models.overview(o),n.accessTokenClaims()]),d=i.instanceModelCount===void 0?"model":"metamodel",l=await qG(n,o,d==="metamodel"&&an(a)),{branch:c}=s,m=le(r),p=BG(m);return{result:{id:s.id,name:s.name,kind:d,...i.metamodel===void 0?{}:{metamodel:{id:i.metamodel.modelId,name:i.metamodel.name,...i.metamodel.pin?{pin:i.metamodel.pin}:{}}},...s.owner?{owner:s.owner}:{},createdAt:s.createdAt,updatedAt:s.updatedAt,ref:m,branch:{id:p?.id??c.id,name:p?.name??c.name,head:{id:c.head.id,createdAt:c.head.createdAt,author:c.head.createdBy,...c.head.message?{message:c.head.message}:{}}},overview:{ref:{kind:"branch",id:r.main.id,name:r.main.name},release:i.release,dependsOn:i.dependsOn,dependedOnBy:i.dependedOnBy,signals:i.signals,...i.instanceModelCount===void 0?{}:{instanceModelCount:i.instanceModelCount}},...l===void 0?{}:{versions:l},url:e.webUrl({kind:"model",modelId:s.id})}}},render:VG});var YG=e=>e.subtreeAt!==void 0?` [multi-owned, listed under ${g(e.subtreeAt)}]`:e.multiOwned?" [multi-owned]":"",KG=e=>e.map(t=>`${" ".repeat(t.depth-1)}${t.label===void 0?"(no label)":g(t.label)} (${t.type})`+YG(t)),dT=A({path:["model","tree"],effect:"read",summary:"Show a model's element tree",description:"Shows the elements of a model as a tree, one line per element with its label and type. An element owned twice appears under each owner, marked. The platform's internal `@` elements are left out, as in the app, unless --internal is passed. Without a ref, reads your draft while it holds staged changes; --json carries every row's id, its label path (usable wherever an element is addressed) and what was read as ref.",positionals:[N(Nt)],flags:{depth:{type:"number",placeholder:"n",description:"Show this many levels below the model root."},type:{type:"string",placeholder:"type",description:"Show only elements of this type, with their ancestors for context."},...Dr},listing:{narrowHint:"Pass --depth or --type to narrow the tree."},examples:["modeldesk model tree <model> --depth 2","modeldesk model tree <model>@main --type NodeShape --json","modeldesk model tree <model>@feat/shapes"],run:async e=>{let{depth:t,type:n,internal:r}=e.flags;if(t!==void 0&&(!Number.isInteger(t)||t<1))throw k(`--depth must be a positive whole number, got ${t}.`,"modeldesk model tree --help");let{model:o,ref:s,read:i,tree:a}=await Lr(e,e.args.model,Nt),d=n===void 0?void 0:new Set([Ia(oo(i),n,r)]),l=await e.list(ft(a,{maxDepth:t,types:d,internal:r}));return{result:{model:o,ref:s,rootElementId:a.rootId,...l}}},render:e=>[Ae(e.ref,e.model),...e.items.length===0?["No elements."]:KG(e.items)].join(`
267
+ `)});var cl={modelRename:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},before:{type:"string",description:"The name before the change."},after:{type:"string",description:"The name after it, or that it would have on a dry run."},updated:{type:"boolean",description:"False on a dry run, and when the name was already the one asked for. One of false, true."},dryRun:{type:"boolean",description:"One of false, true."},url:{type:"string",description:"The model in the app."}},required:["schemaVersion","model","before","after","updated","dryRun","url"]},modelAccess:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},before:{type:"string",description:'Who could read the model before the change: SHARED for its organization, INDIVIDUAL for its creator alone. One of "INDIVIDUAL", "SHARED".'},after:{type:"string",description:'One of "INDIVIDUAL", "SHARED".'},updated:{type:"boolean",description:"False on a dry run, and when the access mode was already the one asked for. One of false, true."},dryRun:{type:"boolean",description:"One of false, true."},url:{type:"string"}},required:["schemaVersion","model","before","after","updated","dryRun","url"]},modelMetamodel:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},before:{type:"object",properties:{metamodelVersion:{type:"string"},extensions:{type:"array",items:{type:"object",properties:{id:{type:"string"},version:{type:"string"}}}},addOns:{type:"array",items:{type:"object",properties:{id:{type:"string"},version:{type:"string"}}}}}},after:{type:"object",properties:{metamodelVersion:{type:"string"},extensions:{type:"array",items:{type:"object",properties:{id:{type:"string"},version:{type:"string"}}}},addOns:{type:"array",items:{type:"object",properties:{id:{type:"string"},version:{type:"string"}}}}}},blockedBy:{type:"object",properties:{branches:{type:"array",items:{type:"string"}},generatedBranches:{type:"number"}},description:"The side branches by name and the generated branches by count that refuse adding or removing an extension or an add-on; a change of versions alone is never refused by them."},updated:{type:"boolean",description:"False on a dry run. One of false, true."},dryRun:{type:"boolean",description:"One of false, true."},url:{type:"string"}},required:["schemaVersion","model","before","after","blockedBy","updated","dryRun","url"]}};var pu="change",fu={name:"model_update",description:"Changes the model itself, each change landing at once with no draft to review: its name, who may read it (SHARED, its organization; INDIVIDUAL, its creator alone), or the metamodel version and extensions it is written in. It needs the person's 'Act without your review' permission. Call it with dryRun: true first, show the person what it reports, and change only on their word. A model whose catalog record makes it public is renamed, shared or taken down only with their 'Publish' permission."},uu="--dry-run reports the change and makes none.",hu="Under an agent host it is left to a person (exit 6) unless they let the agent commit (MODELDESK_ALLOW_COMMIT=1).",gu=(e,t)=>ie(e,t.model).identity(),yu=(e,t)=>e.webUrl({kind:"model",modelId:t}),cT=A({path:["model","rename"],effect:"land-direct",summary:"Rename a model",description:`Gives the model another name, at once and for everyone who can read it. ${uu} ${hu}`,positionals:[N(de),{name:"name",type:"string",required:!0,description:"The model's new name."}],dryRun:!0,examples:['modeldesk model rename <model> "Shapes 2" --dry-run','modeldesk model rename <model> "Shapes 2"'],mcp:{...fu,choice:{member:pu,value:"name",description:"Rename the model to name."}},resultSchema:cl.modelRename,run:async e=>{let t=e.args.name.trim();if(t==="")throw k("A model needs a name that is not blank.",`modeldesk ${e.commandName} --help`,{reason:"A model needs a name that is not blank."});let n=await gu(e,e.args.model),r=n.name!==t;return!e.dryRun&&r&&await e.api().models.update(n.id,{name:t}),{result:{model:{id:n.id,name:r&&!e.dryRun?t:n.name},before:n.name,after:t,updated:r&&!e.dryRun,dryRun:e.dryRun,url:yu(e,n.id)}}},render:e=>{let t=`${g(e.before)} to ${g(e.after)}`;return e.dryRun?`Would rename model ${t}. Dry run: nothing was changed.`:e.updated?`Renamed model ${t}.`:`Model ${g(e.before)} already has that name.`}}),JG={enum:["shared","individual"]},mT=A({path:["model","access"],effect:"land-direct",summary:"Share a model with its organization, or keep it its creator\u2019s alone",description:`Sets who may read the model: shared, everyone in its organization with a seat; individual, its creator alone. Only the creator changes it. ${uu} ${hu}`,positionals:[N(de),{name:"mode",type:JG,required:!0,description:"shared or individual."}],dryRun:!0,examples:["modeldesk model access <model> shared --dry-run","modeldesk model access <model> shared"],mcp:{...fu,choice:{member:pu,value:"access",description:"Set who may read the model to mode: shared, its organization; individual, its creator alone."}},resultSchema:cl.modelAccess,run:async e=>{let t=e.args.mode==="shared"?"SHARED":"INDIVIDUAL",n=await gu(e,e.args.model),r=n.accessMode??"SHARED",o=n.accessMode!==t;return!e.dryRun&&o&&await e.api().models.update(n.id,{accessMode:t}),{result:{model:{id:n.id,name:n.name},before:r,after:t,updated:o&&!e.dryRun,dryRun:e.dryRun,url:yu(e,n.id)}}},render:e=>{let t=g(e.model.name),n=r=>r==="SHARED"?"shared with its organization":"its creator\u2019s alone";return e.dryRun?`Would make model ${t} ${n(e.after)}. Dry run: nothing was changed.`:e.updated?`Model ${t} is now ${n(e.after)}.`:`Model ${t} is already ${n(e.after)}.`}}),XG=(e,t)=>{let n=e.indexOf("@"),r=n===-1?e:e.slice(0,n),o=n===-1?void 0:e.slice(n+1);if(!B(r)||o==="")throw k(`--extension takes <id>[@<version>], got '${g(e)}'.`,`modeldesk ${t} --help`,{reason:`extension takes <id>[@<version>], got '${g(e)}'.`});return{extensionId:r.toLowerCase(),...o===void 0?{}:{versionName:o}}},lT=e=>({...e.metamodelVersion?{metamodelVersion:e.metamodelVersion}:{},extensions:e.extensionVersions.map(({extensionId:t,versionName:n})=>({id:t,...n===void 0?{}:{version:n}})),addOns:(e.addOnVersions??[]).map(({addOnId:t,versionName:n})=>({id:t,...n===void 0?{}:{version:n}}))}),pT=A({path:["model","metamodel"],effect:"land-direct",summary:"Move a model to another metamodel version or extension set",description:`Pins the model to another version of its metamodel, or to another set of extensions, as one commit on main. What is left out is kept: without --version the version stays, without --extension or --no-extensions the extensions stay, and the add-ons always do. Adding or removing an extension is refused while the model has side branches. ${uu} ${hu}`,positionals:[N(de)],flags:{version:{type:"string",placeholder:"version",description:"The metamodel version to pin."},extension:{type:{list:"string"},placeholder:"id[@version]",description:"An extension to pin, by id, at a version or its current release; once per extension. They replace the extensions pinned now."},"no-extensions":{type:"boolean",description:"Pin no extension."}},dryRun:!0,examples:["modeldesk model metamodel <model> --version 2.0 --dry-run","modeldesk model metamodel <model> --extension <id>@1.1"],mcp:{...fu,choice:{member:pu,value:"metamodel",description:"Pin the metamodel version, the extensions (by id, id@version) or noExtensions; what is left out is kept."}},resultSchema:cl.modelMetamodel,run:async e=>{let{flags:t,commandName:n}=e,r=`modeldesk ${n} --help`;if(t.extension.length>0&&t["no-extensions"])throw k("--extension and --no-extensions exclude each other.",r,{reason:"extension and noExtensions exclude each other."});if(t.version===void 0&&t.extension.length===0&&!t["no-extensions"])throw k("Pass what to change: --version, --extension or --no-extensions.",r,{reason:"Give what to change: version, extension or noExtensions."});let o=await gu(e,e.args.model),s=e.api(),{pin:i,setChangeBlockedBy:a}=await s.models.metamodelPin(o.id),d=t.version??i.metamodelVersion;if(d===void 0||d.trim()==="")throw k("The model pins no metamodel version, so pass one with --version.",r,{reason:"The model pins no metamodel version, so give one as version."});let l=i.extensionVersions;t["no-extensions"]?l=[]:t.extension.length>0&&(l=t.extension.map(p=>XG(p,n)));let c={metamodelVersion:d,extensionVersions:l,addOnVersions:i.addOnVersions};return e.dryRun||await s.models.updateMetamodelPin(o.id,c),{result:{model:{id:o.id,name:o.name},before:lT({metamodelVersion:i.metamodelVersion??"",extensionVersions:i.extensionVersions,addOnVersions:i.addOnVersions}),after:lT(c),blockedBy:a,updated:!e.dryRun,dryRun:e.dryRun,url:yu(e,o.id)}}},render:e=>{let t=r=>{let o=r.extensions.map(({id:s,version:i})=>i?`${s}@${i}`:s);return`version ${r.metamodelVersion??"(none)"}, extensions ${o.length>0?o.join(", "):"(none)"}`},n=`from ${t(e.before)} to ${t(e.after)}`;return e.dryRun?`Would move model ${g(e.model.name)} ${n}. Dry run: nothing was changed.`:`Moved model ${g(e.model.name)} ${n}.`}});import{rmdirSync as QG,rmSync as ZG,writeFileSync as eV}from"node:fs";import{dirname as tV,join as fT,posix as ml}from"node:path";var uT=J({path:["note","add"],effect:"local",summary:"Create an empty note file for an element and add it to the repo's notes.json",description:"Finds the element by name in the last pull's manifest (or by --element), creates an empty note file at the path the next pull reads it from, and records it in .modeldesk/notes.json. A name several elements share is asked about at a terminal and refused elsewhere, listing their ids. The after note of the model or a package needs --heading. Nothing is overwritten, and nothing is written when the command refuses.",positionals:[{name:"name",type:{list:"string"},description:"The element's title; a name of several words may be passed unquoted."}],flags:{slot:{type:{enum:Fe},default:"intro",description:"The slot the note fills: intro, after the element's heading, or after, after its content."},heading:{type:"string",placeholder:"text",description:"The heading the after note of the model or a package comes under (required there)."},dir:{type:"string",placeholder:"dir",description:"The folder to create the note in (default: notesDir in the repo config, or md-notes/)."},element:{type:"string",placeholder:"id",description:"The element's id, which decides when a name is given too."},stack:{type:"string",placeholder:"id",description:"The content stack whose last pull is searched (default: MODELDESK_STACK or the repo config)."}},examples:["modeldesk note add Pand","modeldesk note add Domein Fundering --slot after --heading Afsluiting"],run:async e=>{let{flags:t,args:n}=e,r=nn(e.cwd),{repoRoot:o}=r,s=Oo(jn({stack:t.stack},e.env,r.config).stack,"stack",G.stack,"--stack"),i=t.slot,a=ea(o,s);if(a===void 0)throw new f("Run 'modeldesk bundle pull' first: note add finds the element in the last pull's manifest.");let d=Gw(a),l=await iV(e,a,d,n.name.join(" "),t.element),c=pl(l),m=dV(l,i,c,t.heading),p=Zi(s),h=r.config.notesDir??bi,u=lV(o,p,t.dir??h,l,i),y=fT(o,u),w=sa(o),E=w.entries.get(l.elementId);if(nV(o,w,E,{slot:i,label:c}),rV(w,u),Xn(y)!==void 0){let x=l.path!==void 0&&oa(h,p,l.path,i)===u;throw new f(cV(u,c,i,x))}qt(w.path);let I=sV(y,u,m),v=new Map(w.entries),$=E===void 0?{...l.title===void 0?{}:{name:l.title},[i]:u}:{...E,[i]:u};v.set(l.elementId,$);try{ia(w.path,Jr(v))}catch(x){throw ZG(y,{force:!0}),I(),x instanceof f?x:new f(`Could not write ${w.path}, so ${u} was not kept: ${Ge(x)}`)}return{result:{file:u,slot:i,elementId:l.elementId,...l.title===void 0?{}:{name:l.title},label:c,...m===void 0?{}:{heading:m}}}},render:({file:e,slot:t,label:n,heading:r})=>{let o=r===void 0?"":`, under the heading "${r}"`;return`Created ${e}, the ${t} note of ${n}${o}.`}}),nV=(e,t,n,{slot:r,label:o})=>{let s=n?.[r];if(s===void 0)return;let i=Xn(fT(e,s))===void 0?"That file does not exist yet: create it":"Write in that file";throw new f(`${o} already has an ${r} note, ${s}. ${i}, or take the entry out of ${t.path} first.`)},rV=(e,t)=>{let n=[...e.entries].find(([,r])=>Fe.some(o=>r[o]!==void 0&&ml.normalize(r[o])===ml.normalize(t)));if(n!==void 0)throw new f(`${e.path} already names ${t} as a note of ${n[1].name??n[0]}; pick another folder with --dir.`)},oV=e=>{for(let t of e.toReversed())try{QG(t)}catch{return}},sV=(e,t,n)=>{let r;try{r=Xd(tV(e))}catch(s){throw new f(`Could not create ${ml.dirname(t)}: ${Ge(s)}`)}let o=()=>oV(r);try{eV(e,n===void 0?"":`${aa(n)}
256
268
 
257
- `,{flag:"wx"})}catch(o){throw s(),new p(`Could not create ${t}: ${et(o)}`)}return s},ad=e=>{let t=e.kind===void 0?"":` (${e.kind})`;return e.title===void 0?`${e.elementId}${t}`:`${e.title}${t}`},TF=async(e,t,n,r,s)=>{if(s!==void 0)return OF(e,t,n,r,s);if(r.trim()==="")throw new p("Name the element: modeldesk note add <name>, or pass --element <id>.");let o=Hl(n,r);if(o.length===1)return o[0];if(o.length===0){let a=sy(Ul(t),r);if(a.length>0)throw new p(`"${r.trim()}" is ${nS(a)}; anchor-level parts carry no note slots.`);let d=oy(n,r),l=d.map(m=>`"${m}"`).join(", "),c=d.length===0?"":` Did you mean ${l}?`;throw new p(`No element in the last pull's manifest is named "${r.trim()}".${c}`)}if(e.interactive){e.io.err(`Several elements are named "${r.trim()}":
258
- `);let a=o.map((l,c)=>[`${c+1}.`,ad(l),l.path??""]);e.io.err(`${j(a,{indent:" "}).join(`
269
+ `,{flag:"wx"})}catch(s){throw o(),new f(`Could not create ${t}: ${Ge(s)}`)}return o},pl=e=>{let t=e.kind===void 0?"":` (${e.kind})`;return e.title===void 0?`${e.elementId}${t}`:`${e.title}${t}`},iV=async(e,t,n,r,o)=>{if(o!==void 0)return aV(e,t,n,r,o);if(r.trim()==="")throw new f("Name the element: modeldesk note add <name>, or pass --element <id>.");let s=Yc(n,r);if(s.length===1)return s[0];if(s.length===0){let a=Vw(Vc(t),r);if(a.length>0)throw new f(`"${r.trim()}" is ${hT(a)}; anchor-level parts carry no note slots.`);let d=Yw(n,r),l=d.map(m=>`"${m}"`).join(", "),c=d.length===0?"":` Did you mean ${l}?`;throw new f(`No element in the last pull's manifest is named "${r.trim()}".${c}`)}if(e.interactive){e.io.err(`Several elements are named "${r.trim()}":
270
+ `);let a=s.map((l,c)=>[`${c+1}.`,pl(l),l.path??""]);e.io.err(`${W(a,{indent:" "}).join(`
259
271
  `)}
260
- `);let d=await e.choose("Which one?",o.length);if(d===void 0)throw new p("No element chosen, so nothing was created.");return o[d]}let i=o.map(a=>[a.elementId,ad(a),a.path??""]);throw new p(`Several elements in the last pull's manifest are named "${r.trim()}"; pass --element <id> to pick one:
261
- `+j(i,{indent:" "}).join(`
262
- `))},OF=(e,t,n,r,s)=>{let o=s.trim().toLowerCase();if(o==="")throw new p("--element is blank; give the id of the element the note is for.");let i=n.find(a=>a.elementId===o);if(i===void 0){let a=Ul(t).filter(d=>d.elementId===o);throw a.length>0?new p(`${s.trim()} is ${nS(a)}; anchor-level parts carry no note slots.`):new p(`The last pull's manifest has no element ${s.trim()}. Run 'modeldesk bundle pull' if the model changed since.`)}return r.trim()!==""&&Hl([i],r).length===0&&e.io.err(`note: --element picks ${ad(i)}, so the name "${r.trim()}" was ignored.
263
- `),i},nS=e=>{let t=e.map(n=>{let r=/^[aeiou]/i.test(n.kind)?"an":"a";return n.owner===void 0?`${r} ${n.kind}`:`${r} ${n.kind} inside ${n.owner}`});return[...new Set(t)].join(" or ")},NF=(e,t,n,r)=>{if(t==="after"&&e.container){if(e.anchor===void 0)throw new p(`The last pull's manifest gives ${n} no anchor to build its after heading's id from, so a note there cannot be placed.`);if(r===void 0)throw new p(`The after note of ${n} comes under a heading of its own; pass --heading <text>.`);let s=gs(r);if(s!==void 0)throw new p(`--heading ${s}; give the text of the heading the note comes under on one line.`);return r.trim()}if(r!==void 0)throw new p(`--heading is only for the after note of the model or a package; the ${t} note of ${n} takes none.`)},LF=(e,t,n,r,s)=>{let o=li(n,t)??Vl(e,n);if(o!==void 0)throw new p(`${o[0].toUpperCase()}${o.slice(1)}.`);let a=(r.path===void 0?void 0:ci(n,t,r.path,s))??id.join(n,`${vn(r.title??"")||r.elementId}${s==="after"?".after":""}.md`),[d]=Xl(e,t,a);if(d!==void 0)throw new p(`${d[0].toUpperCase()}${d.slice(1)}. Pick another folder with --dir, or "notesDir" in .modeldesk/config.json.`);return a},PF=(e,t,n,r)=>r?`${e} already exists, and note add never overwrites a file. The next pull places it as the ${n} note of ${t}; write in it.`:`${e} already exists, and note add never overwrites a file; pick another folder with --dir.`;var Gf="daaddd57-d61e-41e2-8751-19497881b8b2",DF="@element",_F=[["@metamodel","metamodel"],["@metamodelExtensions","extension"]],qr=(e,t)=>{let n=e?.attributes?.[t]?.[0];return typeof n=="string"&&n!==""?n:void 0},rS=(e,t)=>Object.values(e?.relations?.[t]??{}).flatMap(n=>n.map(r=>r.id)),sS=e=>e.rootElementId===void 0?void 0:e.elements[e.rootElementId],dd=e=>{let t=sS(e);return _F.flatMap(([n,r])=>rS(t,n).flatMap(s=>{let o=e.elements[s],i=qr(o,"@modelId");if(i===void 0)return[];let a=qr(o,"@commitId"),d=qr(o,"@version");return[{role:r,modelId:i,...a?{commitId:a}:{},...d?{version:d}:{}}]}))},ld=e=>{let[t]=rS(sS(e),DF);return t===void 0?void 0:qr(e.elements[t],"standardVersion")},oS=e=>Object.values(e.elements).flatMap(t=>{if(t.type!=="@ManagedDependency")return[];let n=qr(t,"@sourceMetamodelId"),r=qr(t,"@commitId");return n&&r?[{sourceMetamodelId:n,commitId:r}]:[]});var Br=e=>({id:e.id,name:e.name,commitId:e.commitId,createdAt:e.createdAt,...e.description?{description:e.description}:{}}),Un=e=>{let t=e.compiledMetamodel?.standardVersion??e.compiledExtension?.standardVersion,n=e.builtInElementModelCommitId;return{...Br(e),...t?{standardVersion:t}:{},...n?{builtInCommitId:n}:{}}},pt=async(e,t)=>Vf((await e.metamodelModels.versions(t)).map(Un));var Wr=async(e,t,n)=>{let r;for(;;){let{items:s}=await e.models.versions(t,{limit:100,cursor:r}),o=s.find(a=>a.name===n);if(o!==void 0)return o.commitId;let i=s.at(-1)?.id;if(s.length<100||i===void 0||i===r)return null;r=i}},Vf=e=>[...e].sort((t,n)=>Date.parse(n.createdAt)-Date.parse(t.createdAt)||n.name.localeCompare(t.name)),cd=(e,t)=>e.find(n=>t===void 0?n.standardVersion===void 0:n.name===t);var J=e=>e?e.slice(0,8):"none",md=(e,t)=>new p(e.reason,{exitCode:e.exitCode,hint:t,type:e.type,requestId:e.requestId,details:e.details});var iS="super-admin-required",jF=e=>{let t;return()=>t??=e()},aS=new WeakMap,Ze=(e,t)=>{let n=aS.get(e)??new Map;aS.set(e,n);let r=n.get(t);if(r!==void 0)return r;let s=oe(e,t),o=jF(async()=>{try{return{overview:await e.api().models.overview(await s.id())}}catch(d){if(d instanceof H&&d.status===403)return{refusal:d};throw d}}),i=async()=>{let d=await o();if("refusal"in d)throw d.refusal;return d.overview},a={model:s,overview:i,overviewIfReadable:async()=>{let d=await o();return"overview"in d?d.overview:void 0},isMetamodelModel:async()=>(await i()).metamodel?.modelId===Gf};return n.set(t,a),a},FF=(e,t)=>Ie(e.env)?new p(`'${e.commandName}' on the metamodel-model '${t}' needs an interactive super-admin login: no /metamodel-models route is open to a service account, so CI cannot release, re-pin or plan metamodels. Nothing was changed.`,{exitCode:b.NeedsHuman,type:iS,hint:"Run it from a terminal logged in as a super-admin ('modeldesk auth login')."}):new p(`'${e.commandName}' on the metamodel-model '${t}' needs a super-admin: only a super-admin may call the /metamodel-models routes that release and pin metamodels. Nothing was changed.`,{exitCode:b.NeedsHuman,type:iS,hint:"Ask a super-admin to run it, or log in as one with 'modeldesk auth login'."}),ht=async(e,t,n={})=>{if(qt(await e.api().accessTokenClaims()))return;let r=Ze(e,t);if((n.readsOnly?await r.overviewIfReadable():await r.overview())?.metamodel?.modelId===Gf)throw FF(e,t)};var Ne="@HEAD",qF=e=>e.kind==="pin"||e.kind==="base-pin",dS=e=>e.models.flatMap(t=>t.steps),Yf=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),BF=e=>{let t=e.hiddenDependents.filter(({count:s})=>s>0);if(t.length===0)return;let n=t.reduce((s,{count:o})=>s+o,0),r=t.map(({modelId:s,count:o})=>`${o} of ${e.models[s]?.name??s}`);throw new p(`${P(n,"model")} depending on the cascade's metamodels ${n===1?"is":"are"} hidden from you (${r.join(", ")}), so the cascade cannot plan ${n===1?"its":"their"} pins. Nothing was changed.`,{hint:"Run the cascade as a super-admin, who can read every metamodel-model.",details:{hiddenDependents:t}})},WF=e=>{let t=new Map(Object.keys(e.models).map(n=>[n,new Set]));for(let{modelId:n,targetId:r}of[...e.edges,...e.basePins])n!==r&&e.models[r]!==void 0&&t.get(n)?.add(r);return t},UF=(e,t,n)=>{let r=a=>[...a].map(d=>e.models[d]).sort(Yf)[0].id,s=[],o=new Map,i=r(n);for(;!o.has(i);)o.set(i,s.length),s.push(i),i=r([...t.get(i)??[]].filter(a=>n.has(a)));return[...s.slice(o.get(i)),i].map(a=>e.models[a].name)},HF=e=>{let t=WF(e),n=new Map([...t].map(([o,i])=>[o,new Set(i)])),r=[],s=()=>[...n].filter(([,o])=>o.size===0).map(([o])=>e.models[o]).sort(Yf).map(o=>o.id);for(let o=s();o.length>0;o=s()){let[i]=o;r.push(i),n.delete(i),n.forEach(a=>a.delete(i))}if(n.size>0){let o=UF(e,t,new Set(n.keys()));throw new p(`The metamodels depend on each other in a cycle, so there is no order to release them in: ${o.join(" \u2192 ")} (each depends on the next). Nothing was changed.`,{hint:"Remove one of the dependencies in the app, then run the cascade again.",details:{cycle:o}})}return r},Kf=(e,t,n,r)=>e?t:n!==r?"stale":void 0,lS=e=>{BF(e);let t=HF(e),n=u=>e.models[u],r=new Set,s=new Map,o=[],i=0,a=(u,h,y)=>{if(y===Ne)return Kf(r.has(h.id),"target-moves",u.commitId,h.headCommitId);if(s.has(h.id)&&s.get(h.id)===y)return r.has(h.id)||u.commitId!==h.headCommitId?"release-moves":void 0;let k=h.releases.find(S=>S.name===y);return k===void 0?"unresolved":u.commitId!==k.commitId?"stale":void 0},d=(u,h)=>{let y=n(u.targetId),k=u.versionRef??Ne,S=a(u,y,k);if(S==="unresolved"){o.push({modelId:h.id,modelName:h.name,dependencyId:u.dependencyId,name:u.name,targetId:y.id,targetName:y.name,versionRef:k});return}let I={dependencyId:u.dependencyId,targetId:y.id,targetName:y.name,...u.newerRelease?{newerRelease:u.newerRelease}:{}};return S===void 0?{kind:"pin",name:u.name,...u.versionRef===void 0?{}:{versionRef:u.versionRef},commitId:u.commitId,...I}:{kind:"refresh-pin",step:++i,modelId:h.id,modelName:h.name,dependencyName:u.name,versionRef:k,legacy:u.versionRef===void 0,fromCommitId:u.commitId,reason:S,...I}},l=(u,h)=>{let y=n(u.targetId),k=Kf(r.has(y.id),"base-moves",u.commitId,y.headCommitId);return k===void 0?{kind:"base-pin",dependencyId:u.dependencyId,name:y.name,targetId:y.id,targetName:y.name,commitId:u.commitId}:{kind:"refresh-base-pin",step:++i,modelId:h.id,modelName:h.name,dependencyId:u.dependencyId,baseId:y.id,baseName:y.name,fromCommitId:u.commitId,reason:k}},c=u=>{let h=r.has(u.id);if(!u.released||!h&&u.outdated===void 0)return;let y=cd(u.releases,u.standardVersion);return s.set(u.id,y?.name??u.standardVersion),{kind:"re-release",step:++i,modelId:u.id,modelName:u.name,...u.standardVersion?{release:u.standardVersion}:{},inPlace:y!==void 0,...y?{releaseId:y.id,releaseName:y.name,fromCommitId:y.commitId,...y.builtInCommitId?{fromBuiltInCommitId:y.builtInCommitId}:{},...y.description?{description:y.description}:{}}:{},reason:h?"pins-move":"outdated",...u.outdated?{outdated:u.outdated}:{},...u.outdated==="SOURCE"||u.outdated==="BOTH"?{unreleasedEdits:!0}:{},...u.instanceModelCount===void 0?{}:{instanceModelCount:u.instanceModelCount}}},m=t.map(u=>{let h=n(u),y=[],k=[],S=x=>{x!==void 0&&(qF(x)?k.push(x):(y.push(x),r.add(u)))};e.edges.filter(x=>x.modelId===u&&e.models[x.targetId]!==void 0).sort((x,E)=>Yf({name:x.name,id:x.dependencyId},{name:E.name,id:E.dependencyId})).forEach(x=>S(d(x,h))),e.basePins.filter(x=>x.modelId===u&&e.models[x.targetId]!==void 0).forEach(x=>S(l(x,h)));let I=c(h);return I!==void 0&&y.push(I),{id:u,name:h.name,role:h.role,...h.baseId?{baseId:h.baseId}:{},released:h.released,steps:y,current:k,...h.outdated?{outdated:h.outdated}:{},...h.instanceModelCount===void 0?{}:{instanceModelCount:h.instanceModelCount}}}),f=e.siblingPins.flatMap(u=>{let h=e.models[u.targetId],y=e.models[u.modelId];if(h===void 0||y===void 0)return[];let k=Kf(r.has(h.id),"target-moves",u.commitId,h.headCommitId);return k===void 0?[]:[{modelId:y.id,modelName:y.name,dependencyId:u.dependencyId,targetId:h.id,targetName:h.name,commitId:u.commitId,reason:k}]}),g=n(e.baseId);return{base:{id:g.id,name:g.name},models:m,stepCount:i,staleSiblingPins:f,unresolvedPins:o,outsideDependents:e.outsideDependents.map(u=>({...u,targetName:e.models[u.targetId]?.name??u.targetId}))}};var zf=e=>e===void 0||e===Ne,cS=e=>{let t=[];return zf(e.versionRef)?e.targetHeadCommitId!==void 0&&e.targetHeadCommitId!==e.commitId&&t.push("head-moved"):(e.newerRelease!==void 0&&t.push("newer-release"),e.releaseCommitId===null?t.push("release-missing"):e.releaseCommitId!==void 0&&e.releaseCommitId!==e.commitId&&t.push("release-moved")),{standing:t.length===0?"current":"behind",reasons:t}};var GF=e=>new Map((e?.signals??[]).flatMap(t=>t.code==="DEPENDENCY_MOVED_ON"&&t.subject&&typeof t.detail.latestVersion=="string"?[[t.subject.modelId,t.detail.latestVersion]]:[])),VF=(e,t)=>{let n=new Map([...e.metamodel?[[e.metamodel.id,e.metamodel.name]]:[],...(e.metamodelExtensions??[]).map(r=>[r.id,r.name]),...t?.metamodel?[[t.metamodel.modelId,t.metamodel.name]]:[]]);return dd(e).map(r=>{let s=n.get(r.modelId)??r.modelId;return{kind:r.role,name:s,target:{id:r.modelId,name:s},...r.commitId?{commitId:r.commitId}:{},...r.version?{release:r.version}:{},settable:!1}})},KF=async(e,t,n,r)=>{let s=zf(t.versionRef),[o,i]=await Promise.all([s?e.models.identity(t.modelId).then(c=>c.branch.head.id):void 0,s||t.versionRef===void 0?void 0:Wr(e,t.modelId,t.versionRef)]),a=s?void 0:r.get(t.modelId),{standing:d,reasons:l}=cS({versionRef:t.versionRef,commitId:t.commitId,...o===void 0?{}:{targetHeadCommitId:o},...i===void 0?{}:{releaseCommitId:i},...a===void 0?{}:{newerRelease:a}});return{kind:"internal",name:t.name,dependencyId:t.id,target:{id:t.modelId,...n?{name:n}:{}},versionRef:t.versionRef??null,commitId:t.commitId,...s?{}:{release:t.versionRef},settable:!0,standing:d,...l.length>0?{reasons:l}:{},...a?{latestRelease:a}:{}}},YF=async(e,t,n)=>{let r=new Map((n?.dependsOn.items??[]).flatMap(i=>i.modelId?[[i.modelId,i.name]]:[])),s=GF(n),o=t.filter(i=>!i.transitive);return Promise.all(o.map(async i=>{switch(i.type){case"EXTERNAL":return{kind:"external",name:i.name,dependencyId:i.id,location:i.location,settable:!1};case"MANAGED":return{kind:"managed",name:i.name,dependencyId:i.id,target:{id:i.modelId},commitId:i.commitId,source:{metamodelId:i.sourceMetamodelId,version:i.sourceMetamodelVersion},settable:!1};case"INTERNAL":return KF(e,i,r.get(i.modelId),s)}}))},zF={"newer-release":"newer release","release-moved":"release re-released","release-missing":"release gone","head-moved":"head moved"},JF=e=>e.kind!=="internal"?"":e.versionRef===null?"@HEAD (legacy)":w(e.versionRef??""),XF=e=>e.standing===void 0?"read-only":e.standing==="current"?"current":`behind (${(e.reasons??[]).map(n=>n==="newer-release"&&e.latestRelease?`newer release ${w(e.latestRelease)}`:zF[n]).join(", ")})`,QF=["ID","KIND","NAME","TARGET","SELECTOR","COMMIT","RELEASE","STANDING"],mS=O({path:["pin","list"],effect:"read",summary:"List a model's pins and whether each is behind",description:"Lists the model's metamodel and extension pins and its direct dependencies: the id pin set takes, name, target, selector (@HEAD, a version name, or @HEAD (legacy) on an edge that predates selectors), commit, release and standing. A version pin is behind when a newer release exists or its release was re-released in place; a @HEAD pin is behind when the target's head moved past it. Managed, external, metamodel and extension pins are read-only here.",positionals:[_(fe)],listing:{},examples:["modeldesk pin list <model>","modeldesk pin list <model> --json"],run:async e=>{await ht(e,e.args.model.model,{readsOnly:!0});let t=Ze(e,e.args.model.model),n=e.api(),r=await t.model.id(),[s,o,i,a]=await Promise.all([t.model.identity(),t.overviewIfReadable(),n.dependencies.list(r),n.models.get(r)]),d=[...VF(a,o),...await YF(n,i.items,o)];return{result:{model:{id:s.id,name:s.name},newerReleaseChecked:o!==void 0,...await e.list(d)}}},render:e=>{let t=e.items.map(n=>[n.dependencyId??"",n.kind,w(n.name),w(n.target?.name??n.target?.id??n.location??""),JF(n),n.commitId?J(n.commitId):"",w(n.release??""),XF(n)]);return[`Pins of ${w(e.model.name)}:`,...t.length===0?["No pins."]:j([QF,...t]),...e.newerReleaseChecked?[]:["Newer releases were not checked: your access does not reach the model's overview."]].join(`
264
- `)}});var ZF=(e,t)=>e.filter(n=>n.id.toLowerCase()===t||"modelId"in n&&n.modelId?.toLowerCase()===t),eq=(e,t)=>{let n=`'${w(e.name)}'`;if(e.type==="MANAGED")throw new p(`${n} is a managed dependency of ${t}: built-in elements its metamodel supplies, pinned through the metamodel version, which pin set does not change.`,{hint:"Change the model's metamodel version in the app's model settings."});if(e.type==="EXTERNAL")throw new p(`${n} is an external document, not a model, so it has no version to pin.`);if(e.transitive){let r=(e.providedVia??[]).map(o=>`'${w(o.name)}'`),s=r.length?`, brought in by ${r.join(", ")}`:"";throw new p(`${n} is a transitive dependency of ${t}${s}: it follows the dependency that provides it.`,{hint:"Pin the direct dependency that provides it instead."})}},tq=(e,t,n)=>{let r=ZF(e,t);if(r.length===0)throw new p(`${n.name} has no dependency with the id '${t}'.`,{exitCode:b.NotFound,hint:`Run 'modeldesk pin list ${n.address}' to see its dependencies.`});if(r.length>1)throw new p(`${r.length} dependencies of ${n.name} match '${t}'; address the one you mean by id.`,{exitCode:b.Usage,details:{candidates:r.map(o=>({id:o.id,name:o.name,type:o.type,..."modelId"in o?{modelId:o.modelId}:{}}))}});let[s]=r;return eq(s,n.name),s},nq=({ref:e})=>e.kind==="release"?e.name:Ne,fS=O({path:["pin","set"],effect:"land-direct",summary:"Pin a dependency to a release or to the head",description:"Re-pins one of the model's direct dependencies on another model. <dependency>@<release> pins that release's commit; <dependency>@main pins the target's head as it is now, and moves again only when you re-pin. The server resolves the selector, and writes nothing when the pin already resolves there. Managed, external and transitive dependencies are refused, with the reason.",positionals:[_(fe),{name:"dependency",type:{address:"model",slot:ph},required:!0,description:"The dependency's id, or its target model's id, from pin list, at @<release> for that release of the target or @main for the target's head now."}],dryRun:!0,examples:["modeldesk pin set <model> <dependency>@1.2.0","modeldesk pin set <model> <dependency>@main --json"],run:async e=>{await ht(e,e.args.model.model);let t=Ze(e,e.args.model.model),n=e.api(),r=await t.model.id(),[s,o]=await Promise.all([t.model.identity(),n.dependencies.list(r)]),i={id:s.id,name:s.name},a=tq(o.items,e.args.dependency.model,{name:w(s.name),address:e.args.model.model}),d=nq(e.args.dependency),l=W(e.instance(),{kind:"model",modelId:s.id}),c={id:a.id,name:a.name,target:{id:a.modelId},versionRef:a.versionRef??null,commitId:a.commitId};if(e.globals.dryRun){if(d!==Ne&&await Wr(n,a.modelId,d)===null)throw new p(`The target of '${w(a.name)}' has no release named '${d}'.`,{exitCode:b.NotFound,hint:`Run 'modeldesk release list ${a.modelId}' to see the releases it can be pinned to.`});return{result:{dryRun:!0,model:i,dependency:c,versionRef:d,url:l}}}let m;try{m=await n.dependencies.update(r,a.id,{versionRef:d})}catch(y){throw y instanceof H&&y.status===400?md(y,`Run 'modeldesk release list ${a.modelId}' to see the releases it can be pinned to.`):y}let f=m,g=f.versionRef??Ne,u=f.commitId!==c.commitId||g!==(c.versionRef??Ne),h=u&&await t.isMetamodelModel()?`${w(s.name)} is a metamodel-model and its head moved: run 'modeldesk release cascade ${s.id}' to re-release it and refresh the metamodels depending on it.`:void 0;return{result:{model:i,dependency:{id:f.id,name:f.name,target:{id:f.modelId},versionRef:g,commitId:f.commitId,...g===Ne?{}:{release:g}},previous:{versionRef:c.versionRef,commitId:c.commitId},changed:u,...h?{hint:h}:{},url:l}}},render:e=>{let t=`'${w(e.dependency.name)}' of ${w(e.model.name)}`;if("dryRun"in e)return`Dry run: would re-pin ${t} to ${w(e.versionRef)} (now ${w(e.dependency.versionRef??"@HEAD (legacy)")} at ${J(e.dependency.commitId)}). Nothing was changed.`;let n=`${w(e.dependency.versionRef)} at ${J(e.dependency.commitId)}`;return[e.changed?`Pinned ${t} to ${n} (was ${w(e.previous.versionRef??"@HEAD (legacy)")} at ${J(e.previous.commitId)}).`:`${t} is already pinned to ${n}; nothing changed.`,...e.hint?[e.hint]:[],` url: ${e.url}`].join(`
265
- `)}});var rq=e=>String.raw`\u${e.codePointAt(0).toString(16).padStart(4,"0")}`,Xf=e=>`${JSON.stringify(e).replace(/[\u007f-\u009f]/g,rq)}
266
- `,sq=(e,t)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`'${e.path.join(" ")}' returned a result that is not a JSON object.`);return{schemaVersion:e.schemaVersion??1,...t}},pS=(e,t,n,r,s={})=>{if(t&&n.listing&&s.allRows){for(let a of r.items)e.out(Xf(a));return}if(t){e.out(Xf(sq(n,r)));return}let o=ae(n.render?.(r)??"");o!==""&&e.out(o.endsWith(`
267
- `)?o:`${o}
268
- `);let i=r;n.listing&&i.truncated&&i.hint&&e.err(ae(`note: ${i.hint}
269
- `))},oq=e=>e instanceof Error?e.message:String(e),bo=e=>e instanceof p?e:new p(oq(e)),iq=e=>({code:e.exitCode,message:e.reason,...e.hint?{hint:e.hint}:{},retryable:e.exitCode===b.Transient,...e.type?{type:e.type}:{},...e.requestId?{requestId:e.requestId}:{},details:e.details}),Jf=e=>e!==null&&typeof e=="object"?JSON.stringify(e):String(e),uS=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return Jf(e);let{message:t,...n}=e,r=Object.entries(n).filter(([,o])=>o!=null).map(([o,i])=>`${o} ${Jf(i)}`).join(", ");if(t===void 0)return r;let s=Jf(t);return r===""?s:`${s} (${r})`},aq=e=>Object.entries(e).flatMap(([t,n])=>Array.isArray(n)?[` ${t}:`,...n.map(r=>` - ${uS(r)}`)]:[` ${t}: ${uS(n)}`]),Qf=(e,t,n)=>{let r=bo(n);if(t)e.err(Xf({error:iq(r)}));else{let o=aq(r.details).map(i=>`${i}
270
- `).join("");e.err(ae(`error: ${r.message}
271
- ${o}`))}return r.exitCode};var dq=(e,t)=>{let r=Object.values(e.elements).find(s=>s.type==="@ManagedDependency"&&s.attributes?.["@modelId"]?.[0]===t)?.attributes?.["@commitId"]?.[0];return typeof r=="string"?r:void 0},lq=async(e,t)=>{let n=t.releaseId?(await pt(e,t.modelId)).find(a=>a.id===t.releaseId):void 0,r=Un(await e.releases.createMetamodelRelease(t.modelId,n?.description)),s=t.releaseId!==void 0&&r.id===t.releaseId,o=n??{commitId:t.fromCommitId,builtInCommitId:t.fromBuiltInCommitId};return{...{id:r.id,name:r.name,commitId:r.commitId,createdAt:r.createdAt,...r.description?{description:r.description}:{}},inPlace:s,moved:s&&(r.commitId!==o.commitId||r.builtInCommitId!==o.builtInCommitId)}},cq=async(e,t)=>{if(t.kind==="refresh-pin"){let r=await e.dependencies.update(t.modelId,t.dependencyId,{versionRef:t.versionRef}),s="commitId"in r?r.commitId:void 0;return{changed:s!==t.fromCommitId,...s?{commitId:s}:{}}}let n=dq(await e.releases.refreshExtensionBase(t.modelId),t.baseId);return{changed:n!==t.fromCommitId,...n?{commitId:n}:{}}},hS=async(e,t,n)=>{let r=[],s=new Set;for(let o of t){let i={step:o.step,kind:o.kind,modelId:o.modelId,modelName:o.modelName},a;try{if(o.kind!=="re-release"){let d=await cq(e,o);d.changed&&s.add(o.modelId),a={...i,status:"done",...d}}else o.reason==="pins-move"&&o.outdated===void 0&&!s.has(o.modelId)?a={...i,status:"skipped"}:a={...i,status:"done",release:await lq(e,o)}}catch(d){let l=bo(d);return a={...i,status:"failed",error:{message:l.message,code:l.exitCode,...l.type?{type:l.type}:{}}},r.push(a),n(a),{outcomes:r,failure:l}}r.push(a),n(a)}return{outcomes:r}};var mq=e=>new Map([...e.draftModelIds.map(t=>[t,{role:"metamodel"}]),...e.metamodels.map(t=>[t.id,{role:"metamodel"}]),...e.extensions.map(t=>[t.id,{role:"extension",baseId:t.metamodel}])]),fq=async(e,t)=>{let[n,r,s]=await Promise.all([e.models.overview(t),e.models.identity(t),e.dependencies.list(t)]);return{id:t,name:r.name,headCommitId:r.branch.head.id,overview:n,dependencies:s.items}},uq=async(e,t)=>{let[n,r]=await Promise.all([pt(e,t),e.models.get(t)]),s=ld(r);return{releases:n,...s?{standardVersion:s}:{}}},pq=e=>{let t=new Map;for(let{id:n,overview:r}of e)for(let s of r.signals){let o=s.detail.latestVersion;s.subject===void 0||typeof o!="string"||(s.code==="DEPENDENT_BEHIND"?t.set(`${s.subject.modelId} ${n}`,o):s.code==="DEPENDENCY_MOVED_ON"&&t.set(`${n} ${s.subject.modelId}`,o))}return t},hq=(e,t,n,r)=>{let s=new Set,{dependedOnBy:o}=e.overview;o.hiddenCount>0&&r.hiddenDependents.push({modelId:e.id,count:o.hiddenCount});for(let i of o.items)i.modelId!==void 0&&(t.has(i.modelId)?s.add(i.modelId):r.outside.set(`${i.modelId} ${e.id}`,{modelId:i.modelId,name:i.name,targetId:e.id}));return n.extensions.filter(i=>i.metamodel===e.id).forEach(({id:i})=>s.add(i)),s},gq=async(e,t,n,r)=>{let s={nodes:new Map,hiddenDependents:[],outside:new Map},o=[t];for(;o.length>0;){let i=await Promise.all(o.map(d=>fq(e,d)));i.forEach(d=>s.nodes.set(d.id,d)),o=[...new Set(i.flatMap(d=>[...hq(d,n,r,s)]))].filter(d=>!s.nodes.has(d))}return s},yq=(e,t,n,r)=>({id:e.id,name:e.name,role:t.role,...t.baseId?{baseId:t.baseId}:{},headCommitId:e.headCommitId,released:n!==void 0,...r?{outdated:r}:{},...n?.standardVersion?{standardVersion:n.standardVersion}:{},releases:n?.releases??[],...e.overview.instanceModelCount===void 0?{}:{instanceModelCount:e.overview.instanceModelCount}}),wq=async(e,t,n,r)=>{let s=new Map(await Promise.all([...t.keys()].filter(i=>!r.draftModelIds.includes(i)).map(async i=>[i,await uq(e,i)]))),o=r.outdatedReleases;return Object.fromEntries([...t.values()].map(i=>[i.id,yq(i,n.get(i.id)??{role:"metamodel"},s.get(i.id),o[i.id])]))},bq=(e,t,n,r)=>{if(t.transitive||!n.has(t.modelId)||t.modelId===e.id)return;let s=r.get(`${e.id} ${t.modelId}`);return{modelId:e.id,dependencyId:t.id,name:t.name,targetId:t.modelId,...t.versionRef?{versionRef:t.versionRef}:{},commitId:t.commitId,...s?{newerRelease:s}:{}}},kq=e=>{let t=pq([...e.values()]);return[...e.values()].flatMap(n=>n.dependencies.flatMap(r=>r.type==="INTERNAL"?bq(n,r,e,t)??[]:[]))},Eq=(e,t,n)=>{let r=[],s=[];for(let o of e.values()){let i=t[o.id].baseId;if(i!==void 0)for(let a of o.dependencies){if(a.type!=="MANAGED"||!e.has(a.modelId))continue;let d={modelId:o.id,dependencyId:a.id,targetId:a.modelId,commitId:a.commitId};a.modelId===i?r.push(d):n.get(a.modelId)?.role==="extension"&&s.push(d)}}return{basePins:r,siblingPins:s}},gS=async(e,t,n)=>{let r=mq(n),{nodes:s,hiddenDependents:o,outside:i}=await gq(e,t,r,n),a=await wq(e,s,r,n);return{baseId:t,models:a,edges:kq(s),...Eq(s,a,r),hiddenDependents:o,outsideDependents:[...i.values()]}},yS=async(e,t)=>{let n=Object.values(t.models);return(await Promise.all(n.map(async s=>{let[o,i]=await Promise.all([e.models.identity(s.id),s.released?pt(e,s.id):Promise.resolve([])]),a={modelId:s.id,modelName:s.name},d=o.branch.head.id===s.headCommitId?[]:[{...a,kind:"head",from:s.headCommitId,to:o.branch.head.id}],l=new Map(i.map(f=>[f.id,f])),c=new Map(s.releases.map(f=>[f.id,f])),m=[...new Set([...l.keys(),...c.keys()])].flatMap(f=>{let g=c.get(f),u=l.get(f);return g?.commitId===u?.commitId&&g?.builtInCommitId===u?.builtInCommitId?[]:[{...a,kind:"release",release:(u??g)?.name,...g?{from:g.commitId}:{},...u?{to:u.commitId}:{}}]});return[...d,...m]}))).flat()};var wS=8,Zf=500,Cq=(e,t,n,r)=>{let s=e.refs.find(a=>a.modelId===t.id&&a.role===(t.role==="metamodel"?"metamodel":"extension"));if(s===void 0)return{status:"not-pinned"};let o=n.find(a=>a.name===s.version);if(s.version===void 0||o===void 0)return{status:"unknown-release",...s.version?{version:s.version}:{}};if(r==="run"&&s.version!==t.awaited)return{status:"other-release",version:s.version};let i=o.builtInCommitId===void 0?void 0:e.builtIns.find(a=>a.sourceMetamodelId===t.id&&a.commitId!==o.builtInCommitId);return s.commitId===o.commitId&&i===void 0?{status:"current",version:s.version}:{status:"behind",version:s.version,...s.commitId?{commitId:s.commitId}:{},expectedCommitId:o.commitId,...i?{builtInCommitId:i.commitId,expectedBuiltInCommitId:o.builtInCommitId}:{}}},bS=e=>e.behind+e.stuck+e.unverified>0,fd=e=>e.role==="extension"&&e.baseId?e.baseId:e.id,Rq=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),Sq=e=>e instanceof p&&e.exitCode===b.Transient,kS=async(e,t,n)=>{let r=new Map(await Promise.all(t.map(async u=>[u.id,await pt(e,u.id)]))),s=[...new Set(t.map(fd))],o=[];await wo(s,wS,async u=>{let h=[...(await e.models.list({metamodel:u})).items].sort(Rq);o.push({group:u,models:h.slice(0,n.limit),truncated:h.length>n.limit})});let i=o.flatMap(({group:u,models:h})=>h.map(y=>({id:y.id,name:y.name,group:u}))),a=new Set(o.filter(({truncated:u})=>u).map(({group:u})=>u)),d=new Map(i.map(u=>[u.id,{kind:"unread"}])),l=async u=>{try{let h=await e.models.get(u.id),y={refs:dd(h),builtIns:oS(h)},k=new Map(t.filter(S=>fd(S)===u.group).map(S=>[S.id,Cq(y,S,r.get(S.id)??[],n.scope)]));d.set(u.id,{kind:"read",standings:k})}catch(h){if(h instanceof H&&h.status===404)d.set(u.id,{kind:"gone"});else if(!Sq(h))throw h}},c=u=>{let h=d.get(u.id);return h?.kind==="unread"?!0:h?.kind!=="read"?!1:[...h.standings].some(([y,k])=>{let S=t.find(I=>I.id===y)?.awaited;return k.status==="behind"&&k.version===S})},m=i;await uo({read:async()=>(await wo(m,wS,l),m=m.filter(c),m.length),settled:u=>u===0,deadline:n.clock.now()+n.timeoutMs,clock:n.clock,interval:n.interval??xf});let f=t.map(u=>{let h=i.filter(E=>E.group===fd(u)),y=E=>{let M=d.get(E.id);return M?.kind==="read"?M.standings.get(u.id):void 0},k=E=>{let M=y(E);return M?.status!=="behind"?[]:[{id:E.id,name:E.name,version:M.version,...M.commitId?{commitId:M.commitId}:{},expectedCommitId:M.expectedCommitId,...M.builtInCommitId?{builtInCommitId:M.builtInCommitId,expectedBuiltInCommitId:M.expectedBuiltInCommitId}:{}}]},S=h.flatMap(k),I=E=>E.version===u.awaited,x=h.filter(E=>y(E)?.status==="current").length;return{id:u.id,name:u.name,releasedNow:u.releasedNow,...u.awaited?{awaited:u.awaited}:{},checked:h.filter(E=>{let M=y(E);return M!==void 0&&M.status!=="not-pinned"}).length,repinned:x,behind:S.filter(I),stuck:S.filter(E=>!I(E)),otherRelease:h.filter(E=>y(E)?.status==="other-release").length,unknownRelease:h.flatMap(E=>{let M=y(E);return M?.status==="unknown-release"?[{id:E.id,name:E.name,...M.version?{version:M.version}:{}}]:[]}),unverified:h.filter(E=>d.get(E.id)?.kind==="unread").map(({id:E,name:M})=>({id:E,name:M})),gone:h.filter(E=>d.get(E.id)?.kind==="gone").map(({id:E,name:M})=>({id:E,name:M})),truncated:a.has(fd(u))}}),g=u=>f.reduce((h,y)=>h+u(y),0);return{scope:n.scope,timeoutSeconds:n.timeoutMs/1e3,repinned:g(u=>u.repinned),behind:g(u=>u.behind.length),stuck:g(u=>u.stuck.length),unverified:new Set(f.flatMap(u=>u.unverified.map(h=>h.id))).size,unknownRelease:g(u=>u.unknownRelease.length),truncated:f.some(u=>u.truncated),models:f}};var eu=e=>`'${w(e)}'`,tu=(e,t=e===void 0)=>t?`${Ne} (legacy)`:w(e??Ne),CS=(e,t)=>e?`; ${w(t)} has a newer release ${w(e)}, which 'pin set' adopts`:"",ko=e=>{switch(e.kind){case"refresh-pin":return`refresh pin ${eu(e.dependencyName)} of ${w(e.modelName)} (${tu(e.versionRef,e.legacy)})`;case"refresh-base-pin":return`re-pin ${w(e.modelName)} to the head of its base ${w(e.baseName)}`;case"re-release":{if(e.inPlace)return`re-release ${w(e.modelName)} ${w(e.releaseName??"")} in place`;let t=e.release?w(e.release):"(named by the server)";return`release ${w(e.modelName)} ${t} for the first time`}}},vq=(e,t)=>e.reason==="target-moves"?`${t}'s head moves first`:e.reason==="release-moves"?`${t} ${w(e.versionRef)} is re-released first`:`it already trails what ${tu(e.versionRef,e.legacy)} resolves to`,Iq=e=>{switch(e.kind){case"refresh-pin":{let t=w(e.targetName),n=vq(e,t);return`pinned at ${J(e.fromCommitId)}; ${n}${CS(e.newerRelease,e.targetName)}`}case"refresh-base-pin":return`pinned at ${J(e.fromCommitId)}; ${e.reason==="base-moves"?`${w(e.baseName)}'s head moves first`:"it already trails the base head"}`;case"re-release":{let t=e.reason==="pins-move"?"its pins move":`its release trails its head (${e.outdated})`,n=e.unreleasedEdits?"; this publishes its current head, including the edits made since its last release":"",r=e.inPlace&&e.instanceModelCount?`; then the platform re-pins its ${P(e.instanceModelCount,"instance model")}`:"";return`${t}${n}${r}`}}},$q=e=>e.kind==="base-pin"?`- base pin on ${w(e.targetName)} at ${J(e.commitId)} is current`:`- pin ${eu(e.name)} (${tu(e.versionRef)}) at ${J(e.commitId)} is current`+CS(e.newerRelease,e.targetName),xq=(e,t)=>{let n=e.baseId?t.models.find(o=>o.id===e.baseId)?.name:void 0,r=n?` of ${w(n)}`:"",s=e.role==="extension"?`extension${r}`:"metamodel";return` ${w(e.name)} (${s}${e.released?"":", never released"})`},RS=e=>{let t=[`Release cascade from ${w(e.base.name)}: ${P(e.models.length,"metamodel-model")}, ${P(e.stepCount,"step")}.`,...e.models.flatMap(n=>[xq(n,e),...n.steps.map(r=>` ${r.step}. ${ko(r)}: ${Iq(r)}`),...n.current.map(r=>` ${$q(r)}`),...n.steps.length===0&&n.current.length===0?[" - nothing to do"]:[]])];return e.staleSiblingPins.length>0&&t.push("Not refreshed, since no route refreshes a dependsOn pin between sibling extensions (re-add it in the app):",...e.staleSiblingPins.map(n=>` ${w(n.modelName)} on ${w(n.targetName)} at ${J(n.commitId)}: `+(n.reason==="target-moves"?`${w(n.targetName)}'s head moves`:"it trails the head"))),e.unresolvedPins.length>0&&t.push("Left as they are, since they name a release that no longer exists (re-pin them with pin set):",...e.unresolvedPins.map(n=>` ${eu(n.name)} of ${w(n.modelName)} pins ${w(n.targetName)} ${w(n.versionRef)}`)),e.outsideDependents.length>0&&t.push("Not in the cascade, since they are not metamodel-models (their owners re-pin them with pin set):",...e.outsideDependents.map(n=>` ${w(n.name)} depends on ${w(n.targetName)}`)),`${t.join(`
272
+ `);let d=await e.choose("Which one?",s.length);if(d===void 0)throw new f("No element chosen, so nothing was created.");return s[d]}let i=s.map(a=>[a.elementId,pl(a),a.path??""]);throw new f(`Several elements in the last pull's manifest are named "${r.trim()}"; pass --element <id> to pick one:
273
+ `+W(i,{indent:" "}).join(`
274
+ `))},aV=(e,t,n,r,o)=>{let s=o.trim().toLowerCase();if(s==="")throw new f("--element is blank; give the id of the element the note is for.");let i=n.find(a=>a.elementId===s);if(i===void 0){let a=Vc(t).filter(d=>d.elementId===s);throw a.length>0?new f(`${o.trim()} is ${hT(a)}; anchor-level parts carry no note slots.`):new f(`The last pull's manifest has no element ${o.trim()}. Run 'modeldesk bundle pull' if the model changed since.`)}return r.trim()!==""&&Yc([i],r).length===0&&e.io.err(`note: --element picks ${pl(i)}, so the name "${r.trim()}" was ignored.
275
+ `),i},hT=e=>{let t=e.map(n=>{let r=/^[aeiou]/i.test(n.kind)?"an":"a";return n.owner===void 0?`${r} ${n.kind}`:`${r} ${n.kind} inside ${n.owner}`});return[...new Set(t)].join(" or ")},dV=(e,t,n,r)=>{if(t==="after"&&e.container){if(e.anchor===void 0)throw new f(`The last pull's manifest gives ${n} no anchor to build its after heading's id from, so a note there cannot be placed.`);if(r===void 0)throw new f(`The after note of ${n} comes under a heading of its own; pass --heading <text>.`);let o=zo(r);if(o!==void 0)throw new f(`--heading ${o}; give the text of the heading the note comes under on one line.`);return r.trim()}if(r!==void 0)throw new f(`--heading is only for the after note of the model or a package; the ${t} note of ${n} takes none.`)},lV=(e,t,n,r,o)=>{let s=ra(n,t)??zc(e,n);if(s!==void 0)throw new f(`${s[0].toUpperCase()}${s.slice(1)}.`);let a=(r.path===void 0?void 0:oa(n,t,r.path,o))??ml.join(n,`${zn(r.title??"")||r.elementId}${o==="after"?".after":""}.md`),[d]=em(e,t,a);if(d!==void 0)throw new f(`${d[0].toUpperCase()}${d.slice(1)}. Pick another folder with --dir, or "notesDir" in .modeldesk/config.json.`);return a},cV=(e,t,n,r)=>r?`${e} already exists, and note add never overwrites a file. The next pull places it as the ${n} note of ${t}; write in it.`:`${e} already exists, and note add never overwrites a file; pick another folder with --dir.`;var wu=e=>e===void 0||e===Ee,gT=e=>{let t=[];return wu(e.versionRef)?e.targetHeadCommitId!==void 0&&e.targetHeadCommitId!==e.commitId&&t.push("head-moved"):(e.newerRelease!==void 0&&t.push("newer-release"),e.releaseCommitId===null?t.push("release-missing"):e.releaseCommitId!==void 0&&e.releaseCommitId!==e.commitId&&t.push("release-moved")),{standing:t.length===0?"current":"behind",reasons:t}};var yT={pinList:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What the pins were read at: your draft while it holds staged changes, else your working branch, or the ref named."},newerReleaseChecked:{type:"boolean",description:"Whether the newer-release check ran. It reads the overview, which a caller's access may not reach; the commit comparisons run either way. One of false, true."},items:{type:"array",items:{type:"object",properties:{kind:{type:"string",description:'`internal`: a dependency on another model, whose pin can be moved. `managed`: built-in elements a metamodel supplies, pinned through the metamodel version. `external`: a document outside the platform. `metamodel` and `extension`: the model\'s own metamodel and the extensions it applies. One of "extension", "external", "internal", "managed", "metamodel".'},name:{type:"string"},dependencyId:{type:"string",description:"The dependency's id, by which its pin is moved; absent on a metamodel or extension pin."},target:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},location:{type:"string",description:"An external document's address."},versionRef:{description:"An internal pin's selector as authored: `@HEAD`, a version name, or null on a legacy edge (tracks the head). May be null."},commitId:{type:"string"},release:{type:"string",description:"The release the pin resolves to: a version pin's, or the version label of a metamodel pin. Never a head pin's."},source:{type:"object",properties:{metamodelId:{type:"string"},version:{type:"string"}},description:"A managed pin's source: the metamodel or extension, and its release, that supplies the built-ins."},settable:{type:"boolean",description:"Whether pin set can move its pin on main: an internal pin main holds. Read at a draft or another branch, a dependency that exists only there cannot; a staged re-pin moves any direct internal one. One of false, true."},standing:{type:"string",description:`An internal pin's standing; read-only pins have none. One of "behind", "current".`},reasons:{type:"array",items:{type:"string",description:'One of "head-moved", "newer-release", "release-missing", "release-moved".'}},latestRelease:{type:"string",description:"The newer release a version pin trails."}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","model","ref","newerReleaseChecked","items","truncated"]}};var pV=e=>new Map((e?.signals??[]).flatMap(t=>t.code==="DEPENDENCY_MOVED_ON"&&t.subject&&typeof t.detail.latestVersion=="string"?[[t.subject.modelId,t.detail.latestVersion]]:[])),fV=(e,t)=>new Map([...e.metamodel?[[e.metamodel.id,e.metamodel.name]]:[],...(e.metamodelExtensions??[]).map(n=>[n.id,n.name]),...t?.metamodel?[[t.metamodel.modelId,t.metamodel.name]]:[]]),uV=(e,t)=>ha(e).map(n=>{let r=t.get(n.modelId)??n.modelId;return{kind:n.role,name:r,target:{id:n.modelId,name:r},...n.commitId?{commitId:n.commitId}:{},...n.version?{release:n.version}:{},settable:!1}}),hV=async(e,t,n,r,o)=>{let s=wu(t.versionRef),[i,a]=await Promise.all([s?e.models.identity(t.modelId).then(m=>m.branch.head.id):void 0,s||t.versionRef===void 0?void 0:Qr(e,t.modelId,t.versionRef)]),d=s?void 0:r.get(t.modelId),{standing:l,reasons:c}=gT({versionRef:t.versionRef,commitId:t.commitId,...i===void 0?{}:{targetHeadCommitId:i},...a===void 0?{}:{releaseCommitId:a},...d===void 0?{}:{newerRelease:d}});return{kind:"internal",name:t.name,dependencyId:t.id,target:{id:t.modelId,...n?{name:n}:{}},versionRef:t.versionRef??null,commitId:t.commitId,...s?{}:{release:t.versionRef},settable:o,standing:l,...c.length>0?{reasons:c}:{},...d?{latestRelease:d}:{}}},gV=async(e,t,n,r,o)=>{let s=new Map((n?.dependsOn.items??[]).flatMap(d=>d.modelId?[[d.modelId,d.name]]:[])),i=pV(n),a=t.filter(d=>!d.transitive);return Promise.all(a.map(async d=>{switch(d.type){case"EXTERNAL":return{kind:"external",name:d.name,dependencyId:d.id,location:d.location,settable:!1};case"MANAGED":{let l=o.get(d.sourceMetamodelId);return{kind:"managed",name:d.name,dependencyId:d.id,target:{id:d.modelId,...l?{name:l}:{}},commitId:d.commitId,source:{metamodelId:d.sourceMetamodelId,version:d.sourceMetamodelVersion},settable:!1}}case"INTERNAL":return hV(e,d,s.get(d.modelId)??d.name,i,r?.has(d.id)??!0)}}))},yV={"newer-release":"newer release","release-moved":"release re-released","release-missing":"release gone","head-moved":"head moved"},wV=e=>e.kind!=="internal"?"":e.versionRef===null?"@HEAD (legacy)":g(e.versionRef??""),bV=e=>e.standing===void 0?"read-only":e.standing==="current"?"current":`behind (${(e.reasons??[]).map(n=>n==="newer-release"&&e.latestRelease?`newer release ${g(e.latestRelease)}`:yV[n]).join(", ")})`,EV=["ID","KIND","NAME","TARGET","SELECTOR","COMMIT","RELEASE","STANDING"],wT=A({path:["pin","list"],effect:"read",summary:"List a model's pins and whether each is behind",description:"Lists the model's metamodel and extension pins and its direct dependencies, as the addressed ref holds them, so a dependency staged in your draft shows before it is committed: the id pin set takes, name, target, selector (@HEAD, a version name, or @HEAD (legacy) on an edge that predates selectors), commit, release and standing. A version pin is behind when a newer release exists or its release was re-released in place; a @HEAD pin is behind when the target's head moved past it. Managed, external, metamodel and extension pins are read-only here. pin set moves a pin on main only, so a dependency that exists only in your draft or on a branch is listed as not settable, while dependency pin stages a move of any direct internal one; a newer release is looked for on main.",positionals:[N(_e)],listing:{},examples:["modeldesk pin list <model>","modeldesk pin list <model>@draft --json"],mcp:{name:"list_dependencies",description:"Lists the model's dependencies at the ref you give, ones staged in your draft included: each with its dependencyId, the target model's id and name, the release it is pinned to (versionRef @HEAD tracks the target's head) and whether it is behind. Its metamodel and extension pins come first. Call it before dependency_change, to see whether the model already depends on a model and which release it pins."},resultSchema:yT.pinList,run:async e=>{let t=dt(e,e.args.model.model),n=e.api(),r=await ae(e,e.args.model,_e),o=r.id,s=rt(r.ref),[i,a,d,l]=await Promise.all([t.model.identity(),t.overviewIfReadable(),n.dependencies.list(o,s),n.models.get(o,s)]),m=r.ref.kind==="branch"&&r.ref.branch.main?void 0:new Set((await n.dependencies.list(o)).items.filter(y=>!y.transitive).map(y=>y.id)),p=fV(l,a),h=[...uV(l,p),...await gV(n,d.items,a,m,p)];return{result:{model:{id:i.id,name:i.name},ref:le(r),newerReleaseChecked:a!==void 0,...await e.list(h)}}},render:e=>{let t=e.items.map(n=>[n.dependencyId??"",n.kind,g(n.name),g(n.target?.name??n.target?.id??n.location??""),wV(n),n.commitId?Z(n.commitId):"",g(n.release??""),bV(n)]);return[Ae(e.ref,e.model),`Pins of ${g(e.model.name)}:`,...t.length===0?["No pins."]:W([EV,...t]),...e.newerReleaseChecked?[]:["Newer releases were not checked: your access does not reach the model's overview."]].join(`
276
+ `)}});var CV=e=>String.raw`\u${e.codePointAt(0).toString(16).padStart(4,"0")}`,Eu=e=>`${JSON.stringify(e).replace(/[\u007f-\u009f]/g,CV)}
277
+ `,RV=(e,t)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`'${e.path.join(" ")}' returned a result that is not a JSON object.`);return{schemaVersion:e.schemaVersion??1,...t}},ET=(e,t,n,r,o={})=>{if(t&&n.listing&&o.allRows){for(let a of r.items)e.out(Eu(a));return}if(t){e.out(Eu(RV(n,r)));return}let s=ye(n.render?.(r,o.flags??{})??"");s!==""&&e.out(s.endsWith(`
278
+ `)?s:`${s}
279
+ `);let i=r;n.listing&&i.truncated&&i.hint&&e.err(ye(`note: ${i.hint}
280
+ `))},kV=e=>e instanceof Error?e.message:String(e),si=e=>e instanceof f?e:new f(kV(e)),vV=e=>({code:e.exitCode,message:e.reason,...e.hint?{hint:e.hint}:{},retryable:e.exitCode===b.Transient,...e.type?{type:e.type}:{},...e.requestId?{requestId:e.requestId}:{},details:e.details}),bu=e=>e!==null&&typeof e=="object"?JSON.stringify(e):String(e),bT=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return bu(e);let{message:t,...n}=e,r=Object.entries(n).filter(([,s])=>s!=null).map(([s,i])=>`${s} ${bu(i)}`).join(", ");if(t===void 0)return r;let o=bu(t);return r===""?o:`${o} (${r})`},IV=e=>Object.entries(e).flatMap(([t,n])=>Array.isArray(n)?[` ${t}:`,...n.map(r=>` - ${bT(r)}`)]:[` ${t}: ${bT(n)}`]),Cu=(e,t,n)=>{let r=si(n);if(t)e.err(Eu({error:vV(r)}));else{let s=IV(r.details).map(i=>`${i}
281
+ `).join("");e.err(ye(`error: ${r.message}
282
+ ${s}`))}return r.exitCode};var SV=(e,t)=>{let r=Object.values(e.elements).find(o=>o.type==="@ManagedDependency"&&o.attributes?.["@modelId"]?.[0]===t)?.attributes?.["@commitId"]?.[0];return typeof r=="string"?r:void 0},$V=async(e,t)=>{let n=t.releaseId?(await it(e,t.modelId)).find(a=>a.id===t.releaseId):void 0,r=er(await e.releases.createMetamodelRelease(t.modelId,n?.description)),o=t.releaseId!==void 0&&r.id===t.releaseId,s=n??{commitId:t.fromCommitId,builtInCommitId:t.fromBuiltInCommitId};return{...{id:r.id,name:r.name,commitId:r.commitId,createdAt:r.createdAt,...r.description?{description:r.description}:{}},inPlace:o,moved:o&&(r.commitId!==s.commitId||r.builtInCommitId!==s.builtInCommitId)}},TV=async(e,t)=>{if(t.kind==="refresh-pin"){let r=await e.dependencies.update(t.modelId,t.dependencyId,{versionRef:t.versionRef}),o="commitId"in r?r.commitId:void 0;return{changed:o!==t.fromCommitId,...o?{commitId:o}:{}}}let n=SV(await e.releases.refreshExtensionBase(t.modelId),t.baseId);return{changed:n!==t.fromCommitId,...n?{commitId:n}:{}}},CT=async(e,t,n)=>{let r=[],o=new Set;for(let s of t){let i={step:s.step,kind:s.kind,modelId:s.modelId,modelName:s.modelName},a;try{if(s.kind!=="re-release"){let d=await TV(e,s);d.changed&&o.add(s.modelId),a={...i,status:"done",...d}}else s.reason==="pins-move"&&s.outdated===void 0&&!o.has(s.modelId)?a={...i,status:"skipped"}:a={...i,status:"done",release:await $V(e,s)}}catch(d){let l=si(d);return a={...i,status:"failed",error:{message:l.message,code:l.exitCode,...l.type?{type:l.type}:{}}},r.push(a),n(a),{outcomes:r,failure:l}}r.push(a),n(a)}return{outcomes:r}};var xV=e=>new Map([...e.draftModelIds.map(t=>[t,{role:"metamodel"}]),...e.metamodels.map(t=>[t.id,{role:"metamodel"}]),...e.extensions.map(t=>[t.id,{role:"extension",baseId:t.metamodel}])]),AV=async(e,t)=>{let[n,r,o]=await Promise.all([e.models.overview(t),e.models.identity(t),e.dependencies.list(t)]);return{id:t,name:r.name,headCommitId:r.branch.head.id,overview:n,dependencies:o.items}},OV=async(e,t)=>{let[n,r]=await Promise.all([it(e,t),e.models.get(t)]),o=rs(r);return{releases:n,...o?{standardVersion:o}:{}}},MV=e=>{let t=new Map;for(let{id:n,overview:r}of e)for(let o of r.signals){let s=o.detail.latestVersion;o.subject===void 0||typeof s!="string"||(o.code==="DEPENDENT_BEHIND"?t.set(`${o.subject.modelId} ${n}`,s):o.code==="DEPENDENCY_MOVED_ON"&&t.set(`${n} ${o.subject.modelId}`,s))}return t},NV=(e,t,n,r)=>{let o=new Set,{dependedOnBy:s}=e.overview;s.hiddenCount>0&&r.hiddenDependents.push({modelId:e.id,count:s.hiddenCount});for(let i of s.items)i.modelId!==void 0&&(t.has(i.modelId)?o.add(i.modelId):r.outside.set(`${i.modelId} ${e.id}`,{modelId:i.modelId,name:i.name,targetId:e.id}));return n.extensions.filter(i=>i.metamodel===e.id).forEach(({id:i})=>o.add(i)),o},PV=async(e,t,n,r)=>{let o={nodes:new Map,hiddenDependents:[],outside:new Map},s=[t];for(;s.length>0;){let i=await Promise.all(s.map(d=>AV(e,d)));i.forEach(d=>o.nodes.set(d.id,d)),s=[...new Set(i.flatMap(d=>[...NV(d,n,r,o)]))].filter(d=>!o.nodes.has(d))}return o},DV=(e,t,n,r)=>({id:e.id,name:e.name,role:t.role,...t.baseId?{baseId:t.baseId}:{},headCommitId:e.headCommitId,released:n!==void 0,...r?{outdated:r}:{},...n?.standardVersion?{standardVersion:n.standardVersion}:{},releases:n?.releases??[],...e.overview.instanceModelCount===void 0?{}:{instanceModelCount:e.overview.instanceModelCount}}),LV=async(e,t,n,r)=>{let o=new Map(await Promise.all([...t.keys()].filter(i=>!r.draftModelIds.includes(i)).map(async i=>[i,await OV(e,i)]))),s=r.outdatedReleases;return Object.fromEntries([...t.values()].map(i=>[i.id,DV(i,n.get(i.id)??{role:"metamodel"},o.get(i.id),s[i.id])]))},_V=(e,t,n,r)=>{if(t.transitive||!n.has(t.modelId)||t.modelId===e.id)return;let o=r.get(`${e.id} ${t.modelId}`);return{modelId:e.id,dependencyId:t.id,name:t.name,targetId:t.modelId,...t.versionRef?{versionRef:t.versionRef}:{},commitId:t.commitId,...o?{newerRelease:o}:{}}},jV=e=>{let t=MV([...e.values()]);return[...e.values()].flatMap(n=>n.dependencies.flatMap(r=>r.type==="INTERNAL"?_V(n,r,e,t)??[]:[]))},FV=(e,t,n)=>{let r=[],o=[];for(let s of e.values()){let i=t[s.id].baseId;if(i!==void 0)for(let a of s.dependencies){if(a.type!=="MANAGED"||!e.has(a.modelId))continue;let d={modelId:s.id,dependencyId:a.id,targetId:a.modelId,commitId:a.commitId};a.modelId===i?r.push(d):n.get(a.modelId)?.role==="extension"&&o.push(d)}}return{basePins:r,siblingPins:o}},RT=async(e,t,n)=>{let r=xV(n),{nodes:o,hiddenDependents:s,outside:i}=await PV(e,t,r,n),a=await LV(e,o,r,n);return{baseId:t,models:a,edges:jV(o),...FV(o,a,r),hiddenDependents:s,outsideDependents:[...i.values()]}},kT=async(e,t)=>{let n=Object.values(t.models);return(await Promise.all(n.map(async o=>{let[s,i]=await Promise.all([e.models.identity(o.id),o.released?it(e,o.id):Promise.resolve([])]),a={modelId:o.id,modelName:o.name},d=s.branch.head.id===o.headCommitId?[]:[{...a,kind:"head",from:o.headCommitId,to:s.branch.head.id}],l=new Map(i.map(p=>[p.id,p])),c=new Map(o.releases.map(p=>[p.id,p])),m=[...new Set([...l.keys(),...c.keys()])].flatMap(p=>{let h=c.get(p),u=l.get(p);return h?.commitId===u?.commitId&&h?.builtInCommitId===u?.builtInCommitId?[]:[{...a,kind:"release",release:(u??h)?.name,...h?{from:h.commitId}:{},...u?{to:u.commitId}:{}}]});return[...d,...m]}))).flat()};var vT=8,Ru=500,qV=(e,t,n,r)=>{let o=e.refs.find(a=>a.modelId===t.id&&a.role===(t.role==="metamodel"?"metamodel":"extension"));if(o===void 0)return{status:"not-pinned"};let s=n.find(a=>a.name===o.version);if(o.version===void 0||s===void 0)return{status:"unknown-release",...o.version?{version:o.version}:{}};if(r==="run"&&o.version!==t.awaited)return{status:"other-release",version:o.version};let i=s.builtInCommitId===void 0?void 0:e.builtIns.find(a=>a.sourceMetamodelId===t.id&&a.commitId!==s.builtInCommitId);return o.commitId===s.commitId&&i===void 0?{status:"current",version:o.version}:{status:"behind",version:o.version,...o.commitId?{commitId:o.commitId}:{},expectedCommitId:s.commitId,...i?{builtInCommitId:i.commitId,expectedBuiltInCommitId:s.builtInCommitId}:{}}},IT=e=>e.behind+e.stuck+e.unverified>0,fl=e=>e.role==="extension"&&e.baseId?e.baseId:e.id,WV=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"})||e.id.localeCompare(t.id),HV=e=>e instanceof f&&e.exitCode===b.Transient,ST=async(e,t,n)=>{let r=new Map(await Promise.all(t.map(async u=>[u.id,await it(e,u.id)]))),o=[...new Set(t.map(fl))],s=[];await or(o,vT,async u=>{let y=[...(await e.models.list({metamodel:u})).items].sort(WV);s.push({group:u,models:y.slice(0,n.limit),truncated:y.length>n.limit})});let i=s.flatMap(({group:u,models:y})=>y.map(w=>({id:w.id,name:w.name,group:u}))),a=new Set(s.filter(({truncated:u})=>u).map(({group:u})=>u)),d=new Map(i.map(u=>[u.id,{kind:"unread"}])),l=async u=>{try{let y=await e.models.get(u.id),w={refs:ha(y),builtIns:Wb(y)},E=new Map(t.filter(I=>fl(I)===u.group).map(I=>[I.id,qV(w,I,r.get(I.id)??[],n.scope)]));d.set(u.id,{kind:"read",standings:E})}catch(y){if(y instanceof V&&y.status===404)d.set(u.id,{kind:"gone"});else if(!HV(y))throw y}},c=u=>{let y=d.get(u.id);return y?.kind==="unread"?!0:y?.kind!=="read"?!1:[...y.standings].some(([w,E])=>{let I=t.find(v=>v.id===w)?.awaited;return E.status==="behind"&&E.version===I})},m=i;await ei({read:async()=>(await or(m,vT,l),m=m.filter(c),m.length),settled:u=>u===0,deadline:n.clock.now()+n.timeoutMs,clock:n.clock,interval:n.interval??Kf});let p=t.map(u=>{let y=i.filter(C=>C.group===fl(u)),w=C=>{let x=d.get(C.id);return x?.kind==="read"?x.standings.get(u.id):void 0},E=C=>{let x=w(C);return x?.status!=="behind"?[]:[{id:C.id,name:C.name,version:x.version,...x.commitId?{commitId:x.commitId}:{},expectedCommitId:x.expectedCommitId,...x.builtInCommitId?{builtInCommitId:x.builtInCommitId,expectedBuiltInCommitId:x.expectedBuiltInCommitId}:{}}]},I=y.flatMap(E),v=C=>C.version===u.awaited,$=y.filter(C=>w(C)?.status==="current").length;return{id:u.id,name:u.name,releasedNow:u.releasedNow,...u.awaited?{awaited:u.awaited}:{},checked:y.filter(C=>{let x=w(C);return x!==void 0&&x.status!=="not-pinned"}).length,repinned:$,behind:I.filter(v),stuck:I.filter(C=>!v(C)),otherRelease:y.filter(C=>w(C)?.status==="other-release").length,unknownRelease:y.flatMap(C=>{let x=w(C);return x?.status==="unknown-release"?[{id:C.id,name:C.name,...x.version?{version:x.version}:{}}]:[]}),unverified:y.filter(C=>d.get(C.id)?.kind==="unread").map(({id:C,name:x})=>({id:C,name:x})),gone:y.filter(C=>d.get(C.id)?.kind==="gone").map(({id:C,name:x})=>({id:C,name:x})),truncated:a.has(fl(u))}}),h=u=>p.reduce((y,w)=>y+u(w),0);return{scope:n.scope,timeoutSeconds:n.timeoutMs/1e3,repinned:h(u=>u.repinned),behind:h(u=>u.behind.length),stuck:h(u=>u.stuck.length),unverified:new Set(p.flatMap(u=>u.unverified.map(y=>y.id))).size,unknownRelease:h(u=>u.unknownRelease.length),truncated:p.some(u=>u.truncated),models:p}};var ku=e=>`'${g(e)}'`,vu=(e,t=e===void 0)=>t?`${Ee} (legacy)`:g(e??Ee),TT=(e,t)=>e?`; ${g(t)} has a newer release ${g(e)}, which 'pin set' adopts`:"",ii=e=>{switch(e.kind){case"refresh-pin":return`refresh pin ${ku(e.dependencyName)} of ${g(e.modelName)} (${vu(e.versionRef,e.legacy)})`;case"refresh-base-pin":return`re-pin ${g(e.modelName)} to the head of its base ${g(e.baseName)}`;case"re-release":{if(e.inPlace)return`re-release ${g(e.modelName)} ${g(e.releaseName??"")} in place`;let t=e.release?g(e.release):"(named by the server)";return`release ${g(e.modelName)} ${t} for the first time`}}},BV=(e,t)=>e.reason==="target-moves"?`${t}'s head moves first`:e.reason==="release-moves"?`${t} ${g(e.versionRef)} is re-released first`:`it already trails what ${vu(e.versionRef,e.legacy)} resolves to`,UV=e=>{switch(e.kind){case"refresh-pin":{let t=g(e.targetName),n=BV(e,t);return`pinned at ${Z(e.fromCommitId)}; ${n}${TT(e.newerRelease,e.targetName)}`}case"refresh-base-pin":return`pinned at ${Z(e.fromCommitId)}; ${e.reason==="base-moves"?`${g(e.baseName)}'s head moves first`:"it already trails the base head"}`;case"re-release":{let t=e.reason==="pins-move"?"its pins move":`its release trails its head (${e.outdated})`,n=e.unreleasedEdits?"; this publishes its current head, including the edits made since its last release":"",r=e.inPlace&&e.instanceModelCount?`; then the platform re-pins its ${P(e.instanceModelCount,"instance model")}`:"";return`${t}${n}${r}`}}},GV=e=>e.kind==="base-pin"?`- base pin on ${g(e.targetName)} at ${Z(e.commitId)} is current`:`- pin ${ku(e.name)} (${vu(e.versionRef)}) at ${Z(e.commitId)} is current`+TT(e.newerRelease,e.targetName),VV=(e,t)=>{let n=e.baseId?t.models.find(s=>s.id===e.baseId)?.name:void 0,r=n?` of ${g(n)}`:"",o=e.role==="extension"?`extension${r}`:"metamodel";return` ${g(e.name)} (${o}${e.released?"":", never released"})`},xT=e=>{let t=[`Release cascade from ${g(e.base.name)}: ${P(e.models.length,"metamodel-model")}, ${P(e.stepCount,"step")}.`,...e.models.flatMap(n=>[VV(n,e),...n.steps.map(r=>` ${r.step}. ${ii(r)}: ${UV(r)}`),...n.current.map(r=>` ${GV(r)}`),...n.steps.length===0&&n.current.length===0?[" - nothing to do"]:[]])];return e.staleSiblingPins.length>0&&t.push("Not refreshed, since no route refreshes a dependsOn pin between sibling extensions (re-add it in the app):",...e.staleSiblingPins.map(n=>` ${g(n.modelName)} on ${g(n.targetName)} at ${Z(n.commitId)}: `+(n.reason==="target-moves"?`${g(n.targetName)}'s head moves`:"it trails the head"))),e.unresolvedPins.length>0&&t.push("Left as they are, since they name a release that no longer exists (re-pin them with pin set):",...e.unresolvedPins.map(n=>` ${ku(n.name)} of ${g(n.modelName)} pins ${g(n.targetName)} ${g(n.versionRef)}`)),e.outsideDependents.length>0&&t.push("Not in the cascade, since they are not metamodel-models (their owners re-pin them with pin set):",...e.outsideDependents.map(n=>` ${g(n.name)} depends on ${g(n.targetName)}`)),`${t.join(`
272
283
  `)}
273
284
 
274
- `},SS=(e,t,n)=>{let r=`[${e.step}/${n}]`;if(e.status==="failed")return`${r} FAILED: ${ko(t)}: ${w(e.error?.message??"")}
275
- `;if(e.status==="skipped")return`${r} skipped: ${ko(t)}, since none of its pins moved
276
- `;if(e.release)return`${r} done: ${ko(t)}, at ${J(e.release.commitId)}
277
- `;let s=e.changed&&t.kind!=="re-release"?`${J(t.fromCommitId)} -> ${J(e.commitId)}`:`already at ${J(e.commitId)}`;return`${r} done: ${ko(t)} (${s})
278
- `},ES=(e,t)=>` ${w(e.name)} (${e.id}) pins ${w(t.name)} ${w(e.version)} `+(e.builtInCommitId?`with its built-in elements at ${J(e.builtInCommitId)}, not ${J(e.expectedBuiltInCommitId)}`:`at ${J(e.commitId)}, not ${J(e.expectedCommitId)}`),ud=e=>e.map(t=>`${w(t.name)} (${t.id})`).join(", "),vS=e=>[`Instance re-pins (${e.scope==="all"?"every release of the family":"the releases this run moved"}): ${e.repinned} at their release's commit, ${e.behind} still behind after ${e.timeoutSeconds} s, ${e.stuck} behind a release this run did not move, ${e.unverified} not read.`,...e.models.flatMap(t=>[...t.behind.map(n=>ES(n,t)),...t.stuck.map(n=>`${ES(n,t)} (not waited on)`),...t.unverified.length>0?[` ${w(t.name)}: not verified, never read before the timeout: ${ud(t.unverified)}`]:[],...t.unknownRelease.map(n=>` ${w(n.name)} (${n.id}) pins ${w(t.name)} ${w(n.version??"(no version)")}, which has no release: it cannot be verified`),...t.gone.length>0?[` ${w(t.name)}: deleted while being checked: ${ud(t.gone)}`]:[],...t.otherRelease>0?[` ${w(t.name)}: ${P(t.otherRelease,"instance model")} pin another release, which this run did not move (--verify-all checks them)`]:[],...t.truncated?[` ${w(t.name)}: more instance models exist than were checked`]:[]])],IS=e=>{let t=e.models.flatMap(r=>r.stuck),n=e.models.flatMap(r=>r.unknownRelease);return[...e.unverified>0?[`${P(e.unverified,"instance model")} could not be read before the timeout, so ${e.unverified===1?"its pins are":"their pins are"} not verified: re-run the cascade to check again.`]:[],...e.behind>0?["Re-run the cascade to check again (it plans to no-ops and re-reads the pins). A model that stays behind across runs was skipped by the platform's background re-pin; the repin-models maintenance task re-pins every dependent idempotently."]:[],...t.length>0?[`Not waited on, since the platform moves them on no release of this run: ${ud(t)}; the repin-models maintenance task re-pins them.`]:[],...n.length>0?[`Not verifiable, since they pin a version that has no release: ${ud(n)}; re-pin them in the app's model settings.`]:[]]};var Mq=e=>e.map(t=>w(t).replace(/["\\$`,]/g,"")).join(","),pd=e=>{let t=Mq(e);return[{description:"Regenerate the committed bundles of what was released, from the repository root",command:`config/metamodels/regenerate.sh --models "${t}"`},{description:"Review the regenerated bundles in config/metamodels/ and commit them"},{description:"Promote them to each target environment: from backend/, with TARGET_API_URL and TARGET_SERVICE_TOKEN set for that environment (add --dry-run first to see its plan)",command:`java -jar maintenance/target/modeldesk-backend-maintenance-*-exec.jar push-metamodels --models "${t}"`}]},hd=e=>e.length===0?[]:["Next steps (the CLI runs none of these):",...e.flatMap((t,n)=>[` ${n+1}. ${t.description}${t.command?":":"."}`,...t.command?[` ${t.command}`]:[]])];var nu="modeldesk release cascade --help",Aq="Re-run the cascade to resume: it plans again from live state, so the finished steps read as no-ops and only the rest runs.",$S=(e,t,n)=>{if(!Number.isInteger(e)||e<1)throw $(`${t} must be a positive whole number, got ${e}.`,nu);if(n!==void 0&&e>n)throw $(`${t} is at most ${n}, got ${e}.`,nu);return e},Tq=e=>{let t=w(e.modelName);if(e.kind==="head")return`${t}'s head moved (${J(e.from)} -> ${J(e.to)})`;let n=`${t} ${w(e.release??"")}`;return e.from===void 0?`${n} was released`:e.to===void 0?`${n} was removed`:`${n} was re-released (${J(e.from)} -> ${J(e.to)})`},Oq=e=>{if(e.length>0)throw new p(`The metamodels changed after the plan was made: ${e.map(Tq).join("; ")}. Nothing was changed.`,{exitCode:b.Conflict,hint:"Re-run the cascade to plan again from what is there now.",details:{changes:e}})},ru=e=>e.filter(t=>t.status==="done"&&t.release!==void 0),Nq=(e,t,n)=>{let r=new Map(ru(t).map(s=>[s.modelId,s.release]));return Object.values(e.models).flatMap(s=>{let o=r.get(s.id),i=o?.moved?o.name:void 0;return i===void 0&&!(n&&(s.released||o!==void 0))?[]:[{id:s.id,name:s.name,role:s.role,...s.baseId?{baseId:s.baseId}:{},releasedNow:o!==void 0,...i?{awaited:i}:{}}]})},Lq=e=>({message:e.message,code:e.exitCode,...e.type?{type:e.type}:{}}),Pq=e=>{let t=e.steps.find(a=>a.status==="failed"),n=e.steps.filter(a=>a.status==="done").length,r=e.steps.filter(a=>a.status==="skipped").length,s=r>0?`, ${r} skipped`:"",o=`${P(n,"step")} run${s}`;return[{planned:"Dry run: nothing was changed.","nothing-to-do":"Every pin and release is current: nothing to run.",completed:`Cascade complete: ${o}.`,failed:`Stopped at step ${t?.step}, after ${o} (they stay done).`}[e.outcome],...e.verification?vS(e.verification):[],...e.verificationError?[`Checking the instance re-pins failed: ${w(e.verificationError.message)}`]:[],...e.hint?[e.hint]:[],` url: ${e.url}`,...hd(e.nextSteps)].join(`
279
- `)},xS=O({path:["release","cascade"],effect:"land-direct",summary:"Re-pin and re-release the metamodels depending on a metamodel",description:"Plans from live state over the metamodel-models that depend on <base> (transitively) and the extensions of any of them: which dependency pins to refresh, which extensions to re-pin to their base, which models to re-release in place (those whose pins move or whose release trails their head, unreleased edits included), and which pins are already current. It prints the plan and asks to go on (--yes when it cannot ask), checks that nothing moved since the plan, runs the steps in order and stops at the first failure. Then it waits for the platform to re-pin the instance models of the releases it moved, and names any left behind or not verified; --verify-all checks every release of the family. Re-running it plans again, so finished steps read as no-ops. Needs an interactive super-admin login.",positionals:[{name:"base",type:{address:"model",slot:fe},required:!0,description:"The id of the metamodel-model that changed, from model list --kind metamodel."}],flags:{timeout:{type:"number",placeholder:"seconds",default:120,description:"How many seconds to wait for the platform to re-pin the instance models."},"instance-limit":{type:"number",placeholder:"n",default:50,description:`How many instance models to check per metamodel, at most ${Zf}.`},"verify-all":{type:"boolean",description:"Check the instance pins of every release in the family, not only the releases this run moved."}},dryRun:!0,examples:["modeldesk release cascade <model> --dry-run","modeldesk release cascade <model> --yes --json"],run:async e=>{let t=$S(e.flags.timeout,"--timeout"),n=$S(e.flags["instance-limit"],"--instance-limit",Zf),r=e.flags["verify-all"];await ht(e,e.args.base.model);let s=Ze(e,e.args.base.model),o=e.api(),[i,a]=await Promise.all([s.model.identity(),s.isMetamodelModel()]);if(!a)throw $(`'release cascade' works on metamodel-models, and ${w(i.name)} is a model. A model's dependents own their pins: list them with 'modeldesk pin list', move one with 'modeldesk pin set'.`,nu);let d=await gS(o,i.id,await o.releases.metamodelOverview()),l=lS(d),c=dS(l);e.print(RS(l));let m={id:i.id,name:i.name},f=W(e.instance(),{kind:"model",modelId:i.id});if(e.globals.dryRun)return{result:{base:m,plan:l,outcome:"planned",steps:[],nextSteps:[],url:f}};c.length>0&&(await it(e,`Run the ${P(c.length,"step")} of this cascade?`,`The release cascade from ${w(i.name)}`),Oq(await yS(o,d)));let g=new Map(c.map(x=>[x.step,x])),u=await hS(o,c,x=>{let E=g.get(x.step);E&&e.print(SS(x,E,c.length))}),h=x=>x.length>0?pd(x.map(E=>E.modelName)):[];if(u.failure)return{result:{base:m,plan:l,outcome:"failed",steps:u.outcomes,nextSteps:h(ru(u.outcomes)),hint:Aq,url:f},exitCode:u.failure.exitCode};let y=c.length===0?"nothing-to-do":"completed",k={base:m,plan:l,outcome:y,steps:u.outcomes,nextSteps:h(ru(u.outcomes)),url:f},S=Nq(d,u.outcomes,r);if(S.length===0)return{result:k};e.print(`Checking the platform's instance re-pins (up to ${t} s)...
280
- `);try{k.verification=await kS(o,S,{timeoutMs:t*1e3,limit:n,clock:Qa,scope:r?"all":"run"})}catch(x){let E=bo(x);return k.verificationError=Lq(E),k.hint="The steps above stand. Re-run the cascade to check the instance re-pins again.",{result:k,exitCode:E.exitCode}}let I=IS(k.verification);return I.length>0&&(k.hint=I.join(" ")),{result:k,...bS(k.verification)?{exitCode:b.Transient}:{}}},render:Pq});var gd="modeldesk release create --help",MS=({ref:e})=>e.kind==="commit"?e.id:void 0,yd=e=>({id:e.id,name:e.name}),Dq=async(e,t,n,r,s)=>{if(r!==void 0&&r.toLowerCase()!==t.branch.head.id.toLowerCase())throw new p(`${J(r)} is not the head of ${w(t.name)}: a release is cut at the head.`,{exitCode:b.Validation,hint:`Drop @${r} to release the head.`});if(await Wr(e,t.id,n)!==null)throw new p(`Version name '${w(n)}' already exists for this model.`,{exitCode:b.Validation,hint:`Run 'modeldesk release list ${s}' to see the releases it has.`})},_q=async(e,t,n)=>{let{name:r,description:s}=e.flags,o=MS(e.args.model);if(r===void 0||r.trim()==="")throw $("'release create' on a model needs --name <version>: you name a model's releases.",gd);if(r.includes("@"))throw $(`--name '${w(r)}' must not contain '@': it starts refs such as @HEAD.`,gd);let i=W(e.instance(),{kind:"model",modelId:n.id});if(e.globals.dryRun)return await Dq(t,n,r,o,e.args.model.model),{dryRun:!0,model:yd(n),kind:"model",outcome:"created",release:{name:r,commitId:o??n.branch.head.id,...s?{description:s}:{}},url:i};try{let a=await t.releases.createVersion(n.id,{name:r,...s===void 0?{}:{description:s},...o===void 0?{}:{commitId:o}});return{model:yd(n),kind:"model",outcome:"created",release:Br(a),url:i}}catch(a){throw a instanceof H&&a.status===400?md(a,`Run 'modeldesk release list ${e.args.model.model}' to see the releases it has.`):a}},jq=async(e,t,n,r)=>{if(e.flags.name!==void 0)throw $(`${n.name} is a metamodel-model: its release is named after the standard version it declares, so --name does not apply. Change its standardVersion to release another version.`,gd);if(MS(e.args.model)!==void 0)throw $(`${n.name} is a metamodel-model: its release is always cut at the branch head, so @<commit> does not apply.`,gd);let[s,o]=await Promise.all([pt(t,n.id),t.models.get(n.id)]),i=ld(o),a=cd(s,i),d=e.flags.description??a?.description,l=W(e.instance(),{kind:"model",modelId:n.id});if(e.globals.dryRun){let y=a?.name??i;return{dryRun:!0,model:yd(n),kind:"metamodel",outcome:a?"in-place":"created",release:{...y?{name:y}:{},commitId:n.branch.head.id,...d?{description:d}:{}},standardVersion:i??null,url:l}}let c=d;if(a!==void 0){let y=w(n.name);await it(e,`Re-release ${y} ${w(a.name)} in place? The platform then re-pins the models written in it.`,`Re-releasing ${y} ${w(a.name)} in place`);let k=(await pt(t,n.id)).find(S=>S.id===a.id);c=e.flags.description??k?.description}let m=await t.releases.createMetamodelRelease(n.id,c),f=Un(m),g=Br(m),u=s.find(y=>y.id===g.id),h=u!==void 0&&(u.commitId!==g.commitId||u.builtInCommitId!==f.builtInCommitId);return{model:yd(n),kind:"metamodel",outcome:u?"in-place":"created",release:g,...u?{previousCommitId:u.commitId}:{},standardVersion:i??null,...h&&r!==void 0?{instanceModelCount:r}:{},nextSteps:[{description:`Re-pin and re-release the metamodels depending on ${n.name}, and check the platform's instance re-pins (the platform re-pins instance models only)`,command:`modeldesk release cascade ${n.id}`},...pd([n.name])],url:l}},su=e=>`${e.name?w(e.name):"(named by the server)"} at ${J(e.commitId)}`+(e.description?` ("${w(e.description)}")`:""),Fq=e=>{let t=w(e.model.name),n=e.standardVersion===null?[`${t} declares no standard version, so the server names the release itself.`]:[];return"dryRun"in e?[`Dry run: would ${e.outcome==="in-place"?"overwrite its release in place:":"cut a new release:"} ${t} ${su(e.release)}. Nothing was changed.`,...n].join(`
281
- `):[...e.outcome==="in-place"?[`Re-released ${t} ${su(e.release)} in place (was ${J(e.previousCommitId)}): the same release id, name and date, at the new commit.`,e.previousCommitId===e.release.commitId?"The release already pointed at the head, so nothing moved and no model is re-pinned.":`The platform re-pins the ${P(e.instanceModelCount??0,"model")} written in ${t} in the background.`]:[`Released ${t} ${su(e.release)}.`],...n,` url: ${e.url}`,...hd(e.nextSteps??[])].join(`
282
- `)},AS=O({path:["release","create"],effect:"land-direct",summary:"Release a model, or re-release a metamodel in place",description:"On an ordinary model, cuts a version named --name at main's head (or at <model>@<commit>, which must be the head). On a metamodel-model, releases it under the standard version its head declares: --name and @<commit> do not apply, and re-releasing a version overwrites that release in place (same id, name and date, advanced commit), after which the platform re-pins the instance models in the background; it asks first (--yes when it cannot ask). Without --description an in-place re-release keeps the description it had. A metamodel release needs an interactive super-admin login.",positionals:[_(uh)],flags:{name:{type:"string",placeholder:"name",description:"The version's name; required on an ordinary model, refused on a metamodel-model."},description:{type:"string",placeholder:"text",description:"What the release is, in a sentence."}},dryRun:!0,examples:['modeldesk release create <model> --name 1.2.0 --description "Adds severity"',"modeldesk release create <model> --dry-run"],run:async e=>{await ht(e,e.args.model.model);let t=Ze(e,e.args.model.model),n=e.api(),[r,s]=await Promise.all([t.model.identity(),t.isMetamodelModel()]);if(!s)return{result:await _q(e,n,r)};let o=await t.overview();return{result:await jq(e,n,r,o?.instanceModelCount)}},render:Fq});var qq=["NAME","DATE","COMMIT","DESCRIPTION"],TS=O({path:["release","list"],effect:"read",summary:"List a model's releases",description:"Lists a model's releases newest first, with name, date, commit and description. A metamodel-model's releases are its standard versions; re-releasing one overwrites it in place, so its date stays and its commit moves. A metamodel-model's releases are listed for a super-admin only.",positionals:[_(fe)],listing:{},examples:["modeldesk release list <model>","modeldesk release list <model> --json"],run:async e=>{await ht(e,e.args.model.model);let t=Ze(e,e.args.model.model),n=e.api(),[r,s]=await Promise.all([t.model.identity(),t.isMetamodelModel()]),o=s?await e.list(Vf((await n.metamodelModels.versions(r.id)).map(Un))):await e.list(td(async(a,d)=>(await n.models.versions(r.id,{limit:a,cursor:d})).items.map(Br),a=>a.id));return{result:{model:{id:r.id,name:r.name},kind:s?"metamodel":"model",...o}}},render:e=>{let t=e.kind==="metamodel"?`Releases of ${w(e.model.name)}, a metamodel-model (a re-release overwrites its version in place):`:`Releases of ${w(e.model.name)}:`,n=e.items.map(r=>[w(r.name),r.createdAt,r.commitId,w(r.description??"")]);return[t,...n.length===0?["No releases."]:j([qq,...n])].join(`
283
- `)}});var Bq=["ID","TYPE","PATH"],ou=e=>e==null?[]:Array.isArray(e)?e.flatMap(ou):typeof e=="object"?Object.values(e).flatMap(ou):typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[String(e)]:[],Wq=(e,t,n={})=>{let{type:r,internal:s}=n,o=t.toLowerCase(),i=a=>a?.toLowerCase().includes(o)??!1;return Wt(nt(e,{internal:s})).filter(a=>r===void 0||a.type===r).filter(a=>i(a.label)||Object.values(e.element(a.id)?.attributes??{}).some(d=>ou(d).some(i))).map(a=>({id:a.id,path:a.path,type:a.type,...a.label===void 0?{}:{label:a.label}}))},OS=O({path:["search"],effect:"read",summary:"Find elements of a model by label or attribute value",description:"Finds the elements whose label or any attribute value contains the text, ignoring case, in tree order. Each row carries the element id and its label path, either of which el show takes. The platform's internal `@` elements are searched only with --internal. Without a ref, reads your draft while it holds staged changes.",positionals:[_(wt),{name:"text",type:"string",required:!0,description:"The text to look for."}],flags:{type:{type:"string",placeholder:"type",description:"Find only elements of this type."},...ir},listing:{narrowHint:"Pass --type or longer text to narrow the search."},examples:["modeldesk search <model> severity","modeldesk search <model>@main severity","modeldesk search <model> person --type Objecttype --json"],run:async e=>{let{text:t}=e.args;if(t.trim()==="")throw $("Pass the text to search for.","modeldesk search --help");let{model:n,ref:r,read:s,tree:o}=await dr(e,e.args.model,wt),{internal:i}=e.flags,a=e.flags.type===void 0?void 0:Ri(Cr(s),e.flags.type,i);return{result:{model:n,ref:r,...await e.list(Wq(o,t,{type:a,internal:i}))}}},render:e=>{let t=e.items.map(n=>[n.id,n.type,w(n.path)]);return[$e(e.ref,e.model),...t.length===0?["No matches."]:j([Bq,...t])].join(`
284
- `)}});var Uq=/<([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^\s<>"'=/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s<>"'=]+))?)*)\s*\/?>/g,Hq=/([^\s<>"'=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s<>"'=]+)))?/g,Gq=/^ {0,3}#{1,6}[ \t].*\{#([\w-]+)\}[ \t]*$/gm,Vq=/\]\(#([^)\s]+)\)/g,Kq=/<!--[\s\S]*?-->/g,Yq={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},zq=e=>e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,(t,n)=>n.startsWith("#x")?String.fromCodePoint(Number.parseInt(n.slice(2),16)):n.startsWith("#")?String.fromCodePoint(Number.parseInt(n.slice(1),10)):Yq[n]),Jq=e=>{let t=new Map;for(let n of e.matchAll(Hq)){let r=n[1].toLowerCase();t.has(r)||t.set(r,zq(n[2]??n[3]??n[4]??""))}return t},Xq=e=>e.replace(Kq,t=>t.replace(/[^\n]/g," ")),NS=e=>{let t=[0];for(let n=e.indexOf(`
285
+ `},AT=(e,t,n)=>{let r=`[${e.step}/${n}]`;if(e.status==="failed")return`${r} FAILED: ${ii(t)}: ${g(e.error?.message??"")}
286
+ `;if(e.status==="skipped")return`${r} skipped: ${ii(t)}, since none of its pins moved
287
+ `;if(e.release)return`${r} done: ${ii(t)}, at ${Z(e.release.commitId)}
288
+ `;let o=e.changed&&t.kind!=="re-release"?`${Z(t.fromCommitId)} -> ${Z(e.commitId)}`:`already at ${Z(e.commitId)}`;return`${r} done: ${ii(t)} (${o})
289
+ `},$T=(e,t)=>` ${g(e.name)} (${e.id}) pins ${g(t.name)} ${g(e.version)} `+(e.builtInCommitId?`with its built-in elements at ${Z(e.builtInCommitId)}, not ${Z(e.expectedBuiltInCommitId)}`:`at ${Z(e.commitId)}, not ${Z(e.expectedCommitId)}`),ul=e=>e.map(t=>`${g(t.name)} (${t.id})`).join(", "),OT=e=>[`Instance re-pins (${e.scope==="all"?"every release of the family":"the releases this run moved"}): ${e.repinned} at their release's commit, ${e.behind} still behind after ${e.timeoutSeconds} s, ${e.stuck} behind a release this run did not move, ${e.unverified} not read.`,...e.models.flatMap(t=>[...t.behind.map(n=>$T(n,t)),...t.stuck.map(n=>`${$T(n,t)} (not waited on)`),...t.unverified.length>0?[` ${g(t.name)}: not verified, never read before the timeout: ${ul(t.unverified)}`]:[],...t.unknownRelease.map(n=>` ${g(n.name)} (${n.id}) pins ${g(t.name)} ${g(n.version??"(no version)")}, which has no release: it cannot be verified`),...t.gone.length>0?[` ${g(t.name)}: deleted while being checked: ${ul(t.gone)}`]:[],...t.otherRelease>0?[` ${g(t.name)}: ${P(t.otherRelease,"instance model")} pin another release, which this run did not move (--verify-all checks them)`]:[],...t.truncated?[` ${g(t.name)}: more instance models exist than were checked`]:[]])],MT=e=>{let t=e.models.flatMap(r=>r.stuck),n=e.models.flatMap(r=>r.unknownRelease);return[...e.unverified>0?[`${P(e.unverified,"instance model")} could not be read before the timeout, so ${e.unverified===1?"its pins are":"their pins are"} not verified: re-run the cascade to check again.`]:[],...e.behind>0?["Re-run the cascade to check again (it plans to no-ops and re-reads the pins). A model that stays behind across runs was skipped by the platform's background re-pin; the repin-models maintenance task re-pins every dependent idempotently."]:[],...t.length>0?[`Not waited on, since the platform moves them on no release of this run: ${ul(t)}; the repin-models maintenance task re-pins them.`]:[],...n.length>0?[`Not verifiable, since they pin a version that has no release: ${ul(n)}; re-pin them in the app's model settings.`]:[]]};var YV=e=>e.map(t=>g(t).replace(/["\\$`,]/g,"")).join(","),hl=e=>{let t=YV(e);return[{description:"Regenerate the committed bundles of what was released, from the repository root",command:`config/metamodels/regenerate.sh --models "${t}"`},{description:"Review the regenerated bundles in config/metamodels/ and commit them"},{description:"Promote them to each target environment: from backend/, with TARGET_API_URL and TARGET_SERVICE_TOKEN set for that environment (add --dry-run first to see its plan)",command:`java -jar maintenance/target/modeldesk-backend-maintenance-*-exec.jar push-metamodels --models "${t}"`}]},gl=e=>e.length===0?[]:["Next steps (the CLI runs none of these):",...e.flatMap((t,n)=>[` ${n+1}. ${t.description}${t.command?":":"."}`,...t.command?[` ${t.command}`]:[]])];var Iu="modeldesk release cascade --help",KV="Re-run the cascade to resume: it plans again from live state, so the finished steps read as no-ops and only the rest runs.",NT=(e,t,n)=>{if(!Number.isInteger(e)||e<1)throw k(`${t} must be a positive whole number, got ${e}.`,Iu);if(n!==void 0&&e>n)throw k(`${t} is at most ${n}, got ${e}.`,Iu);return e},zV=e=>{let t=g(e.modelName);if(e.kind==="head")return`${t}'s head moved (${Z(e.from)} -> ${Z(e.to)})`;let n=`${t} ${g(e.release??"")}`;return e.from===void 0?`${n} was released`:e.to===void 0?`${n} was removed`:`${n} was re-released (${Z(e.from)} -> ${Z(e.to)})`},JV=e=>{if(e.length>0)throw new f(`The metamodels changed after the plan was made: ${e.map(zV).join("; ")}. Nothing was changed.`,{exitCode:b.Conflict,hint:"Re-run the cascade to plan again from what is there now.",details:{changes:e}})},Su=e=>e.filter(t=>t.status==="done"&&t.release!==void 0),XV=(e,t,n)=>{let r=new Map(Su(t).map(o=>[o.modelId,o.release]));return Object.values(e.models).flatMap(o=>{let s=r.get(o.id),i=s?.moved?s.name:void 0;return i===void 0&&!(n&&(o.released||s!==void 0))?[]:[{id:o.id,name:o.name,role:o.role,...o.baseId?{baseId:o.baseId}:{},releasedNow:s!==void 0,...i?{awaited:i}:{}}]})},QV=e=>({message:e.message,code:e.exitCode,...e.type?{type:e.type}:{}}),ZV=e=>{let t=e.steps.find(a=>a.status==="failed"),n=e.steps.filter(a=>a.status==="done").length,r=e.steps.filter(a=>a.status==="skipped").length,o=r>0?`, ${r} skipped`:"",s=`${P(n,"step")} run${o}`;return[{planned:"Dry run: nothing was changed.","nothing-to-do":"Every pin and release is current: nothing to run.",completed:`Cascade complete: ${s}.`,failed:`Stopped at step ${t?.step}, after ${s} (they stay done).`}[e.outcome],...e.verification?OT(e.verification):[],...e.verificationError?[`Checking the instance re-pins failed: ${g(e.verificationError.message)}`]:[],...e.hint?[e.hint]:[],` url: ${e.url}`,...gl(e.nextSteps)].join(`
290
+ `)},PT=J({path:["release","cascade"],effect:"publish",summary:"Re-pin and re-release the metamodels depending on a metamodel",audience:"super-admin",description:"Plans from live state over the metamodel-models that depend on <base> (transitively) and the extensions of any of them: which dependency pins to refresh, which extensions to re-pin to their base, which models to re-release in place (those whose pins move or whose release trails their head, unreleased edits included), and which pins are already current. It prints the plan and asks to go on (--yes when it cannot ask), checks that nothing moved since the plan, runs the steps in order and stops at the first failure. Then it waits for the platform to re-pin the instance models of the releases it moved, and names any left behind or not verified; --verify-all checks every release of the family. Re-running it plans again, so finished steps read as no-ops. Needs an interactive super-admin login.",positionals:[{name:"base",type:{address:"model",slot:de},required:!0,description:"The id of the metamodel-model that changed, from model list --kind metamodel."}],flags:{timeout:{type:"number",placeholder:"seconds",default:120,description:"How many seconds to wait for the platform to re-pin the instance models."},"instance-limit":{type:"number",placeholder:"n",default:50,description:`How many instance models to check per metamodel, at most ${Ru}.`},"verify-all":{type:"boolean",description:"Check the instance pins of every release in the family, not only the releases this run moved."}},dryRun:!0,examples:["modeldesk release cascade <model> --dry-run","modeldesk release cascade <model> --yes --json"],run:async e=>{let t=NT(e.flags.timeout,"--timeout"),n=NT(e.flags["instance-limit"],"--instance-limit",Ru),r=e.flags["verify-all"],o=dt(e,e.args.base.model),s=e.api(),[i,a]=await Promise.all([o.model.identity(),o.isMetamodelModel()]);if(!a)throw k(`'release cascade' does not apply to ${g(i.name)}, which is a model. A model's dependents own their pins: list them with 'modeldesk pin list', move one with 'modeldesk pin set'.`,Iu);let d=await RT(s,i.id,await s.releases.metamodelOverview()),l=Cb(d),c=Eb(l);e.print(xT(l));let m={id:i.id,name:i.name},p=be(e.instance(),{kind:"model",modelId:i.id});if(e.globals.dryRun)return{result:{base:m,plan:l,outcome:"planned",steps:[],nextSteps:[],url:p}};c.length>0&&(await yt(e,`Run the ${P(c.length,"step")} of this cascade?`,`The release cascade from ${g(i.name)}`),JV(await kT(s,d)));let h=new Map(c.map($=>[$.step,$])),u=await CT(s,c,$=>{let C=h.get($.step);C&&e.print(AT($,C,c.length))}),y=$=>$.length>0?hl($.map(C=>C.modelName)):[];if(u.failure)return{result:{base:m,plan:l,outcome:"failed",steps:u.outcomes,nextSteps:y(Su(u.outcomes)),hint:KV,url:p},exitCode:u.failure.exitCode};let w=c.length===0?"nothing-to-do":"completed",E={base:m,plan:l,outcome:w,steps:u.outcomes,nextSteps:y(Su(u.outcomes)),url:p},I=XV(d,u.outcomes,r);if(I.length===0)return{result:E};e.print(`Checking the platform's instance re-pins (up to ${t} s)...
291
+ `);try{E.verification=await ST(s,I,{timeoutMs:t*1e3,limit:n,clock:nl,scope:r?"all":"run"})}catch($){let C=si($);return E.verificationError=QV(C),E.hint="The steps above stand. Re-run the cascade to check the instance re-pins again.",{result:E,exitCode:C.exitCode}}let v=MT(E.verification);return v.length>0&&(E.hint=v.join(" ")),{result:E,...IT(E.verification)?{exitCode:b.Transient}:{}}},render:ZV});var DT={releaseCreate:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},kind:{type:"string",description:'`model` for a model\'s named version, `metamodel` for a metamodel\'s standard-version release. One of "metamodel", "model".'},outcome:{type:"string",description:'`created`, or `in-place` for a metamodel\'s release overwritten at an advanced commit. One of "created", "in-place".'},release:{type:"object",properties:{id:{type:"string"},name:{type:"string",description:"Absent where the server names the release."},commitId:{type:"string",description:"The commit the release points at; an in-place re-release advances it."},createdAt:{type:"string"},description:{type:"string"}}},previousCommitId:{type:"string",description:"In place: the commit before."},standardVersion:{},instanceModelCount:{type:"number",description:"Metamodel, moved in place: the models the platform re-pins."},nextSteps:{type:"array",items:{type:"object",properties:{description:{type:"string"},command:{type:"string",description:"The exact command, when the step is one."}}},description:"Metamodel: what is left to do."},url:{type:"string"},dryRun:{type:"boolean",description:"Always true."},moves:{type:"object",properties:{pinnedModelCount:{type:"number"},platformPinnedModelCount:{type:"number"},commitsSince:{type:"array",items:{type:"object",properties:{id:{type:"string"},message:{type:"string"}}}},moreCommitsSince:{type:"boolean",description:"Whether more commits than those listed may have landed since: the release's commit was not among them. One of false, true."},builtInCommitsSince:{items:{type:"object",properties:{id:{type:"string"},message:{type:"string"}}},description:"Newest first, at most 50; null where the server did not say, so nothing is known of them. May be null."},moreBuiltInCommitsSince:{type:"boolean",description:"Whether more built-in element model commits than those listed may have landed since. One of false, true."}},description:"Metamodel, where a release of that version exists: what releasing it again moves. The live models pinned to it, the platform organization's own counted apart, which the platform re-pins after it; the commits on main since the commit it points at, newest first, at most {@link SINCE_LIMIT}; and the commits of the metamodel's built-in element model since the one the release pinned, which the release ships as they stand."}},required:["schemaVersion","model","kind","outcome","release","url"]}};var Tu="modeldesk release create --help",LT=50,t2=async(e,t,n)=>{let[r,o]=await Promise.all([e.metamodelModels.dependents(t),e.models.commits(t,{limit:LT+1,includeSystem:!0})]),s=r.versions.find(l=>l.name===n.name),i=o.items.findIndex(l=>l.id.toLowerCase()===n.commitId.toLowerCase()),a=(i===-1?o.items:o.items.slice(0,i)).slice(0,LT),d=s?.moreBuiltInElementModelCommitsSince;return{pinnedModelCount:s?.pinnedModelCount??0,platformPinnedModelCount:s?.platformPinnedModelCount??0,commitsSince:a.map(_T),moreCommitsSince:i===-1,builtInCommitsSince:d===void 0?null:(s?.builtInElementModelCommitsSince??[]).map(_T),moreBuiltInCommitsSince:d??!1}},_T=e=>({id:e.id,...e.message?{message:e.message}:{}}),FT=({ref:e})=>e.kind==="commit"?e.id:void 0,yl=e=>({id:e.id,name:e.name}),qT=e=>e.agent?.surface==="mcp",WT=(e,t,n)=>{if(qT(e)&&!e.dryRun&&n===void 0)throw new f(`Releasing ${g(t.name)} needs the commit its dry run reported, as <model>@<commitId>, so the release is the one the person agreed to. Nothing was changed.`,{exitCode:b.Validation,hint:`Call it again with model ${e.args.model.model}@<commitId>, the commitId of the dry run you showed the person.`})},n2=async(e,t,n,r,o)=>{if(r!==void 0&&r.toLowerCase()!==t.branch.head.id.toLowerCase())throw new f(`${Z(r)} is not the head of ${g(t.name)}: a release is cut at the head.`,{exitCode:b.Validation,hint:`Drop @${r} to release the head.`});if(await Qr(e,t.id,n)!==null)throw new f(`Version name '${g(n)}' already exists for this model.`,{exitCode:b.Validation,hint:`Run 'modeldesk release list ${o}' to see the releases it has.`})},r2=async(e,t,n)=>{let{name:r,description:o}=e.flags,s=FT(e.args.model);if(r===void 0||r.trim()==="")throw k("'release create' on a model needs --name <version>: you name a model's releases.",Tu);if(r.includes("@"))throw k(`--name '${g(r)}' must not contain '@': it starts refs such as @HEAD.`,Tu);let i=e.webUrl({kind:"model",modelId:n.id});if(WT(e,n,s),e.dryRun)return await n2(t,n,r,s,e.args.model.model),{dryRun:!0,model:yl(n),kind:"model",outcome:"created",release:{name:r,commitId:s??n.branch.head.id,...o?{description:o}:{}},url:i};try{let a=await t.releases.createVersion(n.id,{name:r,...o===void 0?{}:{description:o},...s===void 0?{}:{commitId:s}});return{model:yl(n),kind:"model",outcome:"created",release:Xr(a),url:i}}catch(a){throw a instanceof V&&a.status===400?ua(a,`Run 'modeldesk release list ${e.args.model.model}' to see the releases it has.`):a}},o2=async(e,t,n)=>{let{overwritten:r,standardVersion:o,description:s,url:i}=n,a=r?.name??o;return{dryRun:!0,model:yl(t),kind:"metamodel",outcome:r?"in-place":"created",release:{...a?{name:a}:{},commitId:t.branch.head.id,...s?{description:s}:{}},standardVersion:o??null,...r?{moves:await t2(e,t.id,r)}:{},url:i}},s2=async(e,t,n,r,o)=>{if(e.flags.name!==void 0)throw k(`${n.name} is a metamodel-model: its release is named after the standard version it declares, so --name does not apply. Change its standardVersion to release another version.`,Tu);let s=FT(e.args.model);if(WT(e,n,s),s!==void 0&&s.toLowerCase()!==n.branch.head.id.toLowerCase())throw new f(`${g(n.name)} moved to ${Z(n.branch.head.id)} past ${Z(s)}, so nothing was released: a metamodel-model is released at the head.`,{exitCode:b.Conflict,hint:`Run 'modeldesk release create ${n.id} --dry-run' to see what it would release now.`,hosted:{hint:I=>`Call ${I("release create")} with dryRun: true again, show the person what it would release now, and ask again.`}});let[i,a]=await Promise.all([it(t,n.id),t.models.get(n.id)]),d=rs(a),l=Jo(i,d),c=e.flags.description??l?.description,m=e.webUrl({kind:"model",modelId:n.id});if(e.dryRun)return o2(t,n,{overwritten:l,standardVersion:d,description:c,url:m});let p=c;if(l!==void 0){let I=qT(e)&&s!==void 0;if(o?.inPlace!==l.id&&!I)throw new f(`Re-releasing ${g(n.name)} ${g(l.name)} in place needs the person's confirmation, which this run did not get. Nothing was changed.`,{exitCode:b.NeedsHuman,hint:"Re-run at a terminal, or with --yes to confirm.",hosted:{hint:"Call it with dryRun: true, show the person what releasing it again moves, and on their word call it again with model given as <model>@<commitId> of that dry run."}});let v=(await it(t,n.id)).find($=>$.id===l.id);p=e.flags.description??v?.description}let h=await t.releases.createMetamodelRelease(n.id,p,s),u=er(h),y=Xr(h),w=i.find(I=>I.id===y.id),E=w!==void 0&&(w.commitId!==y.commitId||w.builtInCommitId!==u.builtInCommitId);return{model:yl(n),kind:"metamodel",outcome:w?"in-place":"created",release:y,...w?{previousCommitId:w.commitId}:{},standardVersion:d??null,...E&&r!==void 0?{instanceModelCount:r}:{},nextSteps:e.agent?.surface==="mcp"?[{description:`Tell the person that the metamodels depending on ${n.name} are re-pinned and re-released, and the released bundles regenerated and promoted, at a shell`}]:[{description:`Re-pin and re-release the metamodels depending on ${n.name}, and check the platform's instance re-pins (the platform re-pins instance models only)`,command:`modeldesk release cascade ${n.id}`},...hl([n.name])],url:m}},$u=e=>`${e.name?g(e.name):"(named by the server)"} at ${Z(e.commitId)}`+(e.description?` ("${g(e.description)}")`:""),i2=e=>e===void 0?[]:[`The platform then re-pins ${P(e.pinnedModelCount,"model")} of other organizations and ${P(e.platformPinnedModelCount,"model")} of the platform's own pinned to it.`,`${P(e.commitsSince.length,"commit")} on main since the release${e.moreCommitsSince?", and more":""}:`,...e.commitsSince.map(jT),...e.builtInCommitsSince===null?["The built-in element model's commits since the release could not be read."]:[`${P(e.builtInCommitsSince.length,"commit")} on the built-in element model since the release${e.moreBuiltInCommitsSince?", and more":""}${e.builtInCommitsSince.length===0?".":":"}`,...e.builtInCommitsSince.map(jT)]],jT=e=>` ${Z(e.id)} ${g((e.message??"").split(/\r?\n/)[0])}`,a2=e=>{let t=g(e.model.name),n=e.standardVersion===null?[`${t} declares no standard version, so the server names the release itself.`]:[];return"dryRun"in e?[`Dry run: would ${e.outcome==="in-place"?"overwrite its release in place:":"cut a new release:"} ${t} ${$u(e.release)}. Nothing was changed.`,...n,...i2(e.moves)].join(`
292
+ `):[...e.outcome==="in-place"?[`Re-released ${t} ${$u(e.release)} in place (was ${Z(e.previousCommitId)}): the same release id, name and date, at the new commit.`,e.previousCommitId===e.release.commitId?"The release already pointed at the head, so nothing moved and no model is re-pinned.":`The platform re-pins the ${P(e.instanceModelCount??0,"model")} written in ${t} in the background.`]:[`Released ${t} ${$u(e.release)}.`],...n,` url: ${e.url}`,...gl(e.nextSteps??[])].join(`
293
+ `)},d2=async e=>{if(e.dryRun||e.flags.name!==void 0)return;let t=dt(e,e.args.model.model);if(!await t.isMetamodelModel())return;let n=e.api(),r=await t.model.identity(),[o,s]=await Promise.all([it(n,r.id),n.models.get(r.id)]),i=Jo(o,rs(s));if(i===void 0)return;let a=g(r.name);return await yt(e,`Re-release ${a} ${g(i.name)} in place? The platform then re-pins the models written in it.`,`Re-releasing ${a} ${g(i.name)} in place`),{inPlace:i.id}},HT=A({path:["release","create"],effect:"publish",summary:"Release a model",description:["Cuts a version of the model named --name at main's head (or at <model>@<commit>, which must be the head).",{audience:"super-admin",text:"On a metamodel-model, releases it under the standard version its head declares: --name does not apply, @<commit> only holds the release to a head that has not moved (exit 5), and re-releasing a version overwrites that release in place (same id, name and date, advanced commit), after which the platform re-pins the instance models in the background; it asks first (--yes when it cannot ask). Without --description an in-place re-release keeps the description it had. A metamodel release needs an interactive super-admin login."}],positionals:[N(Hg)],flags:{name:{type:"string",placeholder:"name",description:"The version's name, which a model's release needs."},description:{type:"string",placeholder:"text",description:"What the release is, in a sentence."}},dryRun:!0,examples:['modeldesk release create <model> --name 1.2.0 --description "Adds severity"',"modeldesk release create <model> --dry-run"],mcp:{name:"release_create",description:"Cuts a version of the model named name at the head of main, which people outside the organization can see and nobody can take back. First call it with dryRun: true, which reports the release it would cut, commitId included, and writes nothing, and model_log on main for the commits since the last release (its rows name the releases cut at each commit); show the person both and release only on their word, with model given as <model>@<commitId> of that dry run, so main moving in between is refused rather than released. It needs the person's 'Publish' permission and an organization that lets agents publish."},resultSchema:DT.releaseCreate,prepare:d2,run:async(e,t)=>{let n=dt(e,e.args.model.model),r=e.api(),[o,s]=await Promise.all([n.model.identity(),n.isMetamodelModel()]);if(!s)return{result:await r2(e,r,o)};let i=await n.overview();return{result:await s2(e,r,o,i?.instanceModelCount,t)}},render:a2});var l2=["NAME","DATE","COMMIT","DESCRIPTION"],BT=J({path:["release","list"],effect:"read",summary:"List a model's releases",description:["Lists a model's releases newest first, with name, date, commit and description.",{audience:"super-admin",text:"A metamodel-model's releases are its standard versions; re-releasing one overwrites it in place, so its date stays and its commit moves. A metamodel-model's releases are listed for a super-admin only."}],positionals:[N(de)],listing:{},examples:["modeldesk release list <model>","modeldesk release list <model> --json"],run:async e=>{let t=dt(e,e.args.model.model),n=e.api(),[r,o]=await Promise.all([t.model.identity(),t.isMetamodelModel()]),s=o?await e.list(om((await n.metamodelModels.versions(r.id)).map(er))):await e.list(sl(async(a,d)=>(await n.models.versions(r.id,{limit:a,cursor:d})).items.map(Xr),a=>a.id));return{result:{model:{id:r.id,name:r.name},kind:o?"metamodel":"model",...s}}},render:e=>{let t=e.kind==="metamodel"?`Releases of ${g(e.model.name)}, a metamodel-model (a re-release overwrites its version in place):`:`Releases of ${g(e.model.name)}:`,n=e.items.map(r=>[g(r.name),r.createdAt,r.commitId,g(r.description??"")]);return[t,...n.length===0?["No releases."]:W([l2,...n])].join(`
294
+ `)}});var UT={search:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What was read: a branch, your draft or a commit, as the address resolved."},items:{type:"array",items:{type:"object",properties:{id:{type:"string"},path:{type:"string"},type:{type:"string"},label:{type:"string"}}}},truncated:{type:"boolean",description:"True when more rows exist than this page carries. One of false, true."},nextCursor:{type:"string",description:"Where the next page starts, to continue from; present exactly when truncated."},hint:{type:"string",description:"One line on how to continue or narrow the query; present exactly when truncated."}},required:["schemaVersion","model","ref","items","truncated"]}};var m2=["ID","TYPE","PATH"],xu=e=>e==null?[]:Array.isArray(e)?e.flatMap(xu):typeof e=="object"?Object.values(e).flatMap(xu):typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[String(e)]:[],p2=(e,t,n={})=>{let{type:r,internal:o}=n,s=t.toLowerCase(),i=a=>a?.toLowerCase().includes(s)??!1;return ln(ft(e,{internal:o})).filter(a=>r===void 0||a.type===r).filter(a=>i(a.label)||Object.values(e.element(a.id)?.attributes??{}).some(d=>xu(d).some(i))).map(a=>({id:a.id,path:a.path,type:a.type,...a.label===void 0?{}:{label:a.label}}))},GT=A({path:["search"],effect:"read",summary:"Find elements of a model by label or attribute value",description:"Finds the elements whose label or any attribute value contains the text, ignoring case, in tree order. Each row carries the element id and its label path, either of which el show takes. The platform's internal `@` elements are searched only with --internal. Without a ref, reads your draft while it holds staged changes.",positionals:[N(Nt),{name:"text",type:"string",required:!0,description:"The text to look for."}],flags:{type:{type:"string",placeholder:"type",description:"Find only elements of this type."},...Dr},listing:{narrowHint:"Pass --type or longer text to narrow the search.",toolNarrowHint:"Give a type or longer text to narrow the search."},examples:["modeldesk search <model> severity","modeldesk search <model>@main severity","modeldesk search <model> person --type Objecttype --json"],mcp:{name:"search_elements",description:"Finds the model's elements whose label or any attribute value contains text, ignoring case, in tree order. Each row carries the element's id and label path, either of which stage_changes takes to address it. Narrow with type; internal: true includes the platform's own @ elements. A long result is truncated with nextCursor. Write the ref (model@agent/<topic>) to read where you work.",slot:_e},resultSchema:UT.search,run:async e=>{let{text:t}=e.args;if(t.trim()==="")throw k("Pass the text to search for.","modeldesk search --help");let{model:n,ref:r,read:o,tree:s}=await Lr(e,e.args.model,Nt),{internal:i}=e.flags,a=e.flags.type===void 0?void 0:Ia(oo(o),e.flags.type,i);return{result:{model:n,ref:r,...await e.list(p2(s,t,{type:a,internal:i}))}}},render:e=>{let t=e.items.map(n=>[n.id,n.type,g(n.path)]);return[Ae(e.ref,e.model),...t.length===0?["No matches."]:W([m2,...t])].join(`
295
+ `)}});var f2=/<([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^\s<>"'=/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s<>"'=]+))?)*)\s*\/?>/g,u2=/([^\s<>"'=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s<>"'=]+)))?/g,h2=/^ {0,3}#{1,6}[ \t].*\{#([\w-]+)\}[ \t]*$/gm,g2=/\]\(#([^)\s]+)\)/g,y2=/<!--[\s\S]*?-->/g,w2={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},b2=e=>e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,(t,n)=>n.startsWith("#x")?String.fromCodePoint(Number.parseInt(n.slice(2),16)):n.startsWith("#")?String.fromCodePoint(Number.parseInt(n.slice(1),10)):w2[n]),E2=e=>{let t=new Map;for(let n of e.matchAll(u2)){let r=n[1].toLowerCase();t.has(r)||t.set(r,b2(n[2]??n[3]??n[4]??""))}return t},C2=e=>e.replace(y2,t=>t.replace(/[^\n]/g," ")),VT=e=>{let t=[0];for(let n=e.indexOf(`
285
296
  `);n!==-1;n=e.indexOf(`
286
- `,n+1))t.push(n+1);return n=>{let r=0,s=t.length-1;for(;r<s;){let o=r+s+1>>1;t[o]<=n?r=o:s=o-1}return r+1}},Qq=e=>{let t=NS(e);return[...e.matchAll(Uq)].map(n=>({name:n[1].toLowerCase(),attributes:Jq(n[2]),line:t(n.index)}))},pn=e=>`${e.kind} '${e.title}'`,LS=(e,t)=>{let n=t.elements??[],r=new Map(n.map(a=>[a.anchor,a])),s=new Map(n.map(a=>[a.id,a])),o=[],i=new Map;for(let[a,d]of e){let l=Xq(d),c=NS(l),m=new Set;i.set(a,m);for(let f of Qq(l)){let g=f.attributes.get("id"),u=f.attributes.get("data-md-element"),h=g===void 0?void 0:r.get(g);if(h!==void 0)m.add(h.anchor),u!==h.id&&o.push({kind:"unmarked-container",path:a,line:f.line,message:u===void 0?`<${f.name} id="${g}"> declares the anchor of ${pn(h)} but carries no data-md-element.`:`<${f.name} id="${g}"> declares the anchor of ${pn(h)} but its data-md-element names '${u}'.`});else if(u!==void 0){let S=s.get(u);o.push(S===void 0?{kind:"unindexed-container",path:a,line:f.line,message:`<${f.name}> carries data-md-element="${u}", an element the index does not list.`}:{kind:"unmarked-container",path:a,line:f.line,message:`<${f.name}> carries the markers of ${pn(S)} but not its anchor, id="${S.anchor}".`})}let y=f.name==="a"?f.attributes.get("href"):void 0,k=y?.startsWith("#")?r.get(y.slice(1)):void 0;k!==void 0&&f.attributes.get("data-md-ref")!==k.id&&o.push({kind:"unmarked-link",path:a,line:f.line,message:`The link to ${pn(k)} (${y}) carries no data-md-ref="${k.id}".`})}for(let f of l.matchAll(Gq)){let g=r.get(f[1]);g!==void 0&&(m.add(g.anchor),o.push({kind:"unmarked-container",path:a,line:c(f.index),message:`A Markdown heading declares the anchor of ${pn(g)} and cannot carry its markers; write it as <hN id="${g.anchor}" data-md-element="${g.id}">.`}))}for(let f of l.matchAll(Vq)){let g=r.get(f[1]);g!==void 0&&o.push({kind:"unmarked-link",path:a,line:c(f.index),message:`A Markdown link to ${pn(g)} (#${f[1]}) cannot carry data-md-ref; write it as <a href="#${f[1]}" data-md-ref="${g.id}">.`})}}for(let a of n){let d=i.get(a.path);(d===void 0||!d.has(a.anchor))&&o.push({kind:"missing-container",path:a.path,message:d===void 0?`The index places ${pn(a)} in ${a.path}, which the document does not have.`:`The index places ${pn(a)} in ${a.path}, which does not declare its anchor '${a.anchor}'.`})}return o};import{existsSync as Zq,readdirSync as eB,readFileSync as DS,statSync as tB}from"node:fs";import{join as _S,relative as nB,resolve as rB,sep as jS}from"node:path";var PS="index.json",sB=".md",FS=O({path:["template","lint"],effect:"local",summary:"Check a rendered document against the marker convention its index.json relies on",description:"Reads the document's index.json and every Markdown fragment beside it, and checks that each element's anchor is declared where its markers are, each link to an element is marked, each element of the index is declared in its file, and no file marks an element the index does not list. Each problem is printed with its file and line; any problem exits 4.",positionals:[{name:"dir",type:"string",required:!0,description:"The folder that holds the document's index.json beside its fragments (data/model in a repo)."}],examples:["modeldesk template lint data/model","modeldesk template lint data/model --json"],run:async({args:e,cwd:t})=>{let n=rB(t,e.dir),r=oB(n),s=dB(n,(r.elements??[]).map(d=>d.path)),o=lB(n,s),i=LS(o,r);return{result:{dir:e.dir,files:o.size,elements:r.elements?.length??0,problems:i},...i.length===0?{}:{exitCode:b.Validation}}},render:({files:e,elements:t,problems:n})=>[...n.map(r=>`${mB(r)}: ${r.message}`),n.length===0?`No problems in ${e} file(s) against ${t} element(s) of the index.`:`${n.length} problem(s) in ${e} file(s).`].join(`
287
- `)}),oB=e=>{let t=_S(e,PS);if(!Zq(t))throw new p(`There is no ${PS} in ${e}; name the folder a pull writes it to, such as data/model.`);let n;try{n=JSON.parse(DS(t,"utf8"))}catch(s){throw new p(`${t} is not JSON: ${s instanceof Error?s.message:String(s)}`)}let r=aB(n);if(r!==void 0)throw new p(`${t} is not a document index: ${r}. Pull the bundle again to rewrite it.`);return n},iB=["id","anchor","path","title","kind"],aB=e=>{let t=typeof e=="object"&&e!==null?e.elements:void 0;if(!Array.isArray(t))return"it has no list of elements";for(let[n,r]of t.entries()){let s=typeof r=="object"&&r!==null?r:{},o=iB.find(i=>typeof s[i]!="string");if(o!==void 0)return`element ${n+1} has no ${o}`}},dB=(e,t)=>{if(t.length===0)return"";let n=t.map(o=>o.split("/").slice(0,-1)),r=[];for(let[o,i]of n[0].entries()){if(!n.every(a=>a[o]===i))break;r.push(i)}let s=e.split(jS).filter(o=>o!=="");for(let o=r.length;o>0;o-=1){let i=r.slice(0,o);if(i.every((a,d)=>s[s.length-o+d]===a))return`${i.join("/")}/`}return""},lB=(e,t)=>{let n=new Map,r=s=>{for(let o of eB(s,{withFileTypes:!0})){let i=_S(s,o.name);o.isDirectory()?r(i):o.isFile()&&o.name.endsWith(sB)&&n.set(t+nB(e,i).split(jS).join("/"),DS(i,"utf8"))}};return tB(e).isDirectory()&&r(e),new Map([...n].sort(([s],[o])=>cB(s,o)))},cB=(e,t)=>e===t?0:e<t?-1:1,mB=({path:e,line:t})=>t===void 0?e:`${e}:${t}`;var fB={error:new Set(["ERROR"]),warning:new Set(["ERROR","WARN"])},qS=["ERROR","WARN","INFO"],uB=["LEVEL","ELEMENT","CODE","MESSAGE"],BS=e=>{let t=qS.indexOf(e);return t===-1?qS.length:t},pB=e=>[...e].sort((t,n)=>BS(t.logLevel)-BS(n.logLevel)),hB=e=>{let t=n=>e.filter(r=>r.logLevel===n).length;return{error:t("ERROR"),warn:t("WARN"),info:t("INFO")}},gB=async(e,t,n,r)=>{if(r.size===0)return new Map;let s=await e.models.get(t,{...st(n),expand:["labels"]});return new Map(Wt(nt(Bt(s))).filter(o=>r.has(o.id)).map(o=>[o.id,o.path]))},yB=(e,t)=>{let n=e.modelElementId===void 0?void 0:t.get(e.modelElementId);return{logLevel:e.logLevel,code:e.code,title:e.title,detailMessage:e.detailMessage,...e.modelElementId===void 0?{}:{modelElementId:e.modelElementId},...n===void 0?{}:{elementPath:n},...e.property===void 0?{}:{property:e.property,...e.valueIndex===void 0?{}:{valueIndex:e.valueIndex}}}},wB=e=>{let{counts:t,gate:n}=e,r=e.logEntries.map(o=>[o.logLevel,w(o.elementPath??o.modelElementId??""),w(o.code),w(o.detailMessage)]),s=`${n.passed?"passes":"fails"} --fail-on ${n.failOn}`;return[$e(e.ref,e.model),...r.length===0?["No findings."]:j([uB,...r]),...e.hint?[e.hint]:[],`${P(t.error,"error")}, ${P(t.warn,"warning")}, ${t.info} info: ${s}.`].join(`
288
- `)},WS=O({path:["validate"],effect:"read",summary:"Validate a model and gate on its findings",description:"Runs the server's validation of a model, metamodel-models included, and lists its findings errors first. Exits 4 when a finding at or above --fail-on exists: any ERROR by default, any ERROR or WARN with --fail-on warning. INFO never fails, and neither does the server marking a model invalid over warnings alone. Without a ref it validates your draft while it holds staged changes, else your working branch head. When a listed finding names an element, one more read of the model gives the element its label path.",positionals:[_(ar)],flags:{"fail-on":{type:{enum:["error","warning"]},default:"error",placeholder:"level",description:"The least severe level that fails the gate (exit 4): error, or warning for ERROR and WARN."},limit:{type:"number",default:vd,placeholder:"n",description:"List at most this many findings, errors first; the counts and the gate cover them all."}},examples:["modeldesk validate <model>","modeldesk validate <model>@draft --fail-on warning","modeldesk validate <model>@feat/shapes --json"],run:async e=>{let{limit:t}=e.flags,n=e.flags["fail-on"];if(!Number.isInteger(t)||t<1)throw $(`--limit must be a positive whole number, got ${t}.`,"modeldesk validate --help");let r=e.api(),s=await Z(e,e.args.model,ar),{id:o}=s,i=await r.validation.get(o,st(s.ref)),a=pB(i.logEntries),d=a.slice(0,t),l=new Set(d.flatMap(u=>u.modelElementId?[u.modelElementId]:[])),c=await gB(r,o,s.ref,l),m=!a.some(u=>fB[n].has(u.logLevel)),f=d.length<a.length;return{result:{model:{id:o,name:s.name},ref:de(s),valid:i.valid,counts:hB(a),logEntries:d.map(u=>yB(u,c)),truncated:f,...f?{hint:`Showing the first ${d.length} of ${a.length} findings; pass --limit ${a.length} for all of them.`}:{},gate:{failOn:n,passed:m}},...m?{}:{exitCode:b.Validation}}},render:wB});var US=[xy,Ty,tS,FS,nh,rh,oh,jR,QR,ZR,FR,Yw,zw,TR,PR,DR,OR,_R,iR,BR,MC,YR,Uw,Hw,Fw,$w,Lw,Pw,Nw,xw,Tw,Ow,Sw,OS,Ly,WS,Ch,Fy,$h,qy,Gh,Py,_y,Mh,Rh,Sh,xh,zh,AS,TS,xS,mS,fS];var bB=500,HS=async(e,t,n)=>{let r=await e(t,n);if(r.items.length>n)throw new p(`The listing returned ${r.items.length} rows for a page of at most ${n}, so it cannot say where to continue.`);if(r.nextCursor!==void 0&&r.nextCursor===t)throw new p(`The listing returned the cursor it was asked for (${t}), so it cannot advance.`);return r},kB=(e,t)=>{if(!Number.isInteger(e)||e<1)throw $(`--limit must be a positive whole number, got ${e}.`,t);return e},EB=(e,t,n)=>`Showing the first ${e} rows; more exist. Continue with --cursor ${t}, or pass --all for every row.`+(n?` ${n}`:""),iu=async(e,t,n)=>{let r=[];if(t.all){let i=t.cursor;do{let a=await HS(e,i,bB);r.push(...a.items),i=a.nextCursor}while(i!==void 0);return{items:r,truncated:!1}}let s=kB(t.limit,n.helpCommand),o=t.cursor;do{let i=await HS(e,o,s-r.length);r.push(...i.items),o=i.nextCursor}while(o!==void 0&&r.length<s);return o===void 0?{items:r,truncated:!1}:{items:r,truncated:!0,nextCursor:o,hint:EB(r.length,o,n.narrowHint)}},GS=(e,t,n)=>iu(async(r,s)=>{let o=r===void 0?0:Number(r);if(!/^\d+$/.test(r??"0")||o>e.length)throw $(`--cursor ${r} is not a cursor this listing returned.`,n.helpCommand);let i=o+s;return{items:e.slice(o,i),nextCursor:i<e.length?String(i):void 0}},t,n);var KS="modeldesk",VS=e=>{let t;return()=>(t??={value:e()},t.value)},CB=Ad(US),wd=e=>{let t=e.indexOf("--");return t===-1?e:e.slice(0,t)},YS=e=>wd(e).some(t=>t==="--help"||t==="-h"),RB=(e,t)=>!("version"in yt(e))&&wd(t).some(n=>n==="--version"||n==="-v"),SB=(e,t)=>{let n=wd(e);return n.includes("--no-json")?!1:n.includes("--json")||t!==void 0},vB=(e,t)=>{let n=e,r=[],s=!0;for(let o=0;o<t.length;o++){let i=t[o];if(i==="--"){r.push(...t.slice(o));break}if(s&&n.kind==="group")if(i.startsWith("-")){if(i==="--host"&&o+1<t.length){r.push(i,t[++o]);continue}}else{let a=n.children.get(i);if(a){n=a;continue}s=!1}r.push(i)}return{node:n,rest:r}},IB=(e,t)=>{try{let[n]=Md(e,t).positionals;return n==="help"?void 0:n}catch{return}},$B=(e,t,n)=>{let s=`${[KS,...e.path].join(" ")} --help`,o=e.path.length===0?pp(e):hp(e);if(YS(t)&&IB(t,s)===void 0)return n.out(o),0;let{globals:i,positionals:a}=Md(t,s),[d]=a;if(d==="help")return n.out(o),0;if(d!==void 0){let l=e.path.length===0?`Unknown command '${d}'.`:`Unknown '${e.path.join(" ")}' command '${d}'.`;throw $(l,s)}if(i.version)return n.out(`${sr}
289
- `),0;if(e.path.length===0)return n.out(o),0;throw $(`'${e.path.join(" ")}' requires a subcommand (${[...e.children.keys()].join(", ")}).`,s)},xB=async(e,t,n,r,s,o)=>{let{spec:i}=e,a=e.path.join(" "),d=`${KS} ${a} --help`;if(YS(t))return n.out(gp(i)),0;if(RB(i,t))return n.out(`${sr}
290
- `),0;let l=dp(i,t,d);if(l.globals.json&&l.globals.noJson)throw $("Pass --json or --no-json, not both.",d);if(l.globals.dryRun&&!i.dryRun)throw $(`'${a}' has no --dry-run; nothing was run.`,d);let c=!l.globals.noJson&&(l.globals.json||s!==void 0);c&&!l.globals.json&&o();let m=bp(i.effect,i.escalate,l.flags,l.globals.dryRun),f=m===i.escalate?.to&&m!==i.effect;Cp({agentHost:s,env:r.env},m,f?`${a} --${i.escalate?.flag}`:a);let g=Zp(r),u={flags:l.flags,args:l.args,globals:{json:c,host:l.globals.host,dryRun:l.globals.dryRun,yes:l.globals.yes},commandName:a,effect:m,env:r.env,cwd:r.cwd,io:n,interactive:g,stdoutIsTTY:r.stdoutIsTTY,agentHost:s,color:!c&&eh(r),print:y=>{c||n.out(ae(y))},warn:y=>n.err(ae(`warning: ${y}
291
- `)),confirm:async y=>{if(!g)return!1;let k=await r.ask(`${y} [y/N] `);return k!==void 0&&/^y(es)?$/i.test(k.trim())},choose:async(y,k)=>{if(!g)return;let S=Number((await r.ask(`${y} [1-${k}] `))?.trim());return Number.isInteger(S)&&S>=1&&S<=k?S-1:void 0},list:async y=>{if(!i.listing)throw new Error(`'${a}' lists rows but declares no listing.`);let k={limit:l.flags.limit,cursor:l.flags.cursor,all:l.flags.all===!0},S={helpCommand:d,narrowHint:i.listing.narrowHint};return typeof y=="function"?iu(y,k,S):GS(y,k,S)},readStdin:r.readStdin,instance:VS(()=>zn(u,{gateMachineHost:!0})),api:VS(()=>ju(mh(u.instance(),u)))};i.prepare?.(u);let h=await i.run(u);return pS(n,c,i,h.result,{allRows:l.flags.all===!0}),h.refusal!==void 0?Qf(n,c,h.refusal):h.exitCode??0},zS=async(e,t=Xp,n={})=>{let r=n.runtime??Qp(),s=Qd(r.env),o=!1,i=()=>{o||(o=!0,t.err(`note: running under ${s}, so output is JSON. Pass --no-json for text.
292
- `))};try{let a=n.commands?Ad(n.commands):CB,{node:d,rest:l}=vB(a,e);return d.kind==="group"?$B(d,l,t):await xB(d,l,t,r,s,i)}catch(a){let d=SB(e,s);return d&&!wd(e).includes("--json")&&i(),Qf(t,d,a)}};var MB=await zS(process.argv.slice(2));process.exitCode=MB;
297
+ `,n+1))t.push(n+1);return n=>{let r=0,o=t.length-1;for(;r<o;){let s=r+o+1>>1;t[s]<=n?r=s:o=s-1}return r+1}},R2=e=>{let t=VT(e);return[...e.matchAll(f2)].map(n=>({name:n[1].toLowerCase(),attributes:E2(n[2]),line:t(n.index)}))},Ln=e=>`${e.kind} '${e.title}'`,YT=(e,t)=>{let n=t.elements??[],r=new Map(n.map(a=>[a.anchor,a])),o=new Map(n.map(a=>[a.id,a])),s=[],i=new Map;for(let[a,d]of e){let l=C2(d),c=VT(l),m=new Set;i.set(a,m);for(let p of R2(l)){let h=p.attributes.get("id"),u=p.attributes.get("data-md-element"),y=h===void 0?void 0:r.get(h);if(y!==void 0)m.add(y.anchor),u!==y.id&&s.push({kind:"unmarked-container",path:a,line:p.line,message:u===void 0?`<${p.name} id="${h}"> declares the anchor of ${Ln(y)} but carries no data-md-element.`:`<${p.name} id="${h}"> declares the anchor of ${Ln(y)} but its data-md-element names '${u}'.`});else if(u!==void 0){let I=o.get(u);s.push(I===void 0?{kind:"unindexed-container",path:a,line:p.line,message:`<${p.name}> carries data-md-element="${u}", an element the index does not list.`}:{kind:"unmarked-container",path:a,line:p.line,message:`<${p.name}> carries the markers of ${Ln(I)} but not its anchor, id="${I.anchor}".`})}let w=p.name==="a"?p.attributes.get("href"):void 0,E=w?.startsWith("#")?r.get(w.slice(1)):void 0;E!==void 0&&p.attributes.get("data-md-ref")!==E.id&&s.push({kind:"unmarked-link",path:a,line:p.line,message:`The link to ${Ln(E)} (${w}) carries no data-md-ref="${E.id}".`})}for(let p of l.matchAll(h2)){let h=r.get(p[1]);h!==void 0&&(m.add(h.anchor),s.push({kind:"unmarked-container",path:a,line:c(p.index),message:`A Markdown heading declares the anchor of ${Ln(h)} and cannot carry its markers; write it as <hN id="${h.anchor}" data-md-element="${h.id}">.`}))}for(let p of l.matchAll(g2)){let h=r.get(p[1]);h!==void 0&&s.push({kind:"unmarked-link",path:a,line:c(p.index),message:`A Markdown link to ${Ln(h)} (#${p[1]}) cannot carry data-md-ref; write it as <a href="#${p[1]}" data-md-ref="${h.id}">.`})}}for(let a of n){let d=i.get(a.path);(d===void 0||!d.has(a.anchor))&&s.push({kind:"missing-container",path:a.path,message:d===void 0?`The index places ${Ln(a)} in ${a.path}, which the document does not have.`:`The index places ${Ln(a)} in ${a.path}, which does not declare its anchor '${a.anchor}'.`})}return s};import{existsSync as k2,readdirSync as v2,readFileSync as zT,statSync as I2}from"node:fs";import{join as JT,relative as S2,resolve as $2,sep as XT}from"node:path";var KT="index.json",T2=".md",QT=J({path:["template","lint"],effect:"local",summary:"Check a rendered document against the marker convention its index.json relies on",description:"Reads the document's index.json and every Markdown fragment beside it, and checks that each element's anchor is declared where its markers are, each link to an element is marked, each element of the index is declared in its file, and no file marks an element the index does not list. Each problem is printed with its file and line; any problem exits 4.",positionals:[{name:"dir",type:"string",required:!0,description:"The folder that holds the document's index.json beside its fragments (data/model in a repo)."}],examples:["modeldesk template lint data/model","modeldesk template lint data/model --json"],run:async({args:e,cwd:t})=>{let n=$2(t,e.dir),r=x2(n),o=M2(n,(r.elements??[]).map(d=>d.path)),s=N2(n,o),i=YT(s,r);return{result:{dir:e.dir,files:s.size,elements:r.elements?.length??0,problems:i},...i.length===0?{}:{exitCode:b.Validation}}},render:({files:e,elements:t,problems:n})=>[...n.map(r=>`${D2(r)}: ${r.message}`),n.length===0?`No problems in ${e} file(s) against ${t} element(s) of the index.`:`${n.length} problem(s) in ${e} file(s).`].join(`
298
+ `)}),x2=e=>{let t=JT(e,KT);if(!k2(t))throw new f(`There is no ${KT} in ${e}; name the folder a pull writes it to, such as data/model.`);let n;try{n=JSON.parse(zT(t,"utf8"))}catch(o){throw new f(`${t} is not JSON: ${o instanceof Error?o.message:String(o)}`)}let r=O2(n);if(r!==void 0)throw new f(`${t} is not a document index: ${r}. Pull the bundle again to rewrite it.`);return n},A2=["id","anchor","path","title","kind"],O2=e=>{let t=typeof e=="object"&&e!==null?e.elements:void 0;if(!Array.isArray(t))return"it has no list of elements";for(let[n,r]of t.entries()){let o=typeof r=="object"&&r!==null?r:{},s=A2.find(i=>typeof o[i]!="string");if(s!==void 0)return`element ${n+1} has no ${s}`}},M2=(e,t)=>{if(t.length===0)return"";let n=t.map(s=>s.split("/").slice(0,-1)),r=[];for(let[s,i]of n[0].entries()){if(!n.every(a=>a[s]===i))break;r.push(i)}let o=e.split(XT).filter(s=>s!=="");for(let s=r.length;s>0;s-=1){let i=r.slice(0,s);if(i.every((a,d)=>o[o.length-s+d]===a))return`${i.join("/")}/`}return""},N2=(e,t)=>{let n=new Map,r=o=>{for(let s of v2(o,{withFileTypes:!0})){let i=JT(o,s.name);s.isDirectory()?r(i):s.isFile()&&s.name.endsWith(T2)&&n.set(t+S2(e,i).split(XT).join("/"),zT(i,"utf8"))}};return I2(e).isDirectory()&&r(e),new Map([...n].sort(([o],[s])=>P2(o,s)))},P2=(e,t)=>e===t?0:e<t?-1:1,D2=({path:e,line:t})=>t===void 0?e:`${e}:${t}`;var ZT={validate:{type:"object",properties:{schemaVersion:{type:"number",description:"The document's version; bumped only for an additive change."},model:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}},ref:{type:"object",properties:{kind:{type:"string",description:'One of "branch", "commit", "draft".'},id:{type:"string"},name:{type:"string"},draftIgnored:{type:"boolean",description:"Present when the read skipped a draft aimed at another branch than the one read. Always true."},note:{type:"string"},branch:{type:"object",properties:{id:{type:"string"},name:{type:"string"}}}},description:"What was validated: a branch head, or your draft, as the address resolved."},valid:{type:"boolean",description:"The server's verdict, false on any `ERROR` or `WARN`. The gate reads the entries instead. One of false, true."},counts:{type:"object",properties:{error:{type:"number"},warn:{type:"number"},info:{type:"number"}},description:"Every entry the server reported, by level, however many `logEntries` carries."},logEntries:{type:"array",items:{type:"object",properties:{logLevel:{type:"string",description:'One of "ERROR", "INFO", "WARN".'},code:{type:"string"},title:{type:"string"},detailMessage:{type:"string"},modelElementId:{type:"string"},elementPath:{type:"string",description:"The element's label path from the model root, which `el show` takes. Absent for an element the tree does not show: the platform's internal `@` elements, and an element no owner reaches."},property:{type:"string"},valueIndex:{type:"number",description:"Which value of {@link property} the finding is about."}}},description:"`ERROR` first, then `WARN`, then `INFO`, each level in the server's order; at most the limit asked for."},truncated:{type:"boolean",description:"One of false, true."},hint:{type:"string",description:"How to see the entries left out; present exactly when truncated."},gate:{type:"object",properties:{failOn:{type:"string",description:'One of "error", "warning".'},passed:{type:"boolean",description:"One of false, true."}},description:"The threshold applied, and whether the model passed it."}},required:["schemaVersion","model","ref","valid","counts","logEntries","truncated","gate"]}};var _2={error:new Set(["ERROR"]),warning:new Set(["ERROR","WARN"])},ex=["ERROR","WARN","INFO"],j2=["LEVEL","ELEMENT","CODE","MESSAGE"],tx=e=>{let t=ex.indexOf(e);return t===-1?ex.length:t},F2=e=>[...e].sort((t,n)=>tx(t.logLevel)-tx(n.logLevel)),q2=e=>{let t=n=>e.filter(r=>r.logLevel===n).length;return{error:t("ERROR"),warn:t("WARN"),info:t("INFO")}},W2=async(e,t,n,r)=>{if(r.size===0)return new Map;let o=await e.models.get(t,{...rt(n),expand:["labels"]});return new Map(ln(ft(dn(o))).filter(s=>r.has(s.id)).map(s=>[s.id,s.path]))},H2=(e,t)=>{let n=e.modelElementId===void 0?void 0:t.get(e.modelElementId);return{logLevel:e.logLevel,code:e.code,title:e.title,detailMessage:e.detailMessage,...e.modelElementId===void 0?{}:{modelElementId:e.modelElementId},...n===void 0?{}:{elementPath:n},...e.property===void 0?{}:{property:e.property,...e.valueIndex===void 0?{}:{valueIndex:e.valueIndex}}}},B2=e=>{let{counts:t,gate:n}=e,r=e.logEntries.map(s=>[s.logLevel,g(s.elementPath??s.modelElementId??""),g(s.code),g(s.detailMessage)]),o=`${n.passed?"passes":"fails"} --fail-on ${n.failOn}`;return[Ae(e.ref,e.model),...r.length===0?["No findings."]:W([j2,...r]),...e.hint?[e.hint]:[],`${P(t.error,"error")}, ${P(t.warn,"warning")}, ${t.info} info: ${o}.`].join(`
299
+ `)},nx=A({path:["validate"],effect:"read",summary:"Validate a model and gate on its findings",description:["Runs the server's validation of a model and lists its findings errors first.",{audience:"super-admin",text:"It validates a metamodel-model as it does any model."},"Exits 4 when a finding at or above --fail-on exists: any ERROR by default, any ERROR or WARN with --fail-on warning. INFO never fails, and neither does the server marking a model invalid over warnings alone. Without a ref it validates your draft while it holds staged changes, else your working branch head. When a listed finding names an element, one more read of the model gives the element its label path."],positionals:[N(_e)],flags:{"fail-on":{type:{enum:["error","warning"]},default:"error",placeholder:"level",description:"The least severe level that fails the gate (exit 4): error, or warning for ERROR and WARN.",toolDescription:"The least severe level that fails the gate, which makes the call an error whose result still lists the findings: error, or warning for ERROR and WARN."},limit:{type:"number",default:jl,placeholder:"n",description:"List at most this many findings, errors first; the counts and the gate cover them all."}},examples:["modeldesk validate <model>","modeldesk validate <model>@draft --fail-on warning","modeldesk validate <model>@feat/shapes --json"],mcp:{name:"validate",description:"Runs the server's validation of the model and lists its findings, errors first. Without a ref it validates your draft while it holds staged changes, else your working branch head. A finding at or above failOn (error by default) makes the call an error whose result still lists the findings. Call it after staging, before you hand off or commit."},resultSchema:ZT.validate,run:async e=>{let{limit:t}=e.flags,n=e.flags["fail-on"];if(!Number.isInteger(t)||t<1)throw k(`--limit must be a positive whole number, got ${t}.`,"modeldesk validate --help");let r=e.api(),o=await ae(e,e.args.model,_e),{id:s}=o,i=await r.validation.get(s,rt(o.ref)),a=F2(i.logEntries),d=a.slice(0,t),l=new Set(d.flatMap(u=>u.modelElementId?[u.modelElementId]:[])),c=await W2(r,s,o.ref,l),m=!a.some(u=>_2[n].has(u.logLevel)),p=d.length<a.length;return{result:{model:{id:s,name:o.name},ref:le(o),valid:i.valid,counts:q2(a),logEntries:d.map(u=>H2(u,c)),truncated:p,...p?{hint:`Showing the first ${d.length} of ${a.length} findings; ${vr(e).allRows(a.length)}`}:{},gate:{failOn:n,passed:m}},...m?{}:{exitCode:b.Validation}}},render:B2});var rx=[gb,bb,uT,QT,Mg,Ng,Dg,H$,aT,dT,U$,XR,ek,cT,mT,pT,Y$,K$,P$,j$,F$,D$,q$,l$,J$,PS,rT,HC,BC,jC,EC,NC,PC,AC,RC,$C,TC,uC,_R,BR,UR,GR,tR,nR,rR,oR,fR,uR,hR,gR,SR,TR,xR,MR,NR,PR,DR,GT,vE,nx,Qg,jE,dy,YE,xy,WE,$E,GE,py,ey,oy,cy,_y,HT,BT,PT,wT,Bb,Kb,yE,pE,rE,aE,cE,EE,sg];var ox=(e,t)=>{try{if(Wn(e.env).mode!=="interactive")return Ao;let{config:n}=nn(e.cwd),{host:r}=Hn(jn({host:e.host},e.env,n).host),o=t(r)?.accessToken,s=o===void 0?void 0:Gn(o);return{superAdmin:s!==void 0&&an(s)}}catch{return Ao}};var U2=2e3,G2=6e4,V2=3,sx=/\r\n|\r|\n/,ax=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),br=e=>typeof e=="string",Y2=(e,t)=>{let n=[],r=e;for(let o=sx.exec(r);o!==null&&!(!t&&o[0]==="\r"&&o.index===r.length-1);o=sx.exec(r))n.push(r.slice(0,o.index)),r=r.slice(o.index+o[0].length);return{lines:n,rest:r}},K2=e=>{let t=e.indexOf(":");return t===-1?{field:e,value:""}:{field:e.slice(0,t),value:e.slice(t+1).replace(/^ /,"")}},z2=()=>{let e="",t=[];return n=>{if(n===""){let s=t.length>0?{event:e||"message",data:t.join(`
300
+ `)}:void 0;return e="",t=[],s}let{field:r,value:o}=K2(n);r==="event"?e=o:r==="data"&&t.push(o)}};async function*J2(e,t){let n=e.getReader(),r=()=>{n.cancel().catch(()=>{})};t.addEventListener("abort",r);let o=new TextDecoder,s=z2(),i="";try{for(let a=t.aborted;!a;){let d=await n.read();a=d.done;let l=d.done?o.decode():o.decode(d.value,{stream:!0}),{lines:c,rest:m}=Y2(i+l,a);i=m;for(let p of c){let h=s(p);h!==void 0&&(yield h)}}}finally{t.removeEventListener("abort",r),r()}}var X2=e=>ax(e)&&br(e.refId)&&br(e.headCommitId)&&typeof e.resets=="number",Q2=e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(!ax(t))return;let{refId:n,headCommitId:r}=t;switch(e.event){case"heads":return Array.isArray(t.heads)?{event:"heads",heads:t.heads.filter(X2)}:void 0;case"ref-created":return br(n)&&br(r)&&(t.kind==="BRANCH"||t.kind==="DRAFT")?{event:"ref-created",refId:n,kind:t.kind,headCommitId:r}:void 0;case"head-advanced":return br(n)&&br(r)?{event:"head-advanced",refId:n,headCommitId:r,reset:t.reset===!0}:void 0;case"ref-deleted":case"draft-handoff":return br(n)?{event:e.event,refId:n}:void 0;case"resync":return{event:"resync"};default:return}},Z2=e=>e instanceof f&&e.exitCode===b.Transient,eY=e=>new f(`The model's event stream could not be re-established (${e}).`,{exitCode:b.Transient,hint:"Run the same command again to keep waiting.",hosted:{hint:"Call again to keep waiting."}}),tY=(e,t)=>new Promise(n=>{let r=()=>{clearTimeout(o),t.removeEventListener("abort",r),n()},o=setTimeout(r,e);t.addEventListener("abort",r)}),ix=e=>e instanceof f?e.reason:Ge(e);async function*nY(e,t,n){let r=new AbortController,o="the stream ended before its first event",s=()=>r.abort(),i=()=>{o=`no event within ${n/1e3} seconds`,r.abort()};t.addEventListener("abort",s);let a=setTimeout(i,n);try{let d;try{d=await e(r.signal)}catch(c){if(r.signal.aborted||Z2(c))return{delivered:!1,reason:r.signal.aborted?o:ix(c)};throw c}let l=!1;try{for await(let c of J2(d,r.signal)){l=!0,clearTimeout(a);let m=Q2(c);m!==void 0&&(yield m),a=setTimeout(i,n)}}catch(c){o=ix(c)}return l?{delivered:l}:{delivered:l,reason:o}}finally{clearTimeout(a),t.removeEventListener("abort",s)}}async function*dx(e,t){let{signal:n}=t,r=t.sleep??tY,o=0;for(;!n.aborted;){let s=yield*nY(e,n,t.idleMs??G2);if(n.aborted)return;if(o=s.delivered?0:o+1,!s.delivered&&o>=V2)throw eY(s.reason);await r(U2,n)}}var rY=500,lx=async(e,t,n)=>{let r=await e(t,n);if(r.items.length>n)throw new f(`The listing returned ${r.items.length} rows for a page of at most ${n}, so it cannot say where to continue.`);if(r.nextCursor!==void 0&&r.nextCursor===t)throw new f(`The listing returned the cursor it was asked for (${t}), so it cannot advance.`);return r},oY=(e,t)=>{if(!Number.isInteger(e)||e<1)throw k(`--limit must be a positive whole number, got ${e}.`,t);return e},sY=e=>`Continue with --cursor ${e}, or pass --all for every row.`,iY=(e,t,n)=>`Showing the first ${e} rows; more exist. ${(n.continueHint??sY)(t)}`+(n.narrowHint?` ${n.narrowHint}`:""),Au=async(e,t,n)=>{let r=[];if(t.all){let i=t.cursor;do{let a=await lx(e,i,rY);r.push(...a.items),i=a.nextCursor}while(i!==void 0);return{items:r,truncated:!1}}let o=oY(t.limit,n.helpCommand),s=t.cursor;do{let i=await lx(e,s,o-r.length);r.push(...i.items),s=i.nextCursor}while(s!==void 0&&r.length<o);return s===void 0?{items:r,truncated:!1}:{items:r,truncated:!0,nextCursor:s,hint:iY(r.length,s,n)}},cx=(e,t,n)=>Au(async(r,o)=>{let s=r===void 0?0:Number(r);if(!/^\d+$/.test(r??"0")||s>e.length)throw k(`--cursor ${r} is not a cursor this listing returned.`,n.helpCommand,{reason:`'cursor' ${r} is not a cursor this listing returned.`});let i=s+o;return{items:e.slice(s,i),nextCursor:i<e.length?String(i):void 0}},t,n);var mx={read:(e,t,n)=>e.models.get(t,{...rt(n),expand:["labels"]}),advance:()=>{},drop:()=>{},schema:(e,t,n,r)=>e.models.schema(t,{ref:n,type:r}),schemaChanged:()=>{}};var Ou="modeldesk",px=e=>{let t;return()=>(t??={value:e()},t.value)},aY=Bl(rx),ai=e=>{let t=e.indexOf("--");return t===-1?e:e.slice(0,t)},fx=e=>ai(e).some(t=>t==="--help"||t==="-h"),dY=e=>{let t=ai(e);return t.reduce((n,r,o)=>r==="--host"?t[o+1]??n:r.startsWith("--host=")?r.slice(7):n,void 0)},lY=(e,t)=>!("version"in Mt(e))&&ai(t).some(n=>n==="--version"||n==="-v"),cY=(e,t)=>{let n=ai(e);return n.includes("--no-json")?!1:n.includes("--json")||t!==void 0},mY=(e,t)=>{let n=e,r=[],o=!0;for(let s=0;s<t.length;s++){let i=t[s];if(i==="--"){r.push(...t.slice(s));break}if(o&&n.kind==="group")if(i.startsWith("-")){if(i==="--host"&&s+1<t.length){r.push(i,t[++s]);continue}}else{let a=n.children.get(i);if(a){n=a;continue}o=!1}r.push(i)}return{node:n,rest:r}},pY=(e,t)=>{try{let[n]=Hl(e,t).positionals;return n==="help"?void 0:n}catch{return}},ux=(e,t)=>k(e.length===0?`Unknown command '${t}'.`:`Unknown '${e.join(" ")}' command '${t}'.`,`${[Ou,...e].join(" ")} --help`),fY=(e,t)=>[...e.children].filter(([,n])=>n.kind==="group"?Ti(n,t).length>0:Zt(n.spec.audience,t)).map(([n])=>n),uY=(e,t,n,r)=>{let s=`${[Ou,...e.path].join(" ")} --help`,i=e.path.length===0?tg(e,r):ng(e,r);if(fx(t)&&pY(t,s)===void 0)return n.out(i),0;let{globals:a,positionals:d}=Hl(t,s),[l]=d;if(l==="help")return n.out(i),0;if(l!==void 0)throw ux(e.path,l);if(a.version)return n.out(`${Pr}
301
+ `),0;if(e.path.length===0)return n.out(i),0;throw k(`'${e.path.join(" ")}' requires a subcommand (${fY(e,r).join(", ")}).`,s)},hY=async(e,t,n,r,o,s,i,a)=>{let{spec:d}=e,l=e.path.join(" "),c=`${Ou} ${l} --help`;if(fx(t)){if(!Zt(d.audience,a))throw ux(e.path.slice(0,-1),e.path.at(-1)??l);return n.out(rg(d,a)),0}if(lY(d,t))return n.out(`${Pr}
302
+ `),0;let m=zh(d,t,c,a);if(m.globals.json&&m.globals.noJson)throw k("Pass --json or --no-json, not both.",c);if(m.globals.dryRun&&!d.dryRun)throw k(`'${l}' has no --dry-run; nothing was run.`,c);let p=!m.globals.noJson&&(m.globals.json||o!==void 0);p&&!m.globals.json&&i();let h=Hu(d.effect,d.escalate,m.flags,m.globals.dryRun),u=h===d.escalate?.to&&h!==d.effect;Uu({agent:o},h,u?`${l} --${d.escalate?.flag}`:l);let y=xg(r),w=v=>n.err(ye(`warning: ${v}
303
+ `)),E={flags:m.flags,args:m.args,commandName:l,effect:h,agent:o,origin:s,api:px(()=>gh(Wg(E.instance(),{env:r.env,interactive:y,agentHost:o?.host}))),content:mx,events:(v,$)=>dx(C=>E.api().models.events(v,C),{signal:$}),list:async v=>{if(!d.listing)throw new Error(`'${l}' lists rows but declares no listing.`);let $={limit:m.flags.limit,cursor:m.flags.cursor,all:m.flags.all===!0},C={helpCommand:c,narrowHint:d.listing.narrowHint};return typeof v=="function"?Au(v,$,C):cx(v,$,C)},note:w,dryRun:m.globals.dryRun,webUrl:v=>be(E.instance(),v),globals:{json:p,host:m.globals.host,dryRun:m.globals.dryRun,yes:m.globals.yes},env:r.env,cwd:r.cwd,io:n,interactive:y,stdoutIsTTY:r.stdoutIsTTY,color:!p&&Ag(r),print:v=>{p||n.out(ye(v))},warn:w,confirm:async v=>{if(!y)return!1;let $=await r.ask(`${v} [y/N] `);return $!==void 0&&/^y(es)?$/i.test($.trim())},choose:async(v,$)=>{if(!y)return;let C=Number((await r.ask(`${v} [1-${$}] `))?.trim());return Number.isInteger(C)&&C>=1&&C<=$?C-1:void 0},readStdin:r.readStdin,instance:px(()=>Ar(E,{gateMachineHost:!0}))},I=await gY(d,E,p);return ET(n,p,d,I.result,{allRows:m.flags.all===!0,flags:m.flags}),I.refusal!==void 0?Cu(n,p,I.refusal):I.exitCode??0},gY=async(e,t,n)=>{try{let r=await e.prepare?.(t);return await e.run(t,r)}catch(r){if(n||!(r instanceof f))throw r;let o=e.renderRefusal?.(r);throw o===void 0?r:(t.print(o),new f(r.reason,{exitCode:r.exitCode,type:r.type,hint:r.hint,requestId:r.requestId}))}},hx=async(e,t=$g,n={})=>{let r=n.runtime??Tg(),o=Gu(r.env),s=Vu(r.env,o),i=!1,a=()=>{i||(i=!0,t.err(`note: running under ${s?.host}, so output is JSON. Pass --no-json for text.
304
+ `))};try{let d=n.commands?Bl(n.commands):aY,{node:l,rest:c}=mY(d,e),m=ox({host:dY(e),env:r.env,cwd:r.cwd},n.storedCredential??(p=>new Ve().read(p)));return l.kind==="group"?uY(l,c,t,m):await hY(l,c,t,r,s,o,a,m)}catch(d){let l=cY(e,s);return l&&!ai(e).includes("--json")&&a(),Cu(t,l,d)}};var yY=await hx(process.argv.slice(2));process.exitCode=yY;