nemar-cli 0.10.34-PR2199.cbcc72e → 0.10.34-PR2199.eb4ccf1

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.
@@ -23,7 +23,7 @@ ${t}`,zM,GM,KM=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=VM.bind(null,n,
23
23
  `)}var Fl=!1;var{spawn:WF}=globalThis.Bun;function Vl(e,t=[]){let r=e.replace(YF,'("$1","<redacted>")');for(let n of t)if(n.length>=XF)r=r.split(n).join("<redacted>");return r}function QF(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],r=new Set;for(let n of[process.env,e??{}])for(let s of t){let o=n[s];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function hw(e,t){let r=e.getReader(),n=new TextDecoder,s="";while(!0){let{done:o,value:i}=await r.read();if(o)break;if(i.byteLength===0)continue;t(),s+=n.decode(i,{stream:!0})}return s+n.decode()}async function mw(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete r[y];let n=WF({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),s=!1,o,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??JF)};if(u(),t.timeout)o=setTimeout(()=>{s=!0,c(),n.kill()},t.timeout);let d=ic()?[...QF(r),...t.redact??[]]:[];if(ic()){let y=t.cwd?` (cwd=${t.cwd})`:"";qs(Nt.dim(Vl(`$ ${e.join(" ")}${y}`,d)))}let l=()=>{a=performance.now(),u()},p,f,h,m=n.exited.then((y)=>(c(),y));try{[p,f,h]=await Promise.all([hw(n.stdout,l),hw(n.stderr,l),m])}finally{if(c(),o)clearTimeout(o)}if(ic()){if(t.sensitiveOutput)qs(Nt.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())qs(Nt.dim(Vl(p.trimEnd(),d)));if(f.trim())qs(Nt.yellow(Vl(f.trimEnd(),d)))}qs(Nt.dim(`(exit ${h})`))}if(s)return{stdout:p,stderr:f||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:f,exitCode:h,timedOut:!1}}var YF,XF=8,JF=120000;var gw=F(()=>{Ul();YF=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function eV(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function _w(e,t=eV()){return e.installInstructions[t]}function tV(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function nV(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:rV}async function vw(e){try{let{exitCode:t,stdout:r,timedOut:n}=await mw(e.cmd,{timeout:nV()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:tV(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 zl(){let e=Object.entries(yw);return Promise.all(e.map(async([t,r])=>{let{available:n,version:s,timedOut:o}=await vw(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:s,timedOut:o,installInstruction:_w(r)}}))}async function Z3(){let t=(await zl()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
24
24
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let r of t)console.warn(` - ${r.name} (${r.purpose})`),console.warn(` Install: ${r.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function eB(e){let r=ZF[e].map((i)=>yw[i]).filter(Boolean),n=await Promise.all(r.map(async(i)=>{let a=await vw(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of n)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let s=n.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:_w(i.check)}));if(s.length===0)return;let o=[`
25
25
  Missing required tools:`];for(let i of s)o.push(` ${i.tool} not installed`),o.push(` Install: ${i.installInstruction}`);throw Error(o.join(`
26
- `))}var yw,ZF,rV=4000;var $w=F(()=>{gw();yw={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)"}}},ZF={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 bw;var Ew=F(()=>{bw={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.34-PR2199.cbcc72e",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Ew();ac=bw.version});import{mkdirSync as oV,readdirSync as iV,unlinkSync as aV,writeFileSync as cV}from"fs";import{join as Kl}from"path";function dB(){Ds=!0}function lc(){return Ds}function fB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function pB(e){Tw=e,pr(`Step: ${e}`)}function hB(){xw=!0}function mB(){return xw}function gB(){if(Rw)return;Bl=!0}function yB(){Bl=!1,Rw=!0}function _B(){return Bl}function pr(e){if(Ds)process.stderr.write(`[debug] ${e}
26
+ `))}var yw,ZF,rV=4000;var $w=F(()=>{gw();yw={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)"}}},ZF={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 bw;var Ew=F(()=>{bw={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.34-PR2199.eb4ccf1",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Ew();ac=bw.version});import{mkdirSync as oV,readdirSync as iV,unlinkSync as aV,writeFileSync as cV}from"fs";import{join as Kl}from"path";function dB(){Ds=!0}function lc(){return Ds}function fB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function pB(e){Tw=e,pr(`Step: ${e}`)}function hB(){xw=!0}function mB(){return xw}function gB(){if(Rw)return;Bl=!0}function yB(){Bl=!1,Rw=!0}function _B(){return Bl}function pr(e){if(Ds)process.stderr.write(`[debug] ${e}
27
27
  `)}function fV(e){let t={};for(let[r,n]of Object.entries(e))t[r]=dV.has(r.toLowerCase())?"[REDACTED]":n;return t}function Ow(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Hl(e,t,r=0){if(r>hV)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>Hl(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[s,o]of Object.entries(t))n[s]=Hl(s,o,r+1);return n}if(typeof t==="string"){if(pV.test(e))return"[REDACTED]";return t.replace(kw,Ow)}return t}function Wl(e){return e.replace(mV,"Bearer [REDACTED]").replace(gV,"[REDACTED_AWS_KEY]").replace(yV,"$1[REDACTED]").replace(_V,"$1$2=[REDACTED]").replace(kw,Ow)}function vV(e){return Wl(e)}function ww(e,t=lV){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(Hl("",n))}catch{}if(r=Wl(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function dc(e){if(!Ds)return;let t=vV(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?fV(e.requestHeaders):void 0,requestBody:ww(e.requestBody),responseBody:ww(e.responseBody)};uc.push(r),pr(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=dr(r);uc.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),pr(`redaction failed for ${e.method} ${t}: ${n}`)}}async function $V(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${ac}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${dr(t)})`)}e.push(""),e.push("Active account:");try{let t=hn();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: ${dr(t)})`)}e.push(""),e.push("External tools:");try{let t=await zl();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: ${dr(t)})`)}return e}async function EV(){return(await $V()).join(`
28
28
  `)}async function vB(){if(!Ds||cc!==void 0)return;try{cc=await EV()}catch(e){let t=dr(e);cc=`(could not build environment report: ${t})`,pr(`environment snapshot failed: ${t}`)}}function Aw(e){if(Sw.has(e))return{flag:e};for(let t of Sw){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 bV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Aw(n);if(!s){t.push(n);continue}if(s.kind==="long-eq")t.push(`${s.flag}=[REDACTED]`);else if(s.kind==="short-attached")t.push(`${s.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function wV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Aw(n);if(!s){t.push(n);continue}if(!s.kind&&r+1<e.length)r++}return t}function SV(e){let t=[];for(let n of wV(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 xV(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${Wl(bV(e).join(" "))}`),r.push(""),r.push(cc??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),uc.length===0)r.push(" (none)");else uc.forEach((n,s)=>{if(r.push(` [${s+1}] ${n.method} ${n.url} -> ${n.status??"ERROR"} (${n.durationMs}ms)`),n.error)r.push(` Error: ${n.error}`);if(n.note)r.push(` Note: ${n.note}`);if(n.requestHeaders)r.push(` Request headers: ${JSON.stringify(n.requestHeaders)}`);if(n.requestBody)r.push(` Request body: ${n.requestBody}`);if(n.responseBody)r.push(` Response body: ${n.responseBody}`)});return r.push(""),r.push(`Failing step: ${Tw??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
29
29
  `)}
package/dist/index.js CHANGED
@@ -99,7 +99,7 @@ ${t}`,zXe,VXe,WXe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=GXe.bind(nul
99
99
  `)}var dM=!1;var{spawn:z0t}=globalThis.Bun;function mp(e,t=[]){let n=e.replace(V0t,'("$1","<redacted>")');for(let r of t)if(r.length>=W0t)n=n.split(r).join("<redacted>");return n}function VR(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],n=new Set;for(let r of[process.env,e??{}])for(let o of t){let s=r[o];if(typeof s==="string"&&s.length>0)n.add(s)}return[...n]}async function mge(e,t){let n=e.getReader(),r=new TextDecoder,o="";while(!0){let{done:s,value:i}=await n.read();if(s)break;if(i.byteLength===0)continue;t(),o+=r.decode(i,{stream:!0})}return o+r.decode()}async function A(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=z0t({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:n}),o=!1,s,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},l=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??K0t)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=Ug()?[...VR(n),...t.redact??[]]:[];if(Ug()){let y=t.cwd?` (cwd=${t.cwd})`:"";qd(u.dim(mp(`$ ${e.join(" ")}${y}`,d)))}let f=()=>{a=performance.now(),l()},p,m,h,g=r.exited.then((y)=>(c(),y));try{[p,m,h]=await Promise.all([mge(r.stdout,f),mge(r.stderr,f),g])}finally{if(c(),s)clearTimeout(s)}if(Ug()){if(t.sensitiveOutput)qd(u.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())qd(u.dim(mp(p.trimEnd(),d)));if(m.trim())qd(u.yellow(mp(m.trimEnd(),d)))}qd(u.dim(`(exit ${h})`))}if(o)return{stdout:p,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:m,exitCode:h,timedOut:!1}}var V0t,W0t=8,K0t=120000;var zt=H(()=>{We();V0t=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function Y0t(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function gge(e,t=Y0t()){return e.installInstructions[t]}function X0t(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function Z0t(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Q0t}async function yge(e){try{let{exitCode:t,stdout:n,timedOut:r}=await A(e.cmd,{timeout:Z0t()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:X0t(n)}}catch(t){let n=t instanceof Error?t.message:String(t);if(!n.includes("ENOENT")&&!n.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${n}`);return{available:!1}}}async function jw(){let e=Object.entries(hge);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await yge(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:gge(n)}}))}async function bge(){let t=(await jw()).filter((n)=>n.required&&!n.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 n of t)console.warn(` - ${n.name} (${n.purpose})`),console.warn(` Install: ${n.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function hp(e){let n=J0t[e].map((i)=>hge[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await yge(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of r)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let o=r.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:gge(i.check)}));if(o.length===0)return;let s=[`
101
101
  Missing required tools:`];for(let i of o)s.push(` ${i.tool} not installed`),s.push(` Install: ${i.installInstruction}`);throw Error(s.join(`
102
- `))}var hge,J0t,Q0t=4000;var Lw=H(()=>{zt();hge={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)"}}},J0t={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 _ge;var wge=H(()=>{_ge={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.34-PR2199.cbcc72e",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Ls;var gp=H(()=>{wge();Ls=_ge.version});import{mkdirSync as twt,readdirSync as nwt,unlinkSync as rwt,writeFileSync as owt}from"fs";import{join as fM}from"path";function Rge(){Bg=!0}function Nl(){return Bg}function $ge(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Uw(e){kge=e,Tn(`Step: ${e}`)}function Wo(){Ege=!0}function Dge(){return Ege}function de(){if(Sge)return;mM=!0}function Bw(){mM=!1,Sge=!0}function Cge(){return mM}function Tn(e){if(Bg)process.stderr.write(`[debug] ${e}
102
+ `))}var hge,J0t,Q0t=4000;var Lw=H(()=>{zt();hge={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)"}}},J0t={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 _ge;var wge=H(()=>{_ge={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.34-PR2199.eb4ccf1",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Ls;var gp=H(()=>{wge();Ls=_ge.version});import{mkdirSync as twt,readdirSync as nwt,unlinkSync as rwt,writeFileSync as owt}from"fs";import{join as fM}from"path";function Rge(){Bg=!0}function Nl(){return Bg}function $ge(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Uw(e){kge=e,Tn(`Step: ${e}`)}function Wo(){Ege=!0}function Dge(){return Ege}function de(){if(Sge)return;mM=!0}function Bw(){mM=!1,Sge=!0}function Cge(){return mM}function Tn(e){if(Bg)process.stderr.write(`[debug] ${e}
103
103
  `)}function cwt(e){let t={};for(let[n,r]of Object.entries(e))t[n]=awt.has(n.toLowerCase())?"[REDACTED]":r;return t}function Oge(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function pM(e,t,n=0){if(n>uwt)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>pM(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=pM(o,s,n+1);return r}if(typeof t==="string"){if(lwt.test(e))return"[REDACTED]";return t.replace(Age,Oge)}return t}function hM(e){return e.replace(dwt,"Bearer [REDACTED]").replace(fwt,"[REDACTED_AWS_KEY]").replace(pwt,"$1[REDACTED]").replace(mwt,"$1$2=[REDACTED]").replace(Age,Oge)}function hwt(e){return hM(e)}function xge(e,t=iwt){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(pM("",r))}catch{}if(n=hM(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function JR(e){if(!Bg)return;let t=hwt(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?cwt(e.requestHeaders):void 0,requestBody:xge(e.requestBody),responseBody:xge(e.responseBody)};KR.push(n),Tn(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=W(n);KR.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),Tn(`redaction failed for ${e.method} ${t}: ${r}`)}}async function gwt(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${Ls}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${W(t)})`)}e.push(""),e.push("Active account:");try{let t=Yt();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${W(t)})`)}e.push(""),e.push("External tools:");try{let t=await jw();for(let n of t){let r=n.available?n.version??"installed":n.timedOut?"(timed out)":"not installed";e.push(` ${n.name}: ${r}`)}}catch(t){e.push(` (could not probe external tools: ${W(t)})`)}return e}async function gM(){return(await gwt()).join(`
104
104
  `)}async function Tge(){if(!Bg||WR!==void 0)return;try{WR=await gM()}catch(e){let t=W(e);WR=`(could not build environment report: ${t})`,Tn(`environment snapshot failed: ${t}`)}}function Pge(e){if(vge.has(e))return{flag:e};for(let t of vge){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 ywt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=Pge(r);if(!o){t.push(r);continue}if(o.kind==="long-eq")t.push(`${o.flag}=[REDACTED]`);else if(o.kind==="short-attached")t.push(`${o.flag}[REDACTED]`);else if(t.push(r),n+1<e.length)t.push("[REDACTED]"),n++}return t}function bwt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=Pge(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function wwt(e){let t=[];for(let r of bwt(e)){if(r.startsWith("-"))continue;if(t.push(r),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function _wt(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${hM(ywt(e).join(" "))}`),n.push(""),n.push(WR??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),KR.length===0)n.push(" (none)");else KR.forEach((r,o)=>{if(n.push(` [${o+1}] ${r.method} ${r.url} -> ${r.status??"ERROR"} (${r.durationMs}ms)`),r.error)n.push(` Error: ${r.error}`);if(r.note)n.push(` Note: ${r.note}`);if(r.requestHeaders)n.push(` Request headers: ${JSON.stringify(r.requestHeaders)}`);if(r.requestBody)n.push(` Request body: ${r.requestBody}`);if(r.responseBody)n.push(` Response body: ${r.responseBody}`)});return n.push(""),n.push(`Failing step: ${kge??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
105
105
  `)}
@@ -249,7 +249,7 @@ sub-02 30 F
249
249
  `)),t.keys.length>0){let x=C("Verifying copied data...").start(),v=await Bl(Lx,`${o}/objects/`,gm),S=ojt(t.keys,v);if(S.length>0){let L=`${S.length} of ${t.keys.length} objects missing at s3://${Lx}/${o}/objects/. Re-run the copy phase before finalizing.`;throw x.fail(L),Error(L)}x.succeed(`Verified ${t.keys.length} objects present`);let E=await ef(r,e.devRemote??h3);if(E!==i){let L=`${e.devRemote??h3} uuid drifted (prepare=${i} now=${E}). Aborting before registering keys against the wrong remote.`;throw console.error(u.red(L)),Error(L)}let O=C("Registering files in git-annex...").start(),I=await tf(r,t.keys,i);if(I.failed>0){let L=`${I.failed} of ${t.keys.length} git-annex key registrations are not in the location log (e.g. ${I.missing.slice(0,3).join(", ")}). Re-run finalize to retry.`;throw O.fail(L),Error(L)}O.succeed(`Registered ${I.success} files in git-annex`);let V=C("Pushing git-annex branch...").start(),T=await _r(r,"origin");if(!T.success){let L=`Failed to push git-annex branch: ${T.error}`;throw V.fail(L),Error(L)}if(T.warning){let L=`git-annex branch push failed: ${T.warning}`;throw V.fail(L),Error(L)}V.succeed("Pushed git-annex branch")}let a=!1,c=C("Deploying CI workflows...").start();try{await Fl(o),c.succeed("CI workflows deployed (BIDS validation, LLM enrichment, archive generation)"),a=!0}catch(x){let v=x instanceof Error?x.message:String(x);c.fail(`CI deployment failed: ${v}`),console.log(u.dim(` After fixing the deploy failure, run 'nemar admin ci add ${o}'.`))}if(a){let x=C("Waiting for BIDS validation run to register...").start(),v=await dq(o,x);if(v.kind==="found")x.succeed("BIDS validation run registered");else if(v.kind==="timeout")x.warn("BIDS validation run did not register within 120s; continuing (ci_check retries at approval).");else{let S=v.lastError instanceof Error?v.lastError.message:String(v.lastError);x.fail(`BIDS validation polls failed: ${S}`)}}let l=!1,d=C("Refreshing metadata + LLM enrichment...").start();try{let x=await Qg(o),v=x.enrichment?.status==="ok",S=x.sync?.metadata_columns_written===!0;if(l=v&&S,l)d.succeed("Refreshed enrichment + metadata columns");else d.warn(`Partial reindex (run 'nemar admin reindex ${o}' to retry)`)}catch(x){let v=x instanceof Error?x.message:String(x);d.warn(`Reindex failed (non-fatal): ${v}`)}if(!n.publish){console.log(u.green(`
250
250
  Exemplar clone complete: ${s} -> ${o} (not published; re-run with --publish).`));return}if(!l)throw Error(`Refusing to publish ${o}: metadata reindex did not fully succeed, so .nemar/metadata.json may still carry the source dataset's real identity. Re-run 'nemar admin reindex ${o}' until it succeeds, then 'nemar admin repo publish request/approve ${o}' to publish manually.`);let f=5,p=300000,m=C("Requesting publication...").start(),h=!1;for(let x=1;x<=f;x++)try{await zg(o),h=!0;break}catch(v){let S=v instanceof Error?v.message:String(v);if(!S.includes("BIDS validation is currently running")){let E=`Failed to request publication: ${S}`;throw m.fail(E),Error(E)}if(x===f){let E=`BIDS validation still running after ${f} attempts. Re-run 'nemar admin repo publish request/approve ${o}' once validation completes.`;throw m.fail(E),Error(E)}m.text=`Waiting for BIDS validation to complete... (attempt ${x}/${f})`,await new Promise((E)=>setTimeout(E,p))}if(h)m.succeed("Publication requested");let g=C("Approving publication (sandbox DOI)...").start(),y=10,b=!1;for(let x=1;x<=y;x++)try{await Jg(o,x>1,!0),b=!0;break}catch(v){let S=v instanceof Error?v.message:String(v);if(x<y)g.text=`Approving publication... (attempt ${x+1}/${y})`,await new Promise((E)=>setTimeout(E,3000));else{let E=`Failed to approve publication after ${y} attempts: ${S}`;throw g.fail(E),Error(E)}}if(b)g.succeed("Publication approved (sandbox DOI)");console.log(u.green(`
251
251
  Exemplar clone + publish complete: ${s} -> ${o}`)),console.log(u.dim(` GitHub: https://github.com/${jx}/${o}`))}async function b3(e){let t=await njt(e.xxId,e.sourceId,{workDir:e.workDir,name:e.name,description:e.description,...e.mirror!==void 0?{mirror:e.mirror}:{}}),n=await rjt(t,{includeDerived:e.includeDerived});await sjt(t,n,{publish:e.publish})}var jx="nemarDatasets",xOe="nemar",Lx="nemar-dev",gm="us-east-2",SOe=16,kOe,ROe,p3="nemar-s3",h3="nemar-s3-dev",vOe="nemar-s3-source",Z6t="annex-uuid";var a1=H(()=>{We();vo();_c();Ve();ta();Ei();kc();zt();Nc();Wr();xx();Ss();kOe=/^xx0999\d{2}$/,ROe=/^(nm|on)\d{6}$/});import{rmSync as ijt}from"fs";function Ux(e){let t=!w3(e),n=e.gitResidentData.length>0;if(t&&n)return"policy-and-data";if(n)return"data";if(t)return"policy";return"compliant"}function cjt(e){let t=new Map;for(let r of e.split(`
252
- `)){let o=r.match(/^(\d+(?:\.\d+)?)s\s+(\S+)\s*(.*)$/);if(!o)continue;let[,s,i,a]=o,c=Number(s),l=a.trim(),d=t.get(i);if(!d||d.at<=c)t.set(i,{at:c,value:l})}let n=new Map;for(let[r,{value:o}]of t)if(o!=="")n.set(r,o);return n}function ljt(e){let t=[];for(let[i,a]of e.attributeContents){let c=df(a);if(c.stripped===0&&c.skipped.length===0)continue;t.push({path:i,rulesRemoved:c.stripped,declined:c.skipped})}t.sort((i,a)=>i.path.localeCompare(a.path));let r=(e.configLog?cjt(e.configLog):new Map).get("annex.largefiles")??null,o=[],s=[];for(let i of e.entries){if(i.mode!=="100644"&&i.mode!=="100755")continue;let a=i.size??Number.POSITIVE_INFINITY;if(!Ko(i.path,a))continue;if(a<=_3){s.push(i.path);continue}o.push({path:i.path,size:a})}return{datasetId:e.datasetId,attributeFiles:t,policyConfigured:r!==null&&$0e(r),configuredExpression:r,gitResidentData:o,pointerSuspects:s,treeTruncated:e.treeTruncated}}function ujt(e){return e.filter((t)=>t.path===".gitattributes"||t.path.endsWith("/.gitattributes")).map((t)=>t.path).sort()}async function AOe(e={}){let t=e.baseUrl??"https://api.github.com",n=process.env.GH_TOKEN?.trim()||process.env.GITHUB_TOKEN?.trim()||"";if(!n){let{stdout:r,exitCode:o,stderr:s}=await A(["gh","auth","token"],{sensitiveOutput:!0});if(o!==0||!r.trim())throw Error(`No GitHub token available: set GH_TOKEN, or run \`gh auth login\` (gh said: ${s.trim()||`exit ${o}`}). A sweep of the fleet cannot run on the anonymous rate limit.`);n=r.trim()}return{async get(r){let o=`${t}/${r.replace(/^\//,"")}`,s="";for(let i=0;i<3;i++){let a;try{a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"nemar-cli fleet annex-policy sweep"}})}catch(c){s=c instanceof Error?c.message:String(c),await new Promise((l)=>setTimeout(l,500*(i+1)));continue}if(a.status===403||a.status===429){let c=a.headers.get("x-ratelimit-remaining"),l=a.headers.get("x-ratelimit-reset");if(c==="0"){let d=l?new Date(Number(l)*1000).toISOString():"unknown";throw new el(`GitHub rate limit exhausted; it resets at ${d}. Re-run the sweep after that, or narrow it with --limit.`,a.status,!0)}}if(a.status>=500||a.status===429){s=`HTTP ${a.status}`,await new Promise((c)=>setTimeout(c,500*(i+1)));continue}return{status:a.status,body:await a.text()}}throw new el(`GET ${r} failed after 3 attempts: ${s}`,0)}}}function DOe(e,t){let n=JSON.parse(e);if(n.encoding!=="base64"||typeof n.content!=="string")throw Error(`${t}: expected a base64 blob, got encoding=${n.encoding}`);return Buffer.from(n.content.replace(/\n/g,""),"base64").toString("utf8")}async function c1(e,t,n={}){let r=n.branch??"main",o=`repos/${ajt}/${e}`,s=await t.get(`${o}/git/trees/${r}?recursive=1`);if(s.status!==200)throw new el(`Could not read ${e}'s ${r} tree: HTTP ${s.status}`,s.status);let i=JSON.parse(s.body),a=(i.tree??[]).filter((p)=>p.type==="blob"),c=a.map((p)=>({path:p.path,mode:p.mode,size:p.size})),l=new Map;for(let p of ujt(c)){let m=a.find((g)=>g.path===p)?.sha;if(!m)continue;let h=await t.get(`${o}/git/blobs/${m}`);if(h.status!==200)throw new el(`Could not read ${e}:${p} (blob ${m.slice(0,8)}): HTTP ${h.status}`,h.status);l.set(p,DOe(h.body,`${e}:${p}`))}let d=await t.get(`${o}/contents/config.log?ref=git-annex`),f=null;if(d.status===200)f=DOe(d.body,`${e}:git-annex:config.log`);else if(d.status!==404)throw new el(`Could not read ${e}'s git-annex config.log: HTTP ${d.status}`,d.status);return ljt({datasetId:e,entries:c,treeTruncated:Boolean(i.truncated),attributeContents:l,configLog:f})}async function djt(e){await A(["chmod","-R","u+w",e]),ijt(e,{recursive:!0,force:!0})}async function OOe(e,t,n){let r=await c1(e,t),o=Ux(r);if(o==="compliant")return{datasetId:e,before:r,action:"compliant"};if((o==="data"||o==="policy-and-data")&&!n.includeData)return{datasetId:e,before:r,action:"skipped-has-data",notes:[`${r.gitResidentData.length} file(s) NEMAR policy calls data are in git; that needs the S3 leg (nemar admin annex-normalize ${e})`]};let s=`${n.workRoot.replace(/\/$/,"")}/${e}`;try{let i=await OA(e,{workDir:n.workRoot,originUrl:n.originUrl});if(i.files.length>0&&!n.includeData)return{datasetId:e,before:r,action:"skipped-has-data",notes:[`the clone found ${i.files.length} data file(s) in git that the tree listing did not; re-run with --include-data or use nemar admin annex-normalize ${e}`]};let a=await TA(i,{push:n.push!==!1,credentials:n.credentials,maxBytes:n.maxBytes});if(!a.committed&&!a.pushed)return{datasetId:e,before:r,action:"compliant",committed:!1,pushed:!1,notes:[...a.notes,"the clone found nothing to change"]};let c;if(n.push!==!1)try{c=await fjt(e,t)}catch(d){if(d instanceof el&&d.fatal)throw d;return{datasetId:e,before:r,action:"unverified",committed:a.committed,pushed:a.pushed,notes:[...a.notes,`pushed, but the read-back could not be completed: ${d instanceof Error?d.message:String(d)}. Re-run the read-only report for this dataset to confirm.`]}}let l=[...a.notes];if(c?.remainingDeclined.length)l.push(`left alone: ${c.remainingDeclined.join(", ")} (a quoted pattern the strip will not split; fix by hand)`);return{datasetId:e,before:r,action:c===void 0||c.landed?"applied":"unverified",committed:a.committed,pushed:a.pushed,notes:l,after:c?.state}}catch(i){return{datasetId:e,before:r,action:"failed",error:i instanceof Error?i.message:String(i)}}finally{if(!n.keepClone)try{await djt(s)}catch{}}}async function fjt(e,t,n={}){let r=n.attempts??3,o=n.delayMs??3000,s=await c1(e,t);for(let i=1;i<r;i++){if(w3(s))break;await new Promise((a)=>setTimeout(a,o)),s=await c1(e,t)}return{landed:w3(s),state:s,remainingDeclined:s.attributeFiles.filter((i)=>i.declined.length>0).map((i)=>i.path)}}function w3(e){if(e.treeTruncated)return!1;return e.policyConfigured&&e.attributeFiles.every((t)=>t.rulesRemoved===0)}function COe(e){let t={compliant:[],policy:[],"policy-and-data":[],data:[]},n=[],r=[],o=[];for(let s of e)if(s.state){if(r.push(s.state),t[Ux(s.state)].push(s.datasetId),s.state.treeTruncated)o.push(s.datasetId)}else if(s.error)n.push({datasetId:s.datasetId,error:s.error});return{scanned:r.length,byLabel:t,truncated:o,failed:n,states:r}}async function TOe(e,t,n={}){let r=[];await pjt(e,n.concurrency??4,async(s)=>{try{let i=await c1(s,t);n.onResult?.({datasetId:s,state:i}),r.push({datasetId:s,state:i})}catch(i){if(i instanceof el&&i.fatal)throw new l1(i,COe(r));let a=i instanceof Error?i.message:String(i);n.onResult?.({datasetId:s,error:a}),r.push({datasetId:s,error:a})}});let o=new Map(e.map((s,i)=>[s,i]));return r.sort((s,i)=>(o.get(s.datasetId)??0)-(o.get(i.datasetId)??0)),COe(r)}function POe(e,t){let n=t.prefix??"on",r=t.exclude??new Set,o=e.map((s)=>s.dataset_id).filter((s)=>s.startsWith(n)).filter((s)=>t.force||!r.has(s)).sort();return t.limit!==void 0?o.slice(0,t.limit):o}async function pjt(e,t,n){let r=Array(e.length),o=0,s=Array.from({length:Math.max(1,Math.min(t,e.length))},()=>(async()=>{while(!0){let i=o++;if(i>=e.length)return;r[i]=await n(e[i],i)}})());return await Promise.all(s),r}var ajt="nemarDatasets",_3=256,el,l1;var u1=H(()=>{na();zt();ff();PA();el=class el extends Error{status;fatal;constructor(e,t,n=!1){super(e);this.status=t;this.fatal=n;this.name="GitHubReadError"}};l1=class l1 extends Error{cause;partial;constructor(e,t){super(e.message);this.cause=e;this.partial=t;this.name="FleetSweepAborted"}}});function XLt(e){return e.replace(/\/+$/,"")}function o2e(e,t=YLt){return`${XLt(t)}/dataset/${e}`}var r2e,OSn,YLt="https://nemar.org";var j3=H(()=>{r2e=["IsCitedBy","Cites","IsSupplementTo","IsSupplementedBy","IsContinuedBy","Continues","IsDescribedBy","Describes","HasMetadata","IsMetadataFor","HasVersion","IsVersionOf","IsNewVersionOf","IsPreviousVersionOf","IsPartOf","HasPart","IsReferencedBy","References","IsDocumentedBy","Documents","IsCompiledBy","Compiles","IsVariantFormOf","IsOriginalFormOf","IsIdenticalTo","IsCollectedBy","Collects","IsRequiredBy","Requires","IsObsoletedBy","Obsoletes","IsDerivedFrom","IsSourceOf","IsReviewedBy","Reviews","IsPublishedIn","HasTranslation","IsTranslationOf"],OSn=new Set(r2e)});var FPe=()=>{};function MPe(e){return e.replace(/^(doi:|https?:\/\/(dx\.)?doi\.org\/)/i,"").trim()}function jPe(e){let t=e.split(",").map((n)=>n.trim());if(t.length>=2)return{name:e,familyName:t[0],givenName:t.slice(1).join(", ")};return{name:e}}var LPe=H(()=>{j3();Yi();FPe()});function Qqt(e){let t=e,n=(t.match(/\(/g)??[]).length,r=(t.match(/\)/g)??[]).length;while(r>n&&t.endsWith(")"))t=t.slice(0,-1),r-=1;return t}function qPe(e){let t=e.trim().replace(/^(?:doi:|https?:\/\/(?:dx\.)?doi\.org\/)/i,""),n;do n=t,t=Qqt(t).replace(/[.,;:]+$/,"").trim();while(t!==n);return t.toLowerCase()}var UPe=()=>{};function r3t(e){if(t3t.has(e))return"absent";return e>=200&&e<300?"found":"failed"}function o3t(e){let t=e instanceof Error?`${e.name} ${e.message}`:String(e);return/AbortError|TimeoutError|timeout|fetch|network/i.test(t)}async function s3t(e,t,n){let{base:r,accept:o}=n3t[e],s=AbortSignal.timeout(e3t);try{let i=await fetch(`${r}/${encodeURIComponent(t)}`,{headers:{Accept:o,"User-Agent":Zqt},signal:n?AbortSignal.any([s,n]):s}),a=r3t(i.status);if(a==="absent")return{outcome:"absent"};if(a==="failed"){let c=`HTTP ${i.status}`;return console.warn(`[doi-registry] ${e} returned ${c} for ${t}`),{outcome:"failed",detail:c}}return{outcome:"found",body:await i.json()}}catch(i){if(n?.aborted)return{outcome:"failed",detail:"deadline reached"};let a=i instanceof Error?i.message:String(i);if(o3t(i))console.warn(`[doi-registry] ${e} lookup failed for ${t}: ${a}`);else console.error(`[doi-registry] Unexpected error querying ${e} for ${t}:`,i);return{outcome:"failed",detail:a}}}function wU(e,t,n,r){let o=qPe(t),s=`${e}:${o}`,i=n?.get(s);if(i)return i;if(r?.aborted)return Promise.resolve({outcome:"failed",detail:"deadline reached"});let a=s3t(e,o,r);if(n){if(n.set(s,a),r)a.then((c)=>{if(c.outcome==="failed"&&r.aborted&&n.get(s)===a)n.delete(s)})}return a}var Zqt="NEMAR/1.0 (https://nemar.org; mailto:nemar@ucsd.edu)",e3t=1e4,t3t,n3t;var BPe=H(()=>{UPe();t3t=new Set([400,404,410]),n3t={DataCite:{base:"https://api.datacite.org/application/vnd.datacite.datacite+json",accept:"application/vnd.datacite.datacite+json"},Crossref:{base:"https://api.crossref.org/works",accept:"application/json"}}});function c3t(e){let t=[],n=new Set,r=(o,s)=>{let i=MPe(o).trim();if(i3t.test(i)&&!n.has(i))n.add(i),t.push({doi:i,source:s})};if(Array.isArray(e.SourceDatasets))for(let o of e.SourceDatasets){if(!o||typeof o!=="object")continue;let s=o;if(typeof s.DOI==="string")r(s.DOI,"SourceDatasets");else if(typeof s.URL==="string"){let i=s.URL.match(/(?:doi\.org\/|doi:)(10\.\d{4,}\/.+)/);if(i)r(i[1],"SourceDatasets")}}if(Array.isArray(e.ReferencesAndLinks))for(let o of e.ReferencesAndLinks){if(typeof o!=="string"||!o)continue;let s=o.match(/(?:doi\.org\/|^)(10\.\d{4,}\/[^\s]+)/);if(s)r(s[1],"ReferencesAndLinks")}if(typeof e.HowToAcknowledge==="string"){let s=e.HowToAcknowledge.matchAll(/(?:doi\.org\/|(?<=\s|^))(10\.\d{4,}\/[^\s,)]+)/g);for(let i of s)r(i[1].replace(/[.;:]+$/,""),"HowToAcknowledge")}return t}async function l3t(e,t){let n=await wU("DataCite",e,t);if(n.outcome!=="found")return null;let r=n.body;return{doi:e,creators:Array.isArray(r?.creators)?r.creators.map((o)=>({...o})):[]}}async function u3t(e,t){let n=await wU("Crossref",e,t);if(n.outcome!=="found")return null;let o=n.body?.message?.author;if(!Array.isArray(o)||o.length===0)return null;let s=o.map((i)=>{let a=[];if(i.ORCID)a.push({nameIdentifier:i.ORCID,nameIdentifierScheme:"ORCID"});return{name:i.family&&i.given?`${i.family}, ${i.given}`:i.name||i.family||"",givenName:i.given,familyName:i.family,nameIdentifiers:a,affiliation:(i.affiliation||[]).filter((c)=>c.name)}}).filter((i)=>i.name.trim()!=="");return{doi:e,creators:s}}async function d3t(e,t){let n=await l3t(e,t),r=await u3t(e,t);if(!n)return r;if(!r)return n;for(let o of n.creators){if(o.nameIdentifiers?.some((c)=>c.nameIdentifierScheme==="ORCID")||!o.familyName)continue;let a=r.creators.find((c)=>c.familyName&&Mi(c.familyName)===Mi(o.familyName))?.nameIdentifiers?.find((c)=>c.nameIdentifierScheme==="ORCID");if(a)o.nameIdentifiers=[...o.nameIdentifiers??[],a]}return n}function Mi(e){return e.normalize("NFD").replace(/\p{Diacritic}/gu,"").replace(/\./g,"").toLowerCase().trim()}function HPe(e){if(!e)return"";return Mi(e).charAt(0)}function f3t(e,t){let n=[],r=new Set,o=new Set,s=t.map((i)=>({original:i,parsed:jPe(i)}));for(let i=0;i<e.length;i++){if(o.has(i))continue;let a=e[i],c=Mi(a.name);for(let l of s){if(r.has(l.original))continue;if(Mi(l.original)===c){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"exact"}),r.add(l.original),o.add(i);break}if(l.parsed.familyName&&l.parsed.givenName){if(Mi(`${l.parsed.givenName} ${l.parsed.familyName}`)===c){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"exact"}),r.add(l.original),o.add(i);break}}if(a.givenName&&a.familyName){let d=Mi(`${a.givenName} ${a.familyName}`);if(Mi(l.original)===d){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"exact"}),r.add(l.original),o.add(i);break}}}}for(let i=0;i<e.length;i++){if(o.has(i))continue;let a=e[i];if(!a.familyName)continue;let c=Mi(a.familyName),l=HPe(a.givenName);for(let d of s){if(r.has(d.original))continue;if(!d.parsed.familyName)continue;if(Mi(d.parsed.familyName)!==c)continue;let p=HPe(d.parsed.givenName);if(p&&l&&p===l){n.push({bidsAuthor:d.original,matchedCreator:a,confidence:"high"}),r.add(d.original),o.add(i);break}}}for(let i=0;i<e.length;i++){if(o.has(i))continue;let a=e[i];if(!a.familyName)continue;let c=Mi(a.familyName);for(let l of s){if(r.has(l.original))continue;if(!l.parsed.familyName)continue;if(Mi(l.parsed.familyName)===c){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"medium"}),r.add(l.original),o.add(i);break}}}return n}async function zPe(e,t,n,r){let o=c3t(e);if(n?.length)o.push(...n);if(o.length===0)return{discoveries:{},unresolvedDois:[],totalDoisQueried:0};let s=Array.isArray(e.Authors)?e.Authors.filter((f)=>typeof f==="string"):[];if(s.length===0)return{discoveries:{},unresolvedDois:[],totalDoisQueried:o.length};let i=new Set;if(t){for(let[f,p]of Object.entries(t))if(p.orcid)i.add(f)}let a=s.filter((f)=>!i.has(f));if(a.length===0)return{discoveries:{},unresolvedDois:[],totalDoisQueried:o.length};let c=[],l=new Map;for(let f=0;f<o.length;f+=GPe){let p=o.slice(f,f+GPe),m=await Promise.all(p.map((h)=>d3t(h.doi,r)));for(let h=0;h<p.length;h++)if(m[h])l.set(p[h].doi,m[h]?.creators??[]);else c.push(p[h].doi)}let d={};for(let[f,p]of l){let m=p.filter((g)=>g.nameIdentifiers?.some((y)=>y.nameIdentifierScheme==="ORCID"));if(m.length===0)continue;let h=f3t(m,a);for(let g of h){if(d[g.bidsAuthor])continue;let y=g.matchedCreator.nameIdentifiers.find((v)=>v.nameIdentifierScheme==="ORCID");if(!y)continue;let b=y.nameIdentifier.replace(/^https?:\/\/orcid\.org\//i,"").trim();if(!a3t.test(b))continue;let x=g.matchedCreator.affiliation?.filter((v)=>v.name).map((v)=>({name:v.name,...v.affiliationIdentifier&&{identifier:v.affiliationIdentifier},...v.affiliationIdentifierScheme&&{scheme:v.affiliationIdentifierScheme}}));d[g.bidsAuthor]={orcid:b,affiliations:x?.length?x:void 0,sourceDoi:f,confidence:g.confidence}}}return{discoveries:d,unresolvedDois:c,totalDoisQueried:o.length}}var i3t,a3t,GPe=5;var VPe=H(()=>{LPe();BPe();i3t=/^10\.\d{4,}\/[^\s]+$/,a3t=/^\d{4}-\d{4}-\d{4}-[\dX]{4}$/});var yO={};YU(yO,{program:()=>E8,createCommand:()=>S8,createOption:()=>k8,createArgument:()=>R8,Command:()=>$8,Option:()=>D8,Argument:()=>C8,Help:()=>A8,CommanderError:()=>O8,InvalidArgumentError:()=>T8,InvalidOptionArgumentError:()=>P8},{program:(jUt)=>E8=jUt,createCommand:(jUt)=>S8=jUt,createOption:(jUt)=>k8=jUt,createArgument:(jUt)=>R8=jUt,Command:(jUt)=>$8=jUt,Option:(jUt)=>D8=jUt,Argument:(jUt)=>C8=jUt,Help:(jUt)=>A8=jUt,CommanderError:(jUt)=>O8=jUt,InvalidArgumentError:(jUt)=>T8=jUt,InvalidOptionArgumentError:(jUt)=>P8=jUt});We();var{Argument:_8}=fv(),{Command:gO}=w8(),{CommanderError:iFe,InvalidArgumentError:x8}=Db(),{Help:aFe}=fO(),{Option:v8}=pO();var E8=new gO,S8=(e)=>new gO(e),k8=(e,t)=>new v8(e,t),R8=(e,t)=>new _8(e,t),$8=gO,D8=v8,C8=_8,A8=aFe,O8=iFe,T8=x8,P8=x8;var{program:qUt,createCommand:UUt,createArgument:BUt,createOption:HUt,CommanderError:GUt,InvalidArgumentError:Lo,InvalidOptionArgumentError:zUt,Command:ae,Argument:VUt,Option:qi,Help:WUt}=yO;var bO={dataset:["search","download","upload","validate","status","list"],admin:["users","approve","revoke","publish","pr-reviews","mail","doi","make-public","delete-dataset","notify","doctor"]};var wO=process.argv.includes("--help-all");if(process.argv.includes("--no-color"))u.level=0;var I8=process.argv.indexOf("--help-all");if(I8!==-1)process.argv[I8]="--help";var Cb=ae.prototype.addHelpText,N8=`
252
+ `)){let o=r.match(/^(\d+(?:\.\d+)?)s\s+(\S+)\s*(.*)$/);if(!o)continue;let[,s,i,a]=o,c=Number(s),l=a.trim(),d=t.get(i);if(!d||d.at<=c)t.set(i,{at:c,value:l})}let n=new Map;for(let[r,{value:o}]of t)if(o!=="")n.set(r,o);return n}function ljt(e){let t=[];for(let[i,a]of e.attributeContents){let c=df(a);if(c.stripped===0&&c.skipped.length===0)continue;t.push({path:i,rulesRemoved:c.stripped,declined:c.skipped})}t.sort((i,a)=>i.path.localeCompare(a.path));let r=(e.configLog?cjt(e.configLog):new Map).get("annex.largefiles")??null,o=[],s=[];for(let i of e.entries){if(i.mode!=="100644"&&i.mode!=="100755")continue;let a=i.size??Number.POSITIVE_INFINITY;if(!Ko(i.path,a))continue;if(a<=_3){s.push(i.path);continue}o.push({path:i.path,size:a})}return{datasetId:e.datasetId,attributeFiles:t,policyConfigured:r!==null&&$0e(r),configuredExpression:r,gitResidentData:o,pointerSuspects:s,treeTruncated:e.treeTruncated}}function ujt(e){return e.filter((t)=>t.path===".gitattributes"||t.path.endsWith("/.gitattributes")).map((t)=>t.path).sort()}async function AOe(e={}){let t=e.baseUrl??"https://api.github.com",n=process.env.GH_TOKEN?.trim()||process.env.GITHUB_TOKEN?.trim()||"";if(!n){let{stdout:r,exitCode:o,stderr:s}=await A(["gh","auth","token"],{sensitiveOutput:!0});if(o!==0||!r.trim())throw Error(`No GitHub token available: set GH_TOKEN, or run \`gh auth login\` (gh said: ${s.trim()||`exit ${o}`}). A sweep of the fleet cannot run on the anonymous rate limit.`);n=r.trim()}return{async get(r){let o=`${t}/${r.replace(/^\//,"")}`,s="";for(let i=0;i<3;i++){let a;try{a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"nemar-cli fleet annex-policy sweep"}})}catch(c){s=c instanceof Error?c.message:String(c),await new Promise((l)=>setTimeout(l,500*(i+1)));continue}if(a.status===403||a.status===429){let c=a.headers.get("x-ratelimit-remaining"),l=a.headers.get("x-ratelimit-reset");if(c==="0"){let d=l?new Date(Number(l)*1000).toISOString():"unknown";throw new el(`GitHub rate limit exhausted; it resets at ${d}. Re-run the sweep after that, or narrow it with --limit.`,a.status,!0)}}if(a.status>=500||a.status===429){s=`HTTP ${a.status}`,await new Promise((c)=>setTimeout(c,500*(i+1)));continue}return{status:a.status,body:await a.text()}}throw new el(`GET ${r} failed after 3 attempts: ${s}`,0)}}}function DOe(e,t){let n=JSON.parse(e);if(n.encoding!=="base64"||typeof n.content!=="string")throw Error(`${t}: expected a base64 blob, got encoding=${n.encoding}`);return Buffer.from(n.content.replace(/\n/g,""),"base64").toString("utf8")}async function c1(e,t,n={}){let r=n.branch??"main",o=`repos/${ajt}/${e}`,s=await t.get(`${o}/git/trees/${r}?recursive=1`);if(s.status!==200)throw new el(`Could not read ${e}'s ${r} tree: HTTP ${s.status}`,s.status);let i=JSON.parse(s.body),a=(i.tree??[]).filter((p)=>p.type==="blob"),c=a.map((p)=>({path:p.path,mode:p.mode,size:p.size})),l=new Map;for(let p of ujt(c)){let m=a.find((g)=>g.path===p)?.sha;if(!m)continue;let h=await t.get(`${o}/git/blobs/${m}`);if(h.status!==200)throw new el(`Could not read ${e}:${p} (blob ${m.slice(0,8)}): HTTP ${h.status}`,h.status);l.set(p,DOe(h.body,`${e}:${p}`))}let d=await t.get(`${o}/contents/config.log?ref=git-annex`),f=null;if(d.status===200)f=DOe(d.body,`${e}:git-annex:config.log`);else if(d.status!==404)throw new el(`Could not read ${e}'s git-annex config.log: HTTP ${d.status}`,d.status);return ljt({datasetId:e,entries:c,treeTruncated:Boolean(i.truncated),attributeContents:l,configLog:f})}async function djt(e){await A(["chmod","-R","u+w",e]),ijt(e,{recursive:!0,force:!0})}async function OOe(e,t,n){let r=await c1(e,t),o=Ux(r);if(o==="compliant")return{datasetId:e,before:r,action:"compliant"};if((o==="data"||o==="policy-and-data")&&!n.includeData)return{datasetId:e,before:r,action:"skipped-has-data",notes:[`${r.gitResidentData.length} file(s) NEMAR policy calls data are in git; that needs the S3 leg (nemar admin annex-normalize ${e})`]};let s=`${n.workRoot.replace(/\/$/,"")}/${e}`;try{let i=await OA(e,{workDir:n.workRoot,originUrl:n.originUrl});if(i.files.length>0&&!n.includeData)return{datasetId:e,before:r,action:"skipped-has-data",notes:[`the clone found ${i.files.length} data file(s) in git that the tree listing did not; re-run with --include-data or use nemar admin annex-normalize ${e}`]};let a=await TA(i,{push:n.push!==!1,credentials:n.credentials,maxBytes:n.maxBytes});if(!a.committed&&!a.pushed)return{datasetId:e,before:r,action:"compliant",committed:!1,pushed:!1,notes:[...a.notes,"the clone found nothing to change"]};let c;if(n.push!==!1)try{c=await fjt(e,t)}catch(d){if(d instanceof el&&d.fatal)throw d;return{datasetId:e,before:r,action:"unverified",committed:a.committed,pushed:a.pushed,notes:[...a.notes,`pushed, but the read-back could not be completed: ${d instanceof Error?d.message:String(d)}. Re-run the read-only report for this dataset to confirm.`]}}let l=[...a.notes];if(c?.remainingDeclined.length)l.push(`left alone: ${c.remainingDeclined.join(", ")} (a quoted pattern the strip will not split; fix by hand)`);return{datasetId:e,before:r,action:c===void 0||c.landed?"applied":"unverified",committed:a.committed,pushed:a.pushed,notes:l,after:c?.state}}catch(i){return{datasetId:e,before:r,action:"failed",error:i instanceof Error?i.message:String(i)}}finally{if(!n.keepClone)try{await djt(s)}catch{}}}async function fjt(e,t,n={}){let r=n.attempts??3,o=n.delayMs??3000,s=await c1(e,t);for(let i=1;i<r;i++){if(w3(s))break;await new Promise((a)=>setTimeout(a,o)),s=await c1(e,t)}return{landed:w3(s),state:s,remainingDeclined:s.attributeFiles.filter((i)=>i.declined.length>0).map((i)=>i.path)}}function w3(e){if(e.treeTruncated)return!1;return e.policyConfigured&&e.attributeFiles.every((t)=>t.rulesRemoved===0)}function COe(e){let t={compliant:[],policy:[],"policy-and-data":[],data:[]},n=[],r=[],o=[];for(let s of e)if(s.state){if(r.push(s.state),t[Ux(s.state)].push(s.datasetId),s.state.treeTruncated)o.push(s.datasetId)}else if(s.error)n.push({datasetId:s.datasetId,error:s.error});return{scanned:r.length,byLabel:t,truncated:o,failed:n,states:r}}async function TOe(e,t,n={}){let r=[];await pjt(e,n.concurrency??4,async(s)=>{try{let i=await c1(s,t);n.onResult?.({datasetId:s,state:i}),r.push({datasetId:s,state:i})}catch(i){if(i instanceof el&&i.fatal)throw new l1(i,COe(r));let a=i instanceof Error?i.message:String(i);n.onResult?.({datasetId:s,error:a}),r.push({datasetId:s,error:a})}});let o=new Map(e.map((s,i)=>[s,i]));return r.sort((s,i)=>(o.get(s.datasetId)??0)-(o.get(i.datasetId)??0)),COe(r)}function POe(e,t){let n=t.prefix??"on",r=t.exclude??new Set,o=e.map((s)=>s.dataset_id).filter((s)=>s.startsWith(n)).filter((s)=>t.force||!r.has(s)).sort();return t.limit!==void 0?o.slice(0,t.limit):o}async function pjt(e,t,n){let r=Array(e.length),o=0,s=Array.from({length:Math.max(1,Math.min(t,e.length))},()=>(async()=>{while(!0){let i=o++;if(i>=e.length)return;r[i]=await n(e[i],i)}})());return await Promise.all(s),r}var ajt="nemarDatasets",_3=256,el,l1;var u1=H(()=>{na();zt();ff();PA();el=class el extends Error{status;fatal;constructor(e,t,n=!1){super(e);this.status=t;this.fatal=n;this.name="GitHubReadError"}};l1=class l1 extends Error{cause;partial;constructor(e,t){super(e.message);this.cause=e;this.partial=t;this.name="FleetSweepAborted"}}});function XLt(e){return e.replace(/\/+$/,"")}function o2e(e,t=YLt){return`${XLt(t)}/dataset/${e}`}var r2e,OSn,YLt="https://nemar.org";var j3=H(()=>{r2e=["IsCitedBy","Cites","IsSupplementTo","IsSupplementedBy","IsContinuedBy","Continues","IsDescribedBy","Describes","HasMetadata","IsMetadataFor","HasVersion","IsVersionOf","IsNewVersionOf","IsPreviousVersionOf","IsPartOf","HasPart","IsReferencedBy","References","IsDocumentedBy","Documents","IsCompiledBy","Compiles","IsVariantFormOf","IsOriginalFormOf","IsIdenticalTo","IsCollectedBy","Collects","IsRequiredBy","Requires","IsObsoletedBy","Obsoletes","IsDerivedFrom","IsSourceOf","IsReviewedBy","Reviews","IsPublishedIn","HasTranslation","IsTranslationOf"],OSn=new Set(r2e)});var FPe=()=>{};function MPe(e){return e.replace(/^(doi:|https?:\/\/(dx\.)?doi\.org\/)/i,"").trim()}function jPe(e){let t=e.split(",").map((n)=>n.trim());if(t.length>=2)return{name:e,familyName:t[0],givenName:t.slice(1).join(", ")};return{name:e}}var LPe=H(()=>{j3();Yi();FPe()});function Qqt(e){let t=e,n=(t.match(/\(/g)??[]).length,r=(t.match(/\)/g)??[]).length;while(r>n&&t.endsWith(")"))t=t.slice(0,-1),r-=1;return t}function qPe(e){let t=e.trim().replace(/^(?:doi:|https?:\/\/(?:dx\.)?doi\.org\/)/i,""),n;do n=t,t=Qqt(t).replace(/[.,;:]+$/,"").trim();while(t!==n);return t.toLowerCase()}var UPe=()=>{};function r3t(e){if(t3t.has(e))return"absent";return e>=200&&e<300?"found":"failed"}function o3t(e){let t=e instanceof Error?`${e.name} ${e.message}`:String(e);return/AbortError|TimeoutError|timeout|fetch|network/i.test(t)}async function s3t(e,t,n){let{base:r,accept:o}=n3t[e],s=AbortSignal.timeout(e3t);try{let i=await fetch(`${r}/${encodeURIComponent(t)}`,{headers:{Accept:o,"User-Agent":Zqt},signal:n?AbortSignal.any([s,n]):s}),a=r3t(i.status);if(a==="absent")return{outcome:"absent"};if(a==="failed"){let c=`HTTP ${i.status}`;return console.warn(`[doi-registry] ${e} returned ${c} for ${t}`),{outcome:"failed",detail:c}}return{outcome:"found",body:await i.json()}}catch(i){if(n?.aborted)return{outcome:"failed",detail:"deadline reached"};let a=i instanceof Error?i.message:String(i);if(o3t(i))console.warn(`[doi-registry] ${e} lookup failed for ${t}: ${a}`);else console.error(`[doi-registry] Unexpected error querying ${e} for ${t}:`,i);return{outcome:"failed",detail:a}}}function wU(e,t,n,r){let o=qPe(t),s=`${e}:${o}`,i=n?.get(s);if(i)return i;if(r?.aborted)return Promise.resolve({outcome:"failed",detail:"deadline reached"});let a=s3t(e,o,r);if(n){if(n.set(s,a),r)a.then((c)=>{if(c.outcome==="failed"&&r.aborted&&n.get(s)===a)n.delete(s)})}return a}var Zqt="NEMAR/1.0 (https://nemar.org; mailto:nemar@ucsd.edu)",e3t=1e4,t3t,n3t;var BPe=H(()=>{UPe();t3t=new Set([400,404,410]),n3t={DataCite:{base:"https://api.datacite.org/application/vnd.datacite.datacite+json",accept:"application/vnd.datacite.datacite+json"},Crossref:{base:"https://api.crossref.org/works",accept:"application/json"}}});function c3t(e){let t=[],n=new Set,r=(o,s)=>{let i=MPe(o).trim();if(i3t.test(i)&&!n.has(i))n.add(i),t.push({doi:i,source:s})};if(Array.isArray(e.SourceDatasets))for(let o of e.SourceDatasets){if(!o||typeof o!=="object")continue;let s=o;if(typeof s.DOI==="string")r(s.DOI,"SourceDatasets");else if(typeof s.URL==="string"){let i=s.URL.match(/(?:doi\.org\/|doi:)(10\.\d{4,}\/.+)/);if(i)r(i[1],"SourceDatasets")}}if(Array.isArray(e.ReferencesAndLinks))for(let o of e.ReferencesAndLinks){if(typeof o!=="string"||!o)continue;let s=o.match(/(?:doi\.org\/|^)(10\.\d{4,}\/[^\s]+)/);if(s)r(s[1],"ReferencesAndLinks")}if(typeof e.HowToAcknowledge==="string"){let s=e.HowToAcknowledge.matchAll(/(?:doi\.org\/|(?<=\s|^))(10\.\d{4,}\/[^\s,)]+)/g);for(let i of s)r(i[1].replace(/[.;:]+$/,""),"HowToAcknowledge")}return t}async function l3t(e,t){let n=await wU("DataCite",e,t);if(n.outcome!=="found")return null;let r=n.body;return{doi:e,creators:Array.isArray(r?.creators)?r.creators.map((o)=>({...o})):[]}}async function u3t(e,t){let n=await wU("Crossref",e,t);if(n.outcome!=="found")return null;let o=n.body?.message?.author;if(!Array.isArray(o)||o.length===0)return null;let s=o.map((i)=>{let a=[];if(i.ORCID)a.push({nameIdentifier:i.ORCID,nameIdentifierScheme:"ORCID"});return{name:i.family&&i.given?`${i.family}, ${i.given}`:i.name||i.family||"",givenName:i.given,familyName:i.family,nameIdentifiers:a,affiliation:(i.affiliation||[]).filter((c)=>c.name)}}).filter((i)=>i.name.trim()!=="");return{doi:e,creators:s}}async function d3t(e,t){let n=await l3t(e,t),r=await u3t(e,t);if(!n)return r;if(!r)return n;for(let o of n.creators){if(o.nameIdentifiers?.some((c)=>c.nameIdentifierScheme==="ORCID")||!o.familyName)continue;let a=r.creators.find((c)=>c.familyName&&Mi(c.familyName)===Mi(o.familyName))?.nameIdentifiers?.find((c)=>c.nameIdentifierScheme==="ORCID");if(a)o.nameIdentifiers=[...o.nameIdentifiers??[],a]}return n}function Mi(e){return e.normalize("NFD").replace(/\p{Diacritic}/gu,"").replace(/\./g,"").toLowerCase().trim()}function HPe(e){if(!e)return"";return Mi(e).charAt(0)}function f3t(e,t){let n=[],r=new Set,o=new Set,s=t.map((i)=>({original:i,parsed:jPe(i)}));for(let i=0;i<e.length;i++){if(o.has(i))continue;let a=e[i],c=Mi(a.name);for(let l of s){if(r.has(l.original))continue;if(Mi(l.original)===c){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"exact"}),r.add(l.original),o.add(i);break}if(l.parsed.familyName&&l.parsed.givenName){if(Mi(`${l.parsed.givenName} ${l.parsed.familyName}`)===c){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"exact"}),r.add(l.original),o.add(i);break}}if(a.givenName&&a.familyName){let d=Mi(`${a.givenName} ${a.familyName}`);if(Mi(l.original)===d){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"exact"}),r.add(l.original),o.add(i);break}}}}for(let i=0;i<e.length;i++){if(o.has(i))continue;let a=e[i];if(!a.familyName)continue;let c=Mi(a.familyName),l=HPe(a.givenName);for(let d of s){if(r.has(d.original))continue;if(!d.parsed.familyName)continue;if(Mi(d.parsed.familyName)!==c)continue;let p=HPe(d.parsed.givenName);if(p&&l&&p===l){n.push({bidsAuthor:d.original,matchedCreator:a,confidence:"high"}),r.add(d.original),o.add(i);break}}}for(let i=0;i<e.length;i++){if(o.has(i))continue;let a=e[i];if(!a.familyName)continue;let c=Mi(a.familyName);for(let l of s){if(r.has(l.original))continue;if(!l.parsed.familyName)continue;if(Mi(l.parsed.familyName)===c){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"medium"}),r.add(l.original),o.add(i);break}}}return n}async function zPe(e,t,n,r){let o=c3t(e);if(n?.length)o.push(...n);if(o.length===0)return{discoveries:{},unresolvedDois:[],totalDoisQueried:0};let s=Array.isArray(e.Authors)?e.Authors.filter((f)=>typeof f==="string"):[];if(s.length===0)return{discoveries:{},unresolvedDois:[],totalDoisQueried:o.length};let i=new Set;if(t){for(let[f,p]of Object.entries(t))if(p.orcid)i.add(f)}let a=s.filter((f)=>!i.has(f));if(a.length===0)return{discoveries:{},unresolvedDois:[],totalDoisQueried:o.length};let c=[],l=new Map;for(let f=0;f<o.length;f+=GPe){let p=o.slice(f,f+GPe),m=await Promise.all(p.map((h)=>d3t(h.doi,r)));for(let h=0;h<p.length;h++)if(m[h])l.set(p[h].doi,m[h]?.creators??[]);else c.push(p[h].doi)}let d={};for(let[f,p]of l){let m=p.filter((g)=>g.nameIdentifiers?.some((y)=>y.nameIdentifierScheme==="ORCID"));if(m.length===0)continue;let h=f3t(m,a);for(let g of h){if(d[g.bidsAuthor])continue;let y=g.matchedCreator.nameIdentifiers.find((v)=>v.nameIdentifierScheme==="ORCID");if(!y)continue;let b=y.nameIdentifier.replace(/^https?:\/\/orcid\.org\//i,"").trim();if(!a3t.test(b))continue;let x=g.matchedCreator.affiliation?.filter((v)=>v.name).map((v)=>({name:v.name,...v.affiliationIdentifier&&{identifier:v.affiliationIdentifier},...v.affiliationIdentifierScheme&&{scheme:v.affiliationIdentifierScheme}}));d[g.bidsAuthor]={orcid:b,affiliations:x?.length?x:void 0,sourceDoi:f,confidence:g.confidence}}}return{discoveries:d,unresolvedDois:c,totalDoisQueried:o.length}}var i3t,a3t,GPe=5;var VPe=H(()=>{LPe();BPe();i3t=/^10\.\d{4,}\/[^\s]+$/,a3t=/^\d{4}-\d{4}-\d{4}-[\dX]{4}$/});var yO={};YU(yO,{program:()=>E8,createCommand:()=>S8,createOption:()=>k8,createArgument:()=>R8,Command:()=>$8,Option:()=>D8,Argument:()=>C8,Help:()=>A8,CommanderError:()=>O8,InvalidArgumentError:()=>T8,InvalidOptionArgumentError:()=>P8},{program:(jUt)=>E8=jUt,createCommand:(jUt)=>S8=jUt,createOption:(jUt)=>k8=jUt,createArgument:(jUt)=>R8=jUt,Command:(jUt)=>$8=jUt,Option:(jUt)=>D8=jUt,Argument:(jUt)=>C8=jUt,Help:(jUt)=>A8=jUt,CommanderError:(jUt)=>O8=jUt,InvalidArgumentError:(jUt)=>T8=jUt,InvalidOptionArgumentError:(jUt)=>P8=jUt});We();var{Argument:_8}=fv(),{Command:gO}=w8(),{CommanderError:iFe,InvalidArgumentError:x8}=Db(),{Help:aFe}=fO(),{Option:v8}=pO();var E8=new gO,S8=(e)=>new gO(e),k8=(e,t)=>new v8(e,t),R8=(e,t)=>new _8(e,t),$8=gO,D8=v8,C8=_8,A8=aFe,O8=iFe,T8=x8,P8=x8;var{program:qUt,createCommand:UUt,createArgument:BUt,createOption:HUt,CommanderError:GUt,InvalidArgumentError:Lo,InvalidOptionArgumentError:zUt,Command:ae,Argument:VUt,Option:qi,Help:WUt}=yO;var bO={dataset:["search","download","upload","validate","status","list"],admin:["users","approve","revoke","repo","pr-reviews","mail","doi","make-public","delete-dataset","notify","doctor"]};var wO=process.argv.includes("--help-all");if(process.argv.includes("--no-color"))u.level=0;var I8=process.argv.indexOf("--help-all");if(I8!==-1)process.argv[I8]="--help";var Cb=ae.prototype.addHelpText,N8=`
253
253
  Run with --help-all for examples and detailed descriptions.
254
254
  `,pv=new WeakSet;ae.prototype.addHelpText=function(e,t){if(e==="after"||e==="afterAll"){if(wO)return Cb.call(this,e,t);if(!pv.has(this))return pv.add(this),Cb.call(this,e,N8);return this}return Cb.call(this,e,t)};function cFe(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(" ")}function lr(e){let t=[];for(let n=e;n;n=n.parent)t.unshift(n.name());return t.join(" ")}var lFe={formatHelp(e,t){let n=t.helpWidth??80,r=2,o=2,s=40,i=Math.max(8,n-2-2-40),a=(I)=>Math.min(i,I.reduce((V,T)=>Math.max(V,T.length),0));function c(I,V,T,L){if(!T)return V;let q=L+2;if(I.length>L){let P=t.wrap(T,n-2-4,0);return`${V}
255
255
  ${P.replace(/^/gm," ")}`}let G=" ".repeat(Math.max(0,q-I.length)),B=`${I}${G}${T}`,M=t.wrap(B,n-2,q);return V+M.slice(I.length)}function l(I){return I.join(`
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.34-PR2199.cbcc72e",
4
+ "version": "0.10.34-PR2199.eb4ccf1",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",