nemar-cli 0.10.19-dev.3634 → 0.10.19

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 +4 -4
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -99,18 +99,18 @@ ${t}`,t3e,r3e,n3e=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,i=e3e.bind(nul
99
99
  `)}var mC=!1;var{spawn:MXe}=globalThis.Bun;function ou(e,t=[]){let r=e.replace(qXe,'("$1","<redacted>")');for(let n of t)if(n.length>=LXe)r=r.split(n).join("<redacted>");return r}function Nw(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 i of t){let o=n[i];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function fne(e,t){let r=e.getReader(),n=new TextDecoder,i="";while(!0){let{done:o,value:s}=await r.read();if(o)break;if(s.byteLength===0)continue;t(),i+=n.decode(s,{stream:!0})}return i+n.decode()}async function k(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let b of t.unsetEnv??[])delete r[b];let n=MXe({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),i=!1,o,s,a=performance.now(),c=()=>{if(s!==void 0)clearTimeout(s),s=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),s=setTimeout(()=>{s=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??BXe)};if(u(),t.timeout)o=setTimeout(()=>{i=!0,c(),n.kill()},t.timeout);let d=Fw()?[...Nw(r),...t.redact??[]]:[];if(Fw()){let b=t.cwd?` (cwd=${t.cwd})`:"";Kc(l.dim(ou(`$ ${e.join(" ")}${b}`,d)))}let f=()=>{a=performance.now(),u()},p,m,g,h=n.exited.then((b)=>(c(),b));try{[p,m,g]=await Promise.all([fne(n.stdout,f),fne(n.stderr,f),h])}finally{if(c(),o)clearTimeout(o)}if(Fw()){if(t.sensitiveOutput)Kc(l.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())Kc(l.dim(ou(p.trimEnd(),d)));if(m.trim())Kc(l.yellow(ou(m.trimEnd(),d)))}Kc(l.dim(`(exit ${g})`))}if(i)return{stdout:p,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:g??1,timedOut:!0};return{stdout:p,stderr:m,exitCode:g,timedOut:!1}}var qXe,LXe=8,BXe=120000;var Mt=N(()=>{Ne();qXe=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function zXe(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function mne(e,t=zXe()){return e.installInstructions[t]}function VXe(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function GXe(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:HXe}async function hne(e){try{let{exitCode:t,stdout:r,timedOut:n}=await k(e.cmd,{timeout:GXe()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:VXe(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 qh(){let e=Object.entries(pne);return Promise.all(e.map(async([t,r])=>{let{available:n,version:i,timedOut:o}=await hne(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:i,timedOut:o,installInstruction:mne(r)}}))}async function gne(){let t=(await qh()).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 su(e){let r=UXe[e].map((s)=>pne[s]).filter(Boolean),n=await Promise.all(r.map(async(s)=>{let a=await hne(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 i=n.filter((s)=>!s.available&&!s.timedOut&&s.check.required).map((s)=>({tool:s.check.name,installInstruction:mne(s.check)}));if(i.length===0)return;let o=[`
101
101
  Missing required tools:`];for(let s of i)o.push(` ${s.tool} not installed`),o.push(` Install: ${s.installInstruction}`);throw Error(o.join(`
102
- `))}var pne,UXe,HXe=4000;var Lh=N(()=>{Mt();pne={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)"}}},UXe={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 bne;var yne=N(()=>{bne={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.19-dev.3634",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/","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"]},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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var oo;var Gf=N(()=>{yne();oo=bne.version});import{mkdirSync as KXe,readdirSync as YXe,unlinkSync as JXe,writeFileSync as XXe}from"fs";import{join as hC}from"path";function Ene(){Wf=!0}function au(){return Wf}function Sne(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Uh(e){Dne=e,Zt(`Step: ${e}`)}function zh(){vne=!0}function $ne(){return vne}function Pe(){if(_ne)return;yC=!0}function bC(){yC=!1,_ne=!0}function kne(){return yC}function Zt(e){if(Wf)process.stderr.write(`[debug] ${e}
102
+ `))}var pne,UXe,HXe=4000;var Lh=N(()=>{Mt();pne={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)"}}},UXe={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 bne;var yne=N(()=>{bne={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.19",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/","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"]},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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var oo;var Gf=N(()=>{yne();oo=bne.version});import{mkdirSync as KXe,readdirSync as YXe,unlinkSync as JXe,writeFileSync as XXe}from"fs";import{join as hC}from"path";function Ene(){Wf=!0}function au(){return Wf}function Sne(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Uh(e){Dne=e,Zt(`Step: ${e}`)}function zh(){vne=!0}function $ne(){return vne}function Pe(){if(_ne)return;yC=!0}function bC(){yC=!1,_ne=!0}function kne(){return yC}function Zt(e){if(Wf)process.stderr.write(`[debug] ${e}
103
103
  `)}function tQe(e){let t={};for(let[r,n]of Object.entries(e))t[r]=eQe.has(r.toLowerCase())?"[REDACTED]":n;return t}function Cne(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function gC(e,t,r=0){if(r>nQe)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>gC(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[i,o]of Object.entries(t))n[i]=gC(i,o,r+1);return n}if(typeof t==="string"){if(rQe.test(e))return"[REDACTED]";return t.replace(Rne,Cne)}return t}function xC(e){return e.replace(iQe,"Bearer [REDACTED]").replace(oQe,"[REDACTED_AWS_KEY]").replace(sQe,"$1[REDACTED]").replace(aQe,"$1$2=[REDACTED]").replace(Rne,Cne)}function cQe(e){return xC(e)}function xne(e,t=ZXe){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(gC("",n))}catch{}if(r=xC(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function qw(e){if(!Wf)return;let t=cQe(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?tQe(e.requestHeaders):void 0,requestBody:xne(e.requestBody),responseBody:xne(e.responseBody)};Mw.push(r),Zt(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=L(r);Mw.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),Zt(`redaction failed for ${e.method} ${t}: ${n}`)}}async function lQe(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${oo}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${L(t)})`)}e.push(""),e.push("Active account:");try{let t=Ft();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: ${L(t)})`)}e.push(""),e.push("External tools:");try{let t=await qh();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: ${L(t)})`)}return e}async function wC(){return(await lQe()).join(`
104
104
  `)}async function Ane(){if(!Wf||jw!==void 0)return;try{jw=await wC()}catch(e){let t=L(e);jw=`(could not build environment report: ${t})`,Zt(`environment snapshot failed: ${t}`)}}function One(e){if(wne.has(e))return{flag:e};for(let t of wne){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 uQe(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=One(n);if(!i){t.push(n);continue}if(i.kind==="long-eq")t.push(`${i.flag}=[REDACTED]`);else if(i.kind==="short-attached")t.push(`${i.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function dQe(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=One(n);if(!i){t.push(n);continue}if(!i.kind&&r+1<e.length)r++}return t}function fQe(e){let t=[];for(let n of dQe(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 pQe(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${xC(uQe(e).join(" "))}`),r.push(""),r.push(jw??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),Mw.length===0)r.push(" (none)");else Mw.forEach((n,i)=>{if(r.push(` [${i+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: ${Dne??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
105
105
  `)}
106
106
  `}function mQe(e,t){let r;try{r=YXe(e).filter((i)=>i.startsWith("nemar-")&&i.endsWith(".log"))}catch(i){if(i.code!=="ENOENT")Zt(`could not list ${e} for log rotation: ${L(i)}`);return}r.sort();let n=r.length-t;for(let i=0;i<n;i++)try{JXe(hC(e,r[i]))}catch(o){if(o.code!=="ENOENT")Zt(`could not remove old log ${r[i]}: ${L(o)}`)}}function Tne(){return Bh}function Pne(e,t){if(!Wf)return null;let r=hC(vC(),"logs");try{KXe(r,{recursive:!0})}catch(s){return Bh=L(s),Zt(`could not create log directory ${r}: ${Bh}`),null}let i=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${fQe(e)}.log`,o=hC(r,i);try{XXe(o,pQe(e,t),"utf8")}catch(s){return Bh=L(s),Zt(`could not write log file ${o}: ${Bh}`),null}return mQe(r,QXe),o}var QXe=10,ZXe=2048,Wf=!1,vne=!1,yC=!1,_ne=!1,Dne,jw,Mw,eQe,rQe,Rne,nQe=32,iQe,oQe,sQe,aQe,wne,Bh;var jr=N(()=>{At();Oi();Lh();Gf();Mw=[];eQe=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);rQe=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code)$/i,Rne=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;iQe=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,oQe=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,sQe=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,aQe=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;wne=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as hQe,copyFileSync as gQe,existsSync as _C,mkdirSync as yQe,statSync as bQe}from"fs";import{homedir as Lw}from"os";import{join as Kf}from"path";function wQe(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 vC(){return process.env.NEMAR_CONFIG_DIR||Kf(Lw(),".config","nemar")}function _Qe(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Kf(e,"config.json");if(_C(t))return;let r=[];if(process.platform==="darwin")r.push(Kf(Lw(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let n=process.env.APPDATA||Kf(Lw(),"AppData","Roaming");r.push(Kf(n,"nemar-nodejs","config.json"))}r.push(Kf(Lw(),".config","nemar-nodejs","config.json"));for(let n of r)if(_C(n))try{yQe(e,{recursive:!0}),gQe(n,t),console.error(`[nemar] Config migrated from ${n} to ${t}
107
107
  [nemar] You can safely remove the old file.`);return}catch(i){console.error(`[nemar] Failed to migrate config from ${n}:`,i,`
108
- [nemar] You can manually copy ${n} to ${t}`)}}function Ti(){let e=vC();if(Vh&&Ine===e)return Vh;if(_Qe(e),Vh=new Iw({projectName:"nemar",configFileMode:DC,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}),Ine=e,!Fne.has(e))Fne.add(e),DQe(Vh.path),SQe(),$Qe();return Vh}function DQe(e){if(process.platform==="win32")return;if(!_C(e))return;try{if((bQe(e).mode&511)!==DC)hQe(e,DC)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function SQe(){let e=Ti(),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 i=n||"default",o={};for(let s of EQe){let a=e.get(s);if(a!==void 0)o[s]=a}e.store={activeAccount:i,accounts:{[i]:o}}}catch(i){console.error("Config migration failed (legacy config preserved):",i)}}function $Qe(){let e=Ti(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,s]of Object.entries(r)){let a=s?.apiUrl;if(!a)continue;if(xQe.has(wQe(a)))r[o]={...s,apiUrl:Yf},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${a} -> ${Yf}`),n=!0}let i=t.apiUrl;if(r&&Object.keys(r).length>0&&i!==void 0){let{apiUrl:o,...s}=t;try{e.store=s,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${i})`),n=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(n)try{e.store={...e.store,accounts:r}}catch(o){console.error("API URL migration failed (config file unchanged):",o)}}function Hh(){return Ti().get("activeAccount")}function Yc(){return Ti().get("accounts")||{}}function Ft(){let e={apiUrl:Yf},t=Hh();if(!t)return e;return Yc()[t]||e}function er(e,t){let r=Ti(),n=r.get("activeAccount")||"default",i=r.get("accounts")||{};if(!i[n])i[n]={apiUrl:Yf};i[n][e]=t,r.store={...r.store,accounts:i,activeAccount:n}}function Gh(e){let t=Hh();if(!t)return;let r=Yc();if(r[t])delete r[t][e],Ti().set("accounts",r)}function Nne(){let e=Ti(),t=Hh();if(!t){e.clear();return}let r=Yc();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 jne(){Ti().clear()}function et(){return!!Ft().apiKey}function EC(){return Ti().path}function Wh(){let e=Yc(),t=Hh();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 Mne(e){return e.username?.trim()||e.email}function kQe(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(Yc()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){Zt(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function qne(e,t){let r=Ti(),n=Yc(),i;if(n[e])i=e;else if(t.email)i=kQe(t.email);let o=i?n[i]:void 0,s={...o??{apiUrl:Yf},...t};if(i&&i!==e)delete n[i];return n[e]=s,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function Lne(e){let t=e.trim();if(!t)return"unchanged";let r=Ti(),n=Hh();if(!n||n===t)return"unchanged";let i=Yc(),o=i[n];if(!o)return"unchanged";if(i[t])return"key_taken";return delete i[n],i[t]={...o,username:t},r.store={...r.store,accounts:i,activeAccount:t},"renamed"}function SC(e){let t=Ti(),r=Yc();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,i]of Object.entries(r))if(i.githubUsername===e)return t.store={...t.store,activeAccount:n},i;return null}var Yf="https://nemar-api-dev.sccn-org.workers.dev",DC=384,xQe,vQe,dAt,Vh=null,Ine=null,Fne,EQe;var Oi=N(()=>{une();Fn();Gd();jr();xQe=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);vQe=Y({field:_(),blocks:le(_()).optional(),set_on:le(_()).optional()}).passthrough(),dAt=Y({apiKey:_().optional(),apiUrl:_().url().default(Yf),username:_().optional(),email:_().email().optional(),githubUsername:_().optional(),sandboxCompleted:Le().optional(),sandboxDatasetId:_().optional(),dismissedNoticeIds:le(C()).optional(),serviceAccess:Le().optional(),profileGaps:le(vQe).optional(),orcidVerified:Le().optional(),role:_().optional(),accountKind:Hl.optional(),pendingEmailChange:_().email().optional()});Fne=new Set;EQe=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function Bw(e){if(Bne)return;Bne=!0;let t=l.yellow("\u2500".repeat(60)),r=l.yellow.bold("[MAINTENANCE]"),n=l.dim(`mode: ${e.mode}`),i=e.eta?`
108
+ [nemar] You can manually copy ${n} to ${t}`)}}function Ti(){let e=vC();if(Vh&&Ine===e)return Vh;if(_Qe(e),Vh=new Iw({projectName:"nemar",configFileMode:DC,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}),Ine=e,!Fne.has(e))Fne.add(e),DQe(Vh.path),SQe(),$Qe();return Vh}function DQe(e){if(process.platform==="win32")return;if(!_C(e))return;try{if((bQe(e).mode&511)!==DC)hQe(e,DC)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function SQe(){let e=Ti(),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 i=n||"default",o={};for(let s of EQe){let a=e.get(s);if(a!==void 0)o[s]=a}e.store={activeAccount:i,accounts:{[i]:o}}}catch(i){console.error("Config migration failed (legacy config preserved):",i)}}function $Qe(){let e=Ti(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,s]of Object.entries(r)){let a=s?.apiUrl;if(!a)continue;if(xQe.has(wQe(a)))r[o]={...s,apiUrl:Yf},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${a} -> ${Yf}`),n=!0}let i=t.apiUrl;if(r&&Object.keys(r).length>0&&i!==void 0){let{apiUrl:o,...s}=t;try{e.store=s,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${i})`),n=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(n)try{e.store={...e.store,accounts:r}}catch(o){console.error("API URL migration failed (config file unchanged):",o)}}function Hh(){return Ti().get("activeAccount")}function Yc(){return Ti().get("accounts")||{}}function Ft(){let e={apiUrl:Yf},t=Hh();if(!t)return e;return Yc()[t]||e}function er(e,t){let r=Ti(),n=r.get("activeAccount")||"default",i=r.get("accounts")||{};if(!i[n])i[n]={apiUrl:Yf};i[n][e]=t,r.store={...r.store,accounts:i,activeAccount:n}}function Gh(e){let t=Hh();if(!t)return;let r=Yc();if(r[t])delete r[t][e],Ti().set("accounts",r)}function Nne(){let e=Ti(),t=Hh();if(!t){e.clear();return}let r=Yc();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 jne(){Ti().clear()}function et(){return!!Ft().apiKey}function EC(){return Ti().path}function Wh(){let e=Yc(),t=Hh();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 Mne(e){return e.username?.trim()||e.email}function kQe(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(Yc()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){Zt(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function qne(e,t){let r=Ti(),n=Yc(),i;if(n[e])i=e;else if(t.email)i=kQe(t.email);let o=i?n[i]:void 0,s={...o??{apiUrl:Yf},...t};if(i&&i!==e)delete n[i];return n[e]=s,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function Lne(e){let t=e.trim();if(!t)return"unchanged";let r=Ti(),n=Hh();if(!n||n===t)return"unchanged";let i=Yc(),o=i[n];if(!o)return"unchanged";if(i[t])return"key_taken";return delete i[n],i[t]={...o,username:t},r.store={...r.store,accounts:i,activeAccount:t},"renamed"}function SC(e){let t=Ti(),r=Yc();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,i]of Object.entries(r))if(i.githubUsername===e)return t.store={...t.store,activeAccount:n},i;return null}var Yf="https://api.nemar.org",DC=384,xQe,vQe,dAt,Vh=null,Ine=null,Fne,EQe;var Oi=N(()=>{une();Fn();Gd();jr();xQe=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);vQe=Y({field:_(),blocks:le(_()).optional(),set_on:le(_()).optional()}).passthrough(),dAt=Y({apiKey:_().optional(),apiUrl:_().url().default(Yf),username:_().optional(),email:_().email().optional(),githubUsername:_().optional(),sandboxCompleted:Le().optional(),sandboxDatasetId:_().optional(),dismissedNoticeIds:le(C()).optional(),serviceAccess:Le().optional(),profileGaps:le(vQe).optional(),orcidVerified:Le().optional(),role:_().optional(),accountKind:Hl.optional(),pendingEmailChange:_().email().optional()});Fne=new Set;EQe=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function Bw(e){if(Bne)return;Bne=!0;let t=l.yellow("\u2500".repeat(60)),r=l.yellow.bold("[MAINTENANCE]"),n=l.dim(`mode: ${e.mode}`),i=e.eta?`
109
109
  ${l.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
110
110
  ${r} ${e.message}
111
111
  ${n}${i}
112
112
  ${t}
113
- `)}var Bne=!1;var $C=N(()=>{Ne()});function Uw(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(RC)return kC;return Ft().apiUrl||kC}async function M(e,t={},r=!1,n){let i=`${Uw()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":oo,...t.headers};if(r){let p=Ft();if(!p.apiKey&&r===!0)throw new B(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)o.Authorization=`Bearer ${p.apiKey}`}let s=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(i,{...t,headers:o})}catch(p){if(au())qw({method:s,url:i,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new B(0,`Network error: Could not connect to ${Uw()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(au())qw({method:s,url:i,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new B(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(au())qw({method:s,url:i,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new B(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(f.mode==="read-only"||f.mode==="full")){let U=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",P=typeof f.eta==="string"?f.eta:null,j=new cc(f.mode,U,P,f.details);throw Bw(j),j}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((U)=>typeof U==="string"):void 0,g=typeof f.error==="string"&&(Fz.includes(f.error)||Qz.includes(f.error)),h=typeof f.error==="string"&&(xb.options.includes(f.error)||nV.includes(f.error)),b=typeof f.error==="string"&&Cz.includes(f.error),x=typeof f.error==="string"&&Nz.includes(f.error),w=typeof f.error==="string"&&Yz.includes(f.error),D=typeof f.error==="string"&&Kz.includes(f.error),R=typeof f.error==="string"&&Jz.includes(f.error),O=p||D||R||g||h||b||x||w||m!==void 0&&typeof f.error==="string"&&Iz.includes(f.error)?f.message||f.error:f.error||f.message;if(u.status===404&&f.error==="Not Found"&&typeof f.message==="string")O=`${f.message}. This NEMAR backend does not support this command yet.`;let A=new B(u.status,O||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")A.code=f.error;if(typeof f.reason==="string")A.reason=f.reason;throw A.rawBody=f,A}if(n){let p=n.safeParse(f);if(!p.success)throw new B(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var kC="https://nemar-api-dev.sccn-org.workers.dev",RC;var na=N(()=>{Zm();_b();X1();eh();Gd();Oi();jr();$C();Gf();At();RC=kC.includes("workers.dev")});async function Jf(e,t={}){return M(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function Xf(e){return M(`/datasets/${e}/publish/status`,{},!0)}async function Vne(e){return M(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function Hne(e){return M(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function cu(e={}){let{statuses:t,search:r}=typeof e==="string"?{statuses:e?[e]:[]}:e,n=await Une(t,r),i=n;if(t!==void 0&&t.length>1&&n.requests.length===0){let o=[];for(let a of new Set(t))o.push(await Une([a],r));let s=o.flatMap((a)=>a.requests).sort(Gne);i={...n,requests:s,count:s.length}}return r?RQe(i,r):i}function Gne(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function Une(e,t){let r=new URLSearchParams;if(e&&e.length>0)r.set("status",e.join(","));if(t)r.set("search",t);let n=r.size>0?`?${r}`:"";return M(`/admin/publish/requests${n}`,{},!0)}function RQe(e,t){let r=e.requests.filter((o)=>CV(t,[o.dataset_id,o.requested_by_username,o.dataset_name])),n=(o)=>AV(o.dataset_id,t)?0:1,i=[...r].sort((o,s)=>n(o)-n(s)||Gne(o,s));return{...e,requests:i,count:i.length}}async function Qf(e,t,r){return M(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...r!==void 0?{request_id:r}:{}})},!0)}async function zw(e){return M(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function Vw(e){return M(`/admin/publish/${e}/review`,{},!0)}async function Wne(e){return M(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function Kne(e,t){let r={message:t};return M(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},!0)}function Zf(e){if(!(e instanceof B))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let r=t.code;return typeof r==="string"?r:void 0}function CQe(e,t=[]){if(e){let r=No.indexOf(e);if(r>=0)return r+1}return Math.min(t.length+1,No.length)}function AQe(e){if(!(e instanceof B))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}function OQe(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return Pb;let t=Number(e);return Number.isSafeInteger(t)&&t<=Pb?t:Pb}async function ep(e,t=!1,r=!1,n=!1,i,o,s,a,c){let d=OQe(),f,p,m=0,g=!1,h,b=t,x=[],w;function D(R,E,O,A){if(!o)return;o({step:R,stepIndex:CQe(R,E),stepTotal:No.length,s3LockLocked:O,s3LockTotal:A,s3LockResumed:R==="s3_lock"&&g?!0:void 0})}for(let R=1;R<=5;R++)try{let E,O=!0;do{if(E=await M(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[Xz]:c.dispatchToken}:{}},body:JSON.stringify({resume:O?b:!0,sandbox:r,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:n,...s!==void 0?{acknowledge_identifier_screen:s}:{},...a!==void 0?{[$V]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),O=!1,E.step_results)x.push(...E.step_results);if(E.s3_lock_total!==void 0)p=E.s3_lock_total;if(E.s3_lock_batch_count!==void 0)m+=E.s3_lock_batch_count;let A=E.step??E.step_results?.[E.step_results.length-1]?.step;if(A&&(A!==h||A==="s3_lock"))D(A,E.steps_completed??[],A==="s3_lock"?m:void 0,A==="s3_lock"?p:void 0),h=A;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)f=E.s3_lock_continuation_token;else break}while(E.hasMore);if(x.length>0)E.step_results=zne(x);return E}catch(E){if(w=E,R===5||!AQe(E)){if(E instanceof B&&x.length>0)E.stepResults=zne(x);throw E}let A=E;if(i?.({attempt:R,maxAttempts:5,delayMs:d,step:A.step,error:A.message}),await new Promise((U)=>setTimeout(U,d)),b=!0,f!==void 0)g=!0}throw w}function zne(e){let t=new Map;for(let r of e)t.set(r.step,r);return Array.from(t.values())}var so=N(()=>{Tb();eh();Fb();na();At()});function Ww(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function jC(e,t,r,n,i={}){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);if(i.search!==void 0)o.set("q",i.search);if(i.includeDeleted)o.set("include_deleted","true");let s=o.toString()?`?${o.toString()}`:"";return M(`/admin/users${s}`,{},!0,Tz)}async function Kw(e,t=!1){return M(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,qz)}async function rie(e,t){return M(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,Lz)}async function nie(e){return M(`/admin/approve/${e}`,{method:"POST"},!0)}async function iie(e){return M(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function oie(e){return M(`/admin/revoke/${e}`,{method:"POST"},!0)}async function sie(e){return M(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function aie(e){return M(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function cie(e,t){return M(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function lie(e,t){return M(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function uie(e){return M(`/admin/users/${e}`,{},!0)}async function die(e,t){return M(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,vb)}async function fie(e){return M(`/admin/users/${e}/keys`,{},!0,wb)}async function pie(e,t){return M(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function MC(e,t){return M(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function mie(e){return M(`/datasets/${e}/publish`,{method:"POST"},!0)}async function hie(e){return M(`/admin/datasets/${e}/ci`,{},!0)}async function oa(e){return M(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function qC(e){return M(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function LC(e){return M(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function gie(e,t){return M(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function Jh(e){return M(`/admin/datasets/${e}/doi`,{},!0)}async function BC(e,t){return M(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function yie(e,t){return M(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function bie(e,t){return M(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function xie(e){return M(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function wie(e,t=!1){return M(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function vie(e){return M("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function _ie(e){return M("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function Die(e){return M("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function Eie(e){return M(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function UC(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 M(`/admin/imports${n?`?${n}`:""}`,{},!0)}async function Sie(e){return M(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function $ie(e){return M(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function zC(e){return M(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function kie(e){return M("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function ip(e,t){return M(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function Rie(e,t){return M("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function Cie(e){let t=e?.limit??15;return M(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Aie(){return M("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Oie(e){let t=e?.limit??50;return M(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Tie(){return M("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Pie(e){let t=e?.limit??15;return M(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Iie(){return M("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Fie(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 M(`/admin/datasets/data-integrity-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Nie(){return M("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function jie(e,t){let r=t?.write?"":"?dry_run=1";return M(`/admin/datasets/${e}/availability-report${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Mie(e){let t=e?.limit??30,r=new URLSearchParams({limit:String(t)});if(e?.missingOnly)r.set("missing-only","1");return M(`/admin/datasets/availability-report-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function qie(){return M("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Lie(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 M(`/admin/fleet/drift${r}`,{},!0)}async function op(e,t){return M(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function Bie(e){return M("/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 Uie(e,t=!1){return M(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function zie(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return M(`/admin/email-preferences${t}`,{},!0)}async function Vie(e,t){let r=t?`?user=${encodeURIComponent(t)}`:"";return M(`/admin/email-preferences${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function VC(e){return M("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function Hie(){return M("/admin/summary/coverage",{},!0)}async function Gie(e,t,r){return M("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:r?.skipCanary??!1})},!0)}async function HC(e){return M("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function GC(e){return M("/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 Wie(){return M("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function Kie(e){return M("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function Yie(){return M("/admin/neurobagel/status",{method:"GET"},!0)}async function Jie(){return M("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Xie(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return M(`/admin/datasets/zarr-fidelity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Qie(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 M(`/admin/imports/issue-triage${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Zie(e){let t=e?.apply?"?apply=1":"";return M(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function eoe(e){let t=e?.apply?"?apply=1":"";return M(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function toe(e){return M("/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 roe(e){return M("/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 noe(){return M("/admin/users/duplicates",{},!0,Zz)}async function ioe(e){return M(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,eV)}async function ooe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return M(`/admin/datasets/anonymity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function soe(){return M("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Yw(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let r=t.toString()?`?${t.toString()}`:"";return M(`/admin/pr-reviews${r}`,{method:"GET"},!0)}async function WC(e,t,r){let n=r?`?head=${encodeURIComponent(r)}`:"";return M(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${n}`,{method:"GET"},!0)}async function KC(e,t){return M(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start`,{method:"POST"},!0)}async function aoe(e){return M(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function coe(e,t,r){return M(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(r?{mode:t,reason:r}:{mode:t})},!0)}async function loe(e){return M(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}var du=N(()=>{Zm();Qd();na()});async function Jr(e,t){return M(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function YC(e,t){return M(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function uoe(e){return M(`/admin/datasets/${e}/files`,{},!0)}async function doe(e){let t,r=0,n=[],i=!0;while(i){let o=await M(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(r+=o.locked,o.failed?.length)n.push(...o.failed);if(i=o.hasMore,t=o.continuation_token,i&&!t)throw new B(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:r,failed:n}}var sa=N(()=>{na();At()});async function Xw(e){return M(`/datasets/${e}/ci/status`,{},!0)}async function foe(e){return M(`/datasets/${e}/manifest`,{},!0)}async function Qw(e,t){return M(`/datasets/${e}/manifest/${t}`,{},!0)}function poe(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 Qc(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[i,o]of Object.entries(e.facets))t.set(i,o);if(e.includeUnknown)t.set("include_unknown","1");let r=t.toString()?`?${t.toString()}`:"",n=await M(`/datasets${r}`,{},e.mine?!0:"optional");return n.datasets=n.datasets.map(poe),n}async function moe(e){return M(`/datasets/resolve/${e}`,{},"optional")}async function hoe(){return M("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",yb)}async function goe(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[i,o]of Object.entries(t.facets))r.set(i,o);if(t.includeUnknown)r.set("include_unknown","1");return await M(`/datasets/search?${r.toString()}`,{},"optional",Gz)}async function _r(e){let t=await M(`/datasets/${e}`,{},"optional");return poe(t.dataset)}async function yoe(e){return M(`/datasets/${e}/versions`,{},!0)}async function Zw(e){return M("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function boe(e,t){return M(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function ev(e){return M(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function JC(e){return M(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function xoe(e,t){let r=t?`?status=${t}`:"";return M(`/datasets/${e}/access-requests${r}`,{},!0)}async function woe(e,t){return M(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function voe(e,t){return M(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function _oe(e,t){return M(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function Doe(e){return M(`/datasets/${e}/collaborators`,{},!0)}async function Eoe(e,t){return M(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var Jw;var Zc=N(()=>{Qd();na();Jw=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function Yoe(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"&&!aa.has(r)).filter((r)=>t.prefix?r.startsWith(t.prefix):!0).sort()}var aa;var iv=N(()=>{aa=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function Xr(e){return e.replace(UQe,(t)=>{if(t===`
113
+ `)}var Bne=!1;var $C=N(()=>{Ne()});function Uw(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(RC)return kC;return Ft().apiUrl||kC}async function M(e,t={},r=!1,n){let i=`${Uw()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":oo,...t.headers};if(r){let p=Ft();if(!p.apiKey&&r===!0)throw new B(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)o.Authorization=`Bearer ${p.apiKey}`}let s=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(i,{...t,headers:o})}catch(p){if(au())qw({method:s,url:i,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new B(0,`Network error: Could not connect to ${Uw()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(au())qw({method:s,url:i,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new B(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(au())qw({method:s,url:i,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new B(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(f.mode==="read-only"||f.mode==="full")){let U=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",P=typeof f.eta==="string"?f.eta:null,j=new cc(f.mode,U,P,f.details);throw Bw(j),j}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((U)=>typeof U==="string"):void 0,g=typeof f.error==="string"&&(Fz.includes(f.error)||Qz.includes(f.error)),h=typeof f.error==="string"&&(xb.options.includes(f.error)||nV.includes(f.error)),b=typeof f.error==="string"&&Cz.includes(f.error),x=typeof f.error==="string"&&Nz.includes(f.error),w=typeof f.error==="string"&&Yz.includes(f.error),D=typeof f.error==="string"&&Kz.includes(f.error),R=typeof f.error==="string"&&Jz.includes(f.error),O=p||D||R||g||h||b||x||w||m!==void 0&&typeof f.error==="string"&&Iz.includes(f.error)?f.message||f.error:f.error||f.message;if(u.status===404&&f.error==="Not Found"&&typeof f.message==="string")O=`${f.message}. This NEMAR backend does not support this command yet.`;let A=new B(u.status,O||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")A.code=f.error;if(typeof f.reason==="string")A.reason=f.reason;throw A.rawBody=f,A}if(n){let p=n.safeParse(f);if(!p.success)throw new B(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var kC="https://api.nemar.org",RC;var na=N(()=>{Zm();_b();X1();eh();Gd();Oi();jr();$C();Gf();At();RC=kC.includes("workers.dev")});async function Jf(e,t={}){return M(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function Xf(e){return M(`/datasets/${e}/publish/status`,{},!0)}async function Vne(e){return M(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function Hne(e){return M(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function cu(e={}){let{statuses:t,search:r}=typeof e==="string"?{statuses:e?[e]:[]}:e,n=await Une(t,r),i=n;if(t!==void 0&&t.length>1&&n.requests.length===0){let o=[];for(let a of new Set(t))o.push(await Une([a],r));let s=o.flatMap((a)=>a.requests).sort(Gne);i={...n,requests:s,count:s.length}}return r?RQe(i,r):i}function Gne(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function Une(e,t){let r=new URLSearchParams;if(e&&e.length>0)r.set("status",e.join(","));if(t)r.set("search",t);let n=r.size>0?`?${r}`:"";return M(`/admin/publish/requests${n}`,{},!0)}function RQe(e,t){let r=e.requests.filter((o)=>CV(t,[o.dataset_id,o.requested_by_username,o.dataset_name])),n=(o)=>AV(o.dataset_id,t)?0:1,i=[...r].sort((o,s)=>n(o)-n(s)||Gne(o,s));return{...e,requests:i,count:i.length}}async function Qf(e,t,r){return M(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...r!==void 0?{request_id:r}:{}})},!0)}async function zw(e){return M(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function Vw(e){return M(`/admin/publish/${e}/review`,{},!0)}async function Wne(e){return M(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function Kne(e,t){let r={message:t};return M(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},!0)}function Zf(e){if(!(e instanceof B))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let r=t.code;return typeof r==="string"?r:void 0}function CQe(e,t=[]){if(e){let r=No.indexOf(e);if(r>=0)return r+1}return Math.min(t.length+1,No.length)}function AQe(e){if(!(e instanceof B))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}function OQe(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return Pb;let t=Number(e);return Number.isSafeInteger(t)&&t<=Pb?t:Pb}async function ep(e,t=!1,r=!1,n=!1,i,o,s,a,c){let d=OQe(),f,p,m=0,g=!1,h,b=t,x=[],w;function D(R,E,O,A){if(!o)return;o({step:R,stepIndex:CQe(R,E),stepTotal:No.length,s3LockLocked:O,s3LockTotal:A,s3LockResumed:R==="s3_lock"&&g?!0:void 0})}for(let R=1;R<=5;R++)try{let E,O=!0;do{if(E=await M(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[Xz]:c.dispatchToken}:{}},body:JSON.stringify({resume:O?b:!0,sandbox:r,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:n,...s!==void 0?{acknowledge_identifier_screen:s}:{},...a!==void 0?{[$V]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),O=!1,E.step_results)x.push(...E.step_results);if(E.s3_lock_total!==void 0)p=E.s3_lock_total;if(E.s3_lock_batch_count!==void 0)m+=E.s3_lock_batch_count;let A=E.step??E.step_results?.[E.step_results.length-1]?.step;if(A&&(A!==h||A==="s3_lock"))D(A,E.steps_completed??[],A==="s3_lock"?m:void 0,A==="s3_lock"?p:void 0),h=A;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)f=E.s3_lock_continuation_token;else break}while(E.hasMore);if(x.length>0)E.step_results=zne(x);return E}catch(E){if(w=E,R===5||!AQe(E)){if(E instanceof B&&x.length>0)E.stepResults=zne(x);throw E}let A=E;if(i?.({attempt:R,maxAttempts:5,delayMs:d,step:A.step,error:A.message}),await new Promise((U)=>setTimeout(U,d)),b=!0,f!==void 0)g=!0}throw w}function zne(e){let t=new Map;for(let r of e)t.set(r.step,r);return Array.from(t.values())}var so=N(()=>{Tb();eh();Fb();na();At()});function Ww(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function jC(e,t,r,n,i={}){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);if(i.search!==void 0)o.set("q",i.search);if(i.includeDeleted)o.set("include_deleted","true");let s=o.toString()?`?${o.toString()}`:"";return M(`/admin/users${s}`,{},!0,Tz)}async function Kw(e,t=!1){return M(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,qz)}async function rie(e,t){return M(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,Lz)}async function nie(e){return M(`/admin/approve/${e}`,{method:"POST"},!0)}async function iie(e){return M(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function oie(e){return M(`/admin/revoke/${e}`,{method:"POST"},!0)}async function sie(e){return M(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function aie(e){return M(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function cie(e,t){return M(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function lie(e,t){return M(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function uie(e){return M(`/admin/users/${e}`,{},!0)}async function die(e,t){return M(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,vb)}async function fie(e){return M(`/admin/users/${e}/keys`,{},!0,wb)}async function pie(e,t){return M(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function MC(e,t){return M(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function mie(e){return M(`/datasets/${e}/publish`,{method:"POST"},!0)}async function hie(e){return M(`/admin/datasets/${e}/ci`,{},!0)}async function oa(e){return M(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function qC(e){return M(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function LC(e){return M(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function gie(e,t){return M(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function Jh(e){return M(`/admin/datasets/${e}/doi`,{},!0)}async function BC(e,t){return M(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function yie(e,t){return M(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function bie(e,t){return M(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function xie(e){return M(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function wie(e,t=!1){return M(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function vie(e){return M("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function _ie(e){return M("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function Die(e){return M("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function Eie(e){return M(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function UC(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 M(`/admin/imports${n?`?${n}`:""}`,{},!0)}async function Sie(e){return M(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function $ie(e){return M(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function zC(e){return M(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function kie(e){return M("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function ip(e,t){return M(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function Rie(e,t){return M("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function Cie(e){let t=e?.limit??15;return M(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Aie(){return M("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Oie(e){let t=e?.limit??50;return M(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Tie(){return M("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Pie(e){let t=e?.limit??15;return M(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Iie(){return M("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Fie(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 M(`/admin/datasets/data-integrity-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Nie(){return M("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function jie(e,t){let r=t?.write?"":"?dry_run=1";return M(`/admin/datasets/${e}/availability-report${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Mie(e){let t=e?.limit??30,r=new URLSearchParams({limit:String(t)});if(e?.missingOnly)r.set("missing-only","1");return M(`/admin/datasets/availability-report-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function qie(){return M("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Lie(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 M(`/admin/fleet/drift${r}`,{},!0)}async function op(e,t){return M(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function Bie(e){return M("/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 Uie(e,t=!1){return M(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function zie(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return M(`/admin/email-preferences${t}`,{},!0)}async function Vie(e,t){let r=t?`?user=${encodeURIComponent(t)}`:"";return M(`/admin/email-preferences${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function VC(e){return M("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function Hie(){return M("/admin/summary/coverage",{},!0)}async function Gie(e,t,r){return M("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:r?.skipCanary??!1})},!0)}async function HC(e){return M("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function GC(e){return M("/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 Wie(){return M("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function Kie(e){return M("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function Yie(){return M("/admin/neurobagel/status",{method:"GET"},!0)}async function Jie(){return M("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Xie(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return M(`/admin/datasets/zarr-fidelity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Qie(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 M(`/admin/imports/issue-triage${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Zie(e){let t=e?.apply?"?apply=1":"";return M(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function eoe(e){let t=e?.apply?"?apply=1":"";return M(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function toe(e){return M("/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 roe(e){return M("/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 noe(){return M("/admin/users/duplicates",{},!0,Zz)}async function ioe(e){return M(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,eV)}async function ooe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return M(`/admin/datasets/anonymity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function soe(){return M("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Yw(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let r=t.toString()?`?${t.toString()}`:"";return M(`/admin/pr-reviews${r}`,{method:"GET"},!0)}async function WC(e,t,r){let n=r?`?head=${encodeURIComponent(r)}`:"";return M(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${n}`,{method:"GET"},!0)}async function KC(e,t){return M(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start`,{method:"POST"},!0)}async function aoe(e){return M(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function coe(e,t,r){return M(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(r?{mode:t,reason:r}:{mode:t})},!0)}async function loe(e){return M(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}var du=N(()=>{Zm();Qd();na()});async function Jr(e,t){return M(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function YC(e,t){return M(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function uoe(e){return M(`/admin/datasets/${e}/files`,{},!0)}async function doe(e){let t,r=0,n=[],i=!0;while(i){let o=await M(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(r+=o.locked,o.failed?.length)n.push(...o.failed);if(i=o.hasMore,t=o.continuation_token,i&&!t)throw new B(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:r,failed:n}}var sa=N(()=>{na();At()});async function Xw(e){return M(`/datasets/${e}/ci/status`,{},!0)}async function foe(e){return M(`/datasets/${e}/manifest`,{},!0)}async function Qw(e,t){return M(`/datasets/${e}/manifest/${t}`,{},!0)}function poe(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 Qc(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[i,o]of Object.entries(e.facets))t.set(i,o);if(e.includeUnknown)t.set("include_unknown","1");let r=t.toString()?`?${t.toString()}`:"",n=await M(`/datasets${r}`,{},e.mine?!0:"optional");return n.datasets=n.datasets.map(poe),n}async function moe(e){return M(`/datasets/resolve/${e}`,{},"optional")}async function hoe(){return M("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",yb)}async function goe(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[i,o]of Object.entries(t.facets))r.set(i,o);if(t.includeUnknown)r.set("include_unknown","1");return await M(`/datasets/search?${r.toString()}`,{},"optional",Gz)}async function _r(e){let t=await M(`/datasets/${e}`,{},"optional");return poe(t.dataset)}async function yoe(e){return M(`/datasets/${e}/versions`,{},!0)}async function Zw(e){return M("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function boe(e,t){return M(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function ev(e){return M(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function JC(e){return M(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function xoe(e,t){let r=t?`?status=${t}`:"";return M(`/datasets/${e}/access-requests${r}`,{},!0)}async function woe(e,t){return M(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function voe(e,t){return M(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function _oe(e,t){return M(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function Doe(e){return M(`/datasets/${e}/collaborators`,{},!0)}async function Eoe(e,t){return M(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var Jw;var Zc=N(()=>{Qd();na();Jw=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function Yoe(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"&&!aa.has(r)).filter((r)=>t.prefix?r.startsWith(t.prefix):!0).sort()}var aa;var iv=N(()=>{aa=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function Xr(e){return e.replace(UQe,(t)=>{if(t===`
114
114
  `)return"\\n";if(t==="\r")return"\\r";if(t==="\t")return"\\t";let r=t.codePointAt(0)??0;return r<=255?`\\x${r.toString(16).padStart(2,"0")}`:`\\u${r.toString(16).padStart(4,"0")}`})}function ov(e,t=", "){return e.map(Xr).join(t)}var UQe,ds=(e)=>Xr(e)===e;var sp=N(()=>{UQe=/[\p{Cc}\u2028\u2029\u202a-\u202e\u2066-\u2069]/gu});async function zQe(){try{let{exitCode:e,stderr:t}=await k(["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 fu(){try{let{stdout:e,exitCode:t,stderr:r}=await k(["gh","auth","token"],{sensitiveOutput:!0});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 sv(e){try{let{stdout:t,exitCode:r,stderr:n}=await k(["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 i=t.trim();if(!i)return{authenticated:!1,error:"gh CLI returned empty username"};if(e){let o=i.toLowerCase()===e.toLowerCase();return{authenticated:!0,username:i,matches:o,error:o?void 0:`gh CLI authenticated as '${i}', expected '${e}'`}}return{authenticated:!0,username:i}}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 av(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 k(["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 i=null;try{i=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(!i){let{exitCode:a}=await k(["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:o,stderr:s}=await k(["gh","api","--method","PATCH",`/user/repository_invitations/${i}`]);if(o!==0)return{accepted:!1,error:`Failed to accept invitation: ${s.trim()||"unknown error"}`};return{accepted:!0}}async function fs(e,t,r="origin"){let n=t;if(process.env.GH_TOKEN&&t.startsWith("git@github.com:")){let i=process.env.GH_TOKEN.trim();if(!i||/\s/.test(i))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 k(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${i}'`],{cwd:e,redact:[i]})}else if(t.startsWith("git@github.com:")){let i=t.replace("git@github.com:",""),o=await fu();if(o.token)n=`https://github.com/${i}`,await k(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${o.token}'`],{cwd:e,redact:[o.token]});else{let s=await zQe();if(s.works)n=t;else return{success:!1,error:`GitHub authentication not configured.
115
115
 
116
116
  gh CLI failed: ${o.error||"could not get token"}
@@ -1452,7 +1452,7 @@ ${u.slice(0,10).join(`
1452
1452
  `)}}}eh();At();function phe(e){return e instanceof B&&e.statusCode===422&&e.rawBody?.status==="blocked"&&bb(e.blockReason)}function mhe(e){let t=e.rawBody?.ci_url;return typeof t==="string"&&/^https:\/\/\S+$/.test(t)?t:void 0}function pT(e){return e==="bids_validation_in_progress"?"Request recorded: BIDS validation is still running.":"Request recorded: BIDS validation has not started yet."}function mT(e,t=!1){let r=`nemar dataset publish request ${e}${t?" --anonymous":""}`;return[" Your request is recorded. NEMAR re-checks it automatically and continues once validation passes.",` If you would rather not wait for that, check validation with: nemar dataset ci ${e}`,` Once it has passed, request again: ${r}`," If it says a request already exists, nothing more is needed."," If validation fails or a submission minimum fails, the request stays blocked and nothing is emailed:",` check nemar dataset ci ${e} or nemar dataset publish status ${e}.`]}At();Oi();async function DD(){let e=Ft().sandboxCompleted;if(e!==void 0)return{status:e?"completed":"not_completed"};try{let t=await tv();if(er("sandboxCompleted",t.sandbox_completed),t.sandbox_dataset_id)er("sandboxDatasetId",t.sandbox_dataset_id);return t.sandbox_completed?{status:"completed"}:{status:"not_completed"}}catch(t){return{status:"unknown",reason:L(t)}}}var hT=Be(Iv(),1);function ED(e){if(e!==e.trim())return null;let t=hT.default.parse(e);if(!t)return null;if(t.prerelease.length>0||t.build.length>0)return null;return{major:t.major,minor:t.minor,patch:t.patch}}function Tu(e,t){let r=ED(e);if(!r)throw Error(`Invalid version: ${e}`);let n=hT.default.inc(`${r.major}.${r.minor}.${r.patch}`,t);if(!n)throw Error(`Invalid version: ${e}`);return n}function gT(e){return ED(e)!==null}Ne();Ii();UA();Ne();sn();du();At();kp();__();sp();Ii();tl();$_();HA();bl();vu();import{existsSync as yT,mkdirSync as Fft,readFileSync as Nft,statSync as jft,writeFileSync as hhe}from"fs";import{join as Mft,resolve as bT}from"path";function ghe(e,t,r){if(!fo(r,"metadata_write")){if(t)try{let n=bT(e,".nemar"),i=bT(n,"metadata.json");if(!yT(i)){if(!yT(n))Fft(n,{recursive:!0});hhe(i,JSON.stringify(t,null,2))}let o=bT(e,".bidsignore"),s="";if(yT(o))s=Nft(o,"utf-8");if(!s.includes(".nemar/")){let a=s?`${s.trimEnd()}
1453
1453
  .nemar/
1454
1454
  `:`.nemar/
1455
- `;hhe(o,a)}console.log(l.dim(" Updated .bidsignore for NEMAR metadata"))}catch(n){console.log(l.yellow(` Warning: Could not update .bidsignore: ${L(n)}`)),console.log(l.dim(" Upload will continue without author enrichment."))}ga(r,"metadata_write"),Br(e,r)}else console.log(l.dim(" Metadata write already completed (skipping)"))}var yhe=1073741824;function qft(e,t,r=yhe){let n=[],i=0;for(let o of t){let s=e.files[o];if(!s||s.mtimeMs===void 0)continue;n.push({path:o,size:s.size,mtimeMs:s.mtimeMs}),i+=s.size}return i>=r?n:null}function Lft(e,t){return t.filter((r)=>{try{return el(r.path,jft(Mft(e,r.path)).size)}catch{return!0}})}function Bft(e){let t=0;for(let r of Object.values(e.files))t+=r.size;return t}function Uft(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${k_(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function bhe(e,t,r,n={}){if(!fo(r,"dataset_save")){let i=S({text:"Saving dataset changes...",...n.spinnerStream?{stream:n.spinnerStream}:{}}).start(),o=n.skipMinBytes??yhe,s=[];if(Bft(r)>=o){let c=n.annexedPaths??null;if(c===null)try{c=await yl(e)}catch(u){console.log(l.dim(` Could not list annexed files (${L(u)}); staging will re-read them`))}if(c!==null)s=Lft(e,qft(r,c,o)??[])}let a=await ca(e,"Initial NEMAR dataset upload",t,{skipContentCheck:s,onInactivityWarning:(c)=>{i=Og(i,Uft(c))},...n.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:n.inactivityWarningAfterMs}});if(!a.success)return Br(e,r),gn(i,"Failed to save dataset",a.error),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e;if(n.verifyRemote){let c;try{c=await QA(e,n.verifyRemote)}catch(u){return Br(e,r),gn(i,"Could not confirm the saved files are at the S3 remote",u),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e}if(c.length>0){ya(r,"s3_upload"),Br(e,r);let u=ov(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return gn(i,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${u}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(l.yellow("Re-run the same command: it uploads them and saves again.")),$e}}i.succeed("Dataset changes saved"),ga(r,"dataset_save"),Br(e,r)}else console.log(l.dim(" Dataset save already completed (skipping)"));return Lt()}async function xhe(e,t){if(!fo(t,"github_push")){let r=S("Pushing metadata to GitHub...").start(),n=await Dr(e);if(!n.success)return Br(e,t),gn(r,"Failed to push to GitHub",n.error),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e;if(n.warning)r.warn("Metadata pushed to GitHub (with warning)"),console.log(l.yellow(` ${n.warning}`));else r.succeed("Metadata pushed to GitHub");ga(t,"github_push"),Br(e,t)}else console.log(l.dim(" GitHub push already completed (skipping)"));return Lt()}async function whe(e,t,r){if(!fo(r,"ci_deploy")){let n=S("Setting up BIDS validation CI...").start(),i="configured";try{await oa(t),n.succeed("BIDS validation CI configured")}catch(o){if(i="not-configured",o instanceof B&&o.statusCode===403)n.info("CI workflow will be configured by an admin");else{let s=o instanceof Error?o.message:String(o);n.warn(`Could not configure CI: ${s}`),console.log(l.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return ga(r,"ci_deploy"),Br(e,r),i}return console.log(l.dim(" CI deploy already completed (skipping)")),"unknown"}function zft(e,t){let r=e.startsWith("xx");if(t==="not-configured"){if(r)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${l.cyan(`nemar dataset publish request ${e}`)}`),console.log();return}if(console.log("BIDS validation runs on GitHub after the upload."),console.log(` Check it with: ${l.cyan(`nemar dataset ci ${e}`)}`),!r)console.log(` Once it has passed, request publication: ${l.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function vhe(e,t,r="unknown"){Ag(e),Uue(e),console.log(),console.log(l.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${l.cyan(t.dataset_id)}`),console.log(` GitHub: ${l.cyan(t.github_url)}`),console.log(),console.log(l.dim("To download this dataset:")),console.log(l.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),zft(t.dataset_id,r),console.log(l.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(l.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(l.yellow("After publishing, the data will be publicly available for everyone."))}bl();vu();async function _he(e,t={}){let r=await _se(e.absolutePath);if(!r.success)return console.log(l.red(r.error)),console.log(l.yellow("Re-run the same command to retry.")),$e;if(r.cleared>0)console.log(l.yellow(` Cleared ${r.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let n=await Kue(e.absolutePath);if(n.status==="error")return console.log(l.red(n.error)),$e;if(n.status==="warning")console.log(l.yellow(` ${n.warning}`));if(n.status==="restored")console.log(l.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let i=await kde(e.absolutePath,e.options,e.dataFiles,e.filesToUpload,e.uploadProgress,e.datasetInfo,{openRemote:t.openRemote,...t.primeMinBytes===void 0?{}:{primeMinBytes:t.primeMinBytes},...t.primeOnSuspended?{primeOnSuspended:t.primeOnSuspended}:{}});if(i.status==="fail")return $e;let{progress:o,annexedPaths:s}=i.value;if(ghe(e.absolutePath,e.coAuthorEnrichment,o),(await(t.saveStep??bhe)(e.absolutePath,e.author,o,{annexedPaths:s,verifyRemote:Es,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return $e;return Lt(o)}Ne();bu();xu();cO();jr();Mt();import{randomBytes as Spt}from"crypto";import{constants as ET,accessSync as $pt,chmodSync as kpt,chownSync as Rpt,closeSync as RT,copyFileSync as Cpt,existsSync as Whe,fsyncSync as Khe,lstatSync as Rs,mkdirSync as Apt,mkdtempSync as Opt,openSync as CT,readSync as Tpt,readdirSync as Ppt,renameSync as Ipt,rmSync as AT,rmdirSync as Fpt,statSync as Yhe,writeSync as Npt}from"fs";import{tmpdir as jpt}from"os";import{dirname as OD,join as go}from"path";Ne();import{lstatSync as ypt,readdirSync as bpt,statSync as Fhe}from"fs";import{open as xpt}from"fs/promises";import{join as Ihe}from"path";xi();sn();bu();var khe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",Vft="https://nemar-api-dev.sccn-org.workers.dev",Hft="https://data.nemar.org",Gft="https://nemar.s3.us-east-2.amazonaws.com",Wft="https://api.github.com";function RD(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function SD(e,t,r){RD("pool size",t);let n=0,i=Array.from({length:Math.min(t,e.length)},async()=>{while(n<e.length){let a=e[n++];await r(a)}}),s=(await Promise.allSettled(i)).find((a)=>a.status==="rejected");if(s)throw s.reason}function Kft(e){RD("limit",e);let t=0,r=[];return async(n)=>{if(t>=e)await new Promise((i)=>r.push(i));else t++;try{return await n()}finally{let i=r.shift();if(i)i();else t--}}}class mr extends Error{cls;status;retryable;retryAfterMs;constructor(e,t={}){super(e);this.name="ReadFailure",this.cls=e,this.status=t.status,this.retryable=t.retryable??!1,this.retryAfterMs=t.retryAfterMs}}function Yft(e,t=Date.now()){let r=e?.trim();if(!r)return;if(/^\d+$/.test(r))return Number(r)*1000;let n=Date.parse(r);return Number.isNaN(n)?void 0:Math.max(0,n-t)}function Jft(e,t){let r=e>=500||e===429;return new mr(`http-${e}`,{status:e,retryable:r,retryAfterMs:r?Yft(t):void 0})}class xT extends Error{constructor(e){super(e);this.name="RunAborted"}}function Xft(e){RD("abort streak",e.streak);let t=e.now??Date.now,r={tripped:null},n=(i)=>{let o=0,s=0,a=(c)=>{throw r.tripped=new xT(c),r.tripped};return{check(){if(r.tripped)throw r.tripped},ok(){o=0},pausedUntilMs(){return s},observe(c){if(r.tripped)throw r.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${i} asked to wait ${Math.round(c.retryAfterMs/1000)} s (Retry-After), over the ${Math.round(e.retryAfterCapMs/1000)} s cap (${c.cls})`);if(c.retryAfterMs!==void 0)s=Math.max(s,t()+c.retryAfterMs);if(!c.retryable){o=0;return}if(o++,o>=e.streak)a(`${o} consecutive 429, 5xx, timeout or network failures from ${i} (last ${c.cls})`)}}};return{worker:n("the Worker"),direct:n("direct reads")}}function Dhe(e){let t=e instanceof Error?e.name:"";return new mr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function Qft(e){if(e instanceof mr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function Zft(e,t={}){let r=t.tries??3,n=t.baseMs??400,i=t.sleep??((o)=>new Promise((s)=>setTimeout(s,o)));RD("tries",r);for(let o=1;;o++)try{return await e()}catch(s){if(!(s instanceof mr&&s.retryable)||o>=r)throw s;let c=s.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw s;await i(Math.max(n*2**(o-1),c))}}async function ept(e){await e.body?.cancel().catch(()=>{return})}async function tpt(e,t,r={}){let n;try{n=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":r.userAgent??khe},signal:AbortSignal.timeout(r.timeoutMs??30000)})}catch(a){throw Dhe(a)}if(n.status!==200&&n.status!==206)throw await ept(n),Jft(n.status,n.headers.get("retry-after"));let i=n.body?.getReader();if(!i)throw new mr("no-body");let o=new Uint8Array(t),s=0;try{while(s<t){let{done:a,value:c}=await i.read();if(a||!c)break;let u=Math.min(c.length,t-s);o.set(c.subarray(0,u),s),s+=u}}catch(a){throw Dhe(a)}finally{await i.cancel().catch(()=>{return})}if(s<(r.minBytes??0))throw new mr("short-body");return o.subarray(0,s)}var Rhe={sideFileBytes:2097152,participantsBytes:16777216};function rpt(e,t){let r=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(r)return/^\d+$/.test(r)?`aws/http-${r}`:`aws/error-${r}`;return`aws/exit-${t}`}async function npt(e,t,r={}){let n;try{let i=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...r.env?{env:r.env}:{}}),o=!1;n=setTimeout(()=>{o=!0,i.kill("SIGKILL")},r.timeoutMs??600000);let[s,a,c]=await Promise.all([new Response(i.stdout).text(),new Response(i.stderr).text(),i.exited]);if(o)throw new mr("aws/timeout");if(c!==0)throw new mr(rpt(a,c));return s}catch(i){if(i instanceof mr)throw i;throw new mr("aws/unavailable")}finally{clearTimeout(n)}}function ipt(){let e;return async()=>{if(e!==void 0)return e;if(process.env.GITHUB_TOKEN)return e=process.env.GITHUB_TOKEN,e;try{let t=Bun.spawn(["gh","auth","token"],{stdout:"pipe",stderr:"ignore"}),r=(await new Response(t.stdout).text()).trim();e=r===""?null:r}catch{e=null}return e}}var $D=(e)=>e.replace(/\/+$/,"");function Che(e={}){let t=e.retryAfterCapMs??30000,r=e.awsTimeoutMs??600000;return{api:$D(e.api??process.env.NEMAR_API_BASE??Vft),data:$D(e.data??process.env.NEMAR_DATA_BASE??Hft),s3Base:$D(e.s3Base??Gft),githubApi:$D(e.githubApi??Wft),userAgent:e.userAgent??khe,fileConcurrency:e.fileConcurrency??24,workerLimit:Kft(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((n)=>new Promise((i)=>setTimeout(i,n))),now:e.now??Date.now,retryAfterCapMs:t,breakers:Xft({streak:e.abortStreak??25,retryAfterCapMs:t,now:e.now??Date.now}),limits:{treeHeaderSample:300,scansTables:1,jsonFiles:300,textFiles:300,sideFileBytes:65536,participantsBytes:1048576,...e.limits},readVersionManifest:e.readVersionManifest??((n,i)=>npt(n,i,{timeoutMs:r,env:e.awsEnv})),githubToken:e.githubToken??ipt(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var Ahe=(e,t)=>t.startsWith(`${e.data}/`),opt=(e,t)=>Ahe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function spt(e,t,r){let n=opt(e,t);n.check();let i=n.pausedUntilMs()-e.now();if(i>0)await e.sleep(i),n.check();try{let o=await r();return n.ok(),o}catch(o){if(o instanceof mr)n.observe(o);throw o}}var apt=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var Ehe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function She(e,t,r){if(t<1)return[];if(e.length<=t)return[...e];let n=new Map;for(let c of e){let u=r(c),d=n.get(u);if(d)d.push(c);else n.set(u,[c])}let i=[...n.entries()].sort(([c],[u])=>c<u?-1:c>u?1:0).map(([,c])=>c);if(i.length>t)return Array.from({length:t},(c,u)=>i[Math.floor((u+0.5)*i.length/t)][0]);let o=i.map((c,u)=>({list:c,index:u})).sort((c,u)=>c.list.length-u.list.length||c.index-u.index),s=t,a=[];return o.forEach(({list:c},u)=>{let d=Math.min(c.length,Math.ceil(s/(o.length-u)));for(let f=0;f<d;f++)a.push(c[Math.floor((f+0.5)*c.length/d)]);s-=d}),a}var cpt=(e)=>e.severity==="identifier"&&nle.has(e.kind),lpt=(e)=>yu.has(e.kind);function Ohe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function upt(e){if(e.findings.some(cpt))return"direct-identifiers";if(e.findings.some((t)=>!lpt(t)))return"review";if(!Ohe(e))return"unchecked";if(e.edfCount>0&&e.unscreenedCount>0)return"clean-edf-only-others-unscreened";if(e.edfCount===0)return e.unscreenedCount>0?"not-screened":"no-recordings";return e.findings.length>0?"dates-only":"clean"}var dpt=/\.(edf|bdf)$/i,fpt=(e)=>e.edf===!0||dpt.test(e.path);function ppt(e){return{edf:e.filter(fpt),participants:e.find((t)=>t.path==="participants.tsv"),scans:e.filter((t)=>t.path.endsWith("_scans.tsv")),json:e.filter((t)=>t.path.endsWith(".json")).filter((t)=>t.path.startsWith("sourcedata/")||!mpt.test(t.path)).filter((t)=>!hpt.test(t.path)),text:e.filter((t)=>gpt.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var mpt=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,hpt=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,gpt=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function The(e,t,r,n=0){let i=()=>spt(e,t.url,()=>{let o={minBytes:n,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,r,o):tpt(t.url,r,o)});return Zft(()=>Ahe(e,t.url)?e.workerLimit(i):i(),apt(e))}async function kD(e,t,r){let n=await The(e,t,r),i=t.size===null?n.length>=r:t.size>r;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(n),truncated:i}}function Pp(e,t){for(let r of t)e.push(r)}var $he="edf/superseded-absent";async function Phe(e,t,r,n,i,o={}){let s=n.map((Se)=>Se.path),a=i==="clone",c=(Se,rt,rn)=>a?[...Se]:She(Se,rt,rn),u=[...e_([...s,...o.extraPaths??[]])],d=mle(s),f=Object.values(d.unscreened).reduce((Se,rt)=>Se+rt,0),p={},m=(Se,rt)=>{if(rt instanceof xT)throw rt;let rn=`${Se}/${Qft(rt)}`;p[rn]=(p[rn]??0)+1},g=(Se)=>Ehe(Se.path),h=ppt(n),b=new Set(o.supersededEdf??[]),x=[...h.edf,...b],{participants:w,scans:D,json:R,text:E}=h,O=i==="git-tree"?She(x,e.limits.treeHeaderSample,g):[...x],A=0,U=0,P=0,j=0,K={},I=new Set,G=new Set,re=new Set,F=new Set,q=new Set,ye=new Set;await SD(O,e.fileConcurrency,async(Se)=>{try{let rt=await The(e,Se,vt,vt),rn=fa(rt),{patient:LD}=Qv(rt);if(!rn.some((Hi)=>Hi.kind==="edf-unreadable")){I.add(LD);let Hi=LD.split(/\s+/);if(Hi.length>=4)re.add(Hi[0]),q.add(Hi[2]),F.add(Hi[3])}if(ye.add(Ehe(Se.path)),rn.some((Hi)=>Hi.severity==="identifier"))j++,G.add(LD);Pp(u,rn);for(let Hi of new Set(rn.map((y0e)=>y0e.kind)))K[Hi]=(K[Hi]??0)+1;A++}catch(rt){if(b.has(Se)&&rt instanceof mr&&rt.status===404){P++,p[$he]=(p[$he]??0)+1;return}U++,m("edf",rt)}});let ce=x.length-P,br=!1,St=!1;if(w&&w.size!==0)try{let{text:Se,truncated:rt}=await kD(e,w,e.limits.participantsBytes),rn=Se.indexOf(`
1455
+ `;hhe(o,a)}console.log(l.dim(" Updated .bidsignore for NEMAR metadata"))}catch(n){console.log(l.yellow(` Warning: Could not update .bidsignore: ${L(n)}`)),console.log(l.dim(" Upload will continue without author enrichment."))}ga(r,"metadata_write"),Br(e,r)}else console.log(l.dim(" Metadata write already completed (skipping)"))}var yhe=1073741824;function qft(e,t,r=yhe){let n=[],i=0;for(let o of t){let s=e.files[o];if(!s||s.mtimeMs===void 0)continue;n.push({path:o,size:s.size,mtimeMs:s.mtimeMs}),i+=s.size}return i>=r?n:null}function Lft(e,t){return t.filter((r)=>{try{return el(r.path,jft(Mft(e,r.path)).size)}catch{return!0}})}function Bft(e){let t=0;for(let r of Object.values(e.files))t+=r.size;return t}function Uft(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${k_(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function bhe(e,t,r,n={}){if(!fo(r,"dataset_save")){let i=S({text:"Saving dataset changes...",...n.spinnerStream?{stream:n.spinnerStream}:{}}).start(),o=n.skipMinBytes??yhe,s=[];if(Bft(r)>=o){let c=n.annexedPaths??null;if(c===null)try{c=await yl(e)}catch(u){console.log(l.dim(` Could not list annexed files (${L(u)}); staging will re-read them`))}if(c!==null)s=Lft(e,qft(r,c,o)??[])}let a=await ca(e,"Initial NEMAR dataset upload",t,{skipContentCheck:s,onInactivityWarning:(c)=>{i=Og(i,Uft(c))},...n.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:n.inactivityWarningAfterMs}});if(!a.success)return Br(e,r),gn(i,"Failed to save dataset",a.error),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e;if(n.verifyRemote){let c;try{c=await QA(e,n.verifyRemote)}catch(u){return Br(e,r),gn(i,"Could not confirm the saved files are at the S3 remote",u),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e}if(c.length>0){ya(r,"s3_upload"),Br(e,r);let u=ov(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return gn(i,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${u}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(l.yellow("Re-run the same command: it uploads them and saves again.")),$e}}i.succeed("Dataset changes saved"),ga(r,"dataset_save"),Br(e,r)}else console.log(l.dim(" Dataset save already completed (skipping)"));return Lt()}async function xhe(e,t){if(!fo(t,"github_push")){let r=S("Pushing metadata to GitHub...").start(),n=await Dr(e);if(!n.success)return Br(e,t),gn(r,"Failed to push to GitHub",n.error),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e;if(n.warning)r.warn("Metadata pushed to GitHub (with warning)"),console.log(l.yellow(` ${n.warning}`));else r.succeed("Metadata pushed to GitHub");ga(t,"github_push"),Br(e,t)}else console.log(l.dim(" GitHub push already completed (skipping)"));return Lt()}async function whe(e,t,r){if(!fo(r,"ci_deploy")){let n=S("Setting up BIDS validation CI...").start(),i="configured";try{await oa(t),n.succeed("BIDS validation CI configured")}catch(o){if(i="not-configured",o instanceof B&&o.statusCode===403)n.info("CI workflow will be configured by an admin");else{let s=o instanceof Error?o.message:String(o);n.warn(`Could not configure CI: ${s}`),console.log(l.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return ga(r,"ci_deploy"),Br(e,r),i}return console.log(l.dim(" CI deploy already completed (skipping)")),"unknown"}function zft(e,t){let r=e.startsWith("xx");if(t==="not-configured"){if(r)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${l.cyan(`nemar dataset publish request ${e}`)}`),console.log();return}if(console.log("BIDS validation runs on GitHub after the upload."),console.log(` Check it with: ${l.cyan(`nemar dataset ci ${e}`)}`),!r)console.log(` Once it has passed, request publication: ${l.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function vhe(e,t,r="unknown"){Ag(e),Uue(e),console.log(),console.log(l.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${l.cyan(t.dataset_id)}`),console.log(` GitHub: ${l.cyan(t.github_url)}`),console.log(),console.log(l.dim("To download this dataset:")),console.log(l.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),zft(t.dataset_id,r),console.log(l.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(l.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(l.yellow("After publishing, the data will be publicly available for everyone."))}bl();vu();async function _he(e,t={}){let r=await _se(e.absolutePath);if(!r.success)return console.log(l.red(r.error)),console.log(l.yellow("Re-run the same command to retry.")),$e;if(r.cleared>0)console.log(l.yellow(` Cleared ${r.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let n=await Kue(e.absolutePath);if(n.status==="error")return console.log(l.red(n.error)),$e;if(n.status==="warning")console.log(l.yellow(` ${n.warning}`));if(n.status==="restored")console.log(l.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let i=await kde(e.absolutePath,e.options,e.dataFiles,e.filesToUpload,e.uploadProgress,e.datasetInfo,{openRemote:t.openRemote,...t.primeMinBytes===void 0?{}:{primeMinBytes:t.primeMinBytes},...t.primeOnSuspended?{primeOnSuspended:t.primeOnSuspended}:{}});if(i.status==="fail")return $e;let{progress:o,annexedPaths:s}=i.value;if(ghe(e.absolutePath,e.coAuthorEnrichment,o),(await(t.saveStep??bhe)(e.absolutePath,e.author,o,{annexedPaths:s,verifyRemote:Es,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return $e;return Lt(o)}Ne();bu();xu();cO();jr();Mt();import{randomBytes as Spt}from"crypto";import{constants as ET,accessSync as $pt,chmodSync as kpt,chownSync as Rpt,closeSync as RT,copyFileSync as Cpt,existsSync as Whe,fsyncSync as Khe,lstatSync as Rs,mkdirSync as Apt,mkdtempSync as Opt,openSync as CT,readSync as Tpt,readdirSync as Ppt,renameSync as Ipt,rmSync as AT,rmdirSync as Fpt,statSync as Yhe,writeSync as Npt}from"fs";import{tmpdir as jpt}from"os";import{dirname as OD,join as go}from"path";Ne();import{lstatSync as ypt,readdirSync as bpt,statSync as Fhe}from"fs";import{open as xpt}from"fs/promises";import{join as Ihe}from"path";xi();sn();bu();var khe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",Vft="https://api.nemar.org",Hft="https://data.nemar.org",Gft="https://nemar.s3.us-east-2.amazonaws.com",Wft="https://api.github.com";function RD(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function SD(e,t,r){RD("pool size",t);let n=0,i=Array.from({length:Math.min(t,e.length)},async()=>{while(n<e.length){let a=e[n++];await r(a)}}),s=(await Promise.allSettled(i)).find((a)=>a.status==="rejected");if(s)throw s.reason}function Kft(e){RD("limit",e);let t=0,r=[];return async(n)=>{if(t>=e)await new Promise((i)=>r.push(i));else t++;try{return await n()}finally{let i=r.shift();if(i)i();else t--}}}class mr extends Error{cls;status;retryable;retryAfterMs;constructor(e,t={}){super(e);this.name="ReadFailure",this.cls=e,this.status=t.status,this.retryable=t.retryable??!1,this.retryAfterMs=t.retryAfterMs}}function Yft(e,t=Date.now()){let r=e?.trim();if(!r)return;if(/^\d+$/.test(r))return Number(r)*1000;let n=Date.parse(r);return Number.isNaN(n)?void 0:Math.max(0,n-t)}function Jft(e,t){let r=e>=500||e===429;return new mr(`http-${e}`,{status:e,retryable:r,retryAfterMs:r?Yft(t):void 0})}class xT extends Error{constructor(e){super(e);this.name="RunAborted"}}function Xft(e){RD("abort streak",e.streak);let t=e.now??Date.now,r={tripped:null},n=(i)=>{let o=0,s=0,a=(c)=>{throw r.tripped=new xT(c),r.tripped};return{check(){if(r.tripped)throw r.tripped},ok(){o=0},pausedUntilMs(){return s},observe(c){if(r.tripped)throw r.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${i} asked to wait ${Math.round(c.retryAfterMs/1000)} s (Retry-After), over the ${Math.round(e.retryAfterCapMs/1000)} s cap (${c.cls})`);if(c.retryAfterMs!==void 0)s=Math.max(s,t()+c.retryAfterMs);if(!c.retryable){o=0;return}if(o++,o>=e.streak)a(`${o} consecutive 429, 5xx, timeout or network failures from ${i} (last ${c.cls})`)}}};return{worker:n("the Worker"),direct:n("direct reads")}}function Dhe(e){let t=e instanceof Error?e.name:"";return new mr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function Qft(e){if(e instanceof mr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function Zft(e,t={}){let r=t.tries??3,n=t.baseMs??400,i=t.sleep??((o)=>new Promise((s)=>setTimeout(s,o)));RD("tries",r);for(let o=1;;o++)try{return await e()}catch(s){if(!(s instanceof mr&&s.retryable)||o>=r)throw s;let c=s.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw s;await i(Math.max(n*2**(o-1),c))}}async function ept(e){await e.body?.cancel().catch(()=>{return})}async function tpt(e,t,r={}){let n;try{n=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":r.userAgent??khe},signal:AbortSignal.timeout(r.timeoutMs??30000)})}catch(a){throw Dhe(a)}if(n.status!==200&&n.status!==206)throw await ept(n),Jft(n.status,n.headers.get("retry-after"));let i=n.body?.getReader();if(!i)throw new mr("no-body");let o=new Uint8Array(t),s=0;try{while(s<t){let{done:a,value:c}=await i.read();if(a||!c)break;let u=Math.min(c.length,t-s);o.set(c.subarray(0,u),s),s+=u}}catch(a){throw Dhe(a)}finally{await i.cancel().catch(()=>{return})}if(s<(r.minBytes??0))throw new mr("short-body");return o.subarray(0,s)}var Rhe={sideFileBytes:2097152,participantsBytes:16777216};function rpt(e,t){let r=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(r)return/^\d+$/.test(r)?`aws/http-${r}`:`aws/error-${r}`;return`aws/exit-${t}`}async function npt(e,t,r={}){let n;try{let i=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...r.env?{env:r.env}:{}}),o=!1;n=setTimeout(()=>{o=!0,i.kill("SIGKILL")},r.timeoutMs??600000);let[s,a,c]=await Promise.all([new Response(i.stdout).text(),new Response(i.stderr).text(),i.exited]);if(o)throw new mr("aws/timeout");if(c!==0)throw new mr(rpt(a,c));return s}catch(i){if(i instanceof mr)throw i;throw new mr("aws/unavailable")}finally{clearTimeout(n)}}function ipt(){let e;return async()=>{if(e!==void 0)return e;if(process.env.GITHUB_TOKEN)return e=process.env.GITHUB_TOKEN,e;try{let t=Bun.spawn(["gh","auth","token"],{stdout:"pipe",stderr:"ignore"}),r=(await new Response(t.stdout).text()).trim();e=r===""?null:r}catch{e=null}return e}}var $D=(e)=>e.replace(/\/+$/,"");function Che(e={}){let t=e.retryAfterCapMs??30000,r=e.awsTimeoutMs??600000;return{api:$D(e.api??process.env.NEMAR_API_BASE??Vft),data:$D(e.data??process.env.NEMAR_DATA_BASE??Hft),s3Base:$D(e.s3Base??Gft),githubApi:$D(e.githubApi??Wft),userAgent:e.userAgent??khe,fileConcurrency:e.fileConcurrency??24,workerLimit:Kft(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((n)=>new Promise((i)=>setTimeout(i,n))),now:e.now??Date.now,retryAfterCapMs:t,breakers:Xft({streak:e.abortStreak??25,retryAfterCapMs:t,now:e.now??Date.now}),limits:{treeHeaderSample:300,scansTables:1,jsonFiles:300,textFiles:300,sideFileBytes:65536,participantsBytes:1048576,...e.limits},readVersionManifest:e.readVersionManifest??((n,i)=>npt(n,i,{timeoutMs:r,env:e.awsEnv})),githubToken:e.githubToken??ipt(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var Ahe=(e,t)=>t.startsWith(`${e.data}/`),opt=(e,t)=>Ahe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function spt(e,t,r){let n=opt(e,t);n.check();let i=n.pausedUntilMs()-e.now();if(i>0)await e.sleep(i),n.check();try{let o=await r();return n.ok(),o}catch(o){if(o instanceof mr)n.observe(o);throw o}}var apt=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var Ehe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function She(e,t,r){if(t<1)return[];if(e.length<=t)return[...e];let n=new Map;for(let c of e){let u=r(c),d=n.get(u);if(d)d.push(c);else n.set(u,[c])}let i=[...n.entries()].sort(([c],[u])=>c<u?-1:c>u?1:0).map(([,c])=>c);if(i.length>t)return Array.from({length:t},(c,u)=>i[Math.floor((u+0.5)*i.length/t)][0]);let o=i.map((c,u)=>({list:c,index:u})).sort((c,u)=>c.list.length-u.list.length||c.index-u.index),s=t,a=[];return o.forEach(({list:c},u)=>{let d=Math.min(c.length,Math.ceil(s/(o.length-u)));for(let f=0;f<d;f++)a.push(c[Math.floor((f+0.5)*c.length/d)]);s-=d}),a}var cpt=(e)=>e.severity==="identifier"&&nle.has(e.kind),lpt=(e)=>yu.has(e.kind);function Ohe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function upt(e){if(e.findings.some(cpt))return"direct-identifiers";if(e.findings.some((t)=>!lpt(t)))return"review";if(!Ohe(e))return"unchecked";if(e.edfCount>0&&e.unscreenedCount>0)return"clean-edf-only-others-unscreened";if(e.edfCount===0)return e.unscreenedCount>0?"not-screened":"no-recordings";return e.findings.length>0?"dates-only":"clean"}var dpt=/\.(edf|bdf)$/i,fpt=(e)=>e.edf===!0||dpt.test(e.path);function ppt(e){return{edf:e.filter(fpt),participants:e.find((t)=>t.path==="participants.tsv"),scans:e.filter((t)=>t.path.endsWith("_scans.tsv")),json:e.filter((t)=>t.path.endsWith(".json")).filter((t)=>t.path.startsWith("sourcedata/")||!mpt.test(t.path)).filter((t)=>!hpt.test(t.path)),text:e.filter((t)=>gpt.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var mpt=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,hpt=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,gpt=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function The(e,t,r,n=0){let i=()=>spt(e,t.url,()=>{let o={minBytes:n,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,r,o):tpt(t.url,r,o)});return Zft(()=>Ahe(e,t.url)?e.workerLimit(i):i(),apt(e))}async function kD(e,t,r){let n=await The(e,t,r),i=t.size===null?n.length>=r:t.size>r;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(n),truncated:i}}function Pp(e,t){for(let r of t)e.push(r)}var $he="edf/superseded-absent";async function Phe(e,t,r,n,i,o={}){let s=n.map((Se)=>Se.path),a=i==="clone",c=(Se,rt,rn)=>a?[...Se]:She(Se,rt,rn),u=[...e_([...s,...o.extraPaths??[]])],d=mle(s),f=Object.values(d.unscreened).reduce((Se,rt)=>Se+rt,0),p={},m=(Se,rt)=>{if(rt instanceof xT)throw rt;let rn=`${Se}/${Qft(rt)}`;p[rn]=(p[rn]??0)+1},g=(Se)=>Ehe(Se.path),h=ppt(n),b=new Set(o.supersededEdf??[]),x=[...h.edf,...b],{participants:w,scans:D,json:R,text:E}=h,O=i==="git-tree"?She(x,e.limits.treeHeaderSample,g):[...x],A=0,U=0,P=0,j=0,K={},I=new Set,G=new Set,re=new Set,F=new Set,q=new Set,ye=new Set;await SD(O,e.fileConcurrency,async(Se)=>{try{let rt=await The(e,Se,vt,vt),rn=fa(rt),{patient:LD}=Qv(rt);if(!rn.some((Hi)=>Hi.kind==="edf-unreadable")){I.add(LD);let Hi=LD.split(/\s+/);if(Hi.length>=4)re.add(Hi[0]),q.add(Hi[2]),F.add(Hi[3])}if(ye.add(Ehe(Se.path)),rn.some((Hi)=>Hi.severity==="identifier"))j++,G.add(LD);Pp(u,rn);for(let Hi of new Set(rn.map((y0e)=>y0e.kind)))K[Hi]=(K[Hi]??0)+1;A++}catch(rt){if(b.has(Se)&&rt instanceof mr&&rt.status===404){P++,p[$he]=(p[$he]??0)+1;return}U++,m("edf",rt)}});let ce=x.length-P,br=!1,St=!1;if(w&&w.size!==0)try{let{text:Se,truncated:rt}=await kD(e,w,e.limits.participantsBytes),rn=Se.indexOf(`
1456
1456
  `);if(rn<0&&rt)throw new mr("header-truncated");Pp(u,ule(rn<0?Se:Se.slice(0,rn))),Pp(u,fle(Se)),St=rt}catch(Se){br=!0,m("participants",Se)}let gr=c(D,e.limits.scansTables,g),tn=0;await SD(gr,e.fileConcurrency,async(Se)=>{if(Se.size===0){tn++;return}try{let{text:rt}=await kD(e,Se,e.limits.sideFileBytes);Pp(u,Zv(rt)),tn++}catch(rt){m("scans",rt)}});let Cr=e.limits.sideFileBytes,Ur=(Se)=>Se.size!==null&&Se.size>Cr,ee=c(R.filter((Se)=>!Ur(Se)),e.limits.jsonFiles,g),z=c(E.filter((Se)=>!Ur(Se)),e.limits.textFiles,g),ne=0,Z=0;await SD(ee,e.fileConcurrency,async(Se)=>{if(Se.size===0){ne++;return}try{let{text:rt}=await kD(e,Se,Cr),rn;try{rn=JSON.parse(rt)}catch{throw new mr("json-parse")}Pp(u,gu(rn)),ne++}catch(rt){m("json",rt)}}),await SD(z,e.fileConcurrency,async(Se)=>{if(Se.size===0){Z++;return}try{let{text:rt}=await kD(e,Se,Cr);Pp(u,ple(rt)),Z++}catch(rt){m("text",rt)}});let J={edf_headers:{candidates:ce,oversize:0,selected:O.length-P,scanned:A},scans_tables:{candidates:D.length,oversize:0,selected:gr.length,scanned:tn},json_files:{candidates:R.length,oversize:R.filter(Ur).length,selected:ee.length,scanned:ne},text_files:{candidates:E.length,oversize:E.filter(Ur).length,selected:z.length,scanned:Z}},ot=new Set,ci=(Se,rt)=>{if(rt.oversize>0)ot.add(`${Se}-oversize`);if(rt.candidates-rt.oversize>rt.selected)ot.add(`${Se}-sampled`);if(rt.scanned<rt.selected)ot.add(`${Se}-unread`)};if(ci("edf-headers",J.edf_headers),ci("json",J.json_files),ci("text",J.text_files),J.scans_tables.scanned<J.scans_tables.selected)ot.add("scans-unread");if(br)ot.add("participants-unread");if(St)ot.add("participants-truncated");for(let Se of o.extraIncompleteReasons??[])ot.add(Se);let As=[...ot].sort(),VT={findings:u,edfCount:ce,headerRead:A,unscreenedCount:f,incompleteReasons:As},h0e=u.filter((Se)=>Se.severity==="identifier"),g0e=Object.entries(p).filter(([Se])=>!Se.startsWith("edf/")).reduce((Se,[,rt])=>Se+rt,0);return{id:t,version:r,scanned_at:new Date().toISOString(),manifest_source:i,status:upt(VT),incomplete:!Ohe(VT),incomplete_reasons:As,files:{total:n.length,edf_bdf:ce,header_read:A,header_read_failed:U},sampling:J,read_failures:p,edf_bdf_files_flagged:j,distinct_patient_field_values:I.size,distinct_subjects_with_edf_bdf:ye.size,distinct_patient_code_subfield:re.size,distinct_patient_name_subfield:F.size,distinct_patient_birth_subfield:q.size,distinct_patient_field_values_in_flagged_files:G.size,findings_by_kind:hle(u),edf_bdf_files_by_kind:K,unscreened_formats:d.unscreened,side_reads_failed:g0e,finding_fields:[...new Set(h0e.map((Se)=>`${Se.kind}:${Se.field}`))].sort()}}xu();jr();Gf();vu();var Pu="--acknowledge-identifier-preflight",wpt=16,vpt="local:";function _T(e){let t=[],r=new Map,n=0,i=[""];while(i.length>0){let o=i.pop(),s;try{s=bpt(o===""?e:Ihe(e,o),{withFileTypes:!0})}catch{n++;continue}s.sort((c,u)=>c.name<u.name?-1:c.name>u.name?1:0);let a=[];for(let c of s){let u=c.name;if(o===""&&(u===".git"||u===".nemar"))continue;let d=o===""?u:`${o}/${u}`;if(c.isDirectory()){a.push(d);continue}if(u===".gitattributes")continue;let f=`${vpt}${t.length}`,p=Ihe(e,d),m=null;try{let g=Fhe(p);if(g.isFile())m=g.size,r.set(f,p);else if(g.isDirectory()&&!ypt(p).isSymbolicLink()){a.push(d);continue}}catch{}t.push({path:d,size:m,url:f})}for(let c=a.length-1;c>=0;c--)i.push(a[c])}return{entries:t,readable:r,unlisted:n}}function _pt(e,t=new Map){return async(r,n,i)=>{let o=e.get(r.url);if(o===void 0)throw new mr("unreadable-entry");let s=t.get(o),a;try{a=await xpt(o,"r")}catch{throw new mr("unreadable-entry")}try{let c=r.size===null?n:Math.min(n,r.size),u=new Uint8Array(c),d=0;while(d<c){let{bytesRead:f}=await a.read(u,d,c-d,d);if(f===0)break;d+=f}if(d<i.minBytes)throw new mr("short-body");if(s)u.set(s.subarray(0,Math.min(d,s.length)),0);return u.subarray(0,d)}catch(c){if(c instanceof mr)throw c;throw new mr("unreadable-entry")}finally{await a.close().catch(()=>{return})}}}async function Nhe(e,t){let r=_T(e),n=Che({fileConcurrency:wpt,workerConcurrency:1,limits:{...Rhe},readEntryHead:_pt(r.readable,t),githubToken:async()=>null,readVersionManifest:async()=>{throw new mr("unreadable-entry")},sleep:async()=>{return}}),i=await Phe(n,"local",null,r.entries,"clone",{extraIncompleteReasons:r.unlisted>0?["tree-truncated"]:[]}),o={scanned_at:i.scanned_at,status:i.status,incomplete:i.incomplete,incomplete_reasons:i.incomplete_reasons,files:i.files,findings_by_kind:i.findings_by_kind,edf_bdf_files_flagged:i.edf_bdf_files_flagged,unscreened_formats:i.unscreened_formats,read_failures:i.read_failures};return nA(Ele(Sle(o)))}function AD(e){if(ll(e.status)!=="acknowledge")return[];let t=new Set([e.status]);if(e.incomplete&&e.status!=="unchecked")t.add("unchecked");let r=Object.values(e.unscreened_formats).reduce((i,o)=>i+o,0),n=e.status==="not-screened"||e.status==="clean-edf-only-others-unscreened";if(r>0&&!n)t.add("not-screened");return[...t].sort()}var jhe=(e,t)=>e.length===t.length&&e.every((r,n)=>r===t[n]);function Mhe(e,t){let r=e.split(",").map((i)=>i.trim()).filter((i)=>i!==""),n=o_;if(r.length===0||!r.every((i)=>n.includes(i)))throw new qp(`Allowed verdicts are ${n.join(", ")}. Direct identifiers cannot be acknowledged.`);return[...t??[],...r]}function Dpt(e,t){let r=ll(e.status);if(r==="clear")return{action:"proceed",acknowledgedVia:null};if(r!=="acknowledge")return{action:"refuse"};if(t.acknowledge!==void 0){let n=[...new Set(t.acknowledge)].sort();return jhe(n,AD(e))?{action:"proceed",acknowledgedVia:"flag"}:{action:"stop",why:"acknowledgment-mismatch"}}if(t.dryRun)return{action:"preview"};if(t.no)return{action:"stop",why:"declined"};if(t.isTty)return{action:"prompt"};return{action:"stop",why:"acknowledgment-required"}}var Ept={review:"the scanner found something a person should look at (the kinds are listed above)",unchecked:"the scanner could not read everything it should have (see Incomplete above)","not-screened":"some recordings are in formats the scanner cannot read, so their headers were not checked","clean-edf-only-others-unscreened":"the EDF/BDF headers are clean, but other recordings are in formats the scanner cannot read"},wT=(e)=>`${Pu} ${e.join(",")}`;function vT(e){console.log(l.yellow(" This does not stop an upload, but it needs your explicit acknowledgment of:"));for(let t of e)console.log(l.yellow(` ${t}: ${Ept[t]??"not clean"}.`));console.log(l.dim(" Your acknowledgment is recorded with your deposit attestation. NEMAR screens the dataset again when you request publication, and an administrator decides then."))}function qhe(){console.log(),console.log(l.red(" Upload refused: the preflight found direct identifiers (a name, a birth date finer than the year, a record number, an age over 89, or an identifying column or key). Nothing was sent.")),console.log(l.red(" Remove them from the files (for EDF/BDF, the patient and recording fields of the header) and run the upload again.")),console.log(l.dim(` There is no override, and ${Pu} does not apply. If this is a false positive, please report it, so the scanner is fixed for every dataset. Terms: ${yD}`))}function Lhe(e){if(e instanceof r_)return`report-${e.message}`;let t=e instanceof Error&&/^[A-Za-z]{1,40}$/.test(e.name)?e.name:"unknown",r=e?.code;return typeof r==="string"&&/^E[A-Z0-9]{1,20}$/.test(r)?`${t} ${r}`:t}function Bhe(e,t){e.fail("Identifier preflight: DID NOT FINISH"),console.log(l.red(` The preflight could not produce a verdict, so nothing was uploaded (${Lhe(t)}).`)),console.log(l.dim(" Please report this: https://github.com/nemarOrg/nemar-cli/issues"))}function CD(e,t,r=""){let n=iA(t,null),i=`${n.headline}${r}`;if(n.tone==="ok")e.succeed(i);else if(n.tone==="stop")e.fail(i);else e.warn(i);for(let o of Ds({state:t.status,...n},2).slice(1))console.log(o)}function Uhe(e,t){try{return Lt($le({version:t_,scanner:`nemar-cli@${oo}`,scan:e,acknowledged_via:t}))}catch(r){return console.log(l.red(` The preflight's record did not fit the report contract (${Lhe(r)}), so nothing was uploaded.`)),$e}}async function zhe(e,t,r=process.stdin.isTTY===!0,n){let i=S("Screening for identifiers on this machine (nothing is sent)...").start(),o=!1;try{o=Fhe(e).isDirectory()}catch{o=!1}if(!o)return i.fail("Identifier preflight: the dataset path is not a directory"),$e;let s=new Map((n?.items??[]).map((p)=>[p.path,p.after])),a;try{a=await Nhe(e,s)}catch(p){return Bhe(i,p),$e}CD(i,a);let c=AD(a),u=Dpt(a,{acknowledge:t.acknowledgeIdentifierPreflight,dryRun:t.dryRun,no:t.no,isTty:r}),d;switch(u.action){case"proceed":if(u.acknowledgedVia==="flag")console.log(l.dim(` Acknowledged with ${wT(c)}.`));else if(t.acknowledgeIdentifierPreflight!==void 0)console.log(l.dim(` Nothing to acknowledge; ${Pu} was not needed.`));d=u.acknowledgedVia;break;case"preview":return vT(c),console.log(l.yellow(` A real upload stops here until you acknowledge it: answer the prompt, or pass ${wT(c)}.`)),console.log(),Lt(null);case"prompt":{vT(c);let p=!1,m=()=>{console.log(l.red(`
1457
1457
  Upload cancelled. Nothing was sent.`)),Pe(),process.exit(130)};process.once("SIGINT",m);let g=setInterval(()=>{return},1000);try{({acknowledged:p}=await _e.prompt([{type:"confirm",name:"acknowledged",message:"Upload anyway?",default:!1}]))}catch{p=!1}finally{clearInterval(g),process.off("SIGINT",m)}if(p!==!0)return console.log(l.red(" Upload cancelled. Nothing was sent.")),Pe(),$e;console.log(l.dim(" Acknowledged at the prompt.")),d="prompt";break}case"refuse":return qhe(),Pe(),$e;case"stop":if(u.why==="acknowledgment-mismatch")console.log(l.red(` ${Pu} must name exactly what was found, which is: ${c.join(",")}. It does not acknowledge this scan. Nothing was sent.`));else vT(c),console.log(l.red(u.why==="declined"?" Declined (--no). Nothing was sent.":` No terminal to ask at: run interactively, or pass ${wT(c)}. --yes does not acknowledge a finding. Nothing was sent.`));return Pe(),$e}let f=Uhe(a,d);if(f.status==="ok")console.log();return f}async function Vhe(e,t){let r=S("Screening again, right before anything is sent...").start(),n;try{n=await Nhe(e)}catch(a){return Bhe(r,a),$e}let i=ll(n.status);if(i!=="clear"&&i!=="acknowledge")return CD(r,n),qhe(),Pe(),$e;let o=AD(t.scan),s=AD(n);if(!jhe(o,s))return CD(r,n),console.log(l.red(` The files changed since the preflight, and so did what it found (acknowledged: ${o.join(",")||"nothing"}; now: ${s.join(",")}). Nothing was sent. Run the upload again.`)),Pe(),$e;if(n_(n.findings_by_kind)!==n_(t.scan.findings_by_kind))CD(r,n," (screened again)");else r.succeed(`${iA(n,null).headline} (screened again)`);return Uhe(n,t.acknowledged_via)}var Mpt=/\.(edf|bdf)$/i,Jhe=go(".nemar","date-normalization"),qpt=()=>({tracked:0,"nested-repository":0,ignored:0,"tracking-unknown":0,link:0,"not-writable":0,"other-filesystem":0,unverified:0});function Lpt(){return{items:[],left:qpt()}}function Bpt(e){if(process.env.GIT_DIR||process.env.GIT_WORK_TREE)return!0;for(let t=e;;t=OD(t)){if(Whe(go(t,".git")))return!0;if(OD(t)===t)return!1}}var ST=(e)=>e.normalize("NFC").toLowerCase();async function DT(e,t,r){try{let n=await k(e,{cwd:t,...r===void 0?{}:{stdin:r}});if(!(n.exitCode===0||e.includes("check-ignore")&&n.exitCode===1))return null;return new Set(n.stdout.split("\x00").filter(Boolean).map(ST))}catch{return null}}async function Upt(e,t){let r=`${t.join("\x00")}\x00`;if(Bpt(e)){let i=await DT(["git","ls-files","-z"],e),o=await DT(["git","check-ignore","-z","--stdin"],e,r);return i&&o?{tracked:i,ignored:o}:null}let n=null;try{if(n=Opt(go(jpt(),"nemar-ignore-")),(await k(["git","init","-q","--bare",n],{cwd:e})).exitCode!==0)return null;let o=await DT(["git",`--git-dir=${n}`,`--work-tree=${e}`,"check-ignore","--no-index","-z","--stdin"],e,r);return o?{tracked:new Set,ignored:o}:null}catch{return null}finally{if(n!==null)try{AT(n,{recursive:!0,force:!0})}catch{}}}function $T(e){let t;try{t=CT(e,"r")}catch{return null}try{let r=new Uint8Array(vt),n=0;while(n<vt){let i=Tpt(t,r,n,vt-n,n);if(i===0)break;n+=i}return n===vt?r:null}catch{return null}finally{try{RT(t)}catch{}}}var Hhe=(e,t)=>e!==null&&e.length===t.length&&e.every((r,n)=>r===t[n]);function Ghe(e){try{return $pt(e,ET.W_OK),!0}catch{return!1}}function zpt(e,t,r){let n=t.split("/").slice(0,-1);for(let i=1;i<=n.length;i++){let o=n.slice(0,i).join("/"),s=r.get(o);if(s===void 0){s=Whe(go(e,o,".git"));try{s||=Rs(go(e,o,".git")).isSymbolicLink()}catch{}r.set(o,s)}if(s)return!0}return!1}async function Xhe(e){let t=Lpt();try{await Vpt(e,t)}catch(r){Zt(`date normalization: planning stopped (${r instanceof Error?r.name:"unknown"})`)}return t}async function Vpt(e,t){let r=Yhe(e).dev,n=_T(e),i=[];for(let c of n.entries){if(!Mpt.test(c.path))continue;let u=n.readable.get(c.url);if(u===void 0)continue;let d=$T(u);if(d===null)continue;try{let f=B_(d);if(f.changed)i.push({path:u,rel:c.path,before:d,after:f.header})}catch(f){if(f instanceof ba)continue;t.left.unverified++,Zt(`date normalization: a header was not planned (${f instanceof Error?f.name:"unknown"})`)}}if(i.length===0)return;let o=await Upt(e,i.map((c)=>c.rel)),s=new Map,a=typeof process.getuid==="function"?process.getuid():null;for(let c of i){if(o===null){t.left["tracking-unknown"]++;continue}if(o.tracked.has(ST(c.rel))){t.left.tracked++;continue}if(zpt(e,c.rel,s)){t.left["nested-repository"]++;continue}if(o.ignored.has(ST(c.rel))){t.left.ignored++;continue}let u;try{u=Rs(c.path)}catch{continue}if(u.isSymbolicLink()){t.left.link++;continue}if(!u.isFile())continue;if(u.dev!==r){t.left["other-filesystem"]++;continue}if(a!==null&&u.uid!==a||(u.mode&128)===0||!Ghe(c.path)||!Ghe(OD(c.path))){t.left["not-writable"]++;continue}t.items.push({path:c.path,rel:c.rel,dev:u.dev,ino:u.ino,size:u.size,mtimeMs:u.mtimeMs,mode:u.mode,gid:u.gid,before:c.before,after:c.after})}}var Hpt=/^\d+-[0-9a-f]{16}$/;function Gpt(e){try{let t=go(e,Jhe);for(let r of[go(e,".nemar"),t])if(!Rs(r).isDirectory())return;for(let r of Ppt(t))if(Hpt.test(r))AT(go(t,r),{force:!0})}catch{}}function kT(e){for(let t of e)try{Fpt(t)}catch{}}function Wpt(e,t){let r=[],n=go(e,Jhe);try{for(let i of[go(e,".nemar"),n]){let o;try{o=Rs(i)}catch{Apt(i),r.push(i),o=Rs(i)}if(!o.isDirectory()||o.dev!==t)return kT([...r].reverse()),null}return{dir:n,made:r}}catch{return kT([...r].reverse()),null}}function Kpt(e){try{let t=CT(e,"r");try{Khe(t)}finally{RT(t)}}catch{}}function Ypt(e,t){let r=null;try{let n=(o)=>o.isFile()&&o.dev===e.dev&&o.ino===e.ino&&o.size===e.size&&o.mtimeMs===e.mtimeMs;if(!n(Rs(e.path))||!Hhe($T(e.path),e.before))return null;if(r=go(t,`${process.pid}-${Spt(8).toString("hex")}`),Cpt(e.path,r,ET.COPYFILE_EXCL|ET.COPYFILE_FICLONE),Rs(r).gid!==e.gid)Rpt(r,-1,e.gid);kpt(r,e.mode&4095);let i=CT(r,"r+");try{if(Npt(i,e.after,0,vt,0)!==vt)return null;Khe(i)}finally{RT(i)}if(Rs(r).size!==e.size||!Hhe($T(r),e.after))return null;if(!n(Rs(e.path)))return null;return Ipt(r,e.path),r=null,Kpt(OD(e.path)),Rs(e.path).mtimeMs}catch(n){return Zt(`date normalization: a header was not set (${n instanceof Error?n.name:"unknown"})`),null}finally{if(r!==null)try{AT(r,{force:!0})}catch{}}}function Qhe(e,t){let r={set:0,left:0,mtimes:new Map};if(Gpt(e),t.items.length===0)return r;let n=null;try{n=Wpt(e,Yhe(e).dev)}catch{}if(n===null)return r.left=t.items.length,Zt("date normalization: no work directory, nothing set"),r;try{for(let i of t.items){let o=Ypt(i,n.dir);if(o===null){r.left++;continue}r.set++,r.mtimes.set(i.rel,o)}}finally{kT([n.dir,...[...n.made].reverse().filter((i)=>i!==n.dir)])}if(r.set>0)console.log(l.dim(` ${vle(r.set)}`));return r}Ne();xi();sn();import{existsSync as c0,mkdirSync as mmt,readFileSync as l0,writeFileSync as yge}from"fs";import{basename as hmt,resolve as Iu}from"path";Zc();At();ii();xi();import{existsSync as TD,readFileSync as OT,writeFileSync as ege}from"fs";import{resolve as PD}from"path";var TT=[{spdxId:"CC0-1.0",name:"CC0 1.0 Universal (Public Domain)",description:"No rights reserved. Anyone can use the data for any purpose.",url:"https://creativecommons.org/publicdomain/zero/1.0/",allowsResearchUse:!0},{spdxId:"PDDL-1.0",name:"Open Data Commons Public Domain Dedication and License (PDDL)",description:"Database-specific public domain dedication.",url:"https://opendatacommons.org/licenses/pddl/1-0/",allowsResearchUse:!0},{spdxId:"CC-BY-4.0",name:"Creative Commons Attribution 4.0 International",description:"Attribution required. Free for any use including commercial.",url:"https://creativecommons.org/licenses/by/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-SA-4.0",name:"Creative Commons Attribution-ShareAlike 4.0 International",description:"Attribution + share-alike required. Derivatives must use same license.",url:"https://creativecommons.org/licenses/by-sa/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-4.0",name:"Creative Commons Attribution-NonCommercial 4.0 International",description:"Attribution required. Non-commercial use only.",url:"https://creativecommons.org/licenses/by-nc/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-SA-4.0",name:"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International",description:"Attribution + non-commercial + share-alike required.",url:"https://creativecommons.org/licenses/by-nc-sa/4.0/",allowsResearchUse:!0},{spdxId:"ODC-By-1.0",name:"Open Data Commons Attribution License v1.0",description:"Database-specific attribution license.",url:"https://opendatacommons.org/licenses/by/1.0/",allowsResearchUse:!0},{spdxId:"ODbL-1.0",name:"Open Data Commons Open Database License v1.0",description:"Database attribution + share-alike. Produced works can be any license.",url:"https://opendatacommons.org/licenses/odbl/1.0/",allowsResearchUse:!0}],Zhe=new Set(["CC0-1.0","CC-BY-4.0","CC-BY-SA-4.0","CC-BY-NC-4.0","CC-BY-NC-SA-4.0","CC-BY-ND-4.0","CC-BY-NC-ND-4.0","PDDL-1.0","ODC-By-1.0","ODbL-1.0","MIT","Apache-2.0","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","BSD-2-Clause","BSD-3-Clause","ISC","Unlicense"]);function tge(e){let t=PD(e,"dataset_description.json");if(TD(t))try{let n=JSON.parse(OT(t,"utf-8"));if(typeof n.License==="string"&&n.License.trim())return{spdxId:n.License.trim(),source:"dataset_description"}}catch(n){if(n instanceof SyntaxError)console.warn(` Warning: dataset_description.json has invalid JSON: ${n.message}`);else console.warn(` Warning: Could not read dataset_description.json: ${n instanceof Error?n.message:String(n)}`)}let r=["LICENSE","LICENSE.txt","LICENSE.md","LICENCE","LICENCE.txt"];for(let n of r){let i=PD(e,n);if(TD(i)){try{let o=OT(i,"utf-8").toLowerCase();if(o.includes("cc0")||o.includes("public domain dedication"))return{spdxId:"CC0-1.0",source:"license_file"};if(o.includes("attribution-noncommercial-sharealike"))return{spdxId:"CC-BY-NC-SA-4.0",source:"license_file"};if(o.includes("attribution-noncommercial"))return{spdxId:"CC-BY-NC-4.0",source:"license_file"};if(o.includes("attribution-sharealike"))return{spdxId:"CC-BY-SA-4.0",source:"license_file"};if(o.includes("creativecommons")&&o.includes("attribution"))return{spdxId:"CC-BY-4.0",source:"license_file"};if(o.includes("open database license")||o.includes("odbl"))return{spdxId:"ODbL-1.0",source:"license_file"};if(o.includes("open data commons")&&o.includes("attribution"))return{spdxId:"ODC-By-1.0",source:"license_file"};if(o.includes("public domain dedication and license")||o.includes("pddl"))return{spdxId:"PDDL-1.0",source:"license_file"};if(o.includes("permission is hereby granted, free of charge")||o.includes("mit license"))return{spdxId:"MIT",source:"license_file"}}catch(o){console.warn(` Warning: Could not read ${n}: ${o instanceof Error?o.message:String(o)}`)}return{spdxId:void 0,source:"license_file"}}}return{spdxId:void 0,source:"none"}}async function PT(e){let t=TT.map((i)=>({name:`${i.spdxId.padEnd(22)} ${i.description}`,value:i.spdxId,short:i.spdxId}));t.push({name:"Other (enter SPDX ID manually)",value:"__custom__",short:"Custom"});let r=e?TT.find((i)=>i.spdxId===e)?.spdxId:void 0,{selected:n}=await _e.prompt([{type:"list",name:"selected",message:"Select a license for this dataset:",choices:t,default:r,pageSize:t.length}]);if(n==="__custom__"){let{customId:i}=await _e.prompt([{type:"input",name:"customId",message:"Enter SPDX license ID (e.g., MIT, Apache-2.0):",validate:(o)=>{if(!o.trim())return"License ID is required";return!0}}]);return i.trim()}return n}function rge(e){let t=e.toUpperCase().replace(/\s+/g,"-");if(Zhe.has(e))return!0;for(let r of Zhe)if(r.toUpperCase()===t)return!0;return!1}function Jpt(e){let t=TT.find((r)=>r.spdxId===e);if(t)return`${t.name}
1458
1458
 
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.19-dev.3634",
4
+ "version": "0.10.19",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",