nemar-cli 0.10.5-dev.2790 → 0.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +3 -3
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -99,18 +99,18 @@ ${t}`,ESe,SSe,$Se=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,o=DSe.bind(nul
99
99
  `)}var pE=!1;var{spawn:mLe}=globalThis.Bun;async function C(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let u of t.unsetEnv??[])delete r[u];let n=mLe({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),o=!1,i;if(t.timeout)i=setTimeout(()=>{o=!0,n.kill()},t.timeout);if(mE()){let u=t.cwd?` (cwd=${t.cwd})`:"";Tf(l.dim(`$ ${e.join(" ")}${u}`))}let s=await new Response(n.stdout).text(),a=await new Response(n.stderr).text(),c=await n.exited;if(i)clearTimeout(i);if(mE()){if(s.trim())Tf(l.dim(s.trimEnd()));if(a.trim())Tf(l.yellow(a.trimEnd()));Tf(l.dim(`(exit ${c})`))}if(o)return{stdout:s,stderr:a||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:c??1,timedOut:!0};return{stdout:s,stderr:a,exitCode:c,timedOut:!1}}var vt=O(()=>{Xe()});function gLe(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function oY(e,t=gLe()){return e.installInstructions[t]}function yLe(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function xLe(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:bLe}async function iY(e){try{let{exitCode:t,stdout:r,timedOut:n}=await C(e.cmd,{timeout:xLe()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:yLe(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 Nf(){let e=Object.entries(nY);return Promise.all(e.map(async([t,r])=>{let{available:n,version:o,timedOut:i}=await iY(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:o,timedOut:i,installInstruction:oY(r)}}))}async function sY(){let t=(await Nf()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
100
100
  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 Oa(e){let r=hLe[e].map((s)=>nY[s]).filter(Boolean),n=await Promise.all(r.map(async(s)=>{let a=await iY(s);return{check:s,available:a.available,timedOut:a.timedOut}}));for(let s of n)if(s.timedOut&&s.check.required)console.warn(`Warning: ${s.check.name} did not respond to a version check in time; continuing anyway.`);let o=n.filter((s)=>!s.available&&!s.timedOut&&s.check.required).map((s)=>({tool:s.check.name,installInstruction:oY(s.check)}));if(o.length===0)return;let i=[`
101
101
  Missing required tools:`];for(let s of o)i.push(` ${s.tool} not installed`),i.push(` Install: ${s.installInstruction}`);throw Error(i.join(`
102
- `))}var nY,hLe,bLe=4000;var jf=O(()=>{vt();nY={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)"}}},hLe={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 cY;var aY=O(()=>{cY={name:"nemar-cli",version:"0.10.5-dev.2790",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.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/","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"]},devDependencies:{"@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",bcryptjs:"^3.0.3",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Ei;var qf=O(()=>{aY();Ei=cY.version});import{mkdirSync as vLe,readdirSync as wLe,unlinkSync as DLe,writeFileSync as ELe}from"fs";import{join as hE}from"path";function mY(){Ol=!0}function Fa(){return Ol}function hY(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Lf(e){pY=e,$r(`Step: ${e}`)}function Bf(){dY=!0}function gY(){return dY}function yE(){fY=!0}function yY(){return fY}function $r(e){if(Ol)process.stderr.write(`[debug] ${e}
102
+ `))}var nY,hLe,bLe=4000;var jf=O(()=>{vt();nY={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)"}}},hLe={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 cY;var aY=O(()=>{cY={name:"nemar-cli",version:"0.10.5",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.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/","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"]},devDependencies:{"@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",bcryptjs:"^3.0.3",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Ei;var qf=O(()=>{aY();Ei=cY.version});import{mkdirSync as vLe,readdirSync as wLe,unlinkSync as DLe,writeFileSync as ELe}from"fs";import{join as hE}from"path";function mY(){Ol=!0}function Fa(){return Ol}function hY(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Lf(e){pY=e,$r(`Step: ${e}`)}function Bf(){dY=!0}function gY(){return dY}function yE(){fY=!0}function yY(){return fY}function $r(e){if(Ol)process.stderr.write(`[debug] ${e}
103
103
  `)}function kLe(e){let t={};for(let[r,n]of Object.entries(e))t[r]=CLe.has(r.toLowerCase())?"[REDACTED]":n;return t}function xY(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function gE(e,t,r=0){if(r>ALe)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>gE(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[o,i]of Object.entries(t))n[o]=gE(o,i,r+1);return n}if(typeof t==="string"){if(RLe.test(e))return"[REDACTED]";return t.replace(bY,xY)}return t}function bE(e){return e.replace(OLe,"Bearer [REDACTED]").replace(FLe,"[REDACTED_AWS_KEY]").replace(PLe,"$1[REDACTED]").replace(ILe,"$1$2=[REDACTED]").replace(bY,xY)}function TLe(e){return bE(e)}function lY(e,t=$Le){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(gE("",n))}catch{}if(r=bE(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function P0(e){if(!Ol)return;let t=TLe(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?kLe(e.requestHeaders):void 0,requestBody:lY(e.requestBody),responseBody:lY(e.responseBody)};F0.push(r),$r(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=T(r);F0.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),$r(`redaction failed for ${e.method} ${t}: ${n}`)}}async function NLe(){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: ${T(t)})`)}e.push(""),e.push("Active account:");try{let t=ot();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: ${T(t)})`)}e.push(""),e.push("External tools:");try{let t=await Nf();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: ${T(t)})`)}return e}async function xE(){return(await NLe()).join(`
104
104
  `)}async function _Y(){if(!Ol||O0!==void 0)return;try{O0=await xE()}catch(e){let t=T(e);O0=`(could not build environment report: ${t})`,$r(`environment snapshot failed: ${t}`)}}function vY(e){if(uY.has(e))return{flag:e};for(let t of uY){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 jLe(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],o=vY(n);if(!o){t.push(n);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(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function qLe(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],o=vY(n);if(!o){t.push(n);continue}if(!o.kind&&r+1<e.length)r++}return t}function MLe(e){let t=[];for(let n of qLe(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 LLe(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${bE(jLe(e).join(" "))}`),r.push(""),r.push(O0??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),F0.length===0)r.push(" (none)");else F0.forEach((n,o)=>{if(r.push(` [${o+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: ${pY??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
105
105
  `)}
106
106
  `}function BLe(e,t){let r;try{r=wLe(e).filter((o)=>o.startsWith("nemar-")&&o.endsWith(".log"))}catch(o){if(o.code!=="ENOENT")$r(`could not list ${e} for log rotation: ${T(o)}`);return}r.sort();let n=r.length-t;for(let o=0;o<n;o++)try{DLe(hE(e,r[o]))}catch(i){if(i.code!=="ENOENT")$r(`could not remove old log ${r[o]}: ${T(i)}`)}}function wY(){return Mf}function DY(e,t){if(!Ol)return null;let r=hE(_E(),"logs");try{vLe(r,{recursive:!0})}catch(s){return Mf=T(s),$r(`could not create log directory ${r}: ${Mf}`),null}let o=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${MLe(e)}.log`,i=hE(r,o);try{ELe(i,LLe(e,t),"utf8")}catch(s){return Mf=T(s),$r(`could not write log file ${i}: ${Mf}`),null}return BLe(r,SLe),i}var SLe=10,$Le=2048,Ol=!1,dY=!1,fY=!1,pY,O0,F0,CLe,RLe,bY,ALe=32,OLe,FLe,PLe,ILe,uY,Mf;var jo=O(()=>{Pt();qo();jf();qf();F0=[];CLe=new Set(["authorization","cookie","set-cookie","x-api-key"]);RLe=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code)$/i,bY=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;OLe=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,FLe=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,PLe=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,ILe=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;uY=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as ULe,copyFileSync as zLe,existsSync as vE,mkdirSync as VLe,statSync as GLe}from"fs";import{homedir as I0}from"os";import{join as Fl}from"path";function WLe(e){let t=e.trim().replace(/\/+$/,"");try{let r=new URL(t);return r.protocol=r.protocol.toLowerCase(),r.host=r.host.toLowerCase(),r.toString().replace(/\/+$/,"")}catch{return console.error(`[nemar] could not parse stored apiUrl ${JSON.stringify(e)}; leaving as-is`),t}}function _E(){return process.env.NEMAR_CONFIG_DIR||Fl(I0(),".config","nemar")}function YLe(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Fl(e,"config.json");if(vE(t))return;let r=[];if(process.platform==="darwin")r.push(Fl(I0(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let n=process.env.APPDATA||Fl(I0(),"AppData","Roaming");r.push(Fl(n,"nemar-nodejs","config.json"))}r.push(Fl(I0(),".config","nemar-nodejs","config.json"));for(let n of r)if(vE(n))try{VLe(e,{recursive:!0}),zLe(n,t),console.error(`[nemar] Config migrated from ${n} to ${t}
107
107
  [nemar] You can safely remove the old file.`);return}catch(o){console.error(`[nemar] Failed to migrate config from ${n}:`,o,`
108
- [nemar] You can manually copy ${n} to ${t}`)}}function Sn(){let e=_E();if(Uf&&EY===e)return Uf;if(YLe(e),Uf=new A0({projectName:"nemar",configFileMode:wE,schema:{activeAccount:{type:"string"},accounts:{type:"object"},apiKey:{type:"string"},apiUrl:{type:"string"},username:{type:"string"},email:{type:"string"},githubUsername:{type:"string"},sandboxCompleted:{type:"boolean"},sandboxDatasetId:{type:"string"}},cwd:e}),EY=e,!SY.has(e))SY.add(e),JLe(Uf.path),ZLe(),QLe();return Uf}function JLe(e){if(process.platform==="win32")return;if(!vE(e))return;try{if((GLe(e).mode&511)!==wE)ULe(e,wE)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function ZLe(){let e=Sn(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let r=e.get("apiKey"),n=e.get("username");if(!r&&!n)return;try{let o=n||"default",i={};for(let s of XLe){let a=e.get(s);if(a!==void 0)i[s]=a}e.store={activeAccount:o,accounts:{[o]:i}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function QLe(){let e=Sn(),t=e.store,r=t.accounts,n=!1;if(r)for(let[i,s]of Object.entries(r)){let a=s?.apiUrl;if(!a)continue;if(HLe.has(WLe(a)))r[i]={...s,apiUrl:Pl},console.error(`[nemar] migrated stored apiUrl for account "${i}": ${a} -> ${Pl}`),n=!0}let o=t.apiUrl;if(r&&Object.keys(r).length>0&&o!==void 0){let{apiUrl:i,...s}=t;try{e.store=s,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),n=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(n)try{e.store={...e.store,accounts:r}}catch(i){console.error("API URL migration failed (config file unchanged):",i)}}function zf(){return Sn().get("activeAccount")}function Is(){return Sn().get("accounts")||{}}function ot(){let e={apiUrl:Pl},t=zf();if(!t)return e;return Is()[t]||e}function wt(e,t){let r=Sn(),n=r.get("activeAccount")||"default",o=r.get("accounts")||{};if(!o[n])o[n]={apiUrl:Pl};o[n][e]=t,r.store={...r.store,accounts:o,activeAccount:n}}function Vf(e){let t=zf();if(!t)return;let r=Is();if(r[t])delete r[t][e],Sn().set("accounts",r)}function $Y(){let e=Sn(),t=zf();if(!t){e.clear();return}let r=Is();delete r[t];let n=Object.keys(r);if(n.length>0)e.store={...e.store,accounts:r,activeAccount:n[0]};else e.clear()}function CY(){Sn().clear()}function Ne(){return!!ot().apiKey}function DE(){return Sn().path}function Gf(){let e=Is(),t=zf();return Object.entries(e).map(([r,n])=>({key:r,username:n.username,email:n.email,githubUsername:n.githubUsername,active:r===t,keySource:n.keySource}))}function kY(e){return e.username?.trim()||e.email}function eBe(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(Is()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){$r(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function RY(e,t){let r=Sn(),n=Is(),o;if(n[e])o=e;else if(t.email)o=eBe(t.email);let i=o?n[o]:void 0,s={...i??{apiUrl:Pl},...t};if(o&&o!==e)delete n[o];return n[e]=s,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:i}}function AY(e){let t=e.trim();if(!t)return"unchanged";let r=Sn(),n=zf();if(!n||n===t)return"unchanged";let o=Is(),i=o[n];if(!i)return"unchanged";if(o[t])return"key_taken";return delete o[n],o[t]={...i,username:t},r.store={...r.store,accounts:o,activeAccount:t},"renamed"}function EE(e){let t=Sn(),r=Is();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,o]of Object.entries(r))if(o.githubUsername===e)return t.store={...t.store,activeAccount:n},o;return null}var Pl="https://nemar-api-dev.sccn-org.workers.dev",wE=384,HLe,KLe,zmt,Uf=null,EY=null,SY,XLe;var qo=O(()=>{tY();en();Cd();jo();HLe=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);KLe=U({field:w(),blocks:oe(w()).optional(),set_on:oe(w()).optional()}).passthrough(),zmt=U({apiKey:w().optional(),apiUrl:w().url().default(Pl),username:w().optional(),email:w().email().optional(),githubUsername:w().optional(),sandboxCompleted:ge().optional(),sandboxDatasetId:w().optional(),dismissedNoticeIds:oe(R()).optional(),serviceAccess:ge().optional(),profileGaps:oe(KLe).optional(),orcidVerified:ge().optional(),role:w().optional(),accountKind:$d.optional(),pendingEmailChange:w().email().optional()});SY=new Set;XLe=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function T0(e){if(OY)return;OY=!0;let t=l.yellow("\u2500".repeat(60)),r=l.yellow.bold("[MAINTENANCE]"),n=l.dim(`mode: ${e.mode}`),o=e.eta?`
108
+ [nemar] You can manually copy ${n} to ${t}`)}}function Sn(){let e=_E();if(Uf&&EY===e)return Uf;if(YLe(e),Uf=new A0({projectName:"nemar",configFileMode:wE,schema:{activeAccount:{type:"string"},accounts:{type:"object"},apiKey:{type:"string"},apiUrl:{type:"string"},username:{type:"string"},email:{type:"string"},githubUsername:{type:"string"},sandboxCompleted:{type:"boolean"},sandboxDatasetId:{type:"string"}},cwd:e}),EY=e,!SY.has(e))SY.add(e),JLe(Uf.path),ZLe(),QLe();return Uf}function JLe(e){if(process.platform==="win32")return;if(!vE(e))return;try{if((GLe(e).mode&511)!==wE)ULe(e,wE)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function ZLe(){let e=Sn(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let r=e.get("apiKey"),n=e.get("username");if(!r&&!n)return;try{let o=n||"default",i={};for(let s of XLe){let a=e.get(s);if(a!==void 0)i[s]=a}e.store={activeAccount:o,accounts:{[o]:i}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function QLe(){let e=Sn(),t=e.store,r=t.accounts,n=!1;if(r)for(let[i,s]of Object.entries(r)){let a=s?.apiUrl;if(!a)continue;if(HLe.has(WLe(a)))r[i]={...s,apiUrl:Pl},console.error(`[nemar] migrated stored apiUrl for account "${i}": ${a} -> ${Pl}`),n=!0}let o=t.apiUrl;if(r&&Object.keys(r).length>0&&o!==void 0){let{apiUrl:i,...s}=t;try{e.store=s,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),n=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(n)try{e.store={...e.store,accounts:r}}catch(i){console.error("API URL migration failed (config file unchanged):",i)}}function zf(){return Sn().get("activeAccount")}function Is(){return Sn().get("accounts")||{}}function ot(){let e={apiUrl:Pl},t=zf();if(!t)return e;return Is()[t]||e}function wt(e,t){let r=Sn(),n=r.get("activeAccount")||"default",o=r.get("accounts")||{};if(!o[n])o[n]={apiUrl:Pl};o[n][e]=t,r.store={...r.store,accounts:o,activeAccount:n}}function Vf(e){let t=zf();if(!t)return;let r=Is();if(r[t])delete r[t][e],Sn().set("accounts",r)}function $Y(){let e=Sn(),t=zf();if(!t){e.clear();return}let r=Is();delete r[t];let n=Object.keys(r);if(n.length>0)e.store={...e.store,accounts:r,activeAccount:n[0]};else e.clear()}function CY(){Sn().clear()}function Ne(){return!!ot().apiKey}function DE(){return Sn().path}function Gf(){let e=Is(),t=zf();return Object.entries(e).map(([r,n])=>({key:r,username:n.username,email:n.email,githubUsername:n.githubUsername,active:r===t,keySource:n.keySource}))}function kY(e){return e.username?.trim()||e.email}function eBe(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(Is()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){$r(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function RY(e,t){let r=Sn(),n=Is(),o;if(n[e])o=e;else if(t.email)o=eBe(t.email);let i=o?n[o]:void 0,s={...i??{apiUrl:Pl},...t};if(o&&o!==e)delete n[o];return n[e]=s,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:i}}function AY(e){let t=e.trim();if(!t)return"unchanged";let r=Sn(),n=zf();if(!n||n===t)return"unchanged";let o=Is(),i=o[n];if(!i)return"unchanged";if(o[t])return"key_taken";return delete o[n],o[t]={...i,username:t},r.store={...r.store,accounts:o,activeAccount:t},"renamed"}function EE(e){let t=Sn(),r=Is();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,o]of Object.entries(r))if(o.githubUsername===e)return t.store={...t.store,activeAccount:n},o;return null}var Pl="https://api.nemar.org",wE=384,HLe,KLe,zmt,Uf=null,EY=null,SY,XLe;var qo=O(()=>{tY();en();Cd();jo();HLe=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);KLe=U({field:w(),blocks:oe(w()).optional(),set_on:oe(w()).optional()}).passthrough(),zmt=U({apiKey:w().optional(),apiUrl:w().url().default(Pl),username:w().optional(),email:w().email().optional(),githubUsername:w().optional(),sandboxCompleted:ge().optional(),sandboxDatasetId:w().optional(),dismissedNoticeIds:oe(R()).optional(),serviceAccess:ge().optional(),profileGaps:oe(KLe).optional(),orcidVerified:ge().optional(),role:w().optional(),accountKind:$d.optional(),pendingEmailChange:w().email().optional()});SY=new Set;XLe=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function T0(e){if(OY)return;OY=!0;let t=l.yellow("\u2500".repeat(60)),r=l.yellow.bold("[MAINTENANCE]"),n=l.dim(`mode: ${e.mode}`),o=e.eta?`
109
109
  ${l.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
110
110
  ${r} ${e.message}
111
111
  ${n}${o}
112
112
  ${t}
113
- `)}var OY=!1;var SE=O(()=>{Xe()});function N0(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(CE)return $E;return ot().apiUrl||$E}async function F(e,t={},r=!1,n){let o=`${N0()}${e}`,i={"Content-Type":"application/json","X-CLI-Version":Ei,...t.headers};if(r){let m=ot();if(!m.apiKey&&r===!0)throw new q(401,"Not authenticated. Run 'nemar auth login' first.");if(m.apiKey)i.Authorization=`Bearer ${m.apiKey}`}let s=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(o,{...t,headers:i})}catch(m){if(Fa())P0({method:s,url:o,status:null,durationMs:Date.now()-c,requestHeaders:i,requestBody:a,error:m instanceof Error?m.message:String(m)});throw new q(0,`Network error: Could not connect to ${N0()}`,{originalError:m instanceof Error?m.message:String(m)})}let d;try{d=await u.text()}catch(m){if(Fa())P0({method:s,url:o,status:u.status,durationMs:Date.now()-c,requestHeaders:i,requestBody:a,error:m instanceof Error?m.message:String(m)});throw new q(0,"Failed to read response body",{httpStatus:u.status,originalError:m instanceof Error?m.message:String(m)})}if(Fa())P0({method:s,url:o,status:u.status,durationMs:Date.now()-c,requestHeaders:i,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new q(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(f.mode==="read-only"||f.mode==="full")){let A=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",E=typeof f.eta==="string"?f.eta:null,P=new Ps(f.mode,A,E,f.details);throw T0(P),P}let m=typeof f.block_reason==="string",p=Array.isArray(f.missing)?f.missing.filter((A)=>typeof A==="string"):void 0,h=typeof f.error==="string"&&(Rq.includes(f.error)||Nq.includes(f.error)),y=typeof f.error==="string"&&(Nh.options.includes(f.error)||Bq.includes(f.error)),x=typeof f.error==="string"&&Dq.includes(f.error),v=m||h||y||x||p!==void 0&&typeof f.error==="string"&&kq.includes(f.error)?f.message||f.error:f.error||f.message;if(u.status===404&&f.error==="Not Found"&&typeof f.message==="string")v=`${f.message}. This NEMAR backend does not support this command yet.`;let S=new q(u.status,v||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,m?f.block_reason:void 0,p);if(typeof f.error==="string")S.code=f.error;if(typeof f.reason==="string")S.reason=f.reason;throw S.rawBody=f,S}if(n){let m=n.safeParse(f);if(!m.success)throw new q(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:m.error.issues});return m.data}return f}var $E="https://nemar-api-dev.sccn-org.workers.dev",CE;var Si=O(()=>{Mh();Cw();Cd();qo();jo();SE();qf();Pt();CE=$E.includes("workers.dev")});function j0(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function FY(e,t,r,n){let o=new URLSearchParams;if(e)o.set("status",e);if(t)o.set("role",t);if(r)o.set("awaiting_approval","1");if(n)o.set("kind",n);let i=o.toString()?`?${o.toString()}`:"";return F(`/admin/users${i}`,{},!0,$q)}async function PY(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function IY(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function TY(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function NY(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function jY(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function qY(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function MY(e){return F(`/admin/users/${e}`,{},!0)}async function LY(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,qh)}async function BY(e){return F(`/admin/users/${e}/keys`,{},!0,jh)}async function UY(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function kE(e,t){return F(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function zY(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function VY(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function $i(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function RE(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function AE(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function GY(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function Hf(e){return F(`/admin/datasets/${e}/doi`,{},!0)}async function OE(e,t){return F(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function HY(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function WY(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function KY(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function YY(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function JY(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function XY(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function ZY(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function QY(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function FE(e,t){let r=new URLSearchParams;if(e)r.set("status",e);if(t!==void 0)r.set("blocklisted",t?"1":"0");let n=r.toString();return F(`/admin/imports${n?`?${n}`:""}`,{},!0)}async function eJ(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function tJ(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function PE(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function rJ(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Il(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function nJ(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function oJ(e){let t=e?.limit??15;return F(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function iJ(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function sJ(e){let t=e?.limit??50;return F(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function aJ(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function cJ(e){let t=e?.limit??15;return F(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function lJ(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function uJ(e){let t=e?.limit??15,r=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)r.set("older-than",String(e.olderThan));if(e?.before!=null)r.set("before",e.before);return F(`/admin/datasets/data-integrity-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function dJ(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function fJ(e,t){let r=t?.write?"":"?dry_run=1";return F(`/admin/datasets/${e}/availability-report${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function pJ(e){let t=e?.limit??30,r=new URLSearchParams({limit:String(t)});if(e?.missingOnly)r.set("missing-only","1");return F(`/admin/datasets/availability-report-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function mJ(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function hJ(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return F(`/admin/fleet/drift${r}`,{},!0)}async function Tl(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function gJ(e){return F("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function yJ(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function bJ(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function xJ(e,t){let r=t?`?user=${encodeURIComponent(t)}`:"";return F(`/admin/email-preferences${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function IE(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function _J(){return F("/admin/summary/coverage",{},!0)}async function vJ(e,t,r){return F("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:r?.skipCanary??!1})},!0)}async function TE(e){return F("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function NE(e){return F("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function wJ(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function DJ(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/zarr-fidelity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function EJ(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let r=t.toString()?`?${t.toString()}`:"";return F(`/admin/imports/issue-triage${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function SJ(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function $J(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function CJ(e){return F("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function kJ(e){return F("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function RJ(){return F("/admin/users/duplicates",{},!0,jq)}async function AJ(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,qq)}async function OJ(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/anonymity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function FJ(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}var Nl=O(()=>{il();Si()});async function dr(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function jE(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function PJ(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function IJ(e){let t,r=0,n=[],o=!0;while(o){let i=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(r+=i.locked,i.failed?.length)n.push(...i.failed);if(o=i.hasMore,t=i.continuation_token,o&&!t)throw new q(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:r,failed:n}}var Ci=O(()=>{Si();Pt()});async function M0(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function TJ(e){return F(`/datasets/${e}/manifest`,{},!0)}async function L0(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function NJ(e){let t=e;if(!t.status)t.status="active";else if(!["active","archived","deleted"].includes(t.status))throw Error(`Invalid dataset status: ${t.status}`);if(!t.visibility)t.visibility="private";else if(!["public","private"].includes(t.visibility))throw Error(`Invalid dataset visibility: ${t.visibility}`);return t}async function Ts(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,i]of Object.entries(e.facets))t.set(o,i);if(e.includeUnknown)t.set("include_unknown","1");let r=t.toString()?`?${t.toString()}`:"",n=await F(`/datasets${r}`,{},e.mine?!0:"optional");return n.datasets=n.datasets.map(NJ),n}async function jJ(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function qJ(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",Th)}async function MJ(e,t={}){let r=new URLSearchParams({q:e});if(t.modality)r.set("modality",t.modality);if(t.limit)r.set("limit",String(t.limit));if(t.hasHed)r.set("has_hed","1");if(t.hasZarr)r.set("has_zarr","1");if(t.hasZarrVerified)r.set("has_zarr_verified","1");if(t.author)r.set("author",t.author);if(t.task)r.set("task",t.task);if(t.license)r.set("license",t.license);if(t.hasDoi)r.set("has_doi","true");if(t.dataComplete)r.set("data_complete","1");if(t.recent)r.set("recent",String(t.recent));if(t.facets)for(let[o,i]of Object.entries(t.facets))r.set(o,i);if(t.includeUnknown)r.set("include_unknown","1");return await F(`/datasets/search?${r.toString()}`,{},"optional",Iq)}async function It(e){let t=await F(`/datasets/${e}`,{},"optional");return NJ(t.dataset)}async function LJ(e){return F(`/datasets/${e}/versions`,{},!0)}async function B0(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function U0(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function qE(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function BJ(e,t){let r=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${r}`,{},!0)}async function UJ(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function zJ(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function VJ(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function GJ(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function HJ(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var q0;var Ns=O(()=>{il();Si();q0=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});async function jl(e,t={}){return F(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function z0(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function ZJ(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function QJ(e){let t=e?`?status=${e}`:"";return F(`/admin/publish/requests${t}`,{},!0)}async function eX(e,t){return F(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t})},!0)}function tBe(e,t=[]){if(e){let r=bs.indexOf(e);if(r>=0)return r+1}return Math.min(t.length+1,bs.length)}function rBe(e){if(!(e instanceof q))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}async function ql(e,t=!1,r=!1,n=!1,o,i){let c,u,d=0,f=!1,m,p=t,h=[],y;function x(b,v,S,A){if(!i)return;i({step:b,stepIndex:tBe(b,v),stepTotal:bs.length,s3LockLocked:S,s3LockTotal:A,s3LockResumed:b==="s3_lock"&&f?!0:void 0})}for(let b=1;b<=5;b++)try{let v,S=!0;do{if(v=await F(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resume:S?p:!0,sandbox:r,s3_lock_continuation_token:c,s3_lock_total:u,skip_ci_check:n})},!0),S=!1,v.step_results)h.push(...v.step_results);if(v.s3_lock_total!==void 0)u=v.s3_lock_total;if(v.s3_lock_batch_count!==void 0)d+=v.s3_lock_batch_count;let A=v.step??v.step_results?.[v.step_results.length-1]?.step;if(A&&(A!==m||A==="s3_lock"))x(A,v.steps_completed??[],A==="s3_lock"?d:void 0,A==="s3_lock"?u:void 0),m=A;if(v.hasMore&&v.s3_lock_continuation_token!==void 0)c=v.s3_lock_continuation_token;else break}while(v.hasMore);if(h.length>0)v.step_results=XJ(h);return v}catch(v){if(y=v,b===5||!rBe(v)){if(v instanceof q&&h.length>0)v.stepResults=XJ(h);throw v}let A=v;if(o?.({attempt:b,maxAttempts:5,delayMs:1e4,step:A.step,error:A.message}),await new Promise((E)=>setTimeout(E,1e4)),p=!0,c!==void 0)f=!0}throw y}function XJ(e){let t=new Map;for(let r of e)t.set(r.step,r);return Array.from(t.values())}var Wf=O(()=>{Yh();Si();Pt()});function wX(e,t){return e.filter((r)=>r.visibility==="public").map((r)=>r.dataset_id).filter((r)=>r.startsWith("nm")||r.startsWith("on")).filter((r)=>r!=="nm099999"&&!ki.has(r)).filter((r)=>t.prefix?r.startsWith(t.prefix):!0).sort()}var ki;var W0=O(()=>{ki=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});async function cBe(){try{let{exitCode:e,stderr:t}=await C(["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=5","git@github.com"]),r=t.includes("successfully authenticated");if(!r)console.warn("SSH test to github.com failed:",{exitCode:e,stderr:t.trim().slice(0,500)});return{works:r,error:r?void 0:t.trim().slice(0,500)}}catch(e){let t=e instanceof Error?e.message:String(e);return console.warn("SSH test exception:",t),{works:!1,error:t}}}async function Pa(){try{let{stdout:e,exitCode:t,stderr:r}=await C(["gh","auth","token"]);if(t!==0)return console.warn("gh CLI returned non-zero exit code:",t),console.warn("stderr:",r),{token:null,error:`gh auth token failed: ${r.trim()||"unknown error"}`};if(!e.trim())return console.warn("gh auth token returned empty output"),{token:null,error:"gh CLI returned empty token"};return{token:e.trim()}}catch(e){let t=e instanceof Error?e.message:String(e);if(console.error("Failed to get GitHub token from gh CLI:",t),t.includes("ENOENT")||t.includes("not found"))return{token:null,error:"gh CLI not installed (command not found)"};return{token:null,error:`gh CLI error: ${t}`}}}async function K0(e){try{let{stdout:t,exitCode:r,stderr:n}=await C(["gh","api","user","--jq",".login"]);if(r!==0){if(n.includes("not logged in")||n.includes("auth login"))return{authenticated:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};return{authenticated:!1,error:`gh CLI error: ${n.trim()||"unknown error"}`}}let o=t.trim();if(!o)return{authenticated:!1,error:"gh CLI returned empty username"};if(e){let i=o.toLowerCase()===e.toLowerCase();return{authenticated:!0,username:o,matches:i,error:i?void 0:`gh CLI authenticated as '${o}', expected '${e}'`}}return{authenticated:!0,username:o}}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes("ENOENT")||r.includes("not found"))return{authenticated:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{authenticated:!1,error:`Failed to verify gh CLI: ${r}`}}}async function Y0(e){if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(e))return{accepted:!1,error:`Invalid repository format: ${e}`};let{stdout:t,exitCode:r,stderr:n}=await C(["gh","api","/user/repository_invitations"]);if(r!==0){if(n.includes("not logged in")||n.includes("auth login"))return{accepted:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};if(n.includes("API rate limit")||n.includes("403"))return{accepted:!1,error:"GitHub API rate limit exceeded. Please try again in a few minutes."};if(n.includes("ENOENT")||n.includes("not found"))return{accepted:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{accepted:!1,error:`Failed to list invitations: ${n.trim()||"unknown error"}`}}let o=null;try{o=JSON.parse(t||"[]").find((u)=>u.repository.full_name===e)?.id??null}catch(a){let c=a instanceof Error?a.message:String(a);return console.error("Failed to parse GitHub invitations response:",c),console.error(" Raw response (first 500 chars):",(t||"").slice(0,500)),{accepted:!1,error:`Failed to parse GitHub API response: ${c}`}}if(!o){let{exitCode:a}=await C(["gh","api",`/repos/${e}`,"--silent"]);if(a===0)return{accepted:!0,alreadyCollaborator:!0};return{accepted:!1,error:`No pending invitation found for ${e}. You may need to accept it manually via GitHub.`}}let{exitCode:i,stderr:s}=await C(["gh","api","--method","PATCH",`/user/repository_invitations/${o}`]);if(i!==0)return{accepted:!1,error:`Failed to accept invitation: ${s.trim()||"unknown error"}`};return{accepted:!0}}async function Mo(e,t,r="origin"){let n=t;if(process.env.GH_TOKEN&&t.startsWith("git@github.com:")){let o=process.env.GH_TOKEN.trim();if(!o||/\s/.test(o))return{success:!1,error:"GH_TOKEN environment variable is set but appears malformed (empty or contains whitespace)"};n=`https://github.com/${t.replace("git@github.com:","")}`,await C(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${o}'`],{cwd:e})}else if(t.startsWith("git@github.com:")){let o=t.replace("git@github.com:",""),i=await Pa();if(i.token)n=`https://github.com/${o}`,await C(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${i.token}'`],{cwd:e});else{let s=await cBe();if(s.works)n=t;else return{success:!1,error:`GitHub authentication not configured.
113
+ `)}var OY=!1;var SE=O(()=>{Xe()});function N0(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(CE)return $E;return ot().apiUrl||$E}async function F(e,t={},r=!1,n){let o=`${N0()}${e}`,i={"Content-Type":"application/json","X-CLI-Version":Ei,...t.headers};if(r){let m=ot();if(!m.apiKey&&r===!0)throw new q(401,"Not authenticated. Run 'nemar auth login' first.");if(m.apiKey)i.Authorization=`Bearer ${m.apiKey}`}let s=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(o,{...t,headers:i})}catch(m){if(Fa())P0({method:s,url:o,status:null,durationMs:Date.now()-c,requestHeaders:i,requestBody:a,error:m instanceof Error?m.message:String(m)});throw new q(0,`Network error: Could not connect to ${N0()}`,{originalError:m instanceof Error?m.message:String(m)})}let d;try{d=await u.text()}catch(m){if(Fa())P0({method:s,url:o,status:u.status,durationMs:Date.now()-c,requestHeaders:i,requestBody:a,error:m instanceof Error?m.message:String(m)});throw new q(0,"Failed to read response body",{httpStatus:u.status,originalError:m instanceof Error?m.message:String(m)})}if(Fa())P0({method:s,url:o,status:u.status,durationMs:Date.now()-c,requestHeaders:i,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new q(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(f.mode==="read-only"||f.mode==="full")){let A=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",E=typeof f.eta==="string"?f.eta:null,P=new Ps(f.mode,A,E,f.details);throw T0(P),P}let m=typeof f.block_reason==="string",p=Array.isArray(f.missing)?f.missing.filter((A)=>typeof A==="string"):void 0,h=typeof f.error==="string"&&(Rq.includes(f.error)||Nq.includes(f.error)),y=typeof f.error==="string"&&(Nh.options.includes(f.error)||Bq.includes(f.error)),x=typeof f.error==="string"&&Dq.includes(f.error),v=m||h||y||x||p!==void 0&&typeof f.error==="string"&&kq.includes(f.error)?f.message||f.error:f.error||f.message;if(u.status===404&&f.error==="Not Found"&&typeof f.message==="string")v=`${f.message}. This NEMAR backend does not support this command yet.`;let S=new q(u.status,v||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,m?f.block_reason:void 0,p);if(typeof f.error==="string")S.code=f.error;if(typeof f.reason==="string")S.reason=f.reason;throw S.rawBody=f,S}if(n){let m=n.safeParse(f);if(!m.success)throw new q(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:m.error.issues});return m.data}return f}var $E="https://api.nemar.org",CE;var Si=O(()=>{Mh();Cw();Cd();qo();jo();SE();qf();Pt();CE=$E.includes("workers.dev")});function j0(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function FY(e,t,r,n){let o=new URLSearchParams;if(e)o.set("status",e);if(t)o.set("role",t);if(r)o.set("awaiting_approval","1");if(n)o.set("kind",n);let i=o.toString()?`?${o.toString()}`:"";return F(`/admin/users${i}`,{},!0,$q)}async function PY(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function IY(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function TY(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function NY(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function jY(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function qY(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function MY(e){return F(`/admin/users/${e}`,{},!0)}async function LY(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,qh)}async function BY(e){return F(`/admin/users/${e}/keys`,{},!0,jh)}async function UY(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function kE(e,t){return F(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function zY(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function VY(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function $i(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function RE(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function AE(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function GY(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function Hf(e){return F(`/admin/datasets/${e}/doi`,{},!0)}async function OE(e,t){return F(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function HY(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function WY(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function KY(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function YY(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function JY(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function XY(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function ZY(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function QY(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function FE(e,t){let r=new URLSearchParams;if(e)r.set("status",e);if(t!==void 0)r.set("blocklisted",t?"1":"0");let n=r.toString();return F(`/admin/imports${n?`?${n}`:""}`,{},!0)}async function eJ(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function tJ(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function PE(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function rJ(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Il(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function nJ(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function oJ(e){let t=e?.limit??15;return F(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function iJ(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function sJ(e){let t=e?.limit??50;return F(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function aJ(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function cJ(e){let t=e?.limit??15;return F(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function lJ(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function uJ(e){let t=e?.limit??15,r=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)r.set("older-than",String(e.olderThan));if(e?.before!=null)r.set("before",e.before);return F(`/admin/datasets/data-integrity-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function dJ(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function fJ(e,t){let r=t?.write?"":"?dry_run=1";return F(`/admin/datasets/${e}/availability-report${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function pJ(e){let t=e?.limit??30,r=new URLSearchParams({limit:String(t)});if(e?.missingOnly)r.set("missing-only","1");return F(`/admin/datasets/availability-report-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function mJ(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function hJ(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return F(`/admin/fleet/drift${r}`,{},!0)}async function Tl(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function gJ(e){return F("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function yJ(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function bJ(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function xJ(e,t){let r=t?`?user=${encodeURIComponent(t)}`:"";return F(`/admin/email-preferences${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function IE(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function _J(){return F("/admin/summary/coverage",{},!0)}async function vJ(e,t,r){return F("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:r?.skipCanary??!1})},!0)}async function TE(e){return F("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function NE(e){return F("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function wJ(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function DJ(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/zarr-fidelity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function EJ(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let r=t.toString()?`?${t.toString()}`:"";return F(`/admin/imports/issue-triage${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function SJ(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function $J(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function CJ(e){return F("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function kJ(e){return F("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function RJ(){return F("/admin/users/duplicates",{},!0,jq)}async function AJ(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,qq)}async function OJ(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/anonymity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function FJ(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}var Nl=O(()=>{il();Si()});async function dr(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function jE(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function PJ(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function IJ(e){let t,r=0,n=[],o=!0;while(o){let i=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(r+=i.locked,i.failed?.length)n.push(...i.failed);if(o=i.hasMore,t=i.continuation_token,o&&!t)throw new q(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:r,failed:n}}var Ci=O(()=>{Si();Pt()});async function M0(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function TJ(e){return F(`/datasets/${e}/manifest`,{},!0)}async function L0(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function NJ(e){let t=e;if(!t.status)t.status="active";else if(!["active","archived","deleted"].includes(t.status))throw Error(`Invalid dataset status: ${t.status}`);if(!t.visibility)t.visibility="private";else if(!["public","private"].includes(t.visibility))throw Error(`Invalid dataset visibility: ${t.visibility}`);return t}async function Ts(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,i]of Object.entries(e.facets))t.set(o,i);if(e.includeUnknown)t.set("include_unknown","1");let r=t.toString()?`?${t.toString()}`:"",n=await F(`/datasets${r}`,{},e.mine?!0:"optional");return n.datasets=n.datasets.map(NJ),n}async function jJ(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function qJ(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",Th)}async function MJ(e,t={}){let r=new URLSearchParams({q:e});if(t.modality)r.set("modality",t.modality);if(t.limit)r.set("limit",String(t.limit));if(t.hasHed)r.set("has_hed","1");if(t.hasZarr)r.set("has_zarr","1");if(t.hasZarrVerified)r.set("has_zarr_verified","1");if(t.author)r.set("author",t.author);if(t.task)r.set("task",t.task);if(t.license)r.set("license",t.license);if(t.hasDoi)r.set("has_doi","true");if(t.dataComplete)r.set("data_complete","1");if(t.recent)r.set("recent",String(t.recent));if(t.facets)for(let[o,i]of Object.entries(t.facets))r.set(o,i);if(t.includeUnknown)r.set("include_unknown","1");return await F(`/datasets/search?${r.toString()}`,{},"optional",Iq)}async function It(e){let t=await F(`/datasets/${e}`,{},"optional");return NJ(t.dataset)}async function LJ(e){return F(`/datasets/${e}/versions`,{},!0)}async function B0(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function U0(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function qE(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function BJ(e,t){let r=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${r}`,{},!0)}async function UJ(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function zJ(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function VJ(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function GJ(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function HJ(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var q0;var Ns=O(()=>{il();Si();q0=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});async function jl(e,t={}){return F(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function z0(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function ZJ(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function QJ(e){let t=e?`?status=${e}`:"";return F(`/admin/publish/requests${t}`,{},!0)}async function eX(e,t){return F(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t})},!0)}function tBe(e,t=[]){if(e){let r=bs.indexOf(e);if(r>=0)return r+1}return Math.min(t.length+1,bs.length)}function rBe(e){if(!(e instanceof q))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}async function ql(e,t=!1,r=!1,n=!1,o,i){let c,u,d=0,f=!1,m,p=t,h=[],y;function x(b,v,S,A){if(!i)return;i({step:b,stepIndex:tBe(b,v),stepTotal:bs.length,s3LockLocked:S,s3LockTotal:A,s3LockResumed:b==="s3_lock"&&f?!0:void 0})}for(let b=1;b<=5;b++)try{let v,S=!0;do{if(v=await F(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resume:S?p:!0,sandbox:r,s3_lock_continuation_token:c,s3_lock_total:u,skip_ci_check:n})},!0),S=!1,v.step_results)h.push(...v.step_results);if(v.s3_lock_total!==void 0)u=v.s3_lock_total;if(v.s3_lock_batch_count!==void 0)d+=v.s3_lock_batch_count;let A=v.step??v.step_results?.[v.step_results.length-1]?.step;if(A&&(A!==m||A==="s3_lock"))x(A,v.steps_completed??[],A==="s3_lock"?d:void 0,A==="s3_lock"?u:void 0),m=A;if(v.hasMore&&v.s3_lock_continuation_token!==void 0)c=v.s3_lock_continuation_token;else break}while(v.hasMore);if(h.length>0)v.step_results=XJ(h);return v}catch(v){if(y=v,b===5||!rBe(v)){if(v instanceof q&&h.length>0)v.stepResults=XJ(h);throw v}let A=v;if(o?.({attempt:b,maxAttempts:5,delayMs:1e4,step:A.step,error:A.message}),await new Promise((E)=>setTimeout(E,1e4)),p=!0,c!==void 0)f=!0}throw y}function XJ(e){let t=new Map;for(let r of e)t.set(r.step,r);return Array.from(t.values())}var Wf=O(()=>{Yh();Si();Pt()});function wX(e,t){return e.filter((r)=>r.visibility==="public").map((r)=>r.dataset_id).filter((r)=>r.startsWith("nm")||r.startsWith("on")).filter((r)=>r!=="nm099999"&&!ki.has(r)).filter((r)=>t.prefix?r.startsWith(t.prefix):!0).sort()}var ki;var W0=O(()=>{ki=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});async function cBe(){try{let{exitCode:e,stderr:t}=await C(["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=5","git@github.com"]),r=t.includes("successfully authenticated");if(!r)console.warn("SSH test to github.com failed:",{exitCode:e,stderr:t.trim().slice(0,500)});return{works:r,error:r?void 0:t.trim().slice(0,500)}}catch(e){let t=e instanceof Error?e.message:String(e);return console.warn("SSH test exception:",t),{works:!1,error:t}}}async function Pa(){try{let{stdout:e,exitCode:t,stderr:r}=await C(["gh","auth","token"]);if(t!==0)return console.warn("gh CLI returned non-zero exit code:",t),console.warn("stderr:",r),{token:null,error:`gh auth token failed: ${r.trim()||"unknown error"}`};if(!e.trim())return console.warn("gh auth token returned empty output"),{token:null,error:"gh CLI returned empty token"};return{token:e.trim()}}catch(e){let t=e instanceof Error?e.message:String(e);if(console.error("Failed to get GitHub token from gh CLI:",t),t.includes("ENOENT")||t.includes("not found"))return{token:null,error:"gh CLI not installed (command not found)"};return{token:null,error:`gh CLI error: ${t}`}}}async function K0(e){try{let{stdout:t,exitCode:r,stderr:n}=await C(["gh","api","user","--jq",".login"]);if(r!==0){if(n.includes("not logged in")||n.includes("auth login"))return{authenticated:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};return{authenticated:!1,error:`gh CLI error: ${n.trim()||"unknown error"}`}}let o=t.trim();if(!o)return{authenticated:!1,error:"gh CLI returned empty username"};if(e){let i=o.toLowerCase()===e.toLowerCase();return{authenticated:!0,username:o,matches:i,error:i?void 0:`gh CLI authenticated as '${o}', expected '${e}'`}}return{authenticated:!0,username:o}}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes("ENOENT")||r.includes("not found"))return{authenticated:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{authenticated:!1,error:`Failed to verify gh CLI: ${r}`}}}async function Y0(e){if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(e))return{accepted:!1,error:`Invalid repository format: ${e}`};let{stdout:t,exitCode:r,stderr:n}=await C(["gh","api","/user/repository_invitations"]);if(r!==0){if(n.includes("not logged in")||n.includes("auth login"))return{accepted:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};if(n.includes("API rate limit")||n.includes("403"))return{accepted:!1,error:"GitHub API rate limit exceeded. Please try again in a few minutes."};if(n.includes("ENOENT")||n.includes("not found"))return{accepted:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{accepted:!1,error:`Failed to list invitations: ${n.trim()||"unknown error"}`}}let o=null;try{o=JSON.parse(t||"[]").find((u)=>u.repository.full_name===e)?.id??null}catch(a){let c=a instanceof Error?a.message:String(a);return console.error("Failed to parse GitHub invitations response:",c),console.error(" Raw response (first 500 chars):",(t||"").slice(0,500)),{accepted:!1,error:`Failed to parse GitHub API response: ${c}`}}if(!o){let{exitCode:a}=await C(["gh","api",`/repos/${e}`,"--silent"]);if(a===0)return{accepted:!0,alreadyCollaborator:!0};return{accepted:!1,error:`No pending invitation found for ${e}. You may need to accept it manually via GitHub.`}}let{exitCode:i,stderr:s}=await C(["gh","api","--method","PATCH",`/user/repository_invitations/${o}`]);if(i!==0)return{accepted:!1,error:`Failed to accept invitation: ${s.trim()||"unknown error"}`};return{accepted:!0}}async function Mo(e,t,r="origin"){let n=t;if(process.env.GH_TOKEN&&t.startsWith("git@github.com:")){let o=process.env.GH_TOKEN.trim();if(!o||/\s/.test(o))return{success:!1,error:"GH_TOKEN environment variable is set but appears malformed (empty or contains whitespace)"};n=`https://github.com/${t.replace("git@github.com:","")}`,await C(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${o}'`],{cwd:e})}else if(t.startsWith("git@github.com:")){let o=t.replace("git@github.com:",""),i=await Pa();if(i.token)n=`https://github.com/${o}`,await C(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${i.token}'`],{cwd:e});else{let s=await cBe();if(s.works)n=t;else return{success:!1,error:`GitHub authentication not configured.
114
114
 
115
115
  gh CLI failed: ${i.error||"could not get token"}
116
116
  SSH failed: ${s.error||"could not connect"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nemar-cli",
3
- "version": "0.10.5-dev.2790",
3
+ "version": "0.10.5",
4
4
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",