authoring-cli 0.1.34 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HELP.md +4 -4
- package/README.md +18 -9
- package/dist/index.js +27 -26
- package/package.json +1 -1
package/HELP.md
CHANGED
|
@@ -194,8 +194,8 @@ authoring-cli validate-review-concepts
|
|
|
194
194
|
- `authoring-cli watch-notification [--entity-type TYPE] [--timeout SECONDS]` — Wait for next notification
|
|
195
195
|
|
|
196
196
|
### Skill Management
|
|
197
|
-
- `authoring-cli install-skill [--agent claude|codex|all] [--force]` —
|
|
198
|
-
- `authoring-cli uninstall-skill [--agent claude|codex|all]` — Unregister the skill (run before uninstalling the package)
|
|
197
|
+
- `authoring-cli install-skill [--agent claude|codex|agents|dsh|all] [--project] [--force]` — Copy the authoring guidance skill into your AI agent(s) (Claude Code, Codex, DeepSeek Harness); re-run after upgrading
|
|
198
|
+
- `authoring-cli uninstall-skill [--agent claude|codex|agents|dsh|all]` — Unregister the skill (run before uninstalling the package)
|
|
199
199
|
|
|
200
200
|
---
|
|
201
201
|
|
|
@@ -289,7 +289,7 @@ The package includes detailed guidance on SNOMED CT authoring best practices, Sn
|
|
|
289
289
|
authoring-cli install-skill
|
|
290
290
|
```
|
|
291
291
|
|
|
292
|
-
Then use `/authoring-cli` in Claude Code or your agent to get guidance while you work.
|
|
292
|
+
Then use `/authoring-cli` in Claude Code, Codex, DeepSeek Harness (dsh) or your agent to get guidance while you work.
|
|
293
293
|
|
|
294
294
|
### Server-side Constraints
|
|
295
295
|
If you encounter a server error (4xx/5xx), check the error message carefully — it often tells you exactly what's wrong. Common issues:
|
|
@@ -313,7 +313,7 @@ https://github.com/snomed/authoring-cli
|
|
|
313
313
|
A: The CLI runs on any Node.js 24+ environment. Automatic session capture during login works on macOS with Chrome, and on Linux with Chromium/Chrome (including a Termux:X11 proot-distro Debian on Android — `apt install chromium sqlite3`; `login` auto-starts both the Termux:X11 app and its backend so there's no manual open-once step, provided Termux has been granted Android's "Draw over other apps" permission — a one-time device setting under Settings → Apps → Termux that can't be requested from inside the proot; without it, open the Termux:X11 app by hand once instead so `login` has a display to draw its sign-in window on). `login` doesn't require any Chrome profile to already exist — it opens (and creates, if needed) a dedicated "authoring-cli" profile, so a fresh machine or CI image that has never launched Chrome before still works on the very first run. On Windows and any other unsupported platform, `login` will fail with a clear message — but you can still sign in there using `authoring-cli login --cookie <value>` with a session cookie copied from any signed-in browser's DevTools, which needs no Chrome automation at all.
|
|
314
314
|
|
|
315
315
|
**Q: How do I use this with an AI agent?**
|
|
316
|
-
A: Install the bundled authoring skill (`authoring-cli install-skill`), then invoke `/authoring-cli` in Claude Code or
|
|
316
|
+
A: Install the bundled authoring skill (`authoring-cli install-skill`), then invoke `/authoring-cli` in Claude Code, Codex or DeepSeek Harness. The skill teaches the agent about Snowstorm constraints and SNOMED CT modeling rules.
|
|
317
317
|
|
|
318
318
|
**Q: Can I undo a change?**
|
|
319
319
|
A: There's no built-in undo. However:
|
package/README.md
CHANGED
|
@@ -20,21 +20,30 @@ authoring-cli install-skill
|
|
|
20
20
|
|
|
21
21
|
```
|
|
22
22
|
Installed skill 'authoring-cli' for:
|
|
23
|
-
claude
|
|
24
|
-
|
|
23
|
+
claude ~/.claude/skills/authoring-cli (installed — copied from /usr/local/lib/node_modules/authoring-cli/skills/authoring-cli (v0.1.35))
|
|
24
|
+
dsh ~/.dsh/skills/authoring-cli (installed — copied from /usr/local/lib/node_modules/authoring-cli/skills/authoring-cli (v0.1.35))
|
|
25
25
|
|
|
26
26
|
Restart your agent, then use /authoring-cli.
|
|
27
27
|
```
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
Each target gets a **real copy** of the skill (`SKILL.md` + `references/`), stamped with a small `.installed-by-authoring-cli.json` marker. A copy doesn't follow the package, so **re-run `authoring-cli install-skill` after `npm update -g authoring-cli`** — it recognises its own earlier copy by the marker and refreshes it (`updated`), with no `--force`. By default it targets whichever of `claude`, `codex` and `dsh` are present on the machine (falling back to `claude`).
|
|
30
|
+
|
|
31
|
+
| Target | Skill lands in | Notes |
|
|
32
|
+
|---|---|---|
|
|
33
|
+
| `claude` | `~/.claude/skills/authoring-cli/` | `--project` puts it in `./.claude/skills/` instead |
|
|
34
|
+
| `codex` | `~/.codex/skills/authoring-cli/` (or `$CODEX_HOME/skills/`) | A legacy `~/.codex/prompts/authoring-cli.md` pointer from earlier versions is removed |
|
|
35
|
+
| `dsh` | `~/.dsh/skills/authoring-cli/` (or `$DSH_HOME/skills/`) | DeepSeek Harness — its skill catalog is separate from Claude Code's, so a Claude-only install is invisible to it. Auto-detected when `~/.dsh` exists |
|
|
36
|
+
| `agents` | `~/.agents/skills/authoring-cli/` (or `$DSH_AGENTS_HOME/skills/`) | The cross-tool root DSH also scans. **Never auto-selected** (it would register the skill with DSH twice) — name it explicitly |
|
|
30
37
|
|
|
31
38
|
| Flag | Effect |
|
|
32
39
|
|---|---|
|
|
33
|
-
| `--agent claude\|codex\|all` | Register for specific agents (comma-separated) instead of the detected ones |
|
|
34
|
-
| `--project` |
|
|
35
|
-
| `--force` | Replace an existing
|
|
40
|
+
| `--agent claude\|codex\|agents\|dsh\|all` | Register for specific agents (comma-separated) instead of the detected ones |
|
|
41
|
+
| `--project` | Claude Code only: install into `./.claude/skills/` for this repo rather than your home directory |
|
|
42
|
+
| `--force` | Replace an existing directory of the same name that isn't recognizably ours |
|
|
43
|
+
|
|
44
|
+
A DSH session already open won't see the skill until you start a new one — its catalog is loaded at session start.
|
|
36
45
|
|
|
37
|
-
Nothing is written outside the package until you run this — installing the npm package doesn't touch `~/.claude` or `~/.
|
|
46
|
+
Nothing is written outside the package until you run this — installing the npm package doesn't touch `~/.claude`, `~/.codex`, `~/.dsh` or `~/.agents` on its own.
|
|
38
47
|
|
|
39
48
|
### Unregistering
|
|
40
49
|
|
|
@@ -44,9 +53,9 @@ authoring-cli uninstall-skill # run this BEFORE npm rm -g authoring-cli
|
|
|
44
53
|
|
|
45
54
|
**Order matters.** npm 7 removed the uninstall lifecycle scripts — `preuninstall` and `postuninstall` are never run — so `npm rm -g authoring-cli` cannot clean up after itself, and by the time the package is gone, so is the command that would have. Unregister first, remove the package second.
|
|
46
55
|
|
|
47
|
-
If you do it the other way round, nothing breaks: the leftover
|
|
56
|
+
If you do it the other way round, nothing breaks: the leftover copies are inert files that agents simply read as a (now unmaintained) skill. A later `npm install -g authoring-cli && authoring-cli install-skill` silently refreshes them (no `--force` needed — the marker says they're ours), or you can delete the `authoring-cli` directory under each skills folder by hand.
|
|
48
57
|
|
|
49
|
-
`uninstall-skill` only removes registrations it can recognize as its own: a symlink
|
|
58
|
+
`uninstall-skill` only removes registrations it can recognize as its own: a marked copy, a symlink from an earlier version of this tool (live or dangling), a byte-identical copy of the shipped skill, or a legacy Codex pointer prompt. A skill directory you wrote under the same name is reported and left alone unless you pass `--force`. It takes the same `--agent`/`--project` flags, and defaults to checking every supported agent so nothing is left behind.
|
|
50
59
|
|
|
51
60
|
## Sign in
|
|
52
61
|
|
package/dist/index.js
CHANGED
|
@@ -1,27 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Ni=Object.create;var $e=Object.defineProperty;var Di=Object.getOwnPropertyDescriptor;var Oi=Object.getOwnPropertyNames;var Fi=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var Ki=(e,t)=>{for(var r in t)$e(e,r,{get:t[r],enumerable:!0})},Zt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Oi(t))!Li.call(e,n)&&n!==r&&$e(e,n,{get:()=>t[n],enumerable:!(o=Di(t,n))||o.enumerable});return e};var v=(e,t,r)=>(r=e!=null?Ni(Fi(e)):{},Zt(t||!e||!e.__esModule?$e(r,"default",{value:e,enumerable:!0}):r,e)),_i=e=>Zt($e({},"__esModule",{value:!0}),e);var _a={};Ki(_a,{COMMANDS:()=>Qt,main:()=>ji,parsePositionals:()=>Ei});module.exports=_i(_a);var z={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"}},Mi={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},Ee=Object.keys(z);function eo(e){return Mi[e.trim().toLowerCase()]??null}var le="uat",Ba=z.uat.imsEndpoint,Ua=z.uat.terminologyServerEndpoint,Va=z.uat.authoringServicesEndpoint;var Bi=v(require("http")),Ui=v(require("https"));function x(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:"?Ui: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 I="";g.on("data",E=>{I+=E}),g.on("end",()=>{if(y)return;y=!0,clearTimeout(h);let E=g.statusCode??0,N=(g.headers["content-type"]??"").includes("application/json"),O=null,Re=!1;if(I)try{O=JSON.parse(I)}catch{Re=!N}a({statusCode:E,body:O,rawBody:I,sessionExpired:Re})})});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 V="900000000000509007",Q="900000000000508004";var to={[V]:"en-us",[Q]:"en-gb"},oo={[V]:"true",[Q]:"true"},Vi={},qi={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:to,dialectDefaults:oo,readOnlyDialects:Vi,defaultLanguage:"en"};function no(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return qi;let t={[V]:"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?to:t,dialectDefaults:a?oo:r,readOnlyDialects:o,defaultLanguage:n[0]??"en"}}function lt(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 Pe(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[V]:"PREFERRED"}:lt(e,"PREFERRED",t,"en")}var Ji="900000000000207008";function ro(e){return e.replace(/\/$/,"")}function A(e){return ro(e.terminologyServerEndpoint)}function P(e){return ro(e.authoringServicesEndpoint)}function io(e){return`${new URL(P(e)).origin}/authoring-traceability-service`}function Z(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: pass --project/--task explicitly, or work in a named context ("--context <name>" with "select-task") or a pinned session (AUTHORING_CLI_TASK).'}:(s||(s=await ut(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 ee(e,t){let r=A(e),o=await x(`${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 x(`${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 ut(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}`;return(await x(o,{cookie:e.cookie})).body?.branchPath??null}async function so(e,t,r){let o=r?.get(t);if(o)return o;let n=`${P(e)}/projects/${t}`,s=(await x(n,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function B(e,t,r){let o=await so(e,t,r),n=o.multipleModuleEditingDisabled,i=!n||n==="false";return o.expectedExtensionModules?.length&&i?o.expectedExtensionModules[0]:o.defaultModuleId?o.defaultModuleId:Ji}async function te(e,t,r){let o=await so(e,t,r);return no(o)}async function oe(e,t){let r=e.replace(/\/$/,"")+"/auth",o=await x(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 co=v(require("crypto"));async function K(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}`;return(await x(o,{cookie:e.cookie})).body??null}function ao(e){let t=e?.trim();return t?t.toLowerCase():null}async function S(e,t){let r=ao(e.currentUsername);if(!r)return null;let o=await K(e,t.projectKey,t.taskKey),n=ao(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 Gi="116680003";function ue(e,t,r,o,n="PREFERRED",i=!1){let s=e==="FSN"?Pe(o,i):lt(o,n,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function lo(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=Z(c),l=t.moduleId||await B(e,s,o),u=await te(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:[ue("FSN",y,l,u,"PREFERRED",!0),ue("SYNONYM",p,l,u,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:co.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:l,relationships:[{active:!0,groupId:0,type:{conceptId:Gi},target:{conceptId:t.parentConceptId}}]}]},h=`${A(e)}/browser/${d}/${s}/${a}/concepts/?validate=true`,g=await x(h,{method:"POST",body:k,cookie:e.cookie});if(g.sessionExpired){let D="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: SESSION EXPIRED`),{statusCode:401,body:{error:D}}}let I=g.body,E=I&&"conceptId"in I?I.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,I?.validationResults),{statusCode:g.statusCode,body:g.body}}var Hi=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],Wi={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function Yi(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(o=>o.active!==!1).length}function uo(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(o=>o.characteristicType===t)}function pe(e){return{conceptId:e.conceptId,fsn:e.fsn,pt:e.pt,active:e.active,definitionStatus:e.definitionStatus}}function me(e){return typeof e=="object"&&e!==null}function Xi(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((me(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:me(u)?u.conceptId:void 0,targetFsn:me(u)&&me(u.fsn)?u.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return n}async function je(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=Hi.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>Wi[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 x(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 x(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||!me(i.body))return{statusCode:i.statusCode,body:i.body};let s=i.body;if(t.attributeType){let a=t.gci?"gciAxioms":"classAxioms",c=Xi(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:{...pe(s),descriptions:a}}}return t.descriptionFull?{statusCode:i.statusCode,body:{...pe(s),descriptions:s.descriptions??[]}}:t.axioms?{statusCode:i.statusCode,body:{...pe(s),classAxioms:s.classAxioms??[],relationships:uo(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...pe(s),relationships:uo(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...pe(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:Yi(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var zi=500,Qi=1e4;async function Ne(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 x(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(zi,Qi-d);if(l<=0)break;let u=await x(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 fe=1e3;function Zi(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 po(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)),x(`${n}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let l=await i(t.limit??fe,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(fe,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<fe||c>=a)break;d+=fe}return{statusCode:200,body:{total:a,limit:fe,offset:0,referencesByType:Zi(s)}}}var ft=v(require("crypto"));function mo(e){return typeof e=="object"&&e!==null}function es(e){let t=e.type,r=e.target,o=mo(t)?t.conceptId:void 0,n=mo(r)?r.conceptId:void 0;return typeof o=="string"&&typeof n=="string"?{typeId:o,targetId:n}:null}function ts(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 fo(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(es).filter(d=>d!=null);ts(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 os=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],ns=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],rs=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],is=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],ss=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],gt=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function So(e){return gt.includes(e)}function ge(e,t){let r={};for(let o of t)o in e&&(r[o]=e[o]);return r}function De(e){return typeof e=="object"&&e!==null}function go(e){return De(e)?ge(e,is):e}function wo(e){if(!De(e))return e;let t=ge(e,rs);return"type"in t&&(t.type=go(t.type)),"target"in t&&(t.target=go(t.target)),t}function as(e){return De(e)?ge(e,ns):e}function yo(e){if(!De(e))return e;let t=ge(e,ss);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(wo)),t}function yt(e){let t=ge(e,os);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(as)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(wo)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(yo)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(yo)),t}function cs(e){return new Promise(t=>setTimeout(t,e))}function ds(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 pt=[300,600,1200,2400,4800],ho=new Map;function ls(e,t){let o=(ho.get(e)??Promise.resolve()).then(t,t);return ho.set(e,o.then(()=>{},()=>{})),o}async function $(e,t,r,o){try{return await ls(t.branchPath,()=>us(e,t,r,o))}catch(n){return{statusCode:500,body:{error:n instanceof Error?n.message:String(n)}}}}async function us(e,t,r,o){for(let n=0;;n++){let i=A(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await x(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=Z(t.branchPath),u=`${i}/browser/${l}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await x(u,{method:"PUT",body:yt(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(ds(p)&&n<pt.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${n+1}/${pt.length})`),await cs(pt[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 ko=["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&&!ko.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${ko.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 B(e,n.projectKey,o),a=await te(e,n.projectKey,o),c=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return $(e,n,t.conceptId,d=>{let l=Array.isArray(d.descriptions)?d.descriptions:[];return l.push(ue(t.type,c,s,a,t.acceptability??"ACCEPTABLE",!1)),d.descriptions=l,null})}async function Ao(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 $(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 Ro(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 $(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 $o(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||$(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 Eo(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&&!So(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${gt.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||$(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 Po(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!So(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${gt.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||$(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 mt=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function Co(e){return mt.includes(e)}function jo(e){return e.us&&!Co(e.us)?{statusCode:400,body:{error:`us must be one of: ${mt.join(", ")}.`}}:e.gb&&!Co(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${mt.join(", ")}.`}}:null}function No(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.`}}:jo(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function ht(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[V]:n[V]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete n[Q]:n[Q]=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 Do(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=No(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||$(e,i,t.conceptId,a=>{let c=Array.isArray(a.descriptions)?a.descriptions:[];return ht(c,t.conceptId,o)})}async function Oo(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=No(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||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[];for(let a of t.entries){let c=ht(s,t.conceptId,a);if(c)return c}return null})}async function Fo(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||$(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 Oe="REFERS_TO";async function Lo(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||$(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={[Oe]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}function xo(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 Ko(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=jo(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 te(e,a.projectKey,o);return $(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={[Oe]:[t.associationTargetId]})}}return p.active=!0,delete p.inactivationIndicator,delete p.associationTargets,p.acceptabilityMap=Pe(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=ht(u,t.conceptId,n);return y||(n.us==="PREFERRED"&&xo(u,t.descriptionId,V),n.gb==="PREFERRED"&&xo(u,t.descriptionId,Q),null)})}var ps="900000000000490003",Io=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function _o(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!Io.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${Io.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=${ps}&active=true`,a=await x(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.`}}:$(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={[Oe]:[t.targetId]}:delete u.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function Mo(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 B(e,n.projectKey,o),a=await te(e,n.projectKey,o),c=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return $(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={[Oe]:[t.associationTargetId]}),l.push(ue("FSN",c,s,a,"PREFERRED",!1)),d.descriptions=l,null)})}function Bo(e,t,r){return $(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 Uo(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||Bo(e,o,t)}async function Vo(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||$(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 qo(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 B(e,n.projectKey,o);return $(e,n,t.conceptId,a=>{let c=Array.isArray(a.classAxioms)?a.classAxioms:[];return c.push({axiomId:ft.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.classAxioms=c,null})}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."}};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 B(e,n.projectKey,o);return $(e,n,t.conceptId,a=>{let c=Array.isArray(a.gciAxioms)?a.gciAxioms:[];return c.push({axiomId:ft.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.gciAxioms=c,null})}async function Go(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||$(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 Ho(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||$(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 ms="116680003";function bo(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 fs(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:ms},target:{conceptId:i.id}});let o=Array.isArray(e.attributes)?e.attributes:[];for(let i of o)t.push(bo(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(bo(c,s+1))}),t}async function Wo(e,t,r,o){let n=A(e),i=await x(`${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 gs="116680003";function ys(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==gs?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function hs(e,t,r){let o=A(e),n=await x(`${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=fs(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 ks(e,t,r,o){let n=await Wo(e,t,r,o);if(!n.ok)return n;let i=await hs(e,t,r);return i.ok?{ok:!0,value:{axiom:n.value.axiom,axiomId:n.value.axiomId,targetRelationships:i.value}}:i}function Cs(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 vo(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(Cs(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 xs(e,t){let r=vo(e),o=vo(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 Yo(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 ks(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 xs(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}}):Bo(e,o,{conceptId:t.conceptId,axiomId:a,relationships:c})}async function Fe(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 Wo(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 ys(a)?{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!0,conforms:!1}}:{statusCode:200,body:{conceptId:t.conceptId,axiomId:s,conclusive:!1,message:"Stated Is-a targets are all primitive \u2014 this cannot rule out a missing/mismatched attribute. Run transform-axiom to get a definitive, self-fixing answer."}}}async function Xo(e,t,r){if(!t.conceptId||!t.axiomId)return{statusCode:400,body:{error:"conceptId and axiomId are required."}};if(!t.relationshipId&&t.relationshipIndex==null)return{statusCode:400,body:{error:"One of relationshipId or relationshipIndex is required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await S(e,o);return n||$(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 zo(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||$(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=fo(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 Qo(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||$(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 Zo(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||$(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 Is=8;async function Le(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 Fe(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(Is,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:n,skipped:i}}async function en(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await Ne(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 Le(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 tn(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 x(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 x(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 ye="733073007",on=["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 bs(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||!on.includes(o)?`OWL expression doesn't start with a recognized top-level axiom keyword${o?` (saw "${o}")`:""} \u2014 expected one of ${on.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 nn(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=bs(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 B(e,i.projectKey,o),d=`${A(e)}/${i.branchPath}/members`,l=await x(d,{method:"POST",cookie:e.cookie,body:{active:!0,moduleId:a,refsetId:ye,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 rn(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=${ye}&limit=${o}&offset=${n}`;t.activeOnly&&(a+="&active=true");let c=await x(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:ye,total:c.body.total??l.length,axioms:l}}}async function sn(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 x(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!==ye)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 ${ye}.`}};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 x(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 vs(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 Ke(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 x(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=Z(o.branchPath),c=`${n}/browser/${a}/${o.projectKey}/${o.taskKey}/validate/concept`,d=await x(c,{method:"POST",body:yt(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)?vs(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 an=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+=an){let a=r.slice(s,s+an),c=await x(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 C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=[],i=0;for(;;){let h=`${io(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(o.branchPath)}`,g=await x(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 I=g.body?.totalPages??1;if(g.body?.last!==!1||i+1>=I)break;i+=1}let s=new Map,a=new Map,c=(h,g,I,E)=>{let D=h.get(g);D?(E.forEach(N=>N&&D.componentSubTypes.add(N)),D.lastUpdatedTime=I):h.set(g,{conceptId:g,lastUpdatedTime:I,componentSubTypes:new Set(E.filter(N=>!!N))})};for(let h of n)if(!(h.activityType!=="CONTENT_CHANGE"&&h.activityType!=="CLASSIFICATION_SAVE"))for(let g of h.conceptChanges??[]){let I=String(g.conceptId),E=g.componentChanges??[],D=E.map(O=>O.componentSubType);if(h.activityType==="CLASSIFICATION_SAVE"){c(a,I,h.commitDate,D);continue}let N=E.some(O=>O.componentSubType!=="INFERRED_RELATIONSHIP");c(N?s:a,I,h.commitDate,D)}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,I)=>(I.lastUpdatedTime??"").localeCompare(g.lastUpdatedTime??"")).map(g=>{let I=u&&!l.has(g.conceptId);return{conceptId:g.conceptId,fsn:l.get(g.conceptId)?.fsn,pt:l.get(g.conceptId)?.pt,...I?{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 cn(e,t,r){let o=await C(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 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 Le(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 ws(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 Ke(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 dn(e,t,r){let o=await C(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 ws(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 ln(e,t,r){let o=await C(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 l=await je(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 kt=new Set;function un(e){if(!(!e||typeof e!="object"))for(let t of kt)t(e)}function Ts(e){return kt.add(e),()=>kt.delete(e)}function As(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 _e(e){let t=()=>{};return{promise:new Promise(o=>{t=Ts(n=>{As(n,e)&&(t(),o(n))})}),cancel:t}}var bt=["RUNNING","BUILDING","SCHEDULED","QUEUED"],vt=["QUEUED","SCHEDULED","RUNNING"],Rs=["Promoted","Completed"],pn=5e3;function It(e){return new Promise(t=>setTimeout(t,e))}async function $s(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 It(t)}}function Es(){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 Ps=Es(),js=180;function Ns(){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 Ds=Ns(),Os=900;async function gn(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?_e(o):void 0,l=await Promise.race(d?[It(c).then(()=>{}),d.promise]:[It(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 yn(e,t,r){let o=await K(e,t,r);if(!o)return{error:`Could not fetch task ${t}/${r}.`};if(o.status&&Rs.includes(o.status))return{error:`Task ${t}/${r} is ${o.status} \u2014 cannot start a new job.`};if(o.status==="New"){let n=`${P(e)}/projects/${t}/tasks/${r}`;await x(n,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function St(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await x(o,{method:"POST",body:{},cookie:e.cookie}),(await K(e,t,r))?.latestClassificationJson}async function mn(e,t,r,o,n){let i,{value:s,timedOut:a}=await gn(async()=>{let d=(await St(e,t,r))?.status;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||bt.includes(d)),value:d}},Ps,n,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function Ct(e,t,r){let o=`${A(e)}/${t}/classifications`,n=await x(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 hn(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 St(e,n,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:bt.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function kn(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 yn(e,i,s);if(c.error)return{statusCode:400,body:{error:c.error}};let d=t.timeoutSeconds??js,l=await St(e,i,s),u=l?.status,p=l?.id;if(p&&u&&bt.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:N,timedOut:O}=await mn(e,i,s,a,d),Re=await Ct(e,a,p),dt={accepted:!1};return!O&&N==="COMPLETED"&&(dt=await xt(e,a,i,s,p)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: attached job ${p} final status ${N??"unknown"}${O?" (timed out waiting)":""}, save ${JSON.stringify(dt)}`),{statusCode:200,body:{jobId:p,finalStatus:N,timedOut:O,details:Re,save:dt,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 N=await Ct(e,a,p),O=await xt(e,a,i,s,p);return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: accepted existing job ${p}, save ${JSON.stringify(O)}`),{statusCode:200,body:{jobId:p,finalStatus:"COMPLETED",timedOut:!1,details:N,save:O,acceptedExisting:!0}}}let y=`${P(e)}/projects/${i}/tasks/${s}/classifications`,k=await x(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:I}=await mn(e,i,s,a,d),E=await Ct(e,a,h),D={accepted:!1};return!I&&g==="COMPLETED"&&(D=await xt(e,a,i,s,h)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: final status ${g??"unknown"}${I?" (timed out waiting)":""}, save ${JSON.stringify(D)}`),{statusCode:200,body:{jobId:h,finalStatus:g,timedOut:I,details:E,save:D}}}var Fs=["SAVED","STALE","SAVE_FAILED"],Ls=120;async function xt(e,t,r,o,n){let i=`${A(e)}/${t}/classifications/${n}`,s=await x(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(Ls*1e3/pn),{value:c,timedOut:d}=await $s(async()=>{let u=(await x(i,{cookie:e.cookie})).body?.status;return{done:!!u&&Fs.includes(u),value:u}},pn,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 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}=o,a=(await K(e,n,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&vt.includes(a)}}}async function fn(e,t,r,o,n){let i,{value:s,timedOut:a}=await gn(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||vt.includes(d)),value:d}},Ds,n,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function xn(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 yn(e,n,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Os,l=(await K(e,n,i))?.latestValidationStatus;if(l&&vt.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 fn(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=`${P(e)}/projects/${n}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await x(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 fn(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 In(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",o=`${P(e)}/projects${r}`;return(await x(o,{cookie:e.cookie})).body??[]}async function bn(e,t){let r=`${P(e)}/projects/${t}/tasks`;return(await x(r,{cookie:e.cookie})).body??[]}async function vn(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",o=`${P(e)}/projects/my-tasks${r}`;return(await x(o,{cookie:e.cookie})).body??[]}async function Sn(e,t){let r=`${P(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 x(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 wn(e,t){let r=`${P(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,o=await x(r,{cookie:e.cookie});return Array.isArray(o.body)?o.body:[]}var Ks="IN_PROGRESS";async function Tn(e,t){let r=`${P(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,o=await x(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 x(r,{method:"PUT",body:{status:Ks},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 An(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 wt(e){return JSON.stringify([e])}function Rn(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 Tt(e,t={},r=""){let o=Object.entries(t).map(([n,i])=>`${n}:${i}`);return[e,...o,"",r].join(`
|
|
3
|
-
`)+"\0"}function
|
|
2
|
+
"use strict";var _i=Object.create;var $e=Object.defineProperty;var Ki=Object.getOwnPropertyDescriptor;var Mi=Object.getOwnPropertyNames;var Bi=Object.getPrototypeOf,Ui=Object.prototype.hasOwnProperty;var Vi=(e,t)=>{for(var r in t)$e(e,r,{get:t[r],enumerable:!0})},to=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Mi(t))!Ui.call(e,n)&&n!==r&&$e(e,n,{get:()=>t[n],enumerable:!(o=Ki(t,n))||o.enumerable});return e};var S=(e,t,r)=>(r=e!=null?_i(Bi(e)):{},to(t||!e||!e.__esModule?$e(r,"default",{value:e,enumerable:!0}):r,e)),qi=e=>to($e({},"__esModule",{value:!0}),e);var Ya={};Vi(Ya,{COMMANDS:()=>eo,main:()=>Li,parsePositionals:()=>Oi});module.exports=qi(Ya);var z={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"}},Hi={prod:"production",production:"production",live:"production",uat:"uat",staging:"uat",dev:"dev",development:"dev"},Ee=Object.keys(z);function oo(e){return Hi[e.trim().toLowerCase()]??null}var ue="uat",za=z.uat.imsEndpoint,Qa=z.uat.terminologyServerEndpoint,Za=z.uat.authoringServicesEndpoint;var Gi=S(require("http")),Ji=S(require("https"));function x(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:"?Ji:Gi,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 I="";g.on("data",E=>{I+=E}),g.on("end",()=>{if(y)return;y=!0,clearTimeout(h);let E=g.statusCode??0,N=(g.headers["content-type"]??"").includes("application/json"),O=null,Re=!1;if(I)try{O=JSON.parse(I)}catch{Re=!N}a({statusCode:E,body:O,rawBody:I,sessionExpired:Re})})});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 q="900000000000509007",Q="900000000000508004";var no={[q]:"en-us",[Q]:"en-gb"},ro={[q]:"true",[Q]:"true"},Wi={},Yi={isExtension:!1,useInternationalLanguageRefsets:!1,dialects:no,dialectDefaults:ro,readOnlyDialects:Wi,defaultLanguage:"en"};function io(e){if(!e||!("defaultModuleId"in e)||e.defaultModuleId==null)return Yi;let t={[q]:"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?no:t,dialectDefaults:a?ro:r,readOnlyDialects:o,defaultLanguage:n[0]??"en"}}function lt(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 Pe(e,t){return e.isExtension&&!e.useInternationalLanguageRefsets?{[q]:"PREFERRED"}:lt(e,"PREFERRED",t,"en")}var Xi="900000000000207008";function so(e){return e.replace(/\/$/,"")}function A(e){return so(e.terminologyServerEndpoint)}function P(e){return so(e.authoringServicesEndpoint)}function ao(e){return`${new URL(P(e)).origin}/authoring-traceability-service`}function Z(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: pass --project/--task explicitly, or work in a named context ("--context <name>" with "select-task") or a pinned session (AUTHORING_CLI_TASK).'}:(s||(s=await ut(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 ee(e,t){let r=A(e),o=await x(`${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 x(`${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 ut(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}`;return(await x(o,{cookie:e.cookie})).body?.branchPath??null}async function co(e,t,r){let o=r?.get(t);if(o)return o;let n=`${P(e)}/projects/${t}`,s=(await x(n,{cookie:e.cookie})).body?.metadata??{};return r?.set(t,s),s}async function B(e,t,r){let o=await co(e,t,r),n=o.multipleModuleEditingDisabled,i=!n||n==="false";return o.expectedExtensionModules?.length&&i?o.expectedExtensionModules[0]:o.defaultModuleId?o.defaultModuleId:Xi}async function te(e,t,r){let o=await co(e,t,r);return io(o)}async function oe(e,t){let r=e.replace(/\/$/,"")+"/auth",o=await x(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 uo=S(require("crypto"));async function _(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}`;return(await x(o,{cookie:e.cookie})).body??null}function lo(e){let t=e?.trim();return t?t.toLowerCase():null}async function w(e,t){let r=lo(e.currentUsername);if(!r)return null;let o=await _(e,t.projectKey,t.taskKey),n=lo(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 zi="116680003";function pe(e,t,r,o,n="PREFERRED",i=!1){let s=e==="FSN"?Pe(o,i):lt(o,n,i,"en");return{active:!0,moduleId:r,type:e,term:t,lang:"en",caseSignificance:"CASE_INSENSITIVE",acceptabilityMap:s}}async function po(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 w(e,n);if(i)return i;let{projectKey:s,taskKey:a,branchPath:c}=n,d=Z(c),l=t.moduleId||await B(e,s,o),u=await te(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:[pe("FSN",y,l,u,"PREFERRED",!0),pe("SYNONYM",p,l,u,"PREFERRED",!0)],relationships:[],classAxioms:[{axiomId:uo.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:l,relationships:[{active:!0,groupId:0,type:{conceptId:zi},target:{conceptId:t.parentConceptId}}]}]},h=`${A(e)}/browser/${d}/${s}/${a}/concepts/?validate=true`,g=await x(h,{method:"POST",body:k,cookie:e.cookie});if(g.sessionExpired){let D="IMS session expired \u2014 re-sign in.";return e.onLog?.(`[${new Date().toISOString()}] create-concept ${s}/${a}: SESSION EXPIRED`),{statusCode:401,body:{error:D}}}let I=g.body,E=I&&"conceptId"in I?I.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,I?.validationResults),{statusCode:g.statusCode,body:g.body}}var Qi=["descriptions","descriptionFull","axioms","inferred","gci","gciAxiomsCount","full"],Zi={descriptions:"--descriptions",descriptionFull:"--description-full",axioms:"--axioms",inferred:"--inferred",gci:"--gci",gciAxiomsCount:"--gci-axioms-count",full:"--full"};function es(e,t){return(Array.isArray(e[t])?e[t]:[]).filter(o=>o.active!==!1).length}function mo(e,t){return(Array.isArray(e.relationships)?e.relationships:[]).filter(o=>o.characteristicType===t)}function me(e){return{conceptId:e.conceptId,fsn:e.fsn,pt:e.pt,active:e.active,definitionStatus:e.definitionStatus}}function fe(e){return typeof e=="object"&&e!==null}function ts(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((fe(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:fe(u)?u.conceptId:void 0,targetFsn:fe(u)&&fe(u.fsn)?u.fsn.term:void 0,active:a.active!==!1,effectiveTime:a.effectiveTime??null,released:a.released??!1})})}return n}async function je(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=Qi.filter(c=>t[c]);if(a.length>1)return{statusCode:400,body:{error:`Specify only one of ${a.map(c=>Zi[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 x(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 x(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||!fe(i.body))return{statusCode:i.statusCode,body:i.body};let s=i.body;if(t.attributeType){let a=t.gci?"gciAxioms":"classAxioms",c=ts(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:{...me(s),descriptions:a}}}return t.descriptionFull?{statusCode:i.statusCode,body:{...me(s),descriptions:s.descriptions??[]}}:t.axioms?{statusCode:i.statusCode,body:{...me(s),classAxioms:s.classAxioms??[],relationships:mo(s,"STATED_RELATIONSHIP")}}:t.inferred?{statusCode:i.statusCode,body:{...me(s),relationships:mo(s,"INFERRED_RELATIONSHIP")}}:t.gci?{statusCode:i.statusCode,body:{...me(s),gciAxioms:s.gciAxioms??[]}}:t.gciAxiomsCount?{statusCode:i.statusCode,body:{conceptId:s.conceptId,gciAxiomsCount:es(s,"gciAxioms")}}:{statusCode:i.statusCode,body:s}}var os=500,ns=1e4;async function Ne(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 x(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(os,ns-d);if(l<=0)break;let u=await x(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 ge=1e3;function rs(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 fo(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)),x(`${n}?${p.toString()}`,{cookie:e.cookie})};if(typeof t.limit=="number"||typeof t.offset=="number"){let l=await i(t.limit??ge,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(ge,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<ge||c>=a)break;d+=ge}return{statusCode:200,body:{total:a,limit:ge,offset:0,referencesByType:rs(s)}}}var ft=S(require("crypto"));function go(e){return typeof e=="object"&&e!==null}function is(e){let t=e.type,r=e.target,o=go(t)?t.conceptId:void 0,n=go(r)?r.conceptId:void 0;return typeof o=="string"&&typeof n=="string"?{typeId:o,targetId:n}:null}function ss(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 yo(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(is).filter(d=>d!=null);ss(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 as=["fsn","released","conceptId","definitionStatus","active","moduleId","isLeafInferred","effectiveTime","descriptions","annotations","preferredSynonym","relationships","inactivationIndicator","associationTargets","classAxioms","gciAxioms"],cs=["conceptId","released","active","moduleId","term","lang","caseSignificance","effectiveTime","descriptionId","type","acceptabilityMap","inactivationIndicator","associationTargets"],ds=["active","released","moduleId","target","relationshipId","effectiveTime","characteristicType","sourceId","modifier","type","groupId","concreteValue"],ls=["conceptId","fsn","pt","active","definitionStatus","effectiveTime","moduleId","released"],us=["axiomId","definitionStatus","effectiveTime","active","released","moduleId","relationships"],gt=["CASE_INSENSITIVE","INITIAL_CHARACTER_CASE_INSENSITIVE","ENTIRE_TERM_CASE_SENSITIVE"];function To(e){return gt.includes(e)}function ye(e,t){let r={};for(let o of t)o in e&&(r[o]=e[o]);return r}function De(e){return typeof e=="object"&&e!==null}function ho(e){return De(e)?ye(e,ls):e}function Ao(e){if(!De(e))return e;let t=ye(e,ds);return"type"in t&&(t.type=ho(t.type)),"target"in t&&(t.target=ho(t.target)),t}function ps(e){return De(e)?ye(e,cs):e}function ko(e){if(!De(e))return e;let t=ye(e,us);return Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Ao)),t}function yt(e){let t=ye(e,as);return Array.isArray(t.descriptions)&&(t.descriptions=t.descriptions.map(ps)),Array.isArray(t.relationships)&&(t.relationships=t.relationships.map(Ao)),Array.isArray(t.classAxioms)&&(t.classAxioms=t.classAxioms.map(ko)),Array.isArray(t.gciAxioms)&&(t.gciAxioms=t.gciAxioms.map(ko)),t}function ms(e){return new Promise(t=>setTimeout(t,e))}function fs(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 pt=[300,600,1200,2400,4800],Co=new Map;function gs(e,t){let o=(Co.get(e)??Promise.resolve()).then(t,t);return Co.set(e,o.then(()=>{},()=>{})),o}async function $(e,t,r,o){try{return await gs(t.branchPath,()=>ys(e,t,r,o))}catch(n){return{statusCode:500,body:{error:n instanceof Error?n.message:String(n)}}}}async function ys(e,t,r,o){for(let n=0;;n++){let i=A(e),s=`${i}/browser/${t.branchPath}/concepts/${r}`,a=await x(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=Z(t.branchPath),u=`${i}/browser/${l}/${t.projectKey}/${t.taskKey}/concepts/${r}?validate=true`,p=await x(u,{method:"PUT",body:yt(c),cookie:e.cookie});if(p.sessionExpired)return{statusCode:401,body:{error:"IMS session expired \u2014 re-sign in."}};if(fs(p)&&n<pt.length){e.onLog?.(`[${new Date().toISOString()}] update-concept ${t.projectKey}/${t.taskKey}: branch locked, retrying \u2014 ${r} (attempt ${n+1}/${pt.length})`),await ms(pt[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 xo=["PREFERRED","ACCEPTABLE"];async function Ro(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&&!xo.includes(t.acceptability))return{statusCode:400,body:{error:`acceptability must be one of: ${xo.join(", ")}.`}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await w(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o),a=await te(e,n.projectKey,o),c=t.type==="FSN"&&t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return $(e,n,t.conceptId,d=>{let l=Array.isArray(d.descriptions)?d.descriptions:[];return l.push(pe(t.type,c,s,a,t.acceptability??"ACCEPTABLE",!1)),d.descriptions=l,null})}async function $o(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 w(e,o);if(n)return n;let i=t.axiomIndex??0;return $(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 Eo(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 w(e,o);if(n)return n;let i=t.axiomIndex??0;return $(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 Po(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 w(e,o);return n||$(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 jo(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&&!To(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${gt.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(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 No(e,t,r){if(!t.conceptId||!t.descriptionId||!t.caseSignificance)return{statusCode:400,body:{error:"conceptId, descriptionId, and caseSignificance are required."}};if(!To(t.caseSignificance))return{statusCode:400,body:{error:`caseSignificance must be one of: ${gt.join(", ")}.`}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(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 mt=["PREFERRED","ACCEPTABLE","NOT_ACCEPTABLE"];function Io(e){return mt.includes(e)}function Do(e){return e.us&&!Io(e.us)?{statusCode:400,body:{error:`us must be one of: ${mt.join(", ")}.`}}:e.gb&&!Io(e.gb)?{statusCode:400,body:{error:`gb must be one of: ${mt.join(", ")}.`}}:null}function Oo(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.`}}:Do(e):{statusCode:400,body:{error:"Each entry requires a descriptionId."}}}function ht(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[q]:n[q]=r.us),r.gb&&(r.gb==="NOT_ACCEPTABLE"?delete n[Q]:n[Q]=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 Fo(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=Oo(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 w(e,i);return s||$(e,i,t.conceptId,a=>{let c=Array.isArray(a.descriptions)?a.descriptions:[];return ht(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=Oo(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 w(e,o);return n||$(e,o,t.conceptId,i=>{let s=Array.isArray(i.descriptions)?i.descriptions:[];for(let a of t.entries){let c=ht(s,t.conceptId,a);if(c)return c}return null})}async function _o(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 w(e,o);return n||$(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 Oe="REFERS_TO";async function Ko(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 w(e,o);return n||$(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={[Oe]:[t.associationTargetId]}),null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}function bo(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 Mo(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=Do(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 w(e,a);if(c)return c;let d=await te(e,a.projectKey,o);return $(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={[Oe]:[t.associationTargetId]})}}return p.active=!0,delete p.inactivationIndicator,delete p.associationTargets,p.acceptabilityMap=Pe(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=ht(u,t.conceptId,n);return y||(n.us==="PREFERRED"&&bo(u,t.descriptionId,q),n.gb==="PREFERRED"&&bo(u,t.descriptionId,Q),null)})}var hs="900000000000490003",vo=["NOT_SEMANTICALLY_EQUIVALENT","OUTDATED","GRAMMATICAL_DESCRIPTION_ERROR","NONCONFORMANCE_TO_EDITORIAL_POLICY"];async function Bo(e,t,r){if(!t.conceptId||!t.descriptionId||!t.reason)return{statusCode:400,body:{error:"conceptId, descriptionId, and reason are required."}};if(!vo.includes(t.reason))return{statusCode:400,body:{error:`reason must be one of: ${vo.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 w(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members?referencedComponentId=${encodeURIComponent(t.descriptionId)}&referenceSet=${hs}&active=true`,a=await x(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.`}}:$(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={[Oe]:[t.targetId]}:delete u.associationTargets,null):{statusCode:404,body:{error:`Concept ${t.conceptId} has no description ${t.descriptionId}.`}}})}async function Uo(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 w(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o),a=await te(e,n.projectKey,o),c=t.semanticTag?`${t.term} (${t.semanticTag})`:t.term;return $(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={[Oe]:[t.associationTargetId]}),l.push(pe("FSN",c,s,a,"PREFERRED",!1)),d.descriptions=l,null)})}function Vo(e,t,r){return $(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 qo(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 w(e,o);return n||Vo(e,o,t)}async function Ho(e,t,r){if(!t.conceptId||!t.axiomId||!Array.isArray(t.relationships))return{statusCode:400,body:{error:"conceptId, axiomId, and relationships (array) are required."}};let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);return n||$(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 Go(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 w(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o);return $(e,n,t.conceptId,a=>{let c=Array.isArray(a.classAxioms)?a.classAxioms:[];return c.push({axiomId:ft.randomUUID(),definitionStatus:t.definitionStatus??"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.classAxioms=c,null})}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."}};let n=await C(e,t,r);if(!n.ok)return{statusCode:400,body:{error:n.error}};let i=await w(e,n);if(i)return i;let s=t.moduleId||await B(e,n.projectKey,o);return $(e,n,t.conceptId,a=>{let c=Array.isArray(a.gciAxioms)?a.gciAxioms:[];return c.push({axiomId:ft.randomUUID(),definitionStatus:"PRIMITIVE",effectiveTime:null,active:!0,released:!1,moduleId:s,relationships:t.relationships}),a.gciAxioms=c,null})}async function Wo(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 w(e,o);return n||$(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 Yo(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 w(e,o);return n||$(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 ks="116680003";function So(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 Cs(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:ks},target:{conceptId:i.id}});let o=Array.isArray(e.attributes)?e.attributes:[];for(let i of o)t.push(So(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(So(c,s+1))}),t}async function Xo(e,t,r,o){let n=A(e),i=await x(`${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 xs="116680003";function Is(e){return e.some(t=>t.active===!1||(typeof t.typeId=="string"?t.typeId:t.type?.conceptId)!==xs?!1:t.target?.definitionStatus==="FULLY_DEFINED")}async function bs(e,t,r){let o=A(e),n=await x(`${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=Cs(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 vs(e,t,r,o){let n=await Xo(e,t,r,o);if(!n.ok)return n;let i=await bs(e,t,r);return i.ok?{ok:!0,value:{axiom:n.value.axiom,axiomId:n.value.axiomId,targetRelationships:i.value}}:i}function Ss(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 wo(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(Ss(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 ws(e,t){let r=wo(e),o=wo(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 zo(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 w(e,o);if(n)return n;let i=await vs(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 ws(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}}):Vo(e,o,{conceptId:t.conceptId,axiomId:a,relationships:c})}async function Fe(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 Xo(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 Is(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 Qo(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 w(e,o);return n||$(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 Zo(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 w(e,o);return n||$(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=yo(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 en(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 w(e,o);return n||$(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 tn(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 w(e,o);return n||$(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 Ts=8;async function Le(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 Fe(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(Ts,r.length);return await Promise.all(Array.from({length:c},()=>a())),{matched:n,skipped:i}}async function on(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await Ne(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 Le(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 nn(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 w(e,o);if(n)return n;let i=A(e),s=`${i}/browser/${o.branchPath}/concepts/${t.conceptId}`,a=await x(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 x(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 he="733073007",rn=["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 As(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||!rn.includes(o)?`OWL expression doesn't start with a recognized top-level axiom keyword${o?` (saw "${o}")`:""} \u2014 expected one of ${rn.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 sn(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=As(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 w(e,i);if(s)return s;let a=t.moduleId||await B(e,i.projectKey,o),d=`${A(e)}/${i.branchPath}/members`,l=await x(d,{method:"POST",cookie:e.cookie,body:{active:!0,moduleId:a,refsetId:he,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 an(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=${he}&limit=${o}&offset=${n}`;t.activeOnly&&(a+="&active=true");let c=await x(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:he,total:c.body.total??l.length,axioms:l}}}async function cn(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 w(e,o);if(n)return n;let s=`${A(e)}/${o.branchPath}/members/${encodeURIComponent(t.memberId)}`,a=await x(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!==he)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 ${he}.`}};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 x(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 Rs(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 _e(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 x(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=Z(o.branchPath),c=`${n}/browser/${a}/${o.projectKey}/${o.taskKey}/validate/concept`,d=await x(c,{method:"POST",body:yt(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)?Rs(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 dn=200;async function $s(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+=dn){let a=r.slice(s,s+dn),c=await x(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 H(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=`${ao(e)}/activities?size=500&page=${i}&onBranch=${encodeURIComponent(o.branchPath)}`,g=await x(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 I=g.body?.totalPages??1;if(g.body?.last!==!1||i+1>=I)break;i+=1}let s=new Map,a=new Map,c=(h,g,I,E)=>{let D=h.get(g);D?(E.forEach(N=>N&&D.componentSubTypes.add(N)),D.lastUpdatedTime=I):h.set(g,{conceptId:g,lastUpdatedTime:I,componentSubTypes:new Set(E.filter(N=>!!N))})};for(let h of n)if(!(h.activityType!=="CONTENT_CHANGE"&&h.activityType!=="CLASSIFICATION_SAVE"))for(let g of h.conceptChanges??[]){let I=String(g.conceptId),E=g.componentChanges??[],D=E.map(O=>O.componentSubType);if(h.activityType==="CLASSIFICATION_SAVE"){c(a,I,h.commitDate,D);continue}let N=E.some(O=>O.componentSubType!=="INFERRED_RELATIONSHIP");c(N?s:a,I,h.commitDate,D)}for(let h of s.keys())a.delete(h);let d=[...new Set([...s.keys(),...a.keys()])],{terms:l,resolved:u}=await $s(e,o.branchPath,d),p=h=>[...h.values()].sort((g,I)=>(I.lastUpdatedTime??"").localeCompare(g.lastUpdatedTime??"")).map(g=>{let I=u&&!l.has(g.conceptId);return{conceptId:g.conceptId,fsn:l.get(g.conceptId)?.fsn,pt:l.get(g.conceptId)?.pt,...I?{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 ln(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await H(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 Le(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 Es(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 _e(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 un(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await H(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 Es(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 pn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await H(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 je(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 kt=new Set;function mn(e){if(!(!e||typeof e!="object"))for(let t of kt)t(e)}function Ps(e){return kt.add(e),()=>kt.delete(e)}function js(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 Ke(e){let t=()=>{};return{promise:new Promise(o=>{t=Ps(n=>{js(n,e)&&(t(),o(n))})}),cancel:t}}var bt=["RUNNING","BUILDING","SCHEDULED","QUEUED"],vt=["QUEUED","SCHEDULED","RUNNING"],Ns=["Promoted","Completed"],fn=5e3;function It(e){return new Promise(t=>setTimeout(t,e))}async function Ds(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 It(t)}}function Os(){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 Fs=Os(),Ls=180;function _s(){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 Ks=_s(),Ms=900;async function hn(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?Ke(o):void 0,l=await Promise.race(d?[It(c).then(()=>{}),d.promise]:[It(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 kn(e,t,r){let o=await _(e,t,r);if(!o)return{error:`Could not fetch task ${t}/${r}.`};if(o.status&&Ns.includes(o.status))return{error:`Task ${t}/${r} is ${o.status} \u2014 cannot start a new job.`};if(o.status==="New"){let n=`${P(e)}/projects/${t}/tasks/${r}`;await x(n,{method:"PUT",body:{status:"IN_PROGRESS"},cookie:e.cookie})}return{}}async function St(e,t,r){let o=`${P(e)}/projects/${t}/tasks/${r}/classifications/status/cache-evict`;return await x(o,{method:"POST",body:{},cookie:e.cookie}),(await _(e,t,r))?.latestClassificationJson}async function gn(e,t,r,o,n){let i,{value:s,timedOut:a}=await hn(async()=>{let d=(await St(e,t,r))?.status;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] classify ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||bt.includes(d)),value:d}},Fs,n,{entityType:"Classification",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}async function Ct(e,t,r){let o=`${A(e)}/${t}/classifications`,n=await x(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 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}=o,s=await St(e,n,i);return s?{statusCode:200,body:{hasClassification:!0,jobId:s.id,status:s.status,running:bt.includes(s.status),latestClassificationJson:s}}:{statusCode:200,body:{hasClassification:!1}}}async function xn(e,t,r){let o=await C(e,t,r);if(!o.ok)return{statusCode:400,body:{error:o.error}};let n=await w(e,o);if(n)return n;let{projectKey:i,taskKey:s,branchPath:a}=o,c=await kn(e,i,s);if(c.error)return{statusCode:400,body:{error:c.error}};let d=t.timeoutSeconds??Ls,l=await St(e,i,s),u=l?.status,p=l?.id;if(p&&u&&bt.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:N,timedOut:O}=await gn(e,i,s,a,d),Re=await Ct(e,a,p),dt={accepted:!1};return!O&&N==="COMPLETED"&&(dt=await xt(e,a,i,s,p)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: attached job ${p} final status ${N??"unknown"}${O?" (timed out waiting)":""}, save ${JSON.stringify(dt)}`),{statusCode:200,body:{jobId:p,finalStatus:N,timedOut:O,details:Re,save:dt,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 N=await Ct(e,a,p),O=await xt(e,a,i,s,p);return e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: accepted existing job ${p}, save ${JSON.stringify(O)}`),{statusCode:200,body:{jobId:p,finalStatus:"COMPLETED",timedOut:!1,details:N,save:O,acceptedExisting:!0}}}let y=`${P(e)}/projects/${i}/tasks/${s}/classifications`,k=await x(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:I}=await gn(e,i,s,a,d),E=await Ct(e,a,h),D={accepted:!1};return!I&&g==="COMPLETED"&&(D=await xt(e,a,i,s,h)),e.onLog?.(`[${new Date().toISOString()}] classify ${i}/${s}: final status ${g??"unknown"}${I?" (timed out waiting)":""}, save ${JSON.stringify(D)}`),{statusCode:200,body:{jobId:h,finalStatus:g,timedOut:I,details:E,save:D}}}var Bs=["SAVED","STALE","SAVE_FAILED"],Us=120;async function xt(e,t,r,o,n){let i=`${A(e)}/${t}/classifications/${n}`,s=await x(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/fn),{value:c,timedOut:d}=await Ds(async()=>{let u=(await x(i,{cookie:e.cookie})).body?.status;return{done:!!u&&Bs.includes(u),value:u}},fn,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 In(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 _(e,n,i))?.latestValidationStatus;return{statusCode:200,body:{hasValidation:!!a,status:a,running:!!a&&vt.includes(a)}}}async function yn(e,t,r,o,n){let i,{value:s,timedOut:a}=await hn(async()=>{let d=(await _(e,t,r))?.latestValidationStatus;return d!==i&&(i=d,e.onLog?.(`[${new Date().toISOString()}] validate-task ${t}/${r}: status ${d??"unknown"}`)),{done:!(!d||vt.includes(d)),value:d}},Ks,n,{entityType:"Validation",projectKey:t,taskKey:r,branchPath:o},e.onLog);return{finalStatus:s,timedOut:a}}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=await kn(e,n,i);if(a.error)return{statusCode:400,body:{error:a.error}};let c=t.timeoutSeconds??Ms,l=(await _(e,n,i))?.latestValidationStatus;if(l&&vt.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 yn(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=`${P(e)}/projects/${n}/tasks/${i}/validation`;typeof t.enableMrcmValidation=="boolean"&&(u+=`?enableMRCMValidation=${t.enableMrcmValidation}`);let p=await x(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 yn(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 vn(e,t={}){let r=t.lightweight!==void 0?`?lightweight=${t.lightweight}`:"",o=`${P(e)}/projects${r}`;return(await x(o,{cookie:e.cookie})).body??[]}async function Sn(e,t){let r=`${P(e)}/projects/${t}/tasks`;return(await x(r,{cookie:e.cookie})).body??[]}async function wn(e,t={}){let r=t.excludePromoted!==void 0?`?excludePromoted=${t.excludePromoted}`:"",o=`${P(e)}/projects/my-tasks${r}`;return(await x(o,{cookie:e.cookie})).body??[]}async function Tn(e,t){let r=`${P(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 x(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 An(e,t){let r=`${P(e)}/projects/tasks/search?projectKeys=${encodeURIComponent(t)}&statuses=Deleted`,o=await x(r,{cookie:e.cookie});return Array.isArray(o.body)?o.body:[]}var Vs="IN_PROGRESS";async function Rn(e,t){let r=`${P(e)}/projects/${t.projectKey}/tasks/${t.taskKey}`,o=await x(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 x(r,{method:"PUT",body:{status:Vs},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 $n(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 wt(e){return JSON.stringify([e])}function En(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 Tt(e,t={},r=""){let o=Object.entries(t).map(([n,i])=>`${n}:${i}`);return[e,...o,"",r].join(`
|
|
3
|
+
`)+"\0"}function Pn(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
|
|
7
|
-
`).map(l=>l.trim()).filter(Boolean),d=0;for(let l of c)Nt(l,s)!==null&&d++;return{checked:c.length,decrypted:d}}catch{return{checked:0,decrypted:0}}finally{
|
|
8
|
-
`),[s,a]=i;if(s&&a)return`ws://127.0.0.1:${s}${a}`}if(Date.now()>=n)throw new W(`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 Ft=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 Jn.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 W(`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
|
|
9
|
-
am start --user 0 -n ${
|
|
10
|
-
`;try{F.writeFileSync(e,o,{mode:493}),F.chmodSync(e,493),await
|
|
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 Nn=S(require("ws"));var jn=[1e3,2e3,5e3,1e4,3e4];function Dn(e,t={}){let r=t.createSocket??((l,u)=>new Nn.default(l,u)),o=!1,n,i=0,s,a=e.cookie.replace(/[^\x20-\x7e\t]/g,""),c=()=>{if(o)return;let l=jn[Math.min(i,jn.length-1)];i+=1,s=setTimeout(d,l)};function d(){if(o)return;let u=`${e.authoringServicesEndpoint.replace(/\/+$/,"")+"/"}authoring-services-websocket/${En()}`,p=r(u,a?{headers:{cookie:a}}:{});n=p,p.on("message",y=>{let k=$n(y.toString());if(k.type==="open"){p.send(wt(Tt("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=Pn(h);if(g){if(g.command==="CONNECTED"){i=0;let I=`/topic/user/${e.login}/notifications`;p.send(wt(Tt("SUBSCRIBE",{id:`sca-subscription-id-${e.login}`,destination:I})));continue}if(g.command==="MESSAGE"){try{e.onNotification(JSON.parse(g.body))}catch(I){console.warn("[authoring-cli] scaNotificationRelay: failed to parse notification body:",I)}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 On(e,t,r={}){let o=r.startRelay??Dn,n=r.onNotification??mn,i=o({authoringServicesEndpoint:e.authoringServicesEndpoint,cookie:e.cookie,login:t,onNotification:n});return{stop:()=>i.stop()}}var qs=60;async function Fn(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??qs,c=Ke({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 cr=S(require("http")),Qe=require("child_process"),dr=require("util");var Me=S(require("fs")),Ln=S(require("os")),Be=S(require("path"));function Rt(){return Be.join(Ln.homedir(),".authoring-cli-chrome")}function U(){return Be.join(Rt(),"profile")}function Hs(){return Be.join(U(),"Local State")}function Gs(){let e=Hs();if(!Me.existsSync(e))return[];let t;try{t=JSON.parse(Me.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 At="authoring-cli";function Ue(e=Gs()){return e.find(r=>r.directoryName===At)??{directoryName:At,displayName:At}}var Vn=require("child_process"),qn=require("util"),ke=S(require("fs")),Ye=S(require("os")),Ce=S(require("path"));var _n=require("child_process"),Kn=require("util"),Ve=S(require("crypto")),J=S(require("fs")),Js=(0,Kn.promisify)(_n.exec);function $t(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 Et(e=process.platform){if(e==="darwin"){let{stdout:t}=await Js('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 Mn=1003,Ys=1;function Pt(e){if(e==="darwin")return Mn;if(e==="linux")return Ys;throw new Error(`Chrome cookie decryption is only supported on macOS and Linux. Detected platform: ${e}.`)}function jt(e,t=Mn){return Ve.pbkdf2Sync(e,"saltysalt",t,16,"sha1")}function Nt(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=Ve.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&&$t(a)&&!$t(s)&&(c=a),$t(c)?c.toString("utf8"):null}function qe(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 He(e){for(let t of[e,e+"-wal",e+"-shm"])try{J.unlinkSync(t)}catch{}}var Bn=S(require("fs"));var Un=[{path:"/usr/bin/chromium",configDir:"chromium"},{path:"/usr/bin/chromium-browser",configDir:"chromium"},{path:"/usr/bin/google-chrome-stable",configDir:"google-chrome"},{path:"/usr/bin/google-chrome",configDir:"google-chrome"},{path:"/snap/bin/chromium",configDir:"chromium"}],kl=Array.from(new Set(Un.map(e=>e.configDir)));function Ge(){return Un.find(e=>Bn.existsSync(e.path))??null}function Je(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 Hn=(0,qn.promisify)(Vn.exec),We=class extends Error{},ne=class extends Error{};function Dt(e){return Ce.join(U(),e,"Cookies")}function Xs(e=process.platform){return e==="linux"?Ge()!==null:ke.existsSync("/Applications/Google Chrome.app")}function zs(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 Qs(e){let t=e?.code;return t==="EPERM"||t==="EACCES"}async function Ot(e,t,r,o=process.platform){let n=Dt(e);if(!n||!ke.existsSync(n))return null;let i=Ce.join(Ye.tmpdir(),`authoring-cli-chrome-cookies-${process.pid}-${Date.now()}.db`);try{qe(n,i);let s;try{s=await Et(o)}catch{return null}let a=jt(s,Pt(o)),c=p=>`'${p.replace(/'/g,"''")}'`,l=`SELECT hex(encrypted_value) FROM cookies WHERE host_key IN (${zs(t).map(c).join(", ")}) AND name = ${c(r)} ORDER BY length(host_key) DESC, creation_utc DESC LIMIT 1;`,{stdout:u}=await Hn(`sqlite3 "${i}" "${l}"`);return Nt(u.trim(),a)}catch{return null}finally{He(i)}}async function Zs(e,t=process.platform,r=25){let o=Dt(e);if(!o||!ke.existsSync(o))return{checked:0,decrypted:0};let n=Ce.join(Ye.tmpdir(),`authoring-cli-chrome-cookies-diag-${process.pid}-${Date.now()}.db`);try{qe(o,n);let i;try{i=await Et(t)}catch{return{checked:0,decrypted:0}}let s=jt(i,Pt(t)),{stdout:a}=await Hn(`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)Nt(l,s)!==null&&d++;return{checked:c.length,decrypted:d}}catch{return{checked:0,decrypted:0}}finally{He(n)}}function ea(e){let t=Dt(e);if(!ke.existsSync(t))return null;let r=Ce.join(Ye.tmpdir(),`authoring-cli-chrome-cookies-precheck-${process.pid}-${Date.now()}.db`);try{return qe(t,r),null}catch(o){return Qs(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{He(r)}}function ta(e){return new Promise(t=>setTimeout(t,e))}async function Gn(e,t={}){let r=t.platform??process.platform,o=t.isChromeInstalled??(()=>Xs(r));if(r!=="darwin"&&r!=="linux")throw new We(`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 We(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,I,E)=>Ot(g,I,E,r)),i=t.sleep??ta,s=t.onWarning??(g=>console.error(g)),a=t.checkCookieFileReadable??ea,c=t.diagnoseDecryption??Zs,d=Je(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 ne(`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 ne(`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 re=S(require("fs")),Lt=S(require("path")),Jn=S(require("ws"));var W=class extends Error{};function Wn(e){try{re.unlinkSync(Lt.join(e,"DevToolsActivePort"))}catch{}}async function oa(e,t=1e4,r=100){let o=Lt.join(e,"DevToolsActivePort"),n=Date.now()+t;for(;;){if(re.existsSync(o)){let i=re.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 W(`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 Ft=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 Jn.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 W(`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 na(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 W(`No page target appeared via CDP within ${t}ms.`);await new Promise(s=>setTimeout(s,r))}}async function Yn(e,t={}){let r=t.waitForPort??oa,o=t.connect??Ft.connect,n=t.sleep??(u=>new Promise(p=>setTimeout(p,u))),i=e.setupTimeoutMs??1e4,s=e.pollIntervalMs??750,a=e.timeoutMs??12e4,c=Je(t.validateCookie),d=await r(e.userDataDir,i),l=await o(d,i);try{let u=await na(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(I=>I.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 ne(`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 ze=require("child_process"),zn=require("util"),F=S(require("fs")),Qn=S(require("net")),Zn=(0,zn.promisify)(ze.exec),Xe=1,xe=`:${Xe}`,ra=["termux-x11","/data/data/com.termux/files/usr/bin/termux-x11"],_t="/data/data/com.termux/files/usr/bin",Xn="com.termux.x11",ia=`${Xn}/${Xn}.MainActivity`,sa="termux-x11-start-app";function Kt(e){return`/tmp/.X11-unix/X${e}`}async function aa(){for(let e of ra){if(e.startsWith("/")){if(F.existsSync(e))return e;continue}try{return await Zn(`command -v ${e}`),e}catch{}}return null}function ca(e,t=500){return new Promise(r=>{let o=Kt(e);if(!F.existsSync(o)){r(!1);return}let n=Qn.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 da(e,t=1e4){let r=Date.now()+t;return new Promise((o,n)=>{let i=()=>{if(F.existsSync(Kt(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 la(){if(!F.existsSync(_t))return;let e=`${_t}/${sa}`,t=`${_t}/bash`,o=`#!${F.existsSync(t)?t:"/bin/sh"}
|
|
9
|
+
am start --user 0 -n ${ia} >/dev/null 2>&1
|
|
10
|
+
`;try{F.writeFileSync(e,o,{mode:493}),F.chmodSync(e,493),await Zn(e,{timeout:5e3})}catch{}}async function er(e=process.platform){if(e!=="linux"||await ca(Xe))return xe;await la();let t=await aa();if(t===null)return xe;try{F.unlinkSync(Kt(Xe))}catch{}return(0,ze.spawn)(t,[xe],{detached:!0,stdio:"ignore"}).unref(),await da(Xe),xe}var L=S(require("fs")),or=S(require("os")),V=S(require("path"));var Ie=class extends Error{},ua="com.ysgao.authoring-cli.chrome-login",nr="authoring-cli-chrome",pa="/Applications/Google Chrome.app";function ma(e=pa,t=L.existsSync){let r=V.join(e,"Contents","MacOS","Google Chrome");if(t(r))return r;throw new Ie(`No Google Chrome installation found at ${e}. Install Google Chrome to use automatic session capture.`)}function tr(e){return`'${e.replace(/'/g,"'\\''")}'`}function fa(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 ${tr(e)} \\`,t.map(r=>` ${tr(r)}`).join(` \\
|
|
11
11
|
`),""].join(`
|
|
12
|
-
`)}function
|
|
12
|
+
`)}function ga(){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
13
13
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
14
14
|
<plist version="1.0">
|
|
15
15
|
<dict>
|
|
16
|
-
<key>CFBundleExecutable</key><string>${
|
|
17
|
-
<key>CFBundleIdentifier</key><string>${
|
|
16
|
+
<key>CFBundleExecutable</key><string>${nr}</string>
|
|
17
|
+
<key>CFBundleIdentifier</key><string>${ua}</string>
|
|
18
18
|
<key>CFBundleName</key><string>authoring-cli sign-in</string>
|
|
19
19
|
<key>CFBundlePackageType</key><string>APPL</string>
|
|
20
20
|
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
|
|
21
21
|
<key>CFBundleShortVersionString</key><string>1.0</string>
|
|
22
22
|
</dict>
|
|
23
23
|
</plist>
|
|
24
|
-
`}function
|
|
24
|
+
`}function ya(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 Ie(`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 rr(){return[V.join(Rt(),"launcher"),V.join(or.tmpdir(),"authoring-cli-chrome-launcher")]}function ir(){return`login-${process.pid}.app`}function sr(e){let t=e.chromeBinary??ma(),r=fa(t,e.flags);ya(r,e.profileDirectory);let o=e.dirCandidates??rr(),n=[];for(let i of o){let s=V.join(i,ir()),a=V.join(s,"Contents","MacOS");try{L.mkdirSync(a,{recursive:!0}),L.writeFileSync(V.join(s,"Contents","Info.plist"),ga());let c=V.join(a,nr);return L.writeFileSync(c,r,{mode:493}),L.chmodSync(c,493),s}catch(c){n.push(`${i}: ${c instanceof Error?c.message:String(c)}`)}}throw new Ie(`Could not create the Chrome launcher bundle in any candidate directory (${n.join("; ")}).`)}function ar(e=rr()){for(let t of e)try{L.rmSync(V.join(t,ir()),{recursive:!0,force:!0})}catch{}}var Mt=(0,dr.promisify)(Qe.exec);function Bt(e){let t=e.match(/^([a-z0-9]+)-snowstorm\.ihtsdotools\.org$/i);return t?`${t[1].toLowerCase()}-ims-ihtsdo`:"ims-ihtsdo"}var ha=["--no-sandbox","--password-store=basic","--force-device-scale-factor=2"],lr=["--no-first-run","--no-default-browser-check","--remote-debugging-port=0"];async function ka(e,t){let r=Ge();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 er();(0,Qe.spawn)(r.path,[...lr,...ha,`--user-data-dir=${U()}`,`--profile-directory=${t}`,e],{detached:!0,stdio:"ignore",env:{...process.env,DISPLAY:o}}).unref()}async function Ca(e,t){let r=`--user-data-dir=${U()}`,o=[r,`--profile-directory=${t}`,...lr,e],n=sr({flags:o,profileDirectory:t});await Mt(`open -n -a ${(s=>`'${s.replace(/'/g,"'\\''")}'`)(n)}`),ba(r).then(s=>{s&&ar()})}var xa=1e4,Ia=250;function ur(e){return new Promise(t=>setTimeout(t,e))}async function ba(e,t=xa,r=Ia){let o=i=>`'${i.replace(/'/g,"'\\''")}'`,n=Date.now()+t;for(;;){try{let{stdout:i}=await Mt(`pgrep -f ${o(e)}`);if(i.trim().length>0)return!0}catch{}if(Date.now()>=n)return!1;await ur(r)}}async function va(e,t=8e3,r=200){let o=`--user-data-dir=${e}`,n=async()=>{try{let{stdout:a}=await Mt(`pgrep -fl ${`'${o.replace(/'/g,"'\\''")}'`}`);return a.split(`
|
|
25
|
+
`).filter(c=>c.trim()&&!c.includes("--type=")).map(c=>parseInt(c.trim().split(/\s+/)[0],10)).filter(c=>Number.isFinite(c)&&c!==process.pid)}catch{return[]}},i=await n();for(let a of i)try{process.kill(a,"SIGTERM")}catch{}let s=Date.now()+t;for(;i.length>0&&Date.now()<s&&(await n()).length>0;)await ur(r)}function Sa(e,t,r){return r==="linux"?ka(e,t):Ca(e,t)}function wa(){return`<!DOCTYPE html>
|
|
25
26
|
<html>
|
|
26
27
|
<head>
|
|
27
28
|
<meta charset="utf-8">
|
|
@@ -32,20 +33,20 @@ am start --user 0 -n ${ea} >/dev/null 2>&1
|
|
|
32
33
|
<h3>You're signed in.</h3>
|
|
33
34
|
<p>Return to your terminal \u2014 the CLI is finishing sign-in automatically. You can close this tab.</p>
|
|
34
35
|
</body>
|
|
35
|
-
</html>`}async function
|
|
36
|
-
Expected one of: ${Ee.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=z[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||Mt(s),d=t===le&&!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}`,I=await oe(o,g).catch(()=>null);if(!I){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}ve({cookie:g,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:I,currentTask:null}),console.log(`${ot(I)} (from --cookie \u2014 no browser opened.)`),nt(l),console.log(` Session: ${Se()}`);return}let u=await $a(o);if(u){ve({cookie:u.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:u.account,currentTask:null}),console.log(`${ot(u.account)} (reused the already-stored session \u2014 no Chrome involved at all.)`),nt(l),console.log(` Session: ${Se()}`);return}let p=Ue(),y=await Ea(o,s,c,p.directoryName);if(y){ve({cookie:y.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:y.account,currentTask:null}),console.log(`${ot(y.account)} (reused an existing Chrome session in profile "${p.directoryName}" \u2014 no browser opened.)`),nt(l),console.log(` Session: ${Se()}`);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 lr({imsEndpoint:o,host:s,cookieName:c},{validateCookie:g=>oe(o,`${c}=${g}`).then(I=>I!==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 oe(o,k.cookie).catch(()=>null);ve({cookie:k.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:h,currentTask:null}),console.log(ot(h)),nt(l),console.log(` Session: ${Se()}`)}async function xr(){pr(),console.log("Signed out.")}var it=v(require("fs")),rt=v(require("path"));async function Ir(){let e=[rt.join(__dirname,"../../HELP.md"),rt.join(__dirname,"../HELP.md"),rt.join(process.cwd(),"HELP.md")];for(let t of e)try{if(it.existsSync(t)){let r=it.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 f(){let e;try{e=tt(),e&&(e=kr(e))}catch(t){console.error(t instanceof Error?t.message:String(t)),process.exit(1)}return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function Jt(e){let t=e.account;return t?.login??t?.username}function m(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,currentUsername:Jt(e),onLog:t=>console.error(t)}}function br(e){return e.projectKey??e.key??"?"}async function vr(e){let t=f(),r=m(t),o=await In(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=>br(i).length))+1;for(let i of o){let s=i.title??"";console.log(`${br(i).padEnd(n)}${s?`"${s}"`:""}`)}}function st(e){return e.taskKey??e.key??"?"}function Sr(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Pa(e){return e.projectKey||st(e).split("-")[0]||"?"}function Gt(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 Ht(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 wr(e){let t=f(),r=m(t),o=e.mine||!e.project,n=o?await vn(r):await bn(r,e.project);if(o&&e.project){let l=e.project.toLowerCase();n=n.filter(u=>(u.projectKey??"").toLowerCase()===l||st(u).toLowerCase().startsWith(`${l}-`))}if(e.status){let l=e.status.trim().toLowerCase();n=n.filter(u=>(u.status??"").toLowerCase()===l)}let i=Gt(n,Pa),s=Gt(n,Sr),a=Gt(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&&Ht("By project",i),!o&&s.length>1&&Ht("By assignee",s),a.length>1&&Ht("By status",a);return}let d=Math.max(...n.map(l=>st(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(`${st(l).padEnd(d)}${u?`"${u}"`:""}${p}${y}`)}}async function Tr(e){e.noSelect||X();let t=f(),r=m(t),o=Jt(t),n=e.unassigned?void 0:e.assignee||o,i=await Sn(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 ee(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}se({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function Ar(e){let t=f(),r=m(t);if(!e.task){let i=await wn(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}e.noSelect||X({projectKey:e.project,taskKey:e.task});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 ee(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||(se({projectKey:e.project,taskKey:e.task,branchPath:n}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function Rr(e){X({projectKey:e.project,taskKey:e.task});let t=f(),r=m(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 ee(r,o.branchPath);if(!n.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${n.error}`),process.exitCode=1;return}se({projectKey:e.project,taskKey:e.task,branchPath:o.branchPath});let i=Y();console.log(`\u2713 Current task set to ${e.project}/${e.task} (${o.branchPath})${i?` in context "${i}"`:""}`);let s=hr(e.task,i);s.length&&console.error(` Warning: context(s) ${s.map(a=>`"${a}"`).join(", ")} also hold ${e.task} \u2014 concurrent writes to one branch contend for its lock.`),n.created&&console.log(` created branch ${o.branchPath}`)}async function $r(e){let t=f(),r=qt();if(!r.task){r.source==="context"?console.log(`Context "${r.context}" has no task selected yet. Run "select-task --context ${r.context} --project <projectKey> --task <taskKey>".`):console.log(`No task context. Name this session with "--context <name>" (or ${ie}), pin it with ${_}, or pass --project/--task explicitly to any command.`);return}let{projectKey:o,taskKey:n}=r.task,i=r.task.branchPath||await ut(m(t),o,n)||"(branch not resolved)",s=r.source==="pin"?`pinned via ${_}`:`context "${r.context}"`;console.log(`Current task: ${o}/${n} (${i}) [${s}]`),(e.project||e.task)&&((!e.project||e.project===o)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function Er(e){if(e.remove!==void 0){if(!e.remove){console.error("--remove needs a context name."),process.exitCode=1;return}console.log(gr(e.remove)?`\u2713 Removed context "${e.remove}".`:`No context named "${e.remove}".`);return}let t=Vt(),r=Y(),o=we();t.length===0&&console.log("No contexts yet. Create one with: select-task --context <name> --project <projectKey> --task <taskKey>");let n=new Map;for(let i of t)i.currentTask&&n.set(i.currentTask.taskKey,[...n.get(i.currentTask.taskKey)??[],i.name]);for(let i of t){let s=i.name===r?"*":" ",a=i.currentTask,c=a&&(n.get(a.taskKey)?.length??0)>1?" (same task as another context \u2014 branch-lock contention possible)":"";console.log(`${s} ${i.name}: ${a?`${a.projectKey}/${a.taskKey} (${a.branchPath})`:"no task selected"}${i.updatedAt?` [${i.updatedAt}]`:""}${c}`)}o?console.log(`This session is pinned to ${o.projectKey}/${o.taskKey}.`):r&&console.log("(* = this session's context)")}async function Pr(e){let t=f(),r=m(t),o=await lo(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 jr(e){let t=f(),r=m(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 en(r,o,t.currentTask):await Ne(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 Nr(e){let t=f(),r=m(t),o=await je(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 Dr(e){let t=f(),r=m(t),o=await po(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 Or(e){let t=f(),r=m(t),o=await Ke(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 Fr(e){let t=f(),r=m(t),o=e.checkStatedParentsDefinitionStatus?await cn(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 Lr(e){let t=f(),r=m(t),o=await dn(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 Kr(e){let t=f(),r=m(t),o=await ln(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 _r(e){let t=f(),r=m(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}`),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 Mr(e){let t=f(),r=m(t),o=await Ao(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=f(),r=m(t),o=await Xo(r,{conceptId:e.id,axiomId:e.axiomId,relationshipId:e.relationshipId,relationshipIndex:e.relationshipIndex?Number(e.relationshipIndex):void 0,projectKey:e.project,taskKey:e.task},t.currentTask),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 Ur(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=f(),o=m(r),n=await zo(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 Vr(e){let t=f(),r=m(t),o=await Eo(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 qr(e){let t=f(),r=m(t),o=await Po(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 Jr(e){let t=f(),r=m(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 Oo(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 Do(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 Gr(e){let t=f(),r=m(t),o=await $o(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 Hr(e){let t=f(),r=m(t),o=await Ro(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 Wr(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=f(),o=m(r),n=await Uo(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 Yr(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=f(),o=m(r),n=await Vo(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 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}if(!Array.isArray(t)){console.error("--relationships must be a JSON array of relationship objects."),process.exitCode=1;return}let r=f(),o=m(r),n=await Jo(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 zr(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=f(),o=m(r),n=await qo(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 Qr(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=f(),r=m(t),o=await nn(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 Zr(e){let t=f(),r=m(t),o=await rn(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 ei(e){let t=f(),r=m(t),o=await sn(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 ti(e){let t=f(),r=m(t),o=await tn(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 oi(e){let t=f(),r=m(t),o=await Fo(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 ni(e){let t=f(),r=m(t),o=await Lo(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 ri(e){let t=f(),r=m(t),o=await Ko(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 ii(e){let t=f(),r=m(t),o=await Mo(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 si(e){let t=f(),r=m(t),o=await _o(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 ai(e){let t=f(),r=m(t),o=await Go(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 ci(e){let t=f(),r=m(t),o=await Ho(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 di(e){let t=f(),r=m(t),o=await Yo(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 li(e){let t=f(),r=m(t),o=await Fe(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 ui(e){let t=f(),r=m(t),o=await Qo(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 pi(e){let t=f(),r=m(t),o=await Zo(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 ae(e){let t=e.account?.login;return t?Nn(m(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 mi(e){let t=f(),r=m(t),o=ae(t),n;try{n=await kn(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 fi(e){let t=f(),r=m(t),o=await hn(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 gi(e){let t=f(),r=m(t),o=ae(t),n;try{n=await xn(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 yi(e){let t=f(),r=m(t),o=await Cn(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 hi(e){let t=f(),r=m(t),o=ae(t);try{let n=await Dn(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 Xt=v(require("os")),ce=v(require("path"));var T=v(require("fs")),Wt=v(require("os")),w=v(require("path")),j="authoring-cli",M=["claude","codex"];function at(e){let t=[w.resolve(e,"..","skills",j),w.resolve(e,"..","..","skills",j)];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/${j}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function ja(e){let t=[];return T.existsSync(w.join(e,".claude"))&&t.push("claude"),T.existsSync(w.join(e,".codex"))&&t.push("codex"),t}function Te(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=ja(t);return r.length?r:["claude"]}var Ci="# authoring-cli \u2014 SNOMED CT authoring guidance";function Na(e){let t=w.join(e,"SKILL.md"),r=w.join(e,"references","batch-authoring.md");return[Ci,"",`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
|
-
`)
|
|
38
|
-
`)
|
|
39
|
-
|
|
40
|
-
Project-scoped install:
|
|
41
|
-
|
|
42
|
-
Restart your agent, then use /${j}.`),
|
|
43
|
-
Skipped ${s.join(", ")} (no config directory found). Pass --agent ${s.join(",")} to register anyway.`)}var
|
|
44
|
-
Restart your agent to drop /authoring-cli from its command list.`)}function Ka(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 Ei(e){let t=[];for(let r of e){if(r.startsWith("--"))break;t.push(r)}return t}var Qt=[{name:"login",usage:`login [${Ee.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 ${le}; 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)=>Cr({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:()=>xr()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>Ir()},{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=>Ti({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=>Ri({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=>vr({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=>wr({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 into the active --context \u2014 pass --no-select if there is no context or the session is pinned; assigned to you unless overridden)',required:["project","summary"],run:e=>Tr({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 into the active --context unless --no-select \u2014 there is no delete-task command; delete a task in the Authoring Workbench UI instead)",required:["project"],run:e=>Ar({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> --context <name> (selects the task for the named context \u2014 a context is mandatory, so one session's selection can never move another's; commands in that context then target it when --project/--task are omitted. A session pinned with AUTHORING_CLI_TASK cannot select a different task)",required:["project","task"],run:e=>Rr({project:e.project,task:e.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints this session's task and where it comes from \u2014 pin or context; with --project/--task, notes whether they match)",run:e=>$r({project:e.project,task:e.task})},{name:"contexts",usage:"contexts [--remove <name>] (lists the named contexts in this directory and the task each holds, flagging tasks held by more than one; --remove deletes a stale one)",run:e=>Er({remove:e.remove})},{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=>jr({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=>Nr({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=>Dr({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=>Or({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=>Fr({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=>Lr({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=>Kr({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=>_r({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=>Vr({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=>qr({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=>Jr({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=>
|
|
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=>
|
|
47
|
-
`)}async function
|
|
36
|
+
</html>`}async function Ta(e){let t=Date.now();try{return await Yn({userDataDir:U(),host:e.host,cookieName:e.cookieName,cookieUrl:`https://${e.host}/`,timeoutMs:e.timeoutMs},{validateCookie:e.validateCookie})}catch(r){if(!(r instanceof W))throw r;let o=Math.max(e.timeoutMs-(Date.now()-t),5e3);return Gn({...e,timeoutMs:o},{validateCookie:e.validateCookie})}}function pr(e,t={}){let r=e.cookieName??Bt(e.host),o=t.platform??process.platform,n=t.openChrome??((l,u)=>Sa(l,u,o)),i=t.resolveProfile??Ue,s=t.captureCookie??Ta,a=t.quitRunningChrome??va,c=e.timeoutMs??12e4,d=i();return new Promise((l,u)=>{let p=!1,y=h=>{p||(p=!0,k.close(),h())},k=cr.createServer((h,g)=>{if((h.url||"/").split("?")[0]==="/callback"){g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(wa());return}g.writeHead(404),g.end()});k.listen(0,"127.0.0.1",()=>{let g=`http://localhost:${k.address().port}/callback`,I=`${e.imsEndpoint}?serviceReferer=${encodeURIComponent(g)}`;(async()=>{try{await a(U()),Wn(U()),await n(I,d.directoryName);let E=await s({profileDirectory:d.directoryName,host:e.host,cookieName:r,timeoutMs:c,validateCookie:t.validateCookie});y(()=>l({cookie:`${r}=${E}`}))}catch(E){y(()=>u(E))}})()}),k.on("error",h=>y(()=>u(h)))})}var R=S(require("fs")),G=S(require("path")),mr="AUTHORING_CLI_HOME";function Aa(){return G.join(process.cwd(),".authoring-cli")}function Ra(){let e=process.env[mr];return e&&e.trim()!==""?G.resolve(e):null}function ve(){return Ra()??Aa()}function be(e){return G.join(e,"session.json")}function tt(){let e=be(ve());if(!R.existsSync(e))return null;let t=R.readFileSync(e,"utf8");return{...JSON.parse(t),currentTask:null}}function Se(e){let t=ve(),r={...e,currentTask:null,updatedAt:new Date().toISOString()};try{R.mkdirSync(t,{recursive:!0,mode:448}),R.writeFileSync(be(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 ${be(t)} (${n}): the current directory isn't writable. Run authoring-cli from a writable directory, or set ${mr} to an explicit, writable location.`):o}}function fr(){let e=be(ve());R.existsSync(e)&&R.unlinkSync(e)}function we(){return be(ve())}var ie="AUTHORING_CLI_CONTEXT",K="AUTHORING_CLI_TASK",Ze="AUTHORING_CLI_PROJECT",$a=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function et(e){let t=process.env[e];return t&&t.trim()!==""?t.trim():null}function gr(e){if(!$a.test(e))throw new Error(`Invalid context name "${e}": use letters, digits, ".", "_" or "-" (max 64, starting with a letter or digit), e.g. "ANCRJAN22-1069".`);return e}function Y(){let e=et(ie);return e===null?null:gr(e)}function Ea(e){let t=/^(.+)-\d+$/.exec(e);return t?t[1]:null}function Te(){let e=et(K);if(e===null){if(et(Ze)!==null)throw new Error(`${Ze} is set without ${K} \u2014 set both, or neither.`);return null}let t=et(Ze)??Ea(e);if(!t)throw new Error(`${K}=${e} doesn't look like "<PROJECT>-<n>"; also set ${Ze}.`);return{projectKey:t,taskKey:e,branchPath:""}}function Ut(){return G.join(ve(),"contexts")}function Vt(e){return G.join(Ut(),`${gr(e)}.json`)}function yr(e,t){let r;try{r=JSON.parse(R.readFileSync(e,"utf8"))}catch(o){throw new Error(`Context "${t}" is unreadable (${e}): ${o instanceof Error?o.message:String(o)}. Re-run select-task, or delete the file.`)}return{name:t,currentTask:r.currentTask??null,updatedAt:r.updatedAt??null}}function Pa(e){let t=Vt(e);return R.existsSync(t)?yr(t,e):null}function qt(){let e=Ut();return R.existsSync(e)?R.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>yr(G.join(e,t),t.slice(0,-5))).sort((t,r)=>t.name.localeCompare(r.name)):[]}function hr(e){let t=Vt(e);return R.existsSync(t)?(R.unlinkSync(t),!0):!1}function Ht(){let e=Y(),t=Te();return t?{task:t,source:"pin",context:e}:e?{task:Pa(e)?.currentTask??null,source:"context",context:e}:{task:null,source:"none",context:null}}function ja(){return Ht().task}var Na=`Name this session's context with "--context <name>" (or ${ie}=<name>) \u2014 e.g. one per task \u2014 or pin it with ${K}=<TASK-KEY>; or pass --project/--task on every command.`;function X(e){let t=Te();if(t){if(e&&e.taskKey!==t.taskKey)throw new Error(`This session is pinned to ${t.projectKey}/${t.taskKey} (${K}) and can't switch to ${e.projectKey}/${e.taskKey}. Use a separate session (or unset the pin) for the other task.`);if(!e)throw new Error(`This session is pinned to ${t.projectKey}/${t.taskKey} (${K}); a newly created task can't become its selection. Pass --no-select.`);return}if(!Y())throw new Error(`No context to store a task selection in. ${Na}`)}function kr(e){let t=Te();if(t&&e&&e!==t.taskKey)throw new Error(`--task ${e} conflicts with this session's pin ${t.projectKey}/${t.taskKey} (${K}). Refusing to act on a different task from a pinned session; use a separate session for it.`)}function se(e){X(e);let t=Y();if(!t)return;let r=Ut(),o=Vt(t),n=JSON.stringify({currentTask:e,updatedAt:new Date().toISOString()},null,2),i=`${o}.${process.pid}.tmp`;try{R.mkdirSync(r,{recursive:!0,mode:448}),R.writeFileSync(i,n,{mode:384}),R.renameSync(i,o)}catch(s){throw R.rmSync(i,{force:!0}),s}}function Cr(e,t){return qt().filter(r=>r.name!==t&&r.currentTask?.taskKey===e).map(r=>r.name)}function xr(e){return{...e,currentTask:ja()}}async function Da(e){let t=tt();if(!t||t.imsEndpoint!==e)return null;let r=await oe(e,t.cookie).catch(()=>null);return r?{cookie:t.cookie,account:r,currentTask:t.currentTask}:null}async function Oa(e,t,r,o){let n=await Ot(o,t,r).catch(()=>null);if(!n)return null;let i=`${r}=${n}`,s=await oe(e,i).catch(()=>null);return s?{cookie:i,account:s}:null}function ot(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 nt(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 Ir(e){let t=e.environment?oo(e.environment):ue;if(!t){console.error(`Unknown environment: ${e.environment}
|
|
37
|
+
Expected one of: ${Ee.join(", ")} (or pass --ims-endpoint/--terminology-server-endpoint/--authoring-services-endpoint explicitly).`),process.exitCode=1;return}let r=z[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||Bt(s),d=t===ue&&!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}`,I=await oe(o,g).catch(()=>null);if(!I){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}Se({cookie:g,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:I,currentTask:null}),console.log(`${ot(I)} (from --cookie \u2014 no browser opened.)`),nt(l),console.log(` Session: ${we()}`);return}let u=await Da(o);if(u){Se({cookie:u.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:u.account,currentTask:null}),console.log(`${ot(u.account)} (reused the already-stored session \u2014 no Chrome involved at all.)`),nt(l),console.log(` Session: ${we()}`);return}let p=Ue(),y=await Oa(o,s,c,p.directoryName);if(y){Se({cookie:y.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:y.account,currentTask:null}),console.log(`${ot(y.account)} (reused an existing Chrome session in profile "${p.directoryName}" \u2014 no browser opened.)`),nt(l),console.log(` Session: ${we()}`);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 pr({imsEndpoint:o,host:s,cookieName:c},{validateCookie:g=>oe(o,`${c}=${g}`).then(I=>I!==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 oe(o,k.cookie).catch(()=>null);Se({cookie:k.cookie,imsEndpoint:o,terminologyServerEndpoint:n,authoringServicesEndpoint:i,account:h,currentTask:null}),console.log(ot(h)),nt(l),console.log(` Session: ${we()}`)}async function br(){fr(),console.log("Signed out.")}var it=S(require("fs")),rt=S(require("path"));async function vr(){let e=[rt.join(__dirname,"../../HELP.md"),rt.join(__dirname,"../HELP.md"),rt.join(process.cwd(),"HELP.md")];for(let t of e)try{if(it.existsSync(t)){let r=it.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 f(){let e;try{e=tt(),e&&(e=xr(e))}catch(t){console.error(t instanceof Error?t.message:String(t)),process.exit(1)}return e||(console.error('Not signed in. Run "login" first.'),process.exit(1)),e}function Gt(e){let t=e.account;return t?.login??t?.username}function m(e){return{cookie:e.cookie,terminologyServerEndpoint:e.terminologyServerEndpoint,authoringServicesEndpoint:e.authoringServicesEndpoint,imsEndpoint:e.imsEndpoint,currentUsername:Gt(e),onLog:t=>console.error(t)}}function Sr(e){return e.projectKey??e.key??"?"}async function wr(e){let t=f(),r=m(t),o=await vn(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=>Sr(i).length))+1;for(let i of o){let s=i.title??"";console.log(`${Sr(i).padEnd(n)}${s?`"${s}"`:""}`)}}function st(e){return e.taskKey??e.key??"?"}function Tr(e){return e.assignee?.displayName??e.assignee?.username??"unassigned"}function Fa(e){return e.projectKey||st(e).split("-")[0]||"?"}function Jt(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 Wt(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=f(),r=m(t),o=e.mine||!e.project,n=o?await wn(r):await Sn(r,e.project);if(o&&e.project){let l=e.project.toLowerCase();n=n.filter(u=>(u.projectKey??"").toLowerCase()===l||st(u).toLowerCase().startsWith(`${l}-`))}if(e.status){let l=e.status.trim().toLowerCase();n=n.filter(u=>(u.status??"").toLowerCase()===l)}let i=Jt(n,Fa),s=Jt(n,Tr),a=Jt(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&&Wt("By project",i),!o&&s.length>1&&Wt("By assignee",s),a.length>1&&Wt("By status",a);return}let d=Math.max(...n.map(l=>st(l).length))+1;for(let l of n){let u=l.summary??l.title??"",p=l.status?` status=${l.status}`:"",y=o?"":` [${Tr(l)}]`;console.log(`${st(l).padEnd(d)}${u?`"${u}"`:""}${p}${y}`)}}async function Rr(e){e.noSelect||X();let t=f(),r=m(t),o=Gt(t),n=e.unassigned?void 0:e.assignee||o,i=await Tn(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 ee(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}se({projectKey:e.project,taskKey:a,branchPath:c}),e.json||console.log(`\u2713 Current task set to ${e.project}/${a}`)}}async function $r(e){let t=f(),r=m(t);if(!e.task){let i=await An(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}e.noSelect||X({projectKey:e.project,taskKey:e.task});let o=await Rn(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 ee(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||(se({projectKey:e.project,taskKey:e.task,branchPath:n}),console.log(`\u2713 Current task set to ${e.project}/${e.task}`))}async function Er(e){X({projectKey:e.project,taskKey:e.task});let t=f(),r=m(t),o=await _(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 ee(r,o.branchPath);if(!n.ok){console.error(`Could not prepare branch for ${e.project}/${e.task}: ${n.error}`),process.exitCode=1;return}se({projectKey:e.project,taskKey:e.task,branchPath:o.branchPath});let i=Y();console.log(`\u2713 Current task set to ${e.project}/${e.task} (${o.branchPath})${i?` in context "${i}"`:""}`);let s=Cr(e.task,i);s.length&&console.error(` Warning: context(s) ${s.map(a=>`"${a}"`).join(", ")} also hold ${e.task} \u2014 concurrent writes to one branch contend for its lock.`),n.created&&console.log(` created branch ${o.branchPath}`)}async function Pr(e){let t=f(),r=Ht();if(!r.task){r.source==="context"?console.log(`Context "${r.context}" has no task selected yet. Run "select-task --context ${r.context} --project <projectKey> --task <taskKey>".`):console.log(`No task context. Name this session with "--context <name>" (or ${ie}), pin it with ${K}, or pass --project/--task explicitly to any command.`);return}let{projectKey:o,taskKey:n}=r.task,i=r.task.branchPath||await ut(m(t),o,n)||"(branch not resolved)",s=r.source==="pin"?`pinned via ${K}`:`context "${r.context}"`;console.log(`Current task: ${o}/${n} (${i}) [${s}]`),(e.project||e.task)&&((!e.project||e.project===o)&&(!e.task||e.task===n)||console.log(`Note: --project/--task (${e.project??"*"}/${e.task??"*"}) do not match the currently selected task.`))}async function jr(e){if(e.remove!==void 0){if(!e.remove){console.error("--remove needs a context name."),process.exitCode=1;return}console.log(hr(e.remove)?`\u2713 Removed context "${e.remove}".`:`No context named "${e.remove}".`);return}let t=qt(),r=Y(),o=Te();t.length===0&&console.log("No contexts yet. Create one with: select-task --context <name> --project <projectKey> --task <taskKey>");let n=new Map;for(let i of t)i.currentTask&&n.set(i.currentTask.taskKey,[...n.get(i.currentTask.taskKey)??[],i.name]);for(let i of t){let s=i.name===r?"*":" ",a=i.currentTask,c=a&&(n.get(a.taskKey)?.length??0)>1?" (same task as another context \u2014 branch-lock contention possible)":"";console.log(`${s} ${i.name}: ${a?`${a.projectKey}/${a.taskKey} (${a.branchPath})`:"no task selected"}${i.updatedAt?` [${i.updatedAt}]`:""}${c}`)}o?console.log(`This session is pinned to ${o.projectKey}/${o.taskKey}.`):r&&console.log("(* = this session's context)")}async function Nr(e){let t=f(),r=m(t),o=await po(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 Dr(e){let t=f(),r=m(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 on(r,o,t.currentTask):await Ne(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 Or(e){let t=f(),r=m(t),o=await je(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 Fr(e){let t=f(),r=m(t),o=await fo(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 Lr(e){let t=f(),r=m(t),o=await _e(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 _r(e){let t=f(),r=m(t),o=e.checkStatedParentsDefinitionStatus?await ln(r,{projectKey:e.project,taskKey:e.task},t.currentTask):await H(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=f(),r=m(t),o=await un(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 Mr(e){let t=f(),r=m(t),o=await pn(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 Br(e){let t=f(),r=m(t),o=await Ro(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 Ur(e){let t=f(),r=m(t),o=await $o(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 Vr(e){let t=f(),r=m(t),o=await Qo(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 qr(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=f(),o=m(r),n=await Zo(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 Hr(e){let t=f(),r=m(t),o=await jo(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 Gr(e){let t=f(),r=m(t),o=await No(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 Jr(e){let t=f(),r=m(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 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}`),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 Fo(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 Wr(e){let t=f(),r=m(t),o=await Po(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 Yr(e){let t=f(),r=m(t),o=await Eo(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 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=f(),o=m(r),n=await qo(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 zr(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=f(),o=m(r),n=await Ho(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 Qr(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=f(),o=m(r),n=await Jo(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 Zr(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=f(),o=m(r),n=await Go(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 ei(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=f(),r=m(t),o=await sn(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 ti(e){let t=f(),r=m(t),o=await an(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 oi(e){let t=f(),r=m(t),o=await cn(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 ni(e){let t=f(),r=m(t),o=await nn(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 ri(e){let t=f(),r=m(t),o=await _o(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 ii(e){let t=f(),r=m(t),o=await Ko(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 si(e){let t=f(),r=m(t),o=await Mo(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 ai(e){let t=f(),r=m(t),o=await Uo(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 ci(e){let t=f(),r=m(t),o=await Bo(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 di(e){let t=f(),r=m(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){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 li(e){let t=f(),r=m(t),o=await Yo(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 ui(e){let t=f(),r=m(t),o=await zo(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 pi(e){let t=f(),r=m(t),o=await Fe(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 mi(e){let t=f(),r=m(t),o=await en(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 fi(e){let t=f(),r=m(t),o=await tn(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 ae(e){let t=e.account?.login;return t?On(m(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 gi(e){let t=f(),r=m(t),o=ae(t),n;try{n=await xn(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 yi(e){let t=f(),r=m(t),o=await Cn(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 hi(e){let t=f(),r=m(t),o=ae(t),n;try{n=await bn(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 ki(e){let t=f(),r=m(t),o=await In(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 Ci(e){let t=f(),r=m(t),o=ae(t);try{let n=await Fn(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 Qt=S(require("os")),de=S(require("path"));var T=S(require("fs")),Yt=S(require("os")),v=S(require("path")),j="authoring-cli",Xt=".installed-by-authoring-cli.json",Ii=new Set([".DS_Store"]),M=["claude","codex","agents","dsh"];function zt(e,t){let r=process.env.CODEX_HOME;return t!==void 0?v.resolve(t):r!==void 0&&r.trim().length>0?v.resolve(r):v.join(e,".codex")}function La(e,t){return t??process.env.DSH_AGENTS_HOME??v.join(e,".agents")}function bi(e,t){let r=process.env.DSH_HOME,o=t??(r!==void 0&&r.trim().length>0?r:void 0);return o===void 0?v.join(e,".dsh"):o==="~"?e:o.startsWith("~/")||o.startsWith("~\\")?v.join(e,o.slice(2)):v.resolve(o)}function ct(e){let t=[v.resolve(e,"..","skills",j),v.resolve(e,"..","..","skills",j)];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/${j}/SKILL.md in: ${t.join(", ")}). This means the installed package is incomplete \u2014 reinstall with "npm install -g authoring-cli".`)}function vi(e){try{let t=JSON.parse(T.readFileSync(v.resolve(e,"..","..","package.json"),"utf8"));return typeof t.version=="string"?t.version:void 0}catch{return}}function _a(e,t={}){let r=[];return T.existsSync(v.join(e,".claude"))&&r.push("claude"),T.existsSync(zt(e,t.codexHomeDir))&&r.push("codex"),T.existsSync(bi(e,t.dshHomeDir))&&r.push("dsh"),r}function Ae(e,t,r={}){if(e==="all")return[...M];if(e){let n=e.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),i=n.filter(s=>!M.includes(s));if(i.length)throw new Error(`Unknown --agent value(s): ${i.join(", ")}. Supported: ${M.join(", ")}, all.`);return n}let o=_a(t,r);return o.length?o:["claude"]}var Ka="# authoring-cli \u2014 SNOMED CT authoring guidance";function at(e){try{return v.resolve(v.dirname(e),T.readlinkSync(e))}catch{return null}}function ce(e){try{return T.lstatSync(e)}catch{return null}}function Si(e){let t=at(e);return t?T.existsSync(t)?`an existing symlink -> ${t}`:`a dangling symlink -> ${t}`:ce(e)?.isDirectory()?"an existing directory":"an existing file"}function wi(e){let t=at(e);return t!==null&&v.basename(t)===j&&v.basename(v.dirname(t))==="skills"}function Ma(e){if(!ce(e)?.isFile())return!1;try{return T.readFileSync(e,"utf8").startsWith(Ka)}catch{return!1}}function Ti(e){let t=ce(e);return t!==null&&t.isDirectory()&&!t.isSymbolicLink()&&T.existsSync(v.join(e,Xt))}function xi(e){return T.readdirSync(e,{recursive:!0,withFileTypes:!0}).filter(t=>t.isFile()&&t.name!==Xt&&!Ii.has(t.name)).map(t=>v.relative(e,v.join(t.parentPath,t.name))).sort()}function Ai(e,t){if(!t||!T.existsSync(t)||!ce(e)?.isDirectory())return!1;try{let r=xi(t);return r.join(`
|
|
38
|
+
`)!==xi(e).join(`
|
|
39
|
+
`)?!1:r.every(o=>T.readFileSync(v.join(e,o)).equals(T.readFileSync(v.join(t,o))))}catch{return!1}}function Ba(e,t){T.mkdirSync(v.dirname(t),{recursive:!0}),T.cpSync(e,t,{recursive:!0,filter:o=>!Ii.has(v.basename(o))});let r={installer:"authoring-cli",version:vi(e)??null,source:e,installedAt:new Date().toISOString(),note:"This directory is a copy managed by `authoring-cli install-skill`; re-run it to refresh, or `authoring-cli uninstall-skill` to remove."};T.writeFileSync(v.join(t,Xt),JSON.stringify(r,null,2)+`
|
|
40
|
+
`,"utf8")}function Ri(e,t,r,o){switch(e){case"claude":return v.join(t.project?o:r,".claude","skills");case"codex":return v.join(zt(r,t.codexHomeDir),"skills");case"agents":return v.join(La(r,t.agentsHomeDir),"skills");case"dsh":return v.join(bi(r,t.dshHomeDir),"skills")}}function Ua(e,t){return v.join(zt(t,e.codexHomeDir),"prompts",`${j}.md`)}function $i(e,t){let r=Ua(e,t);return Ma(r)?(T.rmSync(r,{force:!0}),`removed legacy pointer prompt ${r}`):null}function Va(e,t,r){let o=v.join(t,j),n=r.shippedSkillDir,i=vi(n),s=`copied from ${n}${i?` (v${i})`:""}`,a="installed";if(ce(o)){let c=Ai(o,n);if(Ti(o)){if(c)return{agent:e,path:o,status:"already-current",kind:"copy",detail:s};a="updated"}else if(wi(o)||c)a="replaced";else if(r.force)a="replaced";else return{agent:e,path:o,status:"blocked",kind:"copy",detail:Si(o)};T.rmSync(o,{recursive:!0,force:!0})}return Ba(n,o),{agent:e,path:o,status:a,kind:"copy",detail:s}}function Ei(e){let t=e.homeDir??Yt.homedir(),r=e.cwd??process.cwd();return(e.agents??Ae(void 0,t,e)).map(n=>{let i=Va(n,Ri(n,e,t,r),e);if(n==="codex"&&i.status!=="blocked"){let s=$i(e,t);s&&(i.detail=i.detail?`${i.detail}; ${s}`:s)}return i})}function Pi(e){let t=e.homeDir??Yt.homedir(),r=e.cwd??process.cwd();return e.agents.map(o=>{let n=v.join(Ri(o,e,t,r),j),i=o==="codex"?$i(e,t):null;if(!ce(n))return{agent:o,path:n,status:"not-registered",...i?{detail:i}:{}};if(!(Ti(n)||wi(n)||Ai(n,e.shippedSkillDir))&&!e.force)return{agent:o,path:n,status:"left-alone",detail:`${Si(n)} \u2014 not something this CLI created; re-run with --force to delete it anyway`};let a=at(n)?`symlink -> ${at(n)}`:"installed copy";return T.rmSync(n,{recursive:!0,force:!0}),{agent:o,path:n,status:"removed",detail:i?`${a}; ${i}`:a}})}function qa(e){let t=Qt.homedir();return e===t||e.startsWith(t+de.sep)?de.join("~",de.relative(t,e)):e}function Ha(e){let t=qa(e.path);switch(e.status){case"installed":case"updated":case"replaced":return`${t} (${e.status} \u2014 ${e.detail})`;case"already-current":return`${t} (already up to date \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 ji(e){let t=ct(__dirname),r=Ae(e.agent,Qt.homedir());e.project&&!r.includes("claude")&&console.log("Note: --project only applies to Claude Code; the other targets are always user-level.");let o=Ei({agents:r,project:e.project,force:e.force,shippedSkillDir:t}),n=o.filter(a=>a.status==="installed"||a.status==="updated"||a.status==="replaced"),i=o.filter(a=>a.status==="blocked");console.log(n.length?`Installed skill '${j}' for:`:i.length?`Could not install skill '${j}':`:`Skill '${j}' is already registered:`);for(let a of o)console.log(` ${a.agent.padEnd(6)} ${Ha(a)}`);if(e.project&&r.includes("claude")&&console.log(`
|
|
41
|
+
Project-scoped install: .claude/skills now holds a copy of the skill \u2014 commit it if you want teammates
|
|
42
|
+
to get the guidance, and re-run install-skill after upgrading authoring-cli to refresh it.`),i.length){process.exitCode=1;return}n.length&&(console.log(`
|
|
43
|
+
Restart your agent, then use /${j}.`),console.log('Each target is a copy: re-run "authoring-cli install-skill" after "npm update -g authoring-cli" to refresh it.'),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(`
|
|
44
|
+
Skipped ${s.join(", ")} (no config directory found; "agents" is never auto-selected). Pass --agent ${s.join(",")} to register anyway.`)}var Zt=S(require("os")),le=S(require("path"));function Ga(e){let t=Zt.homedir();return e===t||e.startsWith(t+le.sep)?le.join("~",le.relative(t,e)):e}function Ja(e){let t=Ga(e.path);switch(e.status){case"removed":return`${t} (removed${e.detail?` \u2014 ${e.detail}`:""})`;case"not-registered":return`${t} (nothing registered here)`;case"left-alone":return`${t} KEPT \u2014 ${e.detail}`}}async function Ni(e){let t=e.agent?Ae(e.agent,Zt.homedir()):[...M],r;try{r=ct(__dirname)}catch{r=void 0}let o=Pi({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 '${j}' registration for:`:i.length?`Left every registration of '${j}' in place:`:`No '${j}' registration found:`);for(let s of o)console.log(` ${s.agent.padEnd(6)} ${Ja(s)}`);if(i.length){process.exitCode=1;return}n.length&&console.log(`
|
|
45
|
+
Restart your agent to drop /authoring-cli from its command list.`)}function Wa(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 eo=[{name:"login",usage:`login [${Ee.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 ${ue}; 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)=>Ir({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:()=>br()},{name:"help",usage:"help (display comprehensive help guide)",run:()=>vr()},{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=>ji({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=>Ni({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=>wr({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 into the active --context \u2014 pass --no-select if there is no context or the session is pinned; assigned to you unless overridden)',required:["project","summary"],run:e=>Rr({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 into the active --context unless --no-select \u2014 there is no delete-task command; delete a task in the Authoring Workbench UI instead)",required:["project"],run:e=>$r({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> --context <name> (selects the task for the named context \u2014 a context is mandatory, so one session's selection can never move another's; commands in that context then target it when --project/--task are omitted. A session pinned with AUTHORING_CLI_TASK cannot select a different task)",required:["project","task"],run:e=>Er({project:e.project,task:e.task})},{name:"current-task",usage:"current-task [--project <projectKey> --task <taskKey>] (prints this session's task and where it comes from \u2014 pin or context; with --project/--task, notes whether they match)",run:e=>Pr({project:e.project,task:e.task})},{name:"contexts",usage:"contexts [--remove <name>] (lists the named contexts in this directory and the task each holds, flagging tasks held by more than one; --remove deletes a stale one)",run:e=>jr({remove:e.remove})},{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=>Dr({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=>Or({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=>Fr({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=>Lr({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=>_r({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=>Mr({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=>Br({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=>Hr({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)
|
|
46
|
+
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=>Jr({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=>Ur({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=>Vr({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=>qr({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=>Wr({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=>Yr({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=>Xr({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=>Zr({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=>Qr({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=>zr({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=>ei({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=>ti({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=>oi({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=>ni({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=>ri({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=>ii({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)
|
|
47
|
+
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=>si({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=>ai({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=>ci({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=>di({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=>li({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=>ui({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=>pi({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=>mi({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=>fi({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=>gi({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=>yi({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=>hi({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=>ki({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=>Ci({project:e.project,task:e.task,entityType:e["entity-type"],timeout:e.timeout})}];function Fi(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 Di(){return["Usage: authoring-cli <command> [options]","","Commands:",...eo.map(e=>` ${Fi(e)}`),"",'Run "login" first to sign in.',"Every session must say which task it works on, so tasks never get mixed up:",' --context <name> (or AUTHORING_CLI_CONTEXT) \u2014 a named selection; "select-task" in one context never moves another'," AUTHORING_CLI_TASK=<TASK-KEY> \u2014 pins the process to one task; a different --task is refused"," --project/--task on a command \u2014 targets that task for that call only","With none of these, no task is implied and task-targeting commands fail."].join(`
|
|
48
|
+
`)}async function Li(e=process.argv){let[,,t,...r]=e,o=Wa(r),n=Oi(r);if(!t){console.log(Di());return}let i=eo.find(a=>a.name===t||a.aliases?.includes(t));if(!i){console.error(`Unknown command: ${t}
|
|
48
49
|
|
|
49
|
-
${
|
|
50
|
+
${Di()}`),process.exitCode=1;return}if("context"in o){if(!o.context){console.error("--context needs a name, e.g. --context ANCRJAN22-1069."),process.exitCode=1;return}process.env[ie]=o.context}if(i.name!=="recover-task")try{kr(o.task)}catch(a){console.error(a instanceof Error?a.message:String(a)),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(", ")}
|
|
50
51
|
|
|
51
|
-
Usage: ${
|
|
52
|
+
Usage: ${Fi(i)}`),process.exitCode=1;return}await i.run(o,n)}require.main===module&&Li().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});0&&(module.exports={COMMANDS,main,parsePositionals});
|