authoring-cli 0.1.26 → 0.1.30

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 (2) hide show
  1. package/dist/index.js +24 -22
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,25 +1,27 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var ii=Object.create;var ye=Object.defineProperty;var si=Object.getOwnPropertyDescriptor;var ai=Object.getOwnPropertyNames;var ci=Object.getPrototypeOf,di=Object.prototype.hasOwnProperty;var ui=(e,t)=>{for(var r in t)ye(e,r,{get:t[r],enumerable:!0})},Et=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ai(t))!di.call(e,n)&&n!==r&&ye(e,n,{get:()=>t[n],enumerable:!(o=si(t,n))||o.enumerable});return e};var w=(e,t,r)=>(r=e!=null?ii(ci(e)):{},Et(t||!e||!e.__esModule?ye(r,"default",{value:e,enumerable:!0}):r,e)),li=e=>Et(ye({},"__esModule",{value:!0}),e);var na={};ui(na,{COMMANDS:()=>Rt,main:()=>ri,parsePositionals:()=>oi});module.exports=li(na);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"}},pi={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},ge=Object.keys(G);function $t(e){return pi[e.trim().toLowerCase()]??null}var te="uat",ia=G.uat.imsEndpoint,sa=G.uat.terminologyServerEndpoint,aa=G.uat.authoringServicesEndpoint;var mi=w(require("http")),fi=w(require("https"));function C(e,t={}){let{method:r="GET",cookie:o,body:n,headers:i={},timeoutMs:s=15e3}=t;return new Promise((a,c)=>{let d;try{d=new URL(e)}catch(g){c(g);return}let u=d.protocol==="https:"?fi:mi,l=n!==void 0?JSON.stringify(n):void 0,p={accept:"application/json",...i};if(l!==void 0&&(p["content-type"]="application/json",p["content-length"]=String(Buffer.byteLength(l))),o){let g=o.replace(/[^\x20-\x7e\t]/g,"");g&&(p.cookie=g)}let y=!1,I=u.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:p},g=>{let S="";g.on("data",j=>{S+=j}),g.on("end",()=>{if(y)return;y=!0,clearTimeout(h);let j=g.statusCode??0,P=(g.headers["content-type"]??"").includes("application/json"),D=null,fe=!1;if(S)try{D=JSON.parse(S)}catch{fe=!P}a({statusCode:j,body:D,rawBody:S,sessionExpired:fe})})});I.on("error",g=>{y||(y=!0,clearTimeout(h),c(g))});let h=setTimeout(()=>{y||(y=!0,I.destroy(),c(new Error(`Request to ${e} timed out after ${s}ms`)))},s);l!==void 0&&I.write(l),I.end()})}var U="900000000000509007",J="900000000000508004";var jt={[U]:"en-us",[J]:"en-gb"},Pt={[U]:"true",[J]:"true"},yi={},gi={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:jt,dialectDefaults:Pt,readOnlyDialects:yi,defaultLanguage:"en"};function Nt(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return gi;let t={[U]:"en-us"},r={},o={},n=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let u=d[1];t[String(e[c])]=u,n.length===0&&n.push(u)}}let i=e.requiredLanguageRefsets;if(Array.isArray(i))for(let c of i){if(typeof c!="object"||c===null)continue;let d=null,u=null;for(let[I,h]of Object.entries(c))I.length===2&&(d=I,u=String(h));if(!d||!u)continue;let l=c.dialectName;t[u]=typeof l=="string"?l:d;let p=c.default;p==="true"&&!n.includes(d)&&n.push(d),p!=null&&(r[u]=String(p));let y=c.readOnly;y!=null&&(o[u]=String(y))}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?jt:t,dialectDefaults:a?Pt:r,readOnlyDialects:o,defaultLanguage:n[0]??"en"}}function Ge(e,t,r,o){let n={};for(let i of Object.keys(e.dialects)){let s=e.dialects[i];e.isExtension&&!r?s.includes(o)?n[i]="PREFERRED":s.includes(e.defaultLanguage)&&(n[i]="ACCEPTABLE"):s.includes(o)&&(n[i]=t),e.dialectDefaults[i]==="false"&&!r&&delete n[i],e.readOnlyDialects[i]==="true"&&delete n[i]}return n}function he(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[U]:"PREFERRED"}:Ge(e,"PREFERRED",t,"en")}var hi="900000000000207008";function Dt(e){return e.replace(/\/$/,"")}function A(e){return Dt(e.terminologyServerEndpoint)}function E(e){return Dt(e.authoringServicesEndpoint)}function Ot(e){return`${new URL(E(e)).origin}/authoring-traceability-service`}function H(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function k(e,t,r){let o=t.projectKey||r?.projectKey,n=t.taskKey||r?.taskKey,i=!t.projectKey&&!t.taskKey,s=t.branchPath||(i?r?.branchPath:void 0);return!o||!n?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(s||(s=await ki(e,o,n)??void 0),s?{ok:!0,projectKey:o,taskKey:n,branchPath:s}:{ok:!1,error:`Could not resolve branch path for ${o}/${n}.`})}async function W(e,t){let r=A(e),o=await C(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(o.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(o.statusCode>=200&&o.statusCode<300)return{ok:!0,created:!1};if(o.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${o.statusCode}).`};let n=t.split("/").filter(Boolean),i=n[n.length-1],s=n.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 C(`${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 ki(e,t,r){let o=`${E(e)}/projects/${t}/tasks/${r}`;return(await C(o,{cookie:e.cookie})).body?.branchPath??null}async function Ft(e,t,r){let o=r?.get(t);if(o)return o;let n=`${E(e)}/projects/${t}`,s=(await C(n,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function _(e,t,r){let o=await Ft(e,t,r),n=o.multipleModuleEditingDisabled,i=!n||n==="false";return o.expectedExtensionModules?.length&&i?o.expectedExtensionModules[0]:o.defaultModuleId?o.defaultModuleId:hi}async function Y(e,t,r){let o=await Ft(e,t,r);return Nt(o)}async function Je(e,t){let r=e.replace(/\/$/,"")+"/auth",o=await C(r,{cookie:t,timeoutMs:8e3});return o.statusCode>=200&&o.statusCode<300&&o.body?o.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${o.statusCode} from ${r}`),null)}var Kt=w(require("crypto"));async function K(e,t,r){let o=`${E(e)}/projects/${t}/tasks/${r}`;return(await C(o,{cookie:e.cookie})).body??null}function Lt(e){let t=e?.trim();return t?t.toLowerCase():null}async function b(e,t){let r=Lt(e.currentUsername);if(!r)return null;let o=await K(e,t.projectKey,t.taskKey),n=Lt(o?.assignee?.username);return n?n!==r?{statusCode:403,body:{error:`Not allowed: ${t.projectKey}/${t.taskKey} is authored by "${n}", but the signed-in user is "${r}". Only the Task Author can make changes to a task, including classification.`}}:null:{statusCode:403,body:{error:`Task ${t.projectKey}/${t.taskKey} has no assignee. Only the Task Author may make changes to a task \u2014 including classification \u2014 and nobody is currently assigned.`}}}var Ci="116680003";function oe(e,t,r,o,n="PREFERRED",i=!1){let s=e==="FSN"?he(o,i):Ge(o,n,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function Mt(e,t,r,o=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let n=await k(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await b(e,n);if(i)return i;let{projectKey:s,taskKey:a,branchPath:c}=n,d=H(c),u=t.moduleId||await _(e,s,o),l=await Y(e,s,o),p=t.preferredTerm||t.fsn,y=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,I={conceptId:null,moduleId:u,definitionStatus:"PRIMITIVE",active:!0,descriptions:[oe("FSN",y,u,l,"PREFERRED",!0),oe("SYNONYM",p,u,l,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:Kt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:u,relationships:[{active:!0,groupId:0,type:{conceptId:Ci},target:{conceptId:t.parentConceptId}}]}]},h=`${A(e)}/browser/${d}/${s}/${a}/concepts/?validate=true`,g=await C(h,{method:"POST",body:I,cookie:e.cookie});if(g.sessionExpired){let N="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: SESSION EXPIRED`),{statusCode:401,body:{error:N}}}let S=g.body,j=S&&"conceptId"in S?S.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: ${g.statusCode<300?"OK":"FAILED ("+g.statusCode+")"} \u2014 ${y}`+(j?` \u2192 ${j}`:"")),typeof j=="string"&&e.onValidationResults?.(j,S?.validationResults),{statusCode:g.statusCode,body:g.body}}var Ii=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],xi={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function bi(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(o=>o.active!==!1).length}function _t(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(o=>o.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 vi(e,t,r){let o=Array.isArray(e[r])?e[r]:[],n=[];for(let i of o){if(i.active===!1||typeof i.axiomId!="string")continue;(Array.isArray(i.relationships)?i.relationships:[]).forEach((a,c)=>{let d=a.type;if((re(d)?d.conceptId:void 0)!==t)return;let l=a.target;n.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(l)?l.conceptId:void 0,targetFsn:re(l)&&re(l.fsn)?l.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return n}async function ke(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};if(!t.attributeType){let a=Ii.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>xi[c]).join(", ")}.`}}}if(!t.attributeType&&!t.descriptions&&!t.descriptionFull&&!t.axioms&&!t.inferred&&!t.gci&&!t.gciAxiomsCount&&!t.full){let a=`${A(e)}/${o.branchPath}/concepts/${t.conceptId}`,c=await C(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 n=`${A(e)}/browser/${o.branchPath}/concepts/${t.conceptId}`,i=await C(n,{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=vi(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:_t(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...ne(s),relationships:_t(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...ne(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:bi(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var Si=500,wi=1e4;async function Ce(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n={expand:"fsn()"};t.term&&(n.termFilter=t.term),t.ecl&&(n.eclFilter=t.ecl),typeof t.active=="boolean"&&(n.activeFilter=t.active);let i=`${A(e)}/${o.branchPath}/concepts/search`,s=u=>({conceptId:u.conceptId,fsn:u.fsn?.term,pt:u.pt?.term,active:u.active,moduleId:u.moduleId});if(t.limit!==void 0){let u=await C(i,{method:"POST",body:{...n,limit:t.limit},cookie:e.cookie});if(u.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let l=(u.body?.items??[]).map(s);return{statusCode:u.statusCode,body:{total:u.body?.total??l.length,items:l}}}let a=[],c=0,d=0;for(;;){let u=Math.min(Si,wi-d);if(u<=0)break;let l=await C(i,{method:"POST",body:{...n,limit:u,offset:d},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:l.body??{error:"Concept search failed."}};let p=l.body?.items??[];if(a.push(...p.map(s)),c=l.body?.total??a.length,d+=p.length,p.length===0||d>=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 Ti(e){let t=new Map;for(let r of e)for(let o of r){let n=o.referenceType?.conceptId??"",i=t.get(n);i?i.referencingConcepts=[...i.referencingConcepts??[],...o.referencingConcepts??[]]:t.set(n,{...o,referencingConcepts:[...o.referencingConcepts??[]]})}return[...t.values()]}async function Bt(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=`${A(e)}/${o.branchPath}/concepts/${t.conceptId}/references`,i=(u,l)=>{let p=new URLSearchParams;return typeof t.stated=="boolean"&&p.set("stated",String(t.stated)),p.set("limit",String(u)),p.set("offset",String(l)),C(`${n}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let u=await i(t.limit??ie,t.offset??0);return u.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:u.statusCode,body:u.body}}let s=[],a=0,c=0,d=0;for(;;){let u=await i(ie,d);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:"Could not fetch references."}};let l=u.body?.referencesByType??[];s.push(l),a=u.body?.total??a;let p=l.reduce((y,I)=>y+(I.referencingConcepts?.length??0),0);if(c+=p,p===0||p<ie||c>=a)break;d+=ie}return{statusCode:200,body:{total:a,limit:ie,offset:0,referencesByType:Ti(s)}}}var Ye=w(require("crypto"));function Ut(e){return typeof e=="object"&&e!==null}function Ai(e){let t=e.type,r=e.target,o=Ut(t)?t.conceptId:void 0,n=Ut(r)?r.conceptId:void 0;return typeof o=="string"&&typeof n=="string"?{typeId:o,targetId:n}:null}function Ri(e,t){let r=[...t];for(let o of e){let n=r.findIndex(i=>i.typeId===o.typeId&&i.targetId===o.targetId);if(n===-1)return!1;r.splice(n,1)}return!0}function qt(e,t,r){let o=new Map;for(let s of e){let a=typeof s.groupId=="number"?s.groupId:0,c=o.get(a);c?c.push(s):o.set(a,[s])}let n=[];for(let[s,a]of o){if(r!=null?s!==r:s===0)continue;let c=a.map(Ai).filter(d=>d!=null);Ri(t,c)&&n.push(s)}if(n.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(n.length>1)return{ok:!1,statusCode:409,error:`has ${n.length} role groups matching the given attributes (groupIds: ${n.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let i=n[0];return{ok:!0,groupId:i,relationships:o.get(i)}}var Ei=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],$i=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],ji=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],Pi=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],Ni=["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 o of t)o in e&&(r[o]=e[o]);return r}function Ie(e){return typeof e=="object"&&e!==null}function Vt(e){return Ie(e)?se(e,Pi):e}function eo(e){if(!Ie(e))return e;let t=se(e,ji);return"type"in t&&(t.type=Vt(t.type)),"target"in t&&(t.target=Vt(t.target)),t}function Di(e){return Ie(e)?se(e,$i):e}function Gt(e){if(!Ie(e))return e;let t=se(e,Ni);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(eo)),t}function Qe(e){let t=se(e,Ei);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(Di)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(eo)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(Gt)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(Gt)),t}function Oi(e){return new Promise(t=>setTimeout(t,e))}function Fi(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],Jt=new Map;function Li(e,t){let o=(Jt.get(e)??Promise.resolve()).then(t,t);return Jt.set(e,o.then(()=>{},()=>{})),o}async function R(e,t,r,o){try{return await Li(t.branchPath,()=>Ki(e,t,r,o))}catch(n){return{statusCode:500,body:{error:n instanceof Error?n.message:String(n)}}}}async function Ki(e,t,r,o){for(let n=0;;n++){let i=A(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await C(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,d=o(c);if(d)return d;let u=H(t.branchPath),l=`${i}/browser/${u}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await C(l,{method:"PUT",body:Qe(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(Fi(p)&&n<He.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${n+1}/${He.length})`),await Oi(He[n]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${p.statusCode<300?"OK":"FAILED ("+p.statusCode+")"} \u2014 ${r}`);let y=p.body;return e.onValidationResults?.(r,y?.validationResults),{statusCode:p.statusCode,body:p.body}}}var Ht=["PREFERRED","ACCEPTABLE"];async function to(e,t,r,o=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 n=await k(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await b(e,n);if(i)return i;let s=t.moduleId||await _(e,n.projectKey,o),a=await Y(e,n.projectKey,o),c=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return R(e,n,t.conceptId,d=>{let u=Array.isArray(d.descriptions)?d.descriptions:[];return u.push(oe(t.type,c,s,a,t.acceptability??"ACCEPTABLE",!1)),d.descriptions=u,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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);if(n)return n;let i=t.axiomIndex??0;return R(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[],c=a[i];if(!c)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${i} (has ${a.length}).`}};let d=Array.isArray(c.relationships)?c.relationships:[];return d.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),c.relationships=d,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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);if(n)return n;let i=t.axiomIndex??0;return R(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[],c=a[i];return c?(c.definitionStatus=t.status,s.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${i} (has ${a.length}).`}}})}async function ro(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>i.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(i.active=!1,i.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(i.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null))}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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?a.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(a.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(a.term=t.term),t.caseSignificance&&(a.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?(a.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}var We=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function Wt(e){return We.includes(e)}function ao(e){return e.us&&!Wt(e.us)?{statusCode:400,body:{error:`us must be one of: ${We.join(", ")}.`}}:e.gb&&!Wt(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${We.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 o=e.find(i=>i.descriptionId===r.descriptionId);if(!o)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(o.lang=r.lang);let n={...o.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete n[U]:n[U]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete n[J]:n[J]=r.gb),o.active!==!1&&Object.keys(n).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.`}}:(o.acceptabilityMap=n,null)}async function uo(e,t,r){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},n=co(o);if(n)return n;let i=await k(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let s=await b(e,i);return s||R(e,i,t.conceptId,a=>{let c=Array.isArray(a.descriptions)?a.descriptions:[];return ze(c,t.conceptId,o)})}async function lo(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 i of t.entries){let s=co(i);if(s)return s}let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[];for(let a of t.entries){let c=ze(s,t.conceptId,a);if(c)return c}return null})}async function po(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[],a=s.findIndex(c=>c.descriptionId===t.descriptionId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(s.splice(a,1),i.descriptions=s,null)})}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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?a.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(a.active=!1,a.inactivationIndicator=t.indicator,a.acceptabilityMap={},t.associationTargetId&&(a.associationTargets={[xe]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}function Yt(e,t,r){for(let o of e){if(o.descriptionId===t||o.active===!1||o.type!=="SYNONYM")continue;let n=o.acceptabilityMap;n?.[r]==="PREFERRED"&&(o.acceptabilityMap={...n,[r]:"ACCEPTABLE"})}}async function fo(e,t,r,o=new Map){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},i=ao(n);if(i)return i;let s=!!(t.lang||t.us||t.gb),a=await k(e,t,r);if(!a.ok)return{statusCode:400,body:{error:a.error}};let c=await b(e,a);if(c)return c;let d=await Y(e,a.projectKey,o);return R(e,a,t.conceptId,u=>{let l=Array.isArray(u.descriptions)?u.descriptions:[],p=l.find(I=>I.descriptionId===t.descriptionId);if(!p)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(p.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(p.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 I=l.filter(h=>h.type==="FSN"&&h.active!==!1&&h.descriptionId!==t.descriptionId);if(I.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${I.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(I.length===1){let h=I[0];if(h.effectiveTime==null)l.splice(l.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 p.active=!0,delete p.inactivationIndicator,delete p.associationTargets,p.acceptabilityMap=he(d,!1),u.descriptions=l,null}if(!s)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};p.active=!0,delete p.inactivationIndicator,delete p.associationTargets;let y=ze(l,t.conceptId,n);return y||(n.us==="PREFERRED"&&Yt(l,t.descriptionId,U),n.gb==="PREFERRED"&&Yt(l,t.descriptionId,J),null)})}var Mi="900000000000490003",Xt=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function yo(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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${Mi}&active=true`,a=await C(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||500,body:{error:`Could not check description ${t.descriptionId}'s current inactivation reason.`,details:a.body}};let c=(a.body.items??[])[0];return c?.released===!0?{statusCode:409,body:{error:`Description ${t.descriptionId}'s inactivation reason has already been published (effectiveTime ${String(c.effectiveTime)}) and cannot be changed.`}}:R(e,o,t.conceptId,d=>{let l=(Array.isArray(d.descriptions)?d.descriptions:[]).find(p=>p.descriptionId===t.descriptionId);return l?l.active!==!1?{statusCode:409,body:{error:`Description ${t.descriptionId} is active \u2014 use inactivate-description to inactivate it with a reason.`}}:(l.inactivationIndicator=t.reason,t.reason==="NOT_SEMANTICALLY_EQUIVALENT"?l.associationTargets={[xe]:[t.targetId]}:delete l.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function go(e,t,r,o=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let n=await k(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await b(e,n);if(i)return i;let s=t.moduleId||await _(e,n.projectKey,o),a=await Y(e,n.projectKey,o),c=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return R(e,n,t.conceptId,d=>{let u=Array.isArray(d.descriptions)?d.descriptions:[],l;if(t.descriptionId){if(l=u.find(p=>p.descriptionId===t.descriptionId),!l)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(l.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(l.type)}, not an FSN.`}}}else{let p=u.filter(y=>y.type==="FSN"&&y.active!==!1);if(p.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${p.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};l=p[0]}return l.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(l.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(l.active=!1,l.inactivationIndicator=t.indicator,l.acceptabilityMap={},t.associationTargetId&&(l.associationTargets={[xe]:[t.associationTargetId]}),u.push(oe("FSN",c,s,a,"PREFERRED",!1)),d.descriptions=u,null)})}function ho(e,t,r){return R(e,t,r.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(s=>s.axiomId===r.axiomId);return i?(i.relationships=r.relationships,r.active!=null&&(i.active=r.active),null):{statusCode:404,body:{error:`Concept ${r.conceptId} has no class axiom ${r.axiomId}.`}}})}async function ko(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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||ho(e,o,t)}async function Co(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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.gciAxioms)?i.gciAxioms:[]).find(c=>c.axiomId===t.axiomId);return a?(a.relationships=t.relationships,t.active!=null&&(a.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}})}async function Io(e,t,r,o=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 n=await k(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await b(e,n);if(i)return i;let s=t.moduleId||await _(e,n.projectKey,o);return R(e,n,t.conceptId,a=>{let c=Array.isArray(a.classAxioms)?a.classAxioms:[];return c.push({axiomId:Ye.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.classAxioms=c,null})}async function xo(e,t,r,o=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 n=await k(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await b(e,n);if(i)return i;let s=t.moduleId||await _(e,n.projectKey,o);return R(e,n,t.conceptId,a=>{let c=Array.isArray(a.gciAxioms)?a.gciAxioms:[];return c.push({axiomId:Ye.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.gciAxioms=c,null})}async function bo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s.findIndex(c=>c.axiomId===t.axiomId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:s.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(s.splice(a,1),i.classAxioms=s,null)})}async function vo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s.find(d=>d.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};if(a.active===!1)return{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}};if(a.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}};let c=s.filter(d=>d!==a&&d.active!==!1);return c.length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:c.every(d=>d.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.`}}:(a.active=!1,null)})}var _i="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 Bi(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:_i},target:{conceptId:i.id}});let o=Array.isArray(e.attributes)?e.attributes:[];for(let i of o)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 So(e,t,r,o){let n=A(e),i=await C(`${n}/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(o){if(a=s.find(c=>c.axiomId===o),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${o}.`,undetermined:!0}}}}else{let c=s.filter(d=>d.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 Ui="116680003";function qi(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==Ui?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function Vi(e,t,r){let o=A(e),n=await C(`${o}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(n.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(n.statusCode<200||n.statusCode>=300||!n.body)return{ok:!1,result:{statusCode:n.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:n.body,undetermined:!0}}};let i=Bi(n.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 Gi(e,t,r,o){let n=await So(e,t,r,o);if(!n.ok)return n;let i=await Vi(e,t,r);return i.ok?{ok:!0,value:{axiom:n.value.axiom,axiomId:n.value.axiomId,targetRelationships:i.value}}:i}function Ji(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let o=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${o}`}function zt(e){let t=new Map;for(let n of e){if(n.active===!1)continue;let i=typeof n.groupId=="number"?n.groupId:0,s=t.get(i)??[];s.push(Ji(n)),t.set(i,s)}let r=(t.get(0)??[]).slice().sort(),o=[];for(let[n,i]of t)n!==0&&o.push(i.slice().sort());return{ungrouped:r,groups:o}}function Hi(e,t){let r=zt(e),o=zt(t);if(r.ungrouped.join("|")!==o.ungrouped.join("|"))return!1;let n=r.groups.map(s=>s.join("|")).sort(),i=o.groups.map(s=>s.join("|")).sort();return n.join("||")===i.join("||")}async function wo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);if(n)return n;let i=await Gi(e,o,t.conceptId,t.axiomId);if(!i.ok)return i.result;let{axiom:s,axiomId:a,targetRelationships:c}=i.value,d=Array.isArray(s.relationships)?s.relationships:[];return Hi(d,c)?(e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${o.projectKey}/${o.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:a,alreadyConformed:!0}}):ho(e,o,{conceptId:t.conceptId,axiomId:a,relationships:c})}async function be(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await So(e,o,t.conceptId,t.axiomId);if(!n.ok)return n.result;let{axiom:i,axiomId:s}=n.value,a=Array.isArray(i.relationships)?i.relationships:[];return qi(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 To(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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.classAxioms)?i.classAxioms:[]).find(l=>l.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let c=Array.isArray(a.relationships)?a.relationships:[],d=t.relationshipId?c.findIndex(l=>l.relationshipId===t.relationshipId):t.relationshipIndex,u=d>=0?c[d]:void 0;return u?u.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${d}`} has effectiveTime ${String(u.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(c.splice(d,1),a.relationships=c,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}})}async function Ao(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 i of t.attributes)if(!i||typeof i.typeId!="string"||typeof i.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.classAxioms)?i.classAxioms:[]).find(l=>l.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let c=Array.isArray(a.relationships)?a.relationships:[],d=qt(c,t.attributes,t.groupId);if(!d.ok)return{statusCode:d.statusCode,body:{error:`Axiom ${t.axiomId} ${d.error}`}};let u=d.relationships.find(l=>l.effectiveTime!=null);return u?{statusCode:409,body:{error:`Role group (groupId ${d.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(u.relationshipId)}) with effectiveTime ${String(u.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.relationships=c.filter(l=>(typeof l.groupId=="number"?l.groupId:0)!==d.groupId),null)})}async function Ro(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.gciAxioms)?i.gciAxioms:[],a=s.findIndex(c=>c.axiomId===t.axiomId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(s.splice(a,1),i.gciAxioms=s,null)})}async function Eo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.gciAxioms)?i.gciAxioms:[],a=s.find(d=>d.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}};if(a.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(a.active===!1)return{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}};let c=s.filter(d=>d!==a&&d.active!==!1);return c.length>0&&c.every(d=>d.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.`}}:(a.active=!1,null)})}var Wi=8;async function ve(e,t,r,o){let n=[],i=[],s=0,a=async()=>{for(;;){let d=s++;if(d>=r.length)return;let u=r[d];try{let l=await be(e,{conceptId:u.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),p=l.body;if(l.statusCode<200||l.statusCode>=300){i.push({...u,error:p?.error??`HTTP ${l.statusCode}`});continue}p?.conclusive&&n.push({...u,axiomId:p.axiomId})}catch(l){i.push({...u,error:l instanceof Error?l.message:String(l)})}}},c=Math.min(Wi,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:n,skipped:i}}async function $o(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await Ce(e,{...t,branchPath:o.branchPath},r);if(n.statusCode<200||n.statusCode>=300)return n;let i=n.body?.items??[],s=i.map(d=>({conceptId:d.conceptId,fsn:d.fsn,pt:d.pt})),{matched:a,skipped:c}=await ve(e,o,s,r);return{statusCode:200,body:{branchPath:o.branchPath,totalSearched:i.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function jo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);if(n)return n;let i=A(e),s=`${i}/browser/${o.branchPath}/concepts/${t.conceptId}`,a=await C(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 ${t.conceptId}.`,details:a.body}};if(a.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let c=`${i}/${o.branchPath}/concepts/${t.conceptId}`,d=await C(c,{method:"DELETE",cookie:e.cookie});return d.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] delete-concept ${o.projectKey}/${o.taskKey}: ${d.statusCode<300?"OK":"FAILED ("+d.statusCode+")"} \u2014 ${t.conceptId}`),d.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${t.conceptId} \u2014 one or more of its components is published.`,details:d.body}}:{statusCode:d.statusCode,body:d.body})}var ae="733073007",Po=["Import","SubClassOf","EquivalentClasses","DisjointClasses","DisjointUnion","Annotation","AnnotationAssertion","SubAnnotationPropertyOf","AnnotationPropertyDomain","AnnotationPropertyRange","HasKey","Declaration","InverseObjectProperties","DatatypeDefinition","SubObjectPropertyOf","EquivalentObjectProperties","DisjointObjectProperties","ObjectPropertyDomain","ObjectPropertyRange","FunctionalObjectProperty","InverseFunctionalObjectProperty","ReflexiveObjectProperty","IrreflexiveObjectProperty","SymmetricObjectProperty","AsymmetricObjectProperty","TransitiveObjectProperty","SubDataPropertyOf","EquivalentDataProperties","DisjointDataProperties","DataPropertyDomain","DataPropertyRange","FunctionalDataProperty","SameIndividual","DifferentIndividuals","ClassAssertion","ObjectPropertyAssertion","NegativeObjectPropertyAssertion","DataPropertyAssertion","NegativeDataPropertyAssertion","DLSafeRule"];function Yi(e){let t=e.trim(),r=0;for(let n of t)if(n==="(")r+=1;else if(n===")"&&(r-=1,r<0))return"Unbalanced parentheses in OWL expression (an unmatched ')' ) \u2014 refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly.";if(r!==0)return`Unbalanced parentheses in OWL expression (${r} unclosed '(') \u2014 refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly.`;let o=/^([A-Za-z]+)\s*\(/.exec(t)?.[1];return!o||!Po.includes(o)?`OWL expression doesn't start with a recognized top-level axiom keyword${o?` (saw "${o}")`:""} \u2014 expected one of ${Po.slice(0,6).join(", ")}, ... Refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly. This is only a shallow keyword/paren check, not a real OWL parser \u2014 passing it doesn't guarantee the expression is actually valid.`:null}async function No(e,t,r,o=new Map){if(!t.propertyId)return{statusCode:400,body:{error:"propertyId is required."}};if(!t.owlExpression||!t.owlExpression.trim())return{statusCode:400,body:{error:"owlExpression is required."}};let n=Yi(t.owlExpression);if(n)return{statusCode:400,body:{error:n}};let i=await k(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let s=await b(e,i);if(s)return s;let a=t.moduleId||await _(e,i.projectKey,o),d=`${A(e)}/${i.branchPath}/members`,u=await C(d,{method:"POST",cookie:e.cookie,body:{active:!0,moduleId:a,refsetId:ae,referencedComponentId:t.propertyId,additionalFields:{owlExpression:t.owlExpression}}});return u.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] add-property-axiom ${i.projectKey}/${i.taskKey}: ${u.statusCode>=200&&u.statusCode<300?"OK":"FAILED ("+u.statusCode+")"} \u2014 ${t.propertyId}`),{statusCode:u.statusCode,body:u.body})}async function Do(e,t,r,o=200,n=0){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let i=await k(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let a=`${A(e)}/${i.branchPath}/members?referencedComponentId=${encodeURIComponent(t.conceptId)}&referenceSet=${ae}&limit=${o}&offset=${n}`;t.activeOnly&&(a+="&active=true");let c=await C(a,{cookie:e.cookie});if(c.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(c.statusCode<200||c.statusCode>=300||!c.body)return{statusCode:c.statusCode||500,body:{error:`Could not fetch property axioms for ${t.conceptId}.`,details:c.body}};let u=(c.body.items??[]).map(l=>({memberId:l.memberId,active:l.active,released:l.released,effectiveTime:l.effectiveTime??null,moduleId:l.moduleId,owlExpression:l.additionalFields?.owlExpression??null}));return{statusCode:200,body:{conceptId:t.conceptId,refsetId:ae,total:c.body.total??u.length,axioms:u}}}async function Oo(e,t,r){if(!t.conceptId||!t.memberId)return{statusCode:400,body:{error:"conceptId and memberId are required."}};let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members/${encodeURIComponent(t.memberId)}`,a=await C(s,{cookie:e.cookie});if(a.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(a.statusCode===404)return{statusCode:404,body:{error:`No reference set member ${t.memberId} on this branch.`}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||500,body:{error:`Could not fetch property axiom ${t.memberId}.`,details:a.body}};let c=a.body;if(c.refsetId!==ae)return{statusCode:400,body:{error:`Member ${t.memberId} is not an OWL Axiom reference set member (refsetId ${String(c.refsetId??"unknown")}) \u2014 delete-property-axiom only removes members of refset ${ae}.`}};if(String(c.referencedComponentId)!==t.conceptId)return{statusCode:400,body:{error:`Member ${t.memberId} belongs to concept ${String(c.referencedComponentId)}, not ${t.conceptId} \u2014 refusing to delete; double check the conceptId/memberId pair against get-property-axioms output.`}};let d=await C(s,{method:"DELETE",cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(e.onLog?.(`[${new Date().toISOString()}] delete-property-axiom ${o.projectKey}/${o.taskKey}: ${d.statusCode>=200&&d.statusCode<300?"OK":"FAILED ("+d.statusCode+")"} \u2014 ${t.memberId}`),d.statusCode>=200&&d.statusCode<300){let u=c.additionalFields;return{statusCode:200,body:{deleted:!0,conceptId:t.conceptId,memberId:t.memberId,owlExpression:u?.owlExpression??null}}}return{statusCode:d.statusCode,body:d.body??{error:`Failed to delete property axiom ${t.memberId}.`}}}function Xi(e){let t=[];for(let r of e)t.some(n=>n.componentId===r.componentId&&n.severity===r.severity&&n.conceptId===r.conceptId&&n.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 o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=A(e),i=`${n}/browser/${o.branchPath}/concepts/${t.conceptId}`,s=await C(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(o.branchPath),c=`${n}/browser/${a}/${o.projectKey}/${o.taskKey}/validate/concept`,d=await C(c,{method:"POST",body:Qe(s.body),cookie:e.cookie});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:{error:"Validation check failed.",details:d.body}};let u=Array.isArray(d.body)?Xi(d.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:u,hasErrors:u.some(l=>l.severity==="ERROR"),hasWarnings:u.some(l=>l.severity==="WARNING")}}}var Fo=200;async function Qi(e,t,r){let o=new Map;if(r.length===0)return{terms:o,resolved:!0};let n=`${A(e)}/browser/${t}/concepts/bulk-load`,i=!0;for(let s=0;s<r.length;s+=Fo){let a=r.slice(s,s+Fo),c=await C(n,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){i=!1;continue}for(let d of c.body)o.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:o,resolved:i}}async function q(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=[],i=0;for(;;){let h=`${Ot(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(o.branchPath)}`,g=await C(h,{cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(g.statusCode===404)return{statusCode:200,body:{branchPath:o.branchPath,concepts:[],conceptsClassified:[]}};if(g.statusCode<200||g.statusCode>=300)return{statusCode:g.statusCode,body:{error:"Could not fetch traceability for branch.",details:g.body}};n.push(...g.body?.content??[]);let S=g.body?.totalPages??1;if(g.body?.last!==!1||i+1>=S)break;i+=1}let s=new Map,a=new Map,c=(h,g,S,j)=>{let N=h.get(g);N?(j.forEach(P=>P&&N.componentSubTypes.add(P)),N.lastUpdatedTime=S):h.set(g,{conceptId:g,lastUpdatedTime:S,componentSubTypes:new Set(j.filter(P=>!!P))})};for(let h of n)if(!(h.activityType!=="CONTENT_CHANGE"&&h.activityType!=="CLASSIFICATION_SAVE"))for(let g of h.conceptChanges??[]){let S=String(g.conceptId),j=g.componentChanges??[],N=j.map(D=>D.componentSubType);if(h.activityType==="CLASSIFICATION_SAVE"){c(a,S,h.commitDate,N);continue}let P=j.some(D=>D.componentSubType!=="INFERRED_RELATIONSHIP");c(P?s:a,S,h.commitDate,N)}for(let h of s.keys())a.delete(h);let d=[...new Set([...s.keys(),...a.keys()])],{terms:u,resolved:l}=await Qi(e,o.branchPath,d),p=h=>[...h.values()].sort((g,S)=>(S.lastUpdatedTime??"").localeCompare(g.lastUpdatedTime??"")).map(g=>{let S=l&&!u.has(g.conceptId);return{conceptId:g.conceptId,fsn:u.get(g.conceptId)?.fsn,pt:u.get(g.conceptId)?.pt,...S?{deleted:!0}:{},lastUpdatedTime:g.lastUpdatedTime,changedComponentTypes:[...g.componentSubTypes]}}),y=p(s),I=p(a);return{statusCode:200,body:{branchPath:o.branchPath,...l?{summary:{concepts:y.length,conceptsDeleted:y.filter(h=>h.deleted).length,conceptsClassified:I.length}}:{},concepts:y,conceptsClassified:I}}}async function Lo(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await q(e,t,r);if(n.statusCode<200||n.statusCode>=300){let u=n.body;return{statusCode:n.statusCode,body:{error:u.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=i.filter(u=>!u.deleted),a=s.map(u=>({conceptId:u.conceptId,fsn:u.fsn})),{matched:c,skipped:d}=await ve(e,o,a,r);return{statusCode:200,body:{branchPath:o.branchPath,totalReviewed:s.length,matched:c.length,skipped:d.length,skippedDeleted:i.length-s.length,results:c,skippedConcepts:d}}}async function zi(e,t,r,o){let n=[];for(let i of r){if(i.deleted){n.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},o),a=s.body;if(s.statusCode<200||s.statusCode>=300){n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"failed",error:a.error??`HTTP ${s.statusCode}`});continue}let c=a.validationResults??[];n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return n}async function Ko(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await q(e,t,r);if(n.statusCode<200||n.statusCode>=300){let c=n.body;return{statusCode:n.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=await zi(e,o,i,r),a=c=>s.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:o.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 Mo(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await q(e,t,r);if(n.statusCode<200||n.statusCode>=300){let c=n.body;return{statusCode:n.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=[];for(let[c,d]of i.entries()){if(d.deleted){s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"deleted"});continue}let u=await ke(e,{conceptId:d.conceptId,projectKey:o.projectKey,taskKey:o.taskKey,branchPath:o.branchPath},r),l=u.body,p=`(${c+1}/${i.length})`;if(u.statusCode<200||u.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${o.projectKey}/${o.taskKey}: FAILED (${u.statusCode}) \u2014 ${d.conceptId} ${p}`),s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"failed",error:l?.error??`HTTP ${u.statusCode}`});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${o.projectKey}/${o.taskKey}: OK \u2014 ${d.conceptId} ${p}`),s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"fetched",concept:u.body})}let a=c=>s.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:o.branchPath,summary:{total:s.length,fetched:a("fetched"),skippedDeleted:a("deleted"),failed:a("failed")},concepts:s}}}var Ze=new Set;function _o(e){if(!(!e||typeof e!="object"))for(let t of Ze)t(e)}function Zi(e){return Ze.add(e),()=>Ze.delete(e)}function es(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 we(e){let t=()=>{};return{promise:new Promise(o=>{t=Zi(n=>{es(n,e)&&(t(),o(n))})}),cancel:t}}var nt=["RUNNING","BUILDING","SCHEDULED","QUEUED"],rt=["QUEUED","SCHEDULED","RUNNING"],ts=["Promoted","Completed"],Bo=5e3;function ot(e){return new Promise(t=>setTimeout(t,e))}async function os(e,t,r){let o=0;for(;;){let{done:n,value:i}=await e();if(n)return{value:i,timedOut:!1};if(o>=r)return{value:i,timedOut:!0};o++,await ot(t)}}function ns(){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 rs=ns(),is=180;function ss(){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 as=ss(),cs=900;async function Vo(e,t,r,o,n){let i=r*1e3,s=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],d=o?we(o):void 0,u=await Promise.race(d?[ot(c).then(()=>{}),d.promise]:[ot(c).then(()=>{})]);if(d?.cancel(),u){let y=u.event;n?.(`[${new Date().toISOString()}] woken by notification${y?`: ${y}`:""}`)}let{done:l,value:p}=await e();if(l)return{value:p,timedOut:!1};if(Date.now()-s>=i)return{value:p,timedOut:!0};a++}}async function Go(e,t,r){let o=await K(e,t,r);if(!o)return{error:`Could not fetch task ${t}/${r}.`};if(o.status&&ts.includes(o.status))return{error:`Task ${t}/${r} is ${o.status} \u2014 cannot start a new job.`};if(o.status==="New"){let n=`${E(e)}/projects/${t}/tasks/${r}`;await C(n,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function it(e,t,r){let o=`${E(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await C(o,{method:"POST",body:{},cookie:e.cookie}),(await K(e,t,r))?.latestClassificationJson}async function Uo(e,t,r,o,n){let i,{value:s,timedOut:a}=await Vo(async()=>{let d=(await it(e,t,r))?.status;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||nt.includes(d)),value:d}},rs,n,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function et(e,t,r){let o=`${A(e)}/${t}/classifications`,n=await C(o,{cookie:e.cookie});if(n.body?.items?.length)return n.body.items.find(i=>i.id===r)??n.body.items[n.body.items.length-1]}async function Jo(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i}=o,s=await it(e,n,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 Ho(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await b(e,o);if(n)return n;let{projectKey:i,taskKey:s,branchPath:a}=o,c=await Go(e,i,s);if(c.error)return{statusCode:400,body:{error:c.error}};let d=t.timeoutSeconds??is,u=await it(e,i,s),l=u?.status,p=u?.id;if(p&&l&&nt.includes(l)){e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: found job ${p} already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:P,timedOut:D}=await Uo(e,i,s,a,d),fe=await et(e,a,p),Ve={accepted:!1};return!D&&P==="COMPLETED"&&(Ve=await tt(e,a,i,s,p)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: attached job ${p} final status ${P??"unknown"}${D?" (timed out waiting)":""}, save ${JSON.stringify(Ve)}`),{statusCode:200,body:{jobId:p,finalStatus:P,timedOut:D,details:fe,save:Ve,attachedToExisting:!0}}}if(p&&l==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: found job ${p} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let P=await et(e,a,p),D=await tt(e,a,i,s,p);return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: accepted existing job ${p}, save ${JSON.stringify(D)}`),{statusCode:200,body:{jobId:p,finalStatus:"COMPLETED",timedOut:!1,details:P,save:D,acceptedExisting:!0}}}let y=`${E(e)}/projects/${i}/tasks/${s}/classifications`,I=await C(y,{method:"POST",body:{},cookie:e.cookie});if(I.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!I.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: start failed (HTTP ${I.statusCode}) \u2014 raw body: ${I.rawBody}`),{statusCode:I.statusCode||500,body:{error:"Failed to start classification.",details:I.body??I.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: started (${I.body.status??"unknown"})`);let h=I.body.id;if(!t.wait)return{statusCode:200,body:{jobId:h,status:I.body.status}};let{finalStatus:g,timedOut:S}=await Uo(e,i,s,a,d),j=await et(e,a,h),N={accepted:!1};return!S&&g==="COMPLETED"&&(N=await tt(e,a,i,s,h)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: final status ${g??"unknown"}${S?" (timed out waiting)":""}, save ${JSON.stringify(N)}`),{statusCode:200,body:{jobId:h,finalStatus:g,timedOut:S,details:j,save:N}}}var ds=["SAVED","STALE","SAVE_FAILED"],us=120;async function tt(e,t,r,o,n){let i=`${A(e)}/${t}/classifications/${n}`,s=await C(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(us*1e3/Bo),{value:c,timedOut:d}=await os(async()=>{let l=(await C(i,{cookie:e.cookie})).body?.status;return{done:!!l&&ds.includes(l),value:l}},Bo,a);return d?{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 Wo(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i}=o,a=(await K(e,n,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&rt.includes(a)}}}async function qo(e,t,r,o,n){let i,{value:s,timedOut:a}=await Vo(async()=>{let d=(await K(e,t,r))?.latestValidationStatus;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||rt.includes(d)),value:d}},as,n,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function Yo(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i,branchPath:s}=o,a=await Go(e,n,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??cs,u=(await K(e,n,i))?.latestValidationStatus;if(u&&rt.includes(u)){e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: validation already ${u} \u2014 waiting on it instead of starting a new one`);let{finalStatus:h,timedOut:g}=await qo(e,n,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: attached run final status ${h??"unknown"}${g?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:h,timedOut:g,attachedToExisting:!0}}}let l=`${E(e)}/projects/${n}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(l+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await C(l,{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 ${n}/${i}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:y,timedOut:I}=await qo(e,n,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: final status ${y??"unknown"}${I?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:y,timedOut:I}}}async function Xo(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",o=`${E(e)}/projects${r}`;return(await C(o,{cookie:e.cookie})).body??[]}async function Qo(e,t){let r=`${E(e)}/projects/${t}/tasks`;return(await C(r,{cookie:e.cookie})).body??[]}async function zo(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",o=`${E(e)}/projects/my-tasks${r}`;return(await C(o,{cookie:e.cookie})).body??[]}async function Zo(e,t){let r=`${E(e)}/projects/${t.projectKey}/tasks`,o={summary:t.summary};t.description!==void 0&&(o.description=t.description),t.assigneeUsername&&(o.assignee={username:t.assigneeUsername});let n=await C(r,{method:"POST",body:o,cookie:e.cookie});return n.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:n.statusCode<200||n.statusCode>=300||!n.body?{statusCode:n.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${n.statusCode})${n.rawBody?`: ${n.rawBody}`:""}`}:{statusCode:n.statusCode,task:n.body}}async function en(e,t){let r=`${E(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,o=await C(r,{cookie:e.cookie});return Array.isArray(o.body)?o.body:[]}var ls="IN_PROGRESS";async function tn(e,t){let r=`${E(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,o=await C(r,{cookie:e.cookie});if(o.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(o.statusCode<200||o.statusCode>=300||!o.body)return{statusCode:o.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${o.statusCode}).`};if(o.body.status!=="Deleted")return{statusCode:200,task:o.body,notDeleted:!0};let n=await C(r,{method:"PUT",body:{status:ls},cookie:e.cookie});return n.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:n.statusCode<200||n.statusCode>=300||!n.body?{statusCode:n.statusCode||500,error:`Failed to recover ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode})${n.rawBody?`: ${n.rawBody}`:""}`}:{statusCode:n.statusCode,task:n.body}}function on(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 nn(e=Math.random){let t=String(Math.floor(e()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",o="";for(let n=0;n<8;n++)o+=r[Math.floor(e()*r.length)];return`${t}/${o}/websocket`}function at(e,t={},r=""){let o=Object.entries(t).map(([n,i])=>`${n}:${i}`);return[e,...o,"",r].join(`
3
- `)+"\0"}function rn(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
2
+ "use strict";var fi=Object.create;var Se=Object.defineProperty;var gi=Object.getOwnPropertyDescriptor;var yi=Object.getOwnPropertyNames;var hi=Object.getPrototypeOf,ki=Object.prototype.hasOwnProperty;var Ci=(e,t)=>{for(var r in t)Se(e,r,{get:t[r],enumerable:!0})},Bt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of yi(t))!ki.call(e,n)&&n!==r&&Se(e,n,{get:()=>t[n],enumerable:!(o=gi(t,n))||o.enumerable});return e};var v=(e,t,r)=>(r=e!=null?fi(hi(e)):{},Bt(t||!e||!e.__esModule?Se(r,"default",{value:e,enumerable:!0}):r,e)),Ii=e=>Bt(Se({},"__esModule",{value:!0}),e);var ya={};Ci(ya,{COMMANDS:()=>_t,main:()=>mi,parsePositionals:()=>ui});module.exports=Ii(ya);var H={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"}},xi={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},we=Object.keys(H);function Ut(e){return xi[e.trim().toLowerCase()]??null}var se="uat",ka=H.uat.imsEndpoint,Ca=H.uat.terminologyServerEndpoint,Ia=H.uat.authoringServicesEndpoint;var bi=v(require("http")),vi=v(require("https"));function I(e,t={}){let{method:r="GET",cookie:o,body:n,headers:i={},timeoutMs:s=15e3}=t;return new Promise((a,c)=>{let d;try{d=new URL(e)}catch(g){c(g);return}let l=d.protocol==="https:"?vi:bi,u=n!==void 0?JSON.stringify(n):void 0,p={accept:"application/json",...i};if(u!==void 0&&(p["content-type"]="application/json",p["content-length"]=String(Buffer.byteLength(u))),o){let g=o.replace(/[^\x20-\x7e\t]/g,"");g&&(p.cookie=g)}let y=!1,k=l.request({hostname:d.hostname,port:d.port||void 0,path:d.pathname+d.search,method:r,headers:p},g=>{let x="";g.on("data",E=>{x+=E}),g.on("end",()=>{if(y)return;y=!0,clearTimeout(h);let E=g.statusCode??0,j=(g.headers["content-type"]??"").includes("application/json"),D=null,ve=!1;if(x)try{D=JSON.parse(x)}catch{ve=!j}a({statusCode:E,body:D,rawBody:x,sessionExpired:ve})})});k.on("error",g=>{y||(y=!0,clearTimeout(h),c(g))});let h=setTimeout(()=>{y||(y=!0,k.destroy(),c(new Error(`Request to ${e} timed out after ${s}ms`)))},s);u!==void 0&&k.write(u),k.end()})}var U="900000000000509007",W="900000000000508004";var Vt={[U]:"en-us",[W]:"en-gb"},qt={[U]:"true",[W]:"true"},Si={},wi={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:Vt,dialectDefaults:qt,readOnlyDialects:Si,defaultLanguage:"en"};function Jt(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return wi;let t={[U]:"en-us"},r={},o={},n=[];for(let c of Object.keys(e)){let d=c.match(/^requiredLanguageRefset\.(.+)/);if(d){let l=d[1];t[String(e[c])]=l,n.length===0&&n.push(l)}}let i=e.requiredLanguageRefsets;if(Array.isArray(i))for(let c of i){if(typeof c!="object"||c===null)continue;let d=null,l=null;for(let[k,h]of Object.entries(c))k.length===2&&(d=k,l=String(h));if(!d||!l)continue;let u=c.dialectName;t[l]=typeof u=="string"?u:d;let p=c.default;p==="true"&&!n.includes(d)&&n.push(d),p!=null&&(r[l]=String(p));let y=c.readOnly;y!=null&&(o[l]=String(y))}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?Vt:t,dialectDefaults:a?qt:r,readOnlyDialects:o,defaultLanguage:n[0]??"en"}}function nt(e,t,r,o){let n={};for(let i of Object.keys(e.dialects)){let s=e.dialects[i];e.isExtension&&!r?s.includes(o)?n[i]="PREFERRED":s.includes(e.defaultLanguage)&&(n[i]="ACCEPTABLE"):s.includes(o)&&(n[i]=t),e.dialectDefaults[i]==="false"&&!r&&delete n[i],e.readOnlyDialects[i]==="true"&&delete n[i]}return n}function Te(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[U]:"PREFERRED"}:nt(e,"PREFERRED",t,"en")}var Ti="900000000000207008";function Gt(e){return e.replace(/\/$/,"")}function A(e){return Gt(e.terminologyServerEndpoint)}function $(e){return Gt(e.authoringServicesEndpoint)}function Ht(e){return`${new URL($(e)).origin}/authoring-traceability-service`}function Y(e){return e.split("/").filter(Boolean).slice(0,-2).join("/")}async function C(e,t,r){let o=t.projectKey||r?.projectKey,n=t.taskKey||r?.taskKey,i=!t.projectKey&&!t.taskKey,s=t.branchPath||(i?r?.branchPath:void 0);return!o||!n?{ok:!1,error:'No task context: run "select-task", or pass --project/--task explicitly.'}:(s||(s=await Ai(e,o,n)??void 0),s?{ok:!0,projectKey:o,taskKey:n,branchPath:s}:{ok:!1,error:`Could not resolve branch path for ${o}/${n}.`})}async function X(e,t){let r=A(e),o=await I(`${r}/branches/${encodeURIComponent(t)}`,{cookie:e.cookie});if(o.sessionExpired)return{ok:!1,error:"IMS session expired \u2014 re-sign in."};if(o.statusCode>=200&&o.statusCode<300)return{ok:!0,created:!1};if(o.statusCode!==404)return{ok:!1,error:`Could not check branch ${t} (HTTP ${o.statusCode}).`};let n=t.split("/").filter(Boolean),i=n[n.length-1],s=n.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 Ai(e,t,r){let o=`${$(e)}/projects/${t}/tasks/${r}`;return(await I(o,{cookie:e.cookie})).body?.branchPath??null}async function Wt(e,t,r){let o=r?.get(t);if(o)return o;let n=`${$(e)}/projects/${t}`,s=(await I(n,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function _(e,t,r){let o=await Wt(e,t,r),n=o.multipleModuleEditingDisabled,i=!n||n==="false";return o.expectedExtensionModules?.length&&i?o.expectedExtensionModules[0]:o.defaultModuleId?o.defaultModuleId:Ti}async function z(e,t,r){let o=await Wt(e,t,r);return Jt(o)}async function Q(e,t){let r=e.replace(/\/$/,"")+"/auth",o=await I(r,{cookie:t,timeoutMs:8e3});return o.statusCode>=200&&o.statusCode<300&&o.body?o.body:(console.warn(`[authoring-cli] fetchAccountDetails: HTTP ${o.statusCode} from ${r}`),null)}var Xt=v(require("crypto"));async function M(e,t,r){let o=`${$(e)}/projects/${t}/tasks/${r}`;return(await I(o,{cookie:e.cookie})).body??null}function Yt(e){let t=e?.trim();return t?t.toLowerCase():null}async function S(e,t){let r=Yt(e.currentUsername);if(!r)return null;let o=await M(e,t.projectKey,t.taskKey),n=Yt(o?.assignee?.username);return n?n!==r?{statusCode:403,body:{error:`Not allowed: ${t.projectKey}/${t.taskKey} is authored by "${n}", but the signed-in user is "${r}". Only the Task Author can make changes to a task, including classification.`}}:null:{statusCode:403,body:{error:`Task ${t.projectKey}/${t.taskKey} has no assignee. Only the Task Author may make changes to a task \u2014 including classification \u2014 and nobody is currently assigned.`}}}var Ri="116680003";function ae(e,t,r,o,n="PREFERRED",i=!1){let s=e==="FSN"?Te(o,i):nt(o,n,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function zt(e,t,r,o=new Map){if(!t.fsn||!t.parentConceptId)return{statusCode:400,body:{error:"fsn and parentConceptId are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let{projectKey:s,taskKey:a,branchPath:c}=n,d=Y(c),l=t.moduleId||await _(e,s,o),u=await z(e,s,o),p=t.preferredTerm||t.fsn,y=t.semanticTag?`${t.fsn} (${t.semanticTag})`:t.fsn,k={conceptId:null,moduleId:l,definitionStatus:"PRIMITIVE",active:!0,descriptions:[ae("FSN",y,l,u,"PREFERRED",!0),ae("SYNONYM",p,l,u,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:Xt.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:l,relationships:[{active:!0,groupId:0,type:{conceptId:Ri},target:{conceptId:t.parentConceptId}}]}]},h=`${A(e)}/browser/${d}/${s}/${a}/concepts/?validate=true`,g=await I(h,{method:"POST",body:k,cookie:e.cookie});if(g.sessionExpired){let N="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: SESSION EXPIRED`),{statusCode:401,body:{error:N}}}let x=g.body,E=x&&"conceptId"in x?x.conceptId:void 0;return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: ${g.statusCode<300?"OK":"FAILED ("+g.statusCode+")"} \u2014 ${y}`+(E?` \u2192 ${E}`:"")),typeof E=="string"&&e.onValidationResults?.(E,x?.validationResults),{statusCode:g.statusCode,body:g.body}}var Ei=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],$i={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function Pi(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(o=>o.active!==!1).length}function Qt(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(o=>o.characteristicType===t)}function ce(e){return{conceptId:e.conceptId,fsn:e.fsn,pt:e.pt,active:e.active,definitionStatus:e.definitionStatus}}function de(e){return typeof e=="object"&&e!==null}function ji(e,t,r){let o=Array.isArray(e[r])?e[r]:[],n=[];for(let i of o){if(i.active===!1||typeof i.axiomId!="string")continue;(Array.isArray(i.relationships)?i.relationships:[]).forEach((a,c)=>{let d=a.type;if((de(d)?d.conceptId:void 0)!==t)return;let u=a.target;n.push({axiomId:i.axiomId,relationshipId:typeof a.relationshipId=="string"?a.relationshipId:void 0,relationshipIndex:c,groupId:typeof a.groupId=="number"?a.groupId:0,targetId:de(u)?u.conceptId:void 0,targetFsn:de(u)&&de(u.fsn)?u.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return n}async function Ae(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};if(!t.attributeType){let a=Ei.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>$i[c]).join(", ")}.`}}}if(!t.attributeType&&!t.descriptions&&!t.descriptionFull&&!t.axioms&&!t.inferred&&!t.gci&&!t.gciAxiomsCount&&!t.full){let a=`${A(e)}/${o.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 n=`${A(e)}/browser/${o.branchPath}/concepts/${t.conceptId}`,i=await I(n,{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||!de(i.body))return{statusCode:i.statusCode,body:i.body};let s=i.body;if(t.attributeType){let a=t.gci?"gciAxioms":"classAxioms",c=ji(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:{...ce(s),descriptions:a}}}return t.descriptionFull?{statusCode:i.statusCode,body:{...ce(s),descriptions:s.descriptions??[]}}:t.axioms?{statusCode:i.statusCode,body:{...ce(s),classAxioms:s.classAxioms??[],relationships:Qt(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...ce(s),relationships:Qt(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...ce(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:Pi(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var Ni=500,Di=1e4;async function Re(e,t,r){if(!t.term&&!t.ecl)return{statusCode:400,body:{error:"term or ecl is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n={expand:"fsn()"};t.term&&(n.termFilter=t.term),t.ecl&&(n.eclFilter=t.ecl),typeof t.active=="boolean"&&(n.activeFilter=t.active);let i=`${A(e)}/${o.branchPath}/concepts/search`,s=l=>({conceptId:l.conceptId,fsn:l.fsn?.term,pt:l.pt?.term,active:l.active,moduleId:l.moduleId});if(t.limit!==void 0){let l=await I(i,{method:"POST",body:{...n,limit:t.limit},cookie:e.cookie});if(l.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};let u=(l.body?.items??[]).map(s);return{statusCode:l.statusCode,body:{total:l.body?.total??u.length,items:u}}}let a=[],c=0,d=0;for(;;){let l=Math.min(Ni,Di-d);if(l<=0)break;let u=await I(i,{method:"POST",body:{...n,limit:l,offset:d},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,d+=p.length,p.length===0||d>=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 le=1e3;function Oi(e){let t=new Map;for(let r of e)for(let o of r){let n=o.referenceType?.conceptId??"",i=t.get(n);i?i.referencingConcepts=[...i.referencingConcepts??[],...o.referencingConcepts??[]]:t.set(n,{...o,referencingConcepts:[...o.referencingConcepts??[]]})}return[...t.values()]}async function Zt(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=`${A(e)}/${o.branchPath}/concepts/${t.conceptId}/references`,i=(l,u)=>{let p=new URLSearchParams;return typeof t.stated=="boolean"&&p.set("stated",String(t.stated)),p.set("limit",String(l)),p.set("offset",String(u)),I(`${n}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let l=await i(t.limit??le,t.offset??0);return l.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:{statusCode:l.statusCode,body:l.body}}let s=[],a=0,c=0,d=0;for(;;){let l=await i(le,d);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:l.body??{error:"Could not fetch references."}};let u=l.body?.referencesByType??[];s.push(u),a=l.body?.total??a;let p=u.reduce((y,k)=>y+(k.referencingConcepts?.length??0),0);if(c+=p,p===0||p<le||c>=a)break;d+=le}return{statusCode:200,body:{total:a,limit:le,offset:0,referencesByType:Oi(s)}}}var st=v(require("crypto"));function eo(e){return typeof e=="object"&&e!==null}function Fi(e){let t=e.type,r=e.target,o=eo(t)?t.conceptId:void 0,n=eo(r)?r.conceptId:void 0;return typeof o=="string"&&typeof n=="string"?{typeId:o,targetId:n}:null}function Li(e,t){let r=[...t];for(let o of e){let n=r.findIndex(i=>i.typeId===o.typeId&&i.targetId===o.targetId);if(n===-1)return!1;r.splice(n,1)}return!0}function to(e,t,r){let o=new Map;for(let s of e){let a=typeof s.groupId=="number"?s.groupId:0,c=o.get(a);c?c.push(s):o.set(a,[s])}let n=[];for(let[s,a]of o){if(r!=null?s!==r:s===0)continue;let c=a.map(Fi).filter(d=>d!=null);Li(t,c)&&n.push(s)}if(n.length===0)return{ok:!1,statusCode:404,error:"has no role group containing all of the given attributes."};if(n.length>1)return{ok:!1,statusCode:409,error:`has ${n.length} role groups matching the given attributes (groupIds: ${n.join(", ")}) \u2014 ambiguous. Add another attribute pair to narrow it down to one group, or pass groupId to target one directly.`};let i=n[0];return{ok:!0,groupId:i,relationships:o.get(i)}}var Mi=["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"],_i=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],Bi=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],Ui=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],at=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function po(e){return at.includes(e)}function ue(e,t){let r={};for(let o of t)o in e&&(r[o]=e[o]);return r}function Ee(e){return typeof e=="object"&&e!==null}function oo(e){return Ee(e)?ue(e,Bi):e}function mo(e){if(!Ee(e))return e;let t=ue(e,_i);return"type"in t&&(t.type=oo(t.type)),"target"in t&&(t.target=oo(t.target)),t}function Vi(e){return Ee(e)?ue(e,Ki):e}function no(e){if(!Ee(e))return e;let t=ue(e,Ui);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(mo)),t}function ct(e){let t=ue(e,Mi);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(Vi)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(mo)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(no)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(no)),t}function qi(e){return new Promise(t=>setTimeout(t,e))}function Ji(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 rt=[300,600,1200,2400,4800],ro=new Map;function Gi(e,t){let o=(ro.get(e)??Promise.resolve()).then(t,t);return ro.set(e,o.then(()=>{},()=>{})),o}async function R(e,t,r,o){try{return await Gi(t.branchPath,()=>Hi(e,t,r,o))}catch(n){return{statusCode:500,body:{error:n instanceof Error?n.message:String(n)}}}}async function Hi(e,t,r,o){for(let n=0;;n++){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,d=o(c);if(d)return d;let l=Y(t.branchPath),u=`${i}/browser/${l}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await I(u,{method:"PUT",body:ct(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(Ji(p)&&n<rt.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${n+1}/${rt.length})`),await qi(rt[n]);continue}e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: ${p.statusCode<300?"OK":"FAILED ("+p.statusCode+")"} \u2014 ${r}`);let y=p.body;return e.onValidationResults?.(r,y?.validationResults),{statusCode:p.statusCode,body:p.body}}}var io=["PREFERRED","ACCEPTABLE"];async function fo(e,t,r,o=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&&!io.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${io.join(", ")}.`}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let s=t.moduleId||await _(e,n.projectKey,o),a=await z(e,n.projectKey,o),c=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return R(e,n,t.conceptId,d=>{let l=Array.isArray(d.descriptions)?d.descriptions:[];return l.push(ae(t.type,c,s,a,t.acceptability??"ACCEPTABLE",!1)),d.descriptions=l,null})}async function go(e,t,r){if(!t.conceptId||!t.typeId||!t.targetId)return{statusCode:400,body:{error:"conceptId, typeId, and targetId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let i=t.axiomIndex??0;return R(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[],c=a[i];if(!c)return{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${i} (has ${a.length}).`}};let d=Array.isArray(c.relationships)?c.relationships:[];return d.push({active:!0,groupId:t.groupId??0,type:{conceptId:t.typeId},target:{conceptId:t.targetId}}),c.relationships=d,null})}async function yo(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let i=t.axiomIndex??0;return R(e,o,t.conceptId,s=>{let a=Array.isArray(s.classAxioms)?s.classAxioms:[],c=a[i];return c?(c.definitionStatus=t.status,s.definitionStatus=t.status,null):{statusCode:400,body:{error:`Concept ${t.conceptId} has no classAxiom at index ${i} (has ${a.length}).`}}})}async function ho(e,t,r){if(!t.conceptId||!t.indicator)return{statusCode:400,body:{error:"conceptId and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>i.effectiveTime==null?{statusCode:409,body:{error:`Unpublished concept ${t.conceptId} cannot be inactivated \u2014 it should be deleted instead (use delete-concept).`}}:(i.active=!1,i.inactivationIndicator=t.indicator,t.associationRefsetId&&t.associationTargetId&&(i.associationTargets={[t.associationRefsetId]:[t.associationTargetId]}),null))}async function ko(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&&!po(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${at.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?a.effectiveTime!=null?{statusCode:409,body:{error:`Description ${t.descriptionId} has effectiveTime ${String(a.effectiveTime)} set (already versioned) \u2014 cannot update.`}}:(t.term&&(a.term=t.term),t.caseSignificance&&(a.caseSignificance=t.caseSignificance),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function Co(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!po(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${at.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?(a.caseSignificance=t.caseSignificance,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}var it=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function so(e){return it.includes(e)}function Io(e){return e.us&&!so(e.us)?{statusCode:400,body:{error:`us must be one of: ${it.join(", ")}.`}}:e.gb&&!so(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${it.join(", ")}.`}}:null}function xo(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 dt(e,t,r){let o=e.find(i=>i.descriptionId===r.descriptionId);if(!o)return{statusCode:404,body:{error:`Concept ${t} has no description ${r.descriptionId}.`}};r.lang&&(o.lang=r.lang);let n={...o.acceptabilityMap??{}};return r.us&&(r.us==="NOT_ACCEPTABLE"?delete n[U]:n[U]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete n[W]:n[W]=r.gb),o.active!==!1&&Object.keys(n).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.`}}:(o.acceptabilityMap=n,null)}async function bo(e,t,r){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},n=xo(o);if(n)return n;let i=await C(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let s=await S(e,i);return s||R(e,i,t.conceptId,a=>{let c=Array.isArray(a.descriptions)?a.descriptions:[];return dt(c,t.conceptId,o)})}async function vo(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 i of t.entries){let s=xo(i);if(s)return s}let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[];for(let a of t.entries){let c=dt(s,t.conceptId,a);if(c)return c}return null})}async function So(e,t,r){if(!t.conceptId||!t.descriptionId)return{statusCode:400,body:{error:"conceptId and descriptionId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[],a=s.findIndex(c=>c.descriptionId===t.descriptionId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published description ${t.descriptionId} cannot be deleted \u2014 use inactivate-description instead.`}}:(s.splice(a,1),i.descriptions=s,null)})}var $e="REFERS_TO";async function wo(e,t,r){if(!t.conceptId||!t.descriptionId||!t.indicator)return{statusCode:400,body:{error:"conceptId, descriptionId, and indicator are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.descriptions)?i.descriptions:[]).find(c=>c.descriptionId===t.descriptionId);return a?a.effectiveTime==null?{statusCode:409,body:{error:`Unpublished description ${t.descriptionId} cannot be inactivated \u2014 it should be deleted instead (use delete-description).`}}:(a.active=!1,a.inactivationIndicator=t.indicator,a.acceptabilityMap={},t.associationTargetId&&(a.associationTargets={[$e]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}function ao(e,t,r){for(let o of e){if(o.descriptionId===t||o.active===!1||o.type!=="SYNONYM")continue;let n=o.acceptabilityMap;n?.[r]==="PREFERRED"&&(o.acceptabilityMap={...n,[r]:"ACCEPTABLE"})}}async function To(e,t,r,o=new Map){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},i=Io(n);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 S(e,a);if(c)return c;let d=await z(e,a.projectKey,o);return R(e,a,t.conceptId,l=>{let u=Array.isArray(l.descriptions)?l.descriptions:[],p=u.find(k=>k.descriptionId===t.descriptionId);if(!p)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(p.active!==!1)return{statusCode:409,body:{error:`Description ${t.descriptionId} is already active.`}};if(p.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 k=u.filter(h=>h.type==="FSN"&&h.active!==!1&&h.descriptionId!==t.descriptionId);if(k.length>1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${k.length} other active FSNs \u2014 cannot restore unambiguously.`}};if(k.length===1){let h=k[0];if(h.effectiveTime==null)u.splice(u.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={[$e]:[t.associationTargetId]})}}return p.active=!0,delete p.inactivationIndicator,delete p.associationTargets,p.acceptabilityMap=Te(d,!1),l.descriptions=u,null}if(!s)return{statusCode:400,body:{error:"At least one of lang, us, or gb is required to restore this description's acceptability."}};p.active=!0,delete p.inactivationIndicator,delete p.associationTargets;let y=dt(u,t.conceptId,n);return y||(n.us==="PREFERRED"&&ao(u,t.descriptionId,U),n.gb==="PREFERRED"&&ao(u,t.descriptionId,W),null)})}var Wi="900000000000490003",co=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function Ao(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!co.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${co.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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${Wi}&active=true`,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||500,body:{error:`Could not check description ${t.descriptionId}'s current inactivation reason.`,details:a.body}};let c=(a.body.items??[])[0];return c?.released===!0?{statusCode:409,body:{error:`Description ${t.descriptionId}'s inactivation reason has already been published (effectiveTime ${String(c.effectiveTime)}) and cannot be changed.`}}:R(e,o,t.conceptId,d=>{let u=(Array.isArray(d.descriptions)?d.descriptions:[]).find(p=>p.descriptionId===t.descriptionId);return u?u.active!==!1?{statusCode:409,body:{error:`Description ${t.descriptionId} is active \u2014 use inactivate-description to inactivate it with a reason.`}}:(u.inactivationIndicator=t.reason,t.reason==="NOT_SEMANTICALLY_EQUIVALENT"?u.associationTargets={[$e]:[t.targetId]}:delete u.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function Ro(e,t,r,o=new Map){if(!t.conceptId||!t.term||!t.indicator)return{statusCode:400,body:{error:"conceptId, term, and indicator are required."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let s=t.moduleId||await _(e,n.projectKey,o),a=await z(e,n.projectKey,o),c=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return R(e,n,t.conceptId,d=>{let l=Array.isArray(d.descriptions)?d.descriptions:[],u;if(t.descriptionId){if(u=l.find(p=>p.descriptionId===t.descriptionId),!u)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}};if(u.type!=="FSN")return{statusCode:400,body:{error:`Description ${t.descriptionId} is a ${String(u.type)}, not an FSN.`}}}else{let p=l.filter(y=>y.type==="FSN"&&y.active!==!1);if(p.length!==1)return{statusCode:400,body:{error:`Concept ${t.conceptId} has ${p.length} active FSNs \u2014 pass --description-id to say which one to replace.`}};u=p[0]}return u.effectiveTime==null?{statusCode:409,body:{error:`Description ${String(u.descriptionId)} has no effectiveTime (never versioned) \u2014 use update-description instead.`}}:(u.active=!1,u.inactivationIndicator=t.indicator,u.acceptabilityMap={},t.associationTargetId&&(u.associationTargets={[$e]:[t.associationTargetId]}),l.push(ae("FSN",c,s,a,"PREFERRED",!1)),d.descriptions=l,null)})}function Eo(e,t,r){return R(e,t,r.conceptId,o=>{let i=(Array.isArray(o.classAxioms)?o.classAxioms:[]).find(s=>s.axiomId===r.axiomId);return i?(i.relationships=r.relationships,r.active!=null&&(i.active=r.active),null):{statusCode:404,body:{error:`Concept ${r.conceptId} has no class axiom ${r.axiomId}.`}}})}async function $o(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||Eo(e,o,t)}async function Po(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.gciAxioms)?i.gciAxioms:[]).find(c=>c.axiomId===t.axiomId);return a?(a.relationships=t.relationships,t.active!=null&&(a.active=t.active),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}})}async function jo(e,t,r,o=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 n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let s=t.moduleId||await _(e,n.projectKey,o);return R(e,n,t.conceptId,a=>{let c=Array.isArray(a.classAxioms)?a.classAxioms:[];return c.push({axiomId:st.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.classAxioms=c,null})}async function No(e,t,r,o=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 n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await S(e,n);if(i)return i;let s=t.moduleId||await _(e,n.projectKey,o);return R(e,n,t.conceptId,a=>{let c=Array.isArray(a.gciAxioms)?a.gciAxioms:[];return c.push({axiomId:st.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.gciAxioms=c,null})}async function Do(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s.findIndex(c=>c.axiomId===t.axiomId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-axiom instead.`}}:s.length<2?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one class axiom \u2014 a concept must retain at least one.`}}:(s.splice(a,1),i.classAxioms=s,null)})}async function Oo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.classAxioms)?i.classAxioms:[],a=s.find(d=>d.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};if(a.active===!1)return{statusCode:409,body:{error:`Axiom ${t.axiomId} is already inactive.`}};if(a.effectiveTime==null)return{statusCode:409,body:{error:`Unpublished axiom ${t.axiomId} cannot be inactivated \u2014 it should be deleted instead (use delete-axiom).`}};let c=s.filter(d=>d!==a&&d.active!==!1);return c.length===0?{statusCode:409,body:{error:`Concept ${t.conceptId} has only one active class axiom \u2014 a concept must retain at least one.`}}:c.every(d=>d.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.`}}:(a.active=!1,null)})}var Yi="116680003";function lo(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 Xi(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:Yi},target:{conceptId:i.id}});let o=Array.isArray(e.attributes)?e.attributes:[];for(let i of o)t.push(lo(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(lo(c,s+1))}),t}async function Fo(e,t,r,o){let n=A(e),i=await I(`${n}/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(o){if(a=s.find(c=>c.axiomId===o),!a)return{ok:!1,result:{statusCode:404,body:{error:`Concept ${r} has no class axiom ${o}.`,undetermined:!0}}}}else{let c=s.filter(d=>d.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 zi="116680003";function Qi(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==zi?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function Zi(e,t,r){let o=A(e),n=await I(`${o}/${t.branchPath}/concepts/${r}/authoring-form`,{cookie:e.cookie,timeoutMs:6e4});if(n.sessionExpired)return{ok:!1,result:{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in.",undetermined:!0}}};if(n.statusCode<200||n.statusCode>=300||!n.body)return{ok:!1,result:{statusCode:n.statusCode||500,body:{error:`Could not compute authoring form for ${r}.`,details:n.body,undetermined:!0}}};let i=Xi(n.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 es(e,t,r,o){let n=await Fo(e,t,r,o);if(!n.ok)return n;let i=await Zi(e,t,r);return i.ok?{ok:!0,value:{axiom:n.value.axiom,axiomId:n.value.axiomId,targetRelationships:i.value}}:i}function ts(e){let t=typeof e.typeId=="string"?e.typeId:e.type?.conceptId,r=e.concreteValue;if(r)return`${t}=#${r.dataType}:${r.value}`;let o=typeof e.destinationId=="string"?e.destinationId:e.target?.conceptId;return`${t}=${o}`}function uo(e){let t=new Map;for(let n of e){if(n.active===!1)continue;let i=typeof n.groupId=="number"?n.groupId:0,s=t.get(i)??[];s.push(ts(n)),t.set(i,s)}let r=(t.get(0)??[]).slice().sort(),o=[];for(let[n,i]of t)n!==0&&o.push(i.slice().sort());return{ungrouped:r,groups:o}}function os(e,t){let r=uo(e),o=uo(t);if(r.ungrouped.join("|")!==o.ungrouped.join("|"))return!1;let n=r.groups.map(s=>s.join("|")).sort(),i=o.groups.map(s=>s.join("|")).sort();return n.join("||")===i.join("||")}async function Lo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let i=await es(e,o,t.conceptId,t.axiomId);if(!i.ok)return i.result;let{axiom:s,axiomId:a,targetRelationships:c}=i.value,d=Array.isArray(s.relationships)?s.relationships:[];return os(d,c)?(e.onLog?.(`[${new Date().toISOString()}] transform-axiom ${o.projectKey}/${o.taskKey}: already conforms \u2014 ${t.conceptId}`),{statusCode:200,body:{conceptId:t.conceptId,axiomId:a,alreadyConformed:!0}}):Eo(e,o,{conceptId:t.conceptId,axiomId:a,relationships:c})}async function Pe(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await Fo(e,o,t.conceptId,t.axiomId);if(!n.ok)return n.result;let{axiom:i,axiomId:s}=n.value,a=Array.isArray(i.relationships)?i.relationships:[];return Qi(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 Mo(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 o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.classAxioms)?i.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let c=Array.isArray(a.relationships)?a.relationships:[],d=t.relationshipId?c.findIndex(u=>u.relationshipId===t.relationshipId):t.relationshipIndex,l=d>=0?c[d]:void 0;return l?l.effectiveTime!=null?{statusCode:409,body:{error:`Relationship ${t.relationshipId??`at index ${d}`} has effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(c.splice(d,1),a.relationships=c,null):{statusCode:404,body:{error:`Axiom ${t.axiomId} has no relationship ${t.relationshipId??`at index ${t.relationshipIndex}`}.`}}})}async function Ko(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 i of t.attributes)if(!i||typeof i.typeId!="string"||typeof i.targetId!="string")return{statusCode:400,body:{error:"Each attributes entry requires typeId and targetId."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let a=(Array.isArray(i.classAxioms)?i.classAxioms:[]).find(u=>u.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no class axiom ${t.axiomId}.`}};let c=Array.isArray(a.relationships)?a.relationships:[],d=to(c,t.attributes,t.groupId);if(!d.ok)return{statusCode:d.statusCode,body:{error:`Axiom ${t.axiomId} ${d.error}`}};let l=d.relationships.find(u=>u.effectiveTime!=null);return l?{statusCode:409,body:{error:`Role group (groupId ${d.groupId}) on axiom ${t.axiomId} has a relationship (relationshipId ${String(l.relationshipId)}) with effectiveTime ${String(l.effectiveTime)} set (already versioned) \u2014 cannot remove.`}}:(a.relationships=c.filter(u=>(typeof u.groupId=="number"?u.groupId:0)!==d.groupId),null)})}async function _o(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.gciAxioms)?i.gciAxioms:[],a=s.findIndex(c=>c.axiomId===t.axiomId);return a===-1?{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}}:s[a].effectiveTime!=null?{statusCode:409,body:{error:`Published GCI axiom ${t.axiomId} cannot be deleted \u2014 use inactivate-gci-axiom instead.`}}:(s.splice(a,1),i.gciAxioms=s,null)})}async function Bo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||R(e,o,t.conceptId,i=>{let s=Array.isArray(i.gciAxioms)?i.gciAxioms:[],a=s.find(d=>d.axiomId===t.axiomId);if(!a)return{statusCode:404,body:{error:`Concept ${t.conceptId} has no GCI axiom ${t.axiomId}.`}};if(a.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(a.active===!1)return{statusCode:409,body:{error:`GCI axiom ${t.axiomId} is already inactive.`}};let c=s.filter(d=>d!==a&&d.active!==!1);return c.length>0&&c.every(d=>d.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.`}}:(a.active=!1,null)})}var ns=8;async function je(e,t,r,o){let n=[],i=[],s=0,a=async()=>{for(;;){let d=s++;if(d>=r.length)return;let l=r[d];try{let u=await Pe(e,{conceptId:l.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),p=u.body;if(u.statusCode<200||u.statusCode>=300){i.push({...l,error:p?.error??`HTTP ${u.statusCode}`});continue}p?.conclusive&&n.push({...l,axiomId:p.axiomId})}catch(u){i.push({...l,error:u instanceof Error?u.message:String(u)})}}},c=Math.min(ns,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:n,skipped:i}}async function Uo(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await Re(e,{...t,branchPath:o.branchPath},r);if(n.statusCode<200||n.statusCode>=300)return n;let i=n.body?.items??[],s=i.map(d=>({conceptId:d.conceptId,fsn:d.fsn,pt:d.pt})),{matched:a,skipped:c}=await je(e,o,s,r);return{statusCode:200,body:{branchPath:o.branchPath,totalSearched:i.length,matched:a.length,skipped:c.length,results:a,skippedConcepts:c}}}async function Vo(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let i=A(e),s=`${i}/browser/${o.branchPath}/concepts/${t.conceptId}`,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 ${t.conceptId}.`,details:a.body}};if(a.body.effectiveTime!=null)return{statusCode:409,body:{error:`Published concept ${t.conceptId} cannot be deleted \u2014 use inactivate-concept instead.`}};let c=`${i}/${o.branchPath}/concepts/${t.conceptId}`,d=await I(c,{method:"DELETE",cookie:e.cookie});return d.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] delete-concept ${o.projectKey}/${o.taskKey}: ${d.statusCode<300?"OK":"FAILED ("+d.statusCode+")"} \u2014 ${t.conceptId}`),d.statusCode===409?{statusCode:409,body:{error:`Cannot delete concept ${t.conceptId} \u2014 one or more of its components is published.`,details:d.body}}:{statusCode:d.statusCode,body:d.body})}var pe="733073007",qo=["Import","SubClassOf","EquivalentClasses","DisjointClasses","DisjointUnion","Annotation","AnnotationAssertion","SubAnnotationPropertyOf","AnnotationPropertyDomain","AnnotationPropertyRange","HasKey","Declaration","InverseObjectProperties","DatatypeDefinition","SubObjectPropertyOf","EquivalentObjectProperties","DisjointObjectProperties","ObjectPropertyDomain","ObjectPropertyRange","FunctionalObjectProperty","InverseFunctionalObjectProperty","ReflexiveObjectProperty","IrreflexiveObjectProperty","SymmetricObjectProperty","AsymmetricObjectProperty","TransitiveObjectProperty","SubDataPropertyOf","EquivalentDataProperties","DisjointDataProperties","DataPropertyDomain","DataPropertyRange","FunctionalDataProperty","SameIndividual","DifferentIndividuals","ClassAssertion","ObjectPropertyAssertion","NegativeObjectPropertyAssertion","DataPropertyAssertion","NegativeDataPropertyAssertion","DLSafeRule"];function rs(e){let t=e.trim(),r=0;for(let n of t)if(n==="(")r+=1;else if(n===")"&&(r-=1,r<0))return"Unbalanced parentheses in OWL expression (an unmatched ')' ) \u2014 refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly.";if(r!==0)return`Unbalanced parentheses in OWL expression (${r} unclosed '(') \u2014 refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly.`;let o=/^([A-Za-z]+)\s*\(/.exec(t)?.[1];return!o||!qo.includes(o)?`OWL expression doesn't start with a recognized top-level axiom keyword${o?` (saw "${o}")`:""} \u2014 expected one of ${qo.slice(0,6).join(", ")}, ... Refusing to send this to Snowstorm: a malformed expression here can leave the branch permanently locked server-side (confirmed live; see addPropertyAxiom's doc comment), not just fail cleanly. This is only a shallow keyword/paren check, not a real OWL parser \u2014 passing it doesn't guarantee the expression is actually valid.`:null}async function Jo(e,t,r,o=new Map){if(!t.propertyId)return{statusCode:400,body:{error:"propertyId is required."}};if(!t.owlExpression||!t.owlExpression.trim())return{statusCode:400,body:{error:"owlExpression is required."}};let n=rs(t.owlExpression);if(n)return{statusCode:400,body:{error:n}};let i=await C(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let s=await S(e,i);if(s)return s;let a=t.moduleId||await _(e,i.projectKey,o),d=`${A(e)}/${i.branchPath}/members`,l=await I(d,{method:"POST",cookie:e.cookie,body:{active:!0,moduleId:a,refsetId:pe,referencedComponentId:t.propertyId,additionalFields:{owlExpression:t.owlExpression}}});return l.sessionExpired?{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}}:(e.onLog?.(`[${new Date().toISOString()}] add-property-axiom ${i.projectKey}/${i.taskKey}: ${l.statusCode>=200&&l.statusCode<300?"OK":"FAILED ("+l.statusCode+")"} \u2014 ${t.propertyId}`),{statusCode:l.statusCode,body:l.body})}async function Go(e,t,r,o=200,n=0){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let i=await C(e,t,r);if(!i.ok)return{statusCode:400,body:{error:i.error}};let a=`${A(e)}/${i.branchPath}/members?referencedComponentId=${encodeURIComponent(t.conceptId)}&referenceSet=${pe}&limit=${o}&offset=${n}`;t.activeOnly&&(a+="&active=true");let c=await I(a,{cookie:e.cookie});if(c.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(c.statusCode<200||c.statusCode>=300||!c.body)return{statusCode:c.statusCode||500,body:{error:`Could not fetch property axioms for ${t.conceptId}.`,details:c.body}};let l=(c.body.items??[]).map(u=>({memberId:u.memberId,active:u.active,released:u.released,effectiveTime:u.effectiveTime??null,moduleId:u.moduleId,owlExpression:u.additionalFields?.owlExpression??null}));return{statusCode:200,body:{conceptId:t.conceptId,refsetId:pe,total:c.body.total??l.length,axioms:l}}}async function Ho(e,t,r){if(!t.conceptId||!t.memberId)return{statusCode:400,body:{error:"conceptId and memberId are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members/${encodeURIComponent(t.memberId)}`,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===404)return{statusCode:404,body:{error:`No reference set member ${t.memberId} on this branch.`}};if(a.statusCode<200||a.statusCode>=300||!a.body)return{statusCode:a.statusCode||500,body:{error:`Could not fetch property axiom ${t.memberId}.`,details:a.body}};let c=a.body;if(c.refsetId!==pe)return{statusCode:400,body:{error:`Member ${t.memberId} is not an OWL Axiom reference set member (refsetId ${String(c.refsetId??"unknown")}) \u2014 delete-property-axiom only removes members of refset ${pe}.`}};if(String(c.referencedComponentId)!==t.conceptId)return{statusCode:400,body:{error:`Member ${t.memberId} belongs to concept ${String(c.referencedComponentId)}, not ${t.conceptId} \u2014 refusing to delete; double check the conceptId/memberId pair against get-property-axioms output.`}};let d=await I(s,{method:"DELETE",cookie:e.cookie});if(d.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(e.onLog?.(`[${new Date().toISOString()}] delete-property-axiom ${o.projectKey}/${o.taskKey}: ${d.statusCode>=200&&d.statusCode<300?"OK":"FAILED ("+d.statusCode+")"} \u2014 ${t.memberId}`),d.statusCode>=200&&d.statusCode<300){let l=c.additionalFields;return{statusCode:200,body:{deleted:!0,conceptId:t.conceptId,memberId:t.memberId,owlExpression:l?.owlExpression??null}}}return{statusCode:d.statusCode,body:d.body??{error:`Failed to delete property axiom ${t.memberId}.`}}}function is(e){let t=[];for(let r of e)t.some(n=>n.componentId===r.componentId&&n.severity===r.severity&&n.conceptId===r.conceptId&&n.message===r.message)||t.push(r);return t}async function Ne(e,t,r){if(!t.conceptId)return{statusCode:400,body:{error:"conceptId is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=A(e),i=`${n}/browser/${o.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=Y(o.branchPath),c=`${n}/browser/${a}/${o.projectKey}/${o.taskKey}/validate/concept`,d=await I(c,{method:"POST",body:ct(s.body),cookie:e.cookie});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:{error:"Validation check failed.",details:d.body}};let l=Array.isArray(d.body)?is(d.body):[];return{statusCode:200,body:{conceptId:t.conceptId,validationResults:l,hasErrors:l.some(u=>u.severity==="ERROR"),hasWarnings:l.some(u=>u.severity==="WARNING")}}}var Wo=200;async function ss(e,t,r){let o=new Map;if(r.length===0)return{terms:o,resolved:!0};let n=`${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(n,{method:"POST",body:{conceptIds:a},cookie:e.cookie});if(c.statusCode<200||c.statusCode>=300||!Array.isArray(c.body)){i=!1;continue}for(let d of c.body)o.set(d.conceptId,{fsn:d.fsn?.term,pt:d.pt?.term})}return{terms:o,resolved:i}}async function V(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=[],i=0;for(;;){let h=`${Ht(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(o.branchPath)}`,g=await I(h,{cookie:e.cookie});if(g.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(g.statusCode===404)return{statusCode:200,body:{branchPath:o.branchPath,concepts:[],conceptsClassified:[]}};if(g.statusCode<200||g.statusCode>=300)return{statusCode:g.statusCode,body:{error:"Could not fetch traceability for branch.",details:g.body}};n.push(...g.body?.content??[]);let x=g.body?.totalPages??1;if(g.body?.last!==!1||i+1>=x)break;i+=1}let s=new Map,a=new Map,c=(h,g,x,E)=>{let N=h.get(g);N?(E.forEach(j=>j&&N.componentSubTypes.add(j)),N.lastUpdatedTime=x):h.set(g,{conceptId:g,lastUpdatedTime:x,componentSubTypes:new Set(E.filter(j=>!!j))})};for(let h of n)if(!(h.activityType!=="CONTENT_CHANGE"&&h.activityType!=="CLASSIFICATION_SAVE"))for(let g of h.conceptChanges??[]){let x=String(g.conceptId),E=g.componentChanges??[],N=E.map(D=>D.componentSubType);if(h.activityType==="CLASSIFICATION_SAVE"){c(a,x,h.commitDate,N);continue}let j=E.some(D=>D.componentSubType!=="INFERRED_RELATIONSHIP");c(j?s:a,x,h.commitDate,N)}for(let h of s.keys())a.delete(h);let d=[...new Set([...s.keys(),...a.keys()])],{terms:l,resolved:u}=await ss(e,o.branchPath,d),p=h=>[...h.values()].sort((g,x)=>(x.lastUpdatedTime??"").localeCompare(g.lastUpdatedTime??"")).map(g=>{let x=u&&!l.has(g.conceptId);return{conceptId:g.conceptId,fsn:l.get(g.conceptId)?.fsn,pt:l.get(g.conceptId)?.pt,...x?{deleted:!0}:{},lastUpdatedTime:g.lastUpdatedTime,changedComponentTypes:[...g.componentSubTypes]}}),y=p(s),k=p(a);return{statusCode:200,body:{branchPath:o.branchPath,...u?{summary:{concepts:y.length,conceptsDeleted:y.filter(h=>h.deleted).length,conceptsClassified:k.length}}:{},concepts:y,conceptsClassified:k}}}async function Yo(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await V(e,t,r);if(n.statusCode<200||n.statusCode>=300){let l=n.body;return{statusCode:n.statusCode,body:{error:l.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=i.filter(l=>!l.deleted),a=s.map(l=>({conceptId:l.conceptId,fsn:l.fsn})),{matched:c,skipped:d}=await je(e,o,a,r);return{statusCode:200,body:{branchPath:o.branchPath,totalReviewed:s.length,matched:c.length,skipped:d.length,skippedDeleted:i.length-s.length,results:c,skippedConcepts:d}}}async function as(e,t,r,o){let n=[];for(let i of r){if(i.deleted){n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"deleted"});continue}let s=await Ne(e,{conceptId:i.conceptId,projectKey:t.projectKey,taskKey:t.taskKey,branchPath:t.branchPath},o),a=s.body;if(s.statusCode<200||s.statusCode>=300){n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:"failed",error:a.error??`HTTP ${s.statusCode}`});continue}let c=a.validationResults??[];n.push({conceptId:i.conceptId,fsn:i.fsn,outcome:c.length===0?"clean":"issues",validationResults:c.length?c:void 0,hasErrors:a.hasErrors})}return n}async function Xo(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await V(e,t,r);if(n.statusCode<200||n.statusCode>=300){let c=n.body;return{statusCode:n.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=await as(e,o,i,r),a=c=>s.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:o.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 zo(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await V(e,t,r);if(n.statusCode<200||n.statusCode>=300){let c=n.body;return{statusCode:n.statusCode,body:{error:c.error??"Could not list concepts for review."}}}let i=n.body.concepts??[],s=[];for(let[c,d]of i.entries()){if(d.deleted){s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"deleted"});continue}let l=await Ae(e,{conceptId:d.conceptId,projectKey:o.projectKey,taskKey:o.taskKey,branchPath:o.branchPath},r),u=l.body,p=`(${c+1}/${i.length})`;if(l.statusCode<200||l.statusCode>=300){e.onLog?.(`[${new Date().toISOString()}] get-concept ${o.projectKey}/${o.taskKey}: FAILED (${l.statusCode}) \u2014 ${d.conceptId} ${p}`),s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"failed",error:u?.error??`HTTP ${l.statusCode}`});continue}e.onLog?.(`[${new Date().toISOString()}] get-concept ${o.projectKey}/${o.taskKey}: OK \u2014 ${d.conceptId} ${p}`),s.push({conceptId:d.conceptId,fsn:d.fsn,outcome:"fetched",concept:l.body})}let a=c=>s.filter(d=>d.outcome===c).length;return{statusCode:200,body:{branchPath:o.branchPath,summary:{total:s.length,fetched:a("fetched"),skippedDeleted:a("deleted"),failed:a("failed")},concepts:s}}}var lt=new Set;function Qo(e){if(!(!e||typeof e!="object"))for(let t of lt)t(e)}function cs(e){return lt.add(e),()=>lt.delete(e)}function ds(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 De(e){let t=()=>{};return{promise:new Promise(o=>{t=cs(n=>{ds(n,e)&&(t(),o(n))})}),cancel:t}}var ft=["RUNNING","BUILDING","SCHEDULED","QUEUED"],gt=["QUEUED","SCHEDULED","RUNNING"],ls=["Promoted","Completed"],Zo=5e3;function mt(e){return new Promise(t=>setTimeout(t,e))}async function us(e,t,r){let o=0;for(;;){let{done:n,value:i}=await e();if(n)return{value:i,timedOut:!1};if(o>=r)return{value:i,timedOut:!0};o++,await mt(t)}}function ps(){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 ms=ps(),fs=180;function gs(){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 ys=gs(),hs=900;async function on(e,t,r,o,n){let i=r*1e3,s=Date.now(),a=0;for(;;){let c=t[Math.min(a,t.length-1)],d=o?De(o):void 0,l=await Promise.race(d?[mt(c).then(()=>{}),d.promise]:[mt(c).then(()=>{})]);if(d?.cancel(),l){let y=l.event;n?.(`[${new Date().toISOString()}] woken by notification${y?`: ${y}`:""}`)}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 nn(e,t,r){let o=await M(e,t,r);if(!o)return{error:`Could not fetch task ${t}/${r}.`};if(o.status&&ls.includes(o.status))return{error:`Task ${t}/${r} is ${o.status} \u2014 cannot start a new job.`};if(o.status==="New"){let n=`${$(e)}/projects/${t}/tasks/${r}`;await I(n,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function yt(e,t,r){let o=`${$(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await I(o,{method:"POST",body:{},cookie:e.cookie}),(await M(e,t,r))?.latestClassificationJson}async function en(e,t,r,o,n){let i,{value:s,timedOut:a}=await on(async()=>{let d=(await yt(e,t,r))?.status;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||ft.includes(d)),value:d}},ms,n,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function ut(e,t,r){let o=`${A(e)}/${t}/classifications`,n=await I(o,{cookie:e.cookie});if(n.body?.items?.length)return n.body.items.find(i=>i.id===r)??n.body.items[n.body.items.length-1]}async function rn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i}=o,s=await yt(e,n,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:ft.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function sn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);if(n)return n;let{projectKey:i,taskKey:s,branchPath:a}=o,c=await nn(e,i,s);if(c.error)return{statusCode:400,body:{error:c.error}};let d=t.timeoutSeconds??fs,l=await yt(e,i,s),u=l?.status,p=l?.id;if(p&&u&&ft.includes(u)){e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: found job ${p} already ${u} \u2014 waiting on it instead of starting a new one`);let{finalStatus:j,timedOut:D}=await en(e,i,s,a,d),ve=await ut(e,a,p),ot={accepted:!1};return!D&&j==="COMPLETED"&&(ot=await pt(e,a,i,s,p)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: attached job ${p} final status ${j??"unknown"}${D?" (timed out waiting)":""}, save ${JSON.stringify(ot)}`),{statusCode:200,body:{jobId:p,finalStatus:j,timedOut:D,details:ve,save:ot,attachedToExisting:!0}}}if(p&&u==="COMPLETED"){e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: found job ${p} already COMPLETED and unsaved \u2014 accepting it instead of starting a new run`);let j=await ut(e,a,p),D=await pt(e,a,i,s,p);return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: accepted existing job ${p}, save ${JSON.stringify(D)}`),{statusCode:200,body:{jobId:p,finalStatus:"COMPLETED",timedOut:!1,details:j,save:D,acceptedExisting:!0}}}let y=`${$(e)}/projects/${i}/tasks/${s}/classifications`,k=await I(y,{method:"POST",body:{},cookie:e.cookie});if(k.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(!k.body?.id)return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: start failed (HTTP ${k.statusCode}) \u2014 raw body: ${k.rawBody}`),{statusCode:k.statusCode||500,body:{error:"Failed to start classification.",details:k.body??k.rawBody}};e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: started (${k.body.status??"unknown"})`);let h=k.body.id;if(!t.wait)return{statusCode:200,body:{jobId:h,status:k.body.status}};let{finalStatus:g,timedOut:x}=await en(e,i,s,a,d),E=await ut(e,a,h),N={accepted:!1};return!x&&g==="COMPLETED"&&(N=await pt(e,a,i,s,h)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: final status ${g??"unknown"}${x?" (timed out waiting)":""}, save ${JSON.stringify(N)}`),{statusCode:200,body:{jobId:h,finalStatus:g,timedOut:x,details:E,save:N}}}var ks=["SAVED","STALE","SAVE_FAILED"],Cs=120;async function pt(e,t,r,o,n){let i=`${A(e)}/${t}/classifications/${n}`,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(Cs*1e3/Zo),{value:c,timedOut:d}=await us(async()=>{let u=(await I(i,{cookie:e.cookie})).body?.status;return{done:!!u&&ks.includes(u),value:u}},Zo,a);return d?{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 an(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i}=o,a=(await M(e,n,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&gt.includes(a)}}}async function tn(e,t,r,o,n){let i,{value:s,timedOut:a}=await on(async()=>{let d=(await M(e,t,r))?.latestValidationStatus;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||gt.includes(d)),value:d}},ys,n,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function cn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i,branchPath:s}=o,a=await nn(e,n,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??hs,l=(await M(e,n,i))?.latestValidationStatus;if(l&&gt.includes(l)){e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: validation already ${l} \u2014 waiting on it instead of starting a new one`);let{finalStatus:h,timedOut:g}=await tn(e,n,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: attached run final status ${h??"unknown"}${g?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:h,timedOut:g,attachedToExisting:!0}}}let u=`${$(e)}/projects/${n}/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 ${n}/${i}: started`),!t.wait)return{statusCode:200,body:{started:!0}};let{finalStatus:y,timedOut:k}=await tn(e,n,i,s,c);return e.onLog?.(`[${new Date().toISOString()}] validate ${n}/${i}: final status ${y??"unknown"}${k?" (timed out waiting)":""}`),{statusCode:200,body:{finalStatus:y,timedOut:k}}}async function dn(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",o=`${$(e)}/projects${r}`;return(await I(o,{cookie:e.cookie})).body??[]}async function ln(e,t){let r=`${$(e)}/projects/${t}/tasks`;return(await I(r,{cookie:e.cookie})).body??[]}async function un(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",o=`${$(e)}/projects/my-tasks${r}`;return(await I(o,{cookie:e.cookie})).body??[]}async function pn(e,t){let r=`${$(e)}/projects/${t.projectKey}/tasks`,o={summary:t.summary};t.description!==void 0&&(o.description=t.description),t.assigneeUsername&&(o.assignee={username:t.assigneeUsername});let n=await I(r,{method:"POST",body:o,cookie:e.cookie});return n.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:n.statusCode<200||n.statusCode>=300||!n.body?{statusCode:n.statusCode||500,error:`Failed to create task in ${t.projectKey} (HTTP ${n.statusCode})${n.rawBody?`: ${n.rawBody}`:""}`}:{statusCode:n.statusCode,task:n.body}}async function mn(e,t){let r=`${$(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,o=await I(r,{cookie:e.cookie});return Array.isArray(o.body)?o.body:[]}var Is="IN_PROGRESS";async function fn(e,t){let r=`${$(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,o=await I(r,{cookie:e.cookie});if(o.sessionExpired)return{statusCode:401,error:"IMS session expired \u2014 re-sign in."};if(o.statusCode<200||o.statusCode>=300||!o.body)return{statusCode:o.statusCode||404,error:`No task ${t.projectKey}/${t.taskKey} (HTTP ${o.statusCode}).`};if(o.body.status!=="Deleted")return{statusCode:200,task:o.body,notDeleted:!0};let n=await I(r,{method:"PUT",body:{status:Is},cookie:e.cookie});return n.sessionExpired?{statusCode:401,error:"IMS session expired \u2014 re-sign in."}:n.statusCode<200||n.statusCode>=300||!n.body?{statusCode:n.statusCode||500,error:`Failed to recover ${t.projectKey}/${t.taskKey} (HTTP ${n.statusCode})${n.rawBody?`: ${n.rawBody}`:""}`}:{statusCode:n.statusCode,task:n.body}}function gn(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 ht(e){return JSON.stringify([e])}function yn(e=Math.random){let t=String(Math.floor(e()*1e3)).padStart(3,"0"),r="abcdefghijklmnopqrstuvwxyz0123456789",o="";for(let n=0;n<8;n++)o+=r[Math.floor(e()*r.length)];return`${t}/${o}/websocket`}function kt(e,t={},r=""){let o=Object.entries(t).map(([n,i])=>`${n}:${i}`);return[e,...o,"",r].join(`
3
+ `)+"\0"}function hn(e){let t=e.replace(/\0$/,"");if(t.trim()==="")return null;let r=t.indexOf(`
4
4
 
5
5
  `),o=r===-1?t:t.slice(0,r),n=r===-1?"":t.slice(r+2),i=o.split(`
6
- `),s=i[0],a={};for(let c of i.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:s,headers:a,body:n}}var an=w(require("ws"));var sn=[1e3,2e3,5e3,1e4,3e4];function cn(e,t={}){let r=t.createSocket??((u,l)=>new an.default(u,l)),o=!1,n,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(o)return;let u=sn[Math.min(i,sn.length-1)];i+=1,s=setTimeout(d,u)};function d(){if(o)return;let l=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${nn()}`,p=r(l,a?{headers:{cookie:a}}:{});n=p,p.on("message",y=>{let I=on(y.toString());if(I.type==="open"){p.send(st(at("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(I.type==="close"){p.close();return}if(I.type==="message")for(let h of I.messages){let g=rn(h);if(g){if(g.command==="CONNECTED"){i=0;let S=`/topic/user/${e.login}/notifications`;p.send(st(at("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:S})));continue}if(g.command==="MESSAGE"){try{e.onNotification(JSON.parse(g.body))}catch(S){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",S)}continue}g.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",g.headers,g.body)}}}),p.on("unexpected-response",(y,I)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${I.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),p.terminate()}),p.on("error",y=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",y.message)}),p.on("close",c)}return d(),{stop(){o=!0,s&&clearTimeout(s),n?.removeAllListeners(),n?.close()}}}function dn(e,t,r={}){let o=r.startRelay??cn,n=r.onNotification??_o,i=o({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:n});return{stop:()=>i.stop()}}var ps=60;async function un(e,t,r){let o=await k(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i,branchPath:s}=o,a=t.timeoutSeconds??ps,c=we({entityType:t.entityType,projectKey:n,taskKey:i,branchPath:s}),d,u=new Promise(y=>{d=setTimeout(()=>y({kind:"timeout"}),a*1e3)}),l=c.promise.then(y=>({kind:"notification",payload:y})),p=await Promise.race([l,u]);return c.cancel(),clearTimeout(d),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",o=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",n=t.componentId??t.conceptId??"?";console.log(`${o} ${r} [${n}] ${t.message??""}`)}}var Ln=w(require("http")),Fe=require("child_process"),Kn=require("util");var Te=w(require("fs")),ln=w(require("os")),Ae=w(require("path"));function dt(){return Ae.join(ln.homedir(),".authoring-cli-chrome")}function X(){return Ae.join(dt(),"profile")}function ms(){return Ae.join(X(),"Local State")}function fs(){let e=ms();if(!Te.existsSync(e))return[];let t;try{t=JSON.parse(Te.readFileSync(e,"utf8"))}catch{return[]}let r=t?.profile?.info_cache??{};return Object.entries(r).map(([o,n])=>({directoryName:o,displayName:typeof n?.name=="string"&&n.name?n.name:o}))}var ct="authoring-cli";function Re(e=fs()){return e.find(r=>r.directoryName===ct)??{directoryName:ct,displayName:ct}}var xn=require("child_process"),bn=require("util"),Pe=w(require("fs")),ft=w(require("os")),Ne=w(require("path"));var pn=require("child_process"),mn=require("util"),Ee=w(require("crypto")),V=w(require("fs")),ys=(0,mn.promisify)(pn.exec);function ut(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}var gs="peanuts";async function fn(e=process.platform){if(e==="darwin"){let{stdout:t}=await ys('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return t.trim()}if(e==="linux")return gs;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}var yn=1003,hs=1;function gn(e){if(e==="darwin")return yn;if(e==="linux")return hs;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}function hn(e,t=yn){return Ee.pbkdf2Sync(e,"saltysalt",t,16,"sha1")}function kn(e,t){if(!e)return null;let r=Buffer.from(e,"hex");if(r.length<4)return null;let o=r.subarray(0,3).toString("utf8");if(o!=="v10"&&o!=="v11")return null;let n=Buffer.alloc(16,32),i=r.subarray(3),s;try{let d=Ee.createDecipheriv("aes-128-cbc",t,n);s=Buffer.concat([d.update(i),d.final()])}catch{return null}let a=s.length>32?s.subarray(32):null,c=s;return a&&ut(a)&&!ut(s)&&(c=a),ut(c)?c.toString("utf8"):null}function lt(e,t){V.copyFileSync(e,t);for(let r of["-wal","-shm"]){let o=e+r;V.existsSync(o)&&V.copyFileSync(o,t+r)}}function pt(e){for(let t of[e,e+"-wal",e+"-shm"])try{V.unlinkSync(t)}catch{}}var Cn=w(require("fs"));var In=[{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"}],Td=Array.from(new Set(In.map(e=>e.configDir)));function $e(){return In.find(e=>Cn.existsSync(e.path))??null}var ks=(0,bn.promisify)(xn.exec),je=class extends Error{},mt=class extends Error{};function vn(e){return Ne.join(X(),e,"Cookies")}function Cs(e=process.platform){return e==="linux"?$e()!==null:Pe.existsSync("/Applications/Google Chrome.app")}function Is(e){let t=e.split(".").filter(Boolean),r=[];for(let o=0;o+1<t.length;o++){let n=t.slice(o).join(".");r.push(n,`.${n}`)}return r}function xs(e){let t=e?.code;return t==="EPERM"||t==="EACCES"}async function yt(e,t,r,o=process.platform){let n=vn(e);if(!n||!Pe.existsSync(n))return null;let i=Ne.join(ft.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);try{lt(n,i);let s;try{s=await fn(o)}catch{return null}let a=hn(s,gn(o)),c=p=>`'${p.replace(/'/g,"''")}'`,u=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${Is(t).map(c).join(", ")}) AND name = ${c(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:l}=await ks(`sqlite3 "${i}" "${u}"`);return kn(l.trim(),a)}catch{return null}finally{pt(i)}}function bs(e){let t=vn(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 lt(t,r),null}catch(o){return xs(o)?`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 vs(e){return new Promise(t=>setTimeout(t,e))}async function Sn(e,t={}){let r=t.platform??process.platform,o=t.isChromeInstalled??(()=>Cs(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(!o())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 n=t.readCookie??((y,I,h)=>yt(y,I,h,r)),i=t.sleep??vs,s=t.onWarning??(y=>console.error(y)),a=t.checkCookieFileReadable??bs,c=e.pollIntervalMs??750,d=e.timeoutMs??15e3,u=a(e.profileDirectory);u&&s(u);let l=await n(e.profileDirectory,e.host,e.cookieName),p=Date.now()+d;for(;Date.now()<p;){let y=await n(e.profileDirectory,e.host,e.cookieName);if(y&&y!==l)return y;await i(c)}throw new mt(`Timed out after ${d}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"),Tn=require("util"),O=w(require("fs")),An=w(require("net")),Rn=(0,Tn.promisify)(Oe.exec),De=1,ce=`:${De}`,Ss=["termux-x11","/data/data/com.termux/files/usr/bin/termux-x11"],gt="/data/data/com.termux/files/usr/bin",wn="com.termux.x11",ws=`${wn}/${wn}.MainActivity`,Ts="termux-x11-start-app";function ht(e){return`/tmp/.X11-unix/X${e}`}async function As(){for(let e of Ss){if(e.startsWith("/")){if(O.existsSync(e))return e;continue}try{return await Rn(`command -v ${e}`),e}catch{}}return null}function Rs(e,t=500){return new Promise(r=>{let o=ht(e);if(!O.existsSync(o)){r(!1);return}let n=An.createConnection({path:o}),i=s=>{n.removeAllListeners(),n.destroy(),r(s)};n.setTimeout(t),n.once("connect",()=>i(!0)),n.once("error",()=>i(!1)),n.once("timeout",()=>i(!1))})}function Es(e,t=1e4){let r=Date.now()+t;return new Promise((o,n)=>{let i=()=>{if(O.existsSync(ht(e))){o();return}if(Date.now()>r){n(new Error(`Termux:X11's display socket for :${e} never appeared within ${t}ms`));return}setTimeout(i,100)};i()})}async function $s(){if(!O.existsSync(gt))return;let e=`${gt}/${Ts}`,t=`${gt}/bash`,o=`#!${O.existsSync(t)?t:"/bin/sh"}
7
- am start --user 0 -n ${ws} >/dev/null 2>&1
8
- `;try{O.writeFileSync(e,o,{mode:493}),O.chmodSync(e,493),await Rn(e,{timeout:5e3})}catch{}}async function En(e=process.platform){if(e!=="linux"||await Rs(De))return ce;await $s();let t=await As();if(t===null)return ce;try{O.unlinkSync(ht(De))}catch{}return(0,Oe.spawn)(t,[ce],{detached:!0,stdio:"ignore"}).unref(),await Es(De),ce}var F=w(require("fs")),jn=w(require("os")),B=w(require("path"));var de=class extends Error{},js="com.ysgao.authoring-cli.chrome-login",Pn="authoring-cli-chrome",Ps="/Applications/Google Chrome.app";function Ns(e=Ps,t=F.existsSync){let r=B.join(e,"Contents","MacOS","Google Chrome");if(t(r))return r;throw new de(`No Google Chrome installation found at ${e}. Install Google Chrome to use automatic session capture.`)}function $n(e){return`'${e.replace(/'/g,"'\\''")}'`}function Ds(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 ${$n(e)} \\`,t.map(r=>` ${$n(r)}`).join(` \\
6
+ `),s=i[0],a={};for(let c of i.slice(1)){let d=c.indexOf(":");d!==-1&&(a[c.slice(0,d)]=c.slice(d+1))}return{command:s,headers:a,body:n}}var Cn=v(require("ws"));var kn=[1e3,2e3,5e3,1e4,3e4];function In(e,t={}){let r=t.createSocket??((l,u)=>new Cn.default(l,u)),o=!1,n,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(o)return;let l=kn[Math.min(i,kn.length-1)];i+=1,s=setTimeout(d,l)};function d(){if(o)return;let u=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${yn()}`,p=r(u,a?{headers:{cookie:a}}:{});n=p,p.on("message",y=>{let k=gn(y.toString());if(k.type==="open"){p.send(ht(kt("CONNECT",{"accept-version":"1.1,1.0","heart-beat":"0,0",host:"/"})));return}if(k.type==="close"){p.close();return}if(k.type==="message")for(let h of k.messages){let g=hn(h);if(g){if(g.command==="CONNECTED"){i=0;let x=`/topic/user/${e.login}/notifications`;p.send(ht(kt("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:x})));continue}if(g.command==="MESSAGE"){try{e.onNotification(JSON.parse(g.body))}catch(x){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",x)}continue}g.command==="ERROR"&&console.warn("[authoring-cli] scaNotificationRelay: STOMP ERROR frame",g.headers,g.body)}}}),p.on("unexpected-response",(y,k)=>{console.warn(`[authoring-cli] scaNotificationRelay: unexpected HTTP ${k.statusCode} on WS upgrade \u2014 check authoringServicesEndpoint/cookie`),p.terminate()}),p.on("error",y=>{console.warn("[authoring-cli] scaNotificationRelay: WebSocket error:",y.message)}),p.on("close",c)}return d(),{stop(){o=!0,s&&clearTimeout(s),n?.removeAllListeners(),n?.close()}}}function xn(e,t,r={}){let o=r.startRelay??In,n=r.onNotification??Qo,i=o({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:n});return{stop:()=>i.stop()}}var xs=60;async function bn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let{projectKey:n,taskKey:i,branchPath:s}=o,a=t.timeoutSeconds??xs,c=De({entityType:t.entityType,projectKey:n,taskKey:i,branchPath:s}),d,l=new Promise(y=>{d=setTimeout(()=>y({kind:"timeout"}),a*1e3)}),u=c.promise.then(y=>({kind:"notification",payload:y})),p=await Promise.race([u,l]);return c.cancel(),clearTimeout(d),p.kind==="timeout"?{statusCode:200,body:{timedOut:!0}}:{statusCode:200,body:{timedOut:!1,notification:p.payload}}}function b(e){if(!(!Array.isArray(e)||e.length===0))for(let t of e){let r=t.severity??"INFO",o=r==="ERROR"?"\u2717":r==="WARNING"?"\u26A0":"\u2139",n=t.componentId??t.conceptId??"?";console.log(`${o} ${r} [${n}] ${t.message??""}`)}}var Wn=v(require("http")),He=require("child_process"),Yn=require("util");var Oe=v(require("fs")),vn=v(require("os")),Fe=v(require("path"));function It(){return Fe.join(vn.homedir(),".authoring-cli-chrome")}function q(){return Fe.join(It(),"profile")}function bs(){return Fe.join(q(),"Local State")}function vs(){let e=bs();if(!Oe.existsSync(e))return[];let t;try{t=JSON.parse(Oe.readFileSync(e,"utf8"))}catch{return[]}let r=t?.profile?.info_cache??{};return Object.entries(r).map(([o,n])=>({directoryName:o,displayName:typeof n?.name=="string"&&n.name?n.name:o}))}var Ct="authoring-cli";function Le(e=vs()){return e.find(r=>r.directoryName===Ct)??{directoryName:Ct,displayName:Ct}}var En=require("child_process"),$n=require("util"),me=v(require("fs")),qe=v(require("os")),fe=v(require("path"));var Sn=require("child_process"),wn=require("util"),Me=v(require("crypto")),J=v(require("fs")),Ss=(0,wn.promisify)(Sn.exec);function xt(e){for(let t=0;t<e.length;t++){let r=e[t];if(r<32||r>=127)return!1}return!0}var ws="peanuts";async function bt(e=process.platform){if(e==="darwin"){let{stdout:t}=await Ss('security find-generic-password -w -s "Chrome Safe Storage" -a "Chrome"');return t.trim()}if(e==="linux")return ws;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}var Tn=1003,Ts=1;function vt(e){if(e==="darwin")return Tn;if(e==="linux")return Ts;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}function St(e,t=Tn){return Me.pbkdf2Sync(e,"saltysalt",t,16,"sha1")}function wt(e,t){if(!e)return null;let r=Buffer.from(e,"hex");if(r.length<4)return null;let o=r.subarray(0,3).toString("utf8");if(o!=="v10"&&o!=="v11")return null;let n=Buffer.alloc(16,32),i=r.subarray(3),s;try{let d=Me.createDecipheriv("aes-128-cbc",t,n);s=Buffer.concat([d.update(i),d.final()])}catch{return null}let a=s.length>32?s.subarray(32):null,c=s;return a&&xt(a)&&!xt(s)&&(c=a),xt(c)?c.toString("utf8"):null}function Ke(e,t){J.copyFileSync(e,t);for(let r of["-wal","-shm"]){let o=e+r;J.existsSync(o)&&J.copyFileSync(o,t+r)}}function _e(e){for(let t of[e,e+"-wal",e+"-shm"])try{J.unlinkSync(t)}catch{}}var An=v(require("fs"));var Rn=[{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"}],Kd=Array.from(new Set(Rn.map(e=>e.configDir)));function Be(){return Rn.find(e=>An.existsSync(e.path))??null}function Ue(e){let t=null;return async(r,o)=>{if(!r)return!1;if(!e)return r!==o;if(r===t)return!1;let n=await e(r);return n||(t=r),n}}var Pn=(0,$n.promisify)(En.exec),Ve=class extends Error{},Z=class extends Error{};function Tt(e){return fe.join(q(),e,"Cookies")}function As(e=process.platform){return e==="linux"?Be()!==null:me.existsSync("/Applications/Google Chrome.app")}function Rs(e){let t=e.split(".").filter(Boolean),r=[];for(let o=0;o+1<t.length;o++){let n=t.slice(o).join(".");r.push(n,`.${n}`)}return r}function Es(e){let t=e?.code;return t==="EPERM"||t==="EACCES"}async function At(e,t,r,o=process.platform){let n=Tt(e);if(!n||!me.existsSync(n))return null;let i=fe.join(qe.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);try{Ke(n,i);let s;try{s=await bt(o)}catch{return null}let a=St(s,vt(o)),c=p=>`'${p.replace(/'/g,"''")}'`,l=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${Rs(t).map(c).join(", ")}) AND name = ${c(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:u}=await Pn(`sqlite3 "${i}" "${l}"`);return wt(u.trim(),a)}catch{return null}finally{_e(i)}}async function $s(e,t=process.platform,r=25){let o=Tt(e);if(!o||!me.existsSync(o))return{checked:0,decrypted:0};let n=fe.join(qe.tmpdir(),`authoring-cli-chrome-cookies-diag-${process.pid}-${Date.now()}.db`);try{Ke(o,n);let i;try{i=await bt(t)}catch{return{checked:0,decrypted:0}}let s=St(i,vt(t)),{stdout:a}=await Pn(`sqlite3 "${n}" "SELECT hex(encrypted_value) FROM cookies WHERE length(encrypted_value) > 0 LIMIT ${r};"`),c=a.split(`
7
+ `).map(l=>l.trim()).filter(Boolean),d=0;for(let l of c)wt(l,s)!==null&&d++;return{checked:c.length,decrypted:d}}catch{return{checked:0,decrypted:0}}finally{_e(n)}}function Ps(e){let t=Tt(e);if(!me.existsSync(t))return null;let r=fe.join(qe.tmpdir(),`authoring-cli-chrome-cookies-precheck-${process.pid}-${Date.now()}.db`);try{return Ke(t,r),null}catch(o){return Es(o)?`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{_e(r)}}function js(e){return new Promise(t=>setTimeout(t,e))}async function jn(e,t={}){let r=t.platform??process.platform,o=t.isChromeInstalled??(()=>As(r));if(r!=="darwin"&&r!=="linux")throw new Ve(`Automatic session capture is only supported on macOS or Linux with Chrome/Chromium. Detected platform: ${r}. Use the manual cookie-paste fallback instead.`);if(!o())throw new Ve(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 n=t.readCookie??((g,x,E)=>At(g,x,E,r)),i=t.sleep??js,s=t.onWarning??(g=>console.error(g)),a=t.checkCookieFileReadable??Ps,c=t.diagnoseDecryption??$s,d=Ue(t.validateCookie),l=e.pollIntervalMs??750,u=e.timeoutMs??15e3,p=a(e.profileDirectory);p&&s(p);let y=await n(e.profileDirectory,e.host,e.cookieName);if(await d(y,y))return y;let k=Date.now()+u;for(;Date.now()<k;){let g=await n(e.profileDirectory,e.host,e.cookieName);if(await d(g,y))return g;await i(l)}let h=await c(e.profileDirectory,r).catch(()=>({checked:0,decrypted:0}));throw h.checked>0&&h.decrypted===0?new Z(`Timed out after ${u}ms waiting for a fresh "${e.cookieName}" cookie for ${e.host} in Chrome profile "${e.profileDirectory}" \u2014 but this is NOT the usual "signed into the wrong window" mistake: ${h.checked} existing cookie(s) already in this exact profile's own jar all failed to decrypt with this tool's current decryption routine (0 of ${h.checked} readable). That means the sign-in almost certainly worked, but the installed Chrome has changed its cookie-encryption format to something this version of authoring-cli no longer knows how to decrypt \u2014 most likely from a Chrome auto-update since the last time login worked. Retrying login will not help. Use the manual cookie-paste fallback instead: open this same Chrome profile, open DevTools \u2192 Application/Storage \u2192 Cookies \u2192 ${e.host}, copy the "${e.cookieName}" row's Value, and run "authoring-cli login --cookie <value>".`):new Z(`Timed out after ${u}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 (authoring-cli login --cookie <value>).`)}var ee=v(require("fs")),Et=v(require("path")),Nn=v(require("ws"));var G=class extends Error{};function Dn(e){try{ee.unlinkSync(Et.join(e,"DevToolsActivePort"))}catch{}}async function Ns(e,t=1e4,r=100){let o=Et.join(e,"DevToolsActivePort"),n=Date.now()+t;for(;;){if(ee.existsSync(o)){let i=ee.readFileSync(o,"utf8").trim().split(`
8
+ `),[s,a]=i;if(s&&a)return`ws://127.0.0.1:${s}${a}`}if(Date.now()>=n)throw new G(`Timed out after ${t}ms waiting for Chrome's DevToolsActivePort file at ${o} \u2014 --remote-debugging-port may not be supported on this Chrome build/platform.`);await new Promise(i=>setTimeout(i,r))}}var Rt=class e{constructor(t){this.socket=t;t.on("message",r=>{let o;try{o=JSON.parse(r.toString())}catch{return}let n=this.pending.get(o.id);n&&(this.pending.delete(o.id),o.error?n.reject(new Error(o.error.message)):n.resolve(o.result))})}socket;nextId=1;pending=new Map;static async connect(t,r=1e4,o=i=>new Nn.default(i),n=150){let i=Date.now()+r,s;for(;;)try{return await e.attemptConnect(t,Math.max(i-Date.now(),1),o)}catch(c){if(s=c,Date.now()>=i)break;await new Promise(d=>setTimeout(d,n))}let a=s instanceof Error?s.message:String(s);throw new G(`Could not connect to CDP at ${t} within ${r}ms: ${a}`)}static attemptConnect(t,r,o){return new Promise((n,i)=>{let s=o(t),a=setTimeout(()=>{s.terminate(),i(new Error(`timed out after ${r}ms`))},r);s.once("open",()=>{clearTimeout(a),n(new e(s))}),s.once("error",c=>{clearTimeout(a),i(c)})})}send(t,r={},o){let n=this.nextId++,i={id:n,method:t,params:r};return o&&(i.sessionId=o),new Promise((s,a)=>{this.pending.set(n,{resolve:s,reject:a}),this.socket.send(JSON.stringify(i),c=>{c&&(this.pending.delete(n),a(c))})})}close(){this.socket.close()}};async function Ds(e,t,r=100){let o=Date.now()+t;for(;;){let{targetInfos:n}=await e.send("Target.getTargets"),i=n.find(s=>s.type==="page");if(i)return i.targetId;if(Date.now()>=o)throw new G(`No page target appeared via CDP within ${t}ms.`);await new Promise(s=>setTimeout(s,r))}}async function On(e,t={}){let r=t.waitForPort??Ns,o=t.connect??Rt.connect,n=t.sleep??(u=>new Promise(p=>setTimeout(p,u))),i=e.setupTimeoutMs??1e4,s=e.pollIntervalMs??750,a=e.timeoutMs??12e4,c=Ue(t.validateCookie),d=await r(e.userDataDir,i),l=await o(d,i);try{let u=await Ds(l,i),{sessionId:p}=await l.send("Target.attachToTarget",{targetId:u,flatten:!0});await l.send("Network.enable",{},p);let y=async()=>{let{cookies:g}=await l.send("Network.getCookies",{urls:[e.cookieUrl]},p);return g.find(x=>x.name===e.cookieName)?.value??null},k=await y();if(await c(k,k))return k;let h=Date.now()+a;for(;Date.now()<h;){let g=await y();if(await c(g,k))return g;await n(s)}throw new Z(`Timed out after ${a}ms waiting for a valid "${e.cookieName}" cookie for ${e.host} via Chrome's own DevTools Protocol \u2014 Chrome itself reports no live session, which rules out a decryption problem (this path never decrypts anything; Chrome hands the value over directly). A common cause: sign-in happened in a DIFFERENT, already-open Chrome window/profile instead of the one this command opened. Otherwise use the manual cookie-paste fallback (authoring-cli login --cookie <value>).`)}finally{l.close()}}var Ge=require("child_process"),Ln=require("util"),O=v(require("fs")),Mn=v(require("net")),Kn=(0,Ln.promisify)(Ge.exec),Je=1,ge=`:${Je}`,Os=["termux-x11","/data/data/com.termux/files/usr/bin/termux-x11"],$t="/data/data/com.termux/files/usr/bin",Fn="com.termux.x11",Fs=`${Fn}/${Fn}.MainActivity`,Ls="termux-x11-start-app";function Pt(e){return`/tmp/.X11-unix/X${e}`}async function Ms(){for(let e of Os){if(e.startsWith("/")){if(O.existsSync(e))return e;continue}try{return await Kn(`command -v ${e}`),e}catch{}}return null}function Ks(e,t=500){return new Promise(r=>{let o=Pt(e);if(!O.existsSync(o)){r(!1);return}let n=Mn.createConnection({path:o}),i=s=>{n.removeAllListeners(),n.destroy(),r(s)};n.setTimeout(t),n.once("connect",()=>i(!0)),n.once("error",()=>i(!1)),n.once("timeout",()=>i(!1))})}function _s(e,t=1e4){let r=Date.now()+t;return new Promise((o,n)=>{let i=()=>{if(O.existsSync(Pt(e))){o();return}if(Date.now()>r){n(new Error(`Termux:X11's display socket for :${e} never appeared within ${t}ms`));return}setTimeout(i,100)};i()})}async function Bs(){if(!O.existsSync($t))return;let e=`${$t}/${Ls}`,t=`${$t}/bash`,o=`#!${O.existsSync(t)?t:"/bin/sh"}
9
+ am start --user 0 -n ${Fs} >/dev/null 2>&1
10
+ `;try{O.writeFileSync(e,o,{mode:493}),O.chmodSync(e,493),await Kn(e,{timeout:5e3})}catch{}}async function _n(e=process.platform){if(e!=="linux"||await Ks(Je))return ge;await Bs();let t=await Ms();if(t===null)return ge;try{O.unlinkSync(Pt(Je))}catch{}return(0,Ge.spawn)(t,[ge],{detached:!0,stdio:"ignore"}).unref(),await _s(Je),ge}var F=v(require("fs")),Un=v(require("os")),B=v(require("path"));var ye=class extends Error{},Us="com.ysgao.authoring-cli.chrome-login",Vn="authoring-cli-chrome",Vs="/Applications/Google Chrome.app";function qs(e=Vs,t=F.existsSync){let r=B.join(e,"Contents","MacOS","Google Chrome");if(t(r))return r;throw new ye(`No Google Chrome installation found at ${e}. Install Google Chrome to use automatic session capture.`)}function Bn(e){return`'${e.replace(/'/g,"'\\''")}'`}function Js(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 ${Bn(e)} \\`,t.map(r=>` ${Bn(r)}`).join(` \\
9
11
  `),""].join(`
10
- `)}function Os(){return`<?xml version="1.0" encoding="UTF-8"?>
12
+ `)}function Gs(){return`<?xml version="1.0" encoding="UTF-8"?>
11
13
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
12
14
  <plist version="1.0">
13
15
  <dict>
14
- <key>CFBundleExecutable</key><string>${Pn}</string>
15
- <key>CFBundleIdentifier</key><string>${js}</string>
16
+ <key>CFBundleExecutable</key><string>${Vn}</string>
17
+ <key>CFBundleIdentifier</key><string>${Us}</string>
16
18
  <key>CFBundleName</key><string>authoring-cli sign-in</string>
17
19
  <key>CFBundlePackageType</key><string>APPL</string>
18
20
  <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
19
21
  <key>CFBundleShortVersionString</key><string>1.0</string>
20
22
  </dict>
21
23
  </plist>
22
- `}function Fs(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 de(`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 Nn(){return[B.join(dt(),"launcher"),B.join(jn.tmpdir(),"authoring-cli-chrome-launcher")]}function Dn(){return`login-${process.pid}.app`}function On(e){let t=e.chromeBinary??Ns(),r=Ds(t,e.flags);Fs(r,e.profileDirectory);let o=e.dirCandidates??Nn(),n=[];for(let i of o){let s=B.join(i,Dn()),a=B.join(s,"Contents","MacOS");try{F.mkdirSync(a,{recursive:!0}),F.writeFileSync(B.join(s,"Contents","Info.plist"),Os());let c=B.join(a,Pn);return F.writeFileSync(c,r,{mode:493}),F.chmodSync(c,493),s}catch(c){n.push(`${i}: ${c instanceof Error?c.message:String(c)}`)}}throw new de(`Could not create the Chrome launcher bundle in any candidate directory (${n.join("; ")}).`)}function Fn(e=Nn()){for(let t of e)try{F.rmSync(B.join(t,Dn()),{recursive:!0,force:!0})}catch{}}var Mn=(0,Kn.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 Ls=["--no-sandbox","--password-store=basic","--force-device-scale-factor=2"],_n=["--no-first-run","--no-default-browser-check"];async function Ks(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 o=process.env.DISPLAY||await En();(0,Fe.spawn)(r.path,[..._n,...Ls,`--user-data-dir=${X()}`,`--profile-directory=${t}`,e],{detached:!0,stdio:"ignore",env:{...process.env,DISPLAY:o}}).unref()}async function Ms(e,t){let r=`--user-data-dir=${X()}`,o=[r,`--profile-directory=${t}`,..._n,e],n=On({flags:o,profileDirectory:t});await Mn(`open -n -a ${(s=>`'${s.replace(/'/g,"'\\''")}'`)(n)}`),qs(r).then(s=>{s&&Fn()})}var _s=1e4,Bs=250;function Us(e){return new Promise(t=>setTimeout(t,e))}async function qs(e,t=_s,r=Bs){let o=i=>`'${i.replace(/'/g,"'\\''")}'`,n=Date.now()+t;for(;;){try{let{stdout:i}=await Mn(`pgrep -f ${o(e)}`);if(i.trim().length>0)return!0}catch{}if(Date.now()>=n)return!1;await Us(r)}}function Vs(e,t,r){return r==="linux"?Ks(e,t):Ms(e,t)}function Gs(){return`<!DOCTYPE html>
24
+ `}function Hs(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 ye(`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 qn(){return[B.join(It(),"launcher"),B.join(Un.tmpdir(),"authoring-cli-chrome-launcher")]}function Jn(){return`login-${process.pid}.app`}function Gn(e){let t=e.chromeBinary??qs(),r=Js(t,e.flags);Hs(r,e.profileDirectory);let o=e.dirCandidates??qn(),n=[];for(let i of o){let s=B.join(i,Jn()),a=B.join(s,"Contents","MacOS");try{F.mkdirSync(a,{recursive:!0}),F.writeFileSync(B.join(s,"Contents","Info.plist"),Gs());let c=B.join(a,Vn);return F.writeFileSync(c,r,{mode:493}),F.chmodSync(c,493),s}catch(c){n.push(`${i}: ${c instanceof Error?c.message:String(c)}`)}}throw new ye(`Could not create the Chrome launcher bundle in any candidate directory (${n.join("; ")}).`)}function Hn(e=qn()){for(let t of e)try{F.rmSync(B.join(t,Jn()),{recursive:!0,force:!0})}catch{}}var Xn=(0,Yn.promisify)(He.exec);function jt(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}var Ws=["--no-sandbox","--password-store=basic","--force-device-scale-factor=2"],zn=["--no-first-run","--no-default-browser-check","--remote-debugging-port=0"];async function Ys(e,t){let r=Be();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 o=process.env.DISPLAY||await _n();(0,He.spawn)(r.path,[...zn,...Ws,`--user-data-dir=${q()}`,`--profile-directory=${t}`,e],{detached:!0,stdio:"ignore",env:{...process.env,DISPLAY:o}}).unref()}async function Xs(e,t){let r=`--user-data-dir=${q()}`,o=[r,`--profile-directory=${t}`,...zn,e],n=Gn({flags:o,profileDirectory:t});await Xn(`open -n -a ${(s=>`'${s.replace(/'/g,"'\\''")}'`)(n)}`),ea(r).then(s=>{s&&Hn()})}var zs=1e4,Qs=250;function Zs(e){return new Promise(t=>setTimeout(t,e))}async function ea(e,t=zs,r=Qs){let o=i=>`'${i.replace(/'/g,"'\\''")}'`,n=Date.now()+t;for(;;){try{let{stdout:i}=await Xn(`pgrep -f ${o(e)}`);if(i.trim().length>0)return!0}catch{}if(Date.now()>=n)return!1;await Zs(r)}}function ta(e,t,r){return r==="linux"?Ys(e,t):Xs(e,t)}function oa(){return`<!DOCTYPE html>
23
25
  <html>
24
26
  <head>
25
27
  <meta charset="utf-8">
@@ -30,20 +32,20 @@ am start --user 0 -n ${ws} >/dev/null 2>&1
30
32
  <h3>You're signed in.</h3>
31
33
  <p>Return to your terminal \u2014 the CLI is finishing sign-in automatically. You can close this tab.</p>
32
34
  </body>
33
- </html>`}function Bn(e,t={}){let r=e.cookieName??kt(e.host),o=t.platform??process.platform,n=t.openChrome??((d,u)=>Vs(d,u,o)),i=t.resolveProfile??Re,s=t.captureCookie??Sn,a=e.timeoutMs??12e4,c=i();return new Promise((d,u)=>{let l=!1,p=I=>{l||(l=!0,y.close(),I())},y=Ln.createServer((I,h)=>{if((I.url||"/").split("?")[0]==="/callback"){h.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),h.end(Gs());return}h.writeHead(404),h.end()});y.listen(0,"127.0.0.1",()=>{let h=`http://localhost:${y.address().port}/callback`,g=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(h)}`;(async()=>{try{await n(g,c.directoryName);let S=await s({profileDirectory:c.directoryName,host:e.host,cookieName:r,timeoutMs:a});p(()=>d({cookie:`${r}=${S}`}))}catch(S){p(()=>u(S))}})()}),y.on("error",I=>p(()=>u(I)))})}var L=w(require("fs")),le=w(require("path")),Un="AUTHORING_CLI_HOME";function Js(){return le.join(process.cwd(),".authoring-cli")}function Hs(){let e=process.env[Un];return e&&e.trim()!==""?le.resolve(e):null}function Le(){return Hs()??Js()}function ue(e){return le.join(e,"session.json")}function Ct(){let e=ue(Le());if(!L.existsSync(e))return null;let t=L.readFileSync(e,"utf8");return JSON.parse(t)}function Ke(e){let t=Le(),r={...e,updatedAt:new Date().toISOString()};try{L.mkdirSync(t,{recursive:!0,mode:448}),L.writeFileSync(ue(t),JSON.stringify(r,null,2),{mode:384})}catch(o){let n=o?.code;throw n==="EPERM"||n==="EACCES"?new Error(`Couldn't write the session to ${ue(t)} (${n}): the current directory isn't writable. Run authoring-cli from a writable directory, or set ${Un} to an explicit, writable location.`):o}}function qn(){let e=ue(Le());L.existsSync(e)&&L.unlinkSync(e)}function It(){return ue(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 Ws(e,t,r,o){let n=await yt(o,t,r).catch(()=>null);if(!n)return null;let i=`${r}=${n}`,s=await Je(e,i).catch(()=>null);return s?{cookie:i,account:s}:null}function Vn(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 Gn(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:o,explicit:n,source:i}of e)console.log(` ${(o+":").padEnd(t+2)}${r} (${n?"from flag":i})`)}async function Jn(e){let t=e.environment?$t(e.environment):te;if(!t){console.error(`Unknown environment: ${e.environment}
34
- Expected one of: ${ge.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=G[t],o=e.imsEndpoint||r.imsEndpoint,n=e.terminologyServerEndpoint||r.terminologyServerEndpoint,i=e.authoringServicesEndpoint||r.authoringServicesEndpoint,s;try{s=new URL(o).hostname}catch{console.error(`Invalid --ims-endpoint: ${o}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||kt(s),d=t===te&&!e.environment?`${t}, default`:t,u=[{url:o,label:"IMS",explicit:!!e.imsEndpoint},{url:n,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:i,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(h=>({...h,source:d})),l=Re(),p=await Ws(o,s,c,l.directoryName);if(p){Ke({cookie:p.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:p.account,currentTask:null}),console.log(`${Vn(p.account)} (reused an existing Chrome session in profile "${l.directoryName}" \u2014 no browser opened.)`),Gn(u),console.log(` Session: ${It()}`);return}console.log(`Opening Chrome (profile "${l.directoryName}") to sign in to ${o} ...`),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 "${l.directoryName}" \u2014 not whichever Chrome window happened to already be in front.`);let y;try{y=await Bn({imsEndpoint:o,host:s,cookieName:c})}catch(h){console.error(h instanceof Error?h.message:String(h)),process.exitCode=1;return}if(!y){console.error("Timed out waiting for sign-in to complete. Try again, or check that Chrome opened correctly."),process.exitCode=1;return}let I=await Je(o,y.cookie).catch(()=>null);Ke({cookie:y.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:I,currentTask:null}),console.log(Vn(I)),Gn(u),console.log(` Session: ${It()}`)}async function Hn(){qn(),console.log("Signed out.")}var _e=w(require("fs")),Me=w(require("path"));async function Wn(){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(_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=Ct();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function xt(e){let t=e.account;return t?.login??t?.username}function f(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,currentUsername:xt(e),onLog:t=>console.error(t)}}function Yn(e){return e.projectKey??e.key??"?"}async function Xn(e){let t=m(),r=f(t),o=await Xo(r);if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log("No projects available.");return}let n=Math.max(...o.map(i=>Yn(i).length))+1;for(let i of o){let s=i.title??"";console.log(`${Yn(i).padEnd(n)}${s?`"${s}"`:""}`)}}function Be(e){return e.taskKey??e.key??"?"}function Qn(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Ys(e){return e.projectKey||Be(e).split("-")[0]||"?"}function bt(e,t){let r=new Map;for(let o of e){let n=t(o);r.set(n,(r.get(n)??0)+1)}return[...r].sort((o,n)=>n[1]-o[1]||o[0].localeCompare(n[0]))}function vt(e,t){let r=Math.max(...t.map(([n])=>n.length)),o=Math.max(...t.map(([,n])=>String(n).length));console.log(""),console.log(`${e}:`);for(let[n,i]of t)console.log(` ${n.padEnd(r)} ${String(i).padStart(o)}`)}async function zn(e){let t=m(),r=f(t),o=e.mine||!e.project,n=o?await zo(r):await Qo(r,e.project);if(o&&e.project){let u=e.project.toLowerCase();n=n.filter(l=>(l.projectKey??"").toLowerCase()===u||Be(l).toLowerCase().startsWith(`${u}-`))}if(e.status){let u=e.status.trim().toLowerCase();n=n.filter(l=>(l.status??"").toLowerCase()===u)}let i=bt(n,Ys),s=bt(n,Qn),a=bt(n,u=>u.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:n.length,byProject:Object.fromEntries(i),byAssignee:Object.fromEntries(s),byStatus:Object.fromEntries(a)}:n,null,2));return}let c=[o?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(n.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${n.length} task${n.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),i.length>1&&vt("By project",i),!o&&s.length>1&&vt("By assignee",s),a.length>1&&vt("By status",a);return}let d=Math.max(...n.map(u=>Be(u).length))+1;for(let u of n){let l=u.summary??u.title??"",p=u.status?` status=${u.status}`:"",y=o?"":` [${Qn(u)}]`;console.log(`${Be(u).padEnd(d)}${l?`"${l}"`:""}${p}${y}`)}}async function Zn(e){let t=m(),r=f(t),o=xt(t),n=e.unassigned?void 0:e.assignee||o,i=await Zo(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:n});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 d=s.assignee?.displayName??s.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await W(r,c);if(!d.ok){console.error(`Task created, but its branch could not be prepared: ${d.error}`),process.exitCode=1;return}d.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 er(e){let t=m(),r=f(t);if(!e.task){let i=await en(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 o=await tn(r,{projectKey:e.project,taskKey:e.task});if(o.error){console.error(o.error),process.exitCode=1;return}if(o.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${o.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${o.task?.status??"In Progress"})`);let n=o.task?.branchPath;if(n){let i=await W(r,n);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 ${n}`:` branch ${n} still holds its content`)}e.noSelect||!n||(Q({projectKey:e.project,taskKey:e.task,branchPath:n}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function tr(e){let t=m(),r=f(t),o=await K(r,e.project,e.task);if(!o||!o.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let n=await W(r,o.branchPath);if(!n.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${n.error}`),process.exitCode=1;return}Q({projectKey:e.project,taskKey:e.task,branchPath:o.branchPath}),console.log(`\u2713 Current task set to ${e.project}/${e.task} (${o.branchPath})`),n.created&&console.log(` created branch ${o.branchPath}`)}async function or(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:o,branchPath:n}=t.currentTask;console.log(`Current task: ${r}/${o} (${n})`),(e.project||e.task)&&((!e.project||e.project===r)&&(!e.task||e.task===o)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function nr(e){let t=m(),r=f(t),o=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),n=o.body;if(o.statusCode>=200&&o.statusCode<300&&n.conceptId){console.log(`Created concept ${n.conceptId}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to create concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function rr(e){let t=m(),r=f(t),o={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},n=e.checkStatedParentsDefinitionStatus?await $o(r,o,t.currentTask):await Ce(r,o,t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to search concepts (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function ir(e){let t=m(),r=f(t),o=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(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to get concept (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function sr(e){let t=m(),r=f(t),o=await Bt(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(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to find references (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function ar(e){let t=m(),r=f(t),o=await Se(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let s=n.error?n.error:JSON.stringify(n);console.error(`Failed to validate concept (HTTP ${o.statusCode}): ${s}`),process.exitCode=1;return}let i=n.validationResults;if(!Array.isArray(i)||i.length===0){console.log(`No validation issues for concept ${e.id}.`);return}x(i),n.hasErrors&&(process.exitCode=1)}async function cr(e){let t=m(),r=f(t),o=e.checkStatedParentsDefinitionStatus?await Lo(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await q(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to list concepts for review (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function dr(e){let t=m(),r=f(t),o=await Ko(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${o.statusCode}): ${n.error??JSON.stringify(n)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(o.body,null,2)),n.summary&&(n.summary.withIssues>0||n.summary.failed>0)&&(process.exitCode=1);return}let i=n.results??[],s=n.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 ur(e){let t=m(),r=f(t),o=await Mo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to fetch concepts for review (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function lr(e){let t=m(),r=f(t),o=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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added ${e.type} description to concept ${e.id}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to add description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function pr(e){let t=m(),r=f(t),o=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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added relationship (${e.type} -> ${e.target}) to concept ${e.id}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to add relationship (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function mr(e){let t=m(),r=f(t),o=await To(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to remove relationship (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function fr(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(),o=f(r),n=await Ao(o,{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=n.body;if(n.statusCode>=200&&n.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 ${n.statusCode}): ${s}`),process.exitCode=1}async function yr(e){let t=m(),r=f(t),o=await io(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated description ${e.descriptionId} on concept ${e.id}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to update description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function gr(e){let t=m(),r=f(t),o=await so(r,{conceptId:e.id,descriptionId:e.descriptionId,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set case significance of description ${e.descriptionId} to ${e.caseSignificance}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set case significance (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function hr(e){let t=m(),r=f(t);if(e.entries){let s;try{s=JSON.parse(e.entries)}catch(u){console.error(`--entries is not valid JSON: ${u.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 lo(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 d=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${d}`),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 o=await uo(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.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(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set acceptability (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function kr(e){let t=m(),r=f(t),o=await ro(r,{conceptId:e.id,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated concept ${e.id}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to inactivate concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Cr(e){let t=m(),r=f(t),o=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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set definition status of concept ${e.id} to ${e.status}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set definition status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Ir(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(),o=f(r),n=await ko(o,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.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 ${n.statusCode}): ${s}`),process.exitCode=1}async function xr(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(),o=f(r),n=await Co(o,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.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 ${n.statusCode}): ${s}`),process.exitCode=1}async function br(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(),o=f(r),n=await xo(o,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){let a=Array.isArray(i.gciAxioms)?i.gciAxioms.map(d=>d.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 ${n.statusCode}): ${s}`),process.exitCode=1}async function vr(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(),o=f(r),n=await Io(o,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){let a=Array.isArray(i.classAxioms)?i.classAxioms.map(d=>d.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 ${n.statusCode}): ${s}`),process.exitCode=1}async function Sr(e){if(!e.expression||!e.expression.trim()){console.error("--expression must be a non-empty OWL functional-syntax axiom string."),process.exitCode=1;return}let t=m(),r=f(t),o=await No(r,{propertyId:e.propertyId,owlExpression:e.expression,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added property axiom to ${e.propertyId}${n.memberId?` (memberId ${n.memberId})`:""}: ${e.expression}`),console.log("Note: this write returns no structured validationResults (no ?validate=true equivalent for this endpoint). Syntactically invalid OWL is still rejected (as an HTTP 500 with a raw parser error, not a 400), but a semantically wrong-but-valid expression would only surface downstream, e.g. on the next classification run.");return}let i=n.message||n.error||JSON.stringify(n);console.error(`Failed to add property axiom (HTTP ${o.statusCode}): ${i}`),o.statusCode===500&&console.error('WARNING: a 500 here means the expression reached Snowstorm and its OWL parser rejected it \u2014 confirmed live, that can leave this task branch permanently locked server-side (not just this failed write). Try a plain read (e.g. get-property-axioms) or another small write next; if that also fails with "already locked", the branch needs an admin to run the unlock action \u2014 a regular author/project-lead account cannot self-service it.'),process.exitCode=1}async function wr(e){let t=m(),r=f(t),o=await Do(r,{conceptId:e.id,activeOnly:e.activeOnly,projectKey:e.project,taskKey:e.task},t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to get property axioms (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function Tr(e){let t=m(),r=f(t),o=await Oo(r,{conceptId:e.id,memberId:e.memberId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted property axiom ${e.memberId} from ${e.id}${n.owlExpression?`: ${n.owlExpression}`:""}`);return}let i=n.message||n.error||JSON.stringify(n);console.error(`Failed to delete property axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Ar(e){let t=m(),r=f(t),o=await jo(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Rr(e){let t=m(),r=f(t),o=await po(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Er(e){let t=m(),r=f(t),o=await mo(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function $r(e){let t=m(),r=f(t),o=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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to restore description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function jr(e){let t=m(),r=f(t),o=await go(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to replace FSN (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Pr(e){let t=m(),r=f(t),o=await yo(r,{conceptId:e.id,descriptionId:e.descriptionId,reason:e.reason,targetId:e.targetId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set inactivation reason ${e.reason} on description ${e.descriptionId} (concept ${e.id})`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set description inactivation reason (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Nr(e){let t=m(),r=f(t),o=await bo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Dr(e){let t=m(),r=f(t),o=await vo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Or(e){let t=m(),r=f(t),o=await wo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){if(n.alreadyConformed)console.log(`Concept ${e.id}'s axiom${n.axiomId?` ${n.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(n.replacedAxiomId){let s=Array.isArray(n.addResult?.classAxioms)?n.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 ${n.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),x(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to transform axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Fr(e){let t=m(),r=f(t),o=await be(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}if(n.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${n.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 ${n.axiomId}) \u2014 ${n.message}`)}async function Lr(e){let t=m(),r=f(t),o=await Ro(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Kr(e){let t=m(),r=f(t),o=await Eo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}function z(e){let t=e.account?.login;return t?dn(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 Mr(e){let t=m(),r=f(t),o=z(t),n;try{n=await Ho(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{o?.stop()}let i=n.body;if(n.statusCode>=200&&n.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 ${n.statusCode}): ${i.error??JSON.stringify(i)}${s}`),process.exitCode=1}async function _r(e){let t=m(),r=f(t),o=await Jo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check classification status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function Br(e){let t=m(),r=f(t),o=z(t),n;try{n=await Yo(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{o?.stop()}let i=n.body;if(n.statusCode>=200&&n.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 ${n.statusCode}): ${i.error??JSON.stringify(i)}`),process.exitCode=1}async function Ur(e){let t=m(),r=f(t),o=await Wo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check validation status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function qr(e){let t=m(),r=f(t),o=z(t);try{let n=await un(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),i=n.body;if(n.statusCode<200||n.statusCode>=300){let s=i.error?i.error:JSON.stringify(i);console.error(`Failed to watch for a notification (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2)),i.timedOut&&(process.exitCode=1)}finally{o?.stop()}}var Tt=w(require("os")),Z=w(require("path"));var T=w(require("fs")),St=w(require("os")),v=w(require("path")),$="authoring-cli",M=["claude","codex"];function Ue(e){let t=[v.resolve(e,"..","skills",$),v.resolve(e,"..","..","skills",$)];for(let r of t)if(T.existsSync(v.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 Xs(e){let t=[];return T.existsSync(v.join(e,".claude"))&&t.push("claude"),T.existsSync(v.join(e,".codex"))&&t.push("codex"),t}function pe(e,t){if(e==="all")return[...M];if(e){let o=e.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean),n=o.filter(i=>!M.includes(i));if(n.length)throw new Error(`Unknown --agent value(s): ${n.join(", ")}. Supported: ${M.join(", ")}, all.`);return o}let r=Xs(t);return r.length?r:["claude"]}var Gr="# authoring-cli \u2014 SNOMED CT authoring guidance";function Qs(e){let t=v.join(e,"SKILL.md"),r=v.join(e,"references","batch-authoring.md");return[Gr,"",`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 v.resolve(v.dirname(e),T.readlinkSync(e))}catch{return null}}function me(e){try{return T.lstatSync(e)}catch{return null}}function wt(e){let t=qe(e);return t?T.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:me(e)?.isDirectory()?"an existing directory":"an existing file"}function Jr(e){let t=qe(e);return t!==null&&v.basename(t)===$&&v.basename(v.dirname(t))==="skills"}function Hr(e){if(!me(e)?.isFile())return!1;try{return T.readFileSync(e,"utf8").startsWith(Gr)}catch{return!1}}function Vr(e){return T.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>v.relative(e,v.join(t.parentPath,t.name))).sort()}function Wr(e,t){if(!t||!T.existsSync(t))return!1;try{let r=Vr(t);return r.join(`
36
- `)!==Vr(e).join(`
37
- `)?!1:r.every(o=>T.readFileSync(v.join(e,o)).equals(T.readFileSync(v.join(t,o))))}catch{return!1}}function zs(e,t,r){let o=e.project?v.join(r,".claude","skills"):v.join(t,".claude","skills"),n=v.join(o,$),i=e.shippedSkillDir,s=e.project&&i.startsWith(r+v.sep)?v.relative(v.dirname(n),i):i,a=me(n),c=!1;if(a){let d=qe(n);if(d===i&&T.existsSync(d))return{agent:"claude",path:n,status:"already-current",kind:"symlink",detail:i};if(!(Jr(n)||Wr(n,i))&&!e.force)return{agent:"claude",path:n,status:"blocked",kind:"symlink",detail:wt(n)};T.rmSync(n,{recursive:!0,force:!0}),c=!0}T.mkdirSync(o,{recursive:!0});try{return T.symlinkSync(s,n,"dir"),{agent:"claude",path:n,status:c?"replaced":"installed",kind:"symlink",detail:s}}catch(d){let u=d.code;if(u!=="EPERM"&&u!=="EACCES")throw d;return T.cpSync(i,n,{recursive:!0}),{agent:"claude",path:n,status:c?"replaced":"installed",kind:"copy",detail:"symlinks unavailable on this platform \u2014 copied instead; re-run install-skill after upgrading the CLI"}}}function Zs(e,t){let r=v.join(t,".codex","prompts"),o=v.join(r,`${$}.md`),n=Qs(e.shippedSkillDir),i=me(o),s=!1;if(i){if((i.isFile()?T.readFileSync(o,"utf8"):null)===n)return{agent:"codex",path:o,status:"already-current",kind:"pointer"};if(!Hr(o)&&!e.force)return{agent:"codex",path:o,status:"blocked",kind:"pointer",detail:wt(o)};T.rmSync(o,{recursive:!0,force:!0}),s=!0}return T.mkdirSync(r,{recursive:!0}),T.writeFileSync(o,n,"utf8"),{agent:"codex",path:o,status:s?"replaced":"installed",kind:"pointer"}}function Yr(e){let t=e.homeDir??St.homedir(),r=e.cwd??process.cwd();return(e.agents??pe(void 0,t)).map(n=>n==="claude"?zs(e,t,r):Zs(e,t))}function Xr(e){let t=e.homeDir??St.homedir(),r=e.cwd??process.cwd();return e.agents.map(o=>{let n=o==="claude"?v.join(e.project?v.join(r,".claude"):v.join(t,".claude"),"skills",$):v.join(t,".codex","prompts",`${$}.md`);if(!me(n))return{agent:o,path:n,status:"not-registered"};if(!(o==="claude"?Jr(n)||Wr(n,e.shippedSkillDir):Hr(n))&&!e.force)return{agent:o,path:n,status:"left-alone",detail:`${wt(n)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let s=qe(n)??void 0;return T.rmSync(n,{recursive:!0,force:!0}),{agent:o,path:n,status:"removed",detail:s}})}function Qr(e){let t=Tt.homedir();return e===t||e.startsWith(t+Z.sep)?Z.join("~",Z.relative(t,e)):e}function ea(e){let t=Qr(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${Qr(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 zr(e){let t=Ue(__dirname),r=pe(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 o=Yr({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),n=o.filter(a=>a.status==="installed"||a.status==="replaced"),i=o.filter(a=>a.status==="blocked");console.log(n.length?`Installed skill '${$}' for:`:i.length?`Could not install skill '${$}':`:`Skill '${$}' is already registered:`);for(let a of o)console.log(` ${a.agent.padEnd(7)} ${ea(a)}`);if(e.project&&r.includes("claude")&&console.log(`
35
+ </html>`}async function na(e){let t=Date.now();try{return await On({userDataDir:q(),host:e.host,cookieName:e.cookieName,cookieUrl:`https://${e.host}/`,timeoutMs:e.timeoutMs},{validateCookie:e.validateCookie})}catch(r){if(!(r instanceof G))throw r;let o=Math.max(e.timeoutMs-(Date.now()-t),5e3);return jn({...e,timeoutMs:o},{validateCookie:e.validateCookie})}}function Qn(e,t={}){let r=e.cookieName??jt(e.host),o=t.platform??process.platform,n=t.openChrome??((d,l)=>ta(d,l,o)),i=t.resolveProfile??Le,s=t.captureCookie??na,a=e.timeoutMs??12e4,c=i();return new Promise((d,l)=>{let u=!1,p=k=>{u||(u=!0,y.close(),k())},y=Wn.createServer((k,h)=>{if((k.url||"/").split("?")[0]==="/callback"){h.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),h.end(oa());return}h.writeHead(404),h.end()});y.listen(0,"127.0.0.1",()=>{let h=`http://localhost:${y.address().port}/callback`,g=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(h)}`;(async()=>{try{Dn(q()),await n(g,c.directoryName);let x=await s({profileDirectory:c.directoryName,host:e.host,cookieName:r,timeoutMs:a,validateCookie:t.validateCookie});p(()=>d({cookie:`${r}=${x}`}))}catch(x){p(()=>l(x))}})()}),y.on("error",k=>p(()=>l(k)))})}var L=v(require("fs")),ke=v(require("path")),Zn="AUTHORING_CLI_HOME";function ra(){return ke.join(process.cwd(),".authoring-cli")}function ia(){let e=process.env[Zn];return e&&e.trim()!==""?ke.resolve(e):null}function We(){return ia()??ra()}function he(e){return ke.join(e,"session.json")}function Ce(){let e=he(We());if(!L.existsSync(e))return null;let t=L.readFileSync(e,"utf8");return JSON.parse(t)}function te(e){let t=We(),r={...e,updatedAt:new Date().toISOString()};try{L.mkdirSync(t,{recursive:!0,mode:448}),L.writeFileSync(he(t),JSON.stringify(r,null,2),{mode:384})}catch(o){let n=o?.code;throw n==="EPERM"||n==="EACCES"?new Error(`Couldn't write the session to ${he(t)} (${n}): the current directory isn't writable. Run authoring-cli from a writable directory, or set ${Zn} to an explicit, writable location.`):o}}function er(){let e=he(We());L.existsSync(e)&&L.unlinkSync(e)}function Ie(){return he(We())}function oe(e){let t=Ce();if(!t)throw new Error('Not signed in \u2014 run "login" first.');te({...t,currentTask:e})}async function sa(e){let t=Ce();if(!t||t.imsEndpoint!==e)return null;let r=await Q(e,t.cookie).catch(()=>null);return r?{cookie:t.cookie,account:r,currentTask:t.currentTask}:null}async function aa(e,t,r,o){let n=await At(o,t,r).catch(()=>null);if(!n)return null;let i=`${r}=${n}`,s=await Q(e,i).catch(()=>null);return s?{cookie:i,account:s}:null}function Ye(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 Xe(e){let t=Math.max(...e.map(r=>r.label.length));for(let{url:r,label:o,explicit:n,source:i}of e)console.log(` ${(o+":").padEnd(t+2)}${r} (${n?"from flag":i})`)}async function tr(e){let t=e.environment?Ut(e.environment):se;if(!t){console.error(`Unknown environment: ${e.environment}
36
+ Expected one of: ${we.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=H[t],o=e.imsEndpoint||r.imsEndpoint,n=e.terminologyServerEndpoint||r.terminologyServerEndpoint,i=e.authoringServicesEndpoint||r.authoringServicesEndpoint,s;try{s=new URL(o).hostname}catch{console.error(`Invalid --ims-endpoint: ${o}`),process.exitCode=1;return}let a=e.imsEndpoint?null:r.cookieName,c=e.cookieName||a||jt(s),d=t===se&&!e.environment?`${t}, default`:t,l=[{url:o,label:"IMS",explicit:!!e.imsEndpoint},{url:n,label:"Terminology server",explicit:!!e.terminologyServerEndpoint},{url:i,label:"Authoring services",explicit:!!e.authoringServicesEndpoint}].map(g=>({...g,source:d}));if(e.cookie){let g=`${c}=${e.cookie}`,x=await Q(o,g).catch(()=>null);if(!x){console.error(`That cookie value was rejected by IMS (${o}) \u2014 either it's stale/expired, or it's not the right cookie. Re-copy the current "${c}" cookie's Value from the signed-in browser's DevTools (Application/Storage tab \u2192 Cookies) and try again.`),process.exitCode=1;return}te({cookie:g,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:x,currentTask:null}),console.log(`${Ye(x)} (from --cookie \u2014 no browser opened.)`),Xe(l),console.log(` Session: ${Ie()}`);return}let u=await sa(o);if(u){te({cookie:u.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:u.account,currentTask:u.currentTask}),console.log(`${Ye(u.account)} (reused the already-stored session \u2014 no Chrome involved at all.)`),Xe(l),console.log(` Session: ${Ie()}`);return}let p=Le(),y=await aa(o,s,c,p.directoryName);if(y){te({cookie:y.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:y.account,currentTask:null}),console.log(`${Ye(y.account)} (reused an existing Chrome session in profile "${p.directoryName}" \u2014 no browser opened.)`),Xe(l),console.log(` Session: ${Ie()}`);return}console.log(`Opening Chrome (profile "${p.directoryName}") to sign in to ${o} ...`),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 "${p.directoryName}" \u2014 not whichever Chrome window happened to already be in front.`);let k;try{k=await Qn({imsEndpoint:o,host:s,cookieName:c},{validateCookie:g=>Q(o,`${c}=${g}`).then(x=>x!==null)})}catch(g){console.error(g instanceof Error?g.message:String(g)),process.exitCode=1;return}if(!k){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 Q(o,k.cookie).catch(()=>null);te({cookie:k.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:h,currentTask:null}),console.log(Ye(h)),Xe(l),console.log(` Session: ${Ie()}`)}async function or(){er(),console.log("Signed out.")}var Qe=v(require("fs")),ze=v(require("path"));async function nr(){let e=[ze.join(__dirname,"../../HELP.md"),ze.join(__dirname,"../HELP.md"),ze.join(process.cwd(),"HELP.md")];for(let t of e)try{if(Qe.existsSync(t)){let r=Qe.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=Ce();return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function Nt(e){let t=e.account;return t?.login??t?.username}function f(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,currentUsername:Nt(e),onLog:t=>console.error(t)}}function rr(e){return e.projectKey??e.key??"?"}async function ir(e){let t=m(),r=f(t),o=await dn(r);if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log("No projects available.");return}let n=Math.max(...o.map(i=>rr(i).length))+1;for(let i of o){let s=i.title??"";console.log(`${rr(i).padEnd(n)}${s?`"${s}"`:""}`)}}function Ze(e){return e.taskKey??e.key??"?"}function sr(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function ca(e){return e.projectKey||Ze(e).split("-")[0]||"?"}function Dt(e,t){let r=new Map;for(let o of e){let n=t(o);r.set(n,(r.get(n)??0)+1)}return[...r].sort((o,n)=>n[1]-o[1]||o[0].localeCompare(n[0]))}function Ot(e,t){let r=Math.max(...t.map(([n])=>n.length)),o=Math.max(...t.map(([,n])=>String(n).length));console.log(""),console.log(`${e}:`);for(let[n,i]of t)console.log(` ${n.padEnd(r)} ${String(i).padStart(o)}`)}async function ar(e){let t=m(),r=f(t),o=e.mine||!e.project,n=o?await un(r):await ln(r,e.project);if(o&&e.project){let l=e.project.toLowerCase();n=n.filter(u=>(u.projectKey??"").toLowerCase()===l||Ze(u).toLowerCase().startsWith(`${l}-`))}if(e.status){let l=e.status.trim().toLowerCase();n=n.filter(u=>(u.status??"").toLowerCase()===l)}let i=Dt(n,ca),s=Dt(n,sr),a=Dt(n,l=>l.status??"unknown");if(e.json){console.log(JSON.stringify(e.summary?{total:n.length,byProject:Object.fromEntries(i),byAssignee:Object.fromEntries(s),byStatus:Object.fromEntries(a)}:n,null,2));return}let c=[o?"assigned to you":null,e.project?`in project ${e.project}`:null,e.status?`with status "${e.status}"`:null].filter(Boolean);if(n.length===0){console.log(c.length?`No tasks ${c.join(" ")}.`:"No tasks found.");return}if(e.summary){console.log(`${n.length} task${n.length===1?"":"s"}${c.length?` ${c.join(" ")}`:""}.`),i.length>1&&Ot("By project",i),!o&&s.length>1&&Ot("By assignee",s),a.length>1&&Ot("By status",a);return}let d=Math.max(...n.map(l=>Ze(l).length))+1;for(let l of n){let u=l.summary??l.title??"",p=l.status?` status=${l.status}`:"",y=o?"":` [${sr(l)}]`;console.log(`${Ze(l).padEnd(d)}${u?`"${u}"`:""}${p}${y}`)}}async function cr(e){let t=m(),r=f(t),o=Nt(t),n=e.unassigned?void 0:e.assignee||o,i=await pn(r,{projectKey:e.project,summary:e.summary,description:e.description,assigneeUsername:n});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 d=s.assignee?.displayName??s.assignee?.username;console.log(` assignee: ${d??"unassigned"}`)}if(c){let d=await X(r,c);if(!d.ok){console.error(`Task created, but its branch could not be prepared: ${d.error}`),process.exitCode=1;return}d.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}oe({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function dr(e){let t=m(),r=f(t);if(!e.task){let i=await mn(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 o=await fn(r,{projectKey:e.project,taskKey:e.task});if(o.error){console.error(o.error),process.exitCode=1;return}if(o.notDeleted){console.log(`${e.project}/${e.task} is not deleted (status ${o.task?.status??"unknown"}) \u2014 nothing to recover.`);return}console.log(`\u2713 Recovered task ${e.project}/${e.task} (status ${o.task?.status??"In Progress"})`);let n=o.task?.branchPath;if(n){let i=await X(r,n);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 ${n}`:` branch ${n} still holds its content`)}e.noSelect||!n||(oe({projectKey:e.project,taskKey:e.task,branchPath:n}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function lr(e){let t=m(),r=f(t),o=await M(r,e.project,e.task);if(!o||!o.branchPath){console.error(`Could not resolve task ${e.project}/${e.task} (no branchPath returned).`),process.exitCode=1;return}let n=await X(r,o.branchPath);if(!n.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${n.error}`),process.exitCode=1;return}oe({projectKey:e.project,taskKey:e.task,branchPath:o.branchPath}),console.log(`\u2713 Current task set to ${e.project}/${e.task} (${o.branchPath})`),n.created&&console.log(` created branch ${o.branchPath}`)}async function ur(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:o,branchPath:n}=t.currentTask;console.log(`Current task: ${r}/${o} (${n})`),(e.project||e.task)&&((!e.project||e.project===r)&&(!e.task||e.task===o)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function pr(e){let t=m(),r=f(t),o=await zt(r,{fsn:e.fsn,semanticTag:e.tag,preferredTerm:e.pt,parentConceptId:e.parent,moduleId:e.module,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300&&n.conceptId){console.log(`Created concept ${n.conceptId}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to create concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function mr(e){let t=m(),r=f(t),o={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},n=e.checkStatedParentsDefinitionStatus?await Uo(r,o,t.currentTask):await Re(r,o,t.currentTask);if(n.statusCode>=200&&n.statusCode<300){console.log(JSON.stringify(n.body,null,2));return}console.error(`Failed to search concepts (HTTP ${n.statusCode}): ${JSON.stringify(n.body)}`),process.exitCode=1}async function fr(e){let t=m(),r=f(t),o=await Ae(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(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to get concept (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function gr(e){let t=m(),r=f(t),o=await Zt(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(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to find references (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function yr(e){let t=m(),r=f(t),o=await Ne(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let s=n.error?n.error:JSON.stringify(n);console.error(`Failed to validate concept (HTTP ${o.statusCode}): ${s}`),process.exitCode=1;return}let i=n.validationResults;if(!Array.isArray(i)||i.length===0){console.log(`No validation issues for concept ${e.id}.`);return}b(i),n.hasErrors&&(process.exitCode=1)}async function hr(e){let t=m(),r=f(t),o=e.checkStatedParentsDefinitionStatus?await Yo(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await V(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to list concepts for review (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function kr(e){let t=m(),r=f(t),o=await Xo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){console.error(`Failed to validate concepts for review (HTTP ${o.statusCode}): ${n.error??JSON.stringify(n)}`),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(o.body,null,2)),n.summary&&(n.summary.withIssues>0||n.summary.failed>0)&&(process.exitCode=1);return}let i=n.results??[],s=n.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}`),b(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 Cr(e){let t=m(),r=f(t),o=await zo(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to fetch concepts for review (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function Ir(e){let t=m(),r=f(t),o=await fo(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added ${e.type} description to concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to add description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function xr(e){let t=m(),r=f(t),o=await go(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added relationship (${e.type} -> ${e.target}) to concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to add relationship (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function br(e){let t=m(),r=f(t),o=await Mo(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Removed relationship from axiom ${e.axiomId} on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to remove relationship (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function vr(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(),o=f(r),n=await Ko(o,{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=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Removed role group from axiom ${e.axiomId} on concept ${e.id}`),b(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 ${n.statusCode}): ${s}`),process.exitCode=1}async function Sr(e){let t=m(),r=f(t),o=await ko(r,{conceptId:e.id,descriptionId:e.descriptionId,term:e.term,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Updated description ${e.descriptionId} on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to update description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function wr(e){let t=m(),r=f(t),o=await Co(r,{conceptId:e.id,descriptionId:e.descriptionId,caseSignificance:e.caseSignificance,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set case significance of description ${e.descriptionId} to ${e.caseSignificance}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set case significance (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Tr(e){let t=m(),r=f(t);if(e.entries){let s;try{s=JSON.parse(e.entries)}catch(l){console.error(`--entries is not valid JSON: ${l.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 vo(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}`),b(c.validationResults);return}let d=c.error?c.error:c.validationResults?JSON.stringify(c.validationResults,null,2):JSON.stringify(c);console.error(`Failed to set acceptability (HTTP ${a.statusCode}): ${d}`),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 o=await bo(r,{conceptId:e.id,descriptionId:e.descriptionId,lang:e.lang,us:e.us,gb:e.gb,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.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(", ")})`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set acceptability (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Ar(e){let t=m(),r=f(t),o=await ho(r,{conceptId:e.id,indicator:e.indicator,associationRefsetId:e.associationRefset,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to inactivate concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Rr(e){let t=m(),r=f(t),o=await yo(r,{conceptId:e.id,status:e.status,axiomIndex:e.axiomIndex?Number(e.axiomIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set definition status of concept ${e.id} to ${e.status}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set definition status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Er(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(),o=f(r),n=await $o(o,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated axiom ${e.axiomId} on concept ${e.id}`),b(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 ${n.statusCode}): ${s}`),process.exitCode=1}async function $r(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(),o=f(r),n=await Po(o,{conceptId:e.id,axiomId:e.axiomId,relationships:t,active:e.reactivate?!0:void 0,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){console.log(`Updated GCI axiom ${e.axiomId} on concept ${e.id}`),b(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 ${n.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(),o=f(r),n=await No(o,{conceptId:e.id,relationships:t,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){let a=Array.isArray(i.gciAxioms)?i.gciAxioms.map(d=>d.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})`:""}`),b(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 ${n.statusCode}): ${s}`),process.exitCode=1}async function jr(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(),o=f(r),n=await jo(o,{conceptId:e.id,relationships:t,moduleId:e.moduleId,definitionStatus:e.definitionStatus,projectKey:e.project,taskKey:e.task},r.currentTask),i=n.body;if(n.statusCode>=200&&n.statusCode<300){let a=Array.isArray(i.classAxioms)?i.classAxioms.map(d=>d.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})`:""}`),b(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 ${n.statusCode}): ${s}`),process.exitCode=1}async function Nr(e){if(!e.expression||!e.expression.trim()){console.error("--expression must be a non-empty OWL functional-syntax axiom string."),process.exitCode=1;return}let t=m(),r=f(t),o=await Jo(r,{propertyId:e.propertyId,owlExpression:e.expression,moduleId:e.moduleId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Added property axiom to ${e.propertyId}${n.memberId?` (memberId ${n.memberId})`:""}: ${e.expression}`),console.log("Note: this write returns no structured validationResults (no ?validate=true equivalent for this endpoint). Syntactically invalid OWL is still rejected (as an HTTP 500 with a raw parser error, not a 400), but a semantically wrong-but-valid expression would only surface downstream, e.g. on the next classification run.");return}let i=n.message||n.error||JSON.stringify(n);console.error(`Failed to add property axiom (HTTP ${o.statusCode}): ${i}`),o.statusCode===500&&console.error('WARNING: a 500 here means the expression reached Snowstorm and its OWL parser rejected it \u2014 confirmed live, that can leave this task branch permanently locked server-side (not just this failed write). Try a plain read (e.g. get-property-axioms) or another small write next; if that also fails with "already locked", the branch needs an admin to run the unlock action \u2014 a regular author/project-lead account cannot self-service it.'),process.exitCode=1}async function Dr(e){let t=m(),r=f(t),o=await Go(r,{conceptId:e.id,activeOnly:e.activeOnly,projectKey:e.project,taskKey:e.task},t.currentTask);if(o.statusCode>=200&&o.statusCode<300){console.log(JSON.stringify(o.body,null,2));return}console.error(`Failed to get property axioms (HTTP ${o.statusCode}): ${JSON.stringify(o.body)}`),process.exitCode=1}async function Or(e){let t=m(),r=f(t),o=await Ho(r,{conceptId:e.id,memberId:e.memberId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted property axiom ${e.memberId} from ${e.id}${n.owlExpression?`: ${n.owlExpression}`:""}`);return}let i=n.message||n.error||JSON.stringify(n);console.error(`Failed to delete property axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Fr(e){let t=m(),r=f(t),o=await Vo(r,{conceptId:e.id,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete concept (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Lr(e){let t=m(),r=f(t),o=await So(r,{conceptId:e.id,descriptionId:e.descriptionId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted description ${e.descriptionId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Mr(e){let t=m(),r=f(t),o=await wo(r,{conceptId:e.id,descriptionId:e.descriptionId,indicator:e.indicator,associationTargetId:e.associationTarget,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated description ${e.descriptionId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Kr(e){let t=m(),r=f(t),o=await To(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Restored description ${e.descriptionId} on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to restore description (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function _r(e){let t=m(),r=f(t),o=await Ro(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),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Replaced FSN on concept ${e.id}`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to replace FSN (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Br(e){let t=m(),r=f(t),o=await Ao(r,{conceptId:e.id,descriptionId:e.descriptionId,reason:e.reason,targetId:e.targetId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Set inactivation reason ${e.reason} on description ${e.descriptionId} (concept ${e.id})`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to set description inactivation reason (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Ur(e){let t=m(),r=f(t),o=await Do(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted axiom ${e.axiomId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Vr(e){let t=m(),r=f(t),o=await Oo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated axiom ${e.axiomId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function qr(e){let t=m(),r=f(t),o=await Lo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){if(n.alreadyConformed)console.log(`Concept ${e.id}'s axiom${n.axiomId?` ${n.axiomId}`:""} already conforms to authoring form \u2014 no changes made.`);else if(n.replacedAxiomId){let s=Array.isArray(n.addResult?.classAxioms)?n.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 ${n.replacedAxiomId}.`)}else console.log(`Transformed axiom${e.axiomId?` ${e.axiomId}`:""} on concept ${e.id} to authoring form.`),b(n.validationResults);return}let i=n.error?n.error:n.validationResults?JSON.stringify(n.validationResults,null,2):JSON.stringify(n);console.error(`Failed to transform axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Jr(e){let t=m(),r=f(t),o=await Pe(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check stated parents for concept ${e.id} (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}if(n.conclusive){console.log(`Concept ${e.id} does NOT conform to authoring form (axiom ${n.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 ${n.axiomId}) \u2014 ${n.message}`)}async function Gr(e){let t=m(),r=f(t),o=await _o(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Deleted GCI axiom ${e.axiomId} from concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to delete GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}async function Hr(e){let t=m(),r=f(t),o=await Bo(r,{conceptId:e.id,axiomId:e.axiomId,projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode>=200&&o.statusCode<300){console.log(`Inactivated GCI axiom ${e.axiomId} on concept ${e.id}`);return}let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to inactivate GCI axiom (HTTP ${o.statusCode}): ${i}`),process.exitCode=1}function ne(e){let t=e.account?.login;return t?xn(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),o=ne(t),n;try{n=await sn(r,{wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{o?.stop()}let i=n.body;if(n.statusCode>=200&&n.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 ${n.statusCode}): ${i.error??JSON.stringify(i)}${s}`),process.exitCode=1}async function Yr(e){let t=m(),r=f(t),o=await rn(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check classification status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function Xr(e){let t=m(),r=f(t),o=ne(t),n;try{n=await cn(r,{enableMrcmValidation:e.enableMrcm,wait:!!e.wait,timeoutSeconds:e.timeout?Number(e.timeout):void 0,projectKey:e.project,taskKey:e.task},t.currentTask)}finally{o?.stop()}let i=n.body;if(n.statusCode>=200&&n.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 ${n.statusCode}): ${i.error??JSON.stringify(i)}`),process.exitCode=1}async function zr(e){let t=m(),r=f(t),o=await an(r,{projectKey:e.project,taskKey:e.task},t.currentTask),n=o.body;if(o.statusCode<200||o.statusCode>=300){let i=n.error?n.error:JSON.stringify(n);console.error(`Failed to check validation status (HTTP ${o.statusCode}): ${i}`),process.exitCode=1;return}console.log(JSON.stringify(o.body,null,2))}async function Qr(e){let t=m(),r=f(t),o=ne(t);try{let n=await bn(r,{projectKey:e.project,taskKey:e.task,entityType:e.entityType,timeoutSeconds:e.timeout?Number(e.timeout):void 0},t.currentTask),i=n.body;if(n.statusCode<200||n.statusCode>=300){let s=i.error?i.error:JSON.stringify(i);console.error(`Failed to watch for a notification (HTTP ${n.statusCode}): ${s}`),process.exitCode=1;return}console.log(JSON.stringify(n.body,null,2)),i.timedOut&&(process.exitCode=1)}finally{o?.stop()}}var Mt=v(require("os")),re=v(require("path"));var T=v(require("fs")),Ft=v(require("os")),w=v(require("path")),P="authoring-cli",K=["claude","codex"];function et(e){let t=[w.resolve(e,"..","skills",P),w.resolve(e,"..","..","skills",P)];for(let r of t)if(T.existsSync(w.join(r,"SKILL.md")))return r;throw new Error(`Could not find the bundled skill (looked for skills/${P}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function da(e){let t=[];return T.existsSync(w.join(e,".claude"))&&t.push("claude"),T.existsSync(w.join(e,".codex"))&&t.push("codex"),t}function xe(e,t){if(e==="all")return[...K];if(e){let o=e.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean),n=o.filter(i=>!K.includes(i));if(n.length)throw new Error(`Unknown --agent value(s): ${n.join(", ")}. Supported: ${K.join(", ")}, all.`);return o}let r=da(t);return r.length?r:["claude"]}var ei="# authoring-cli \u2014 SNOMED CT authoring guidance";function la(e){let t=w.join(e,"SKILL.md"),r=w.join(e,"references","batch-authoring.md");return[ei,"",`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(`
37
+ `)}function tt(e){try{return w.resolve(w.dirname(e),T.readlinkSync(e))}catch{return null}}function be(e){try{return T.lstatSync(e)}catch{return null}}function Lt(e){let t=tt(e);return t?T.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:be(e)?.isDirectory()?"an existing directory":"an existing file"}function ti(e){let t=tt(e);return t!==null&&w.basename(t)===P&&w.basename(w.dirname(t))==="skills"}function oi(e){if(!be(e)?.isFile())return!1;try{return T.readFileSync(e,"utf8").startsWith(ei)}catch{return!1}}function Zr(e){return T.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()).map(t=>w.relative(e,w.join(t.parentPath,t.name))).sort()}function ni(e,t){if(!t||!T.existsSync(t))return!1;try{let r=Zr(t);return r.join(`
38
+ `)!==Zr(e).join(`
39
+ `)?!1:r.every(o=>T.readFileSync(w.join(e,o)).equals(T.readFileSync(w.join(t,o))))}catch{return!1}}function ua(e,t,r){let o=e.project?w.join(r,".claude","skills"):w.join(t,".claude","skills"),n=w.join(o,P),i=e.shippedSkillDir,s=e.project&&i.startsWith(r+w.sep)?w.relative(w.dirname(n),i):i,a=be(n),c=!1;if(a){let d=tt(n);if(d===i&&T.existsSync(d))return{agent:"claude",path:n,status:"already-current",kind:"symlink",detail:i};if(!(ti(n)||ni(n,i))&&!e.force)return{agent:"claude",path:n,status:"blocked",kind:"symlink",detail:Lt(n)};T.rmSync(n,{recursive:!0,force:!0}),c=!0}T.mkdirSync(o,{recursive:!0});try{return T.symlinkSync(s,n,"dir"),{agent:"claude",path:n,status:c?"replaced":"installed",kind:"symlink",detail:s}}catch(d){let l=d.code;if(l!=="EPERM"&&l!=="EACCES")throw d;return T.cpSync(i,n,{recursive:!0}),{agent:"claude",path:n,status:c?"replaced":"installed",kind:"copy",detail:"symlinks unavailable on this platform \u2014 copied instead; re-run install-skill after upgrading the CLI"}}}function pa(e,t){let r=w.join(t,".codex","prompts"),o=w.join(r,`${P}.md`),n=la(e.shippedSkillDir),i=be(o),s=!1;if(i){if((i.isFile()?T.readFileSync(o,"utf8"):null)===n)return{agent:"codex",path:o,status:"already-current",kind:"pointer"};if(!oi(o)&&!e.force)return{agent:"codex",path:o,status:"blocked",kind:"pointer",detail:Lt(o)};T.rmSync(o,{recursive:!0,force:!0}),s=!0}return T.mkdirSync(r,{recursive:!0}),T.writeFileSync(o,n,"utf8"),{agent:"codex",path:o,status:s?"replaced":"installed",kind:"pointer"}}function ri(e){let t=e.homeDir??Ft.homedir(),r=e.cwd??process.cwd();return(e.agents??xe(void 0,t)).map(n=>n==="claude"?ua(e,t,r):pa(e,t))}function ii(e){let t=e.homeDir??Ft.homedir(),r=e.cwd??process.cwd();return e.agents.map(o=>{let n=o==="claude"?w.join(e.project?w.join(r,".claude"):w.join(t,".claude"),"skills",P):w.join(t,".codex","prompts",`${P}.md`);if(!be(n))return{agent:o,path:n,status:"not-registered"};if(!(o==="claude"?ti(n)||ni(n,e.shippedSkillDir):oi(n))&&!e.force)return{agent:o,path:n,status:"left-alone",detail:`${Lt(n)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let s=tt(n)??void 0;return T.rmSync(n,{recursive:!0,force:!0}),{agent:o,path:n,status:"removed",detail:s}})}function si(e){let t=Mt.homedir();return e===t||e.startsWith(t+re.sep)?re.join("~",re.relative(t,e)):e}function ma(e){let t=si(e.path);switch(e.status){case"installed":case"replaced":return e.kind==="symlink"?`${t} (symlink -> ${si(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 ai(e){let t=et(__dirname),r=xe(e.agent,Mt.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; Codex prompts are always user-global.");let o=ri({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),n=o.filter(a=>a.status==="installed"||a.status==="replaced"),i=o.filter(a=>a.status==="blocked");console.log(n.length?`Installed skill '${P}' for:`:i.length?`Could not install skill '${P}':`:`Skill '${P}' is already registered:`);for(let a of o)console.log(` ${a.agent.padEnd(7)} ${ma(a)}`);if(e.project&&r.includes("claude")&&console.log(`
38
40
  Project-scoped install: commit .claude/skills only if authoring-cli is a dependency of this
39
41
  repo \u2014 a link into a globally installed package resolves on your machine alone.`),i.length){process.exitCode=1;return}n.length&&(console.log(`
40
- Restart your agent, then use /${$}.`),o.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=M.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 At=w(require("os")),ee=w(require("path"));function Zr(e){let t=At.homedir();return e===t||e.startsWith(t+ee.sep)?ee.join("~",ee.relative(t,e)):e}function ta(e){let t=Zr(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${Zr(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function ei(e){let t=e.agent?pe(e.agent,At.homedir()):[...M],r;try{r=Ue(__dirname)}catch{r=void 0}let o=Xr({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),n=o.filter(s=>s.status==="removed"),i=o.filter(s=>s.status==="left-alone");console.log(n.length?`Removed skill '${$}' registration for:`:i.length?`Left every registration of '${$}' in place:`:`No '${$}' registration found:`);for(let s of o)console.log(` ${s.agent.padEnd(7)} ${ta(s)}`);if(i.length){process.exitCode=1;return}n.length&&console.log(`
42
- Restart your agent to drop /authoring-cli from its command list.`)}function oa(e){let t={};for(let r=0;r<e.length;r++){let o=e[r];if(o.startsWith("--")){let n=o.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:"";t[n]=s}}return t}function oi(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var Rt=[{name:"login",usage:`login [${ge.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)=>Jn({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:()=>Hn()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>Wn()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${M.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=>zr({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${M.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=>ei({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=>Xn({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=>zn({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=>Zn({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=>er({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=>tr({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=>or({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=>nr({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=>rr({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=>ir({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=>sr({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; run classify --wait then transform-axiom yourself if you want that checked/fixed)",required:["id"],run:e=>ar({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=>cr({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 \u2014 classify --wait then transform-axiom yourself for that)',run:e=>dr({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:`review-concepts [--project <projectKey> --task <taskKey>] (read-only: fetches each concept's full current representation \u2014 descriptions, relationships, axioms \u2014 for every concept with pending stated changes on the task, the "concepts" list from get-concepts-for-review, so an editorial review has everything it needs in one call without a manual loop. Does not classify the branch or run transform-axiom (run classify --wait then transform-axiom yourself first if you want axiom-authoring-form conformance fixed before reviewing), and does not re-run Snowstorm's own convention check (that already happened on each edit's own save) \u2014 run validate-review-concepts yourself if you want that re-checked in batch. Not gated by Task Author since it never writes anything; usable by any reviewer, not just the task's own assignee. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)`,run:e=>ur({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=>lr({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=>yr({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=>gr({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=>hr({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=>pr({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=>mr({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=>fr({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=>kr({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=>Cr({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=>Ir({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=>vr({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=>br({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=>xr({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"add-property-axiom",usage:'add-property-axiom --property-id <SCTID> --expression "<OWL functional-syntax axiom>" [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds an OWL axiom whose subject is a property/attribute concept, not a class \u2014 e.g. a property-chain composition axiom such as SubObjectPropertyOf(ObjectPropertyChain(:A :B) :A), or a plain property subsumption SubObjectPropertyOf(:A :B). This is NOT reachable via add-axiom/update-axiom \u2014 those edit classAxioms on a concept, which cannot represent a property-chain axiom at all, confirmed live. Writes the raw OWL expression directly as an OWL Axiom reference set member (733073007); unlike add-axiom this call returns no structured validationResults \u2014 syntactically invalid OWL is still rejected as an HTTP 500 with a raw parser error, but a semantically wrong-but-valid expression is accepted as-is. CAUTION: a malformed expression that reaches Snowstorm can leave the whole branch permanently locked with no self-service unlock, confirmed live \u2014 a shallow client-side syntax check (balanced parens, recognized leading keyword) catches the obvious case before sending anything, but is not a real OWL parser)',required:["property-id","expression"],run:e=>Sr({propertyId:e["property-id"],expression:e.expression,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"get-property-axioms",usage:"get-property-axioms --id <SCTID> [--active-only] [--project <projectKey> --task <taskKey>] (lists every raw OWL Axiom reference set member (733073007) addressed at this concept, read directly off the refset \u2014 including property axioms such as a property-chain composition that get-concept --axioms cannot render at all, confirmed live on 127489000 |Has active ingredient|. Works for a class concept too, returning the same raw owlExpression text get-concept --axioms reformats into relationships. Shows inactive members too unless --active-only is passed)",required:["id"],run:e=>wr({id:e.id,activeOnly:"active-only"in e,project:e.project,task:e.task})},{name:"delete-property-axiom",usage:"delete-property-axiom --id <SCTID> --member-id <memberId> [--project <projectKey> --task <taskKey>] (deletes an OWL Axiom reference set member from the property concept <SCTID> \u2014 memberId comes from get-property-axioms or add-property-axiom's own output, not an axiomId. Only ever removes a never-released member; a released one is refused by Snowstorm itself (HTTP 400, not 409 like delete-axiom/delete-concept \u2014 confirmed live) with no --force escape hatch exposed here. Also refuses if memberId belongs to a different concept than --id, or is not an OWL Axiom member at all)",required:["id","member-id"],run:e=>Tr({id:e.id,memberId:e["member-id"],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=>Ar({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=>Rr({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=>Er({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=>$r({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=>jr({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=>Pr({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=>Nr({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=>Dr({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=>Or({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=>Fr({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=>Lr({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=>Kr({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=>Mr({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=>_r({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=>Br({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=>Ur({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=>qr({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function ni(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 ti(){return["Usage: authoring-cli <command> [options]","","Commands:",...Rt.map(e=>` ${ni(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 ri(e=process.argv){let[,,t,...r]=e,o=oa(r),n=oi(r);if(!t){console.log(ti());return}let i=Rt.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
42
+ Restart your agent, then use /${P}.`),o.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=K.filter(a=>!r.includes(a));s.length&&!e.agent&&console.log(`
43
+ Skipped ${s.join(", ")} (no config directory found). Pass --agent ${s.join(",")} to register anyway.`)}var Kt=v(require("os")),ie=v(require("path"));function ci(e){let t=Kt.homedir();return e===t||e.startsWith(t+ie.sep)?ie.join("~",ie.relative(t,e)):e}function fa(e){let t=ci(e.path);switch(e.status){case"removed":return e.detail?`${t} (was a symlink -> ${ci(e.detail)})`:`${t} (removed)`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function di(e){let t=e.agent?xe(e.agent,Kt.homedir()):[...K],r;try{r=et(__dirname)}catch{r=void 0}let o=ii({agents:t,project:e.project,force:e.force,shippedSkillDir:r}),n=o.filter(s=>s.status==="removed"),i=o.filter(s=>s.status==="left-alone");console.log(n.length?`Removed skill '${P}' registration for:`:i.length?`Left every registration of '${P}' in place:`:`No '${P}' registration found:`);for(let s of o)console.log(` ${s.agent.padEnd(7)} ${fa(s)}`);if(i.length){process.exitCode=1;return}n.length&&console.log(`
44
+ Restart your agent to drop /authoring-cli from its command list.`)}function ga(e){let t={};for(let r=0;r<e.length;r++){let o=e[r];if(o.startsWith("--")){let n=o.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:"";t[n]=s}}return t}function ui(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var _t=[{name:"login",usage:`login [${we.join("|")}] [--ims-endpoint <url>] [--terminology-server-endpoint <url>] [--authoring-services-endpoint <url>] [--cookie-name <name>] [--cookie <value>] (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 ${se}; any --*-endpoint overrides that environment's value. --cookie is the manual fallback: paste the session cookie's raw Value from a signed-in browser's own DevTools (Application/Storage tab \u2192 Cookies) to skip Chrome automation entirely \u2014 use it when automatic capture times out because Chrome's own cookie-encryption format isn't one this tool's decryption routine recognizes, not just when sign-in itself fails)`,run:(e,t)=>tr({environment:t[0],imsEndpoint:e["ims-endpoint"],terminologyServerEndpoint:e["terminology-server-endpoint"],authoringServicesEndpoint:e["authoring-services-endpoint"],cookieName:e["cookie-name"],cookie:e.cookie})},{name:"logout",usage:"logout (deletes the locally stored session)",run:()=>or()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>nr()},{name:"install-skill",aliases:["install-skills"],usage:`install-skill [--agent ${K.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=>ai({agent:e.agent,project:"project"in e,force:"force"in e})},{name:"uninstall-skill",aliases:["uninstall-skills"],usage:`uninstall-skill [--agent ${K.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=>di({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=>ir({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=>ar({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=>cr({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=>dr({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=>lr({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=>ur({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=>pr({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=>mr({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=>fr({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=>gr({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; run classify --wait then transform-axiom yourself if you want that checked/fixed)",required:["id"],run:e=>yr({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=>hr({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 \u2014 classify --wait then transform-axiom yourself for that)',run:e=>kr({project:e.project,task:e.task,json:"json"in e})},{name:"review-concepts",usage:`review-concepts [--project <projectKey> --task <taskKey>] (read-only: fetches each concept's full current representation \u2014 descriptions, relationships, axioms \u2014 for every concept with pending stated changes on the task, the "concepts" list from get-concepts-for-review, so an editorial review has everything it needs in one call without a manual loop. Does not classify the branch or run transform-axiom (run classify --wait then transform-axiom yourself first if you want axiom-authoring-form conformance fixed before reviewing), and does not re-run Snowstorm's own convention check (that already happened on each edit's own save) \u2014 run validate-review-concepts yourself if you want that re-checked in batch. Not gated by Task Author since it never writes anything; usable by any reviewer, not just the task's own assignee. Still leaves the judgment-call checklist to a human/agent; see skills/authoring-cli/references/review-concepts.md)`,run:e=>Cr({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=>Ir({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=>wr({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)
45
+ 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=>Tr({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=>xr({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=>br({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=>vr({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=>Ar({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=>Rr({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=>Er({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=>jr({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=>$r({id:e.id,axiomId:e["axiom-id"],relationships:e.relationships,reactivate:"reactivate"in e,project:e.project,task:e.task})},{name:"add-property-axiom",usage:'add-property-axiom --property-id <SCTID> --expression "<OWL functional-syntax axiom>" [--module-id <moduleId>] [--project <projectKey> --task <taskKey>] (adds an OWL axiom whose subject is a property/attribute concept, not a class \u2014 e.g. a property-chain composition axiom such as SubObjectPropertyOf(ObjectPropertyChain(:A :B) :A), or a plain property subsumption SubObjectPropertyOf(:A :B). This is NOT reachable via add-axiom/update-axiom \u2014 those edit classAxioms on a concept, which cannot represent a property-chain axiom at all, confirmed live. Writes the raw OWL expression directly as an OWL Axiom reference set member (733073007); unlike add-axiom this call returns no structured validationResults \u2014 syntactically invalid OWL is still rejected as an HTTP 500 with a raw parser error, but a semantically wrong-but-valid expression is accepted as-is. CAUTION: a malformed expression that reaches Snowstorm can leave the whole branch permanently locked with no self-service unlock, confirmed live \u2014 a shallow client-side syntax check (balanced parens, recognized leading keyword) catches the obvious case before sending anything, but is not a real OWL parser)',required:["property-id","expression"],run:e=>Nr({propertyId:e["property-id"],expression:e.expression,moduleId:e["module-id"],project:e.project,task:e.task})},{name:"get-property-axioms",usage:"get-property-axioms --id <SCTID> [--active-only] [--project <projectKey> --task <taskKey>] (lists every raw OWL Axiom reference set member (733073007) addressed at this concept, read directly off the refset \u2014 including property axioms such as a property-chain composition that get-concept --axioms cannot render at all, confirmed live on 127489000 |Has active ingredient|. Works for a class concept too, returning the same raw owlExpression text get-concept --axioms reformats into relationships. Shows inactive members too unless --active-only is passed)",required:["id"],run:e=>Dr({id:e.id,activeOnly:"active-only"in e,project:e.project,task:e.task})},{name:"delete-property-axiom",usage:"delete-property-axiom --id <SCTID> --member-id <memberId> [--project <projectKey> --task <taskKey>] (deletes an OWL Axiom reference set member from the property concept <SCTID> \u2014 memberId comes from get-property-axioms or add-property-axiom's own output, not an axiomId. Only ever removes a never-released member; a released one is refused by Snowstorm itself (HTTP 400, not 409 like delete-axiom/delete-concept \u2014 confirmed live) with no --force escape hatch exposed here. Also refuses if memberId belongs to a different concept than --id, or is not an OWL Axiom member at all)",required:["id","member-id"],run:e=>Or({id:e.id,memberId:e["member-id"],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=>Lr({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=>Mr({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)
46
+ 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=>_r({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=>Br({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=>Ur({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=>Vr({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=>qr({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=>Jr({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=>Gr({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=>Hr({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=>Yr({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=>Xr({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=>zr({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=>Qr({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function pi(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 li(){return["Usage: authoring-cli <command> [options]","","Commands:",..._t.map(e=>` ${pi(e)}`),"",'Run "login" first to sign in.',"With no --project/--task, actions target whatever task was",'last set via "select-task".'].join(`
47
+ `)}async function mi(e=process.argv){let[,,t,...r]=e,o=ga(r),n=ui(r);if(!t){console.log(li());return}let i=_t.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
46
48
 
47
- ${ti()}`),process.exitCode=1;return}let s=(i.required??[]).filter(a=>!o[a]);if(s.length){console.error(`Missing required flag(s): ${s.map(a=>`--${a}`).join(", ")}
49
+ ${li()}`),process.exitCode=1;return}let s=(i.required??[]).filter(a=>!o[a]);if(s.length){console.error(`Missing required flag(s): ${s.map(a=>`--${a}`).join(", ")}
48
50
 
49
- Usage: ${ni(i)}`),process.exitCode=1;return}await i.run(o,n)}require.main===module&&ri().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
51
+ Usage: ${pi(i)}`),process.exitCode=1;return}await i.run(o,n)}require.main===module&&mi().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.26",
3
+ "version": "0.1.30",
4
4
  "description": "CLI for SNOMED CT authoring against authoring-services",
5
5
  "license": "Apache-2.0",
6
6
  "bin": {