@modeldesk/cli 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -2
- package/dist/modeldesk.js +70 -47
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -27,13 +27,14 @@ signed scripts for your own account with `Set-ExecutionPolicy -Scope CurrentUser
|
|
|
27
27
|
```
|
|
28
28
|
modeldesk bundle pull Materialize a model's content bundle into the repository
|
|
29
29
|
modeldesk bundle templates List a model's document templates (its stack/template pairs)
|
|
30
|
+
modeldesk note add Create an empty note file for an element and add it to the repo's notes.json
|
|
30
31
|
modeldesk auth login Log in through the browser (OAuth authorization code + PKCE)
|
|
31
32
|
modeldesk auth logout Remove the stored credential for the active host
|
|
32
33
|
modeldesk auth status Show the active host, identity, and token validity
|
|
33
34
|
```
|
|
34
35
|
|
|
35
|
-
Global options: `--help` (`-h`), `--version` (`-v`).
|
|
36
|
-
|
|
36
|
+
Global options: `--help` (`-h`), `--version` (`-v`). Commands take named flags; `note add` also takes
|
|
37
|
+
the element's name as a positional argument.
|
|
37
38
|
|
|
38
39
|
## Log in
|
|
39
40
|
|
|
@@ -125,6 +126,17 @@ searched, and a pull writes its content and manifest under the directory you run
|
|
|
125
126
|
environment only and are never placed in the committed config. In a machine run the host must
|
|
126
127
|
also come from `--host` or `MODELDESK_HOST` (see [Authenticate in CI](#authenticate-in-ci)).
|
|
127
128
|
|
|
129
|
+
Two more keys serve [notes](#note-add). They are read from the config file only, and each folder is a path
|
|
130
|
+
relative to the repository root:
|
|
131
|
+
|
|
132
|
+
- **`notesDir`** (default `md-notes/` at the repository root): the notes folder. A pull places every Markdown
|
|
133
|
+
file in it as a note, by its path, and `note add` creates note files in it; `--dir` overrides it for one
|
|
134
|
+
note. It cannot be the repository root, lie in the content root or hold it, or be a symlink.
|
|
135
|
+
- **`publishDirs`** (no default): the folders your document's publish step copies, such as
|
|
136
|
+
`["data", "media", "js", "css"]` for Geonovum's NL-ReSpec-template. A ReSpec snapshot inlines the note
|
|
137
|
+
Markdown, but an image a note links must sit in a copied folder; with `publishDirs` set, a pull warns
|
|
138
|
+
about every image outside them.
|
|
139
|
+
|
|
128
140
|
## `bundle pull`
|
|
129
141
|
|
|
130
142
|
A pull is a **full sync** of the content root (for ReSpec, `data/model/`). It writes every
|
|
@@ -223,6 +235,67 @@ respec logisch-toc MIM logisch (TOC hiërarchisch)
|
|
|
223
235
|
Take a `STACK` / `TEMPLATE` pair from the table straight into a pull. Pass `--stack <id>` to list
|
|
224
236
|
only the templates of one stack.
|
|
225
237
|
|
|
238
|
+
## `note add`
|
|
239
|
+
|
|
240
|
+
A **note** is your own Markdown under a generated element, a package, or the model root, kept outside the
|
|
241
|
+
content root so a pull never removes it. `intro` sits after the element's heading and diagrams, `after` at
|
|
242
|
+
the end of the element's own content (before nested subtypes).
|
|
243
|
+
|
|
244
|
+
A note file names its element by its path: the element's generated file under `data/model/`, with the notes
|
|
245
|
+
folder (`notesDir`, default `md-notes/`) in its place, ending in `.after.md` for the `after` slot. So
|
|
246
|
+
`md-notes/bestuurlijk-gebied/objecttype/gemeentegebied.md` is the `intro` note of the object type whose file is
|
|
247
|
+
`data/model/bestuurlijk-gebied/objecttype/gemeentegebied.md`, and `md-notes/bestuurlijk-gebied/index.after.md`
|
|
248
|
+
the `after` note of that domain. Creating the file is all an editor does, in the GitHub web editor if need be.
|
|
249
|
+
|
|
250
|
+
Every pull, CI's included, matches new note files against the manifest the server sends and records them in
|
|
251
|
+
`.modeldesk/notes.json` (committed: add `.modeldesk` to the workflow's commit beside `data/model`), keyed by
|
|
252
|
+
element id so a rename keeps the note in place. An entry can also name a file elsewhere, written by hand:
|
|
253
|
+
|
|
254
|
+
```json
|
|
255
|
+
{
|
|
256
|
+
"notes": {
|
|
257
|
+
"dafddbaf-9e2a-4eda-88f7-9fae3a47362f": {
|
|
258
|
+
"name": "Gemeentegebied",
|
|
259
|
+
"intro": "md-notes/bestuurlijk-gebied/objecttype/gemeentegebied.md"
|
|
260
|
+
},
|
|
261
|
+
"125cd721-c388-49ef-bc26-d9ee56964357": {
|
|
262
|
+
"name": "Domein Bestuurlijk gebied",
|
|
263
|
+
"intro": "data/model-overzicht.md",
|
|
264
|
+
"after": "md-notes/bestuurlijk-gebied/index.after.md"
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
`name` is refreshed by every pull and read by nothing. A package's or the model's `after` note comes under a
|
|
271
|
+
heading of its own, which becomes a numbered section in the table of contents; the note names it on its
|
|
272
|
+
first line, `<!-- heading: Afsluiting -->`, an HTML comment the document does not show.
|
|
273
|
+
|
|
274
|
+
Note paths are relative to the repository root, outside `data/model/`, and free of `..`, `%`, `#`, `?`,
|
|
275
|
+
backslashes and leading or trailing spaces. Editing a note's text needs no pull; adding or removing one, or
|
|
276
|
+
changing a heading line, does. Notes need a server that renders the `respec` stack at 1.4 or later with a
|
|
277
|
+
MIM template; a bundle without any note slot fails the pull once, naming its stack version.
|
|
278
|
+
|
|
279
|
+
```bash
|
|
280
|
+
modeldesk note add <name> [--slot intro|after] [--heading <text>] [--dir <dir>] [--element <id>] [--stack <id>]
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
`note add` creates the note at its path under `--dir` or `notesDir` (holding only the heading line for a
|
|
284
|
+
container's `after`, empty otherwise) and adds its entry to `notes.json`. It finds the element in the last
|
|
285
|
+
pull's manifest, so run `bundle pull` first; it contacts no server. A name several elements share is asked
|
|
286
|
+
about on a terminal and refused elsewhere, listing the ids for `--element`. `--heading` is required for a
|
|
287
|
+
package's or the model's `after` slot and refused elsewhere. It never overwrites a file, replaces a filled
|
|
288
|
+
slot, or names a file another entry names.
|
|
289
|
+
|
|
290
|
+
On pull, the CLI checks `notes.json` and the files it names before contacting the server. Once the bundle
|
|
291
|
+
has arrived, it stops before writing on a note file that matches no element (naming close paths), a note
|
|
292
|
+
file for a slot another file already fills, a missing note file, a path inside the content root, a slot the
|
|
293
|
+
element does not carry, or a container's `after` note without a heading line. It warns on an element not in
|
|
294
|
+
the bundle (the entry is kept), a heading line in a note that takes none, a missing image, an image outside
|
|
295
|
+
`publishDirs` or without alt text, a heading text two notes share without an explicit `{#id}`, and one file
|
|
296
|
+
filling several slots. `--dry-run` prints an `adopt <file>: <title> <slot>` line per new note file and a
|
|
297
|
+
`fill <title> <slot>: <path>` line per placed note, and writes nothing.
|
|
298
|
+
|
|
226
299
|
---
|
|
227
300
|
|
|
228
301
|
Learn more at [modeldesk.io](https://modeldesk.io).
|
package/dist/modeldesk.js
CHANGED
|
@@ -1,55 +1,78 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
3
|
-
import{chmodSync as
|
|
4
|
-
`,{mode:
|
|
5
|
-
`)},
|
|
6
|
-
${a}`),
|
|
7
|
-
`)},
|
|
8
|
-
`);let n=
|
|
3
|
+
import{chmodSync as vn,existsSync as Qo,mkdirSync as es,readFileSync as ts,writeFileSync as ns}from"node:fs";import{homedir as rs}from"node:os";import{join as Cn}from"node:path";var Nn=448,An=384,D=class{dir;file;constructor(t=Cn(rs(),".modeldesk")){this.dir=t,this.file=Cn(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(!Qo(this.file))return{hosts:{}};try{let t=JSON.parse(ts(this.file,"utf8"));if(t&&typeof t=="object"&&t.hosts&&typeof t.hosts=="object")return t}catch{}return{hosts:{}}}write(t){es(this.dir,{recursive:!0,mode:Nn}),ns(this.file,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`,{mode:An}),vn(this.dir,Nn),vn(this.file,An)}};var Et=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}},Oe=e=>{let t=Et(e);if(t)return t.name&&t.email?`${t.name} <${t.email}>`:t.email??t.name??t.sub};import{spawn as os}from"node:child_process";import{platform as ss}from"node:process";var Mn=e=>{if(!is(e))return;let{command:t,args:n,verbatim:r}=as(e);try{let o=os(t,n,{stdio:"ignore",detached:!0,windowsVerbatimArguments:r});o.on("error",()=>{}),o.unref()}catch{}},is=e=>{try{let{protocol:t}=new URL(e);return t==="http:"||t==="https:"}catch{return!1}},as=(e,t=ss)=>{switch(t){case"darwin":return{command:"open",args:[e]};case"win32":return{command:"cmd",args:["/c","start",'""',ds(e)],verbatim:!0};default:return{command:"xdg-open",args:[e]}}},ds=e=>e.replace(/[&|<>^()%"]/g,t=>`^${t}`);var xe="modeldesk-cli",Rn="modeldesk-federation",Pn="openid",$t="/callback";var ce=e=>e instanceof Error?e.message:String(e),l=class extends Error{exitCode;constructor(t,n=1){super(t),this.name="CliError",this.exitCode=n}};var G=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 l(`Could not reach the auth server at ${e} (${o.message}).`)}if(!n.ok)throw new l(`OpenID discovery failed at ${t}: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.authorization_endpoint||!r.token_endpoint)throw new l(`OpenID discovery at ${t} did not return the authorization and token endpoints.`);return{authorizationEndpoint:r.authorization_endpoint,tokenEndpoint:r.token_endpoint}};import{createServer as cs}from"node:http";var ls=3e5,_n=(e,t=ls)=>new Promise((n,r)=>{let o,s=new Promise((f,m)=>{o={resolve:f,reject:m}}),i=cs((f,m)=>{let u=new URL(f.url??"/","http://127.0.0.1");if(u.pathname!==$t){m.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}ms(u,m,e,o)}),a=setTimeout(()=>o.reject(new l("Timed out waiting for the browser login to complete.")),t);a.unref();let d=!1,c=()=>{d||(d=!0,clearTimeout(a),i.close())};s.then(c,c),i.once("error",f=>r(new l(`Could not start the loopback listener: ${f.message}`))),i.listen(0,"127.0.0.1",()=>{let{port:f}=i.address();n({redirectUri:`http://127.0.0.1:${f}${$t}`,waitForCode:()=>s,close:c})})}),ms=(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");xt(t,"Sign-in failed","Sign-in failed. You can close this window and return to the terminal."),r.reject(new l(`Authorization failed: ${i?`${o} (${i})`:o}`));return}let s=e.searchParams.get("code");if(!s){xt(t,"Sign-in failed","No authorization code was returned. You can close this window."),r.reject(new l("Login failed: no authorization code was returned."));return}xt(t,"Signed in","You are signed in to the ModelDesk CLI. You can close this window and return to the terminal."),r.resolve(s)},xt=(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 fs,randomBytes as Ln}from"node:crypto";var bt=e=>e.toString("base64url"),Dn=()=>{let e=bt(Ln(32)),t=bt(fs("sha256").update(e).digest());return{verifier:e,challenge:t,method:"S256"}},On=()=>bt(Ln(16));var le=class extends l{oauthError;errorDescription;constructor(t,n,r){super(t),this.name="TokenEndpointError",this.oauthError=n,this.errorDescription=r}},Fn=e=>e instanceof le&&e.oauthError==="invalid_grant",Hn=(e,t)=>He(e,new URLSearchParams({grant_type:"authorization_code",code:t.code,redirect_uri:t.redirectUri,client_id:xe,code_verifier:t.codeVerifier})),Fe=(e,t)=>He(e,new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:xe})),Un=(e,t)=>He(e,new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_secret:t.clientSecret})),Bn=(e,t)=>He(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:Rn})),He=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 l(`Could not reach the token endpoint (${o.message}).`)}if(!n.ok){let{message:o,code:s,description:i}=await ps(n);throw new le(`Token request failed: ${o}`,s,i)}let r=await n.json();if(!r.access_token)throw new l("The token response did not include an access token.");return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresInSeconds:r.expires_in??0}},ps=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 Ue={info:e=>process.stderr.write(`${e}
|
|
5
|
+
`)},Be=async(e,t)=>{let{authorizationEndpoint:n,tokenEndpoint:r}=await G(e.issuer),o=Dn(),s=On(),i=await _n(s);try{let a=us(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}`),Mn(a);let d=await i.waitForCode();return await Hn(r,{code:d,redirectUri:i.redirectUri,codeVerifier:o.verifier})}finally{i.close()}},us=(e,t,n,r)=>{let o=new URL(e);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",xe),o.searchParams.set("redirect_uri",t),o.searchParams.set("scope",Pn),o.searchParams.set("state",r),o.searchParams.set("code_challenge",n),o.searchParams.set("code_challenge_method","S256"),o.toString()};var St="modeldesk.io",k={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"},be=(...e)=>e.find(t=>t!==void 0&&t!==""),Se=(e,t,n)=>({host:be(e.host,t[k.host],n.host)??St,model:be(e.model,t[k.model],n.model),stack:be(e.stack,t[k.stack],n.stack),template:be(e.template,t[k.template],n.template),version:be(e.version,t[k.version],n.version)});var jn={requestUrl:"ACTIONS_ID_TOKEN_REQUEST_URL",requestToken:"ACTIONS_ID_TOKEN_REQUEST_TOKEN"},K=e=>e!==void 0&&e!=="",Wn=e=>e==="true"||e==="1",hs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Tt="mdsk_",zn=57,ee=(e,t)=>({mode:"error",reason:e,message:t}),V="org settings \u2192 Service accounts",Te=e=>{if(K(e[k.apiKey]))return ee("legacy-api-key",`${k.apiKey} is no longer supported: the CI credential shipped as service accounts, not bearer keys. Use secret mode (set ${k.clientId} and ${k.clientSecret} from ${V}) or, on GitHub Actions, federated auth (grant 'permissions: id-token: write' and add a trust rule). Unset ${k.apiKey}.`);let t=e[k.clientId],n=e[k.clientSecret];if(K(t)!==K(n)){let[s,i]=K(t)?[k.clientId,k.clientSecret]:[k.clientSecret,k.clientId];return ee("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(K(t)&&K(n))return hs.test(t)?n.startsWith(Tt)?n.length!==zn?ee("invalid-client-secret",`${k.clientSecret} has the wrong length: expected ${zn} characters, got ${n.length}. Check for truncation in the pipeline's secret store.`):{mode:"secret",clientId:t,clientSecret:n}:ee("invalid-client-secret",`${k.clientSecret} does not start with '${Tt}' (an issued secret always does). Check for quoting or truncation in the pipeline's secret store.`):ee("invalid-client-id",`${k.clientId} is not a service-account id: expected a UUID, got a ${t.length}-character value. Copy the account id from ${V}.`);let r=e[jn.requestUrl],o=e[jn.requestToken];return K(r)&&K(o)?{mode:"federated",oidcRequestUrl:r,oidcRequestToken:o}:Wn(e.GITHUB_ACTIONS)?ee("headless-ci",`Running on GitHub Actions without machine credentials. Grant 'permissions: id-token: write' to use federated auth (with a trust rule in ${V}), or set ${k.clientId} and ${k.clientSecret}. The CLI never opens a browser login in CI.`):Wn(e.CI)?ee("headless-ci",`Running in CI without machine credentials. Set ${k.clientId} and ${k.clientSecret} (${V}). The CLI never opens a browser login in CI.`):{mode:"interactive"}},Y=e=>{let t=Te(e);return t.mode==="secret"||t.mode==="federated"?t.mode:void 0},Gn=e=>`${e.slice(0,Tt.length+8)}\u2026`,Kn=`Check ${k.clientId} and ${k.clientSecret}; issue or rotate a secret in ${V}.`,Vn=`The service account may be disabled or deleted \u2014 check ${V}.`,Yn={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/${k.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."},je={unauthorized:`The machine token was rejected. A disabled or deleted service account fails on the next request; a revoked secret within five minutes. Check ${V}.`,forbidden:`The service account's scopes do not permit this \u2014 pulling content needs the 'model:content' scope (${V}).`,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 gs="http://localhost:8080",ys="http://localhost:8082",ws="localhost",ks=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]}},Es=e=>e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]",It=e=>{let t=ks(e);return Es(t)?{host:ws,apiBase:gs,issuer:ys}:{host:t,apiBase:`https://api.${t}`,issuer:`https://auth.${t}`}};import{existsSync as xs,readFileSync as bs}from"node:fs";import{join as Ss}from"node:path";import{posix as $s}from"node:path";var me=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'},T=e=>$s.normalize(e).replace(/(.)\/+$/,"$1"),te=(e,t)=>{let n=T(e),r=T(t);return r==="."||n===r||n.startsWith(`${r}/`)};var pe=".modeldesk",Ts="config.json",We="md-notes/",ze=e=>e.configPath!==void 0,Ie=e=>{let t=Ss(e,pe,Ts);return xs(t)?{config:Is(t),configPath:t,repoRoot:e}:{config:{},repoRoot:e}},Is=e=>{let t;try{t=bs(e,"utf8")}catch(o){throw new l(`Could not read ${e}: ${o.message}`)}let n;try{n=JSON.parse(t)}catch(o){throw new l(`${e} is not valid JSON: ${o.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new l(`${e} must contain a JSON object.`);let r=n;return{host:fe(r,"host",e),model:fe(r,"model",e),stack:fe(r,"stack",e),template:fe(r,"template",e),version:fe(r,"version",e),notesDir:vs(r,"notesDir",e),publishDirs:Cs(r,"publishDirs",e)}},fe=(e,t,n)=>{let r=e[t];if(r!==void 0){if(typeof r!="string")throw new l(`${n}: "${t}" must be a string.`);return r}},vs=(e,t,n)=>{let r=fe(e,t,n);return r!==void 0&&Xn(r,`"${t}"`,n),r},Cs=(e,t,n)=>{let r=e[t];if(r!==void 0){if(!Array.isArray(r)||!r.every(o=>typeof o=="string"))throw new l(`${n}: "${t}" must be an array of strings.`);return r.forEach((o,s)=>Xn(o,`"${t}"[${s}]`,n)),r}},Xn=(e,t,n)=>{let r=me(e);if(r!==void 0)throw new l(`${n}: ${t} ${JSON.stringify(e)} ${r}; give a folder relative to the repository root.`)};import{parseArgs as Ns}from"node:util";var X=(e,t,{positionals:n}={})=>{try{return Ns({args:e,options:t,allowPositionals:n??!1,strict:!0})}catch(r){throw new l(r.message)}};var Jn=(e,t,n)=>{let r=n[k.host];return!(t!==void 0&&t!==""||r!==void 0&&r!=="")&&ze(e)&&!!e.config.host},qn=(e,t,n)=>{Jn(e,t,n)&&e.config.host!==St&&process.stderr.write(`note: using host '${e.config.host}' from ${e.configPath} (it drives login and API calls).
|
|
7
|
+
`)},Zn=(e,t,n)=>{if(Y(n)&&Jn(e,t,n))throw new l(`In a machine-auth run the host must be set explicitly: pass --host or set ${k.host}. The committed ${e.configPath??".modeldesk/config.json"} is not a trusted source for where machine credentials are sent.`)},ue=(e,t={})=>{let{values:n}=X(e.argv,{host:{type:"string"}}),r=Ie(e.cwd),o=Se({host:n.host},e.env,r.config);return t.gateMachineHost&&Zn(r,n.host,e.env),qn(r,n.host,e.env),It(o.host)},Ge=(e,t)=>{let n=Ie(e.cwd),r=Se(t,e.env,n.config);if(Zn(n,t.host,e.env),qn(n,t.host,e.env),!r.model)throw new l(`No model specified. Pass --model, set ${k.model}, or add "model" to .modeldesk/config.json.`);return{instance:It(r.host),model:r.model,stack:r.stack,template:r.template,version:r.version,loaded:n}},ve=(e,t,n,r)=>{let o=e?.trim();if(!o)throw new l(`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 Qn=async e=>{let t=Y(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=ue(e),r=await Be(n,Ue),o=new D;r.refreshToken?o.saveRefreshToken(n.host,r.refreshToken):o.clearHost(n.host);let s=Oe(r.accessToken);return process.stdout.write(`Logged in to ${n.host}${s?` as ${s}`:""}.
|
|
9
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
|
|
11
|
-
`);let n=
|
|
10
|
+
`),0};var er=async e=>{let t=Y(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=ue(e),r=new D().clearHost(n.host);return process.stdout.write(r?`Logged out of ${n.host}.
|
|
12
12
|
`:`No stored credential for ${n.host}.
|
|
13
|
-
`),0};var
|
|
14
|
-
`)},
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");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
|
-
`)
|
|
17
|
-
|
|
18
|
-
`)},
|
|
19
|
-
`)
|
|
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
|
-
`)
|
|
13
|
+
`),0};var vt=6e4,Ke=class{constructor(t,n={}){this.instance=t;this.store=n.store??new D,this.io=n.io??Ue,this.now=n.now??Date.now}instance;store;io;now;accessToken;accessTokenExpiresAt=0;endpoints;async getAccessToken(){if(this.accessToken&&this.now()<this.accessTokenExpiresAt-vt)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 Fe(n,t))}catch(r){if(Fn(r))return;throw r}}async login(){return this.apply(await Be(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 G(this.instance.issuer)),this.endpoints}};var Ct=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??G}instance;mode;mint;now;discover;accessToken;accessTokenExpiresAt=0;endpoints;inflight;async getAccessToken(){return this.accessToken&&this.now()<this.accessTokenExpiresAt-vt?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 Ms(r,this.mode)}if(n.expiresInSeconds<=0)throw new l("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}},As=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 l(`Could not reach the GitHub OIDC token endpoint (${s.message}).`)}if(!r.ok)throw new l(`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 l("The GitHub OIDC token response did not include a token value. Check that the workflow grants 'permissions: id-token: write'.");return o.value},Ve=(e,t,n={})=>{let r=t.mode==="secret"?o=>Un(o,{clientId:t.clientId,clientSecret:t.clientSecret}):async o=>Bn(o,await As(t.oidcRequestUrl,t.oidcRequestToken,e.issuer));return new Ct(e,t.mode,r,n)},Ms=(e,t)=>{if(!(e instanceof le)||!e.oauthError)return e;if(t==="secret")return e.oauthError==="invalid_client"?new l(`${e.message} ${Kn}`):e;if(e.errorDescription===void 0)return e.oauthError==="invalid_grant"?new l(`${e.message} ${Vn}`):e;let n=Yn[e.errorDescription];return n?new l(`${e.message} \u2014 ${n}`):e};var U=e=>{process.stdout.write(`${e}
|
|
14
|
+
`)},tr=async e=>{let t=Te(e.env);if(t.mode==="error")throw new l(t.message);let n=t.mode==="secret"||t.mode==="federated",r=ue(e,{gateMachineHost:n});return U(`Host: ${r.host}`),U(`API: ${r.apiBase}`),t.mode==="secret"||t.mode==="federated"?Rs(r,t,e.env):Ps(r)},Rs=async(e,t,n)=>{t.mode==="secret"?U(`Auth: service account (secret mode), client ${t.clientId}, secret ${Gn(t.clientSecret)}`):U(`Auth: federated (GitHub Actions), repository ${n.GITHUB_REPOSITORY??"unknown"}, ref ${n.GITHUB_REF??"unknown"}`);let r=await Ve(e,t).getAccessToken(),o=Et(r)??{};U(`Status: credential valid. Account ${o.sub??"unknown"}, organization ${o.mdsk_org??"unknown"}.`);let s=typeof o.scope=="string"?o.scope.trim():"";return U(s?`Scopes: ${s}`:"Scopes: enforced server-side from the account's current scopes."),0},Ps=async e=>{let t=new D,n=t.getRefreshToken(e.host);if(!n)return U("Status: not logged in. Run 'modeldesk auth login'."),1;try{let{tokenEndpoint:r}=await G(e.issuer),o=await Fe(r,n);t.saveRefreshTokenIfPresent(e.host,o.refreshToken);let s=Oe(o.accessToken);return U(`Status: logged in${s?` as ${s}`:""} (credential valid).`),0}catch{return U("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 Ye=(e,t)=>e.at(-1)===""&&t==="";var _s=e=>`<figure data-md-diagram="${e}">`,Ls="</figure>",Nt=(e,t)=>{if(t.size===0||e.payloads===void 0)return e;let n=new Set([...t].map(_s)),r=Object.fromEntries(Object.entries(e.payloads).map(([o,s])=>[o,Ds(s,n)]));return{...e,payloads:r}},Ds=(e,t)=>{let n=e.split(`
|
|
15
|
+
`),r=[];for(let o=0;o<n.length;o+=1){let s=t.has(n[o])?n.indexOf(Ls,o):-1;if(s===-1){r.push(n[o]);continue}o=s,Ye(r,n[o+1])&&(o+=1)}return r.join(`
|
|
16
|
+
`)};var At=e=>`${JSON.stringify(e,null,2)}
|
|
17
|
+
`;var A=["intro","after"],O=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},Os=/^<!-- md-slot (?=intro [0-9a-f-]{36} -->$|after )(intro|after) ([0-9a-f-]{36})(?: heading=([1-6]))? -->$/,Fs="<!-- md-slot ",Ce=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},rr=e=>{if(!e.startsWith(Fs))return;let t=Os.exec(e);if(t===null)throw new Ce(e);let n={name:t[1],elementId:t[2]};return t[3]===void 0?n:{...n,heading:Number(t[3])}},or=e=>{let t=new Map;for(let[n,r]of Object.entries(e.payloads??{})){let o=r.split(`
|
|
18
|
+
`).flatMap(s=>rr(s)??[]);o.length>0&&t.set(n,o)}return t},Mt=(e,t)=>{if(e.payloads===void 0)return{bundle:e,filled:[],dropped:[]};let n=O(e.manifest),r=a=>n.get(a)?.anchor,o=[],s=[],i=Object.fromEntries(Object.entries(e.payloads).map(([a,d])=>{let c=Hs(d,t,r);return o.push(...c.filled.map(f=>({...f,address:a}))),s.push(...c.dropped.map(f=>({...f,address:a}))),[a,c.text]}));return{bundle:{...e,payloads:i},filled:o,dropped:s}},Hs=(e,t,n)=>{let r=e.split(`
|
|
19
|
+
`),o=[],s=new Set,i=[],a=[];for(let d=0;d<r.length;d+=1){let c=rr(r[d]);if(c===void 0){o.push(r[d]);continue}let f=t.get(c.elementId)?.[c.name],m=`${c.name} ${c.elementId}`;if(f!==void 0&&!s.has(m)){s.add(m),i.push(c),o.push(...Us(c,f,n));continue}f!==void 0&&a.push(c),Ye(o,r[d+1])&&(d+=1)}return{text:o.join(`
|
|
20
|
+
`),filled:i,dropped:a}},Us=(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[nr(t)]}if(typeof t=="string")throw new Error(`The ${e.name} slot of ${e.elementId} takes a note with a heading.`);let r=n(e.elementId);if(r===void 0)throw new Error(`The bundle's manifest has no anchor for ${e.elementId}.`);let o=t.heading.replace(/\s+/g," ").trim();if(o==="")throw new Error(`The ${e.name} note of ${e.elementId} has an empty heading.`);let s=`${r}-${ne(o)||e.name}`;return[`${"#".repeat(e.heading)} ${js(o)} {#${s}}`,"",nr(t.file)]},ne=e=>e.normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),nr=e=>`<div data-include-format="markdown" data-include="${Bs(e)}"></div>`,Bs=e=>e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">").replace(/\n/g," ").replace(/\r/g," "),js=e=>e.replace(/[\\`*_[\]()!#|~]/g,"\\$&").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\{/g,"{").replace(/\}/g,"}");var Ws=/[ \t\n\r\f]+/g,zs=/^[ \t\n\r\f]+|[ \t\n\r\f]+$/g,Gs=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Ne=e=>e.replace(Gs,"");var Ks=(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)},Rt=e=>Ks(e,2);var Vs=e=>e.replace(Ws," ").replace(zs,""),Pt=e=>Vs(Ne(e)).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var Ae="http://www.w3.org/2000/svg",ar="Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",_t="group",Lt="spacingAndGlyphs",Dt="italic",Ot="underline",he="none";var Xe="hidden",Je="stroke",Ft="auto";var Ys="start",qe="clip",Xs=/^[A-Za-z0-9_-]+$/,Js=/[^A-Za-z0-9_-]+/g,Ht=e=>Xs.test(e),dr=e=>e.replace(Js,"-");var Ut=(e,t)=>t?`${e}-${Ys}`:e,sr=String.raw`-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?`,ir=String.raw`[a-zA-Z]+\(\s*(?:${sr}(?:[\s,]+${sr})*)?\s*\)`,qs=new RegExp(String.raw`^${ir}(?:\s+${ir})*$`),cr=e=>qs.test(e);var Zs=/[\u0000- \u007F]/g,Qs=/^([a-zA-Z][a-zA-Z0-9+.-]*):/,ei=new Set(["http","https","mailto"]),Ze=e=>{let t=Ne(e).replace(Zs,"");if(t==="")return!1;let n=Qs.exec(t);return n===null||ei.has(n[1].toLowerCase())};var $="#4b5563";var P="white";var Bt="strokeWidth",Qe=[{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:$,stroke:$,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:P,stroke:$,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:$,stroke:$,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:P,stroke:$,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:$,strokeWidth:2}]},{id:"bar",markerWidth:18,markerHeight:12,refX:18,refY:6,shapes:[{element:"line",x1:13,y1:1,x2:13,y2:11,stroke:$,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:P,stroke:$,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:$,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:$,strokeWidth:1.5},{element:"line",x1:4,y1:1,x2:4,y2:11,stroke:$,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:$,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:P,stroke:$,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:$,strokeWidth:1.5},{element:"circle",cx:4,cy:6,r:2.75,fill:P,stroke:$,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:$,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:P,stroke:$,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:P,stroke:$,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:$,strokeWidth:1.5},{element:"path",d:"M 19 1 L 19 11 L 11 6 Z",fill:P,stroke:$,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:$,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:P,stroke:$,strokeWidth:1.5,strokeLinejoin:"round"},{element:"circle",cx:8.25,cy:6,r:2.75,fill:P,stroke:$,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:P,stroke:$,strokeWidth:1.5,strokeLinejoin:"round"},{element:"line",x1:8,y1:1,x2:8,y2:11,stroke:$,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:$,strokeWidth:1.5}]}],El=new Map(Qe.map(e=>[e.id,e]));var si=" ",jt=["fill","fill-opacity","stroke","stroke-opacity","stroke-width","stroke-dasharray"],ii={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",...jt],path:["d",...jt,"stroke-linejoin","marker-start","marker-end","visibility","pointer-events"],polygon:["points",...jt],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"]},hr=new Map(Object.entries(ii).map(([e,t])=>[e,new Set(t)])),ai=new Set(["title","desc","text"]),lr="svg",ge="g",B="a",gr="title",Me="data-md-element",yr="path",wr=["visibility","pointer-events"],kr=new Set(["rect","text","polygon","line"]),di={"clip-path":"clipPath","marker-start":"marker","marker-end":"marker"},Er=/&(amp|lt|gt|quot|apos);/g,ci={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"},li=/[<>"']/,mi=/[\u0000-\u001F]/,fi=/^<([^\s/>]+)/,pi=/^<\/([^\s/>]+)>/,Wt=/ ([^\s=/>"'<]+)=/y,zt=/"([^"]*)"/y,ui=/^on/i,hi=/^ */,gi=64,mr=/[\p{Cc}\p{Cf}\u2028\u2029]/gu,j=String.raw`-?\d+(?:\.\d+)?(?:e\+\d+)?`,yi=new RegExp(`^${j}$`),wi=/^(?:[1-9]\d{0,2}|1000)$/,ki=new RegExp(`^0 0 ${j} ${j}$`),Ei=new RegExp(`^${j}(?:[ ,]${j})*$`),$i=new RegExp(`^(?:${j},${j}(?: ${j},${j})*)?$`),xi=/^[MmZzLlHhVvCcSsQqTtAa0-9eE.,+\- ]*$/,$r=/^url\(#([A-Za-z0-9_-]+)\)$/,xr=/^#[0-9a-f]{6}$/,fr=Array.from(new Set([he,...Qe.flatMap(({shapes:e})=>e.flatMap(t=>["fill"in t?t.fill:he,t.stroke])).filter(e=>!xr.test(e))])),br=Qe.flatMap(({id:e})=>[Ut(e,!1),Ut(e,!0)]),bi=new RegExp(`^${qe}-[1-9]\\d*$`),Si=new RegExp(`-${qe}-[1-9]\\d*$`),Vt=`${"md"}-`,Yt=e=>`U+${e.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}`,C=e=>{let t=[];for(let n of e){if(t.length===gi)return`${t.join("").replace(mr,Yt)}\u2026`;t.push(n)}return e.replace(mr,Yt)},Sr=e=>{if(e.includes("&#"))return"a numeric character reference is not allowed";let t=e.replace(Er,"");if(t.includes("&"))return"& does not start one of the five XML entities";let n=li.exec(t);return n===null?void 0:`an unescaped ${n[0]} is not allowed`},Tr=e=>e.replace(Er,(t,n)=>ci[n]),re=(e,t)=>n=>e.test(n)?void 0:`"${C(n)}" is not ${t}`,_=(e,t)=>n=>e.includes(Tr(n))?void 0:`"${C(n)}" is not ${t}`,pr=()=>{},S=re(yi,"a number as the serializer writes one"),ur=e=>xr.test(e)||fr.includes(e)?void 0:`"${C(e)}" is not a paint the serializer writes (#rrggbb, ${fr.join(", ")})`,Gt=re($r,"a reference to a definition in the file, as url(#\u2026)"),Ti=e=>bi.test(e)?"clipPath":br.includes(e)?"marker":void 0,Ii=(e,t)=>{if(!e.startsWith(Vt))return;let n=e.slice(Vt.length);if(t!==void 0)return n.startsWith(`${t}-`)?Ti(n.slice(t.length+1)):void 0;if(Ht(n))return(Si.exec(n)?.index??0)>0?"clipPath":br.some(r=>n.length>r.length+1&&n.endsWith(`-${r}`))?"marker":void 0},vi=(e,t,{idPrefix:n})=>{if(Ii(e,n)===t)return;let r=n??"<prefix>",o=t==="marker"?"<marker>[-start]":`${qe}-<n>`;return`"${C(e)}" is not an id the serializer gives a <${t}> (${Vt}${r}-${o})`},Ci=e=>{let t=Tr(e);return t.startsWith("#")&&Ze(t)?void 0:`"${C(e)}" does not point at a section of the page (#\u2026)`},Ni={xmlns:_([Ae],"the SVG namespace"),viewBox:re(ki,"a viewBox the serializer writes (0 0 width height)"),width:S,height:S,role:_([_t],`the role the serializer writes (${_t})`),"aria-label":pr,"font-family":_([ar],"the serializer's font stack"),id:vi,markerWidth:S,markerHeight:S,refX:S,refY:S,orient:_([Ft],`the marker orientation the serializer writes (${Ft})`),markerUnits:_([Bt],`the marker units the serializer writes (${Bt})`),"data-md-element":pr,"clip-path":Gt,transform:e=>cr(e)?void 0:`"${C(e)}" is not a transform of numbers the serializer writes`,href:Ci,x:S,y:S,rx:S,fill:ur,"fill-opacity":S,stroke:ur,"stroke-opacity":S,"stroke-width":S,"stroke-dasharray":re(Ei,"a dash pattern of numbers"),d:re(xi,"path data (commands and numbers only)"),"stroke-linejoin":_(["round"],"the line join the serializer writes (round)"),"marker-start":Gt,"marker-end":Gt,points:re($i,"polygon points as the serializer writes them (x,y x,y \u2026)"),x1:S,y1:S,x2:S,y2:S,cx:S,cy:S,r:S,"font-size":S,"font-weight":re(wi,"a numeric font weight (1 to 1000)"),"font-style":_([Dt],`the font style the serializer writes (${Dt})`),"text-decoration":_([Ot],`the decoration the serializer writes (${Ot})`),textLength:S,lengthAdjust:_([Lt],`the length adjustment the serializer writes (${Lt})`),visibility:_([Xe],`the visibility of a hit area (${Xe})`),"pointer-events":_([Je],`the pointer events of a hit area (${Je})`)},Ai=(e,t)=>{if(ui.test(t))return`the event-handler attribute ${C(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 ${C(t)} is not allowed`;if(!hr.get(e).has(t))return`<${e}> does not take the attribute ${C(t)}`},Mi=(e,t,n,r)=>{let o=Sr(n)??Ni[t](n,e,r);return o===void 0?void 0:`${t}: ${o}`},Ri=(e,t,n,r)=>{let o=new Map,s=n;for(;t[s]!==">"&&!t.startsWith("/>",s);){Wt.lastIndex=s;let i=Wt.exec(t)?.[1];if(i===void 0)return{problem:'a tag the serializer would not write: expected ` name="value"`, `>` or `/>`'};zt.lastIndex=Wt.lastIndex;let a=zt.exec(t)?.[1];if(a===void 0)return{problem:`the value of ${C(i)} is not double-quoted`};let d=Ai(e,i)??Mi(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=zt.lastIndex}return{attributes:o,end:s}},Kt=e=>e.startsWith("<")?"more than one element on one line":"text outside <title> and <text>",Pi=(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=pi.exec(e);if(m===null)return{problem:"a closing tag the serializer would not write"};let u=e.slice(m[0].length);return u!==""?{problem:Kt(u)}:{line:{kind:"close",name:m[1]}}}let n=fi.exec(e)?.[1];if(n===void 0)return{problem:"the line does not start with a tag"};if(!hr.has(n))return{problem:`<${C(n)}> is not an element the diagram serializer writes`};let r=Ri(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(!ai.has(n))return a!==""?{problem:Kt(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}>`,c=a.indexOf(d);if(c===-1)return{problem:`<${n}> is not closed on its line`};if(c+d.length!==a.length)return{problem:Kt(a.slice(c+d.length))};let f=Sr(a.slice(0,c));return f===void 0?{line:{kind:"text",name:n,attributes:o}}:{problem:`text: ${f}`}},_i=(e,t)=>{if(e.name===lr!=(t===0))return t===0?`the file opens with <${e.name}>, not the serializer's <svg xmlns="${Ae}"> root`:"<svg> is only the root, never nested";if(e.name===lr&&(e.kind!=="open"||e.attributes.get("xmlns")!==Ae))return`the root is not the serializer's <svg xmlns="${Ae}">`;if(e.name===B&&!e.attributes.has("href"))return"<a> without an href"},Li=(e,t,n)=>{if(t.name===B&&t.children===0&&e.name!==gr)return"<a> has to open with the <title> of the group it links";if(e.name===B)return e.kind!=="open"?"<a> is only written open, around the title and body of the group it links":t.name!==ge||!t.stamped||t.children!==0?`<a> is only written as the first child of a <g ${Me}>`:n>0?"an <a> inside another <a>":void 0},Ir=e=>wr.some(t=>e.attributes.has(t)),Di=(e,t)=>e.size===t.size&&Array.from(t).every(([n,r])=>e.get(n)===r),vr=e=>e.findLast(t=>t.stamped),Cr="a line's group draws no box: it holds no <rect>, <text>, <polygon> or <line>",Nr="a line's group holds no stamped group of its own",et="desc",Oi=e=>e!==void 0&&(e.hitArea||e.described),Fi={d:()=>!0,fill:e=>e===he,stroke:e=>e===$,"stroke-opacity":e=>e==="0","stroke-width":e=>e===Rt(1),"stroke-dasharray":e=>e==="6 4","marker-start":()=>!0,"marker-end":()=>!0},Ar=e=>e.name===yr&&e.attributes.get("fill")===he&&e.attributes.get("stroke")===$&&Array.from(e.attributes).every(([t,n])=>Fi[t]?.(n)??!1),Mr=e=>{let t=e.at(-1),n=t?.name===B?e.at(-2):t;return n?.name===ge&&n.stamped?n:void 0},Hi=(e,t)=>{if(!Ir(e))return;let n=t.at(-1),r=n.name===B?t.at(-2):n;if(r?.name!==ge||!r.stamped)return`a hit area (${wr.join(", ")}) is only written in a <g ${Me}>`;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 Cr;if(r.nestsStamp)return Nr;let o=n.previous;if(o===void 0||o!==n.firstPath||!Ar(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",he],["stroke",$],["stroke-width",Rt(10)],["visibility",Xe],["pointer-events",Je]]);return Di(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`},Ui=(e,t)=>{let n=vr(t);if(Oi(n))return kr.has(e.name)?Cr:e.name===ge&&e.attributes.has(Me)?Nr:void 0},Bi=(e,t)=>{if(e.name!==et)return;let n=t.at(-1);return Mr(t)===void 0||n.children!==1||n.previous?.name!==gr?`a <${et}> is only written right after the <title> that opens a stamped group`:void 0},Xt=(e,t={})=>{if(t.idPrefix!==void 0&&!Ht(t.idPrefix))return`the id prefix "${C(t.idPrefix)}" is not one the serializer accepts`;let n=e.split(`
|
|
21
|
+
`);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[f,m]of n.entries()){let u=f+1,h=x=>`line ${u}: ${x}`;if(m==="")return h("a blank line");let p=mi.exec(m);if(p!==null)return h(`the control character ${Yt(p[0])} is not allowed`);if(Ne(m)!==m)return h("a code point XML cannot carry is not allowed");if(a)return h("content after the root element");let y=m.replace(hi,""),E=Pi(y,t);if("problem"in E)return h(E.problem);let{line:g}=E,w=g.kind==="close"?r.pop():void 0;if(g.kind==="close"&&w?.name!==g.name)return h(w===void 0?`</${C(g.name)}> closes nothing`:`</${C(g.name)}> closes <${w.name}>, opened on line ${w.lineNumber}`);let b=m.length-y.length,N=r.length*si.length;if(b!==N)return h(`indented ${b} spaces where the nesting calls for ${N}`);if(g.kind==="close"){if(w.name===B){if(w.children===0)return h("<a> has to open with the <title> of the group it links");i-=1}if(w.described&&!w.drawsRoute)return h(`a <${et}> belongs to a line's route group, and this group draws no route`);a=r.length===0;continue}let I=r.at(-1),M=_i(g,r.length)??(I&&(Li(g,I,i)??Hi(g,r)??Bi(g,r)??Ui(g,r)));if(M!==void 0)return h(M);let L=g.attributes.get("id");if(L!==void 0){if(o.has(L))return h(`the id ${C(L)} is declared twice`);o.set(L,g.name)}for(let[x,Z]of g.attributes){let Q=di[x];Q!==void 0&&s.push({attribute:x,id:$r.exec(Z)[1],kind:Q,lineNumber:u})}I!==void 0&&(I.children+=1,I.previous=g,I.firstPath??=g.name===yr?g:void 0,I.linked||=I.stamped&&g.name===B),Ir(g)&&((I.name===B?r.at(-2):I).hitArea=!0);let F=Mr(r);F!==void 0&&(F.described||=g.name===et,F.drawsRoute||=I.firstPath===g&&Ar(g));let H=vr(r);H!==void 0&&kr.has(g.name)&&(H.drawsBox=!0),H!==void 0&&g.name===ge&&g.attributes.has(Me)&&(H.nestsStamp=!0),g.kind==="open"&&(r.push({name:g.name,lineNumber:u,stamped:g.name===ge&&g.attributes.has(Me),children:0,linked:!1,hitArea:!1,drawsBox:!1,described:!1,drawsRoute:!1,nestsStamp:!1}),i+=g.name===B?1:0)}let d=r.at(-1);if(d!==void 0)return`<${d.name}> opened on line ${d.lineNumber} is never closed`;let c=s.find(({id:f,kind:m})=>o.get(f)!==m);return c===void 0?void 0:`line ${c.lineNumber}: ${c.attribute}: url(#${C(c.id)}) names no <${c.kind}> the file declares`};var Jt=" ",_r=/^( *)<g data-md-element="([^"]*)">$/,ji=/^<title>[^<]*<\/title>$/,qt=".svg",Rr=".png",Pr=[137,80,78,71,13,10,26,10],Wi=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},zi=e=>{let t=new Map;for(let[n,r]of e){let o=Pt(n);!t.has(o)&&Ze(r)&&t.set(o,r)}return t},Gi=(e,t,n)=>{let r=n+Jt,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}},Ki=(e,t)=>{if(t.size===0)return e;let n=e.split(`
|
|
22
|
+
`),r=[],o=0;for(;o<n.length;){let s=n[o];r.push(s),o+=1;let i=_r.exec(s),a=i?t.get(i[2]):void 0;if(!i||a===void 0)continue;let d=i[1],c=d+Jt,f=n[o];if(f===void 0||!f.startsWith(c)||!ji.test(f.slice(c.length)))continue;let m=Gi(n,o-1,d);if(m!==void 0){for(r.push(`${c}<a href="${Pt(a)}">`);o<m;o+=1)r.push(Jt+n[o]);r.push(`${c}</a>`)}}return r.join(`
|
|
23
|
+
`)},Vi=e=>e.split(`
|
|
24
|
+
`).some(t=>_r.test(t)),Lr=(e,t)=>e.toLowerCase().endsWith(qt)&&!Vi(new TextDecoder().decode(t));var W=class extends Error{path;problem;constructor(t,n){super(`Refused the diagram file ${t}: ${n}`),this.name="RefusedMediaError",this.path=t,this.problem=n}},Yi=e=>e.length>=Pr.length&&Pr.every((t,n)=>e[n]===t),Xi=(e,t)=>{let n=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return typeof n=="string"?{idPrefix:dr(n)}:{}},Dr=({manifest:e,mediaIndex:t})=>{let n=zi(Wi(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 W(i,"the bytes are not UTF-8 text")}let c=Xi(t,i),f=Xt(d,c);if(f!==void 0)throw new W(i,f);let m=Ki(d,n);if(m===d)return a;let u=Xt(m,c);if(u!==void 0)throw new W(i,`once linked, ${u}`);return o.encode(m)};return(i,a)=>{let d=i.toLowerCase();if(d.endsWith(qt))return s(i,a);if(!d.endsWith(Rr))throw new W(i,`a diagram file is an ${qt} or a ${Rr}, and this is neither`);if(!Yi(a))throw new W(i,"the bytes are not a PNG image");return a}};var oe=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},Or="image/svg+xml, image/png",tt=e=>{let t=[];for(let n of e.fragments??[])for(let r of n.realization?.media??[])t.push(r);return[...new Set(t)]},ye=(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 Fr=(e,t)=>{let n=Dr(e),r=Hr(e),o=new Map,s=[],i=[];for(let{path:m,bytes:u}of t){if(u===void 0){s.push(m);continue}try{o.set(m,n(m,u))}catch(h){if(!(h instanceof W))throw h;s.push(m),i.push({path:m,problem:h.problem})}}let a=new Set;for(let[m,u]of o){let h=r(m);h!==void 0&&Lr(m,u)&&a.add(h)}let d=m=>{let u=r(m);return u!==void 0&&a.has(u)},c=new Map([...o].filter(([m])=>!d(m))),f=s.filter(m=>!d(m));return{mediaBytesByPath:c,missingPaths:f,refusals:i.filter(({path:m})=>!d(m)),emptyDiagramIds:a,emptyDiagramPaths:t.map(({path:m})=>m).filter(d),...Ji(e,f,c)}},Hr=e=>{let t=e.mediaIndex??{};return n=>Object.hasOwn(t,n)?t[n]:void 0},Ji=(e,t,n)=>{let r=e.mediaIndex??{},o=Hr(e),s=new Set([...n.keys()].map(o)),i=a=>{let d=o(a);return d!==void 0&&s.has(d)};return{missingDiagrams:ye(t.filter(a=>!i(a)),r),partialDiagrams:ye(t.filter(i),r)}};import{existsSync as Zt,lstatSync as Br,realpathSync as qi,statSync as Zi}from"node:fs";import{homedir as Qi}from"node:os";import{basename as ea,dirname as ta,isAbsolute as jr,join as Wr,relative as na,resolve as we,sep as ra}from"node:path";var nt=(e,t,n)=>{if(jr(n))throw new l(`Refusing an absolute path from the bundle manifest: ${n}`);let r=we(e,t),o=we(e,n);if(o===r||!Qt(r,o))throw new l(`Refusing a bundle path that escapes the content root: ${n}`);return o},Qt=(e,t)=>{let n=na(e,t);return n===""||!jr(n)&&n!==".."&&!n.startsWith(`..${ra}`)},Re=(e,t,{ignoreCase:n=!1}={})=>{let r=Ur(e),o=Ur(t);return n?Qt(r.toLowerCase(),o.toLowerCase()):Qt(r,o)},se=e=>{try{return Br(e)}catch{return}},ie=e=>{try{return Zi(e)}catch{return}},Ur=e=>{let t=[],n=e;for(;!Zt(n);){let o=ta(n);if(o===n)return e;t.unshift(ea(n)),n=o}let r=qi(n);return t.length>0?Wr(r,...t):r},z=e=>{if(se(e)?.isSymbolicLink())throw new l(`Refusing to write through an existing symlink at a managed path: ${e}`)},rt=(e,t)=>{if(!Re(e,t))throw new l(`Refusing a path that escapes the content root through a symlink: ${t}`)},en=(e,t)=>{let n=we(e,t);if(n===we(e))throw new l(`The content root resolves to the repository root (${n}); refusing to sync it.`);if(n===we(Qi()))throw new l("The content root resolves to your home directory; refusing to sync it.");if(Zt(n)){if(Br(n).isSymbolicLink())throw new l(`The content root ${n} is a symlink; refusing to sync it.`);if(Zt(Wr(n,".git")))throw new l(`The content root ${n} contains a .git directory (it looks like a repo root); refusing.`)}if(!Re(we(e),n))throw new l(`The content root ${n} resolves outside the repository via a symlinked ancestor; refusing.`);return n};var zr={respec:"data/model"},tn=e=>Object.hasOwn(zr,e)?zr[e]:void 0,ot=e=>{let t=tn(e);if(!t)throw new l(`The CLI does not know the content root for stack '${e}'.`);return t};var oa=1500,sa=6e5,ia=e=>new Promise(t=>setTimeout(t,e)),aa=e=>e==="COMPLETED"||e==="COMPLETED_WITH_ERRORS"||e==="FAILED",Gr=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 l("The diagram render did not return a resolved commit; cannot pin the pull.");return r},Kr=async(e,t,n,r,o,s={})=>{let i=s.sleep??ia,a=s.now??Date.now,d=a()+sa;for(r.update(0,o);;){let c=await e.getJson(`/models/${t}/export-jobs/${n}`);if(c.progress&&r.update(c.progress.completed,c.progress.total,c.progress.currentItem),aa(c.status))return r.done(),c;if(a()>=d)throw new l("Timed out waiting for the diagram render to finish.");await i(oa)}},Vr=(e,t,n,r)=>e.getBytes(`/models/${t}/content-bundle/media`,{path:n,template:r.template,commit:r.commit});var Yr=e=>{let t=new Map;for(let n of e.fragments??[])n.realization?.path&&t.set(n.elementId,n.realization.path);return t},Xr=(e,t)=>{let n=Yr(e),r=[];for(let[o,s]of Yr(t)){let i=n.get(o);i&&i!==s&&r.push({elementId:o,oldPath:i,newPath:s})}return r};import{existsSync as da,mkdirSync as ca,readFileSync as la,writeFileSync as ma}from"node:fs";import{join as Jr}from"node:path";var qr=(e,t)=>Jr(e,pe,`${t}.manifest.json`),st=(e,t)=>{let n=qr(e,t);if(!da(n))return;let r;try{r=JSON.parse(la(n,"utf8"))}catch{return}return fa(r)?r:void 0},fa=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")},Zr=(e,t,n)=>{ca(Jr(e,pe),{recursive:!0}),ma(qr(e,t),At(n))},Qr=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};import{existsSync as eo,mkdirSync as to,readdirSync as pa,rmSync as ua,writeFileSync as no}from"node:fs";import{dirname as ro,join as Pe,relative as ha,sep as ga}from"node:path";var oo=(e,t)=>{let n=Pe(e,t);if(!eo(n))return[];let r=[],o=s=>{for(let i of pa(s,{withFileTypes:!0})){let a=Pe(s,i.name);i.isDirectory()?o(a):i.isFile()&&r.push(ha(e,a).split(ga).join("/"))}};return o(n),r},nn=(e,t,n)=>{let r=Pe(e,t);for(let o of n){let s=nt(e,t,o.path);z(s),rt(r,s),to(ro(s),{recursive:!0}),no(s,o.content)}},ya=(e,t,n,r)=>{let o=Pe(e,t),s=nt(e,t,n);z(s),rt(o,s),to(ro(s),{recursive:!0}),no(s,r)},so=(e,t,n,{mediaBytesByPath:r,emptyDiagramIds:o})=>{let s=[];for(let[d,c]of r)try{ya(e,t,d,c)}catch(f){s.push({path:d,error:f})}if(o.size===0)return s;let i=new Map(oe(n).map(d=>[d.path,d.content])),a=oe(Nt(n,o)).filter(d=>i.get(d.path)!==d.content);return nn(e,t,a),s},rn=(e,t,n)=>{let r=nt(e,t,n);return rt(Pe(e,t),r),eo(r)?(ua(r),!0):!1},io=(e,t,n)=>{for(let r of n)rn(e,t,r)};var wa=100,co=e=>{if(e.newTextPaths.length===0&&!e.allowEmpty)throw new l("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=ao([...e.newTextPaths,...e.newMediaPaths]).sort(),n=new Set(t),r=new Set(e.existingFiles),o=t.filter(f=>r.has(f)),s=e.priorManifestPaths!==void 0?"manifest-tracked":"full-sync",i=e.priorManifestPaths??e.existingFiles,a=ao(i).filter(f=>!n.has(f)).sort(),d=a.length>0&&!e.adopted,c=a.length>0&&(a.length>t.length||a.length>wa);return{writes:t,overwrites:o,orphanCandidates:a,mode:s,adoptionNeeded:d,outsized:c}},on=(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 l(`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:[]}},ao=e=>[...new Set(e)];var lo=(e,t)=>{let n=Te(t);switch(n.mode){case"error":throw new l(n.message);case"secret":case"federated":return Ve(e,n);case"interactive":return new Ke(e)}};var ka=6e4,mo={unauthorized:"Run 'modeldesk auth login' and try again.",forbidden:"Your account may lack access to this model."},Ea={unauthorized:je.unauthorized,forbidden:je.forbidden,notFound:je.notFound},J=class extends l{status;constructor(t,n){super(t),this.name="ApiError",this.status=n}},it=(e,t)=>new sn(e.apiBase,lo(e,t),Y(t)?Ea:mo),sn=class{constructor(t,n,r=mo){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:Or}},n);return new Uint8Array(await r.arrayBuffer())}async request(t,n,r){let o=await this.tokens.getAccessToken(),s=$a(this.apiBase,t,r),i;try{i=await fetch(s,{...n,headers:{Authorization:`Bearer ${o}`,Accept:"application/json",...n.headers??{}},signal:AbortSignal.timeout(ka)})}catch(a){throw new l(`Could not reach ${this.apiBase} (${a.message}). Check the host and that the ModelDesk server is reachable.`)}if(!i.ok)throw await xa(i,t,this.hints);return i}},$a=(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()},xa=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 J(`Authentication failed (${r}). ${n.unauthorized}`,e.status):e.status===403?new J(`Not authorized (${r}). ${n.forbidden}`,e.status):e.status===404&&n.notFound?new J(`Not found (${r}). ${n.notFound}`,e.status):new J(`Request to ${t} failed: ${r}`,e.status)};import{readdirSync as Sa}from"node:fs";import{join as _e,posix as Le}from"node:path";var po=e=>{let t=O(e),n=new Map;for(let r of e.fragments??[]){let o=n.get(r.elementId),s=r.realization?.path,i=s!==void 0&&(s===fo||s.endsWith(`/${fo}`));n.set(r.elementId,{elementId:r.elementId,title:t.get(r.elementId)?.title,kind:t.get(r.elementId)?.kind,path:o?.path??s,anchor:t.get(r.elementId)?.anchor,container:(o?.container??!1)||i})}return[...n.values()]},fo="index.md",an=e=>{let t=O(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})))},uo=(e,t)=>{let n=ne(t);return n===""?[]:e.filter(r=>r.slug===n)},at=e=>e.replace(/\s+/g," ").trim().toLowerCase(),dn=(e,t)=>{let n=at(t);return e.filter(r=>r.title!==void 0&&at(r.title)===n)},ba=5,ho=(e,t)=>{let n=at(t),r=n.length>=4?2:1,s=e.flatMap(i=>i.title===void 0?[]:[i.title]).filter(i=>{let a=at(i);return n.length>=3&&a.includes(n)||cn(a,n)<=r});return[...new Set(s)].slice(0,ba)},cn=(e,t)=>{let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r];for(let s=1;s<=t.length;s+=1)o[s]=Math.min(n[s]+1,o[s-1]+1,n[s-1]+(e[r-1]===t[s-1]?0:1));n=o}return n[t.length]};var dt=".after.md",ae=".md",yo=e=>e.toLowerCase().endsWith(dt),wo=e=>yo(e)?"after":"intro",ct=(e,t)=>{let n=me(e);if(n!==void 0)return`the notes folder ${JSON.stringify(e)} ${n}; give a folder relative to the repository root`;if(T(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(te(e.toLowerCase(),t.toLowerCase())||te(t.toLowerCase(),e.toLowerCase()))return`the notes folder ${e} overlaps the content root ${t}/, which every pull replaces; keep notes outside it`},lt=(e,t,n,r)=>{let o=`${T(t)}/`,s=T(n);if(!s.startsWith(o)||!s.endsWith(ae))return;let i=s.slice(o.length,-ae.length);return Le.join(T(e),`${i}${r==="after"?dt:ae}`)},ln=(e,t)=>se(_e(e,T(t)))?.isSymbolicLink()?`the notes folder ${T(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,ko=(e,t)=>{let n=T(t),r=ln(e,t);if(r!==void 0)throw new l(`${r[0].toUpperCase()}${r.slice(1)}.`);if(se(_e(e,n))?.isDirectory()!==!0)return[];let o=[],s=a=>{try{return Sa(_e(e,a),{withFileTypes:!0})}catch(d){throw new l(`Could not read the notes folder ${a}: ${d.message}`)}},i=a=>{for(let d of s(a)){if(d.name.startsWith("."))continue;let c=Le.join(a,d.name);d.isDirectory()?i(c):d.name.toLowerCase().endsWith(ae)&&!Ta(e,c,d)&&o.push(c)}};return i(n),o.sort()},Ta=(e,t,n)=>n.isSymbolicLink()?ie(_e(e,t))?.isDirectory()===!0:!1,Ia=5,Eo=({repoRoot:e,files:t,notesDir:n,contentRoot:r,manifest:o,entries:s})=>{let i=[...s.values()].flatMap(h=>A.flatMap(p=>h[p]===void 0?[]:[T(h[p])])),a=new Set(i),d=new Set(i.flatMap(h=>go(e,h)??[])),c=h=>{if(a.has(T(h)))return!0;let p=go(e,h);return p!==void 0&&d.has(p)},f=new Map;for(let h of o.fragments??[]){let p=h.realization?.path;p!==void 0&&!f.has(T(p))&&f.set(T(p),{elementId:h.elementId,title:h.title||void 0})}let m=[],u=new Map;for(let h of t.filter(p=>!c(p))){let p=wo(h),y=va(n,r,h),E=y===void 0?void 0:f.get(y);if(E===void 0){m.push(Ca(h,y,n,r,[...f.keys()]));continue}let g=s.get(E.elementId)?.[p],w=E.title??E.elementId;if(g!==void 0){m.push(`the note ${h} would be the ${p} note of ${w}, which notes.json already gives as ${g}; keep one of the two files.`);continue}let b=`${p} ${E.elementId}`,N=u.get(b);if(N!==void 0){m.push(`the notes ${N.file} and ${h} would both be the ${p} note of ${w}, which appears at more than one place in the document; keep one of the two files.`);continue}u.set(b,{file:h,elementId:E.elementId,slot:p,title:E.title})}return{adoptions:[...u.values()],errors:m}},go=(e,t)=>{let n=ie(_e(e,t));return n?.isFile()?`${n.dev}:${n.ino}`:void 0},va=(e,t,n)=>{let r=`${T(e)}/`,o=T(n);if(!o.startsWith(r))return;let s=o.slice(r.length),i=yo(s)?s.slice(0,-dt.length):s.toLowerCase().endsWith(ae)?s.slice(0,-ae.length):void 0;return i===void 0?void 0:Le.join(T(t),`${i}${ae}`)},Ca=(e,t,n,r,o)=>{let s=`A note's path is its element's file under ${T(r)}/ with ${T(n)}/ in its place, ending in ${dt} for the note after the element's content.`;if(t===void 0)return`the note ${e} matches no element: its name does not end in .md. ${s}`;let i=Le.basename(t),a=o.map(c=>({path:c,distance:cn(c,t)})).filter(({path:c,distance:f})=>Le.basename(c)===i||f<=2).sort((c,f)=>c.distance-f.distance||c.path.localeCompare(f.path)).slice(0,Ia).map(({path:c})=>lt(n,r,c,wo(e))).filter(c=>c!==void 0),d=a.length===0?"":` Did you mean ${a.join(", ")}?`;return`the note ${e} matches no element: this bundle has no ${t}.${d} ${s}`},mn=(e,t)=>{let n=new Map(e);for(let{file:r,elementId:o,slot:s,title:i}of t){let a=n.get(o);n.set(o,a===void 0?{...i===void 0?{}:{name:i},[s]:r}:{...a,[s]:r})}return n};import{join as fn}from"node:path";var pn=({repoRoot:e,contentRoot:t,entries:n})=>[...n].flatMap(([r,o])=>A.flatMap(s=>{let i=o[s];return i===void 0?[]:Na(e,t,i).map(a=>`${ke(r,o.name)} ${s}: ${a}.`)})),$o=({manifest:e,slots:t,entries:n,notesDir:r})=>{let o=Ma(e,t),s=[],i=[],d=[...n].some(([c,f])=>o.has(c)&&A.some(m=>f[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[c,f]of n){let m=o.get(c),u=ke(c,m?.title??f.name);if(m===void 0){i.push(`${u} is not in this bundle; its entry in notes.json is kept.`);continue}if(d===void 0)for(let h of A)f[h]!==void 0&&s.push(...Aa(m,h).map(p=>`${u} ${h}: ${p}.`))}return{errors:s,warnings:i,slotless:d}},un=e=>typeof e=="string"?e:e.file,hn=(e,t,n)=>{let r=me(n);if(r!==void 0)return[`the note path ${JSON.stringify(n)} ${r}; note paths are relative to the repository root`];if(te(n.toLowerCase(),t.toLowerCase()))return[`the note ${n} lies in the content root ${t}/, which every pull replaces, so the pull would remove it; keep notes outside it`];let o=fn(e,n);return Re(fn(e,t),o,{ignoreCase:!0})?[`the note ${n} lies in the content root ${t}/ through a symlink, and every pull replaces that folder, so the pull would remove it; keep notes outside it`]:Re(e,o)?[]:[`the note ${n} lies outside the repository through a symlink; keep notes inside it`]},Na=(e,t,n)=>{let r=hn(e,t,n);if(r.length>0)return r;let o=ie(fn(e,n));return o===void 0?[`the note ${n} does not exist`]:o.isFile()?[]:[`the note ${n} is not a file`]},Aa=(e,t)=>{let n=e.slots.get(t);if(n===void 0){let r=[...e.slots.keys()],o=e.kind===void 0?"the element":`this ${e.kind}`;return[r.length===0?`${o} carries no slots`:`${o} carries no ${t} slot, only ${r.join(" and ")}`]}return n.headed&&e.anchor===void 0?["the bundle's manifest gives the element no anchor to build the heading's id from"]:[]},Ma=(e,t)=>{let n=new Map;for(let[r,o]of O(e))n.set(r,{...o,slots:new Map});for(let r of(e.fragments??[]).flatMap(o=>o.anchors??[]))n.has(r.elementId)||n.set(r.elementId,{kind:r.kind,slots:new Map});for(let r of[...t.values()].flat()){let o=n.get(r.elementId)??{slots:new Map};n.set(r.elementId,o);let s=o.slots.get(r.name)?.headed??!1;o.slots.set(r.name,{headed:s||r.heading!==void 0})}return n},ke=(e,t)=>t===void 0?e:`${t} (${e})`;import{existsSync as Ra,readFileSync as xo}from"node:fs";import{join as Pa}from"node:path";var _a="notes.json",La=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Da=["name",...A],Oa=e=>Pa(e,pe,_a),mt=e=>{let t=Oa(e);if(!Ra(t))return{path:t,entries:new Map};let n;try{n=xo(t,"utf8")}catch(s){throw new l(`Could not read ${t}: ${s.message}`)}let r;try{r=JSON.parse(n)}catch(s){throw new l(`${t} is not valid JSON: ${s.message}`)}if(!gn(r))throw new l(`${t} must contain a JSON object with a "notes" object.`);for(let s of Object.keys(r))if(s!=="notes")throw new l(`${t}: unknown key "${s}"; the file holds only "notes".`);if(!gn(r.notes))throw new l(`${t}: "notes" must be an object of entries keyed by element id.`);let o=new Map;for(let[s,i]of Object.entries(r.notes))o.set(s,Ua(t,s,i));return Ha(t,n,o),{path:t,entries:o,raw:n}},Fa=/"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"\s*:/g,Ha=(e,t,n)=>{let r=new Map;for(let[,o]of t.matchAll(Fa))r.set(o,(r.get(o)??0)+1);for(let o of n.keys())if((r.get(o)??0)>1)throw new l(`${e}: notes key "${o}" appears more than once, and JSON keeps only the last; merge the entries.`)},Ua=(e,t,n)=>{if(!La.test(t))throw new l(`${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(!gn(n))throw new l(`${e}: ${r} must be an object.`);for(let o of Object.keys(n))if(!Da.includes(o))throw new l(`${e}: ${r} has an unknown key "${o}"; an entry takes "name", "intro" and "after".`);if(n.name!==void 0&&typeof n.name!="string")throw new l(`${e}: ${r}.name must be a string.`);for(let o of A)if(n[o]!==void 0&&typeof n[o]!="string")throw new l(`${e}: ${r}.${o} must be a note path. A note that comes under a heading names it on its own first line, <!-- heading: \u2026 -->.`);return n},gn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),bo=e=>{try{return xo(e,"utf8")}catch{return}};import{readFileSync as Ya}from"node:fs";import{join as vo,posix as Xa}from"node:path";var Ba=/^ {0,3}(`{3,}|~{3,})/,yn=/^(?: {4}|\t)/,ja=/^ {0,3}(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$)/,To=e=>{let t=[],n,r=!1,o=!0,s=!1;for(let i of e.split(/\r?\n/)){let a=i.trim()==="",d=Ba.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||yn.test(i)))){if(r=!1,d!==void 0){n=d,o=!1;continue}if(yn.test(i)&&o&&!s){r=!0;continue}a||(s=ja.test(i)||s&&yn.test(i)),o=a,t.push(i)}}return t},Wa=/(?<!`)(`+)(?!`)(.*?[^`])\1(?!`)/g,za=/!\[([^\]]*)\]\(\s*(?:<([^>]*)>|([^\s)]+))(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)/g,Ga=/<img\b([^>]*)>/gi,Ka=/([^\s=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g,Io=e=>{let t=To(e).map(r=>r.replace(Wa,o=>" ".repeat(o.length))).join(`
|
|
25
|
+
`),n=[];for(let r of t.matchAll(za))n.push({src:r[2]??r[3],alt:r[1],syntax:"markdown"});for(let r of t.matchAll(Ga)){let o=new Map;for(let i of r[1].matchAll(Ka))o.set(i[1].toLowerCase(),i[2]??i[3]??i[4]??"");let s=o.get("src");s!==void 0&&n.push({src:s,alt:o.get("alt"),syntax:"html"})}return n},Va=/^ {0,3}#{1,6}(?=[ \t]|$)(.*)$/,So=/\s*\{#[^\s}]+\}$/,wn=e=>To(e).flatMap(t=>{let n=Va.exec(t);if(n===null)return[];let r=n[1].replace(/(?:^|[ \t]+)#+[ \t]*$/,"").trim(),o=So.test(r),s=o?r.replace(So,""):r;return s===""?[]:[{text:s,explicitId:o}]});var Co=e=>{let{repoRoot:t,manifest:n,slots:r,entries:o,notes:s,placed:i}=e,a=O(n),d=p=>a.get(p)?.title??o.get(p)?.name,c=new Map;for(let{name:p,elementId:y}of i.filled){let E=s.get(y)?.[p],g=`${p} ${y}`;E!==void 0&&!c.has(g)&&c.set(g,{elementId:y,title:d(y)??y,slot:p,target:E})}let f=[],m=[],u=new Map;for(let{target:p}of c.values())u.set(un(p),(u.get(un(p))??0)+1);for(let[p,y]of u)try{m.push({file:p,text:Ya(vo(t,p),"utf8"),slots:y})}catch(E){f.push(`could not read the note ${p}, so its images and headings were not checked: ${ce(E)}`)}for(let p of m)f.push(...Za(t,p.file,p.text,e.publishDirs));f.push(...Qa(m),...ed(n,i.dropped,d));let h=[...r.values()].reduce((p,y)=>p+y.length,0);return{warnings:f,substitutions:[...c.values()],removedSlots:h-i.filled.length}},Ja=/^(?:https?:|data:|\/\/)/i,qa=e=>{let t=e.replace(/[?#].*$/,""),n=t;try{n=decodeURIComponent(t)}catch{}return Xa.normalize(n.replace(/^\/+/,""))},Za=(e,t,n,r)=>Io(n).flatMap(({src:o,alt:s,syntax:i})=>{let a=[];if((s===void 0||i==="markdown"&&s.trim()==="")&&a.push(`the note ${t} has an image without alt text, ${o}; describe it for readers who cannot see it.`),Ja.test(o))return a;let d=qa(o);if(d==="."||d==="")return a;if(ie(vo(e,d))?.isFile()!==!0){let c=d===o?"":` (${d} in the repository)`;a.push(`the note ${t} links the image ${o}${c}, which does not exist; image paths resolve against the repository root.`)}return r!==void 0&&!r.some(c=>te(d,c))&&a.push(`the note ${t} links the image ${o}, which lies outside the publishDirs (${r.join(", ")||"none"}), so the published copy will miss it.`),a}),Qa=e=>{let t=new Map;for(let o of e)for(let s of wn(o.text)){if(s.explicitId)continue;let i=ne(s.text),a=t.get(i)??{text:s.text,files:[]};a.files.includes(o.file)||t.set(i,{...a,files:[...a.files,o.file]})}let n=[...t.values()].filter(({files:o})=>o.length>1).map(({text:o,files:s})=>`the notes ${s.join(" and ")} each have the heading "${o}" without an explicit {#id}. ReSpec numbers the later ids, so a link to one shifts when the notes change; give each heading its own {#id}.`),r=e.filter(o=>o.slots>1&&wn(o.text).length>0).map(o=>`the note ${o.file} fills ${o.slots} slots, so each of its headings appears ${o.slots} times and their ids repeat or get numbered; give each place its own note file.`);return[...n,...r]},ed=(e,t,n)=>{let r=new Map((e.fragments??[]).map(s=>[s.address,s.realization?.path])),o=new Map;for(let{name:s,elementId:i,address:a}of t){let d=`${s} ${i}`,c=o.get(d)??{slot:s,elementId:i,files:new Set};o.set(d,{...c,files:c.files.add(r.get(a)??a)})}return[...o.values()].map(({slot:s,elementId:i,files:a})=>`${ke(i,n(i))} appears more than once in ${[...a].join(", ")}; its ${s} note goes in at the first place only.`)};import{renameSync as td,rmSync as No,writeFileSync as nd}from"node:fs";var Ao=(e,t)=>{let n=O(t);return[...e].flatMap(([r,o])=>{let s=n.get(r)?.title;return s===void 0||s===o.name?[]:[{elementId:r,from:o.name,to:s}]})},Mo=(e,t)=>{let n=new Map(t.map(r=>[r.elementId,r.to]));return new Map([...e].map(([r,o])=>{let s=n.get(r);return s===void 0?[r,o]:[r,"name"in o?{...o,name:s}:{name:s,...o}]}))},Ee=e=>`${JSON.stringify({notes:Object.fromEntries(e)},null,2)}
|
|
26
|
+
`,ft=(e,t)=>{z(e);let n=`${e}.tmp`;try{No(n,{force:!0}),nd(n,t,{flag:"wx"}),td(n,e)}catch(r){throw No(n,{force:!0}),r}};import{readFileSync as od}from"node:fs";import{join as sd}from"node:path";var rd=/^<!--\s*heading:(.*)-->$/i,Ro=e=>{let t=e.split(/\r?\n/).find(n=>n.trim()!=="");return t===void 0?void 0:rd.exec(t.trim())?.[1].trim()},pt=e=>`<!-- heading: ${e} -->`,De=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 Po=({repoRoot:e,slots:t,entries:n})=>{let r=[...t.values()].flat(),o=new Set(r.flatMap(c=>c.heading===void 0?[]:[`${c.name} ${c.elementId}`])),s=new Set(r.map(c=>c.elementId)),i=new Map,a=[],d=[];for(let[c,f]of n){let m={};for(let u of A){let h=f[u];if(h===void 0)continue;if(!s.has(c)){m[u]=h;continue}let p=id(e,h),y=`${ke(c,f.name)} ${u}`;o.has(`${u} ${c}`)?p===void 0||p===""?a.push(`${y}: the note ${h} comes under a heading of its own, so its first line names it, such as ${pt("Afsluiting")}.`):De(p)!==void 0?a.push(`${y}: the heading line of the note ${h} ${De(p)}.`):m[u]={file:h,heading:p}:(p!==void 0&&d.push(`${y}: the note ${h} starts with a heading line, which only the closing note of a package or the model takes; the line is left as a comment.`),m[u]=h)}i.set(c,m)}return{notes:i,errors:a,warnings:d}},id=(e,t)=>{try{return Ro(od(sd(e,t),"utf8"))}catch{return}};var ad=(e,t)=>{let n=t>0?Math.min(1,e/t):0,r=Math.round(n*24);return`[${"#".repeat(r)}${"-".repeat(24-r)}]`},_o=(e,t=n=>{process.stderr.write(n)})=>{let n=-1;return{update(r,o,s){if(e){let i=s?` ${s}`:"";t(`\r${ad(r,o)} ${r}/${o}${i}\x1B[K`)}else if(r!==n){let i=s?` (${s})`:"";t(`Rendering diagrams: ${r}/${o}${i}
|
|
22
27
|
`),n=r}},done(){e&&t(`
|
|
23
|
-
`)}}};import{createInterface as
|
|
24
|
-
`)},
|
|
25
|
-
`),
|
|
26
|
-
|
|
27
|
-
`)
|
|
28
|
-
|
|
29
|
-
`),(
|
|
30
|
-
`)
|
|
31
|
-
`),
|
|
32
|
-
`);for(let
|
|
33
|
-
|
|
34
|
-
`)}
|
|
35
|
-
`)
|
|
36
|
-
`),
|
|
37
|
-
`)
|
|
38
|
-
`);let
|
|
39
|
-
`)
|
|
40
|
-
`)
|
|
41
|
-
`),
|
|
42
|
-
`)
|
|
43
|
-
`);
|
|
44
|
-
`);
|
|
45
|
-
`)
|
|
46
|
-
`),
|
|
47
|
-
`)
|
|
48
|
-
`);
|
|
28
|
+
`)}}};import{createInterface as dd}from"node:readline";var de=()=>!!(process.stdin.isTTY&&process.stdout.isTTY),Lo=async e=>{let t=dd({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()}},kn=async e=>{if(!de())return!1;let t=await Lo(`${e} [y/N] `);return t!==void 0&&/^y(es)?$/i.test(t.trim())},Do=async(e,t)=>{if(!de())return;let n=await Lo(`${e} [1-${t}] `);if(n===void 0)return;let r=Number(n.trim());return Number.isInteger(r)&&r>=1&&r<=t?r-1:void 0};var v=e=>{process.stdout.write(e)},R=e=>{process.stderr.write(e)},En=e=>{for(let t of e)R(`warning: ${t}
|
|
29
|
+
`)},Oo=e=>{for(let t of e)R(` ${t}
|
|
30
|
+
`)},Uo=async e=>{let{values:t}=X(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=Ge(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=it(n.instance,e.env),s=ve(n.stack,"stack",k.stack,"--stack"),i=ve(n.template,"template",k.template,"--template"),{repoRoot:a}=n.loaded,d=mt(a),c=n.loaded.config.notesDir??We,f=tn(s);f!==void 0&&(ld(c,f),ut(pn({repoRoot:a,contentRoot:f,entries:d.entries})));let u=!r.noDiagrams&&!r.dryRun?await Gr(o,n.model,{template:i,version:n.version}):void 0,h=u?.commit,p=await o.getJson(`/models/${n.model}/content-bundle`,{template:i,commit:h,version:h?void 0:n.version});if(p.manifest.stack!==s)throw new l(`Requested stack '${s}', but template '${i}' renders under stack '${p.manifest.stack}'. Run 'modeldesk bundle templates' to see valid stack/template pairs.`);let y=ot(s);en(a,y);let{adoptions:E,errors:g}=Eo({repoRoot:a,files:ko(a,c),notesDir:c,contentRoot:y,manifest:p.manifest,entries:d.entries});ut([...g,...pn({repoRoot:a,contentRoot:y,entries:md(E)})]);let w=mn(d.entries,E),b=Fo(()=>or(p));cd($o({manifest:p.manifest,slots:b,entries:w,notesDir:c}));let N=Po({repoRoot:a,slots:b,entries:w});En(N.warnings),ut(N.errors);let I=Fo(()=>Mt(p,N.notes)),{bundle:M}=I,L=Co({repoRoot:a,manifest:p.manifest,slots:b,entries:w,notes:N.notes,placed:I,publishDirs:n.loaded.config.publishDirs});En(L.warnings);let F=Ao(w,M.manifest),H=Mo(w,F),x=Ee(H)!==Ee(d.entries),Z=oe(M),Q=tt(M.manifest),wt=ye(Q,M.mediaIndex),$e=st(n.loaded.repoRoot,s),kt=co({newTextPaths:Z.map(Zo=>Zo.path),newMediaPaths:Q,priorManifestPaths:$e?Qr($e):void 0,existingFiles:oo(n.loaded.repoRoot,y),adopted:$e!==void 0||ze(n.loaded),allowEmpty:r.allowEmpty}),Sn=$e?Xr($e,M.manifest):[],Tn={stack:s,version:M.manifest.stackVersion};if(r.dryRun)return Ho(n,i,Tn,h,kt,void 0,Sn,wt,!0),wd(L,E,F),0;x&&z(d.path);let In=await pd(kt,r);return Ho(n,i,Tn,h,kt,In,Sn,wt,!1),en(a,y),nn(a,y,Z),io(a,y,In.deletes),Zr(a,s,M.manifest),x&&fd(d,H,E.length,F.length),Q.length===0||!u?0:ud(o,n,i,h,u,M,{media:Q,diagramCount:wt},y)},Fo=e=>{try{return e()}catch(t){throw t instanceof Ce?new l(`${t.message} Update @modeldesk/cli and pull again.`):t}},cd=e=>{if(En(e.warnings),e.slotless!==void 0)throw new l(e.slotless);ut(e.errors)},ut=e=>{if(e.length>0)throw new l(`The notes have ${e.length} problem(s), so the pull stopped before writing anything:
|
|
31
|
+
`+e.map(t=>` - ${t}`).join(`
|
|
32
|
+
`))},ld=(e,t)=>{let n=ct(e,t);if(n!==void 0)throw new l(`${n[0].toUpperCase()}${n.slice(1)}. Set "notesDir" in .modeldesk/config.json.`)},md=e=>mn(new Map,e),fd=(e,t,n,r)=>{if(bo(e.path)!==e.raw){R(`warning: ${e.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.
|
|
33
|
+
`);return}ft(e.path,Ee(t));let o=[...n>0?[`${n} note(s) added`]:[],...r>0?[`${r} name(s) updated`]:[]];v(` notes.json: ${o.join(", ")||"rewritten"}
|
|
34
|
+
`)},pd=async(e,t)=>{let{adopt:n,yes:r}=t;if(e.orphanCandidates.length===0)return on(e,{adopt:n,yes:r});let o=de();return e.adoptionNeeded&&!n&&(R(`The content root has ${e.orphanCandidates.length} file(s) the CLI does not track:
|
|
35
|
+
`),Oo(e.orphanCandidates),o&&(n=await kn("Adopt this directory and allow the CLI to remove these files?"))),e.outsized&&!r&&(n||!e.adoptionNeeded)&&(R(`This pull would remove ${e.orphanCandidates.length} file(s), more than the ${e.writes.length} it writes:
|
|
36
|
+
`),Oo(e.orphanCandidates),o&&(r=await kn("Proceed with removing them?"))),on(e,{adopt:n,yes:r})},ud=async(e,t,n,r,o,s,{media:i,diagramCount:a},d)=>{let c=_o(de()),f=await Kr(e,t.model,o.id,c,a);if(f.status==="FAILED")return R(`warning: the diagram render failed. Text fragments are written; media was not fetched. Re-run to retry.
|
|
37
|
+
`),1;let{repoRoot:m}=t.loaded,u=[],h=new Map;for(let w of i)try{u.push({path:w,bytes:await Vr(e,t.model,w,{template:n,commit:r})})}catch(b){u.push({path:w}),h.set(w,b)}let p=Fr(s,u),y=so(m,d,s,p),E=new Map(p.refusals.map(({path:w,problem:b})=>[w,b]));for(let w of p.missingPaths){let b=E.get(w),N=h.get(w);R(b!==void 0?`warning: refused the diagram file ${w} and did not write it: ${b}
|
|
38
|
+
`:`warning: could not fetch media ${w}: ${ce(N)}
|
|
39
|
+
`),(b!==void 0||yd(N))&&Bo(m,d,w)}for(let{path:w,error:b}of y)R(`warning: could not write media ${w}: ${ce(b)}
|
|
40
|
+
`);p.emptyDiagramIds.size>0&&hd(m,d,p.emptyDiagramIds.size,p.emptyDiagramPaths);let g=p.missingPaths.length+y.length;return f.status==="COMPLETED_WITH_ERRORS"||g>0?(R(`warning: ${g} media file(s) could not be written; the pull is re-runnable.
|
|
41
|
+
`),1):0},hd=(e,t,n,r)=>{v(` Left out ${n} empty diagram(s), which draw no model element:
|
|
42
|
+
`);for(let o of r.filter(s=>s.toLowerCase().endsWith(".svg")))v(` - ${o}
|
|
43
|
+
`);for(let o of r)Bo(e,t,o,s=>v(` ${s}`))},gd=404,yd=e=>e instanceof J&&e.status===gd,Bo=(e,t,n,r=o=>R(`warning: ${o}`))=>{try{rn(e,t,n)&&r(`removed the copy of ${n} an earlier pull wrote.
|
|
44
|
+
`)}catch(o){R(`warning: could not remove the copy of ${n} an earlier pull wrote: ${ce(o)}
|
|
45
|
+
`)}},Ho=(e,t,n,r,o,s,i,a,d)=>{let c=r?`commit ${r}`:e.version?`version ${e.version}`:"HEAD",f=`${n.stack} ${n.version}`;v(`${d?"Dry run: ":""}Pulling ${e.model} (stack ${f}, template ${t}) at ${c} into ${e.instance.host}.
|
|
46
|
+
`),v(` Write: ${o.writes.length} file(s)${o.overwrites.length?` (${o.overwrites.length} overwritten)`:""}
|
|
47
|
+
`),v(` Diagrams: ${a}
|
|
48
|
+
`);let m=d?o.orphanCandidates:s?.deletes??[];v(` Remove: ${m.length} file(s) [${o.mode}]
|
|
49
|
+
`);for(let u of m)v(` - ${u}
|
|
50
|
+
`);if(d)o.adoptionNeeded&&v(` note: removing these needs --adopt (the root is not CLI-managed yet).
|
|
51
|
+
`),o.outsized&&v(` note: this removal is larger than the write set and needs --yes.
|
|
52
|
+
`);else for(let u of s?.warnings??[])R(`warning: ${u}
|
|
53
|
+
`);for(let u of i)v(` moved: ${u.oldPath} -> ${u.newPath}
|
|
54
|
+
`);if(d)for(let u of o.writes)v(` write ${u}
|
|
55
|
+
`)},wd=(e,t,n)=>{for(let{file:r,elementId:o,slot:s,title:i}of t)v(` adopt ${r}: ${i??o} ${s}
|
|
56
|
+
`);for(let{title:r,slot:o,target:s}of e.substitutions){let i=typeof s=="string"?s:`${s.file} under the heading "${s.heading}"`;v(` fill ${r} ${o}: ${i}
|
|
57
|
+
`)}v(` slots removed: ${e.removedSlots}
|
|
58
|
+
`);for(let{elementId:r,from:o,to:s}of n)v(` rename ${r} in notes.json: ${o===void 0?"(no name)":`"${o}"`} -> "${s}"
|
|
59
|
+
`)};var ht=e=>{let t=[];for(let n of e)n.forEach((r,o)=>{t[o]=Math.max(t[o]??0,r.length)});return t},q=(e,{indent:t="",gap:n=2,widths:r}={})=>{let s=ht(e).map((a,d)=>r?.[d]??a),i=" ".repeat(n);return e.map(a=>t+a.map((d,c)=>c===a.length-1?d:d.padEnd(s[c])).join(i))};var kd=["STACK","TEMPLATE","NAME"],jo=async e=>{let{values:t}=X(e.argv,{host:{type:"string"},model:{type:"string"},stack:{type:"string"}}),n=Ge(e,{host:t.host,model:t.model}),r=it(n.instance,e.env),o=await r.getJson(`/models/${n.model}`),s=(o.metamodelExtensions??[]).map(u=>u.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.
|
|
60
|
+
`),0;let c=t.stack,f=c?d.filter(u=>u.stack===c):d;if(f.length===0)return process.stdout.write(`No document templates for stack '${c}'.
|
|
61
|
+
`),0;let m=f.map(u=>[u.stack??"",u.key??u.id,u.name]);for(let u of q([kd,...m]))process.stdout.write(`${u}
|
|
62
|
+
`);return 0};import{mkdirSync as Ed,rmdirSync as $d,rmSync as xd,writeFileSync as bd}from"node:fs";import{dirname as $n,join as Wo,posix as gt}from"node:path";var Sd=e=>{process.stdout.write(e)},xn=e=>{process.stderr.write(e)},zo=async e=>{let{values:t,positionals:n}=X(e.argv,{slot:{type:"string"},heading:{type:"string"},dir:{type:"string"},element:{type:"string"},stack:{type:"string"}},{positionals:!0}),r=Ie(e.cwd),{repoRoot:o}=r,s=ve(Se({stack:t.stack},e.env,r.config).stack,"stack",k.stack,"--stack"),i=Td(t.slot),a=st(o,s);if(a===void 0)throw new l("Run 'modeldesk bundle pull' first: note add finds the element in the last pull's manifest.");let d=po(a),c=await Id(a,d,n.join(" "),t.element),f=yt(c),m=Cd(c,i,f,t.heading),u=ot(s),h=r.config.notesDir??We,p=Nd(o,u,t.dir??h,c,i),y=Wo(o,p),E=mt(o),g=E.entries.get(c.elementId),w=g?.[i];if(w!==void 0){let x=se(Wo(o,w))===void 0?"That file does not exist yet: create it":"Write in that file";throw new l(`${f} already has an ${i} note, ${w}. ${x}, or take the entry out of ${E.path} first.`)}let b=[...E.entries].find(([,x])=>A.some(Z=>x[Z]!==void 0&>.normalize(x[Z])===gt.normalize(p)));if(b!==void 0)throw new l(`${E.path} already names ${p} as a note of ${b[1].name??b[0]}; pick another folder with --dir.`);if(se(y)!==void 0){let x=c.path!==void 0&<(h,u,c.path,i)===p;throw new l(Ad(p,f,i,x))}z(E.path);let N=gt.dirname(p),I;try{I=Ed($n(y),{recursive:!0})}catch(x){throw new l(`Could not create ${N}: ${x.message}`)}let M=()=>{if(I!==void 0)for(let x=$n(y);;x=$n(x)){try{$d(x)}catch{return}if(x===I)return}};try{bd(y,m===void 0?"":`${pt(m)}
|
|
63
|
+
|
|
64
|
+
`,{flag:"wx"})}catch(x){throw M(),new l(`Could not create ${p}: ${x.message}`)}let L=new Map(E.entries),F=g===void 0?{...c.title===void 0?{}:{name:c.title},[i]:p}:{...g,[i]:p};L.set(c.elementId,F);try{ft(E.path,Ee(L))}catch(x){throw xd(y,{force:!0}),M(),x instanceof l?x:new l(`Could not write ${E.path}, so ${p} was not kept: ${x.message}`)}let H=m===void 0?"":`, under the heading "${m}"`;return Sd(`Created ${p}, the ${i} note of ${f}${H}.
|
|
65
|
+
`),0},Td=e=>{if(e===void 0)return"intro";if(!A.includes(e))throw new l(`--slot takes ${A.join(" or ")}, not "${e}".`);return e},yt=e=>{let t=e.kind===void 0?"":` (${e.kind})`;return e.title===void 0?`${e.elementId}${t}`:`${e.title}${t}`},Id=async(e,t,n,r)=>{if(r!==void 0)return vd(e,t,n,r);if(n.trim()==="")throw new l("Name the element: modeldesk note add <name>, or pass --element <id>.");let o=dn(t,n);if(o.length===1)return o[0];if(o.length===0){let i=uo(an(e),n);if(i.length>0)throw new l(`"${n.trim()}" is ${Go(i)}; anchor-level parts carry no note slots.`);let a=ho(t,n),d=a.length===0?"":` Did you mean ${a.map(c=>`"${c}"`).join(", ")}?`;throw new l(`No element in the last pull's manifest is named "${n.trim()}".${d}`)}if(de()){xn(`Several elements are named "${n.trim()}":
|
|
66
|
+
`);let i=o.map((d,c)=>[`${c+1}.`,yt(d),d.path??""]);xn(`${q(i,{indent:" "}).join(`
|
|
67
|
+
`)}
|
|
68
|
+
`);let a=await Do("Which one?",o.length);if(a===void 0)throw new l("No element chosen, so nothing was created.");return o[a]}let s=o.map(i=>[i.elementId,yt(i),i.path??""]);throw new l(`Several elements in the last pull's manifest are named "${n.trim()}"; pass --element <id> to pick one:
|
|
69
|
+
`+q(s,{indent:" "}).join(`
|
|
70
|
+
`))},vd=(e,t,n,r)=>{let o=r.trim().toLowerCase();if(o==="")throw new l("--element is blank; give the id of the element the note is for.");let s=t.find(i=>i.elementId===o);if(s===void 0){let i=an(e).filter(a=>a.elementId===o);throw i.length>0?new l(`${r.trim()} is ${Go(i)}; anchor-level parts carry no note slots.`):new l(`The last pull's manifest has no element ${r.trim()}. Run 'modeldesk bundle pull' if the model changed since.`)}return n.trim()!==""&&dn([s],n).length===0&&xn(`note: --element picks ${yt(s)}, so the name "${n.trim()}" was ignored.
|
|
71
|
+
`),s},Go=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 ")},Cd=(e,t,n,r)=>{if(t==="after"&&e.container){if(e.anchor===void 0)throw new l(`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 l(`The after note of ${n} comes under a heading of its own; pass --heading <text>.`);let o=De(r);if(o!==void 0)throw new l(`--heading ${o}; give the text of the heading the note comes under on one line.`);return r.trim()}if(r!==void 0)throw new l(`--heading is only for the after note of the model or a package; the ${t} note of ${n} takes none.`)},Nd=(e,t,n,r,o)=>{let s=ct(n,t)??ln(e,n);if(s!==void 0)throw new l(`${s[0].toUpperCase()}${s.slice(1)}.`);let a=(r.path===void 0?void 0:lt(n,t,r.path,o))??gt.join(n,`${ne(r.title??"")||r.elementId}${o==="after"?".after":""}.md`),[d]=hn(e,t,a);if(d!==void 0)throw new l(`${d[0].toUpperCase()}${d.slice(1)}. Pick another folder with --dir, or "notesDir" in .modeldesk/config.json.`);return a},Ad=(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 bn={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:Uo},templates:{summary:"List a model's document templates",usage:"bundle templates --model <id> [--stack <id>] [--host <host>]",handler:jo}},note:{add:{summary:"Create an empty note file for an element and add it to the repo's notes.json",usage:"note add <name> [--slot intro|after] [--heading <text>] [--dir <dir>] [--element <id>] [--stack <id>]",handler:zo}},auth:{login:{summary:"Log in through the browser (OAuth authorization code + PKCE)",usage:"auth login [--host <host>]",handler:Qn},logout:{summary:"Remove the stored credential for the active host",usage:"auth logout [--host <host>]",handler:er},status:{summary:"Show the active host, logged-in identity, and token validity",usage:"auth status [--host <host>]",handler:tr}}};var Ko={name:"@modeldesk/cli",version:"0.6.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.4"}};var Vo=Ko.version;var Rd={out:e=>process.stdout.write(e),err:e=>process.stderr.write(e)},Xo=new Set(["--help","-h","help"]),qo=async(e,t=Rd)=>{try{return await Pd(e,t)}catch(n){return n instanceof l?(t.err(`error: ${n.message}
|
|
49
72
|
`),n.exitCode):(t.err(`error: ${n instanceof Error?n.message:String(n)}
|
|
50
|
-
`),1)}},
|
|
51
|
-
`),0;let o=
|
|
73
|
+
`),1)}},Pd=async(e,t)=>{let[n,...r]=e;if(n===void 0||Xo.has(n))return t.out(_d()),0;if(n==="--version"||n==="-v")return t.out(`${Vo}
|
|
74
|
+
`),0;let o=bn[n];if(!o)throw new l(`Unknown command '${n}'. Run 'modeldesk --help' to see available commands.`);let[s,...i]=r;if(s===void 0){let f=Object.keys(o).join(", ");throw new l(`'${n}' requires a subcommand (${f}). Run 'modeldesk ${n} --help'.`)}if(Xo.has(s))return t.out(Ld(n,o)),0;let a=o[s];if(!a)throw new l(`Unknown '${n}' command '${s}'. Run 'modeldesk ${n} --help'.`);let d={argv:i,env:process.env,cwd:process.cwd()},c=await a.handler(d);return typeof c=="number"?c:0},Jo=[["--help, -h","Show help"],["--version, -v","Show the CLI version"]],_d=()=>{let e=[];for(let[r,o]of Object.entries(bn))for(let[s,i]of Object.entries(o))e.push([`${r} ${s}`,i.summary]);let[t]=ht([...e,...Jo]);return`${["ModelDesk CLI","","Usage: modeldesk <command> <subcommand> [options]","","Commands:",...q(e,{indent:" ",widths:[t]}),"","Global options:",...q(Jo,{indent:" ",widths:[t]}),""].join(`
|
|
52
75
|
`)}
|
|
53
|
-
`},
|
|
76
|
+
`},Ld=(e,t)=>{let[n=0]=ht(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(`
|
|
54
77
|
`)}
|
|
55
|
-
`};var
|
|
78
|
+
`};var Dd=await qo(process.argv.slice(2));process.exitCode=Dd;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@modeldesk/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Command-line interface (CLI) for the ModelDesk platform",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"modeldesk",
|
|
@@ -52,6 +52,6 @@
|
|
|
52
52
|
"prettier": "^3.9.9",
|
|
53
53
|
"typescript": "^6.0.3",
|
|
54
54
|
"typescript-eslint": "^8.71.1",
|
|
55
|
-
"vitest": "^5.0.
|
|
55
|
+
"vitest": "^5.0.4"
|
|
56
56
|
}
|
|
57
57
|
}
|