authoring-cli 0.1.21 → 0.1.22

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.
Files changed (3) hide show
  1. package/HELP.md +3 -3
  2. package/dist/index.js +21 -21
  3. package/package.json +1 -1
package/HELP.md CHANGED
@@ -13,7 +13,7 @@ npm install -g authoring-cli
13
13
  ```bash
14
14
  authoring-cli login
15
15
  ```
16
- This opens Chrome to your organization's login page, always in one dedicated "authoring-cli" Chrome profile (created automatically the first time, separate from your everyday browsing profile). Once you sign in, your session is captured automatically. This is the *only* profile `login` ever reads or writes cookies for — there's no flag to point it at a different (e.g. your everyday) profile instead, so there is never any ambiguity about which Chrome window/session the CLI is actually looking at.
16
+ This opens Chrome to your organization's login page, always in one dedicated "authoring-cli" Chrome profile stored in its own directory (`~/.authoring-cli-chrome`, created automatically the first time) — entirely separate from your everyday Chrome data, not just a different profile inside it. Once you sign in, your session is captured automatically. This is the *only* profile `login` ever reads or writes cookies for — there's no flag to point it at a different (e.g. your everyday) profile instead, so there is never any ambiguity about which Chrome window/session the CLI is actually looking at.
17
17
 
18
18
  **Important:** because this profile is separate, it opens its own Chrome window and (the first time) starts out *not* signed in — even if you already have a different Chrome window open and signed in. Sign in inside the window `login` just opened, not whichever Chrome window happened to be in front already; the command's own output names the profile ("Opening Chrome (profile \"authoring-cli\") ...") so you can check its avatar in Chrome's top-right corner. Signing in to the wrong window is the most common cause of `login` waiting out its full timeout and then failing with "Not signed in" on every subsequent command — if that happens, retry and make sure you type your credentials into the new window the command opens.
19
19
 
@@ -196,8 +196,8 @@ authoring-cli validate-review-concepts
196
196
  - Your session is stored in `<current working directory>/.authoring-cli/session.json` by default — not under your home directory, so it stays confined to whichever directory/workspace you run the CLI from; `login`'s own output always names exactly where it landed
197
197
  - Set `AUTHORING_CLI_HOME` to store it somewhere else instead — the session file is then `$AUTHORING_CLI_HOME/session.json`
198
198
  - If the working directory isn't writable, commands fail with a clear message rather than silently storing the session somewhere else — set `AUTHORING_CLI_HOME` in that case
199
- - `login` always uses (and creates on first use) one dedicated "authoring-cli" Chrome profile — never your everyday browsing profile, and with no flag to point it elsewhere — so sign in inside the window it opens, not whichever Chrome window was already in front
200
- - On macOS, `login` needs permission to read Chrome's cookie file — if the terminal/app you're running it from doesn't have "Full Disk Access" (System Settings → Privacy & Security → Full Disk Access), `login` now warns about this immediately, up front, rather than only failing silently after the full sign-in wait. Add your terminal app there and try again
199
+ - `login` always uses (and creates on first use) one dedicated "authoring-cli" Chrome profile, stored in its own directory (`~/.authoring-cli-chrome`) separate from your everyday Chrome data entirely — not just a different profile inside your real Chrome, so no macOS "Full Disk Access" permission is needed and signing in/out here never disturbs (or is disturbed by) your everyday browsing session. Sign in inside the window `login` opens, not whichever Chrome window was already in front
200
+ - If something else is still restricting access to that dedicated directory (an unusual sandbox, a read-only mount, ...), `login` warns about it immediately, up front, rather than only failing silently after the full sign-in wait
201
201
  - If your session expires during use, you'll get a `401 Unauthorized` error — run `authoring-cli login` again
202
202
 
203
203
  ### Task Selection
