nemar-cli 0.10.27-dev.4110 → 0.10.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/git-annex-remote-nemar.js +3 -3
- package/dist/index.js +69 -69
- package/package.json +1 -1
|
@@ -23,18 +23,18 @@ ${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 hb(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 mb(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([hb(n.stdout,l),hb(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 gb=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 _b(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 vb(e){try{let{exitCode:t,stdout:r,timedOut:n}=await mb(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(yb);return Promise.all(e.map(async([t,r])=>{let{available:n,version:s,timedOut:o}=await vb(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:s,timedOut:o,installInstruction:_b(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)=>yb[i]).filter(Boolean),n=await Promise.all(r.map(async(i)=>{let a=await vb(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:_b(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 yb,ZF,rV=4000;var $b=F(()=>{gb();yb={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 wb;var Eb=F(()=>{wb={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.27
|
|
26
|
+
`))}var yb,ZF,rV=4000;var $b=F(()=>{gb();yb={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 wb;var Eb=F(()=>{wb={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.27",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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Eb();ac=wb.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){Tb=e,pr(`Step: ${e}`)}function hB(){xb=!0}function mB(){return xb}function gB(){if(Rb)return;Bl=!0}function yB(){Bl=!1,Rb=!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 Ob(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(kb,Ob)}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(kb,Ob)}function vV(e){return Wl(e)}function bb(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:bb(e.requestBody),responseBody:bb(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 Ab(e){if(Sb.has(e))return{flag:e};for(let t of Sb){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 wV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Ab(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 bV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Ab(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 bV(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(wV(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: ${Tb??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
|
|
29
29
|
`)}
|
|
30
30
|
`}function RV(e,t){let r;try{r=iV(e).filter((s)=>s.startsWith("nemar-")&&s.endsWith(".log"))}catch(s){if(s.code!=="ENOENT")pr(`could not list ${e} for log rotation: ${dr(s)}`);return}r.sort();let n=r.length-t;for(let s=0;s<n;s++)try{aV(Kl(e,r[s]))}catch(o){if(o.code!=="ENOENT")pr(`could not remove old log ${r[s]}: ${dr(o)}`)}}function $B(){return zo}function EB(e,t){if(!Ds)return null;let r=Kl(Xl(),"logs");try{oV(r,{recursive:!0})}catch(i){return zo=dr(i),pr(`could not create log directory ${r}: ${zo}`),null}let s=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${SV(e)}.log`,o=Kl(r,s);try{cV(o,xV(e,t),"utf8")}catch(i){return zo=dr(i),pr(`could not write log file ${o}: ${zo}`),null}return RV(r,uV),o}var uV=10,lV=2048,Ds=!1,xb=!1,Bl=!1,Rb=!1,Tb,cc,uc,dV,pV,kb,hV=32,mV,gV,yV,_V,Sb,zo;var Yl=F(()=>{Cl();fc();$b();Gl();uc=[];dV=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);pV=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code|dispatch[_-]?token)$/i,kb=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;mV=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,gV=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,yV=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,_V=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;Sb=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as TV,copyFileSync as kV,existsSync as Jl,mkdirSync as OV,statSync as AV}from"fs";import{homedir as pc}from"os";import{join as Ms}from"path";function NV(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 Xl(){return process.env.NEMAR_CONFIG_DIR||Ms(pc(),".config","nemar")}function CV(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Ms(e,"config.json");if(Jl(t))return;let r=[];if(process.platform==="darwin")r.push(Ms(pc(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let n=process.env.APPDATA||Ms(pc(),"AppData","Roaming");r.push(Ms(n,"nemar-nodejs","config.json"))}r.push(Ms(pc(),".config","nemar-nodejs","config.json"));for(let n of r)if(Jl(n))try{OV(e,{recursive:!0}),kV(n,t),console.error(`[nemar] Config migrated from ${n} to ${t}
|
|
31
31
|
[nemar] You can safely remove the old file.`);return}catch(s){console.error(`[nemar] Failed to migrate config from ${n}:`,s,`
|
|
32
|
-
[nemar] You can manually copy ${n} to ${t}`)}}function St(){let e=Xl();if(Go&&Pb===e)return Go;if(CV(e),Go=new Ka({projectName:"nemar",configFileMode:Ql,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}),Pb=e,!Nb.has(e))Nb.add(e),jV(Go.path),DV(),MV();return Go}function jV(e){if(process.platform==="win32")return;if(!Jl(e))return;try{if((AV(e).mode&511)!==Ql)TV(e,Ql)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function DV(){let e=St(),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 s=n||"default",o={};for(let i of qV){let a=e.get(i);if(a!==void 0)o[i]=a}e.store={activeAccount:s,accounts:{[s]:o}}}catch(s){console.error("Config migration failed (legacy config preserved):",s)}}function MV(){let e=St(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,i]of Object.entries(r)){let a=i?.apiUrl;if(!a)continue;if(PV.has(NV(a)))r[o]={...i,apiUrl:Ls},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${a} -> ${Ls}`),n=!0}let s=t.apiUrl;if(r&&Object.keys(r).length>0&&s!==void 0){let{apiUrl:o,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${s})`),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 Ko(){return St().get("activeAccount")}function mn(){return St().get("accounts")||{}}function hn(){let e={apiUrl:Ls},t=Ko();if(!t)return e;return mn()[t]||e}function PB(e,t){let r=St(),n=r.get("activeAccount")||"default",s=r.get("accounts")||{};if(!s[n])s[n]={apiUrl:Ls};s[n][e]=t,r.store={...r.store,accounts:s,activeAccount:n}}function NB(e){let t=Ko();if(!t)return;let r=mn();if(r[t])delete r[t][e],St().set("accounts",r)}function IB(){let e=St(),t=Ko();if(!t){e.clear();return}let r=mn();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 CB(){St().clear()}function jB(){return!!hn().apiKey}function qB(){return St().path}function DB(){let e=mn(),t=Ko();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 MB(e){return e.username?.trim()||e.email}function LV(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(mn()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){pr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function LB(e,t){let r=St(),n=mn(),s;if(n[e])s=e;else if(t.email)s=LV(t.email);let o=s?n[s]:void 0,i={...o??{apiUrl:Ls},...t};if(s&&s!==e)delete n[s];return n[e]=i,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function UB(e){let t=e.trim();if(!t)return"unchanged";let r=St(),n=Ko();if(!n||n===t)return"unchanged";let s=mn(),o=s[n];if(!o)return"unchanged";if(s[t])return"key_taken";return delete s[n],s[t]={...o,username:t},r.store={...r.store,accounts:s,activeAccount:t},"renamed"}function FB(e){let t=St(),r=mn();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,s]of Object.entries(r))if(s.githubUsername===e)return t.store={...t.store,activeAccount:n},s;return null}var Ls="https://nemar-api-dev.sccn-org.workers.dev",Ql=384,PV,IV,AB,Go=null,Pb=null,Nb,qV;var fc=F(()=>{Fw();jn();nc();Yl();PV=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);IV=ne({field:v(),blocks:Ze(v()).optional(),set_on:Ze(v()).optional()}).passthrough(),AB=ne({apiKey:v().optional(),apiUrl:v().url().default(Ls),username:v().optional(),email:v().email().optional(),githubUsername:v().optional(),sandboxCompleted:Ue().optional(),sandboxDatasetId:v().optional(),dismissedNoticeIds:Ze(fe()).optional(),serviceAccess:Ue().optional(),profileGaps:Ze(IV).optional(),orcidVerified:Ue().optional(),role:v().optional(),accountKind:qn.optional(),pendingEmailChange:v().email().optional()});Nb=new Set;qV=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});var UV,FV,KB,VV,HB,zV,Ib,BB,WB=8,YB=100,Cb,XB,GV,JB;var jb=F(()=>{jn();nc();UV=["given_name","family_name","affiliation","city","country"],FV=["username","github_username","email","orcid"],KB=[...UV,...FV],VV={given_name:v().max(200).optional(),family_name:v().max(200).optional(),affiliation:v().max(500).optional(),city:v().max(200).optional(),country:v().max(200).optional(),username:v().max(100).optional(),github_username:v().max(100).optional(),email:v().max(320).optional(),orcid:v().max(40).optional()},HB=ne(VV),zV=Ve(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),Ib=zV.options,BB=["exact","name","prefix","substring","fuzzy"],Cb=ne({id:fe().int(),username:v().nullable(),email:v(),github_username:v().nullable(),status:v(),role:v().nullable(),account_kind:qn.optional(),email_verified:fe().int().nullable().optional(),orcid:v().nullable().optional(),orcid_verified:fe().int().nullable().optional(),given_name:v().nullable().optional(),family_name:v().nullable().optional(),affiliation:v().nullable().optional(),city:v().nullable().optional(),country:v().nullable().optional(),description:v().nullable().optional(),signup_source:v().nullable().optional(),created_at:v(),updated_at:v().nullable().optional(),approved_at:v().nullable().optional(),revoked_at:v().nullable().optional(),deleted_at:v().nullable().optional(),service_access:fe().int().nullable().optional(),service_access_granted_at:v().nullable().optional(),service_access_granted_by:fe().int().nullable().optional(),upload_access_requested_at:v().nullable().optional(),upload_access_notified_at:v().nullable().optional(),identity_conflict:fe().int().nullable().optional(),username_auto_assigned:fe().int().nullable().optional(),sandbox_completed:fe().int().nullable().optional(),sandbox_completed_at:v().nullable().optional(),sandbox_dataset_id:v().nullable().optional(),aws_iam_username:v().nullable().optional(),dataset_count:fe().int().optional(),active_tokens:fe().int().optional(),linked_identities:Ze(v()).optional()}).passthrough(),XB=ne({user:Cb}).passthrough(),GV=ne({from:v().nullable(),to:v().nullable()}),JB=ne({message:v(),changed:wF(v(),GV),notes:Ze(v()).optional(),old_address_notified:Ue().optional(),user:Cb}).passthrough()});var e6=120,t6=64,r6="unnamed machine",KV=25,qb,n6,Us,Db,s6,o6,i6,HV,BV,a6,Zl,c6,u6,l6,d6,f6;var Mb=F(()=>{jn();qb=Ve(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),n6={authorization_pending:"Waiting for you to authorize this machine in the browser.",slow_down:"Polling too quickly; the CLI will slow down automatically.",expired_token:"The code expired. Run `nemar auth login` again for a new one.",access_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",invalid_grant:"That code is no longer valid. Run `nemar auth login` again for a new one."},Us=Ve(["device_code_unknown","device_code_expired","device_code_used","device_code_denied","account_pending","account_revoked","identity_conflict","service_account","person_account","too_many_keys","key_not_found"]),Db=Us.options,s6={device_code_unknown:"That code was not found. Check the code shown in your terminal, or run `nemar auth login` again for a new one.",device_code_expired:"The code expired. Run `nemar auth login` again for a new one.",device_code_used:"That code has already been used. Run `nemar auth login` again for a new one.",device_code_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",account_pending:"Verify your email address first. Check your inbox for the NEMAR verification code, then authorize again.",account_revoked:"Your NEMAR account access has been revoked. Contact the NEMAR team if you think this is a mistake.",identity_conflict:"This account shares an identifier with another NEMAR account and cannot sign in until that is resolved. Fix it in Settings on nemar.org or contact the NEMAR team.",service_account:"This is a service or test account, and it cannot sign in this way. Ask an owner to create a key for it with `nemar admin keys create`.",person_account:"This account belongs to a person. A person creates their own keys with `nemar auth login` or in Settings on nemar.org.",too_many_keys:`This account already has ${KV} active keys. Revoke one in Settings on nemar.org or with \`nemar auth keys\`, then try again.`,key_not_found:"That key was not found on this account, or it is already revoked. Run `nemar auth keys` to see the active ones."},o6=ne({error:Us,message:v()}).passthrough(),i6=ne({device_code:v(),user_code:v(),verification_uri:v(),verification_uri_complete:v(),expires_in:fe().int(),interval:fe().int()}).passthrough(),HV=Yw("error",[ne({error:In("authorization_pending"),message:v()}).passthrough(),ne({error:In("slow_down"),message:v()}).passthrough()]),BV=Yw("error",[ne({error:In("expired_token"),reason:Us,message:v()}).passthrough(),ne({error:In("access_denied"),reason:Us,message:v()}).passthrough(),ne({error:In("invalid_grant"),reason:Us,message:v()}).passthrough()]),a6=EF([HV,BV]),Zl=ne({id:fe().int(),name:v().nullable(),prefix:v(),created_at:v(),last_used_at:v().nullable(),current:Ue()}).passthrough(),c6=ne({api_key:v(),key:Zl,user:ne({username:v().nullable(),email:v(),github_username:v().nullable(),role:v(),sandbox_completed:Ue(),sandbox_dataset_id:v().nullable()}).passthrough()}).passthrough(),u6=ne({user_code:v(),machine_name:v(),requested_at:v(),expires_in:fe().int(),account:ne({username:v().nullable(),email_masked:v()}).passthrough(),refusal:ne({code:Us,message:v()}).passthrough().nullable()}).passthrough(),l6=ne({ok:In(!0),machine_name:v()}).passthrough(),d6=ne({keys:Ze(Zl)}).passthrough(),f6=ne({api_key:v(),key:Zl}).passthrough()});var WV,Lb,Ho="https://nemar.org/settings",m6,YV,XV,JV,g6,y6;var Ub=F(()=>{jn();WV=Ve(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),Lb=WV.options,m6={orcid_in_use:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${Ho}).`,orcid_already_linked:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${Ho}).`,orcid_linked_other:`That ORCID iD is linked to a different NEMAR account. Unlink it there first (Settings, ${Ho}), then link it here.`,email_in_use:`That email address already belongs to a NEMAR account. Sign in to that account instead, or change its address first (Settings, ${Ho}).`,github_in_use:`That GitHub account is already linked to a NEMAR account. Sign in to that account instead, or change its GitHub username first (Settings, ${Ho}).`,identity_conflict_remains:"The collision that flagged this account is still there. Resolve it on the other account first (change its email or GitHub username, or unlink its ORCID iD), or delete that account, then clear the flag."},YV=Ve(["orcid","email","github"]),XV=ne({id:fe().int(),username:v().nullable(),email:v(),created_at:v(),has_oauth_identity:Ue(),dataset_count:fe().int(),identity_conflict:fe().int(),canonical:Ue()}).passthrough(),JV=ne({kind:YV,value:v(),canonical_user_id:fe().int(),accounts:Ze(XV)}).passthrough(),g6=ne({groups:Ze(JV),group_count:fe().int(),flagged_count:fe().int()}).passthrough(),y6=ne({ok:In(!0),id:fe().int(),cleared:Ue()}).passthrough()});function b6(e){return typeof e==="string"&&ZV.includes(e)}var QV,$6,E6,w6,ZV,e9="ci_check_unavailable",Fb,Vb,zb,S6="X-Approval-Dispatch-Token",x6;var Gb=F(()=>{jn();QV=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/,$6=v().regex(QV,"ORCID must be in format 0000-0000-0000-000X"),E6=Ve(["found","no_public_name","lookup_failed"]),w6=Ve(["bids_validation_failed","bids_validation_pending","bids_validation_in_progress","prescreen_failed","min_requirements_failed","owner_name_missing","identifier_screen_findings"]),ZV=["bids_validation_pending","bids_validation_in_progress"];Fb=[e9],Vb=["identifier_screen_pending","identifier_screen_not_clear","identifier_screen_not_applicable"],zb=["publication_review_not_clear","request_blocked","request_changed","request_mismatch","dispatch_superseded","dispatch_expired","decision_with_dispatch_token","approval_in_flight","deny_after_publishing","invalid_dataset_id","approval_closed_during_run"],x6=Ve(["filled","would_fill","no_public_name","lookup_failed","write_failed"])});function Hb(e){if(Kb)return;Kb=!0;let t=Nt.yellow("\u2500".repeat(60)),r=Nt.yellow.bold("[MAINTENANCE]"),n=Nt.dim(`mode: ${e.mode}`),s=e.eta?`
|
|
32
|
+
[nemar] You can manually copy ${n} to ${t}`)}}function St(){let e=Xl();if(Go&&Pb===e)return Go;if(CV(e),Go=new Ka({projectName:"nemar",configFileMode:Ql,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}),Pb=e,!Nb.has(e))Nb.add(e),jV(Go.path),DV(),MV();return Go}function jV(e){if(process.platform==="win32")return;if(!Jl(e))return;try{if((AV(e).mode&511)!==Ql)TV(e,Ql)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function DV(){let e=St(),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 s=n||"default",o={};for(let i of qV){let a=e.get(i);if(a!==void 0)o[i]=a}e.store={activeAccount:s,accounts:{[s]:o}}}catch(s){console.error("Config migration failed (legacy config preserved):",s)}}function MV(){let e=St(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,i]of Object.entries(r)){let a=i?.apiUrl;if(!a)continue;if(PV.has(NV(a)))r[o]={...i,apiUrl:Ls},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${a} -> ${Ls}`),n=!0}let s=t.apiUrl;if(r&&Object.keys(r).length>0&&s!==void 0){let{apiUrl:o,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${s})`),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 Ko(){return St().get("activeAccount")}function mn(){return St().get("accounts")||{}}function hn(){let e={apiUrl:Ls},t=Ko();if(!t)return e;return mn()[t]||e}function PB(e,t){let r=St(),n=r.get("activeAccount")||"default",s=r.get("accounts")||{};if(!s[n])s[n]={apiUrl:Ls};s[n][e]=t,r.store={...r.store,accounts:s,activeAccount:n}}function NB(e){let t=Ko();if(!t)return;let r=mn();if(r[t])delete r[t][e],St().set("accounts",r)}function IB(){let e=St(),t=Ko();if(!t){e.clear();return}let r=mn();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 CB(){St().clear()}function jB(){return!!hn().apiKey}function qB(){return St().path}function DB(){let e=mn(),t=Ko();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 MB(e){return e.username?.trim()||e.email}function LV(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(mn()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){pr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function LB(e,t){let r=St(),n=mn(),s;if(n[e])s=e;else if(t.email)s=LV(t.email);let o=s?n[s]:void 0,i={...o??{apiUrl:Ls},...t};if(s&&s!==e)delete n[s];return n[e]=i,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function UB(e){let t=e.trim();if(!t)return"unchanged";let r=St(),n=Ko();if(!n||n===t)return"unchanged";let s=mn(),o=s[n];if(!o)return"unchanged";if(s[t])return"key_taken";return delete s[n],s[t]={...o,username:t},r.store={...r.store,accounts:s,activeAccount:t},"renamed"}function FB(e){let t=St(),r=mn();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,s]of Object.entries(r))if(s.githubUsername===e)return t.store={...t.store,activeAccount:n},s;return null}var Ls="https://api.nemar.org",Ql=384,PV,IV,AB,Go=null,Pb=null,Nb,qV;var fc=F(()=>{Fw();jn();nc();Yl();PV=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);IV=ne({field:v(),blocks:Ze(v()).optional(),set_on:Ze(v()).optional()}).passthrough(),AB=ne({apiKey:v().optional(),apiUrl:v().url().default(Ls),username:v().optional(),email:v().email().optional(),githubUsername:v().optional(),sandboxCompleted:Ue().optional(),sandboxDatasetId:v().optional(),dismissedNoticeIds:Ze(fe()).optional(),serviceAccess:Ue().optional(),profileGaps:Ze(IV).optional(),orcidVerified:Ue().optional(),role:v().optional(),accountKind:qn.optional(),pendingEmailChange:v().email().optional()});Nb=new Set;qV=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});var UV,FV,KB,VV,HB,zV,Ib,BB,WB=8,YB=100,Cb,XB,GV,JB;var jb=F(()=>{jn();nc();UV=["given_name","family_name","affiliation","city","country"],FV=["username","github_username","email","orcid"],KB=[...UV,...FV],VV={given_name:v().max(200).optional(),family_name:v().max(200).optional(),affiliation:v().max(500).optional(),city:v().max(200).optional(),country:v().max(200).optional(),username:v().max(100).optional(),github_username:v().max(100).optional(),email:v().max(320).optional(),orcid:v().max(40).optional()},HB=ne(VV),zV=Ve(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),Ib=zV.options,BB=["exact","name","prefix","substring","fuzzy"],Cb=ne({id:fe().int(),username:v().nullable(),email:v(),github_username:v().nullable(),status:v(),role:v().nullable(),account_kind:qn.optional(),email_verified:fe().int().nullable().optional(),orcid:v().nullable().optional(),orcid_verified:fe().int().nullable().optional(),given_name:v().nullable().optional(),family_name:v().nullable().optional(),affiliation:v().nullable().optional(),city:v().nullable().optional(),country:v().nullable().optional(),description:v().nullable().optional(),signup_source:v().nullable().optional(),created_at:v(),updated_at:v().nullable().optional(),approved_at:v().nullable().optional(),revoked_at:v().nullable().optional(),deleted_at:v().nullable().optional(),service_access:fe().int().nullable().optional(),service_access_granted_at:v().nullable().optional(),service_access_granted_by:fe().int().nullable().optional(),upload_access_requested_at:v().nullable().optional(),upload_access_notified_at:v().nullable().optional(),identity_conflict:fe().int().nullable().optional(),username_auto_assigned:fe().int().nullable().optional(),sandbox_completed:fe().int().nullable().optional(),sandbox_completed_at:v().nullable().optional(),sandbox_dataset_id:v().nullable().optional(),aws_iam_username:v().nullable().optional(),dataset_count:fe().int().optional(),active_tokens:fe().int().optional(),linked_identities:Ze(v()).optional()}).passthrough(),XB=ne({user:Cb}).passthrough(),GV=ne({from:v().nullable(),to:v().nullable()}),JB=ne({message:v(),changed:wF(v(),GV),notes:Ze(v()).optional(),old_address_notified:Ue().optional(),user:Cb}).passthrough()});var e6=120,t6=64,r6="unnamed machine",KV=25,qb,n6,Us,Db,s6,o6,i6,HV,BV,a6,Zl,c6,u6,l6,d6,f6;var Mb=F(()=>{jn();qb=Ve(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),n6={authorization_pending:"Waiting for you to authorize this machine in the browser.",slow_down:"Polling too quickly; the CLI will slow down automatically.",expired_token:"The code expired. Run `nemar auth login` again for a new one.",access_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",invalid_grant:"That code is no longer valid. Run `nemar auth login` again for a new one."},Us=Ve(["device_code_unknown","device_code_expired","device_code_used","device_code_denied","account_pending","account_revoked","identity_conflict","service_account","person_account","too_many_keys","key_not_found"]),Db=Us.options,s6={device_code_unknown:"That code was not found. Check the code shown in your terminal, or run `nemar auth login` again for a new one.",device_code_expired:"The code expired. Run `nemar auth login` again for a new one.",device_code_used:"That code has already been used. Run `nemar auth login` again for a new one.",device_code_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",account_pending:"Verify your email address first. Check your inbox for the NEMAR verification code, then authorize again.",account_revoked:"Your NEMAR account access has been revoked. Contact the NEMAR team if you think this is a mistake.",identity_conflict:"This account shares an identifier with another NEMAR account and cannot sign in until that is resolved. Fix it in Settings on nemar.org or contact the NEMAR team.",service_account:"This is a service or test account, and it cannot sign in this way. Ask an owner to create a key for it with `nemar admin keys create`.",person_account:"This account belongs to a person. A person creates their own keys with `nemar auth login` or in Settings on nemar.org.",too_many_keys:`This account already has ${KV} active keys. Revoke one in Settings on nemar.org or with \`nemar auth keys\`, then try again.`,key_not_found:"That key was not found on this account, or it is already revoked. Run `nemar auth keys` to see the active ones."},o6=ne({error:Us,message:v()}).passthrough(),i6=ne({device_code:v(),user_code:v(),verification_uri:v(),verification_uri_complete:v(),expires_in:fe().int(),interval:fe().int()}).passthrough(),HV=Yw("error",[ne({error:In("authorization_pending"),message:v()}).passthrough(),ne({error:In("slow_down"),message:v()}).passthrough()]),BV=Yw("error",[ne({error:In("expired_token"),reason:Us,message:v()}).passthrough(),ne({error:In("access_denied"),reason:Us,message:v()}).passthrough(),ne({error:In("invalid_grant"),reason:Us,message:v()}).passthrough()]),a6=EF([HV,BV]),Zl=ne({id:fe().int(),name:v().nullable(),prefix:v(),created_at:v(),last_used_at:v().nullable(),current:Ue()}).passthrough(),c6=ne({api_key:v(),key:Zl,user:ne({username:v().nullable(),email:v(),github_username:v().nullable(),role:v(),sandbox_completed:Ue(),sandbox_dataset_id:v().nullable()}).passthrough()}).passthrough(),u6=ne({user_code:v(),machine_name:v(),requested_at:v(),expires_in:fe().int(),account:ne({username:v().nullable(),email_masked:v()}).passthrough(),refusal:ne({code:Us,message:v()}).passthrough().nullable()}).passthrough(),l6=ne({ok:In(!0),machine_name:v()}).passthrough(),d6=ne({keys:Ze(Zl)}).passthrough(),f6=ne({api_key:v(),key:Zl}).passthrough()});var WV,Lb,Ho="https://nemar.org/settings",m6,YV,XV,JV,g6,y6;var Ub=F(()=>{jn();WV=Ve(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),Lb=WV.options,m6={orcid_in_use:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${Ho}).`,orcid_already_linked:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${Ho}).`,orcid_linked_other:`That ORCID iD is linked to a different NEMAR account. Unlink it there first (Settings, ${Ho}), then link it here.`,email_in_use:`That email address already belongs to a NEMAR account. Sign in to that account instead, or change its address first (Settings, ${Ho}).`,github_in_use:`That GitHub account is already linked to a NEMAR account. Sign in to that account instead, or change its GitHub username first (Settings, ${Ho}).`,identity_conflict_remains:"The collision that flagged this account is still there. Resolve it on the other account first (change its email or GitHub username, or unlink its ORCID iD), or delete that account, then clear the flag."},YV=Ve(["orcid","email","github"]),XV=ne({id:fe().int(),username:v().nullable(),email:v(),created_at:v(),has_oauth_identity:Ue(),dataset_count:fe().int(),identity_conflict:fe().int(),canonical:Ue()}).passthrough(),JV=ne({kind:YV,value:v(),canonical_user_id:fe().int(),accounts:Ze(XV)}).passthrough(),g6=ne({groups:Ze(JV),group_count:fe().int(),flagged_count:fe().int()}).passthrough(),y6=ne({ok:In(!0),id:fe().int(),cleared:Ue()}).passthrough()});function b6(e){return typeof e==="string"&&ZV.includes(e)}var QV,$6,E6,w6,ZV,e9="ci_check_unavailable",Fb,Vb,zb,S6="X-Approval-Dispatch-Token",x6;var Gb=F(()=>{jn();QV=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/,$6=v().regex(QV,"ORCID must be in format 0000-0000-0000-000X"),E6=Ve(["found","no_public_name","lookup_failed"]),w6=Ve(["bids_validation_failed","bids_validation_pending","bids_validation_in_progress","prescreen_failed","min_requirements_failed","owner_name_missing","identifier_screen_findings"]),ZV=["bids_validation_pending","bids_validation_in_progress"];Fb=[e9],Vb=["identifier_screen_pending","identifier_screen_not_clear","identifier_screen_not_applicable"],zb=["publication_review_not_clear","request_blocked","request_changed","request_mismatch","dispatch_superseded","dispatch_expired","decision_with_dispatch_token","approval_in_flight","deny_after_publishing","invalid_dataset_id","approval_closed_during_run"],x6=Ve(["filled","would_fill","no_public_name","lookup_failed","write_failed"])});function Hb(e){if(Kb)return;Kb=!0;let t=Nt.yellow("\u2500".repeat(60)),r=Nt.yellow.bold("[MAINTENANCE]"),n=Nt.dim(`mode: ${e.mode}`),s=e.eta?`
|
|
33
33
|
${Nt.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
|
|
34
34
|
${r} ${e.message}
|
|
35
35
|
${n}${s}
|
|
36
36
|
${t}
|
|
37
|
-
`)}var Kb=!1;var Bb=F(()=>{Ul()});function Wb(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(td)return ed;return hn().apiUrl||ed}async function L6(e,t={},r=!1,n){let s=`${Wb()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":ac,...t.headers};if(r){let p=hn();if(!p.apiKey&&r===!0)throw new fr(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)o.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(s,{...t,headers:o})}catch(p){if(lc())dc({method:i,url:s,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new fr(0,`Network error: Could not connect to ${Wb()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(lc())dc({method:i,url:s,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new fr(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(lc())dc({method:i,url:s,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,responseBody:d});let l;try{l=JSON.parse(d)}catch{throw new fr(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(l.mode==="read-only"||l.mode==="full")){let xt=typeof l.message==="string"?l.message:"NEMAR is in maintenance mode. Please retry shortly.",hr=typeof l.eta==="string"?l.eta:null,et=new Il(l.mode,xt,hr,l.details);throw Hb(et),et}let p=typeof l.block_reason==="string",f=Array.isArray(l.missing)?l.missing.filter((xt)=>typeof xt==="string"):void 0,h=typeof l.error==="string"&&(eb.includes(l.error)||Lb.includes(l.error)),m=typeof l.error==="string"&&(qb.options.includes(l.error)||Db.includes(l.error)),y=typeof l.error==="string"&&Jw.includes(l.error),_=typeof l.error==="string"&&Ib.includes(l.error),O=typeof l.error==="string"&&Vb.includes(l.error),T=typeof l.error==="string"&&Fb.includes(l.error),M=typeof l.error==="string"&&zb.includes(l.error),_e=p||T||M||h||m||y||_||O||f!==void 0&&typeof l.error==="string"&&Zw.includes(l.error)?l.message||l.error:l.error||l.message;if(u.status===404&&l.error==="Not Found"&&typeof l.message==="string")_e=`${l.message}. This NEMAR backend does not support this command yet.`;let ve=new fr(u.status,_e||"Request failed",l.details,typeof l.step==="string"?l.step:void 0,p?l.block_reason:void 0,f);if(typeof l.error==="string")ve.code=l.error;if(typeof l.reason==="string")ve.reason=l.reason;throw ve.rawBody=l,ve}if(n){let p=n.safeParse(l);if(!p.success)throw new fr(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return l}var ed="https://nemar-api-dev.sccn-org.workers.dev",td;var Yb=F(()=>{jb();Mb();Ub();Gb();nc();fc();Yl();Bb();Gl();Cl();td=ed.includes("workers.dev")});fc();import{open as c9,rm as u9}from"fs/promises";Yb();var Xb="NEMAR_DATA_HOSTS",t9="NEMAR_DATA_HOSTS_ONLY",r9="https://private.nemar.org",n9="https://private-test.nemar.org",s9=/^[a-z]{2,3}[0-9]{6}$/;function Jb(e){return s9.test(e)}function o9(e){return e}function Qb(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function Zb(e){let t=e.trim();if(t===""||/[?#@]/.test(t))return null;let r;try{r=new URL(t)}catch{return null}if(r.username!==""||r.password!=="")return null;if(r.pathname!=="/")return null;if(r.protocol==="https:")return r.origin;if(r.protocol==="http:"&&Qb(r.hostname))return r.origin;return null}function eS(e){let t=[],r=[];for(let n of(e??"").split(",")){let s=n.trim();if(s==="")continue;let o=Zb(s);if(o===null)r.push(s);else if(!t.includes(o))t.push(o)}return{origins:t,rejected:r}}function tS(e){return e.env??process.env}function i9(e={}){let t=tS(e),r=e.isDevBuild??td,n=t[t9]==="1"?[]:[r?n9:r9],{origins:s}=eS(t[Xb]);return[...n,...s.filter((o)=>!n.includes(o))].map(o9)}function V6(e={}){return eS(tS(e)[Xb]).rejected}function hc(e,t={}){let r=Zb(e);if(r===null)return null;return i9(t).find((n)=>n===r)??null}function rS(e,t={}){return hc(e,t)!==null}function z6(e,t={}){let r;try{r=new URL(e)}catch{return null}if(r.username!==""||r.password!=="")return null;return hc(r.origin,t)}function nS(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&Qb(e.hostname)&&new URL(t).protocol==="http:"}var a9="NEMAR_DATA_HOST_TIMEOUT_MS";function rd(e,t=process.env){let r=t[a9];if(r===void 0||!/^[0-9]+$/.test(r))return e;let n=Number(r);return n>0&&n<e?n:e}function nd(e){if(!(e instanceof Error))return"error";let t=e.code;return typeof t==="string"&&/^[A-Z][A-Z0-9_]+$/.test(t)?`${e.name} ${t}`:e.name}var sS=3,iS=60000,l9=262144,aS=255,cS=/^[A-Z0-9][A-Z0-9_]*-s([0-9]{1,16})(?:-S([0-9]{1,16})-C([0-9]{1,16}))?--[A-Za-z0-9._-]+$/;function uS(e){return e.length<=aS&&cS.test(e)}function d9(e){if(e.length>aS)return null;let t=cS.exec(e);if(!t||t[2]!==void 0)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}function f9(e,t,r={}){if(!e)return{ok:!1,message:"The remote has no host setting."};if(!t)return{ok:!1,message:"The remote has no dataset setting."};if(!Jb(t))return{ok:!1,message:"The dataset setting is not a dataset id (two or three letters and six digits)."};let n=hc(e,r);if(n===null)return{ok:!1,message:`The host setting ${It(e)} is not an https origin on this CLI's list of data hosts. The remote's host setting is part of the repository, so it cannot add one.`};return{ok:!0,settings:{origin:n,dataset:t,options:r}}}function It(e,t=200){let r=e.replace(/[^\x20-\x7e]/g,"?");return r.length>t?`${r.slice(0,t)}...`:r}function p9(e,t){return new URL(`${e.origin}/o/${encodeURIComponent(e.dataset)}/${encodeURIComponent(t)}`)}function lS(e,t){if(t)return`The storage address was refused (status ${e}).`;if(e===401)return"The data host refused the API key. Run 'nemar auth login' to sign in again.";if(e===404)return"The data host has no such object, or this account has no access to the dataset.";if(e===429)return"The data host is limiting requests; try again shortly.";return`The data host answered status ${e}.`}async function dS(e,t,r,n,s,o){if(!rS(e.origin,e.options))return{kind:"failed",message:"The host is not on this CLI's list of data hosts."};let i=p9(e,t),a=!1;for(let c=0;;c++){let u={"Accept-Encoding":"identity"};if(i.origin===e.origin)u.Authorization=`Bearer ${r}`;let d;try{d=await fetch(i,{method:n,headers:u,redirect:"manual",signal:o})}catch(f){if(o.aborted)return{kind:"failed",message:"The request timed out."};return{kind:"failed",message:`Could not reach the host (${nd(f)}).`}}if(d.status<300||d.status>=400)return{kind:"response",response:d,redirected:a};if(await d.body?.cancel().catch(()=>{}),!s)return{kind:"response",response:d,redirected:a};if(c>=sS)return{kind:"failed",message:`More than ${sS} redirects.`};let l=d.headers.get("location");if(!l)return{kind:"failed",message:"A redirect named no address."};let p;try{p=new URL(l,i)}catch{return{kind:"failed",message:"A redirect named an address that is not a URL."}}if(!nS(p,e.origin))return{kind:"failed",message:"A redirect named an address that is not https."};i=p,a=!0}}async function fS(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(),e),s=()=>{clearTimeout(n),n=setTimeout(()=>r.abort(),e)};try{return await t(r.signal,s)}finally{clearTimeout(n)}}async function h9(e,t,r,n,s){if(!uS(t))return{ok:!1,message:"The key is not one a data host serves."};let o=d9(t);return fS(rd(iS,e.options?.env),async(i,a)=>{let c=await dS(e,t,r,"GET",!0,i);if(c.kind==="failed")return{ok:!1,message:c.message};let{response:u,redirected:d}=c;if(u.status!==200||!u.body)return await u.body?.cancel().catch(()=>{}),{ok:!1,message:lS(u.status,d)};let l=u.headers.get("content-length");if(o!==null&&l!==null&&Number(l)!==o)return await u.body.cancel().catch(()=>{}),{ok:!1,message:`The object is ${It(l,20)} bytes but its key says ${o}.`};a();let p,f=0,h=0;try{p=await c9(n,"w");let m=u.body.getReader();while(!0){let{done:y,value:_}=await m.read();if(y)break;if(a(),f+=_.byteLength,o!==null&&f>o)throw await m.cancel().catch(()=>{}),new mc(`More bytes arrived than the key's ${o}.`);if(await p.write(_),f-h>=l9)h=f,s(f)}if(await p.close(),p=void 0,o!==null&&f!==o)throw new mc(`The object ended after ${f} bytes; its key says ${o}.`);if(f!==h)s(f);return{ok:!0,bytes:f}}catch(m){if(await p?.close().catch(()=>{}),await u9(n,{force:!0}).catch(()=>{}),m instanceof mc)return{ok:!1,message:m.message};if(i.aborted)return{ok:!1,message:"The transfer stalled and timed out."};return{ok:!1,message:`The transfer failed (${nd(m)}).`}}})}class mc extends Error{constructor(e){super(e);this.name="SizeError"}}async function m9(e,t,r){if(!uS(t))return{state:"unknown",message:"The key is not one a data host serves."};return fS(rd(iS,e.options?.env),async(n)=>{let s=await dS(e,t,r,"HEAD",!1,n);if(s.kind==="failed")return{state:"unknown",message:s.message};let{status:o}=s.response;if(await s.response.body?.cancel().catch(()=>{}),o===200)return{state:"present"};if(o===404)return{state:"absent"};return{state:"unknown",message:lS(o,!1)}})}class gc extends Error{constructor(e){super(e);this.name="ProtocolAbort"}}async function pS(e,t){let r=e.lines[Symbol.asyncIterator](),n=[],s=null,o=null,i=async()=>{let d=n.shift();if(d!==void 0)return d;let l=await r.next();return l.done?null:l.value},a=async(d)=>{await e.send(`GETCONFIG ${d}`);while(!0){let l=await r.next();if(l.done)throw new gc("git-annex closed the connection");let p=l.value;if(p==="VALUE"||p.startsWith("VALUE ")){let f=p.slice(5).trimStart();return f===""?void 0:f}if(p.startsWith("ERROR"))throw new gc(p);n.push(p)}},c=async()=>{let d=await a("host"),l=await a("dataset");return f9(d,l,t.options)},u=async(d,l)=>{if(!s||!o){await e.send(`TRANSFER-FAILURE RETRIEVE ${It(d)} The remote has not been prepared.`);return}let p=Promise.resolve(),f=await h9(s,d,o,l,(h)=>{p=p.then(()=>e.send(`PROGRESS ${h}`))});if(await p,f.ok)await e.send(`TRANSFER-SUCCESS RETRIEVE ${d}`);else await e.send(`TRANSFER-FAILURE RETRIEVE ${It(d)} ${It(f.message)}`)};await e.send("VERSION 1");while(!0){let d=await i();if(d===null)return 0;if(d.trim()==="")continue;let[l,...p]=oS(d,1),f=p[0]??"";try{switch(l){case"EXTENSIONS":await e.send("EXTENSIONS");break;case"INITREMOTE":{let h=await c();await e.send(h.ok?"INITREMOTE-SUCCESS":`INITREMOTE-FAILURE ${It(h.message)}`);break}case"PREPARE":{let h=await c();if(!h.ok){s=null,await e.send(`PREPARE-FAILURE ${It(h.message)}`);break}let m=t.loadApiKey();if(!m){s=null,await e.send("PREPARE-FAILURE No NEMAR API key is stored. Run 'nemar auth login' first.");break}s=h.settings,o=m,await e.send("PREPARE-SUCCESS");break}case"LISTCONFIGS":await e.send("CONFIG host The https origin of the NEMAR data host"),await e.send("CONFIG dataset The dataset id on that host"),await e.send("CONFIGEND");break;case"GETCOST":await e.send("COST 200");break;case"GETAVAILABILITY":await e.send("AVAILABILITY GLOBAL");break;case"GETINFO":if(s)await e.send("INFOFIELD host"),await e.send(`INFOVALUE ${s.origin}`),await e.send("INFOFIELD dataset"),await e.send(`INFOVALUE ${s.dataset}`);await e.send("INFOEND");break;case"EXPORTSUPPORTED":await e.send("EXPORTSUPPORTED-FAILURE");break;case"IMPORTSUPPORTED":await e.send("IMPORTSUPPORTED-FAILURE");break;case"WHEREIS":await e.send("WHEREIS-FAILURE");break;case"CLAIMURL":await e.send("CLAIMURL-FAILURE");break;case"CHECKURL":await e.send("CHECKURL-FAILURE");break;case"TRANSFER":{let[h,m,...y]=oS(f,2);if(h==="STORE")await e.send(`TRANSFER-FAILURE STORE ${It(m??"")} This remote is read-only for now.`);else if(h==="RETRIEVE"&&m&&y[0])await u(m,y[0]);else await e.send("UNSUPPORTED-REQUEST");break}case"CHECKPRESENT":{if(!f){await e.send("UNSUPPORTED-REQUEST");break}if(!s||!o){await e.send(`CHECKPRESENT-UNKNOWN ${It(f)} The remote has not been prepared.`);break}let h=await m9(s,f,o);if(h.state==="present")await e.send(`CHECKPRESENT-SUCCESS ${f}`);else if(h.state==="absent")await e.send(`CHECKPRESENT-FAILURE ${f}`);else await e.send(`CHECKPRESENT-UNKNOWN ${It(f)} ${h.message}`);break}case"REMOVE":await e.send(`REMOVE-FAILURE ${It(f)} This remote is read-only for now.`);break;case"ERROR":return 1;case"VALUE":break;default:await e.send("UNSUPPORTED-REQUEST")}}catch(h){if(h instanceof gc)return 1;throw h}}}function oS(e,t){let r=[],n=e;for(let s=0;s<t;s++){let o=n.indexOf(" ");if(o<0)break;r.push(n.slice(0,o)),n=n.slice(o+1)}return r.push(n),r}async function*g9(){let e=new TextDecoder,t="";for await(let r of Bun.stdin.stream()){t+=e.decode(r,{stream:!0});let n=t.indexOf(`
|
|
37
|
+
`)}var Kb=!1;var Bb=F(()=>{Ul()});function Wb(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(td)return ed;return hn().apiUrl||ed}async function L6(e,t={},r=!1,n){let s=`${Wb()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":ac,...t.headers};if(r){let p=hn();if(!p.apiKey&&r===!0)throw new fr(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)o.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(s,{...t,headers:o})}catch(p){if(lc())dc({method:i,url:s,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new fr(0,`Network error: Could not connect to ${Wb()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(lc())dc({method:i,url:s,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new fr(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(lc())dc({method:i,url:s,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,responseBody:d});let l;try{l=JSON.parse(d)}catch{throw new fr(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(l.mode==="read-only"||l.mode==="full")){let xt=typeof l.message==="string"?l.message:"NEMAR is in maintenance mode. Please retry shortly.",hr=typeof l.eta==="string"?l.eta:null,et=new Il(l.mode,xt,hr,l.details);throw Hb(et),et}let p=typeof l.block_reason==="string",f=Array.isArray(l.missing)?l.missing.filter((xt)=>typeof xt==="string"):void 0,h=typeof l.error==="string"&&(eb.includes(l.error)||Lb.includes(l.error)),m=typeof l.error==="string"&&(qb.options.includes(l.error)||Db.includes(l.error)),y=typeof l.error==="string"&&Jw.includes(l.error),_=typeof l.error==="string"&&Ib.includes(l.error),O=typeof l.error==="string"&&Vb.includes(l.error),T=typeof l.error==="string"&&Fb.includes(l.error),M=typeof l.error==="string"&&zb.includes(l.error),_e=p||T||M||h||m||y||_||O||f!==void 0&&typeof l.error==="string"&&Zw.includes(l.error)?l.message||l.error:l.error||l.message;if(u.status===404&&l.error==="Not Found"&&typeof l.message==="string")_e=`${l.message}. This NEMAR backend does not support this command yet.`;let ve=new fr(u.status,_e||"Request failed",l.details,typeof l.step==="string"?l.step:void 0,p?l.block_reason:void 0,f);if(typeof l.error==="string")ve.code=l.error;if(typeof l.reason==="string")ve.reason=l.reason;throw ve.rawBody=l,ve}if(n){let p=n.safeParse(l);if(!p.success)throw new fr(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return l}var ed="https://api.nemar.org",td;var Yb=F(()=>{jb();Mb();Ub();Gb();nc();fc();Yl();Bb();Gl();Cl();td=ed.includes("workers.dev")});fc();import{open as c9,rm as u9}from"fs/promises";Yb();var Xb="NEMAR_DATA_HOSTS",t9="NEMAR_DATA_HOSTS_ONLY",r9="https://private.nemar.org",n9="https://private-test.nemar.org",s9=/^[a-z]{2,3}[0-9]{6}$/;function Jb(e){return s9.test(e)}function o9(e){return e}function Qb(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function Zb(e){let t=e.trim();if(t===""||/[?#@]/.test(t))return null;let r;try{r=new URL(t)}catch{return null}if(r.username!==""||r.password!=="")return null;if(r.pathname!=="/")return null;if(r.protocol==="https:")return r.origin;if(r.protocol==="http:"&&Qb(r.hostname))return r.origin;return null}function eS(e){let t=[],r=[];for(let n of(e??"").split(",")){let s=n.trim();if(s==="")continue;let o=Zb(s);if(o===null)r.push(s);else if(!t.includes(o))t.push(o)}return{origins:t,rejected:r}}function tS(e){return e.env??process.env}function i9(e={}){let t=tS(e),r=e.isDevBuild??td,n=t[t9]==="1"?[]:[r?n9:r9],{origins:s}=eS(t[Xb]);return[...n,...s.filter((o)=>!n.includes(o))].map(o9)}function V6(e={}){return eS(tS(e)[Xb]).rejected}function hc(e,t={}){let r=Zb(e);if(r===null)return null;return i9(t).find((n)=>n===r)??null}function rS(e,t={}){return hc(e,t)!==null}function z6(e,t={}){let r;try{r=new URL(e)}catch{return null}if(r.username!==""||r.password!=="")return null;return hc(r.origin,t)}function nS(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&Qb(e.hostname)&&new URL(t).protocol==="http:"}var a9="NEMAR_DATA_HOST_TIMEOUT_MS";function rd(e,t=process.env){let r=t[a9];if(r===void 0||!/^[0-9]+$/.test(r))return e;let n=Number(r);return n>0&&n<e?n:e}function nd(e){if(!(e instanceof Error))return"error";let t=e.code;return typeof t==="string"&&/^[A-Z][A-Z0-9_]+$/.test(t)?`${e.name} ${t}`:e.name}var sS=3,iS=60000,l9=262144,aS=255,cS=/^[A-Z0-9][A-Z0-9_]*-s([0-9]{1,16})(?:-S([0-9]{1,16})-C([0-9]{1,16}))?--[A-Za-z0-9._-]+$/;function uS(e){return e.length<=aS&&cS.test(e)}function d9(e){if(e.length>aS)return null;let t=cS.exec(e);if(!t||t[2]!==void 0)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}function f9(e,t,r={}){if(!e)return{ok:!1,message:"The remote has no host setting."};if(!t)return{ok:!1,message:"The remote has no dataset setting."};if(!Jb(t))return{ok:!1,message:"The dataset setting is not a dataset id (two or three letters and six digits)."};let n=hc(e,r);if(n===null)return{ok:!1,message:`The host setting ${It(e)} is not an https origin on this CLI's list of data hosts. The remote's host setting is part of the repository, so it cannot add one.`};return{ok:!0,settings:{origin:n,dataset:t,options:r}}}function It(e,t=200){let r=e.replace(/[^\x20-\x7e]/g,"?");return r.length>t?`${r.slice(0,t)}...`:r}function p9(e,t){return new URL(`${e.origin}/o/${encodeURIComponent(e.dataset)}/${encodeURIComponent(t)}`)}function lS(e,t){if(t)return`The storage address was refused (status ${e}).`;if(e===401)return"The data host refused the API key. Run 'nemar auth login' to sign in again.";if(e===404)return"The data host has no such object, or this account has no access to the dataset.";if(e===429)return"The data host is limiting requests; try again shortly.";return`The data host answered status ${e}.`}async function dS(e,t,r,n,s,o){if(!rS(e.origin,e.options))return{kind:"failed",message:"The host is not on this CLI's list of data hosts."};let i=p9(e,t),a=!1;for(let c=0;;c++){let u={"Accept-Encoding":"identity"};if(i.origin===e.origin)u.Authorization=`Bearer ${r}`;let d;try{d=await fetch(i,{method:n,headers:u,redirect:"manual",signal:o})}catch(f){if(o.aborted)return{kind:"failed",message:"The request timed out."};return{kind:"failed",message:`Could not reach the host (${nd(f)}).`}}if(d.status<300||d.status>=400)return{kind:"response",response:d,redirected:a};if(await d.body?.cancel().catch(()=>{}),!s)return{kind:"response",response:d,redirected:a};if(c>=sS)return{kind:"failed",message:`More than ${sS} redirects.`};let l=d.headers.get("location");if(!l)return{kind:"failed",message:"A redirect named no address."};let p;try{p=new URL(l,i)}catch{return{kind:"failed",message:"A redirect named an address that is not a URL."}}if(!nS(p,e.origin))return{kind:"failed",message:"A redirect named an address that is not https."};i=p,a=!0}}async function fS(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(),e),s=()=>{clearTimeout(n),n=setTimeout(()=>r.abort(),e)};try{return await t(r.signal,s)}finally{clearTimeout(n)}}async function h9(e,t,r,n,s){if(!uS(t))return{ok:!1,message:"The key is not one a data host serves."};let o=d9(t);return fS(rd(iS,e.options?.env),async(i,a)=>{let c=await dS(e,t,r,"GET",!0,i);if(c.kind==="failed")return{ok:!1,message:c.message};let{response:u,redirected:d}=c;if(u.status!==200||!u.body)return await u.body?.cancel().catch(()=>{}),{ok:!1,message:lS(u.status,d)};let l=u.headers.get("content-length");if(o!==null&&l!==null&&Number(l)!==o)return await u.body.cancel().catch(()=>{}),{ok:!1,message:`The object is ${It(l,20)} bytes but its key says ${o}.`};a();let p,f=0,h=0;try{p=await c9(n,"w");let m=u.body.getReader();while(!0){let{done:y,value:_}=await m.read();if(y)break;if(a(),f+=_.byteLength,o!==null&&f>o)throw await m.cancel().catch(()=>{}),new mc(`More bytes arrived than the key's ${o}.`);if(await p.write(_),f-h>=l9)h=f,s(f)}if(await p.close(),p=void 0,o!==null&&f!==o)throw new mc(`The object ended after ${f} bytes; its key says ${o}.`);if(f!==h)s(f);return{ok:!0,bytes:f}}catch(m){if(await p?.close().catch(()=>{}),await u9(n,{force:!0}).catch(()=>{}),m instanceof mc)return{ok:!1,message:m.message};if(i.aborted)return{ok:!1,message:"The transfer stalled and timed out."};return{ok:!1,message:`The transfer failed (${nd(m)}).`}}})}class mc extends Error{constructor(e){super(e);this.name="SizeError"}}async function m9(e,t,r){if(!uS(t))return{state:"unknown",message:"The key is not one a data host serves."};return fS(rd(iS,e.options?.env),async(n)=>{let s=await dS(e,t,r,"HEAD",!1,n);if(s.kind==="failed")return{state:"unknown",message:s.message};let{status:o}=s.response;if(await s.response.body?.cancel().catch(()=>{}),o===200)return{state:"present"};if(o===404)return{state:"absent"};return{state:"unknown",message:lS(o,!1)}})}class gc extends Error{constructor(e){super(e);this.name="ProtocolAbort"}}async function pS(e,t){let r=e.lines[Symbol.asyncIterator](),n=[],s=null,o=null,i=async()=>{let d=n.shift();if(d!==void 0)return d;let l=await r.next();return l.done?null:l.value},a=async(d)=>{await e.send(`GETCONFIG ${d}`);while(!0){let l=await r.next();if(l.done)throw new gc("git-annex closed the connection");let p=l.value;if(p==="VALUE"||p.startsWith("VALUE ")){let f=p.slice(5).trimStart();return f===""?void 0:f}if(p.startsWith("ERROR"))throw new gc(p);n.push(p)}},c=async()=>{let d=await a("host"),l=await a("dataset");return f9(d,l,t.options)},u=async(d,l)=>{if(!s||!o){await e.send(`TRANSFER-FAILURE RETRIEVE ${It(d)} The remote has not been prepared.`);return}let p=Promise.resolve(),f=await h9(s,d,o,l,(h)=>{p=p.then(()=>e.send(`PROGRESS ${h}`))});if(await p,f.ok)await e.send(`TRANSFER-SUCCESS RETRIEVE ${d}`);else await e.send(`TRANSFER-FAILURE RETRIEVE ${It(d)} ${It(f.message)}`)};await e.send("VERSION 1");while(!0){let d=await i();if(d===null)return 0;if(d.trim()==="")continue;let[l,...p]=oS(d,1),f=p[0]??"";try{switch(l){case"EXTENSIONS":await e.send("EXTENSIONS");break;case"INITREMOTE":{let h=await c();await e.send(h.ok?"INITREMOTE-SUCCESS":`INITREMOTE-FAILURE ${It(h.message)}`);break}case"PREPARE":{let h=await c();if(!h.ok){s=null,await e.send(`PREPARE-FAILURE ${It(h.message)}`);break}let m=t.loadApiKey();if(!m){s=null,await e.send("PREPARE-FAILURE No NEMAR API key is stored. Run 'nemar auth login' first.");break}s=h.settings,o=m,await e.send("PREPARE-SUCCESS");break}case"LISTCONFIGS":await e.send("CONFIG host The https origin of the NEMAR data host"),await e.send("CONFIG dataset The dataset id on that host"),await e.send("CONFIGEND");break;case"GETCOST":await e.send("COST 200");break;case"GETAVAILABILITY":await e.send("AVAILABILITY GLOBAL");break;case"GETINFO":if(s)await e.send("INFOFIELD host"),await e.send(`INFOVALUE ${s.origin}`),await e.send("INFOFIELD dataset"),await e.send(`INFOVALUE ${s.dataset}`);await e.send("INFOEND");break;case"EXPORTSUPPORTED":await e.send("EXPORTSUPPORTED-FAILURE");break;case"IMPORTSUPPORTED":await e.send("IMPORTSUPPORTED-FAILURE");break;case"WHEREIS":await e.send("WHEREIS-FAILURE");break;case"CLAIMURL":await e.send("CLAIMURL-FAILURE");break;case"CHECKURL":await e.send("CHECKURL-FAILURE");break;case"TRANSFER":{let[h,m,...y]=oS(f,2);if(h==="STORE")await e.send(`TRANSFER-FAILURE STORE ${It(m??"")} This remote is read-only for now.`);else if(h==="RETRIEVE"&&m&&y[0])await u(m,y[0]);else await e.send("UNSUPPORTED-REQUEST");break}case"CHECKPRESENT":{if(!f){await e.send("UNSUPPORTED-REQUEST");break}if(!s||!o){await e.send(`CHECKPRESENT-UNKNOWN ${It(f)} The remote has not been prepared.`);break}let h=await m9(s,f,o);if(h.state==="present")await e.send(`CHECKPRESENT-SUCCESS ${f}`);else if(h.state==="absent")await e.send(`CHECKPRESENT-FAILURE ${f}`);else await e.send(`CHECKPRESENT-UNKNOWN ${It(f)} ${h.message}`);break}case"REMOVE":await e.send(`REMOVE-FAILURE ${It(f)} This remote is read-only for now.`);break;case"ERROR":return 1;case"VALUE":break;default:await e.send("UNSUPPORTED-REQUEST")}}catch(h){if(h instanceof gc)return 1;throw h}}}function oS(e,t){let r=[],n=e;for(let s=0;s<t;s++){let o=n.indexOf(" ");if(o<0)break;r.push(n.slice(0,o)),n=n.slice(o+1)}return r.push(n),r}async function*g9(){let e=new TextDecoder,t="";for await(let r of Bun.stdin.stream()){t+=e.decode(r,{stream:!0});let n=t.indexOf(`
|
|
38
38
|
`);while(n>=0)yield t.slice(0,n).replace(/\r$/,""),t=t.slice(n+1),n=t.indexOf(`
|
|
39
39
|
`)}if(t+=e.decode(),t!=="")yield t}var sd=Bun.stdout.writer(),y9=await pS({lines:g9(),send:async(e)=>{sd.write(`${e}
|
|
40
40
|
`),await sd.flush()}},{loadApiKey:()=>hn().apiKey||void 0});await sd.end();process.exit(y9);
|