nemar-cli 0.10.40-dev.4833 → 0.10.40-dev.4861
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/git-annex-remote-nemar.js +1 -1
- package/dist/index.js +3 -3
- package/package.json +1 -1
|
@@ -23,7 +23,7 @@ ${t}`,QM,ZM,eL=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=JM.bind(null,n,
|
|
|
23
23
|
`)}var Vl=!1;var{spawn:nV}=globalThis.Bun;function zl(e,t=[]){let r=e.replace(sV,'("$1","<redacted>")');for(let n of t)if(n.length>=oV)r=r.split(n).join("<redacted>");return r}function iV(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],r=new Set;for(let n of[process.env,e??{}])for(let s of t){let o=n[s];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function hE(e,t){let r=e.getReader(),n=new TextDecoder,s="";while(!0){let{done:o,value:a}=await r.read();if(o)break;if(a.byteLength===0)continue;t(),s+=n.decode(a,{stream:!0})}return s+n.decode()}async function gE(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete r[y];let n=nV({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),s=!1,o,a,i=performance.now(),c=()=>{if(a!==void 0)clearTimeout(a),a=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),a=setTimeout(()=>{a=void 0;try{t.onInactivityWarning?.(performance.now()-i)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??aV)};if(u(),t.timeout)o=setTimeout(()=>{s=!0,c(),n.kill()},t.timeout);let l=cc()?[...iV(r),...t.redact??[]]:[];if(cc()){let y=t.cwd?` (cwd=${t.cwd})`:"";Ls(Pt.dim(zl(`$ ${e.join(" ")}${y}`,l)))}let d=()=>{i=performance.now(),u()},m,f,p,h=n.exited.then((y)=>(c(),y));try{[m,f,p]=await Promise.all([hE(n.stdout,d),hE(n.stderr,d),h])}finally{if(c(),o)clearTimeout(o)}if(cc()){if(t.sensitiveOutput)Ls(Pt.dim("[sensitive subprocess output suppressed]"));else{if(m.trim())Ls(Pt.dim(zl(m.trimEnd(),l)));if(f.trim())Ls(Pt.yellow(zl(f.trimEnd(),l)))}Ls(Pt.dim(`(exit ${p})`))}if(s)return{stdout:m,stderr:f||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:p??1,timedOut:!0};return{stdout:m,stderr:f,exitCode:p,timedOut:!1}}var sV,oV=8,aV=120000;var yE=L(()=>{Fl();sV=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function uV(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function vE(e,t=uV()){return e.installInstructions[t]}function lV(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function fV(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:dV}async function bE(e){try{let{exitCode:t,stdout:r,timedOut:n}=await gE(e.cmd,{timeout:fV()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:lV(r)}}catch(t){let r=t instanceof Error?t.message:String(t);if(!r.includes("ENOENT")&&!r.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${r}`);return{available:!1}}}async function Gl(){let e=Object.entries(_E);return Promise.all(e.map(async([t,r])=>{let{available:n,version:s,timedOut:o}=await bE(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:s,timedOut:o,installInstruction:vE(r)}}))}async function bB(){let t=(await Gl()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
|
|
24
24
|
Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let r of t)console.warn(` - ${r.name} (${r.purpose})`),console.warn(` Install: ${r.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function wB(e){let r=cV[e].map((a)=>_E[a]).filter(Boolean),n=await Promise.all(r.map(async(a)=>{let i=await bE(a);return{check:a,available:i.available,timedOut:i.timedOut}}));for(let a of n)if(a.timedOut&&a.check.required)console.warn(`Warning: ${a.check.name} did not respond to a version check in time; continuing anyway.`);let s=n.filter((a)=>!a.available&&!a.timedOut&&a.check.required).map((a)=>({tool:a.check.name,installInstruction:vE(a.check)}));if(s.length===0)return;let o=[`
|
|
25
25
|
Missing required tools:`];for(let a of s)o.push(` ${a.tool} not installed`),o.push(` Install: ${a.installInstruction}`);throw Error(o.join(`
|
|
26
|
-
`))}var _E,cV,dV=4000;var wE=L(()=>{yE();_E={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},cV={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var EE;var $E=L(()=>{EE={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.40-dev.
|
|
26
|
+
`))}var _E,cV,dV=4000;var wE=L(()=>{yE();_E={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},cV={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var EE;var $E=L(()=>{EE={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.40-dev.4861",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var uc;var Kl=L(()=>{$E();uc=EE.version});import{mkdirSync as mV,readdirSync as hV,unlinkSync as gV,writeFileSync as yV}from"fs";import{join as Hl}from"path";function PB(){Us=!0}function fc(){return Us}function CB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function IB(e){TE=e,mr(`Step: ${e}`)}function jB(){RE=!0}function qB(){return RE}function DB(){if(kE)return;Wl=!0}function MB(){Wl=!1,kE=!0}function LB(){return Wl}function mr(e){if(Us)process.stderr.write(`[debug] ${e}
|
|
27
27
|
`)}function wV(e){let t={};for(let[r,n]of Object.entries(e))t[r]=bV.has(r.toLowerCase())?"[REDACTED]":n;return t}function OE(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Bl(e,t,r=0){if(r>EV)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>Bl(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[s,o]of Object.entries(t))n[s]=Bl(s,o,r+1);return n}if(typeof t==="string"){if($V.test(e))return"[REDACTED]";return t.replace(AE,OE)}return t}function Yl(e){return e.replace(SV,"Bearer [REDACTED]").replace(xV,"[REDACTED_AWS_KEY]").replace(RV,"$1[REDACTED]").replace(kV,"$1$2=[REDACTED]").replace(AE,OE)}function TV(e){return Yl(e)}function SE(e,t=vV){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(Bl("",n))}catch{}if(r=Yl(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function pc(e){if(!Us)return;let t=TV(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?wV(e.requestHeaders):void 0,requestBody:SE(e.requestBody),responseBody:SE(e.responseBody)};dc.push(r),mr(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=fr(r);dc.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),mr(`redaction failed for ${e.method} ${t}: ${n}`)}}async function AV(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${uc}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${fr(t)})`)}e.push(""),e.push("Active account:");try{let t=vn();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${fr(t)})`)}e.push(""),e.push("External tools:");try{let t=await Gl();for(let r of t){let n=r.available?r.version??"installed":r.timedOut?"(timed out)":"not installed";e.push(` ${r.name}: ${n}`)}}catch(t){e.push(` (could not probe external tools: ${fr(t)})`)}return e}async function OV(){return(await AV()).join(`
|
|
28
28
|
`)}async function UB(){if(!Us||lc!==void 0)return;try{lc=await OV()}catch(e){let t=fr(e);lc=`(could not build environment report: ${t})`,mr(`environment snapshot failed: ${t}`)}}function NE(e){if(xE.has(e))return{flag:e};for(let t of xE){if(!e.startsWith(t)||e.length<=t.length)continue;if(t.length===2)return{flag:t,kind:"short-attached"};if(e[t.length]==="=")return{flag:t,kind:"long-eq"}}return null}function NV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=NE(n);if(!s){t.push(n);continue}if(s.kind==="long-eq")t.push(`${s.flag}=[REDACTED]`);else if(s.kind==="short-attached")t.push(`${s.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function PV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=NE(n);if(!s){t.push(n);continue}if(!s.kind&&r+1<e.length)r++}return t}function CV(e){let t=[];for(let n of PV(e)){if(n.startsWith("-"))continue;if(t.push(n),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function IV(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${Yl(NV(e).join(" "))}`),r.push(""),r.push(lc??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),dc.length===0)r.push(" (none)");else dc.forEach((n,s)=>{if(r.push(` [${s+1}] ${n.method} ${n.url} -> ${n.status??"ERROR"} (${n.durationMs}ms)`),n.error)r.push(` Error: ${n.error}`);if(n.note)r.push(` Note: ${n.note}`);if(n.requestHeaders)r.push(` Request headers: ${JSON.stringify(n.requestHeaders)}`);if(n.requestBody)r.push(` Request body: ${n.requestBody}`);if(n.responseBody)r.push(` Response body: ${n.responseBody}`)});return r.push(""),r.push(`Failing step: ${TE??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
|
|
29
29
|
`)}
|
package/dist/index.js
CHANGED
|
@@ -100,7 +100,7 @@ ${t}`,Unt,qnt,Bnt=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=Lnt.bind(nul
|
|
|
100
100
|
`)}var Wj=!1;var{spawn:dSt}=globalThis.Bun;function Xf(e,t=[]){let n=e.replace(pSt,'("$1","<redacted>")');for(let r of t)if(r.length>=fSt)n=n.split(r).join("<redacted>");return n}function rD(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],n=new Set;for(let r of[process.env,e??{}])for(let o of t){let s=r[o];if(typeof s==="string"&&s.length>0)n.add(s)}return[...n]}async function Qbe(e,t){let n=e.getReader(),r=new TextDecoder,o="";while(!0){let{done:s,value:i}=await n.read();if(s)break;if(i.byteLength===0)continue;t(),o+=r.decode(i,{stream:!0})}return o+r.decode()}async function T(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=dSt({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:n}),o=!1,s,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},l=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??mSt)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=Ay()?[...rD(n),...t.redact??[]]:[];if(Ay()){let y=t.cwd?` (cwd=${t.cwd})`:"";mp(u.dim(Xf(`$ ${e.join(" ")}${y}`,d)))}let p=()=>{a=performance.now(),l()},f,m,h,g=r.exited.then((y)=>(c(),y));try{[f,m,h]=await Promise.all([Qbe(r.stdout,p),Qbe(r.stderr,p),g])}finally{if(c(),s)clearTimeout(s)}if(Ay()){if(t.sensitiveOutput)mp(u.dim("[sensitive subprocess output suppressed]"));else{if(f.trim())mp(u.dim(Xf(f.trimEnd(),d)));if(m.trim())mp(u.yellow(Xf(m.trimEnd(),d)))}mp(u.dim(`(exit ${h})`))}if(o)return{stdout:f,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:f,stderr:m,exitCode:h,timedOut:!1}}var pSt,fSt=8,mSt=120000;var Vt=z(()=>{Le();pSt=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function gSt(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function t0e(e,t=gSt()){return e.installInstructions[t]}function ySt(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function wSt(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:bSt}async function n0e(e){try{let{exitCode:t,stdout:n,timedOut:r}=await T(e.cmd,{timeout:wSt()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:ySt(n)}}catch(t){let n=t instanceof Error?t.message:String(t);if(!n.includes("ENOENT")&&!n.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${n}`);return{available:!1}}}async function j_(){let e=Object.entries(e0e);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await n0e(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:t0e(n)}}))}async function r0e(){let t=(await j_()).filter((n)=>n.required&&!n.available);if(t.length===0)return[];console.warn(`
|
|
101
101
|
Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let n of t)console.warn(` - ${n.name} (${n.purpose})`),console.warn(` Install: ${n.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function Zf(e){let n=hSt[e].map((i)=>e0e[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await n0e(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of r)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let o=r.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:t0e(i.check)}));if(o.length===0)return;let s=[`
|
|
102
102
|
Missing required tools:`];for(let i of o)s.push(` ${i.tool} not installed`),s.push(` Install: ${i.installInstruction}`);throw Error(s.join(`
|
|
103
|
-
`))}var e0e,hSt,bSt=4000;var L_=z(()=>{Vt();e0e={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},hSt={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var s0e;var o0e=z(()=>{s0e={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.40-dev.
|
|
103
|
+
`))}var e0e,hSt,bSt=4000;var L_=z(()=>{Vt();e0e={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},hSt={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var s0e;var o0e=z(()=>{s0e={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.40-dev.4861",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ei;var Qf=z(()=>{o0e();ei=s0e.version});import{mkdirSync as xSt,readdirSync as vSt,unlinkSync as ESt,writeFileSync as SSt}from"fs";import{join as Kj}from"path";function d0e(){Oy=!0}function ou(){return Oy}function p0e(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function q_(e){u0e=e,Ln(`Step: ${e}`)}function ns(){c0e=!0}function f0e(){return c0e}function ce(){if(l0e)return;Yj=!0}function hp(){Yj=!1,l0e=!0}function m0e(){return Yj}function Ln(e){if(Oy)process.stderr.write(`[debug] ${e}
|
|
104
104
|
`)}function DSt(e){let t={};for(let[n,r]of Object.entries(e))t[n]=$St.has(n.toLowerCase())?"[REDACTED]":r;return t}function g0e(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Jj(e,t,n=0){if(n>ASt)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>Jj(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=Jj(o,s,n+1);return r}if(typeof t==="string"){if(CSt.test(e))return"[REDACTED]";return t.replace(h0e,g0e)}return t}function Xj(e){return e.replace(OSt,"Bearer [REDACTED]").replace(TSt,"[REDACTED_AWS_KEY]").replace(PSt,"$1[REDACTED]").replace(NSt,"$1$2=[REDACTED]").replace(h0e,g0e)}function ISt(e){return Xj(e)}function i0e(e,t=RSt){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(Jj("",r))}catch{}if(n=Xj(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function iD(e){if(!Oy)return;let t=ISt(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?DSt(e.requestHeaders):void 0,requestBody:i0e(e.requestBody),responseBody:i0e(e.responseBody)};sD.push(n),Ln(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=W(n);sD.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),Ln(`redaction failed for ${e.method} ${t}: ${r}`)}}async function FSt(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${ei}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${W(t)})`)}e.push(""),e.push("Active account:");try{let t=Wt();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${W(t)})`)}e.push(""),e.push("External tools:");try{let t=await j_();for(let n of t){let r=n.available?n.version??"installed":n.timedOut?"(timed out)":"not installed";e.push(` ${n.name}: ${r}`)}}catch(t){e.push(` (could not probe external tools: ${W(t)})`)}return e}async function Zj(){return(await FSt()).join(`
|
|
105
105
|
`)}async function y0e(){if(!Oy||oD!==void 0)return;try{oD=await Zj()}catch(e){let t=W(e);oD=`(could not build environment report: ${t})`,Ln(`environment snapshot failed: ${t}`)}}function b0e(e){if(a0e.has(e))return{flag:e};for(let t of a0e){if(!e.startsWith(t)||e.length<=t.length)continue;if(t.length===2)return{flag:t,kind:"short-attached"};if(e[t.length]==="=")return{flag:t,kind:"long-eq"}}return null}function MSt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=b0e(r);if(!o){t.push(r);continue}if(o.kind==="long-eq")t.push(`${o.flag}=[REDACTED]`);else if(o.kind==="short-attached")t.push(`${o.flag}[REDACTED]`);else if(t.push(r),n+1<e.length)t.push("[REDACTED]"),n++}return t}function jSt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=b0e(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function LSt(e){let t=[];for(let r of jSt(e)){if(r.startsWith("-"))continue;if(t.push(r),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function USt(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${Xj(MSt(e).join(" "))}`),n.push(""),n.push(oD??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),sD.length===0)n.push(" (none)");else sD.forEach((r,o)=>{if(n.push(` [${o+1}] ${r.method} ${r.url} -> ${r.status??"ERROR"} (${r.durationMs}ms)`),r.error)n.push(` Error: ${r.error}`);if(r.note)n.push(` Note: ${r.note}`);if(r.requestHeaders)n.push(` Request headers: ${JSON.stringify(r.requestHeaders)}`);if(r.requestBody)n.push(` Request body: ${r.requestBody}`);if(r.responseBody)n.push(` Response body: ${r.responseBody}`)});return n.push(""),n.push(`Failing step: ${u0e??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
|
|
106
106
|
`)}
|
|
@@ -256,7 +256,7 @@ Exemplar clone + publish complete: ${s} -> ${o}`)),console.log(u.dim(` GitHub:
|
|
|
256
256
|
${N.replace(/^/gm," ")}`}let G=" ".repeat(Math.max(0,q-I.length)),B=`${I}${G}${P}`,M=t.wrap(B,n-2,q);return H+M.slice(I.length)}function l(I){return I.join(`
|
|
257
257
|
`).replace(/^/gm," ".repeat(2))}let d=[];d.push(`Usage: ${t.commandUsage(e)}`,"");let p=t.commandDescription(e);if(p.length>0)d.push(t.wrap(p,n,0),"");let f=t.visibleArguments(e),m=a(f.map((I)=>t.argumentTerm(I))),h=f.map((I)=>{let H=t.argumentTerm(I);return c(H,u.blue(H),t.argumentDescription(I),m)});if(h.length>0)d.push(u.bold("Arguments:"),l(h),"");let g=t.visibleOptions(e),y=a(g.map((I)=>t.optionTerm(I))),w=g.map((I)=>{let H=t.optionTerm(I);return c(H,u.cyan(H),t.optionDescription(I),y)});if(w.length>0)d.push(u.bold("Options:"),l(w),"");let x=(I,H)=>I.name().localeCompare(H.name()),v=(I)=>{let H=a(I.map((P)=>t.subcommandTerm(P)));return I.map((P)=>{let U=t.subcommandTerm(P);return c(U,u.bold.cyan(U),t.subcommandDescription(P),H)})},S=t.visibleCommands(e),E=tUe(e),C=BT||!Object.hasOwn(qT,E)?void 0:qT[E];if(C){let I=new Map(S.map((q)=>[q.name(),q])),H=C.map((q)=>I.get(q)).filter((q)=>q!==void 0),P=new Set(H.map((q)=>q.name())),U=S.filter((q)=>!P.has(q.name())&&q.name()!=="help").sort(x);if(H.length===0)return d.push(u.bold("Commands:"),l(v([...S].sort(x))),""),d.join(`
|
|
258
258
|
`);if(d.push(u.bold("Commands:"),l(v(H)),""),U.length>0){let q=U.map((G)=>G.name()).join(", ");d.push(u.bold("More commands")+u.dim(" (--help-all for details):"),t.wrap(q,n-2,0).replace(/^/gm," "),"")}}else if(S.length>0)d.push(u.bold("Commands:"),l(v([...S].sort(x))),"");return d.join(`
|
|
259
|
-
`)}};function H5(e){z5(e)}function z5(e){e.configureHelp(nUe);for(let t of e.commands)z5(t)}function xr(e,t){if(BT)S0.call(e,"after",t);else if(!_E.has(e))_E.add(e),S0.call(e,"after",B5)}Le();Le();import{existsSync as CO,mkdirSync as sNe,mkdtempSync as pB,readFileSync as _Bt,writeFileSync as Uv}from"fs";import{tmpdir as fB}from"os";import{join as Uu}from"path";xs();Po();function Cre(e,t){return Math.min(Math.floor(Math.log(e)/Math.log(1024)),t)}function $t(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],n=Cre(e,t.length-1);return`${(e/1024**n).toFixed(n===0?0:1)} ${t[n]}`}function Are(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],n=Cre(e,t.length-1);return`${Number.parseFloat((e/1024**n).toFixed(2))} ${t[n]}`}Js();Mw();Fg();qw();var Qk=50;var die=["store","node","registration","drift"];function pie(e){let{verification:t,writerMode:n,now:r}=e;if(t===null)return n==="enabled"?{verdict:"unknown",note:"none recorded: the daily verification sweep has not run, which is unknown and not healthy"}:{verdict:"unchecked",note:null};let o=Date.parse(t.at),s=r.getTime()-o;if(Number.isNaN(o)||s>129600000){let i=Number.isNaN(o)?null:Math.floor(s/3600000);return{verdict:"unknown",note:i===null?"the last record has no readable time, so it says nothing about today":`the last record is ${i} hours old, so it says nothing about today`}}return{verdict:t.overall,note:null}}function LF(e){return e==="alarm"?1:e==="unknown"?2:0}wg();var Pit=["store","node","registration","drift"];function Nit(e){return Pit.filter((t)=>e.checkDays[t].unchecked>0)}function UF(e){let t=[];if(e.coverageStatus==="alarm")t.push("coverage is alarming");if(e.coverageStatus==="unknown")t.push("coverage could not be determined");if(e.autoImportEnabled===!1)t.push("auto-import is OFF");if(e.dispatchLost===!0)t.push("dispatches are not landing");if(e.issuesClosed===null)t.push("no daily sweep activity was recorded, so the daily jobs may not be running");let n=e.neurobagel??null,r=[];if(n===null)t.push("no Neurobagel verification run was recorded, so that job may not be running");else{if(r=Nit(n),n.latest.overall==="alarm")t.push("Neurobagel verification is alarming");if(n.latest.overall==="unknown")t.push("Neurobagel verification could not be determined");if(n.days.alarm>0&&n.latest.overall!=="alarm")t.push(`Neurobagel verification alarmed on ${n.days.alarm} day(s) this week`);if(n.days.unknown>0&&n.latest.overall!=="unknown")t.push(`Neurobagel verification could not be determined on ${n.days.unknown} day(s)`);if(n.failedRuns>0)t.push(`the Neurobagel sweep itself failed on ${n.failedRuns} run(s)`);let o=Math.max(0,7-n.runs);if(o>1)t.push(`the daily Neurobagel verification is missing for ${o} of 7 day(s)`)}if(e.neurobagelFindings===null||e.neurobagelFindings===void 0)t.push("Neurobagel findings could not be counted");else if(e.neurobagelFindings>0)t.push(`${e.neurobagelFindings} Neurobagel finding(s) need attention (see the audit log)`);if(e.upstream===null||e.upstream===void 0)t.push("upstream freshness could not be determined");if(e.repulls===null||e.repulls===void 0)t.push("upstream re-pull activity could not be determined");else t.push(...e.repulls.attention);if(e.errors.length>0)t.push(`${e.errors.length} part(s) of this report failed`);return{attention:t.length>0,problems:t,notChecked:r}}ha();Le();Js();var Mg=2000,Ss=10,ks=500,Dd=/^(nm|on|xx)\d{6}$/;Ue();_a();Sr();sn();function k(e){return typeof e==="string"?e.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu,""):""}function Kn(e,t){let n=k(e);return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function V_(e,t=Date.now()){let n=Date.parse(e);if(Number.isNaN(n))return"?";let r=Math.max(0,Math.floor((t-n)/1000));if(r<3600)return`${Math.floor(r/60)}m`;if(r<86400)return`${Math.floor(r/3600)}h`;return`${Math.floor(r/86400)}d`}var i6={owner_name_missing:`The owner has no researcher name on file. ${Sn("cli.admin.owner_name_missing.fix")} (ADR 0042)`};function an(e){return e?(t)=>console.error(t):(t)=>console.log(t)}function yp(e){if(!(e instanceof L))return!1;if(e.statusCode>=400&&e.statusCode<500)return!0;let t=My(e);return t!==void 0&&t!=="internal"}function s6(e,t,n,r){if(t)t.fail(e);else n(u.red(e));if(r)n(u.dim(` ${r}`))}function F0e(e,t,n,r,o){if(e instanceof L){let i=(e.blockReason?i6[e.blockReason]:void 0)??r?.[e.statusCode]??(e.statusCode===403?"This command requires admin privileges":void 0);s6(k(e.message),t,o,i);return}s6(n,t,o,`Error details: ${k(W(e))}`)}function Bt(e,t,n,r){F0e(e,t,n,r,an(!1))}function Fe(e,t,n,r,o={}){if(F0e(e,t,n,r,an(o.json)),process.exitCode=1,yp(e))ce();else hp()}function J(e,t){if(s6(k(e),t.spinner,an(t.json),t.hint),process.exitCode=1,t.answered)ce();else hp()}function Hc(e,t){if(Dd.test(e))return e;return J(`"${e}" is not a dataset id (like nm000108).`,{json:t,answered:!0}),null}function skt(e){return/^[a-z]{2}\d{0,6}$/.test(e)}function a6(e){return/^(nm|on|xx)0\d{5}$/.test(e)}function M0e(e,t){if(skt(e))return e;return J(`"${e}" is not a dataset id prefix: use two lowercase letters, then up to six digits (like nm or nm0001).`,{json:t,answered:!0}),null}function j0e(e,t){if(a6(e))return e;return J(`"${e}" is not a dataset id (like nm000312). --after takes the last id of the previous page.`,{json:t,answered:!0}),null}function de(e){if(et())return!0;let t=an(e);return t(u.red("Error: Not authenticated")),t(u.dim(" Run 'nemar auth login' first")),process.exitCode=1,ce(),!1}Le();Mw();Le();function Ly(e){return(t)=>{try{return e(t)}catch{return String(t)}}}var Xr={id:Ly(u.cyan),metric:Ly(u.magenta),label:Ly(u.bold),warn:Ly(u.yellow),muted:Ly(u.dim),match:Ly(u.green)};var ikt=/[\u001b\u009b][\[\]()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PR-TZcf-ntqry=><~]/g,akt=/[\n\r\t]+/g,ckt=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;function jr(e){return e.replace(ikt,"").replace(akt," ").replace(ckt,"").trim()}var lkt=/(<mark>[\s\S]*?<\/mark>)/g,ukt=/^<mark>([\s\S]*)<\/mark>$/,L0e=400;function U0e(e){if(!e||typeof e!=="string")return null;try{let t=e.length>L0e?e.slice(0,L0e):e,n=jr(t);if(!n)return null;return n.split(lkt).filter((r)=>r.length>0).map((r)=>{let o=r.match(ukt);return o?Xr.match(o[1]):Xr.muted(r)}).join("")}catch{return null}}function q0e(e,t){if(!Number.isFinite(t)||t<=0)return e;if(e.length<=t)return e;let n=e.split(","),r=[],o=0;for(let i of n){let a=r.length===0?i.length:o+1+i.length;if(a>t)break;r.push(i),o=a}let s=n.length-r.length;if(r.length===0){let i=n[0],a=Math.max(0,t-1),c=a>0?`${i.slice(0,a)}\u2026`:"\u2026",l=n.length-1;return l>0?`${c} +${l}`:c}return s>0?`${r.join(",")} +${s}`:r.join(",")}function rm(e){return jr(e??"")}function c6(e){let t=e.match_kind;return typeof t==="string"&&Kre.includes(t)?t:void 0}function l6(e){let t=e.filter((n)=>c6(n)==="exact");return t.length===1?t[0]:null}function u6(e){return e.length>0&&e.every((t)=>c6(t)==="fuzzy")}function d6(e){return e.length===0||e.some((t)=>c6(t)!==void 0)}function B0e(e){if(e.length===0)return{kind:"none"};let t=l6(e);if(t)return{kind:"one",user:t,match:"exact"};let n=u6(e)?"fuzzy":"partial";if(e.length===1)return{kind:"one",user:e[0],match:n};return{kind:"many",users:[...e],match:n}}var pD=[["givenName","given_name"],["familyName","family_name"],["affiliation","affiliation"],["city","city"],["country","country"],["username","username"],["github","github_username"],["email","email"],["orcid","orcid"]];var dD=[{option:"clearAffiliation",valueOption:"affiliation",field:"affiliation"},{option:"clearGithub",valueOption:"github",field:"github_username"}];function bp(e){return`--${e.replace(/[A-Z]/g,(t)=>`-${t.toLowerCase()}`)}`}function H0e(e){let t={};for(let[n,r]of pD){let o=e[n];if(typeof o!=="string")continue;if((r==="github_username"?o.trim().replace(/^@/,""):o.trim())===""){let i=dD.find((a)=>a.valueOption===n);return{ok:!1,message:i?`${bp(n)} needs a value. To remove it, say so with ${bp(i.option)}.`:`${bp(n)} needs a value.`}}t[r]=o}for(let{option:n,valueOption:r,field:o}of dD){if(e[n]!==!0)continue;if(o in t)return{ok:!1,message:`Use either ${bp(r)} or ${bp(n)}, not both.`};t[o]=""}return{ok:!0,body:t}}function z0e(e,t){let n=[];for(let[,r]of pD){let o=t[r];if(o===void 0)continue;let s=e[r]??null;if((s??"")===o){if(r==="orcid"&&!e.orcid_verified)n.push({field:r,from:`${o} (unverified)`,to:`${o} (verified, attested)`});continue}n.push({field:r,from:s,to:o})}return n}function ti(e,t="-"){let n=rm(e);return n!==""?n:t}function W_(e){if(e===null)return u.dim("(none)");if(e==="")return u.dim("(cleared)");return ti(e,u.dim("(blank)"))}function nm(e){if(!e)return"-";let t=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(t.getTime())?rm(e):t.toISOString().replace("T"," ").slice(0,16)}function p6(e){let t=(a)=>u.dim(`${a}:`.padEnd(15)),n=[e.given_name,e.family_name].filter(Boolean).join(" "),r=[e.city,e.country].filter(Boolean).join(", "),o=e.role||"member",s=e.service_access===void 0||e.service_access===null?"unknown":e.service_access?"upload":"browse",i=[];if(i.push(`${u.cyan(ti(e.username??e.email))}${u.dim(` [${rm(o)}] id ${e.id}`)}${e.username===null?u.dim(" (no username)"):""}`),i.push(` ${t("Name")}${ti(n)}`),i.push(` ${t("Email")}${ti(e.email)} ${e.email_verified?u.green("(verified)"):u.yellow("(unverified)")}`),i.push(` ${t("GitHub")}${e.github_username?`@${ti(e.github_username)}`:"-"}`),i.push(` ${t("ORCID")}${e.orcid?`${ti(e.orcid)} ${e.orcid_verified?u.green("(verified)"):u.yellow("(unverified)")}`:"-"}`),i.push(` ${t("Affiliation")}${ti(e.affiliation)}`),i.push(` ${t("Location")}${ti(r)}`),i.push(` ${t("Status")}${rm(e.status)}`),i.push(` ${t("Upload access")}${s}${e.service_access&&e.service_access_granted_at?u.dim(` (granted ${nm(e.service_access_granted_at)}${e.service_access_granted_by?` by id ${e.service_access_granted_by}`:""})`):""}`),e.upload_access_requested_at)i.push(` ${t("Asked")}${nm(e.upload_access_requested_at)} (upload access)`);if(i.push(` ${t("Kind")}${rm(e.account_kind)||"-"}`),i.push(` ${t("Signed up via")}${ti(e.signup_source)}`),i.push(` ${t("Created")}${nm(e.created_at)}`),e.approved_at)i.push(` ${t("Approved")}${nm(e.approved_at)}`);if(e.revoked_at)i.push(` ${t("Revoked")}${nm(e.revoked_at)}`);if(i.push(` ${t("Last changed")}${nm(e.updated_at)}`),i.push(` ${t("Datasets")}${e.dataset_count??"-"}${u.dim(" API keys: ")}${e.active_tokens??"-"}`),i.push(` ${t("Sign-in")}${e.linked_identities&&e.linked_identities.length>0?e.linked_identities.map((a)=>rm(a)).join(", "):"-"}`),e.description)i.push(` ${t("Description")}${ti(e.description)}`);if(e.identity_conflict)i.push(` ${u.yellow("! Flagged as a duplicate identity: see 'nemar admin users duplicates'")}`);if(e.username_auto_assigned)i.push(` ${u.dim("The username was derived from the name, not chosen")}`);if(e.deleted_at)i.push(` ${u.red(`Deleted ${nm(e.deleted_at)} (tombstoned)`)}`);return i}function f6(e){let t=[e.given_name,e.family_name].filter(Boolean).join(" "),n=e.matched_in&&e.matched_in.length>0?u.dim(` matched: ${e.matched_in.map((r)=>rm(r)).join(", ")}`):"";return` ${String(e.id).padStart(5)} ${u.cyan(ti(e.username,"(no username)"))} ${ti(t,"")} ${u.dim(ti(e.email))}${n}`}zc();Gc();Vc();Ue();gr();var A6=["critical","warning","maintenance","announcement","tip"];async function I_e(){return F("/notices",{},"optional")}async function F_e(){return F("/admin/notices",{},!0)}async function M_e(e){return F("/admin/notices",{method:"POST",body:JSON.stringify(e)},!0)}async function j_e(e){return F(`/admin/notices/${e}`,{method:"DELETE"},!0)}function xa(e,t,n=[]){e.option("--apply",t);for(let r of n){let o=new lo(r,`Hidden alias of --apply: ${t}`).hideHelp();e.addOption(o);let s=o.attributeName();e.on(`option:${o.name()}`,()=>{delete e.opts()[s],e.setOptionValueWithSource("apply",!0,"cli")})}return e}Sr();xs();async function De(e,t,n=!1){if(t.no)return"declined";if(t.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{confirmed:r}=await Pe.prompt([{type:"confirm",name:"confirmed",message:e,default:n}]);return r?"confirmed":"cancelled"}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("closed")||o.includes("TTY")||o.includes("SIGINT")||o.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",o);return"cancelled"}}async function L_e(e,t,n){if(n.no)return"declined";if(n.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{input:r}=await Pe.prompt([{type:"input",name:"input",message:e,validate:(o)=>{if(o!==t)return`Input does not match. Expected: ${t}`;return!0}}]);return r===t?"confirmed":"cancelled"}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("closed")||o.includes("TTY")||o.includes("SIGINT")||o.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",o);return"cancelled"}}var lt="-y, --yes",Ct="-n, --no",xt="Skip confirmation and proceed",kt="Skip confirmation and decline";sn();var U_e="__Host-nemar_docs_session";Fg();gr();Ue();async function O6(e){return F("/auth/login",{method:"POST",body:JSON.stringify({api_key:e})})}async function q_e(e){return F("/auth/resend-verification",{method:"POST",body:JSON.stringify({email:e})})}async function B_e(e){return F("/auth/request-key-regeneration",{method:"POST",body:JSON.stringify({email:e})})}async function wo(){return(await F("/users/me",{},!0,Bre)).user}async function H_e(e){return F("/sandbox/complete",{method:"POST",body:JSON.stringify({dataset_id:e})},!0)}async function z_e(){return F("/sandbox/reset",{method:"POST"},!0)}async function xD(){return F("/sandbox/status",{},!0)}async function G_e(e){return F("/users/me/upload-access/request",{method:"POST",body:JSON.stringify({why:e})},!0)}async function V_e(){return F("/users/me/email-preferences",{},!0)}async function W_e(e){return F("/users/me/email-preferences",{method:"PUT",body:JSON.stringify(e)},!0)}async function K_e(e){return F("/auth/email/change/request",{method:"POST",body:JSON.stringify({email:e})},!0)}async function J_e(e,t){return F("/auth/email/change/verify",{method:"POST",body:JSON.stringify({email:e,code:t})},!0)}async function T6(e){return F("/auth/profile",{method:"PATCH",body:JSON.stringify(e)},!0)}async function Y_e(e){return F("/auth/orcid/cli-start",{method:"POST",body:JSON.stringify({mode:e})},!0)}async function X_e(){return F("/auth/orcid/unlink",{method:"POST"},!0)}async function Z_e(e){return F("/auth/device/start",{method:"POST",body:JSON.stringify({machine_name:e})},!1,goe)}function dkt(e){return typeof e==="string"&&Ek.options.includes(e)}function pkt(e){if(typeof e!=="object"||e===null)return;let t=e.message;return typeof t==="string"?t:void 0}async function Q_e(e,t){try{return{status:"success",data:await F("/auth/device/token",{method:"POST",body:JSON.stringify({device_code:e}),signal:t},!1,boe)}}catch(n){if(n instanceof L&&n.statusCode===400){let r=yoe.safeParse(n.rawBody);if(r.success){let o=r.data;if(o.error==="authorization_pending")return{status:"pending"};if(o.error==="slow_down")return{status:"slow_down"};return{status:"terminal",error:o.error,reason:o.reason,message:o.message}}if(dkt(n.code)&&n.code!=="authorization_pending"&&n.code!=="slow_down")return{status:"terminal",error:n.code,reason:void 0,message:pkt(n.rawBody)??moe[n.code]}}throw n}}async function exe(){return F("/auth/keys",{},!0,Sk)}async function txe(e){return F("/auth/keys",{method:"POST",body:JSON.stringify({name:e})},!0,kk)}async function nxe(){return F("/auth/docs/cli-session",{method:"POST"},!0)}async function vD(e){return F(`/auth/keys/${e}`,{method:"DELETE"},!0)}async function rxe(e,t){return F(`/auth/keys/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}},!1)}async function oxe(){return F("/auth/profile/username-suggestion",{},!0,zre)}var fkt="https://docs.nemar.org";function ED(){return process.env.NEMAR_DOCS_URL||fkt}var sxe=20000;function mkt(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let r=new URL(t),o=new URL(ED()).hostname;if(r.hostname.toLowerCase()!==o.toLowerCase())throw Error(`Not a ${o} URL: ${e}`);t=r.pathname}if(t=t.replace(/[?#].*$/,""),!t.startsWith("/"))t=`/${t}`;if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);if(t===""||t==="/")return"/index.md";return t.slice(t.lastIndexOf("/")+1).includes(".")?t:`${t}.md`}function hkt(e,t){if(e===302||e===301||e===307||e===308){if(t?.includes("/auth/docs/authorize"))return"the documentation session was refused (it may have expired mid-run); try again";return`redirected to ${t??"an unknown location"}`}if(e===404)return"not found, or it is a gated page and this account is not an admin";if(e===401)return"the documentation session was rejected; it may have expired, try again";if(e===403)return"this account is no longer an admin, so the documentation session was refused";if(e===503)return"the documentation gate could not reach the API; try again shortly";return`unexpected status ${e}`}async function ixe(e){let t=e.map((i)=>{try{return{input:i,path:mkt(i)}}catch(a){return{input:i,error:a.message}}});if(!t.some((i)=>i.path))return t.map((i)=>({path:i.input,ok:!1,error:i.error??"not a usable documentation path"}));let n=await nxe();if(typeof n?.session!=="string"||n.session.length===0)throw Error("The API returned no documentation session value.");let r=ED().replace(/\/$/,""),o=`${U_e}=${n.session}`,s=[];for(let i of t){if(!i.path){s.push({path:i.input,ok:!1,error:i.error??"unusable path"});continue}let a=i.path;try{let c=await fetch(`${r}${a}`,{redirect:"manual",signal:AbortSignal.timeout(sxe),headers:{Cookie:o,"User-Agent":"nemar-cli"}});if(c.status===200){s.push({path:a,ok:!0,body:await c.text()});continue}s.push({path:a,ok:!1,error:hkt(c.status,c.headers.get("Location"))})}catch(c){let l=c.name;s.push({path:a,ok:!1,error:l==="TimeoutError"?`no response within ${sxe/1000}s`:c.message})}}return s}SD();ji();Jc();Vt();var nC=pt(tC(),1);function XDt(e,t){let n=nC.default.coerce(e),r=nC.default.coerce(t);if(!n||!r)return!1;return nC.default.gte(n,r)}async function AEe(){try{let{stdout:t,exitCode:n,stderr:r}=await T(["git-annex","version"]);if(n!==0)return console.warn("git-annex version returned non-zero exit code:",n),console.warn("stderr:",r),{installed:!1,minVersion:"10.0",error:`Version check failed: ${r.trim()}`};let o=t.match(/version:\s*(\d+\.\d+)/),s=o?o[1]:void 0;if(!s)console.warn("Could not parse git-annex version from output:",t);return{installed:!0,version:s,minVersion:"10.0",compatible:s?XDt(s,"10.0"):void 0}}catch(t){let n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found"))return console.info("git-annex not found in PATH"),{installed:!1,minVersion:"10.0"};return console.error("Error checking git-annex installation:",n),{installed:!1,minVersion:"10.0",error:n}}}async function ZDt(){if(process.env.GH_TOKEN)return{accessible:!0,username:"token-auth",useHttps:!0};try{let{stdout:e,stderr:t}=await T(["ssh","-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=10","git@github.com"]),n=e+t,r=n.match(/Hi ([^!]+)!/);if(r)return{accessible:!0,username:r[1]};if(n.includes("Permission denied"))return{accessible:!1};return{accessible:n.includes("successfully authenticated")}}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes("ENOENT")||t.includes("not found"))console.info("SSH command not found");else console.error("Error checking GitHub SSH access:",t);return{accessible:!1}}}function OEe(){let e=process.platform;if(e==="darwin")return"brew install git-annex";if(e==="linux")return"apt install git-annex (Debian/Ubuntu)";return"See https://git-annex.branchable.com/install/"}async function rC(){let[e,t]=await Promise.all([AEe(),ZDt()]),n=[];if(!e.installed)n.push(`git-annex is not installed. Install: ${OEe()}`);else if(e.compatible===!1)n.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);if(!t.accessible){if(!(await im()).token)n.push("GitHub authentication not configured. Run 'gh auth login' to authenticate.")}return{gitAnnex:e,githubSSH:t,allPassed:n.length===0,errors:n}}async function ax(){let e=await AEe(),t=[];if(!e.installed)t.push(`git-annex is not installed. Install: ${OEe()}`);else if(e.compatible===!1)t.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);return{gitAnnex:e,allPassed:t.length===0,errors:t}}zy();Le();Js();sn();var QDt=[{oldPath:"publish",newPath:"dataset publish"},{oldPath:"withdraw",newPath:"dataset withdraw"},{oldPath:"restore",newPath:"dataset restore"},{oldPath:"ci",newPath:"dataset ci"},{oldPath:"ci check",newPath:"dataset ci check"},{oldPath:"ci add",newPath:"dataset ci add"},{oldPath:"ci validate",newPath:"dataset ci validate"},{oldPath:"ci sync",newPath:"dataset ci sync"},{oldPath:"doi",newPath:"dataset doi"},{oldPath:"doi create",newPath:"dataset doi create"},{oldPath:"doi info",newPath:"dataset doi info"},{oldPath:"doi update",newPath:"dataset doi update"},{oldPath:"doi enrich",newPath:"dataset doi enrich"},{oldPath:"exemplar",newPath:"dataset exemplar"},{oldPath:"exemplar create",newPath:"dataset exemplar create"},{oldPath:"exemplar status",newPath:"dataset exemplar status"},{oldPath:"exemplar remint-dois",newPath:"dataset exemplar remint-dois"},{oldPath:"doctor scan",newPath:"dataset doctor scan"},{oldPath:"doctor fix",newPath:"dataset doctor fix"},{oldPath:"regenerate-iam",retired:"S3 access uses backend-scoped credentials, so there are no per-user IAM keys to regenerate."},{oldPath:"make-public",retired:"a bare visibility flip that skipped the publication request and screen no longer exists; use 'nemar admin dataset publish'."},{oldPath:"delete-dataset",newPath:"dataset delete"},{oldPath:"bulk-delete",newPath:"dataset bulk-delete"},{oldPath:"reindex",newPath:"dataset reindex"},{oldPath:"s3",newPath:"dataset s3"},{oldPath:"s3 lock",newPath:"dataset s3 lock"},{oldPath:"s3 credential-check",newPath:"dataset s3 credential-check"},{oldPath:"s3 regenerate-iam",retired:"S3 access uses backend-scoped credentials, so there are no per-user IAM keys to regenerate."},{oldPath:"approve",newPath:"users approve"},{oldPath:"revoke",newPath:"users revoke"},{oldPath:"role",newPath:"users role"},{oldPath:"verify",newPath:"users verify"},{oldPath:"kind",newPath:"users kind"},{oldPath:"keys",newPath:"users keys"},{oldPath:"keys create",newPath:"users keys create"},{oldPath:"keys list",newPath:"users keys list"},{oldPath:"keys revoke",newPath:"users keys revoke"},{oldPath:"email-preferences",newPath:"users email-preferences"},{oldPath:"email-preferences show",newPath:"users email-preferences show"},{oldPath:"email-preferences update",newPath:"users email-preferences update"},{oldPath:"duplicates",newPath:"users duplicates"},{oldPath:"backfill-usernames",newPath:"users backfill-usernames"},{oldPath:"doctor",newPath:"dataset doctor"},{oldPath:"doctor kinds",newPath:"users kind-check"},{oldPath:"backfill-names",retired:`names now come from ORCID at sign-up, and the backfill has nothing left to fill. ${Sn("cli.admin.owner_name_missing.fix")}`},{oldPath:"revert",newPath:"rework revert"},{oldPath:"annex-normalize",newPath:"rework annex normalize"},{oldPath:"fleet annex-policy",newPath:"rework annex policy"},{oldPath:"fleet key-registration",newPath:"rework annex key-registration"},{oldPath:"fleet content-recovery",newPath:"rework annex content-recovery"},{oldPath:"recover",newPath:"rework recover"},{oldPath:"recover status",newPath:"rework recover status"},{oldPath:"import-openneuro",newPath:"import openneuro"},{oldPath:"import-issue-triage",newPath:"import triage"},{oldPath:"import-coverage",newPath:"import coverage"},{oldPath:"import-weekly",newPath:"import weekly"},{oldPath:"upstream-status",newPath:"repull upstream-status"},{oldPath:"upstream-backfill",newPath:"repull upstream-backfill"},{oldPath:"hed-sweep",newPath:"fleet sweep hed"},{oldPath:"recording-stats-sweep",newPath:"fleet sweep recording-stats"},{oldPath:"signal-defaults-sweep",newPath:"fleet sweep signal-defaults"},{oldPath:"data-integrity-sweep",newPath:"fleet sweep data-integrity"},{oldPath:"zarr-fidelity-sweep",newPath:"fleet sweep zarr-fidelity"},{oldPath:"anonymity-sweep",newPath:"fleet sweep anonymity"},{oldPath:"availability-report",newPath:"fleet sweep availability"},{oldPath:"summary",newPath:"fleet summary"},{oldPath:"summary check",newPath:"fleet summary check"},{oldPath:"zarr-catalog",newPath:"fleet zarr-catalog"},{oldPath:"zarr-catalog publish",newPath:"fleet zarr-catalog publish"},{oldPath:"e2e-test",newPath:"fleet e2e-test"}],lL=new WeakMap;function TEe(e){return lL.has(e)}function PEe(e,t){let n=e,r=t.indexOf("--")<0?t.length:t.indexOf("--");for(let o=0;o<r;o++){if(t[o].startsWith("-"))continue;if(t[o]==="help"&&n.commands.length>0&&!cL(n,"help"))continue;let s=cL(n,t[o]);if(!s)return;let i=lL.get(s);if(i)i(t.slice(o+1,r));n=s}}function eCt(e,t){return`'${e}' moved to '${t}'. Nothing was run.`}function tCt(e,t){return`'${e}' was retired: ${t} Nothing was run.`}function nCt(e,t){let n=`${t} ${oC(e.oldPath).join(" ")}`;if("retired"in e)return tCt(n,e.retired);return eCt(n,`${t} ${oC(e.newPath).join(" ")}`)}function oC(e){let t=e.trim().split(/\s+/);if(t.length===0||t[0]==="")throw Error("moved-commands: empty path");return t}function rCt(e){let t=[];for(let n=e;n;n=n.parent)t.unshift(n.name());return t.join(" ")}function cL(e,t){return e.commands.find((n)=>n.name()===t||n.aliases().includes(t))}function NEe(e,t=QDt){let n=new Map;for(let o of t){let s=oC(o.oldPath).join(" ");if("retired"in o){if(!/\S.*\.$/.test(o.retired))throw Error(`moved-commands: '${s}' needs a retirement reason ending in a period`)}else oC(o.newPath);if(n.has(s))throw Error(`moved-commands: duplicate old path '${s}'`);n.set(s,o)}let r=new Map;for(let o of n.keys()){let s=o.split(" "),i=e,a=0;for(;a<s.length;a++){let l=cL(i,s[a]);if(!l)break;i=l}if(a===s.length)throw Error(`moved-commands: '${o}' is a row but still a live command`);let c=s.slice(0,a+1).join(" ");if(!n.has(c))throw Error(`moved-commands: '${o}' sits under '${c}', which is gone; add a row for '${c}'`);r.set(c,{parent:i,name:s[a]})}for(let[o,{parent:s,name:i}]of r){let a=o.split(" "),c=(d)=>{let p=n.get(o);for(let f=1;f<=d.length;f++){let m=n.get([...a,...d.slice(0,f)].join(" "));if(m)p=m}console.error(u.red(nCt(p,rCt(e)))),ce(),process.exit(1)},l=s.command(i,{hidden:!0}).helpOption(!1).allowUnknownOption().allowExcessArguments().action((d,p)=>c(p.args));lL.set(l,c)}}import{readFileSync as oCt}from"fs";var sCt=/^on\d{6}$/;function iCt(e){if(!Array.isArray(e))throw Error("Recover-datasets file must be a JSON array");return e.map((t,n)=>{if(typeof t!=="object"||t===null)throw Error(`Recover-datasets entry ${n} is not an object`);let{dataset_id:r,note:o}=t;if(typeof r!=="string"||!sCt.test(r))throw Error(`Recover-datasets entry ${n}: dataset_id "${r}" is not valid`);if(typeof o!=="string"||o.length===0)throw Error(`Recover-datasets entry ${n} (${r}): note is required`);return{dataset_id:r,note:o}})}function uL(e){let t;try{t=JSON.parse(oCt(e,"utf-8"))}catch(n){throw Error(`Failed to read/parse recover-datasets file at ${e}: ${n instanceof Error?n.message:String(n)}`)}return iCt(t)}function IEe(e,t,n){let r=new Set(t.map((o)=>o.dataset_id));for(let o of e)if(!r.has(o)&&!n.force)return{error:`${o} is not on the checked-in recover-datasets list. Pass --force to override.`};return{targets:e}}function FEe(e,t){let n=new Set(e),r=new Map;for(let s of t)if(n.has(s.dataset_id)&&s.source_id)r.set(s.dataset_id,s.source_id);let o=e.filter((s)=>!r.has(s));return{sourceByTarget:r,missingSource:o}}import{readFileSync as aCt}from"fs";var MEe=new Set(["upstream_403","no_source","recovered"]),cCt=/^(nm|xx|on)\d{6}$/;function lCt(e){if(!Array.isArray(e))throw Error("Withdrawn-datasets file must be a JSON array");return e.map((t,n)=>{if(typeof t!=="object"||t===null)throw Error(`Withdrawn-datasets entry ${n} is not an object`);let{dataset_id:r,reason:o,note:s,withdrawn:i,data_available:a,data_keys_missing:c,data_keys_total:l}=t;if(typeof r!=="string"||!cCt.test(r))throw Error(`Withdrawn-datasets entry ${n}: dataset_id "${r}" is not valid`);if(typeof o!=="string"||!MEe.has(o))throw Error(`Withdrawn-datasets entry ${n} (${r}): reason "${o}" must be one of ${[...MEe].join(", ")}`);if(typeof s!=="string"||s.length===0)throw Error(`Withdrawn-datasets entry ${n} (${r}): note is required`);if(i!==void 0&&typeof i!=="boolean")throw Error(`Withdrawn-datasets entry ${n} (${r}): withdrawn must be a boolean`);if(a!==void 0&&(typeof a!=="number"||a<0||a>1))throw Error(`Withdrawn-datasets entry ${n} (${r}): data_available must be between 0 and 1`);let d=i??!0;if(o==="recovered"&&d)throw Error(`Withdrawn-datasets entry ${n} (${r}): reason "recovered" means the content came back, so withdrawn must be false`);let p=typeof c==="number",f=typeof l==="number";if(p!==f)throw Error(`Withdrawn-datasets entry ${n} (${r}): data_keys_missing and data_keys_total must be given together`);if(p&&f){if(c<0||l<0)throw Error(`Withdrawn-datasets entry ${n} (${r}): key counts cannot be negative`);if(c>l)throw Error(`Withdrawn-datasets entry ${n} (${r}): ${c} missing of ${l} total is not possible`);if(typeof a==="number"&&l>0){let m=(l-c)/l;if(Math.abs(m-a)>0.001)throw Error(`Withdrawn-datasets entry ${n} (${r}): data_available ${a} disagrees with ${c} missing of ${l} (${m.toFixed(4)})`)}}return{dataset_id:r,reason:o,note:s,withdrawn:d,...typeof a==="number"?{data_available:a}:{},...p?{data_keys_missing:c}:{},...f?{data_keys_total:l}:{}}})}function dL(e){let t;try{t=JSON.parse(aCt(e,"utf-8"))}catch(n){throw Error(`Failed to read/parse withdrawn-datasets file at ${e}: ${n instanceof Error?n.message:String(n)}`)}return lCt(t)}function jEe(e,t,n){let r=new Map(t.map((s)=>[s.dataset_id,s])),o=[];for(let s of e){let i=r.get(s);if(!i&&!n.force)return{error:`${s} is not on the checked-in withdrawn-datasets list. Pass --force to override.`};if(i?.withdrawn===!1&&!n.force)return{error:`${s} was reinstated (${i.reason}); its entry is a record, not a target. Pass --force to withdraw it again.`};let a=n.reason||i?.reason;if(!a)return{error:`${s}: no --reason given and it has no default entry in the list.`};o.push({datasetId:s,reason:a})}return{targets:o}}function pL(e){return e.filter((t)=>t.withdrawn!==!1)}import{randomUUID as XSe}from"crypto";import{readFileSync as sAt,statSync as iAt}from"fs";pa();Rd();mr();Mf();Rd();mn();var LEe=O({ok:He(!0),state:b().nullable(),outcome:b(),cancelled:Q().optional()}).passthrough(),amn=O({links:Y(O({path:b(),size:D().int().nonnegative(),url:b()}).passthrough()),expires_at:b(),total:D().int().nonnegative(),truncated:Q(),next_after:b().nullable()}).passthrough(),cmn=O({ok:He(!0),snapshots:D().int().nonnegative(),sacct_rows:D().int().nonnegative(),matched:D().int().nonnegative(),settled:D().int().nonnegative(),mismatched:D().int().nonnegative(),unmatched:D().int().nonnegative(),skipped:D().int().nonnegative(),truncated:He(!0).optional(),settlement_failed:He(!0).optional()}).passthrough();Zk();Yk();gr();Ue();async function UEe(){return F("/admin/compute/policy",{},!0,gF)}async function qEe(e,t,n=!1){return F("/admin/compute/policy",{method:"PUT",body:JSON.stringify({policy:e,...t===void 0?{}:{note:t},...n?{force_partner_off:!0}:{}})},!0,gF)}async function BEe(e={}){let t=new URLSearchParams;if(e.holderKind)t.set("holder_kind",e.holderKind);if(e.after!==void 0)t.set("after",String(e.after));if(e.limit!==void 0)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/compute/pools${n}`,{},!0,cse)}async function HEe(e){return F(`/admin/compute/pools/by-id/${e}`,{},!0,lse)}function sC(e,t,n){return F(e,{method:"POST",body:JSON.stringify(t),headers:{"Idempotency-Key":n}},!0,use)}async function zEe(e,t,n){return sC(`/admin/compute/pools/by-id/${e}/grant`,t,n)}async function GEe(e,t,n){return sC(`/admin/compute/pools/by-id/${e}/adjust`,t,n)}async function VEe(e,t,n){return sC(`/admin/compute/pools/platform/${encodeURIComponent(e)}/grant`,t,n)}async function WEe(e,t,n){return sC(`/admin/compute/pools/platform/${encodeURIComponent(e)}/adjust`,t,n)}async function KEe(){return F("/admin/compute/status",{},!0,dse)}async function JEe(e){return F(`/admin/compute/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST"},!0,bF)}async function YEe(e){return F(`/admin/compute/jobs/${encodeURIComponent(e)}/advance`,{method:"POST"},!0,bF)}async function XEe(e,t,n=!1){return F(`/admin/compute/jobs/${encodeURIComponent(e)}/move-charge`,{method:"POST",body:JSON.stringify({to_account_id:t,...n?{confirm_unproven_owner:!0}:{}})},!0,Cse)}async function ZEe(e){return F("/admin/compute/pipeline/run",{method:"POST",body:JSON.stringify(e)},!0,fse)}async function QEe(e={}){let t=new URLSearchParams;if(e.recipe)t.set("recipe",e.recipe);if(e.dataset)t.set("dataset",e.dataset);if(e.state)t.set("state",e.state);if(e.before!==void 0)t.set("before",String(e.before));if(e.limit!==void 0)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/compute/pipeline/status${n}`,{},!0,mse)}var lm=(e)=>e.toString()?`?${e.toString()}`:"";async function eSe(e={}){let t=new URLSearchParams;if(e.flag)t.set("flag",e.flag);if(e.state)t.set("state",e.state);if(e.account!==void 0)t.set("account",String(e.account));if(e.executor)t.set("executor",e.executor);if(e.accounting)t.set("accounting",e.accounting);if(e.runner)t.set("runner",e.runner);if(e.limit!==void 0)t.set("limit",String(e.limit));if(e.after!==void 0)t.set("after",String(e.after));return F(`/admin/compute/jobs${lm(t)}`,{},!0,hse)}async function tSe(e){let t=new URLSearchParams({unmatched:"1"});if(e!==void 0)t.set("limit",String(e));return F(`/admin/compute/jobs${lm(t)}`,{},!0,gse)}async function nSe(e){return F(`/admin/compute/records/${encodeURIComponent(e)}`,{},!0,yse)}async function rSe(e,t,n){return F(`/admin/compute/records/${encodeURIComponent(e)}/read`,{method:"POST",body:JSON.stringify({name:t,reason:n})},!0,bse)}async function oSe(e){let t=new URLSearchParams({account:String(e.account),from:e.from,to:e.to});return F(`/admin/compute/report${lm(t)}`,{},!0,wse)}async function sSe(e){let t=new URLSearchParams({quarter:e});return F(`/admin/compute/access-report${lm(t)}`,{},!0,Ese)}async function fL(e={}){let t=new URLSearchParams;if(e.scope)t.set("scope",e.scope);if(e.ref)t.set("ref",e.ref);return F(`/admin/compute/holds${lm(t)}`,{},!0,kse)}async function iSe(e){return F("/admin/compute/holds",{method:"POST",body:JSON.stringify(e)},!0,SF)}async function aSe(e){return F(`/admin/compute/holds/${e}`,{method:"DELETE"},!0,SF)}async function cSe(e={}){let t=new URLSearchParams;if(e.state)t.set("state",e.state);if(e.limit!==void 0)t.set("limit",String(e.limit));if(e.after)t.set("after",e.after);return F(`/admin/compute/access-reports${lm(t)}`,{},!0,Rse)}async function lSe(e){return F(`/admin/compute/access-reports/${encodeURIComponent(e)}/requeue`,{method:"POST",body:JSON.stringify({confirmed_not_recorded:!0})},!0,$se)}async function uSe(){return F("/admin/compute/observer-runs",{method:"POST"},!0,Dse)}function Sp(e){if(!(e instanceof L))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let{code:n,blocked_by:r,reason:o}=t;if(typeof n!=="string")return;let s=Array.isArray(r)?r.filter((i)=>typeof i==="string"):[];return{code:n,blockedBy:s,...typeof o==="string"?{reason:o}:{}}}async function dSe(e){return F("/users/me/compute-access/request",{method:"POST",body:JSON.stringify(e)},!0,Ose)}async function iC(){return F("/compute/me",{},!0,Mse)}async function pSe(e={}){let t=new URLSearchParams;if(e.state)t.set("state",e.state);if(e.limit!==void 0)t.set("limit",String(e.limit));if(e.after)t.set("after",e.after);return F(`/compute/me/jobs${lm(t)}`,{},!0,Lse)}async function aC(e,t={}){return F(`/compute/me/jobs/${encodeURIComponent(e)}`,t.signal?{signal:t.signal}:{},!0,Use,"json",t.timeoutMs)}async function fSe(e,t){return F("/compute/jobs",{method:"POST",body:JSON.stringify(e),headers:{[Hse]:t}},!0,Gse)}async function mSe(e,t){return F(`/compute/jobs/${encodeURIComponent(e)}/finalize`,{method:"POST",body:JSON.stringify(t)},!0,Vse)}async function hSe(e){let t=await F(`/compute/jobs/${encodeURIComponent(e)}/logs`,{},!0,void 0,"text");return{text:t.text,truncated:t.headers.get(zse)?.toLowerCase()==="true"}}var gSe=(e)=>e===void 0?"":`?${new URLSearchParams({after:e}).toString()}`;async function ySe(e,t){return F(`/compute/jobs/${encodeURIComponent(e)}/results${gSe(t)}`,{},!0,CF)}async function bSe(e,t){return F(`/compute/jobs/${encodeURIComponent(e)}/results/renew${gSe(t)}`,{method:"POST"},!0,CF)}async function wSe(e){return F(`/compute/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST"},!0,LEe)}var Ky=["none","requested","active","suspended","denied","revoked"];var uCt={none:["requested"],requested:["active","denied"],active:["suspended","revoked"],suspended:["active","revoked"],denied:["active"],revoked:["active"]};function cC(e,t){return uCt[e].includes(t)}var _Se=["grant","deny","suspend","revoke"];var bmn={grant:Ky.filter((e)=>cC(e,"active")),deny:Ky.filter((e)=>cC(e,"denied")),suspend:Ky.filter((e)=>cC(e,"suspended")),revoke:Ky.filter((e)=>cC(e,"revoked"))};Mf();mr();Mf();gr();Ue();async function xSe(e={}){let t=new URLSearchParams;if(e.state!==void 0)t.set("state",e.state);if(e.limit!==void 0)t.set("limit",String(e.limit));if(e.after!==void 0)t.set("after",String(e.after));let n=t.size>0?`?${t.toString()}`:"";return F(`/admin/compute/access${n}`,{},!0,Nse)}async function vSe(e,t,n,r){let o={};if(n!==void 0)o.reason=n;if(r!==void 0)o.notice=r.trim();let s="id"in t?`by-id/${t.id}`:encodeURIComponent(t.username);return F(`/admin/compute/access/${e}/${s}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},!0,Ise)}var cu=(e)=>console.log(e),Qc=(e)=>k(e??""),mL=Ky.filter((e)=>e!=="none");function SSe(e){let t=[e.given_name,e.family_name].filter(Boolean).join(" ");return`${e.username?Qc(e.username):`(no username, id ${e.id})`}${t?` ${Qc(t)}`:""}`}function dCt(e){let t=[e.affiliation,e.city,e.country].filter(Boolean).map(Qc).join(", "),n=e.compute_access_requested_at?` asked ${Qc(e.compute_access_requested_at)}`:"";return`${String(e.id).padEnd(7)} ${Qc(e.compute_access).padEnd(10)} ${SSe(e)}${t?` [${t}]`:""}${n}`}var pCt=`
|
|
259
|
+
`)}};function H5(e){z5(e)}function z5(e){e.configureHelp(nUe);for(let t of e.commands)z5(t)}function xr(e,t){if(BT)S0.call(e,"after",t);else if(!_E.has(e))_E.add(e),S0.call(e,"after",B5)}Le();Le();import{existsSync as CO,mkdirSync as sNe,mkdtempSync as pB,readFileSync as _Bt,writeFileSync as Uv}from"fs";import{tmpdir as fB}from"os";import{join as Uu}from"path";xs();Po();function Cre(e,t){return Math.min(Math.floor(Math.log(e)/Math.log(1024)),t)}function $t(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],n=Cre(e,t.length-1);return`${(e/1024**n).toFixed(n===0?0:1)} ${t[n]}`}function Are(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],n=Cre(e,t.length-1);return`${Number.parseFloat((e/1024**n).toFixed(2))} ${t[n]}`}Js();Mw();Fg();qw();var Qk=50;var die=["store","node","registration","drift"];function pie(e){let{verification:t,writerMode:n,now:r}=e;if(t===null)return n==="enabled"?{verdict:"unknown",note:"none recorded: the daily verification sweep has not run, which is unknown and not healthy"}:{verdict:"unchecked",note:null};let o=Date.parse(t.at),s=r.getTime()-o;if(Number.isNaN(o)||s>129600000){let i=Number.isNaN(o)?null:Math.floor(s/3600000);return{verdict:"unknown",note:i===null?"the last record has no readable time, so it says nothing about today":`the last record is ${i} hours old, so it says nothing about today`}}return{verdict:t.overall,note:null}}function LF(e){return e==="alarm"?1:e==="unknown"?2:0}wg();var Pit=["store","node","registration","drift"];function Nit(e){return Pit.filter((t)=>e.checkDays[t].unchecked>0)}function UF(e){let t=[];if(e.coverageStatus==="alarm")t.push("coverage is alarming");if(e.coverageStatus==="unknown")t.push("coverage could not be determined");if(e.autoImportEnabled===!1)t.push("auto-import is OFF");if(e.dispatchLost===!0)t.push("dispatches are not landing");if(e.issuesClosed===null)t.push("no daily sweep activity was recorded, so the daily jobs may not be running");let n=e.neurobagel??null,r=[];if(n===null)t.push("no Neurobagel verification run was recorded, so that job may not be running");else{if(r=Nit(n),n.latest.overall==="alarm")t.push("Neurobagel verification is alarming");if(n.latest.overall==="unknown")t.push("Neurobagel verification could not be determined");if(n.days.alarm>0&&n.latest.overall!=="alarm")t.push(`Neurobagel verification alarmed on ${n.days.alarm} day(s) this week`);if(n.days.unknown>0&&n.latest.overall!=="unknown")t.push(`Neurobagel verification could not be determined on ${n.days.unknown} day(s)`);if(n.failedRuns>0)t.push(`the Neurobagel sweep itself failed on ${n.failedRuns} run(s)`);let o=Math.max(0,7-n.runs);if(o>1)t.push(`the daily Neurobagel verification is missing for ${o} of 7 day(s)`)}if(e.neurobagelFindings===null||e.neurobagelFindings===void 0)t.push("Neurobagel findings could not be counted");else if(e.neurobagelFindings>0)t.push(`${e.neurobagelFindings} Neurobagel finding(s) need attention (see the audit log)`);if(e.upstream===null||e.upstream===void 0)t.push("upstream freshness could not be determined");if(e.repulls===null||e.repulls===void 0)t.push("upstream re-pull activity could not be determined");else t.push(...e.repulls.attention);if(e.rfcs===null||e.rfcs===void 0)t.push("the RFC clock could not be determined");else t.push(...e.rfcs.attention);if(e.errors.length>0)t.push(`${e.errors.length} part(s) of this report failed`);return{attention:t.length>0,problems:t,notChecked:r}}ha();Le();Js();var Mg=2000,Ss=10,ks=500,Dd=/^(nm|on|xx)\d{6}$/;Ue();_a();Sr();sn();function k(e){return typeof e==="string"?e.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu,""):""}function Kn(e,t){let n=k(e);return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function V_(e,t=Date.now()){let n=Date.parse(e);if(Number.isNaN(n))return"?";let r=Math.max(0,Math.floor((t-n)/1000));if(r<3600)return`${Math.floor(r/60)}m`;if(r<86400)return`${Math.floor(r/3600)}h`;return`${Math.floor(r/86400)}d`}var i6={owner_name_missing:`The owner has no researcher name on file. ${Sn("cli.admin.owner_name_missing.fix")} (ADR 0042)`};function an(e){return e?(t)=>console.error(t):(t)=>console.log(t)}function yp(e){if(!(e instanceof L))return!1;if(e.statusCode>=400&&e.statusCode<500)return!0;let t=My(e);return t!==void 0&&t!=="internal"}function s6(e,t,n,r){if(t)t.fail(e);else n(u.red(e));if(r)n(u.dim(` ${r}`))}function F0e(e,t,n,r,o){if(e instanceof L){let i=(e.blockReason?i6[e.blockReason]:void 0)??r?.[e.statusCode]??(e.statusCode===403?"This command requires admin privileges":void 0);s6(k(e.message),t,o,i);return}s6(n,t,o,`Error details: ${k(W(e))}`)}function Bt(e,t,n,r){F0e(e,t,n,r,an(!1))}function Fe(e,t,n,r,o={}){if(F0e(e,t,n,r,an(o.json)),process.exitCode=1,yp(e))ce();else hp()}function J(e,t){if(s6(k(e),t.spinner,an(t.json),t.hint),process.exitCode=1,t.answered)ce();else hp()}function Hc(e,t){if(Dd.test(e))return e;return J(`"${e}" is not a dataset id (like nm000108).`,{json:t,answered:!0}),null}function skt(e){return/^[a-z]{2}\d{0,6}$/.test(e)}function a6(e){return/^(nm|on|xx)0\d{5}$/.test(e)}function M0e(e,t){if(skt(e))return e;return J(`"${e}" is not a dataset id prefix: use two lowercase letters, then up to six digits (like nm or nm0001).`,{json:t,answered:!0}),null}function j0e(e,t){if(a6(e))return e;return J(`"${e}" is not a dataset id (like nm000312). --after takes the last id of the previous page.`,{json:t,answered:!0}),null}function de(e){if(et())return!0;let t=an(e);return t(u.red("Error: Not authenticated")),t(u.dim(" Run 'nemar auth login' first")),process.exitCode=1,ce(),!1}Le();Mw();Le();function Ly(e){return(t)=>{try{return e(t)}catch{return String(t)}}}var Xr={id:Ly(u.cyan),metric:Ly(u.magenta),label:Ly(u.bold),warn:Ly(u.yellow),muted:Ly(u.dim),match:Ly(u.green)};var ikt=/[\u001b\u009b][\[\]()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PR-TZcf-ntqry=><~]/g,akt=/[\n\r\t]+/g,ckt=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;function jr(e){return e.replace(ikt,"").replace(akt," ").replace(ckt,"").trim()}var lkt=/(<mark>[\s\S]*?<\/mark>)/g,ukt=/^<mark>([\s\S]*)<\/mark>$/,L0e=400;function U0e(e){if(!e||typeof e!=="string")return null;try{let t=e.length>L0e?e.slice(0,L0e):e,n=jr(t);if(!n)return null;return n.split(lkt).filter((r)=>r.length>0).map((r)=>{let o=r.match(ukt);return o?Xr.match(o[1]):Xr.muted(r)}).join("")}catch{return null}}function q0e(e,t){if(!Number.isFinite(t)||t<=0)return e;if(e.length<=t)return e;let n=e.split(","),r=[],o=0;for(let i of n){let a=r.length===0?i.length:o+1+i.length;if(a>t)break;r.push(i),o=a}let s=n.length-r.length;if(r.length===0){let i=n[0],a=Math.max(0,t-1),c=a>0?`${i.slice(0,a)}\u2026`:"\u2026",l=n.length-1;return l>0?`${c} +${l}`:c}return s>0?`${r.join(",")} +${s}`:r.join(",")}function rm(e){return jr(e??"")}function c6(e){let t=e.match_kind;return typeof t==="string"&&Kre.includes(t)?t:void 0}function l6(e){let t=e.filter((n)=>c6(n)==="exact");return t.length===1?t[0]:null}function u6(e){return e.length>0&&e.every((t)=>c6(t)==="fuzzy")}function d6(e){return e.length===0||e.some((t)=>c6(t)!==void 0)}function B0e(e){if(e.length===0)return{kind:"none"};let t=l6(e);if(t)return{kind:"one",user:t,match:"exact"};let n=u6(e)?"fuzzy":"partial";if(e.length===1)return{kind:"one",user:e[0],match:n};return{kind:"many",users:[...e],match:n}}var pD=[["givenName","given_name"],["familyName","family_name"],["affiliation","affiliation"],["city","city"],["country","country"],["username","username"],["github","github_username"],["email","email"],["orcid","orcid"]];var dD=[{option:"clearAffiliation",valueOption:"affiliation",field:"affiliation"},{option:"clearGithub",valueOption:"github",field:"github_username"}];function bp(e){return`--${e.replace(/[A-Z]/g,(t)=>`-${t.toLowerCase()}`)}`}function H0e(e){let t={};for(let[n,r]of pD){let o=e[n];if(typeof o!=="string")continue;if((r==="github_username"?o.trim().replace(/^@/,""):o.trim())===""){let i=dD.find((a)=>a.valueOption===n);return{ok:!1,message:i?`${bp(n)} needs a value. To remove it, say so with ${bp(i.option)}.`:`${bp(n)} needs a value.`}}t[r]=o}for(let{option:n,valueOption:r,field:o}of dD){if(e[n]!==!0)continue;if(o in t)return{ok:!1,message:`Use either ${bp(r)} or ${bp(n)}, not both.`};t[o]=""}return{ok:!0,body:t}}function z0e(e,t){let n=[];for(let[,r]of pD){let o=t[r];if(o===void 0)continue;let s=e[r]??null;if((s??"")===o){if(r==="orcid"&&!e.orcid_verified)n.push({field:r,from:`${o} (unverified)`,to:`${o} (verified, attested)`});continue}n.push({field:r,from:s,to:o})}return n}function ti(e,t="-"){let n=rm(e);return n!==""?n:t}function W_(e){if(e===null)return u.dim("(none)");if(e==="")return u.dim("(cleared)");return ti(e,u.dim("(blank)"))}function nm(e){if(!e)return"-";let t=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(t.getTime())?rm(e):t.toISOString().replace("T"," ").slice(0,16)}function p6(e){let t=(a)=>u.dim(`${a}:`.padEnd(15)),n=[e.given_name,e.family_name].filter(Boolean).join(" "),r=[e.city,e.country].filter(Boolean).join(", "),o=e.role||"member",s=e.service_access===void 0||e.service_access===null?"unknown":e.service_access?"upload":"browse",i=[];if(i.push(`${u.cyan(ti(e.username??e.email))}${u.dim(` [${rm(o)}] id ${e.id}`)}${e.username===null?u.dim(" (no username)"):""}`),i.push(` ${t("Name")}${ti(n)}`),i.push(` ${t("Email")}${ti(e.email)} ${e.email_verified?u.green("(verified)"):u.yellow("(unverified)")}`),i.push(` ${t("GitHub")}${e.github_username?`@${ti(e.github_username)}`:"-"}`),i.push(` ${t("ORCID")}${e.orcid?`${ti(e.orcid)} ${e.orcid_verified?u.green("(verified)"):u.yellow("(unverified)")}`:"-"}`),i.push(` ${t("Affiliation")}${ti(e.affiliation)}`),i.push(` ${t("Location")}${ti(r)}`),i.push(` ${t("Status")}${rm(e.status)}`),i.push(` ${t("Upload access")}${s}${e.service_access&&e.service_access_granted_at?u.dim(` (granted ${nm(e.service_access_granted_at)}${e.service_access_granted_by?` by id ${e.service_access_granted_by}`:""})`):""}`),e.upload_access_requested_at)i.push(` ${t("Asked")}${nm(e.upload_access_requested_at)} (upload access)`);if(i.push(` ${t("Kind")}${rm(e.account_kind)||"-"}`),i.push(` ${t("Signed up via")}${ti(e.signup_source)}`),i.push(` ${t("Created")}${nm(e.created_at)}`),e.approved_at)i.push(` ${t("Approved")}${nm(e.approved_at)}`);if(e.revoked_at)i.push(` ${t("Revoked")}${nm(e.revoked_at)}`);if(i.push(` ${t("Last changed")}${nm(e.updated_at)}`),i.push(` ${t("Datasets")}${e.dataset_count??"-"}${u.dim(" API keys: ")}${e.active_tokens??"-"}`),i.push(` ${t("Sign-in")}${e.linked_identities&&e.linked_identities.length>0?e.linked_identities.map((a)=>rm(a)).join(", "):"-"}`),e.description)i.push(` ${t("Description")}${ti(e.description)}`);if(e.identity_conflict)i.push(` ${u.yellow("! Flagged as a duplicate identity: see 'nemar admin users duplicates'")}`);if(e.username_auto_assigned)i.push(` ${u.dim("The username was derived from the name, not chosen")}`);if(e.deleted_at)i.push(` ${u.red(`Deleted ${nm(e.deleted_at)} (tombstoned)`)}`);return i}function f6(e){let t=[e.given_name,e.family_name].filter(Boolean).join(" "),n=e.matched_in&&e.matched_in.length>0?u.dim(` matched: ${e.matched_in.map((r)=>rm(r)).join(", ")}`):"";return` ${String(e.id).padStart(5)} ${u.cyan(ti(e.username,"(no username)"))} ${ti(t,"")} ${u.dim(ti(e.email))}${n}`}zc();Gc();Vc();Ue();gr();var A6=["critical","warning","maintenance","announcement","tip"];async function I_e(){return F("/notices",{},"optional")}async function F_e(){return F("/admin/notices",{},!0)}async function M_e(e){return F("/admin/notices",{method:"POST",body:JSON.stringify(e)},!0)}async function j_e(e){return F(`/admin/notices/${e}`,{method:"DELETE"},!0)}function xa(e,t,n=[]){e.option("--apply",t);for(let r of n){let o=new lo(r,`Hidden alias of --apply: ${t}`).hideHelp();e.addOption(o);let s=o.attributeName();e.on(`option:${o.name()}`,()=>{delete e.opts()[s],e.setOptionValueWithSource("apply",!0,"cli")})}return e}Sr();xs();async function De(e,t,n=!1){if(t.no)return"declined";if(t.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{confirmed:r}=await Pe.prompt([{type:"confirm",name:"confirmed",message:e,default:n}]);return r?"confirmed":"cancelled"}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("closed")||o.includes("TTY")||o.includes("SIGINT")||o.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",o);return"cancelled"}}async function L_e(e,t,n){if(n.no)return"declined";if(n.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{input:r}=await Pe.prompt([{type:"input",name:"input",message:e,validate:(o)=>{if(o!==t)return`Input does not match. Expected: ${t}`;return!0}}]);return r===t?"confirmed":"cancelled"}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("closed")||o.includes("TTY")||o.includes("SIGINT")||o.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",o);return"cancelled"}}var lt="-y, --yes",Ct="-n, --no",xt="Skip confirmation and proceed",kt="Skip confirmation and decline";sn();var U_e="__Host-nemar_docs_session";Fg();gr();Ue();async function O6(e){return F("/auth/login",{method:"POST",body:JSON.stringify({api_key:e})})}async function q_e(e){return F("/auth/resend-verification",{method:"POST",body:JSON.stringify({email:e})})}async function B_e(e){return F("/auth/request-key-regeneration",{method:"POST",body:JSON.stringify({email:e})})}async function wo(){return(await F("/users/me",{},!0,Bre)).user}async function H_e(e){return F("/sandbox/complete",{method:"POST",body:JSON.stringify({dataset_id:e})},!0)}async function z_e(){return F("/sandbox/reset",{method:"POST"},!0)}async function xD(){return F("/sandbox/status",{},!0)}async function G_e(e){return F("/users/me/upload-access/request",{method:"POST",body:JSON.stringify({why:e})},!0)}async function V_e(){return F("/users/me/email-preferences",{},!0)}async function W_e(e){return F("/users/me/email-preferences",{method:"PUT",body:JSON.stringify(e)},!0)}async function K_e(e){return F("/auth/email/change/request",{method:"POST",body:JSON.stringify({email:e})},!0)}async function J_e(e,t){return F("/auth/email/change/verify",{method:"POST",body:JSON.stringify({email:e,code:t})},!0)}async function T6(e){return F("/auth/profile",{method:"PATCH",body:JSON.stringify(e)},!0)}async function Y_e(e){return F("/auth/orcid/cli-start",{method:"POST",body:JSON.stringify({mode:e})},!0)}async function X_e(){return F("/auth/orcid/unlink",{method:"POST"},!0)}async function Z_e(e){return F("/auth/device/start",{method:"POST",body:JSON.stringify({machine_name:e})},!1,goe)}function dkt(e){return typeof e==="string"&&Ek.options.includes(e)}function pkt(e){if(typeof e!=="object"||e===null)return;let t=e.message;return typeof t==="string"?t:void 0}async function Q_e(e,t){try{return{status:"success",data:await F("/auth/device/token",{method:"POST",body:JSON.stringify({device_code:e}),signal:t},!1,boe)}}catch(n){if(n instanceof L&&n.statusCode===400){let r=yoe.safeParse(n.rawBody);if(r.success){let o=r.data;if(o.error==="authorization_pending")return{status:"pending"};if(o.error==="slow_down")return{status:"slow_down"};return{status:"terminal",error:o.error,reason:o.reason,message:o.message}}if(dkt(n.code)&&n.code!=="authorization_pending"&&n.code!=="slow_down")return{status:"terminal",error:n.code,reason:void 0,message:pkt(n.rawBody)??moe[n.code]}}throw n}}async function exe(){return F("/auth/keys",{},!0,Sk)}async function txe(e){return F("/auth/keys",{method:"POST",body:JSON.stringify({name:e})},!0,kk)}async function nxe(){return F("/auth/docs/cli-session",{method:"POST"},!0)}async function vD(e){return F(`/auth/keys/${e}`,{method:"DELETE"},!0)}async function rxe(e,t){return F(`/auth/keys/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}},!1)}async function oxe(){return F("/auth/profile/username-suggestion",{},!0,zre)}var fkt="https://docs.nemar.org";function ED(){return process.env.NEMAR_DOCS_URL||fkt}var sxe=20000;function mkt(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let r=new URL(t),o=new URL(ED()).hostname;if(r.hostname.toLowerCase()!==o.toLowerCase())throw Error(`Not a ${o} URL: ${e}`);t=r.pathname}if(t=t.replace(/[?#].*$/,""),!t.startsWith("/"))t=`/${t}`;if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);if(t===""||t==="/")return"/index.md";return t.slice(t.lastIndexOf("/")+1).includes(".")?t:`${t}.md`}function hkt(e,t){if(e===302||e===301||e===307||e===308){if(t?.includes("/auth/docs/authorize"))return"the documentation session was refused (it may have expired mid-run); try again";return`redirected to ${t??"an unknown location"}`}if(e===404)return"not found, or it is a gated page and this account is not an admin";if(e===401)return"the documentation session was rejected; it may have expired, try again";if(e===403)return"this account is no longer an admin, so the documentation session was refused";if(e===503)return"the documentation gate could not reach the API; try again shortly";return`unexpected status ${e}`}async function ixe(e){let t=e.map((i)=>{try{return{input:i,path:mkt(i)}}catch(a){return{input:i,error:a.message}}});if(!t.some((i)=>i.path))return t.map((i)=>({path:i.input,ok:!1,error:i.error??"not a usable documentation path"}));let n=await nxe();if(typeof n?.session!=="string"||n.session.length===0)throw Error("The API returned no documentation session value.");let r=ED().replace(/\/$/,""),o=`${U_e}=${n.session}`,s=[];for(let i of t){if(!i.path){s.push({path:i.input,ok:!1,error:i.error??"unusable path"});continue}let a=i.path;try{let c=await fetch(`${r}${a}`,{redirect:"manual",signal:AbortSignal.timeout(sxe),headers:{Cookie:o,"User-Agent":"nemar-cli"}});if(c.status===200){s.push({path:a,ok:!0,body:await c.text()});continue}s.push({path:a,ok:!1,error:hkt(c.status,c.headers.get("Location"))})}catch(c){let l=c.name;s.push({path:a,ok:!1,error:l==="TimeoutError"?`no response within ${sxe/1000}s`:c.message})}}return s}SD();ji();Jc();Vt();var nC=pt(tC(),1);function XDt(e,t){let n=nC.default.coerce(e),r=nC.default.coerce(t);if(!n||!r)return!1;return nC.default.gte(n,r)}async function AEe(){try{let{stdout:t,exitCode:n,stderr:r}=await T(["git-annex","version"]);if(n!==0)return console.warn("git-annex version returned non-zero exit code:",n),console.warn("stderr:",r),{installed:!1,minVersion:"10.0",error:`Version check failed: ${r.trim()}`};let o=t.match(/version:\s*(\d+\.\d+)/),s=o?o[1]:void 0;if(!s)console.warn("Could not parse git-annex version from output:",t);return{installed:!0,version:s,minVersion:"10.0",compatible:s?XDt(s,"10.0"):void 0}}catch(t){let n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found"))return console.info("git-annex not found in PATH"),{installed:!1,minVersion:"10.0"};return console.error("Error checking git-annex installation:",n),{installed:!1,minVersion:"10.0",error:n}}}async function ZDt(){if(process.env.GH_TOKEN)return{accessible:!0,username:"token-auth",useHttps:!0};try{let{stdout:e,stderr:t}=await T(["ssh","-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=10","git@github.com"]),n=e+t,r=n.match(/Hi ([^!]+)!/);if(r)return{accessible:!0,username:r[1]};if(n.includes("Permission denied"))return{accessible:!1};return{accessible:n.includes("successfully authenticated")}}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes("ENOENT")||t.includes("not found"))console.info("SSH command not found");else console.error("Error checking GitHub SSH access:",t);return{accessible:!1}}}function OEe(){let e=process.platform;if(e==="darwin")return"brew install git-annex";if(e==="linux")return"apt install git-annex (Debian/Ubuntu)";return"See https://git-annex.branchable.com/install/"}async function rC(){let[e,t]=await Promise.all([AEe(),ZDt()]),n=[];if(!e.installed)n.push(`git-annex is not installed. Install: ${OEe()}`);else if(e.compatible===!1)n.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);if(!t.accessible){if(!(await im()).token)n.push("GitHub authentication not configured. Run 'gh auth login' to authenticate.")}return{gitAnnex:e,githubSSH:t,allPassed:n.length===0,errors:n}}async function ax(){let e=await AEe(),t=[];if(!e.installed)t.push(`git-annex is not installed. Install: ${OEe()}`);else if(e.compatible===!1)t.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);return{gitAnnex:e,allPassed:t.length===0,errors:t}}zy();Le();Js();sn();var QDt=[{oldPath:"publish",newPath:"dataset publish"},{oldPath:"withdraw",newPath:"dataset withdraw"},{oldPath:"restore",newPath:"dataset restore"},{oldPath:"ci",newPath:"dataset ci"},{oldPath:"ci check",newPath:"dataset ci check"},{oldPath:"ci add",newPath:"dataset ci add"},{oldPath:"ci validate",newPath:"dataset ci validate"},{oldPath:"ci sync",newPath:"dataset ci sync"},{oldPath:"doi",newPath:"dataset doi"},{oldPath:"doi create",newPath:"dataset doi create"},{oldPath:"doi info",newPath:"dataset doi info"},{oldPath:"doi update",newPath:"dataset doi update"},{oldPath:"doi enrich",newPath:"dataset doi enrich"},{oldPath:"exemplar",newPath:"dataset exemplar"},{oldPath:"exemplar create",newPath:"dataset exemplar create"},{oldPath:"exemplar status",newPath:"dataset exemplar status"},{oldPath:"exemplar remint-dois",newPath:"dataset exemplar remint-dois"},{oldPath:"doctor scan",newPath:"dataset doctor scan"},{oldPath:"doctor fix",newPath:"dataset doctor fix"},{oldPath:"regenerate-iam",retired:"S3 access uses backend-scoped credentials, so there are no per-user IAM keys to regenerate."},{oldPath:"make-public",retired:"a bare visibility flip that skipped the publication request and screen no longer exists; use 'nemar admin dataset publish'."},{oldPath:"delete-dataset",newPath:"dataset delete"},{oldPath:"bulk-delete",newPath:"dataset bulk-delete"},{oldPath:"reindex",newPath:"dataset reindex"},{oldPath:"s3",newPath:"dataset s3"},{oldPath:"s3 lock",newPath:"dataset s3 lock"},{oldPath:"s3 credential-check",newPath:"dataset s3 credential-check"},{oldPath:"s3 regenerate-iam",retired:"S3 access uses backend-scoped credentials, so there are no per-user IAM keys to regenerate."},{oldPath:"approve",newPath:"users approve"},{oldPath:"revoke",newPath:"users revoke"},{oldPath:"role",newPath:"users role"},{oldPath:"verify",newPath:"users verify"},{oldPath:"kind",newPath:"users kind"},{oldPath:"keys",newPath:"users keys"},{oldPath:"keys create",newPath:"users keys create"},{oldPath:"keys list",newPath:"users keys list"},{oldPath:"keys revoke",newPath:"users keys revoke"},{oldPath:"email-preferences",newPath:"users email-preferences"},{oldPath:"email-preferences show",newPath:"users email-preferences show"},{oldPath:"email-preferences update",newPath:"users email-preferences update"},{oldPath:"duplicates",newPath:"users duplicates"},{oldPath:"backfill-usernames",newPath:"users backfill-usernames"},{oldPath:"doctor",newPath:"dataset doctor"},{oldPath:"doctor kinds",newPath:"users kind-check"},{oldPath:"backfill-names",retired:`names now come from ORCID at sign-up, and the backfill has nothing left to fill. ${Sn("cli.admin.owner_name_missing.fix")}`},{oldPath:"revert",newPath:"rework revert"},{oldPath:"annex-normalize",newPath:"rework annex normalize"},{oldPath:"fleet annex-policy",newPath:"rework annex policy"},{oldPath:"fleet key-registration",newPath:"rework annex key-registration"},{oldPath:"fleet content-recovery",newPath:"rework annex content-recovery"},{oldPath:"recover",newPath:"rework recover"},{oldPath:"recover status",newPath:"rework recover status"},{oldPath:"import-openneuro",newPath:"import openneuro"},{oldPath:"import-issue-triage",newPath:"import triage"},{oldPath:"import-coverage",newPath:"import coverage"},{oldPath:"import-weekly",newPath:"import weekly"},{oldPath:"upstream-status",newPath:"repull upstream-status"},{oldPath:"upstream-backfill",newPath:"repull upstream-backfill"},{oldPath:"hed-sweep",newPath:"fleet sweep hed"},{oldPath:"recording-stats-sweep",newPath:"fleet sweep recording-stats"},{oldPath:"signal-defaults-sweep",newPath:"fleet sweep signal-defaults"},{oldPath:"data-integrity-sweep",newPath:"fleet sweep data-integrity"},{oldPath:"zarr-fidelity-sweep",newPath:"fleet sweep zarr-fidelity"},{oldPath:"anonymity-sweep",newPath:"fleet sweep anonymity"},{oldPath:"availability-report",newPath:"fleet sweep availability"},{oldPath:"summary",newPath:"fleet summary"},{oldPath:"summary check",newPath:"fleet summary check"},{oldPath:"zarr-catalog",newPath:"fleet zarr-catalog"},{oldPath:"zarr-catalog publish",newPath:"fleet zarr-catalog publish"},{oldPath:"e2e-test",newPath:"fleet e2e-test"}],lL=new WeakMap;function TEe(e){return lL.has(e)}function PEe(e,t){let n=e,r=t.indexOf("--")<0?t.length:t.indexOf("--");for(let o=0;o<r;o++){if(t[o].startsWith("-"))continue;if(t[o]==="help"&&n.commands.length>0&&!cL(n,"help"))continue;let s=cL(n,t[o]);if(!s)return;let i=lL.get(s);if(i)i(t.slice(o+1,r));n=s}}function eCt(e,t){return`'${e}' moved to '${t}'. Nothing was run.`}function tCt(e,t){return`'${e}' was retired: ${t} Nothing was run.`}function nCt(e,t){let n=`${t} ${oC(e.oldPath).join(" ")}`;if("retired"in e)return tCt(n,e.retired);return eCt(n,`${t} ${oC(e.newPath).join(" ")}`)}function oC(e){let t=e.trim().split(/\s+/);if(t.length===0||t[0]==="")throw Error("moved-commands: empty path");return t}function rCt(e){let t=[];for(let n=e;n;n=n.parent)t.unshift(n.name());return t.join(" ")}function cL(e,t){return e.commands.find((n)=>n.name()===t||n.aliases().includes(t))}function NEe(e,t=QDt){let n=new Map;for(let o of t){let s=oC(o.oldPath).join(" ");if("retired"in o){if(!/\S.*\.$/.test(o.retired))throw Error(`moved-commands: '${s}' needs a retirement reason ending in a period`)}else oC(o.newPath);if(n.has(s))throw Error(`moved-commands: duplicate old path '${s}'`);n.set(s,o)}let r=new Map;for(let o of n.keys()){let s=o.split(" "),i=e,a=0;for(;a<s.length;a++){let l=cL(i,s[a]);if(!l)break;i=l}if(a===s.length)throw Error(`moved-commands: '${o}' is a row but still a live command`);let c=s.slice(0,a+1).join(" ");if(!n.has(c))throw Error(`moved-commands: '${o}' sits under '${c}', which is gone; add a row for '${c}'`);r.set(c,{parent:i,name:s[a]})}for(let[o,{parent:s,name:i}]of r){let a=o.split(" "),c=(d)=>{let p=n.get(o);for(let f=1;f<=d.length;f++){let m=n.get([...a,...d.slice(0,f)].join(" "));if(m)p=m}console.error(u.red(nCt(p,rCt(e)))),ce(),process.exit(1)},l=s.command(i,{hidden:!0}).helpOption(!1).allowUnknownOption().allowExcessArguments().action((d,p)=>c(p.args));lL.set(l,c)}}import{readFileSync as oCt}from"fs";var sCt=/^on\d{6}$/;function iCt(e){if(!Array.isArray(e))throw Error("Recover-datasets file must be a JSON array");return e.map((t,n)=>{if(typeof t!=="object"||t===null)throw Error(`Recover-datasets entry ${n} is not an object`);let{dataset_id:r,note:o}=t;if(typeof r!=="string"||!sCt.test(r))throw Error(`Recover-datasets entry ${n}: dataset_id "${r}" is not valid`);if(typeof o!=="string"||o.length===0)throw Error(`Recover-datasets entry ${n} (${r}): note is required`);return{dataset_id:r,note:o}})}function uL(e){let t;try{t=JSON.parse(oCt(e,"utf-8"))}catch(n){throw Error(`Failed to read/parse recover-datasets file at ${e}: ${n instanceof Error?n.message:String(n)}`)}return iCt(t)}function IEe(e,t,n){let r=new Set(t.map((o)=>o.dataset_id));for(let o of e)if(!r.has(o)&&!n.force)return{error:`${o} is not on the checked-in recover-datasets list. Pass --force to override.`};return{targets:e}}function FEe(e,t){let n=new Set(e),r=new Map;for(let s of t)if(n.has(s.dataset_id)&&s.source_id)r.set(s.dataset_id,s.source_id);let o=e.filter((s)=>!r.has(s));return{sourceByTarget:r,missingSource:o}}import{readFileSync as aCt}from"fs";var MEe=new Set(["upstream_403","no_source","recovered"]),cCt=/^(nm|xx|on)\d{6}$/;function lCt(e){if(!Array.isArray(e))throw Error("Withdrawn-datasets file must be a JSON array");return e.map((t,n)=>{if(typeof t!=="object"||t===null)throw Error(`Withdrawn-datasets entry ${n} is not an object`);let{dataset_id:r,reason:o,note:s,withdrawn:i,data_available:a,data_keys_missing:c,data_keys_total:l}=t;if(typeof r!=="string"||!cCt.test(r))throw Error(`Withdrawn-datasets entry ${n}: dataset_id "${r}" is not valid`);if(typeof o!=="string"||!MEe.has(o))throw Error(`Withdrawn-datasets entry ${n} (${r}): reason "${o}" must be one of ${[...MEe].join(", ")}`);if(typeof s!=="string"||s.length===0)throw Error(`Withdrawn-datasets entry ${n} (${r}): note is required`);if(i!==void 0&&typeof i!=="boolean")throw Error(`Withdrawn-datasets entry ${n} (${r}): withdrawn must be a boolean`);if(a!==void 0&&(typeof a!=="number"||a<0||a>1))throw Error(`Withdrawn-datasets entry ${n} (${r}): data_available must be between 0 and 1`);let d=i??!0;if(o==="recovered"&&d)throw Error(`Withdrawn-datasets entry ${n} (${r}): reason "recovered" means the content came back, so withdrawn must be false`);let p=typeof c==="number",f=typeof l==="number";if(p!==f)throw Error(`Withdrawn-datasets entry ${n} (${r}): data_keys_missing and data_keys_total must be given together`);if(p&&f){if(c<0||l<0)throw Error(`Withdrawn-datasets entry ${n} (${r}): key counts cannot be negative`);if(c>l)throw Error(`Withdrawn-datasets entry ${n} (${r}): ${c} missing of ${l} total is not possible`);if(typeof a==="number"&&l>0){let m=(l-c)/l;if(Math.abs(m-a)>0.001)throw Error(`Withdrawn-datasets entry ${n} (${r}): data_available ${a} disagrees with ${c} missing of ${l} (${m.toFixed(4)})`)}}return{dataset_id:r,reason:o,note:s,withdrawn:d,...typeof a==="number"?{data_available:a}:{},...p?{data_keys_missing:c}:{},...f?{data_keys_total:l}:{}}})}function dL(e){let t;try{t=JSON.parse(aCt(e,"utf-8"))}catch(n){throw Error(`Failed to read/parse withdrawn-datasets file at ${e}: ${n instanceof Error?n.message:String(n)}`)}return lCt(t)}function jEe(e,t,n){let r=new Map(t.map((s)=>[s.dataset_id,s])),o=[];for(let s of e){let i=r.get(s);if(!i&&!n.force)return{error:`${s} is not on the checked-in withdrawn-datasets list. Pass --force to override.`};if(i?.withdrawn===!1&&!n.force)return{error:`${s} was reinstated (${i.reason}); its entry is a record, not a target. Pass --force to withdraw it again.`};let a=n.reason||i?.reason;if(!a)return{error:`${s}: no --reason given and it has no default entry in the list.`};o.push({datasetId:s,reason:a})}return{targets:o}}function pL(e){return e.filter((t)=>t.withdrawn!==!1)}import{randomUUID as XSe}from"crypto";import{readFileSync as sAt,statSync as iAt}from"fs";pa();Rd();mr();Mf();Rd();mn();var LEe=O({ok:He(!0),state:b().nullable(),outcome:b(),cancelled:Q().optional()}).passthrough(),amn=O({links:Y(O({path:b(),size:D().int().nonnegative(),url:b()}).passthrough()),expires_at:b(),total:D().int().nonnegative(),truncated:Q(),next_after:b().nullable()}).passthrough(),cmn=O({ok:He(!0),snapshots:D().int().nonnegative(),sacct_rows:D().int().nonnegative(),matched:D().int().nonnegative(),settled:D().int().nonnegative(),mismatched:D().int().nonnegative(),unmatched:D().int().nonnegative(),skipped:D().int().nonnegative(),truncated:He(!0).optional(),settlement_failed:He(!0).optional()}).passthrough();Zk();Yk();gr();Ue();async function UEe(){return F("/admin/compute/policy",{},!0,gF)}async function qEe(e,t,n=!1){return F("/admin/compute/policy",{method:"PUT",body:JSON.stringify({policy:e,...t===void 0?{}:{note:t},...n?{force_partner_off:!0}:{}})},!0,gF)}async function BEe(e={}){let t=new URLSearchParams;if(e.holderKind)t.set("holder_kind",e.holderKind);if(e.after!==void 0)t.set("after",String(e.after));if(e.limit!==void 0)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/compute/pools${n}`,{},!0,cse)}async function HEe(e){return F(`/admin/compute/pools/by-id/${e}`,{},!0,lse)}function sC(e,t,n){return F(e,{method:"POST",body:JSON.stringify(t),headers:{"Idempotency-Key":n}},!0,use)}async function zEe(e,t,n){return sC(`/admin/compute/pools/by-id/${e}/grant`,t,n)}async function GEe(e,t,n){return sC(`/admin/compute/pools/by-id/${e}/adjust`,t,n)}async function VEe(e,t,n){return sC(`/admin/compute/pools/platform/${encodeURIComponent(e)}/grant`,t,n)}async function WEe(e,t,n){return sC(`/admin/compute/pools/platform/${encodeURIComponent(e)}/adjust`,t,n)}async function KEe(){return F("/admin/compute/status",{},!0,dse)}async function JEe(e){return F(`/admin/compute/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST"},!0,bF)}async function YEe(e){return F(`/admin/compute/jobs/${encodeURIComponent(e)}/advance`,{method:"POST"},!0,bF)}async function XEe(e,t,n=!1){return F(`/admin/compute/jobs/${encodeURIComponent(e)}/move-charge`,{method:"POST",body:JSON.stringify({to_account_id:t,...n?{confirm_unproven_owner:!0}:{}})},!0,Cse)}async function ZEe(e){return F("/admin/compute/pipeline/run",{method:"POST",body:JSON.stringify(e)},!0,fse)}async function QEe(e={}){let t=new URLSearchParams;if(e.recipe)t.set("recipe",e.recipe);if(e.dataset)t.set("dataset",e.dataset);if(e.state)t.set("state",e.state);if(e.before!==void 0)t.set("before",String(e.before));if(e.limit!==void 0)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/compute/pipeline/status${n}`,{},!0,mse)}var lm=(e)=>e.toString()?`?${e.toString()}`:"";async function eSe(e={}){let t=new URLSearchParams;if(e.flag)t.set("flag",e.flag);if(e.state)t.set("state",e.state);if(e.account!==void 0)t.set("account",String(e.account));if(e.executor)t.set("executor",e.executor);if(e.accounting)t.set("accounting",e.accounting);if(e.runner)t.set("runner",e.runner);if(e.limit!==void 0)t.set("limit",String(e.limit));if(e.after!==void 0)t.set("after",String(e.after));return F(`/admin/compute/jobs${lm(t)}`,{},!0,hse)}async function tSe(e){let t=new URLSearchParams({unmatched:"1"});if(e!==void 0)t.set("limit",String(e));return F(`/admin/compute/jobs${lm(t)}`,{},!0,gse)}async function nSe(e){return F(`/admin/compute/records/${encodeURIComponent(e)}`,{},!0,yse)}async function rSe(e,t,n){return F(`/admin/compute/records/${encodeURIComponent(e)}/read`,{method:"POST",body:JSON.stringify({name:t,reason:n})},!0,bse)}async function oSe(e){let t=new URLSearchParams({account:String(e.account),from:e.from,to:e.to});return F(`/admin/compute/report${lm(t)}`,{},!0,wse)}async function sSe(e){let t=new URLSearchParams({quarter:e});return F(`/admin/compute/access-report${lm(t)}`,{},!0,Ese)}async function fL(e={}){let t=new URLSearchParams;if(e.scope)t.set("scope",e.scope);if(e.ref)t.set("ref",e.ref);return F(`/admin/compute/holds${lm(t)}`,{},!0,kse)}async function iSe(e){return F("/admin/compute/holds",{method:"POST",body:JSON.stringify(e)},!0,SF)}async function aSe(e){return F(`/admin/compute/holds/${e}`,{method:"DELETE"},!0,SF)}async function cSe(e={}){let t=new URLSearchParams;if(e.state)t.set("state",e.state);if(e.limit!==void 0)t.set("limit",String(e.limit));if(e.after)t.set("after",e.after);return F(`/admin/compute/access-reports${lm(t)}`,{},!0,Rse)}async function lSe(e){return F(`/admin/compute/access-reports/${encodeURIComponent(e)}/requeue`,{method:"POST",body:JSON.stringify({confirmed_not_recorded:!0})},!0,$se)}async function uSe(){return F("/admin/compute/observer-runs",{method:"POST"},!0,Dse)}function Sp(e){if(!(e instanceof L))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let{code:n,blocked_by:r,reason:o}=t;if(typeof n!=="string")return;let s=Array.isArray(r)?r.filter((i)=>typeof i==="string"):[];return{code:n,blockedBy:s,...typeof o==="string"?{reason:o}:{}}}async function dSe(e){return F("/users/me/compute-access/request",{method:"POST",body:JSON.stringify(e)},!0,Ose)}async function iC(){return F("/compute/me",{},!0,Mse)}async function pSe(e={}){let t=new URLSearchParams;if(e.state)t.set("state",e.state);if(e.limit!==void 0)t.set("limit",String(e.limit));if(e.after)t.set("after",e.after);return F(`/compute/me/jobs${lm(t)}`,{},!0,Lse)}async function aC(e,t={}){return F(`/compute/me/jobs/${encodeURIComponent(e)}`,t.signal?{signal:t.signal}:{},!0,Use,"json",t.timeoutMs)}async function fSe(e,t){return F("/compute/jobs",{method:"POST",body:JSON.stringify(e),headers:{[Hse]:t}},!0,Gse)}async function mSe(e,t){return F(`/compute/jobs/${encodeURIComponent(e)}/finalize`,{method:"POST",body:JSON.stringify(t)},!0,Vse)}async function hSe(e){let t=await F(`/compute/jobs/${encodeURIComponent(e)}/logs`,{},!0,void 0,"text");return{text:t.text,truncated:t.headers.get(zse)?.toLowerCase()==="true"}}var gSe=(e)=>e===void 0?"":`?${new URLSearchParams({after:e}).toString()}`;async function ySe(e,t){return F(`/compute/jobs/${encodeURIComponent(e)}/results${gSe(t)}`,{},!0,CF)}async function bSe(e,t){return F(`/compute/jobs/${encodeURIComponent(e)}/results/renew${gSe(t)}`,{method:"POST"},!0,CF)}async function wSe(e){return F(`/compute/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST"},!0,LEe)}var Ky=["none","requested","active","suspended","denied","revoked"];var uCt={none:["requested"],requested:["active","denied"],active:["suspended","revoked"],suspended:["active","revoked"],denied:["active"],revoked:["active"]};function cC(e,t){return uCt[e].includes(t)}var _Se=["grant","deny","suspend","revoke"];var bmn={grant:Ky.filter((e)=>cC(e,"active")),deny:Ky.filter((e)=>cC(e,"denied")),suspend:Ky.filter((e)=>cC(e,"suspended")),revoke:Ky.filter((e)=>cC(e,"revoked"))};Mf();mr();Mf();gr();Ue();async function xSe(e={}){let t=new URLSearchParams;if(e.state!==void 0)t.set("state",e.state);if(e.limit!==void 0)t.set("limit",String(e.limit));if(e.after!==void 0)t.set("after",String(e.after));let n=t.size>0?`?${t.toString()}`:"";return F(`/admin/compute/access${n}`,{},!0,Nse)}async function vSe(e,t,n,r){let o={};if(n!==void 0)o.reason=n;if(r!==void 0)o.notice=r.trim();let s="id"in t?`by-id/${t.id}`:encodeURIComponent(t.username);return F(`/admin/compute/access/${e}/${s}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},!0,Ise)}var cu=(e)=>console.log(e),Qc=(e)=>k(e??""),mL=Ky.filter((e)=>e!=="none");function SSe(e){let t=[e.given_name,e.family_name].filter(Boolean).join(" ");return`${e.username?Qc(e.username):`(no username, id ${e.id})`}${t?` ${Qc(t)}`:""}`}function dCt(e){let t=[e.affiliation,e.city,e.country].filter(Boolean).map(Qc).join(", "),n=e.compute_access_requested_at?` asked ${Qc(e.compute_access_requested_at)}`:"";return`${String(e.id).padEnd(7)} ${Qc(e.compute_access).padEnd(10)} ${SSe(e)}${t?` [${t}]`:""}${n}`}var pCt=`
|
|
260
260
|
Description:
|
|
261
261
|
Lists the accounts that have a compute-access state, oldest account first: who asked, where they
|
|
262
262
|
work, what for, and what is decided. --state narrows it (requested is the queue to answer; the others
|
|
@@ -2294,7 +2294,7 @@ Nothing was changed. Re-run with --apply to fix.`))}catch(l){c.fail("Dry run fai
|
|
|
2294
2294
|
${u.bold(e)}: ${u.green(`${i.fixed} fixed`)}, ${i.skipped} skipped, ${i.failed>0?u.red(`${i.failed} failed`):"0 failed"}${c}`)}if(i.failed>0)process.exit(1)});async function LBt(e,t,n){let r={fixed:0,skipped:0,failed:0,resolved:0},o=[];for(let[s,i]of e.entries()){let a;try{let c=await t(i,s);if(a=c.results,a.length===0)r.resolved++;else r.fixed+=c.fixed,r.skipped+=c.skipped,r.failed+=c.failed}catch(c){r.failed++,a=[{dataset_id:i,status:"failed",message:W(c)}]}o.push(...a),n?.onDataset?.(i,a)}return{totals:r,results:o}}Qi.command("kind-check").description("Check that operational accounts carry their expected account kind (read-only)").action(async()=>{if(!Oe())return;let e=Object.entries(Lre),t=A(`Checking ${e.length} operational account kind(s)...`).start(),n=[],r=[];try{for(let[o,s]of e)try{let{user:i}=await hD(o);if(i.account_kind!==s)n.push(`${o}: expected '${s}', found '${i.account_kind??"unknown"}'`)}catch(i){if(i instanceof L&&i.statusCode===404)r.push(o);else throw i}if(t.stop(),n.length===0&&r.length===0){console.log(u.green(`All ${e.length} operational account(s) carry their expected kind.`));return}for(let o of n)console.log(` ${u.yellow("kind mismatch")} ${o}`);for(let o of r)console.log(` ${u.yellow("account absent")} ${o}`);console.log(u.yellow(`
|
|
2295
2295
|
${n.length+r.length} finding(s). Fix a mismatch with \`nemar admin users kind <username> <kind>\`.`))}catch(o){t.fail("Account kind check failed"),console.error(u.red(W(o))),process.exit(1)}});mi.addCommand(bB);var wB=new ne("email-preferences").description("Manage email notification preferences"),kNe=[{key:"user_approval",label:"User approval notifications"},{key:"publication_request",label:"Publication request notifications"},{key:"dataset_anonymity",label:"Anonymity sweep findings"},{key:"identifier_sweep",label:"Identifier sweep weekly report"},{key:"support_tickets",label:"Support tickets assigned to you"},{key:"compute_requests",label:"Compute access requests"}];wB.command("show").description("Show email notification preferences").option("--user <username>","(owner or admin) show another user's preferences; an admin sees the community categories only").action(async(e)=>{if(!et())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let t=A("Fetching email preferences...").start();try{let n=await Pwe(e.user),r=n.username?`${n.username}'s`:"Your";t.succeed(`${r} email notification preferences:`),console.log();let o=(s)=>s?u.green("enabled"):u.dim("disabled");for(let s of kNe){let i=n[s.key];if(i===void 0)continue;console.log(` ${s.label.padEnd(40)} ${o(i)}`)}for(let s of Es)console.log(` ${lc(s).padEnd(40)} ${o(n[s])}`);console.log(` ${lc("recall").padEnd(40)} ${u.green("always on")}`),console.log(u.dim(` ${Eg()}`)),console.log(),console.log(u.dim(" Use 'nemar admin users email-preferences update' to change settings."))}catch(n){t.fail("Failed to fetch preferences"),console.error(u.red(W(n)))}});wB.command("update").description("Update email notification preferences").option("--user-approval <bool>","Enable/disable user approval notifications").option("--publication-request <bool>","Enable/disable publication request notifications").option("--news <bool>","Enable/disable news emails").option("--rfcs <bool>","Enable/disable requests-for-comments emails").option("--maintenance <bool>","Enable/disable maintenance emails").addOption(new lo("--announcements <bool>","Retired: use --news, --rfcs and --maintenance").hideHelp()).option("--dataset-anonymity <bool>","Enable/disable anonymity sweep findings").option("--identifier-sweep <bool>","Enable/disable the identifier sweep weekly report").option("--support-tickets <bool>","Enable/disable support ticket notifications").option("--compute-requests <bool>","Enable/disable compute access request notifications").option("--all <bool>","Enable/disable all notifications (recalls are always on)").option("--user <username>","(owner or admin) update another user's preferences; an admin may change news, rfcs and maintenance only").action(async(e)=>{if(!et())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.announcements!==void 0)console.error(u.red("--announcements was split into three categories. Use --news, --rfcs and --maintenance instead.")),process.exit(1);function t(o){if(o===void 0)return;let s=o.toLowerCase();if(s==="true"||s==="1"||s==="on"||s==="yes")return!0;if(s==="false"||s==="0"||s==="off"||s==="no")return!1;console.error(u.red(`Invalid boolean value: "${o}". Use true/false, on/off, yes/no.`)),process.exit(1)}let n={};if(e.all!==void 0){let o=t(e.all);n.user_approval=o,n.publication_request=o,n.dataset_anonymity=o,n.identifier_sweep=o,n.support_tickets=o,n.compute_requests=o;for(let s of Es)n[s]=o}else{let o={user_approval:t(e.userApproval),publication_request:t(e.publicationRequest),news:t(e.news),rfcs:t(e.rfcs),maintenance:t(e.maintenance),dataset_anonymity:t(e.datasetAnonymity),identifier_sweep:t(e.identifierSweep),support_tickets:t(e.supportTickets),compute_requests:t(e.computeRequests)};if(Object.values(o).every((s)=>s===void 0))console.error(u.red("No preferences specified.")),console.log(" --user-approval <bool> User approval notifications"),console.log(" --publication-request <bool> Publication request notifications"),console.log(" --news <bool> News emails"),console.log(" --rfcs <bool> Requests-for-comments emails"),console.log(" --maintenance <bool> Maintenance emails"),console.log(" --dataset-anonymity <bool> Anonymity sweep findings"),console.log(" --identifier-sweep <bool> Identifier sweep weekly report"),console.log(" --support-tickets <bool> Support ticket notifications"),console.log(" --compute-requests <bool> Compute access request notifications"),console.log(" --all <bool> All notifications"),process.exit(1);for(let[s,i]of Object.entries(o))if(i!==void 0)n[s]=i}let r=A("Updating email preferences...").start();try{let o=await Nwe(n,e.user),s=o.username?`${o.username}'s`:"Your";r.succeed(`${s} email preferences updated:`),console.log();let i=(c)=>c?u.green("enabled"):u.dim("disabled"),a={user_approval:"User approval: ",publication_request:"Publication request: ",dataset_anonymity:"Anonymity findings: ",identifier_sweep:"Identifier sweep: ",support_tickets:"Support tickets: ",compute_requests:"Compute requests: "};for(let c of kNe){let l=o[c.key];if(l===void 0)continue;console.log(` ${a[c.key]} ${i(l)}`)}for(let c of Es)console.log(` ${`${lc(c)}:`.padEnd(22)} ${i(o[c])}`);console.log(` ${`${lc("recall")}:`.padEnd(22)} ${u.green("always on")}`)}catch(o){r.fail("Failed to update preferences"),console.error(u.red(W(o)))}});Qi.addCommand(wB);var PO=new ne("notice").description("Manage system notices displayed to CLI users");PO.command("list").description("List all notices (including expired)").action(async()=>{if(!et())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let e=A("Fetching notices...").start();try{let{notices:t}=await F_e();if(t.length===0){e.succeed("No notices found.");return}e.succeed(`${t.length} notice(s):`),console.log();for(let n of t){let o={critical:u.red.bold,warning:u.yellow,maintenance:u.magenta,announcement:u.green,tip:u.blue,info:u.blue}[n.level]||u.white,s=n.expires_at&&new Date(n.expires_at)<new Date?u.dim(" (expired)"):"";if(console.log(` ${u.dim(`#${n.id}`)} ${o(`[${n.level.toUpperCase()}]`)} ${u.dim(`scope:${n.scope}`)}${s}`),console.log(` ${n.message}`),console.log(` ${u.dim(`Created: ${n.created_at}`)}`),n.expires_at)console.log(` ${u.dim(`Expires: ${n.expires_at}`)}`);console.log()}}catch(t){Bt(t,e,"Failed to fetch notices")}});PO.command("set").description("Create a new system notice").requiredOption("-m, --message <text>","Notice message text").option("-l, --level <level>","Notice level: tip, announcement, maintenance, warning, critical","tip").option("-s, --scope <scope>","Target scope: all, admins, members","all").option("-e, --expires <datetime>","Expiry datetime (ISO 8601)").action(async(e)=>{if(!et())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(![...A6,"info"].includes(e.level))console.error(u.red(`Invalid level: ${e.level}. Use ${A6.join(", ")}.`)),process.exit(1);if(!["all","admins","members"].includes(e.scope))console.error(u.red(`Invalid scope: ${e.scope}. Use all, admins, or members.`)),process.exit(1);let t=A("Creating notice...").start();try{let n=await M_e({message:e.message,level:e.level,scope:e.scope,expires_at:e.expires});if(t.succeed(`Notice created (ID: ${n.id})`),console.log(` Level: ${n.level}`),console.log(` Scope: ${n.scope}`),console.log(` Message: ${n.message}`),n.expires_at)console.log(` Expires: ${n.expires_at}`)}catch(n){Bt(n,t,"Failed to create notice")}});PO.command("clear <id>").description("Delete a notice by ID").option(lt,xt).option(Ct,kt).action(async(e,t)=>{if(!et())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let n=Number.parseInt(e,10);if(Number.isNaN(n))console.error(u.red("Invalid notice ID")),process.exit(1);if(await De(`Delete notice #${n}?`,t,!1)!=="confirmed")return;let o=A("Deleting notice...").start();try{await j_e(n),o.succeed(`Notice #${n} deleted`)}catch(s){Bt(s,o,"Failed to delete notice")}});Co.addCommand(PO);function UBt(e){let t=[`${u.bold(`Announcement ${e.id}`)} ${u.cyan(e.status)}`,` Subject: ${e.subject}`,` To: ${e.recipient_group}`];if(e.category)t.push(` Category: ${e.category}`);if(e.recall_reference)t.push(` Recall reference: ${e.recall_reference}`);if(t.push(` Sent at: ${e.sent_at}`),e.status==="sent")t.push(` Delivered: ${e.queued_count>0?e.delivered_count:"n/a (sent inline)"}`),t.push(` Failed: ${e.failure_count}`);else{t.push(` Queued: ${e.queued_count}`),t.push(` Delivered: ${e.delivered_count}`),t.push(` Failed: ${e.failure_count}`),t.push(` Unconfirmed: ${e.unknown_count} (not retried; the provider never confirmed them)`);let n=e.skipped_count??0;if(n>0)t.push(` Skipped: ${n} (opted out or account changed after the send was queued)`);let r=e.queued_count-e.delivered_count-e.failure_count-e.unknown_count-n;if(r>0)t.push(` Pending: ${r}`)}if(e.failed_recipients.length>0){t.push(" Failed addresses are shown redacted and may not be unique:");for(let n of e.failed_recipients)t.push(u.red(` Failed: ${n}`))}return t}function qBt(e){let t=[];if(e.counts)t.push(` Audience by group: ${Object.entries(e.counts).map(([n,r])=>`${n} ${r}`).join(", ")}`);if(e.deliverable_count!==void 0&&e.deliverable_count!==e.recipient_count)t.push(u.yellow(` ${e.deliverable_count} of ${e.recipient_count} would be delivered; the rest are withheld by the non-production delivery fence`));if(e.would_refuse==="duplicate_send")t.push(u.yellow(` A real send would be refused as a repeat of announcement ${e.duplicate_of} (use --allow-repeat to send anyway)`));for(let n of e.blockers??[])t.push(u.red(` A real send would be refused now: ${n}`));if(e.recipients){t.push("");for(let n of e.recipients)t.push(` ${n}`)}else if(e.sample&&e.sample.length>0)t.push(` Sample (redacted): ${e.sample.join(", ")}`),t.push(" Addresses are listed in production only.");return t}async function BBt(e,t){if(t!==void 0)return t.trim()===e?e:void 0;if(!process.stdin.isTTY)return;try{let{typed:n}=await Pe.prompt([{type:"input",name:"typed",message:`A recall reaches every account in the selected group, ignores email preferences and cannot be undone. Type the reference (${e}) to send it:`}]);return typeof n==="string"&&n.trim()===e?e:void 0}catch{return}}function HBt(e){if(e.notice_id!==void 0)return[u.green(` Site notice #${e.notice_id} published. Clear it when the recall is resolved: nemar admin notice clear ${e.notice_id}`)];if(e.notice_skipped==="canary")return[u.yellow(" No site notice yet: this send went to part of the audience. The send to all publishes it.")];if(e.notice_skipped==="nothing_queued")return[u.yellow(" No site notice was published because nothing was queued. Run the recall again; it publishes the notice once it goes out.")];return[u.yellow.bold(" OWNER STEP: a recall also needs a public site notice, and none was published."),u.yellow(' Publish one now: nemar admin notice set --level critical --message "NEMAR recall: <subject> (reference: <reference>). Check your email for what to do."')]}Co.command("notify").description("Send a categorized email to a group, or an email to a single user").option("--to <group>","Recipient group: all, admins, members").option("--category <category>",`Category of a group send (required with --to): ${Uw.join(", ")}. Recipients who turned it off are skipped; a recall (owner only) ignores that`).option("--recall-ref <reference>","What a recall is about: a dataset id with optional version (nm000104@v1.2.0) or a nemarOrg issue, pull request or security advisory URL").option("--confirm-recall <reference>","Type the recall reference again to confirm sending a recall (--yes does not replace it)").option("--allow-repeat","Send even if the same category, subject and group went out in the last 24 hours").option("--user <username>","Send to a single user by username (direct contact, no category)").option("--subject <text>","Email subject line").option("--body <text>","Email body (markdown)").option("--body-file <path>","Read email body from file (markdown)").option("--dry-run","Preview recipients without sending").option("--status <id>","Show the progress of a queued announcement by its ID").option("--json","Output raw JSON (with --status)").option(lt,xt).option(Ct,kt).action(async(e)=>{if(!et())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.status!==void 0){let p=Number(e.status);if(!Number.isInteger(p)||p<1)console.error(u.red(`Invalid announcement ID: ${e.status}`)),process.exit(1);let f=e.json?null:A("Fetching announcement status...").start();try{let m=await Iwe(p);if(e.json){console.log(JSON.stringify(m,null,2));return}f?.stop();for(let h of UBt(m))console.log(h)}catch(m){Bt(m,f??A(),"Failed to fetch announcement status")}return}if(!e.subject)console.error(u.red("Email subject required. Use --subject.")),process.exit(1);let t=e.subject;if(e.to&&e.user)console.error(u.red("--to and --user are mutually exclusive. Provide exactly one.")),process.exit(1);if(!e.to&&!e.user)console.error(u.red("Provide either --to <group> or --user <username>.")),process.exit(1);if(e.to&&!["all","admins","members"].includes(e.to))console.error(u.red(`Invalid group: ${e.to}. Use all, admins, or members.`)),process.exit(1);if(e.user){if(e.category||e.recallRef||e.confirmRecall||e.allowRepeat)console.error(u.red("--user is direct contact and takes no --category, --recall-ref, --confirm-recall or --allow-repeat.")),process.exit(1)}else if(!e.category)console.error(u.red(`A group send needs --category <${Uw.join("|")}>. Use --user for direct contact.`)),process.exit(1);else if(!Soe(e.category))console.error(u.red(`Invalid category: ${e.category}. Use ${Uw.join(", ")}.`)),process.exit(1);let n=e.category===Pf;if(!n&&(e.recallRef||e.confirmRecall))console.error(u.red("--recall-ref and --confirm-recall belong to --category recall only.")),process.exit(1);let r=e.recallRef?.trim();if(n){if(!r||!Doe(r))console.error(u.red(`--recall-ref is required. ${Coe}`)),process.exit(1)}let o;if(e.bodyFile){if(!CO(e.bodyFile))console.error(u.red(`File not found: ${e.bodyFile}`)),process.exit(1);o=_Bt(e.bodyFile,"utf-8")}else if(e.body)o=e.body;else console.error(u.red("Email body required. Use --body or --body-file.")),process.exit(1);if(n){let p=$oe(o);if(p.length>0)console.error(u.red(`A recall body needs the headings ${WI.map((f)=>`"${f}"`).join(" and ")} (markdown, for example "## What is affected"). Missing: ${p.join(", ")}.`)),process.exit(1)}let s=e.user?`user:${e.user}`:`${e.to} (${e.category})`,i=e.user?{user:e.user,subject:t,body:o}:{to:e.to,category:e.category,...n?{recall_reference:r}:{},...e.allowRepeat?{allow_repeat:!0}:{},subject:t,body:o};if(e.dryRun){let p=A("Checking recipients...").start();try{let f=await _6({...i,dry_run:!0});if("dry_run"in f){p.succeed(`Dry run: ${f.recipient_count} recipient(s) for "${f.recipient_group}"${f.category?` (${f.category})`:""}`);for(let m of qBt(f))console.log(m)}}catch(f){Bt(f,p,"Failed to check recipients")}return}if(console.log(u.bold("Email preview:")),console.log(` To: ${u.cyan(s)}`),n)console.log(u.red.bold(" RECALL: reaches every account in this group, ignores email preferences, cannot be unsubscribed from.")),console.log(` Reference: ${r}`);console.log(` Subject: ${t}`),console.log(` Body: ${o.length>100?`${o.substring(0,100)}...`:o}`),console.log();let a=e.user?`Send this email to ${e.user}?`:"Send this broadcast email?";if(await De(a,e,!1)!=="confirmed")return;let l;if(n){if(l=await BBt(r,e.confirmRecall),l===void 0)console.error(u.red(`Recall not sent: the confirmation must be the reference exactly as given (${r}).`)),process.exit(1)}let d=A(e.user?`Sending to ${e.user}...`:"Sending broadcast...").start();try{let p=await _6({...i,...l===void 0?{}:{confirm_recall:l}});if("broadcast_id"in p){if(p.error==="queue_enqueue_failed")d.warn(`Enqueue failed (ID ${p.broadcast_id}): ${p.recipient_count} queued, ${p.failure_count} not queued; check progress with: nemar admin notify --status ${p.broadcast_id}`);else if(p.status==="queued"&&p.failure_count===0)d.succeed(`Queued ${p.recipient_count} announcement(s) (ID ${p.broadcast_id}); check progress with: nemar admin notify --status ${p.broadcast_id}`);else if(p.failure_count>0){d.warn(`Email send: ${p.recipient_count} delivered, ${p.failure_count} failed`);for(let f of p.failed_recipients)console.log(u.red(` Failed: ${f}`))}else{let f=e.user?`Email sent to ${e.user}`:`Broadcast sent to ${p.recipient_count} recipient(s)`;d.succeed(`${f} (ID: ${p.broadcast_id})`)}if((p.suppressed_count??0)>0)console.log(u.yellow(` ${p.suppressed_count} recipient(s) withheld by the non-production delivery fence`));if(n)for(let f of HBt(p))console.log(f)}}catch(p){Bt(p,d,"Failed to send email")}});var zBt=1500;function GBt(e){switch(e.kind){case"ok":return u.green(`ok ${e.schema_version}`);case"stale":return u.yellow(`stale ${e.schema_version}`);case"missing":return u.red("missing");case"error":return u.red(`error ${e.status||"?"}: ${e.message}`)}}function VBt(e){return e.kind==="stale"||e.kind==="missing"}function WBt(e){let n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`)}var RNe=new ne("summary").description("summary.json coverage across published dataset versions");xa(RNe.command("check").description("Report which (dataset_id, version) pairs have stale or missing summary.json"),"Dispatch generate-manifest for every stale/missing version",["--fix"]).option("--id <id>","Limit to a single dataset_id (exact match)").option("--match <glob>","Limit to dataset_ids matching a glob pattern: `*` matches any run of chars, `?` matches one char. Examples: `on*`, `nm00010?`, `*99999`. Can be combined with --id (id wins if both passed).").option("--only-stale","Print only rows that are not ok (suppresses ok rows)").option("--json","Emit the full report as JSON instead of a table").option(lt,xt).option(Ct,kt).action(async(e)=>{if(!Oe())return;let t=A("Building coverage report...").start(),n;try{n=await Fwe()}catch(f){Bt(f,t,"Failed to fetch coverage report");return}t.succeed(`Coverage: target=schema ${n.target_schema}, versions=${n.totals.versions}`);let r=n.versions,o=null;if(e.id){if(r=r.filter((f)=>f.dataset_id===e.id),o=`dataset_id=${e.id}`,r.length===0){console.log(u.yellow(`No rows for ${o}`));return}}else if(e.match){let f=WBt(e.match);if(r=r.filter((m)=>f.test(m.dataset_id)),o=`--match ${e.match}`,r.length===0){console.log(u.yellow(`No rows match ${o}`));return}console.log(u.dim(`Scoped to ${r.length} version(s) matching ${e.match}`))}if(e.json){console.log(JSON.stringify(o?{...n,versions:r,totals:rNe(r)}:n,null,2));return}let s=e.onlyStale?r.filter((f)=>f.state.kind!=="ok"):r;if(s.length===0)console.log(u.green("All versions at target schema \u2014 no drift."));else{let f=Math.max(...s.map((h)=>h.dataset_id.length),10),m=Math.max(...s.map((h)=>h.version.length),7);for(let h of s)console.log(` ${h.dataset_id.padEnd(f)} ${h.version.padEnd(m)} ${GBt(h.state)}`)}let i=o?rNe(r):n.totals;if(console.log(),console.log(` Total: ${i.versions} ${u.green(`ok=${i.ok}`)} ${u.yellow(`stale=${i.stale}`)} ${u.red(`missing=${i.missing}`)} ${u.red(`error=${i.error}`)}`),!e.apply){if(i.stale+i.missing>0)console.log(u.dim(`
|
|
2296
2296
|
Run with --apply to dispatch generate-manifest for the ${i.stale+i.missing} drifted version(s).`));return}let a=r.filter((f)=>VBt(f.state));if(a.length===0){console.log(u.green(`
|
|
2297
|
-
Nothing to dispatch.`));return}let c=o?` (scoped to ${o})`:"",l=await De(`Dispatch generate-manifest for ${a.length} version(s)${c}? Each dispatch queues a runner job on nemarDatasets/.github.`,e);if(l!=="confirmed"){console.log(u.dim(l==="declined"?"Skipped":"Cancelled"));return}let d=0,p=0;console.log();for(let[f,m]of a.entries()){let h=`${m.dataset_id}@${m.version}`,g=A(`[${f+1}/${a.length}] dispatching ${h}...`).start();try{await Mwe(m.dataset_id,m.version),g.succeed(`[${f+1}/${a.length}] dispatched ${h}`),d++}catch(y){g.fail(`[${f+1}/${a.length}] ${h}: ${W(y)}`),p++}if(f<a.length-1)await new Promise((y)=>setTimeout(y,zBt))}if(console.log(),console.log(p===0?u.green(`All ${d} dispatches succeeded.`):u.yellow(`${d} succeeded, ${p} failed.`)),console.log(u.dim("Workflow runs will appear on https://github.com/nemarDatasets/.github/actions. Re-run `nemar admin fleet summary check` once they complete to verify drift cleared.")),p>0)process.exitCode=1});function rNe(e){return{versions:e.length,ok:e.filter((t)=>t.state.kind==="ok").length,stale:e.filter((t)=>t.state.kind==="stale").length,missing:e.filter((t)=>t.state.kind==="missing").length,error:e.filter((t)=>t.state.kind==="error").length}}Bu.addCommand(RNe);var $Ne=new ne("zarr-catalog").description("Top-level Zarr discovery catalog (zarr-catalog.json)");$Ne.command("publish").description("Rebuild and republish zarr-catalog.json to this environment's bucket").action(async()=>{if(!Oe())return;let e=A("Publishing zarr-catalog.json...").start();try{let t=await jwe();e.succeed(`Published zarr-catalog.json: ${t.count} dataset(s), ${t.bytes} bytes`)}catch(t){Bt(t,e,"Failed to publish zarr catalog"),process.exit(1)}});Bu.addCommand($Ne);function KBt(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}function JBt(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}var $O=20,DNe=new ne("import-issue-triage").description("Close recovered import-failure issues and retire stale cause labels (dry run by default)");DNe.option("--apply","Perform the changes (without this flag, only report what would change)").option("--limit <n>","Issues per batch (server clamps to [1,30])","15").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=e.limit??"15",n=t.trim()===""?Number.NaN:Number(t);if(!Number.isInteger(n)||n<1){console.error(u.red(`Invalid --limit ${JSON.stringify(t)}: expected an integer >= 1.`)),process.exitCode=1;return}let r=e.apply===!0,o=A(r?"Triaging import-failure issues...":"Checking import-failure issues...").start(),s;try{s=await Gwe({apply:r,limit:n}),o.stop()}catch(i){o.fail("Import-failure issue triage failed"),console.error(u.red(W(i)));let a=i instanceof L?i.details:void 0,c=KBt(a)?a.errors:[];if(e.json)console.log(JSON.stringify(i instanceof L?i.rawBody??{errors:c}:{errors:c},null,2));else for(let l of c)console.error(`${u.red("ERROR".padEnd(15))} #${l.issue} ${l.dataset_id??""} ${l.stage}: ${l.error}`);process.exitCode=1;return}if(s.errors.length>0)process.exitCode=1;if(e.json){console.log(JSON.stringify(s,null,2));return}if(console.log(),!s.applied)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));for(let i of s.plan){let a=i.failed?"FAILED ":s.applied?"":"WOULD ",c=`#${i.issueNumber} ${i.datasetId??"(unknown)"}`;if(i.kind==="close"){let l=`${a}CLOSE`.padEnd(15);console.log(`${i.failed?u.red(l):u.green(l)} ${c} ${u.dim(i.reason)}`)}else if(i.kind==="relabel"){let l=`${a}RELABEL`.padEnd(15);console.log(`${i.failed?u.red(l):u.yellow(l)} ${c} ${u.dim(i.reason)}`)}else console.log(`${u.dim("KEEP".padEnd(15))} ${c} ${u.dim(i.reason)}`)}for(let i of s.rollups){let c=(i.outcome==="failed"?"FAILED RELEASE":i.outcome==="released"?"RELEASE":s.mode==="per-dataset"?"WOULD RELEASE":"ROLLUP").padEnd(15);console.log(`${i.outcome==="failed"?u.red(c):u.magenta(c)} #${i.number} ${u.dim(i.title)}`)}for(let i of s.errors)console.log(`${u.red("ERROR".padEnd(15))} #${i.issue} ${i.dataset_id??""} ${i.stage}: ${i.error}`);if(console.log(),console.log(u.cyan(`open=${s.openIssues} mode=${s.mode} examined=${s.examined} attempted=${s.attempted} ${s.applied?"closed":"would_close"}=${s.closed} ${s.applied?"relabelled":"would_relabel"}=${s.relabelled} kept=${s.kept} errors=${s.errors.length} remaining=${s.remaining}`)),s.remaining>0)console.log(u.dim(` ${s.remaining} candidate(s) outside this run's window; the window rotates daily.`));if(s.mode==="rollup")console.log(u.dim(" Rollup mode: new failures with a cause that already has a rollup join it instead of opening their own issue."));if(s.rollupsReleased>0)console.log(u.dim(` ${s.applied?"Released":"Would release"} ${s.rollupsReleased} rollup(s): the backlog has drained, so per-dataset filing resumes.`));if(s.audit_failed)console.log(u.yellow(` Changes were applied but the audit row failed to write: ${s.audit_failed}`));if(!s.applied&&(s.closed>0||s.relabelled>0||s.rollupsReleased>0))console.log(u.dim(" Re-run with --apply to perform these changes."));if(s.reconcile==null)console.log(),console.log(u.yellow(`reconcile=unknown${s.reconcileError?`: ${s.reconcileError}`:""}`));else{let i=s.reconcile;console.log(),console.log(u.cyan(`reconcile rows_without_issue=${i.rowsWithoutIssue.length} issues_without_row=${i.issuesWithoutRow.length} parked=${i.parked} quarantined=${i.quarantined} rows_examined=${i.rowsExamined} issues_examined=${i.issuesExamined}`));for(let l of i.rowsWithoutIssue.slice(0,$O))console.log(`${u.yellow("UNTRACKED".padEnd(15))} ${l.datasetId} (${l.sourceId}) ${l.status} at ${l.stage} ${u.dim(l.cause)}`);let a=i.rowsWithoutIssue.length-$O;if(a>0)console.log(u.dim(` ... and ${a} more untracked`));for(let l of i.issuesWithoutRow.slice(0,$O))console.log(`${u.yellow("NO IMPORT ROW".padEnd(15))} #${l.number} ${l.datasetId}`);let c=i.issuesWithoutRow.length-$O;if(c>0)console.log(u.dim(` ... and ${c} more`));if(console.log(u.dim(` ${i.reason}`)),i.rowsWithoutIssue.length>0||i.issuesWithoutRow.length>0)console.log(u.dim(" Reported only: this command files and closes nothing for these."))}});qu.addCommand(DNe.name("triage"));var CNe=new ne("import-coverage").description("Check whether the import pipeline is keeping up with OpenNeuro (dry run by default)"),DO=20,oNe=5,YBt={created:"create",refreshed:"refresh",relabelled:"relabel",closed:"close"};CNe.option("--apply","File, update or close the tracking issue (production only)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=e.apply===!0,n=A("Checking import coverage...").start(),r;try{r=await Vwe({apply:t}),n.stop()}catch(c){n.fail("Import coverage check failed"),console.error(u.red(W(c)));let l=c instanceof L?c.details:void 0,d=JBt(l)?l.errors:[];if(e.json)console.log(JSON.stringify(c instanceof L?c.rawBody??{errors:d}:{errors:d},null,2));else for(let p of d)console.error(`${u.red("ERROR".padEnd(12))} ${p.stage}: ${p.error}`);process.exitCode=c instanceof L&&c.statusCode===502?2:1;return}if(r.status==="unknown")process.exitCode=2;else if(r.status!=="healthy"||r.errors.length>0)process.exitCode=1;if(process.exitCode!==0)ce();if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.backlog,s=o.neverAttempted.length+o.untracked.length;console.log();let i=`${r.status.toUpperCase()}${r.kind?` (${r.kind})`:""}`;console.log(r.status==="healthy"?u.green(i):u.red(u.bold(i))),console.log(r.reason),console.log(),console.log(u.cyan(`auto_import=${r.enabled?"enabled":u.red("DISABLED")} last_dispatch=${r.dispatchAgeHours===null?"never":r.dispatchAgeHours<0?"dated in the future":`${r.dispatchAgeHours}h ago`}${r.lastDispatchSourceId?` (${r.lastDispatchSourceId})`:""} dispatch_lost=${r.dispatchLost}`));let a=r.importedInScan+r.inFlight+r.terminal+s+o.tracked.length+o.blocklisted.length;if(console.log(u.cyan(`discovered=${r.discovered} in_scan=${r.importedInScan} in_flight=${r.inFlight} terminal=${r.terminal} tracked=${o.tracked.length} blocklisted=${o.blocklisted.length}`)),console.log(u.cyan(`outstanding=${s} (never_attempted=${o.neverAttempted.length} untracked=${o.untracked.length})`)),r.importedNotInScan>0)console.log(u.dim(` ${r.importedNotInScan} of ${r.imported} mirror(s) are no longer in the scan (upstream removal, unreadable snapshot, or a modality retag). Drift, not a gap.`));if(a!==r.discovered)console.log(u.yellow(` Counts do not balance (${a} accounted for vs ${r.discovered} discovered): this run did not get a complete view, so treat the verdict as unreliable.`));if(o.neverAttempted.length>0){let c=o.neverAttempted.slice(0,DO).join(", "),l=o.neverAttempted.length-DO;console.log(u.dim(` never attempted: ${c}${l>0?` ... and ${l} more`:""}`))}if(o.untracked.length>0){let c=o.untracked.slice(0,DO).join(", "),l=o.untracked.length-DO;console.log(u.dim(` stale row nothing owns: ${c}${l>0?` ... and ${l} more`:""}`))}for(let c of r.errors){let l=`${c.stage}: ${c.error}`;console.log(c.stage==="anomaly"?`${u.yellow("ANOMALY".padEnd(12))} ${l}`:`${u.red("ERROR".padEnd(12))} ${l}`)}if(r.issue){let c=r.applied?r.issue.action:`would ${YBt[r.issue.action]??r.issue.action}`,l=r.issue.number===null?"":` #${r.issue.number}`;if(console.log(u.dim(` Issue: ${c}${l} on nemarDatasets/.github`)),r.issue.labelError)console.log(u.yellow(` The body was updated but its labels were not: ${r.issue.labelError}`));if(r.issue.commentError)console.log(u.yellow(` The issue changed but its comment failed: ${r.issue.commentError}`))}if(r.audit_failed)console.log(u.yellow(` Changes applied but the audit row failed to write: ${r.audit_failed}`));if(!r.applied&&r.issue)console.log(u.dim(" Re-run with --apply to perform this change."))});qu.addCommand(CNe.name("coverage"));var ANe=new ne("import-weekly").description("Read this week's import summary (dry run by default; the cron posts it on Mondays)");function XBt(e){return UF(e).attention}function vn(e){return e==null?u.yellow("unknown"):String(e)}ANe.option("--apply","Actually file the issue (production only; the cron normally does this)").option("--json","Output raw JSON instead of the human summary").option("--body","Also print the issue body exactly as it would be posted").action(async(e)=>{if(!Oe())return;let t=e.apply===!0,n=A("Building the weekly import summary...").start(),r;try{r=await Wwe({apply:t}),n.stop()}catch(a){n.fail("Weekly import summary failed"),console.error(u.red(W(a))),process.exitCode=1;return}let o=r.facts;if(o===null)process.exitCode=0;else if(o.errors.length>0)process.exitCode=2;else if(XBt(o))process.exitCode=1;if(process.exitCode!==0)ce();if(e.json){console.log(JSON.stringify(r,null,2));return}if(o===null){console.log(),console.log(u.yellow(`Nothing computed: ${r.gateReason}`)),console.log(u.dim(" The report is built once a week; --apply files it."));return}console.log(),console.log(u.bold(`Import summary ${o.week}`)),console.log(u.dim(`${o.windowStart} to ${o.windowEnd} (UTC)`)),console.log(),console.log(u.cyan(`imported_this_week=${vn(o.importedThisWeek)} total=${vn(o.importedTotal)} in_scope=${vn(o.discovered)} not_in_scope=${vn(o.importedNotInScan)}`));let s=o.coverageStatus===null?u.yellow("unknown"):o.coverageStatus==="healthy"?u.green(o.coverageStatus):u.red(o.coverageStatus);if(console.log(u.cyan(`coverage=${s} outstanding=${vn(o.outstanding)}`)),console.log(u.cyan(`auto_import=${o.autoImportEnabled===null?u.yellow("unknown"):o.autoImportEnabled?"enabled":u.red("DISABLED")} last_dispatch=${o.dispatchPhrase??u.yellow("unknown")} dispatch_lost=${o.dispatchLost===null?u.yellow("unknown"):o.dispatchLost}`)),console.log(u.cyan(`open_failures=${vn(o.openFailureTotal)} parked=${o.parked===null?u.yellow("unknown"):o.parked.length} closed_this_week=${vn(o.issuesClosed)} relabelled=${vn(o.issuesRelabelled)}`)),o.upstream==null)console.log(u.cyan(`upstream=${u.yellow("unknown")}`));else{let a=o.upstream.counts.states,c=o.upstream.truncated?` ${u.yellow("(did not reach every mirror)")}`:"",l=`upstream: stale=${vn(o.upstream.counts.stale)} current=${vn(a.current)} anomaly=${vn(a.anomaly)} unknown=${vn(a.unknown)} unchecked=${vn(a.unchecked)}`;console.log(u.cyan(`${l}${c}`))}if(o.repulls==null)console.log(u.cyan(`repulls=${u.yellow("unknown")}`));else{let a=o.repulls,c=a.switches,l=c.auto_repull_merge_enabled?"open+merge":c.auto_repull_enabled?"open":"off";console.log(u.cyan(`repulls: switches=${l} dispatched=${vn(a.dispatches.sent)} opened=${vn(a.dispatches.by_status.opened)} refused=${vn(a.dispatches.by_status.refused)} failed=${vn(a.dispatches.by_status.failed)} unreported=${vn(a.dispatches.by_status.unreported)} not_accepted=${vn(a.dispatches.by_status.dispatch_failed)}`)),console.log(u.cyan(`repulls: open=${vn(a.open_automatic.total)} held=${vn(a.open_automatic.held)} claims_held=${vn(a.held_claims)} ended_failed=${vn(a.ended_failed)} merged_worker=${vn(a.merged.worker)} merged_admin=${vn(a.merged.administrator)} merged_outside=${vn(a.merged.outside_tool)} merged_unattributed=${vn(a.merged.unattributed)}`))}if(o.failuresByCause!==null){let a=Object.entries(o.failuresByCause).filter(([,c])=>c>0);for(let[c,l]of a)console.log(u.dim(` ${c}: ${l}`))}if(o.parked!==null&&o.parked.length>0){for(let c of o.parked.slice(0,oNe))console.log(u.dim(` parked ${c.datasetId} (${c.reason??"unknown"}): ${c.parkedDays==null?"unknown":`${c.parkedDays} days`}`));let a=o.parked.length-oNe;if(a>0)console.log(u.dim(` ... and ${a} more parked`))}for(let a of o.errors)console.log(`${u.yellow("UNKNOWN".padEnd(10))} ${a.stage}: ${a.error}`);let i=UF(o);if(i.attention)console.log(u.yellow(`Needs attention: ${i.problems.join("; ")}.`));if(console.log(),!r.posted&&!t)console.log(u.dim("Dry run: nothing was filed.")),console.log(u.dim(" Re-run with --apply to file it (production only)."));else if(!r.posted)console.log(u.yellow(`Not posted: ${r.gateReason}`));else console.log(u.green(`Posted${r.issue?.number?` #${r.issue.number}`:""}${r.closedPrevious?`, closed #${r.closedPrevious}`:""}`));if(e.body)console.log(),console.log(u.dim("--- rendered issue body ---")),console.log(r.renderedBody??u.yellow("(no body was rendered)"))});qu.addCommand(ANe.name("weekly"));var ONe=new ne("backfill-usernames").description("Give username-less accounts a username from their name (dry run by default)");ONe.option("--apply","Write the usernames and send verification messages").option("--limit <n>","Users per batch (server clamps to [1,100])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=Number.parseInt(e.limit??"25",10)||25,n=e.apply===!0,r=A(n?"Assigning usernames...":"Checking which accounts need a username...").start(),o;try{o=await Kwe({apply:n,limit:t}),r.stop()}catch(s){r.fail("Username backfill failed"),console.error(u.red(W(s))),process.exit(1);return}if(o.lookup_failed>0||o.conflict>0||(o.exhausted??0)>0||(o.write_failed??0)>0||(o.verify_failed??0)>0||(o.verify_rate_limited??0)>0||o.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.apply)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(u.cyan(`scanned=${o.scanned} ${o.apply?"assigned":"would_assign"}=${o.apply?o.assigned:o.would_assign} single_name=${o.single_name} no_name=${o.no_name} lookup_failed=${o.lookup_failed} conflict=${o.conflict} exhausted=${o.exhausted??0} write_failed=${o.write_failed??0} verify_sent=${o.verify_sent} verify_failed=${o.verify_failed??0} verify_rate_limited=${o.verify_rate_limited??0} remaining=${o.remaining??"unknown"}`));for(let s of o.results){let i=`id ${s.id} <${s.email}>`,a=[s.given_name,s.family_name].filter(Boolean).join(" ");if(s.outcome==="assigned"||s.outcome==="would_assign"){let c=s.outcome==="assigned"?u.green("assigned "):u.cyan("would give"),l=s.outcome==="assigned"?` [verify: ${s.verify}]`:"";console.log(` ${c} ${i}: ${u.cyan(s.username??"?")} (${a})${l}`)}else if(s.outcome==="single_name")console.log(` ${u.yellow("one name ")} ${i}: only "${a}" on record; pick a username by hand`);else if(s.outcome==="no_name")console.log(` ${u.yellow("no name ")} ${i}: no name on record. ${Sn("cli.admin.owner_name_missing.fix")}`);else if(s.outcome==="conflict")console.log(` ${u.yellow("conflict ")} ${i}: ${s.error}`);else if(s.outcome==="exhausted")console.log(` ${u.yellow("exhausted ")} ${i}: ${s.error}; pick a username by hand`);else if(s.outcome==="write_failed")console.log(` ${u.red("write ")} ${i}: ${s.error}; retry the batch`);else console.log(` ${u.red("error ")} ${i}: ${s.error}`)}for(let s of o.verify_retries??[]){let i=s.verify==="sent"?u.green("re-sent "):s.verify==="not_attempted"?u.cyan("would send"):u.yellow(`verify ${s.verify}`);console.log(` ${i} id ${s.id} <${s.email}>`)}if(o.warning)console.log(u.yellow(` Warning: ${o.warning}`));if(o.single_name>0||o.no_name>0)console.log(),console.log(u.dim("Accounts with one name or none are listed, never guessed at: a username derived from an email address is a handle the person never chose."))});Qi.addCommand(ONe);var TNe=new ne("duplicates").description("Report live accounts sharing an ORCID iD, email, or GitHub handle");function ZBt(e){let t=e.username??u.dim("(no username)"),n=[];if(e.canonical)n.push(u.green("canonical"));if(e.identity_conflict===1)n.push(u.yellow("flagged"));if(e.has_oauth_identity)n.push(u.dim("orcid-login"));let r=n.length>0?` [${n.join(", ")}]`:"",o=`created ${e.created_at} datasets=${e.dataset_count}`;console.log(` id ${String(e.id).padEnd(5)} ${t} <${e.email}> ${o}${r}`)}TNe.option("--json","Output raw JSON instead of the human report").option("--clear <id>","Clear one account's identity-conflict flag (refuses while the collision remains)").action(async(e)=>{if(!Oe())return;if(e.clear!==void 0){let r=Number.parseInt(e.clear,10);if(!Number.isInteger(r)||r<=0){console.error(u.red(`Invalid user id: ${e.clear}`)),process.exit(1);return}let o=A(`Clearing identity-conflict flag on user ${r}...`).start();try{let s=await Ywe(r);if(o.stop(),e.json){console.log(JSON.stringify(s,null,2));return}console.log(s.cleared?u.green(`Cleared the identity-conflict flag on user ${r}.`):u.dim(`User ${r} was not flagged; nothing to clear.`))}catch(s){o.fail(s instanceof L&&s.statusCode===409?"Still colliding; flag not cleared":"Failed to clear the identity-conflict flag"),console.error(u.red(W(s))),process.exit(1)}return}let t=A("Checking for duplicate accounts...").start(),n;try{n=await Jwe(),t.stop()}catch(r){t.fail("Duplicate report failed"),console.error(u.red(W(r))),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.groups.length===0){if(console.log(u.green("No duplicate accounts.")),n.flagged_count>0)console.log(u.yellow(`${n.flagged_count} account(s) still carry an identity-conflict flag with no remaining collision.`)),console.log(u.dim(" Clear each with 'nemar admin users duplicates --clear <id>'."));return}console.log(u.cyan(`${n.group_count} duplicate group(s); ${n.flagged_count} account(s) flagged`));for(let r of n.groups){console.log(),console.log(` ${u.bold(r.kind)} ${r.value}`);for(let o of r.accounts)ZBt(o)}console.log(),console.log(u.dim("The fix is self-service on the surviving account: change its email or GitHub username, or unlink/re-link its ORCID iD, in Settings on nemar.org. Merging two accounts is manual.")),process.exitCode=1});Qi.addCommand(TNe);var NO=new ne("neurobagel").description("Neurobagel federation artifacts: regenerate and inspect the private store (epic #1586)"),Ua=(e)=>e===null?u.yellow("unknown"):String(e),dB=(e)=>e==="healthy"?u.green(e):e==="alarm"?u.red(e):e==="unknown"?u.yellow(e):u.dim(e);function PNe(e){console.log(`${u.bold("Verification")} ${dB(e.overall)} ${e.at} (${e.trigger})${e.failed?u.red(` the sweep itself failed: ${e.error??"no reason recorded"}`):""}`);for(let t of die){let n=e.checks[t];console.log(` ${t.padEnd(13)}${dB(n.verdict)} ${n.reason}`)}for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`))}function QBt(e){if(console.log(),e.dry_run)console.log(u.yellow("DRY RUN: nothing was written. Re-run with --apply to write."));if(e.status!=="ok"){let t=e.status==="disabled"?"the writer is disabled (NEUROBAGEL_WRITER_ENABLED is not 1)":e.status==="store_unconfigured"?"no NEUROBAGEL bucket is bound":e.error??"the run failed";console.log(u.red(`status=${e.status}: ${t}`))}console.log(u.cyan(`eligible=${Ua(e.eligible)} examined=${e.examined} limit=${e.limit} unexamined=${e.unexamined} removed=${e.removed.length} removals_pending=${e.removals_pending} index_entries=${Ua(e.index.entries)} index_written=${e.index.written} index_patched=${e.index.patched??0} anonymity_findings=${e.anonymity_findings} ops=${e.ops.spent}/${e.ops.budget}`));for(let t of e.results)switch(t.outcome){case"written":console.log(` ${u.green("written ")} ${t.id}${t.flags.length>0?` needs review: ${t.flags.join(", ")}`:""}`);break;case"would_write":console.log(` ${u.cyan("would write")} ${t.id} (${t.reason})`);break;case"unchanged":console.log(` ${u.dim("unchanged ")} ${t.id}`);break;case"would_remove":console.log(` ${u.cyan("would remove")} ${t.id}`);break;case"removed":console.log(` ${u.green("removed ")} ${t.id}`);break;case"refused":console.log(` ${u.red("refused ")} ${t.id} ${t.code}${t.detail?`: ${t.detail}`:""}`);break;case"error":console.log(` ${u.red("error ")} ${t.id} ${t.error}`);break}if(e.stopped==="ops_budget")console.log(u.yellow(` the run spent its operation budget (${e.ops.spent} of ${e.ops.budget}, ${e.ops.reserved} of it held back to finish) with ${e.unexamined} dataset(s) not yet examined: run the same command again to continue`));else if(e.unexamined>0&&e.stopped===null)console.log(u.yellow(` ${e.unexamined} dataset(s) are still waiting beyond this call's limit: run the same command again to continue`));if(e.index.contended)console.log(u.red(" the index was replaced by another run during this one; re-run to settle it"));for(let t of e.index.problems??[])console.log(u.red(` index not written: ${t}`));for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`));if(e.anonymity_findings>0)console.log(u.red(` ${e.anonymity_findings} dataset(s) were refused because their data says anonymous. They are in the audit log (neurobagel_anonymity_finding); nothing was filed or mailed.`))}xa(NO.command("regenerate").description("Examine datasets and write what changed to the Neurobagel artifact store (dry run unless --apply)"),"Write to the store (without it, only report what would change)",["--execute"]).option("--dataset <ids...>","Examine exactly these dataset ids instead of the next ones due").option("--limit <n>",`Datasets to examine (default: the server's per-tick bound, at most ${Qk}); run again to continue`).option("--force","Rewrite even when the fingerprint matches").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=e.limit===void 0?void 0:/^[1-9][0-9]*$/.test(e.limit)?Number(e.limit):Number.NaN;if(t!==void 0&&!Number.isInteger(t)){console.error(u.red("--limit must be a positive whole number")),process.exit(1);return}if(t!==void 0&&t>Qk){console.error(u.red(`--limit is at most ${Qk} per call (each call runs inside one request); run the command again to continue`)),process.exit(1);return}let n=e.apply===!0,r=A(n?"Regenerating Neurobagel artifacts...":"Checking what would change...").start(),o;try{o=await Lwe({...n?{execute:!0}:{},...e.dataset&&e.dataset.length>0?{datasets:e.dataset}:{},...t!==void 0?{limit:t}:{},...e.force?{force:!0}:{}}),r.stop()}catch(i){Bt(i,r,"Neurobagel regenerate failed",{409:"Set NEUROBAGEL_WRITER_ENABLED=1 (and bind the bucket) to write. A dry run needs neither the switch nor --apply."}),process.exit(1);return}if(e.json)console.log(JSON.stringify(o,null,2));else QBt(o);let s=o.results.some((i)=>i.outcome==="error");if(o.status!=="ok"||s||o.index.contended||o.stopped==="index_patch"||(o.index.problems?.length??0)>0||o.anonymity_findings>0)process.exitCode=1});NO.command("status").description("What is eligible, written, stale and waiting on a person in the Neurobagel store, and the latest verification (exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=A("Reading the Neurobagel store...").start(),n;try{n=await Uwe(),t.stop()}catch(l){Bt(l,t,"Neurobagel status failed"),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.writer.mode==="enabled"?u.green("enabled"):n.writer.mode==="disabled"?u.yellow("disabled (NEUROBAGEL_WRITER_ENABLED is not 1)"):u.red("store_unconfigured (no NEUROBAGEL bucket is bound)");console.log(),console.log(`${u.bold("Writer")} ${r}`),console.log(`${u.bold("Read route")} ${n.read_route.token_configured?u.green("token configured"):u.yellow("no NEUROBAGEL_READ_TOKEN: the route answers 404")}`),console.log(`${u.bold("Per tick")} ${n.limits.reconcile_max} datasets (hard limit ${n.limits.hard_max})`),console.log();let o=n.counts;console.log(`${u.bold("Datasets")} eligible=${Ua(o.eligible)} written=${Ua(o.written)} missing=${Ua(o.missing)} stale=${Ua(o.stale)} incomplete=${Ua(o.incomplete)} waiting to be removed=${Ua(o.residue)}`),console.log(`${u.bold("Store")} objects=${Ua(n.store.objects)} bytes=${Ua(n.store.total_bytes)}${n.store.over_loader_cap?u.red(" OVER the loader's total cap"):""}${(n.store.unexpected_objects??0)>0?u.yellow(` ${n.store.unexpected_objects} object(s) that are not the writer's`):""}`);let s=n.index.matches_store===null?u.yellow("unknown"):n.index.matches_store?u.green("matches the store"):u.yellow("differs from what the store and eligibility imply (the next run settles it)");console.log(`${u.bold("Index")} ${n.index.present===null?u.yellow("unknown"):n.index.present?`${Ua(n.index.entries)} entries, generated ${n.index.generated_at??"?"}`:u.dim("not written yet")} ${s}`);let i=n.last_reconcile;console.log(`${u.bold("Last reconcile")} ${i?`${i.at} (${JSON.stringify(i.summary)})`:u.dim("none recorded")}`),console.log(`${u.bold("Anonymity")} ${n.anonymity_findings===null?u.yellow("unknown"):n.anonymity_findings===0?"no findings":u.red(`${n.anonymity_findings} finding(s): see the audit log (neurobagel_anonymity_finding); ids are not shown here`)}`);let a=pie({verification:n.verification,writerMode:n.writer.mode,now:new Date});if(n.verification)PNe(n.verification);if(a.note)console.log(`${u.bold("Verification")} ${dB(a.verdict)} ${a.note}`);else if(!n.verification)console.log(`${u.bold("Verification")} ${u.dim("none recorded; the writer is off, so none is expected")}`);if(n.needs_review.length>0){console.log(),console.log(u.bold(`Needs review (${n.needs_review.length})`));for(let l of n.needs_review)console.log(` ${l.id} ${l.source==="refusal"?u.red(`refused: ${l.code}${l.since?` (last confirmed ${l.since})`:""}`):u.yellow((l.flags??[]).join(", "))}`)}for(let l of n.warnings)console.log(u.yellow(`warning: ${l}`));let c=n.writer.mode==="store_unconfigured"||(n.anonymity_findings??0)>0||n.counts.eligible===null||a.verdict==="alarm";process.exitCode=c?1:LF(a.verdict)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined (no verification recorded while the writer is on, a record over 36 hours old, or an unknown verdict). The same as `verify`.");NO.command("verify").description("Run the verification sweep now: the store against eligibility, the node, registration and upstream drift (reports only; exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=A("Verifying the Neurobagel federation...").start(),n;try{n=await qwe(),t.stop()}catch(r){Bt(r,t,"Neurobagel verify failed"),process.exit(1);return}if(e.json)console.log(JSON.stringify(n,null,2));else if(console.log(),PNe(n),!n.heartbeat_written)console.log(u.yellow("The heartbeat could not be written: this run is not recorded."));process.exitCode=LF(n.overall)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined. The same as `status`.");Co.addCommand(NO);Co.addCommand(ja);Co.addCommand(La);Co.addCommand(nb);Co.addCommand(yke);Co.addCommand(qi);NEe(Co);Le();xs();Po();Js();qw();Tf();yg();Le();Js();Lw();Tf();var e8t=Je["cli.gaps.section.title"];function NNe(e){if(e.gaps===void 0)return[e.unknownReason??Je["cli.gaps.unknown"]];let t=vg(e.gaps,{orcidVerified:e.orcidVerified}).map(Ck);if(e.sandboxCompleted===!1)t.push(Ak());return t.length>0?t:[Je["gaps.none"]]}function t8t(e){let t=NNe(e);return t.length===1&&t[0]===Je["gaps.none"]}function zv(e){let t=e.gaps===void 0||t8t(e);console.log(),console.log(u.bold(e8t));for(let n of NNe(e))console.log(` ${t?u.dim(n):u.yellow(n)}`)}function IO(e,t,n={}){let r=n.indent??" ";console.log(),console.log(`${r}${e}`);for(let o of t)console.log(`${r} ${u.yellow(o.label)} ${GI(o)}`)}function INe(e){if(e.flag)return"flag";return(e.published??$k)&&e.interactive&&e.gapFields.has("affiliation")?"prompt":"none"}function FNe(e=$k){return e?[` Compute access ${u.dim("one-time admin approval; nemar compute request-access")}`]:[]}Ue();Am();Sr();sn();Le();Rk();import{hostname as n8t}from"os";Ue();sn();function r8t(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").trim();return t?t.slice(0,foe):BI}function o8t(){try{return r8t(n8t())}catch{return BI}}function s8t(e,t,n=qI){return e+(t+n)*1000}function LNe(e){switch(e.kind){case"cancelled":return{lines:["Sign-in canceled. Run `nemar auth login` to try again."],exitCode:130};case"denied":case"expired":case"invalid":return{lines:[e.message],exitCode:1};case"unreachable":return{lines:[`NEMAR could not be reached: ${e.detail}`,"Run `nemar auth login` again once you're back online."],exitCode:1};case"server_error":return{lines:[`NEMAR keeps answering with an error (${e.detail}). Try again in a few minutes; if it keeps happening, run \`nemar auth login --debug\` and report the log.`],exitCode:1};case"start_failed":return{lines:[`Could not start sign-in: ${e.detail}`],exitCode:1}}}var i8t=15000,MNe=1000,a8t=5000,jNe=3;function c8t(e){if(e instanceof L&&e.statusCode!==0)return`HTTP ${e.statusCode}`;return W(e)}function l8t(e){if(typeof AbortSignal.any==="function")return AbortSignal.any(e);let t=new AbortController;for(let n of e){if(n.aborted){t.abort();break}n.addEventListener("abort",()=>t.abort(),{once:!0})}return t.signal}function u8t(e,t){return new Promise((n)=>{if(t.aborted){n();return}let r=setTimeout(()=>{t.removeEventListener("abort",o),n()},e);function o(){clearTimeout(r),n()}t.addEventListener("abort",o,{once:!0})})}async function d8t(e,t={}){let n=Date.now(),r=s8t(n,e.expires_in,t.graceSeconds??qI),o=Math.max(e.interval*1000,MNe),s=new AbortController,i=()=>s.abort();process.on("SIGINT",i);let a=0;try{while(!0){if(s.signal.aborted)return{kind:"cancelled"};if(Date.now()>=r)return{kind:"unreachable",detail:"gave up waiting to reach NEMAR"};if(await u8t(o,s.signal),s.signal.aborted)return{kind:"cancelled"};let c=l8t([s.signal,AbortSignal.timeout(i8t)]),l;try{l=await Q_e(e.device_code,c),a=0}catch(d){if(s.signal.aborted)return{kind:"cancelled"};if(d instanceof L&&d.statusCode===0){console.log(u.dim(" NEMAR is unreachable; retrying...")),a=0;continue}let p=c8t(d);if(a+=1,Ln(`poll error ${a}/${jNe}: ${p} -- ${W(d)}`),console.log(u.dim(` NEMAR answered with an error (${p}); retrying...`)),a>=jNe)return{kind:"server_error",detail:p};continue}if(l.status==="pending")continue;if(l.status==="slow_down"){o=Math.max(o+a8t,e.interval*1000,MNe);continue}if(l.status==="success")return{...l.data,kind:"success"};if(l.error==="expired_token")return{kind:"expired",message:l.message};if(l.error==="access_denied")return{kind:"denied",message:l.message};return{kind:"invalid",message:l.message}}}finally{process.off("SIGINT",i)}}async function _B(e={}){let t;try{t=await Z_e(o8t())}catch(n){return{kind:"start_failed",detail:W(n)}}if(console.log(` ${t.verification_uri_complete}`),console.log(` Code: ${u.cyan(t.user_code)}`),console.log(u.dim(" (if the page asks for it)")),console.log(),e.open!==!1&&ib(t.verification_uri_complete))console.log(u.dim(" (trying to open your browser; use the link above if it doesn't)")),console.log();return d8t(t)}gr();var UNe="NEMAR_DATA_HOSTS",p8t="NEMAR_DATA_HOSTS_ONLY",f8t="https://private.nemar.org",m8t="https://private-test.nemar.org",h8t=/^[a-z]{2,3}[0-9]{6}$/;function FO(e){return h8t.test(e)}function g8t(e){return e}function qNe(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function BNe(e){let t=e.trim();if(t===""||/[?#@]/.test(t))return null;let n;try{n=new URL(t)}catch{return null}if(n.username!==""||n.password!=="")return null;if(n.pathname!=="/")return null;if(n.protocol==="https:")return n.origin;if(n.protocol==="http:"&&qNe(n.hostname))return n.origin;return null}function HNe(e){let t=[],n=[];for(let r of(e??"").split(",")){let o=r.trim();if(o==="")continue;let s=BNe(o);if(s===null)n.push(o);else if(!t.includes(s))t.push(s)}return{origins:t,rejected:n}}function zNe(e){return e.env??process.env}function MO(e={}){let t=zNe(e),n=e.isDevBuild??em,r=t[p8t]==="1"?[]:[n?m8t:f8t],{origins:o}=HNe(t[UNe]);return[...r,...o.filter((s)=>!r.includes(s))].map(g8t)}function GNe(e={}){return HNe(zNe(e)[UNe]).rejected}function jO(e,t={}){let n=BNe(e);if(n===null)return null;return MO(t).find((r)=>r===n)??null}function LO(e,t={}){return jO(e,t)!==null}function VNe(e,t={}){let n;try{n=new URL(e)}catch{return null}if(n.username!==""||n.password!=="")return null;return jO(n.origin,t)}function KTn(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&qNe(e.hostname)&&new URL(t).protocol==="http:"}var y8t="NEMAR_DATA_HOST_TIMEOUT_MS";function WNe(e,t=process.env){let n=t[y8t];if(n===void 0||!/^[0-9]+$/.test(n))return e;let r=Number(n);return r>0&&r<e?r:e}function KNe(e){if(!(e instanceof Error))return"error";let t=e.code;return typeof t==="string"&&/^[A-Z][A-Z0-9_]+$/.test(t)?`${e.name} ${t}`:e.name}var b8t="nemar";function JNe(e){let t={};for(let n of e.split(`
|
|
2297
|
+
Nothing to dispatch.`));return}let c=o?` (scoped to ${o})`:"",l=await De(`Dispatch generate-manifest for ${a.length} version(s)${c}? Each dispatch queues a runner job on nemarDatasets/.github.`,e);if(l!=="confirmed"){console.log(u.dim(l==="declined"?"Skipped":"Cancelled"));return}let d=0,p=0;console.log();for(let[f,m]of a.entries()){let h=`${m.dataset_id}@${m.version}`,g=A(`[${f+1}/${a.length}] dispatching ${h}...`).start();try{await Mwe(m.dataset_id,m.version),g.succeed(`[${f+1}/${a.length}] dispatched ${h}`),d++}catch(y){g.fail(`[${f+1}/${a.length}] ${h}: ${W(y)}`),p++}if(f<a.length-1)await new Promise((y)=>setTimeout(y,zBt))}if(console.log(),console.log(p===0?u.green(`All ${d} dispatches succeeded.`):u.yellow(`${d} succeeded, ${p} failed.`)),console.log(u.dim("Workflow runs will appear on https://github.com/nemarDatasets/.github/actions. Re-run `nemar admin fleet summary check` once they complete to verify drift cleared.")),p>0)process.exitCode=1});function rNe(e){return{versions:e.length,ok:e.filter((t)=>t.state.kind==="ok").length,stale:e.filter((t)=>t.state.kind==="stale").length,missing:e.filter((t)=>t.state.kind==="missing").length,error:e.filter((t)=>t.state.kind==="error").length}}Bu.addCommand(RNe);var $Ne=new ne("zarr-catalog").description("Top-level Zarr discovery catalog (zarr-catalog.json)");$Ne.command("publish").description("Rebuild and republish zarr-catalog.json to this environment's bucket").action(async()=>{if(!Oe())return;let e=A("Publishing zarr-catalog.json...").start();try{let t=await jwe();e.succeed(`Published zarr-catalog.json: ${t.count} dataset(s), ${t.bytes} bytes`)}catch(t){Bt(t,e,"Failed to publish zarr catalog"),process.exit(1)}});Bu.addCommand($Ne);function KBt(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}function JBt(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}var $O=20,DNe=new ne("import-issue-triage").description("Close recovered import-failure issues and retire stale cause labels (dry run by default)");DNe.option("--apply","Perform the changes (without this flag, only report what would change)").option("--limit <n>","Issues per batch (server clamps to [1,30])","15").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=e.limit??"15",n=t.trim()===""?Number.NaN:Number(t);if(!Number.isInteger(n)||n<1){console.error(u.red(`Invalid --limit ${JSON.stringify(t)}: expected an integer >= 1.`)),process.exitCode=1;return}let r=e.apply===!0,o=A(r?"Triaging import-failure issues...":"Checking import-failure issues...").start(),s;try{s=await Gwe({apply:r,limit:n}),o.stop()}catch(i){o.fail("Import-failure issue triage failed"),console.error(u.red(W(i)));let a=i instanceof L?i.details:void 0,c=KBt(a)?a.errors:[];if(e.json)console.log(JSON.stringify(i instanceof L?i.rawBody??{errors:c}:{errors:c},null,2));else for(let l of c)console.error(`${u.red("ERROR".padEnd(15))} #${l.issue} ${l.dataset_id??""} ${l.stage}: ${l.error}`);process.exitCode=1;return}if(s.errors.length>0)process.exitCode=1;if(e.json){console.log(JSON.stringify(s,null,2));return}if(console.log(),!s.applied)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));for(let i of s.plan){let a=i.failed?"FAILED ":s.applied?"":"WOULD ",c=`#${i.issueNumber} ${i.datasetId??"(unknown)"}`;if(i.kind==="close"){let l=`${a}CLOSE`.padEnd(15);console.log(`${i.failed?u.red(l):u.green(l)} ${c} ${u.dim(i.reason)}`)}else if(i.kind==="relabel"){let l=`${a}RELABEL`.padEnd(15);console.log(`${i.failed?u.red(l):u.yellow(l)} ${c} ${u.dim(i.reason)}`)}else console.log(`${u.dim("KEEP".padEnd(15))} ${c} ${u.dim(i.reason)}`)}for(let i of s.rollups){let c=(i.outcome==="failed"?"FAILED RELEASE":i.outcome==="released"?"RELEASE":s.mode==="per-dataset"?"WOULD RELEASE":"ROLLUP").padEnd(15);console.log(`${i.outcome==="failed"?u.red(c):u.magenta(c)} #${i.number} ${u.dim(i.title)}`)}for(let i of s.errors)console.log(`${u.red("ERROR".padEnd(15))} #${i.issue} ${i.dataset_id??""} ${i.stage}: ${i.error}`);if(console.log(),console.log(u.cyan(`open=${s.openIssues} mode=${s.mode} examined=${s.examined} attempted=${s.attempted} ${s.applied?"closed":"would_close"}=${s.closed} ${s.applied?"relabelled":"would_relabel"}=${s.relabelled} kept=${s.kept} errors=${s.errors.length} remaining=${s.remaining}`)),s.remaining>0)console.log(u.dim(` ${s.remaining} candidate(s) outside this run's window; the window rotates daily.`));if(s.mode==="rollup")console.log(u.dim(" Rollup mode: new failures with a cause that already has a rollup join it instead of opening their own issue."));if(s.rollupsReleased>0)console.log(u.dim(` ${s.applied?"Released":"Would release"} ${s.rollupsReleased} rollup(s): the backlog has drained, so per-dataset filing resumes.`));if(s.audit_failed)console.log(u.yellow(` Changes were applied but the audit row failed to write: ${s.audit_failed}`));if(!s.applied&&(s.closed>0||s.relabelled>0||s.rollupsReleased>0))console.log(u.dim(" Re-run with --apply to perform these changes."));if(s.reconcile==null)console.log(),console.log(u.yellow(`reconcile=unknown${s.reconcileError?`: ${s.reconcileError}`:""}`));else{let i=s.reconcile;console.log(),console.log(u.cyan(`reconcile rows_without_issue=${i.rowsWithoutIssue.length} issues_without_row=${i.issuesWithoutRow.length} parked=${i.parked} quarantined=${i.quarantined} rows_examined=${i.rowsExamined} issues_examined=${i.issuesExamined}`));for(let l of i.rowsWithoutIssue.slice(0,$O))console.log(`${u.yellow("UNTRACKED".padEnd(15))} ${l.datasetId} (${l.sourceId}) ${l.status} at ${l.stage} ${u.dim(l.cause)}`);let a=i.rowsWithoutIssue.length-$O;if(a>0)console.log(u.dim(` ... and ${a} more untracked`));for(let l of i.issuesWithoutRow.slice(0,$O))console.log(`${u.yellow("NO IMPORT ROW".padEnd(15))} #${l.number} ${l.datasetId}`);let c=i.issuesWithoutRow.length-$O;if(c>0)console.log(u.dim(` ... and ${c} more`));if(console.log(u.dim(` ${i.reason}`)),i.rowsWithoutIssue.length>0||i.issuesWithoutRow.length>0)console.log(u.dim(" Reported only: this command files and closes nothing for these."))}});qu.addCommand(DNe.name("triage"));var CNe=new ne("import-coverage").description("Check whether the import pipeline is keeping up with OpenNeuro (dry run by default)"),DO=20,oNe=5,YBt={created:"create",refreshed:"refresh",relabelled:"relabel",closed:"close"};CNe.option("--apply","File, update or close the tracking issue (production only)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=e.apply===!0,n=A("Checking import coverage...").start(),r;try{r=await Vwe({apply:t}),n.stop()}catch(c){n.fail("Import coverage check failed"),console.error(u.red(W(c)));let l=c instanceof L?c.details:void 0,d=JBt(l)?l.errors:[];if(e.json)console.log(JSON.stringify(c instanceof L?c.rawBody??{errors:d}:{errors:d},null,2));else for(let p of d)console.error(`${u.red("ERROR".padEnd(12))} ${p.stage}: ${p.error}`);process.exitCode=c instanceof L&&c.statusCode===502?2:1;return}if(r.status==="unknown")process.exitCode=2;else if(r.status!=="healthy"||r.errors.length>0)process.exitCode=1;if(process.exitCode!==0)ce();if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.backlog,s=o.neverAttempted.length+o.untracked.length;console.log();let i=`${r.status.toUpperCase()}${r.kind?` (${r.kind})`:""}`;console.log(r.status==="healthy"?u.green(i):u.red(u.bold(i))),console.log(r.reason),console.log(),console.log(u.cyan(`auto_import=${r.enabled?"enabled":u.red("DISABLED")} last_dispatch=${r.dispatchAgeHours===null?"never":r.dispatchAgeHours<0?"dated in the future":`${r.dispatchAgeHours}h ago`}${r.lastDispatchSourceId?` (${r.lastDispatchSourceId})`:""} dispatch_lost=${r.dispatchLost}`));let a=r.importedInScan+r.inFlight+r.terminal+s+o.tracked.length+o.blocklisted.length;if(console.log(u.cyan(`discovered=${r.discovered} in_scan=${r.importedInScan} in_flight=${r.inFlight} terminal=${r.terminal} tracked=${o.tracked.length} blocklisted=${o.blocklisted.length}`)),console.log(u.cyan(`outstanding=${s} (never_attempted=${o.neverAttempted.length} untracked=${o.untracked.length})`)),r.importedNotInScan>0)console.log(u.dim(` ${r.importedNotInScan} of ${r.imported} mirror(s) are no longer in the scan (upstream removal, unreadable snapshot, or a modality retag). Drift, not a gap.`));if(a!==r.discovered)console.log(u.yellow(` Counts do not balance (${a} accounted for vs ${r.discovered} discovered): this run did not get a complete view, so treat the verdict as unreliable.`));if(o.neverAttempted.length>0){let c=o.neverAttempted.slice(0,DO).join(", "),l=o.neverAttempted.length-DO;console.log(u.dim(` never attempted: ${c}${l>0?` ... and ${l} more`:""}`))}if(o.untracked.length>0){let c=o.untracked.slice(0,DO).join(", "),l=o.untracked.length-DO;console.log(u.dim(` stale row nothing owns: ${c}${l>0?` ... and ${l} more`:""}`))}for(let c of r.errors){let l=`${c.stage}: ${c.error}`;console.log(c.stage==="anomaly"?`${u.yellow("ANOMALY".padEnd(12))} ${l}`:`${u.red("ERROR".padEnd(12))} ${l}`)}if(r.issue){let c=r.applied?r.issue.action:`would ${YBt[r.issue.action]??r.issue.action}`,l=r.issue.number===null?"":` #${r.issue.number}`;if(console.log(u.dim(` Issue: ${c}${l} on nemarDatasets/.github`)),r.issue.labelError)console.log(u.yellow(` The body was updated but its labels were not: ${r.issue.labelError}`));if(r.issue.commentError)console.log(u.yellow(` The issue changed but its comment failed: ${r.issue.commentError}`))}if(r.audit_failed)console.log(u.yellow(` Changes applied but the audit row failed to write: ${r.audit_failed}`));if(!r.applied&&r.issue)console.log(u.dim(" Re-run with --apply to perform this change."))});qu.addCommand(CNe.name("coverage"));var ANe=new ne("import-weekly").description("Read this week's import summary (dry run by default; the cron posts it on Mondays)");function XBt(e){return UF(e).attention}function vn(e){return e==null?u.yellow("unknown"):String(e)}ANe.option("--apply","Actually file the issue (production only; the cron normally does this)").option("--json","Output raw JSON instead of the human summary").option("--body","Also print the issue body exactly as it would be posted").action(async(e)=>{if(!Oe())return;let t=e.apply===!0,n=A("Building the weekly import summary...").start(),r;try{r=await Wwe({apply:t}),n.stop()}catch(a){n.fail("Weekly import summary failed"),console.error(u.red(W(a))),process.exitCode=1;return}let o=r.facts;if(o===null)process.exitCode=0;else if(o.errors.length>0)process.exitCode=2;else if(XBt(o))process.exitCode=1;if(process.exitCode!==0)ce();if(e.json){console.log(JSON.stringify(r,null,2));return}if(o===null){console.log(),console.log(u.yellow(`Nothing computed: ${r.gateReason}`)),console.log(u.dim(" The report is built once a week; --apply files it."));return}console.log(),console.log(u.bold(`Import summary ${o.week}`)),console.log(u.dim(`${o.windowStart} to ${o.windowEnd} (UTC)`)),console.log(),console.log(u.cyan(`imported_this_week=${vn(o.importedThisWeek)} total=${vn(o.importedTotal)} in_scope=${vn(o.discovered)} not_in_scope=${vn(o.importedNotInScan)}`));let s=o.coverageStatus===null?u.yellow("unknown"):o.coverageStatus==="healthy"?u.green(o.coverageStatus):u.red(o.coverageStatus);if(console.log(u.cyan(`coverage=${s} outstanding=${vn(o.outstanding)}`)),console.log(u.cyan(`auto_import=${o.autoImportEnabled===null?u.yellow("unknown"):o.autoImportEnabled?"enabled":u.red("DISABLED")} last_dispatch=${o.dispatchPhrase??u.yellow("unknown")} dispatch_lost=${o.dispatchLost===null?u.yellow("unknown"):o.dispatchLost}`)),console.log(u.cyan(`open_failures=${vn(o.openFailureTotal)} parked=${o.parked===null?u.yellow("unknown"):o.parked.length} closed_this_week=${vn(o.issuesClosed)} relabelled=${vn(o.issuesRelabelled)}`)),o.upstream==null)console.log(u.cyan(`upstream=${u.yellow("unknown")}`));else{let a=o.upstream.counts.states,c=o.upstream.truncated?` ${u.yellow("(did not reach every mirror)")}`:"",l=`upstream: stale=${vn(o.upstream.counts.stale)} current=${vn(a.current)} anomaly=${vn(a.anomaly)} unknown=${vn(a.unknown)} unchecked=${vn(a.unchecked)}`;console.log(u.cyan(`${l}${c}`))}if(o.repulls==null)console.log(u.cyan(`repulls=${u.yellow("unknown")}`));else{let a=o.repulls,c=a.switches,l=c.auto_repull_merge_enabled?"open+merge":c.auto_repull_enabled?"open":"off";console.log(u.cyan(`repulls: switches=${l} dispatched=${vn(a.dispatches.sent)} opened=${vn(a.dispatches.by_status.opened)} refused=${vn(a.dispatches.by_status.refused)} failed=${vn(a.dispatches.by_status.failed)} unreported=${vn(a.dispatches.by_status.unreported)} not_accepted=${vn(a.dispatches.by_status.dispatch_failed)}`)),console.log(u.cyan(`repulls: open=${vn(a.open_automatic.total)} held=${vn(a.open_automatic.held)} claims_held=${vn(a.held_claims)} ended_failed=${vn(a.ended_failed)} merged_worker=${vn(a.merged.worker)} merged_admin=${vn(a.merged.administrator)} merged_outside=${vn(a.merged.outside_tool)} merged_unattributed=${vn(a.merged.unattributed)}`))}if(o.rfcs==null)console.log(u.cyan(`rfcs=${u.yellow("unknown")}`));else{let a=o.rfcs,c=u.yellow("unknown"),l=a.workflow==null?c:a.workflow.state,d=a.run==null?c:a.run.latest===null?u.red("never"):`${a.run.latest.createdAt.slice(0,16)}Z ${a.run.latest.conclusion??"not ended"}`;console.log(u.cyan(`rfcs: listed=${a.index==null?c:a.index.listed.length} closed_awaiting_decision=${a.index==null?c:a.index.listed.filter((p)=>p.phase==="closed").length} clock=${l} last_run=${d}`))}if(o.failuresByCause!==null){let a=Object.entries(o.failuresByCause).filter(([,c])=>c>0);for(let[c,l]of a)console.log(u.dim(` ${c}: ${l}`))}if(o.parked!==null&&o.parked.length>0){for(let c of o.parked.slice(0,oNe))console.log(u.dim(` parked ${c.datasetId} (${c.reason??"unknown"}): ${c.parkedDays==null?"unknown":`${c.parkedDays} days`}`));let a=o.parked.length-oNe;if(a>0)console.log(u.dim(` ... and ${a} more parked`))}for(let a of o.errors)console.log(`${u.yellow("UNKNOWN".padEnd(10))} ${a.stage}: ${a.error}`);let i=UF(o);if(i.attention)console.log(u.yellow(`Needs attention: ${i.problems.join("; ")}.`));if(console.log(),!r.posted&&!t)console.log(u.dim("Dry run: nothing was filed.")),console.log(u.dim(" Re-run with --apply to file it (production only)."));else if(!r.posted)console.log(u.yellow(`Not posted: ${r.gateReason}`));else console.log(u.green(`Posted${r.issue?.number?` #${r.issue.number}`:""}${r.closedPrevious?`, closed #${r.closedPrevious}`:""}`));if(e.body)console.log(),console.log(u.dim("--- rendered issue body ---")),console.log(r.renderedBody??u.yellow("(no body was rendered)"))});qu.addCommand(ANe.name("weekly"));var ONe=new ne("backfill-usernames").description("Give username-less accounts a username from their name (dry run by default)");ONe.option("--apply","Write the usernames and send verification messages").option("--limit <n>","Users per batch (server clamps to [1,100])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=Number.parseInt(e.limit??"25",10)||25,n=e.apply===!0,r=A(n?"Assigning usernames...":"Checking which accounts need a username...").start(),o;try{o=await Kwe({apply:n,limit:t}),r.stop()}catch(s){r.fail("Username backfill failed"),console.error(u.red(W(s))),process.exit(1);return}if(o.lookup_failed>0||o.conflict>0||(o.exhausted??0)>0||(o.write_failed??0)>0||(o.verify_failed??0)>0||(o.verify_rate_limited??0)>0||o.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.apply)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(u.cyan(`scanned=${o.scanned} ${o.apply?"assigned":"would_assign"}=${o.apply?o.assigned:o.would_assign} single_name=${o.single_name} no_name=${o.no_name} lookup_failed=${o.lookup_failed} conflict=${o.conflict} exhausted=${o.exhausted??0} write_failed=${o.write_failed??0} verify_sent=${o.verify_sent} verify_failed=${o.verify_failed??0} verify_rate_limited=${o.verify_rate_limited??0} remaining=${o.remaining??"unknown"}`));for(let s of o.results){let i=`id ${s.id} <${s.email}>`,a=[s.given_name,s.family_name].filter(Boolean).join(" ");if(s.outcome==="assigned"||s.outcome==="would_assign"){let c=s.outcome==="assigned"?u.green("assigned "):u.cyan("would give"),l=s.outcome==="assigned"?` [verify: ${s.verify}]`:"";console.log(` ${c} ${i}: ${u.cyan(s.username??"?")} (${a})${l}`)}else if(s.outcome==="single_name")console.log(` ${u.yellow("one name ")} ${i}: only "${a}" on record; pick a username by hand`);else if(s.outcome==="no_name")console.log(` ${u.yellow("no name ")} ${i}: no name on record. ${Sn("cli.admin.owner_name_missing.fix")}`);else if(s.outcome==="conflict")console.log(` ${u.yellow("conflict ")} ${i}: ${s.error}`);else if(s.outcome==="exhausted")console.log(` ${u.yellow("exhausted ")} ${i}: ${s.error}; pick a username by hand`);else if(s.outcome==="write_failed")console.log(` ${u.red("write ")} ${i}: ${s.error}; retry the batch`);else console.log(` ${u.red("error ")} ${i}: ${s.error}`)}for(let s of o.verify_retries??[]){let i=s.verify==="sent"?u.green("re-sent "):s.verify==="not_attempted"?u.cyan("would send"):u.yellow(`verify ${s.verify}`);console.log(` ${i} id ${s.id} <${s.email}>`)}if(o.warning)console.log(u.yellow(` Warning: ${o.warning}`));if(o.single_name>0||o.no_name>0)console.log(),console.log(u.dim("Accounts with one name or none are listed, never guessed at: a username derived from an email address is a handle the person never chose."))});Qi.addCommand(ONe);var TNe=new ne("duplicates").description("Report live accounts sharing an ORCID iD, email, or GitHub handle");function ZBt(e){let t=e.username??u.dim("(no username)"),n=[];if(e.canonical)n.push(u.green("canonical"));if(e.identity_conflict===1)n.push(u.yellow("flagged"));if(e.has_oauth_identity)n.push(u.dim("orcid-login"));let r=n.length>0?` [${n.join(", ")}]`:"",o=`created ${e.created_at} datasets=${e.dataset_count}`;console.log(` id ${String(e.id).padEnd(5)} ${t} <${e.email}> ${o}${r}`)}TNe.option("--json","Output raw JSON instead of the human report").option("--clear <id>","Clear one account's identity-conflict flag (refuses while the collision remains)").action(async(e)=>{if(!Oe())return;if(e.clear!==void 0){let r=Number.parseInt(e.clear,10);if(!Number.isInteger(r)||r<=0){console.error(u.red(`Invalid user id: ${e.clear}`)),process.exit(1);return}let o=A(`Clearing identity-conflict flag on user ${r}...`).start();try{let s=await Ywe(r);if(o.stop(),e.json){console.log(JSON.stringify(s,null,2));return}console.log(s.cleared?u.green(`Cleared the identity-conflict flag on user ${r}.`):u.dim(`User ${r} was not flagged; nothing to clear.`))}catch(s){o.fail(s instanceof L&&s.statusCode===409?"Still colliding; flag not cleared":"Failed to clear the identity-conflict flag"),console.error(u.red(W(s))),process.exit(1)}return}let t=A("Checking for duplicate accounts...").start(),n;try{n=await Jwe(),t.stop()}catch(r){t.fail("Duplicate report failed"),console.error(u.red(W(r))),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.groups.length===0){if(console.log(u.green("No duplicate accounts.")),n.flagged_count>0)console.log(u.yellow(`${n.flagged_count} account(s) still carry an identity-conflict flag with no remaining collision.`)),console.log(u.dim(" Clear each with 'nemar admin users duplicates --clear <id>'."));return}console.log(u.cyan(`${n.group_count} duplicate group(s); ${n.flagged_count} account(s) flagged`));for(let r of n.groups){console.log(),console.log(` ${u.bold(r.kind)} ${r.value}`);for(let o of r.accounts)ZBt(o)}console.log(),console.log(u.dim("The fix is self-service on the surviving account: change its email or GitHub username, or unlink/re-link its ORCID iD, in Settings on nemar.org. Merging two accounts is manual.")),process.exitCode=1});Qi.addCommand(TNe);var NO=new ne("neurobagel").description("Neurobagel federation artifacts: regenerate and inspect the private store (epic #1586)"),Ua=(e)=>e===null?u.yellow("unknown"):String(e),dB=(e)=>e==="healthy"?u.green(e):e==="alarm"?u.red(e):e==="unknown"?u.yellow(e):u.dim(e);function PNe(e){console.log(`${u.bold("Verification")} ${dB(e.overall)} ${e.at} (${e.trigger})${e.failed?u.red(` the sweep itself failed: ${e.error??"no reason recorded"}`):""}`);for(let t of die){let n=e.checks[t];console.log(` ${t.padEnd(13)}${dB(n.verdict)} ${n.reason}`)}for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`))}function QBt(e){if(console.log(),e.dry_run)console.log(u.yellow("DRY RUN: nothing was written. Re-run with --apply to write."));if(e.status!=="ok"){let t=e.status==="disabled"?"the writer is disabled (NEUROBAGEL_WRITER_ENABLED is not 1)":e.status==="store_unconfigured"?"no NEUROBAGEL bucket is bound":e.error??"the run failed";console.log(u.red(`status=${e.status}: ${t}`))}console.log(u.cyan(`eligible=${Ua(e.eligible)} examined=${e.examined} limit=${e.limit} unexamined=${e.unexamined} removed=${e.removed.length} removals_pending=${e.removals_pending} index_entries=${Ua(e.index.entries)} index_written=${e.index.written} index_patched=${e.index.patched??0} anonymity_findings=${e.anonymity_findings} ops=${e.ops.spent}/${e.ops.budget}`));for(let t of e.results)switch(t.outcome){case"written":console.log(` ${u.green("written ")} ${t.id}${t.flags.length>0?` needs review: ${t.flags.join(", ")}`:""}`);break;case"would_write":console.log(` ${u.cyan("would write")} ${t.id} (${t.reason})`);break;case"unchanged":console.log(` ${u.dim("unchanged ")} ${t.id}`);break;case"would_remove":console.log(` ${u.cyan("would remove")} ${t.id}`);break;case"removed":console.log(` ${u.green("removed ")} ${t.id}`);break;case"refused":console.log(` ${u.red("refused ")} ${t.id} ${t.code}${t.detail?`: ${t.detail}`:""}`);break;case"error":console.log(` ${u.red("error ")} ${t.id} ${t.error}`);break}if(e.stopped==="ops_budget")console.log(u.yellow(` the run spent its operation budget (${e.ops.spent} of ${e.ops.budget}, ${e.ops.reserved} of it held back to finish) with ${e.unexamined} dataset(s) not yet examined: run the same command again to continue`));else if(e.unexamined>0&&e.stopped===null)console.log(u.yellow(` ${e.unexamined} dataset(s) are still waiting beyond this call's limit: run the same command again to continue`));if(e.index.contended)console.log(u.red(" the index was replaced by another run during this one; re-run to settle it"));for(let t of e.index.problems??[])console.log(u.red(` index not written: ${t}`));for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`));if(e.anonymity_findings>0)console.log(u.red(` ${e.anonymity_findings} dataset(s) were refused because their data says anonymous. They are in the audit log (neurobagel_anonymity_finding); nothing was filed or mailed.`))}xa(NO.command("regenerate").description("Examine datasets and write what changed to the Neurobagel artifact store (dry run unless --apply)"),"Write to the store (without it, only report what would change)",["--execute"]).option("--dataset <ids...>","Examine exactly these dataset ids instead of the next ones due").option("--limit <n>",`Datasets to examine (default: the server's per-tick bound, at most ${Qk}); run again to continue`).option("--force","Rewrite even when the fingerprint matches").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=e.limit===void 0?void 0:/^[1-9][0-9]*$/.test(e.limit)?Number(e.limit):Number.NaN;if(t!==void 0&&!Number.isInteger(t)){console.error(u.red("--limit must be a positive whole number")),process.exit(1);return}if(t!==void 0&&t>Qk){console.error(u.red(`--limit is at most ${Qk} per call (each call runs inside one request); run the command again to continue`)),process.exit(1);return}let n=e.apply===!0,r=A(n?"Regenerating Neurobagel artifacts...":"Checking what would change...").start(),o;try{o=await Lwe({...n?{execute:!0}:{},...e.dataset&&e.dataset.length>0?{datasets:e.dataset}:{},...t!==void 0?{limit:t}:{},...e.force?{force:!0}:{}}),r.stop()}catch(i){Bt(i,r,"Neurobagel regenerate failed",{409:"Set NEUROBAGEL_WRITER_ENABLED=1 (and bind the bucket) to write. A dry run needs neither the switch nor --apply."}),process.exit(1);return}if(e.json)console.log(JSON.stringify(o,null,2));else QBt(o);let s=o.results.some((i)=>i.outcome==="error");if(o.status!=="ok"||s||o.index.contended||o.stopped==="index_patch"||(o.index.problems?.length??0)>0||o.anonymity_findings>0)process.exitCode=1});NO.command("status").description("What is eligible, written, stale and waiting on a person in the Neurobagel store, and the latest verification (exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=A("Reading the Neurobagel store...").start(),n;try{n=await Uwe(),t.stop()}catch(l){Bt(l,t,"Neurobagel status failed"),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.writer.mode==="enabled"?u.green("enabled"):n.writer.mode==="disabled"?u.yellow("disabled (NEUROBAGEL_WRITER_ENABLED is not 1)"):u.red("store_unconfigured (no NEUROBAGEL bucket is bound)");console.log(),console.log(`${u.bold("Writer")} ${r}`),console.log(`${u.bold("Read route")} ${n.read_route.token_configured?u.green("token configured"):u.yellow("no NEUROBAGEL_READ_TOKEN: the route answers 404")}`),console.log(`${u.bold("Per tick")} ${n.limits.reconcile_max} datasets (hard limit ${n.limits.hard_max})`),console.log();let o=n.counts;console.log(`${u.bold("Datasets")} eligible=${Ua(o.eligible)} written=${Ua(o.written)} missing=${Ua(o.missing)} stale=${Ua(o.stale)} incomplete=${Ua(o.incomplete)} waiting to be removed=${Ua(o.residue)}`),console.log(`${u.bold("Store")} objects=${Ua(n.store.objects)} bytes=${Ua(n.store.total_bytes)}${n.store.over_loader_cap?u.red(" OVER the loader's total cap"):""}${(n.store.unexpected_objects??0)>0?u.yellow(` ${n.store.unexpected_objects} object(s) that are not the writer's`):""}`);let s=n.index.matches_store===null?u.yellow("unknown"):n.index.matches_store?u.green("matches the store"):u.yellow("differs from what the store and eligibility imply (the next run settles it)");console.log(`${u.bold("Index")} ${n.index.present===null?u.yellow("unknown"):n.index.present?`${Ua(n.index.entries)} entries, generated ${n.index.generated_at??"?"}`:u.dim("not written yet")} ${s}`);let i=n.last_reconcile;console.log(`${u.bold("Last reconcile")} ${i?`${i.at} (${JSON.stringify(i.summary)})`:u.dim("none recorded")}`),console.log(`${u.bold("Anonymity")} ${n.anonymity_findings===null?u.yellow("unknown"):n.anonymity_findings===0?"no findings":u.red(`${n.anonymity_findings} finding(s): see the audit log (neurobagel_anonymity_finding); ids are not shown here`)}`);let a=pie({verification:n.verification,writerMode:n.writer.mode,now:new Date});if(n.verification)PNe(n.verification);if(a.note)console.log(`${u.bold("Verification")} ${dB(a.verdict)} ${a.note}`);else if(!n.verification)console.log(`${u.bold("Verification")} ${u.dim("none recorded; the writer is off, so none is expected")}`);if(n.needs_review.length>0){console.log(),console.log(u.bold(`Needs review (${n.needs_review.length})`));for(let l of n.needs_review)console.log(` ${l.id} ${l.source==="refusal"?u.red(`refused: ${l.code}${l.since?` (last confirmed ${l.since})`:""}`):u.yellow((l.flags??[]).join(", "))}`)}for(let l of n.warnings)console.log(u.yellow(`warning: ${l}`));let c=n.writer.mode==="store_unconfigured"||(n.anonymity_findings??0)>0||n.counts.eligible===null||a.verdict==="alarm";process.exitCode=c?1:LF(a.verdict)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined (no verification recorded while the writer is on, a record over 36 hours old, or an unknown verdict). The same as `verify`.");NO.command("verify").description("Run the verification sweep now: the store against eligibility, the node, registration and upstream drift (reports only; exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Oe())return;let t=A("Verifying the Neurobagel federation...").start(),n;try{n=await qwe(),t.stop()}catch(r){Bt(r,t,"Neurobagel verify failed"),process.exit(1);return}if(e.json)console.log(JSON.stringify(n,null,2));else if(console.log(),PNe(n),!n.heartbeat_written)console.log(u.yellow("The heartbeat could not be written: this run is not recorded."));process.exitCode=LF(n.overall)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined. The same as `status`.");Co.addCommand(NO);Co.addCommand(ja);Co.addCommand(La);Co.addCommand(nb);Co.addCommand(yke);Co.addCommand(qi);NEe(Co);Le();xs();Po();Js();qw();Tf();yg();Le();Js();Lw();Tf();var e8t=Je["cli.gaps.section.title"];function NNe(e){if(e.gaps===void 0)return[e.unknownReason??Je["cli.gaps.unknown"]];let t=vg(e.gaps,{orcidVerified:e.orcidVerified}).map(Ck);if(e.sandboxCompleted===!1)t.push(Ak());return t.length>0?t:[Je["gaps.none"]]}function t8t(e){let t=NNe(e);return t.length===1&&t[0]===Je["gaps.none"]}function zv(e){let t=e.gaps===void 0||t8t(e);console.log(),console.log(u.bold(e8t));for(let n of NNe(e))console.log(` ${t?u.dim(n):u.yellow(n)}`)}function IO(e,t,n={}){let r=n.indent??" ";console.log(),console.log(`${r}${e}`);for(let o of t)console.log(`${r} ${u.yellow(o.label)} ${GI(o)}`)}function INe(e){if(e.flag)return"flag";return(e.published??$k)&&e.interactive&&e.gapFields.has("affiliation")?"prompt":"none"}function FNe(e=$k){return e?[` Compute access ${u.dim("one-time admin approval; nemar compute request-access")}`]:[]}Ue();Am();Sr();sn();Le();Rk();import{hostname as n8t}from"os";Ue();sn();function r8t(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").trim();return t?t.slice(0,foe):BI}function o8t(){try{return r8t(n8t())}catch{return BI}}function s8t(e,t,n=qI){return e+(t+n)*1000}function LNe(e){switch(e.kind){case"cancelled":return{lines:["Sign-in canceled. Run `nemar auth login` to try again."],exitCode:130};case"denied":case"expired":case"invalid":return{lines:[e.message],exitCode:1};case"unreachable":return{lines:[`NEMAR could not be reached: ${e.detail}`,"Run `nemar auth login` again once you're back online."],exitCode:1};case"server_error":return{lines:[`NEMAR keeps answering with an error (${e.detail}). Try again in a few minutes; if it keeps happening, run \`nemar auth login --debug\` and report the log.`],exitCode:1};case"start_failed":return{lines:[`Could not start sign-in: ${e.detail}`],exitCode:1}}}var i8t=15000,MNe=1000,a8t=5000,jNe=3;function c8t(e){if(e instanceof L&&e.statusCode!==0)return`HTTP ${e.statusCode}`;return W(e)}function l8t(e){if(typeof AbortSignal.any==="function")return AbortSignal.any(e);let t=new AbortController;for(let n of e){if(n.aborted){t.abort();break}n.addEventListener("abort",()=>t.abort(),{once:!0})}return t.signal}function u8t(e,t){return new Promise((n)=>{if(t.aborted){n();return}let r=setTimeout(()=>{t.removeEventListener("abort",o),n()},e);function o(){clearTimeout(r),n()}t.addEventListener("abort",o,{once:!0})})}async function d8t(e,t={}){let n=Date.now(),r=s8t(n,e.expires_in,t.graceSeconds??qI),o=Math.max(e.interval*1000,MNe),s=new AbortController,i=()=>s.abort();process.on("SIGINT",i);let a=0;try{while(!0){if(s.signal.aborted)return{kind:"cancelled"};if(Date.now()>=r)return{kind:"unreachable",detail:"gave up waiting to reach NEMAR"};if(await u8t(o,s.signal),s.signal.aborted)return{kind:"cancelled"};let c=l8t([s.signal,AbortSignal.timeout(i8t)]),l;try{l=await Q_e(e.device_code,c),a=0}catch(d){if(s.signal.aborted)return{kind:"cancelled"};if(d instanceof L&&d.statusCode===0){console.log(u.dim(" NEMAR is unreachable; retrying...")),a=0;continue}let p=c8t(d);if(a+=1,Ln(`poll error ${a}/${jNe}: ${p} -- ${W(d)}`),console.log(u.dim(` NEMAR answered with an error (${p}); retrying...`)),a>=jNe)return{kind:"server_error",detail:p};continue}if(l.status==="pending")continue;if(l.status==="slow_down"){o=Math.max(o+a8t,e.interval*1000,MNe);continue}if(l.status==="success")return{...l.data,kind:"success"};if(l.error==="expired_token")return{kind:"expired",message:l.message};if(l.error==="access_denied")return{kind:"denied",message:l.message};return{kind:"invalid",message:l.message}}}finally{process.off("SIGINT",i)}}async function _B(e={}){let t;try{t=await Z_e(o8t())}catch(n){return{kind:"start_failed",detail:W(n)}}if(console.log(` ${t.verification_uri_complete}`),console.log(` Code: ${u.cyan(t.user_code)}`),console.log(u.dim(" (if the page asks for it)")),console.log(),e.open!==!1&&ib(t.verification_uri_complete))console.log(u.dim(" (trying to open your browser; use the link above if it doesn't)")),console.log();return d8t(t)}gr();var UNe="NEMAR_DATA_HOSTS",p8t="NEMAR_DATA_HOSTS_ONLY",f8t="https://private.nemar.org",m8t="https://private-test.nemar.org",h8t=/^[a-z]{2,3}[0-9]{6}$/;function FO(e){return h8t.test(e)}function g8t(e){return e}function qNe(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function BNe(e){let t=e.trim();if(t===""||/[?#@]/.test(t))return null;let n;try{n=new URL(t)}catch{return null}if(n.username!==""||n.password!=="")return null;if(n.pathname!=="/")return null;if(n.protocol==="https:")return n.origin;if(n.protocol==="http:"&&qNe(n.hostname))return n.origin;return null}function HNe(e){let t=[],n=[];for(let r of(e??"").split(",")){let o=r.trim();if(o==="")continue;let s=BNe(o);if(s===null)n.push(o);else if(!t.includes(s))t.push(s)}return{origins:t,rejected:n}}function zNe(e){return e.env??process.env}function MO(e={}){let t=zNe(e),n=e.isDevBuild??em,r=t[p8t]==="1"?[]:[n?m8t:f8t],{origins:o}=HNe(t[UNe]);return[...r,...o.filter((s)=>!r.includes(s))].map(g8t)}function GNe(e={}){return HNe(zNe(e)[UNe]).rejected}function jO(e,t={}){let n=BNe(e);if(n===null)return null;return MO(t).find((r)=>r===n)??null}function LO(e,t={}){return jO(e,t)!==null}function VNe(e,t={}){let n;try{n=new URL(e)}catch{return null}if(n.username!==""||n.password!=="")return null;return jO(n.origin,t)}function KTn(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&qNe(e.hostname)&&new URL(t).protocol==="http:"}var y8t="NEMAR_DATA_HOST_TIMEOUT_MS";function WNe(e,t=process.env){let n=t[y8t];if(n===void 0||!/^[0-9]+$/.test(n))return e;let r=Number(n);return r>0&&r<e?r:e}function KNe(e){if(!(e instanceof Error))return"error";let t=e.code;return typeof t==="string"&&/^[A-Z][A-Z0-9_]+$/.test(t)?`${e.name} ${t}`:e.name}var b8t="nemar";function JNe(e){let t={};for(let n of e.split(`
|
|
2298
2298
|
`)){let r=n.replace(/\r$/,"");if(r==="")break;let o=r.indexOf("=");if(o<=0)continue;t[r.slice(0,o)]=r.slice(o+1)}return t}function xB(e,t={}){let{protocol:n,host:r}=e;if(!n||!r)return!1;if(/[/?#@\s]/.test(r))return!1;return LO(`${n}://${r}`,t)}function YNe(e,t,n,r={}){if(e!=="get"||!n||!xB(t,r))return"";return`username=${b8t}
|
|
2299
2299
|
password=${n}
|
|
2300
2300
|
`}function XNe(e){let t=e.filter((n)=>!n.startsWith("-"));return t[0]==="auth"&&t[1]==="git-credential"}L_();import{appendFileSync as w8t,existsSync as rf,mkdirSync as ZNe,readFileSync as qO,writeFileSync as _8t}from"fs";import{homedir as x8t}from"os";import{join as UO}from"path";var{spawn:QNe}=globalThis.Bun;function Qm(){let e=UO(x8t(),".ssh");return{sshDir:e,privateKey:UO(e,"nemar_ed25519"),publicKey:UO(e,"nemar_ed25519.pub"),configFile:UO(e,"config")}}function eIe(){let e=Qm();return rf(e.privateKey)&&rf(e.publicKey)}async function tIe(e){let t=Qm();if(!rf(t.sshDir))try{ZNe(t.sshDir,{mode:448})}catch(n){return{success:!1,error:`Cannot create ~/.ssh directory: ${n.message}`}}if(rf(t.privateKey))try{return{success:!0,publicKey:qO(t.publicKey,"utf-8").trim()}}catch(n){return{success:!1,error:`NEMAR SSH key exists but cannot read public key: ${n.message}`}}try{let n=QNe({cmd:["ssh-keygen","-t","ed25519","-f",t.privateKey,"-N","","-C",`nemar-cli-${e}`],stdout:"pipe",stderr:"pipe"}),r=await new Response(n.stderr).text();if(await n.exited!==0)return{success:!1,error:`ssh-keygen failed: ${r}`};return{success:!0,publicKey:qO(t.publicKey,"utf-8").trim()}}catch(n){return{success:!1,error:`Failed to generate SSH key: ${n.message}`}}}function nIe(){let e=Qm();if(!rf(e.publicKey))return null;try{return qO(e.publicKey,"utf-8").trim()}catch{return null}}function v8t(){let e=Qm();if(!rf(e.configFile))return!1;try{let t=qO(e.configFile,"utf-8");return t.includes("IdentityFile ~/.ssh/nemar_ed25519")||t.includes(`IdentityFile ${e.privateKey}`)}catch{return!1}}function rIe(){let e=Qm();if(!rf(e.sshDir))try{ZNe(e.sshDir,{mode:448})}catch(n){return{success:!1,error:`Cannot create ~/.ssh directory: ${n.message}`}}if(v8t())return{success:!0};let t=`
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nemar-cli",
|
|
3
3
|
"packageManager": "bun@1.4.3",
|
|
4
|
-
"version": "0.10.40-dev.
|
|
4
|
+
"version": "0.10.40-dev.4861",
|
|
5
5
|
"description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "dist/index.js",
|