package/dist/index.js CHANGED
@@ -1,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Hr=Object.create;var ge=Object.defineProperty;var Yr=Object.getOwnPropertyDescriptor;var Wr=Object.getOwnPropertyNames;var Xr=Object.getPrototypeOf,Qr=Object.prototype.hasOwnProperty;var zr=(e,t)=>{for(var r in t)ge(e,r,{get:t[r],enumerable:!0})},$t=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Wr(t))!Qr.call(e,o)&&o!==r&&ge(e,o,{get:()=>t[o],enumerable:!(n=Yr(t,o))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?Hr(Xr(e)):{},$t(t||!e||!e.__esModule?ge(r,"default",{value:e,enumerable:!0}):r,e)),Zr=e=>$t(ge({},"__esModule",{value:!0}),e);var Gs={};zr(Gs,{COMMANDS:()=>Et,main:()=>Gr,parsePositionals:()=>qr});module.exports=Zr(Gs);var J={production:{imsEndpoint:"https://authoring.ihtsdotools.org/",terminologyServerEndpoint:"https://authoring.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://authoring.ihtsdotools.org/authoring-services/",cookieName:"ims-ihtsdo"},uat:{imsEndpoint:"https://uat-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://uat-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://uat-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"uat-ims-ihtsdo"},dev:{imsEndpoint:"https://dev-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://dev-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://dev-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"dev-ims-ihtsdo"}},ei={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},ye=Object.keys(J);function jt(e){return ei[e.trim().toLowerCase()]??null}var te="uat",Ys=J.uat.imsEndpoint,Ws=J.uat.terminologyServerEndpoint,Xs=J.uat.authoringServicesEndpoint;var ti=v(require("http")),oi=v(require("https"));function I(e,t={}){let{method:r="GET",cookie:n,body:o,headers:i={},timeoutMs:s=15e3}=t;return new Promise((a,c)=>{let l;try{l=new URL(e)}catch(k){c(k);return}let d=l.protocol==="https:"?oi:ti,u=o!==void 0?JSON.stringify(o):void 0,p={accept:"application/json",...i};if(u!==void 0&&(p["content-type"]="application/json",p["content-length"]=String(Buffer.byteLength(u))),n){let k=n.replace(/[^\x20-\x7e\t]/g,"");k&&(p.cookie=k)}let g=!1,h=d.request({hostname:l.hostname,port:l.port||void 0,path:l.pathname+l.search,method:r,headers:p},k=>{let b="";k.on("data",R=>{b+=R}),k.on("end",()=>{if(g)return;g=!0,clearTimeout(y);let R=k.statusCode??0,P=(k.headers["content-type"]??"").includes("application/json"),K=null,q=!1;if(b)try{K=JSON.parse(b)}catch{q=!P}a({statusCode:R,body:K,rawBody:b,sessionExpired:q})})});h.on("error",k=>{g||(g=!0,clearTimeout(y),c(k))});let y=setTimeout(()=>{g||(g=!0,h.destroy(),c(new Error(`Request to ${e} timed out after ${s}ms`)))},s);u!==void 0&&h.write(u),h.end()})}var M="900000000000509007",G="900000000000508004";var Pt={[M]:"en-us",[G]:"en-gb"},Nt={[M]:"true",[G]:"true"},ni={},ri={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:Pt,dialectDefaults:Nt,readOnlyDialects:ni,defaultLanguage:"en"};function Dt(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return ri;let t={[M]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let l=c.match(/^requiredLanguageRefset\.(.+)/);if(l){let d=l[1];t[String(e[c])]=d,o.length===0&&o.push(d)}}let i=e.requiredLanguageRefsets;if(Array.isArray(i))for(let c of i){if(typeof c!="object"||c===null)continue;let l=null,d=null;for(let[h,y]of Object.entries(c))h.length===2&&(l=h,d=String(y));if(!l||!d)continue;let u=c.dialectName;t[d]=typeof u=="string"?u:l;let p=c.default;p==="true"&&!o.includes(l)&&o.push(l),p!=null&&(r[d]=String(p));let g=c.readOnly;g!=null&&(n[d]=String(g))}let s=e.optionalLanguageRefsets;if(Array.isArray(s))for(let c of s)c&&typeof c=="object"&&"refsetId"in c&&(t[String(c.refsetId)]=String(c.language??""));let a=!!e.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?Pt:t,dialectDefaults:a?Nt:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function Je(e,t,r,n){let o={};for(let i of Object.keys(e.dialects)){let s=e.dialects[i];e.isExtension&&!r?s.includes(n)?o[i]="PREFERRED":s.includes(e.defaultLanguage)&&(o[i]="ACCEPTABLE"):s.includes(n)&&(o[i]=t),e.dialectDefaults[i]==="false"&&!r&&delete o[i],e.readOnlyDialects[i]==="true"&&delete o[i]}return o}function he(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[M]:"PREFERRED"}:Je(e,"PREFERRED",t,"en")}var ii="900000000000207008";function Ot(e){return e.replace(/\/$/,"")}function A(e){return Ot(e.terminologyServerEndpoint)}function E(e){return Ot(e.authoringServicesEndpoint)}function Ft(e){return`${new URL(E(e)).origin}/authoring-traceability-service`}function H(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function C(e,t,r){let n=t.projectKey||r?.projectKey,o=t.taskKey||r?.taskKey,i=!t.projectKey&&!t.taskKey,s=t.branchPath||(i?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(s||(s=await si(e,n,o)??void 0),s?{ok:!0,projectKey:n,taskKey:o,branchPath:s}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function Y(e,t){let r=A(e),n=await I(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(n.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode>=200&&n.statusCode<300)return{ok:!0,created:!1};if(n.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${n.statusCode}).`};let o=t.split("/").filter(Boolean),i=o[o.length-1],s=o.slice(0,-1).join("/");if(!i||!s)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await I(`${r}/branches`,{method:"POST",body:{parent:s,name:i},cookie:e.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${t} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function si(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body?.branchPath??null}async function Lt(e,t,r){let n=r?.get(t);if(n)return n;let o=`${E(e)}/projects/${t}`,s=(await I(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function U(e,t,r){let n=await Lt(e,t,r),o=n.multipleModuleEditingDisabled,i=!o||o==="false";return n.expectedExtensionModules?.length&&i?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:ii}async function W(e,t,r){let n=await Lt(e,t,r);return Dt(n)}async function Ge(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await I(r,{cookie:t,timeoutMs:8e3});return n.statusCode>=200&&n.statusCode<300&&n.body?n.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${n.statusCode} from ${r}`),null)}var Kt=v(require("crypto"));var ai="116680003";function oe(e,t,r,n,o="PREFERRED",i=!1){let s=e==="FSN"?he(n,i):Je(n,o,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function Mt(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:i,taskKey:s,branchPath:a}=o,c=H(a),l=t.moduleId||await U(e,i,n),d=await W(e,i,n),u=t.preferredTerm||t.fsn,p=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,g={conceptId:null,moduleId:l,definitionStatus:"PRIMITIVE",active:!0,descriptions:[oe("FSN",p,l,d,"PREFERRED",!0),oe("SYNONYM",u,l,d,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:Kt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:l,relationships:[{active:!0,groupId:0,type:{conceptId:ai},target:{conceptId:t.parentConceptId}}]}]},h=`${A(e)}/browser/${c}/${i}/${s}/concepts/?validate=true`,y=await I(h,{method:"POST",body:g,cookie:e.cookie});if(y.sessionExpired){let R="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: SESSION EXPIRED`),{statusCode:401,body:{error:R}}}let k=y.body,b=k&&"conceptId"in k?k.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: ${y.statusCode<300?"OK":"FAILED ("+y.statusCode+")"} \u2014 ${p}`+(b?` \u2192 ${b}`:"")),typeof b=="string"&&e.onValidationResults?.(b,k?.validationResults),{statusCode:y.statusCode,body:y.body}}var ci=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],di={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function li(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(n=>n.active!==!1).length}function Bt(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(n=>n.characteristicType===t)}function ne(e){return{conceptId:e.conceptId,fsn:e.fsn,pt:e.pt,active:e.active,definitionStatus:e.definitionStatus}}function re(e){return typeof e=="object"&&e!==null}function ui(e,t,r){let n=Array.isArray(e[r])?e[r]:[],o=[];for(let i of n){if(i.active===!1||typeof i.axiomId!="string")continue;(Array.isArray(i.relationships)?i.relationships:[]).forEach((a,c)=>{let l=a.type;if((re(l)?l.conceptId:void 0)!==t)return;let u=a.target;o.push({axiomId:i.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:re(u)?u.conceptId:void 0,targetFsn:re(u)&&re(u.fsn)?u.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return o}async function ke(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};if(!t.attributeType){let a=ci.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>di[c]).join(", ")}.`}}}if(!t.attributeType&&!t.descriptions&&!t.descriptionFull&&!t.axioms&&!t.inferred&&!t.gci&&!t.gciAxiomsCount&&!t.full){let a=`${A(e)}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(a,{cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:c.statusCode,body:c.body}}let o=`${A(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await I(o,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!re(i.body))return{statusCode:i.statusCode,body:i.body};let s=i.body;if(t.attributeType){let a=t.gci?"gciAxioms":"classAxioms",c=ui(s,t.attributeType,a);return{statusCode:i.statusCode,body:{conceptId:t.conceptId,attributeType:t.attributeType,gci:!!t.gci,matches:c}}}if(t.descriptions){let a=Array.isArray(s.descriptions)?s.descriptions.filter(c=>c.active!==!1):[];return{statusCode:i.statusCode,body:{...ne(s),descriptions:a}}}return t.descriptionFull?{statusCode:i.statusCode,body:{...ne(s),descriptions:s.descriptions??[]}}:t.axioms?{statusCode:i.statusCode,body:{...ne(s),classAxioms:s.classAxioms??[],relationships:Bt(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...ne(s),relationships:Bt(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...ne(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:li(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var pi=500,mi=1e4;async function Ce(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={expand:"fsn()"};t.term&&(o.termFilter=t.term),t.ecl&&(o.eclFilter=t.ecl),typeof t.active=="boolean"&&(o.activeFilter=t.active);let i=`${A(e)}/${n.branchPath}/concepts/search`,s=d=>({conceptId:d.conceptId,fsn:d.fsn?.term,pt:d.pt?.term,active:d.active,moduleId:d.moduleId});if(t.limit!==void 0){let d=await I(i,{method:"POST",body:{...o,limit:t.limit},cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let u=(d.body?.items??[]).map(s);return{statusCode:d.statusCode,body:{total:d.body?.total??u.length,items:u}}}let a=[],c=0,l=0;for(;;){let d=Math.min(pi,mi-l);if(d<=0)break;let u=await I(i,{method:"POST",body:{...o,limit:d,offset:l},cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(u.statusCode<200||u.statusCode>=300)return{statusCode:u.statusCode,body:u.body??{error:"Concept search failed."}};let p=u.body?.items??[];if(a.push(...p.map(s)),c=u.body?.total??a.length,l+=p.length,p.length===0||l>=c)break}return{statusCode:200,body:{total:c,items:a,...a.length<c?{truncated:!0,message:`Only ${a.length} of ${c} matches returned \u2014 Snowstorm caps unsorted search at offset+limit 10,000. Narrow the query (--term/--ecl/--active) to see the rest.`}:{}}}}var ie=1e3;function fi(e){let t=new Map;for(let r of e)for(let n of r){let o=n.referenceType?.conceptId??"",i=t.get(o);i?i.referencingConcepts=[...i.referencingConcepts??[],...n.referencingConcepts??[]]:t.set(o,{...n,referencingConcepts:[...n.referencingConcepts??[]]})}return[...t.values()]}async function _t(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${A(e)}/${n.branchPath}/concepts/${t.conceptId}/references`,i=(d,u)=>{let p=new URLSearchParams;return typeof t.stated=="boolean"&&p.set("stated",String(t.stated)),p.set("limit",String(d)),p.set("offset",String(u)),I(`${o}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let d=await i(t.limit??ie,t.offset??0);return d.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:d.statusCode,body:d.body}}let s=[],a=0,c=0,l=0;for(;;){let d=await i(ie,l);if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:d.body??{error:"Could not fetch references."}};let u=d.body?.referencesByType??[];s.push(u),a=d.body?.total??a;let p=u.reduce((g,h)=>g+(h.referencingConcepts?.length??0),0);if(c+=p,p===0||p<ie||c>=a)break;l+=ie}return{statusCode:200,body:{total:a,limit:ie,offset:0,referencesByType:fi(s)}}}var We=v(require("crypto"));function Ut(e){return typeof e=="object"&&e!==null}function gi(e){let t=e.type,r=e.target,n=Ut(t)?t.conceptId:void 0,o=Ut(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function yi(e,t){let r=[...t];for(let n of e){let o=r.findIndex(i=>i.typeId===n.typeId&&i.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function Vt(e,t,r){let n=new Map;for(let s of e){let a=typeof s.groupId=="number"?s.groupId:0,c=n.get(a);c?c.push(s):n.set(a,[s])}let o=[];for(let[s,a]of n){if(r!=null?s!==r:s===0)continue;let c=a.map(gi).filter(l=>l!=null);yi(t,c)&&o.push(s)}if(o.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(o.length>1)return{ok:!1,statusCode:409,error:`has ${o.length} role groups matching the given attributes (groupIds: ${o.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let i=o[0];return{ok:!0,groupId:i,relationships:n.get(i)}}var hi=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],ki=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],Ci=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],Ii=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],xi=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],Xe=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function Zt(e){return Xe.includes(e)}function se(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function Ie(e){return typeof e=="object"&&e!==null}function qt(e){return Ie(e)?se(e,Ii):e}function eo(e){if(!Ie(e))return e;let t=se(e,Ci);return"type"in t&&(t.type=qt(t.type)),"target"in t&&(t.target=qt(t.target)),t}function bi(e){return Ie(e)?se(e,ki):e}function Jt(e){if(!Ie(e))return e;let t=se(e,xi);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(eo)),t}function Qe(e){let t=se(e,hi);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(bi)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(eo)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(Jt)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(Jt)),t}function Si(e){return new Promise(t=>setTimeout(t,e))}function vi(e){if(e.statusCode!==400)return!1;let t=e.body;return t?.error==="BAD_REQUEST"&&typeof t.message=="string"&&t.message.includes("is already locked")}var He=[300,600,1200,2400,4800],Gt=new Map;function Ti(e,t){let n=(Gt.get(e)??Promise.resolve()).then(t,t);return Gt.set(e,n.then(()=>{},()=>{})),n}async function w(e,t,r,n){try{return await Ti(t.branchPath,()=>Ai(e,t,r,n))}catch(o){return{statusCode:500,body:{error:o instanceof Error?o.message:String(o)}}}}async function Ai(e,t,r,n){for(let o=0;;o++){let i=A(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await I(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:a.body}};let c=a.body,l=n(c);if(l)return l;let d=H(t.branchPath),u=`${i}/browser/${d}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await I(u,{method:"PUT",body:Qe(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(vi(p)&&o<He.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${o+1}/${He.length})`),await Si(He[o]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${p.statusCode<300?"OK":"FAILED ("+p.statusCode+")"} \u2014 ${r}`);let g=p.body;return e.onValidationResults?.(r,g?.validationResults),{statusCode:p.statusCode,body:p.body}}}var Ht=["PREFERRED","ACCEPTABLE"];async function to(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.type)return{statusCode:400,body:{error:"conceptId, term, and type are required."}};if(t.type!=="FSN"&&t.type!=="SYNONYM")return{statusCode:400,body:{error:"type must be FSN or SYNONYM."}};if(t.acceptability&&!Ht.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${Ht.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await U(e,o.projectKey,n),s=await W(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return w(e,o,t.conceptId,c=>{let l=Array.isArray(c.descriptions)?c.descriptions:[];return l.push(oe(t.type,a,i,s,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=l,null})}async function oo(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return w(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];if(!a)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.length}).`}};let c=Array.isArray(a.relationships)?a.relationships:[];return c.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),a.relationships=c,null})}async function no(e,t,r){if(!t.conceptId||!t.status)return{statusCode:400,body:{error:"conceptId and status are required."}};if(t.status!=="PRIMITIVE"&&t.status!=="FULLY_DEFINED")return{statusCode:400,body:{error:"status must be PRIMITIVE or FULLY_DEFINED."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return w(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];return a?(a.definitionStatus=t.status,i.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.length}).`}}})}async function ro(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>o.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(o.active=!1,o.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(o.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null)):{statusCode:400,body:{error:n.error}}}async function io(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};if(!t.term&&!t.caseSignificance)return{statusCode:400,body:{error:"At least one of term or caseSignificance must be provided."}};if(t.caseSignificance&&!Zt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Xe.join(", ")}.`}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(s.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(s.term=t.term),t.caseSignificance&&(s.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function so(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!Zt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${Xe.join(", ")}.`}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?(s.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var Ye=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function Yt(e){return Ye.includes(e)}function ao(e){return e.us&&!Yt(e.us)?{statusCode:400,body:{error:`us must be one of: ${Ye.join(", ")}.`}}:e.gb&&!Yt(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${Ye.join(", ")}.`}}:null}function co(e){return e.descriptionId?!e.lang&&!e.us&&!e.gb?{statusCode:400,body:{error:`Entry for description ${e.descriptionId} must set at least one of lang, us, or gb.`}}:ao(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function ze(e,t,r){let n=e.find(i=>i.descriptionId===r.descriptionId);if(!n)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(n.lang=r.lang);let o={...n.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete o[M]:o[M]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[G]:o[G]=r.gb),n.active!==!1&&Object.keys(o).length===0?{statusCode:400,body:{error:`Description ${r.descriptionId} would have an empty acceptabilityMap (Not Acceptable in every dialect) \u2014 an active description must be acceptable in at least one.`}}:(n.acceptabilityMap=o,null)}async function lo(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},o=co(n);if(o)return o;let i=await C(e,t,r);return i.ok?w(e,i,t.conceptId,s=>{let a=Array.isArray(s.descriptions)?s.descriptions:[];return ze(a,t.conceptId,n)}):{statusCode:400,body:{error:i.error}}}async function uo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};if(!Array.isArray(t.entries)||t.entries.length===0)return{statusCode:400,body:{error:"entries must be a non-empty array."}};for(let o of t.entries){let i=co(o);if(i)return i}let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[];for(let s of t.entries){let a=ze(i,t.conceptId,s);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function po(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[],s=i.findIndex(a=>a.descriptionId===t.descriptionId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(i.splice(s,1),o.descriptions=i,null)}):{statusCode:400,body:{error:n.error}}}var xe="REFERS_TO";async function mo(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(s.active=!1,s.inactivationIndicator=t.indicator,s.acceptabilityMap={},t.associationTargetId&&(s.associationTargets={[xe]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}function Wt(e,t,r){for(let n of e){if(n.descriptionId===t||n.active===!1||n.type!=="SYNONYM")continue;let o=n.acceptabilityMap;o?.[r]==="PREFERRED"&&(n.acceptabilityMap={...o,[r]:"ACCEPTABLE"})}}async function fo(e,t,r,n=new Map){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},i=ao(o);if(i)return i;let s=!!(t.lang||t.us||t.gb),a=await C(e,t,r);if(!a.ok)return{statusCode:400,body:{error:a.error}};let c=await W(e,a.projectKey,n);return w(e,a,t.conceptId,l=>{let d=Array.isArray(l.descriptions)?l.descriptions:[],u=d.find(g=>g.descriptionId===t.descriptionId);if(!u)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(u.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(u.type==="FSN"){if(s)return{statusCode:400,body:{error:"lang/us/gb do not apply when restoring an FSN \u2014 it is always PREFERRED in every dialect the project uses."}};let g=d.filter(h=>h.type==="FSN"&&h.active!==!1&&h.descriptionId!==t.descriptionId);if(g.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${g.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(g.length===1){let h=g[0];if(h.effectiveTime==null)d.splice(d.indexOf(h),1);else{if(!t.indicator)return{statusCode:400,body:{error:`Restoring this FSN requires --indicator, to retire the concept's current active (published) FSN ${String(h.descriptionId)} in the same save.`}};h.active=!1,h.inactivationIndicator=t.indicator,h.acceptabilityMap={},t.associationTargetId&&(h.associationTargets={[xe]:[t.associationTargetId]})}}return u.active=!0,delete u.inactivationIndicator,delete u.associationTargets,u.acceptabilityMap=he(c,!1),l.descriptions=d,null}if(!s)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};u.active=!0,delete u.inactivationIndicator,delete u.associationTargets;let p=ze(d,t.conceptId,o);return p||(o.us==="PREFERRED"&&Wt(d,t.descriptionId,M),o.gb==="PREFERRED"&&Wt(d,t.descriptionId,G),null)})}var wi="900000000000490003",Xt=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function go(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!Xt.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${Xt.join(", ")}.`}};if(t.reason==="NOT_SEMANTICALLY_EQUIVALENT"){if(!t.targetId)return{statusCode:400,body:{error:"reason NOT_SEMANTICALLY_EQUIVALENT requires --target-id \u2014 the concept this description actually belongs under."}}}else if(t.targetId)return{statusCode:400,body:{error:`--target-id only applies to reason NOT_SEMANTICALLY_EQUIVALENT (paired with a REFERS_TO association) \u2014 omit it for ${t.reason}.`}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=`${A(e)}/${n.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${wi}&active=true`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||500,body:{error:`Could not check description ${t.descriptionId}'s current inactivation reason.`,details:s.body}};let a=(s.body.items??[])[0];return a?.released===!0?{statusCode:409,body:{error:`Description ${t.descriptionId}'s inactivation reason has already been published (effectiveTime ${String(a.effectiveTime)}) and cannot be changed.`}}:w(e,n,t.conceptId,c=>{let d=(Array.isArray(c.descriptions)?c.descriptions:[]).find(u=>u.descriptionId===t.descriptionId);return d?d.active!==!1?{statusCode:409,body:{error:`Description ${t.descriptionId} is active \u2014 use inactivate-description to inactivate it with a reason.`}}:(d.inactivationIndicator=t.reason,t.reason==="NOT_SEMANTICALLY_EQUIVALENT"?d.associationTargets={[xe]:[t.targetId]}:delete d.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function yo(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await U(e,o.projectKey,n),s=await W(e,o.projectKey,n),a=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return w(e,o,t.conceptId,c=>{let l=Array.isArray(c.descriptions)?c.descriptions:[],d;if(t.descriptionId){if(d=l.find(u=>u.descriptionId===t.descriptionId),!d)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(d.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(d.type)}, not an FSN.`}}}else{let u=l.filter(p=>p.type==="FSN"&&p.active!==!1);if(u.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${u.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};d=u[0]}return d.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(d.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(d.active=!1,d.inactivationIndicator=t.indicator,d.acceptabilityMap={},t.associationTargetId&&(d.associationTargets={[xe]:[t.associationTargetId]}),l.push(oe("FSN",a,i,s,"PREFERRED",!1)),c.descriptions=l,null)})}async function Ze(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?(s.relationships=t.relationships,t.active!=null&&(s.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function ho(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?(s.relationships=t.relationships,t.active!=null&&(s.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function ko(e,t,r,n=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await U(e,o.projectKey,n);return w(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[];return a.push({axiomId:We.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.classAxioms=a,null})}async function Co(e,t,r,n=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await U(e,o.projectKey,n);return w(e,o,t.conceptId,s=>{let a=Array.isArray(s.gciAxioms)?s.gciAxioms:[];return a.push({axiomId:We.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.gciAxioms=a,null})}async function Io(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:i.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(i.splice(s,1),o.classAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function xo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.find(c=>c.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};if(s.active===!1)return{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}};if(s.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}};let a=i.filter(c=>c!==s&&c.active!==!1);return a.length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:a.every(c=>c.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished class axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-axiom to edit ${t.axiomId}'s content in place instead.`}}:(s.active=!1,null)}):{statusCode:400,body:{error:n.error}}}var Ri="116680003";function Qt(e,t){let r={active:!0,groupId:t,type:{conceptId:e.type?.id}};return e.concrete?r.concreteValue={dataType:e.value?.dataType,value:e.value?.value}:r.target={conceptId:e.target?.id},r}function Ei(e){let t=[],r=Array.isArray(e.concepts)?e.concepts:[];for(let i of r)i?.id&&t.push({active:!0,groupId:0,type:{conceptId:Ri},target:{conceptId:i.id}});let n=Array.isArray(e.attributes)?e.attributes:[];for(let i of n)t.push(Qt(i,0));return(Array.isArray(e.groups)?e.groups:[]).forEach((i,s)=>{let a=Array.isArray(i.attributes)?i.attributes:[];for(let c of a)t.push(Qt(c,s+1))}),t}async function bo(e,t,r,n){let o=A(e),i=await I(`${o}/browser/${t.branchPath}/concepts/${r}`,{cookie:e.cookie});if(i.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{ok:!1,result:{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body,undetermined:!0}}};let s=Array.isArray(i.body.classAxioms)?i.body.classAxioms:[],a;if(n){if(a=s.find(c=>c.axiomId===n),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${n}.`,undetermined:!0}}}}else{let c=s.filter(l=>l.active!==!1);if(c.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`,undetermined:!0}}};if(c.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${c.length} active class axioms \u2014 pass axiomId to pick which one.`,undetermined:!0}}};a=c[0]}return{ok:!0,value:{axiom:a,axiomId:a.axiomId}}}var $i="116680003";function ji(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==$i?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function Pi(e,t,r){let n=A(e),o=await I(`${n}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(o.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(o.statusCode<200||o.statusCode>=300||!o.body)return{ok:!1,result:{statusCode:o.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:o.body,undetermined:!0}}};let i=Ei(o.body);return i.length===0?{ok:!1,result:{statusCode:409,body:{error:`Authoring form for ${r} produced no relationships \u2014 the concept likely hasn't been classified since its last stated edit. Run classify --wait first.`,undetermined:!0}}}:{ok:!0,value:i}}async function Ni(e,t,r,n){let o=await bo(e,t,r,n);if(!o.ok)return o;let i=await Pi(e,t,r);return i.ok?{ok:!0,value:{axiom:o.value.axiom,axiomId:o.value.axiomId,targetRelationships:i.value}}:i}function Di(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let n=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${n}`}function zt(e){let t=new Map;for(let o of e){if(o.active===!1)continue;let i=typeof o.groupId=="number"?o.groupId:0,s=t.get(i)??[];s.push(Di(o)),t.set(i,s)}let r=(t.get(0)??[]).slice().sort(),n=[];for(let[o,i]of t)o!==0&&n.push(i.slice().sort());return{ungrouped:r,groups:n}}function Oi(e,t){let r=zt(e),n=zt(t);if(r.ungrouped.join("|")!==n.ungrouped.join("|"))return!1;let o=r.groups.map(s=>s.join("|")).sort(),i=n.groups.map(s=>s.join("|")).sort();return o.join("||")===i.join("||")}async function be(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Ni(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:i,axiomId:s,targetRelationships:a}=o.value,c=Array.isArray(i.relationships)?i.relationships:[];return Oi(c,a)?(e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${n.projectKey}/${n.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,alreadyConformed:!0}}):Ze(e,{conceptId:t.conceptId,axiomId:s,relationships:a,projectKey:n.projectKey,taskKey:n.taskKey},r)}async function Se(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await bo(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:i,axiomId:s}=o.value,a=Array.isArray(i.relationships)?i.relationships:[];return ji(a)?{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!0,conforms:!1}}:{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!1,message:"Stated Is-a targets are all primitive \u2014 this cannot rule out a missing/mismatched attribute. Run transform-axiom to get a definitive, self-fixing answer."}}}async function So(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};if(!t.relationshipId&&t.relationshipIndex==null)return{statusCode:400,body:{error:"One of relationshipId or relationshipIndex is required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(d=>d.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=t.relationshipId?a.findIndex(d=>d.relationshipId===t.relationshipId):t.relationshipIndex,l=c>=0?a[c]:void 0;return l?l.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${c}`} has effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),s.relationships=a,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}}):{statusCode:400,body:{error:n.error}}}async function vo(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.attributes)||t.attributes.length===0)return{statusCode:400,body:{error:"conceptId, axiomId, and a non-empty attributes array are required."}};for(let o of t.attributes)if(!o||typeof o.typeId!="string"||typeof o.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(d=>d.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=Vt(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let l=c.relationships.find(d=>d.effectiveTime!=null);return l?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(l.relationshipId)}) with effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(s.relationships=a.filter(d=>(typeof d.groupId=="number"?d.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function To(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.gciAxioms)?o.gciAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(i.splice(s,1),o.gciAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function Ao(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.gciAxioms)?o.gciAxioms:[],s=i.find(c=>c.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}};if(s.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished GCI axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-gci-axiom).`}};if(s.active===!1)return{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}};let a=i.filter(c=>c!==s&&c.active!==!1);return a.length>0&&a.every(c=>c.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating GCI axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished GCI axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-gci-axiom to edit ${t.axiomId}'s content in place instead.`}}:(s.active=!1,null)}):{statusCode:400,body:{error:n.error}}}var Fi=8;async function ve(e,t,r,n){let o=[],i=[],s=0,a=async()=>{for(;;){let l=s++;if(l>=r.length)return;let d=r[l];try{let u=await Se(e,{conceptId:d.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),p=u.body;if(u.statusCode<200||u.statusCode>=300){i.push({...d,error:p?.error??`HTTP ${u.statusCode}`});continue}p?.conclusive&&o.push({...d,axiomId:p.axiomId})}catch(u){i.push({...d,error:u instanceof Error?u.message:String(u)})}}},c=Math.min(Fi,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:o,skipped:i}}async function wo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Ce(e,{...t,branchPath:n.branchPath},r);if(o.statusCode<200||o.statusCode>=300)return o;let i=o.body?.items??[],s=i.map(l=>({conceptId:l.conceptId,fsn:l.fsn,pt:l.pt})),{matched:a,skipped:c}=await ve(e,n,s,r);return{statusCode:200,body:{branchPath:n.branchPath,totalSearched:i.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function Ro(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};if(s.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(a,{method:"DELETE",cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] delete-concept ${n.projectKey}/${n.taskKey}: ${c.statusCode<300?"OK":"FAILED ("+c.statusCode+")"} \u2014 ${t.conceptId}`),c.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${t.conceptId} \u2014 one or more of its components is published.`,details:c.body}}:{statusCode:c.statusCode,body:c.body})}function Li(e){let t=[];for(let r of e)t.some(o=>o.componentId===r.componentId&&o.severity===r.severity&&o.conceptId===r.conceptId&&o.message===r.message)||t.push(r);return t}async function Te(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};let a=H(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,l=await I(c,{method:"POST",body:Qe(s.body),cookie:e.cookie});if(l.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(l.statusCode<200||l.statusCode>=300)return{statusCode:l.statusCode,body:{error:"Validation check failed.",details:l.body}};let d=Array.isArray(l.body)?Li(l.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:d,hasErrors:d.some(u=>u.severity==="ERROR"),hasWarnings:d.some(u=>u.severity==="WARNING")}}}var Eo=200;async function Ki(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${A(e)}/browser/${t}/concepts/bulk-load`,i=!0;for(let s=0;s<r.length;s+=Eo){let a=r.slice(s,s+Eo),c=await I(o,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){i=!1;continue}for(let l of c.body)n.set(l.conceptId,{fsn:l.fsn?.term,pt:l.pt?.term})}return{terms:n,resolved:i}}async function B(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=[],i=0;for(;;){let y=`${Ft(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(n.branchPath)}`,k=await I(y,{cookie:e.cookie});if(k.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(k.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(k.statusCode<200||k.statusCode>=300)return{statusCode:k.statusCode,body:{error:"Could not fetch traceability for branch.",details:k.body}};o.push(...k.body?.content??[]);let b=k.body?.totalPages??1;if(k.body?.last!==!1||i+1>=b)break;i+=1}let s=new Map,a=new Map,c=(y,k,b,R)=>{let j=y.get(k);j?(R.forEach(P=>P&&j.componentSubTypes.add(P)),j.lastUpdatedTime=b):y.set(k,{conceptId:k,lastUpdatedTime:b,componentSubTypes:new Set(R.filter(P=>!!P))})};for(let y of o)if(!(y.activityType!=="CONTENT_CHANGE"&&y.activityType!=="CLASSIFICATION_SAVE"))for(let k of y.conceptChanges??[]){let b=String(k.conceptId),R=k.componentChanges??[],j=R.map(K=>K.componentSubType);if(y.activityType==="CLASSIFICATION_SAVE"){c(a,b,y.commitDate,j);continue}let P=R.some(K=>K.componentSubType!=="INFERRED_RELATIONSHIP");c(P?s:a,b,y.commitDate,j)}for(let y of s.keys())a.delete(y);let l=[...new Set([...s.keys(),...a.keys()])],{terms:d,resolved:u}=await Ki(e,n.branchPath,l),p=y=>[...y.values()].sort((k,b)=>(b.lastUpdatedTime??"").localeCompare(k.lastUpdatedTime??"")).map(k=>{let b=u&&!d.has(k.conceptId);return{conceptId:k.conceptId,fsn:d.get(k.conceptId)?.fsn,pt:d.get(k.conceptId)?.pt,...b?{deleted:!0}:{},lastUpdatedTime:k.lastUpdatedTime,changedComponentTypes:[...k.componentSubTypes]}}),g=p(s),h=p(a);return{statusCode:200,body:{branchPath:n.branchPath,...u?{summary:{concepts:g.length,conceptsDeleted:g.filter(y=>y.deleted).length,conceptsClassified:h.length}}:{},concepts:g,conceptsClassified:h}}}async function $o(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await B(e,t,r);if(o.statusCode<200||o.statusCode>=300){let d=o.body;return{statusCode:o.statusCode,body:{error:d.error??"Could not list concepts for review."}}}let i=o.body.concepts??[],s=i.filter(d=>!d.deleted),a=s.map(d=>({conceptId:d.conceptId,fsn:d.fsn})),{matched:c,skipped:l}=await ve(e,n,a,r);return{statusCode:200,body:{branchPath:n.branchPath,totalReviewed:s.length,matched:c.length,skipped:l.length,skippedDeleted:i.length-s.length,results:c,skippedConcepts:l}}}async function Mi(e,t,r,n){let o=[];for(let i of r){if(i.deleted){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"deleted"});continue}let s=await Te(e,{conceptId:i.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),a=s.body;if(s.statusCode<200||s.statusCode>=300){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"failed",error:a.error??`HTTP ${s.statusCode}`});continue}let c=a.validationResults??[];o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return o}async function jo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await B(e,t,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=o.body.concepts??[],s=await Mi(e,n,i,r),a=c=>s.filter(l=>l.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:s.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:s}}}async function _(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body??null}var et=new Set;function Po(e){if(!(!e||typeof e!="object"))for(let t of et)t(e)}function Bi(e){return et.add(e),()=>et.delete(e)}function _i(e,t){return t.entityType!==void 0&&e.entityType!==t.entityType?!1:e.task?e.task===t.taskKey&&e.project===t.projectKey:e.project?e.project===t.projectKey:e.branchPath===t.branchPath}function Ae(e){let t=()=>{};return{promise:new Promise(n=>{t=Bi(o=>{_i(o,e)&&(t(),n(o))})}),cancel:t}}var rt=["RUNNING","BUILDING","SCHEDULED","QUEUED"],it=["QUEUED","SCHEDULED","RUNNING"],Ui=["Promoted","Completed"],No=5e3;function nt(e){return new Promise(t=>setTimeout(t,e))}async function Vi(e,t,r){let n=0;for(;;){let{done:o,value:i}=await e();if(o)return{value:i,timedOut:!1};if(n>=r)return{value:i,timedOut:!0};n++,await nt(t)}}function qi(){let e=[9e4];for(let t=0;t<3;t++)e.push(1e4);for(let t=0;t<12;t++)e.push(5e3);return e}var Ji=qi(),Gi=180;function Hi(){let e=[3e5];for(let t=0;t<5;t++)e.push(6e4);for(let t=0;t<10;t++)e.push(3e4);return e}var Yi=Hi(),Wi=900;async function Fo(e,t,r,n,o){let i=r*1e3,s=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],l=n?Ae(n):void 0,d=await Promise.race(l?[nt(c).then(()=>{}),l.promise]:[nt(c).then(()=>{})]);if(l?.cancel(),d){let g=d.event;o?.(`[${new Date().toISOString()}] woken by notification${g?`: ${g}`:""}`)}let{done:u,value:p}=await e();if(u)return{value:p,timedOut:!1};if(Date.now()-s>=i)return{value:p,timedOut:!0};a++}}async function Lo(e,t,r){let n=await _(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&Ui.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${E(e)}/projects/${t}/tasks/${r}`;await I(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function st(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await I(n,{method:"POST",body:{},cookie:e.cookie}),(await _(e,t,r))?.latestClassificationJson}async function Do(e,t,r,n,o){let i,{value:s,timedOut:a}=await Fo(async()=>{let l=(await st(e,t,r))?.status;return l!==i&&(i=l,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${l??"unknown"}`)),{done:!(!l||rt.includes(l)),value:l}},Ji,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function tt(e,t,r){let n=`${A(e)}/${t}/classifications`,o=await I(n,{cookie:e.cookie});if(o.body?.items?.length)return o.body.items.find(i=>i.id===r)??o.body.items[o.body.items.length-1]}async function Ko(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,s=await st(e,o,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:rt.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function we(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await Lo(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Gi,l=await st(e,o,i),d=l?.status,u=l?.id;if(u&&d&&rt.includes(d)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${u} already ${d} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:P}=await Do(e,o,i,s,c),K=await tt(e,s,u),q={accepted:!1};return!P&&j==="COMPLETED"&&(q=await ot(e,s,o,i,u)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: attached job ${u} final status ${j??"unknown"}${P?" (timed out waiting)":""}, save ${JSON.stringify(q)}`),{statusCode:200,body:{jobId:u,finalStatus:j,timedOut:P,details:K,save:q,attachedToExisting:!0}}}if(u&&d==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${u} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await tt(e,s,u),P=await ot(e,s,o,i,u);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: accepted existing job ${u}, save ${JSON.stringify(P)}`),{statusCode:200,body:{jobId:u,finalStatus:"COMPLETED",timedOut:!1,details:j,save:P,acceptedExisting:!0}}}let p=`${E(e)}/projects/${o}/tasks/${i}/classifications`,g=await I(p,{method:"POST",body:{},cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!g.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: start failed (HTTP ${g.statusCode}) \u2014 raw body: ${g.rawBody}`),{statusCode:g.statusCode||500,body:{error:"Failed to start classification.",details:g.body??g.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: started (${g.body.status??"unknown"})`);let h=g.body.id;if(!t.wait)return{statusCode:200,body:{jobId:h,status:g.body.status}};let{finalStatus:y,timedOut:k}=await Do(e,o,i,s,c),b=await tt(e,s,h),R={accepted:!1};return!k&&y==="COMPLETED"&&(R=await ot(e,s,o,i,h)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: final status ${y??"unknown"}${k?" (timed out waiting)":""}, save ${JSON.stringify(R)}`),{statusCode:200,body:{jobId:h,finalStatus:y,timedOut:k,details:b,save:R}}}var Xi=["SAVED","STALE","SAVE_FAILED"],Qi=120;async function ot(e,t,r,n,o){let i=`${A(e)}/${t}/classifications/${o}`,s=await I(i,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(s.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(s.statusCode<200||s.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${s.statusCode}).`};let a=Math.ceil(Qi*1e3/No),{value:c,timedOut:l}=await Vi(async()=>{let u=(await I(i,{cookie:e.cookie})).body?.status;return{done:!!u&&Xi.includes(u),value:u}},No,a);return l?{accepted:!1,status:c,error:"Timed out waiting for classification results to save."}:c==="SAVED"?{accepted:!0,status:c}:{accepted:!1,status:c,error:c==="STALE"?"Report stale \u2014 re-classify and save.":"Saving classification failed."}}async function Mo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,a=(await _(e,o,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&it.includes(a)}}}async function Oo(e,t,r,n,o){let i,{value:s,timedOut:a}=await Fo(async()=>{let l=(await _(e,t,r))?.latestValidationStatus;return l!==i&&(i=l,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${l??"unknown"}`)),{done:!(!l||it.includes(l)),value:l}},Yi,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function Bo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await Lo(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Wi,d=(await _(e,o,i))?.latestValidationStatus;if(d&&it.includes(d)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: validation already ${d} \u2014 waiting on it instead of starting a new one`);let{finalStatus:y,timedOut:k}=await Oo(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: attached run final status ${y??"unknown"}${k?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:y,timedOut:k,attachedToExisting:!0}}}let u=`${E(e)}/projects/${o}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await I(u,{method:"POST",body:{},cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(p.statusCode<200||p.statusCode>=300)return{statusCode:p.statusCode,body:{error:"Failed to start validation.",details:p.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:g,timedOut:h}=await Oo(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: final status ${g??"unknown"}${h?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:g,timedOut:h}}}var zi=8;function Zi(e){return typeof e=="string"&&/timed out after \d+ms/.test(e)}async function _o(e,t,r,n,o,i){let s=0,a=0,c=async()=>{for(;;){let d=a++;if(d>=r.length)return;let u=r[d];try{let p=await be(e,{conceptId:u.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),g=p.body;p.statusCode<200||p.statusCode>=300?g?.undetermined?n.set(u.conceptId,{outcome:"skipped",error:g.error??`HTTP ${p.statusCode}`}):n.set(u.conceptId,{outcome:"failed",error:g?.error??`HTTP ${p.statusCode}`}):n.set(u.conceptId,{outcome:g?.alreadyConformed?"conformed":"transformed"})}catch(p){n.set(u.conceptId,{outcome:"failed",error:p instanceof Error?p.message:String(p)})}s+=1,e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: ${i} \u2014 ${u.conceptId} (${s}/${r.length})`)}},l=Math.min(zi,r.length);await Promise.all(Array.from({length:l},()=>c()))}async function es(e,t,r,n){let o=new Map;return await _o(e,t,r,o,n,"axiom checked"),await ts(e,t,r,o,n),o}async function ts(e,t,r,n,o){let i=r.filter(s=>{let a=n.get(s.conceptId);return a?.outcome==="failed"&&Zi(a.error)});i.length!==0&&(e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: reprocessing ${i.length} concept(s) that timed out on the first pass`),await _o(e,t,i,n,o,"axiom rechecked"))}async function Uo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await we(e,{projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath,wait:!0},r);if(o.statusCode===401)return o;let i=o.body,s=o.statusCode>=200&&o.statusCode<300?{jobId:i?.jobId,finalStatus:i?.finalStatus,timedOut:i?.timedOut,save:i?.save}:{error:i?.error??`HTTP ${o.statusCode}`},a=await B(e,t,r);if(a.statusCode<200||a.statusCode>=300){let h=a.body;return{statusCode:a.statusCode,body:{error:h.error??"Could not list concepts for review."}}}let c=a.body.concepts??[],l=c.filter(h=>!h.deleted).map(h=>({conceptId:h.conceptId,fsn:h.fsn})),d=await es(e,n,l,r),u=[];for(let[h,y]of c.entries()){if(y.deleted){u.push({conceptId:y.conceptId,fsn:y.fsn,outcome:"deleted"});continue}let k=d.get(y.conceptId),b=await ke(e,{conceptId:y.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),R=b.body,j=`(${h+1}/${c.length})`;if(b.statusCode<200||b.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: FAILED (${b.statusCode}) \u2014 ${y.conceptId} ${j}`),u.push({conceptId:y.conceptId,fsn:y.fsn,outcome:"failed",error:R?.error??`HTTP ${b.statusCode}`,axiom:k});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: OK \u2014 ${y.conceptId} ${j}`),u.push({conceptId:y.conceptId,fsn:y.fsn,outcome:"fetched",concept:b.body,axiom:k})}let p=h=>u.filter(y=>y.outcome===h).length,g=h=>Array.from(d.values()).filter(y=>y.outcome===h).length;return{statusCode:200,body:{branchPath:n.branchPath,classification:s,summary:{total:u.length,fetched:p("fetched"),skippedDeleted:p("deleted"),failed:p("failed"),axiomsTransformed:g("transformed"),axiomsConformed:g("conformed"),axiomsSkipped:g("skipped"),axiomsFailed:g("failed")},concepts:u}}}async function Vo(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${E(e)}/projects${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function qo(e,t){let r=`${E(e)}/projects/${t}/tasks`;return(await I(r,{cookie:e.cookie})).body??[]}async function Jo(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${E(e)}/projects/my-tasks${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function Go(e,t){let r=`${E(e)}/projects/${t.projectKey}/tasks`,n={summary:t.summary};t.description!==void 0&&(n.description=t.description),t.assigneeUsername&&(n.assignee={username:t.assigneeUsername});let o=await I(r,{method:"POST",body:n,cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}async function Ho(e,t){let r=`${E(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await I(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var os="IN_PROGRESS";async function Yo(e,t){let r=`${E(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await I(r,{cookie:e.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode}).`};if(n.body.status!=="Deleted")return{statusCode:200,task:n.body,notDeleted:!0};let o=await I(r,{method:"PUT",body:{status:os},cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to recover ${t.projectKey}/${t.taskKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}function Wo(e){if(e==="o")return{type:"open"};if(e==="h")return{type:"heartbeat"};if(e.startsWith("a"))try{return{type:"message",messages:JSON.parse(e.slice(1))}}catch{return{type:"unknown",raw:e}}if(e.startsWith("c"))try{let[t,r]=JSON.parse(e.slice(1));return{type:"close",code:t,reason:r}}catch{return{type:"unknown",raw:e}}return{type:"unknown",raw:e}}function at(e){return JSON.stringify([e])}function Xo(e=Math.random){let t=String(Math.floor(e()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",n="";for(let o=0;o<8;o++)n+=r[Math.floor(e()*r.length)];return`${t}/${n}/websocket`}function ct(e,t={},r=""){let n=Object.entries(t).map(([o,i])=>`${o}:${i}`);return[e,...n,"",r].join(`
3
- `)+"\0"}function Qo(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
2
+ "use strict";var Jr=Object.create;var me=Object.defineProperty;var Hr=Object.getOwnPropertyDescriptor;var Yr=Object.getOwnPropertyNames;var Wr=Object.getPrototypeOf,Xr=Object.prototype.hasOwnProperty;var Qr=(e,t)=>{for(var r in t)me(e,r,{get:t[r],enumerable:!0})},Rt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yr(t))!Xr.call(e,o)&&o!==r&&me(e,o,{get:()=>t[o],enumerable:!(n=Hr(t,o))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?Jr(Wr(e)):{},Rt(t||!e||!e.__esModule?me(r,"default",{value:e,enumerable:!0}):r,e)),zr=e=>Rt(me({},"__esModule",{value:!0}),e);var qs={};Qr(qs,{COMMANDS:()=>wt,main:()=>Gr,parsePositionals:()=>Vr});module.exports=zr(qs);var G={production:{imsEndpoint:"https://authoring.ihtsdotools.org/",terminologyServerEndpoint:"https://authoring.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://authoring.ihtsdotools.org/authoring-services/",cookieName:"ims-ihtsdo"},uat:{imsEndpoint:"https://uat-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://uat-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://uat-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"uat-ims-ihtsdo"},dev:{imsEndpoint:"https://dev-snowstorm.ihtsdotools.org/",terminologyServerEndpoint:"https://dev-snowstorm.ihtsdotools.org/snowstorm/snomed-ct/",authoringServicesEndpoint:"https://dev-snowstorm.ihtsdotools.org/authoring-services/",cookieName:"dev-ims-ihtsdo"}},Zr={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},fe=Object.keys(G);function Et(e){return Zr[e.trim().toLowerCase()]??null}var te="uat",Js=G.uat.imsEndpoint,Hs=G.uat.terminologyServerEndpoint,Ys=G.uat.authoringServicesEndpoint;var ei=v(require("http")),ti=v(require("https"));function I(e,t={}){let{method:r="GET",cookie:n,body:o,headers:i={},timeoutMs:s=15e3}=t;return new Promise((a,c)=>{let l;try{l=new URL(e)}catch(k){c(k);return}let d=l.protocol==="https:"?ti:ei,u=o!==void 0?JSON.stringify(o):void 0,p={accept:"application/json",...i};if(u!==void 0&&(p["content-type"]="application/json",p["content-length"]=String(Buffer.byteLength(u))),n){let k=n.replace(/[^\x20-\x7e\t]/g,"");k&&(p.cookie=k)}let g=!1,h=d.request({hostname:l.hostname,port:l.port||void 0,path:l.pathname+l.search,method:r,headers:p},k=>{let b="";k.on("data",R=>{b+=R}),k.on("end",()=>{if(g)return;g=!0,clearTimeout(y);let R=k.statusCode??0,P=(k.headers["content-type"]??"").includes("application/json"),K=null,q=!1;if(b)try{K=JSON.parse(b)}catch{q=!P}a({statusCode:R,body:K,rawBody:b,sessionExpired:q})})});h.on("error",k=>{g||(g=!0,clearTimeout(y),c(k))});let y=setTimeout(()=>{g||(g=!0,h.destroy(),c(new Error(`Request to ${e} timed out after ${s}ms`)))},s);u!==void 0&&h.write(u),h.end()})}var M="900000000000509007",J="900000000000508004";var $t={[M]:"en-us",[J]:"en-gb"},jt={[M]:"true",[J]:"true"},oi={},ni={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:$t,dialectDefaults:jt,readOnlyDialects:oi,defaultLanguage:"en"};function Pt(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return ni;let t={[M]:"en-us"},r={},n={},o=[];for(let c of Object.keys(e)){let l=c.match(/^requiredLanguageRefset\.(.+)/);if(l){let d=l[1];t[String(e[c])]=d,o.length===0&&o.push(d)}}let i=e.requiredLanguageRefsets;if(Array.isArray(i))for(let c of i){if(typeof c!="object"||c===null)continue;let l=null,d=null;for(let[h,y]of Object.entries(c))h.length===2&&(l=h,d=String(y));if(!l||!d)continue;let u=c.dialectName;t[d]=typeof u=="string"?u:l;let p=c.default;p==="true"&&!o.includes(l)&&o.push(l),p!=null&&(r[d]=String(p));let g=c.readOnly;g!=null&&(n[d]=String(g))}let s=e.optionalLanguageRefsets;if(Array.isArray(s))for(let c of s)c&&typeof c=="object"&&"refsetId"in c&&(t[String(c.refsetId)]=String(c.language??""));let a=!!e.useInternationalLanguageRefsets;return{isExtension:!0,useInternationalLanguageRefsets:a,dialects:a?$t:t,dialectDefaults:a?jt:r,readOnlyDialects:n,defaultLanguage:o[0]??"en"}}function qe(e,t,r,n){let o={};for(let i of Object.keys(e.dialects)){let s=e.dialects[i];e.isExtension&&!r?s.includes(n)?o[i]="PREFERRED":s.includes(e.defaultLanguage)&&(o[i]="ACCEPTABLE"):s.includes(n)&&(o[i]=t),e.dialectDefaults[i]==="false"&&!r&&delete o[i],e.readOnlyDialects[i]==="true"&&delete o[i]}return o}function ge(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[M]:"PREFERRED"}:qe(e,"PREFERRED",t,"en")}var ri="900000000000207008";function Nt(e){return e.replace(/\/$/,"")}function A(e){return Nt(e.terminologyServerEndpoint)}function E(e){return Nt(e.authoringServicesEndpoint)}function Dt(e){return`${new URL(E(e)).origin}/authoring-traceability-service`}function H(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function C(e,t,r){let n=t.projectKey||r?.projectKey,o=t.taskKey||r?.taskKey,i=!t.projectKey&&!t.taskKey,s=t.branchPath||(i?r?.branchPath:void 0);return!n||!o?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(s||(s=await ii(e,n,o)??void 0),s?{ok:!0,projectKey:n,taskKey:o,branchPath:s}:{ok:!1,error:`Could not resolve branch path for ${n}/${o}.`})}async function Y(e,t){let r=A(e),n=await I(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(n.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode>=200&&n.statusCode<300)return{ok:!0,created:!1};if(n.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${n.statusCode}).`};let o=t.split("/").filter(Boolean),i=o[o.length-1],s=o.slice(0,-1).join("/");if(!i||!s)return{ok:!1,error:`Cannot create branch from path "${t}" \u2014 expected a parent and a name.`};let a=await I(`${r}/branches`,{method:"POST",body:{parent:s,name:i},cookie:e.cookie});return a.sessionExpired?{ok:!1,error:"IMS session expired \u2014 re-sign in."}:a.statusCode<200||a.statusCode>=300?{ok:!1,error:`Could not create branch ${t} (HTTP ${a.statusCode}).`}:{ok:!0,created:!0}}async function ii(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body?.branchPath??null}async function Ot(e,t,r){let n=r?.get(t);if(n)return n;let o=`${E(e)}/projects/${t}`,s=(await I(o,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function U(e,t,r){let n=await Ot(e,t,r),o=n.multipleModuleEditingDisabled,i=!o||o==="false";return n.expectedExtensionModules?.length&&i?n.expectedExtensionModules[0]:n.defaultModuleId?n.defaultModuleId:ri}async function W(e,t,r){let n=await Ot(e,t,r);return Pt(n)}async function Ge(e,t){let r=e.replace(/\/$/,"")+"/auth",n=await I(r,{cookie:t,timeoutMs:8e3});return n.statusCode>=200&&n.statusCode<300&&n.body?n.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${n.statusCode} from ${r}`),null)}var Ft=v(require("crypto"));var si="116680003";function oe(e,t,r,n,o="PREFERRED",i=!1){let s=e==="FSN"?ge(n,i):qe(n,o,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function Lt(e,t,r,n=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:i,taskKey:s,branchPath:a}=o,c=H(a),l=t.moduleId||await U(e,i,n),d=await W(e,i,n),u=t.preferredTerm||t.fsn,p=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,g={conceptId:null,moduleId:l,definitionStatus:"PRIMITIVE",active:!0,descriptions:[oe("FSN",p,l,d,"PREFERRED",!0),oe("SYNONYM",u,l,d,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:Ft.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:l,relationships:[{active:!0,groupId:0,type:{conceptId:si},target:{conceptId:t.parentConceptId}}]}]},h=`${A(e)}/browser/${c}/${i}/${s}/concepts/?validate=true`,y=await I(h,{method:"POST",body:g,cookie:e.cookie});if(y.sessionExpired){let R="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: SESSION EXPIRED`),{statusCode:401,body:{error:R}}}let k=y.body,b=k&&"conceptId"in k?k.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${i}/${s}: ${y.statusCode<300?"OK":"FAILED ("+y.statusCode+")"} \u2014 ${p}`+(b?` \u2192 ${b}`:"")),typeof b=="string"&&e.onValidationResults?.(b,k?.validationResults),{statusCode:y.statusCode,body:y.body}}var ai=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],ci={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function di(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(n=>n.active!==!1).length}function Kt(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(n=>n.characteristicType===t)}function ne(e){return{conceptId:e.conceptId,fsn:e.fsn,pt:e.pt,active:e.active,definitionStatus:e.definitionStatus}}function re(e){return typeof e=="object"&&e!==null}function li(e,t,r){let n=Array.isArray(e[r])?e[r]:[],o=[];for(let i of n){if(i.active===!1||typeof i.axiomId!="string")continue;(Array.isArray(i.relationships)?i.relationships:[]).forEach((a,c)=>{let l=a.type;if((re(l)?l.conceptId:void 0)!==t)return;let u=a.target;o.push({axiomId:i.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:re(u)?u.conceptId:void 0,targetFsn:re(u)&&re(u.fsn)?u.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return o}async function ye(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};if(!t.attributeType){let a=ai.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>ci[c]).join(", ")}.`}}}if(!t.attributeType&&!t.descriptions&&!t.descriptionFull&&!t.axioms&&!t.inferred&&!t.gci&&!t.gciAxiomsCount&&!t.full){let a=`${A(e)}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(a,{cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:c.statusCode,body:c.body}}let o=`${A(e)}/browser/${n.branchPath}/concepts/${t.conceptId}`,i=await I(o,{cookie:e.cookie});if(i.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(i.statusCode<200||i.statusCode>=300||!re(i.body))return{statusCode:i.statusCode,body:i.body};let s=i.body;if(t.attributeType){let a=t.gci?"gciAxioms":"classAxioms",c=li(s,t.attributeType,a);return{statusCode:i.statusCode,body:{conceptId:t.conceptId,attributeType:t.attributeType,gci:!!t.gci,matches:c}}}if(t.descriptions){let a=Array.isArray(s.descriptions)?s.descriptions.filter(c=>c.active!==!1):[];return{statusCode:i.statusCode,body:{...ne(s),descriptions:a}}}return t.descriptionFull?{statusCode:i.statusCode,body:{...ne(s),descriptions:s.descriptions??[]}}:t.axioms?{statusCode:i.statusCode,body:{...ne(s),classAxioms:s.classAxioms??[],relationships:Kt(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...ne(s),relationships:Kt(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...ne(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:di(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var ui=500,pi=1e4;async function he(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o={expand:"fsn()"};t.term&&(o.termFilter=t.term),t.ecl&&(o.eclFilter=t.ecl),typeof t.active=="boolean"&&(o.activeFilter=t.active);let i=`${A(e)}/${n.branchPath}/concepts/search`,s=d=>({conceptId:d.conceptId,fsn:d.fsn?.term,pt:d.pt?.term,active:d.active,moduleId:d.moduleId});if(t.limit!==void 0){let d=await I(i,{method:"POST",body:{...o,limit:t.limit},cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let u=(d.body?.items??[]).map(s);return{statusCode:d.statusCode,body:{total:d.body?.total??u.length,items:u}}}let a=[],c=0,l=0;for(;;){let d=Math.min(ui,pi-l);if(d<=0)break;let u=await I(i,{method:"POST",body:{...o,limit:d,offset:l},cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(u.statusCode<200||u.statusCode>=300)return{statusCode:u.statusCode,body:u.body??{error:"Concept search failed."}};let p=u.body?.items??[];if(a.push(...p.map(s)),c=u.body?.total??a.length,l+=p.length,p.length===0||l>=c)break}return{statusCode:200,body:{total:c,items:a,...a.length<c?{truncated:!0,message:`Only ${a.length} of ${c} matches returned \u2014 Snowstorm caps unsorted search at offset+limit 10,000. Narrow the query (--term/--ecl/--active) to see the rest.`}:{}}}}var ie=1e3;function mi(e){let t=new Map;for(let r of e)for(let n of r){let o=n.referenceType?.conceptId??"",i=t.get(o);i?i.referencingConcepts=[...i.referencingConcepts??[],...n.referencingConcepts??[]]:t.set(o,{...n,referencingConcepts:[...n.referencingConcepts??[]]})}return[...t.values()]}async function Mt(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=`${A(e)}/${n.branchPath}/concepts/${t.conceptId}/references`,i=(d,u)=>{let p=new URLSearchParams;return typeof t.stated=="boolean"&&p.set("stated",String(t.stated)),p.set("limit",String(d)),p.set("offset",String(u)),I(`${o}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let d=await i(t.limit??ie,t.offset??0);return d.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:d.statusCode,body:d.body}}let s=[],a=0,c=0,l=0;for(;;){let d=await i(ie,l);if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(d.statusCode<200||d.statusCode>=300)return{statusCode:d.statusCode,body:d.body??{error:"Could not fetch references."}};let u=d.body?.referencesByType??[];s.push(u),a=d.body?.total??a;let p=u.reduce((g,h)=>g+(h.referencingConcepts?.length??0),0);if(c+=p,p===0||p<ie||c>=a)break;l+=ie}return{statusCode:200,body:{total:a,limit:ie,offset:0,referencesByType:mi(s)}}}var Ye=v(require("crypto"));function Bt(e){return typeof e=="object"&&e!==null}function fi(e){let t=e.type,r=e.target,n=Bt(t)?t.conceptId:void 0,o=Bt(r)?r.conceptId:void 0;return typeof n=="string"&&typeof o=="string"?{typeId:n,targetId:o}:null}function gi(e,t){let r=[...t];for(let n of e){let o=r.findIndex(i=>i.typeId===n.typeId&&i.targetId===n.targetId);if(o===-1)return!1;r.splice(o,1)}return!0}function _t(e,t,r){let n=new Map;for(let s of e){let a=typeof s.groupId=="number"?s.groupId:0,c=n.get(a);c?c.push(s):n.set(a,[s])}let o=[];for(let[s,a]of n){if(r!=null?s!==r:s===0)continue;let c=a.map(fi).filter(l=>l!=null);gi(t,c)&&o.push(s)}if(o.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(o.length>1)return{ok:!1,statusCode:409,error:`has ${o.length} role groups matching the given attributes (groupIds: ${o.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let i=o[0];return{ok:!0,groupId:i,relationships:n.get(i)}}var yi=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],hi=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],ki=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],Ci=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],Ii=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],We=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function Qt(e){return We.includes(e)}function se(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function ke(e){return typeof e=="object"&&e!==null}function Ut(e){return ke(e)?se(e,Ci):e}function zt(e){if(!ke(e))return e;let t=se(e,ki);return"type"in t&&(t.type=Ut(t.type)),"target"in t&&(t.target=Ut(t.target)),t}function xi(e){return ke(e)?se(e,hi):e}function Vt(e){if(!ke(e))return e;let t=se(e,Ii);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(zt)),t}function Xe(e){let t=se(e,yi);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(xi)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(zt)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(Vt)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(Vt)),t}function bi(e){return new Promise(t=>setTimeout(t,e))}function Si(e){if(e.statusCode!==400)return!1;let t=e.body;return t?.error==="BAD_REQUEST"&&typeof t.message=="string"&&t.message.includes("is already locked")}var Je=[300,600,1200,2400,4800],qt=new Map;function vi(e,t){let n=(qt.get(e)??Promise.resolve()).then(t,t);return qt.set(e,n.then(()=>{},()=>{})),n}async function w(e,t,r,n){try{return await vi(t.branchPath,()=>Ti(e,t,r,n))}catch(o){return{statusCode:500,body:{error:o instanceof Error?o.message:String(o)}}}}async function Ti(e,t,r,n){for(let o=0;;o++){let i=A(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await I(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:a.body}};let c=a.body,l=n(c);if(l)return l;let d=H(t.branchPath),u=`${i}/browser/${d}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await I(u,{method:"PUT",body:Xe(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(Si(p)&&o<Je.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${o+1}/${Je.length})`),await bi(Je[o]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${p.statusCode<300?"OK":"FAILED ("+p.statusCode+")"} \u2014 ${r}`);let g=p.body;return e.onValidationResults?.(r,g?.validationResults),{statusCode:p.statusCode,body:p.body}}}var Gt=["PREFERRED","ACCEPTABLE"];async function Zt(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.type)return{statusCode:400,body:{error:"conceptId, term, and type are required."}};if(t.type!=="FSN"&&t.type!=="SYNONYM")return{statusCode:400,body:{error:"type must be FSN or SYNONYM."}};if(t.acceptability&&!Gt.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${Gt.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await U(e,o.projectKey,n),s=await W(e,o.projectKey,n),a=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return w(e,o,t.conceptId,c=>{let l=Array.isArray(c.descriptions)?c.descriptions:[];return l.push(oe(t.type,a,i,s,t.acceptability??"ACCEPTABLE",!1)),c.descriptions=l,null})}async function eo(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return w(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];if(!a)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.length}).`}};let c=Array.isArray(a.relationships)?a.relationships:[];return c.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),a.relationships=c,null})}async function to(e,t,r){if(!t.conceptId||!t.status)return{statusCode:400,body:{error:"conceptId and status are required."}};if(t.status!=="PRIMITIVE"&&t.status!=="FULLY_DEFINED")return{statusCode:400,body:{error:"status must be PRIMITIVE or FULLY_DEFINED."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=t.axiomIndex??0;return w(e,n,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s[o];return a?(a.definitionStatus=t.status,i.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${o} (has ${s.length}).`}}})}async function oo(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>o.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(o.active=!1,o.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(o.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null)):{statusCode:400,body:{error:n.error}}}async function no(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};if(!t.term&&!t.caseSignificance)return{statusCode:400,body:{error:"At least one of term or caseSignificance must be provided."}};if(t.caseSignificance&&!Qt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${We.join(", ")}.`}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(s.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(s.term=t.term),t.caseSignificance&&(s.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}async function ro(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!Qt(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${We.join(", ")}.`}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?(s.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}var He=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function Jt(e){return He.includes(e)}function io(e){return e.us&&!Jt(e.us)?{statusCode:400,body:{error:`us must be one of: ${He.join(", ")}.`}}:e.gb&&!Jt(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${He.join(", ")}.`}}:null}function so(e){return e.descriptionId?!e.lang&&!e.us&&!e.gb?{statusCode:400,body:{error:`Entry for description ${e.descriptionId} must set at least one of lang, us, or gb.`}}:io(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function Qe(e,t,r){let n=e.find(i=>i.descriptionId===r.descriptionId);if(!n)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(n.lang=r.lang);let o={...n.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete o[M]:o[M]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete o[J]:o[J]=r.gb),n.active!==!1&&Object.keys(o).length===0?{statusCode:400,body:{error:`Description ${r.descriptionId} would have an empty acceptabilityMap (Not Acceptable in every dialect) \u2014 an active description must be acceptable in at least one.`}}:(n.acceptabilityMap=o,null)}async function ao(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},o=so(n);if(o)return o;let i=await C(e,t,r);return i.ok?w(e,i,t.conceptId,s=>{let a=Array.isArray(s.descriptions)?s.descriptions:[];return Qe(a,t.conceptId,n)}):{statusCode:400,body:{error:i.error}}}async function co(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};if(!Array.isArray(t.entries)||t.entries.length===0)return{statusCode:400,body:{error:"entries must be a non-empty array."}};for(let o of t.entries){let i=so(o);if(i)return i}let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[];for(let s of t.entries){let a=Qe(i,t.conceptId,s);if(a)return a}return null}):{statusCode:400,body:{error:n.error}}}async function lo(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.descriptions)?o.descriptions:[],s=i.findIndex(a=>a.descriptionId===t.descriptionId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(i.splice(s,1),o.descriptions=i,null)}):{statusCode:400,body:{error:n.error}}}var Ce="REFERS_TO";async function uo(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.descriptions)?o.descriptions:[]).find(a=>a.descriptionId===t.descriptionId);return s?s.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(s.active=!1,s.inactivationIndicator=t.indicator,s.acceptabilityMap={},t.associationTargetId&&(s.associationTargets={[Ce]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}}):{statusCode:400,body:{error:n.error}}}function Ht(e,t,r){for(let n of e){if(n.descriptionId===t||n.active===!1||n.type!=="SYNONYM")continue;let o=n.acceptabilityMap;o?.[r]==="PREFERRED"&&(n.acceptabilityMap={...o,[r]:"ACCEPTABLE"})}}async function po(e,t,r,n=new Map){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o={descriptionId:t.descriptionId,lang:t.lang,us:t.us,gb:t.gb},i=io(o);if(i)return i;let s=!!(t.lang||t.us||t.gb),a=await C(e,t,r);if(!a.ok)return{statusCode:400,body:{error:a.error}};let c=await W(e,a.projectKey,n);return w(e,a,t.conceptId,l=>{let d=Array.isArray(l.descriptions)?l.descriptions:[],u=d.find(g=>g.descriptionId===t.descriptionId);if(!u)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(u.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(u.type==="FSN"){if(s)return{statusCode:400,body:{error:"lang/us/gb do not apply when restoring an FSN \u2014 it is always PREFERRED in every dialect the project uses."}};let g=d.filter(h=>h.type==="FSN"&&h.active!==!1&&h.descriptionId!==t.descriptionId);if(g.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${g.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(g.length===1){let h=g[0];if(h.effectiveTime==null)d.splice(d.indexOf(h),1);else{if(!t.indicator)return{statusCode:400,body:{error:`Restoring this FSN requires --indicator, to retire the concept's current active (published) FSN ${String(h.descriptionId)} in the same save.`}};h.active=!1,h.inactivationIndicator=t.indicator,h.acceptabilityMap={},t.associationTargetId&&(h.associationTargets={[Ce]:[t.associationTargetId]})}}return u.active=!0,delete u.inactivationIndicator,delete u.associationTargets,u.acceptabilityMap=ge(c,!1),l.descriptions=d,null}if(!s)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};u.active=!0,delete u.inactivationIndicator,delete u.associationTargets;let p=Qe(d,t.conceptId,o);return p||(o.us==="PREFERRED"&&Ht(d,t.descriptionId,M),o.gb==="PREFERRED"&&Ht(d,t.descriptionId,J),null)})}var Ai="900000000000490003",Yt=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function mo(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!Yt.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${Yt.join(", ")}.`}};if(t.reason==="NOT_SEMANTICALLY_EQUIVALENT"){if(!t.targetId)return{statusCode:400,body:{error:"reason NOT_SEMANTICALLY_EQUIVALENT requires --target-id \u2014 the concept this description actually belongs under."}}}else if(t.targetId)return{statusCode:400,body:{error:`--target-id only applies to reason NOT_SEMANTICALLY_EQUIVALENT (paired with a REFERS_TO association) \u2014 omit it for ${t.reason}.`}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=`${A(e)}/${n.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${Ai}&active=true`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||500,body:{error:`Could not check description ${t.descriptionId}'s current inactivation reason.`,details:s.body}};let a=(s.body.items??[])[0];return a?.released===!0?{statusCode:409,body:{error:`Description ${t.descriptionId}'s inactivation reason has already been published (effectiveTime ${String(a.effectiveTime)}) and cannot be changed.`}}:w(e,n,t.conceptId,c=>{let d=(Array.isArray(c.descriptions)?c.descriptions:[]).find(u=>u.descriptionId===t.descriptionId);return d?d.active!==!1?{statusCode:409,body:{error:`Description ${t.descriptionId} is active \u2014 use inactivate-description to inactivate it with a reason.`}}:(d.inactivationIndicator=t.reason,t.reason==="NOT_SEMANTICALLY_EQUIVALENT"?d.associationTargets={[Ce]:[t.targetId]}:delete d.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function fo(e,t,r,n=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await U(e,o.projectKey,n),s=await W(e,o.projectKey,n),a=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return w(e,o,t.conceptId,c=>{let l=Array.isArray(c.descriptions)?c.descriptions:[],d;if(t.descriptionId){if(d=l.find(u=>u.descriptionId===t.descriptionId),!d)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(d.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(d.type)}, not an FSN.`}}}else{let u=l.filter(p=>p.type==="FSN"&&p.active!==!1);if(u.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${u.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};d=u[0]}return d.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(d.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(d.active=!1,d.inactivationIndicator=t.indicator,d.acceptabilityMap={},t.associationTargetId&&(d.associationTargets={[Ce]:[t.associationTargetId]}),l.push(oe("FSN",a,i,s,"PREFERRED",!1)),c.descriptions=l,null)})}async function ze(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?(s.relationships=t.relationships,t.active!=null&&(s.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function go(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.gciAxioms)?o.gciAxioms:[]).find(a=>a.axiomId===t.axiomId);return s?(s.relationships=t.relationships,t.active!=null&&(s.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}}):{statusCode:400,body:{error:n.error}}}async function yo(e,t,r,n=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};if(t.definitionStatus&&t.definitionStatus!=="PRIMITIVE"&&t.definitionStatus!=="FULLY_DEFINED")return{statusCode:400,body:{error:"definitionStatus must be PRIMITIVE or FULLY_DEFINED."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await U(e,o.projectKey,n);return w(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[];return a.push({axiomId:Ye.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.classAxioms=a,null})}async function ho(e,t,r,n=new Map){if(!t.conceptId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId and relationships (array) are required."}};if(t.relationships.length===0)return{statusCode:400,body:{error:"relationships must contain at least one relationship."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let i=t.moduleId||await U(e,o.projectKey,n);return w(e,o,t.conceptId,s=>{let a=Array.isArray(s.gciAxioms)?s.gciAxioms:[];return a.push({axiomId:Ye.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:i,relationships:t.relationships}),s.gciAxioms=a,null})}async function ko(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:i.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(i.splice(s,1),o.classAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function Co(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.classAxioms)?o.classAxioms:[],s=i.find(c=>c.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};if(s.active===!1)return{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}};if(s.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}};let a=i.filter(c=>c!==s&&c.active!==!1);return a.length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:a.every(c=>c.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished class axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-axiom to edit ${t.axiomId}'s content in place instead.`}}:(s.active=!1,null)}):{statusCode:400,body:{error:n.error}}}var wi="116680003";function Wt(e,t){let r={active:!0,groupId:t,type:{conceptId:e.type?.id}};return e.concrete?r.concreteValue={dataType:e.value?.dataType,value:e.value?.value}:r.target={conceptId:e.target?.id},r}function Ri(e){let t=[],r=Array.isArray(e.concepts)?e.concepts:[];for(let i of r)i?.id&&t.push({active:!0,groupId:0,type:{conceptId:wi},target:{conceptId:i.id}});let n=Array.isArray(e.attributes)?e.attributes:[];for(let i of n)t.push(Wt(i,0));return(Array.isArray(e.groups)?e.groups:[]).forEach((i,s)=>{let a=Array.isArray(i.attributes)?i.attributes:[];for(let c of a)t.push(Wt(c,s+1))}),t}async function Io(e,t,r,n){let o=A(e),i=await I(`${o}/browser/${t.branchPath}/concepts/${r}`,{cookie:e.cookie});if(i.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(i.statusCode<200||i.statusCode>=300||!i.body)return{ok:!1,result:{statusCode:i.statusCode||404,body:{error:`Could not fetch concept ${r}.`,details:i.body,undetermined:!0}}};let s=Array.isArray(i.body.classAxioms)?i.body.classAxioms:[],a;if(n){if(a=s.find(c=>c.axiomId===n),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${n}.`,undetermined:!0}}}}else{let c=s.filter(l=>l.active!==!1);if(c.length===0)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has no active class axiom.`,undetermined:!0}}};if(c.length>1)return{ok:!1,result:{statusCode:409,body:{error:`Concept ${r} has ${c.length} active class axioms \u2014 pass axiomId to pick which one.`,undetermined:!0}}};a=c[0]}return{ok:!0,value:{axiom:a,axiomId:a.axiomId}}}var Ei="116680003";function $i(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==Ei?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function ji(e,t,r){let n=A(e),o=await I(`${n}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(o.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(o.statusCode<200||o.statusCode>=300||!o.body)return{ok:!1,result:{statusCode:o.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:o.body,undetermined:!0}}};let i=Ri(o.body);return i.length===0?{ok:!1,result:{statusCode:409,body:{error:`Authoring form for ${r} produced no relationships \u2014 the concept likely hasn't been classified since its last stated edit. Run classify --wait first.`,undetermined:!0}}}:{ok:!0,value:i}}async function Pi(e,t,r,n){let o=await Io(e,t,r,n);if(!o.ok)return o;let i=await ji(e,t,r);return i.ok?{ok:!0,value:{axiom:o.value.axiom,axiomId:o.value.axiomId,targetRelationships:i.value}}:i}function Ni(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let n=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${n}`}function Xt(e){let t=new Map;for(let o of e){if(o.active===!1)continue;let i=typeof o.groupId=="number"?o.groupId:0,s=t.get(i)??[];s.push(Ni(o)),t.set(i,s)}let r=(t.get(0)??[]).slice().sort(),n=[];for(let[o,i]of t)o!==0&&n.push(i.slice().sort());return{ungrouped:r,groups:n}}function Di(e,t){let r=Xt(e),n=Xt(t);if(r.ungrouped.join("|")!==n.ungrouped.join("|"))return!1;let o=r.groups.map(s=>s.join("|")).sort(),i=n.groups.map(s=>s.join("|")).sort();return o.join("||")===i.join("||")}async function Ie(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Pi(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:i,axiomId:s,targetRelationships:a}=o.value,c=Array.isArray(i.relationships)?i.relationships:[];return Di(c,a)?(e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${n.projectKey}/${n.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,alreadyConformed:!0}}):ze(e,{conceptId:t.conceptId,axiomId:s,relationships:a,projectKey:n.projectKey,taskKey:n.taskKey},r)}async function xe(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Io(e,n,t.conceptId,t.axiomId);if(!o.ok)return o.result;let{axiom:i,axiomId:s}=o.value,a=Array.isArray(i.relationships)?i.relationships:[];return $i(a)?{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!0,conforms:!1}}:{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!1,message:"Stated Is-a targets are all primitive \u2014 this cannot rule out a missing/mismatched attribute. Run transform-axiom to get a definitive, self-fixing answer."}}}async function xo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};if(!t.relationshipId&&t.relationshipIndex==null)return{statusCode:400,body:{error:"One of relationshipId or relationshipIndex is required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(d=>d.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=t.relationshipId?a.findIndex(d=>d.relationshipId===t.relationshipId):t.relationshipIndex,l=c>=0?a[c]:void 0;return l?l.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${c}`} has effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.splice(c,1),s.relationships=a,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}}):{statusCode:400,body:{error:n.error}}}async function bo(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.attributes)||t.attributes.length===0)return{statusCode:400,body:{error:"conceptId, axiomId, and a non-empty attributes array are required."}};for(let o of t.attributes)if(!o||typeof o.typeId!="string"||typeof o.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let s=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(d=>d.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let a=Array.isArray(s.relationships)?s.relationships:[],c=_t(a,t.attributes,t.groupId);if(!c.ok)return{statusCode:c.statusCode,body:{error:`Axiom ${t.axiomId} ${c.error}`}};let l=c.relationships.find(d=>d.effectiveTime!=null);return l?{statusCode:409,body:{error:`Role group (groupId ${c.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(l.relationshipId)}) with effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(s.relationships=a.filter(d=>(typeof d.groupId=="number"?d.groupId:0)!==c.groupId),null)}):{statusCode:400,body:{error:n.error}}}async function So(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.gciAxioms)?o.gciAxioms:[],s=i.findIndex(a=>a.axiomId===t.axiomId);return s===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:i[s].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(i.splice(s,1),o.gciAxioms=i,null)}):{statusCode:400,body:{error:n.error}}}async function vo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let n=await C(e,t,r);return n.ok?w(e,n,t.conceptId,o=>{let i=Array.isArray(o.gciAxioms)?o.gciAxioms:[],s=i.find(c=>c.axiomId===t.axiomId);if(!s)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}};if(s.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished GCI axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-gci-axiom).`}};if(s.active===!1)return{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}};let a=i.filter(c=>c!==s&&c.active!==!1);return a.length>0&&a.every(c=>c.effectiveTime==null)?{statusCode:409,body:{error:`Inactivating GCI axiom ${t.axiomId} would leave concept ${t.conceptId} with only unpublished GCI axiom(s) active \u2014 this is the add-a-replacement-then-inactivate-the-original pattern, which produces two OwlAxiom rows where the real Authoring Workbench produces one. Use update-gci-axiom to edit ${t.axiomId}'s content in place instead.`}}:(s.active=!1,null)}):{statusCode:400,body:{error:n.error}}}var Oi=8;async function be(e,t,r,n){let o=[],i=[],s=0,a=async()=>{for(;;){let l=s++;if(l>=r.length)return;let d=r[l];try{let u=await xe(e,{conceptId:d.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),p=u.body;if(u.statusCode<200||u.statusCode>=300){i.push({...d,error:p?.error??`HTTP ${u.statusCode}`});continue}p?.conclusive&&o.push({...d,axiomId:p.axiomId})}catch(u){i.push({...d,error:u instanceof Error?u.message:String(u)})}}},c=Math.min(Oi,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:o,skipped:i}}async function To(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await he(e,{...t,branchPath:n.branchPath},r);if(o.statusCode<200||o.statusCode>=300)return o;let i=o.body?.items??[],s=i.map(l=>({conceptId:l.conceptId,fsn:l.fsn,pt:l.pt})),{matched:a,skipped:c}=await be(e,n,s,r);return{statusCode:200,body:{branchPath:n.branchPath,totalSearched:i.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function Ao(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};if(s.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let a=`${o}/${n.branchPath}/concepts/${t.conceptId}`,c=await I(a,{method:"DELETE",cookie:e.cookie});return c.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] delete-concept ${n.projectKey}/${n.taskKey}: ${c.statusCode<300?"OK":"FAILED ("+c.statusCode+")"} \u2014 ${t.conceptId}`),c.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${t.conceptId} \u2014 one or more of its components is published.`,details:c.body}}:{statusCode:c.statusCode,body:c.body})}function Fi(e){let t=[];for(let r of e)t.some(o=>o.componentId===r.componentId&&o.severity===r.severity&&o.conceptId===r.conceptId&&o.message===r.message)||t.push(r);return t}async function Se(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=A(e),i=`${o}/browser/${n.branchPath}/concepts/${t.conceptId}`,s=await I(i,{cookie:e.cookie});if(s.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(s.statusCode<200||s.statusCode>=300||!s.body)return{statusCode:s.statusCode||404,body:{error:`Could not fetch concept ${t.conceptId}.`,details:s.body}};let a=H(n.branchPath),c=`${o}/browser/${a}/${n.projectKey}/${n.taskKey}/validate/concept`,l=await I(c,{method:"POST",body:Xe(s.body),cookie:e.cookie});if(l.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(l.statusCode<200||l.statusCode>=300)return{statusCode:l.statusCode,body:{error:"Validation check failed.",details:l.body}};let d=Array.isArray(l.body)?Fi(l.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:d,hasErrors:d.some(u=>u.severity==="ERROR"),hasWarnings:d.some(u=>u.severity==="WARNING")}}}var wo=200;async function Li(e,t,r){let n=new Map;if(r.length===0)return{terms:n,resolved:!0};let o=`${A(e)}/browser/${t}/concepts/bulk-load`,i=!0;for(let s=0;s<r.length;s+=wo){let a=r.slice(s,s+wo),c=await I(o,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){i=!1;continue}for(let l of c.body)n.set(l.conceptId,{fsn:l.fsn?.term,pt:l.pt?.term})}return{terms:n,resolved:i}}async function B(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=[],i=0;for(;;){let y=`${Dt(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(n.branchPath)}`,k=await I(y,{cookie:e.cookie});if(k.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(k.statusCode===404)return{statusCode:200,body:{branchPath:n.branchPath,concepts:[],conceptsClassified:[]}};if(k.statusCode<200||k.statusCode>=300)return{statusCode:k.statusCode,body:{error:"Could not fetch traceability for branch.",details:k.body}};o.push(...k.body?.content??[]);let b=k.body?.totalPages??1;if(k.body?.last!==!1||i+1>=b)break;i+=1}let s=new Map,a=new Map,c=(y,k,b,R)=>{let j=y.get(k);j?(R.forEach(P=>P&&j.componentSubTypes.add(P)),j.lastUpdatedTime=b):y.set(k,{conceptId:k,lastUpdatedTime:b,componentSubTypes:new Set(R.filter(P=>!!P))})};for(let y of o)if(!(y.activityType!=="CONTENT_CHANGE"&&y.activityType!=="CLASSIFICATION_SAVE"))for(let k of y.conceptChanges??[]){let b=String(k.conceptId),R=k.componentChanges??[],j=R.map(K=>K.componentSubType);if(y.activityType==="CLASSIFICATION_SAVE"){c(a,b,y.commitDate,j);continue}let P=R.some(K=>K.componentSubType!=="INFERRED_RELATIONSHIP");c(P?s:a,b,y.commitDate,j)}for(let y of s.keys())a.delete(y);let l=[...new Set([...s.keys(),...a.keys()])],{terms:d,resolved:u}=await Li(e,n.branchPath,l),p=y=>[...y.values()].sort((k,b)=>(b.lastUpdatedTime??"").localeCompare(k.lastUpdatedTime??"")).map(k=>{let b=u&&!d.has(k.conceptId);return{conceptId:k.conceptId,fsn:d.get(k.conceptId)?.fsn,pt:d.get(k.conceptId)?.pt,...b?{deleted:!0}:{},lastUpdatedTime:k.lastUpdatedTime,changedComponentTypes:[...k.componentSubTypes]}}),g=p(s),h=p(a);return{statusCode:200,body:{branchPath:n.branchPath,...u?{summary:{concepts:g.length,conceptsDeleted:g.filter(y=>y.deleted).length,conceptsClassified:h.length}}:{},concepts:g,conceptsClassified:h}}}async function Ro(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await B(e,t,r);if(o.statusCode<200||o.statusCode>=300){let d=o.body;return{statusCode:o.statusCode,body:{error:d.error??"Could not list concepts for review."}}}let i=o.body.concepts??[],s=i.filter(d=>!d.deleted),a=s.map(d=>({conceptId:d.conceptId,fsn:d.fsn})),{matched:c,skipped:l}=await be(e,n,a,r);return{statusCode:200,body:{branchPath:n.branchPath,totalReviewed:s.length,matched:c.length,skipped:l.length,skippedDeleted:i.length-s.length,results:c,skippedConcepts:l}}}async function Ki(e,t,r,n){let o=[];for(let i of r){if(i.deleted){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"deleted"});continue}let s=await Se(e,{conceptId:i.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},n),a=s.body;if(s.statusCode<200||s.statusCode>=300){o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"failed",error:a.error??`HTTP ${s.statusCode}`});continue}let c=a.validationResults??[];o.push({conceptId:i.conceptId,fsn:i.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return o}async function Eo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await B(e,t,r);if(o.statusCode<200||o.statusCode>=300){let c=o.body;return{statusCode:o.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=o.body.concepts??[],s=await Ki(e,n,i,r),a=c=>s.filter(l=>l.outcome===c).length;return{statusCode:200,body:{branchPath:n.branchPath,summary:{total:s.length,validated:a("clean")+a("issues"),clean:a("clean"),withIssues:a("issues"),skippedDeleted:a("deleted"),failed:a("failed")},results:s}}}async function _(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}`;return(await I(n,{cookie:e.cookie})).body??null}var Ze=new Set;function $o(e){if(!(!e||typeof e!="object"))for(let t of Ze)t(e)}function Mi(e){return Ze.add(e),()=>Ze.delete(e)}function Bi(e,t){return t.entityType!==void 0&&e.entityType!==t.entityType?!1:e.task?e.task===t.taskKey&&e.project===t.projectKey:e.project?e.project===t.projectKey:e.branchPath===t.branchPath}function ve(e){let t=()=>{};return{promise:new Promise(n=>{t=Mi(o=>{Bi(o,e)&&(t(),n(o))})}),cancel:t}}var nt=["RUNNING","BUILDING","SCHEDULED","QUEUED"],rt=["QUEUED","SCHEDULED","RUNNING"],_i=["Promoted","Completed"],jo=5e3;function ot(e){return new Promise(t=>setTimeout(t,e))}async function Ui(e,t,r){let n=0;for(;;){let{done:o,value:i}=await e();if(o)return{value:i,timedOut:!1};if(n>=r)return{value:i,timedOut:!0};n++,await ot(t)}}function Vi(){let e=[9e4];for(let t=0;t<3;t++)e.push(1e4);for(let t=0;t<12;t++)e.push(5e3);return e}var qi=Vi(),Gi=180;function Ji(){let e=[3e5];for(let t=0;t<5;t++)e.push(6e4);for(let t=0;t<10;t++)e.push(3e4);return e}var Hi=Ji(),Yi=900;async function Do(e,t,r,n,o){let i=r*1e3,s=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],l=n?ve(n):void 0,d=await Promise.race(l?[ot(c).then(()=>{}),l.promise]:[ot(c).then(()=>{})]);if(l?.cancel(),d){let g=d.event;o?.(`[${new Date().toISOString()}] woken by notification${g?`: ${g}`:""}`)}let{done:u,value:p}=await e();if(u)return{value:p,timedOut:!1};if(Date.now()-s>=i)return{value:p,timedOut:!0};a++}}async function Oo(e,t,r){let n=await _(e,t,r);if(!n)return{error:`Could not fetch task ${t}/${r}.`};if(n.status&&_i.includes(n.status))return{error:`Task ${t}/${r} is ${n.status} \u2014 cannot start a new job.`};if(n.status==="New"){let o=`${E(e)}/projects/${t}/tasks/${r}`;await I(o,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function it(e,t,r){let n=`${E(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await I(n,{method:"POST",body:{},cookie:e.cookie}),(await _(e,t,r))?.latestClassificationJson}async function Po(e,t,r,n,o){let i,{value:s,timedOut:a}=await Do(async()=>{let l=(await it(e,t,r))?.status;return l!==i&&(i=l,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${l??"unknown"}`)),{done:!(!l||nt.includes(l)),value:l}},qi,o,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function et(e,t,r){let n=`${A(e)}/${t}/classifications`,o=await I(n,{cookie:e.cookie});if(o.body?.items?.length)return o.body.items.find(i=>i.id===r)??o.body.items[o.body.items.length-1]}async function Fo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,s=await it(e,o,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:nt.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function Te(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await Oo(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Gi,l=await it(e,o,i),d=l?.status,u=l?.id;if(u&&d&&nt.includes(d)){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${u} already ${d} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:P}=await Po(e,o,i,s,c),K=await et(e,s,u),q={accepted:!1};return!P&&j==="COMPLETED"&&(q=await tt(e,s,o,i,u)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: attached job ${u} final status ${j??"unknown"}${P?" (timed out waiting)":""}, save ${JSON.stringify(q)}`),{statusCode:200,body:{jobId:u,finalStatus:j,timedOut:P,details:K,save:q,attachedToExisting:!0}}}if(u&&d==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: found job ${u} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await et(e,s,u),P=await tt(e,s,o,i,u);return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: accepted existing job ${u}, save ${JSON.stringify(P)}`),{statusCode:200,body:{jobId:u,finalStatus:"COMPLETED",timedOut:!1,details:j,save:P,acceptedExisting:!0}}}let p=`${E(e)}/projects/${o}/tasks/${i}/classifications`,g=await I(p,{method:"POST",body:{},cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!g.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: start failed (HTTP ${g.statusCode}) \u2014 raw body: ${g.rawBody}`),{statusCode:g.statusCode||500,body:{error:"Failed to start classification.",details:g.body??g.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: started (${g.body.status??"unknown"})`);let h=g.body.id;if(!t.wait)return{statusCode:200,body:{jobId:h,status:g.body.status}};let{finalStatus:y,timedOut:k}=await Po(e,o,i,s,c),b=await et(e,s,h),R={accepted:!1};return!k&&y==="COMPLETED"&&(R=await tt(e,s,o,i,h)),e.onLog?.(`[${new Date().toISOString()}] classify ${o}/${i}: final status ${y??"unknown"}${k?" (timed out waiting)":""}, save ${JSON.stringify(R)}`),{statusCode:200,body:{jobId:h,finalStatus:y,timedOut:k,details:b,save:R}}}var Wi=["SAVED","STALE","SAVE_FAILED"],Xi=120;async function tt(e,t,r,n,o){let i=`${A(e)}/${t}/classifications/${o}`,s=await I(i,{method:"PUT",body:{status:"SAVED"},cookie:e.cookie});if(s.statusCode===400)return{accepted:!1,error:"Report stale \u2014 re-classify and save."};if(s.statusCode<200||s.statusCode>=300)return{accepted:!1,error:`Failed to save classification (HTTP ${s.statusCode}).`};let a=Math.ceil(Xi*1e3/jo),{value:c,timedOut:l}=await Ui(async()=>{let u=(await I(i,{cookie:e.cookie})).body?.status;return{done:!!u&&Wi.includes(u),value:u}},jo,a);return l?{accepted:!1,status:c,error:"Timed out waiting for classification results to save."}:c==="SAVED"?{accepted:!0,status:c}:{accepted:!1,status:c,error:c==="STALE"?"Report stale \u2014 re-classify and save.":"Saving classification failed."}}async function Lo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i}=n,a=(await _(e,o,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&rt.includes(a)}}}async function No(e,t,r,n,o){let i,{value:s,timedOut:a}=await Do(async()=>{let l=(await _(e,t,r))?.latestValidationStatus;return l!==i&&(i=l,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${l??"unknown"}`)),{done:!(!l||rt.includes(l)),value:l}},Hi,o,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:n},e.onLog);return{finalStatus:s,timedOut:a}}async function Ko(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=await Oo(e,o,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Yi,d=(await _(e,o,i))?.latestValidationStatus;if(d&&rt.includes(d)){e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: validation already ${d} \u2014 waiting on it instead of starting a new one`);let{finalStatus:y,timedOut:k}=await No(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: attached run final status ${y??"unknown"}${k?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:y,timedOut:k,attachedToExisting:!0}}}let u=`${E(e)}/projects/${o}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await I(u,{method:"POST",body:{},cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(p.statusCode<200||p.statusCode>=300)return{statusCode:p.statusCode,body:{error:"Failed to start validation.",details:p.body}};if(e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:g,timedOut:h}=await No(e,o,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${o}/${i}: final status ${g??"unknown"}${h?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:g,timedOut:h}}}var Qi=8;function zi(e){return typeof e=="string"&&/timed out after \d+ms/.test(e)}async function Mo(e,t,r,n,o,i){let s=0,a=0,c=async()=>{for(;;){let d=a++;if(d>=r.length)return;let u=r[d];try{let p=await Ie(e,{conceptId:u.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),g=p.body;p.statusCode<200||p.statusCode>=300?g?.undetermined?n.set(u.conceptId,{outcome:"skipped",error:g.error??`HTTP ${p.statusCode}`}):n.set(u.conceptId,{outcome:"failed",error:g?.error??`HTTP ${p.statusCode}`}):n.set(u.conceptId,{outcome:g?.alreadyConformed?"conformed":"transformed"})}catch(p){n.set(u.conceptId,{outcome:"failed",error:p instanceof Error?p.message:String(p)})}s+=1,e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: ${i} \u2014 ${u.conceptId} (${s}/${r.length})`)}},l=Math.min(Qi,r.length);await Promise.all(Array.from({length:l},()=>c()))}async function Zi(e,t,r,n){let o=new Map;return await Mo(e,t,r,o,n,"axiom checked"),await es(e,t,r,o,n),o}async function es(e,t,r,n,o){let i=r.filter(s=>{let a=n.get(s.conceptId);return a?.outcome==="failed"&&zi(a.error)});i.length!==0&&(e.onLog?.(`[${new Date().toISOString()}] review-concepts ${t.projectKey}/${t.taskKey}: reprocessing ${i.length} concept(s) that timed out on the first pass`),await Mo(e,t,i,n,o,"axiom rechecked"))}async function Bo(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let o=await Te(e,{projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath,wait:!0},r);if(o.statusCode===401)return o;let i=o.body,s=o.statusCode>=200&&o.statusCode<300?{jobId:i?.jobId,finalStatus:i?.finalStatus,timedOut:i?.timedOut,save:i?.save}:{error:i?.error??`HTTP ${o.statusCode}`},a=await B(e,t,r);if(a.statusCode<200||a.statusCode>=300){let h=a.body;return{statusCode:a.statusCode,body:{error:h.error??"Could not list concepts for review."}}}let c=a.body.concepts??[],l=c.filter(h=>!h.deleted).map(h=>({conceptId:h.conceptId,fsn:h.fsn})),d=await Zi(e,n,l,r),u=[];for(let[h,y]of c.entries()){if(y.deleted){u.push({conceptId:y.conceptId,fsn:y.fsn,outcome:"deleted"});continue}let k=d.get(y.conceptId),b=await ye(e,{conceptId:y.conceptId,projectKey:n.projectKey,taskKey:n.taskKey,branchPath:n.branchPath},r),R=b.body,j=`(${h+1}/${c.length})`;if(b.statusCode<200||b.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: FAILED (${b.statusCode}) \u2014 ${y.conceptId} ${j}`),u.push({conceptId:y.conceptId,fsn:y.fsn,outcome:"failed",error:R?.error??`HTTP ${b.statusCode}`,axiom:k});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${n.projectKey}/${n.taskKey}: OK \u2014 ${y.conceptId} ${j}`),u.push({conceptId:y.conceptId,fsn:y.fsn,outcome:"fetched",concept:b.body,axiom:k})}let p=h=>u.filter(y=>y.outcome===h).length,g=h=>Array.from(d.values()).filter(y=>y.outcome===h).length;return{statusCode:200,body:{branchPath:n.branchPath,classification:s,summary:{total:u.length,fetched:p("fetched"),skippedDeleted:p("deleted"),failed:p("failed"),axiomsTransformed:g("transformed"),axiomsConformed:g("conformed"),axiomsSkipped:g("skipped"),axiomsFailed:g("failed")},concepts:u}}}async function _o(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",n=`${E(e)}/projects${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function Uo(e,t){let r=`${E(e)}/projects/${t}/tasks`;return(await I(r,{cookie:e.cookie})).body??[]}async function Vo(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",n=`${E(e)}/projects/my-tasks${r}`;return(await I(n,{cookie:e.cookie})).body??[]}async function qo(e,t){let r=`${E(e)}/projects/${t.projectKey}/tasks`,n={summary:t.summary};t.description!==void 0&&(n.description=t.description),t.assigneeUsername&&(n.assignee={username:t.assigneeUsername});let o=await I(r,{method:"POST",body:n,cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}async function Go(e,t){let r=`${E(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,n=await I(r,{cookie:e.cookie});return Array.isArray(n.body)?n.body:[]}var ts="IN_PROGRESS";async function Jo(e,t){let r=`${E(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,n=await I(r,{cookie:e.cookie});if(n.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(n.statusCode<200||n.statusCode>=300||!n.body)return{statusCode:n.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode}).`};if(n.body.status!=="Deleted")return{statusCode:200,task:n.body,notDeleted:!0};let o=await I(r,{method:"PUT",body:{status:ts},cookie:e.cookie});return o.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:o.statusCode<200||o.statusCode>=300||!o.body?{statusCode:o.statusCode||500,error:`Failed to recover ${t.projectKey}/${t.taskKey} (HTTP ${o.statusCode})${o.rawBody?`: ${o.rawBody}`:""}`}:{statusCode:o.statusCode,task:o.body}}function Ho(e){if(e==="o")return{type:"open"};if(e==="h")return{type:"heartbeat"};if(e.startsWith("a"))try{return{type:"message",messages:JSON.parse(e.slice(1))}}catch{return{type:"unknown",raw:e}}if(e.startsWith("c"))try{let[t,r]=JSON.parse(e.slice(1));return{type:"close",code:t,reason:r}}catch{return{type:"unknown",raw:e}}return{type:"unknown",raw:e}}function st(e){return JSON.stringify([e])}function Yo(e=Math.random){let t=String(Math.floor(e()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",n="";for(let o=0;o<8;o++)n+=r[Math.floor(e()*r.length)];return`${t}/${n}/websocket`}function at(e,t={},r=""){let n=Object.entries(t).map(([o,i])=>`${o}:${i}`);return[e,...n,"",r].join(`
3
+ `)+"\0"}function Wo(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
4
4
 
5
5
  `),n=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r+2),i=n.split(`
6
- `),s=i[0],a={};for(let c of i.slice(1)){let l=c.indexOf(":");l!==-1&&(a[c.slice(0,l)]=c.slice(l+1))}return{command:s,headers:a,body:o}}var Zo=v(require("ws"));var zo=[1e3,2e3,5e3,1e4,3e4];function en(e,t={}){let r=t.createSocket??((d,u)=>new Zo.default(d,u)),n=!1,o,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(n)return;let d=zo[Math.min(i,zo.length-1)];i+=1,s=setTimeout(l,d)};function l(){if(n)return;let u=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${Xo()}`,p=r(u,a?{headers:{cookie:a}}:{});o=p,p.on("message",g=>{let h=Wo(g.toString());if(h.type==="open"){p.send(at(ct("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(h.type==="close"){p.close();return}if(h.type==="message")for(let y of h.messages){let k=Qo(y);if(k){if(k.command==="CONNECTED"){i=0;let b=`/topic/user/${e.login}/notifications`;p.send(at(ct("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:b})));continue}if(k.command==="MESSAGE"){try{e.onNotification(JSON.parse(k.body))}catch(b){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",b)}continue}k.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",k.headers,k.body)}}}),p.on("unexpected-response",(g,h)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${h.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),p.terminate()}),p.on("error",g=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",g.message)}),p.on("close",c)}return l(),{stop(){n=!0,s&&clearTimeout(s),o?.removeAllListeners(),o?.close()}}}function tn(e,t,r={}){let n=r.startRelay??en,o=r.onNotification??Po,i=n({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:o});return{stop:()=>i.stop()}}var ns=60;async function on(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=t.timeoutSeconds??ns,c=Ae({entityType:t.entityType,projectKey:o,taskKey:i,branchPath:s}),l,d=new Promise(g=>{l=setTimeout(()=>g({kind:"timeout"}),a*1e3)}),u=c.promise.then(g=>({kind:"notification",payload:g})),p=await Promise.race([u,d]);return c.cancel(),clearTimeout(l),p.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:p.payload}}}function x(e){if(!(!Array.isArray(e)||e.length===0))for(let t of e){let r=t.severity??"INFO",n=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",o=t.componentId??t.conceptId??"?";console.log(`${n} ${r} [${o}] ${t.message??""}`)}}var En=v(require("http")),Le=require("child_process"),$n=require("util");var Ee=v(require("fs")),ut=v(require("os")),pt=v(require("path"));var dt=v(require("fs")),nn=v(require("os")),rn=v(require("path")),sn=[{path:"/usr/bin/chromium",configDir:"chromium"},{path:"/usr/bin/chromium-browser",configDir:"chromium"},{path:"/usr/bin/google-chrome-stable",configDir:"google-chrome"},{path:"/usr/bin/google-chrome",configDir:"google-chrome"},{path:"/snap/bin/chromium",configDir:"chromium"}],rs=Array.from(new Set(sn.map(e=>e.configDir)));function ae(){return sn.find(e=>dt.existsSync(e.path))??null}function Re(e=nn.homedir()){for(let t of rs)if(dt.existsSync(rn.join(e,".config",t)))return t;return ae()?.configDir??null}function is(e){if(e==="linux"){let t=Re();return t?pt.join(ut.homedir(),".config",t,"Local State"):""}return pt.join(ut.homedir(),"Library","Application Support","Google","Chrome","Local State")}function ss(e=process.platform){let t=is(e);if(!t||!Ee.existsSync(t))return[];let r;try{r=JSON.parse(Ee.readFileSync(t,"utf8"))}catch{return[]}let n=r?.profile?.info_cache??{};return Object.entries(n).map(([o,i])=>({directoryName:o,displayName:typeof i?.name=="string"&&i.name?i.name:o}))}var lt="authoring-cli";function $e(e=ss()){return e.find(r=>r.directoryName===lt)??{directoryName:lt,displayName:lt}}var fn=require("child_process"),gn=require("util"),Ne=v(require("fs")),X=v(require("os")),ce=v(require("path"));var an=require("child_process"),cn=require("util"),je=v(require("crypto")),V=v(require("fs")),as=(0,cn.promisify)(an.exec);function mt(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}var cs="peanuts";async function dn(e=process.platform){if(e==="darwin"){let{stdout:t}=await as('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return t.trim()}if(e==="linux")return cs;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}var ln=1003,ds=1;function un(e){if(e==="darwin")return ln;if(e==="linux")return ds;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}function pn(e,t=ln){return je.pbkdf2Sync(e,"saltysalt",t,16,"sha1")}function mn(e,t){if(!e)return null;let r=Buffer.from(e,"hex");if(r.length<4)return null;let n=r.subarray(0,3).toString("utf8");if(n!=="v10"&&n!=="v11")return null;let o=Buffer.alloc(16,32),i=r.subarray(3),s;try{let l=je.createDecipheriv("aes-128-cbc",t,o);s=Buffer.concat([l.update(i),l.final()])}catch{return null}let a=s.length>32?s.subarray(32):null,c=s;return a&&mt(a)&&!mt(s)&&(c=a),mt(c)?c.toString("utf8"):null}function ft(e,t){V.copyFileSync(e,t);for(let r of["-wal","-shm"]){let n=e+r;V.existsSync(n)&&V.copyFileSync(n,t+r)}}function gt(e){for(let t of[e,e+"-wal",e+"-shm"])try{V.unlinkSync(t)}catch{}}var ls=(0,gn.promisify)(fn.exec),Pe=class extends Error{},yt=class extends Error{};function yn(e,t){if(t==="linux"){let r=Re();return r?ce.join(X.homedir(),".config",r,e,"Cookies"):""}return ce.join(X.homedir(),"Library","Application Support","Google","Chrome",e,"Cookies")}function us(e=process.platform){return e==="linux"?ae()!==null:Ne.existsSync("/Applications/Google Chrome.app")}function ps(e){let t=e.split(".").filter(Boolean),r=[];for(let n=0;n+1<t.length;n++){let o=t.slice(n).join(".");r.push(o,`.${o}`)}return r}function ms(e){let t=e?.code;return t==="EPERM"||t==="EACCES"}async function ht(e,t,r,n=process.platform){let o=yn(e,n);if(!o||!Ne.existsSync(o))return null;let i=ce.join(X.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);try{ft(o,i);let s;try{s=await dn(n)}catch{return null}let a=pn(s,un(n)),c=p=>`'${p.replace(/'/g,"''")}'`,d=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${ps(t).map(c).join(", ")}) AND name = ${c(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:u}=await ls(`sqlite3 "${i}" "${d}"`);return mn(u.trim(),a)}catch{return null}finally{gt(i)}}function fs(e,t=process.platform){let r=yn(e,t);if(!r||!Ne.existsSync(r))return null;let n=ce.join(X.tmpdir(),`authoring-cli-chrome-cookies-precheck-${process.pid}-${Date.now()}.db`);try{return ft(r,n),null}catch(o){return ms(o)?`Cannot read Chrome's cookie file for profile "${e}" (permission denied). `+(t==="darwin"?'On macOS this usually means the terminal/app running authoring-cli needs "Full Disk Access": System Settings \u2192 Privacy & Security \u2192 Full Disk Access \u2192 add your terminal app, then try again.':"Check this process has permission to read Chrome's profile directory."):null}finally{gt(n)}}function gs(e){return new Promise(t=>setTimeout(t,e))}async function hn(e,t={}){let r=t.platform??process.platform,n=t.isChromeInstalled??(()=>us(r));if(r!=="darwin"&&r!=="linux")throw new Pe(`Automatic session capture is only supported on macOS or Linux with Chrome/Chromium. Detected platform: ${r}. Use the manual cookie-paste fallback instead.`);if(!n())throw new Pe(r==="darwin"?"Automatic session capture requires Google Chrome (checked /Applications/Google Chrome.app), but it was not found. Install Chrome, or use the manual cookie-paste fallback instead.":'Automatic session capture requires a Chromium/Chrome binary (checked common Debian install paths), but none was found. Install one (e.g. "apt install chromium" in this proot-distro Debian), or use the manual cookie-paste fallback instead.');let o=t.readCookie??((g,h,y)=>ht(g,h,y,r)),i=t.sleep??gs,s=t.onWarning??(g=>console.error(g)),a=t.checkCookieFileReadable??fs,c=e.pollIntervalMs??750,l=e.timeoutMs??15e3,d=a(e.profileDirectory,r);d&&s(d);let u=await o(e.profileDirectory,e.host,e.cookieName),p=Date.now()+l;for(;Date.now()<p;){let g=await o(e.profileDirectory,e.host,e.cookieName);if(g&&g!==u)return g;await i(c)}throw new yt(`Timed out after ${l}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host} in Chrome profile "${e.profileDirectory}" \u2014 the one and only profile this command ever reads or writes to. A common cause: sign-in happened in a DIFFERENT, already-open Chrome window/profile instead of the one this command opened \u2014 check that window's profile avatar (top-right corner) reads "${e.profileDirectory}", and that the window actually shows the real IMS login form rather than an unrelated already-signed-in page from another profile. Otherwise use the manual cookie-paste fallback.`)}var Oe=require("child_process"),Cn=require("util"),N=v(require("fs")),In=v(require("net")),xn=(0,Cn.promisify)(Oe.exec),De=1,de=`:${De}`,ys=["termux-x11","/data/data/com.termux/files/usr/bin/termux-x11"],kt="/data/data/com.termux/files/usr/bin",kn="com.termux.x11",hs=`${kn}/${kn}.MainActivity`,ks="termux-x11-start-app";function Ct(e){return`/tmp/.X11-unix/X${e}`}async function Cs(){for(let e of ys){if(e.startsWith("/")){if(N.existsSync(e))return e;continue}try{return await xn(`command -v ${e}`),e}catch{}}return null}function Is(e,t=500){return new Promise(r=>{let n=Ct(e);if(!N.existsSync(n)){r(!1);return}let o=In.createConnection({path:n}),i=s=>{o.removeAllListeners(),o.destroy(),r(s)};o.setTimeout(t),o.once("connect",()=>i(!0)),o.once("error",()=>i(!1)),o.once("timeout",()=>i(!1))})}function xs(e,t=1e4){let r=Date.now()+t;return new Promise((n,o)=>{let i=()=>{if(N.existsSync(Ct(e))){n();return}if(Date.now()>r){o(new Error(`Termux:X11's display socket for :${e} never appeared within ${t}ms`));return}setTimeout(i,100)};i()})}async function bs(){if(!N.existsSync(kt))return;let e=`${kt}/${ks}`,t=`${kt}/bash`,n=`#!${N.existsSync(t)?t:"/bin/sh"}
7
- am start --user 0 -n ${hs} >/dev/null 2>&1
8
- `;try{N.writeFileSync(e,n,{mode:493}),N.chmodSync(e,493),await xn(e,{timeout:5e3})}catch{}}async function bn(e=process.platform){if(e!=="linux"||await Is(De))return de;await bs();let t=await Cs();if(t===null)return de;try{N.unlinkSync(Ct(De))}catch{}return(0,Oe.spawn)(t,[de],{detached:!0,stdio:"ignore"}).unref(),await xs(De),de}var D=v(require("fs")),Fe=v(require("os")),L=v(require("path")),le=class extends Error{},Ss="com.ysgao.authoring-cli.chrome-login",vn="authoring-cli-chrome",vs="/Applications/Google Chrome.app";function Ts(e=vs,t=D.existsSync){let r=L.join(e,"Contents","MacOS","Google Chrome");if(t(r))return r;throw new le(`No Google Chrome installation found at ${e}. Install Google Chrome to use automatic session capture.`)}function Sn(e){return`'${e.replace(/'/g,"'\\''")}'`}function As(e,t){return["#!/bin/sh","# Generated by authoring-cli. Do not edit \u2014 rewritten on every login launch.","# Flags are baked in deliberately: `open --args` does not reliably reach a script bundle","# executable, and Launch Services drops --args entirely when it hands off to an","# already-running Chrome instead of starting a genuinely new process \u2014 see","# assertLaunchFlagsBaked in chromeWrapperApp.ts.",`exec ${Sn(e)} \\`,t.map(r=>` ${Sn(r)}`).join(` \\
6
+ `),s=i[0],a={};for(let c of i.slice(1)){let l=c.indexOf(":");l!==-1&&(a[c.slice(0,l)]=c.slice(l+1))}return{command:s,headers:a,body:o}}var Qo=v(require("ws"));var Xo=[1e3,2e3,5e3,1e4,3e4];function zo(e,t={}){let r=t.createSocket??((d,u)=>new Qo.default(d,u)),n=!1,o,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(n)return;let d=Xo[Math.min(i,Xo.length-1)];i+=1,s=setTimeout(l,d)};function l(){if(n)return;let u=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${Yo()}`,p=r(u,a?{headers:{cookie:a}}:{});o=p,p.on("message",g=>{let h=Ho(g.toString());if(h.type==="open"){p.send(st(at("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(h.type==="close"){p.close();return}if(h.type==="message")for(let y of h.messages){let k=Wo(y);if(k){if(k.command==="CONNECTED"){i=0;let b=`/topic/user/${e.login}/notifications`;p.send(st(at("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:b})));continue}if(k.command==="MESSAGE"){try{e.onNotification(JSON.parse(k.body))}catch(b){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",b)}continue}k.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",k.headers,k.body)}}}),p.on("unexpected-response",(g,h)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${h.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),p.terminate()}),p.on("error",g=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",g.message)}),p.on("close",c)}return l(),{stop(){n=!0,s&&clearTimeout(s),o?.removeAllListeners(),o?.close()}}}function Zo(e,t,r={}){let n=r.startRelay??zo,o=r.onNotification??$o,i=n({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:o});return{stop:()=>i.stop()}}var os=60;async function en(e,t,r){let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let{projectKey:o,taskKey:i,branchPath:s}=n,a=t.timeoutSeconds??os,c=ve({entityType:t.entityType,projectKey:o,taskKey:i,branchPath:s}),l,d=new Promise(g=>{l=setTimeout(()=>g({kind:"timeout"}),a*1e3)}),u=c.promise.then(g=>({kind:"notification",payload:g})),p=await Promise.race([u,d]);return c.cancel(),clearTimeout(l),p.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:p.payload}}}function x(e){if(!(!Array.isArray(e)||e.length===0))for(let t of e){let r=t.severity??"INFO",n=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",o=t.componentId??t.conceptId??"?";console.log(`${n} ${r} [${o}] ${t.message??""}`)}}var Rn=v(require("http")),Fe=require("child_process"),En=require("util");var Ae=v(require("fs")),tn=v(require("os")),we=v(require("path"));function dt(){return we.join(tn.homedir(),".authoring-cli-chrome")}function X(){return we.join(dt(),"profile")}function ns(){return we.join(X(),"Local State")}function rs(){let e=ns();if(!Ae.existsSync(e))return[];let t;try{t=JSON.parse(Ae.readFileSync(e,"utf8"))}catch{return[]}let r=t?.profile?.info_cache??{};return Object.entries(r).map(([n,o])=>({directoryName:n,displayName:typeof o?.name=="string"&&o.name?o.name:n}))}var ct="authoring-cli";function Re(e=rs()){return e.find(r=>r.directoryName===ct)??{directoryName:ct,displayName:ct}}var pn=require("child_process"),mn=require("util"),Pe=v(require("fs")),ft=v(require("os")),Ne=v(require("path"));var on=require("child_process"),nn=require("util"),Ee=v(require("crypto")),V=v(require("fs")),is=(0,nn.promisify)(on.exec);function lt(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}var ss="peanuts";async function rn(e=process.platform){if(e==="darwin"){let{stdout:t}=await is('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return t.trim()}if(e==="linux")return ss;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}var sn=1003,as=1;function an(e){if(e==="darwin")return sn;if(e==="linux")return as;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}function cn(e,t=sn){return Ee.pbkdf2Sync(e,"saltysalt",t,16,"sha1")}function dn(e,t){if(!e)return null;let r=Buffer.from(e,"hex");if(r.length<4)return null;let n=r.subarray(0,3).toString("utf8");if(n!=="v10"&&n!=="v11")return null;let o=Buffer.alloc(16,32),i=r.subarray(3),s;try{let l=Ee.createDecipheriv("aes-128-cbc",t,o);s=Buffer.concat([l.update(i),l.final()])}catch{return null}let a=s.length>32?s.subarray(32):null,c=s;return a&&lt(a)&&!lt(s)&&(c=a),lt(c)?c.toString("utf8"):null}function ut(e,t){V.copyFileSync(e,t);for(let r of["-wal","-shm"]){let n=e+r;V.existsSync(n)&&V.copyFileSync(n,t+r)}}function pt(e){for(let t of[e,e+"-wal",e+"-shm"])try{V.unlinkSync(t)}catch{}}var ln=v(require("fs"));var un=[{path:"/usr/bin/chromium",configDir:"chromium"},{path:"/usr/bin/chromium-browser",configDir:"chromium"},{path:"/usr/bin/google-chrome-stable",configDir:"google-chrome"},{path:"/usr/bin/google-chrome",configDir:"google-chrome"},{path:"/snap/bin/chromium",configDir:"chromium"}],nd=Array.from(new Set(un.map(e=>e.configDir)));function $e(){return un.find(e=>ln.existsSync(e.path))??null}var cs=(0,mn.promisify)(pn.exec),je=class extends Error{},mt=class extends Error{};function fn(e){return Ne.join(X(),e,"Cookies")}function ds(e=process.platform){return e==="linux"?$e()!==null:Pe.existsSync("/Applications/Google Chrome.app")}function ls(e){let t=e.split(".").filter(Boolean),r=[];for(let n=0;n+1<t.length;n++){let o=t.slice(n).join(".");r.push(o,`.${o}`)}return r}function us(e){let t=e?.code;return t==="EPERM"||t==="EACCES"}async function gt(e,t,r,n=process.platform){let o=fn(e);if(!o||!Pe.existsSync(o))return null;let i=Ne.join(ft.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);try{ut(o,i);let s;try{s=await rn(n)}catch{return null}let a=cn(s,an(n)),c=p=>`'${p.replace(/'/g,"''")}'`,d=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${ls(t).map(c).join(", ")}) AND name = ${c(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:u}=await cs(`sqlite3 "${i}" "${d}"`);return dn(u.trim(),a)}catch{return null}finally{pt(i)}}function ps(e){let t=fn(e);if(!Pe.existsSync(t))return null;let r=Ne.join(ft.tmpdir(),`authoring-cli-chrome-cookies-precheck-${process.pid}-${Date.now()}.db`);try{return ut(t,r),null}catch(n){return us(n)?`Cannot read Chrome's cookie file for profile "${e}" at ${t} (permission denied). This is this app's own dedicated directory, not a protected system location \u2014 check its permissions, and that nothing else (an unusual sandboxing setup, a read-only filesystem mount, etc.) is restricting access to it, then try again.`:null}finally{pt(r)}}function ms(e){return new Promise(t=>setTimeout(t,e))}async function gn(e,t={}){let r=t.platform??process.platform,n=t.isChromeInstalled??(()=>ds(r));if(r!=="darwin"&&r!=="linux")throw new je(`Automatic session capture is only supported on macOS or Linux with Chrome/Chromium. Detected platform: ${r}. Use the manual cookie-paste fallback instead.`);if(!n())throw new je(r==="darwin"?"Automatic session capture requires Google Chrome (checked /Applications/Google Chrome.app), but it was not found. Install Chrome, or use the manual cookie-paste fallback instead.":'Automatic session capture requires a Chromium/Chrome binary (checked common Debian install paths), but none was found. Install one (e.g. "apt install chromium" in this proot-distro Debian), or use the manual cookie-paste fallback instead.');let o=t.readCookie??((g,h,y)=>gt(g,h,y,r)),i=t.sleep??ms,s=t.onWarning??(g=>console.error(g)),a=t.checkCookieFileReadable??ps,c=e.pollIntervalMs??750,l=e.timeoutMs??15e3,d=a(e.profileDirectory);d&&s(d);let u=await o(e.profileDirectory,e.host,e.cookieName),p=Date.now()+l;for(;Date.now()<p;){let g=await o(e.profileDirectory,e.host,e.cookieName);if(g&&g!==u)return g;await i(c)}throw new mt(`Timed out after ${l}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host} in Chrome profile "${e.profileDirectory}" \u2014 the one and only profile this command ever reads or writes to. A common cause: sign-in happened in a DIFFERENT, already-open Chrome window/profile instead of the one this command opened \u2014 check that window's profile avatar (top-right corner) reads "${e.profileDirectory}", and that the window actually shows the real IMS login form rather than an unrelated already-signed-in page from another profile. Otherwise use the manual cookie-paste fallback.`)}var Oe=require("child_process"),hn=require("util"),N=v(require("fs")),kn=v(require("net")),Cn=(0,hn.promisify)(Oe.exec),De=1,ae=`:${De}`,fs=["termux-x11","/data/data/com.termux/files/usr/bin/termux-x11"],yt="/data/data/com.termux/files/usr/bin",yn="com.termux.x11",gs=`${yn}/${yn}.MainActivity`,ys="termux-x11-start-app";function ht(e){return`/tmp/.X11-unix/X${e}`}async function hs(){for(let e of fs){if(e.startsWith("/")){if(N.existsSync(e))return e;continue}try{return await Cn(`command -v ${e}`),e}catch{}}return null}function ks(e,t=500){return new Promise(r=>{let n=ht(e);if(!N.existsSync(n)){r(!1);return}let o=kn.createConnection({path:n}),i=s=>{o.removeAllListeners(),o.destroy(),r(s)};o.setTimeout(t),o.once("connect",()=>i(!0)),o.once("error",()=>i(!1)),o.once("timeout",()=>i(!1))})}function Cs(e,t=1e4){let r=Date.now()+t;return new Promise((n,o)=>{let i=()=>{if(N.existsSync(ht(e))){n();return}if(Date.now()>r){o(new Error(`Termux:X11's display socket for :${e} never appeared within ${t}ms`));return}setTimeout(i,100)};i()})}async function Is(){if(!N.existsSync(yt))return;let e=`${yt}/${ys}`,t=`${yt}/bash`,n=`#!${N.existsSync(t)?t:"/bin/sh"}
7
+ am start --user 0 -n ${gs} >/dev/null 2>&1
8
+ `;try{N.writeFileSync(e,n,{mode:493}),N.chmodSync(e,493),await Cn(e,{timeout:5e3})}catch{}}async function In(e=process.platform){if(e!=="linux"||await ks(De))return ae;await Is();let t=await hs();if(t===null)return ae;try{N.unlinkSync(ht(De))}catch{}return(0,Oe.spawn)(t,[ae],{detached:!0,stdio:"ignore"}).unref(),await Cs(De),ae}var D=v(require("fs")),bn=v(require("os")),L=v(require("path"));var ce=class extends Error{},xs="com.ysgao.authoring-cli.chrome-login",Sn="authoring-cli-chrome",bs="/Applications/Google Chrome.app";function Ss(e=bs,t=D.existsSync){let r=L.join(e,"Contents","MacOS","Google Chrome");if(t(r))return r;throw new ce(`No Google Chrome installation found at ${e}. Install Google Chrome to use automatic session capture.`)}function xn(e){return`'${e.replace(/'/g,"'\\''")}'`}function vs(e,t){return["#!/bin/sh","# Generated by authoring-cli. Do not edit \u2014 rewritten on every login launch.","# Flags are baked in deliberately: `open --args` does not reliably reach a script bundle","# executable, and Launch Services drops --args entirely when it hands off to an","# already-running Chrome instead of starting a genuinely new process \u2014 see","# assertLaunchFlagsBaked in chromeWrapperApp.ts.",`exec ${xn(e)} \\`,t.map(r=>` ${xn(r)}`).join(` \\
9
9
  `),""].join(`
10
- `)}function ws(){return`<?xml version="1.0" encoding="UTF-8"?>
10
+ `)}function Ts(){return`<?xml version="1.0" encoding="UTF-8"?>
11
11
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
12
12
  <plist version="1.0">
13
13
  <dict>
14
- <key>CFBundleExecutable</key><string>${vn}</string>
15
- <key>CFBundleIdentifier</key><string>${Ss}</string>
14
+ <key>CFBundleExecutable</key><string>${Sn}</string>
15
+ <key>CFBundleIdentifier</key><string>${xs}</string>
16
16
  <key>CFBundleName</key><string>authoring-cli sign-in</string>
17
17
  <key>CFBundlePackageType</key><string>APPL</string>
18
18
  <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
19
19
  <key>CFBundleShortVersionString</key><string>1.0</string>
20
20
  </dict>
21
21
  </plist>
22
- `}function Rs(e,t){let r=`--profile-directory=${t}`;if(!e.includes(r))throw new le(`Refusing to launch Chrome: its generated launch script is missing ${r}. Launching without it would open a window in whichever profile the user's own Chrome already has active, instead of the dedicated "${t}" profile this command reads/writes cookies for.`)}function Tn(){return[L.join(Fe.homedir(),".authoring-cli","chrome-launcher"),L.join(Fe.tmpdir(),"authoring-cli-chrome-launcher")]}function An(){return`login-${process.pid}.app`}function wn(e){let t=e.chromeBinary??Ts(),r=As(t,e.flags);Rs(r,e.profileDirectory);let n=e.dirCandidates??Tn(),o=[];for(let i of n){let s=L.join(i,An()),a=L.join(s,"Contents","MacOS");try{D.mkdirSync(a,{recursive:!0}),D.writeFileSync(L.join(s,"Contents","Info.plist"),ws());let c=L.join(a,vn);return D.writeFileSync(c,r,{mode:493}),D.chmodSync(c,493),s}catch(c){o.push(`${i}: ${c instanceof Error?c.message:String(c)}`)}}throw new le(`Could not create the Chrome launcher bundle in any candidate directory (${o.join("; ")}).`)}function Rn(e=Tn()){for(let t of e)try{D.rmSync(L.join(t,An()),{recursive:!0,force:!0})}catch{}}var Es=(0,$n.promisify)(Le.exec);function It(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}var $s=["--no-sandbox","--password-store=basic","--force-device-scale-factor=2"],jn=["--no-first-run","--no-default-browser-check"];async function js(e,t){let r=ae();if(!r)throw new Error('No Chromium/Chrome binary found (checked common Debian install paths). Install one (e.g. "apt install chromium" in this proot-distro Debian) and try again.');let n=process.env.DISPLAY||await bn();(0,Le.spawn)(r.path,[...jn,...$s,`--profile-directory=${t}`,e],{detached:!0,stdio:"ignore",env:{...process.env,DISPLAY:n}}).unref()}async function Ps(e,t){let r=[`--profile-directory=${t}`,...jn,e],n=wn({flags:r,profileDirectory:t});await Es(`open -n -a ${(i=>`'${i.replace(/'/g,"'\\''")}'`)(n)}`),Rn()}function Ns(e,t,r){return r==="linux"?js(e,t):Ps(e,t)}function Ds(){return`<!DOCTYPE html>
22
+ `}function As(e,t){let r=[];if(e.includes(`--profile-directory=${t}`)||r.push(`--profile-directory=${t}`),e.includes("--user-data-dir=")||r.push("--user-data-dir="),r.length>0)throw new ce(`Refusing to launch Chrome: its generated launch script is missing ${r.join(" and ")}. Launching without them would open a window in whichever profile the user's own Chrome already has active, instead of the dedicated "${t}" profile this command reads/writes cookies for.`)}function vn(){return[L.join(dt(),"launcher"),L.join(bn.tmpdir(),"authoring-cli-chrome-launcher")]}function Tn(){return`login-${process.pid}.app`}function An(e){let t=e.chromeBinary??Ss(),r=vs(t,e.flags);As(r,e.profileDirectory);let n=e.dirCandidates??vn(),o=[];for(let i of n){let s=L.join(i,Tn()),a=L.join(s,"Contents","MacOS");try{D.mkdirSync(a,{recursive:!0}),D.writeFileSync(L.join(s,"Contents","Info.plist"),Ts());let c=L.join(a,Sn);return D.writeFileSync(c,r,{mode:493}),D.chmodSync(c,493),s}catch(c){o.push(`${i}: ${c instanceof Error?c.message:String(c)}`)}}throw new ce(`Could not create the Chrome launcher bundle in any candidate directory (${o.join("; ")}).`)}function wn(e=vn()){for(let t of e)try{D.rmSync(L.join(t,Tn()),{recursive:!0,force:!0})}catch{}}var ws=(0,En.promisify)(Fe.exec);function kt(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}var Rs=["--no-sandbox","--password-store=basic","--force-device-scale-factor=2"],$n=["--no-first-run","--no-default-browser-check"];async function Es(e,t){let r=$e();if(!r)throw new Error('No Chromium/Chrome binary found (checked common Debian install paths). Install one (e.g. "apt install chromium" in this proot-distro Debian) and try again.');let n=process.env.DISPLAY||await In();(0,Fe.spawn)(r.path,[...$n,...Rs,`--user-data-dir=${X()}`,`--profile-directory=${t}`,e],{detached:!0,stdio:"ignore",env:{...process.env,DISPLAY:n}}).unref()}async function $s(e,t){let r=[`--user-data-dir=${X()}`,`--profile-directory=${t}`,...$n,e],n=An({flags:r,profileDirectory:t});await ws(`open -n -a ${(i=>`'${i.replace(/'/g,"'\\''")}'`)(n)}`),wn()}function js(e,t,r){return r==="linux"?Es(e,t):$s(e,t)}function Ps(){return`<!DOCTYPE html>
23
23
  <html>
24
24
  <head>
25
25
  <meta charset="utf-8">
@@ -30,20 +30,20 @@ am start --user 0 -n ${hs} >/dev/null 2>&1
30
30
  <h3>You're signed in.</h3>
31
31
  <p>Return to your terminal \u2014 the CLI is finishing sign-in automatically. You can close this tab.</p>
32
32
  </body>
33
- </html>`}function Pn(e,t={}){let r=e.cookieName??It(e.host),n=t.platform??process.platform,o=t.openChrome??((l,d)=>Ns(l,d,n)),i=t.resolveProfile??$e,s=t.captureCookie??hn,a=e.timeoutMs??12e4,c=i();return new Promise((l,d)=>{let u=!1,p=h=>{u||(u=!0,g.close(),h())},g=En.createServer((h,y)=>{if((h.url||"/").split("?")[0]==="/callback"){y.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),y.end(Ds());return}y.writeHead(404),y.end()});g.listen(0,"127.0.0.1",()=>{let y=`http://localhost:${g.address().port}/callback`,k=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(y)}`;(async()=>{try{await o(k,c.directoryName);let b=await s({profileDirectory:c.directoryName,host:e.host,cookieName:r,timeoutMs:a});p(()=>l({cookie:`${r}=${b}`}))}catch(b){p(()=>d(b))}})()}),g.on("error",h=>p(()=>d(h)))})}var O=v(require("fs")),pe=v(require("path")),Nn="AUTHORING_CLI_HOME";function Os(){return pe.join(process.cwd(),".authoring-cli")}function Fs(){let e=process.env[Nn];return e&&e.trim()!==""?pe.resolve(e):null}function Ke(){return Fs()??Os()}function ue(e){return pe.join(e,"session.json")}function xt(){let e=ue(Ke());if(!O.existsSync(e))return null;let t=O.readFileSync(e,"utf8");return JSON.parse(t)}function Me(e){let t=Ke(),r={...e,updatedAt:new Date().toISOString()};try{O.mkdirSync(t,{recursive:!0,mode:448}),O.writeFileSync(ue(t),JSON.stringify(r,null,2),{mode:384})}catch(n){let o=n?.code;throw o==="EPERM"||o==="EACCES"?new Error(`Couldn't write the session to ${ue(t)} (${o}): the current directory isn't writable. Run authoring-cli from a writable directory, or set ${Nn} to an explicit, writable location.`):n}}function Dn(){let e=ue(Ke());O.existsSync(e)&&O.unlinkSync(e)}function bt(){return ue(Ke())}function Q(e){let t=xt();if(!t)throw new Error('Not signed in \u2014 run "login" first.');Me({...t,currentTask:e})}async function Ls(e,t,r,n){let o=await ht(n,t,r).catch(()=>null);if(!o)return null;let i=`${r}=${o}`,s=await Ge(e,i).catch(()=>null);return s?{cookie:i,account:s}:null}function On(e){let t=e?.displayName??e?.login;return t?`Signed in as ${t}.`:"Signed in. (Could not confirm account details \u2014 proceed with caution.)"}function Fn(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:n,explicit:o,source:i}of e)console.log(` ${(n+":").padEnd(t+2)}${r} (${o?"from flag":i})`)}async function Ln(e){let t=e.environment?jt(e.environment):te;if(!t){console.error(`Unknown environment: ${e.environment}
34
- Expected one of: ${ye.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=J[t],n=e.imsEndpoint||r.imsEndpoint,o=e.terminologyServerEndpoint||r.terminologyServerEndpoint,i=e.authoringServicesEndpoint||r.authoringServicesEndpoint,s;try{s=new URL(n).hostname}catch{console.error(`Invalid --ims-endpoint: ${n}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||It(s),l=t===te&&!e.environment?`${t}, default`:t,d=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:i,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(y=>({...y,source:l})),u=$e(),p=await Ls(n,s,c,u.directoryName);if(p){Me({cookie:p.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:p.account,currentTask:null}),console.log(`${On(p.account)} (reused an existing Chrome session in profile "${u.directoryName}" \u2014 no browser opened.)`),Fn(d),console.log(` Session: ${bt()}`);return}console.log(`Opening Chrome (profile "${u.directoryName}") to sign in to ${n} ...`),console.log(` This is a separate, dedicated Chrome profile for authoring-cli, isolated from your everyday browsing profile \u2014 it opens its own window and (the first time) starts out NOT signed in, even if another Chrome window/profile already is. Sign in inside THAT new window \u2014 check its profile avatar (top-right) reads "${u.directoryName}" \u2014 not whichever Chrome window happened to already be in front.`);let g;try{g=await Pn({imsEndpoint:n,host:s,cookieName:c})}catch(y){console.error(y instanceof Error?y.message:String(y)),process.exitCode=1;return}if(!g){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let h=await Ge(n,g.cookie).catch(()=>null);Me({cookie:g.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:h,currentTask:null}),console.log(On(h)),Fn(d),console.log(` Session: ${bt()}`)}async function Kn(){Dn(),console.log("Signed out.")}var _e=v(require("fs")),Be=v(require("path"));async function Mn(){let e=[Be.join(__dirname,"../../HELP.md"),Be.join(__dirname,"../HELP.md"),Be.join(process.cwd(),"HELP.md")];for(let t of e)try{if(_e.existsSync(t)){let r=_e.readFileSync(t,"utf8");console.log(r);return}}catch{}console.error("Could not locate HELP.md."),console.log(""),console.log("For help, see the README:"),console.log(" npm view authoring-cli readme"),console.log(""),console.log("Or visit: https://github.com/snomed/authoring-cli"),process.exit(1)}function m(){let e=xt();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function f(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,onLog:t=>console.error(t)}}function Bn(e){return e.projectKey??e.key??"?"}async function _n(e){let t=m(),r=f(t),n=await Vo(r);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log("No projects available.");return}let o=Math.max(...n.map(i=>Bn(i).length))+1;for(let i of n){let s=i.title??"";console.log(`${Bn(i).padEnd(o)}${s?`"${s}"`:""}`)}}function Ue(e){return e.taskKey??e.key??"?"}function Un(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Ks(e){return e.projectKey||Ue(e).split("-")[0]||"?"}function St(e,t){let r=new Map;for(let n of e){let o=t(n);r.set(o,(r.get(o)??0)+1)}return[...r].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0]))}function vt(e,t){let r=Math.max(...t.map(([o])=>o.length)),n=Math.max(...t.map(([,o])=>String(o).length));console.log(""),console.log(`${e}:`);for(let[o,i]of t)console.log(` ${o.padEnd(r)} ${String(i).padStart(n)}`)}async function Vn(e){let t=m(),r=f(t),n=e.mine||!e.project,o=n?await Jo(r):await qo(r,e.project);if(n&&e.project){let d=e.project.toLowerCase();o=o.filter(u=>(u.projectKey??"").toLowerCase()===d||Ue(u).toLowerCase().startsWith(`${d}-`))}if(e.status){let d=e.status.trim().toLowerCase();o=o.filter(u=>(u.status??"").toLowerCase()===d)}let i=St(o,Ks),s=St(o,Un),a=St(o,d=>d.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:o.length,byProject:Object.fromEntries(i),byAssignee:Object.fromEntries(s),byStatus:Object.fromEntries(a)}:o,null,2));return}let c=[n?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(o.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${o.length} task${o.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),i.length>1&&vt("By project",i),!n&&s.length>1&&vt("By assignee",s),a.length>1&&vt("By status",a);return}let l=Math.max(...o.map(d=>Ue(d).length))+1;for(let d of o){let u=d.summary??d.title??"",p=d.status?` status=${d.status}`:"",g=n?"":` [${Un(d)}]`;console.log(`${Ue(d).padEnd(l)}${u?`"${u}"`:""}${p}${g}`)}}async function qn(e){let t=m(),r=f(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,i=await Go(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:o});if(!i.task){console.error(i.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let s=i.task,a=s.key??s.taskKey,c=s.branchPath;if(e.json)console.log(JSON.stringify(s,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${s.summary??e.summary}"${s.status?` status=${s.status}`:""}`),c&&console.log(` branch: ${c}`);let l=s.assignee?.displayName??s.assignee?.username;console.log(` assignee: ${l??"unassigned"}`)}if(c){let l=await Y(r,c);if(!l.ok){console.error(`Task created, but its branch could not be prepared: ${l.error}`),process.exitCode=1;return}l.created&&!e.json&&console.log(` created branch ${c}`)}if(!e.noSelect){if(!a||!c){console.error("Task created, but it could not be selected (no key/branchPath in the response) \u2014 use select-task."),process.exitCode=1;return}Q({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function Jn(e){let t=m(),r=f(t);if(!e.task){let i=await Ho(r,e.project);if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${i.length} deleted task${i.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let s of i){let a=s.assignee?.displayName??s.assignee?.username??"unassigned";console.log(` ${s.key} "${s.summary??""}" [${a}]`)}return}let n=await Yo(r,{projectKey:e.project,taskKey:e.task});if(n.error){console.error(n.error),process.exitCode=1;return}if(n.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${n.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${n.task?.status??"In Progress"})`);let o=n.task?.branchPath;if(o){let i=await Y(r,o);if(!i.ok){console.error(`Task recovered, but its branch could not be prepared: ${i.error}`),process.exitCode=1;return}console.log(i.created?` created branch ${o}`:` branch ${o} still holds its content`)}e.noSelect||!o||(Q({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function Gn(e){let t=m(),r=f(t),n=await _(r,e.project,e.task);if(!n||!n.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let o=await Y(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}Q({projectKey:e.project,taskKey:e.task,branchPath:n.branchPath}),console.log(`\u2713 Current task set to ${e.project}/${e.task} (${n.branchPath})`),o.created&&console.log(` created branch ${n.branchPath}`)}async function Hn(e){let t=m();if(!t.currentTask){console.log('No task currently selected. Run "select-task", or pass --project/--task explicitly to any command.');return}let{projectKey:r,taskKey:n,branchPath:o}=t.currentTask;console.log(`Current task: ${r}/${n} (${o})`),(e.project||e.task)&&((!e.project||e.project===r)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function Yn(e){let t=m(),r=f(t),n=await Mt(r,{fsn:e.fsn,semanticTag:e.tag,preferredTerm:e.pt,parentConceptId:e.parent,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300&&o.conceptId){console.log(`Created concept ${o.conceptId}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Wn(e){let t=m(),r=f(t),n={term:e.term,ecl:e.ecl,active:e.active!==void 0?e.active==="true":void 0,limit:e.limit?Number(e.limit):void 0,projectKey:e.project,taskKey:e.task},o=e.checkStatedParentsDefinitionStatus?await wo(r,n,t.currentTask):await Ce(r,n,t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to search concepts (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function Xn(e){let t=m(),r=f(t),n=await ke(r,{conceptId:e.id,attributeType:e.attributeType,gci:e.gci,descriptions:e.descriptions,descriptionFull:e.descriptionFull,axioms:e.axioms,inferred:e.inferred,gciAxiomsCount:e.gciAxiomsCount,full:e.full,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to get concept (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function Qn(e){let t=m(),r=f(t),n=await _t(r,{conceptId:e.id,stated:e.stated,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):void 0,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to find references (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function zn(e){let t=m(),r=f(t),n=await Te(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to validate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}let i=o.validationResults;if(!Array.isArray(i)||i.length===0){console.log(`No validation issues for concept ${e.id}.`);return}x(i),o.hasErrors&&(process.exitCode=1)}async function Zn(e){let t=m(),r=f(t),n=e.checkStatedParentsDefinitionStatus?await $o(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await B(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to list concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function er(e){let t=m(),r=f(t),n=await jo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${n.statusCode}): ${o.error??JSON.stringify(o)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(n.body,null,2)),o.summary&&(o.summary.withIssues>0||o.summary.failed>0)&&(process.exitCode=1);return}let i=o.results??[],s=o.summary;if(i.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of i){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),x(a.validationResults)}if(s){console.log("");let a=[`${s.validated} validated`,`${s.clean} clean`,`${s.withIssues} with issues`];s.skippedDeleted&&a.push(`${s.skippedDeleted} skipped (deleted on this branch)`),s.failed&&a.push(`${s.failed} failed`),console.log(a.join(", ")+".")}s&&(s.withIssues>0||s.failed>0)&&(process.exitCode=1)}async function tr(e){let t=m(),r=f(t),n=await Uo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to fetch concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function or(e){let t=m(),r=f(t),n=await to(r,{conceptId:e.id,term:e.term,type:e.type,semanticTag:e.tag,moduleId:e.module,acceptability:e.acceptability,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added ${e.type} description to concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function nr(e){let t=m(),r=f(t),n=await oo(r,{conceptId:e.id,typeId:e.type,targetId:e.target,groupId:e.group?Number(e.group):void 0,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added relationship (${e.type} -> ${e.target}) to concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function rr(e){let t=m(),r=f(t),n=await So(r,{conceptId:e.id,axiomId:e.axiomId,relationshipId:e.relationshipId,relationshipIndex:e.relationshipIndex?Number(e.relationshipIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function ir(e){let t;try{t=JSON.parse(e.attributes)}catch(a){console.error(`--attributes must be valid JSON (an array of {"typeId":"...","targetId":"..."} objects): ${a.message}`),process.exitCode=1;return}let r=m(),n=f(r),o=await vo(n,{conceptId:e.id,axiomId:e.axiomId,attributes:t,groupId:e.groupId!=null&&e.groupId!==""?Number(e.groupId):void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function sr(e){let t=m(),r=f(t),n=await io(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function ar(e){let t=m(),r=f(t),n=await so(r,{conceptId:e.id,descriptionId:e.descriptionId,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set case significance of description ${e.descriptionId} to ${e.caseSignificance}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set case significance (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function cr(e){let t=m(),r=f(t);if(e.entries){let s;try{s=JSON.parse(e.entries)}catch(d){console.error(`--entries is not valid JSON: ${d.message}`),process.exitCode=1;return}if(!Array.isArray(s)||s.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await uo(r,{conceptId:e.id,entries:s,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${s.length} description(s) on concept ${e.id}`),x(c.validationResults);return}let l=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${l}`),process.exitCode=1;return}if(!e.descriptionId){console.error("Either --description-id (with --lang/--us/--gb) or --entries is required."),process.exitCode=1;return}let n=await lo(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){let s=[e.lang?`lang=${e.lang}`:void 0,e.us?`us=${e.us}`:void 0,e.gb?`gb=${e.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${e.descriptionId} (${s.join(", ")})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function dr(e){let t=m(),r=f(t),n=await ro(r,{conceptId:e.id,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function lr(e){let t=m(),r=f(t),n=await no(r,{conceptId:e.id,status:e.status,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set definition status of concept ${e.id} to ${e.status}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set definition status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function ur(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=m(),n=f(r),o=await Ze(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function pr(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=m(),n=f(r),o=await ho(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update GCI axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function mr(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=m(),n=f(r),o=await Co(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.gciAxioms)?i.gciAxioms.map(l=>l.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function fr(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=m(),n=f(r),o=await ko(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.classAxioms)?i.classAxioms.map(l=>l.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function gr(e){let t=m(),r=f(t),n=await Ro(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function yr(e){let t=m(),r=f(t),n=await po(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function hr(e){let t=m(),r=f(t),n=await mo(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function kr(e){let t=m(),r=f(t),n=await fo(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to restore description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Cr(e){let t=m(),r=f(t),n=await yo(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,semanticTag:e.tag,indicator:e.indicator,associationTargetId:e.associationTarget,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to replace FSN (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Ir(e){let t=m(),r=f(t),n=await go(r,{conceptId:e.id,descriptionId:e.descriptionId,reason:e.reason,targetId:e.targetId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set inactivation reason ${e.reason} on description ${e.descriptionId} (concept ${e.id})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set description inactivation reason (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function xr(e){let t=m(),r=f(t),n=await Io(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function br(e){let t=m(),r=f(t),n=await xo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Sr(e){let t=m(),r=f(t),n=await be(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){if(o.alreadyConformed)console.log(`Concept ${e.id}'s axiom${o.axiomId?` ${o.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(o.replacedAxiomId){let s=Array.isArray(o.addResult?.classAxioms)?o.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=s.length>0?s[s.length-1]:void 0;console.log(`Transformed concept ${e.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${o.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to transform axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function vr(e){let t=m(),r=f(t),n=await Se(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}if(o.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${o.axiomId}) \u2014 a stated Is-a targets a fully-defined concept; run transform-axiom to fix.`),process.exitCode=1;return}console.log(`Concept ${e.id}: stated Is-a targets are all primitive (axiom ${o.axiomId}) \u2014 ${o.message}`)}async function Tr(e){let t=m(),r=f(t),n=await To(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Ar(e){let t=m(),r=f(t),n=await Ao(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}function z(e){let t=e.account?.login;return t?tn(f(e),t):(console.error("[authoring-cli] no login resolved from the signed-in account \u2014 notifications will only arrive via polling fallback, not a live push."),null)}async function wr(e){let t=m(),r=f(t),n=z(t),o;try{o=await we(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?(console.log(`Classification ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),i.details&&console.log(JSON.stringify(i.details,null,2)),i.save&&(i.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${i.save.error?`: ${i.save.error}`:""}${i.save.status?` (status: ${i.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${i.jobId} (${i.status})`),i.timedOut&&(process.exitCode=1);return}let s=i.details!==void 0?` \u2014 details: ${JSON.stringify(i.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}${s}`),process.exitCode=1}async function Rr(e){let t=m(),r=f(t),n=await Ko(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check classification status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Er(e){let t=m(),r=f(t),n=z(t),o;try{o=await Bo(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?console.log(`Validation ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),i.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}`),process.exitCode=1}async function $r(e){let t=m(),r=f(t),n=await Mo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check validation status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function jr(e){let t=m(),r=f(t),n=z(t);try{let o=await on(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),i=o.body;if(o.statusCode<200||o.statusCode>=300){let s=i.error?i.error:JSON.stringify(i);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),i.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var wt=v(require("os")),Z=v(require("path"));var T=v(require("fs")),Tt=v(require("os")),S=v(require("path")),$="authoring-cli",F=["claude","codex"];function Ve(e){let t=[S.resolve(e,"..","skills",$),S.resolve(e,"..","..","skills",$)];for(let r of t)if(T.existsSync(S.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${$}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function Ms(e){let t=[];return T.existsSync(S.join(e,".claude"))&&t.push("claude"),T.existsSync(S.join(e,".codex"))&&t.push("codex"),t}function me(e,t){if(e==="all")return[...F];if(e){let n=e.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean),o=n.filter(i=>!F.includes(i));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${F.join(", ")}, all.`);return n}let r=Ms(t);return r.length?r:["claude"]}var Nr="# authoring-cli \u2014 SNOMED CT authoring guidance";function Bs(e){let t=S.join(e,"SKILL.md"),r=S.join(e,"references","batch-authoring.md");return[Nr,"",`Read \`${t}\` now, and follow it for the rest of this session whenever you run the`,"`authoring-cli` command \u2014 before any concept creation, description/acceptability edit,","relationship or axiom edit, `classify`, or `validate-task`. It documents server-side","constraints and async behavior that fail or mislead in non-obvious ways, so reading it after","a command has already failed is too late.","",`Also read \`${r}\` when the task is a large, multi-session batch (tens to thousands of`,"concepts generated from a source list).","","Both files live inside the installed `authoring-cli` npm package, so they stay in step with","the CLI itself. If the paths above no longer exist, the package moved or was upgraded to a","different location \u2014 re-run `authoring-cli install-skill` to refresh this prompt.",""].join(`
35
- `)}function qe(e){try{return S.resolve(S.dirname(e),T.readlinkSync(e))}catch{return null}}function fe(e){try{return T.lstatSync(e)}catch{return null}}function At(e){let t=qe(e);return t?T.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:fe(e)?.isDirectory()?"an existing directory":"an existing file"}function Dr(e){let t=qe(e);return t!==null&&S.basename(t)===$&&S.basename(S.dirname(t))==="skills"}function Or(e){if(!fe(e)?.isFile())return!1;try{return T.readFileSync(e,"utf8").startsWith(Nr)}catch{return!1}}function Pr(e){return T.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>S.relative(e,S.join(t.parentPath,t.name))).sort()}function Fr(e,t){if(!t||!T.existsSync(t))return!1;try{let r=Pr(t);return r.join(`
36
- `)!==Pr(e).join(`
37
- `)?!1:r.every(n=>T.readFileSync(S.join(e,n)).equals(T.readFileSync(S.join(t,n))))}catch{return!1}}function _s(e,t,r){let n=e.project?S.join(r,".claude","skills"):S.join(t,".claude","skills"),o=S.join(n,$),i=e.shippedSkillDir,s=e.project&&i.startsWith(r+S.sep)?S.relative(S.dirname(o),i):i,a=fe(o),c=!1;if(a){let l=qe(o);if(l===i&&T.existsSync(l))return{agent:"claude",path:o,status:"already-current",kind:"symlink",detail:i};if(!(Dr(o)||Fr(o,i))&&!e.force)return{agent:"claude",path:o,status:"blocked",kind:"symlink",detail:At(o)};T.rmSync(o,{recursive:!0,force:!0}),c=!0}T.mkdirSync(n,{recursive:!0});try{return T.symlinkSync(s,o,"dir"),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"symlink",detail:s}}catch(l){let d=l.code;if(d!=="EPERM"&&d!=="EACCES")throw l;return T.cpSync(i,o,{recursive:!0}),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"copy",detail:"symlinks unavailable on this platform \u2014 copied instead; re-run install-skill after upgrading the CLI"}}}function Us(e,t){let r=S.join(t,".codex","prompts"),n=S.join(r,`${$}.md`),o=Bs(e.shippedSkillDir),i=fe(n),s=!1;if(i){if((i.isFile()?T.readFileSync(n,"utf8"):null)===o)return{agent:"codex",path:n,status:"already-current",kind:"pointer"};if(!Or(n)&&!e.force)return{agent:"codex",path:n,status:"blocked",kind:"pointer",detail:At(n)};T.rmSync(n,{recursive:!0,force:!0}),s=!0}return T.mkdirSync(r,{recursive:!0}),T.writeFileSync(n,o,"utf8"),{agent:"codex",path:n,status:s?"replaced":"installed",kind:"pointer"}}function Lr(e){let t=e.homeDir??Tt.homedir(),r=e.cwd??process.cwd();return(e.agents??me(void 0,t)).map(o=>o==="claude"?_s(e,t,r):Us(e,t))}function Kr(e){let t=e.homeDir??Tt.homedir(),r=e.cwd??process.cwd();return e.agents.map(n=>{let o=n==="claude"?S.join(e.project?S.join(r,".claude"):S.join(t,".claude"),"skills",$):S.join(t,".codex","prompts",`${$}.md`);if(!fe(o))return{agent:n,path:o,status:"not-registered"};if(!(n==="claude"?Dr(o)||Fr(o,e.shippedSkillDir):Or(o))&&!e.force)return{agent:n,path:o,status:"left-alone",detail:`${At(o)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let s=qe(o)??void 0;return T.rmSync(o,{recursive:!0,force:!0}),{agent:n,path:o,status:"removed",detail:s}})}function Mr(e){let t=wt.homedir();return e===t||e.startsWith(t+Z.sep)?Z.join("~",Z.relative(t,e)):e}function Vs(e){let t=Mr(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${Mr(e.detail??"")})`:e.kind==="copy"?`${t} (copy \u2014 ${e.detail})`:`${t} (pointer into the installed package)`;case"already-current":return`${t} (already registered \u2014 nothing to do)`;case"blocked":return`${t} NOT written \u2014 ${e.detail} is in the way; re-run with --force to replace it`}}async function Br(e){let t=Ve(__dirname),r=me(e.agent,wt.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let n=Lr({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),o=n.filter(a=>a.status==="installed"||a.status==="replaced"),i=n.filter(a=>a.status==="blocked");console.log(o.length?`Installed skill '${$}' for:`:i.length?`Could not install skill '${$}':`:`Skill '${$}' is already registered:`);for(let a of n)console.log(` ${a.agent.padEnd(7)} ${Vs(a)}`);if(e.project&&r.includes("claude")&&console.log(`
33
+ </html>`}function jn(e,t={}){let r=e.cookieName??kt(e.host),n=t.platform??process.platform,o=t.openChrome??((l,d)=>js(l,d,n)),i=t.resolveProfile??Re,s=t.captureCookie??gn,a=e.timeoutMs??12e4,c=i();return new Promise((l,d)=>{let u=!1,p=h=>{u||(u=!0,g.close(),h())},g=Rn.createServer((h,y)=>{if((h.url||"/").split("?")[0]==="/callback"){y.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),y.end(Ps());return}y.writeHead(404),y.end()});g.listen(0,"127.0.0.1",()=>{let y=`http://localhost:${g.address().port}/callback`,k=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(y)}`;(async()=>{try{await o(k,c.directoryName);let b=await s({profileDirectory:c.directoryName,host:e.host,cookieName:r,timeoutMs:a});p(()=>l({cookie:`${r}=${b}`}))}catch(b){p(()=>d(b))}})()}),g.on("error",h=>p(()=>d(h)))})}var O=v(require("fs")),le=v(require("path")),Pn="AUTHORING_CLI_HOME";function Ns(){return le.join(process.cwd(),".authoring-cli")}function Ds(){let e=process.env[Pn];return e&&e.trim()!==""?le.resolve(e):null}function Le(){return Ds()??Ns()}function de(e){return le.join(e,"session.json")}function Ct(){let e=de(Le());if(!O.existsSync(e))return null;let t=O.readFileSync(e,"utf8");return JSON.parse(t)}function Ke(e){let t=Le(),r={...e,updatedAt:new Date().toISOString()};try{O.mkdirSync(t,{recursive:!0,mode:448}),O.writeFileSync(de(t),JSON.stringify(r,null,2),{mode:384})}catch(n){let o=n?.code;throw o==="EPERM"||o==="EACCES"?new Error(`Couldn't write the session to ${de(t)} (${o}): the current directory isn't writable. Run authoring-cli from a writable directory, or set ${Pn} to an explicit, writable location.`):n}}function Nn(){let e=de(Le());O.existsSync(e)&&O.unlinkSync(e)}function It(){return de(Le())}function Q(e){let t=Ct();if(!t)throw new Error('Not signed in \u2014 run "login" first.');Ke({...t,currentTask:e})}async function Os(e,t,r,n){let o=await gt(n,t,r).catch(()=>null);if(!o)return null;let i=`${r}=${o}`,s=await Ge(e,i).catch(()=>null);return s?{cookie:i,account:s}:null}function Dn(e){let t=e?.displayName??e?.login;return t?`Signed in as ${t}.`:"Signed in. (Could not confirm account details \u2014 proceed with caution.)"}function On(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:n,explicit:o,source:i}of e)console.log(` ${(n+":").padEnd(t+2)}${r} (${o?"from flag":i})`)}async function Fn(e){let t=e.environment?Et(e.environment):te;if(!t){console.error(`Unknown environment: ${e.environment}
34
+ Expected one of: ${fe.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=G[t],n=e.imsEndpoint||r.imsEndpoint,o=e.terminologyServerEndpoint||r.terminologyServerEndpoint,i=e.authoringServicesEndpoint||r.authoringServicesEndpoint,s;try{s=new URL(n).hostname}catch{console.error(`Invalid --ims-endpoint: ${n}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||kt(s),l=t===te&&!e.environment?`${t}, default`:t,d=[{url:n,label:"IMS",explicit:!!e.imsEndpoint},{url:o,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:i,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(y=>({...y,source:l})),u=Re(),p=await Os(n,s,c,u.directoryName);if(p){Ke({cookie:p.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:p.account,currentTask:null}),console.log(`${Dn(p.account)} (reused an existing Chrome session in profile "${u.directoryName}" \u2014 no browser opened.)`),On(d),console.log(` Session: ${It()}`);return}console.log(`Opening Chrome (profile "${u.directoryName}") to sign in to ${n} ...`),console.log(` This is a separate, dedicated Chrome profile for authoring-cli, isolated from your everyday browsing profile \u2014 it opens its own window and (the first time) starts out NOT signed in, even if another Chrome window/profile already is. Sign in inside THAT new window \u2014 check its profile avatar (top-right) reads "${u.directoryName}" \u2014 not whichever Chrome window happened to already be in front.`);let g;try{g=await jn({imsEndpoint:n,host:s,cookieName:c})}catch(y){console.error(y instanceof Error?y.message:String(y)),process.exitCode=1;return}if(!g){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let h=await Ge(n,g.cookie).catch(()=>null);Ke({cookie:g.cookie,imsEndpoint:n,terminologyServerEndpoint:o,authoringServicesEndpoint:i,account:h,currentTask:null}),console.log(Dn(h)),On(d),console.log(` Session: ${It()}`)}async function Ln(){Nn(),console.log("Signed out.")}var Be=v(require("fs")),Me=v(require("path"));async function Kn(){let e=[Me.join(__dirname,"../../HELP.md"),Me.join(__dirname,"../HELP.md"),Me.join(process.cwd(),"HELP.md")];for(let t of e)try{if(Be.existsSync(t)){let r=Be.readFileSync(t,"utf8");console.log(r);return}}catch{}console.error("Could not locate HELP.md."),console.log(""),console.log("For help, see the README:"),console.log(" npm view authoring-cli readme"),console.log(""),console.log("Or visit: https://github.com/snomed/authoring-cli"),process.exit(1)}function m(){let e=Ct();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function f(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,onLog:t=>console.error(t)}}function Mn(e){return e.projectKey??e.key??"?"}async function Bn(e){let t=m(),r=f(t),n=await _o(r);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log("No projects available.");return}let o=Math.max(...n.map(i=>Mn(i).length))+1;for(let i of n){let s=i.title??"";console.log(`${Mn(i).padEnd(o)}${s?`"${s}"`:""}`)}}function _e(e){return e.taskKey??e.key??"?"}function _n(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Fs(e){return e.projectKey||_e(e).split("-")[0]||"?"}function xt(e,t){let r=new Map;for(let n of e){let o=t(n);r.set(o,(r.get(o)??0)+1)}return[...r].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0]))}function bt(e,t){let r=Math.max(...t.map(([o])=>o.length)),n=Math.max(...t.map(([,o])=>String(o).length));console.log(""),console.log(`${e}:`);for(let[o,i]of t)console.log(` ${o.padEnd(r)} ${String(i).padStart(n)}`)}async function Un(e){let t=m(),r=f(t),n=e.mine||!e.project,o=n?await Vo(r):await Uo(r,e.project);if(n&&e.project){let d=e.project.toLowerCase();o=o.filter(u=>(u.projectKey??"").toLowerCase()===d||_e(u).toLowerCase().startsWith(`${d}-`))}if(e.status){let d=e.status.trim().toLowerCase();o=o.filter(u=>(u.status??"").toLowerCase()===d)}let i=xt(o,Fs),s=xt(o,_n),a=xt(o,d=>d.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:o.length,byProject:Object.fromEntries(i),byAssignee:Object.fromEntries(s),byStatus:Object.fromEntries(a)}:o,null,2));return}let c=[n?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(o.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${o.length} task${o.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),i.length>1&&bt("By project",i),!n&&s.length>1&&bt("By assignee",s),a.length>1&&bt("By status",a);return}let l=Math.max(...o.map(d=>_e(d).length))+1;for(let d of o){let u=d.summary??d.title??"",p=d.status?` status=${d.status}`:"",g=n?"":` [${_n(d)}]`;console.log(`${_e(d).padEnd(l)}${u?`"${u}"`:""}${p}${g}`)}}async function Vn(e){let t=m(),r=f(t),n=t.account?.login??t.account?.username,o=e.unassigned?void 0:e.assignee||n,i=await qo(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:o});if(!i.task){console.error(i.error??`Failed to create task in ${e.project}.`),process.exitCode=1;return}let s=i.task,a=s.key??s.taskKey,c=s.branchPath;if(e.json)console.log(JSON.stringify(s,null,2));else{console.log(`\u2713 Created task ${e.project}/${a} "${s.summary??e.summary}"${s.status?` status=${s.status}`:""}`),c&&console.log(` branch: ${c}`);let l=s.assignee?.displayName??s.assignee?.username;console.log(` assignee: ${l??"unassigned"}`)}if(c){let l=await Y(r,c);if(!l.ok){console.error(`Task created, but its branch could not be prepared: ${l.error}`),process.exitCode=1;return}l.created&&!e.json&&console.log(` created branch ${c}`)}if(!e.noSelect){if(!a||!c){console.error("Task created, but it could not be selected (no key/branchPath in the response) \u2014 use select-task."),process.exitCode=1;return}Q({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function qn(e){let t=m(),r=f(t);if(!e.task){let i=await Go(r,e.project);if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(`No deleted tasks in ${e.project}.`);return}console.log(`${i.length} deleted task${i.length===1?"":"s"} in ${e.project} \u2014 pass --task <key> to recover one:`);for(let s of i){let a=s.assignee?.displayName??s.assignee?.username??"unassigned";console.log(` ${s.key} "${s.summary??""}" [${a}]`)}return}let n=await Jo(r,{projectKey:e.project,taskKey:e.task});if(n.error){console.error(n.error),process.exitCode=1;return}if(n.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${n.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${n.task?.status??"In Progress"})`);let o=n.task?.branchPath;if(o){let i=await Y(r,o);if(!i.ok){console.error(`Task recovered, but its branch could not be prepared: ${i.error}`),process.exitCode=1;return}console.log(i.created?` created branch ${o}`:` branch ${o} still holds its content`)}e.noSelect||!o||(Q({projectKey:e.project,taskKey:e.task,branchPath:o}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function Gn(e){let t=m(),r=f(t),n=await _(r,e.project,e.task);if(!n||!n.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let o=await Y(r,n.branchPath);if(!o.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${o.error}`),process.exitCode=1;return}Q({projectKey:e.project,taskKey:e.task,branchPath:n.branchPath}),console.log(`\u2713 Current task set to ${e.project}/${e.task} (${n.branchPath})`),o.created&&console.log(` created branch ${n.branchPath}`)}async function Jn(e){let t=m();if(!t.currentTask){console.log('No task currently selected. Run "select-task", or pass --project/--task explicitly to any command.');return}let{projectKey:r,taskKey:n,branchPath:o}=t.currentTask;console.log(`Current task: ${r}/${n} (${o})`),(e.project||e.task)&&((!e.project||e.project===r)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function Hn(e){let t=m(),r=f(t),n=await Lt(r,{fsn:e.fsn,semanticTag:e.tag,preferredTerm:e.pt,parentConceptId:e.parent,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300&&o.conceptId){console.log(`Created concept ${o.conceptId}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to create concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Yn(e){let t=m(),r=f(t),n={term:e.term,ecl:e.ecl,active:e.active!==void 0?e.active==="true":void 0,limit:e.limit?Number(e.limit):void 0,projectKey:e.project,taskKey:e.task},o=e.checkStatedParentsDefinitionStatus?await To(r,n,t.currentTask):await he(r,n,t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to search concepts (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function Wn(e){let t=m(),r=f(t),n=await ye(r,{conceptId:e.id,attributeType:e.attributeType,gci:e.gci,descriptions:e.descriptions,descriptionFull:e.descriptionFull,axioms:e.axioms,inferred:e.inferred,gciAxiomsCount:e.gciAxiomsCount,full:e.full,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to get concept (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function Xn(e){let t=m(),r=f(t),n=await Mt(r,{conceptId:e.id,stated:e.stated,limit:e.limit?Number(e.limit):void 0,offset:e.offset?Number(e.offset):void 0,projectKey:e.project,taskKey:e.task},t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to find references (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function Qn(e){let t=m(),r=f(t),n=await Se(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let s=o.error?o.error:JSON.stringify(o);console.error(`Failed to validate concept (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}let i=o.validationResults;if(!Array.isArray(i)||i.length===0){console.log(`No validation issues for concept ${e.id}.`);return}x(i),o.hasErrors&&(process.exitCode=1)}async function zn(e){let t=m(),r=f(t),n=e.checkStatedParentsDefinitionStatus?await Ro(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await B(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to list concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Zn(e){let t=m(),r=f(t),n=await Eo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${n.statusCode}): ${o.error??JSON.stringify(o)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(n.body,null,2)),o.summary&&(o.summary.withIssues>0||o.summary.failed>0)&&(process.exitCode=1);return}let i=o.results??[],s=o.summary;if(i.length===0){console.log("No concepts with pending stated changes on this task.");return}for(let a of i){let c=`${a.conceptId}${a.fsn?` "${a.fsn}"`:""}`;if(a.outcome==="deleted"){console.log(`\u2014 ${c} deleted on this branch \u2014 skipped`);continue}if(a.outcome==="failed"){console.log(`\u2717 ${c} could not be validated: ${a.error??"unknown error"}`);continue}if(a.outcome==="clean"){console.log(`\u2713 ${c}`);continue}console.log(`\u26A0 ${c}`),x(a.validationResults)}if(s){console.log("");let a=[`${s.validated} validated`,`${s.clean} clean`,`${s.withIssues} with issues`];s.skippedDeleted&&a.push(`${s.skippedDeleted} skipped (deleted on this branch)`),s.failed&&a.push(`${s.failed} failed`),console.log(a.join(", ")+".")}s&&(s.withIssues>0||s.failed>0)&&(process.exitCode=1)}async function er(e){let t=m(),r=f(t),n=await Bo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to fetch concepts for review (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function tr(e){let t=m(),r=f(t),n=await Zt(r,{conceptId:e.id,term:e.term,type:e.type,semanticTag:e.tag,moduleId:e.module,acceptability:e.acceptability,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added ${e.type} description to concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function or(e){let t=m(),r=f(t),n=await eo(r,{conceptId:e.id,typeId:e.type,targetId:e.target,groupId:e.group?Number(e.group):void 0,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Added relationship (${e.type} -> ${e.target}) to concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to add relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function nr(e){let t=m(),r=f(t),n=await xo(r,{conceptId:e.id,axiomId:e.axiomId,relationshipId:e.relationshipId,relationshipIndex:e.relationshipIndex?Number(e.relationshipIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to remove relationship (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function rr(e){let t;try{t=JSON.parse(e.attributes)}catch(a){console.error(`--attributes must be valid JSON (an array of {"typeId":"...","targetId":"..."} objects): ${a.message}`),process.exitCode=1;return}let r=m(),n=f(r),o=await bo(n,{conceptId:e.id,axiomId:e.axiomId,attributes:t,groupId:e.groupId!=null&&e.groupId!==""?Number(e.groupId):void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to remove role group (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function ir(e){let t=m(),r=f(t),n=await no(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to update description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function sr(e){let t=m(),r=f(t),n=await ro(r,{conceptId:e.id,descriptionId:e.descriptionId,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set case significance of description ${e.descriptionId} to ${e.caseSignificance}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set case significance (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function ar(e){let t=m(),r=f(t);if(e.entries){let s;try{s=JSON.parse(e.entries)}catch(d){console.error(`--entries is not valid JSON: ${d.message}`),process.exitCode=1;return}if(!Array.isArray(s)||s.length===0){console.error("--entries must be a non-empty JSON array of {descriptionId, lang?, us?, gb?} objects."),process.exitCode=1;return}let a=await co(r,{conceptId:e.id,entries:s,projectKey:e.project,taskKey:e.task},t.currentTask),c=a.body;if(a.statusCode>=200&&a.statusCode<300){console.log(`Set acceptability of ${s.length} description(s) on concept ${e.id}`),x(c.validationResults);return}let l=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${l}`),process.exitCode=1;return}if(!e.descriptionId){console.error("Either --description-id (with --lang/--us/--gb) or --entries is required."),process.exitCode=1;return}let n=await ao(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){let s=[e.lang?`lang=${e.lang}`:void 0,e.us?`us=${e.us}`:void 0,e.gb?`gb=${e.gb}`:void 0].filter(Boolean);console.log(`Set acceptability of description ${e.descriptionId} (${s.join(", ")})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set acceptability (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function cr(e){let t=m(),r=f(t),n=await oo(r,{conceptId:e.id,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to inactivate concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function dr(e){let t=m(),r=f(t),n=await to(r,{conceptId:e.id,status:e.status,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set definition status of concept ${e.id} to ${e.status}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set definition status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function lr(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=m(),n=f(r),o=await ze(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function ur(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}let r=m(),n=f(r),o=await go(n,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to update GCI axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function pr(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=m(),n=f(r),o=await ho(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.gciAxioms)?i.gciAxioms.map(l=>l.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added GCI axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add GCI axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function mr(e){let t;try{t=JSON.parse(e.relationships)}catch(a){console.error(`--relationships must be valid JSON (an array of relationship objects): ${a.message}`),process.exitCode=1;return}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}if(e.definitionStatus&&e.definitionStatus!=="PRIMITIVE"&&e.definitionStatus!=="FULLY_DEFINED"){console.error("--definition-status must be PRIMITIVE or FULLY_DEFINED."),process.exitCode=1;return}let r=m(),n=f(r),o=await yo(n,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),i=o.body;if(o.statusCode>=200&&o.statusCode<300){let a=Array.isArray(i.classAxioms)?i.classAxioms.map(l=>l.axiomId).filter(Boolean):[],c=a.length>0?a[a.length-1]:void 0;console.log(`Added class axiom to concept ${e.id}${c?` (axiomId ${c})`:""}`),x(i.validationResults);return}let s=i.error?i.error:i.validationResults?JSON.stringify(i.validationResults,null,2):JSON.stringify(i);console.error(`Failed to add axiom (HTTP ${o.statusCode}): ${s}`),process.exitCode=1}async function fr(e){let t=m(),r=f(t),n=await Ao(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete concept (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function gr(e){let t=m(),r=f(t),n=await lo(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function yr(e){let t=m(),r=f(t),n=await uo(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function hr(e){let t=m(),r=f(t),n=await po(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to restore description (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function kr(e){let t=m(),r=f(t),n=await fo(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,semanticTag:e.tag,indicator:e.indicator,associationTargetId:e.associationTarget,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to replace FSN (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Cr(e){let t=m(),r=f(t),n=await mo(r,{conceptId:e.id,descriptionId:e.descriptionId,reason:e.reason,targetId:e.targetId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Set inactivation reason ${e.reason} on description ${e.descriptionId} (concept ${e.id})`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to set description inactivation reason (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Ir(e){let t=m(),r=f(t),n=await ko(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function xr(e){let t=m(),r=f(t),n=await Co(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function br(e){let t=m(),r=f(t),n=await Ie(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){if(o.alreadyConformed)console.log(`Concept ${e.id}'s axiom${o.axiomId?` ${o.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(o.replacedAxiomId){let s=Array.isArray(o.addResult?.classAxioms)?o.addResult.classAxioms.map(c=>c.axiomId).filter(Boolean):[],a=s.length>0?s[s.length-1]:void 0;console.log(`Transformed concept ${e.id} to authoring form: added axiom${a?` ${a}`:""} and inactivated published axiom ${o.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),x(o.validationResults);return}let i=o.error?o.error:o.validationResults?JSON.stringify(o.validationResults,null,2):JSON.stringify(o);console.error(`Failed to transform axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Sr(e){let t=m(),r=f(t),n=await xe(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}if(o.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${o.axiomId}) \u2014 a stated Is-a targets a fully-defined concept; run transform-axiom to fix.`),process.exitCode=1;return}console.log(`Concept ${e.id}: stated Is-a targets are all primitive (axiom ${o.axiomId}) \u2014 ${o.message}`)}async function vr(e){let t=m(),r=f(t),n=await So(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to delete GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}async function Tr(e){let t=m(),r=f(t),n=await vo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to inactivate GCI axiom (HTTP ${n.statusCode}): ${i}`),process.exitCode=1}function z(e){let t=e.account?.login;return t?Zo(f(e),t):(console.error("[authoring-cli] no login resolved from the signed-in account \u2014 notifications will only arrive via polling fallback, not a live push."),null)}async function Ar(e){let t=m(),r=f(t),n=z(t),o;try{o=await Te(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?(console.log(`Classification ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`),i.details&&console.log(JSON.stringify(i.details,null,2)),i.save&&(i.save.accepted?console.log("Classification results accepted and saved."):(console.error(`Classification results NOT saved${i.save.error?`: ${i.save.error}`:""}${i.save.status?` (status: ${i.save.status})`:""}`),process.exitCode=1))):console.log(`Classification started: job ${i.jobId} (${i.status})`),i.timedOut&&(process.exitCode=1);return}let s=i.details!==void 0?` \u2014 details: ${JSON.stringify(i.details)}`:"";console.error(`Failed to start classification (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}${s}`),process.exitCode=1}async function wr(e){let t=m(),r=f(t),n=await Fo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check classification status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function Rr(e){let t=m(),r=f(t),n=z(t),o;try{o=await Ko(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{n?.stop()}let i=o.body;if(o.statusCode>=200&&o.statusCode<300){i.finalStatus!==void 0?console.log(`Validation ${i.finalStatus}${i.timedOut?" (gave up waiting before this was confirmed terminal)":""}`):console.log("Validation started"),i.timedOut&&(process.exitCode=1);return}console.error(`Failed to start validation (HTTP ${o.statusCode}): ${i.error??JSON.stringify(i)}`),process.exitCode=1}async function Er(e){let t=m(),r=f(t),n=await Lo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),o=n.body;if(n.statusCode<200||n.statusCode>=300){let i=o.error?o.error:JSON.stringify(o);console.error(`Failed to check validation status (HTTP ${n.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2))}async function $r(e){let t=m(),r=f(t),n=z(t);try{let o=await en(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),i=o.body;if(o.statusCode<200||o.statusCode>=300){let s=i.error?i.error:JSON.stringify(i);console.error(`Failed to watch for a notification (HTTP ${o.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2)),i.timedOut&&(process.exitCode=1)}finally{n?.stop()}}var Tt=v(require("os")),Z=v(require("path"));var T=v(require("fs")),St=v(require("os")),S=v(require("path")),$="authoring-cli",F=["claude","codex"];function Ue(e){let t=[S.resolve(e,"..","skills",$),S.resolve(e,"..","..","skills",$)];for(let r of t)if(T.existsSync(S.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${$}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function Ls(e){let t=[];return T.existsSync(S.join(e,".claude"))&&t.push("claude"),T.existsSync(S.join(e,".codex"))&&t.push("codex"),t}function ue(e,t){if(e==="all")return[...F];if(e){let n=e.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean),o=n.filter(i=>!F.includes(i));if(o.length)throw new Error(`Unknown --agent value(s): ${o.join(", ")}. Supported: ${F.join(", ")}, all.`);return n}let r=Ls(t);return r.length?r:["claude"]}var Pr="# authoring-cli \u2014 SNOMED CT authoring guidance";function Ks(e){let t=S.join(e,"SKILL.md"),r=S.join(e,"references","batch-authoring.md");return[Pr,"",`Read \`${t}\` now, and follow it for the rest of this session whenever you run the`,"`authoring-cli` command \u2014 before any concept creation, description/acceptability edit,","relationship or axiom edit, `classify`, or `validate-task`. It documents server-side","constraints and async behavior that fail or mislead in non-obvious ways, so reading it after","a command has already failed is too late.","",`Also read \`${r}\` when the task is a large, multi-session batch (tens to thousands of`,"concepts generated from a source list).","","Both files live inside the installed `authoring-cli` npm package, so they stay in step with","the CLI itself. If the paths above no longer exist, the package moved or was upgraded to a","different location \u2014 re-run `authoring-cli install-skill` to refresh this prompt.",""].join(`
35
+ `)}function Ve(e){try{return S.resolve(S.dirname(e),T.readlinkSync(e))}catch{return null}}function pe(e){try{return T.lstatSync(e)}catch{return null}}function vt(e){let t=Ve(e);return t?T.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:pe(e)?.isDirectory()?"an existing directory":"an existing file"}function Nr(e){let t=Ve(e);return t!==null&&S.basename(t)===$&&S.basename(S.dirname(t))==="skills"}function Dr(e){if(!pe(e)?.isFile())return!1;try{return T.readFileSync(e,"utf8").startsWith(Pr)}catch{return!1}}function jr(e){return T.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>S.relative(e,S.join(t.parentPath,t.name))).sort()}function Or(e,t){if(!t||!T.existsSync(t))return!1;try{let r=jr(t);return r.join(`
36
+ `)!==jr(e).join(`
37
+ `)?!1:r.every(n=>T.readFileSync(S.join(e,n)).equals(T.readFileSync(S.join(t,n))))}catch{return!1}}function Ms(e,t,r){let n=e.project?S.join(r,".claude","skills"):S.join(t,".claude","skills"),o=S.join(n,$),i=e.shippedSkillDir,s=e.project&&i.startsWith(r+S.sep)?S.relative(S.dirname(o),i):i,a=pe(o),c=!1;if(a){let l=Ve(o);if(l===i&&T.existsSync(l))return{agent:"claude",path:o,status:"already-current",kind:"symlink",detail:i};if(!(Nr(o)||Or(o,i))&&!e.force)return{agent:"claude",path:o,status:"blocked",kind:"symlink",detail:vt(o)};T.rmSync(o,{recursive:!0,force:!0}),c=!0}T.mkdirSync(n,{recursive:!0});try{return T.symlinkSync(s,o,"dir"),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"symlink",detail:s}}catch(l){let d=l.code;if(d!=="EPERM"&&d!=="EACCES")throw l;return T.cpSync(i,o,{recursive:!0}),{agent:"claude",path:o,status:c?"replaced":"installed",kind:"copy",detail:"symlinks unavailable on this platform \u2014 copied instead; re-run install-skill after upgrading the CLI"}}}function Bs(e,t){let r=S.join(t,".codex","prompts"),n=S.join(r,`${$}.md`),o=Ks(e.shippedSkillDir),i=pe(n),s=!1;if(i){if((i.isFile()?T.readFileSync(n,"utf8"):null)===o)return{agent:"codex",path:n,status:"already-current",kind:"pointer"};if(!Dr(n)&&!e.force)return{agent:"codex",path:n,status:"blocked",kind:"pointer",detail:vt(n)};T.rmSync(n,{recursive:!0,force:!0}),s=!0}return T.mkdirSync(r,{recursive:!0}),T.writeFileSync(n,o,"utf8"),{agent:"codex",path:n,status:s?"replaced":"installed",kind:"pointer"}}function Fr(e){let t=e.homeDir??St.homedir(),r=e.cwd??process.cwd();return(e.agents??ue(void 0,t)).map(o=>o==="claude"?Ms(e,t,r):Bs(e,t))}function Lr(e){let t=e.homeDir??St.homedir(),r=e.cwd??process.cwd();return e.agents.map(n=>{let o=n==="claude"?S.join(e.project?S.join(r,".claude"):S.join(t,".claude"),"skills",$):S.join(t,".codex","prompts",`${$}.md`);if(!pe(o))return{agent:n,path:o,status:"not-registered"};if(!(n==="claude"?Nr(o)||Or(o,e.shippedSkillDir):Dr(o))&&!e.force)return{agent:n,path:o,status:"left-alone",detail:`${vt(o)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let s=Ve(o)??void 0;return T.rmSync(o,{recursive:!0,force:!0}),{agent:n,path:o,status:"removed",detail:s}})}function Kr(e){let t=Tt.homedir();return e===t||e.startsWith(t+Z.sep)?Z.join("~",Z.relative(t,e)):e}function _s(e){let t=Kr(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${Kr(e.detail??"")})`:e.kind==="copy"?`${t} (copy \u2014 ${e.detail})`:`${t} (pointer into the installed package)`;case"already-current":return`${t} (already registered \u2014 nothing to do)`;case"blocked":return`${t} NOT written \u2014 ${e.detail} is in the way; re-run with --force to replace it`}}async function Mr(e){let t=Ue(__dirname),r=ue(e.agent,Tt.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let n=Fr({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),o=n.filter(a=>a.status==="installed"||a.status==="replaced"),i=n.filter(a=>a.status==="blocked");console.log(o.length?`Installed skill '${$}' for:`:i.length?`Could not install skill '${$}':`:`Skill '${$}' is already registered:`);for(let a of n)console.log(` ${a.agent.padEnd(7)} ${_s(a)}`);if(e.project&&r.includes("claude")&&console.log(`
38
38
  Project-scoped install: commit .claude/skills only if authoring-cli is a dependency of this
39
39
  repo \u2014 a link into a globally installed package resolves on your machine alone.`),i.length){process.exitCode=1;return}o.length&&(console.log(`
40
40
  Restart your agent, then use /${$}.`),n.some(a=>a.kind==="symlink")&&console.log('The symlink points into this package, so "npm update -g authoring-cli" updates the skill too.'),console.log('To unregister: "authoring-cli uninstall-skill" \u2014 run it before "npm rm -g authoring-cli".'));let s=F.filter(a=>!r.includes(a));s.length&&!e.agent&&console.log(`
41
- Skipped ${s.join(", ")} (no config directory found). Pass --agent ${s.join(",")} to register anyway.`)}var Rt=v(require("os")),ee=v(require("path"));function _r(e){let t=Rt.homedir();return e===t||e.startsWith(t+ee.sep)?ee.join("~",ee.relative(t,e)):e}function qs(e){let t=_r(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${_r(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function Ur(e){let t=e.agent?me(e.agent,Rt.homedir()):[...F],r;try{r=Ve(__dirname)}catch{r=void 0}let n=Kr({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),o=n.filter(s=>s.status==="removed"),i=n.filter(s=>s.status==="left-alone");console.log(o.length?`Removed skill '${$}' registration for:`:i.length?`Left every registration of '${$}' in place:`:`No '${$}' registration found:`);for(let s of n)console.log(` ${s.agent.padEnd(7)} ${qs(s)}`);if(i.length){process.exitCode=1;return}o.length&&console.log(`
42
- Restart your agent to drop /authoring-cli from its command list.`)}function Js(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(n.startsWith("--")){let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:"";t[o]=s}}return t}function qr(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var Et=[{name:"login",usage:`login [${ye.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--cookie-name <name>] (opens Chrome to sign in; automatically captures the session on macOS (Chrome) or Linux (Chromium/Chrome, incl. Termux:X11). Always uses a dedicated "authoring-cli" Chrome profile (created automatically on first use, isolated from your everyday profile, and the only profile this command ever reads/writes cookies for \u2014 no override). Environment defaults to ${te}; any --*-endpoint overrides that environment's value)`,run:(e,t)=>Ln({environment:t[0],imsEndpoint:e["ims-endpoint"],terminologyServerEndpoint:e["terminology-server-endpoint"],authoringServicesEndpoint:e["authoring-services-endpoint"],cookieName:e["cookie-name"]})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>Kn()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>Mn()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${F.join("|")}|all] [--project] [--force] (registers the authoring guidance skill bundled with this package with your AI agent, so /authoring-cli works alongside these commands \u2014 defaults to whichever agents are installed)`,run:e=>Br({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${F.join("|")}|all] [--project] [--force] (removes what install-skill registered \u2014 run this BEFORE "npm rm -g authoring-cli", since npm runs no uninstall hooks and this command goes away with the package)`,run:e=>Ur({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"projects",usage:"projects [--json] (lists the projects available to you \u2014 no editor UI needed)",run:e=>_n({json:"json"in e})},{name:"tasks",usage:`tasks [--project <projectKey>] [--mine] [--status <status>] [--summary] [--json] (lists a project's tasks, or your own tasks across all projects if --project is omitted; --mine restricts to tasks assigned to you, --status filters by status e.g. "In Progress", --summary prints counts by project/assignee/status instead of one line per task)`,run:e=>Vn({project:e.project,mine:"mine"in e,status:e.status,summary:"summary"in e,json:"json"in e})},{name:"create-task",usage:'create-task --project <projectKey> --summary "<title>" [--description "<text>"] [--assignee <username>] [--unassigned] [--no-select] [--json] (creates a task via authoring-services and selects it; assigned to you unless overridden)',required:["project","summary"],run:e=>qn({project:e.project,summary:e.summary,description:e.description,assignee:e.assignee,unassigned:"unassigned"in e,noSelect:"no-select"in e,json:"json"in e})},{name:"recover-task",usage:"recover-task --project <projectKey> [--task <taskKey>] [--no-select] [--json] (without --task, lists the project's deleted tasks; with it, moves that task out of Deleted, keeps its branch content, and selects it \u2014 there is no delete-task command; delete a task in the Authoring Workbench UI instead)",required:["project"],run:e=>Jn({project:e.project,task:e.task,noSelect:"no-select"in e,json:"json"in e})},{name:"select-task",usage:"select-task --project <projectKey> --task <taskKey> (sets the task subsequent commands target when --project/--task are omitted)",required:["project","task"],run:e=>Gn({project:e.project,task:e.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints the locally selected task; with --project/--task, notes whether they match \u2014 standalone has no editor UI to compare against instead)",run:e=>Hn({project:e.project,task:e.task})},{name:"create-concept",usage:'create-concept --fsn "<term>" --parent <SCTID> [--tag <semantic tag>] [--pt "<preferred term>"] [--module <moduleId>] [--project <projectKey> --task <taskKey>]',required:["fsn","parent"],run:e=>Yn({fsn:e.fsn,tag:e.tag,pt:e.pt,parent:e.parent,module:e.module,project:e.project,task:e.task})},{name:"search-concepts",usage:"search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (without --limit, pages through and returns every match rather than stopping at a fixed page size \u2014 Snowstorm still can't page an unsorted search past offset+limit 10,000, so a match count above that comes back with `truncated: true` and a message to narrow the query; --limit N caps the search to exactly N results in one request instead. --check-stated-parents-definition-status filters the search results down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate, checkable from one concept fetch per result with no classification prerequisite. It's read-only and only ever proves the non-conforming case (never \"conforms\"); an axiom with all-primitive stated parents can still be missing an attribute and simply won't appear here \u2014 run transform-axiom on candidates from a broader list if you need the complete check too. Concepts that can't even be checked for this \u2014 an ambiguous multi-axiom concept, or a fetch failure \u2014 are reported separately under skippedConcepts.)",run:e=>Wn({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--attribute-type <SCTID>] [--gci] [--descriptions] [--description-full] [--axioms] [--inferred] [--gci-axioms-count] [--full] [--project <projectKey> --task <taskKey>] (no flags: a lightweight {conceptId, fsn, pt, active, definitionStatus, moduleId, effectiveTime} summary \u2014 no descriptions array, no relationships/axioms, and no network fetch of the full concept at all. --descriptions: active descriptions only (FSN/PT/synonyms), inactive dropped entirely \u2014 the common case. --description-full: every description, active and inactive, with its full acceptabilityMap. --axioms: classAxioms plus the flat relationships[] list filtered to STATED_RELATIONSHIP \u2014 the stated definition, with no inferred content mixed in. --inferred: the flat relationships[] list filtered to INFERRED_RELATIONSHIP only \u2014 what classification produced, no axioms/stated content. --gci alone: gciAxioms only. --gci-axioms-count: just {conceptId, gciAxiomsCount} \u2014 the count of active gciAxioms, for a plain has-it-got-any-GCIs check that doesn't need the axioms' content at all. --full: the entire raw concept (every description, both axiom types, annotations, both stated and inferred relationships \u2014 this used to be the no-flags default). These are mutually exclusive \u2014 pass only one. --attribute-type filters the response down to just the active relationships of that attribute type \u2014 e.g. --attribute-type 363698007 for Finding site \u2014 returning {axiomId, relationshipId, groupId, targetId, targetFsn} per match, instead of the full concept; matches is [] if the concept has none. Scans classAxioms by default; add --gci to scan gciAxioms instead \u2014 the two are never combined, since a GCI axiom's relationships assert the opposite of a class axiom's. --attribute-type takes precedence over the other flags when combined with them)",required:["id"],run:e=>Xn({id:e.id,attributeType:e["attribute-type"],gci:"gci"in e,descriptions:"descriptions"in e,descriptionFull:"description-full"in e,axioms:"axioms"in e,inferred:"inferred"in e,gciAxiomsCount:"gci-axioms-count"in e,full:"full"in e,project:e.project,task:e.task})},{name:"find-references",usage:"find-references --id <SCTID> [--stated] [--limit N] [--offset N] [--project <projectKey> --task <taskKey>] (lists every concept that references <SCTID> \u2014 as a stated Is-a parent or as an attribute value \u2014 grouped by reference type, via Snowstorm's own concept-references endpoint. Without --stated, reads the realized/inferred view (what's already classified); with --stated, reads the literal stated axioms instead, which is what catches a same-session edit before classification has run. Run both when sweeping referrers before delete-concept/inactivate-concept \u2014 neither view alone is a complete answer on a branch with pending, unclassified changes. Without --limit/--offset, pages through and returns every referencing concept rather than stopping at Snowstorm's own default page size (1000); pass --limit/--offset yourself to page through the results manually instead)",required:["id"],run:e=>Qn({id:e.id,stated:"stated"in e,limit:e.limit,offset:e.offset,project:e.project,task:e.task})},{name:"validate-concept",usage:"validate-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (read-only check of the concept's current saved state \u2014 same convention rules the interactive editor runs on save, without saving anything; does not check class-axiom authoring-form conformance \u2014 that needs the branch classified first, so it is checked and fixed once for the whole batch by review-concepts instead of per single-concept call here)",required:["id"],run:e=>zn({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (lists concepts with pending stated changes and concepts affected only by classification, derived from the task branch's traceability log, same as the Authoring Workbench's "Concepts for Review" tab; entries marked "deleted": true were created and then deleted on this branch and no longer exist. --check-stated-parents-definition-status filters that list down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate. Read-only and only ever proves the non-conforming case; an axiom with all-primitive stated parents can still be missing an attribute and won't appear here. Concepts that can't even be checked for this are reported separately under skippedConcepts)`,run:e=>Zn({checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"validate-review-concepts",usage:'validate-review-concepts [--project <projectKey> --task <taskKey>] [--json] (runs validate-concept on every concept with pending stated changes \u2014 the "concepts" list from get-concepts-for-review \u2014 skipping ones deleted on this branch, and prints a pass/issue tally; exits non-zero if any concept has issues; does not cover class-axiom authoring-form conformance, see review-concepts)',run:e=>er({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (the end-of-task review pipeline for every concept with pending stated changes: classifies the branch, transforms any class axiom that doesn't already match transform-axiom's standard authoring form, then fetches each concept's final representation \u2014 descriptions, relationships, axioms \u2014 reflecting any transform just applied. Does not re-run Snowstorm's own convention check (that already happened on each edit's own save); run validate-review-concepts yourself if you want that re-checked in batch. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)",run:e=>tr({project:e.project,task:e.task})},{name:"add-description",usage:'add-description --id <SCTID> --term "<text>" --type FSN|SYNONYM [--tag <semanticTag>] [--module <id>] [--acceptability PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>]',required:["id","term","type"],run:e=>or({id:e.id,term:e.term,type:e.type,tag:e.tag,module:e.module,acceptability:e.acceptability,project:e.project,task:e.task})},{name:"update-description",usage:'update-description --id <SCTID> --description-id <descriptionId> [--term "<text>"] [--case-significance <value>] [--project <projectKey> --task <taskKey>] (only if never versioned; reuses the existing descriptionId)',required:["id","description-id"],run:e=>sr({id:e.id,descriptionId:e["description-id"],term:e.term,caseSignificance:e["case-significance"],project:e.project,task:e.task})},{name:"set-case-significance",usage:"set-case-significance --id <SCTID> --description-id <descriptionId> --case-significance CASE_INSENSITIVE|INITIAL_CHARACTER_CASE_INSENSITIVE|ENTIRE_TERM_CASE_SENSITIVE [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","description-id","case-significance"],run:e=>ar({id:e.id,descriptionId:e["description-id"],caseSignificance:e["case-significance"],project:e.project,task:e.task})},{name:"set-acceptability",usage:`set-acceptability --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--project <projectKey> --task <taskKey>] (at least one of --lang, --us, --gb required)
43
- set-acceptability --id <SCTID> --entries '[{"descriptionId":"...","gb":"PREFERRED"},{"descriptionId":"...","gb":"ACCEPTABLE"}]' [--project <projectKey> --task <taskKey>] (applies all entries in one save)`,required:["id"],run:e=>cr({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,entries:e.entries,project:e.project,task:e.task})},{name:"add-relationship",usage:"add-relationship --id <SCTID> --type <SCTID> --target <SCTID> [--group N] [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","type","target"],run:e=>nr({id:e.id,type:e.type,target:e.target,group:e.group,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"remove-relationship",aliases:["delete-relationship"],usage:"remove-relationship --id <SCTID> --axiom-id <axiomId> (--relationship-id <relationshipId> | --relationship-index N) [--project <projectKey> --task <taskKey>] (only if the targeted relationship was never versioned)",required:["id","axiom-id"],run:e=>rr({id:e.id,axiomId:e["axiom-id"],relationshipId:e["relationship-id"],relationshipIndex:e["relationship-index"],project:e.project,task:e.task})},{name:"remove-role-group",aliases:["delete-role-group","delete-rolegroup"],usage:`remove-role-group --id <SCTID> --axiom-id <axiomId> --attributes '[{"typeId":"...","targetId":"..."}]' [--group-id N] [--project <projectKey> --task <taskKey>]`,required:["id","axiom-id","attributes"],run:e=>ir({id:e.id,axiomId:e["axiom-id"],attributes:e.attributes,groupId:e["group-id"],project:e.project,task:e.task})},{name:"inactivate-concept",usage:"inactivate-concept --id <SCTID> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (only if published; for an unpublished concept use delete-concept instead)",required:["id","indicator"],run:e=>dr({id:e.id,indicator:e.indicator,associationRefset:e["association-refset"],associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"set-definition-status",usage:"set-definition-status --id <SCTID> --status PRIMITIVE|FULLY_DEFINED [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","status"],run:e=>lr({id:e.id,status:e.status,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"update-axiom",usage:`update-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-axiom)`,required:["id","axiom-id","relationships"],run:e=>ur({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"add-axiom",usage:`add-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--definition-status PRIMITIVE|FULLY_DEFINED] [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (appends a genuinely additional class axiom alongside the concept's existing one(s) \u2014 to change an existing axiom's content instead, use update-axiom in place, published or not)`,required:["id","relationships"],run:e=>fr({id:e.id,relationships:e.relationships,definitionStatus:e["definition-status"],moduleId:e["module-id"],project:e.project,task:e.task})},{name:"add-gci-axiom",usage:`add-gci-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new GCI axiom; the relationships are the axiom's sufficient-condition side)`,required:["id","relationships"],run:e=>mr({id:e.id,relationships:e.relationships,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"update-gci-axiom",usage:`update-gci-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-gci-axiom)`,required:["id","axiom-id","relationships"],run:e=>pr({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if unpublished; a published concept 409s \u2014 use inactivate-concept instead)",required:["id"],run:e=>gr({id:e.id,project:e.project,task:e.task})},{name:"delete-description",usage:"delete-description --id <SCTID> --description-id <descriptionId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published description 409s \u2014 use inactivate-description instead)",required:["id","description-id"],run:e=>yr({id:e.id,descriptionId:e["description-id"],project:e.project,task:e.task})},{name:"inactivate-description",usage:"inactivate-description --id <SCTID> --description-id <descriptionId> --indicator <value> [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (retires a published FSN/PT/synonym without deleting it; --association-target is always a REFERS_TO association \u2014 a description has no other association type; for a never-versioned description use delete-description instead)",required:["id","description-id","indicator"],run:e=>hr({id:e.id,descriptionId:e["description-id"],indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"restore-description",usage:`restore-description --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>] (reactivates a synonym/PT retired via inactivate-description; at least one of --lang, --us, --gb is required since acceptability was cleared on inactivation; restoring PREFERRED into a dialect that already has a PT auto-demotes that PT to ACCEPTABLE in the same save)
44
- restore-description --id <SCTID> --description-id <descriptionId> [--indicator <value>] [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (reactivates an FSN instead \u2014 no --lang/--us/--gb, it is always PREFERRED in every dialect; if the concept currently has another active FSN, a never-versioned one is dropped for free but a published one needs --indicator to retire it in the same save; --association-target there is always a REFERS_TO association)`,required:["id","description-id"],run:e=>kr({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"replace-fsn",usage:'replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value> [--description-id <oldFsnDescriptionId>] [--tag <semantic tag>] [--association-target <SCTID>] [--module <moduleId>] [--project <projectKey> --task <taskKey>] (retires the current FSN and adds its replacement in one save \u2014 neither order works as two separate calls; --description-id is required only if the concept has more than one active FSN; --association-target is always a REFERS_TO association; for a never-versioned FSN use update-description instead)',required:["id","term","indicator"],run:e=>Cr({id:e.id,descriptionId:e["description-id"],term:e.term,tag:e.tag,indicator:e.indicator,associationTarget:e["association-target"],module:e.module,project:e.project,task:e.task})},{name:"set-description-inactivation-reason",usage:"set-description-inactivation-reason --id <SCTID> --description-id <descriptionId> --reason NOT_SEMANTICALLY_EQUIVALENT|OUTDATED|GRAMMATICAL_DESCRIPTION_ERROR|NONCONFORMANCE_TO_EDITORIAL_POLICY [--target-id <SCTID>] [--project <projectKey> --task <taskKey>] (assigns or retargets the reason on a description that is already inactive, without touching its active state \u2014 --target-id is required for reason NOT_SEMANTICALLY_EQUIVALENT (the concept this description actually belongs under, via a REFERS_TO association) and rejected for the other three reasons, which take no target; 409s if the reason currently assigned has already been published \u2014 only an unpublished reason can be retargeted; for a description that is still active, use inactivate-description instead)",required:["id","description-id","reason"],run:e=>Ir({id:e.id,descriptionId:e["description-id"],reason:e.reason,targetId:e["target-id"],project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published axiom 409s \u2014 use inactivate-axiom instead)",required:["id","axiom-id"],run:e=>xr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-axiom",usage:"inactivate-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished axiom use delete-axiom instead; a concept must retain at least one active class axiom; 409s if every other active class axiom is itself unpublished \u2014 that combination is the add-a-replacement-then-inactivate anti-pattern, not a legitimate retirement; use update-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>br({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"transform-axiom",usage:"transform-axiom --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (rewrites a class axiom into the standard authoring form \u2014 Is-a to the proximal primitive parent(s) plus every currently-inferred attribute, per Snowstorm's own authoring-form computation; updates the axiom in place, published or not \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:e=>Sr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"check-stated-parents-definition-status",usage:"check-stated-parents-definition-status --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only, fast: checks only whether the class axiom's stated Is-a targets a fully-defined concept \u2014 provable without Snowstorm's own authoring-form computation, which can take upwards of 20s per concept. Reports non-conformance (and exits non-zero) the moment it finds one; otherwise reports inconclusive rather than conforms, since attribute-only mismatches \u2014 a stated axiom missing an inferred attribute even though its Is-a parents are already primitive \u2014 are invisible from stated relationships alone. Run transform-axiom for a definitive, self-fixing answer when this comes back inconclusive \u2014 it checks conformance itself and reports alreadyConformed: true without writing anything if there's nothing to fix)",required:["id"],run:e=>vr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"delete-gci-axiom",usage:"delete-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published GCI axiom 409s \u2014 use inactivate-gci-axiom instead)",required:["id","axiom-id"],run:e=>Tr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-gci-axiom",usage:"inactivate-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished GCI axiom use delete-gci-axiom instead; unlike inactivate-axiom there is no minimum-active-count guard, since GCI axioms are optional; 409s if every other active GCI axiom is itself unpublished \u2014 use update-gci-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>Ar({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"classify",usage:"classify [--wait] [--timeout <seconds>, default 180] [--project <projectKey> --task <taskKey>] (self-healing: attaches to an already-running job, accepts an already-completed-but-unsaved one, or starts fresh)",run:e=>wr({wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"classification-status",usage:"classification-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>Rr({project:e.project,task:e.task})},{name:"validate-task",usage:"validate-task [--enable-mrcm] [--wait] [--timeout <seconds>, default 900] [--project <projectKey> --task <taskKey>] (validates the whole task branch \u2014 distinct from validate-concept)",run:e=>Er({enableMrcm:"enable-mrcm"in e,wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"validation-status",usage:"validation-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>$r({project:e.project,task:e.task})},{name:"watch-notification",usage:"watch-notification [--entity-type <type>] [--timeout <seconds>, default 60] [--project <projectKey> --task <taskKey>] (blocks until the next real-time notification for this task arrives, or the timeout elapses \u2014 opens a temporary STOMP connection for the duration of this call)",run:e=>jr({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function Jr(e){if(!e.aliases?.length)return e.usage;let t=`(alias: ${e.aliases.join(", ")})`;return e.usage.startsWith(e.name)?`${e.name} ${t}${e.usage.slice(e.name.length)}`:`${e.usage} ${t}`}function Vr(){return["Usage: authoring-cli <command> [options]","","Commands:",...Et.map(e=>` ${Jr(e)}`),"",'Run "login" first to sign in.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
45
- `)}async function Gr(e=process.argv){let[,,t,...r]=e,n=Js(r),o=qr(r);if(!t){console.log(Vr());return}let i=Et.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
41
+ Skipped ${s.join(", ")} (no config directory found). Pass --agent ${s.join(",")} to register anyway.`)}var At=v(require("os")),ee=v(require("path"));function Br(e){let t=At.homedir();return e===t||e.startsWith(t+ee.sep)?ee.join("~",ee.relative(t,e)):e}function Us(e){let t=Br(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${Br(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function _r(e){let t=e.agent?ue(e.agent,At.homedir()):[...F],r;try{r=Ue(__dirname)}catch{r=void 0}let n=Lr({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),o=n.filter(s=>s.status==="removed"),i=n.filter(s=>s.status==="left-alone");console.log(o.length?`Removed skill '${$}' registration for:`:i.length?`Left every registration of '${$}' in place:`:`No '${$}' registration found:`);for(let s of n)console.log(` ${s.agent.padEnd(7)} ${Us(s)}`);if(i.length){process.exitCode=1;return}o.length&&console.log(`
42
+ Restart your agent to drop /authoring-cli from its command list.`)}function Vs(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(n.startsWith("--")){let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:"";t[o]=s}}return t}function Vr(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var wt=[{name:"login",usage:`login [${fe.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--cookie-name <name>] (opens Chrome to sign in; automatically captures the session on macOS (Chrome) or Linux (Chromium/Chrome, incl. Termux:X11). Always uses a dedicated "authoring-cli" Chrome profile (created automatically on first use, isolated from your everyday profile, and the only profile this command ever reads/writes cookies for \u2014 no override). Environment defaults to ${te}; any --*-endpoint overrides that environment's value)`,run:(e,t)=>Fn({environment:t[0],imsEndpoint:e["ims-endpoint"],terminologyServerEndpoint:e["terminology-server-endpoint"],authoringServicesEndpoint:e["authoring-services-endpoint"],cookieName:e["cookie-name"]})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>Ln()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>Kn()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${F.join("|")}|all] [--project] [--force] (registers the authoring guidance skill bundled with this package with your AI agent, so /authoring-cli works alongside these commands \u2014 defaults to whichever agents are installed)`,run:e=>Mr({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${F.join("|")}|all] [--project] [--force] (removes what install-skill registered \u2014 run this BEFORE "npm rm -g authoring-cli", since npm runs no uninstall hooks and this command goes away with the package)`,run:e=>_r({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"projects",usage:"projects [--json] (lists the projects available to you \u2014 no editor UI needed)",run:e=>Bn({json:"json"in e})},{name:"tasks",usage:`tasks [--project <projectKey>] [--mine] [--status <status>] [--summary] [--json] (lists a project's tasks, or your own tasks across all projects if --project is omitted; --mine restricts to tasks assigned to you, --status filters by status e.g. "In Progress", --summary prints counts by project/assignee/status instead of one line per task)`,run:e=>Un({project:e.project,mine:"mine"in e,status:e.status,summary:"summary"in e,json:"json"in e})},{name:"create-task",usage:'create-task --project <projectKey> --summary "<title>" [--description "<text>"] [--assignee <username>] [--unassigned] [--no-select] [--json] (creates a task via authoring-services and selects it; assigned to you unless overridden)',required:["project","summary"],run:e=>Vn({project:e.project,summary:e.summary,description:e.description,assignee:e.assignee,unassigned:"unassigned"in e,noSelect:"no-select"in e,json:"json"in e})},{name:"recover-task",usage:"recover-task --project <projectKey> [--task <taskKey>] [--no-select] [--json] (without --task, lists the project's deleted tasks; with it, moves that task out of Deleted, keeps its branch content, and selects it \u2014 there is no delete-task command; delete a task in the Authoring Workbench UI instead)",required:["project"],run:e=>qn({project:e.project,task:e.task,noSelect:"no-select"in e,json:"json"in e})},{name:"select-task",usage:"select-task --project <projectKey> --task <taskKey> (sets the task subsequent commands target when --project/--task are omitted)",required:["project","task"],run:e=>Gn({project:e.project,task:e.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints the locally selected task; with --project/--task, notes whether they match \u2014 standalone has no editor UI to compare against instead)",run:e=>Jn({project:e.project,task:e.task})},{name:"create-concept",usage:'create-concept --fsn "<term>" --parent <SCTID> [--tag <semantic tag>] [--pt "<preferred term>"] [--module <moduleId>] [--project <projectKey> --task <taskKey>]',required:["fsn","parent"],run:e=>Hn({fsn:e.fsn,tag:e.tag,pt:e.pt,parent:e.parent,module:e.module,project:e.project,task:e.task})},{name:"search-concepts",usage:"search-concepts [--term <text>] [--ecl <expr>] [--active true|false] [--limit N] [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (without --limit, pages through and returns every match rather than stopping at a fixed page size \u2014 Snowstorm still can't page an unsorted search past offset+limit 10,000, so a match count above that comes back with `truncated: true` and a message to narrow the query; --limit N caps the search to exactly N results in one request instead. --check-stated-parents-definition-status filters the search results down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate, checkable from one concept fetch per result with no classification prerequisite. It's read-only and only ever proves the non-conforming case (never \"conforms\"); an axiom with all-primitive stated parents can still be missing an attribute and simply won't appear here \u2014 run transform-axiom on candidates from a broader list if you need the complete check too. Concepts that can't even be checked for this \u2014 an ambiguous multi-axiom concept, or a fetch failure \u2014 are reported separately under skippedConcepts.)",run:e=>Yn({term:e.term,ecl:e.ecl,active:e.active,limit:e.limit,checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"get-concept",usage:"get-concept --id <SCTID> [--attribute-type <SCTID>] [--gci] [--descriptions] [--description-full] [--axioms] [--inferred] [--gci-axioms-count] [--full] [--project <projectKey> --task <taskKey>] (no flags: a lightweight {conceptId, fsn, pt, active, definitionStatus, moduleId, effectiveTime} summary \u2014 no descriptions array, no relationships/axioms, and no network fetch of the full concept at all. --descriptions: active descriptions only (FSN/PT/synonyms), inactive dropped entirely \u2014 the common case. --description-full: every description, active and inactive, with its full acceptabilityMap. --axioms: classAxioms plus the flat relationships[] list filtered to STATED_RELATIONSHIP \u2014 the stated definition, with no inferred content mixed in. --inferred: the flat relationships[] list filtered to INFERRED_RELATIONSHIP only \u2014 what classification produced, no axioms/stated content. --gci alone: gciAxioms only. --gci-axioms-count: just {conceptId, gciAxiomsCount} \u2014 the count of active gciAxioms, for a plain has-it-got-any-GCIs check that doesn't need the axioms' content at all. --full: the entire raw concept (every description, both axiom types, annotations, both stated and inferred relationships \u2014 this used to be the no-flags default). These are mutually exclusive \u2014 pass only one. --attribute-type filters the response down to just the active relationships of that attribute type \u2014 e.g. --attribute-type 363698007 for Finding site \u2014 returning {axiomId, relationshipId, groupId, targetId, targetFsn} per match, instead of the full concept; matches is [] if the concept has none. Scans classAxioms by default; add --gci to scan gciAxioms instead \u2014 the two are never combined, since a GCI axiom's relationships assert the opposite of a class axiom's. --attribute-type takes precedence over the other flags when combined with them)",required:["id"],run:e=>Wn({id:e.id,attributeType:e["attribute-type"],gci:"gci"in e,descriptions:"descriptions"in e,descriptionFull:"description-full"in e,axioms:"axioms"in e,inferred:"inferred"in e,gciAxiomsCount:"gci-axioms-count"in e,full:"full"in e,project:e.project,task:e.task})},{name:"find-references",usage:"find-references --id <SCTID> [--stated] [--limit N] [--offset N] [--project <projectKey> --task <taskKey>] (lists every concept that references <SCTID> \u2014 as a stated Is-a parent or as an attribute value \u2014 grouped by reference type, via Snowstorm's own concept-references endpoint. Without --stated, reads the realized/inferred view (what's already classified); with --stated, reads the literal stated axioms instead, which is what catches a same-session edit before classification has run. Run both when sweeping referrers before delete-concept/inactivate-concept \u2014 neither view alone is a complete answer on a branch with pending, unclassified changes. Without --limit/--offset, pages through and returns every referencing concept rather than stopping at Snowstorm's own default page size (1000); pass --limit/--offset yourself to page through the results manually instead)",required:["id"],run:e=>Xn({id:e.id,stated:"stated"in e,limit:e.limit,offset:e.offset,project:e.project,task:e.task})},{name:"validate-concept",usage:"validate-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (read-only check of the concept's current saved state \u2014 same convention rules the interactive editor runs on save, without saving anything; does not check class-axiom authoring-form conformance \u2014 that needs the branch classified first, so it is checked and fixed once for the whole batch by review-concepts instead of per single-concept call here)",required:["id"],run:e=>Qn({id:e.id,project:e.project,task:e.task})},{name:"get-concepts-for-review",usage:`get-concepts-for-review [--check-stated-parents-definition-status] [--project <projectKey> --task <taskKey>] (lists concepts with pending stated changes and concepts affected only by classification, derived from the task branch's traceability log, same as the Authoring Workbench's "Concepts for Review" tab; entries marked "deleted": true were created and then deleted on this branch and no longer exist. --check-stated-parents-definition-status filters that list down to concepts whose class axiom states an Is-a to a fully-defined concept \u2014 a definite transform-axiom candidate. Read-only and only ever proves the non-conforming case; an axiom with all-primitive stated parents can still be missing an attribute and won't appear here. Concepts that can't even be checked for this are reported separately under skippedConcepts)`,run:e=>zn({checkStatedParentsDefinitionStatus:"check-stated-parents-definition-status"in e,project:e.project,task:e.task})},{name:"validate-review-concepts",usage:'validate-review-concepts [--project <projectKey> --task <taskKey>] [--json] (runs validate-concept on every concept with pending stated changes \u2014 the "concepts" list from get-concepts-for-review \u2014 skipping ones deleted on this branch, and prints a pass/issue tally; exits non-zero if any concept has issues; does not cover class-axiom authoring-form conformance, see review-concepts)',run:e=>Zn({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:"review-concepts [--project <projectKey> --task <taskKey>] (the end-of-task review pipeline for every concept with pending stated changes: classifies the branch, transforms any class axiom that doesn't already match transform-axiom's standard authoring form, then fetches each concept's final representation \u2014 descriptions, relationships, axioms \u2014 reflecting any transform just applied. Does not re-run Snowstorm's own convention check (that already happened on each edit's own save); run validate-review-concepts yourself if you want that re-checked in batch. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)",run:e=>er({project:e.project,task:e.task})},{name:"add-description",usage:'add-description --id <SCTID> --term "<text>" --type FSN|SYNONYM [--tag <semanticTag>] [--module <id>] [--acceptability PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>]',required:["id","term","type"],run:e=>tr({id:e.id,term:e.term,type:e.type,tag:e.tag,module:e.module,acceptability:e.acceptability,project:e.project,task:e.task})},{name:"update-description",usage:'update-description --id <SCTID> --description-id <descriptionId> [--term "<text>"] [--case-significance <value>] [--project <projectKey> --task <taskKey>] (only if never versioned; reuses the existing descriptionId)',required:["id","description-id"],run:e=>ir({id:e.id,descriptionId:e["description-id"],term:e.term,caseSignificance:e["case-significance"],project:e.project,task:e.task})},{name:"set-case-significance",usage:"set-case-significance --id <SCTID> --description-id <descriptionId> --case-significance CASE_INSENSITIVE|INITIAL_CHARACTER_CASE_INSENSITIVE|ENTIRE_TERM_CASE_SENSITIVE [--project <projectKey> --task <taskKey>] (only if never versioned)",required:["id","description-id","case-significance"],run:e=>sr({id:e.id,descriptionId:e["description-id"],caseSignificance:e["case-significance"],project:e.project,task:e.task})},{name:"set-acceptability",usage:`set-acceptability --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE|NOT_ACCEPTABLE] [--project <projectKey> --task <taskKey>] (at least one of --lang, --us, --gb required)
43
+ set-acceptability --id <SCTID> --entries '[{"descriptionId":"...","gb":"PREFERRED"},{"descriptionId":"...","gb":"ACCEPTABLE"}]' [--project <projectKey> --task <taskKey>] (applies all entries in one save)`,required:["id"],run:e=>ar({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,entries:e.entries,project:e.project,task:e.task})},{name:"add-relationship",usage:"add-relationship --id <SCTID> --type <SCTID> --target <SCTID> [--group N] [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","type","target"],run:e=>or({id:e.id,type:e.type,target:e.target,group:e.group,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"remove-relationship",aliases:["delete-relationship"],usage:"remove-relationship --id <SCTID> --axiom-id <axiomId> (--relationship-id <relationshipId> | --relationship-index N) [--project <projectKey> --task <taskKey>] (only if the targeted relationship was never versioned)",required:["id","axiom-id"],run:e=>nr({id:e.id,axiomId:e["axiom-id"],relationshipId:e["relationship-id"],relationshipIndex:e["relationship-index"],project:e.project,task:e.task})},{name:"remove-role-group",aliases:["delete-role-group","delete-rolegroup"],usage:`remove-role-group --id <SCTID> --axiom-id <axiomId> --attributes '[{"typeId":"...","targetId":"..."}]' [--group-id N] [--project <projectKey> --task <taskKey>]`,required:["id","axiom-id","attributes"],run:e=>rr({id:e.id,axiomId:e["axiom-id"],attributes:e.attributes,groupId:e["group-id"],project:e.project,task:e.task})},{name:"inactivate-concept",usage:"inactivate-concept --id <SCTID> --indicator <value> [--association-refset <id> --association-target <SCTID>] [--project <projectKey> --task <taskKey>] (only if published; for an unpublished concept use delete-concept instead)",required:["id","indicator"],run:e=>cr({id:e.id,indicator:e.indicator,associationRefset:e["association-refset"],associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"set-definition-status",usage:"set-definition-status --id <SCTID> --status PRIMITIVE|FULLY_DEFINED [--axiom-index N] [--project <projectKey> --task <taskKey>]",required:["id","status"],run:e=>dr({id:e.id,status:e.status,axiomIndex:e["axiom-index"],project:e.project,task:e.task})},{name:"update-axiom",usage:`update-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-axiom)`,required:["id","axiom-id","relationships"],run:e=>lr({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"add-axiom",usage:`add-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--definition-status PRIMITIVE|FULLY_DEFINED] [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (appends a genuinely additional class axiom alongside the concept's existing one(s) \u2014 to change an existing axiom's content instead, use update-axiom in place, published or not)`,required:["id","relationships"],run:e=>mr({id:e.id,relationships:e.relationships,definitionStatus:e["definition-status"],moduleId:e["module-id"],project:e.project,task:e.task})},{name:"add-gci-axiom",usage:`add-gci-axiom --id <SCTID> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"116680003"},"target":{"conceptId":"..."}}]' [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds a new GCI axiom; the relationships are the axiom's sufficient-condition side)`,required:["id","relationships"],run:e=>pr({id:e.id,relationships:e.relationships,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"update-gci-axiom",usage:`update-gci-axiom --id <SCTID> --axiom-id <axiomId> --relationships '[{"active":true,"groupId":0,"type":{"conceptId":"..."},"target":{"conceptId":"..."}}]' [--reactivate] [--project <projectKey> --task <taskKey>] (replaces the axiom's relationships wholesale in place, same axiomId, published or not \u2014 Snowstorm clears the axiom's effectiveTime on save if it was versioned; --reactivate also sets the axiom active, for repairing one previously retired via inactivate-gci-axiom)`,required:["id","axiom-id","relationships"],run:e=>ur({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"delete-concept",usage:"delete-concept --id <SCTID> [--project <projectKey> --task <taskKey>] (only if unpublished; a published concept 409s \u2014 use inactivate-concept instead)",required:["id"],run:e=>fr({id:e.id,project:e.project,task:e.task})},{name:"delete-description",usage:"delete-description --id <SCTID> --description-id <descriptionId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published description 409s \u2014 use inactivate-description instead)",required:["id","description-id"],run:e=>gr({id:e.id,descriptionId:e["description-id"],project:e.project,task:e.task})},{name:"inactivate-description",usage:"inactivate-description --id <SCTID> --description-id <descriptionId> --indicator <value> [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (retires a published FSN/PT/synonym without deleting it; --association-target is always a REFERS_TO association \u2014 a description has no other association type; for a never-versioned description use delete-description instead)",required:["id","description-id","indicator"],run:e=>yr({id:e.id,descriptionId:e["description-id"],indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"restore-description",usage:`restore-description --id <SCTID> --description-id <descriptionId> [--lang <code, e.g. en>] [--us PREFERRED|ACCEPTABLE] [--gb PREFERRED|ACCEPTABLE] [--project <projectKey> --task <taskKey>] (reactivates a synonym/PT retired via inactivate-description; at least one of --lang, --us, --gb is required since acceptability was cleared on inactivation; restoring PREFERRED into a dialect that already has a PT auto-demotes that PT to ACCEPTABLE in the same save)
44
+ restore-description --id <SCTID> --description-id <descriptionId> [--indicator <value>] [--association-target <SCTID>] [--project <projectKey> --task <taskKey>] (reactivates an FSN instead \u2014 no --lang/--us/--gb, it is always PREFERRED in every dialect; if the concept currently has another active FSN, a never-versioned one is dropped for free but a published one needs --indicator to retire it in the same save; --association-target there is always a REFERS_TO association)`,required:["id","description-id"],run:e=>hr({id:e.id,descriptionId:e["description-id"],lang:e.lang,us:e.us,gb:e.gb,indicator:e.indicator,associationTarget:e["association-target"],project:e.project,task:e.task})},{name:"replace-fsn",usage:'replace-fsn --id <SCTID> --term "<new FSN>" --indicator <value> [--description-id <oldFsnDescriptionId>] [--tag <semantic tag>] [--association-target <SCTID>] [--module <moduleId>] [--project <projectKey> --task <taskKey>] (retires the current FSN and adds its replacement in one save \u2014 neither order works as two separate calls; --description-id is required only if the concept has more than one active FSN; --association-target is always a REFERS_TO association; for a never-versioned FSN use update-description instead)',required:["id","term","indicator"],run:e=>kr({id:e.id,descriptionId:e["description-id"],term:e.term,tag:e.tag,indicator:e.indicator,associationTarget:e["association-target"],module:e.module,project:e.project,task:e.task})},{name:"set-description-inactivation-reason",usage:"set-description-inactivation-reason --id <SCTID> --description-id <descriptionId> --reason NOT_SEMANTICALLY_EQUIVALENT|OUTDATED|GRAMMATICAL_DESCRIPTION_ERROR|NONCONFORMANCE_TO_EDITORIAL_POLICY [--target-id <SCTID>] [--project <projectKey> --task <taskKey>] (assigns or retargets the reason on a description that is already inactive, without touching its active state \u2014 --target-id is required for reason NOT_SEMANTICALLY_EQUIVALENT (the concept this description actually belongs under, via a REFERS_TO association) and rejected for the other three reasons, which take no target; 409s if the reason currently assigned has already been published \u2014 only an unpublished reason can be retargeted; for a description that is still active, use inactivate-description instead)",required:["id","description-id","reason"],run:e=>Cr({id:e.id,descriptionId:e["description-id"],reason:e.reason,targetId:e["target-id"],project:e.project,task:e.task})},{name:"delete-axiom",usage:"delete-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published axiom 409s \u2014 use inactivate-axiom instead)",required:["id","axiom-id"],run:e=>Ir({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-axiom",usage:"inactivate-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished axiom use delete-axiom instead; a concept must retain at least one active class axiom; 409s if every other active class axiom is itself unpublished \u2014 that combination is the add-a-replacement-then-inactivate anti-pattern, not a legitimate retirement; use update-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>xr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"transform-axiom",usage:"transform-axiom --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (rewrites a class axiom into the standard authoring form \u2014 Is-a to the proximal primitive parent(s) plus every currently-inferred attribute, per Snowstorm's own authoring-form computation; updates the axiom in place, published or not \u2014 omit --axiom-id to target the concept's sole active class axiom)",required:["id"],run:e=>br({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"check-stated-parents-definition-status",usage:"check-stated-parents-definition-status --id <SCTID> [--axiom-id <axiomId>] [--project <projectKey> --task <taskKey>] (read-only, fast: checks only whether the class axiom's stated Is-a targets a fully-defined concept \u2014 provable without Snowstorm's own authoring-form computation, which can take upwards of 20s per concept. Reports non-conformance (and exits non-zero) the moment it finds one; otherwise reports inconclusive rather than conforms, since attribute-only mismatches \u2014 a stated axiom missing an inferred attribute even though its Is-a parents are already primitive \u2014 are invisible from stated relationships alone. Run transform-axiom for a definitive, self-fixing answer when this comes back inconclusive \u2014 it checks conformance itself and reports alreadyConformed: true without writing anything if there's nothing to fix)",required:["id"],run:e=>Sr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"delete-gci-axiom",usage:"delete-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if unpublished; a published GCI axiom 409s \u2014 use inactivate-gci-axiom instead)",required:["id","axiom-id"],run:e=>vr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"inactivate-gci-axiom",usage:"inactivate-gci-axiom --id <SCTID> --axiom-id <axiomId> [--project <projectKey> --task <taskKey>] (only if published; for an unpublished GCI axiom use delete-gci-axiom instead; unlike inactivate-axiom there is no minimum-active-count guard, since GCI axioms are optional; 409s if every other active GCI axiom is itself unpublished \u2014 use update-gci-axiom to edit this axiom in place instead)",required:["id","axiom-id"],run:e=>Tr({id:e.id,axiomId:e["axiom-id"],project:e.project,task:e.task})},{name:"classify",usage:"classify [--wait] [--timeout <seconds>, default 180] [--project <projectKey> --task <taskKey>] (self-healing: attaches to an already-running job, accepts an already-completed-but-unsaved one, or starts fresh)",run:e=>Ar({wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"classification-status",usage:"classification-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>wr({project:e.project,task:e.task})},{name:"validate-task",usage:"validate-task [--enable-mrcm] [--wait] [--timeout <seconds>, default 900] [--project <projectKey> --task <taskKey>] (validates the whole task branch \u2014 distinct from validate-concept)",run:e=>Rr({enableMrcm:"enable-mrcm"in e,wait:"wait"in e,timeout:e.timeout,project:e.project,task:e.task})},{name:"validation-status",usage:"validation-status [--project <projectKey> --task <taskKey>] (read-only)",run:e=>Er({project:e.project,task:e.task})},{name:"watch-notification",usage:"watch-notification [--entity-type <type>] [--timeout <seconds>, default 60] [--project <projectKey> --task <taskKey>] (blocks until the next real-time notification for this task arrives, or the timeout elapses \u2014 opens a temporary STOMP connection for the duration of this call)",run:e=>$r({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function qr(e){if(!e.aliases?.length)return e.usage;let t=`(alias: ${e.aliases.join(", ")})`;return e.usage.startsWith(e.name)?`${e.name} ${t}${e.usage.slice(e.name.length)}`:`${e.usage} ${t}`}function Ur(){return["Usage: authoring-cli <command> [options]","","Commands:",...wt.map(e=>` ${qr(e)}`),"",'Run "login" first to sign in.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
45
+ `)}async function Gr(e=process.argv){let[,,t,...r]=e,n=Vs(r),o=Vr(r);if(!t){console.log(Ur());return}let i=wt.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
46
46
 
47
- ${Vr()}`),process.exitCode=1;return}let s=(i.required??[]).filter(a=>!n[a]);if(s.length){console.error(`Missing required flag(s): ${s.map(a=>`--${a}`).join(", ")}
47
+ ${Ur()}`),process.exitCode=1;return}let s=(i.required??[]).filter(a=>!n[a]);if(s.length){console.error(`Missing required flag(s): ${s.map(a=>`--${a}`).join(", ")}
48
48
 
49
- Usage: ${Jr(i)}`),process.exitCode=1;return}await i.run(n,o)}require.main===module&&Gr().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
49
+ Usage: ${qr(i)}`),process.exitCode=1;return}await i.run(n,o)}require.main===module&&Gr().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "authoring-cli",
3
- "version": "0.1.21",
3
+ "version": "0.1.22",
4
4
  "description": "CLI for SNOMED CT authoring against authoring-services",
5
5
  "license": "Apache-2.0",
6
6
  "bin": {