@modeldesk/cli 0.5.0 → 0.7.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,55 +1,292 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
3
- import{chmodSync as It,existsSync as xr,mkdirSync as br,readFileSync as Tr,writeFileSync as Cr}from"node:fs";import{homedir as vr}from"node:os";import{join as $t}from"node:path";var At=448,Rt=384,A=class{dir;file;constructor(t=$t(vr(),".modeldesk")){this.dir=t,this.file=$t(t,"credentials.json")}getRefreshToken(t){let n=this.read().hosts[t]?.refreshToken;return typeof n=="string"?n:void 0}saveRefreshToken(t,n){let r=this.read();r.hosts[t]={refreshToken:n},this.write(r)}saveRefreshTokenIfPresent(t,n){n&&this.saveRefreshToken(t,n)}clearHost(t){let n=this.read();return n.hosts[t]?(delete n.hosts[t],this.write(n),!0):!1}read(){if(!xr(this.file))return{hosts:{}};try{let t=JSON.parse(Tr(this.file,"utf8"));if(t&&typeof t=="object"&&t.hosts&&typeof t.hosts=="object")return t}catch{}return{hosts:{}}}write(t){br(this.dir,{recursive:!0,mode:At}),Cr(this.file,`${JSON.stringify(t,null,2)}
4
- `,{mode:Rt}),It(this.dir,At),It(this.file,Rt)}};var De=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}},ce=e=>{let t=De(e);if(t)return t.name&&t.email?`${t.name} <${t.email}>`:t.email??t.name??t.sub};import{spawn as Sr}from"node:child_process";import{platform as Ir}from"node:process";var _t=e=>{if(!$r(e))return;let{command:t,args:n,verbatim:r}=Ar(e);try{let o=Sr(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});o.on("error",()=>{}),o.unref()}catch{}},$r=e=>{try{let{protocol:t}=new URL(e);return t==="http:"||t==="https:"}catch{return!1}},Ar=(e,t=Ir)=>{switch(t){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start",'""',Rr(e)],verbatim:!0};default:return{command:"xdg-open",args:[e]}}},Rr=e=>e.replace(/[&|<>^()%"]/g,t=>`^${t}`);var q="modeldesk-cli",Pt="modeldesk-federation",Mt="openid",Ne="/callback";var c=class extends Error{exitCode;constructor(t,n=1){super(t),this.name="CliError",this.exitCode=n}};var D=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 c(`Could not reach the auth server at ${e} (${o.message}).`)}if(!n.ok)throw new c(`OpenID discovery failed at ${t}: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.authorization_endpoint||!r.token_endpoint)throw new c(`OpenID discovery at ${t} did not return the authorization and token endpoints.`);return{authorizationEndpoint:r.authorization_endpoint,tokenEndpoint:r.token_endpoint}};import{createServer as _r}from"node:http";var Pr=3e5,Lt=(e,t=Pr)=>new Promise((n,r)=>{let o,s=new Promise((p,l)=>{o={resolve:p,reject:l}}),i=_r((p,l)=>{let f=new URL(p.url??"/","http://127.0.0.1");if(f.pathname!==Ne){l.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}Mr(f,l,e,o)}),a=setTimeout(()=>o.reject(new c("Timed out waiting for the browser login to complete.")),t);a.unref();let d=!1,m=()=>{d||(d=!0,clearTimeout(a),i.close())};s.then(m,m),i.once("error",p=>r(new c(`Could not start the loopback listener: ${p.message}`))),i.listen(0,"127.0.0.1",()=>{let{port:p}=i.address();n({redirectUri:`http://127.0.0.1:${p}${Ne}`,waitForCode:()=>s,close:m})})}),Mr=(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");Oe(t,"Sign-in failed","Sign-in failed. You can close this window and return to the terminal."),r.reject(new c(`Authorization failed: ${i?`${o} (${i})`:o}`));return}let s=e.searchParams.get("code");if(!s){Oe(t,"Sign-in failed","No authorization code was returned. You can close this window."),r.reject(new c("Login failed: no authorization code was returned."));return}Oe(t,"Signed in","You are signed in to the ModelDesk CLI. You can close this window and return to the terminal."),r.resolve(s)},Oe=(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 Lr,randomBytes as Dt}from"node:crypto";var Fe=e=>e.toString("base64url"),Nt=()=>{let e=Fe(Dt(32)),t=Fe(Lr("sha256").update(e).digest());return{verifier:e,challenge:t,method:"S256"}},Ot=()=>Fe(Dt(16));var j=class extends c{oauthError;errorDescription;constructor(t,n,r){super(t),this.name="TokenEndpointError",this.oauthError=n,this.errorDescription=r}},Ft=e=>e instanceof j&&e.oauthError==="invalid_grant",Ht=(e,t)=>me(e,new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:t.redirectUri,client_id:q,code_verifier:t.codeVerifier})),le=(e,t)=>me(e,new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:q})),Ut=(e,t)=>me(e,new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_secret:t.clientSecret})),Wt=(e,t)=>me(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:Pt})),me=async(e,t)=>{let n;try{n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString(),signal:AbortSignal.timeout(3e4)})}catch(o){throw new c(`Could not reach the token endpoint (${o.message}).`)}if(!n.ok){let{message:o,code:s,description:i}=await Dr(n);throw new j(`Token request failed: ${o}`,s,i)}let r=await n.json();if(!r.access_token)throw new c("The token response did not include an access token.");return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresInSeconds:r.expires_in??0}},Dr=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 pe={info:e=>process.stderr.write(`${e}
5
- `)},fe=async(e,t)=>{let{authorizationEndpoint:n,tokenEndpoint:r}=await D(e.issuer),o=Nt(),s=Ot(),i=await Lt(s);try{let a=Nr(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:
6
- ${a}`),_t(a);let d=await i.waitForCode();return await Ht(r,{code:d,redirectUri:i.redirectUri,codeVerifier:o.verifier})}finally{i.close()}},Nr=(e,t,n,r)=>{let o=new URL(e);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",q),o.searchParams.set("redirect_uri",t),o.searchParams.set("scope",Mt),o.searchParams.set("state",r),o.searchParams.set("code_challenge",n),o.searchParams.set("code_challenge_method","S256"),o.toString()};var He="modeldesk.io",h={host:"MODELDESK_HOST",model:"MODELDESK_MODEL",stack:"MODELDESK_STACK",template:"MODELDESK_TEMPLATE",version:"MODELDESK_VERSION",clientId:"MODELDESK_CLIENT_ID",clientSecret:"MODELDESK_CLIENT_SECRET",apiKey:"MODELDESK_API_KEY"},Z=(...e)=>e.find(t=>t!==void 0&&t!==""),Ue=(e,t,n)=>({host:Z(e.host,t[h.host],n.host)??He,model:Z(e.model,t[h.model],n.model),stack:Z(e.stack,t[h.stack],n.stack),template:Z(e.template,t[h.template],n.template),version:Z(e.version,t[h.version],n.version)});var Bt={requestUrl:"ACTIONS_ID_TOKEN_REQUEST_URL",requestToken:"ACTIONS_ID_TOKEN_REQUEST_TOKEN"},N=e=>e!==void 0&&e!=="",zt=e=>e==="true"||e==="1",Or=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,We="mdsk_",jt=57,W=(e,t)=>({mode:"error",reason:e,message:t}),O="org settings \u2192 Service accounts",Q=e=>{if(N(e[h.apiKey]))return W("legacy-api-key",`${h.apiKey} is no longer supported: the CI credential shipped as service accounts, not bearer keys. Use secret mode (set ${h.clientId} and ${h.clientSecret} from ${O}) or, on GitHub Actions, federated auth (grant 'permissions: id-token: write' and add a trust rule). Unset ${h.apiKey}.`);let t=e[h.clientId],n=e[h.clientSecret];if(N(t)!==N(n)){let[s,i]=N(t)?[h.clientId,h.clientSecret]:[h.clientSecret,h.clientId];return W("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(N(t)&&N(n))return Or.test(t)?n.startsWith(We)?n.length!==jt?W("invalid-client-secret",`${h.clientSecret} has the wrong length: expected ${jt} characters, got ${n.length}. Check for truncation in the pipeline's secret store.`):{mode:"secret",clientId:t,clientSecret:n}:W("invalid-client-secret",`${h.clientSecret} does not start with '${We}' (an issued secret always does). Check for quoting or truncation in the pipeline's secret store.`):W("invalid-client-id",`${h.clientId} is not a service-account id: expected a UUID, got a ${t.length}-character value. Copy the account id from ${O}.`);let r=e[Bt.requestUrl],o=e[Bt.requestToken];return N(r)&&N(o)?{mode:"federated",oidcRequestUrl:r,oidcRequestToken:o}:zt(e.GITHUB_ACTIONS)?W("headless-ci",`Running on GitHub Actions without machine credentials. Grant 'permissions: id-token: write' to use federated auth (with a trust rule in ${O}), or set ${h.clientId} and ${h.clientSecret}. The CLI never opens a browser login in CI.`):zt(e.CI)?W("headless-ci",`Running in CI without machine credentials. Set ${h.clientId} and ${h.clientSecret} (${O}). The CLI never opens a browser login in CI.`):{mode:"interactive"}},F=e=>{let t=Q(e);return t.mode==="secret"||t.mode==="federated"?t.mode:void 0},Gt=e=>`${e.slice(0,We.length+8)}\u2026`,Vt=`Check ${h.clientId} and ${h.clientSecret}; issue or rotate a secret in ${O}.`,Kt=`The service account may be disabled or deleted \u2014 check ${O}.`,Yt={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/${h.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."},ue={unauthorized:`The machine token was rejected. A disabled or deleted service account fails on the next request; a revoked secret within five minutes. Check ${O}.`,forbidden:`The service account's scopes do not permit this \u2014 pulling content needs the 'model:content' scope (${O}).`,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 Fr="http://localhost:8080",Hr="http://localhost:8082",Ur="localhost",Wr=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]}},Br=e=>e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]",Be=e=>{let t=Wr(e);return Br(t)?{host:Ur,apiBase:Fr,issuer:Hr}:{host:t,apiBase:`https://api.${t}`,issuer:`https://auth.${t}`}};import{existsSync as zr,readFileSync as jr}from"node:fs";import{join as Gr}from"node:path";var he=".modeldesk",Vr="config.json",ge=e=>e.configPath!==void 0,ze=e=>{let t=Gr(e,he,Vr);return zr(t)?{config:Kr(t),configPath:t,repoRoot:e}:{config:{},repoRoot:e}},Kr=e=>{let t;try{t=jr(e,"utf8")}catch(o){throw new c(`Could not read ${e}: ${o.message}`)}let n;try{n=JSON.parse(t)}catch(o){throw new c(`${e} is not valid JSON: ${o.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new c(`${e} must contain a JSON object.`);let r=n;return{host:ee(r,"host",e),model:ee(r,"model",e),stack:ee(r,"stack",e),template:ee(r,"template",e),version:ee(r,"version",e)}},ee=(e,t,n)=>{let r=e[t];if(r!==void 0){if(typeof r!="string")throw new c(`${n}: "${t}" must be a string.`);return r}};import{parseArgs as Yr}from"node:util";var G=(e,t)=>{try{return Yr({args:e,options:t,allowPositionals:!1,strict:!0})}catch(n){throw new c(n.message)}};var Xt=(e,t,n)=>{let r=n[h.host];return!(t!==void 0&&t!==""||r!==void 0&&r!=="")&&ge(e)&&!!e.config.host},Jt=(e,t,n)=>{Xt(e,t,n)&&e.config.host!==He&&process.stderr.write(`note: using host '${e.config.host}' from ${e.configPath} (it drives login and API calls).
7
- `)},qt=(e,t,n)=>{if(F(n)&&Xt(e,t,n))throw new c(`In a machine-auth run the host must be set explicitly: pass --host or set ${h.host}. The committed ${e.configPath??".modeldesk/config.json"} is not a trusted source for where machine credentials are sent.`)},V=(e,t={})=>{let{values:n}=G(e.argv,{host:{type:"string"}}),r=ze(e.cwd),o=Ue({host:n.host},e.env,r.config);return t.gateMachineHost&&qt(r,n.host,e.env),Jt(r,n.host,e.env),Be(o.host)},ye=(e,t)=>{let n=ze(e.cwd),r=Ue(t,e.env,n.config);if(qt(n,t.host,e.env),Jt(n,t.host,e.env),!r.model)throw new c(`No model specified. Pass --model, set ${h.model}, or add "model" to .modeldesk/config.json.`);return{instance:Be(r.host),model:r.model,stack:r.stack,template:r.template,version:r.version,loaded:n}},je=(e,t,n,r)=>{let o=e?.trim();if(!o)throw new c(`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 Zt=async e=>{let t=F(e.env);t&&process.stderr.write(`warning: machine auth (${t} mode) is active in this environment and takes precedence for API commands; this login only affects interactive use.
8
- `);let n=V(e),r=await fe(n,pe),o=new A;r.refreshToken?o.saveRefreshToken(n.host,r.refreshToken):o.clearHost(n.host);let s=ce(r.accessToken);return process.stdout.write(`Logged in to ${n.host}${s?` as ${s}`:""}.
9
- `),r.refreshToken||process.stderr.write(`warning: the server returned no refresh token, so later commands will re-open the browser each time instead of running unattended.
10
- `),0};var Qt=async e=>{let t=F(e.env);t&&process.stderr.write(`warning: machine auth (${t} mode) is active in this environment and takes precedence for API commands; this logout does not remove machine credentials.
11
- `);let n=V(e),r=new A().clearHost(n.host);return process.stdout.write(r?`Logged out of ${n.host}.
12
- `:`No stored credential for ${n.host}.
13
- `),0};var Ge=6e4,we=class{constructor(t,n={}){this.instance=t;this.store=n.store??new A,this.io=n.io??pe,this.now=n.now??Date.now}instance;store;io;now;accessToken;accessTokenExpiresAt=0;endpoints;async getAccessToken(){if(this.accessToken&&this.now()<this.accessTokenExpiresAt-Ge)return this.accessToken;let t=this.store.getRefreshToken(this.instance.host);if(t){let n=await this.tryRefresh(t);if(n)return n}return this.login()}async tryRefresh(t){let{tokenEndpoint:n}=await this.getEndpoints();try{return this.apply(await le(n,t))}catch(r){if(Ft(r))return;throw r}}async login(){return this.apply(await fe(this.instance,this.io))}apply(t){return this.accessToken=t.accessToken,this.accessTokenExpiresAt=this.now()+t.expiresInSeconds*1e3,this.store.saveRefreshTokenIfPresent(this.instance.host,t.refreshToken),t.accessToken}async getEndpoints(){return this.endpoints||(this.endpoints=await D(this.instance.issuer)),this.endpoints}};var Ve=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??D}instance;mode;mint;now;discover;accessToken;accessTokenExpiresAt=0;endpoints;inflight;async getAccessToken(){return this.accessToken&&this.now()<this.accessTokenExpiresAt-Ge?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 Jr(r,this.mode)}if(n.expiresInSeconds<=0)throw new c("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}},Xr=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 c(`Could not reach the GitHub OIDC token endpoint (${s.message}).`)}if(!r.ok)throw new c(`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 c("The GitHub OIDC token response did not include a token value. Check that the workflow grants 'permissions: id-token: write'.");return o.value},ke=(e,t,n={})=>{let r=t.mode==="secret"?o=>Ut(o,{clientId:t.clientId,clientSecret:t.clientSecret}):async o=>Wt(o,await Xr(t.oidcRequestUrl,t.oidcRequestToken,e.issuer));return new Ve(e,t.mode,r,n)},Jr=(e,t)=>{if(!(e instanceof j)||!e.oauthError)return e;if(t==="secret")return e.oauthError==="invalid_client"?new c(`${e.message} ${Vt}`):e;if(e.errorDescription===void 0)return e.oauthError==="invalid_grant"?new c(`${e.message} ${Kt}`):e;let n=Yt[e.errorDescription];return n?new c(`${e.message} \u2014 ${n}`):e};var _=e=>{process.stdout.write(`${e}
14
- `)},en=async e=>{let t=Q(e.env);if(t.mode==="error")throw new c(t.message);let n=t.mode==="secret"||t.mode==="federated",r=V(e,{gateMachineHost:n});return _(`Host: ${r.host}`),_(`API: ${r.apiBase}`),t.mode==="secret"||t.mode==="federated"?qr(r,t,e.env):Zr(r)},qr=async(e,t,n)=>{t.mode==="secret"?_(`Auth: service account (secret mode), client ${t.clientId}, secret ${Gt(t.clientSecret)}`):_(`Auth: federated (GitHub Actions), repository ${n.GITHUB_REPOSITORY??"unknown"}, ref ${n.GITHUB_REF??"unknown"}`);let r=await ke(e,t).getAccessToken(),o=De(r)??{};_(`Status: credential valid. Account ${o.sub??"unknown"}, organization ${o.mdsk_org??"unknown"}.`);let s=typeof o.scope=="string"?o.scope.trim():"";return _(s?`Scopes: ${s}`:"Scopes: enforced server-side from the account's current scopes."),0},Zr=async e=>{let t=new A,n=t.getRefreshToken(e.host);if(!n)return _("Status: not logged in. Run 'modeldesk auth login'."),1;try{let{tokenEndpoint:r}=await D(e.issuer),o=await le(r,n);t.saveRefreshTokenIfPresent(e.host,o.refreshToken);let s=ce(o.accessToken);return _(`Status: logged in${s?` as ${s}`:""} (credential valid).`),0}catch{return _("Status: the stored credential could not be verified (it may be expired or revoked, or the server is unreachable). Run 'modeldesk auth login'."),1}};var Ke=e=>`${JSON.stringify(e,null,2)}
15
- `;var Qr=/[ \t\n\r\f]+/g,eo=/^[ \t\n\r\f]+|[ \t\n\r\f]+$/g,to=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,te=e=>e.replace(to,"");var no=(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)},Ye=e=>no(e,2);var ro=e=>e.replace(Qr," ").replace(eo,""),Xe=e=>ro(te(e)).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;");var ne="http://www.w3.org/2000/svg",rn="Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",Je="group",qe="spacingAndGlyphs",Ze="italic",Qe="underline",K="none";var Ee="hidden",xe="stroke",et="auto";var oo="start",be="clip",so=/^[A-Za-z0-9_-]+$/,io=/[^A-Za-z0-9_-]+/g,tt=e=>so.test(e),on=e=>e.replace(io,"-");var nt=(e,t)=>t?`${e}-${oo}`:e,tn=String.raw`-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?`,nn=String.raw`[a-zA-Z]+\(\s*(?:${tn}(?:[\s,]+${tn})*)?\s*\)`,ao=new RegExp(String.raw`^${nn}(?:\s+${nn})*$`),sn=e=>ao.test(e);var co=/[\u0000- \u007F]/g,lo=/^([a-zA-Z][a-zA-Z0-9+.-]*):/,mo=new Set(["http","https","mailto"]),Te=e=>{let t=te(e).replace(co,"");if(t==="")return!1;let n=lo.exec(t);return n===null||mo.has(n[1].toLowerCase())};var g="#4b5563";var S="white";var rt="strokeWidth",Ce=[{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:g,stroke:g,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:S,stroke:g,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:g,stroke:g,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:S,stroke:g,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:g,strokeWidth:2}]},{id:"bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:g,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:S,stroke:g,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:g,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:g,strokeWidth:1.5},{element:"line",x1:4,y1:1,x2:4,y2:11,stroke:g,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:g,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:S,stroke:g,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:g,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:S,stroke:g,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:g,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:S,stroke:g,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:S,stroke:g,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:g,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:S,stroke:g,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:g,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:S,stroke:g,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:S,stroke:g,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:S,stroke:g,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:g,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:g,strokeWidth:1.5}]}],va=new Map(Ce.map(e=>[e.id,e]));var go=" ",ot=["fill","fill-opacity","stroke","stroke-opacity","stroke-width","stroke-dasharray"],yo={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",...ot],path:["d",...ot,"stroke-linejoin","marker-start","marker-end","visibility","pointer-events"],polygon:["points",...ot],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"]},pn=new Map(Object.entries(yo).map(([e,t])=>[e,new Set(t)])),wo=new Set(["title","desc","text"]),an="svg",Y="g",P="a",fn="title",re="data-md-element",un="path",hn=["visibility","pointer-events"],gn=new Set(["rect","text","polygon","line"]),ko={"clip-path":"clipPath","marker-start":"marker","marker-end":"marker"},yn=/&(amp|lt|gt|quot|apos);/g,Eo={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},xo=/[<>"']/,bo=/[\u0000-\u001F]/,To=/^<([^\s/>]+)/,Co=/^<\/([^\s/>]+)>/,st=/ ([^\s=/>"'<]+)=/y,it=/"([^"]*)"/y,vo=/^on/i,So=/^ */,Io=64,dn=/[\p{Cc}\p{Cf}\u2028\u2029]/gu,M=String.raw`-?\d+(?:\.\d+)?(?:e\+\d+)?`,$o=new RegExp(`^${M}$`),Ao=/^(?:[1-9]\d{0,2}|1000)$/,Ro=new RegExp(`^0 0 ${M} ${M}$`),_o=new RegExp(`^${M}(?:[ ,]${M})*$`),Po=new RegExp(`^(?:${M},${M}(?: ${M},${M})*)?$`),Mo=/^[MmZzLlHhVvCcSsQqTtAa0-9eE.,+\- ]*$/,wn=/^url\(#([A-Za-z0-9_-]+)\)$/,kn=/^#[0-9a-f]{6}$/,cn=Array.from(new Set([K,...Ce.flatMap(({shapes:e})=>e.flatMap(t=>["fill"in t?t.fill:K,t.stroke])).filter(e=>!kn.test(e))])),En=Ce.flatMap(({id:e})=>[nt(e,!1),nt(e,!0)]),Lo=new RegExp(`^${be}-[1-9]\\d*$`),Do=new RegExp(`-${be}-[1-9]\\d*$`),ct=`${"md"}-`,lt=e=>`U+${e.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}`,E=e=>{let t=[];for(let n of e){if(t.length===Io)return`${t.join("").replace(dn,lt)}\u2026`;t.push(n)}return e.replace(dn,lt)},xn=e=>{if(e.includes("&#"))return"a numeric character reference is not allowed";let t=e.replace(yn,"");if(t.includes("&"))return"& does not start one of the five XML entities";let n=xo.exec(t);return n===null?void 0:`an unescaped ${n[0]} is not allowed`},bn=e=>e.replace(yn,(t,n)=>Eo[n]),B=(e,t)=>n=>e.test(n)?void 0:`"${E(n)}" is not ${t}`,I=(e,t)=>n=>e.includes(bn(n))?void 0:`"${E(n)}" is not ${t}`,ln=()=>{},k=B($o,"a number as the serializer writes one"),mn=e=>kn.test(e)||cn.includes(e)?void 0:`"${E(e)}" is not a paint the serializer writes (#rrggbb, ${cn.join(", ")})`,at=B(wn,"a reference to a definition in the file, as url(#\u2026)"),No=e=>Lo.test(e)?"clipPath":En.includes(e)?"marker":void 0,Oo=(e,t)=>{if(!e.startsWith(ct))return;let n=e.slice(ct.length);if(t!==void 0)return n.startsWith(`${t}-`)?No(n.slice(t.length+1)):void 0;if(tt(n))return(Do.exec(n)?.index??0)>0?"clipPath":En.some(r=>n.length>r.length+1&&n.endsWith(`-${r}`))?"marker":void 0},Fo=(e,t,{idPrefix:n})=>{if(Oo(e,n)===t)return;let r=n??"<prefix>",o=t==="marker"?"<marker>[-start]":`${be}-<n>`;return`"${E(e)}" is not an id the serializer gives a <${t}> (${ct}${r}-${o})`},Ho=e=>{let t=bn(e);return t.startsWith("#")&&Te(t)?void 0:`"${E(e)}" does not point at a section of the page (#\u2026)`},Uo={xmlns:I([ne],"the SVG namespace"),viewBox:B(Ro,"a viewBox the serializer writes (0 0 width height)"),width:k,height:k,role:I([Je],`the role the serializer writes (${Je})`),"aria-label":ln,"font-family":I([rn],"the serializer's font stack"),id:Fo,markerWidth:k,markerHeight:k,refX:k,refY:k,orient:I([et],`the marker orientation the serializer writes (${et})`),markerUnits:I([rt],`the marker units the serializer writes (${rt})`),"data-md-element":ln,"clip-path":at,transform:e=>sn(e)?void 0:`"${E(e)}" is not a transform of numbers the serializer writes`,href:Ho,x:k,y:k,rx:k,fill:mn,"fill-opacity":k,stroke:mn,"stroke-opacity":k,"stroke-width":k,"stroke-dasharray":B(_o,"a dash pattern of numbers"),d:B(Mo,"path data (commands and numbers only)"),"stroke-linejoin":I(["round"],"the line join the serializer writes (round)"),"marker-start":at,"marker-end":at,points:B(Po,"polygon points as the serializer writes them (x,y x,y \u2026)"),x1:k,y1:k,x2:k,y2:k,cx:k,cy:k,r:k,"font-size":k,"font-weight":B(Ao,"a numeric font weight (1 to 1000)"),"font-style":I([Ze],`the font style the serializer writes (${Ze})`),"text-decoration":I([Qe],`the decoration the serializer writes (${Qe})`),textLength:k,lengthAdjust:I([qe],`the length adjustment the serializer writes (${qe})`),visibility:I([Ee],`the visibility of a hit area (${Ee})`),"pointer-events":I([xe],`the pointer events of a hit area (${xe})`)},Wo=(e,t)=>{if(vo.test(t))return`the event-handler attribute ${E(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 ${E(t)} is not allowed`;if(!pn.get(e).has(t))return`<${e}> does not take the attribute ${E(t)}`},Bo=(e,t,n,r)=>{let o=xn(n)??Uo[t](n,e,r);return o===void 0?void 0:`${t}: ${o}`},zo=(e,t,n,r)=>{let o=new Map,s=n;for(;t[s]!==">"&&!t.startsWith("/>",s);){st.lastIndex=s;let i=st.exec(t)?.[1];if(i===void 0)return{problem:'a tag the serializer would not write: expected ` name="value"`, `>` or `/>`'};it.lastIndex=st.lastIndex;let a=it.exec(t)?.[1];if(a===void 0)return{problem:`the value of ${E(i)} is not double-quoted`};let d=Wo(e,i)??Bo(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=it.lastIndex}return{attributes:o,end:s}},dt=e=>e.startsWith("<")?"more than one element on one line":"text outside <title> and <text>",jo=(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 l=Co.exec(e);if(l===null)return{problem:"a closing tag the serializer would not write"};let f=e.slice(l[0].length);return f!==""?{problem:dt(f)}:{line:{kind:"close",name:l[1]}}}let n=To.exec(e)?.[1];if(n===void 0)return{problem:"the line does not start with a tag"};if(!pn.has(n))return{problem:`<${E(n)}> is not an element the diagram serializer writes`};let r=zo(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(!wo.has(n))return a!==""?{problem:dt(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}>`,m=a.indexOf(d);if(m===-1)return{problem:`<${n}> is not closed on its line`};if(m+d.length!==a.length)return{problem:dt(a.slice(m+d.length))};let p=xn(a.slice(0,m));return p===void 0?{line:{kind:"text",name:n,attributes:o}}:{problem:`text: ${p}`}},Go=(e,t)=>{if(e.name===an!=(t===0))return t===0?`the file opens with <${e.name}>, not the serializer's <svg xmlns="${ne}"> root`:"<svg> is only the root, never nested";if(e.name===an&&(e.kind!=="open"||e.attributes.get("xmlns")!==ne))return`the root is not the serializer's <svg xmlns="${ne}">`;if(e.name===P&&!e.attributes.has("href"))return"<a> without an href"},Vo=(e,t,n)=>{if(t.name===P&&t.children===0&&e.name!==fn)return"<a> has to open with the <title> of the group it links";if(e.name===P)return e.kind!=="open"?"<a> is only written open, around the title and body of the group it links":t.name!==Y||!t.stamped||t.children!==0?`<a> is only written as the first child of a <g ${re}>`:n>0?"an <a> inside another <a>":void 0},Tn=e=>hn.some(t=>e.attributes.has(t)),Ko=(e,t)=>e.size===t.size&&Array.from(t).every(([n,r])=>e.get(n)===r),Cn=e=>e.findLast(t=>t.stamped),vn="a line's group draws no box: it holds no <rect>, <text>, <polygon> or <line>",Sn="a line's group holds no stamped group of its own",ve="desc",Yo=e=>e!==void 0&&(e.hitArea||e.described),Xo={d:()=>!0,fill:e=>e===K,stroke:e=>e===g,"stroke-opacity":e=>e==="0","stroke-width":e=>e===Ye(1),"stroke-dasharray":e=>e==="6 4","marker-start":()=>!0,"marker-end":()=>!0},In=e=>e.name===un&&e.attributes.get("fill")===K&&e.attributes.get("stroke")===g&&Array.from(e.attributes).every(([t,n])=>Xo[t]?.(n)??!1),$n=e=>{let t=e.at(-1),n=t?.name===P?e.at(-2):t;return n?.name===Y&&n.stamped?n:void 0},Jo=(e,t)=>{if(!Tn(e))return;let n=t.at(-1),r=n.name===P?t.at(-2):n;if(r?.name!==Y||!r.stamped)return`a hit area (${hn.join(", ")}) is only written in a <g ${re}>`;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 vn;if(r.nestsStamp)return Sn;let o=n.previous;if(o===void 0||o!==n.firstPath||!In(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",K],["stroke",g],["stroke-width",Ye(10)],["visibility",Ee],["pointer-events",xe]]);return Ko(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`},qo=(e,t)=>{let n=Cn(t);if(Yo(n))return gn.has(e.name)?vn:e.name===Y&&e.attributes.has(re)?Sn:void 0},Zo=(e,t)=>{if(e.name!==ve)return;let n=t.at(-1);return $n(t)===void 0||n.children!==1||n.previous?.name!==fn?`a <${ve}> is only written right after the <title> that opens a stamped group`:void 0},mt=(e,t={})=>{if(t.idPrefix!==void 0&&!tt(t.idPrefix))return`the id prefix "${E(t.idPrefix)}" is not one the serializer accepts`;let n=e.split(`
16
- `);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[p,l]of n.entries()){let f=p+1,y=de=>`line ${f}: ${de}`;if(l==="")return y("a blank line");let b=bo.exec(l);if(b!==null)return y(`the control character ${lt(b[0])} is not allowed`);if(te(l)!==l)return y("a code point XML cannot carry is not allowed");if(a)return y("content after the root element");let C=l.replace(So,""),R=jo(C,t);if("problem"in R)return y(R.problem);let{line:u}=R,w=u.kind==="close"?r.pop():void 0;if(u.kind==="close"&&w?.name!==u.name)return y(w===void 0?`</${E(u.name)}> closes nothing`:`</${E(u.name)}> closes <${w.name}>, opened on line ${w.lineNumber}`);let x=l.length-C.length,U=r.length*go.length;if(x!==U)return y(`indented ${x} spaces where the nesting calls for ${U}`);if(u.kind==="close"){if(w.name===P){if(w.children===0)return y("<a> has to open with the <title> of the group it links");i-=1}if(w.described&&!w.drawsRoute)return y(`a <${ve}> belongs to a line's route group, and this group draws no route`);a=r.length===0;continue}let v=r.at(-1),vt=Go(u,r.length)??(v&&(Vo(u,v,i)??Jo(u,r)??Zo(u,r)??qo(u,r)));if(vt!==void 0)return y(vt);let ie=u.attributes.get("id");if(ie!==void 0){if(o.has(ie))return y(`the id ${E(ie)} is declared twice`);o.set(ie,u.name)}for(let[de,Er]of u.attributes){let St=ko[de];St!==void 0&&s.push({attribute:de,id:wn.exec(Er)[1],kind:St,lineNumber:f})}v!==void 0&&(v.children+=1,v.previous=u,v.firstPath??=u.name===un?u:void 0,v.linked||=v.stamped&&u.name===P),Tn(u)&&((v.name===P?r.at(-2):v).hitArea=!0);let Le=$n(r);Le!==void 0&&(Le.described||=u.name===ve,Le.drawsRoute||=v.firstPath===u&&In(u));let ae=Cn(r);ae!==void 0&&gn.has(u.name)&&(ae.drawsBox=!0),ae!==void 0&&u.name===Y&&u.attributes.has(re)&&(ae.nestsStamp=!0),u.kind==="open"&&(r.push({name:u.name,lineNumber:f,stamped:u.name===Y&&u.attributes.has(re),children:0,linked:!1,hitArea:!1,drawsBox:!1,described:!1,drawsRoute:!1,nestsStamp:!1}),i+=u.name===P?1:0)}let d=r.at(-1);if(d!==void 0)return`<${d.name}> opened on line ${d.lineNumber} is never closed`;let m=s.find(({id:p,kind:l})=>o.get(p)!==l);return m===void 0?void 0:`line ${m.lineNumber}: ${m.attribute}: url(#${E(m.id)}) names no <${m.kind}> the file declares`};var pt=" ",_n=/^( *)<g data-md-element="([^"]*)">$/,Qo=/^<title>[^<]*<\/title>$/,ft=".svg",An=".png",Rn=[137,80,78,71,13,10,26,10],es=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},ts=e=>{let t=new Map;for(let[n,r]of e){let o=Xe(n);!t.has(o)&&Te(r)&&t.set(o,r)}return t},ns=(e,t,n)=>{let r=n+pt,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}},rs=(e,t)=>{if(t.size===0)return e;let n=e.split(`
17
- `),r=[],o=0;for(;o<n.length;){let s=n[o];r.push(s),o+=1;let i=_n.exec(s),a=i?t.get(i[2]):void 0;if(!i||a===void 0)continue;let d=i[1],m=d+pt,p=n[o];if(p===void 0||!p.startsWith(m)||!Qo.test(p.slice(m.length)))continue;let l=ns(n,o-1,d);if(l!==void 0){for(r.push(`${m}<a href="${Xe(a)}">`);o<l;o+=1)r.push(pt+n[o]);r.push(`${m}</a>`)}}return r.join(`
18
- `)},os=e=>e.split(`
19
- `).some(t=>_n.test(t)),Pn=(e,t)=>e.toLowerCase().endsWith(ft)&&!os(new TextDecoder().decode(t));var L=class extends Error{path;problem;constructor(t,n){super(`Refused the diagram file ${t}: ${n}`),this.name="RefusedMediaError",this.path=t,this.problem=n}},ss=e=>e.length>=Rn.length&&Rn.every((t,n)=>e[n]===t),is=(e,t)=>{let n=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return typeof n=="string"?{idPrefix:on(n)}:{}},Mn=({manifest:e,mediaIndex:t})=>{let n=ts(es(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 L(i,"the bytes are not UTF-8 text")}let m=is(t,i),p=mt(d,m);if(p!==void 0)throw new L(i,p);let l=rs(d,n);if(l===d)return a;let f=mt(l,m);if(f!==void 0)throw new L(i,`once linked, ${f}`);return o.encode(l)};return(i,a)=>{let d=i.toLowerCase();if(d.endsWith(ft))return s(i,a);if(!d.endsWith(An))throw new L(i,`a diagram file is an ${ft} or a ${An}, and this is neither`);if(!ss(a))throw new L(i,"the bytes are not a PNG image");return a}};var z=e=>{let t=e.payloads??{},n=[];for(let r of e.manifest.fragments??[]){let o=r.realization?.path;if(!o)continue;let s=t[r.address];s!==void 0&&n.push({path:o,content:s})}return n},Ln="image/svg+xml, image/png",Se=e=>{let t=[];for(let n of e.fragments??[])for(let r of n.realization?.media??[])t.push(r);return[...new Set(t)]},X=(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 Dn=(e,t)=>{let n=Mn(e),r=Nn(e),o=new Map,s=[],i=[];for(let{path:l,bytes:f}of t){if(f===void 0){s.push(l);continue}try{o.set(l,n(l,f))}catch(y){if(!(y instanceof L))throw y;s.push(l),i.push({path:l,problem:y.problem})}}let a=new Set;for(let[l,f]of o){let y=r(l);y!==void 0&&Pn(l,f)&&a.add(y)}let d=l=>{let f=r(l);return f!==void 0&&a.has(f)},m=new Map([...o].filter(([l])=>!d(l))),p=s.filter(l=>!d(l));return{mediaBytesByPath:m,missingPaths:p,refusals:i.filter(({path:l})=>!d(l)),emptyDiagramIds:a,emptyDiagramPaths:t.map(({path:l})=>l).filter(d),...as(e,p,m)}},Nn=e=>{let t=e.mediaIndex??{};return n=>Object.hasOwn(t,n)?t[n]:void 0},as=(e,t,n)=>{let r=e.mediaIndex??{},o=Nn(e),s=new Set([...n.keys()].map(o)),i=a=>{let d=o(a);return d!==void 0&&s.has(d)};return{missingDiagrams:X(t.filter(a=>!i(a)),r),partialDiagrams:X(t.filter(i),r)}};import{existsSync as ut,lstatSync as On,realpathSync as ds}from"node:fs";import{homedir as cs}from"node:os";import{basename as ls,dirname as ms,isAbsolute as Ie,join as Fn,relative as ht,resolve as J}from"node:path";var Ae=(e,t,n)=>{if(Ie(n))throw new c(`Refusing an absolute path from the bundle manifest: ${n}`);let r=J(e,t),o=J(e,n),s=ht(r,o);if(s===""||s.startsWith("..")||Ie(s))throw new c(`Refusing a bundle path that escapes the content root: ${n}`);return o},ps=e=>{try{return On(e)}catch{return}},$e=e=>{let t=[],n=e;for(;!ut(n);){let o=ms(n);if(o===n)return e;t.unshift(ls(n)),n=o}let r=ds(n);return t.length>0?Fn(r,...t):r},gt=e=>{if(ps(e)?.isSymbolicLink())throw new c(`Refusing to write through an existing symlink at a managed path: ${e}`)},Re=(e,t)=>{let n=$e(e),r=$e(t),o=ht(n,r);if(o!==""&&(o.startsWith("..")||Ie(o)))throw new c(`Refusing a path that escapes the content root through a symlink: ${t}`)},yt=(e,t)=>{let n=J(e,t);if(n===J(e))throw new c(`The content root resolves to the repository root (${n}); refusing to sync it.`);if(n===J(cs()))throw new c("The content root resolves to your home directory; refusing to sync it.");if(ut(n)){if(On(n).isSymbolicLink())throw new c(`The content root ${n} is a symlink; refusing to sync it.`);if(ut(Fn(n,".git")))throw new c(`The content root ${n} contains a .git directory (it looks like a repo root); refusing.`)}let r=$e(J(e)),o=ht(r,$e(n));if(o!==""&&(o.startsWith("..")||Ie(o)))throw new c(`The content root ${n} resolves outside the repository via a symlinked ancestor; refusing.`);return n};var fs={respec:"data/model"},Hn=e=>{let t=fs[e];if(!t)throw new c(`The CLI does not know the content root for stack '${e}'.`);return t};var us=1500,hs=6e5,gs=e=>new Promise(t=>setTimeout(t,e)),ys=e=>e==="COMPLETED"||e==="COMPLETED_WITH_ERRORS"||e==="FAILED",Un=async(e,t,n)=>{let r=await e.postForJson(`/models/${t}/content-bundle/diagrams`,{template:n.template,version:n.version});if(!r.commit)throw new c("The diagram render did not return a resolved commit; cannot pin the pull.");return r},Wn=async(e,t,n,r,o,s={})=>{let i=s.sleep??gs,a=s.now??Date.now,d=a()+hs;for(r.update(0,o);;){let m=await e.getJson(`/models/${t}/export-jobs/${n}`);if(m.progress&&r.update(m.progress.completed,m.progress.total,m.progress.currentItem),ys(m.status))return r.done(),m;if(a()>=d)throw new c("Timed out waiting for the diagram render to finish.");await i(us)}},Bn=(e,t,n,r)=>e.getBytes(`/models/${t}/content-bundle/media`,{path:n,template:r.template,commit:r.commit});var zn=e=>{let t=new Map;for(let n of e.fragments??[])n.realization?.path&&t.set(n.elementId,n.realization.path);return t},jn=(e,t)=>{let n=zn(e),r=[];for(let[o,s]of zn(t)){let i=n.get(o);i&&i!==s&&r.push({elementId:o,oldPath:i,newPath:s})}return r};import{existsSync as ws,mkdirSync as ks,readFileSync as Es,writeFileSync as xs}from"node:fs";import{join as Gn}from"node:path";var Vn=(e,t)=>Gn(e,he,`${t}.manifest.json`),Kn=(e,t)=>{let n=Vn(e,t);if(!ws(n))return;let r;try{r=JSON.parse(Es(n,"utf8"))}catch{return}return bs(r)?r:void 0},bs=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")},Yn=(e,t,n)=>{ks(Gn(e,he),{recursive:!0}),xs(Vn(e,t),Ke(n))},Xn=e=>{let t=[];for(let n of e.fragments??[]){n.realization?.path&&t.push(n.realization.path);for(let r of n.realization?.media??[])t.push(r)}return t};var Ts=e=>`<figure data-md-diagram="${e}">`,Cs="</figure>",Jn=(e,t)=>{if(t.size===0||e.payloads===void 0)return e;let n=new Set([...t].map(Ts)),r=Object.fromEntries(Object.entries(e.payloads).map(([o,s])=>[o,vs(s,n)]));return{...e,payloads:r}},vs=(e,t)=>{let n=e.split(`
20
- `),r=[];for(let o=0;o<n.length;o+=1){let s=t.has(n[o])?n.indexOf(Cs,o):-1;if(s===-1){r.push(n[o]);continue}o=s,r.at(-1)===""&&n[o+1]===""&&(o+=1)}return r.join(`
21
- `)};import{existsSync as qn,mkdirSync as Zn,readdirSync as Ss,rmSync as Is,writeFileSync as Qn}from"node:fs";import{dirname as er,join as oe,relative as $s,sep as As}from"node:path";var tr=(e,t)=>{let n=oe(e,t);if(!qn(n))return[];let r=[],o=s=>{for(let i of Ss(s,{withFileTypes:!0})){let a=oe(s,i.name);i.isDirectory()?o(a):i.isFile()&&r.push($s(e,a).split(As).join("/"))}};return o(n),r},wt=(e,t,n)=>{let r=oe(e,t);for(let o of n){let s=Ae(e,t,o.path);gt(s),Re(r,s),Zn(er(s),{recursive:!0}),Qn(s,o.content)}},Rs=(e,t,n,r)=>{let o=oe(e,t),s=Ae(e,t,n);gt(s),Re(o,s),Zn(er(s),{recursive:!0}),Qn(s,r)},nr=(e,t,n,{mediaBytesByPath:r,emptyDiagramIds:o})=>{let s=[];for(let[d,m]of r)try{Rs(e,t,d,m)}catch(p){s.push({path:d,error:p})}if(o.size===0)return s;let i=new Map(z(n).map(d=>[d.path,d.content])),a=z(Jn(n,o)).filter(d=>i.get(d.path)!==d.content);return wt(e,t,a),s},kt=(e,t,n)=>{let r=Ae(e,t,n);return Re(oe(e,t),r),qn(r)?(Is(r),!0):!1},rr=(e,t,n)=>{for(let r of n)kt(e,t,r)};var _s=100,sr=e=>{if(e.newTextPaths.length===0&&!e.allowEmpty)throw new c("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=or([...e.newTextPaths,...e.newMediaPaths]).sort(),n=new Set(t),r=new Set(e.existingFiles),o=t.filter(p=>r.has(p)),s=e.priorManifestPaths!==void 0?"manifest-tracked":"full-sync",i=e.priorManifestPaths??e.existingFiles,a=or(i).filter(p=>!n.has(p)).sort(),d=a.length>0&&!e.adopted,m=a.length>0&&(a.length>t.length||a.length>_s);return{writes:t,overwrites:o,orphanCandidates:a,mode:s,adoptionNeeded:d,outsized:m}},Et=(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 c(`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:[]}},or=e=>[...new Set(e)];var ir=(e,t)=>{let n=Q(t);switch(n.mode){case"error":throw new c(n.message);case"secret":case"federated":return ke(e,n);case"interactive":return new we(e)}};var Ps=6e4,ar={unauthorized:"Run 'modeldesk auth login' and try again.",forbidden:"Your account may lack access to this model."},Ms={unauthorized:ue.unauthorized,forbidden:ue.forbidden,notFound:ue.notFound},H=class extends c{status;constructor(t,n){super(t),this.name="ApiError",this.status=n}},_e=(e,t)=>new xt(e.apiBase,ir(e,t),F(t)?Ms:ar),xt=class{constructor(t,n,r=ar){this.apiBase=t;this.tokens=n;this.hints=r}apiBase;tokens;hints;async getJson(t,n){return await(await this.request(t,{method:"GET"},n)).json()}async postForJson(t,n){return await(await this.request(t,{method:"POST"},n)).json()}async getBytes(t,n){let r=await this.request(t,{method:"GET",headers:{Accept:Ln}},n);return new Uint8Array(await r.arrayBuffer())}async request(t,n,r){let o=await this.tokens.getAccessToken(),s=Ls(this.apiBase,t,r),i;try{i=await fetch(s,{...n,headers:{Authorization:`Bearer ${o}`,Accept:"application/json",...n.headers??{}},signal:AbortSignal.timeout(Ps)})}catch(a){throw new c(`Could not reach ${this.apiBase} (${a.message}). Check the host and that the ModelDesk server is reachable.`)}if(!i.ok)throw await Ds(i,t,this.hints);return i}},Ls=(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()},Ds=async(e,t,n)=>{let r=`${e.status} ${e.statusText}`.trim();try{if((e.headers.get("content-type")??"").includes("json")){let s=await e.json(),i=s.detail??s.title;i&&(r=`${e.status} ${i}`)}}catch{}return e.status===401?new H(`Authentication failed (${r}). ${n.unauthorized}`,e.status):e.status===403?new H(`Not authorized (${r}). ${n.forbidden}`,e.status):e.status===404&&n.notFound?new H(`Not found (${r}). ${n.notFound}`,e.status):new H(`Request to ${t} failed: ${r}`,e.status)};var Ns=(e,t)=>{let n=t>0?Math.min(1,e/t):0,r=Math.round(n*24);return`[${"#".repeat(r)}${"-".repeat(24-r)}]`},dr=(e,t=n=>{process.stderr.write(n)})=>{let n=-1;return{update(r,o,s){if(e){let i=s?` ${s}`:"";t(`\r${Ns(r,o)} ${r}/${o}${i}\x1B[K`)}else if(r!==n){let i=s?` (${s})`:"";t(`Rendering diagrams: ${r}/${o}${i}
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(`
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)+`
15
+
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(`(^|(?<!
20
+ ))
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?`|
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=`
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}`:`
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(`
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+=`:
61
+
62
+ ${i}
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=`
77
+
78
+ `),m+=f+y.slice(d)+k,f=`
79
+ `,g=!0):k===""?f===`
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]!==`
84
+ `&&(m+=`
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!==`
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===`
95
+ `||r==="\r")&&!(r==="\r"&&e[t+2]!==`
96
+ `);)r===`
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?`
100
+
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:`
107
+ `}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
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`
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===`
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===`
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(`
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(`
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}
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}.
155
+ `),e.print(l?`Scopes: ${l}
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)}
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(`
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}
22
192
  `),n=r}},done(){e&&t(`
23
- `)}}};import{createInterface as Os}from"node:readline";var Pe=()=>!!(process.stdin.isTTY&&process.stdout.isTTY),bt=async e=>{if(!Pe())return!1;let t=Os({input:process.stdin,output:process.stderr});try{let n=await new Promise(r=>t.question(`${e} [y/N] `,r));return/^y(es)?$/i.test(n.trim())}finally{t.close()}};var T=e=>{process.stdout.write(e)},$=e=>{process.stderr.write(e)},cr=e=>{for(let t of e)$(` ${t}
24
- `)},mr=async e=>{let{values:t}=G(e.argv,{host:{type:"string"},model:{type:"string"},stack:{type:"string"},template:{type:"string"},version:{type:"string"},"no-diagrams":{type:"boolean"},"dry-run":{type:"boolean"},"allow-empty":{type:"boolean"},adopt:{type:"boolean"},yes:{type:"boolean"}}),n=ye(e,{host:t.host,model:t.model,stack:t.stack,template:t.template,version:t.version}),r={noDiagrams:!!t["no-diagrams"],dryRun:!!t["dry-run"],allowEmpty:!!t["allow-empty"],adopt:!!t.adopt,yes:!!t.yes},o=_e(n.instance,e.env),s=je(n.stack,"stack",h.stack,"--stack"),i=je(n.template,"template",h.template,"--template"),d=!r.noDiagrams&&!r.dryRun?await Un(o,n.model,{template:i,version:n.version}):void 0,m=d?.commit,p=await o.getJson(`/models/${n.model}/content-bundle`,{template:i,commit:m,version:m?void 0:n.version});if(p.manifest.stack!==s)throw new c(`Requested stack '${s}', but template '${i}' renders under stack '${p.manifest.stack}'. Run 'modeldesk bundle templates' to see valid stack/template pairs.`);let l=Hn(s);yt(n.loaded.repoRoot,l);let f=z(p),y=Se(p.manifest),b=X(y,p.mediaIndex),C=Kn(n.loaded.repoRoot,s),R=sr({newTextPaths:f.map(U=>U.path),newMediaPaths:y,priorManifestPaths:C?Xn(C):void 0,existingFiles:tr(n.loaded.repoRoot,l),adopted:C!==void 0||ge(n.loaded),allowEmpty:r.allowEmpty}),u=C?jn(C,p.manifest):[],w={stack:s,version:p.manifest.stackVersion};if(r.dryRun)return lr(n,i,w,m,R,void 0,u,b,!0),0;let x=await Fs(R,r);return lr(n,i,w,m,R,x,u,b,!1),yt(n.loaded.repoRoot,l),wt(n.loaded.repoRoot,l,f),rr(n.loaded.repoRoot,l,x.deletes),Yn(n.loaded.repoRoot,s,p.manifest),y.length===0||!d?0:Hs(o,n,i,m,d,p,{media:y,diagramCount:b},l)},Fs=async(e,t)=>{let{adopt:n,yes:r}=t;if(e.orphanCandidates.length===0)return Et(e,{adopt:n,yes:r});let o=Pe();return e.adoptionNeeded&&!n&&($(`The content root has ${e.orphanCandidates.length} file(s) the CLI does not track:
25
- `),cr(e.orphanCandidates),o&&(n=await bt("Adopt this directory and allow the CLI to remove these files?"))),e.outsized&&!r&&(n||!e.adoptionNeeded)&&($(`This pull would remove ${e.orphanCandidates.length} file(s), more than the ${e.writes.length} it writes:
26
- `),cr(e.orphanCandidates),o&&(r=await bt("Proceed with removing them?"))),Et(e,{adopt:n,yes:r})},Hs=async(e,t,n,r,o,s,{media:i,diagramCount:a},d)=>{let m=dr(Pe()),p=await Wn(e,t.model,o.id,m,a);if(p.status==="FAILED")return $(`warning: the diagram render failed. Text fragments are written; media was not fetched. Re-run to retry.
27
- `),1;let{repoRoot:l}=t.loaded,f=[],y=new Map;for(let w of i)try{f.push({path:w,bytes:await Bn(e,t.model,w,{template:n,commit:r})})}catch(x){f.push({path:w}),y.set(w,x)}let b=Dn(s,f),C=nr(l,d,s,b),R=new Map(b.refusals.map(({path:w,problem:x})=>[w,x]));for(let w of b.missingPaths){let x=R.get(w),U=y.get(w);$(x!==void 0?`warning: refused the diagram file ${w} and did not write it: ${x}
28
- `:`warning: could not fetch media ${w}: ${Tt(U)}
29
- `),(x!==void 0||Bs(U))&&pr(l,d,w)}for(let{path:w,error:x}of C)$(`warning: could not write media ${w}: ${Tt(x)}
30
- `);b.emptyDiagramIds.size>0&&Us(l,d,b.emptyDiagramIds.size,b.emptyDiagramPaths);let u=b.missingPaths.length+C.length;return p.status==="COMPLETED_WITH_ERRORS"||u>0?($(`warning: ${u} media file(s) could not be written; the pull is re-runnable.
31
- `),1):0},Us=(e,t,n,r)=>{T(` Left out ${n} empty diagram(s), which draw no model element:
32
- `);for(let o of r.filter(s=>s.toLowerCase().endsWith(".svg")))T(` - ${o}
33
- `);for(let o of r)pr(e,t,o,s=>T(` ${s}`))},Tt=e=>e instanceof Error?e.message:String(e),Ws=404,Bs=e=>e instanceof H&&e.status===Ws,pr=(e,t,n,r=o=>$(`warning: ${o}`))=>{try{kt(e,t,n)&&r(`removed the copy of ${n} an earlier pull wrote.
34
- `)}catch(o){$(`warning: could not remove the copy of ${n} an earlier pull wrote: ${Tt(o)}
35
- `)}},lr=(e,t,n,r,o,s,i,a,d)=>{let m=r?`commit ${r}`:e.version?`version ${e.version}`:"HEAD",p=`${n.stack} ${n.version}`;T(`${d?"Dry run: ":""}Pulling ${e.model} (stack ${p}, template ${t}) at ${m} into ${e.instance.host}.
36
- `),T(` Write: ${o.writes.length} file(s)${o.overwrites.length?` (${o.overwrites.length} overwritten)`:""}
37
- `),T(` Diagrams: ${a}
38
- `);let l=d?o.orphanCandidates:s?.deletes??[];T(` Remove: ${l.length} file(s) [${o.mode}]
39
- `);for(let f of l)T(` - ${f}
40
- `);if(d)o.adoptionNeeded&&T(` note: removing these needs --adopt (the root is not CLI-managed yet).
41
- `),o.outsized&&T(` note: this removal is larger than the write set and needs --yes.
42
- `);else for(let f of s?.warnings??[])$(`warning: ${f}
43
- `);for(let f of i)T(` moved: ${f.oldPath} -> ${f.newPath}
44
- `);if(d)for(let f of o.writes)T(` write ${f}
45
- `)};var Me=e=>{let t=[];for(let n of e)n.forEach((r,o)=>{t[o]=Math.max(t[o]??0,r.length)});return t},se=(e,{indent:t="",gap:n=2,widths:r}={})=>{let s=Me(e).map((a,d)=>r?.[d]??a),i=" ".repeat(n);return e.map(a=>t+a.map((d,m)=>m===a.length-1?d:d.padEnd(s[m])).join(i))};var zs=["STACK","TEMPLATE","NAME"],fr=async e=>{let{values:t}=G(e.argv,{host:{type:"string"},model:{type:"string"},stack:{type:"string"}}),n=ye(e,{host:t.host,model:t.model}),r=_e(n.instance,e.env),o=await r.getJson(`/models/${n.model}`),s=(o.metamodelExtensions??[]).map(f=>f.id),i=s.length>0?{metamodelExtensions:s.join(",")}:void 0,{items:a}=await r.getJson(`/metamodels/${o.metamodel.id}/templates`,i),d=a??[];if(d.length===0)return process.stdout.write(`This model has no document templates.
46
- `),0;let m=t.stack,p=m?d.filter(f=>f.stack===m):d;if(p.length===0)return process.stdout.write(`No document templates for stack '${m}'.
47
- `),0;let l=p.map(f=>[f.stack??"",f.key??f.id,f.name]);for(let f of se([zs,...l]))process.stdout.write(`${f}
48
- `);return 0};var Ct={bundle:{pull:{summary:"Materialize a model's content bundle into a local folder",usage:"bundle pull --model <id> --stack <id> --template <slug> [--host <host>] [--version <name>] [--no-diagrams] [--dry-run]",handler:mr},templates:{summary:"List a model's document templates",usage:"bundle templates --model <id> [--stack <id>] [--host <host>]",handler:fr}},auth:{login:{summary:"Log in through the browser (OAuth authorization code + PKCE)",usage:"auth login [--host <host>]",handler:Zt},logout:{summary:"Remove the stored credential for the active host",usage:"auth logout [--host <host>]",handler:Qt},status:{summary:"Show the active host, logged-in identity, and token validity",usage:"auth status [--host <host>]",handler:en}}};var ur={name:"@modeldesk/cli",version:"0.5.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"],publishConfig:{access:"public"},engines:{node:">=22"},scripts:{build:"node esbuild.config.mjs",prepublishOnly:"npm run build",typecheck:"tsc --noEmit",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.1",esbuild:"^0.28.2",eslint:"^10.12.0","eslint-config-prettier":"^10.1.5","eslint-plugin-prettier":"^5.5.6",globals:"^17.13.0",prettier:"^3.9.9",typescript:"^6.0.3","typescript-eslint":"^8.71.1",vitest:"^5.0.3"}};var hr=ur.version;var Gs={out:e=>process.stdout.write(e),err:e=>process.stderr.write(e)},yr=new Set(["--help","-h","help"]),kr=async(e,t=Gs)=>{try{return await Vs(e,t)}catch(n){return n instanceof c?(t.err(`error: ${n.message}
49
- `),n.exitCode):(t.err(`error: ${n instanceof Error?n.message:String(n)}
50
- `),1)}},Vs=async(e,t)=>{let[n,...r]=e;if(n===void 0||yr.has(n))return t.out(Ks()),0;if(n==="--version"||n==="-v")return t.out(`${hr}
51
- `),0;let o=Ct[n];if(!o)throw new c(`Unknown command '${n}'. Run 'modeldesk --help' to see available commands.`);let[s,...i]=r;if(s===void 0){let p=Object.keys(o).join(", ");throw new c(`'${n}' requires a subcommand (${p}). Run 'modeldesk ${n} --help'.`)}if(yr.has(s))return t.out(Ys(n,o)),0;let a=o[s];if(!a)throw new c(`Unknown '${n}' command '${s}'. Run 'modeldesk ${n} --help'.`);let d={argv:i,env:process.env,cwd:process.cwd()},m=await a.handler(d);return typeof m=="number"?m:0},wr=[["--help, -h","Show help"],["--version, -v","Show the CLI version"]],Ks=()=>{let e=[];for(let[r,o]of Object.entries(Ct))for(let[s,i]of Object.entries(o))e.push([`${r} ${s}`,i.summary]);let[t]=Me([...e,...wr]);return`${["ModelDesk CLI","","Usage: modeldesk <command> <subcommand> [options]","","Commands:",...se(e,{indent:" ",widths:[t]}),"","Global options:",...se(wr,{indent:" ",widths:[t]}),""].join(`
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:
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)`:""}
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.
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)}
256
+
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(`
52
259
  `)}
53
- `},Ys=(e,t)=>{let[n=0]=Me(Object.keys(t).map(o=>[o])),r=[`Usage: modeldesk ${e} <subcommand> [options]`,"","Subcommands:"];for(let[o,s]of Object.entries(t))r.push(` ${o.padEnd(n)}${" ".repeat(2)}${s.summary}`),r.push(` ${" ".repeat(n+2)}modeldesk ${s.usage}`);return r.push(""),`${r.join(`
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(`
54
272
  `)}
55
- `};var Xs=await kr(process.argv.slice(2));process.exitCode=Xs;
273
+
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
+ `);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;